diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml index 5b400d15a2..aaa8fdbedc 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml @@ -18,14 +18,14 @@ en: 5fdde26e9e8c6108 zh: 629559d733c1f0c5 /agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/plugin-resolution-the-vfs-holds-a-real-package-tree-the-closure-manifest-is-the-deploy-root: - en: c35ea4b858448b49 - zh: 1f8ff0a9f82ca881 + en: 985e0eb63f3d1fd6 + zh: 337cc44fadc6227e /agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/build-pipeline-and-artifacts: - en: d3bbd24ead02af4f - zh: 64623d88bee4314b + en: 921085cb9d894688 + zh: 12d99fe153d36738 /agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/python-sdk-distribution-two-carriers-exe-for-production-node-for-development: - en: 9bd60549d4a52ec0 - zh: e2343b7210212ee0 + en: 02e6b36f9f92c83a + zh: edd8b2db7a787483 /agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/naming-lineage: en: 31a5aecb8bf828bb zh: 2dffb6fd2e0f8194 @@ -33,8 +33,8 @@ en: 0426f598f3f44e64 zh: fc66728e17f3bcfb /agent-note-single-file-executable-sdk-runtime-distribution-single-exe/testing: - en: b3c9820f4dc7c6c8 - zh: 3b5768ef1770bfcb + en: 8e7f46bbb595afa9 + zh: 4641894ed285d717 /agent-note-single-file-executable-sdk-runtime-distribution-single-exe/alternatives-considered: en: 50d965ca81a401ba zh: 0c6296245b97b9ac diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md index 27d37ed541..60228735f5 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md @@ -44,19 +44,19 @@ The deploy root is [`python/sdk-runtime/package.json`](../../../../python/sdk-ru The deploy root includes `@deepseek-ai/dsh-mcp-client` as an explicitly supported custom-configuration plugin even though no shipped preset mounts it. An external config can therefore connect to user-supplied stdio and Streamable HTTP MCP servers and register their tools; the distribution does not carry those servers. The optional resource service provides MCP Resources; MCP Prompts remain unsupported. The executable and installed-wheel smokes start a temporary stdio server, discover its tool, and complete one model-requested call. -The [Office kit](2026-09-14-independent-libreoffice-kit.md) and its installed dependency tree live in `-office/node_modules`, preserving complete package contents and helper permissions. Top-level `pkg.ignore` excludes kit packages from the SEA archive, including assets selected by dependency `files` fields; small dependencies shared with other consumers remain available in the VFS. The private Python bootstrap uses Node `registerHooks` to resolve the kit entry and its package manifest from the real directory. Native executables and URL Workers therefore retain their ordinary paths without modifying the kit or the public CLI. Missing required packages and missing installed package manifests fail the copy; absent optionals preserve the kit's engine selection. +The [Office kit](2026-09-14-independent-libreoffice-kit.md) and its installed dependency tree live in the explicitly downloaded sidecar’s `node_modules`, preserving complete package contents and helper permissions. Top-level `pkg.ignore` excludes kit packages from the SEA archive, including assets selected by dependency `files` fields; small dependencies shared with other consumers remain available in the VFS. The private Python bootstrap uses Node `registerHooks` to resolve the kit entry and its package manifest from the real directory. Native executables and URL Workers therefore retain their ordinary paths without modifying the kit or the public CLI. The build locks the selected engine and dependency locations to exact npm tarballs; downloads verify their integrity before publication. ### Build pipeline and artifacts -[`scripts/build-exe-for-python-sdk.ts`](../../../../scripts/build-exe-for-python-sdk.ts): runtime closure verification → `pnpm run build` → (after clearing) `pnpm --filter dsh-python-runtime-closure deploy --legacy --prod --config.allow-unused-patches=true --config.node-linker=hoisted --config.auto-install-peers=false --config.link-workspace-packages=true --config.hoist-workspace-packages=false` **directly into** `python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/`, including [`python/sdk-runtime/runtime-bootstrap.mjs`](../../../../python/sdk-runtime/runtime-bootstrap.mjs) as the carrier-root `runtime-bootstrap.mjs` → restore direct workspace packages omitted by legacy deploy and reject any remaining manifest gap → replace staged dependency symlinks with their target bytes, remove package-manager `.bin` links, and fail if any symlink remains → verify the deployed bootstrap and inject pkg configuration with that bin plus assets covering dynamic profile, bundle, frontend, preset, native-library, and configuration reads → stage the target `node-pty` addon → invoke `pkg --sea` once per target → write `deepseek-harness-sdk-runtime--` under `dist-exe/` and copy it with its target-specific Office directory into the runtime directory. The Python runtime owns that bootstrap. It calls the public CLI export for ordinary launches and dispatches a provider-private selection to the same `@deepseek-ai/dsh-subprocess-local/runner` core without changing CLI grammar or adding another executable; the [native-containment reference](../../../../packages/subprocess/subprocess-local/README.md) owns that private path. Linux CI rebuilds `pty.node` inside the matching manylinux 2.28 container because legacy deploy omits that install side effect. Every target copies its native `@vscode/ripgrep` binary beside the executable as the required `-rg` sidecar; pkg runtimes select that sidecar through `process.pkg`, while ordinary Node execution uses `@vscode/ripgrep` directly. macOS uses its target prebuild and also emits the required `-spawn-helper`. The deploy flags preserve the measured runtime layout: `--legacy` is the mandatory path with inject-workspace-packages off; hoisted supplies package directories that staging makes symlink-free; staging removes nested workspace copies only when pnpm records the same dependency identity at the payload root, preserving singleton services; disabling workspace hoisting excludes unrelated workspace source packages; disabling automatic peer installation prevents undeclared peers from expanding the closure; link-workspace-packages selects direct workspace dependencies. [`pnpm-workspace.yaml`](../../../../pnpm-workspace.yaml) overrides the transitive `@deepseek-ai/cosmokit` and `@deepseek-ai/schemastery` semver requests to the pinned vendor sources so legacy deploy never resolves those unpublished names from a registry. Production deployment permits unused workspace patches because development-only tools can be absent from its closure; included-package patch failures still fail deployment. Workspace installs retain strict unused-patch validation. +[`scripts/build-exe-for-python-sdk.ts`](../../../../scripts/build-exe-for-python-sdk.ts): runtime closure verification → `pnpm run build` → (after clearing) `pnpm --filter dsh-python-runtime-closure deploy --legacy --prod --config.allow-unused-patches=true --config.node-linker=hoisted --config.auto-install-peers=false --config.link-workspace-packages=true --config.hoist-workspace-packages=false` **directly into** `python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/`, including [`python/sdk-runtime/runtime-bootstrap.mjs`](../../../../python/sdk-runtime/runtime-bootstrap.mjs) as the carrier-root `runtime-bootstrap.mjs` → restore direct workspace packages omitted by legacy deploy and reject any remaining manifest gap → replace staged dependency symlinks with their target bytes, remove package-manager `.bin` links, and fail if any symlink remains → verify the deployed bootstrap and inject pkg configuration with that bin plus assets covering dynamic profile, bundle, frontend, preset, native-library, and configuration reads → stage the target `node-pty` addon → invoke `pkg --sea` once per target → write `deepseek-harness-sdk-runtime--` under `dist-exe/` and copy it with its lightweight resource manifest and Office skill assets into the runtime directory. The Python runtime owns that bootstrap. It calls the public CLI export for ordinary launches and dispatches a provider-private selection to the same `@deepseek-ai/dsh-subprocess-local/runner` core without changing CLI grammar or adding another executable; the [native-containment reference](../../../../packages/subprocess/subprocess-local/README.md) owns that private path. Linux CI rebuilds `pty.node` inside the matching manylinux 2.28 container because legacy deploy omits that install side effect. Every target copies its native `@vscode/ripgrep` binary beside the executable as the required `-rg` sidecar; pkg runtimes select that sidecar through `process.pkg`, while ordinary Node execution uses `@vscode/ripgrep` directly. macOS uses its target prebuild and also emits the required `-spawn-helper`. The deploy flags preserve the measured runtime layout: `--legacy` is the mandatory path with inject-workspace-packages off; hoisted supplies package directories that staging makes symlink-free; staging removes nested workspace copies only when pnpm records the same dependency identity at the payload root, preserving singleton services; disabling workspace hoisting excludes unrelated workspace source packages; disabling automatic peer installation prevents undeclared peers from expanding the closure; link-workspace-packages selects direct workspace dependencies. [`pnpm-workspace.yaml`](../../../../pnpm-workspace.yaml) overrides the transitive `@deepseek-ai/cosmokit` and `@deepseek-ai/schemastery` semver requests to the pinned vendor sources so legacy deploy never resolves those unpublished names from a registry. Production deployment permits unused workspace patches because development-only tools can be absent from its closure; included-package patch failures still fail deployment. Workspace installs retain strict unused-patch validation. CI: [`.github/workflows/build-exe-for-python-sdk.yml`](../../../../.github/workflows/build-exe-for-python-sdk.yml) runs [installed-wheel validation](../testing/2026-08-23-installed-python-wheel-black-box-ci.md) on Linux/Windows x64 for pull requests and Linux ARM64 plus both macOS architectures for master pushes. The [public publication workflow](../../archived/process/2026-08-11-python-publication-workflow.md) calls it for all five targets; `workflow_dispatch` can still select a subset. Native builds run on linux-x64 / linux-arm64 (`ubuntu-24.04-arm`) / macos-arm64 / macos-x64 (`macos-15-intel`) / win-x64 (`windows-2025`), with `~/.pkg-cache` cached where applicable, and pkg handles macOS ad-hoc signing. Each leg installs the release-shaped SDK and runtime wheels into a clean venv outside the checkout, verifies their package and executable origin, then drives the complete keyless scenario set through the public SDK and direct NDJSON JSON-RPC. Trusted pull requests and master pushes additionally run a real DeepSeek two-turn tool smoke on their selected targets; fork and Dependabot heads receive no key. Linux inspects the executable and native addon's GLIBC requirements and runs an additional manylinux 2.28 smoke, while macOS checks the runtime, ripgrep, and PTY helper architectures and verifies that all three deployment targets fit the wheel tag. A full five-target run retains six artifacts, each containing one release file: the platform-independent SDK wheel and five native runtime wheels; a subset dispatch retains the SDK wheel and selected runtime wheels. Bare executables and source bundles remain intermediate test inputs. [`.gitlab-ci.yml`](../../../../.gitlab-ci.yml) accepts `python-v` tag pipelines whose version matches the root `package.json`, builds one SDK wheel and five native runtime wheels, then a single serialized job checks and publishes all six to the project PyPI registry. The [`python/sdk-runtime` README](../../../../python/sdk-runtime/README.md) owns the Windows target and the explicit exclusion of Windows arm64. ### Python SDK distribution: two carriers, exe for production, node for development -The Python SDK lives at [`python/`](../../../../python/README.md): `python/sdk` is the client and `python/sdk-runtime` is the runtime carrier package. The runtime package's data directory holds the build-injected platform executable with its required `-rg` sidecar, `-office/` directory, and optional macOS helper, plus the build-injected `runtime/node/` closure tree for repository development. `resolve_bundled_launch_args()` selects the executable by default; explicit `DSH_RUNTIME_MODE=node` runs `runtime/node/node_modules/@deepseek-ai/dsh/lib/bin.js` on system Node 22.19 or newer. The node carrier never enters wheel distributions, and neither carrier uses a checked-in complete `cordis.yml`. +The Python SDK lives at [`python/`](../../../../python/README.md): `python/sdk` is the client and `python/sdk-runtime` is the runtime carrier package. The runtime package's data directory holds the build-injected platform executable with its required `-rg` sidecar, lightweight download metadata and Office skills, and optional macOS helper, plus the build-injected `runtime/node/` closure tree for repository development. `resolve_bundled_launch_args()` selects the executable by default; explicit `DSH_RUNTIME_MODE=node` runs `runtime/node/runtime-bootstrap.mjs` on system Node 22.19 or newer. The node carrier never enters wheel distributions, and neither carrier uses a checked-in complete `cordis.yml`. -[`scripts/build-python-release.py`](../../../../scripts/build-python-release.py) reads the authoritative `X.Y.Z` or prerelease version from the repository root `package.json`, converts prereleases to their PEP 440 spelling, and stages both packages at that wheel version, with `deepseek-harness-sdk` depending exactly on the matching `deepseek-harness-runtime-bin`. An optional `python-v` release tag is a consistency assertion and is rejected when it differs from the repository version; the source `pyproject.toml` development sentinel never determines a release version. Staging also carries the repository license into both wheels and the third-party notices into the bundled runtime wheel. The SDK is a `py3-none-any` wheel; each wheel-only runtime package contains one exe, its Office directory, and its architecture-matched ripgrep sidecar, and the macOS wheel also contains its architecture-matched spawn helper. Runtime wheels use `py3-none-manylinux_2_28_x86_64`, `py3-none-manylinux_2_28_aarch64`, `py3-none-macosx_14_0_arm64`, `py3-none-macosx_14_0_x86_64`, or `py3-none-win_amd64`; the Hatch hook rejects sdists, universal tags, mixed-platform payloads, missing or extra sidecars, and unsupported platforms. Both macOS tags deliberately declare a conservative 14.0 installation floor: the packaged Node 24 executables declare macOS 13.5, and the x64 PTY helper declares 10.7, but release validation proves the complete payload only against the 14.0 wheel claim rather than promising each observed component minimum as a supported host. The two macOS wheels remain architecture-specific; no universal2 wheel is published. +[`scripts/build-python-release.py`](../../../../scripts/build-python-release.py) reads the authoritative `X.Y.Z` or prerelease version from the repository root `package.json`, converts prereleases to their PEP 440 spelling, and stages both packages at that wheel version, with `deepseek-harness-sdk` depending exactly on the matching `deepseek-harness-runtime-bin`. An optional `python-v` release tag is a consistency assertion and is rejected when it differs from the repository version; the source `pyproject.toml` development sentinel never determines a release version. Staging also carries the repository license into both wheels and the third-party notices into the bundled runtime wheel. The SDK is a `py3-none-any` wheel; each wheel-only runtime package contains one exe, lightweight resource metadata and skills, and its architecture-matched ripgrep sidecar, and the macOS wheel also contains its architecture-matched spawn helper. Runtime wheels use `py3-none-manylinux_2_28_x86_64`, `py3-none-manylinux_2_28_aarch64`, `py3-none-macosx_14_0_arm64`, `py3-none-macosx_14_0_x86_64`, or `py3-none-win_amd64`; the Hatch hook rejects sdists, universal tags, mixed-platform payloads, missing or extra sidecars, and unsupported platforms. Both macOS tags deliberately declare a conservative 14.0 installation floor: the packaged Node 24 executables declare macOS 13.5, and the x64 PTY helper declares 10.7, but release validation proves the complete payload only against the 14.0 wheel claim rather than promising each observed component minimum as a supported host. The two macOS wheels remain architecture-specific; no universal2 wheel is published. The Python client launches the packaged `dsh` command with the selected profile (`sdk` by default), ordered patch files, and an explicit Harness home. The profile owns JSON-RPC serving and application composition; missing homes, profiles, bundles, patches, and server rows fail without an external complete-config fallback. @@ -74,7 +74,7 @@ The verification surface has three tiers. Mechanism tier: the measured conclusio Manual-driving caveat: the bin treats stdin EOF as "the client is gone" and disposes immediately, so a short-lived pipe aborts an in-flight turn — pipe-driven runs must keep stdin open until the turn ends. -The installed-wheel `sdk-office` scenario copies the target's complete payload to a private temporary directory, requires exactly one target backend (the declared native target, or WASM when no native target is declared), and converts DOCX once through the shipped SDK profile with that engine. It checks that the kit module resolves inside the relocated directory, that conversion reports the expected backend, and that the output contains PDF bytes. Wheel validation checks the declared engine assets and native helper execute bit; CI uploads the completed wheel, so nested helper permissions stay inside the ZIP archive. +The installed-wheel `sdk-office` scenario relocates the lightweight wheel payload and explicitly downloads the complete npm Office sidecar with its independent Node. It requires exactly one target backend, verifies that the SDK loads the kit from the downloaded sidecar, and converts DOCX through the skill CLI with an empty PATH. Python Office operations use the same CLI. Explicit downloads reuse the existing build preparation implementation; SDK startup performs no downloads. The [runtime reference](../../../../python/sdk-runtime/README.md) owns cache and activation behavior. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md index 4cc6e20459..272c0e80c9 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md @@ -44,19 +44,19 @@ exe 的 VFS 内是**构建产物形态的真实包树**(各包的 `lib/` + 真 部署根目录显式包含 `@deepseek-ai/dsh-mcp-client`,将其作为自定义配置可用的插件,即使随附 preset 均未挂载该插件。外部配置因此可以连接由用户提供的 stdio 与 Streamable HTTP MCP server 并注册其工具;分发物不包含这些 server。可选资源服务提供 MCP Resources;MCP Prompts 仍不受支持。可执行程序与已安装 wheel 包的冒烟测试会启动临时 stdio server,发现其工具,并完成一次由模型请求的调用。 -[Office kit](2026-09-14-independent-libreoffice-kit.zh.md) 及其已安装依赖树位于 `-office/node_modules`,保留完整包内容与辅助程序权限。顶层 `pkg.ignore` 从 SEA 归档排除 kit 包,包括依赖 `files` 字段选中的资源;与其他使用方共享的小型依赖仍可在 VFS 中使用。Python 私有 bootstrap 使用 Node `registerHooks` 从真实目录解析 kit 入口及其包清单。因此原生可执行程序与 URL Worker 保留普通文件路径,无需修改 kit 或公开 CLI。必需包缺失或已安装包缺少清单会使复制失败;未安装的可选包保留 kit 自身的引擎选择规则。 +[Office kit](2026-09-14-independent-libreoffice-kit.zh.md) 及其已安装依赖树位于显式下载的 sidecar 的 `node_modules`,保留完整包内容与辅助程序权限。顶层 `pkg.ignore` 从 SEA 归档排除 kit 包,包括依赖 `files` 字段选中的资源;与其他使用方共享的小型依赖仍可在 VFS 中使用。Python 私有 bootstrap 使用 Node `registerHooks` 从真实目录解析 kit 入口及其包清单。因此原生可执行程序与 URL Worker 保留普通文件路径,无需修改 kit 或公开 CLI。构建将所选引擎和依赖位置锁定到确切的 npm 归档;下载会在发布缓存前校验完整性。 ### 构建流水线与产物 -[`scripts/build-exe-for-python-sdk.ts`](../../../../scripts/build-exe-for-python-sdk.ts):运行时闭包校验 → `pnpm run build` →(清空后)`pnpm --filter dsh-python-runtime-closure deploy --legacy --prod --config.allow-unused-patches=true --config.node-linker=hoisted --config.auto-install-peers=false --config.link-workspace-packages=true --config.hoist-workspace-packages=false` **直接写入** `python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/`,其中包含作为载体根目录 `runtime-bootstrap.mjs` 的 [`python/sdk-runtime/runtime-bootstrap.mjs`](../../../../python/sdk-runtime/runtime-bootstrap.mjs) → 恢复 legacy deploy 遗漏的直接工作区包,并拒绝剩余的 manifest 缺口 → 将暂存依赖中的符号链接替换为目标文件内容,删除包管理器的 `.bin` 链接,并在仍有任何符号链接时失败 → 验证已部署的 bootstrap,并注入以该文件为 bin 的 pkg 配置及覆盖动态读取 profile、bundle、前端、preset、原生库与配置文件的 assets → 暂存目标平台的 `node-pty` addon → 每个构建目标调用一次 `pkg --sea` → 将 `deepseek-harness-sdk-runtime--` 写入 `dist-exe/`,并将它与对应目标的 Office 目录一同拷回运行时目录。该 bootstrap 由 Python runtime 拥有;普通启动时它调用公开 CLI export,而提供方私有选择会分派到同一个 `@deepseek-ai/dsh-subprocess-local/runner` 核心,不改变 CLI 语法,也不增加另一个可执行文件;[原生 containment 参考](../../../../packages/subprocess/subprocess-local/README.zh.md)负责这条私有路径。Linux CI 会在匹配的 manylinux 2.28 容器中重新构建 `pty.node`,因为 legacy deploy 会遗漏这一安装副作用。每个目标都会把对应的原生 `@vscode/ripgrep` 二进制复制到可执行文件旁,作为必需的 `-rg` 伴随文件;pkg 运行时通过 `process.pkg` 选择该伴随文件,普通 Node 执行则直接使用 `@vscode/ripgrep`。macOS 使用对应目标的预构建产物,并额外生成所需的 `-spawn-helper`。部署标志都有实测依据:未启用 `inject-workspace-packages` 时必须使用 `--legacy`;`hoisted` 提供包目录,再由暂存步骤消除符号链接;只有 pnpm 在载荷根目录记录了相同依赖标识时,暂存步骤才删除对应的嵌套工作区副本,以保留服务单例;关闭工作区提升可排除无关的工作区源码包;关闭对等依赖自动安装可防止未声明的对等依赖扩大闭包;`link-workspace-packages` 选择直接工作区依赖。[`pnpm-workspace.yaml`](../../../../pnpm-workspace.yaml) 将传递的 `@deepseek-ai/cosmokit` 与 `@deepseek-ai/schemastery` semver 请求覆盖到固定的 vendor 源码,使 legacy deploy 不会从注册表解析这些未发布名称。 生产部署允许未使用的工作区补丁,因为开发工具可能不属于运行时闭包;闭包内包的补丁应用失败仍会中止部署。工作区安装继续严格校验未使用的补丁。 +[`scripts/build-exe-for-python-sdk.ts`](../../../../scripts/build-exe-for-python-sdk.ts):运行时闭包校验 → `pnpm run build` →(清空后)`pnpm --filter dsh-python-runtime-closure deploy --legacy --prod --config.allow-unused-patches=true --config.node-linker=hoisted --config.auto-install-peers=false --config.link-workspace-packages=true --config.hoist-workspace-packages=false` **直接写入** `python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/`,其中包含作为载体根目录 `runtime-bootstrap.mjs` 的 [`python/sdk-runtime/runtime-bootstrap.mjs`](../../../../python/sdk-runtime/runtime-bootstrap.mjs) → 恢复 legacy deploy 遗漏的直接工作区包,并拒绝剩余的 manifest 缺口 → 将暂存依赖中的符号链接替换为目标文件内容,删除包管理器的 `.bin` 链接,并在仍有任何符号链接时失败 → 验证已部署的 bootstrap,并注入以该文件为 bin 的 pkg 配置及覆盖动态读取 profile、bundle、前端、preset、原生库与配置文件的 assets → 暂存目标平台的 `node-pty` addon → 每个构建目标调用一次 `pkg --sea` → 将 `deepseek-harness-sdk-runtime--` 写入 `dist-exe/`,并将它与轻量资源清单及 Office skill 资源一同拷回运行时目录。该 bootstrap 由 Python runtime 拥有;普通启动时它调用公开 CLI export,而提供方私有选择会分派到同一个 `@deepseek-ai/dsh-subprocess-local/runner` 核心,不改变 CLI 语法,也不增加另一个可执行文件;[原生 containment 参考](../../../../packages/subprocess/subprocess-local/README.zh.md)负责这条私有路径。Linux CI 会在匹配的 manylinux 2.28 容器中重新构建 `pty.node`,因为 legacy deploy 会遗漏这一安装副作用。每个目标都会把对应的原生 `@vscode/ripgrep` 二进制复制到可执行文件旁,作为必需的 `-rg` 伴随文件;pkg 运行时通过 `process.pkg` 选择该伴随文件,普通 Node 执行则直接使用 `@vscode/ripgrep`。macOS 使用对应目标的预构建产物,并额外生成所需的 `-spawn-helper`。部署标志都有实测依据:未启用 `inject-workspace-packages` 时必须使用 `--legacy`;`hoisted` 提供包目录,再由暂存步骤消除符号链接;只有 pnpm 在载荷根目录记录了相同依赖标识时,暂存步骤才删除对应的嵌套工作区副本,以保留服务单例;关闭工作区提升可排除无关的工作区源码包;关闭对等依赖自动安装可防止未声明的对等依赖扩大闭包;`link-workspace-packages` 选择直接工作区依赖。[`pnpm-workspace.yaml`](../../../../pnpm-workspace.yaml) 将传递的 `@deepseek-ai/cosmokit` 与 `@deepseek-ai/schemastery` semver 请求覆盖到固定的 vendor 源码,使 legacy deploy 不会从注册表解析这些未发布名称。 生产部署允许未使用的工作区补丁,因为开发工具可能不属于运行时闭包;闭包内包的补丁应用失败仍会中止部署。工作区安装继续严格校验未使用的补丁。 CI 使用 [`.github/workflows/build-exe-for-python-sdk.yml`](../../../../.github/workflows/build-exe-for-python-sdk.yml):[安装后 wheel 包验证](../testing/2026-08-23-installed-python-wheel-black-box-ci.zh.md)在拉取请求上运行 Linux/Windows x64,在 master 推送上运行 Linux ARM64 与两种 macOS 架构。[公开发布工作流](../../archived/process/2026-08-11-python-publication-workflow.md)调用它构建全部五个目标;`workflow_dispatch` 仍可选择部分目标。linux-x64、linux-arm64(`ubuntu-24.04-arm`)、macos-arm64、macos-x64(`macos-15-intel`)与 win-x64(`windows-2025`)分别进行原生构建,并在适用平台缓存 `~/.pkg-cache`;macOS 的 ad-hoc 签名由 pkg 处理。每个平台都把发布形态的 SDK wheel 包与运行时 wheel 包安装到 checkout 外的干净 venv,证明包与可执行文件来源,再通过公开 SDK 与直接 NDJSON JSON-RPC 运行完整 keyless 场景。可信拉取请求与 master 推送还会在各自选定的目标上运行真实 DeepSeek 双轮工具冒烟测试;fork 与 Dependabot head 不会获得密钥。Linux 会检查可执行文件和原生 addon 各自的 GLIBC 依赖,并额外运行 manylinux 2.28 冒烟测试;macOS 则检查 runtime、ripgrep 与 PTY helper 的架构,并验证三个载荷的部署目标都符合 wheel 包标签。完整构建五个目标时保留 6 个产物,每个产物只含一个发布文件:平台无关的 SDK wheel 包与 5 个原生运行时 wheel 包;手动选择部分目标时保留 SDK wheel 与所选运行时 wheel。裸 exe 与源码包只作为测试中间输入。[`.gitlab-ci.yml`](../../../../.gitlab-ci.yml) 只接受版本与根目录 `package.json` 匹配的 `python-v` 标签流水线,构建一个 SDK wheel 包和 5 个原生运行时 wheel 包,再由单个串行任务校验并将这 6 个文件发布到项目的 PyPI 注册表。[`python/sdk-runtime` README](../../../../python/sdk-runtime/README.zh.md)负责 Windows 目标及对 Windows arm64 的明确排除。 ### Python SDK 分发:双载体,exe 用于生产,`node` 用于开发 -Python SDK 位于 [`python/`](../../../../python/README.zh.md):`python/sdk` 是客户端,`python/sdk-runtime` 是运行时载体包。运行时包的数据目录包含构建注入的平台可执行文件及其必需的 `-rg` 伴随文件、`-office/` 目录和可选的 macOS helper,以及供仓库开发使用的构建注入 `runtime/node/` 闭包树。`resolve_bundled_launch_args()` 默认选择可执行文件;显式设置 `DSH_RUNTIME_MODE=node` 会在系统 Node 22.19 或更高版本上运行 `runtime/node/node_modules/@deepseek-ai/dsh/lib/bin.js`。node 载体从不进入 wheel 分发,两种载体都不使用检入的完整 `cordis.yml`。 +Python SDK 位于 [`python/`](../../../../python/README.zh.md):`python/sdk` 是客户端,`python/sdk-runtime` 是运行时载体包。运行时包的数据目录包含构建注入的平台可执行文件及其必需的 `-rg` 伴随文件、轻量下载元数据与 Office skills 和可选的 macOS helper,以及供仓库开发使用的构建注入 `runtime/node/` 闭包树。`resolve_bundled_launch_args()` 默认选择可执行文件;显式设置 `DSH_RUNTIME_MODE=node` 会在系统 Node 22.19 或更高版本上运行 `runtime/node/runtime-bootstrap.mjs`。node 载体从不进入 wheel 分发,两种载体都不使用检入的完整 `cordis.yml`。 -[`scripts/build-python-release.py`](../../../../scripts/build-python-release.py) 从仓库根目录的 `package.json` 读取权威的 `X.Y.Z` 或预发布版本,把预发布版本转换为 PEP 440 写法,并以该 wheel 包版本暂存两个包,让 `deepseek-harness-sdk` 精确依赖匹配版本的 `deepseek-harness-runtime-bin`。可选的 `python-v` 发布标签只是一项一致性断言,与仓库版本不同时会被拒绝;源码 `pyproject.toml` 中的开发占位版本从不决定发布版本。暂存过程还会把仓库许可证放入两个 wheel 包,并把第三方声明放入内置运行时 wheel 包。SDK 是 `py3-none-any` wheel 包;每个只提供 wheel 包的运行时包都包含一个 exe、其 Office 目录及架构匹配的 ripgrep 伴随文件,macOS wheel 包还包含与其架构匹配的 spawn helper。运行时 wheel 包使用 `py3-none-manylinux_2_28_x86_64`、`py3-none-manylinux_2_28_aarch64`、`py3-none-macosx_14_0_arm64`、`py3-none-macosx_14_0_x86_64` 或 `py3-none-win_amd64`;Hatch 钩子拒绝 sdist、通用标签、混合平台载荷、伴随文件缺失或多余,以及不支持的平台。两个 macOS 标签都会特意声明保守的 14.0 安装下限:打包后的 Node 24 可执行文件声明 macOS 13.5,x64 PTY helper 声明 10.7,但发布验证只按照 14.0 wheel 声明证明完整载荷,不会把各组件实测的最低版本承诺为受支持宿主。两个 macOS wheel 包仍按架构分别发布,不发布 universal2 wheel 包。 +[`scripts/build-python-release.py`](../../../../scripts/build-python-release.py) 从仓库根目录的 `package.json` 读取权威的 `X.Y.Z` 或预发布版本,把预发布版本转换为 PEP 440 写法,并以该 wheel 包版本暂存两个包,让 `deepseek-harness-sdk` 精确依赖匹配版本的 `deepseek-harness-runtime-bin`。可选的 `python-v` 发布标签只是一项一致性断言,与仓库版本不同时会被拒绝;源码 `pyproject.toml` 中的开发占位版本从不决定发布版本。暂存过程还会把仓库许可证放入两个 wheel 包,并把第三方声明放入内置运行时 wheel 包。SDK 是 `py3-none-any` wheel 包;每个只提供 wheel 包的运行时包都包含一个 exe、轻量资源元数据与 skills 及架构匹配的 ripgrep 伴随文件,macOS wheel 包还包含与其架构匹配的 spawn helper。运行时 wheel 包使用 `py3-none-manylinux_2_28_x86_64`、`py3-none-manylinux_2_28_aarch64`、`py3-none-macosx_14_0_arm64`、`py3-none-macosx_14_0_x86_64` 或 `py3-none-win_amd64`;Hatch 钩子拒绝 sdist、通用标签、混合平台载荷、伴随文件缺失或多余,以及不支持的平台。两个 macOS 标签都会特意声明保守的 14.0 安装下限:打包后的 Node 24 可执行文件声明 macOS 13.5,x64 PTY helper 声明 10.7,但发布验证只按照 14.0 wheel 声明证明完整载荷,不会把各组件实测的最低版本承诺为受支持宿主。两个 macOS wheel 包仍按架构分别发布,不发布 universal2 wheel 包。 Python 客户端使用所选 profile(默认 `sdk`)、有序 patch 文件和显式 Harness home 启动打包后的 `dsh` 命令。Profile 负责 JSON-RPC 服务和应用组合;缺失 home、profile、bundle、patch 或 server 配置项都会失败,不存在外部完整配置回退。 @@ -74,7 +74,7 @@ Python 客户端使用所选 profile(默认 `sdk`)、有序 patch 文件和 手工驱动注意:`bin` 将 stdin EOF 视为「客户端已离开」并立即 dispose,生命周期较短的管道会中止进行中的轮次——管道驱动必须保持 stdin 打开,直到轮次结束。 -安装后 wheel 的 `sdk-office` 场景会将目标的完整载荷复制到私有临时目录,要求仅存在一个目标后端(使用已声明的原生目标,未声明原生目标时使用 WASM),并通过随附 SDK profile 使用该引擎转换一次 DOCX。它检查 kit 模块确实解析到迁移后的目录、转换报告预期后端,且输出包含 PDF 字节。wheel 校验会检查声明的引擎资源与原生辅助程序执行位;CI 上传已完成的 wheel,因此嵌套辅助程序权限保留在 ZIP 归档中。 +安装后 wheel 的 `sdk-office` 场景迁移轻量 wheel 载荷,并显式下载完整 npm Office sidecar 及其独立 Node。它要求仅有一个目标后端,验证 SDK 从下载的 sidecar 加载 kit,并通过 skill CLI 在空 PATH 下转换 DOCX。Python Office 操作使用同一 CLI。显式下载复用现有构建准备实现;SDK 启动不执行下载。[运行时参考](../../../../python/sdk-runtime/README.zh.md)拥有缓存和启用行为的说明。 ## 曾考虑的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.i18n.yaml index ca2693afef..d3c4c85807 100644 --- a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.i18n.yaml @@ -15,8 +15,8 @@ en: 4921a060c657b790 zh: 2f9632469c6f0b60 /agent-note-provider-routed-llm-adapters-and-a-generic-pi-ai-backend/decision/explicit-pi-ai-provider-profiles: - en: e24610c474a94bc4 - zh: 96a89035cb8eabf9 + en: 1346315312eb35e2 + zh: 3555f91c3afb49f8 /agent-note-provider-routed-llm-adapters-and-a-generic-pi-ai-backend/decision/recorded-assistant-route-and-replay-state: en: ed60d078eacc67df zh: a22631faf93deee2 diff --git a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.md b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.md index b205104489..d06af266ec 100644 --- a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.md +++ b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.md @@ -36,6 +36,8 @@ The adapter calls pi-ai's `streamSimple()` so each catalog model chooses its reg pi-ai's common stream options do not expose stop sequences. `dsh-llm-pi-ai` rejects a defined Harness `stop` option with `UNSUPPORTED_OPTION` rather than silently ignoring it or growing a second provider-specific payload implementation. `dsh-llm-deepseek` continues to support `stop` through its native request serializer. +pi-ai owns protocol-specific system-message placement and the concatenation fallback for models without in-history system support. Harness preserves later system messages in transcript order and reports catalog capabilities to prompt admission and shared tool-history projection. Duplicating pi-ai's fallback or applying Anthropic's placement rules to every protocol would create a second serialization policy that can drift when pi-ai changes. Capability reporting remains a Harness responsibility because the loop needs it before serialization. + ### Recorded assistant route and replay state Assistant messages carry the request's `provider` and `model`, plus an optional JSON-serializable adapter replay state. A successful `assistant/message` session event records those fields and `deriveMessages()` returns them with the assistant message. User, system, context, and tool-result messages carry no assistant route fields. The provider/model fields are authoritative loop data; an adapter owns only its opaque replay-state payload. diff --git a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.zh.md b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.zh.md index b838d7255a..d07312ce99 100644 --- a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.zh.md @@ -36,6 +36,8 @@ Status: implemented pi-ai 的通用流选项不支持停止序列。若 Harness `stop` 选项已定义,`dsh-llm-pi-ai` 会以 `UNSUPPORTED_OPTION` 拒绝请求,不会静默忽略,也不会增加第二套提供方专用 payload 实现。`dsh-llm-deepseek` 继续通过原生请求序列化器支持 `stop`。 +pi-ai 负责各协议的系统消息位置,以及不支持历史内系统消息的模型所需的拼接回退。Harness 按对话记录顺序保留后续系统消息,并向提示词准入和共享工具历史投影报告目录能力。重复实现 pi-ai 的回退,或将 Anthropic 的位置规则应用于所有协议,会形成第二套序列化策略,并可能随 pi-ai 的变化而偏离。能力报告仍由 Harness 负责,因为循环在序列化之前就需要这些信息。 + ### 已记录的助手路由与回放状态 助手消息携带请求的 `provider` 和 `model`,以及可选的 JSON 可序列化适配器回放状态。成功的 `assistant/message` 会话事件记录这些字段,`deriveMessages()` 返回助手消息时也会包含它们。用户、系统、上下文与工具结果消息不携带助手路由字段。提供方/模型字段是 agent loop 的权威数据;适配器仅拥有其不透明回放状态 payload。 diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml index 7354602835..4573f0a33f 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml @@ -27,8 +27,8 @@ en: fbd101d4576afa92 zh: 35f5d3c2f6cad6a8 /agent-note-cooperative-tool-cancellation-at-the-registry-boundary/alternatives-considered: - en: 1f205f1a78d4fd5b - zh: 6c17e35da2909302 + en: c4d86feb135d2ac4 + zh: 67c56c0bc2213949 /agent-note-cooperative-tool-cancellation-at-the-registry-boundary/consequences: en: 24a9ad2c4c7c86b5 zh: debdd29d272e07ea diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md index 5ca2b44b24..967c7285df 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md @@ -62,7 +62,7 @@ No registry test can prove that arbitrary third-party same-process code observes **Forbid around wrappers from replacing the signal.** Rejected because deadlines and nested operational scopes need lexical derivation. Capturing and fusing the caller signal preserves composition without allowing detachment. -**Race the tool promise against cancellation.** Rejected because it reports completion while side effects may remain live, violating the [quiescent-disposal rule](../../../../docs/defensive-patterns.md#dispose-must-reach-quiescence-not-just-request-it). +**Race the tool promise against cancellation.** Rejected because it reports completion while side effects may remain live, violating the [quiescent-disposal rule](../../../../docs/defensive-patterns/general.md#dispose-must-reach-quiescence-not-just-request-it). ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md index d6d49fb44c..87318c3316 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md @@ -62,7 +62,7 @@ Status: implemented **禁止环绕包装层替换信号。** 不予采纳,因为截止时间和嵌套操作作用域需要词法派生信号。捕获并融合调用方信号既保留组合能力,也不允许切断调用方取消。 -**让工具 promise 与取消竞速。** 不予采纳,因为这种方式会在副作用仍可能存活时报告完成,违反[dispose(资源释放)必须完全停稳的规则](../../../../docs/defensive-patterns.zh.md#dispose-must-reach-quiescence-not-just-request-it)。 +**让工具 promise 与取消竞速。** 不予采纳,因为这种方式会在副作用仍可能存活时报告完成,违反[dispose(资源释放)必须完全停稳的规则](../../../../docs/defensive-patterns/general.zh.md#dispose-must-reach-quiescence-not-just-request-it)。 ## 后果 diff --git a/.agents/notes/implemented/architecture/2026-07-27-compiler-independent-typert-model.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-27-compiler-independent-typert-model.i18n.yaml index 50fa27df10..9f174f4f54 100644 --- a/.agents/notes/implemented/architecture/2026-07-27-compiler-independent-typert-model.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-27-compiler-independent-typert-model.i18n.yaml @@ -18,5 +18,5 @@ en: fa503dcfaa6f438f zh: 26052212a124e133 /agent-note-compiler-independent-typert-type-model/consequences: - en: 4a472acf377f8361 - zh: cb83602b123a4aae + en: e1022cf9523fb28e + zh: 01dfb764fb98de0d diff --git a/.agents/notes/implemented/architecture/2026-07-27-compiler-independent-typert-model.md b/.agents/notes/implemented/architecture/2026-07-27-compiler-independent-typert-model.md index 5083c55176..6ca9186f7f 100644 --- a/.agents/notes/implemented/architecture/2026-07-27-compiler-independent-typert-model.md +++ b/.agents/notes/implemented/architecture/2026-07-27-compiler-independent-typert-model.md @@ -51,3 +51,5 @@ For each supported node kind and literal category, Zod emitter tests run both su New generation targets and static checks can reuse the same TypeGraph, and business categories can extend PackageModel without parsing the AST again. Preserving pre-evaluation types and independent faces makes the model more complex than a flattened schema; emitters must explicitly declare their supported scope and fail on missing capabilities. Explicit package opt-in keeps artifact publication and exports under package ownership. Repository orchestration may still run the whole-workspace Host contract pass for every opted-in package; that pass remains owned by the later Remote Gateway Agent Note. The static Cordis catalogs remain reproducible from the canonical model without coupling `tool-cordis` to runtime registry state. `ctx.typert` reflects only artifacts mounted in the current runtime, and unloading does not control Zod instances that consumers retain after materializing them. + +Ordinary Host and Remote artifacts reuse this model to emit one static method spec per endpoint. Each parameter has normal `codec` and `strictCodec` variants derived from the same checker-resolved type model; neither analysis nor the model carries a per-method input policy. A pure factory returns a lazy info instance whose direct method index and descriptor list share objects; the existing Registry retains those descriptors, while `TYPERT_REMOTE.methods` supplies exact static types. The [unified Typert/Remote metadata note](../../proposed/architecture/2026-09-20-unified-typert-remote-metadata.md) records this delivery mechanism and the incomplete downstream adaptation. Declaration and face-isolation rules remain unchanged; separate Programs and processes do not share object identity. diff --git a/.agents/notes/implemented/architecture/2026-07-27-compiler-independent-typert-model.zh.md b/.agents/notes/implemented/architecture/2026-07-27-compiler-independent-typert-model.zh.md index 70d6954fae..1a4a870fab 100644 --- a/.agents/notes/implemented/architecture/2026-07-27-compiler-independent-typert-model.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-27-compiler-independent-typert-model.zh.md @@ -51,3 +51,5 @@ Zod emitter 对支持的节点和各类 literal 逐类执行成功与失败 pars 新增生成目标或静态检查可复用同一 TypeGraph,业务类目也可在 PackageModel 上扩展,而无需再次解析 AST。保留计算前类型和独立 face 的代价是模型比打平后的 schema 更复杂,emitter 必须显式声明支持范围并对缺失能力失败。 包级显式 opt-in 使产物发布与 exports 由各包自行管理。仓库编排仍可为每个已 opt-in 的包运行全仓 Host 约定 pass;该 pass 仍由后续 Remote Gateway Agent Note 负责说明。静态 Cordis catalog 可从标准模型复现,同时不把 `tool-cordis` 与运行时注册表状态耦合。`ctx.typert` 只反映当前运行时中已挂载的产物;对于消费方物化后仍持有的 Zod 实例,卸载流程无法控制。 + +普通 Host 与 Remote 产物复用此模型,为每个端点生成一份静态方法 spec。每个参数都有从同一 checker 解析后类型模型派生的普通 `codec` 和 `strictCodec` 变体;分析过程与模型均不携带逐方法输入策略。纯 factory 返回惰性 info 实例,其直接方法索引与描述符列表共享对象;既有 Registry 保留这些描述符,而 `TYPERT_REMOTE.methods` 提供精确静态类型。[统一 Typert/Remote 元数据 note](../../proposed/architecture/2026-09-20-unified-typert-remote-metadata.zh.md)记录该交付机制及尚未完成的下游适配。声明与编译面隔离规则保持不变;独立 Program 和进程不共享对象身份。 diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml index a102c752b0..fefceef44e 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml @@ -9,11 +9,11 @@ en: c25db2ef111b2276 zh: 557891ca9e030ae5 /agent-note-one-carrier-level-browser-trust-boundary-for-all-api-routes/decision: - en: 1a1af1e8125ba4b0 - zh: dd6c282651a06af5 + en: ca8044c9e0013be6 + zh: d60af7af291299c3 /agent-note-one-carrier-level-browser-trust-boundary-for-all-api-routes/alternatives-considered: en: 1a4b0ae8072e8e50 zh: d469553ad3b5d112 /agent-note-one-carrier-level-browser-trust-boundary-for-all-api-routes/consequences: - en: 8acf5e6f55a747c2 - zh: bbd0b10927302965 + en: e31df28a2e82a64d + zh: 4ca7097ebbc24cd2 diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md index 397c93e084..9b0c573210 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md @@ -13,9 +13,11 @@ The web GUI host serves `/api` over plain loopback HTTP (default `127.0.0.1:3080 Enforce browser trust once, at the carrier, for the entire `/api` prefix — two halves: - **Media-type fence (dsh-client-connection)**: every `/api` POST must declare `application/json`, else 415 before parsing. Cross-site "simple" requests thereby stop existing: any cross-site attempt is forced into a CORS preflight this server never answers. -- **Authority fence (dsh-client-connection, `src/api-request-trust.ts`)**: every request must present a `Host` that is loopback or matches a `trustedHosts` entry (exact on `host:port`, any port on port-less entries, WHATWG-normalized; rebinding defense). Deliberately no shortcut for unmarked requests: over plain HTTP a browser attaches neither `Origin` nor Fetch-Metadata to reads (EventSource, images, navigations — those headers go only to trustworthy destinations), so an unmarked request may be a rebound browser read whose response the page can read, and Host is the one header rebinding cannot forge; non-browser clients pass via loopback, the derived LAN IP literals, or a declared authority. An attached `Origin` must equal the Host authority; `sec-fetch-site: cross-site` is refused outright. A `trustedHosts` entry that is not a bare, canonical authority fails the plugin load — WHATWG parsing would otherwise quietly authorize the hostname inside a typo or broaden an exact-port grant. `host.pickDirectory` loses its bespoke guard and rides the same fence. +- **Authority fence (dsh-client-connection, `src/api-request-trust.ts`)**: every request must present a `Host` that is loopback or matches a `trustedHosts` entry (exact on `host:port`, any port on port-less entries, WHATWG-normalized; rebinding defense). Deliberately no shortcut for unmarked requests: over plain HTTP a browser attaches neither `Origin` nor Fetch-Metadata to reads (EventSource, images, navigations — those headers go only to trustworthy destinations), so an unmarked request may be a rebound browser read whose response the page can read, and Host is the one header rebinding cannot forge; non-browser clients pass via loopback, a declared authority, or the listener's own bind literal that [Bind one concrete Web address](2026-09-19-concrete-web-bind-address.md) admits. An attached `Origin` must equal the Host authority; `sec-fetch-site: cross-site` is refused outright. A `trustedHosts` entry that is not a bare, canonical authority fails the plugin load — WHATWG parsing would otherwise quietly authorize the hostname inside a typo or broaden an exact-port grant. `host.pickDirectory` loses its bespoke guard and rides the same fence. -Reachability is the webserver binding's policy (`host: 127.0.0.1 | 0.0.0.0`), and this fence is a confused-deputy defense rather than identity. Connection applies the separate [browser token authentication](2026-08-24-browser-token-authentication.md) after the fence. The fence does not inspect peer socket addresses: binding expresses reachability, `trustedHosts` names accepted authorities, and the socket address adds nothing the Host/Origin checks need. +Reachability is the webserver binding's policy (`host`; [Bind one concrete Web address](2026-09-19-concrete-web-bind-address.md) owns which literals it accepts), and this fence is a confused-deputy defense rather than identity. Connection applies the separate [browser token authentication](2026-08-24-browser-token-authentication.md) after the fence. The fence does not inspect peer socket addresses: binding expresses reachability, `trustedHosts` names accepted authorities, and the socket address adds nothing the Host/Origin checks need. + +`HostConnectionHandle.allowsRemoteAuthorities` projects whether any validated `trustedHosts` entry names a non-loopback hostname: a loopback listener behind a proxy can still serve remote browsers, so the directory picker requires a policy without remote authorities before it picks the native chooser. ## Alternatives considered @@ -26,6 +28,6 @@ Reachability is the webserver binding's policy (`host: 127.0.0.1 | 0.0.0.0`), an ## Consequences - Any future `/api` method is covered by construction; there is no per-route trust decision left to forget. -- A custom non-loopback composition must trust its serving authorities or requests are refused, then satisfy browser authentication like every loopback request. The shipped CLI rejects `--host 0.0.0.0`; `--trusted-host` only extends the Host/Origin fence and grants no identity. +- A non-loopback listener accepts its own bind IP directly ([Bind one concrete Web address](2026-09-19-concrete-web-bind-address.md)); other remote authorities require configured trust. Every accepted authority still requires browser authentication. `--trusted-host` extends only the Host/Origin fence and grants no identity. - Clients must label POST bodies `application/json` (ours always did; raw-fetch tests gained the header). - Host and Origin remain request-routing evidence only. The process token and signed cookie establish the browser identity used by every Host method. diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md index 6d3896fd2c..0721f0bf6b 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md @@ -13,9 +13,11 @@ Web GUI 宿主以纯 loopback HTTP 提供 `/api`(默认 `127.0.0.1:3080`;CLI 在载体层对整个 `/api` 前缀一次性执行浏览器信任检查——分为两部分: - **媒体类型栅栏(dsh-client-connection)**:每个 `/api` POST 必须声明 `application/json`,否则在解析前以 415 拒绝。跨站「简单请求」由此不复存在:任何跨站尝试都被逼进一次本服务器从不应答的 CORS 预检。 -- **权威栅栏(dsh-client-connection,`src/api-request-trust.ts`)**:每个请求的 `Host` 都必须是回环地址,或与某个 `trustedHosts` 条目匹配(带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,均经 WHATWG 归一化;rebinding 防御)。刻意不为无标记请求开捷径:明文 HTTP 下浏览器的读取(EventSource、图片、导航——这些头只发给可信目标)既不带 `Origin` 也不带 Fetch-Metadata,因此无标记请求可能是被重绑页面发起且响应可被读走的读取,而 Host 是重绑唯一伪造不了的请求头;非浏览器客户端经由回环地址、推导的 LAN IP 字面量或已声明的权威通过。若带 `Origin` 则必须与 Host 权威完全一致;`sec-fetch-site: cross-site` 一律拒绝。不是单纯规范化 authority 的 `trustedHosts` 条目会导致插件加载失败——否则 WHATWG 解析会悄悄授权笔误里的 hostname,或放大精确端口授权。`host.pickDirectory` 失去专属守卫,与其他请求同栅而行。 +- **权威栅栏(dsh-client-connection,`src/api-request-trust.ts`)**:每个请求的 `Host` 都必须是回环地址,或与某个 `trustedHosts` 条目匹配(带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,均经 WHATWG 归一化;rebinding 防御)。刻意不为无标记请求开捷径:明文 HTTP 下浏览器的读取(EventSource、图片、导航——这些头只发给可信目标)既不带 `Origin` 也不带 Fetch-Metadata,因此无标记请求可能是被重绑页面发起且响应可被读走的读取,而 Host 是重绑唯一伪造不了的请求头;非浏览器客户端经由回环地址、已声明的权威,或[绑定一个具体的 Web 地址](2026-09-19-concrete-web-bind-address.zh.md)所接纳的监听器自身绑定字面量通过。若带 `Origin` 则必须与 Host 权威完全一致;`sec-fetch-site: cross-site` 一律拒绝。不是单纯规范化 authority 的 `trustedHosts` 条目会导致插件加载失败——否则 WHATWG 解析会悄悄授权笔误里的 hostname,或放大精确端口授权。`host.pickDirectory` 失去专属守卫,与其他请求同栅而行。 -可达性由 webserver 的绑定配置(`host: 127.0.0.1 | 0.0.0.0`)控制,这道栅栏是混淆代理人防御,而不是身份。Connection 在栅栏之后应用独立的[浏览器令牌认证](2026-08-24-browser-token-authentication.zh.md)。栅栏不检查对端 socket 地址:绑定表达可达性,`trustedHosts` 点名接受的 authority,socket 地址提供不了 Host/Origin 校验需要的额外信息。 +可达性由 webserver 的绑定配置(`host`;[绑定一个具体的 Web 地址](2026-09-19-concrete-web-bind-address.zh.md)拥有它接受哪些字面量)控制,这道栅栏是混淆代理人防御,而不是身份。Connection 在栅栏之后应用独立的[浏览器令牌认证](2026-08-24-browser-token-authentication.zh.md)。栅栏不检查对端 socket 地址:绑定表达可达性,`trustedHosts` 点名接受的 authority,socket 地址提供不了 Host/Origin 校验需要的额外信息。 + +`HostConnectionHandle.allowsRemoteAuthorities` 表示是否有通过校验的 `trustedHosts` 条目命名非回环主机名:代理后的回环监听器也能服务远程浏览器,因此目录选择器要求策略不接纳远程 authority,才会选择原生交互。 ## 曾考虑的替代方案 @@ -26,6 +28,6 @@ Web GUI 宿主以纯 loopback HTTP 提供 `/api`(默认 `127.0.0.1:3080`;CLI ## 后果 - 未来任何 `/api` 方法天然在覆盖范围内;不存在会被遗忘的按路由信任决定。 -- 自定义非 loopback 组合必须信任其服务 authority,否则请求会被拒绝;随后仍像每个 loopback 请求一样满足浏览器认证。随附 CLI 拒绝 `--host 0.0.0.0`;`--trusted-host` 只扩展 Host/Origin 栅栏,绝不授予身份。 +- 非回环监听器直接接受自己的绑定 IP([绑定一个具体的 Web 地址](2026-09-19-concrete-web-bind-address.zh.md));其他远程 authority 需要配置的信任。每个被接受的 authority 仍须满足浏览器认证。`--trusted-host` 只扩展 Host/Origin 栅栏,绝不授予身份。 - 客户端必须给 POST 体标注 `application/json`(我们自己的客户端一向如此;裸 fetch 测试补上了该头)。 - Host 与 Origin 仍只是请求路由证据。进程令牌与签名 cookie 建立每个 Host 方法使用的浏览器身份。 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 9e09fd093d..053989716f 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 @@ -12,14 +12,14 @@ en: 44d946b53496974c zh: 403447c25a5b2d7c /agent-note-typert-gateway-targeted-method-calls/components-and-cordis-services: - en: aa7f509189ade32e - zh: ef2841bc793f31b2 + en: 02c20706e48467e6 + zh: 2b0916ae0cee351b /agent-note-typert-gateway-targeted-method-calls/business-declarations: - en: c6b70d442b137d2e - zh: 6d0dbefe89937ef1 + en: b9394d5ef98cc82a + zh: 1fce07fe150722ee /agent-note-typert-gateway-targeted-method-calls/decorators-and-the-explicit-gateway-facet: - en: 155afbe4b8af600b - zh: 14705698a9cdbd84 + en: 161dccf2b4cf565d + zh: fa587fe0b46bf551 /agent-note-typert-gateway-targeted-method-calls/lookup-and-remote-scope-registration: en: 9f7448898cf5cadc zh: 419573c589ed6f7d @@ -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: 91033aab32e4d8eb zh: a11ada70e047af55 @@ -48,8 +48,8 @@ en: 5d14e1b7afc53efb zh: e2f4b5814083738f /agent-note-typert-gateway-targeted-method-calls/src-and-lib-operating-modes: - en: 1e366dcfab74831b - zh: 14199f25f20a9352 + en: f1b8426d1cfaed35 + zh: a370376923c98d6e /agent-note-typert-gateway-targeted-method-calls/host-gateway-resolution: en: 88a95d7ab4621caf zh: 89b63fb6440fca79 @@ -66,11 +66,11 @@ en: b1c0c3dd77c56ce8 zh: 769ffd4aeefd949c /agent-note-typert-gateway-targeted-method-calls/alternatives-considered: - en: 0d68c499b7780f4f - zh: bdd1e57232b996e2 + en: eaa3ffe5ca14005c + zh: 1f0b455e30ade872 /agent-note-typert-gateway-targeted-method-calls/verification: en: 7433bdb522bb2083 zh: 545c17613b636f00 /agent-note-typert-gateway-targeted-method-calls/consequences: - en: c3459afdb606cfbe - zh: ec69f2bb39170a7c + en: abab48251550f584 + zh: 2568c46d78dbefdf 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 6fdd5ebd5c..ee161b2469 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 @@ -28,7 +28,7 @@ The Remote consumer projection contains `.d.ts`, `.d.ts.map`, and `.js` files. T | Component | Cordis service | Responsibility | |---|---|---| -| `@deepseek-ai/dsh-typert-protocol` | Declares only the minimal `ctx.typert` protocol | `TypertRemoteService`, decorators, binding fallback, descriptors, lookup/Context, and the Remote map; no dependency on the compiler, Zod, Connection, or Browser | +| `@deepseek-ai/dsh-typert-protocol` | Declares only the minimal `ctx.typert` protocol | `TypertRemoteService`, decorators, binding fallback, descriptors, lookup/Context, the Remote map, and Zod-backed lazy info assembly; no dependency on the compiler, Connection, or Browser | | Typert registry | `ctx.typert` | Separately stores reflection for the current environment, imported Remote contributions, lookup providers, and Context providers | | Typert generator/loader | No new business service | Generates three kinds of `lib` artifacts from the Host/Client Programs and registers the current environment's artifacts with `ctx.typert` | | API Gateway's Host face | `ctx.typertGateway` | Associates Host definitions with live Services, decodes parameters, resolves receivers, invokes methods, and projects unary results into carrier-neutral fields and attachments | @@ -81,16 +81,18 @@ export class ScopedGoalService extends TypertRemoteService { An endpoint selects exactly one invocation mode. A flow that needs an explicit `Agent` parameter uses `@Remote`. A flow that first switches to an Agent Context and then resolves a scoped receiver uses `@RemoteScope('agent')`. Typert does not infer either mode from the method body or from a missing parameter. -Business packages depend only on the lightweight `@deepseek-ai/dsh-typert-protocol`. It provides `TypertRemoteService` and declaration protocols for decorators, the binding fallback, lookup, Remote Scope, and descriptors, without depending on the TypeScript compiler, Zod, HTTP, or the Client runtime. +Business packages depend only on `@deepseek-ai/dsh-typert-protocol`. It provides `TypertRemoteService` and declaration protocols for decorators, the binding fallback, lookup, Remote Scope, and descriptors, without depending on the TypeScript compiler, HTTP, or the Client runtime. Its pure `./remote-info` entry uses Zod to assemble lazy named-input schemas without importing Cordis; the root entry also re-exports it alongside Cordis-backed declarations. A method that cooperatively supports cancellation declares `signal: AbortSignal` as its final Host parameter. This reserved parameter is not a business value, lookup, or JSON field. The generated consumer method exposes it as a final optional parameter so ordinary calls remain unchanged while callers that own cancellation can pass a signal. ## Decorators and the explicit Gateway facet -A decorator only states that a method participates in the Remote contract. It performs no runtime type reflection and injects no hidden symbol into a Service constructor. The arguments to `@Remote('create')` and `@RemoteScope('agent', 'create')` are external method names; the decorated member may be the business method itself or an adapter such as `remoteExportCreate`. The member name becomes the external method name only when no alias is provided. Inheriting `TypertRemoteService` is the normal explicit declaration that a Service has joined the Gateway; its public readonly `typertGateway` field keeps the binding visible on the runtime instance. +A decorator states Remote participation, an optional export name, and stream delivery; `@Remote` options contain only `name` and `mode`. It performs no runtime type reflection and injects no hidden symbol into a Service constructor. The arguments to `@Remote('create')` and `@RemoteScope('agent', 'create')` are external method names; the decorated member may be the business method itself or an adapter such as `remoteExportCreate`. The member name becomes the external method name only when no alias is provided. Inheriting `TypertRemoteService` is the normal explicit declaration that a Service has joined the Gateway; its public readonly `typertRemote` field keeps the binding visible on the runtime instance. In SRC mode, the decorator records the method name and invocation mode in a versioned descriptor on the Service prototype. The descriptor uses a stable string property name, so `remoteMethods()` can read markers produced by another installed copy of `dsh-typert-protocol`; it writes nothing to the Service instance, constructor, or method function. +Ordinary artifacts construct a lazy Remote info instance from one static method spec per endpoint. Its direct `TypertRemoteMethod` objects retain descriptor fields and add named `input(options?)` and `invoke`. Consumers select matching strict parsing and projection with `input({ strict: true })`; `input()` preserves normal handling. Host parameter codecs and the single normal `result` codec are unchanged. Existing Registry queries retain those objects, while `TYPERT_REMOTE.methods` supplies exact static types. Strict source startup prebuilds and loads ordinary Typert artifacts; fallback cannot recover erased schemas. The [unified metadata note](../../proposed/architecture/2026-09-20-unified-typert-remote-metadata.md) records this delivery mechanism and the incomplete consumer adaptation. + In LIB mode, the Typert compiler performs strict method discovery, type resolution, and descriptor generation. It accepts a literal service key in `TypertRemoteService`'s direct `super()` call or the explicit binding fallback; generation neither rewrites business source nor injects hidden registration metadata. ## Lookup and Remote Scope registration @@ -215,7 +217,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. @@ -349,9 +351,9 @@ The Web already depends on build artifacts such as `lib/client.js`, so it requir ## SRC and LIB operating modes -SRC supports local source startup. The versioned prototype descriptors created by `@Remote` and `@RemoteScope()` provide method names and invocation modes. At runtime, the system reads ordered parameter names from the JavaScript function signature and combines them with registered lookup/Context providers to produce a permissive descriptor. +SRC supports local source startup. For methods without registered strict definitions, the versioned prototype descriptors created by `@Remote` and `@RemoteScope()` provide method names and invocation modes. At runtime, the system reads ordered parameter names from the JavaScript function signature and combines them with registered lookup/Context providers to produce a permissive descriptor. -For example, `@Remote('create') remoteExportCreate(agent, request, signal)` resolves to the external method `create`, implementation member `remoteExportCreate`, two top-level business parameters, and one cancellation injection point. Lookup registration rewrites `agent` to the wire field `agentId`, `request` is passed as a same-named JSON parameter, and the final `signal` stays outside the payload. SRC does not start a `ts.Program`, use a preload or loader hook, generate or rewrite source, or inspect the internal structure of an ordinary JSON object. +For example, `@Remote('create') remoteExportCreate(agent, request, signal)` resolves to the external method `create`, implementation member `remoteExportCreate`, two top-level business parameters, and one cancellation injection point. Lookup registration rewrites `agent` to the wire field `agentId`, `request` is passed as a same-named JSON parameter, and the final `signal` stays outside the payload. The conservative fallback does not start a `ts.Program`, use a preload or loader hook, generate or rewrite source, or inspect the internal structure of an ordinary JSON object. A signature that SRC cannot resolve unambiguously fails on the first invocation that resolves its descriptor; Service mounting records only the decorator marker and does not inspect the JavaScript signature. SRC does not guess at object destructuring, ambiguity caused by default parameters, rest parameters, nested lookups, or complex types. @@ -474,7 +476,7 @@ The package topology is `api/remotes → api/gateway → client/connection → h **Perform strict reflection through decorators at runtime.** JavaScript decorators cannot recover erased TypeScript types, public symbol identity, or complete Zod codecs. Injecting a compiler-private symbol into a constructor would also hide the business class's real dependencies, so Typert generates strict information at compile time. -**Use a preload, loader hook, or complete `ts.Program` during SRC startup.** This could reuse LIB analysis but would add requirements to every source startup entry. SRC needs only a usable permissive descriptor, so it uses decorator markers, function parameter names, and explicit providers; strict checks remain in the LIB contract pass. +**Use a preload, loader hook, or complete `ts.Program` during SRC startup.** This could reuse LIB analysis but would add requirements to every source startup entry. Source startup can load ordinary prebuilt artifacts or use conservative markers without loading a TypeScript Program. **Hand-write the Client interface.** A hand-written interface cannot guarantee that it contains only Remote-marked methods and can drift from Host signatures, lookup IDs, and Zod schemas. Client types are therefore projected automatically from the Host Program. @@ -520,7 +522,7 @@ A consumer may import a Remote contract that is not currently mounted on the Hos Connection's general channel API must suit both the current HTTP carrier and a future WebSocket carrier. If the Client Remote or Gateway exposes `fetch`, an HTTP request, or a route handle, WebSocket migration will pierce the Remote layer again. Those physical objects must therefore remain internal to Connection. -Remote endpoints use Connection's `trusted-host` authority. Loopback is accepted by default and LAN callers require an explicit trusted-host configuration, but this layer adds no per-method caller authorization; every trusted host can invoke a mounted Remote endpoint. +Remote endpoints use Connection's `trusted-host` authority. Loopback and the listener's own bind address are accepted by default; any other LAN authority requires an explicit trusted-host configuration. This layer adds no per-method caller authorization; every accepted authority can invoke a mounted Remote endpoint. `hasSeen()` favors strict-definition safety over SRC availability. While a strict descriptor is withdrawn, such as during HMR, the Gateway continues to claim the endpoint and reports it unavailable instead of falling back to a weak SRC descriptor. Re-registration restores it; only a Typert registry restart forgets the historical strict definition. 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 f7d6a03abe..2923b0a225 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 @@ -28,7 +28,7 @@ Remote 消费端投影同时包含 `.d.ts`、`.d.ts.map` 和 `.js`。`.d.ts` 只 | 组件 | Cordis 服务 | 职责 | |---|---|---| -| `@deepseek-ai/dsh-typert-protocol` | 只声明 `ctx.typert` 的最小协议 | `TypertRemoteService`、decorator、binding 回退、descriptor、lookup/Context 和 Remote map;不依赖 compiler、Zod、Connection 或 Browser | +| `@deepseek-ai/dsh-typert-protocol` | 只声明 `ctx.typert` 的最小协议 | `TypertRemoteService`、decorator、binding 回退、descriptor、lookup/Context、Remote map 和基于 Zod 的惰性 info 组装;不依赖 compiler、Connection 或 Browser | | Typert registry | `ctx.typert` | 分开保存当前环境 reflection、导入的 Remote contribution、lookup provider 和 Context provider | | Typert generator/loader | 无新增业务服务 | 从 Host/Client Program 生成三类 `lib` 产物,并把当前环境产物注册到 `ctx.typert` | | API Gateway 的 Host face | `ctx.typertGateway` | 关联 Host definition 与活 Service,解码参数、解析 receiver、调用方法,并将一元结果投影为载体无关的字段与附件 | @@ -81,16 +81,18 @@ export class ScopedGoalService extends TypertRemoteService { 同一个 endpoint 只能选择一种调用模式。需要显式 `Agent` 参数的流程使用 `@Remote`;需要切换到 Agent Context 再解析 scoped receiver 的流程使用 `@RemoteScope('agent')`,两者不会由 Typert 根据方法体或参数缺失自动猜测。 -业务包只依赖轻量的 `@deepseek-ai/dsh-typert-protocol`。它提供 `TypertRemoteService`,以及 decorator、binding 回退、lookup、Remote Scope 和 descriptor 的声明协议,不依赖 TypeScript compiler、Zod、HTTP 或 Client runtime。 +业务包只依赖 `@deepseek-ai/dsh-typert-protocol`。它提供 `TypertRemoteService`,以及 decorator、binding 回退、lookup、Remote Scope 和 descriptor 的声明协议,不依赖 TypeScript compiler、HTTP 或 Client runtime。其纯 `./remote-info` 入口使用 Zod 组装惰性具名输入 schema,不导入 Cordis;根入口在提供依赖 Cordis 的声明之余,也重新导出该能力。 支持协作式取消的方法会把 `signal: AbortSignal` 声明为最后一个 Host 参数。这个保留参数不是业务值、lookup 或 JSON 字段。生成的消费方方法将其暴露为最后一个可选参数,因此普通调用保持不变,而拥有取消控制权的调用方可以传入 signal。 ## Decorator 与显式 Gateway facet -Decorator 只表达“该方法参与 Remote 约定”,不负责运行时类型反射,也不向 Service constructor 注入隐藏 symbol。`@Remote('create')` 和 `@RemoteScope('agent', 'create')` 的参数是外部方法名;被装饰成员既可以是业务方法本身,也可以是 `remoteExportCreate` 这样的适配器。未给别名时才使用成员名作为外部方法名。继承 `TypertRemoteService` 是 Service 加入 Gateway 的常规显式声明;其 public readonly `typertGateway` 字段使运行时实例上的绑定保持可见。 +Decorator 表达 Remote 参与、可选导出名称和流式投递;`@Remote` 选项仅包含 `name` 和 `mode`。它不负责运行时类型反射,也不向 Service constructor 注入隐藏 symbol。`@Remote('create')` 和 `@RemoteScope('agent', 'create')` 的参数是外部方法名;被装饰成员既可以是业务方法本身,也可以是 `remoteExportCreate` 这样的适配器。未给别名时才使用成员名作为外部方法名。继承 `TypertRemoteService` 是 Service 加入 Gateway 的常规显式声明;其 public readonly `typertRemote` 字段使运行时实例上的绑定保持可见。 SRC 模式下,decorator 把方法名和调用模式记录在 Service prototype 上的带版本描述符中。描述符使用稳定的字符串属性名,因此 `remoteMethods()` 可以读取 `dsh-typert-protocol` 另一个已安装副本生成的标记;它不会向 Service 实例、constructor 或方法函数写入任何内容。 +普通产物从每个端点唯一的静态方法 spec 构造惰性 Remote info 实例。其直接 `TypertRemoteMethod` 对象保留描述符字段,并增加具名 `input(options?)` 和 `invoke`。消费方通过 `input({ strict: true })` 选择配套的严格解析与投影;`input()` 保留普通处理。Host 参数 codec 与唯一的普通 `result` codec 保持不变。既有 Registry 查询保留这些对象,`TYPERT_REMOTE.methods` 则提供精确静态类型。严格源码启动预构建并加载普通 Typert 产物;fallback 无法恢复被擦除的 schema。[统一元数据 note](../../proposed/architecture/2026-09-20-unified-typert-remote-metadata.zh.md)记录该交付机制及尚未完成的消费方适配。 + LIB 的严格方法发现、类型解析和 descriptor 生成由 Typert compiler 完成。它接受 `TypertRemoteService` 直接 `super()` 调用中的字面量 service key,或显式 binding 回退;生成过程不改写业务源码,也不注入隐藏注册元数据。 ## Lookup 与 Remote Scope 注册 @@ -215,7 +217,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 既不会读取缺失的声明,也不会针对同一输出并发运行多个生成器。 @@ -349,9 +351,9 @@ Web 本身依赖 `lib/client.js` 等构建产物,因此启动 Web 前要求完 ## SRC 与 LIB 运行模式 -SRC 面向本地源码启动。`@Remote` 和 `@RemoteScope()` 创建的带版本 prototype 描述符给出方法名和调用模式,运行时从 JavaScript 函数签名读取顺序参数名,并结合已注册 lookup/Context provider 生成弱 descriptor。 +SRC 面向本地源码启动。对于没有已注册严格定义的方法,`@Remote` 和 `@RemoteScope()` 创建的带版本 prototype 描述符给出方法名和调用模式,运行时从 JavaScript 函数签名读取顺序参数名,并结合已注册 lookup/Context provider 生成弱 descriptor。 -例如 `@Remote('create') remoteExportCreate(agent, request, signal)` 解析为外部方法 `create`、实现成员 `remoteExportCreate`、两个顶层业务参数和一个取消注入点;lookup 注册把 `agent` 改写为 wire 字段 `agentId`,`request` 按同名 JSON 参数传递,最后一个 `signal` 则留在 payload 之外。SRC 不启动 `ts.Program`,不使用 preload、loader hook、源码生成或模块改写,也不检查普通 JSON 对象的内部结构。 +例如 `@Remote('create') remoteExportCreate(agent, request, signal)` 解析为外部方法 `create`、实现成员 `remoteExportCreate`、两个顶层业务参数和一个取消注入点;lookup 注册把 `agent` 改写为 wire 字段 `agentId`,`request` 按同名 JSON 参数传递,最后一个 `signal` 则留在 payload 之外。保守回退不启动 `ts.Program`,不使用 preload、loader hook、源码生成或模块改写,也不检查普通 JSON 对象的内部结构。 SRC 无法明确解析的签名会在首次调用解析其 descriptor 时失败;Service 挂载只记录 decorator 标记,不检查 JavaScript 签名。SRC 不会猜测对象解构、默认参数造成的歧义、rest 参数、嵌套 lookup 或复杂类型。 @@ -474,7 +476,7 @@ Connection 提供共享 channel interceptor 与当前 HTTP carrier 映射。WebS **让 decorator 在运行时完成严格反射。** JavaScript decorator 无法恢复擦除后的 TypeScript 类型、公共符号身份和完整 Zod codec;向 constructor 注入 compiler 私有 symbol 又会隐藏业务类的真实依赖,因此严格信息由 Typert compiler 生成。 -**SRC 启动时使用 preload、loader hook 或完整 `ts.Program`。** 这能复用 LIB 分析,但增加所有源码启动入口的要求。SRC 只需要可用的弱 descriptor,因此采用 decorator 标记、函数参数名和显式 provider;严格检查留给 LIB 约定 pass。 +**SRC 启动时使用 preload、loader hook 或完整 `ts.Program`。** 这能复用 LIB 分析,但增加所有源码启动入口的要求。源码启动可加载普通预构建产物或使用保守标记,而无需加载 TypeScript Program。 **手写 Client interface。** 手写接口不能保证只包含 Remote 标记的方法,也会与 Host 签名、lookup ID 和 Zod schema 漂移,因此 Client 类型从 Host Program 自动投影。 @@ -520,7 +522,7 @@ SRC 弱 descriptor 不验证普通 JSON 内部结构。Host Remote 签名变化 Connection 的通用 channel API 必须同时适合当前 HTTP carrier 和后续 WebSocket carrier。若 Client Remote 或 Gateway 暴露 `fetch`、HTTP request 或 route handle,WebSocket 迁移会再次穿透 Remote 层,因此这些物理对象必须留在 Connection 内部。 -Remote endpoint 使用 Connection 的 `trusted-host` authority。系统默认接受 loopback;LAN 调用方必须通过显式 trusted-host 配置接入,但本层不增加逐方法调用方授权,因此每个 trusted host 都能调用已挂载的 Remote endpoint。 +Remote endpoint 使用 Connection 的 `trusted-host` authority。系统默认接受 loopback 与监听器自身的绑定地址;其他 LAN authority 必须通过显式 trusted-host 配置接入。本层不增加逐方法调用方授权,因此每个被接受的 authority 都能调用已挂载的 Remote endpoint。 `hasSeen()` 优先保障 strict definition 的安全性,而非 SRC 可用性。strict descriptor 撤回时(例如 HMR 期间),Gateway 会继续认领 endpoint 并报告不可用,而不会回退到弱 SRC descriptor。重新注册即可恢复;只有重启 Typert 注册表才会忘记历史 strict definition。 diff --git a/.agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.i18n.yaml index 9cd1ebd5f3..bdd096c69d 100644 --- a/.agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.md /agent-note-one-ordering-for-configuration-sources-and-what-a-discovered-file-may-not-decide: - en: 1f6ee603f36c2e09 - zh: e08197958663219c + en: 35dea8a3a8bdc842 + zh: 7a1cdf184ffd889f /agent-note-one-ordering-for-configuration-sources-and-what-a-discovered-file-may-not-decide/problem: en: d94bb81479bfa4a1 zh: af44ceaecf84ee51 diff --git a/.agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.md b/.agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.md index b8c146ed76..ee4ea2a5b9 100644 --- a/.agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.md +++ b/.agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.md @@ -4,7 +4,7 @@ Status: implemented English | [中文](2026-08-04-configuration-source-ownership.zh.md) -The non-secret settings tier below is superseded by [profile-owned live configuration](2026-09-19-profile-owned-live-configuration.md). Credential ordering and environment restrictions remain current. +The non-secret settings tier below is superseded by [profile-owned live configuration](2026-09-19-profile-owned-live-configuration.md), and the credential ordering by [stored credential precedence](2026-10-09-stored-credential-precedence.md). Environment restrictions remain current. ## Problem diff --git a/.agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.zh.md b/.agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.zh.md index 22afc15aec..024c93d3d1 100644 --- a/.agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.zh.md @@ -4,7 +4,7 @@ Status: implemented [English](2026-08-04-configuration-source-ownership.md) | 中文 -下文的非秘密 settings 层已由 [profile 所属实时配置](2026-09-19-profile-owned-live-configuration.zh.md) 替代。凭据优先级与环境限制仍然适用。 +下文的非秘密 settings 层已由 [profile 所属实时配置](2026-09-19-profile-owned-live-configuration.zh.md) 替代,凭据优先级已由[存储凭据优先级](2026-10-09-stored-credential-precedence.zh.md)替代。环境限制仍然适用。 ## Problem diff --git a/.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.i18n.yaml index f32414668b..ebe9f20065 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.i18n.yaml @@ -9,14 +9,14 @@ en: 1fe344c95a0de36d zh: 656c3e0f1117f64e /agent-note-forked-children-preserve-the-parent-request-prefix/decision: - en: b70aafc9ce30dd00 - zh: 74e3ff915bd968a9 + en: 3f5b3a4646c9466b + zh: 690172d6a4025b2a /agent-note-forked-children-preserve-the-parent-request-prefix/alternatives-considered: - en: 80504ffd8331e6c5 - zh: 193261bdde24b4bb + en: bc437309b64997ab + zh: 947010eed8d6fac4 /agent-note-forked-children-preserve-the-parent-request-prefix/consequences: - en: 0738d36f17c889b5 - zh: b71ee47f75d6d4e0 + en: 0f4d735328b3211d + zh: db4adb0f46b33bba /agent-note-forked-children-preserve-the-parent-request-prefix/consequences/accepted-risks: - en: f634caa9973eaedb - zh: 820291096c8e7352 + en: 72f4913b603e8596 + zh: 50924c62200070d1 diff --git a/.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.md b/.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.md index 4b52122e86..728d9eb15b 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.md +++ b/.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.md @@ -18,7 +18,7 @@ The model-facing `send_message` tool is registered globally for every Agent in a The base bundle and the `cordis`, `standard`, and `ptc` CLI presets bind fork to the continuable lifecycle. Base-backed profiles, including headless, inherit that default. `ForkInProcessProvider.prepareContinuable()` and `ctx.subagents.startActivation()` preserve the same request-prefix behavior across these compositions. -Byte-identical prefix reuse is qualified by explicit deployment choices. A fork delegation that applies a child persona or `toolFilter` may still change the request head. In particular, filtering out `send_message` removes both the schema and the return guidance from the child; the runtime does not bypass an explicit allow-list. +Byte-identical prefix reuse depends on the assembled inputs. Structured output or generated SDK differences can change the request head. Historical child descriptors can also restore persona or tool restrictions during cold resume; filtering out `send_message` removes both its schema and return guidance. New fork starts inherit the parent preset without these override fields. ## Alternatives considered @@ -28,11 +28,11 @@ Byte-identical prefix reuse is qualified by explicit deployment choices. A fork **Add the return instruction to the system prompt.** This would place child-only bytes ahead of inherited messages. Appending it to the initial user task preserves the inherited prefix and keeps the parent id next to the task that needs it. -**Ignore an explicit child `toolFilter`.** Structural return tools previously bypassed the child allow-list. Rejected because a declared tool restriction must determine both schema visibility and guidance; hidden authority would make the model-facing roster inaccurate. +**Ignore a historical child `toolFilter` on resume.** A stored restriction must continue to determine both schema visibility and guidance; silently discarding it changes the restored agent’s behavior. ## Consequences -- Parent and continuable-fork child expose byte-identical ordered tool schemas when the delegation does not request a persona or tool filter. +- Parent and continuable-fork child expose byte-identical ordered tool schemas when they use the same preset and have no child-only structured output or restored historical overrides. - The inherited Session seed precedes the child's initial task and return guidance. - The base bundle and full CLI presets use local continuable fork for both parent and caller delivery, without a child-only request-head addition. - The child can send messages to its direct parent through `send_message`. Parent delivery adds a separate runtime settlement notice; caller delivery returns the result through the activation receipt. @@ -40,4 +40,4 @@ Byte-identical prefix reuse is qualified by explicit deployment choices. A fork ### Accepted risks -Provider-side prefix reuse still depends on the selected provider and model and on the absence of explicit persona or tool-filter differences. The harness proves equality of its assembled request-head inputs, not a provider's cache behavior. +Provider-side prefix reuse still depends on the selected provider and model and matching assembled inputs. The harness tests equality of its assembled request-head inputs, not a provider’s cache behavior. diff --git a/.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.zh.md b/.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.zh.md index 2c426a1e7c..2ebaa9ddbc 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.zh.md @@ -18,7 +18,7 @@ fork 与 spawn 的差异在于:fork 会用 parent 已完成轮次的前缀作 base 组合包与 `cordis`、`standard` 和 `ptc` CLI preset 将 fork 绑定为可继续生命周期。基于 base 的 profile(包括 headless)继承这一默认值。`ForkInProcessProvider.prepareContinuable()` 与 `ctx.subagents.startActivation()` 在这些组合中保持相同的请求前缀行为。 -逐字节相同的前缀复用受显式部署选择约束。配置 child persona 或 `toolFilter` 的 fork 委派仍可能改变请求头。尤其是过滤掉 `send_message` 时,child 会同时失去该 schema 与返回指引;运行时不会绕过显式 allow-list。 +逐字节相同的前缀复用取决于组装输入。结构化输出或生成 SDK 差异可以改变请求头。历史子级 descriptor 也可在冷恢复时恢复 persona 或工具限制;过滤掉 `send_message` 会同时移除其 schema 和返回指引。新 fork 启动继承父级 preset,不含这些覆盖字段。 ## 考虑过的替代方案 @@ -28,11 +28,11 @@ base 组合包与 `cordis`、`standard` 和 `ptc` CLI preset 将 fork 绑定为 **把返回指令放进系统提示词。** 这会在继承消息之前加入 child-only 字节。将其追加到初始用户任务,可以保留继承前缀,并让 parent id 紧邻需要它的任务。 -**忽略显式 child `toolFilter`。** 结构性返回工具过去会绕过 child allow-list。否决该方案,因为声明的工具限制必须同时决定 schema 可见性与指引;隐藏权限会让面向模型的工具清单失真。 +**恢复时忽略历史子级 `toolFilter`。** 存储的限制必须继续决定 schema 可见性和指引;静默丢弃它会改变恢复 agent 的行为。 ## 后果 -- 未请求 persona 或工具过滤时,parent 与可继续 fork child 暴露逐字节相同且顺序一致的工具 schema。 +- 使用相同 preset 且没有子级专属结构化输出或恢复的历史覆盖时,父级与可继续的 fork 子级公开逐字节相同、顺序一致的工具 schema。 - 继承的 Session 种子位于 child 初始任务及其返回指引之前。 - base 组合包与完整 CLI preset 对 parent 和 caller 投递均使用本地可继续 fork,不增加 child-only 请求头字段。 - child 可以通过 `send_message` 向直接 parent 发消息。parent 投递会追加独立的运行时结算通知;caller 投递通过 activation 回执返回结果。 @@ -40,4 +40,4 @@ base 组合包与 `cordis`、`standard` 和 `ptc` CLI preset 将 fork 绑定为 ### 已接受风险 -提供方侧前缀复用仍取决于选定的提供方和模型,以及是否不存在显式 persona 或工具过滤差异。harness 证明的是自己组装出的请求头输入相等,而不是提供方的缓存行为。 +提供方侧前缀复用仍取决于所选提供方和模型,以及组装输入是否相同。harness 测试的是自身组装请求头输入相等,而非提供方的缓存行为。 diff --git a/.agents/notes/implemented/architecture/2026-08-10-host-plane-ownership-after-presets.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-10-host-plane-ownership-after-presets.i18n.yaml index 6512532f4a..6401383a39 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-host-plane-ownership-after-presets.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-10-host-plane-ownership-after-presets.i18n.yaml @@ -18,5 +18,5 @@ en: ca7c9088d0793e1e zh: ea648bac9e726c64 /agent-note-what-stays-host-plane-once-presets-own-the-agent-plane/consequences: - en: de26cde94adda770 - zh: 7f39760b77958966 + en: 0a426923c2a1f774 + zh: 29626804b99b35ff diff --git a/.agents/notes/implemented/architecture/2026-08-10-host-plane-ownership-after-presets.md b/.agents/notes/implemented/architecture/2026-08-10-host-plane-ownership-after-presets.md index 546423f32e..620692ee9f 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-host-plane-ownership-after-presets.md +++ b/.agents/notes/implemented/architecture/2026-08-10-host-plane-ownership-after-presets.md @@ -38,6 +38,6 @@ Projection key presence is not a per-session capability signal ([session project ## Consequences -The context meter becomes a per-session fact instead of a function of mount history. A preset can no longer opt out of token accounting; no shipped preset did, and `minimal` now says it drops auto-compaction rather than the accounting. +The context meter is a per-session fact independent of mount history. Presets resolve the host meter for token accounting while selecting their own compaction backend; `minimal` supports both automatic compaction and the human `/compact` command. Production entry points must compose Agents explicitly; installing the registry alone does not bind them. An unjoined Agent receives no tools, prompt sections, or skills and reports no error. diff --git a/.agents/notes/implemented/architecture/2026-08-10-host-plane-ownership-after-presets.zh.md b/.agents/notes/implemented/architecture/2026-08-10-host-plane-ownership-after-presets.zh.md index 59d318b410..325758c769 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-host-plane-ownership-after-presets.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-10-host-plane-ownership-after-presets.zh.md @@ -38,6 +38,6 @@ Status: implemented ## 后果 -context meter 成为逐会话的事实,而不再是挂载历史的函数。代价是 preset 不能再选择不做 token 记账;随附的 preset 没有一个这么做,`minimal` 现在也写明它放弃的是自动压缩而非记账。 +context meter 是独立于挂载历史的逐会话事实。Preset 使用宿主 meter 进行 token 记账,并选择自己的压缩后端;`minimal` 同时支持自动压缩和用户 `/compact` 命令。 生产入口必须显式组装 Agent;仅安装注册表不会自动绑定。未加入的 Agent 不会获得工具、提示词段落或 skill,也不会报告错误。 diff --git a/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.i18n.yaml index e33e7f556d..ac13880ddd 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.i18n.yaml @@ -9,8 +9,8 @@ en: c11f54e24be6cc3b zh: c1c274fbb161a57b /agent-note-session-log-versioning-one-integer-an-upgrade-chain-and-a-per-event-ignorable-marker/decision: - en: 084bcb4de484ef32 - zh: 1edf1445913ac7b1 + en: f2c17cd6b83acdba + zh: 148162c0a8043947 /agent-note-session-log-versioning-one-integer-an-upgrade-chain-and-a-per-event-ignorable-marker/decision/writer-and-publication-authority: en: 461eaa03c6a4f441 zh: 7e5b131326dc702c diff --git a/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md b/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md index 9cb0940f76..c2407b2afd 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md +++ b/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md @@ -10,15 +10,17 @@ Session logs must be upgradable after release, and the runtime that ships first ## Decision +The [reader-compatibility review decision](../process/2026-10-08-session-reader-compatibility-review.md) supersedes the structural bump criterion. This note owns the integer, unknown-event marker, direction-aware refusal, and generation-preservation decisions. + **One monotonic integer, no major/minor split.** Whether a version step is auto-upgradable is a property of that step — expressed by whether its upgrader exists — not something a two-level numbering scheme should promise in advance; design time rarely reveals whether the next change will turn out "major". -**The writer decides bumps, not the reader.** A bump is required exactly when an old runtime could no longer handle a new log with full semantic correctness. "Parses without error" is not the bar: silently skipping content that shapes reconstruction is a wrong read. Only structural changes qualify — header shape, event envelope, core event semantics, the surface mechanism (`SurfaceEventType` set, `SurfaceOp` variants). When unsure, bump: a near-identity upgrader is almost free, a missed bump silently corrupts old readers. +**Bump when existing discriminators cannot prevent unsafe interpretation.** Successful parsing alone does not establish compatibility: silently skipping content required for reconstruction is a wrong read. Same-version changes require safe old-reader handling and preservation of historical meaning by new readers. The linked reader-compatibility decision defines the review obligations. **Read rules by direction.** Equal version: read normally. Newer than the reader: refuse, name the direction ("written by a newer harness — upgrade"), and point at the raw log artifact so the user can still see the text (`SessionFormatUnsupportedError`, distinct from `SessionPersistenceCorruptionError` because nothing is damaged). Older than the reader: every event-body operation first runs the complete adjacent chain in memory and leaves the source path, bytes, and inode unchanged. Read handles may consume that current logical result directly; a write open exclusively publishes the final current generation under its canonical versioned filename before append. Header-only listing remains non-mutating and reports the numerically highest canonical generation. Catalog generation and module initialization reject a missing adjacent step, so a published first-party build never exposes a partial historical chain. Retained lower generations are not automatic fallback or a downgrade compatibility promise. **A per-event `ignorable` marker covers vocabulary growth, so ordinary event additions never bump the version.** The event vocabulary is decided by which plugins are mounted, which a single version integer cannot describe. A reader meeting an unrecognized event type refuses to interpret the log unless the event carries `ignorable: true` in its envelope. The default is *required*: forgetting the marker over-refuses a resumable session (an inconvenience), while a default of ignorable would make the same mistake silently resume a gutted one (a safety failure). The architecture makes this sound: model-visible content flows only through the four `surfaceOp`-marked surface event types plus the `request/header`/`request/context` folds, so the dangerous unknowns are exactly the non-surface events that change how the rest of the log is read (`session/end-seed` is the existing example). -The [accepted compatibility checkpoint](../../../../docs/session-format-status.md#finalization-record) prevents an accepted transition from reusing its header increase for later breaking changes. Backward-compatible evolution uses new acknowledgement records at the same Session version; breaking changes require a higher writer. The checkpoint does not change the unknown-event protocol. +**Accepted machine records remain immutable.** The [accepted compatibility checkpoint](../../../../docs/session-format-status.md#finalization-record) preserves accepted declarations and schemas. Later changes receive new acknowledgements, and a version-bump decision needs its own increasing header transition. The checkpoint does not change the unknown-event protocol. ### Writer and publication authority diff --git a/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.zh.md b/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.zh.md index e1424f24e5..9a9b4365d1 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.zh.md @@ -10,15 +10,17 @@ Session log 在发布后必须能升级格式,而最先发布的运行时决 ## 决定 +[读取器兼容性评审决策](../process/2026-10-08-session-reader-compatibility-review.zh.md)取代结构性升版本标准。本说明负责整数版本、未知事件标记、区分方向的拒绝与代际保留决策。 + **一个单调递增的整数,不分大小版本。**某一步能不能自动升级是那一步自己的属性,由它的升级器存在与否表达,不该由两级编号方案提前承诺;设计时很少能预知下一个变更算不算"大"。 -**升不升版本由写入方决定,与读取方能力无关。**当且仅当老运行时无法在语义上完全正确地处理新日志时才必须升版本。"解析不报错"不是标准:静默跳过影响重建的内容就是读错。只有结构性变更够得上这条线:header 形状、事件信封、核心事件语义、surface 机制(`SurfaceEventType` 集合、`SurfaceOp` 变体)。拿不准就升:近似恒等的升级器几乎没有成本,漏升一次会让老读取器静默读坏。 +**既有判别信息无法阻止不安全解释时升版本。** 仅解析成功不能证明兼容:静默跳过重建所需内容属于错误读取。同版本变更要求旧读取器安全处理,并由新读取器保留历史含义。所链接的读取器兼容性决策定义评审义务。 **读取规则按方向区分。**版本相等:正常读。比读取器新:拒绝,说明方向("由更新的 harness 写入,请升级"),并给出原始日志文件的路径,用户仍能看到文本(`SessionFormatUnsupportedError`,与 `SessionPersistenceCorruptionError` 区分,因为数据没有损坏)。比读取器旧:每个事件正文操作先在内存中运行完整相邻链,并保持源路径、字节与 inode 不变。读句柄可以直接使用该 current 逻辑结果;写 open 则在 append 前把最终 current generation 排他发布到其规范版本文件名。仅 header 的列表保持不变更,并报告数值最高的规范 generation。catalog 生成与模块初始化会拒绝缺失的相邻步骤,因此已发布第一方 build 绝不会暴露不完整历史链。保留的低 generation 不是自动 fallback,也不构成 downgrade compatibility 承诺。 **逐事件的 `ignorable` 标记吸收词汇表增长,普通的新增事件永远不用升版本。**事件词汇表由挂载了哪些插件决定,单个版本整数描述不了它。读取器遇到不认识的事件类型时拒绝解读日志,除非该事件的信封带 `ignorable: true`。默认为必需:忘写标记的后果是把一个本可恢复的会话拒绝过头(体验问题),而默认可忽略会让同样的疏忽静默恢复出残缺会话(安全事故)。架构保证了这条规则成立:模型可见内容只经四种带 `surfaceOp` 标记的 surface 事件加 `request/header`、`request/context` 折叠进入重建,危险的未知事件恰好是那些不进 surface 但改变日志其余部分解读方式的事件(`session/end-seed` 是现存例子)。 -[已接受兼容性检查点](../../../../docs/session-format-status.zh.md#finalization-record)阻止已接受转换复用原来的头版本递增来授权后续破坏性变更。向后兼容的演进在相同 Session 版本上使用新的确认记录;破坏性变更要求更高的写入器版本。检查点不改变未知事件协议。 +**已接受的机器记录保持不可变。** [已接受兼容性检查点](../../../../docs/session-format-status.zh.md#finalization-record)保留已接受的声明与 schema。后续变更获得新确认,升版本决策需要自身的递增头版本转换。检查点不改变未知事件协议。 ### 写入器与发布真源 diff --git a/.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.i18n.yaml index 3afca5571b..a5863d41c7 100644 --- a/.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.i18n.yaml @@ -15,8 +15,8 @@ en: a1750de2d48551af zh: ffea0b75c292f186 /agent-note-client-shell-layering-and-dynamic-package-boundaries/decision/shared-module-requests: - en: cedddcca8a7bae6d - zh: a568a1130229f48c + en: 96661da17622132a + zh: dab3424093130c2f /agent-note-client-shell-layering-and-dynamic-package-boundaries/decision/parser-preloading-and-react-handoff: en: 4b503618b271fc28 zh: e2148f44efa769d2 diff --git a/.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.md b/.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.md index ad2bb26b84..68c9ef1235 100644 --- a/.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.md +++ b/.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.md @@ -32,7 +32,7 @@ The `staticLinked` preset leaves every bare specifier as an external import in ` ### Shared module requests -Dynamic browser bundles implicitly externalize the common baseline: `PLATFORM_MODULES` names shell-seeded React, Cordis, and static UI identities, while `PRELOADED_CLIENT_EXTERNALS` is reserved for a dynamic identity that must arrive before shell boot and is currently empty. A package uses `dsh.client.external` only for an exact non-baseline value request. Type-only imports are erased and create no request; permitted third-party implementation libraries remain private bundle contents. +Dynamic browser bundles implicitly externalize the common baseline: `PLATFORM_MODULES` names shell-seeded React, Cordis, selected third-party libraries, and static UI identities, while `PRELOADED_CLIENT_EXTERNALS` is reserved for a dynamic identity that must arrive before shell boot and is currently empty. A package uses `dsh.client.external` only for an exact non-baseline value request. Type-only imports are erased and create no request; non-baseline third-party implementation libraries remain private bundle contents. Shared third-party libraries use the shell's declared versions without per-plugin version negotiation; promotion into the baseline requires a measured reduction across the shell and shipped plugin bundles. A request has exactly two suppliers: diff --git a/.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.zh.md b/.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.zh.md index 70563962b3..79017823a7 100644 --- a/.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.zh.md @@ -32,7 +32,7 @@ Client npm 依赖区段描述安装和开发关系,但不能可靠描述 bundl ### 共享模块请求 -动态浏览器 bundle 会隐式 external 统一基座:`PLATFORM_MODULES` 命名由外壳播种的 React、Cordis 和静态 UI 身份,`PRELOADED_CLIENT_EXTERNALS` 则为必须先于 shell 启动到达的动态身份预留,当前为空。包只在精确请求基座外实体时使用 `dsh.client.external`。纯类型 import 会被擦除,不产生请求;允许的第三方实现库保留为 bundle 私有内容。 +动态浏览器 bundle 会隐式 external 统一基座:`PLATFORM_MODULES` 命名由外壳播种的 React、Cordis、选定的第三方库和静态 UI 身份,`PRELOADED_CLIENT_EXTERNALS` 则为必须先于 shell 启动到达的动态身份预留,当前为空。包只在精确请求基座外实体时使用 `dsh.client.external`。纯类型 import 会被擦除,不产生请求;基座外的第三方实现库保留为 bundle 私有内容。共享第三方库使用外壳声明的版本,不为单个插件协商版本;只有测量确认外壳与随包插件 bundle 的总体积减少,才将库纳入基座。 请求只有两种提供方: diff --git a/.agents/notes/implemented/architecture/2026-08-21-deepseek-llm-api-request-extensions.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-21-deepseek-llm-api-request-extensions.i18n.yaml index 8cc0c37e4d..ea55baad51 100644 --- a/.agents/notes/implemented/architecture/2026-08-21-deepseek-llm-api-request-extensions.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-21-deepseek-llm-api-request-extensions.i18n.yaml @@ -9,8 +9,8 @@ en: 4945ce54f66df55c zh: 9fbd833c1d8122a7 /agent-note-deepseek-llm-api-request-extensions-for-session-logs-and-plugin-packages/decision: - en: 2388519a1afaac92 - zh: 6bf758f0560e29a5 + en: d2452e4a39db0b6b + zh: 87f7e0be1f613285 /agent-note-deepseek-llm-api-request-extensions-for-session-logs-and-plugin-packages/incremental-session-log-field: en: 4e3138fbdd94259b zh: 8fda801522045b88 @@ -21,7 +21,7 @@ en: eb69576e756f4aa1 zh: 5c1923159da3f7a2 /agent-note-deepseek-llm-api-request-extensions-for-session-logs-and-plugin-packages/verification: - en: 9935338a0970d09d + en: ed730f117365f007 zh: a9a36702bc72a9f7 /agent-note-deepseek-llm-api-request-extensions-for-session-logs-and-plugin-packages/alternatives-considered: en: 5faf7699272f99b4 @@ -33,5 +33,5 @@ en: b6eff63f49220dcc zh: 8e4a6c785ed2256a /agent-note-deepseek-llm-api-request-extensions-for-session-logs-and-plugin-packages/consequences: - en: 853cd7b21db6208b - zh: bfaf459f006fe2db + en: fed545acefb91f2a + zh: c474a94bb956bbf6 diff --git a/.agents/notes/implemented/architecture/2026-08-21-deepseek-llm-api-request-extensions.md b/.agents/notes/implemented/architecture/2026-08-21-deepseek-llm-api-request-extensions.md index c2ad167f14..7a6aa226b4 100644 --- a/.agents/notes/implemented/architecture/2026-08-21-deepseek-llm-api-request-extensions.md +++ b/.agents/notes/implemented/architecture/2026-08-21-deepseek-llm-api-request-extensions.md @@ -14,7 +14,7 @@ Both values belong only on the official DeepSeek adapter path. Adding them to `G ## Decision -`@deepseek-ai/dsh-deepseek-llm-api-extensions` registers `ctx.deepseekLlmApiExtensions`, an additive registry of top-level fields for `deepseek-official` request bodies. A contributor claims one declaration-merged field with `register()`. The adapter invokes `prepare()` after serializing the exact wire messages, passes the request cancellation signal, rejects preparation or base-field collision before HTTP, merges the detached fields, and calls the captured `accept()` transaction after HTTP 2xx. A merged body that fails to serialize is sent without extension fields or acceptance under the [bounded-upload decision](2026-09-24-bounded-session-log-upload.md). The registry stops awaiting preparation after cancellation even if a contributor ignores the signal. Acceptance failures remain request failures under `REQUEST_EXTENSION`; transport and non-2xx failures never accept a contribution. A composition without the registry retains the reusable base adapter. Shipped compositions mount the registry and both contributors: both package metadata and Session-log upload are enabled by default; `session-log-deepseek.enabled: false` disables log upload under the [default-upload decision](2026-09-14-session-log-upload-default.md). Keyless `deepseek-official` replay invokes preparation with a synthetic empty base body and the same acceptance transaction before its first recorded chunk, preserving post-2xx extension side effects rather than field bytes. +`@deepseek-ai/dsh-deepseek-llm-api-extensions` registers `ctx.deepseekLlmApiExtensions`, an additive registry of top-level fields for `deepseek-official` request bodies. A contributor claims one declaration-merged field with `register()`. The adapter invokes `prepare()` after serializing the exact wire messages, passes the request cancellation signal, rejects base-field collision before HTTP, merges the detached fields, and calls the captured `accept()` transaction after HTTP 2xx. A merged body that fails to serialize is sent without extension fields or acceptance under the [bounded-upload decision](2026-09-24-bounded-session-log-upload.md). The registry stops awaiting preparation after cancellation even if a contributor ignores the signal. Extension fields are auxiliary and best effort: the registry logs and omits a contributor whose preparation throws, and the adapter logs an acceptance failure without failing the model request; transport and non-2xx failures never accept a contribution. A composition without the registry retains the reusable base adapter. Shipped compositions mount the registry and both contributors: both package metadata and Session-log upload are enabled by default; `session-log-deepseek.enabled: false` disables log upload under the [default-upload decision](2026-09-14-session-log-upload-default.md). Keyless `deepseek-official` replay invokes preparation with a synthetic empty base body and the same acceptance transaction before its first recorded chunk, preserving post-2xx extension side effects rather than field bytes. The provider-neutral `llm` package and `llm-pi-ai` contain no extension type, service lookup, field merge, or acceptance call. @@ -50,7 +50,7 @@ The process-lifetime manifest-identity cache remains separate because in-process ## Verification -Registry tests pin duplicate ownership, effect-scoped disposal, detached field values, concurrent and abortable preparation, receiver-preserving acceptance, one acceptance settlement, and failure aggregation. Session tests pin default-on and explicit-off policies, full-first/suffix-later delivery, direct complete event envelopes independent of base-body messages, incremental watermark folding, persisted restart recovery, fork identity fencing, and out-of-order acceptance. Package-inventory tests pin default-on and explicit-off policies, host and standing-preset discovery, conflicting Loader resolution bases, manifest resolution, lifecycle filtering, and exact name/version ordering. The direct adapter mock proves pre-HTTP preparation failure, cancellation, non-2xx non-acceptance, 2xx acceptance before a later stream failure, and field collision. Keyless replay pins post-2xx extension acceptance, and the TypeScript JSON-RPC plus Python packaged-runtime snapshots project the acceptance event through both SDKs. Real Loader composition pins default package metadata and Session upload plus explicit upload disablement, one real-API request mounts both shipped extensions and proves the official endpoint accepts them, and pi-ai tests retain their unchanged wire requests. +Registry tests pin duplicate ownership, effect-scoped disposal, detached field values, concurrent and abortable preparation, receiver-preserving acceptance, one acceptance settlement, and failure aggregation. Session tests pin default-on and explicit-off policies, full-first/suffix-later delivery, direct complete event envelopes independent of base-body messages, incremental watermark folding, persisted restart recovery, fork identity fencing, and out-of-order acceptance. Package-inventory tests pin default-on and explicit-off policies, host and standing-preset discovery, conflicting Loader resolution bases, manifest resolution, lifecycle filtering, and exact name/version ordering. The direct adapter mock proves pre-HTTP preparation rejection, cancellation, non-2xx non-acceptance, 2xx acceptance before a later stream failure, and field collision. Keyless replay pins post-2xx extension acceptance, and the TypeScript JSON-RPC plus Python packaged-runtime snapshots project the acceptance event through both SDKs. Real Loader composition pins default package metadata and Session upload plus explicit upload disablement, one real-API request mounts both shipped extensions and proves the official endpoint accepts them, and pi-ai tests retain their unchanged wire requests. ## Alternatives considered @@ -85,7 +85,7 @@ About 98% of the measured v1 real-session events were `assistant/chunk`. Omittin ## Consequences -Official DeepSeek requests carry active package versions to their resolved `baseURL`, including configured gateways. Unless Session-log upload is disabled, each eligible request also carries newly unaccepted Session events, up to `maxBytes` per request. The fields are model-hidden and add no prompt tokens or KV-cache changes, but can substantially increase HTTP body size. Manifest resolution, field collision, acceptance logging, or provider schema rejection fails the model request rather than silently dropping metadata. A merged body that fails to serialize is the exception: the request proceeds without extension fields and logs a warning. +Official DeepSeek requests carry active package versions to their resolved `baseURL`, including configured gateways. Unless Session-log upload is disabled, each eligible request also carries newly unaccepted Session events, up to `maxBytes` per request. The fields are model-hidden and add no prompt tokens or KV-cache changes, but can substantially increase HTTP body size. Field collision or provider schema rejection fails the model request. A contributor preparation failure, an acceptance failure, or a merged body that fails to serialize logs a warning and lets the request proceed; a package without a usable version reports only its name. The `delivery-accepted` event becomes part of the canonical log and is itself delivered on a later request. Crash recovery can duplicate a suffix but does not infer acceptance from assistant output or create a second local cursor store. Direct calls without a live Session omit the session field; host package inventory remains available. diff --git a/.agents/notes/implemented/architecture/2026-08-21-deepseek-llm-api-request-extensions.zh.md b/.agents/notes/implemented/architecture/2026-08-21-deepseek-llm-api-request-extensions.zh.md index 91d44f59e0..608661bd5e 100644 --- a/.agents/notes/implemented/architecture/2026-08-21-deepseek-llm-api-request-extensions.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-21-deepseek-llm-api-request-extensions.zh.md @@ -14,7 +14,7 @@ Status: implemented ## 决策 -`@deepseek-ai/dsh-deepseek-llm-api-extensions` 注册 `ctx.deepseekLlmApiExtensions`,即 `deepseek-official` 请求正文顶层字段的增量注册表。贡献方通过 `register()` 认领一个经声明合并的字段。适配器在序列化确切协议消息后调用 `prepare()`、传入请求取消信号,在 HTTP 前拒绝准备失败或基础字段冲突,合并分离字段,并在 HTTP 2xx 后调用捕获的 `accept()` 事务。合并后的正文无法序列化时,按[有上限上传决策](2026-09-24-bounded-session-log-upload.zh.md)不带扩展字段发送,也不执行接受。即使贡献方忽略信号,注册表也会在取消后停止等待准备。接受失败仍以 `REQUEST_EXTENSION` 使请求失败;传输失败与非 2xx 失败绝不会接受贡献。未挂载注册表的组合会保留可复用基础适配器。随附组合会挂载注册表与两个贡献方:插件包元数据和会话日志上传均默认开启;按[默认上传决策](2026-09-14-session-log-upload-default.zh.md),设置 `session-log-deepseek.enabled: false` 可关闭日志上传。无密钥 `deepseek-official` 回放会使用合成的空基础正文执行准备,并在第一个已记录分片前调用同一接受事务;它保持的是 2xx 后扩展副作用,而非字段字节。 +`@deepseek-ai/dsh-deepseek-llm-api-extensions` 注册 `ctx.deepseekLlmApiExtensions`,即 `deepseek-official` 请求正文顶层字段的增量注册表。贡献方通过 `register()` 认领一个经声明合并的字段。适配器在序列化确切协议消息后调用 `prepare()`、传入请求取消信号,在 HTTP 前拒绝基础字段冲突,合并分离字段,并在 HTTP 2xx 后调用捕获的 `accept()` 事务。合并后的正文无法序列化时,按[有上限上传决策](2026-09-24-bounded-session-log-upload.zh.md)不带扩展字段发送,也不执行接受。即使贡献方忽略信号,注册表也会在取消后停止等待准备。扩展字段是辅助信息,按尽力而为处理:贡献方准备时抛错,注册表会记录告警并省略该字段;接受失败时,适配器记录告警而不使模型请求失败;传输失败与非 2xx 失败绝不会接受贡献。未挂载注册表的组合会保留可复用基础适配器。随附组合会挂载注册表与两个贡献方:插件包元数据和会话日志上传均默认开启;按[默认上传决策](2026-09-14-session-log-upload-default.zh.md),设置 `session-log-deepseek.enabled: false` 可关闭日志上传。无密钥 `deepseek-official` 回放会使用合成的空基础正文执行准备,并在第一个已记录分片前调用同一接受事务;它保持的是 2xx 后扩展副作用,而非字段字节。 提供方无关的 `llm` 包与 `llm-pi-ai` 不包含任何扩展类型、服务查找、字段合并或接受调用。 @@ -85,7 +85,7 @@ Status: implemented ## 后果 -DeepSeek 官方请求会把存活包版本发送到解析后的 `baseURL`,包括已配置 gateway。除非关闭会话日志上传,否则符合条件的请求还会携带新的未接受会话事件,每次最多 `maxBytes`。这些字段对模型不可见,不增加提示词 token,也不改变 KV Cache,但可能显著增大 HTTP 正文。Manifest 解析、字段冲突、接受记录或提供方 schema 拒绝会使模型请求失败,而不会静默丢弃元数据。合并后的正文无法序列化是例外:请求不带扩展字段继续发送,并记录一条告警。 +DeepSeek 官方请求会把存活包版本发送到解析后的 `baseURL`,包括已配置 gateway。除非关闭会话日志上传,否则符合条件的请求还会携带新的未接受会话事件,每次最多 `maxBytes`。这些字段对模型不可见,不增加提示词 token,也不改变 KV Cache,但可能显著增大 HTTP 正文。字段冲突或提供方 schema 拒绝会使模型请求失败。贡献方准备失败、接受失败或合并后的正文无法序列化时,系统记录告警并让请求继续;没有可用版本的包只报告名称。 `delivery-accepted` 事件会成为权威日志的一部分,并在后续请求中自行交付。崩溃恢复可能重复后缀,但不会根据 assistant 输出推断接受,也不会创建第二份本地游标存储。缺少存活会话的直接调用会省略会话字段;宿主包清单仍然可用。 diff --git a/.agents/notes/implemented/architecture/2026-08-22-single-dsh-application-launcher.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-22-single-dsh-application-launcher.i18n.yaml index 5e193c9063..ba50248d0c 100644 --- a/.agents/notes/implemented/architecture/2026-08-22-single-dsh-application-launcher.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-22-single-dsh-application-launcher.i18n.yaml @@ -21,8 +21,8 @@ en: 8ee88035cf64eeb3 zh: 6184e50fc4d47348 /agent-note-one-dsh-launcher-for-application-profiles/decision/python-runtime: - en: 5962abadfdece709 - zh: 5db20e96deed49d1 + en: 4b4cf5071b740c85 + zh: 595e5fe8127f9067 /agent-note-one-dsh-launcher-for-application-profiles/decision/enforcement: en: 9ce8d86b65064f38 zh: 27b8ad426cb319a2 diff --git a/.agents/notes/implemented/architecture/2026-08-22-single-dsh-application-launcher.md b/.agents/notes/implemented/architecture/2026-08-22-single-dsh-application-launcher.md index 7d4bb1a9c2..27a8315fe6 100644 --- a/.agents/notes/implemented/architecture/2026-08-22-single-dsh-application-launcher.md +++ b/.agents/notes/implemented/architecture/2026-08-22-single-dsh-application-launcher.md @@ -46,7 +46,7 @@ Direct SDK use follows normal Harness-home resolution: explicit `dshHome`, inher ### Python runtime -The Python runtime wheel stages [`python/sdk-runtime/runtime-bootstrap.mjs`](../../../../python/sdk-runtime/runtime-bootstrap.mjs) as the `dsh-python-runtime-closure` entry. Its ordinary branch calls the public CLI export; a provider-private selector dispatches to the internal subprocess runner before CLI parsing and is not an application entry point. The [native-containment reference](../../../../packages/subprocess/subprocess-local/README.md) owns that private dispatch. The Python client selects `dsh --profile sdk` by default, ordered patch files, and an explicit Harness home; the runnable example under `python/sdk/examples` selects `sdk-minimal`. The installed `dsh` console command exposes the same profile grammar, including the `web` profile. +The Python runtime wheel stages [`python/sdk-runtime/runtime-bootstrap.mjs`](../../../../python/sdk-runtime/runtime-bootstrap.mjs) as the `dsh-python-runtime-closure` entry. Its ordinary branch calls the public CLI export; a provider-private selector dispatches to the internal subprocess runner before CLI parsing and is not an application entry point. A private `DSH_RUNTIME_DOWNLOAD` selector prepares optional resources before application launch and is removed before spawning preparation subprocesses; ordinary CLI arguments do not select downloads. The [native-containment reference](../../../../packages/subprocess/subprocess-local/README.md) owns that private dispatch. The Python client selects `dsh --profile sdk` by default, ordered patch files, and an explicit Harness home; the runnable example under `python/sdk/examples` selects `sdk-minimal`. The installed `dsh` console command exposes the same profile grammar, including the `web` profile. The executable family is `deepseek-harness-sdk-runtime--`. The SDK wire, wheel and import distribution names, sidecar names, and wire identity `deepseek-harness-sdk-runtime` remain stable. The SDK package family is `@deepseek-ai/dsh-sdk-client`, `@deepseek-ai/dsh-sdk-protocol`, and `@deepseek-ai/dsh-sdk-jsonrpc-server`; `@deepseek-ai/dsh-acp` remains the ACP protocol plugin. There is no Python-specific Node application, checked-in complete config, compatibility package, forwarding executable, fallback parser, or SDK/ACP launcher alias. [docs/architecture.md](../../../../docs/architecture.md) owns this launch, and the [`python/sdk-runtime` README](../../../../python/sdk-runtime/README.md) owns the Windows carrier. diff --git a/.agents/notes/implemented/architecture/2026-08-22-single-dsh-application-launcher.zh.md b/.agents/notes/implemented/architecture/2026-08-22-single-dsh-application-launcher.zh.md index eb7d5ff8eb..f9a50ebf5a 100644 --- a/.agents/notes/implemented/architecture/2026-08-22-single-dsh-application-launcher.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-22-single-dsh-application-launcher.zh.md @@ -46,7 +46,7 @@ SDK 用户通过 profile 自定义插件。`dsh plugin --profile ...` 管 ### Python 运行时 -Python 运行时 wheel 将 [`python/sdk-runtime/runtime-bootstrap.mjs`](../../../../python/sdk-runtime/runtime-bootstrap.mjs) 暂存为 `dsh-python-runtime-closure` 入口。其普通分支调用公开 CLI export;提供方私有选择会在 CLI 解析前分派到内部子进程 runner,而不是应用入口。[原生 containment 参考](../../../../packages/subprocess/subprocess-local/README.zh.md)负责该私有分派。Python 客户端默认选择 `dsh --profile sdk`、有序 patch 文件与显式 Harness home;`python/sdk/examples` 下的可运行示例选择 `sdk-minimal`。安装的 `dsh` 控制台命令暴露相同的 profile 语法,包括 `web` profile。 +Python 运行时 wheel 将 [`python/sdk-runtime/runtime-bootstrap.mjs`](../../../../python/sdk-runtime/runtime-bootstrap.mjs) 暂存为 `dsh-python-runtime-closure` 入口。其普通分支调用公开 CLI export;提供方私有选择会在 CLI 解析前分派到内部子进程 runner,而不是应用入口。私有 `DSH_RUNTIME_DOWNLOAD` 选择器在应用启动前准备可选资源,并在启动资源准备子进程前移除;普通 CLI 参数不选择下载。[原生 containment 参考](../../../../packages/subprocess/subprocess-local/README.zh.md)负责该私有分派。Python 客户端默认选择 `dsh --profile sdk`、有序 patch 文件与显式 Harness home;`python/sdk/examples` 下的可运行示例选择 `sdk-minimal`。安装的 `dsh` 控制台命令暴露相同的 profile 语法,包括 `web` profile。 可执行文件族是 `deepseek-harness-sdk-runtime--`。SDK 协议格式、wheel 与 import 分发名称、伴随文件名称,以及协议 identity `deepseek-harness-sdk-runtime` 保持稳定。SDK 包族是 `@deepseek-ai/dsh-sdk-client`、`@deepseek-ai/dsh-sdk-protocol` 与 `@deepseek-ai/dsh-sdk-jsonrpc-server`;`@deepseek-ai/dsh-acp` 继续作为 ACP 协议插件。仓库不保留 Python 专用 Node 应用、检入的完整配置、兼容包、转发可执行文件、后备解析器或 SDK/ACP 启动别名。[docs/architecture.md](../../../../docs/architecture.zh.md)负责该启动方式,[`python/sdk-runtime` README](../../../../python/sdk-runtime/README.zh.md)负责 Windows 载体。 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-24-browser-token-authentication.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml index a67b37efe1..a48e1e3ffb 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml @@ -9,8 +9,8 @@ en: 01293500639c9d79 zh: 6d19e4843955c811 /agent-note-browser-launch-token-authentication/decision: - en: 063f9698b8a94287 - zh: 848b2c1134b7a100 + en: 54efa59339f75256 + zh: 0f53ead3844151c6 /agent-note-browser-launch-token-authentication/verification: en: 189b36d0fc5f3a17 zh: 08993cb585204fc0 @@ -18,5 +18,5 @@ en: 5275c87f19fe6eee zh: ccb922367c4bb3e2 /agent-note-browser-launch-token-authentication/consequences: - en: 0714a8a7cc74918a - zh: 0f3878b09463ab2e + en: af55274a2f345cdd + zh: 4d1810141ef03bae diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md index 47d6afe1bf..0038ca7b9b 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md @@ -14,13 +14,13 @@ The Web Host runs tool-capable Sessions with the current operating-system user's Each Host process generates a random launch token, retained by the root application context across Connection hot reloads. `dsh-web-app` prints and opens the normal root URL with that token in the query once per process. `frontend-static` asks Connection to authorize index responses: only `GET /?token=...` exchanges the process token for a cookie, then redirects to clean `./`; the token is not accepted on API paths or in an Authorization header. An obsolete token paired with a valid cookie redirects to clean `./`. Missing and invalid credentials receive one minimal 401 response. Static non-index assets remain public. -The cookie is a signed, authority-bound bearer. Its deterministic name and signed payload both include the normalized hostname plus port, so one Harness home can run independent Web ports without cookie collisions. The payload carries safe-integer issue and expiry times under an absolute lifetime; `cookieMaxAgeDays` defaults to 30. The cookie is host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`. It omits `Secure` because the shipped server uses loopback HTTP. There is no logout operation. +The cookie is a signed, authority-bound bearer. Its deterministic name and signed payload both include the normalized hostname plus port, so one Harness home can run independent Web ports without cookie collisions. The payload carries safe-integer issue and expiry times under an absolute lifetime; `cookieMaxAgeDays` defaults to 30. The cookie is host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`. The HTTP listener omits `Secure`. There is no logout operation. The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. Connection loads or creates the record during activation and retains the secret for synchronous request verification. An active Connection continues using its loaded secret if the durable record changes; the next activation loads the replacement or creates a missing record, so deleting the record and restarting the process revokes every existing cookie. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority. The in-page Web Worker preview exposes no network socket. Its page-owned `postMessage` tunnel enters the real route first, then retries a 401 or 403 through the worker-local fetch handler. This keeps Connection interceptors while limiting the authentication bypass to the page that created the Host worker. -The shipped CLI continues to reject `--host 0.0.0.0`. Authentication does not imply supported network deployment, TLS, forwarding-header interpretation, or proxy configuration. +The shipped CLI accepts concrete local bind addresses but rejects wildcard addresses such as `--host 0.0.0.0`. Authentication does not configure TLS, forwarding-header interpretation, or proxies. ## Verification @@ -42,6 +42,8 @@ Unit coverage pins process-token retention across Connection reloads, one secret Possession of the browser cookie authorizes the complete tool-capable Host API, matching the authority the Web application exposes after Session creation. `Host` does not grant a higher method tier, and a method migration between API Proxy and Typert Remote cannot change its caller set. -The persistent secret makes cookies survive restarts but gives a stolen cookie up to the configured absolute lifetime. Deleting the record and restarting the process is the global revocation mechanism; the active Connection intentionally avoids credential-provider work on each request. Omitting `Secure` preserves loopback HTTP and permits plaintext transmission if an operator makes the same cookie authority reachable over an unencrypted network. The startup URL contains a process credential and must be treated as sensitive output; runtime diagnostics do not repeat it. +The persistent secret makes cookies survive restarts but gives a stolen cookie up to the configured absolute lifetime. Deleting the record and restarting the process is the global revocation mechanism; the active Connection intentionally avoids credential-provider work on each request. An HTTP listener permits plaintext cookie transmission if its authority is reachable over an unencrypted network. The startup URL contains a process credential and must be treated as sensitive output; runtime diagnostics do not repeat it. The decision partially supersedes the authentication deferral and unauthenticated non-loopback consequences in the [browser trust note](2026-07-28-api-browser-trust-boundary.md). That note remains active authority for media-type, Host, Origin, Fetch-Metadata, and configured-authority validation. No active Agent Note is archived: the overlap is partial and both security rules retain future decision value. + +The [native HTTPS listener decision](2026-09-23-native-https-web-listener.md) supersedes the HTTP-only transport and omitted-`Secure` assumptions here. Listener protocol now determines `Secure`; the token exchange, signed-cookie authority, and credential lifetime remain owned by this note. diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md index 13ecf55e41..a08323b629 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md @@ -14,13 +14,13 @@ Web Host 以当前操作系统用户的权限运行具有工具能力的 Session 每个 Host 进程生成随机启动令牌,并由应用根 context 跨 Connection 热重载保留。`dsh-web-app` 每个进程只打印并打开一次 query 中带该令牌的普通根 URL。`frontend-static` 请求 Connection 授权 index 响应:只有 `GET /?token=...` 会把进程令牌交换为 cookie,再重定向到干净的 `./`;API 路径和 Authorization header 都不接受该令牌。过时令牌如果同时带有有效 cookie,会重定向到干净的 `./`。缺失与无效凭据得到同一份最小 401 响应。非 index 静态资产保持公开。 -cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。随附服务器使用 loopback HTTP,因此不设置 `Secure`。这里没有 logout 操作。 +cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。HTTP 监听器不设置 `Secure`。这里没有 logout 操作。 HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Connection 在激活期间加载或创建该记录,并保留密钥以同步校验请求。持久记录发生变化后,当前 Connection 继续使用已加载的密钥;下一次激活会加载替换记录或创建缺失记录,因此删除记录并重启进程会撤销全部既有 cookie。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。 页内 Web Worker preview 不暴露网络 socket。其由页面持有的 `postMessage` tunnel 先进入真实 route,收到 401 或 403 后再经 worker 本地 fetch handler 重试。这样既保留 Connection interceptor,又把认证绕过限制在创建 Host worker 的页面内。 -随附 CLI 继续拒绝 `--host 0.0.0.0`。认证不代表支持网络部署、TLS、转发 header 解释或代理配置。 +随附 CLI 接受本机具体绑定地址,但拒绝 `--host 0.0.0.0` 等通配地址。认证不会配置 TLS、转发 header 解释或代理。 ## 验证 @@ -42,6 +42,8 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 持有浏览器 cookie 就能调用完整的工具型 Host API,这与 Web 应用在创建 Session 后暴露的 authority 一致。`Host` 不授予更高的方法层级,方法在 API Proxy 与 Typert Remote 之间迁移也不会改变调用者集合。 -持久密钥使 cookie 跨重启生效,也让被盗 cookie 最多保有配置的绝对有效期。删除记录并重启进程是全局撤销机制;当前 Connection 刻意避免在每个请求上访问凭据提供方。不设置 `Secure` 保留 loopback HTTP,但如果操作者让同一 cookie authority 经未加密网络可达,cookie 会以明文传输。启动 URL 含进程凭据,必须视为敏感输出;运行时诊断不会重复它。 +持久密钥使 cookie 跨重启生效,也让被盗 cookie 最多保有配置的绝对有效期。删除记录并重启进程是全局撤销机制;当前 Connection 刻意避免在每个请求上访问凭据提供方。如果 HTTP listener 的 authority 经未加密网络可达,cookie 就可能以明文传输。启动 URL 含进程凭据,必须视为敏感输出;运行时诊断不会重复它。 本决策部分取代[浏览器信任说明](2026-07-28-api-browser-trust-boundary.zh.md)中的认证延期与未认证非 loopback 后果。该说明仍是媒体类型、Host、Origin、Fetch-Metadata 和配置 authority 校验的有效权威。没有 active Agent Note 被归档:重叠只发生在局部,两条安全规则都保有未来决策价值。 + +[原生 HTTPS 监听器决策](2026-09-23-native-https-web-listener.zh.md)取代本说明仅支持 HTTP 传输及不设置 `Secure` 的前提。`Secure` 由监听器协议决定;令牌交换、签名 cookie 的 authority 与凭据有效期仍由本说明定义。 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..ad94eb0bd5 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 @@ -21,11 +21,11 @@ en: 29def175ab33b7d6 zh: 87e55ec28c20c7c1 /agent-note-package-and-update-the-electron-desktop-application/updates-and-recovery: - en: e9f140cd22670dfa - zh: bf85cfe9c12a0345 + en: 4cb7014acfe71762 + zh: 2178e0337cba0324 /agent-note-package-and-update-the-electron-desktop-application/security-and-release-policy: - en: 97ee608e96fc3602 - zh: 932b98e7d344cd87 + en: 5faaa53b58121311 + zh: e1c3fc8d21a27d1a /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..0241afef65 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 @@ -75,13 +75,13 @@ The [immediate-window reference](../../../../apps/desktop/README.md) owns the lo `DSH_DESKTOP_AUTO_UPDATE_ENV` selects the test deployment by default or the production deployment for both the target-specific generic-provider URL and COS destination. Release automation supplies the test HTTPS origin through `DOWNLOAD_TEST_ORIGIN` and each deployment's bucket through `DOWNLOAD_TEST_COS_BUCKET` or `DOWNLOAD_PROD_COS_BUCKET`; keeping mutable test routing and COS storage identities out of source lets deployment infrastructure change without a code release, while the public production origin remains fixed. Packaging resolves only the public updater URL, disables electron-builder publishing, removes every COS credential field from its subprocess environment, and writes a completion record only after electron-builder and every signing or notarization hook succeeds. Target upload additionally requires the selected bucket, then requires the completion record, root dsh version, Desktop version, version-derived channel metadata, artifact names, sizes, and SHA-512 values to agree before it reads the selected credentials or sends data. It uploads immutable versioned updater payloads and any separate blockmaps before replacing the channel metadata emitted by electron-builder, and it never deletes historical objects. Stable versions use the `latest` metadata name; prereleases use the first semantic-version prerelease identifier. NSIS embeds its blockmap in the signed executable; the macOS ZIP carries a separate blockmap. Both let electron-updater download changed blocks when supported, while application replacement and the local pnpm package operation remain separate operations. -Test releases require `DOWNLOAD_TEST_RELEASE_ID` from the platform dotenv file. Their feeds and binaries share `dsh-desk//`; production retains its fixed directories. The ID is part of the packaged update URL, so upload rejects a different ID. Internal distribution can supply a new installer after rotation; installed clients retain their existing feed. Random directories reduce guessing but provide no authorization for link holders. The [release configuration](../../../../apps/desktop/README.md#upload-updates) defines generation and reuse. +Test releases require `DOWNLOAD_TEST_RELEASE_ID` from the platform dotenv file. Their feeds and binaries share `dsh-desk//`; production retains its fixed directories. The ID is part of the packaged update URL, so upload rejects a different ID. Internal distribution can supply a new installer after rotation; installed clients retain their existing feed. Random directories reduce guessing but provide no authorization for link holders. The [release configuration](../../../../apps/desktop/publishing/README.md#upload-updates) defines generation and reuse. ## Security and release policy 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. @@ -91,7 +91,7 @@ Windows package invocations force `ELECTRON_BUILDER_7Z_FILTER=BCJ`. The bundled Local Windows and macOS installation testing uses an explicit `--unsigned` package invocation with the same build and runtime preparation. It strips certificate inputs, isolates artifacts in `unsigned-artifacts`, and omits updater configuration and the release completion record. macOS local builds ignore dotenv files and inherited release settings, use the standard application ID, and omit mandatory-update policy so local testing needs no deployment configuration. Their App receives a certificate-free ad-hoc signature; their DMG is unsigned and unnotarized. Windows local builds retain their platform configuration requirements. The regular package command explicitly selects signed mode even when its parent environment requests unsigned mode. This separation permits installation diagnosis without release credentials while preventing local test output from qualifying for release upload. -Windows application replacement follows the [directory-installation reference](../../../../apps/desktop/README.md): extract beside the destination with a command-line tool that returns failure status, then rename complete directories on the same volume. The installer retains the old directory through staging and restores it if promotion fails. Registration, shortcuts, and the signed uninstaller remain owned by electron-builder. +Windows application replacement follows the [directory-installation reference](../../../../apps/desktop/packaging/README.md#runtime-file-selection): extract beside the destination with a command-line tool that returns failure status, then rename complete directories on the same volume. The installer retains the old directory through staging and restores it if promotion fails. Registration, shortcuts, and the signed uninstaller remain owned by electron-builder. Packaged applications ignore development resource and project environment overrides. Only an unpackaged Electron process can replace the pnpm entry, dsh resources, or active project. 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..f3075a175d 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 @@ -75,13 +75,13 @@ Electron 更新只使用一个 `electron-updater` 发布流和签名 `electron-b `DSH_DESKTOP_AUTO_UPDATE_ENV` 默认为测试部署,也可以选择生产部署,并同时决定目标专用的 generic-provider URL 与 COS 目标。发布自动化通过 `DOWNLOAD_TEST_ORIGIN` 提供测试 HTTPS origin,并通过 `DOWNLOAD_TEST_COS_BUCKET` 或 `DOWNLOAD_PROD_COS_BUCKET` 提供各部署的 bucket;可变的测试路由与 COS 存储身份不写入源码,部署基础设施变更时无需发布新代码,而公开的生产 origin 仍固定。打包只解析公开更新 URL、禁止 electron-builder 发布、从子进程环境中删除每个 COS 凭据字段,并且只有在 electron-builder 以及每个签名或公证 hook 成功后才写入完成记录。目标上传还必须提供所选 bucket,随后会先要求完成记录、根 dsh 版本、Desktop 版本、根据版本得出的频道元数据、产物名称、大小与 SHA-512 全部一致,再读取所选凭据或发送数据。它先上传不可变且带版本的更新载荷与所有独立 blockmap,最后替换 electron-builder 生成的频道元数据,并且不会删除历史对象。稳定版本使用 `latest` 元数据名称,预发布版本则使用语义化版本的第一个预发布标识符。NSIS 把 blockmap 嵌入已签名的可执行文件,macOS ZIP 则使用独立 blockmap;两者都让 electron-updater 在平台支持时只下载变化的数据块,而应用替换与本地 pnpm 包操作仍是两个独立操作。 -测试发布必须从平台 dotenv 文件提供 `DOWNLOAD_TEST_RELEASE_ID`。清单和安装包共用 `dsh-desk//`,生产环境保留固定目录。ID 是打包更新 URL 的一部分,因此上传会拒绝不同的 ID。轮换后可通过内部分发提供新安装包,已安装客户端保留原清单地址。随机目录降低被猜中的概率,但不对持有链接者进行鉴权。[发布配置](../../../../apps/desktop/README.zh.md#upload-updates)定义生成与复用方式。 +测试发布必须从平台 dotenv 文件提供 `DOWNLOAD_TEST_RELEASE_ID`。清单和安装包共用 `dsh-desk//`,生产环境保留固定目录。ID 是打包更新 URL 的一部分,因此上传会拒绝不同的 ID。轮换后可通过内部分发提供新安装包,已安装客户端保留原清单地址。随机目录降低被猜中的概率,但不对持有链接者进行鉴权。[发布配置](../../../../apps/desktop/publishing/README.zh.md#upload-updates)定义生成与复用方式。 ## 安全与发布策略 核心 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 别名执行已安装依赖;发布验收仍要求严格应用验证、公证和启动。 @@ -91,7 +91,7 @@ Windows 打包调用强制设置 `ELECTRON_BUILDER_7Z_FILTER=BCJ`。内置的 7- 本地 Windows 和 macOS 安装测试使用显式的 `--unsigned` 打包调用,并执行相同的构建和运行时准备。它清除证书输入,将产物隔离到 `unsigned-artifacts`,并省略更新器配置和发布完成记录。macOS 本地构建忽略 dotenv 文件和继承的发布配置,使用标准应用 ID,并省略强制更新策略,使本地测试无需部署配置。其 App 使用无需证书的 ad-hoc 签名,DMG 不签名也不公证。Windows 本地构建保留平台配置要求。即使父进程环境请求未签名模式,常规打包命令也会显式选择签名模式。这样既能在没有发布凭据时诊断安装问题,也能防止本地测试产物通过发布上传校验。 -Windows 应用替换遵循[目录安装参考](../../../../apps/desktop/README.zh.md):使用能返回失败状态的命令行工具解压到目标旁边,再在同卷内改名替换完整目录。安装器在暂存期间保留旧目录,正式替换失败时恢复旧目录。注册信息、快捷方式和签名卸载器仍由 electron-builder 持有。 +Windows 应用替换遵循[目录安装参考](../../../../apps/desktop/packaging/README.zh.md#runtime-file-selection):使用能返回失败状态的命令行工具解压到目标旁边,再在同卷内改名替换完整目录。安装器在暂存期间保留旧目录,正式替换失败时恢复旧目录。注册信息、快捷方式和签名卸载器仍由 electron-builder 持有。 打包应用会忽略开发资源和项目环境变量覆盖。只有未打包的 Electron 进程可以替换 pnpm 入口、dsh 资源 或活跃项目。 diff --git a/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.i18n.yaml index 207508cad2..260adf6610 100644 --- a/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.i18n.yaml @@ -12,8 +12,8 @@ en: 1188c699ce6e6ca2 zh: 4d5b974cd1216f06 /agent-note-adjacent-agents-share-one-steer-send-message-operation/decision/one-model-tool-and-one-return-instruction: - en: 8a4be155a4984ca8 - zh: 00c2a61da2443530 + en: 4b0a25389324fa91 + zh: c2cdd9f7e40ef43b /agent-note-adjacent-agents-share-one-steer-send-message-operation/decision/complete-removal-and-reintroduction-condition: en: 5a9ec6478cf7430c zh: f4c2f067cc72040e diff --git a/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.md b/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.md index 43048f9a8c..4efb9d334e 100644 --- a/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.md +++ b/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.md @@ -46,7 +46,7 @@ interface SendMessageInput { } ``` -Parents and children inherit the same definition in the same registry order. The standard definition carries a process-stable internal identity that a scoped same-name tool does not satisfy. A child `toolFilter` may explicitly remove the inherited tool, and a scoped replacement may provide different semantics; neither case receives the standard call instruction. When the standard tool remains visible, the continuation manager appends the JSON-encoded direct parent id and the instruction to send one self-contained result before finishing, plus earlier actionable findings, to the child's initial user task. For a fork child this task follows the inherited completed-turn prefix; no child-only system-prompt section or tool schema precedes that prefix. +Parents and children inherit the same definition in the same registry order. The standard definition carries a process-stable internal identity that a scoped same-name tool does not satisfy. An independently selected preset may omit the tool, a historical descriptor filter may remove it on resume, and a scoped replacement may provide different semantics; neither case receives the standard call instruction. When the standard tool remains visible, the continuation manager appends the JSON-encoded direct parent id and the instruction to send one self-contained result before finishing, plus earlier actionable findings, to the child's initial user task. For a fork child this task follows the inherited completed-turn prefix; no child-only system-prompt section or tool schema precedes that prefix. The instruction is guidance, not settlement enforcement. Sending does not end the child's turn, zero or several calls remain mechanically valid, and the runtime never rejects a child for staying silent. The manager-owned `subagent-settled` notice remains unconditional and separately attributed because it records how an Activation ended and preserves terminal output when the child cannot cooperate. diff --git a/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.zh.md b/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.zh.md index 6d1e2d4923..b7ed157f54 100644 --- a/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.zh.md @@ -46,7 +46,7 @@ interface SendMessageInput { } ``` -parent 与 child 以相同注册表顺序继承相同定义。标准定义携带进程稳定的内部身份,同名的作用域工具不满足该身份。child `toolFilter` 可以显式移除继承的工具,作用域替代工具也可以提供不同语义;两种情况都不会收到标准调用指令。当标准工具仍可见时,继续执行管理器会把经过 JSON 编码的直接 parent id、结束前发送一份自包含结果的指令,以及更早发送可操作发现的指令追加到 child 初始用户任务。对 fork child 而言,该任务位于继承的已完成轮次前缀之后;没有 child 专属系统提示词 section 或工具 schema 位于此前缀之前。 +parent 与 child 以相同注册表顺序继承相同定义。标准定义携带进程稳定的内部身份,同名的作用域工具不满足该身份。独立选择的 preset 可以省略该工具,历史 descriptor 过滤器可在恢复时移除该工具,作用域替代工具也可以提供不同语义;两种情况都不会收到标准调用指令。当标准工具仍可见时,继续执行管理器会把经过 JSON 编码的直接 parent id、结束前发送一份自包含结果的指令,以及更早发送可操作发现的指令追加到 child 初始用户任务。对 fork child 而言,该任务位于继承的已完成轮次前缀之后;没有 child 专属系统提示词 section 或工具 schema 位于此前缀之前。 该指令是指导,不是结算强制。发送不会结束 child 轮次,机制仍允许零次或多次调用,runtime 绝不会因 child 保持沉默而拒绝它。由管理器负责的 `subagent-settled` 通知仍无条件发送并采用独立来源,因为它记录 Activation 如何结束,并在 child 无法配合时保留终态输出。 diff --git a/.agents/notes/implemented/architecture/2026-09-03-jobs-seam-consolidation.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-03-jobs-seam-consolidation.i18n.yaml index 2a8fdcb1f7..b66d66b8e0 100644 --- a/.agents/notes/implemented/architecture/2026-09-03-jobs-seam-consolidation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-03-jobs-seam-consolidation.i18n.yaml @@ -15,5 +15,5 @@ en: 09be2a1cf1d52fd5 zh: 0bf0e18c73542012 /agent-note-one-output-ring-one-projection-one-event-stream-for-background-jobs/consequences: - en: 464eb843a71eb04e - zh: 783062f5b288b1b4 + en: 3263801e173b6b86 + zh: f6f51bb3f77a817e diff --git a/.agents/notes/implemented/architecture/2026-09-03-jobs-seam-consolidation.md b/.agents/notes/implemented/architecture/2026-09-03-jobs-seam-consolidation.md index 0a75d42b30..04f106edf3 100644 --- a/.agents/notes/implemented/architecture/2026-09-03-jobs-seam-consolidation.md +++ b/.agents/notes/implemented/architecture/2026-09-03-jobs-seam-consolidation.md @@ -35,3 +35,5 @@ The job seam had grown by accretion. Producers declared their output twice — a The model-visible text is unchanged: status lines, tool descriptions and schemas, and notice wording are byte-identical, and the only new model-visible fact is the kill reason a `killed` status line now carries. A producer that needs to stream output picks pull sources or `append`; it never formats a consuming delta. The Web client renders every live job as expandable, so a job that never writes shows an empty running panel instead of a static row. `JobKindMap` merges are host-side, so a browser program types `JobView.kind` as the kinds it knows and treats the rest as opaque strings, which is all the roster does with it. Review follow-ups after the master merge tightened four of these edges. A job's first event is always `registered`: the announcement precedes the pump, whose first drain runs synchronously and may announce output. A settled ring keeps every byte the model cursor has not consumed until the first terminal model read, so a job that finishes before its first `job_output` loses nothing the live cap retained. `dsh-tool-jobs` holds one claim per wait call with a `live` flag that the caller's abort clears synchronously from the abort event, so a settlement announced before the registry's rejection reaches the tool still delivers its notice, and a timed-out wait drops only its own claim while a concurrent wait keeps the settlement covered. The browser records an observation failure that precedes the anchor as an errored view, so the panel shows the notice instead of staying blank. The spill file a pull source keeps is job metadata (`JobView.output.spillPaths`, reported by every pump read and withdrawn once a read stops naming it), not per-chunk metadata, and the model's read renders the shell tools' dropped-output notice for a producer-side gap as well as for ring eviction, naming those files even after the gap chunk itself was evicted — the `before this read` variant this change had introduced is gone. An observation generation that sees its job removed mid-stream (the owner's teardown) closes with the removed job's terminal projection instead of a failed read. A rejected background spawn produces no process output, so the shell providers now serve the `spawn failed: …` note as the whole observed stderr stream (the consuming read still folds it in once), and `ShellProcess.observed` with both readers is required: the model's first `job_output` after such a failure reads exactly what master's consuming read rendered. + +The [Session lifecycle decision](../bug-fix/2026-09-30-job-session-lifecycle.md) records registration and settlement for durable SDK consumers while preserving this live event stream and output ownership. diff --git a/.agents/notes/implemented/architecture/2026-09-03-jobs-seam-consolidation.zh.md b/.agents/notes/implemented/architecture/2026-09-03-jobs-seam-consolidation.zh.md index 5cfc88927c..798f9d2b7c 100644 --- a/.agents/notes/implemented/architecture/2026-09-03-jobs-seam-consolidation.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-03-jobs-seam-consolidation.zh.md @@ -35,3 +35,5 @@ job seam 是逐步堆出来的。生产者要把输出声明两次——模型 模型可见文本保持不变:状态行、工具描述与 schema、播报措辞逐字节相同,唯一新增的模型可见事实是 `killed` 状态行现在携带的 kill 原因。需要流式输出的生产者选择拉取源或 `append`,从不格式化消耗式增量。Web 客户端把每个进行中的 job 渲染为可展开,因此从不写输出的 job 显示为空的运行中面板而非静态行。`JobKindMap` 的合并发生在宿主侧,浏览器程序把 `JobView.kind` 视为它认识的 kind 集合,其余当作不透明字符串——名册对它也只做这些。 合并 master 之后的评审跟进收紧了其中四条边。job 的第一个事件永远是 `registered`:通告先于泵,而泵的首轮 drain 同步执行且可能通告输出。已结算的环在模型的首次终态读取之前保留模型游标尚未消费的全部字节,因此在首次 `job_output` 之前结束的 job 不会丢失运行期上限保留的任何内容。`dsh-tool-jobs` 为每次等待调用保存一条带 `live` 标记的认领,调用方 abort 时在 abort 事件里同步清掉该标记,因此注册表的拒绝尚未传回工具之前宣布的结算仍会投递通知;超时的等待只丢弃自己的认领,并发的另一个等待仍覆盖该结算。浏览器把先于锚点发生的观察失败记录为带错误的视图,面板显示提示而不是留白。拉取源保留的 spill 文件是 job 元数据(`JobView.output.spillPaths`,每次泵读取都会上报,读取不再点名时即撤回),不是逐块元数据;模型读取对生产者侧缺口与环淘汰都渲染 shell 工具的丢失输出提示并列出这些文件,即使缺口块本身已被淘汰——本次变更曾引入的 `before this read` 变体已删除。观察生成过程若在流中看到其 job 被移除(拥有者 teardown),以被移除 job 的终态投影收尾,而不是一次失败的读取。被拒绝的后台 spawn 不产生任何进程输出,因此 shell provider 现在把 `spawn failed: …` 提示作为 observed stderr 的整条流提供(消耗式读取仍只折入一次),且 `ShellProcess.observed` 及其两个读取器改为必填:这类失败之后模型的首次 `job_output` 读到的正是 master 的消耗式读取所渲染的内容。 + +[Session 生命周期决策](../bug-fix/2026-09-30-job-session-lifecycle.zh.md)为持久化 SDK 消费方记录注册与结算,同时保留这里的运行期事件流和输出归属。 diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml index 72e167ce59..40b064454f 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml @@ -12,14 +12,14 @@ en: e01df5ba880c2972 zh: e62074a6a9ba5685 /agent-note-bundle-the-desktop-runtime-and-retain-external-plugins/package-ownership: - en: 37cae6b28fd359ef - zh: 63118e361fa8f84c + en: f683605bf4655db8 + zh: de09d610ee1d4193 /agent-note-bundle-the-desktop-runtime-and-retain-external-plugins/transactions-and-upgrades: en: 53d48f71fcc1c52e zh: 7d61923484dbec1c /agent-note-bundle-the-desktop-runtime-and-retain-external-plugins/alternatives-considered: - en: ead5bbd94044c3de - zh: 057cf069413d2a49 + en: 67b3ba2b37e92f88 + zh: 785083e5de098af8 /agent-note-bundle-the-desktop-runtime-and-retain-external-plugins/consequences: en: 6dfa581ec6879c5b zh: f6c735ad6a00b2b3 diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md index f8f6599fe6..a1aeb68f2d 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md @@ -26,7 +26,7 @@ The resource descriptor records the exact release, Node version, platform, archi The [Desktop file policy](../../../../apps/desktop/scripts/runtime-file-policy.ts) applies after production npm installation and before native signing or descriptor generation. npm publication lists serve library consumers and can include declarations, maps, tests, and native build inputs; they do not identify the files needed by the Desktop process. The Desktop copy omits declarations and recognized source maps because Host execution uses JavaScript and generated Typert artifacts. The Host inherits the user environment. Published npm packages and external plugin directories retain their own files. Source debugger navigation is a development-package capability. -Package-specific exclusions remove Domino tests, fs-ext compilation outputs, Koffi's Windows import library, and non-target node-pty prebuilds and debug symbols. The policy retains native executable dependencies, node-pty's ConPTY source distribution, licenses, and unrecognized assets; broad `src`, `test`, `.ts`, or `.map` exclusions could remove executable code or runtime data. Copy tests preserve sentinel assets and seal the filtered inventory; the Electron [payload smoke](../../../../apps/desktop/tests/fixtures/runtime-payload-smoke.mjs) verifies PTY output, native file seeking, FFI, image conversion, and HTML parsing. Runtime preparation still verifies every retained byte and boots the complete Host with an external plugin. +Package-specific exclusions remove Domino tests, fs-ext compilation outputs, Koffi's Windows import library, and non-target node-pty prebuilds and debug symbols. The policy retains native executable dependencies, licenses, and unrecognized assets; node-pty's ConPTY source distribution is retained only for Windows targets; broad `src`, `test`, `.ts`, or `.map` exclusions could remove executable code or runtime data. Copy tests preserve sentinel assets and seal the filtered inventory; the Electron [payload smoke](../../../../apps/desktop/tests/fixtures/runtime-payload-smoke.mjs) verifies PTY output, native file seeking, FFI, image conversion, and HTML parsing. Runtime preparation still verifies every retained byte and boots the complete Host with an external plugin. The shared profile runner supplies missing installation and selected-bundle dependencies through the runtime resolution. pnpm-installed packages take precedence. Runtime resolution delegates to the selected package paths, so Host and plugin imports reaching the same export share its module instance. Distinct ESM and CommonJS conditional exports remain distinct entry points; runtime resolution does not merge a package’s dual implementations. @@ -48,7 +48,7 @@ The [immediate-window reference](../../../../apps/desktop/README.md) owns direct ## Alternatives considered -Full runtime verification belongs to packaging. Startup reads the resource descriptor and checks shared package records and required Host entries. The [release-validation reference](../../../../apps/desktop/README.md) assigns release and target compatibility checks to packaging. Startup neither enumerates nor hashes installed runtime files. Reading every file before backend loading adds I/O proportional to distribution size; unusable modules instead fail when loaded. Build-time verification rejects changed, missing, extra, or linked files against the recorded inventory. +Full runtime verification belongs to packaging. Startup reads the resource descriptor and checks shared package records and required Host entries. The [release-validation reference](../../../../apps/desktop/packaging/README.md#desktop-runtime-preparation) assigns release and target compatibility checks to packaging. Startup neither enumerates nor hashes installed runtime files. Reading every file before backend loading adds I/O proportional to distribution size; unusable modules instead fail when loaded. Build-time verification rejects changed, missing, extra, or linked files against the recorded inventory. - **Install the bundled offline seed at startup.** This preserves an ordinary pnpm installation procedure but repeats core extraction and installation on every affected machine. Materialized resources remove that work at the cost of more application files and release-builder responsibility. - **Force host dependency versions into plugins.** This unnecessarily couples ordinary plugin dependencies to the host. The runtime resolution supplies missing packages while pnpm-owned entries retain independent versions. diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md index 6d14494858..73728d1feb 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md @@ -26,7 +26,7 @@ Desktop 初始化时安装核心依赖图,会重复发布构建器已经完成 [桌面文件规则](../../../../apps/desktop/scripts/runtime-file-policy.ts)在生产 npm 依赖安装之后、原生签名或描述文件生成之前执行。npm 发布列表服务于库的使用者,可以包含声明、map、测试和原生构建输入,不能直接表示桌面进程需要哪些文件。桌面副本排除声明和已识别的 source map,因为 Host 执行 JavaScript 和生成的 Typert 产物。Host 继承用户环境。已发布的 npm 包和外部插件目录保留各自的文件。源码调试导航由开发包提供。 -包专用排除项包括 Domino 测试、fs-ext 编译产物、Koffi 的 Windows 导入库,以及非目标平台的 node-pty 预构建文件和调试符号。规则保留原生可执行依赖、node-pty 的 ConPTY 源分发内容、许可证和未知资源;宽泛排除 `src`、`test`、`.ts` 或 `.map` 可能移除可执行代码或运行时数据。复制测试保留哨兵资源并封存过滤后的清单;Electron 的[产物 smoke](../../../../apps/desktop/tests/fixtures/runtime-payload-smoke.mjs)验证 PTY 输出、原生文件定位、FFI、图像转换和 HTML 解析。运行时准备仍会验证每个保留字节,并携带外部插件启动完整 Host。 +包专用排除项包括 Domino 测试、fs-ext 编译产物、Koffi 的 Windows 导入库,以及非目标平台的 node-pty 预构建文件和调试符号。规则保留原生可执行依赖、许可证和未知资源;node-pty 的 ConPTY 源分发内容仅在 Windows 目标中保留;宽泛排除 `src`、`test`、`.ts` 或 `.map` 可能移除可执行代码或运行时数据。复制测试保留哨兵资源并封存过滤后的清单;Electron 的[产物 smoke](../../../../apps/desktop/tests/fixtures/runtime-payload-smoke.mjs)验证 PTY 输出、原生文件定位、FFI、图像转换和 HTML 解析。运行时准备仍会验证每个保留字节,并携带外部插件启动完整 Host。 共享 profile runner 通过 runtime resolution 补全安装包与选中 bundle 缺失的依赖。pnpm 安装的包优先。运行时解析委托给所选包路径,因此 Host 与插件导入同一导出时共享其模块实例。不同的 ESM 与 CommonJS 条件导出仍是不同入口;运行时解析不会合并包的双重实现。 @@ -48,7 +48,7 @@ profile manifest 分别记录 pnpm 安装的依赖及已启用 bundle 列表。 ## 考虑过的替代方案 -完整运行时验证属于打包流程。启动读取资源描述文件,并检查共享包记录及必要的 Host 入口。[发布验证参考](../../../../apps/desktop/README.zh.md)将发布与目标兼容性检查交给打包流程。启动既不枚举已安装运行时文件,也不计算其哈希。后端加载前读取每个文件会增加与分发体积成正比的 I/O;不可用模块改由加载时失败暴露。构建时验证按记录清单拒绝内容变化、缺失、多余或链接文件。 +完整运行时验证属于打包流程。启动读取资源描述文件,并检查共享包记录及必要的 Host 入口。[发布验证参考](../../../../apps/desktop/packaging/README.zh.md#desktop-runtime-preparation)将发布与目标兼容性检查交给打包流程。启动既不枚举已安装运行时文件,也不计算其哈希。后端加载前读取每个文件会增加与分发体积成正比的 I/O;不可用模块改由加载时失败暴露。构建时验证按记录清单拒绝内容变化、缺失、多余或链接文件。 - **启动时安装内置离线 seed。** 这保留普通 pnpm 安装流程,但会在每台受影响机器上重复核心解压与安装。物化资源消除了这部分工作,代价是更多应用文件和发布构建器责任。 - **强制插件使用 Host 依赖版本。** 这会让普通插件依赖不必要地耦合于 Host。runtime resolution 提供缺失的包,pnpm 拥有的条目保留独立版本。 diff --git a/.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.i18n.yaml index 5cadfbef6f..8d31b237e6 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.i18n.yaml @@ -33,8 +33,8 @@ en: 99308bd758859e02 zh: 35f1e7719fe80d2e /agent-note-add-immutable-profile-resolution-generations/decision/additive-package-changes: - en: 0e5e2006caec3c91 - zh: fb3b61dd5692d2e3 + en: 39d27cff0d419259 + zh: 6cbdc88a450614d0 /agent-note-add-immutable-profile-resolution-generations/decision/filesystem-and-runtime-carriers: en: b0607713102a093d zh: 2de9c33bfaa0e3e2 diff --git a/.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.md b/.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.md index d933a4507e..08aeffa559 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.md +++ b/.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.md @@ -107,7 +107,7 @@ New Workers inherit the latest published generation. Existing Workers keep the g A caller adding a package completes its pnpm transaction before constructing a successor generation. Replacement rejects any generation that changes the directory or version of a retained package. Plugin Manager publishes the successor before mounting the new Loader row. A mount failure may leave the package installed but inactive. -A retained package keeps its normalized directory, version, and scope; installation entries also keep their declaring anchor and cannot be removed. Violating these restrictions requires process restart because Node's ESM Module Map, CommonJS cache, existing object references, and running Workers can retain the old module identity. A profile entry may change its declaring anchor: deselecting the first bundle that reaches a shared dependency can leave another bundle selecting the same physical package. Profile-scoped mappings and profile-local package names may be removed; the caller stops their plugins before deleting package files. These restrictions do not prohibit removing a linked root from the interception scope. Generation replacement does not claim to unload modules. +A retained package keeps its normalized directory, version, and scope; installation entries also keep their declaring anchor and cannot be removed. Violating these restrictions requires process restart because Node's ESM Module Map, CommonJS cache, existing object references, and running Workers can retain the old module identity. A profile entry may change its declaring anchor: deselecting the first bundle that reaches a shared dependency can leave another bundle selecting the same physical package. Profile-scoped mappings and profile-local package names may be removed; the caller stops their plugins before deleting package files. A profile mapping moves to another directory only through removal and a new installation; a linked root may point to another target ([replacement Note](2026-10-01-replace-changed-package-modules-on-recomposition.md)). These restrictions do not prohibit removing a linked root from the interception scope. Generation replacement does not claim to unload modules. ### Filesystem and runtime carriers diff --git a/.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.zh.md b/.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.zh.md index 24da72defb..cf63626c6a 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.zh.md @@ -107,7 +107,7 @@ runtime resolution 列出它提供的包;Loader entries 组成活动插件列 添加包的调用方先完成 pnpm 事务,再构造下一代。替换操作会拒绝改变任何保留包的目录或版本。Plugin Manager 先发布后继 generation,再挂载新的 Loader 配置项。挂载失败可以留下已安装但未启用的包。 -保留包的规范化目录、版本和作用域必须不变;安装条目还必须保留声明锚点,且不能移除。违反这些限制需要重启,因为 Node 的 ESM Module Map、CommonJS cache、现存对象引用和运行中的 Worker 都可能保留旧模块 identity。profile 条目可以改变声明锚点:取消选入最先找到共享依赖的组合包后,另一个组合包仍可能选中同一物理包。profile 范围的映射和 profile 本地包名可以移除;调用方在删除包文件之前先停止相关插件。这些限制不禁止从拦截范围移除 linked root。generation 换代不声称卸载模块。 +保留包的规范化目录、版本和作用域必须不变;安装条目还必须保留声明锚点,且不能移除。违反这些限制需要重启,因为 Node 的 ESM Module Map、CommonJS cache、现存对象引用和运行中的 Worker 都可能保留旧模块 identity。profile 条目可以改变声明锚点:取消选入最先找到共享依赖的组合包后,另一个组合包仍可能选中同一物理包。profile 范围的映射和 profile 本地包名可以移除;调用方在删除包文件之前先停止相关插件。profile 映射只能通过卸载和重新安装移到其他目录;linked root 可以指向其他目标([替换 Note](2026-10-01-replace-changed-package-modules-on-recomposition.zh.md))。这些限制不禁止从拦截范围移除 linked root。generation 换代不声称卸载模块。 ### 文件系统与运行时载体 diff --git a/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.i18n.yaml index 423de99127..6c236fcf0f 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.i18n.yaml @@ -9,8 +9,11 @@ en: f67f6add03a36e85 zh: 656be288f8b2e1d2 /agent-note-posix-ssh-execution-providers/decision: - en: b2d1e370d008f0f3 - zh: 3e98919538d3fb78 + en: bc22949098fc3028 + zh: 76618180bc0bac56 +/agent-note-posix-ssh-execution-providers/decision/helper-deployment: + en: c479fdb58ed617f1 + zh: 17cfefa778e3fd71 /agent-note-posix-ssh-execution-providers/alternatives-considered: en: 4efffb3edba91689 zh: 40100a70e5f55a42 @@ -18,8 +21,8 @@ en: f29359ab89feb084 zh: db7505b8d4a5351a /agent-note-posix-ssh-execution-providers/verification: - en: 822c7c029a77f3c0 - zh: 4a2eaaf3372cba8b + en: ee72e88fd40d6769 + zh: 56f0e0c8f3365973 /agent-note-posix-ssh-execution-providers/deferred-work: en: f300f112c9a09f7e zh: b4708a0b7f596420 diff --git a/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.md b/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.md index d54600faa6..3bd1c340d1 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.md +++ b/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.md @@ -22,12 +22,20 @@ Each stream receives a fresh 256-bit TLS pre-shared key through private administ Collected stdout and stderr carry bounded tail snapshots through handlers that only update output observations. Capture continues while a snapshot is waiting for transport. Final snapshots preserve raw-byte offsets, and completed spill files use the local provider’s retained-output storage after connection disposal. -Readiness verifies the installed helper digest and, when PTC is configured, the installed Node bootstrap digest. These checks pin expected deployment artifacts; they do not authenticate a malicious remote operating system. The helper disables Node debugger activation through `SIGUSR1`: file-effect confinement can still permit same-user signals, which must not expose the helper's unrestricted filesystem and process services. File-effect confinement delegates to the remote local sandbox provider and retains its full/partial disclosure and platform limitations. +Readiness verifies the installed helper script or executable digest and, when a script deployment supplies a PTC bootstrap, that bootstrap's digest. Executable deployments embed the PTC worker and require no separate bootstrap. These checks pin expected deployment artifacts; they do not authenticate a malicious remote operating system. The helper disables Node debugger activation through `SIGUSR1`: file-effect confinement can still permit same-user signals, which must not expose the helper's unrestricted filesystem and process services. File-effect confinement delegates to the remote local sandbox provider and retains its full/partial disclosure and platform limitations. -Path canonicalization belongs where the files exist. The shared policy resolver preserves absolute execution-world spelling; enforcing providers resolve symlinks and `..` on their own filesystem. Headless records and validates cwd through `ctx.fs`. Host-path projection remains unavailable for SSH, so Node execution requires an explicitly installed remote bootstrap. +Path canonicalization belongs where the files exist. The shared policy resolver preserves absolute execution-world spelling; enforcing providers resolve symlinks and `..` on their own filesystem. Headless records and validates cwd through `ctx.fs`. Host-path projection remains unavailable for SSH; PTC uses an explicitly installed remote bootstrap for script deployments or the helper executable's embedded worker. A lost connection invalidates pending operations without reconnect or replay. Helper EOF, signals and a heartbeat lease initiate remote native cleanup. The client cannot turn lease expiry into an observed successful termination: an interrupted mutation or launch can have an unknown outcome. Administrative request deadlines, consumer execution deadlines and cleanup remain separate owners. +### Helper deployment + +The explicit `launch.kind` selects remote `node-script` or `executable` invocation independently of the local Harness carrier. A local `process.pkg` flag cannot describe the remote installation. Protocol 2 includes the remote runtime kind in its readiness response and rejects protocol or launch-kind mismatches, so a client cannot apply script bootstrap rules to an embedded worker. Client and helper protocol upgrades must be deployed together. + +The executable embeds Node, the helper, managed subprocess runners and the PTC worker. It reuses the [SDK executable packaging decision](2026-07-10-single-file-executable-sdk-runtime-distribution.md): `pkg --sea` preserves a package tree and dynamic module resolution instead of maintaining a separate static plugin registry. That record owns the comparison with bare Node SEA. The embedded runtime serves these private entry points; project commands still depend on the remote machine's development tools. + +The four release targets cover Linux and macOS on x64 and arm64, matching the POSIX providers and their supported native resources. Packaging does not add Windows or musl support. Landlock and macOS PTY launchers remain real files beside the executable because the operating system cannot execute paths inside pkg's virtual filesystem. The installation unit is therefore the complete archive directory, with native resources and integrity metadata, rather than the executable alone. The [helper runtime reference](../../../../packages/ssh/ssh-helper-runtime/README.md) owns the build matrix, deployment baselines and archive verification commands. + ## Alternatives considered **Frame every stream over SSH exec stdout/stdin.** This avoids Unix-socket forwarding, but requires per-stream credits, queue bounds and independent EOF semantics inside the application protocol. Independent SSH channels use the transport’s existing flow control and keep program output away from administrative framing. @@ -48,7 +56,7 @@ The portable-consumer decision remains active; this note supplies its SSH realiz ## Verification -Required protocol and lifecycle evidence covers malformed frames, bounds, reservation cancellation, authenticated stream publication and disconnect errors. Native SSH acceptance must exercise remote file guards and symlink identity, Bash confinement, fd 7 binary traffic, control progress under paused output, terminal operations, LSP and Node execution. Live checks require an explicitly configured disposable remote workspace; keyless tests do not provision one. +Required protocol and lifecycle evidence covers malformed frames, bounds, reservation cancellation, authenticated stream publication and disconnect errors. Native SSH acceptance must exercise remote file guards and symlink identity, Bash confinement, fd 7 binary traffic, control progress under paused output, terminal operations, LSP and Node execution. External-host checks require an explicitly configured disposable remote workspace. Packaged Linux acceptance provisions a disposable OpenSSH container without Node; native-host checks own confinement evidence. Security evidence requires both a same-user connector and a replaced socket listener that cannot claim a reserved stream, learn its key, alter another run or receive its plaintext output. Process-lifecycle evidence distinguishes direct exit from managed-range quiescence and tests cancellation both before launch publication and after the payload starts. Source and built profile checks verify the installed helper/bootstrap arrangement without transferring host credentials to program environments. diff --git a/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.zh.md b/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.zh.md index a6b3a84c37..5ad2d3c471 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.zh.md @@ -22,12 +22,20 @@ SSH 提供经过认证的字节通道及逐通道流量控制,但普通 exec 收集的 stdout 与 stderr 通过仅更新输出观测的处理器传递有界尾部快照。快照等待传输时,输出捕获继续进行。最终快照保留原始字节偏移,已完成的 spill 文件在连接释放后使用本地提供方的保留输出存储。 -就绪流程验证已安装辅助程序的摘要,并在配置 PTC 时验证已安装 Node 引导程序的摘要。这些检查固定预期部署产物,不用于认证恶意远端操作系统。辅助程序禁用通过 `SIGUSR1` 启动 Node 调试器:文件效果限制仍可能允许同用户信号,这些信号不得暴露辅助程序不受限的文件系统和进程服务。文件效果限制委托给远端本地沙箱提供方,保留其完整/部分执行披露及平台限制。 +就绪流程验证已安装辅助脚本或可执行文件的摘要;脚本部署提供 PTC 引导程序时,还验证该引导程序的摘要。可执行文件部署内嵌 PTC 工作进程,无需单独的引导程序。这些检查固定预期部署产物,不用于认证恶意远端操作系统。辅助程序禁用通过 `SIGUSR1` 启动 Node 调试器:文件效果限制仍可能允许同用户信号,这些信号不得暴露辅助程序不受限的文件系统和进程服务。文件效果限制委托给远端本地沙箱提供方,保留其完整/部分执行披露及平台限制。 -路径规范化属于文件实际存在的位置。共享策略解析器保留执行环境中的绝对路径写法;执行限制的提供方在自己的文件系统上解析符号链接与 `..`。headless 通过 `ctx.fs` 记录和验证 cwd。SSH 不提供主机路径投影,因此 Node 执行需要显式安装的远端引导程序。 +路径规范化属于文件实际存在的位置。共享策略解析器保留执行环境中的绝对路径写法;执行限制的提供方在自己的文件系统上解析符号链接与 `..`。headless 通过 `ctx.fs` 记录和验证 cwd。SSH 不提供主机路径投影;PTC 在脚本部署中使用显式安装的远端引导程序,在可执行文件部署中使用辅助程序内嵌的工作进程。 连接丢失会使待处理操作失效,不进行重连或重放。辅助进程 EOF、信号及心跳租期会启动远端原生清理。客户端不能把租期到期当作观察到的成功终止:被中断的修改或启动可能结果未知。管理请求截止时限、消费方执行截止时限及清理分别由各自归属方负责。 +### 辅助程序部署 + +显式的 `launch.kind` 选择远端的 `node-script` 或 `executable` 调用方式,与本地 Harness 的运行载体相互独立。本地 `process.pkg` 标志无法描述远端安装。协议 2 在就绪响应中包含远端运行时类型,并拒绝协议版本或启动类型不匹配,避免客户端把脚本引导规则用于内嵌工作进程。客户端与辅助程序的协议升级必须一起部署。 + +可执行文件内嵌 Node、辅助程序、托管子进程运行器与 PTC 工作进程。它复用 [SDK 可执行文件打包决策](2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md):`pkg --sea` 保留包目录树与动态模块解析,无需维护独立的静态插件注册表。该记录负责与裸 Node SEA 的方案比较。内嵌运行时服务于这些私有入口;项目命令仍依赖远端机器的开发工具。 + +四个发布目标覆盖 Linux 和 macOS 的 x64 与 arm64,对应 POSIX 提供方及其支持的原生资源。打包不会增加 Windows 或 musl 支持。Landlock 与 macOS PTY 启动器保留为可执行文件旁的真实文件,因为操作系统无法执行 pkg 虚拟文件系统中的路径。因此,安装单元是包含原生资源与完整性元数据的完整归档目录,而非单个可执行文件。[辅助程序运行时参考](../../../../packages/ssh/ssh-helper-runtime/README.zh.md)负责构建矩阵、部署基线及归档验证命令。 + ## 考虑过的替代方案 **在 SSH exec stdout/stdin 上为所有流分帧。** 这避免了 Unix 套接字转发,但要求应用协议自行实现逐流额度、队列上限及独立 EOF 语义。独立 SSH 通道使用传输层既有流控,并将程序输出与管理帧分开。 @@ -48,7 +56,7 @@ SSH 提供经过认证的字节通道及逐通道流量控制,但普通 exec ## 验证 -必要的协议及生命周期证据覆盖畸形消息、上限、预留取消、经过认证的流发布及断连错误。原生 SSH 验收必须覆盖远端文件保护与符号链接身份、Bash 限制、fd 7 二进制流、输出暂停时的控制进展、终端操作、LSP 及 Node 执行。实时检查要求显式配置的可丢弃远端工作区;无密钥测试不创建远端环境。 +必要的协议及生命周期证据覆盖畸形消息、上限、预留取消、经过认证的流发布及断连错误。原生 SSH 验收必须覆盖远端文件保护与符号链接身份、Bash 限制、fd 7 二进制流、输出暂停时的控制进展、终端操作、LSP 及 Node 执行。外部主机检查要求显式配置的可丢弃远端工作区。打包产物的 Linux 验收会创建未安装 Node 的可丢弃 OpenSSH 容器;原生主机检查负责限制执行的证据。 安全证据要求同时尝试同用户连接与替换套接字监听端点,并确认其无法占用预留流、获知流密钥、修改另一执行或收到其明文输出。进程生命周期证据区分直接退出与托管进程范围静止,并测试启动发布前及程序启动后的取消。源码与构建后配置组合检查验证已安装辅助程序/引导安排,不向程序环境传递主机凭据。 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-14-deepseek-account-login.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.i18n.yaml index 4bef95dc24..b348c71538 100644 --- a/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.i18n.yaml @@ -15,8 +15,8 @@ en: 3c2dd2c948ffb51b zh: d019197df0ee3dcf /agent-note-deepseek-account-browser-login/consequences: - en: a6eff4a0350e9018 - zh: 2e3200ca089023ab + en: 3c5681b492cd34cf + zh: d7707fed9241f9bc /agent-note-deepseek-account-browser-login/verification: en: 881edcb454b941a6 zh: 7dc5a9b7a066f623 diff --git a/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md b/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md index 70ed73f265..2e08d36606 100644 --- a/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md +++ b/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md @@ -46,7 +46,7 @@ Profile and recharge-wallet queries use independent getProfile and getBalance op Deployment authentication uses explicit Host-only requestHeaders on the configured Platform origin. The provider rejects redirects and reserved-header overrides so deployment cookies cannot replace account authorization or follow a browser destination. Environment-specific authentication protocols remain outside the account provider. -The bundled account UI is Desktop-only: its preload bridge enables the account launcher, settings and sign-in onboarding. Plain Web retains API-key onboarding and the standard Settings launcher without account subscription or login. The Host protocol accepts login_source (desktop or web) in auth_init; the bundled UI sends desktop. The backend accepts localhost callbacks. DSH preserves the browser-supplied localhost hostname and port without DNS resolution or conversion to an IP literal. +The bundled account UI mounts the account launcher, settings and sign-in onboarding in both Desktop and plain Web. The Host sends login_source (desktop or web) in auth_init so Platform can choose the completion experience; the UI sends desktop when the Desktop preload bridge is present and web otherwise. Web failures close the authorization tab while the original tab receives Host state; no Web UI return URL is used. The backend accepts localhost callbacks. DSH preserves the browser-supplied localhost hostname and port without DNS resolution or conversion to an IP literal. The macOS development launcher registers an isolated, ad-hoc-signed application bundle for `dsh://open`. The bundle retains the workspace entry and development paths for Launch Services cold starts without copying credentials or changing the package-manager-owned Electron application. Protocol registration targets the latest launched development or packaged application. diff --git a/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md b/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md index 5b0df92064..235fcba920 100644 --- a/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md @@ -46,7 +46,7 @@ DSH 授权通过 x-dsh-auth-token 请求头鉴权 Platform、推理和 Files 请 开发环境认证通过配置的平台来源上的显式 Host 请求头 requestHeaders 完成。提供者拒绝重定向和保留请求头覆盖,防止开发环境 Cookie 替换账号授权或跟随浏览器跳转地址。特定环境的认证协议不属于账号提供者。 -内置账号界面仅用于 Desktop:preload 桥接启用账号入口、设置和登录引导。普通 Web 保留 API Key 引导及标准设置入口,不订阅账号状态或显示登录。Host 协议在 auth_init 中接受 login_source(desktop 或 web);内置界面发送 desktop。后端接受 localhost 回调。DSH 保留浏览器提供的 localhost 主机名和端口,不做 DNS 解析或 IP 字面量转换。 +内置账号界面在 Desktop 和普通 Web 中都挂载账号入口、设置和登录引导。Host 在 auth_init 中发送 login_source(desktop 或 web),以便 Platform 选择完成页体验;存在 Desktop preload 桥接时界面发送 desktop,否则发送 web。Web 登录失败时关闭授权标签页,原标签页通过 Host 状态获知结果;不使用 Web UI 返回 URL。后端接受 localhost 回调。DSH 保留浏览器提供的 localhost 主机名和端口,不做 DNS 解析或 IP 字面量转换。 macOS 开发启动器为 `dsh://open` 注册独立、经临时签名的应用包。该应用包保留工作区入口和开发路径,使 Launch Services 能够冷启动;凭证不会被复制,也不修改包管理器安装的 Electron 应用。协议注册指向最近启动的开发版或打包版应用。 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-19-concrete-web-bind-address.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-19-concrete-web-bind-address.i18n.yaml new file mode 100644 index 0000000000..f729428b68 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-19-concrete-web-bind-address.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-09-19-concrete-web-bind-address.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-19-concrete-web-bind-address.md +/agent-note-bind-one-concrete-web-address: + en: f70f2b6b24ef16dd + zh: 64100dbc55eee33d +/agent-note-bind-one-concrete-web-address/problem: + en: ffc265e61eadc31b + zh: fcc70f0a8817914c +/agent-note-bind-one-concrete-web-address/decision: + en: 5fe4f2ddba2ee2da + zh: bb140a16f056d4b4 +/agent-note-bind-one-concrete-web-address/alternatives-considered: + en: 0e4d475347796821 + zh: e621e606bc5b1045 +/agent-note-bind-one-concrete-web-address/consequences: + en: ba7a839bca09992d + zh: a11171005405d1e2 +/agent-note-bind-one-concrete-web-address/testing: + en: 4bb8f4bf4ad943c3 + zh: 2e24d56d01b52574 diff --git a/.agents/notes/implemented/architecture/2026-09-19-concrete-web-bind-address.md b/.agents/notes/implemented/architecture/2026-09-19-concrete-web-bind-address.md new file mode 100644 index 0000000000..3f6be5132e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-19-concrete-web-bind-address.md @@ -0,0 +1,35 @@ +# Agent Note: Bind one concrete Web address + +Status: implemented + +English | [中文](2026-09-19-concrete-web-bind-address.zh.md) + +## Problem + +The Web listener accepted `127.0.0.1` or `0.0.0.0`. A wildcard bind exposed every interface of the machine, so the bundle sampled the LAN IPv4 addresses at bind time into a `webRuntime` service and appended them to `trustedHosts`, granting authorities for interfaces the operator never named and mixing inferred reachability into configured trust. A container or workstation that should expose exactly one address had no way to say so, IPv6 addresses were not accepted at all, and a browser dialing the exposed address sent it as `Host` only to be refused unless the sampled list happened to contain it. + +## Decision + +`webserver.config.host` accepts one concrete IPv4 or IPv6 address literal, loopback by default; the unspecified address in every spelling (`0.0.0.0`, `::`, `::ffff:0.0.0.0`, and their expansions) is rejected when the config loads, and the shipped `dsh web` command refuses the same spellings for `--host` before any consumer activates. An IPv6 `%zone` is kept for `listen`; classification through the exported `isWildcardHost` and `isLoopbackHost` reads the address alone. + +The browser Host/Origin fence accepts the listener's own bind IP literal as `Host` on any port, independently of `trustedHosts` and ignoring the zone. A browser dialing that literal presents it as `Host`, the literal is no rebinding target, and the Origin and cross-site checks still apply. DNS names resolving to the address, other interfaces, and proxy authorities still require `--trusted-host`. Connection reads the invocation authorities directly from the `webStartup` provider; the `webRuntime` service and LAN sampling no longer exist. + +The advertised URL uses IPv4 for mapped loopback binds, brackets other IPv6 binds, drops a loopback zone, and requires `--public-url` for a zoned non-loopback bind because a zone cannot appear in a URL. A non-loopback bind serves plain HTTP and warns at startup even when an HTTPS `--public-url` fronts it. `web-runtime` is a required startup entry, so a bind failure fails startup instead of leaving a silent listener-less process. Desktop pins `--host 127.0.0.1`, the address Electron dials. + +## Alternatives considered + +**Keep sampling LAN addresses into `trustedHosts`.** Rejected: the listener already owns the concrete bind address. Sampling grants authorities for other interfaces and mixes inferred reachability with configured trust; direct bind-IP acceptance preserves that distinction without another runtime service. + +**Accept the bind IP only on the bound port.** Rejected: a port-less `trustedHosts` entry already matches any port, a proxy on the same address may listen elsewhere, and the port adds nothing to the rebinding defense the Host check provides. + +**Keep `0.0.0.0` with a warning.** Rejected: binding every interface exposes remote code execution to every network the machine joins, and the operator can name each address that should be exposed. + +## Consequences + +An operator exposes exactly the interfaces named by `--host` and reaches the listener through that literal without further configuration; every other remote authority is a `--trusted-host` decision. Compositions that bound `0.0.0.0` fail at load with a message naming the rejected spelling. IPv6-only hosts are supported end to end, including the printed and opened URL. + +The [native HTTPS listener decision](2026-09-23-native-https-web-listener.md) supersedes this note's HTTP-only transport assumption. The non-loopback warning applies only without TLS; bind-address validation and authority admission remain unchanged. + +## Testing + +`packages/host/webserver/tests/webserver.spec.ts` classifies wildcard and loopback spellings and rejects wildcard config; `packages/bundle/web-app/tests/startup.spec.ts` refuses wildcard `--host` before consumers activate; `packages/client/connection/tests/api-request-trust.host.spec.ts` and `node-half.host.spec.ts` admit the bind literal on any port without admitting other authorities; `packages/bundle/web-app/tests/web-app.spec.ts` covers the bracketed IPv6 URL and the plain-HTTP warning; `apps/cli/tests/profiles/web/tests/public-url.expected.e2e.ts` boots the built profile on a non-loopback and a zoned loopback address; `web-failure-matrix.expected.e2e.ts` and `packages/boot/app-boot/tests/app-boot.spec.ts` report the required `web-runtime` entry. diff --git a/.agents/notes/implemented/architecture/2026-09-19-concrete-web-bind-address.zh.md b/.agents/notes/implemented/architecture/2026-09-19-concrete-web-bind-address.zh.md new file mode 100644 index 0000000000..4df6b8384f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-19-concrete-web-bind-address.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 绑定一个具体的 Web 地址 + +Status: implemented + +[English](2026-09-19-concrete-web-bind-address.md) | 中文 + +## 问题 + +Web 监听器只接受 `127.0.0.1` 或 `0.0.0.0`。通配绑定会暴露机器的每个接口,因此 bundle 在绑定时把 LAN IPv4 地址采样进 `webRuntime` 服务并追加到 `trustedHosts`,为操作者从未点名的接口授予 authority,并把推断的可达性混入配置的信任。应当只暴露一个地址的容器或工作站无法表达这一点,IPv6 地址完全不被接受,浏览器拨号已暴露地址时把它作为 `Host` 发送,却只在采样列表恰好包含它时才被接受。 + +## 决策 + +`webserver.config.host` 接受一个具体的 IPv4 或 IPv6 地址字面量,默认回环;未指定地址的所有拼写(`0.0.0.0`、`::`、`::ffff:0.0.0.0` 及其展开形式)在配置加载时被拒绝,随附的 `dsh web` 命令在任何消费者激活前对 `--host` 拒绝同样的拼写。IPv6 的 `%zone` 保留给 `listen`;通过导出的 `isWildcardHost` 与 `isLoopbackHost` 分类时只读取地址本身。 + +浏览器 Host/Origin 栅栏接受监听器自身的绑定 IP 字面量作为任意端口上的 `Host`,独立于 `trustedHosts` 并忽略 zone。拨号该字面量的浏览器把它作为 `Host` 呈现,该字面量不是重绑目标,Origin 与跨站检查仍然生效。解析到该地址的 DNS 名称、其他接口与代理 authority 仍需 `--trusted-host`。Connection 直接从 `webStartup` 提供方读取调用 authority;`webRuntime` 服务与 LAN 采样不再存在。 + +公告 URL 对 mapped 回环绑定使用 IPv4,为其他 IPv6 绑定加方括号、剥离回环 zone,并因 zone 不能出现在 URL 中而要求带 zone 的非回环绑定显式提供 `--public-url`。非回环绑定提供明文 HTTP,即使前置 HTTPS 的 `--public-url` 也会在启动时警告。`web-runtime` 是必需的启动条目,因此绑定失败会使启动失败,而不是留下一个没有监听器的静默进程。Desktop 固定 `--host 127.0.0.1`,即 Electron 拨号的地址。 + +## 备选方案 + +**继续把采样的 LAN 地址加入 `trustedHosts`。** 否决:监听器已经持有具体绑定地址。采样会授权其他接口的 authority,并把推断的可达性混入配置的信任;直接接受绑定 IP 可以保留两者的区分,无需另设运行时服务。 + +**只在绑定端口上接受绑定 IP。** 否决:不带端口的 `trustedHosts` 条目本就匹配任意端口,同一地址上的代理可能监听其他端口,端口对 Host 检查提供的重绑防御没有增益。 + +**保留 `0.0.0.0` 并给出警告。** 否决:绑定所有接口会向机器加入的每个网络暴露远程代码执行,而操作者可以逐个点名应暴露的地址。 + +## 影响 + +操作者只暴露 `--host` 点名的接口,并无需额外配置即可通过该字面量访问监听器;其他每个远程 authority 都是一个 `--trusted-host` 决定。曾绑定 `0.0.0.0` 的组合在加载时失败,并给出点名被拒绝拼写的消息。纯 IPv6 主机得到端到端支持,包括打印与打开的 URL。 + +[原生 HTTPS 监听器决策](2026-09-23-native-https-web-listener.zh.md)取代本说明仅支持 HTTP 传输的前提。非回环警告只适用于未启用 TLS 的监听器;绑定地址校验与 authority 接纳保持不变。 + +## 测试 + +`packages/host/webserver/tests/webserver.spec.ts` 分类通配与回环拼写并拒绝通配配置;`packages/bundle/web-app/tests/startup.spec.ts` 在消费者激活前拒绝通配 `--host`;`packages/client/connection/tests/api-request-trust.host.spec.ts` 与 `node-half.host.spec.ts` 在任意端口上接纳绑定字面量而不接纳其他 authority;`packages/bundle/web-app/tests/web-app.spec.ts` 覆盖带方括号的 IPv6 URL 与明文 HTTP 警告;`apps/cli/tests/profiles/web/tests/public-url.expected.e2e.ts` 在非回环地址与带 zone 的回环地址上启动已构建的 profile;`web-failure-matrix.expected.e2e.ts` 与 `packages/boot/app-boot/tests/app-boot.spec.ts` 报告必需的 `web-runtime` 条目。 diff --git a/.agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.i18n.yaml index 599afcc6f0..0fb431067d 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.i18n.yaml @@ -15,5 +15,5 @@ en: 4089464ad1fb60bd zh: 3168e9e4a205145d /agent-note-keep-live-configuration-in-the-owning-profile/consequences: - en: 6033aaa12b2a521b - zh: 43934413c97670de + en: 41bb170694c785d6 + zh: 17419fdd6d937dce diff --git a/.agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.md b/.agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.md index 7acf109869..65cc8f60b1 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.md +++ b/.agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.md @@ -24,6 +24,6 @@ The rejected alternative is retaining settings as a second store behind a config ## Consequences -This supersedes only the non-secret settings tier in [configuration source ownership](2026-08-04-configuration-source-ownership.md); its environment restrictions and credential ordering remain applicable. [Volatile references](2026-09-18-volatile-config-references.md) own reference lifetime and ordinary update behavior. +This supersedes only the non-secret settings tier in [configuration source ownership](2026-08-04-configuration-source-ownership.md); its environment restrictions remain applicable, and [stored credential precedence](2026-10-09-stored-credential-precedence.md) supersedes its credential ordering. [Volatile references](2026-09-18-volatile-config-references.md) own reference lifetime and ordinary update behavior. Real profile tests cover multiple instances, persisted restart, invalid edits, stale revisions, higher-layer rejection, secret redaction, and configuration expressions. Browser tests exercise form writes and reset through the assembled application. Runtime reference identity is checked across live edits. diff --git a/.agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.zh.md b/.agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.zh.md index c9b88462a5..9ce0952aab 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.zh.md @@ -24,6 +24,6 @@ Cordis config patch 替换完整 entry config。编辑会保留普通字段、 ## 后果 -本决定只替代 [配置来源所有权](2026-08-04-configuration-source-ownership.zh.md) 中的非秘密 settings 层;其中的环境限制和凭据优先级仍适用。[Volatile 引用](2026-09-18-volatile-config-references.zh.md) 负责引用生命周期和普通更新行为。 +本决定只替代 [配置来源所有权](2026-08-04-configuration-source-ownership.zh.md) 中的非秘密 settings 层;其中的环境限制仍适用,其凭据优先级已由[存储凭据优先级](2026-10-09-stored-credential-precedence.zh.md)替代。[Volatile 引用](2026-09-18-volatile-config-references.zh.md) 负责引用生命周期和普通更新行为。 真实 profile 测试覆盖多实例、持久化重启、非法编辑、过期修订、高优先级层拒绝、秘密脱敏及配置表达式。浏览器测试通过完整应用执行表单写入和重置,并检查实时编辑前后的运行时引用身份。 diff --git a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml index 604c1fe195..41376c7c73 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml @@ -30,8 +30,8 @@ en: 743f2dceda3072aa zh: f4d53ddc13a4127e /agent-note-projection-cache-read-only-face-matches-the-lifecycle-identity-the-client-store-separates-cached-and-sequenced-rows/decision/the-client-store-separates-cached-and-sequenced-rows: - en: 8a4e9e9ac2ada06f - zh: b5884535cd934f72 + en: dd1cc7ac96a5a25d + zh: bdea08d20f166e65 /agent-note-projection-cache-read-only-face-matches-the-lifecycle-identity-the-client-store-separates-cached-and-sequenced-rows/decision/what-stays-untouched: en: 1cefba02bbfb2647 zh: 5a96942565ab9d72 diff --git a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md index 5ef27cb076..f0235d8040 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md +++ b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md @@ -97,7 +97,7 @@ Writer classification: | the `projections` block of an `api-session/added` summary (`manager.handleSessionAdded`) | by the block's `kind`; the summary comes from a live session, so in practice `sequenced` | | the history first page's `projections` (`projections.seed` in `session.ts`) | sequenced | | the control baseline, live sessions only (`manager.replaceControlBaseline`) | sequenced | -| the `session.projections` result of `refreshProjections` (a body observation) | sequenced | +| the `session.projections` result of `refreshProjections` | sequenced for an exact read; cached only when [migration is required](2026-09-29-explicit-session-history-preparation.md) | | push frames (the `projection` frame handled by `manager`) | sequenced | | the `title` after a successful rename (`session.ts`) | sequenced | diff --git a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md index e69db37e7e..326e6f028b 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md @@ -97,7 +97,7 @@ seq 比较只在同一条 Host 连接内发生:`handleConnected` 先整表 `cl | `api-session/added` 摘要的 `projections` block(`manager.handleSessionAdded`) | 按 block 的 `kind`;该摘要来自活会话,实际为 `sequenced` | | history 首页 `projections`(`session.ts` 的 `projections.seed`) | sequenced | | control 基线,仅活会话(`manager.replaceControlBaseline`) | sequenced | -| `refreshProjections` 的 `session.projections` 结果(正文观察) | sequenced | +| `refreshProjections` 的 `session.projections` 结果 | 准确读取为 sequenced;仅[需要迁移](2026-09-29-explicit-session-history-preparation.zh.md)时为 cached | | 推送 frame(`manager` 处理 `projection` frame) | sequenced | | rename 成功后的 `title`(`session.ts`) | sequenced | diff --git a/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.i18n.yaml index 3bd20ef0bc..5de15975be 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.i18n.yaml @@ -9,14 +9,14 @@ en: 70a969dce3283824 zh: 18c61bf840a6518a /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/problem/current-state: - en: 8fb06638898de59e - zh: 79ed0cfe79e40be1 -/agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/problem/three-unrelated-uplink-mechanisms: - en: 386be7b691ab63e7 - zh: 935e0db22ae1cf5d -/agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/problem/concrete-costs: - en: f374976b43645d15 - zh: 26b2c7aaafa41fba + en: 2de84c3fc0a3552e + zh: da9cd565588bf2dd +/agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/problem/uplink-consumers: + en: 403103ef08958529 + zh: 2813d9d38c2c55b7 +/agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/problem/consumer-responsibilities: + en: 28f8a3112d6ec5fe + zh: c70d68233e3f6b7f /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/problem/relation-to-background-jobs: en: 5e67475010d52ddb zh: ce23aad2d4aa0d67 @@ -30,8 +30,8 @@ en: 943208904785f7eb zh: bda1969132a16101 /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/decision/terms: - en: 401703adbd9cc1c2 - zh: 56d960c0b6fdff57 + en: a22cd84756773075 + zh: 49efa0c5a37d4b57 /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/decision/type-signatures: en: 5f9cd00890b6f4c3 zh: 600ecba7e60b63f6 @@ -42,8 +42,8 @@ en: a7180d3c194cf9d9 zh: 0dd7833e0e5d0a71 /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/decision/peerscope: - en: 202aa6e8e8b04bd6 - zh: b1fc897c09074a7c + en: a162af337571f56e + zh: 0ae0b9d62d2cb16e /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/decision/client-face: en: 9f10347a73402b8b zh: b939c7a254a8e579 @@ -75,8 +75,8 @@ en: 46a0c0b3ce1e5671 zh: 7743707de42b1d1d /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/decision/in-process-and-worker-carriers: - en: ec339e57dc2c0603 - zh: 3570be8c094ea24c + en: df4ae60d8403cdbb + zh: 70c6024a2a9a1e84 /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/decision/relation-to-events: en: a011793e5a4400ed zh: df8b20115f0348b8 @@ -102,8 +102,8 @@ en: 26dcd8bebdc8d974 zh: e74bcef7c549e70c /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/placement: - en: 41128746334320c7 - zh: 558a676340aae3a2 + en: ecfaff2b9b2ef021 + zh: 85b392d79364e0c3 /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/key-sequences: en: 130e4f9ec7296a10 zh: 2a5aa1302a8db61a @@ -126,17 +126,17 @@ en: b42ab0932f8b31b4 zh: 7fed8cb5b6e36788 /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/alternatives-considered: - en: 04e72789417d6e3a - zh: b57c5cc68dff45a5 + en: b0046c9f7c12a876 + zh: f3c37b466746b0fd /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/consequences: - en: 07524e0c2dc22ad5 - zh: 5bf4f27160d78b43 + en: dbc54ce699ef8e71 + zh: 83144f07ae8f8759 /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/testing: - en: 5c8188930b9d4fdb - zh: 1d94e6563cedde13 + en: 06fbeed7b82ded32 + zh: 66accb4bd2bf64a2 /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/deferred: - en: 3b99a327464edc3e - zh: dcffdc75369925dc + en: 8368c592f30af97f + zh: 2ff89acb7b3ed477 /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/related: - en: 85d77fb246564024 - zh: 8b400818a91a3e3a + en: 475d212ae1f9c1c9 + zh: 21fe6c6cdb900a6b diff --git a/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.md b/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.md index c1333ef62f..5555c46b04 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.md +++ b/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.md @@ -8,41 +8,41 @@ English | [中文](2026-09-19-remote-duplex-stream.zh.md) ### Current state -`dsh-api-gateway` multiplexes every Typert Remote stream over one WebSocket at the fixed path `/api/remote.mux` (`packages/api/gateway/src/stream-protocol.ts`). A Host method decorated with `@Remote({ mode: 'stream' })` that returns an `Iterable` or `AsyncIterable` becomes one Host-to-Client logical stream; the optional final `signal: AbortSignal` is the only reserved parameter, never enters the wire arguments, and is appended by the Gateway after the decoded business parameters (`packages/api/gateway/src/index.ts`). The generated method the Client receives returns a bare `AsyncIterable`. +`dsh-api-gateway` multiplexes Typert Remote streams over one WebSocket at `/api/remote.mux`. A Host method declares both directions with `@Remote({ mode: 'stream' })` and `RemoteStream`; the generated Client method returns `RemoteStreamHandle`. Existing `Iterable` and `AsyncIterable` return types declare downlink-only methods. The optional final `signal: AbortSignal` is supplied by the Gateway and does not enter the wire arguments. -There are only five wire frames: +Both directions share one `streamId`: | Direction | Frame | Definition | | --- | --- | --- | | Client to Host | `{ type: 'open', streamId, endpoint, payload }` | `stream-protocol.ts` | +| Client to Host | `{ type: 'item', streamId, value? }` | `stream-protocol.ts` | +| Client to Host | `{ type: 'end', streamId }` | `stream-protocol.ts` | | Client to Host | `{ type: 'cancel', streamId }` | `stream-protocol.ts` | | Host to Client | `{ type: 'item', streamId, value? }` | `stream-protocol.ts` | | Host to Client | `{ type: 'error', streamId, error: { code, message, details } }` | `stream-protocol.ts` | | Host to Client | `{ type: 'end', streamId }` | `stream-protocol.ts` | -The Client can send only open and cancel. The parser `parseRemoteStreamClientMessage` (`stream-protocol.ts`) throws on any other frame, and a Host connection that receives one closes the whole socket with 1008 (`stream-server.ts`). In short, the Gateway today supports only "a backend iterable sent to the frontend". Every feature that needs the frontend to send data to the backend continuously takes its own detour. +The Client handle's `send()` supplies uplink items, `end()` half-closes the uplink, and `dispose()` cancels the logical stream. The Host reads decoded items through `this.ctx.invocation.uplink()`; the invocation also carries the admitted Peer and cancellation signal. -A Host method also has no notion of who initiated this call: `InvokeRemoteRequest = { namespace, method, args, signal }` (`packages/api/gateway/src/types.ts`) has no caller slot, `RemoteStreamOpener` has the signature `(endpoint, payload, signal)` (`stream-server.ts`), and the WebSocket checks the cookie once, at the handshake. +The transport owns validation, cancellation, and its bounded inbox. Consumer protocols own input authority, acknowledgements, and recovery after disconnection. -### Three unrelated uplink mechanisms +### Uplink consumers | Feature | Uplink path | Location | Cost | | --- | --- | --- | --- | -| Web terminal keystrokes | One unary RPC `terminal.write(agent, id, attachmentId, data)` per xterm `onData`; the Client serializes them through a promise chain and caps its own byte budget | `packages/api/terminal-controller/src/client/model.ts`; Host `src/index.ts` | One HTTP round trip and one authentication per keystroke; two carriers correlated by hand through `attachmentId`; `inputFull` when the budget is exhausted | +| Web terminal input and resize | `terminal.attach` carries `TerminalInput` uplink items and `TerminalFrame` downlink items; the Client pipelines commands and releases its raw-input byte budget on `ack` | `packages/api/terminal-controller/src/client/model.ts`; Host `src/terminal.ts` | The current attachment owns input; `inputFull` when the Client budget is exhausted; input is never replayed after reconnection | | File upload | A `Blob` or `ReadableStream` goes to the native `POST /api/session/uploadFileBinary` outside the Remote layer, with `duplex: 'half'` | `packages/client/file-upload/src/client/runtime.ts`; route `src/index.ts` | Bypasses Typert descriptors; no type projection | | Answers to approvals and questions | The Host sends waterfall frames down the `$events` stream, the Client answers through a separate unary RPC `$events/result`, correlated by `clientId` plus `eventId` | `packages/api/gateway/src/client/remote-events.ts`; Host `index.ts` | A second correlation key; `index.ts` records the race this creates | -These three mechanisms solve the same problem: the Client wants to write into a logical stream that is already open. +These consumers need Client-to-Host data while a related operation remains active. Web terminals use the duplex stream; file upload and event answers retain their own transports. -### Concrete costs +### Consumer responsibilities -- **Aligning two carriers.** The terminal uses `attachmentId` to correlate the `follow` stream with the `write` RPC and to decide who owns input. Approvals use `clientId` to correlate the `$events` stream with the `$events/result` RPC. -- **No ordering guarantee.** A unary RPC travels over HTTP and is unordered relative to the WebSocket downlink; the terminal can preserve order only by serializing writes on the Client. -- **Separate authentication and lookup per uplink.** Every `write(agent, id, attachmentId, data)` resolves `agent`, looks up the terminal, and validates the attachment. -- **No EOF.** The Client cannot express "I am done writing"; a half-close needs yet another RPC. -- **Cancellation does not cover both halves.** Cancelling the downlink stream does not cancel queued uplink writes, and vice versa. -- **Backpressure implemented three times.** The downlink pulls the iterator at the pace of the socket write callback (`stream-server.ts`); the terminal uses a bounded follower that makes a slow consumer fail explicitly (`terminal-controller/src/stream.ts`); the uplink relies on the Client capping `maxInputBytes` itself. -- **The documentation is already stale.** `docs/api-gateway.md:160` still says Remote handles one request and one result, a sentence that lags the stream mode the README records. +- **Input authority.** A terminal retains its controlling attachment as a Host-local follower. Snapshot and state frames report each attachment's `writable` state; older attachments keep receiving output after control transfers. +- **Ordering and acknowledgement.** Terminal writes and resizes share a consecutive command sequence and the terminal's operation queue. An `ack` reports provider acceptance or a control refusal; it never authorizes replay after disconnection. +- **Independent lifetimes.** Cancelling `attach` stops its input and output delivery, drops unstarted commands, and joins an in-flight input operation. The PTY lifetime is owned separately by retention and explicit close. +- **Coordinated byte limits.** The Gateway exposes its complete-frame inbox capacity and this stream's JSON envelope cost through `invocation.uplinkWindow`. The terminal publishes that window in its snapshot and uses provider acknowledgements to release in-flight capacity. Writes and resizes wait in a bounded Client queue when the window is full. `maxInputBytes` limits raw UTF-8 input; `maxBufferedBytes` separately limits the complete encoded input retained by the Client and output retained by each follower. +- **Remaining separate carriers.** Approval answers still correlate `$events` with the `$events/result` RPC through `clientId` and `eventId`. Moving this protocol onto the duplex stream remains deferred. ### Relation to background jobs @@ -66,7 +66,7 @@ Every Remote stream accepts a Client uplink. The method's return type `RemoteStr Client Host ───────────────────────────────── ─────────────────────────────────────────── const s = remote.job.attach(req, signal) - │ open { streamId, endpoint, payload } ───────▶ opener(endpoint, payload, uplink, peer, control) + │ open { streamId, endpoint, payload } ───────▶ opener(endpoint, payload, uplink, peer, control, window) │ │ prepareInvocation │ s.send(v1) → item { streamId, v1 } ───────▶ inbox.push(v1) │ invocation = { request, service, peer, signal, uplink() } │ s.send(v2) → item { streamId, v2 } ───────▶ inbox.push(v2) │ receiverContext.extend({ invocation }).get(service) @@ -88,7 +88,7 @@ Every Remote stream accepts a Client uplink. The method's return type `RemoteStr | Half-close | One direction has ended while the other remains open | | Item | One business value in one direction; every item is validated by the codec independently | | inbox | The bounded uplink queue the Host keeps per logical stream | -| Peer | The party the connection layer admitted, one `PeerScope`; this Host has exactly one Peer, the operator | +| Peer | The party one connection speaks for, one `PeerScope` carrying its principal; every browser connection shares `connection.browserPeer`, and in-process code creates its own through `connection.createPeer()` ([Peer principals](../../implemented/architecture/2026-10-12-peer-principal-and-remote-access.md)) | | Invocation context | `RemoteInvocation`: the request, receiving service, Peer, cancellation signal, and uplink entry of this call | ### Type signatures @@ -135,10 +135,11 @@ export interface RemoteInvocation { } /** Cordis service key of the receiving service. */ readonly service: string - /** The Peer that initiated the call. In-process carriers and unadmitted calls are the operator. */ + /** The Peer that initiated the call; every carrier names it explicitly. */ readonly peer: PeerScope /** Carrier cancellation: Client cancel, socket closure, uplink failure. */ readonly signal: AbortSignal + readonly uplinkWindow?: RemoteUplinkWindow | undefined /** * The uplink items of this call. Can be taken once; the second call throws. With an uplink codec * in the descriptor each item is decoded to In; without one, items are delivered as unknown with @@ -179,24 +180,28 @@ The mechanism relies on two existing Cordis behaviors: /** The opaque identity of one Peer. */ export type PeerId = Branded<'PeerId'> -/** One Peer's session on this Host: opened and released by the admitting side; ctx owns connection-lifetime registrations. */ +/** One Peer's session on this Host: opened and released by its creator; ctx owns connection-lifetime registrations. */ export interface PeerScope { readonly id: PeerId readonly ctx: Context + /** Caller identity fixed at creation. */ + readonly principal: Principal + /** Aborted once the Peer is disposed. */ + readonly signal: AbortSignal dispose(): Promise } ``` -This Host has exactly one Peer: the operator. `@deepseek-ai/dsh-client-connection` creates it with `createScope(connectionCtx, peer)` when the service applies, the same mechanism an Agent uses to create its own scope: the Peer object is the ScopeKey, `peer.ctx` carries connection-lifetime effects, and `dispose()` runs with the Connection's release and quiets the fiber. It is exposed as `connection.operator`. +`@deepseek-ai/dsh-client-connection` implements the one Peer class, `Peer(owner, { principal })`, with `createScope(owner, peer)`, the same mechanism an Agent uses to create its own scope: the Peer object is the ScopeKey, `peer.ctx` carries connection-lifetime effects, `peer.signal` aborts when the scope ends, and `dispose()` quiets the fiber. Connection creates `connection.browserPeer` with the owner principal when the service applies; [Peer principals and method-level Remote access control](../../implemented/architecture/2026-10-12-peer-principal-and-remote-access.md) owns principals, `createPeer()`, and access checks. | Member | Semantics | | --- | --- | -| `connection.operator: PeerScope` | The only Peer; lives and dies with the Connection | -| `connection.admit(request): PeerAdmission` | Runs the existing `requestRejection`: returns `{ rejection: 401 \| 403 }` when refused, otherwise `{ peer: operator }`. Future admitters plug in here | +| `connection.browserPeer: PeerScope` | The Peer every authenticated browser connection shares; owner principal; lives and dies with the Connection | +| `connection.admit(request): PeerAdmission` | Runs the existing `requestRejection`: returns `{ rejection: 401 \| 403 }` when refused, otherwise `{ peer: browserPeer }`. Future admitters plug in here | -The Gateway's `handleUpgrade(req, socket, head, peer)` binds an opener with a fixed Peer to that socket and registers socket closure in `peer.ctx.effect`; when the scope is already inactive, it closes the socket directly with 1001 instead. When `InvokeRemoteRequest.peer?` or the `peer` parameter of `RemoteStreamOpener` is absent, the answer is the operator, so existing in-process callers change nothing; in a composition without a Connection, the operator stand-in the Gateway builds for itself is likewise created through `createScope`, with the same `dispose()` contract. Looking up a Peer by id, associating a carrier with a second Peer, and Peer open and close events all wait until the first consumer that needs multiple Peers appears. +The Gateway's `handleUpgrade(req, socket, head, peer)` binds an opener with a fixed Peer to that socket and registers socket closure in `peer.ctx.effect`; when the scope is already inactive, it closes the socket directly with 1001 instead. `InvokeRemoteRequest.peer` and the `peer` parameter of `RemoteStreamOpener` and `wireStream.open` are required, so every in-process caller names its Peer, and the Gateway creates none. Looking up a Peer by id and Peer open and close events wait until the first consumer that needs them appears. -The Peer carries no access model: who the Peer is and what it may do are attached by business plugins on their own through `peer.ctx`. +The Peer carries its principal; what that principal may call is decided by the roles, bindings, and policies that [Peer principals and method-level Remote access control](../../implemented/architecture/2026-10-12-peer-principal-and-remote-access.md) defines. ### Client face @@ -311,7 +316,7 @@ Credit frames wait until a consumer that needs sustained high-volume uplink appe | Worker tunnel (`packages/experimental/webworker-runtime`) | The page adds `stream-uplink-item` / `stream-uplink-end` frames; `serveStream` assembles them into an `uplink` handed to `seams.openStream`. Same-origin trusted boundary: no inbox limit, and items after `end` are dropped | | `remote-mock` (`packages/test-support/remote-mock`) | `StreamHandle.uplink: AsyncIterable`; `rpc.open` passes it through | -An in-process carrier with no `peer` means the operator. +An in-process carrier passes its Peer explicitly; the in-page Host of the worker tunnel passes `connection.browserPeer`. ### Relation to `$events` @@ -325,7 +330,7 @@ An in-process carrier with no `peer` means the operator. // types.ts export type RemoteStream = AsyncIterable & { readonly [STREAM_UPLINK]?: In } export type PeerId = Branded<'PeerId'> -export interface PeerScope { readonly id: PeerId; readonly ctx: Context; dispose(): Promise } +export interface PeerScope { readonly id: PeerId; readonly ctx: Context; readonly principal: Principal; readonly signal: AbortSignal; dispose(): Promise } export interface RemoteInvocation { … } // see Host face declare module '@deepseek-ai/cordis' { interface Context { readonly invocation: RemoteInvocation | undefined } } @@ -362,13 +367,13 @@ export interface InvokeRemoteRequest { readonly args: Readonly> /** Uplink items; absent is equivalent to an iterator that ends immediately. */ readonly uplink?: AsyncIterable - /** The Peer that initiated the call; absent means the operator. */ - readonly peer?: PeerScope + /** The Peer that initiated the call; required on every path. */ + readonly peer: PeerScope readonly signal?: AbortSignal } export interface TypertGatewayWireStream { - open: (endpoint: string, payload: unknown, uplink: AsyncIterable, peer: PeerScope | undefined, signal: AbortSignal) => Promise> + open: (endpoint: string, payload: unknown, uplink: AsyncIterable, peer: PeerScope, signal: AbortSignal) => Promise> failure: (error: unknown) => RemoteStreamFailure } @@ -379,6 +384,7 @@ export type RemoteStreamOpener = ( uplink: AsyncIterable, peer: PeerScope, control: AbortController, + window: RemoteUplinkWindow, ) => Promise> // index.ts Config addition @@ -394,7 +400,7 @@ const signal = request.signal ?? NEVER_ABORTED_SIGNAL const invocation = new GatewayInvocation( { namespace: request.namespace, method: request.method, args: request.args }, descriptor.service, - request.peer ?? this.operatorPeer(), + request.peer, signal, new UplinkDecoder(request.uplink ?? EMPTY_ASYNC_ITERABLE, descriptor.uplink?.codec, endpoint, control), ) @@ -444,8 +450,8 @@ cancel : missing → ignore; otherwise control.abort(new Error('Remote stream ca | `dsh-typert-protocol` (`types.ts`, `index.ts`) | `RemoteStream`, `RemoteStreamHandle`, `PeerId`, `PeerScope`, `RemoteInvocation`, the `ctx.invocation` declaration merge, `InvocationDescriptor.uplink`; the decorator recognizes only `mode: 'stream'`; `TypertRemoteService` registers the `invocation` accessor when constructed | | `dsh-typert-registry` | Load-time validation that `uplink.codec` is a valid strict codec | | `dsh-typert-generator` (`model.ts`, `analyzer.ts`, `emitter.ts`) | `remoteResultType` recognizes `RemoteStream` and generates the `uplink` boundary; the descriptor emits `uplink: { codec }`; the generated Client signature returns `RemoteStreamHandle`; the parameter loop accepts only business parameters and a final `signal` | -| `dsh-client-connection` (`operator-peer.ts`, `rpc.ts`, `rpc-host.ts`, `index.ts`) | The operator `PeerScope`; `connection.operator` and `admit`; the `/api` and upgrade routes obtain the Peer through `admit`; the optional `uplink` of `rpc.open` | -| `dsh-api-gateway` Host (`stream-protocol.ts`, `stream-server.ts`, `types.ts`, `index.ts`) | `item` / `end` frames; `UplinkInbox`; `Config.streamInboxBytes`; `GatewayInvocation` and `extend({ invocation })`; `UplinkDecoder`; `handleUpgrade(req, socket, head, peer)`; `operatorPeer()` | +| `dsh-client-connection` (`peer.ts`, `rpc.ts`, `rpc-host.ts`, `index.ts`) | The `Peer` class; `connection.browserPeer` and `admit`; the `/api` and upgrade routes obtain the Peer through `admit`; the optional `uplink` of `rpc.open` | +| `dsh-api-gateway` Host (`stream-protocol.ts`, `stream-server.ts`, `types.ts`, `index.ts`) | `item` / `end` frames; `UplinkInbox`; `Config.streamInboxBytes`; `GatewayInvocation` and `extend({ invocation })`; `UplinkDecoder`; `handleUpgrade(req, socket, head, peer)` | | `dsh-api-gateway` Client (`client/index.ts`, `client/stream-client.ts`) | `invokeStream` returns the handle; the uplink pump is driven by the handle's queue | | `dsh-webworker-runtime`, `dsh-remote-mock` | The worker tunnel's two uplink frames and the `serveStream` assembly; `StreamHandle.uplink`; the direct proxy returns the real handle | | Documentation | The READMEs of gateway, the api group, connection, protocol, and generator; `docs/api-gateway`; the type-equiv blocks of `docs/subsystems/typert`; the config and Cordis catalogs | @@ -560,7 +566,7 @@ for await (const reply of stream) replies.push(reply) // ['> a', '> b'] **Putting the Client's `send` on the `AsyncIterable` the generated method returns.** Hanging methods on an `AsyncIterable` is unconventional; the handle type `RemoteStreamHandle` extends it explicitly. -**Copying the Access mechanism.** Access control is business semantics, served by `vouch` and the `remote/invoke` waterfall; this Note only needs "whose stream is this", and `PeerScope` suffices. +**Copying the Access mechanism.** Access control is business semantics, served by `vouch` and the `remote/invoke` waterfall; this Note only needs "whose stream is this", and `PeerScope` suffices. Method-level access control later moved to [Peer principals and method-level Remote access control](../../implemented/architecture/2026-10-12-peer-principal-and-remote-access.md), which supersedes this part. **Keeping unary RPC for the uplink.** One HTTP round trip, one authentication, and one lookup per uplink; two carriers with no ordering relation that only Client-side serialization can order; no EOF; cancellation that does not cover both halves; a hand-made correlation key per feature. @@ -574,10 +580,11 @@ for await (const reply of stream) replies.push(reply) // ['> a', '> b'] - **Bought**: one stream with two directions, so interactive scenarios such as terminal keystrokes, approval answers, and background-job stdin no longer each build their own "one stream plus one unary"; a Host method knows its caller; the uplink and downlink types are declared in one place, the return type; uplink items come from the browser and are validated strictly per item at the Host, while downlink items are Host-produced typed values that pass straight through; the generated output and wire frames of existing `AsyncIterable` methods and unary methods are completely unchanged. - **`this.ctx.invocation` is `undefined` outside a Remote call**, so a method that reads it must handle the optional; a service method invoked only directly in process correctly reads `undefined`. +- **Web terminals use `attach`** for screen output and input commands, with provider acknowledgements and per-attachment writable state; their Client retains the current generation's handle and never replays input. - **The inbox limit applies to every stream**: a method that does not read its uplink fails as a whole when it receives many uplink frames. This is a deliberate explicit failure, recorded in the README. -- **The operator is the only Peer**, and `admit` is the only admission point; the first consumer that needs a second Peer must add opening, association, and events in `dsh-client-connection`. +- **Every browser connection shares `browserPeer`**, and `admit` is the only network admission point; in-process code creates further Peers with `connection.createPeer()`. - **No cross-direction ordering guarantee between uplink and downlink**; a protocol that needs request-response pairing carries its own sequence numbers. -- **Upper-layer protocols do not yet expose `send`**: consumers of `$stream`, snapshot, and journal use only the downlink today; the object they receive is already the handle. +- **Upper-layer supervisors expose only the downlink**: `$stream`, snapshot and journal do not expose `send`; a domain that writes uplink retains its generated physical handle for that generation. - **The worker tunnel behaves differently from the WebSocket carrier**: no inbox limit, and items after `end` are dropped, because page to worker is a same-origin trusted boundary. ## Testing @@ -588,17 +595,15 @@ Retention cases in `gateway-stream.host.spec.ts` and `gateway.client.spec.ts` co - Gateway Host: exact-key validation in frame parsing; `UplinkInbox` buffering during opening, `item` after `end`, overflow, ignored unknown `streamId`, and cleanup on socket closure; `UplinkDecoder` delivery with and without a codec and abort on decode failure; `uplink()` taken only once; the `extend({ invocation })` view and the origin of `peer`; `cancellableStream` closing the uplink before `return()`. - Gateway Client: the handle's `send` (JSON validation, queued before open, throws after termination), idempotent `end`, `dispose` driving the `cancel` frame and ending later reads; the pump's three exits; the pump stopping as soon as a terminal frame arrives. - typert: the analyzer's handling of `RemoteStream`, `RemoteStream`, `never`, and the existing `AsyncIterable`; decorator options; registry load-time validation. -- connection: the three outcomes of `admit`, 401, 403, and the operator; the operator reaching handlers through the bridge and the shared handler; release with the Connection. +- connection: the three outcomes of `admit`, 401, 403, and `browserPeer`; `browserPeer` reaching handlers through the bridge and the shared handler; release with the Connection. - remote-mock and the worker tunnel: uplink pass-through; the direct proxy returning the real handle. - Existing stream and unary method tests pass without changed expectations. ## Deferred - `$stream` / snapshot / journal expose the handle's `send` to upper-layer protocols. -- Web terminal: one `attach` stream replaces `follow` plus `write` plus `resize`, and `attachmentId` retires. - Duplex `$events`: waterfall answers become uplink items on the same `streamId`, and `$events/result` and `clientId` retire. - Credit frames: wait for a consumer that needs sustained high-volume uplink; the inbox limit is the initial credit. -- The `streamInboxBytes` default of 262144 is far more than keyboard and stdin need; if the first consumer is terminal paste, it may be aligned with the `maxInputBytes` of `terminal-controller`. - A Host-initiated half-close frame (the Host stops reading the uplink but keeps writing the downlink): no consumer; not added. - `uplink()` on unary methods: it can read items that arrive while the method runs, semantically valid but of doubtful use; allowed, noted in the README. @@ -606,4 +611,4 @@ Retention cases in `gateway-stream.host.spec.ts` and `gateway.client.spec.ts` co - [Remote event delivery](../../../../packages/api/remotes/README.md): the unary `$events/result` answer path; the duplex `$events` item under Deferred partially supersedes it once it lands. - [Session history and event transport](2026-08-18-session-history-and-event-transport.md): the `$stream()` supervisor and the journal / snapshot protocols above it, which this note leaves unchanged. -- [Web sidebar terminal](../feature/2026-09-09-web-sidebar-terminal.md): the unary terminal `write` and `attachmentId`; the `attach` stream under Deferred replaces it once it lands. +- [Web sidebar terminal](../feature/2026-09-09-web-sidebar-terminal.md): the `attach` stream carries input commands, provider acknowledgements and per-attachment writable state; reconnect never replays input. diff --git a/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.zh.md b/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.zh.md index 791b5e3c81..4e5681b04d 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.zh.md @@ -8,41 +8,41 @@ Status: implemented ### 现状 -`dsh-api-gateway` 在一条 WebSocket 上复用全部 Typert Remote 流,路径固定为 `/api/remote.mux`(`packages/api/gateway/src/stream-protocol.ts`)。一个 Host 方法用 `@Remote({ mode: 'stream' })` 修饰并返回 `Iterable` 或 `AsyncIterable`,就成为一条 Host 到 Client 的逻辑流;可选的末位 `signal: AbortSignal` 是唯一的保留参数,不进线路参数,由网关在解码后的业务参数之后追加(`packages/api/gateway/src/index.ts`)。客户端拿到的生成方法返回一个裸 `AsyncIterable`。 +`dsh-api-gateway` 在 `/api/remote.mux` 的一条 WebSocket 上复用 Typert Remote 流。Host 方法通过 `@Remote({ mode: 'stream' })` 和 `RemoteStream` 声明两个方向;生成的 Client 方法返回 `RemoteStreamHandle`。既有的 `Iterable` 和 `AsyncIterable` 返回类型声明仅下行的方法。可选的末位 `signal: AbortSignal` 由 Gateway 提供,不进入线路参数。 -线路帧只有五种: +两个方向共用一个 `streamId`: | 方向 | 帧 | 定义 | | --- | --- | --- | | Client 到 Host | `{ type: 'open', streamId, endpoint, payload }` | `stream-protocol.ts` | +| Client 到 Host | `{ type: 'item', streamId, value? }` | `stream-protocol.ts` | +| Client 到 Host | `{ type: 'end', streamId }` | `stream-protocol.ts` | | Client 到 Host | `{ type: 'cancel', streamId }` | `stream-protocol.ts` | | Host 到 Client | `{ type: 'item', streamId, value? }` | `stream-protocol.ts` | | Host 到 Client | `{ type: 'error', streamId, error: { code, message, details } }` | `stream-protocol.ts` | | Host 到 Client | `{ type: 'end', streamId }` | `stream-protocol.ts` | -客户端能发的只有打开与取消。解析器 `parseRemoteStreamClientMessage`(`stream-protocol.ts`)对其他任何帧抛错,Host 连接收到后以 1008 关闭整个 socket(`stream-server.ts`)。结论:网关今天只支持"后端 iterable 发到前端"。需要前端向后端持续发数据的功能,各自绕路。 +Client 句柄的 `send()` 提供上行项,`end()` 半关闭上行,`dispose()` 取消逻辑流。Host 通过 `this.ctx.invocation.uplink()` 读取解码后的项;调用上下文同时携带获准接入的 Peer 和取消信号。 -Host 方法也没有"这次调用是谁发起的"这个概念:`InvokeRemoteRequest = { namespace, method, args, signal }`(`packages/api/gateway/src/types.ts`)没有调用者槽位,`RemoteStreamOpener` 的签名是 `(endpoint, payload, signal)`(`stream-server.ts`),WebSocket 只在握手时校一次 cookie。 +传输层负责校验、取消和有界 inbox。消费者协议负责输入权限、确认以及断线后的恢复。 -### 三套各自为政的上行机制 +### 上行消费者 | 功能 | 上行方式 | 位置 | 代价 | | --- | --- | --- | --- | -| Web 终端按键 | 每次 xterm `onData` 一个 unary RPC `terminal.write(agent, id, attachmentId, data)`,客户端用 promise 链串行化并自限字节预算 | `packages/api/terminal-controller/src/client/model.ts`;Host `src/index.ts` | 一次按键一次 HTTP 往返与鉴权;两条载体靠 `attachmentId` 手工关联;满了报 `inputFull` | +| Web 终端输入与尺寸调整 | `terminal.attach` 承载上行 `TerminalInput` 和下行 `TerminalFrame`;Client 连续发送命令,并在收到 `ack` 后释放原始输入字节预算 | `packages/api/terminal-controller/src/client/model.ts`;Host `src/terminal.ts` | 当前附件拥有输入权;Client 预算耗尽时报 `inputFull`;重连后绝不重放输入 | | 文件上传 | `Blob` 或 `ReadableStream` 走 Remote 层之外的原生 `POST /api/session/uploadFileBinary`,`duplex: 'half'` | `packages/client/file-upload/src/client/runtime.ts`;路由 `src/index.ts` | 不经 Typert 描述符,没有类型投影 | | 审批与提问的回答 | Host 在 `$events` 流上下发 waterfall 帧,Client 用一个独立的 unary RPC `$events/result` 回答,靠 `clientId` 加 `eventId` 关联 | `packages/api/gateway/src/client/remote-events.ts`;Host `index.ts` | 第二套关联键;`index.ts` 记录了由此产生的竞态 | -这三套机制解决的是同一个问题:一条已经打开的逻辑流,客户端想往里写。 +这些消费者都需要在相关操作仍进行时从 Client 向 Host 传送数据。Web 终端使用双工流;文件上传和事件回答保留各自的传输方式。 -### 具体代价 +### 消费者职责 -- **两条载体对齐**。终端要用 `attachmentId` 把 `follow` 流与 `write` RPC 关联起来,并用它决定谁拥有输入权。审批要用 `clientId` 把 `$events` 流与 `$events/result` RPC 关联起来。 -- **没有顺序保证**。unary RPC 走 HTTP,与 WebSocket 下行互不排序;终端只能在客户端串行化写入来自保顺序。 -- **每次上行单独鉴权与查找**。`write(agent, id, attachmentId, data)` 每次解析 `agent`、查终端、校验 attachment。 -- **没有 EOF**。客户端无法表达"我这边写完了",半关闭要再加一个 RPC。 -- **取消不覆盖两半**。取消下行流不会取消排队中的上行写;反之亦然。 -- **背压各写一套**。下行按 socket 写回调节拍拉迭代器(`stream-server.ts`);终端用有界 follower 让慢消费者显式失败(`terminal-controller/src/stream.ts`);上行靠客户端自限 `maxInputBytes`。 -- **文档已经过时**。`docs/api-gateway.md:160` 仍写着 Remote 只处理一请求一结果,这一句已经落后于 README 记录的 stream 模式。 +- **输入权限**。终端通过 Host 本地的 follower 持有控制附件。快照和状态帧报告各附件的 `writable` 状态;控制权转移后,旧附件继续接收输出。 +- **顺序与确认**。终端输入和尺寸调整共用连续命令序列及终端操作队列。`ack` 报告提供者已接受操作或输入权限拒绝,绝不授权断线后重放。 +- **独立生命周期**。取消 `attach` 会停止其输入和输出传递、丢弃尚未开始的命令,并等待在途输入操作收尾。PTY 的生命周期由保留机制和显式关闭独立管理。 +- **协调字节限额**。Gateway 通过 `invocation.uplinkWindow` 提供完整帧 inbox 容量及本流的 JSON 封装开销。终端在快照中公布窗口,并通过提供者确认释放在途额度。窗口满时,输入和尺寸调整命令在有界 Client 队列中等待。`maxInputBytes` 限制原始 UTF-8 输入;`maxBufferedBytes` 分别限制 Client 保留的完整编码输入及每个 follower 保留的输出。 +- **仍独立的载体**。审批回答仍通过 `clientId` 和 `eventId` 将 `$events` 与 `$events/result` RPC 关联。将该协议迁入双工流仍属后续工作。 ### 与后台 job 的关系 @@ -66,7 +66,7 @@ Host 方法也没有"这次调用是谁发起的"这个概念:`InvokeRemoteReq Client Host ───────────────────────────────── ─────────────────────────────────────────── const s = remote.job.attach(req, signal) - │ open { streamId, endpoint, payload } ───────▶ opener(endpoint, payload, uplink, peer, control) + │ open { streamId, endpoint, payload } ───────▶ opener(endpoint, payload, uplink, peer, control, window) │ │ prepareInvocation │ s.send(v1) → item { streamId, v1 } ───────▶ inbox.push(v1) │ invocation = { request, service, peer, signal, uplink() } │ s.send(v2) → item { streamId, v2 } ───────▶ inbox.push(v2) │ receiverContext.extend({ invocation }).get(service) @@ -88,7 +88,7 @@ Host 方法也没有"这次调用是谁发起的"这个概念:`InvokeRemoteReq | 半关闭 | 一个方向已结束而另一个方向仍开放 | | 项 | 一个方向上的一个业务值;每项独立经 codec 校验 | | inbox | Host 侧每逻辑流一个的有界上行队列 | -| Peer | 连接层被接纳的一方,一个 `PeerScope`;本 Host 只有操作者一个 Peer | +| Peer | 一条连接代表的一方,一个携带 principal 的 `PeerScope`;所有浏览器连接共享 `connection.browserPeer`,进程内代码经 `connection.createPeer()` 自建([Peer 身份属性](../../implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md)) | | 调用上下文 | `RemoteInvocation`:本次调用的请求、接收服务、Peer、取消信号与上行入口 | ### 类型签名 @@ -135,10 +135,11 @@ export interface RemoteInvocation { } /** Cordis service key of the receiving service. */ readonly service: string - /** The Peer that initiated the call. In-process carriers and unadmitted calls are the operator. */ + /** The Peer that initiated the call; every carrier names it explicitly. */ readonly peer: PeerScope /** Carrier cancellation: Client cancel, socket closure, uplink failure. */ readonly signal: AbortSignal + readonly uplinkWindow?: RemoteUplinkWindow | undefined /** * The uplink items of this call. Can be taken once; the second call throws. With an uplink codec * in the descriptor each item is decoded to In; without one, items are delivered as unknown with @@ -179,24 +180,28 @@ declare module '@deepseek-ai/cordis' { /** The opaque identity of one Peer. */ export type PeerId = Branded<'PeerId'> -/** One Peer's session on this Host: opened and released by the admitting side; ctx owns connection-lifetime registrations. */ +/** One Peer's session on this Host: opened and released by its creator; ctx owns connection-lifetime registrations. */ export interface PeerScope { readonly id: PeerId readonly ctx: Context + /** Caller identity fixed at creation. */ + readonly principal: Principal + /** Aborted once the Peer is disposed. */ + readonly signal: AbortSignal dispose(): Promise } ``` -本 Host 只有一个 Peer:操作者。`@deepseek-ai/dsh-client-connection` 在服务 apply 时用 `createScope(connectionCtx, peer)` 建它,与 Agent 建自己的 scope 是同一机制:Peer 对象就是 ScopeKey,`peer.ctx` 承接连接期效果,`dispose()` 随 connection 释放让 fiber 静默。它以 `connection.operator` 暴露。 +`@deepseek-ai/dsh-client-connection` 实现唯一的 Peer 类 `Peer(owner, { principal })`,用 `createScope(owner, peer)` 建立,与 Agent 建自己的 scope 是同一机制:Peer 对象就是 ScopeKey,`peer.ctx` 承接连接期效果,scope 结束时 `peer.signal` 中止,`dispose()` 让 fiber 静默。Connection 在服务 apply 时以 owner principal 创建 `connection.browserPeer`;principal、`createPeer()` 与访问检查归 [Peer 身份属性与 Remote 方法级访问控制](../../implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md)。 | 成员 | 语义 | | --- | --- | -| `connection.operator: PeerScope` | 唯一的 Peer,随 connection 生灭 | -| `connection.admit(request): PeerAdmission` | 过既有的 `requestRejection`:被拒返回 `{ rejection: 401 \| 403 }`,否则返回 `{ peer: operator }`。将来的接纳方在这里接入 | +| `connection.browserPeer: PeerScope` | 所有通过认证的浏览器连接共享的 Peer;principal 为 owner;随 connection 生灭 | +| `connection.admit(request): PeerAdmission` | 过既有的 `requestRejection`:被拒返回 `{ rejection: 401 \| 403 }`,否则返回 `{ peer: browserPeer }`。将来的接纳方在这里接入 | -网关 `handleUpgrade(req, socket, head, peer)` 为该 socket 绑一个固定 Peer 的 opener,并在 `peer.ctx.effect` 里登记 socket 关闭;scope 已失效时改为直接以 1001 关闭 socket。`InvokeRemoteRequest.peer?` 与 `RemoteStreamOpener` 的 `peer` 形参缺席时按操作者作答,现有进程内调用方零改动;没有 connection 的组合里网关自建的操作者替身同样经 `createScope` 建立,`dispose()` 契约一致。按 id 查 Peer、把载体关联到第二个 Peer、Peer 的开关事件,都等第一个需要多 Peer 的消费者出现时再加。 +网关 `handleUpgrade(req, socket, head, peer)` 为该 socket 绑一个固定 Peer 的 opener,并在 `peer.ctx.effect` 里登记 socket 关闭;scope 已失效时改为直接以 1001 关闭 socket。`InvokeRemoteRequest.peer`、`RemoteStreamOpener` 与 `wireStream.open` 的 `peer` 形参均为 required,每个进程内调用方都显式给出 Peer,网关不自建 Peer。按 id 查 Peer、Peer 的开关事件,都等第一个需要它们的消费者出现时再加。 -Peer 不携带访问模型:Peer 是谁、能做什么,由业务插件通过 `peer.ctx` 自行附加。 +Peer 携带自己的 principal;该 principal 能调用什么,由 [Peer 身份属性与 Remote 方法级访问控制](../../implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md) 定义的 role、binding 与 policy 判定。 ### Client 面 @@ -311,7 +316,7 @@ credit 帧留待需要持续大流量上行的消费者出现时再加;inbox | worker 隧道(`packages/experimental/webworker-runtime`) | 页面新增 `stream-uplink-item` / `stream-uplink-end` 帧;`serveStream` 把它们组装成 `uplink` 交给 `seams.openStream`。同源可信边界:没有 inbox 上限,`end` 之后的项丢弃 | | `remote-mock`(`packages/test-support/remote-mock`) | `StreamHandle.uplink: AsyncIterable`;`rpc.open` 透传 | -进程内载体的 `peer` 缺席即操作者。 +进程内载体显式传入 Peer;worker 隧道的页内 Host 传 `connection.browserPeer`。 ### 与 `$events` 的关系 @@ -325,7 +330,7 @@ credit 帧留待需要持续大流量上行的消费者出现时再加;inbox // types.ts export type RemoteStream = AsyncIterable & { readonly [STREAM_UPLINK]?: In } export type PeerId = Branded<'PeerId'> -export interface PeerScope { readonly id: PeerId; readonly ctx: Context; dispose(): Promise } +export interface PeerScope { readonly id: PeerId; readonly ctx: Context; readonly principal: Principal; readonly signal: AbortSignal; dispose(): Promise } export interface RemoteInvocation { … } // see Host face declare module '@deepseek-ai/cordis' { interface Context { readonly invocation: RemoteInvocation | undefined } } @@ -362,13 +367,13 @@ export interface InvokeRemoteRequest { readonly args: Readonly> /** Uplink items; absent is equivalent to an iterator that ends immediately. */ readonly uplink?: AsyncIterable - /** The Peer that initiated the call; absent means the operator. */ - readonly peer?: PeerScope + /** The Peer that initiated the call; required on every path. */ + readonly peer: PeerScope readonly signal?: AbortSignal } export interface TypertGatewayWireStream { - open: (endpoint: string, payload: unknown, uplink: AsyncIterable, peer: PeerScope | undefined, signal: AbortSignal) => Promise> + open: (endpoint: string, payload: unknown, uplink: AsyncIterable, peer: PeerScope, signal: AbortSignal) => Promise> failure: (error: unknown) => RemoteStreamFailure } @@ -379,6 +384,7 @@ export type RemoteStreamOpener = ( uplink: AsyncIterable, peer: PeerScope, control: AbortController, + window: RemoteUplinkWindow, ) => Promise> // index.ts Config addition @@ -394,7 +400,7 @@ const signal = request.signal ?? NEVER_ABORTED_SIGNAL const invocation = new GatewayInvocation( { namespace: request.namespace, method: request.method, args: request.args }, descriptor.service, - request.peer ?? this.operatorPeer(), + request.peer, signal, new UplinkDecoder(request.uplink ?? EMPTY_ASYNC_ITERABLE, descriptor.uplink?.codec, endpoint, control), ) @@ -444,8 +450,8 @@ cancel : missing → ignore; otherwise control.abort(new Error('Remote stream ca | `dsh-typert-protocol`(`types.ts`、`index.ts`) | `RemoteStream`、`RemoteStreamHandle`、`PeerId`、`PeerScope`、`RemoteInvocation`、`ctx.invocation` 声明合并、`InvocationDescriptor.uplink`;修饰器只认 `mode: 'stream'`;`TypertRemoteService` 构造时注册 `invocation` accessor | | `dsh-typert-registry` | 加载校验 `uplink.codec` 为有效的严格 codec | | `dsh-typert-generator`(`model.ts`、`analyzer.ts`、`emitter.ts`) | `remoteResultType` 识别 `RemoteStream` 并生成 `uplink` boundary;描述符输出 `uplink: { codec }`;生成的 Client 签名返回 `RemoteStreamHandle`;参数循环只认业务参数与末位 `signal` | -| `dsh-client-connection`(`operator-peer.ts`、`rpc.ts`、`rpc-host.ts`、`index.ts`) | 操作者 `PeerScope`;`connection.operator` 与 `admit`;`/api` 与升级路由经 `admit` 取 Peer;`rpc.open` 的可选 `uplink` | -| `dsh-api-gateway` Host(`stream-protocol.ts`、`stream-server.ts`、`types.ts`、`index.ts`) | `item` / `end` 帧;`UplinkInbox`;`Config.streamInboxBytes`;`GatewayInvocation` 与 `extend({ invocation })`;`UplinkDecoder`;`handleUpgrade(req, socket, head, peer)`;`operatorPeer()` | +| `dsh-client-connection`(`peer.ts`、`rpc.ts`、`rpc-host.ts`、`index.ts`) | `Peer` 类;`connection.browserPeer` 与 `admit`;`/api` 与升级路由经 `admit` 取 Peer;`rpc.open` 的可选 `uplink` | +| `dsh-api-gateway` Host(`stream-protocol.ts`、`stream-server.ts`、`types.ts`、`index.ts`) | `item` / `end` 帧;`UplinkInbox`;`Config.streamInboxBytes`;`GatewayInvocation` 与 `extend({ invocation })`;`UplinkDecoder`;`handleUpgrade(req, socket, head, peer)` | | `dsh-api-gateway` Client(`client/index.ts`、`client/stream-client.ts`) | `invokeStream` 返回句柄;上行泵由句柄的队列驱动 | | `dsh-webworker-runtime`、`dsh-remote-mock` | worker 隧道的两种上行帧与 `serveStream` 组装;`StreamHandle.uplink`;直接代理返回真句柄 | | 文档 | gateway、api 组、connection、protocol、generator 的 README;`docs/api-gateway`;`docs/subsystems/typert` 的 type-equiv 块;config 与 Cordis 目录 | @@ -560,7 +566,7 @@ for await (const reply of stream) replies.push(reply) // ['> a', '> b'] **客户端 `send` 放在生成方法返回的 `AsyncIterable` 上。** `AsyncIterable` 上挂方法不常规;句柄类型 `RemoteStreamHandle` 显式扩展它。 -**照搬 Access 机制。** 访问控制是业务语义,`vouch` 与 `remote/invoke` waterfall 为它服务;本 Note 只需要"这条流是谁的",`PeerScope` 就够。 +**照搬 Access 机制。** 访问控制是业务语义,`vouch` 与 `remote/invoke` waterfall 为它服务;本 Note 只需要"这条流是谁的",`PeerScope` 就够。方法级访问控制后来归入 [Peer 身份属性与 Remote 方法级访问控制](../../implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md),该部分由其 supersede。 **继续用 unary RPC 做上行。** 每次上行一次 HTTP 往返、一次鉴权、一次查找;两条载体没有顺序关系,只能靠客户端串行化;没有 EOF;取消不覆盖两半;每个功能各造一套关联键。 @@ -574,10 +580,11 @@ for await (const reply of stream) replies.push(reply) // ['> a', '> b'] - **买到的**:一条流两个方向,终端按键、审批回答、后台任务 stdin 这类交互式场景不再各造一套"一条流加一个 unary";Host 方法知道调用者;上行类型与下行类型在返回类型里一处声明,上行项来自浏览器,在 Host 逐项严格校验,下行项是 Host 自产的类型值,直接透传;既有 `AsyncIterable` 方法与 unary 方法的生成物与线路帧完全不变。 - **`this.ctx.invocation` 在非 Remote 调用下是 `undefined`**,方法读它要处理可选;一个只被进程内直接调用的服务方法读到 `undefined` 是正确行为。 +- **Web 终端使用 `attach`** 传输屏幕输出和输入命令,并提供提供者确认和附件专属可写状态;Client 保留当前代次的句柄,绝不重放输入。 - **inbox 上限对所有流生效**:一个不读上行的方法收到大量上行帧会整流失败。这是刻意的显式失败,README 记明。 -- **Peer 只有操作者一个**,`admit` 是唯一的接纳点;第一个需要第二个 Peer 的消费者要在 `dsh-client-connection` 加上打开、关联与事件。 +- **所有浏览器连接共享 `browserPeer`**,`admit` 是唯一的网络接纳点;进程内代码经 `connection.createPeer()` 创建其他 Peer。 - **上行与下行之间没有跨方向顺序保证**;需要请求应答配对的协议自带序号。 -- **上层协议尚未透出 `send`**:`$stream`、snapshot、journal 的消费者今天只用下行;它们拿到的对象已经是句柄。 +- **上层监督器仅暴露下行**:`$stream`、snapshot 和 journal 不暴露 `send`;需要写入上行的领域保留该代次的生成物理句柄。 - **worker 隧道与 WebSocket 载体行为不同**:没有 inbox 上限,`end` 之后的项丢弃,因为页面到 worker 是同源可信边界。 ## 测试 @@ -588,17 +595,15 @@ for await (const reply of stream) replies.push(reply) // ['> a', '> b'] - 网关 Host:帧解析的精确键校验;`UplinkInbox` 的 opening 缓冲、`end` 后 `item`、超限、未知 `streamId` 忽略、socket 关闭时的收尾;`UplinkDecoder` 有无 codec 两种交付与解码失败中止;`uplink()` 只能取一次;`extend({ invocation })` 视图与 `peer` 的来源;`cancellableStream` 先关 uplink 再 `return()`。 - 网关 Client:句柄的 `send`(JSON 校验、open 前入队、终止后抛错)、`end` 幂等、`dispose` 驱动 `cancel` 帧并结束后续读取;泵的三种退出;终止帧到达即停泵。 - typert:analyzer 对 `RemoteStream`、`RemoteStream`、`never` 与既有 `AsyncIterable` 的处理;修饰器选项;registry 加载校验。 -- connection:`admit` 的 401、403 与操作者三种结果;操作者经桥与共享处理器到达;随 connection 释放。 +- connection:`admit` 的 401、403 与 `browserPeer` 三种结果;`browserPeer` 经桥与共享处理器到达;随 connection 释放。 - remote-mock、worker 隧道:上行透传;直接代理返回真句柄。 - 既有 stream 与 unary 方法的测试不改期望值即通过。 ## 后续 - `$stream` / snapshot / journal 把句柄的 `send` 透出给上层协议。 -- Web 终端:一条 `attach` 流取代 `follow` 加 `write` 加 `resize`,`attachmentId` 退场。 - 双工 `$events`:waterfall 的回答成为同一 `streamId` 上的上行项,`$events/result` 与 `clientId` 退场。 - credit 帧:等需要持续大流量上行的消费者出现;inbox 上限就是初始授信。 -- `streamInboxBytes` 默认值 262144 对键盘与 stdin 远超需要;若第一个消费者是终端粘贴,可能与 `terminal-controller` 的 `maxInputBytes` 对齐。 - Host 发起的半关闭帧(Host 不再读上行但继续写下行):没有消费者,不加。 - unary 方法的 `uplink()`:能读到方法运行期间到达的项,语义成立但用处存疑;允许,README 注明。 @@ -606,4 +611,4 @@ for await (const reply of stream) replies.push(reply) // ['> a', '> b'] - [Remote 事件投递](../../../../packages/api/remotes/README.zh.md):`$events/result` 的 unary 回答路径;「后续」里的双工 `$events` 落地后部分取代它。 - [会话历史与事件传输](2026-08-18-session-history-and-event-transport.zh.md):`$stream()` 监督器与其上的 journal / snapshot 协议,本 Note 不改它们。 -- [Web 侧边栏终端](../feature/2026-09-09-web-sidebar-terminal.zh.md):终端按键的 unary `write` 与 `attachmentId`;「后续」里的 `attach` 流落地后取代它。 +- [Web 侧边栏终端](../feature/2026-09-09-web-sidebar-terminal.zh.md):`attach` 流承载输入命令、提供者确认和附件专属可写状态;重连绝不重放输入。 diff --git a/.agents/notes/implemented/architecture/2026-09-19-timed-user-question-two-settlements.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-19-timed-user-question-two-settlements.i18n.yaml index a54db0a426..596b6ca28b 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-timed-user-question-two-settlements.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-19-timed-user-question-two-settlements.i18n.yaml @@ -15,8 +15,8 @@ en: adccc5dc758ad8f6 zh: 50304d68db42e8b1 /agent-note-timed-user-questions-as-two-settlements/decision/ownership: - en: 0543678ad9d26fc5 - zh: aa6ba207e661c567 + en: a28e37fda6e9eaff + zh: 9ca622e09ab24b4d /agent-note-timed-user-questions-as-two-settlements/decision/foreground-wait-and-claim-lifetime: en: 447713bbdf1ab4d8 zh: 2757678ae47822aa @@ -30,14 +30,14 @@ en: 3a33f2583e30e32a zh: 0ad7e8d1e47dc510 /agent-note-timed-user-questions-as-two-settlements/decision/reply-node-and-grouping: - en: 10323b0e0340a40b - zh: a17fc3a4d4d820a7 + en: d87d7432c37405a7 + zh: 49f1bbf53856851a /agent-note-timed-user-questions-as-two-settlements/alternatives-considered: - en: bf61d0ec80c63bb4 - zh: d4ce4d4438ffb013 + en: 1a070542bfa40e68 + zh: 82e32964da912dd8 /agent-note-timed-user-questions-as-two-settlements/verification: - en: d912a73a5ff409eb - zh: 7b626794773e2301 + en: 1d19d196c363a273 + zh: 7cb0475f0cb554d1 /agent-note-timed-user-questions-as-two-settlements/consequences: - en: 2bc99c99be8ca9da - zh: 8f262ec8b9b0945e + en: 0580e85cc12439c5 + zh: a4b151d2c9e5b747 diff --git a/.agents/notes/implemented/architecture/2026-09-19-timed-user-question-two-settlements.md b/.agents/notes/implemented/architecture/2026-09-19-timed-user-question-two-settlements.md index 4bdf47cb2c..014912c9a8 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-timed-user-question-two-settlements.md +++ b/.agents/notes/implemented/architecture/2026-09-19-timed-user-question-two-settlements.md @@ -29,7 +29,7 @@ Foreground answers use the existing Remote Event waterfall. A timeout ends that | `UserQuestionService` | Foreground waits and Client claims, unattended deadlines, late-answer validation and steering, and the durable question projection. | | Gateway and Remote runtime | Existing request delivery, settlement, cancellation, and Remote stream transport; no question-specific timer or event-name branch. | | `ui-user-questions` | One card per Session and call, answer-channel selection, local countdown and drafts, and the reply Definition and renderer. | -| `ui-chat` | Message-id-based presentation aggregation and ordinary process/Turn folding. | +| `ui-chat` | Ordinary process/Turn folding. | | Question-specific tool row | Pending/answered presentation and panel actions, composed in `QuestionToolRow` without adding `rowAction` to generic `ToolRow`. | The [question service](../../../../packages/interaction/user-questions/README.md), [tool](../../../../packages/interaction/tool-ask-user/README.md), and [questions UI](../../../../packages/client/ui-user-questions/README.md) own their package contracts. @@ -72,11 +72,11 @@ Autofocus applies only when the answer channel is ready, no countdown is active, The questions UI identifies a late reply from `source.kind`, then parses its recorded JSON for question-and-answer presentation. Pasting identical JSON in an ordinary user message does not identify it as a reply. Unreadable recorded payloads retain their raw-text presentation. -The ordinary message Definition and the question-reply Definition both match the appended message and retain separate Node Store projections with the same message id. Chat business grouping omits the `turn-trigger` presentation when a `question-reply` with that id is present. The duplicate trigger neither renders nor splits a group; the reply renders once. The same aggregation applies to unscoped historical input. +The question-reply Definition claims the appended reply message on the Chat target through an [exclusive match](2026-10-12-exclusive-conversation-matches.md), so the ordinary message Definition builds no `turn-trigger` or context projection for it and the reply renders once, including for unscoped historical input. The reply participates in ordinary process grouping and whole-Turn folding. It is not independently visible: reading it can require expanding both its Turn and process group. Turn disclosure stays before the group it controls, including a reply that opens the Turn. -This decision adds no process-role field, independent-layout flag, user-message structure change, or target-local fallback dispatch. The independent-kind rules stay in Chat's existing grouping logic. A node-data-owned declaration of grouping and overlap semantics is deferred infrastructure, not part of the question feature. +This decision adds no independent-layout flag or user-message structure change. The reply declares no group-tree position, so it follows the default placement of process content. ## Alternatives considered @@ -90,7 +90,7 @@ This decision adds no process-role field, independent-layout flag, user-message **Reclassify JSON inside generic `MessageItem`, borrow the relay form, or use the default context row.** Parsing text to identify the business message confuses its source with its content; the relay form describes another agent's message, and a generic context row exposes JSON. A dedicated source, Definition, and renderer own the question presentation. -**Independent reply layout through generic node metadata.** It broadens a question feature into a conversation-infrastructure change. Ordinary folding and Chat-owned aggregation are sufficient for this decision; independently declared node-data grouping semantics remain a separate design task. +**Independent reply layout through generic node metadata.** It broadens a question feature into a conversation-infrastructure change. Ordinary folding is sufficient for this decision; placing the reply as user input through its group-tree position is separate work. **A log-only close event or a manufactured dismissal message on panel close.** A log-only close hides the user's decision from the model and adds another durable mechanism. Manufacturing a reply treats hiding the panel as an answer. Panel close therefore leaves a timed question answerable. @@ -101,7 +101,7 @@ This decision adds no process-role field, independent-layout flag, user-message - [Service tests](../../../../packages/interaction/user-questions/tests/user-questions.spec.ts) and [wait tests](../../../../packages/interaction/user-questions/tests/timed-wait.spec.ts) cover claimed and unclaimed waits, last-claim disconnect, cancellation, timeout error mapping, continued-only answers, and exact answer-id validation. - [Projection tests](../../../../packages/interaction/user-questions/tests/projection.spec.ts) distinguish legacy and timed schemas and cover native and PTC pending calls, other failures, resume repair, queued reply cancellation, and admitted settlement. - [Client listener tests](../../../../packages/client/ui-user-questions/tests/browser-plugin.client.spec.ts) and [composer tests](../../../../packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx) cover claim retention through Host acceptance, focus before handshake, indefinite waits, draft retention, RPC resubmission, and panel actions. -- [Grouping tests](../../../../packages/client/ui-chat/tests/process-groups.client.spec.ts) and [browser replay](../../../../apps/web/tests/question-composer.e2e.ts) cover one rendered reply with both projections retained, ordinary collapsed placement, disclosure ordering, and the original tool row's read-only late-answer panel. +- [Grouping tests](../../../../packages/client/ui-chat/tests/process-groups.client.spec.ts) and [browser replay](../../../../apps/web/tests/question-composer.e2e.ts) cover ordinary collapsed placement, disclosure ordering, and the original tool row's read-only late-answer panel. - Legacy round-trip, cancellation, plan-review intent, and Session-remount regressions remain covered by their owning tests. Live multi-Client delivery races and real Host restart remain integration coverage gaps beyond isolated lifecycle and projection tests. ## Consequences @@ -111,7 +111,6 @@ The model can continue independent work while the question remains answerable. B - Take time affects only one Client. Another Client can answer or expire the shared waterfall; local focus does not establish a global hold. - A terminal claim-stream failure can reject the foreground question rather than produce pending. No unattended-wait fallback is provided for that failure. - Host and Client clocks need not align, but Client system-clock changes can move expiry and transport latency can delay the local countdown's start. -- The duplicate projections remain stored. Aggregation adds linear scans during structural grouping rebuilds; ordinary text-only streaming updates retain their incremental path. This is an algorithmic bound, not a measured latency claim. - Unanswered continued questions can remain after reopening a Session. Panel close records nothing, and visibility follows normal folding rather than an always-visible reply guarantee. - A queued late reply can be canceled before the agent admits it. The question stays answerable until an admitted `user/message` records the answer. - A PTC sub-call interrupted before its `tool/ptc-dispatch` result is recorded cannot be reconstructed from the parent `run_code` failure, so it cannot take a late answer after recovery. diff --git a/.agents/notes/implemented/architecture/2026-09-19-timed-user-question-two-settlements.zh.md b/.agents/notes/implemented/architecture/2026-09-19-timed-user-question-two-settlements.zh.md index 6bce5e9960..91ddd5c6b4 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-timed-user-question-two-settlements.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-19-timed-user-question-two-settlements.zh.md @@ -29,7 +29,7 @@ Status: implemented | `UserQuestionService` | 前台等待与 Client 接手、无人接手时的 deadline、迟到回答校验与 steering(中途引导),以及持久问题投影。 | | Gateway 与 Remote 运行时 | 现有请求投递、结算、取消及 Remote stream 传输;不包含问题专属计时器或按事件名分支。 | | `ui-user-questions` | 每个 Session 和调用的一张卡片、回答通道选择、本地倒计时与草稿,以及回复 Definition 和渲染器。 | -| `ui-chat` | 基于消息 id 的呈现聚合,以及普通过程/轮次折叠。 | +| `ui-chat` | 普通过程/轮次折叠。 | | 问题专用工具行 | pending/已回答呈现与面板操作,在 `QuestionToolRow` 中组合,不向通用 `ToolRow` 添加 `rowAction`。 | [问题服务](../../../../packages/interaction/user-questions/README.zh.md)、[工具](../../../../packages/interaction/tool-ask-user/README.zh.md)和[问题 UI](../../../../packages/client/ui-user-questions/README.zh.md)分别拥有各包的约定。 @@ -72,11 +72,11 @@ Client 计算 `Date.now() + remainingMs`。手动聚焦未编辑的回答区会 问题 UI 通过 `source.kind` 识别迟到回复,再解析已记录的 JSON 来呈现问答。普通用户消息粘贴相同 JSON 不会被识别为回复。无法读取的已记录载荷保留原始文本呈现。 -普通消息 Definition 和问答回复 Definition 都匹配追加的消息,在 Node Store 中保留消息 id 相同的独立投影。存在同 id 的 `question-reply` 时,Chat 业务分组省略 `turn-trigger` 呈现。重复触发节点既不渲染,也不切开分组,回复只显示一次。相同聚合也适用于无轮次归属的历史输入。 +问答回复 Definition 通过[独占匹配](2026-10-12-exclusive-conversation-matches.zh.md)在 Chat target 上认领追加的回复消息,普通消息 Definition 因此不再为它建立 `turn-trigger` 或 context 投影,回复只显示一次;无轮次归属的历史输入同样如此。 回复参与普通过程分组和整轮折叠,不保证独立可见:阅读时可能需要展开所属轮次与过程分组。轮次折叠控件始终在所控制的分组之前,包括由回复开启轮次的情况。 -本决策不添加 process-role 字段、独立布局标记、用户消息结构变更或目标内 fallback 派发。独立 kind 规则保留在 Chat 现有分组逻辑中。由节点 data 声明分组与重叠语义的机制是留待拆分的基础设施,不属于问题功能。 +本决策不添加独立布局标记或用户消息结构变更。回复不声明分组树位置,因此按过程内容的默认位置放置。 ## Alternatives considered @@ -90,7 +90,7 @@ Client 计算 `Date.now() + remainingMs`。手动聚焦未编辑的回答区会 **在通用 `MessageItem` 内重新分类 JSON、借用 relay form,或使用默认 context 行。** 解析文本来识别业务消息混淆了来源与内容;relay form 表示其他 agent 的消息,通用 context 行则会暴露 JSON。专用来源、Definition 和渲染器拥有问题呈现。 -**通过通用节点元数据让回复独立布局。** 这会把问题功能扩大为对话基础设施变更。普通折叠与 Chat 内聚合足以满足本决策;由节点 data 独立声明分组语义仍是单独的设计任务。 +**通过通用节点元数据让回复独立布局。** 这会把问题功能扩大为对话基础设施变更。普通折叠足以满足本决策;通过分组树位置把回复放置为用户输入是单独的工作。 **面板关闭时写仅入日志的关闭事件,或伪造放弃消息。** 仅入日志会让模型看不到用户决定,还增加另一套持久机制。伪造回复则把隐藏面板当成回答。因此关闭面板仍让计时问题保持可回答。 @@ -101,7 +101,7 @@ Client 计算 `Date.now() + remainingMs`。手动聚焦未编辑的回答区会 - [服务测试](../../../../packages/interaction/user-questions/tests/user-questions.spec.ts)与[等待测试](../../../../packages/interaction/user-questions/tests/timed-wait.spec.ts)覆盖有人与无人接手、最后接手方断开、取消、超时错误映射、仅接受已继续问题的回答,以及答案 id 的精确校验。 - [投影测试](../../../../packages/interaction/user-questions/tests/projection.spec.ts)区分 legacy 与 timed schema,并覆盖原生及 PTC pending 调用、其他失败、恢复修复、排队回复取消和准入后结算。 - [Client 监听器测试](../../../../packages/client/ui-user-questions/tests/browser-plugin.client.spec.ts)与[composer 测试](../../../../packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx)覆盖接手保留到 Host 接受结果、握手前聚焦、无限期等待、草稿保留、RPC 重提及面板操作。 -- [分组测试](../../../../packages/client/ui-chat/tests/process-groups.client.spec.ts)与[浏览器回放](../../../../apps/web/tests/question-composer.e2e.ts)覆盖保留两个投影但只渲染一次回复、普通折叠位置、折叠控件顺序,以及原工具行的迟到答案只读面板。 +- [分组测试](../../../../packages/client/ui-chat/tests/process-groups.client.spec.ts)与[浏览器回放](../../../../apps/web/tests/question-composer.e2e.ts)覆盖普通折叠位置、折叠控件顺序,以及原工具行的迟到答案只读面板。 - legacy 问答往返、取消、计划评审意图及 Session 重新挂载的回归仍由各自测试覆盖。真实多 Client 投递竞争与真实 Host 重启仍是独立生命周期和投影测试之外的集成覆盖缺口。 ## Consequences @@ -111,7 +111,6 @@ Client 计算 `Date.now() + remainingMs`。手动聚焦未编辑的回答区会 - 「慢慢回答」只影响一个 Client。其他 Client 可以回答或让共享 waterfall 到期,本地聚焦不构成全局暂停。 - 接手 stream 的终止性失败可能让前台问题失败,而不是产生 pending。不为该失败提供无人接手等待的 fallback。 - Host 与 Client 时钟不必对齐,但 Client 系统时钟变化可能移动到期时间,传输延迟可能推迟本地倒计时的开始。 -- 重复投影仍保留在存储中。聚合在结构性分组重建时增加线性扫描;普通纯文本 stream 更新保留增量路径。这是算法复杂度界限,不是实测延迟结论。 - 无人回答的已继续问题可以在重新打开 Session 后继续存在。关闭面板不写记录,可见性遵循普通折叠,而不是保证回复始终可见。 - 排队的迟到回复可能在 agent 准入前被取消。只有已准入的 `user/message` 记录答案,问题在此之前保持可回答。 - PTC 子调用若在记录 `tool/ptc-dispatch` 结果前中断,无法从父 `run_code` 的失败中重建,因此恢复后不能接受迟到回答。 diff --git a/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.i18n.yaml index e7aef9adc0..448629299d 100644 --- a/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.i18n.yaml @@ -9,11 +9,11 @@ en: 2ba6c43b20a3d347 zh: 5647179ddaa38ad9 /agent-note-ship-experimental-capabilities-as-optional-bundles/decision: - en: e6ffc783859d7509 - zh: 8678f323985a24f4 + en: 6c8583bdefc5e36c + zh: 0928b4f2876bbfe4 /agent-note-ship-experimental-capabilities-as-optional-bundles/alternatives-considered: - en: 9ff0511566948d8b - zh: 4e1e37b79f63d390 + en: d6f40bf02df37ab7 + zh: e5b85ce9d41e8754 /agent-note-ship-experimental-capabilities-as-optional-bundles/consequences: - en: 9d2b313f15fc9ce0 - zh: 522341c83565ac33 + en: 38d27583533cd028 + zh: 9bf11f5489c1aa43 diff --git a/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.md b/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.md index d529b27542..dbdd104da0 100644 --- a/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.md +++ b/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.md @@ -14,7 +14,7 @@ The Web plugin page offered two optional bundles, Agent Teams and voice input. A An optional bundle's dependencies are downloaded with every `dsh` installation. [Reasoning translation](2026-10-05-anonymous-reasoning-translation.md) uses three experimental packages without adding third-party runtime dependencies. Admission therefore considers installation cost and whether a switch supplies a usable composition without an additional configuration form. Browser and computer providers remain explicit compositions because they add substantial runtimes or require an external executable. Stagehand requires model credentials; Python PTC replaces a core provider and conflicts with TypeScript workflow consumers. Demonstrative hooks, webhooks, and mods stay outside the list. [Session Inspector](../feature/2026-09-24-session-inspector.md) owns the Inspector's distinct activation behavior. -Bundles add scoped rows with the [profile patch operation](../../../../packages/boot/app-boot/README.md): `preset` names a declaration row, and the ordinary patch operates on its child list. Full Web presets receive the optional model tools; minimal retains its current shell and working-directory tools. Search, Ralph, and terminals supply their own isolated services. Search opens one in-memory index on demand per retained preset revision; the Host search policy stays unchanged. Badge skills and title providers act on the Host. Existing Agents retain their preset generation, and later user patch layers retain precedence. Title replacement waits for disposal of the previous provider. +Bundles insert ordinary Host rows; optional model tools register in the global tool layer, so every preset, including minimal, receives them. Plugin management, profile composition, and reload need no bundle-specific behavior. Search, Ralph, and terminals supply their own isolated services in a Host group. Search opens one in-memory index on demand; the Host search policy stays unchanged. Badge skills and title providers act on the Host. Switching a bundle registers or removes its tools for live Agents, and later user patch layers retain precedence. A replacement title provider may register once the previous provider's disposal starts; the previous provider's late results never commit. Claude Code and Codex install on demand through the separate `ON_DEMAND_BUNDLES` catalog; the [on-demand native-bundle decision](2026-10-05-official-on-demand-bundles.md) owns the cost, version, and offline-discovery trade-offs. @@ -26,6 +26,8 @@ Claude Code and Codex install on demand through the separate `ON_DEMAND_BUNDLES` **Register preset extensions at runtime.** A separate registration path would need its own ordering, module resolution, generation updates, and inspection behavior. Profile patches keep one effective composition for boot, dumps, validation, and user overrides. +**Insert rows into named presets with a `preset` patch operation.** Limiting tools to full presets required a second patch language across profile composition, reload, plugin management, and the plugin page, plus retained-generation removal checks. Global tools reach the same Agents through the existing Host composition. + ## Consequences -Official discovery does not imply experimental status or a different plugin lifecycle. Switching a bundle off keeps its installed files; failed activation retains the existing saved-selection behavior. Scoped rows appear read-only under their bundle, and removal respects modules retained by live preset generations. Individual and combined composition tests cover the supported presets; live switching and recorded Sessions cover activation and model-visible behavior. +Official discovery does not imply experimental status or a different plugin lifecycle. Switching a bundle off keeps its installed files; failed activation retains the existing saved-selection behavior. Bundle rows are ordinary Host rows with their usual switches. Individual and combined composition tests cover the Host rows and every preset's tool catalog; live switching and recorded Sessions cover activation and model-visible behavior. diff --git a/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.zh.md b/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.zh.md index 13abff45a0..6c9df974e8 100644 --- a/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.zh.md @@ -14,7 +14,7 @@ Web 插件页只提供两个可选 bundle:Agent Teams 与语音输入。Auto r 可选 bundle 的依赖随每次 `dsh` 安装下载。[思考过程翻译](2026-10-05-anonymous-reasoning-translation.zh.md)使用三个实验包,不增加第三方运行时依赖。因此准入需要考虑安装成本,以及开关能否在不增加配置表单的情况下提供可用组合。浏览器与电脑提供方仍使用显式组合,因为它们会增加较大的运行时或要求外部可执行文件。Stagehand 需要模型凭据;Python PTC 替换核心提供方,并与 TypeScript workflow 消费方冲突。演示性钩子、webhook 与模组不进入名单。[Session Inspector](../feature/2026-09-24-session-inspector.zh.md) 管理 Inspector 特有的激活行为。 -Bundle 通过 [profile patch 操作](../../../../packages/boot/app-boot/README.zh.md)添加作用域行:`preset` 指定声明行,普通 patch 对其子列表生效。完整 Web 预设获得可选模型工具;minimal 保持当前的 shell 与工作目录工具。搜索、Ralph 与终端提供自己的隔离服务。搜索在每个保留的预设修订中按需打开一个内存索引;Host 搜索策略保持不变。徽章技能与标题提供方作用于 Host。已有 Agent 保留其预设代际,后续用户 patch 层继续优先。标题替换等待前一个提供方完成清理。 +Bundle 插入普通 Host 行;可选模型工具注册到全局工具层,因此包括 minimal 在内的所有预设都会获得它们。插件管理、profile 组合与重载无需针对 bundle 的特殊行为。搜索、Ralph 与终端在 Host 组内提供自己的隔离服务。搜索按需打开一个内存索引;Host 搜索策略保持不变。徽章技能与标题提供方作用于 Host。切换 bundle 会为运行中的 Agent 注册或移除其工具,后续用户 patch 层继续优先。前一个标题提供方开始清理后,替代提供方即可注册;前一个提供方的迟到结果不会提交。 Claude Code 与 Codex 通过独立的 `ON_DEMAND_BUNDLES` 目录按需安装,其成本、版本与离线发现取舍由[按需原生 bundle 决策](2026-10-05-official-on-demand-bundles.zh.md)管理。 @@ -26,6 +26,8 @@ Claude Code 与 Codex 通过独立的 `ON_DEMAND_BUNDLES` 目录按需安装, **在运行时注册预设扩展。** 独立注册路径需要自己的排序、模块解析、代际更新与检查行为。Profile patch 为启动、配置导出、校验和用户覆盖保留同一个有效组合。 +**用 `preset` patch 操作向指定预设插入行。** 只把工具限定在完整预设中,需要在 profile 组合、重载、插件管理和插件页中引入第二套 patch 语言,并为保留代际增加删除检查。全局工具通过现有 Host 组合即可到达同样的 Agent。 + ## 后果 -官方发现不表示实验性状态,也不引入不同的插件生命周期。关闭 bundle 保留已安装文件;激活失败保留现有的已保存选择行为。作用域行在 bundle 内只读展示,删除操作尊重 live 预设代际仍持有的模块。独立与组合测试覆盖受支持的预设;实时切换与已记录 Session 覆盖激活和模型可见行为。 +官方发现不表示实验性状态,也不引入不同的插件生命周期。关闭 bundle 保留已安装文件;激活失败保留现有的已保存选择行为。Bundle 行是普通 Host 行,使用常规开关。独立与组合测试覆盖 Host 行及每个预设的工具目录;实时切换与已记录 Session 覆盖激活和模型可见行为。 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-09-23-native-https-web-listener.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-23-native-https-web-listener.i18n.yaml new file mode 100644 index 0000000000..0aad921cce --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-23-native-https-web-listener.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-09-23-native-https-web-listener.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-native-https-web-listener.md +/agent-note-native-https-on-the-web-listener: + en: bdb6e7794af113f0 + zh: b9f325b0cbe8d34d +/agent-note-native-https-on-the-web-listener/problem: + en: 685a00e6f84f642d + zh: 404e463f56ec5a1f +/agent-note-native-https-on-the-web-listener/decision: + en: 7f9ea8a4f2577d2f + zh: e9b2a1fc6944428e +/agent-note-native-https-on-the-web-listener/alternatives-considered: + en: 44c051936dd2529e + zh: 7588669ec4c302ef +/agent-note-native-https-on-the-web-listener/consequences: + en: 6a8be07b24f957ba + zh: fbf48476e092dfc8 +/agent-note-native-https-on-the-web-listener/testing: + en: f92f7ec224dba94d + zh: 0f0e0304c834f0af diff --git a/.agents/notes/implemented/architecture/2026-09-23-native-https-web-listener.md b/.agents/notes/implemented/architecture/2026-09-23-native-https-web-listener.md new file mode 100644 index 0000000000..123f762559 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-23-native-https-web-listener.md @@ -0,0 +1,41 @@ +# Agent Note: Native HTTPS on the Web listener + +Status: implemented + +English | [中文](2026-09-23-native-https-web-listener.zh.md) + +## Problem + +A directly reached Web listener needs to encrypt launch tokens and session cookies without requiring a separate reverse proxy. Advertising an HTTPS URL does not encrypt the listener or establish certificate trust. + +## Decision + +WebServer owns optional TLS through `tls: { certFile, keyFile }`, exposed by `dsh web` as paired `--tls-cert` and `--tls-key` flags. Certificate and unencrypted private-key PEM files are loaded before binding; unreadable, empty, invalid, or mismatched material fails activation without an HTTP fallback. HTTP remains the default. Both transports share routing, upgrades, and disposal; disposal also owns incomplete TLS handshakes. + +`webServer.protocol` is the source for the bind-address URL, the non-loopback plain-HTTP warning, and Connection's `Secure` cookie attribute. Neither forwarded headers nor `publicUrl` control encryption or that attribute. Explicit Host-port grants normalize under the listener's scheme, while Origin comparison uses the Origin's HTTP(S) scheme so HTTPS proxies can retain HTTP upstreams. TLS grants no additional Host authority and does not replace authentication. + +The API authority check does not equate a proxy's upstream transport with the browser page's scheme. An HTTPS listener can accept a matching HTTP Origin, but `sec-fetch-site: cross-site` still rejects the request and authentication remains required. Schemeful `SameSite=Strict` cookies prevent cross-scheme browser credential delivery; this is not support for serving a public browser frontend over HTTP with a TLS upstream. + +HTTP cookie audiences retain their existing spelling so enabling TLS support does not invalidate unrelated HTTP sessions. HTTPS cookie names and signed audiences include the `https:` scheme, preventing replay of an HTTP credential on any HTTPS port even if the cookie is renamed. Default ports follow URL normalization without a separate port-443 spelling. + +Certificate issuance, trust, renewal, and replacement belong to the operator. Files are read once per activation; replacement requires a listener reload or process restart. The certificate must cover the hostname or IP the TLS client dials. The default port remains 3080; `--port` selects another port, subject to operating-system permission. + +## Alternatives considered + +**Require a TLS-terminating proxy.** This remains supported, but requires another service for a directly reached listener. + +**Derive transport or cookie security from `publicUrl` or forwarding headers.** An advertisement does not describe the receiving socket, and request headers cannot establish trusted proxy identity. Native listener state keeps this decision independent of proxy policy. + +**Issue, renew, or generate certificates.** This would add certificate lifecycle and trust-distribution responsibilities. An automatically generated certificate would not establish browser trust. + +**Fall back to HTTP on certificate errors.** This would expose credentials despite an explicit request for encryption; activation must fail instead. + +## Consequences + +Direct HTTPS needs no TLS-terminating proxy. An HTTPS proxy in front of an HTTP listener still owns external cookie rewriting. An HTTPS listener emits `Secure` cookies, so public browser-facing deployments must retain HTTPS rather than depend on local-browser exceptions for HTTP. Deployment procedures belong to the [public deployments guide](../../../../docs/user/guide/public-deployments.md). + +This partially supersedes the HTTP-only assumptions in [browser launch-token authentication](2026-08-24-browser-token-authentication.md) and [concrete bind addresses](2026-09-19-concrete-web-bind-address.md). Those notes remain active for cookie payloads and lifetimes, and bind admission respectively. + +## Testing + +The WebServer suite covers verified HTTPS, invalid material, and disposal. Connection covers listener-owned cookie attributes, cross-protocol credential replay, and exact-port grants; Web startup rejects unpaired flags. The built CLI's `public-url.expected.e2e.ts` authenticates over verified TLS with a `Secure` cookie while retaining HTTP and proxy cases; its failure matrix verifies unreadable TLS material exits without opening a listener. Desktop's startup suite covers matching WS/WSS credentials and refusal on a different transport. diff --git a/.agents/notes/implemented/architecture/2026-09-23-native-https-web-listener.zh.md b/.agents/notes/implemented/architecture/2026-09-23-native-https-web-listener.zh.md new file mode 100644 index 0000000000..c34ad19b31 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-23-native-https-web-listener.zh.md @@ -0,0 +1,41 @@ +# Agent Note: Web 监听器原生 HTTPS + +Status: implemented + +[English](2026-09-23-native-https-web-listener.md) | 中文 + +## Problem + +浏览器直接访问的 Web 监听器需要在不依赖独立反向代理的情况下加密启动 token 与会话 cookie。公告 HTTPS URL 不会加密监听器,也不会建立证书信任。 + +## Decision + +WebServer 通过 `tls: { certFile, keyFile }` 拥有可选 TLS,由 `dsh web` 的成对 `--tls-cert` 与 `--tls-key` flag 暴露。证书与不带口令的私钥 PEM 文件在绑定前加载;材料不可读、为空、无效或不匹配时激活失败,绝不回退到 HTTP。HTTP 仍为默认值。两种传输共用路由、升级与释放;释放也负责未完成的 TLS 握手。 + +`webServer.protocol` 决定绑定地址 URL、非 loopback 明文 HTTP 警告及 Connection 的 `Secure` cookie 属性。转发 header 与 `publicUrl` 都不控制加密或该属性。显式 Host 端口授权按监听器的 scheme 归一化,Origin 比较则按 Origin 的 HTTP(S) scheme 进行,以允许 HTTPS 代理保留 HTTP 上游。TLS 不授予额外的 Host authority,也不替代认证。 + +API authority 校验不会把代理的上游传输等同于浏览器页面的 scheme。HTTPS 监听器可接受 authority 匹配的 HTTP Origin,但 `sec-fetch-site: cross-site` 仍会拒绝请求,且请求仍须认证。区分 scheme 的 `SameSite=Strict` cookie 阻止浏览器跨 scheme 携带凭据;这不表示支持以 HTTP 向公开浏览器前端提供页面、同时使用 TLS 上游。 + +HTTP cookie audience 保留既有写法,避免启用 TLS 支持时使无关的 HTTP 会话失效。HTTPS cookie 名称与签名 audience 包含 `https:` scheme,因此即使修改 cookie 名称,HTTP 凭据也不能在任何 HTTPS 端口上重放。默认端口遵循 URL 归一化,不为 443 端口另设写法。 + +证书签发、信任、续期与更换归操作者负责。每次激活只读取一次文件;更换后需重新加载监听器或重启进程。证书必须覆盖 TLS 客户端拨号的 hostname 或 IP。默认端口仍为 3080;`--port` 可选择其他端口,但受操作系统权限约束。 + +## Alternatives considered + +**要求终止 TLS 的代理。** 仍然支持,但会为直接访问的监听器增加一个服务。 + +**根据 `publicUrl` 或转发 header 推导传输或 cookie 安全属性。** 公告不描述接收请求的 socket,请求 header 也不能建立可信代理身份。原生监听器状态使这一决策独立于代理策略。 + +**签发、续期或生成证书。** 这会增加证书生命周期与信任分发职责。自动生成证书本身不能建立浏览器信任。 + +**证书错误时回退到 HTTP。** 这会在操作者明确要求加密时暴露凭据;激活必须失败。 + +## Consequences + +直接 HTTPS 不需要终止 TLS 的代理。HTTP 监听器前的 HTTPS 代理仍负责外部 cookie 重写。HTTPS 监听器签发 `Secure` cookie,因此公开部署的浏览器侧必须保持 HTTPS,而不应依赖本地浏览器对 HTTP 的例外。部署步骤归[公开部署指南](../../../../docs/user/guide/public-deployments.zh.md)所有。 + +本决策部分取代[浏览器启动 token 认证](2026-08-24-browser-token-authentication.zh.md)与[具体绑定地址](2026-09-19-concrete-web-bind-address.zh.md)中仅支持 HTTP 的前提。这些说明分别继续定义 cookie 载荷与有效期及绑定准入,保持活跃。 + +## Testing + +WebServer 套件覆盖校验证书的 HTTPS、无效材料与释放。Connection 覆盖由监听器决定的 cookie 属性、跨协议凭据重放和精确端口授权;Web 启动拒绝未配对的 flag。已构建 CLI 的 `public-url.expected.e2e.ts` 使用 `Secure` cookie 经校验证书的 TLS 完成认证,并保留 HTTP 与代理用例;失败矩阵验证 TLS 材料不可读时进程退出且不打开监听器。Desktop 启动套件覆盖匹配的 WS/WSS 凭据及不同传输下的拒绝。 diff --git a/.agents/notes/implemented/architecture/2026-09-24-bounded-session-log-upload.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-24-bounded-session-log-upload.i18n.yaml index 64f1ca3e65..cc7f108d4c 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-bounded-session-log-upload.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-24-bounded-session-log-upload.i18n.yaml @@ -15,5 +15,5 @@ en: 88985b4e1f5c7a4f zh: 32617f7ff75ee825 /agent-note-bounded-deepseek-session-log-upload/consequences: - en: e19fb6136ffd2250 - zh: 01dacd7a44c3f837 + en: 288834c514df377a + zh: a33a4af2b4d9ebf4 diff --git a/.agents/notes/implemented/architecture/2026-09-24-bounded-session-log-upload.md b/.agents/notes/implemented/architecture/2026-09-24-bounded-session-log-upload.md index b980765eed..27ae7e4117 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-bounded-session-log-upload.md +++ b/.agents/notes/implemented/architecture/2026-09-24-bounded-session-log-upload.md @@ -25,6 +25,6 @@ This supersedes complete-suffix delivery and fail-closed serialization in the [r ## Consequences -A backlog drains at up to 8 MiB per accepted request by default. At the end-to-end rate measured for the 269 MiB upload, about 8 MiB/s, an 8 MiB field adds about 1 s to each request while a backlog drains, and a 0.86 GB backlog drains in about 100 requests. In the same 96,341-event Session, the median per-step append is 11 KiB and the largest event is 414 KiB, so ordinary steps stay far below the limit and only an unusual event or a small configured limit reaches the oversized-event path. While a backlog drains, the endpoint receives a `throughSeq` behind the Session's current tip. Preparation failures, acceptance failures, and provider rejections still fail the model request. +A backlog drains at up to 8 MiB per accepted request by default. At the end-to-end rate measured for the 269 MiB upload, about 8 MiB/s, an 8 MiB field adds about 1 s to each request while a backlog drains, and a 0.86 GB backlog drains in about 100 requests. In the same 96,341-event Session, the median per-step append is 11 KiB and the largest event is 414 KiB, so ordinary steps stay far below the limit and only an unusual event or a small configured limit reaches the oversized-event path. While a backlog drains, the endpoint receives a `throughSeq` behind the Session's current tip. Provider rejections still fail the model request; preparation and acceptance failures are logged and do not. Plugin tests cover the exact byte boundary, UTF-8 counting, backlog draining across accepted requests, the oversized-event warning with its unchanged watermark, an event past the string limit, and the 8 MiB default through plugin configuration. Adapter tests cover the base-body fallback through the provider plugin's logger and through an adapter without a reporter. diff --git a/.agents/notes/implemented/architecture/2026-09-24-bounded-session-log-upload.zh.md b/.agents/notes/implemented/architecture/2026-09-24-bounded-session-log-upload.zh.md index 13dd90ed0a..8e2d6d4785 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-bounded-session-log-upload.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-24-bounded-session-log-upload.zh.md @@ -25,6 +25,6 @@ DeepSeek 适配器把合并后请求正文的序列化失败视为扩展失败 ## 后果 -默认情况下,积压按每次已接受请求最多 8 MiB 补传。按那次 269 MiB 上传实测的端到端速度(约 8 MiB/s),补传期间 8 MiB 的字段让每次请求多约 1 秒,0.86 GB 的积压约 100 次请求补完。在同一个 96,341 条事件的会话中,每步追加量的中位数是 11 KiB,最大单条事件是 414 KiB,因此普通步骤远低于上限,只有异常事件或很小的配置上限才会走到超限事件路径。积压补传期间,端点收到的 `throughSeq` 会落后于会话当前末尾。准备失败、接受失败与提供方拒绝仍会使模型请求失败。 +默认情况下,积压按每次已接受请求最多 8 MiB 补传。按那次 269 MiB 上传实测的端到端速度(约 8 MiB/s),补传期间 8 MiB 的字段让每次请求多约 1 秒,0.86 GB 的积压约 100 次请求补完。在同一个 96,341 条事件的会话中,每步追加量的中位数是 11 KiB,最大单条事件是 414 KiB,因此普通步骤远低于上限,只有异常事件或很小的配置上限才会走到超限事件路径。积压补传期间,端点收到的 `throughSeq` 会落后于会话当前末尾。提供方拒绝仍会使模型请求失败;准备失败与接受失败只记录告警,不会使请求失败。 插件测试覆盖精确字节边界、UTF-8 计数、跨已接受请求的积压补传、超限事件告警及其不变的水位、超过字符串上限的事件,以及经插件配置生效的 8 MiB 默认值。适配器测试覆盖经提供方插件 logger 报告的基础正文回退,以及没有 reporter 的适配器上的同一回退。 diff --git a/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.i18n.yaml new file mode 100644 index 0000000000..71c61113a6 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-09-24-deepseek-account-remote-model-catalog.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-24-deepseek-account-remote-model-catalog.md +/agent-note-deepseek-account-models-come-from-the-account-listing-and-gate-by-client-version: + en: e6d82714ac89a7ae + zh: 54c14278e749e7e1 +/agent-note-deepseek-account-models-come-from-the-account-listing-and-gate-by-client-version/problem: + en: 2eeb916eb65c66e7 + zh: 7bf5c0abb8bb61e4 +/agent-note-deepseek-account-models-come-from-the-account-listing-and-gate-by-client-version/decision: + en: 42e800c4cd3b6ebe + zh: 06fabe5a9681fa27 +/agent-note-deepseek-account-models-come-from-the-account-listing-and-gate-by-client-version/alternatives-considered: + en: 7c7880fdb0cc95f6 + zh: 2b8a539192626789 +/agent-note-deepseek-account-models-come-from-the-account-listing-and-gate-by-client-version/consequences: + en: 352ece6c2decaaf7 + zh: 1d0c3620fd26a35c diff --git a/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.md b/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.md new file mode 100644 index 0000000000..75265db1ce --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.md @@ -0,0 +1,36 @@ +# Agent Note: DeepSeek account models come from the account listing and gate by client version + +Status: implemented + +English | [中文](2026-09-24-deepseek-account-remote-model-catalog.zh.md) + +## Problem + +The account route's catalog was deployment configuration: a build advertised the models it shipped with, a new model reached users only through a release, and nothing kept an older build from requesting a model it cannot drive. The account service publishes per-account model metadata at `GET /models`, and that listing can name models an older build does not understand. + +## Decision + +- [`llm-deepseek-account`](../../../../packages/llm/llm-deepseek-account/README.md) loads the listing lazily for each credential, waits for it once up to `modelsTimeoutMs`, refreshes it in the background after `modelsMaxAgeMs`, keeps the last good listing when a load fails or returns no model, and serves the bundled catalog before any listing loads. The cache lives in memory and is keyed by endpoint and token fingerprint, so per-account rollouts stay separate. +- A listed model is available when its `client_requirements["deepseek-harness"].min_version` is at most the current DeepSeek Harness version in semantic-version order. Without that declaration, only ids the built-in catalog knows are available; the others stay hidden, because a client cannot tell which future version supports them. A request for a refused listed model fails before network I/O with `CLIENT_UPGRADE_REQUIRED` or `MODEL_UNSUPPORTED`. +- Listed capabilities replace bundled ones field by field; the bundled entry keeps client-side knowledge such as tool-update mode and image budgets; `modelOverrides` applies last and reuses the `models` entry fields and validation. `max_output_tokens` bounds the request default instead of becoming it. +- The shared transport gains only two provider hooks, `connect` and `admit`; listing, gating, and merging stay in the account package. + +## Alternatives considered + +**Server-side filtering by client version only.** Codex sends `client_version` and lets its backend drop models. An older build then cannot show that a newer version supports a model, and a listing that omits a declaration would expose an unknown model. + +**Default parameters for unknown models.** Reasonix and Pi drive unknown ids with generic defaults, and MiniMax treats that as a defect. A model that needs client changes would run with the wrong behavior. + +**Whole-listing validation.** Codex, ZCode, and Kimi reject the whole listing on one bad field. One malformed row would then send every account back to the bundled catalog. + +**Persisting the last good listing.** A durable cache adds a persistence format and its migration duty; the bundled catalog already covers offline starts. + +**Keeping `models` with merge-by-id semantics.** The API-key route's `models` replaces its catalog, so the same field name with merge semantics would invert its meaning between sibling routes. + +**Generalizing the shared transport.** Per-model effort levels, an output-capability field, and catalog-change announcements would widen the Messages package for one consumer. The listed effort levels match the bundled defaults, and a model that needs different ones needs a release, which the gate enforces. + +## Consequences + +- An older build never offers a model it does not know unless the service declares a minimum version that build satisfies, and the service must declare `min_version` for a future build to show that an upgrade enables a model. +- A modified client can still request any id; the service enforces version floors only if it rejects such requests itself. +- The first account access after sign-in may wait up to `modelsTimeoutMs`; an offline start uses bundled capabilities until a listing loads; a listing change during a running process reaches the Web picker at its next catalog refresh. diff --git a/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.zh.md b/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.zh.md new file mode 100644 index 0000000000..7199091c73 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-24-deepseek-account-remote-model-catalog.zh.md @@ -0,0 +1,36 @@ +# Agent Note: DeepSeek 账号模型来自账号列表,并按客户端版本门控 + +Status: implemented + +[English](2026-09-24-deepseek-account-remote-model-catalog.md) | 中文 + +## 问题 + +账号路由的目录原本是部署配置:每个构建只提供它发布时自带的模型,新模型只能随发版到达用户,也没有办法阻止旧构建请求它驱动不了的模型。账号服务在 `GET /models` 上按账号发布模型元数据,这份列表可能包含旧构建不认识的模型。 + +## 决策 + +- [`llm-deepseek-account`](../../../../packages/llm/llm-deepseek-account/README.zh.md) 按凭据懒加载列表,首次访问最多等待 `modelsTimeoutMs`,超过 `modelsMaxAgeMs` 后在后台刷新;获取失败或返回的列表中没有模型时保留上一份,还没有加载到任何列表时使用内置目录。缓存只在内存中,以端点和 token 指纹为键,因此按账号灰度互不干扰。 +- 列出的模型在其 `client_requirements["deepseek-harness"].min_version` 按 semver 顺序不高于当前 DeepSeek Harness 版本时可用。没有这个声明时,只有内置目录认识的 id 可用,其余保持隐藏,因为客户端无法判断将来哪个版本会支持它们。请求被拒绝的已列出模型时,在网络请求之前以 `CLIENT_UPGRADE_REQUIRED` 或 `MODEL_UNSUPPORTED` 失败。 +- 列表中的能力逐字段覆盖内置能力;内置条目保留工具更新模式、图片预算等客户端知识;`modelOverrides` 最后叠加,复用 `models` 条目的字段与校验。`max_output_tokens` 只限制请求默认值,不直接成为默认值。 +- 共享传输层只新增 `connect` 与 `admit` 两个提供方钩子;列表、门控与合并都留在账号包中。 + +## 考虑过的替代方案 + +**只在服务端按客户端版本过滤。** Codex 发送 `client_version`,由后端去掉模型。这样旧构建无法提示新版本支持某个模型,而且列表漏掉声明时会暴露未知模型。 + +**未知模型套用默认参数。** Reasonix 和 Pi 用通用默认值驱动未知 id,MiniMax 把这种做法当作缺陷。需要客户端改动的模型会以错误的方式运行。 + +**整份列表严格校验。** Codex、ZCode 和 Kimi 会因为一个坏字段拒绝整份列表。一条格式错误的记录就会让所有账号退回内置目录。 + +**持久化上一次成功的列表。** 持久缓存要新增持久化格式并承担迁移责任;内置目录已经覆盖离线启动。 + +**保留 `models` 并改为按 id 合并。** API key 路由的 `models` 会替换整个目录,同名字段在兄弟路由上改成合并语义会让含义相反。 + +**扩展共享传输层。** 按模型的推理档位、输出能力字段和目录变更通知,会为一个使用方扩大 Messages 包的范围。列表中的推理档位与内置默认值一致;需要不同档位的模型需要发版适配,门控正是用来保证这一点。 + +## 影响 + +- 旧构建永远不会提供它不认识的模型,除非服务端声明了该构建满足的最低版本;服务端必须声明 `min_version`,将来的构建才能提示升级后可用。 +- 改过的客户端仍然可以请求任意 id;只有服务端自己拒绝这类请求时,版本下限才会被强制执行。 +- 登录后的第一次账号访问最多等待 `modelsTimeoutMs`;离线启动在加载到列表之前使用内置能力;进程运行中途的列表变化要等 Web 选择器下一次刷新目录时才会显示。 diff --git a/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.i18n.yaml index 7c2ed58b01..01a5ad7732 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.i18n.yaml @@ -15,8 +15,8 @@ en: 5cfe619038339caa zh: c2d2651d304d867c /agent-note-preset-scoped-schedule-tools/consequences: - en: 546d83d28487d1c1 - zh: 438922cd4f3ff9ec + en: d7c7e6b8e6268559 + zh: 801e5be70e00cc90 /agent-note-preset-scoped-schedule-tools/testing: - en: 1c5f34cf30a24fd7 - zh: 6f7a372de52d0ecd + en: d42cb866907a96b5 + zh: 6e66f8babe744bcb diff --git a/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.md b/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.md index c0b1b34412..169f3bea52 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.md +++ b/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.md @@ -26,9 +26,9 @@ English | [中文](2026-09-24-preset-scoped-schedule-tools.zh.md) - Each preset that mounts the row pays the four schemas' fixed token cost, and tool availability is read from the composition instead of inferred from the Host service's presence. - A deployment can mount `dsh-schedule` for storage and delivery without granting its agents model-driven reminder management. - `dsh-schedule` injects no `ctx.tools` and registers no model-facing tool. -- A delegated child cannot use the four tools through either layer: the `tool-subagent` and `tool-subagent-fork` rows in `standard`, `cordis`, and `ptc` deny all four names through `toolFilter`, and the provider applies that filter in the child scope through `ctx.tools.restrict()`, so the tools leave the child's prompt; `subagentCallerRefusal` in `dsh-tool-schedule` independently returns `{ code: 'subagent_session', message: 'A delegated subagent cannot use reminders.' }` from every one of the four tools when the caller's delegation depth is above zero, so a call that reaches a tool anyway is refused. +- A delegated child inherits the preset's four reminder schemas. `subagentCallerRefusal` in `dsh-tool-schedule` returns `{ code: 'subagent_session', message: 'A delegated subagent cannot use reminders.' }` from each tool when the caller's delegation depth is above zero. The [preset composition decision](../simplification/2026-10-09-preset-owned-subagent-composition.md) removes the redundant child filter; visibility does not authorize execution. - A Session a delegated child owns can never receive a delivered reminder, so `ScheduleService.create` and `ScheduleService.update` refuse it with `subagent_session`. The refusal reads the delegation depth — the accounting the delegation cap itself enforces, carried by the persisted session header across a cold resume. The rule sits in the service, so other consumers reach it too — the Automation surface included. ## Testing -`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` pins the four definitions and their error mapping, including `refuses every tool for a delegated child caller`. `apps/cli/tests/web-agent-presets.e2e.ts` asserts the `minimal` preset's tool list, and `snapshots/web/minimal-preset/tool-schemas.expected.json` records its bash-only tool table. `packages/schedule/schedule/tests/subagent-ownership.spec.ts` pins the delegation-depth refusal, and `scripts/optional-bundles.spec.ts` asserts that both delegation rows in the three presets deny all four tool names. +`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` pins the four definitions and their error mapping, including `refuses every tool for a delegated child caller`. `apps/cli/tests/web-agent-presets.e2e.ts` asserts the `minimal` preset's tool list, and `snapshots/web/minimal-preset/tool-schemas.expected.json` records its tool table without reminder schemas. `packages/schedule/schedule/tests/subagent-ownership.spec.ts` pins the delegation-depth refusal, and `scripts/optional-bundles.spec.ts` asserts that both delegation rows in the three presets omit `toolFilter`. The Web preset e2e also checks equal parent/child tool schemas and refusal from all four reminder executors for fresh and seeded children. `snapshots/web/subagent-fork-schedule` records all four refusals in a seeded fork through the shipped Web composition and shares the standard preset's prompt and schema pins. diff --git a/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.zh.md b/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.zh.md index bb9a8c0894..75b41d8b9e 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.zh.md @@ -26,9 +26,9 @@ Status: implemented - 挂载该行的每个 preset 承担四个 schema 的固定 token 成本,工具可用性取自组合,而不是由宿主服务是否存在推断。 - 部署可以只为存储与投递挂载 `dsh-schedule`,而不授予其 Agent 由模型驱动的提醒管理能力。 - `dsh-schedule` 不注入 `ctx.tools`,也不注册任何面向模型的工具。 -- 被委派的子 agent 无法通过两道中的任何一道使用这四个工具:`standard`、`cordis` 与 `ptc` 中的 `tool-subagent` 与 `tool-subagent-fork` 两行通过 `toolFilter` 拒绝全部四个名称,provider 会在子作用域内通过 `ctx.tools.restrict()` 应用该过滤,因此这些工具会从子 agent 的 prompt 中消失;`dsh-tool-schedule` 中的 `subagentCallerRefusal` 会在调用方委派深度大于零时,从四个工具中的每一个独立返回 `{ code: 'subagent_session', message: 'A delegated subagent cannot use reminders.' }`,因此即使某个调用仍能到达工具,也会被拒绝。 +- 被委派的子 agent 继承 preset 的四个提醒 schema。调用方委派深度大于零时,`dsh-tool-schedule` 中的 `subagentCallerRefusal` 从每个工具返回 `{ code: 'subagent_session', message: 'A delegated subagent cannot use reminders.' }`。[preset 组装决策](../simplification/2026-10-09-preset-owned-subagent-composition.zh.md)移除了重复的子级过滤;可见性不授予执行权限。 - 被委派子 agent 拥有的 Session 永远收不到投递的提醒,因此 `ScheduleService.create` 与 `ScheduleService.update` 会以 `subagent_session` 拒绝它。该拒绝读取委派深度——委派封顶本身执行的记账,由持久化 session header 承载并跨冷恢复保留。这条规则在服务层,因此其它消费方(包括自动化任务页面)也会命中。 ## Testing -`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` 固定这四个定义及其错误映射,包括 `refuses every tool for a delegated child caller`。`apps/cli/tests/web-agent-presets.e2e.ts` 断言 `minimal` preset 的工具列表,`snapshots/web/minimal-preset/tool-schemas.expected.json` 记录其只含 `bash` 的工具表。`packages/schedule/schedule/tests/subagent-ownership.spec.ts` 固定委派深度拒绝,`scripts/optional-bundles.spec.ts` 断言三个 preset 的两行委派行都拒绝全部四个工具名。 +`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` 固定这四个定义及其错误映射,包括 `refuses every tool for a delegated child caller`。`apps/cli/tests/web-agent-presets.e2e.ts` 断言 `minimal` preset 的工具列表,`snapshots/web/minimal-preset/tool-schemas.expected.json` 记录其不含提醒工具 schema 的工具表。`packages/schedule/schedule/tests/subagent-ownership.spec.ts` 固定委派深度拒绝,`scripts/optional-bundles.spec.ts` 断言三个 preset 的两行委派行都不含 `toolFilter`。Web preset e2e 还检查父子工具 schema 相等,且四个提醒执行器对新建和带种子的子级均拒绝执行。`snapshots/web/subagent-fork-schedule` 通过出货 Web 组合记录带种子 fork 中的四次拒绝,并共享 standard preset 的提示和 schema 预期。 diff --git a/.agents/notes/implemented/architecture/2026-09-27-progressive-office-skills.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-27-progressive-office-skills.i18n.yaml new file mode 100644 index 0000000000..01cda717dd --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-27-progressive-office-skills.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-09-27-progressive-office-skills.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-27-progressive-office-skills.md +/agent-note-progressive-office-skills-with-ordinary-shell-execution: + en: 42e2f062c37e9ef1 + zh: 5cd3d421adec1cac +/agent-note-progressive-office-skills-with-ordinary-shell-execution/problem: + en: a9984a594cdac98d + zh: 38768e7699bc8d39 +/agent-note-progressive-office-skills-with-ordinary-shell-execution/decision: + en: d057c558d6b9803c + zh: acf3fdbc4cd7cee3 +/agent-note-progressive-office-skills-with-ordinary-shell-execution/alternatives-considered: + en: 8bca955255e6d982 + zh: bc313a4bcab3f6f9 +/agent-note-progressive-office-skills-with-ordinary-shell-execution/consequences: + en: cd4ff2423b2f5f9e + zh: 63135aeae9c46415 diff --git a/.agents/notes/implemented/architecture/2026-09-27-progressive-office-skills.md b/.agents/notes/implemented/architecture/2026-09-27-progressive-office-skills.md new file mode 100644 index 0000000000..a89b896fe6 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-27-progressive-office-skills.md @@ -0,0 +1,32 @@ +# Agent Note: Progressive Office skills with ordinary shell execution + +Status: implemented + +English | [中文](2026-09-27-progressive-office-skills.zh.md) + +## Problem + +Combined authoring and rendering instructions spend context on operations unrelated to ordinary editing. Rendering tool activation adds a second discovery path and durable state even though shell tools already own execution permissions and process management. A missing renderer can prevent loading otherwise usable editing guidance. + +## Decision + + +The [Office provider](../../../../packages/skill/skill-office/README.md) lists a compact router and six format-specific authoring or operation skills. The model loads full instructions by name and selects rendering for appearance-focused changes unless the user explicitly skips it. Rendering uses a private, randomly named temporary directory inside the task workspace and removes it after inspection. Skills invoke the shared Python checker and configured LibreOffice Kit CLI through ordinary Bash or PowerShell. SDK and Desktop own their Office composition separately; ordinary Web and the shared base do not mount these plugins. + +Carriers own interpreter and resource locations. Operation skills append the configured Node and CLI paths only when their bodies are loaded; authoring skills use the selected Python and shared checker resource. Loading instructions does not prepare engines or authoring payloads. Ordinary shell execution retains its existing permissions and process management. + +Office dependency ranges allow patch updates; the root lock records the resolved adapter and engine versions. + +## Alternatives considered + +**Keep a dedicated renderer tool.** A small typed schema constrains rendering arguments, but requires its own execution configuration, scoped registration, projection, and activation lifecycle. The CLI operation skills accept shell quoting and model-selected arguments in exchange for reusing the existing approval, sandbox, cancellation, and output mechanisms. + +**Hide subskills from the catalog.** This requires a generic visibility policy independent of invocation permission. Listing seven short summaries preserves the existing skill API while full instruction bodies remain demand-loaded. + +**Automatically inject guides for file extensions.** Extensions do not distinguish text edits, recalculation, conversion, and requested visual checks. Model-selected routing keeps unrelated operations out of context and permits explicit direct invocation. + +## Consequences + +Instruction loading appends ordinary logged skill results; completion does not erase them. Historical tool records remain readable and existing declaration reconciliation handles resumed sessions without a Session format change or agent-loop modification. A dedicated renderer would need a new independently justified user or security requirement before reintroduction. + +Verification covers catalog entries, denied and explicit invocation, authoring without executable paths, native/PTC requests, resume and fork, ordinary and minimal profile composition, resource packaging, context budgets, and real-model operation selection. Rendering failures preserve usable sources and stop visual checks; successful commands alone cannot establish usable images. diff --git a/.agents/notes/implemented/architecture/2026-09-27-progressive-office-skills.zh.md b/.agents/notes/implemented/architecture/2026-09-27-progressive-office-skills.zh.md new file mode 100644 index 0000000000..0aeb95eb1d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-27-progressive-office-skills.zh.md @@ -0,0 +1,32 @@ +# Agent Note: Office 技能渐进加载与普通 shell 执行 + +Status: implemented + +[English](2026-09-27-progressive-office-skills.md) | 中文 + +## 问题 + +合并的创作和渲染说明会为普通编辑无关的操作消耗上下文。渲染工具激活增加第二条发现路径和持久状态,而 shell 工具已经负责执行权限及进程管理。缺少渲染器也可能阻止加载原本可用的编辑指南。 + +## 决策 + + +[Office 提供者](../../../../packages/skill/skill-office/README.zh.md) 列出精简路由和六个各格式创作或操作技能。模型按名称加载完整说明;以外观为目标的修改会选择渲染,除非用户明确要求跳过。渲染使用任务工作区内随机命名的私有临时目录,并在检查后删除。技能通过普通 Bash 或 PowerShell 调用共享 Python 检查器和配置的 LibreOffice Kit CLI。SDK 和 Desktop 分别拥有 Office 组合;普通 Web 和共享 base 不挂载这些插件。 + +载体负责解释器和资源位置。操作技能仅在加载正文时附加配置的 Node 与 CLI 路径;创作技能使用选定的 Python 和共享检查器资源。加载说明不准备引擎或创作 payload。普通 shell 执行保留现有权限和进程管理。 + +Office 依赖范围允许补丁版本更新;根锁文件记录实际解析的适配器与引擎版本。 + +## 考虑过的替代方案 + +**保留专属渲染工具。** 小型类型化 schema 能约束渲染参数,但需要专属执行配置、作用域注册、投影和激活生命周期。CLI 操作技能接受 shell 引用和模型选择参数的成本,以复用现有审批、沙箱、取消及输出机制。 + +**从目录隐藏子技能。** 这需要独立于调用权限的通用可见性策略。列出七条简短摘要可保留现有技能 API,完整说明仍按需加载。 + +**按文件扩展名自动注入指南。** 扩展名无法区分文本编辑、重计算、转换和用户要求的视觉检查。模型选路使无关操作不进入上下文,并允许显式直接调用。 + +## 影响 + +说明加载追加普通的已记录技能结果;操作完成不会擦除这些结果。历史工具记录仍可读取,恢复会话使用现有声明更新机制,无需修改 Session 格式或 agent loop。重新引入专属渲染器需要新的、独立成立的用户或安全要求。 + +验证覆盖目录条目、拒绝及显式调用、无可执行文件路径时的创作、native/PTC 请求、恢复和 fork、常规及 minimal 组合、资源打包、上下文预算和真实模型操作选择。渲染失败时保留可用源文件并停止视觉检查;命令成功本身不能证明图片可用。 diff --git a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml new file mode 100644 index 0000000000..ddd6d80912 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-09-29-explicit-session-history-preparation.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-29-explicit-session-history-preparation.md +/agent-note-open-the-session-when-migration-is-required: + en: d409772933407317 + zh: ac258a6d1743965f +/agent-note-open-the-session-when-migration-is-required/problem: + en: ab63c8127d68d294 + zh: d3f99489c96ff1d4 +/agent-note-open-the-session-when-migration-is-required/decision: + en: 32627d744a6e7410 + zh: 2836a95ee5390111 +/agent-note-open-the-session-when-migration-is-required/alternatives-considered: + en: baea781018a49252 + zh: bcc452029bf229fd +/agent-note-open-the-session-when-migration-is-required/consequences: + en: 979eebb53a6bf711 + zh: 013743b0b7a000ce diff --git a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md new file mode 100644 index 0000000000..84b30b6cb4 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md @@ -0,0 +1,43 @@ +# Agent Note: Open the Session when migration is required + +Status: implemented + +English | [中文](2026-09-29-explicit-session-history-preparation.zh.md) + +## Problem + +Expanding a subagent catalog or forking from the sidebar can trigger an old Session's format migration. + +## Decision + +The WorkspaceBrowser row-menu fork request carries `allowMigration: false`, which the Host handles by checking `stat` format information before calling the original fork flow. Only a source format requiring migration is refused, with an app-wide Toast offering to open the original Session. That action only navigates and does not retry fork. Neither an absent live Session nor unopened Client history justifies refusal. + +Other fork callers omit that option and allow automatic migration. + +`session.projections` also checks the stored format first; current-format cold history still uses the original observation flow for exact projections. Success returns `kind: sequenced` and its real `asOfSeq`; required migration returns `kind: migration-required` hints. The Client retains that read state, and cached values cannot replace sequenced values published by history or control. + +The `formatStatus` returned by `stat` carries the migration library's existing classification; `header` remains the current logical format. It describes the stored format, not migration-task progress or prepared in-memory history. + +When migration is required and `subagentCatalog` is absent, Web marks the Session's row “Migration required” and keeps its history-opening actions without descendant expansion or changing its subagent mode. Opening the Session supplies its catalog through history and control projections. Available catalogs remain usable, including empty catalogs. Session-list lineage resolves navigation addresses, not missing catalog membership. Ordinary loading, cancellation, and storage errors do not become this migration branch. + +Create/adopt, full-text search, and ordinary history opening allow automatic migration. + +This decision adds a migration exception to [catalog projection reads](../../archived/simplification/2026-09-08-web-subagent-catalog-projections.md). Exact reads and leases in [Session observations](2026-08-25-session-observations-and-projection-owned-client-state.md), and identity checks and cached/sequenced ordering in [projection-cache reads](2026-09-19-projection-cache-listing-identity-and-cached-rows.md), still apply. + +## Alternatives considered + +**Treat every cold Session as needing migration.** Residency and stored format are different; this would reject otherwise valid forks and discard catalog information available on disk. + +**Globally forbid forks that automatically migrate on the Host.** The sidebar's interaction choice does not govern other callers, so its request explicitly carries the restriction. + +**Automatically open and retry the sidebar fork.** Opening is an explicit user action, and fork does not run automatically after migration. + +**Derive catalogs from Session-list parent ids.** This adds a second membership derivation; explicit Session opening obtains the catalog. + +**Give cached hints `asOfSeq: -1`.** Hints have no event cut in current history and cannot participate in sequence comparisons. + +## Consequences + +Sessions requiring migration use the existing opening flow to prepare history; Sessions that need no migration remain cold-readable and forkable. Catalog hints may lag the log and yield to subsequent exact projections. + +A separate follow-redirection proposal discusses future single-Session migration progress; this decision does not implement that flow. diff --git a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md new file mode 100644 index 0000000000..31925f7a9f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md @@ -0,0 +1,43 @@ +# Agent Note: 需要迁移时引导打开会话 + +Status: implemented + +[English](2026-09-29-explicit-session-history-preparation.md) | 中文 + +## 问题 + +展开 subagent 目录或从侧栏 fork 可能触发旧会话的格式迁移。 + +## 决定 + +WorkspaceBrowser 行菜单的 fork 请求携带 `allowMigration: false`,由 Host 在调用原 fork 流程前检查 `stat` 的格式信息。只有源格式需要迁移时才拒绝,并显示带“打开原会话”操作的应用级 Toast。该操作只导航,不自动重发 fork。没有 live Session 或 Client 尚未打开历史不构成拒绝理由。 + +其他 fork 调用者省略该选项,允许自动迁移。 + +`session.projections` 同样先检查存储格式,当前格式冷历史继续通过原观察流程读取准确投影。成功时返回 `kind: sequenced` 和真实 `asOfSeq`;需要迁移时返回 `kind: migration-required` 的缓存提示。Client 保留这一读取状态,缓存值不能覆盖 history 或 control 已发布的有序值。 + +`stat` 返回的 `formatStatus` 携带迁移库已有的分类;`header` 仍是当前逻辑格式。它描述存储格式,不描述迁移任务进度或内存准备缓存。 + +在需要迁移且缺少 `subagentCatalog` 时,Web 将该会话行标为“需要迁移”,保留打开历史的操作,但不能展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。 + +create/adopt、全文搜索和普通历史打开允许自动迁移。 + +本决策为[目录投影查询](../../archived/simplification/2026-09-08-web-subagent-catalog-projections.md)增加迁移例外。[会话观察](2026-08-25-session-observations-and-projection-owned-client-state.zh.md)的准确读取和租约,以及[投影缓存读取](2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md)的身份校验与缓存/有序分层继续适用。 + +## 考虑过的替代方案 + +**把所有冷会话都视作需要迁移。** 是否驻留与存储格式不同;这样会拒绝可以正常完成的 fork,并丢失能够从磁盘读取的目录信息。 + +**Host 全局禁止自动迁移的 fork。** 侧栏的交互选择不适用于其他调用者,因此限制由该请求显式携带。 + +**侧栏 fork 自动打开并重试。** 打开会话由用户明确选择,fork 不在迁移后自动执行。 + +**按会话列表中的父 id 派生目录。** 这需要第二套成员派生逻辑;显式打开会话即可获取目录。 + +**让缓存提示携带 `asOfSeq: -1`。** 提示没有当前历史的事件切点,不能参与序号比较。 + +## 影响 + +需要迁移的会话通过现有打开流程完成准备;无需迁移的会话仍可冷读和 fork。目录的缓存提示可能落后于日志,后续准确投影替换它们。 + +后续单会话迁移进度由独立的 follow 重定向提案讨论,本决策不实现该流程。 diff --git a/.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.i18n.yaml index 0187f43093..aa017c7b03 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.i18n.yaml @@ -12,23 +12,23 @@ en: a15c7c13f167e5ac zh: a15c7c13f167e5ac /agent-note-refresh-runtime-resolution-after-package-operations-and-expire-hmr-package-configuration/decision/responsibilities: - en: 3ffd0c78fa204b04 - zh: f468bab00a7ff357 + en: d53a850a2deabc08 + zh: 01c2f735f2a9562a /agent-note-refresh-runtime-resolution-after-package-operations-and-expire-hmr-package-configuration/decision/runtime-resolution: - en: ca45b973e1968533 - zh: 002f23bb70e4fed7 + en: 42a3ed903fbb5483 + zh: 7e1f6df1137794c3 /agent-note-refresh-runtime-resolution-after-package-operations-and-expire-hmr-package-configuration/decision/plugin-manager: - en: 9b04926c175f22e8 - zh: fbf05dd4065b0738 + en: 7ec1ad2a691bbd12 + zh: 01057bbe0240056a /agent-note-refresh-runtime-resolution-after-package-operations-and-expire-hmr-package-configuration/decision/hmr-package-configuration-expiry: en: c7de8dafe47a5587 zh: 6010a70d8451edd1 /agent-note-refresh-runtime-resolution-after-package-operations-and-expire-hmr-package-configuration/decision/future-work: - en: 31818f8f7f80470b - zh: ecb7ac85bb49cf6d + en: 8b5faf72418a43dd + zh: 3d676c9b54697a2a /agent-note-refresh-runtime-resolution-after-package-operations-and-expire-hmr-package-configuration/alternatives-considered: - en: 7c1c6d21570cda0d - zh: e6f8334c85f1b404 + en: f04a27b3525180b0 + zh: 9f3a01d0400c5a88 /agent-note-refresh-runtime-resolution-after-package-operations-and-expire-hmr-package-configuration/verification: en: 939cedceed200cb2 zh: c7bb02d0da400c8d diff --git a/.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.md b/.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.md index b1b86be199..83612801d2 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.md +++ b/.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.md @@ -17,9 +17,9 @@ Two pieces of Host state did not follow changes while the process ran: | Owner | Does | Does not | |---|---|---| -| resolver (`app-boot/src/profile-resolution/resolver.ts`) | `replace()` allows removing `scope: profile` entries and profile-local names | Touch any Node cache | -| plugin-manager | Calls `pluginPackages.refresh()` at fixed points of package operations | Construct resolutions or manage module and package-configuration caches | -| HMR (`packages/boot/hmr`) | Expires package configuration and preserves ordinary reloads for manifests loaded as JSON modules | Reload plugins for configuration-only manifests; handle `node_modules` package replacement | +| resolver (`app-boot/src/profile-resolution/resolver.ts`) | `replace()` allows removing `scope: profile` entries and profile-local names, and changing a retained profile entry's version in place | Touch any Node cache | +| plugin-manager | Without HMR, calls `pluginPackages.refresh()` at fixed points of package operations; with HMR, leaves publication to its recomposition | Construct resolutions or manage module and package-configuration caches | +| HMR (`packages/boot/hmr`) | Expires package configuration and preserves ordinary reloads for manifests loaded as JSON modules; replaces plugins whose loaded package files changed during recomposition ([replacement Note](2026-10-01-replace-changed-package-modules-on-recomposition.md)) | Reload plugins for configuration-only manifests | ### Runtime resolution @@ -29,20 +29,18 @@ Validation of a new generation in `replace()`: - `scope: profile` entries may be removed. - Profile-local package names may be removed. -- Retained profile entries keep their normalized directory, version, and scope, but may change declaring anchor when another selected bundle supplies the same package. Installation mappings and declaring anchors remain unchanged. The profile scope cannot change; a new local name cannot override an existing entry; a published link name cannot select another real directory. +- Retained profile entries keep their normalized directory and scope, but may change declaring anchor when another selected bundle supplies the same package, and may change version when the package is upgraded in place ([replacement Note](2026-10-01-replace-changed-package-modules-on-recomposition.md)). Installation mappings and declaring anchors remain unchanged. The profile scope cannot change; a new local name cannot override an existing entry. A published link name may select another real directory; Node's cached real paths of the previous one are relocated. ### Plugin Manager | Operation | Publication point | |---|---| -| Install a new package | After pnpm succeeds and the bundle selection is saved, before reconciliation, whether or not the bundle is enabled | -| Overwrite an installed package | No publication; the result is `restart-required` | -| Enable a bundle | After the selection is saved, before reconciliation | -| Disable a bundle | With HMR, after reconciliation stops its plugins; without HMR, no publication, and running plugins keep the current table | -| Remove | After pnpm remove succeeds, inside the HMR transaction | -| Failed or cancelled install, failed removal | No publication | +| Install, enable, disable or remove with HMR | Inside HMR's recomposition, after the rows the generation drops stopped and before the generation applies ([replacement Note](2026-10-01-replace-changed-package-modules-on-recomposition.md)) | +| Install a new package or enable a bundle without HMR | After the profile files are saved, before reconciliation | +| Remove without HMR | After pnpm remove succeeds | +| Disable without HMR, an install over an installed package, a failed or cancelled install, a failed removal | No publication; an install over a package the spec names is refused before pnpm runs | -`createRuntimeResolution()` returns a `ProfileRuntimeResolution`, which privately keeps the installation anchor, Harness home, and profile directory it was computed from. Its `computeLatestResolution()` rereads that profile with the same inputs and returns a new object for the latest generation, leaving the original unchanged; Workers receive only the table fields. `PluginPackages.refresh()` calls the current resolution's `computeLatestResolution()` and then `replace()`; a resolution constructed as plain data cannot be refreshed and makes the call throw. +`createRuntimeResolution()` returns a `ProfileRuntimeResolution`, which privately keeps the installation anchor, Harness home, and profile directory it was computed from. Its `computeLatestResolution()` rereads that profile with the same inputs and returns a new object for the latest generation, leaving the original unchanged; Workers receive only the table fields. `PluginPackages.refresh()` calls the current resolution's `computeLatestResolution()` and then `replace()`; a resolution constructed as plain data cannot be refreshed and makes the call throw. app-boot's `recomposeProfile()` first stops the rows the generation no longer lists, so their plugins dispose while their packages are still mapped, then publishes the latest generation once; a table that is already published is not published again. Without HMR, deselecting a startup bundle does not stop its plugins. While such a bundle remains deselected, later package operations keep the existing runtime table instead of publishing its removal. Other no-HMR installations and removals of non-running bundles still publish normally. @@ -79,7 +77,7 @@ The binding's `getNearestParentPackageJSON` is called only by `package_json_read ### Future Work -- Online replacement inside `node_modules`, same-path reinstall, changed link targets, and cross-package reload propagation remain unsupported. Package updates need process restart; this does not guarantee that every management result already reports that requirement correctly. +- A retained profile mapping that moves to another directory waits for a restart; Plugin Manager moves a package by removing and installing it. In-place replacement inside `node_modules` is handled by the [replacement Note](2026-10-01-replace-changed-package-modules-on-recomposition.md). - TSX versions using an asynchronous loader thread keep that thread's package configuration outside these hooks. Synchronizing it is deferred; this change does not provide general Worker cache synchronization. - CommonJS private-request-cache refresh with registered synchronous resolve hooks is deferred. Those requests retain their original loader behavior. - Disposing HMR restores the native readers, whose previous cached configuration can become visible again. Preserving invalidation state across HMR replacement is deferred. @@ -90,7 +88,7 @@ The binding's `getNearestParentPackageJSON` is called only by `package_json_read **Reread every observed manifest when runtime resolution publishes (#5496).** This places package-configuration expiry in table publication, decoupled from module caches: overwriting an installed package reports restart, yet the next unrelated publication makes new imports load the new version while the old plugin still runs. Package configuration is content and belongs with module caches, in HMR. -**Let HMR reload packages inside `node_modules`.** It requires finding affected plugins over a module graph that includes `node_modules`, preventing duplicate evaluation of shared libraries and Cordis, and handling missing dynamic-import edges, module side effects, and Workers. It is not done here; those scenarios keep requiring restart. +**Let HMR reload packages inside `node_modules`.** It requires finding affected plugins over a module graph that includes `node_modules`, preventing duplicate evaluation of shared libraries and Cordis, and handling missing dynamic-import edges, module side effects, and Workers. It is not done here; the [replacement Note](2026-10-01-replace-changed-package-modules-on-recomposition.md) adds it at profile recomposition. **Reload every plugin for a package.json change.** Configuration-only manifests do not require module evaluation. Manifests actually imported as JSON modules retain ordinary dependency-driven reloads. diff --git a/.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.zh.md b/.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.zh.md index 9ee201f27a..6f19b5fa4a 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.zh.md @@ -17,9 +17,9 @@ Host 运行期间有两处状态没有随变化更新: | 负责方 | 做什么 | 不做什么 | |---|---|---| -| resolver(`app-boot/src/profile-resolution/resolver.ts`) | `replace()` 允许移除 `scope: profile` 条目和 profile 本地包名 | 不碰 Node 的任何缓存 | -| plugin-manager | 在包操作的确定时点调用 `pluginPackages.refresh()` | 不构造 resolution;不管模块缓存与包配置缓存 | -| HMR(`packages/boot/hmr`) | 使包配置失效,并保留作为 JSON 模块加载的 manifest 的普通重载 | 不因仅作为配置的 manifest 重载插件;不处理 `node_modules` 包替换 | +| resolver(`app-boot/src/profile-resolution/resolver.ts`) | `replace()` 允许移除 `scope: profile` 条目和 profile 本地包名,并允许原地更改保留的 profile 条目的版本 | 不碰 Node 的任何缓存 | +| plugin-manager | 没有 HMR 时,在包操作的确定时点调用 `pluginPackages.refresh()`;有 HMR 时,把发布交给其重新组合 | 不构造 resolution;不管模块缓存与包配置缓存 | +| HMR(`packages/boot/hmr`) | 使包配置失效,并保留作为 JSON 模块加载的 manifest 的普通重载;重新组合时替换已加载包文件发生变化的插件([替换说明](2026-10-01-replace-changed-package-modules-on-recomposition.zh.md)) | 不因仅作为配置的 manifest 重载插件 | ### runtime resolution @@ -29,20 +29,18 @@ Host 运行期间有两处状态没有随变化更新: - `scope: profile` 的条目可以移除。 - profile 本地包名可以移除。 -- 保留的 profile 条目保持规范化目录、版本与作用域不变;另一个已选 bundle 提供同一包时,可以更换声明锚点。安装范围的映射与声明锚点保持不变。profile 范围不能变;新本地包名不能覆盖已有条目;已发布的 link 名称不能换真实目录。 +- 保留的 profile 条目保持规范化目录与作用域不变;另一个已选 bundle 提供同一包时,可以更换声明锚点;包被原地升级时,可以更改版本([替换说明](2026-10-01-replace-changed-package-modules-on-recomposition.zh.md))。安装范围的映射与声明锚点保持不变。profile 范围不能变;新本地包名不能覆盖已有条目。已发布的 link 名称可以选中其他真实目录;Node 缓存的原目录真实路径会被重新定位。 ### plugin-manager | 操作 | 发布时点 | |---|---| -| 安装新包 | pnpm 成功、保存 bundle 选择之后,reconciliation 之前;无论是否立即启用都发布 | -| 覆盖已安装的包 | 不发布,结果为 `restart-required` | -| 启用 bundle | 保存选择后发布,再做 reconciliation | -| 停用 bundle | 有 HMR 时,reconciliation 让插件退出后再发布;没有 HMR 时不发布,运行中的插件继续使用原表 | -| 卸载 | pnpm remove 成功后,在 HMR 事务内发布 | -| 安装失败、取消、卸载失败 | 不发布 | +| 有 HMR 时的安装、启用、停用或卸载 | 在 HMR 的重新组合内,新一代丢弃的行停止之后、新一代应用之前([替换说明](2026-10-01-replace-changed-package-modules-on-recomposition.zh.md)) | +| 没有 HMR 时安装新包或启用 bundle | 保存 profile 文件之后,reconciliation 之前 | +| 没有 HMR 时卸载 | pnpm remove 成功后 | +| 没有 HMR 时停用、覆盖已安装的包、安装失败或取消、卸载失败 | 不发布;spec 指明已安装的包时,覆盖安装在 pnpm 运行之前被拒绝 | -`createRuntimeResolution()` 返回 `ProfileRuntimeResolution`,它私有保存构造时的 installAnchor、home 和 profile 目录;`computeLatestResolution()` 用同一组输入重新读取 profile,返回表示最新代的新对象,原实例不变;Worker 只收到表数据。`PluginPackages.refresh()` 调用当前 resolution 的 `computeLatestResolution()` 再 `replace()`;以纯数据构造的 resolution 无法刷新,调用时抛错。 +`createRuntimeResolution()` 返回 `ProfileRuntimeResolution`,它私有保存构造时的 installAnchor、home 和 profile 目录;`computeLatestResolution()` 用同一组输入重新读取 profile,返回表示最新代的新对象,原实例不变;Worker 只收到表数据。`PluginPackages.refresh()` 调用当前 resolution 的 `computeLatestResolution()`,再调用 `replace()`;以纯数据构造的 resolution 无法刷新,调用时抛错。app-boot 的 `recomposeProfile()` 先停止新一代不再列出的行,使其插件在包仍有映射时完成释放,再发布一次最新一代;已发布的表不会再次发布。 没有 HMR 时,取消启动 bundle 的选择不会停止它的插件。只要该 bundle 仍未选中,后续包操作就保留当前 runtime 表,不发布其移除。其他无 HMR 的安装和未运行 bundle 卸载仍正常发布。 @@ -79,7 +77,7 @@ binding 的 `getNearestParentPackageJSON` 只被 `package_json_reader` 自己调 ### 后续工作 -- 不支持 `node_modules` 内在线替换、同路径重装、link 换目标及跨包重载传播。包更新需要重启进程;这不保证每个管理操作的结果都已正确报告这一要求。 +- 移动到其他目录的保留 profile 映射需要等待重启;Plugin Manager 通过卸载再安装来移动包。`node_modules` 内的原地替换由[替换说明](2026-10-01-replace-changed-package-modules-on-recomposition.zh.md)处理。 - 使用异步 loader 线程的 TSX 版本,其线程内包配置不受这些 hook 管理。线程同步留待后续;本次不提供通用 Worker 缓存同步。 - 注册了同步 resolve hooks 时,CommonJS 私有请求缓存刷新留待后续;这些请求保留原有 loader 行为。 - 销毁 HMR 会恢复原生 reader,其此前缓存的配置可能重新可见。跨 HMR 替换保留失效状态留待后续。 @@ -90,7 +88,7 @@ binding 的 `getNearestParentPackageJSON` 只被 `package_json_reader` 自己调 **在 runtime resolution 发布时全量重读已见过的 manifest(#5496)。** 它把包配置失效放进了绑定表发布,和模块缓存脱了钩:覆盖已安装的包时报需要重启,但下一次无关的发布会让新导入拿到新版本,旧插件仍在运行。包配置缓存属于内容,应该和模块缓存由同一方负责,也就是 HMR。 -**让 HMR 支持 `node_modules` 内的包重载。** 这需要沿包含 `node_modules` 的模块图确定受影响插件,防止共享库和 Cordis 被重复求值,还要处理动态 import 漏边、模块副作用和 Worker。本次不做,这些场景继续要求重启。 +**让 HMR 支持 `node_modules` 内的包重载。** 这需要沿包含 `node_modules` 的模块图确定受影响插件,防止共享库和 Cordis 被重复求值,还要处理动态 import 漏边、模块副作用和 Worker。本次不做;[替换说明](2026-10-01-replace-changed-package-modules-on-recomposition.zh.md)在 profile 重新组合时加入了这一能力。 **package.json 变化时重载所有插件。** 仅作为配置的 manifest 不要求模块求值。实际作为 JSON 模块导入的 manifest 保留普通的依赖驱动重载。 diff --git a/.agents/notes/implemented/architecture/2026-10-01-replace-changed-package-modules-on-recomposition.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-01-replace-changed-package-modules-on-recomposition.i18n.yaml new file mode 100644 index 0000000000..576319b255 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-01-replace-changed-package-modules-on-recomposition.i18n.yaml @@ -0,0 +1,34 @@ +# Bilingual-pair consistency record for 2026-10-01-replace-changed-package-modules-on-recomposition.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-01-replace-changed-package-modules-on-recomposition.md +/agent-note-replace-plugins-whose-loaded-package-files-changed-during-profile-recomposition: + en: 72fe06d4e304418d + zh: bc3c96e957889bc1 +/agent-note-replace-plugins-whose-loaded-package-files-changed-during-profile-recomposition/problem: + en: c43fb0d2df54b28f + zh: 6636548449663fc5 +/agent-note-replace-plugins-whose-loaded-package-files-changed-during-profile-recomposition/decision: + en: a15c7c13f167e5ac + zh: a15c7c13f167e5ac +/agent-note-replace-plugins-whose-loaded-package-files-changed-during-profile-recomposition/decision/one-recomposition-path: + en: f2874c3fc946cf7a + zh: 4c32b9f94e1f9709 +/agent-note-replace-plugins-whose-loaded-package-files-changed-during-profile-recomposition/decision/detecting-changed-modules: + en: 1fedf2dde87f41bf + zh: c2249267d1c2bc78 +/agent-note-replace-plugins-whose-loaded-package-files-changed-during-profile-recomposition/decision/replacing-them: + en: 6fe2cbe5aa3a9786 + zh: fe30fbf672ea8c21 +/agent-note-replace-plugins-whose-loaded-package-files-changed-during-profile-recomposition/decision/plugin-manager-and-runtime-resolution: + en: 794ed33204d91014 + zh: b08daa2a43cbe3b3 +/agent-note-replace-plugins-whose-loaded-package-files-changed-during-profile-recomposition/alternatives-considered: + en: a67d0c6bc4957060 + zh: 32e02ab45b8e71cc +/agent-note-replace-plugins-whose-loaded-package-files-changed-during-profile-recomposition/consequences: + en: 2cb3f39c6a910685 + zh: e14938c868390f39 +/agent-note-replace-plugins-whose-loaded-package-files-changed-during-profile-recomposition/verification: + en: d4750abb810faac2 + zh: 78c9c4d86d719b9b diff --git a/.agents/notes/implemented/architecture/2026-10-01-replace-changed-package-modules-on-recomposition.md b/.agents/notes/implemented/architecture/2026-10-01-replace-changed-package-modules-on-recomposition.md new file mode 100644 index 0000000000..f599d86407 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-01-replace-changed-package-modules-on-recomposition.md @@ -0,0 +1,86 @@ +# Agent Note: Replace plugins whose loaded package files changed during profile recomposition + +Status: implemented + +English | [中文](2026-10-01-replace-changed-package-modules-on-recomposition.zh.md) + +## Problem + +Node caches an evaluated module by file URL. A profile installs packages with pnpm's hoisted layout, so a package lives at `node_modules/` whatever its version. Overwriting, upgrading or reinstalling it keeps every file URL, and a later import or Loader entry restart returns the cached module of the previous version. The [package-refresh Note](2026-09-30-profile-package-refresh-and-manifest-invalidation.md) refreshes runtime resolution and package configuration but leaves this module cache; Plugin Manager therefore reported overwrites as `restart-required`, and a reinstall at the same path after removal reported `applied` while the previous version kept running. A `link:` development package hits the same cache whenever its build output changes, unless its directory is listed in HMR's source watch roots. + +## Decision + +### One recomposition path + +`Hmr.reconcileProfile()` is the profile recomposition used by HMR's profile watches and by Plugin Manager; the Config Editor still recomposes through app-boot directly. It runs inside `runExclusive()`. Plugin Manager only edits profile files and runs pnpm, and refuses to install over an installed package it can name before pnpm runs; another version is a removal and an installation, each with its own recomposition. The steps of a recomposition are: + +1. Read the profile patches and compare loaded modules below the profile directory and its linked package targets with disk. +2. Plan the replacement as below; a patch read or comparison failure throws or is reported before any module changes. +3. Evict the replaceable changed modules and their importers. A changed module whose importers reach the process entry point's static graph or a plugin that no Loader entry owns stays loaded with its importers; the other changes proceed. +4. Stop the Loader entries running the replaced plugins by deleting their runtimes, so the Loader does not record them as disabled. +5. Call app-boot's `recomposeProfile()` once with the entries that ran before the stops. It records the activation state, stops the rows the generation no longer lists by removing them from their groups, publishes the runtime resolution, runs the compatibility preflight against the published packages, and applies the generation. The Loader imports the current files when it starts an entry: rows the generation keeps start once with the new code and their new configuration; rows it disables, refuses or removes stay stopped and never run the new code; an entry it inserts links against the current files. Stopped entries the update did not try to start, below an unchanged Include or outside the profile composition, start afterwards; an entry whose import failed during the update is imported once more. Activation is judged: a stopped entry that failed afterwards fails the operation, while an entry waiting for a service is a warning, since it starts once a provider appears. If no generation applied, the published resolution and the stopped rows are restored, and the stopped entries start again. +6. Evict the loaded modules below the directories of the mappings the recomposition dropped, so a removed or deselected package, including its dynamically imported dependencies, is imported afresh when it returns. A bundle switched off while its package stays mapped keeps its unchanged modules. + +### Detecting changed modules + +[`ModuleFiles`](../../../../packages/boot/hmr/src/module-files.ts) records inode, size and modification time for the loaded ES and CommonJS modules below the profile directory and the real directories of its linked packages. Modules of the dsh installation are outside this scope. Change time is excluded: pnpm imports packages by hard link from its store, and adding a link elsewhere changes a loaded file's change time without changing its content. Records are taken at application readiness, after each recomposition, and for modules a source reload evaluated again. A recomposition records the identities it read before replacing anything, so a write during the recomposition stays detectable; modules first loaded during it are recorded after settlement to avoid an unnecessary restart during the next installation. An edit between first evaluation and that record can be missed; the timestamp fallback still covers modules first loaded outside recomposition. If the readiness observation fails, the fallback starts at HMR construction time, not the Unix epoch. A module is stale when its file disappeared or its identity differs. A module first loaded after the last recording has no record; it is stale when its file was modified at or after that recording, less a 2-second filesystem timestamp resolution, so a reinstall between loading and the next comparison is not missed. Version numbers are not consulted: lockfiles record no content identity for `file:` and `link:` dependencies, and file identity covers registry, tarball, directory and link installs alike. + +### Replacing them + +A stale module whose importer closure reaches the process entry point's static graph, including installed packages, stays loaded and is reported. The remaining stale modules and their static importers, across ES module links and CommonJS `require` children, form the affected set, and every manifest from a stale file up to its profile root or linked target expires through `PackageManifests.invalidate()`. The whole affected set is evicted without a backup before recomposition, so every entry that imports during recomposition reaches the current files. A plugin registered outside a Loader entry has no owner that can start its replacement, so the changes its modules import stay pending; plugins are read from the ES module namespace and from cached CommonJS exports, so a CommonJS plugin registered through `require` keeps its cache too. HMR imports no replacement code itself, so admission is the Loader's ordinary activation: a disabled, removed or refused row never evaluates the new module, and dynamic `disabled` expressions and nested Includes are evaluated as at startup. Every recomposition imports again each enabled entry whose last import failed, after expiring the package configuration below the profile roots and evicting the modules whose links or evaluation failed, which Node keeps cached, so a corrected file or a later-installed dependency takes effect without a restart. A plugin counts as owned only when an affected plugin's own Loader entry fiber starts it; a changed plugin another plugin registers through a dynamic import stays pending. Unchanged dependencies of a replaced plugin are not re-evaluated, so shared libraries keep one instance. Source reloads through `partialReload()` keep their own in-place replacement with rollback. + +`reconcileProfile()` returns `pending`, each stale module that loads only after a restart with its reason (`host-module`, `unmanaged-plugin`, or `module-comparison` when planning failed). Pending modules stay stale, including modules first loaded after the last recording, so the next recomposition retries them. A module first loaded during a recomposition whose file was modified after the comparison also stays stale: activation may have evaluated it before that write. A failure while listing or comparing modules keeps the previous records and sets the profile-wide `restartReason: module-comparison`, even without known module URLs. Neither prevents recomposition. An activation failure, including a replacement that fails to import, is thrown with the Loader's import error; an unchanged failure is returned as a warning by later recompositions. Plugin Manager reports a thrown failure as `failed` with that diagnostic, and turns `pending` into `restart-required` with its `restartReason`, unless the operation reports `overridden`. The Web page localizes the reason, and the agent tool derives a `nextStep` sentence from it, so no surface parses a diagnostic string. + +The [packed worker loader](../../../../packages/experimental/webworker-runtime/src/module-system/module-loader.ts) stores evaluated modules in a private map and its `require` exposes no cache. HMR cannot replace them through Node APIs and reports a restart requirement. Native Node still exposes its caches when using asynchronous module hooks. + +### Plugin Manager and runtime resolution + +Plugin Manager refuses to install over an installed package it can name before pnpm runs, so a new version or location is a removal and an installation: the removal stops the plugins, evicts their modules and drops the mappings, and the installation maps the package afresh. Runtime resolution accepts a retained profile mapping whose version changes while its normalized directory and scope stay, as a shared dependency upgraded by another installation does, and rejects one that moved to another directory. A linked root may point to another directory; a file Node's cached link real path selects below the previous target, for an importer outside it, is relocated below the current one. Rejected publications, including changes to installation mappings or local overrides, leave the resolution and the composition unchanged and report `restart-required` with reason `package-moved`. + +## Alternatives considered + +**A separate package-replacement call from Plugin Manager.** Plugin Manager knows which package it installed, but not which Loader entries import it, and row additions, removals and configuration changes in the new bundle patch must apply in the same step. A second operation would split one profile change into two transactions with an undefined order. Recomposition already reads the new profile; comparing loaded files there covers Plugin Manager, CLI installs followed by a recomposition, and link builds. + +**Compare package versions from the profile manifest or lockfile.** The profile manifest stores specs, not resolved versions, and `pnpm update` can change a version without changing it. Lockfiles carry no content identity for `file:` and `link:` dependencies, and a same-version reinstall of a tarball changes content without changing the version. + +**Let app-boot call HMR from inside its recomposition.** Hooks for the steps before applying and before judging would split the order of one operation between two owners. HMR instead stops everything it replaces first and passes the stopped entries to one app-boot call. + +**Expose the recomposition's stages to HMR.** Separate calls to record activation, prepare after publication, apply, restore and drop mappings let HMR insert its stops between them, but they leave callers ordering obligations that the types cannot express. Stopping before the call costs a restart of the stopped plugins when preparation fails. + +**Publish twice, keeping the dropped mappings while the generation applies.** A temporary table with both the new and the dropped mappings lets one Loader update stop and start entries, but it is a third generation that must stay recomputable when the update fails. Stopping the dropped rows first lets one publication follow them. + +**Overwrite an installed bundle in one operation.** Stopping the bundle before pnpm and starting it afterwards, or detecting moved packages from the loaded module files, keeps one call for an upgrade, but needs a restart path for every pnpm failure, a selection restored in its order, and a release rule for moved directories. Refusing the overwrite leaves a removal and an installation, which the existing operations already run in this order. + +**Preload the replacement and keep the previous plugin when it fails to load.** HMR would import new code before stopping the previous runtime and restore the previous caches on failure. Preloading must not evaluate a row the generation disables, removes or refuses, so HMR would decide admission before the Loader does; dynamic `disabled` expressions and nested Includes cannot be decided without activation, so those changes would need a restart. Rollback must also remove new importers of restored modules, and the previous code would still receive the new configuration. A restart would load the same broken files, so keeping the previous plugin only delays a failure that needs a fix anyway. + +**Restart replaced plugins in place before recomposition.** New code would start with the previous configuration, which an upgraded version may reject, and a row the new composition disables or refuses, for example an incompatible version left on disk by a failed install, would briefly run. + +**Replace running plugins after recomposition.** Recomposition would restart the previous code with the new configuration, which the previous version may reject, so a successful upgrade would be reported as a failure; an entry inserted during recomposition would also link against the previous copy of a changed dependency still cached for a running plugin. + +**Stop affected plugins before pnpm runs.** This prevents previous code from lazily loading files pnpm has already replaced, but adds downtime for the whole install and holds the HMR queue during pnpm. + +**Re-evaluate every dependency of a replaced plugin.** Source reloads reload a plugin's non-`node_modules` dependency tree. Doing the same below `node_modules` would create second instances of unchanged shared libraries and Cordis packages used by other plugins. + +**Record identities in a module load hook.** `module.registerHooks()` could record each file at load time and close the window for modules loaded between recordings, but it adds a hook to every module load and interacts with TSX and the vendored Loader's internals. The timestamp rule only causes an extra reload in that window. + +## Consequences + +- Upgrades through a removal and an installation, and packages whose files changed in place, take effect without a restart when the replacement loads and starts; a replacement that fails to load or start stops the previous plugin and reports `failed` with the error, and it starts once its files or dependencies are corrected. +- Each recomposition stats every loaded file of the profile; the module graph is walked when a file changed, and the host graph is collected on first use. +- Dynamic `import()` edges are not followed: an importer keeps running while its next dynamic import evaluates the new file. Existing Workers and the TSX loader thread keep their caches. +- Replaced Loader entries stop before recomposition and start once afterwards; the previous version does not return. +- Loader entries outside the profile composition restart with replaced code without a new compatibility check ([limitation](../../../../packages/boot/hmr/README.md#known-limitations-and-deferred-work)). +- `ModuleFiles` belongs to one HMR instance. A recomposition that restarts the `hmr` entry itself starts a new instance whose first observation records the current files, so changes pending at that point are no longer reported or retried. +- `pending` describes the whole profile, so a host module brought into scope by a linked workspace package makes later unrelated operations report `restart-required` until the process restarts. +- A file replaced by a hard link to an older store file keeps an older modification time; when its module was first loaded after the last recording, the change is not detected. +- A change confined to `package.json` is not detected. HMR's profile watches do not recompose for dependency-only manifest changes, so installs performed outside Plugin Manager wait for the next recomposition or restart. + +## Verification + +| Coverage | Location | +|---|---| +| In-place upgrades with bundle patch changes, configurations the previous version rejects, inserted entries and disabled rows, plugins without a Loader entry, shared-dependency importers, linked packages, hard links, CommonJS `require` children and their failures, failed replacement and retry, nested groups and Includes, dynamic disabling, same-path reinstall, late-loaded modules, host-graph modules, comparison and recomposition failures, eviction of packages a recomposition stopped using or whose mappings it dropped, and the restart of stopped entries after a rejected publication or failed preparation | `packages/boot/hmr/tests/package-reload.spec.ts` | +| Refused overwrites, removal then installation with HMR, failed installation, relinked and link-to-registry reinstalls, unmanaged plugins, comparison failures | `packages/boot/plugin-manager/tests/package-reload.spec.ts`, `packages/boot/plugin-manager/tests/manager.spec.ts` | +| In-place profile mapping version change, retained directory and scope rejection including a relinked path inside the profiles tree, relinked roots and native lookups relocated below the current target | `packages/boot/app-boot/tests/profile-resolution.spec.ts` | + +Tests need no API key and make no model calls. diff --git a/.agents/notes/implemented/architecture/2026-10-01-replace-changed-package-modules-on-recomposition.zh.md b/.agents/notes/implemented/architecture/2026-10-01-replace-changed-package-modules-on-recomposition.zh.md new file mode 100644 index 0000000000..35ba5c98e9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-01-replace-changed-package-modules-on-recomposition.zh.md @@ -0,0 +1,86 @@ +# Agent Note: profile 重新组合时替换已加载包文件发生变化的插件 + +Status: implemented + +[English](2026-10-01-replace-changed-package-modules-on-recomposition.md) | 中文 + +## Problem + +Node 按文件 URL 缓存已求值的模块。profile 使用 pnpm 的 hoisted 布局安装包,因此无论版本如何,包都位于 `node_modules/`。覆盖、升级或重装包时所有文件 URL 保持不变,之后的导入或 Loader entry 重启返回的是旧版本的缓存模块。[包刷新说明](2026-09-30-profile-package-refresh-and-manifest-invalidation.zh.md)刷新 runtime resolution 和包配置,但不处理这一模块缓存;因此 Plugin Manager 把覆盖报告为 `restart-required`,而删除后在同一路径重装时报告 `applied`,旧版本却仍在运行。`link:` 开发包的构建输出变化时也会命中同一缓存,除非其目录列在 HMR 的源码监听根目录中。 + +## Decision + +### 唯一的重新组合路径 + +`Hmr.reconcileProfile()` 是 HMR 的 profile 监听和 Plugin Manager 共用的 profile 重新组合入口;Config Editor 仍直接通过 app-boot 重新组合。它在 `runExclusive()` 内运行。Plugin Manager 只编辑 profile 文件并运行 pnpm;对于在运行 pnpm 之前能确定包名的已安装包,它拒绝覆盖安装;安装另一个版本需要先卸载再安装,每一步各有一次重新组合。一次重新组合的步骤如下: + +1. 读取 profile patch,将 profile 目录及其已链接包目标之下的已加载模块与磁盘比较。 +2. 按下文规划替换;patch 读取或比较失败时,在任何模块变化之前抛出错误或报告失败。 +3. 逐出可替换的已变化模块及其导入方。若已变化模块的导入方可到达进程入口的静态依赖图,或可到达没有 Loader entry 拥有的插件,该模块连同其导入方保持加载;其余变化照常处理。 +4. 通过删除运行时停止运行被替换插件的 Loader entry,使 Loader 不把它们记录为已停用。 +5. 以停止之前正在运行的条目调用一次 app-boot 的 `recomposeProfile()`。它记录激活状态,把新一代组合不再列出的行从其所在组中移除,以停止这些行,发布 runtime resolution,基于已发布的包运行兼容性预检,然后应用新一代组合。Loader 在启动条目时导入当前文件:新一代组合保留的行以新代码和新配置启动一次;停用、拒绝或删除的行保持停止,不会运行新代码;新插入的条目链接当前文件。更新未尝试启动的已停止条目(位于未变化 Include 之下或 profile 组合之外)随后启动;更新期间导入失败的条目会再导入一次。随后判定激活结果:之后失败的已停止条目使操作失败;等待服务的条目只是警告,因为出现提供方后它即启动。若没有新一代组合被应用,已发布的 resolution 和已停止的行被恢复,已停止的条目重新启动。 +6. 逐出重新组合删除的映射所在目录之下的已加载模块,使已删除或取消选入的包连同其动态导入的依赖在重新加入时重新导入。关闭组合包而其包仍有映射时,它未变化的模块保持加载。 + +### 检测已变化的模块 + +[`ModuleFiles`](../../../../packages/boot/hmr/src/module-files.ts) 为 profile 目录及其已链接包的真实目录之下已加载的 ES 和 CommonJS 模块记录 inode、大小和修改时间。dsh 安装目录中的模块不在此范围内。不记录状态变更时间:pnpm 通过硬链接从其 store 导入包,在其他位置添加链接会改变已加载文件的状态变更时间,而内容不变。记录发生在应用就绪时和每次重新组合之后;源码重载重新求值模块时,也为这些模块记录。重新组合记录的是它在替换任何模块之前读取的文件身份,因此重新组合期间发生的写入仍可被检测到;在重新组合期间首次加载的模块在结算后记录,避免下一次安装时发生不必要的重启。首次求值与记录之间的修改可能漏检;时间戳兜底仍覆盖重新组合之外首次加载的模块。就绪时的观察失败时,兜底从 HMR 构造时间开始,而非 Unix 纪元。文件已消失或身份不同的模块视为陈旧。在上次记录之后才首次加载的模块没有记录;若其文件的修改时间不早于该次记录时间减去 2 秒文件系统时间戳精度,则视为陈旧,因此不会漏掉在加载与下一次比较之间发生的重装。比较不参考版本号:lockfile 不为 `file:` 和 `link:` 依赖记录内容标识,而文件身份同样覆盖 registry、tarball、目录和 link 安装。 + +### 替换 + +导入方闭包可到达进程入口静态依赖图(包括已安装包)的陈旧模块保持加载,并被报告。其余陈旧模块及其静态导入方(沿 ES 模块链接和 CommonJS `require` 子模块)构成受影响集合,从每个陈旧文件到其 profile 根目录或链接目标的各级 manifest 都通过 `PackageManifests.invalidate()` 失效。整个受影响集合在重新组合之前被逐出且不保留备份,因此重新组合期间执行导入的每个条目都读取当前文件。在 Loader entry 之外注册的插件没有能启动其替换版本的所有者,因此其模块导入的变化保持待处理;插件从 ES 模块命名空间和已缓存的 CommonJS exports 中读取,因此通过 `require` 注册的 CommonJS 插件同样保留其缓存。HMR 本身不导入替换代码,因此是否允许加载由 Loader 的普通激活决定:停用、删除或被拒绝的行永远不会对新模块求值,动态 `disabled` 表达式和嵌套 Include 按启动时的方式求值。每次重新组合都会先让 profile 根目录下的包配置失效,并逐出链接或求值失败的模块(Node 会在缓存中保留这些模块),再次导入上次导入失败的每个已启用条目,因此修正后的文件或之后安装的依赖无需重启即生效。只有当受影响插件自身的 Loader entry fiber 启动某个插件时,该插件才算有所有者;由另一个插件通过动态导入注册的已变化插件保持待处理。被替换插件中未变化的依赖不会重新求值,因此共享库保持单一实例。通过 `partialReload()` 进行的源码重载保留其自身带回滚的原地替换。 + +`reconcileProfile()` 返回 `pending`,即每个只有重启后才能加载的陈旧模块及其原因(`host-module`、`unmanaged-plugin`,规划失败时为 `module-comparison`)。待处理模块保持陈旧,包括在上次记录之后才首次加载的模块,因此下一次重新组合会重试它们。在重新组合期间首次加载、且其文件在比较之后被修改的模块同样保持陈旧:激活可能在该写入之前已对其求值。列出或比较模块时发生的失败会保留原有记录,并设置 profile 级 `restartReason: module-comparison`,即使无法确定模块 URL。两种情况都不会阻止重新组合。激活失败(包括替换版本导入失败)会连同 Loader 的导入错误一起抛出;未变化的失败在后续重新组合中作为警告返回。Plugin Manager 把抛出的失败报告为带该诊断的 `failed`,把 `pending` 转为带其 `restartReason` 的 `restart-required`,除非操作报告 `overridden`。Web 页面本地化该原因,agent 工具据此生成一句 `nextStep`,因此没有任何界面解析诊断字符串。 + +[打包 worker loader](../../../../packages/experimental/webworker-runtime/src/module-system/module-loader.ts) 在私有映射中保存已求值模块,其 `require` 不暴露缓存。HMR 无法通过 Node API 替换它们,因此报告需要重启。原生 Node 使用异步模块 hook 时仍暴露其缓存。 + +### Plugin Manager 与 runtime resolution + +对于在运行 pnpm 之前能确定包名的已安装包,Plugin Manager 拒绝覆盖安装,因此新版本或新位置需要先卸载再安装:卸载停止插件、逐出其模块并删除映射,安装再重新映射该包。runtime resolution 接受保留的 profile 映射在规范化目录和作用域不变时更改版本,即共享依赖被另一次安装升级的情形;移动到其他目录的映射被拒绝。linked root 可以指向其他目录;对于原目标之外的导入方,Node 缓存的链接真实路径若选中原目标之下的文件,该文件会被重新定位到当前目标之下。被拒绝的发布,包括对安装范围映射或本地覆盖的更改,不改变 resolution 和组合,并报告原因是 `package-moved` 的 `restart-required`。 + +## Alternatives considered + +**由 Plugin Manager 单独调用包替换。** Plugin Manager 知道自己安装了哪个包,但不知道哪些 Loader entry 导入了它;新组合包 patch 中的行增加、删除和配置变更也必须在同一步应用。第二个操作会把一次 profile 变更拆成两个顺序未定义的事务。重新组合本来就会读取新的 profile;在此处比较已加载文件,同时覆盖 Plugin Manager、之后执行重新组合的 CLI 安装以及 link 构建。 + +**比较 profile manifest 或 lockfile 中的包版本。** profile manifest 存储的是 spec,不是解析后的版本,`pnpm update` 可以在不修改 spec 的情况下改变版本。lockfile 不为 `file:` 和 `link:` 依赖记录内容标识,而同版本重装 tarball 会改变内容却不改变版本。 + +**让 app-boot 在其重新组合内部调用 HMR。** 为应用之前和判定之前的步骤提供 hook,会把一次操作的顺序拆分给两个所有者。HMR 改为先停止它替换的所有内容,再把已停止的条目传给一次 app-boot 调用。 + +**向 HMR 暴露重新组合的各个阶段。** 分别调用记录激活状态、发布后准备、应用、恢复和丢弃映射,可让 HMR 在其间插入停止操作,但会给调用方留下类型无法表达的顺序义务。在调用之前停止插件,代价是准备失败时需要重新启动已停止的插件。 + +**发布两次,在应用新一代组合期间保留被丢弃的映射。** 同时包含新映射和被丢弃映射的临时表,可以让一次 Loader 更新既停止又启动条目,但它是第三个 generation,更新失败时必须仍能重新计算。先停止被丢弃的行,之后只需发布一次。 + +**在一次操作中覆盖已安装的组合包。** 在 pnpm 运行之前停止该组合包、之后再启动,或根据已加载模块文件检测已移动的包,可以让升级只需一次调用;但这需要为每种 pnpm 失败提供重启路径、按原顺序恢复选择列表,并为已移动的目录制定释放规则。拒绝覆盖安装后只剩卸载和安装,现有操作已按此顺序执行。 + +**预加载替换版本,并在其加载失败时保留原插件。** HMR 将在停止旧运行时之前导入新代码,并在失败时恢复旧缓存。预加载不得对新一代组合停用、删除或拒绝的行求值,因此 HMR 要先于 Loader 决定是否允许加载;动态 `disabled` 表达式和嵌套 Include 不经激活就无法判定,因此这些变化需要重启。回滚还必须删除已恢复模块的新导入方,而旧代码仍会收到新配置。重启会加载相同的损坏文件,因此保留原插件只是推迟一个无论如何都需要修复的失败。 + +**在重新组合之前原地重启被替换的插件。** 新代码会先以旧配置启动,而升级后的版本可能拒绝旧配置;新组合停用或拒绝的行(例如安装失败后留在磁盘上的不兼容版本)也会短暂运行。 + +**在重新组合之后替换运行中的插件。** 重新组合会以新配置重启旧代码,而旧版本可能拒绝新配置,导致一次成功的升级被报告为失败;重新组合期间插入的条目也会链接到仍为运行中插件缓存的、已变化依赖的旧副本。 + +**在 pnpm 运行前停止受影响插件。** 这能防止旧代码惰性加载 pnpm 已经替换的文件,但会让整个安装期间插件不可用,并在 pnpm 运行期间占用 HMR 队列。 + +**重新求值被替换插件的全部依赖。** 源码重载会重载插件在 `node_modules` 之外的依赖树。若对 `node_modules` 之下做同样处理,会为其他插件使用的、未变化的共享库和 Cordis 包创建第二个实例。 + +**在模块加载 hook 中记录文件身份。** `module.registerHooks()` 可以在加载时记录每个文件,消除两次记录之间加载的模块的检测空窗,但这会给每次模块加载增加一个 hook,并与 TSX 和 vendored Loader 的内部机制相互影响。时间戳规则在该空窗内只会导致一次多余的重载。 + +## Consequences + +- 通过卸载再安装进行的升级,以及文件被原地更改的包,在替换版本成功加载并启动时无需重启即生效;替换版本加载或启动失败时,原插件停止并报告 `failed` 及该错误,其文件或依赖被修正后它即启动。 +- 每次重新组合对 profile 的所有已加载文件执行一次 stat;有文件变化时才遍历模块图,宿主依赖图在首次使用时收集。 +- 不跟踪动态 `import()` 边:导入方继续运行,而其下一次动态导入会求值新文件。已存在的 Worker 和 TSX loader 线程保留各自的缓存。 +- 被替换的 Loader entry 在重新组合之前停止,之后启动一次;旧版本不会恢复。 +- profile 组合之外的 Loader entry 以替换后的代码重启,不重新进行兼容性检查([限制](../../../../packages/boot/hmr/README.zh.md#known-limitations-and-deferred-work))。 +- `ModuleFiles` 属于单个 HMR 实例。重启 `hmr` 条目本身的重新组合会启动一个新实例,其首次观察记录当前文件,因此此时待处理的变化不再被报告或重试。 +- `pending` 描述整个 profile,因此由已链接工作区包纳入范围的宿主模块,会使后续无关操作也报告 `restart-required`,直到进程重启。 +- 若文件被替换为指向较旧 store 文件的硬链接,它保留较旧的修改时间;当其模块在上次记录之后才首次加载时,该变化不会被检测到。 +- 仅限于 `package.json` 的变化不会被检测到。HMR 的 profile 监听不会因仅涉及依赖的 manifest 变化而重新组合,因此在 Plugin Manager 之外执行的安装要等到下一次重新组合或重启。 + +## Verification + +| 覆盖面 | 位置 | +|---|---| +| 伴随组合包 patch 变更的原地升级、旧版本拒绝的配置、新插入的条目和停用行、没有 Loader entry 的插件、共享依赖的导入方、已链接包、硬链接、CommonJS `require` 子模块及其失败、替换失败与重试、嵌套 group 和 Include、动态停用、同路径重装、延后加载的模块、宿主依赖图中的模块、比较失败与重新组合失败、逐出重新组合不再使用或已删除其映射的包,以及发布被拒绝或准备失败后已停止条目的重启 | `packages/boot/hmr/tests/package-reload.spec.ts` | +| 被拒绝的覆盖安装、有 HMR 时先卸载再安装、安装失败、重新链接和从链接改为 registry 的重装、非托管插件、比较失败 | `packages/boot/plugin-manager/tests/package-reload.spec.ts`、`packages/boot/plugin-manager/tests/manager.spec.ts` | +| profile 映射原地更改版本、保留目录和作用域的拒绝(包括 profiles 树内重新链接的路径)、重新链接的 root 以及被重新定位到当前目标之下的原生查询 | `packages/boot/app-boot/tests/profile-resolution.spec.ts` | + +测试不需要 API key,不调用模型。 diff --git a/.agents/notes/implemented/architecture/2026-10-05-anonymous-reasoning-translation.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-05-anonymous-reasoning-translation.i18n.yaml index ee7758db34..c8cf21b92d 100644 --- a/.agents/notes/implemented/architecture/2026-10-05-anonymous-reasoning-translation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-05-anonymous-reasoning-translation.i18n.yaml @@ -9,8 +9,8 @@ en: 5e10347fa87f98b5 zh: cf3569631af8d66f /agent-note-anonymous-translation-remains-separate-from-model-history/decision: - en: f13c134f53ed63c9 - zh: 868aacd453d26c82 + en: 3c4745cc96d89ffd + zh: 939d5cd494346311 /agent-note-anonymous-translation-remains-separate-from-model-history/alternatives-considered: en: 083d50f8564b0378 zh: 50af332e64ad06f3 diff --git a/.agents/notes/implemented/architecture/2026-10-05-anonymous-reasoning-translation.md b/.agents/notes/implemented/architecture/2026-10-05-anonymous-reasoning-translation.md index 0fa78afa4e..1e67961bf1 100644 --- a/.agents/notes/implemented/architecture/2026-10-05-anonymous-reasoning-translation.md +++ b/.agents/notes/implemented/architecture/2026-10-05-anonymous-reasoning-translation.md @@ -14,7 +14,7 @@ The experimental translator owns explicit Google or Bing routing, provider-langu Bing is the configured default. Enabling the bundle permits transmission of expanded reasoning to the chosen service, disclosed in plugin metadata and settings. Failure never selects another provider. Original remains available; translated text neither replaces persisted assistant output nor enters model input. The [optional-bundle admission policy](2026-09-21-experimental-capabilities-as-optional-bundles.md) keeps the feature disabled until selected. -The reasoning-body chain carries original text and streaming status. Native Chat owns its original Markdown fallback; consumers do not replace the assistant renderer or alter Session projection. Only expanded bodies start translation. Collapsing, changing selection, or unloading aborts outstanding work and excludes late results. +The GUI registers a translation wrapper in the standard `conversation.chat.reasoning.body` Slot and calls the official `conversation.chat.reasoning.content` Factory for original or translated text. The default body is also an ordinary registration; the host supplies no inline Markdown fallback or plugin action state. The translation wrapper owns its toolbar and passes its localized labels to the Factory, which supplies default labels when callers omit them and fixes compact typography. The [reasoning Body Slot and Content Factory design](2026-10-09-reasoning-content-slot-factory.md) supersedes this record's body composition mechanism; external requests remain separate from model history. Consumers do not replace the assistant renderer or alter Session projection. Only expanded bodies start translation. Collapsing, changing selection, or unloading aborts outstanding work and excludes late results. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-10-05-anonymous-reasoning-translation.zh.md b/.agents/notes/implemented/architecture/2026-10-05-anonymous-reasoning-translation.zh.md index 293f74a5ee..4c2bb2854c 100644 --- a/.agents/notes/implemented/architecture/2026-10-05-anonymous-reasoning-translation.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-05-anonymous-reasoning-translation.zh.md @@ -14,7 +14,7 @@ Status: implemented 配置的默认服务为 Bing。启用 Bundle 允许将展开的思考内容发送给所选服务,插件元数据与设置公开说明接收方。失败时不选择其他 Provider。原文始终可访问;译文不替换持久化 assistant 输出,也不进入模型输入。[可选 Bundle 准入规则](2026-09-21-experimental-capabilities-as-optional-bundles.zh.md) 保证功能在显式选择前保持关闭。 -reasoning-body chain 传递原始文本与流式状态。原生 Chat 负责原始 Markdown fallback;消费者不替换 assistant 渲染器,也不改变 Session projection。只有展开内容才开始翻译。折叠、切换设置或卸载都会中止未完成工作并忽略迟到结果。 +GUI 向标准 `conversation.chat.reasoning.body` Slot 注册翻译包装,并调用官方 `conversation.chat.reasoning.content` Factory 展示原文或译文。默认正文同样是普通注册项;宿主不提供内联 Markdown fallback 或插件操作状态。翻译包装自行维护工具栏,并将自己的本地化 labels 传入 Factory;Factory 在调用者省略 labels 时提供默认文案,并固定紧凑排版。[思考正文的 Slot 与 Factory 设计](2026-10-09-reasoning-content-slot-factory.zh.md)取代本记录的正文组合方式,外部请求与模型历史隔离的决策保持不变。消费者不替换 assistant 渲染器,也不改变 Session projection。只有展开内容才开始翻译。折叠、切换设置或卸载都会中止未完成工作并忽略迟到结果。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-10-05-official-on-demand-bundles.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-05-official-on-demand-bundles.i18n.yaml index 4af09bcaae..3060e831f9 100644 --- a/.agents/notes/implemented/architecture/2026-10-05-official-on-demand-bundles.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-05-official-on-demand-bundles.i18n.yaml @@ -9,11 +9,11 @@ en: a590bcef6c9760c0 zh: 19e6f61c2c7d8d3b /agent-note-discover-official-bundles-without-installing-their-runtimes/decision: - en: 31e3c52841f31a11 - zh: ac2ad6e54ef9e150 + en: f0fabc0d4fbd1178 + zh: cf19938a7a7dea93 /agent-note-discover-official-bundles-without-installing-their-runtimes/alternatives-considered: en: 42cb0f808a145871 zh: 225012615d1ecdf5 /agent-note-discover-official-bundles-without-installing-their-runtimes/consequences: - en: 899b07d90024e019 - zh: 01d22ac4b2444feb + en: 293286dcd7e3325e + zh: c6c15212e85d050b diff --git a/.agents/notes/implemented/architecture/2026-10-05-official-on-demand-bundles.md b/.agents/notes/implemented/architecture/2026-10-05-official-on-demand-bundles.md index 0b0ad0cf55..a67acd25f9 100644 --- a/.agents/notes/implemented/architecture/2026-10-05-official-on-demand-bundles.md +++ b/.agents/notes/implemented/architecture/2026-10-05-official-on-demand-bundles.md @@ -12,13 +12,13 @@ Native subagent integrations bring their own runtimes. Shipping those dependenci `ON_DEMAND_BUNDLES` admits the Claude Code and Codex bundles to an installation-owned catalog. The catalog embeds their package-owned localized metadata and icons, so discovery works offline without resolving or importing either package. Official identifies project maintenance; optional delivery and experimental maturity remain independent properties. -Selection uses the ordinary third-party bundle installer, profile dependency, scoped patches, compatibility evaluation, progress, cancellation, registry fallback, and build-script approval. Native authentication and configuration remain provider-owned. +Selection uses the ordinary third-party bundle installer, profile dependency, Host row patches, compatibility evaluation, progress, cancellation, registry fallback, and build-script approval. Native authentication and configuration remain provider-owned. The running installation owns the target. Published applications offer the exact DSH release version and save an exact registry dependency pin. Source Web and development Desktop offer ordinary `link:` dependencies into the same checkout as the running CLI, using its prepared workspace dependencies and peers. The source target follows the actual installation, never the current working directory or a prerelease suffix; an incomplete checkout does not fall back to the registry. A development checkout can share a version string with different published code, so replacing an installed registry copy or another checkout’s link compares the source as well as the version. Replacement is explicit, preserves selection, and reports required restarts; startup does not download providers. [Plugin Manager](../../../../packages/boot/plugin-manager/README.md#use-this-package) owns the operational details. Every Official package remains in the DSH release family. Packed DSH dependencies, optional dependencies, and peers use the exact family version. Publication prerequisites place catalog packages before the DSH package advertising them without adding their runtimes to DSH production dependencies. Catalog verification rejects missing metadata, unsupported membership, and stale generated content. -The [shipped optional-bundle policy](../process/2026-09-15-shipped-optional-bundles.md) still owns lightweight installation-provided bundles. The [optional-composition decision](2026-09-21-experimental-capabilities-as-optional-bundles.md) owns shared patch and preset-generation behavior. Native bundles require the full Web preset targets; custom profiles mount their providers and tools explicitly. The [identity compatibility decision](2026-10-06-web-desktop-plugin-identity-compatibility.md) owns retained names, selectors, and deferred naming cleanup. +The [shipped optional-bundle policy](../process/2026-09-15-shipped-optional-bundles.md) still owns lightweight installation-provided bundles. The [optional-composition decision](2026-09-21-experimental-capabilities-as-optional-bundles.md) owns shared patch behavior and global optional tools. Native bundles insert ordinary Host rows, so any profile can select them; profiles that keep the package without its bundle mount the same rows explicitly. The [identity compatibility decision](2026-10-06-web-desktop-plugin-identity-compatibility.md) owns retained names, selectors, and deferred naming cleanup. ## Alternatives considered @@ -34,4 +34,4 @@ The [shipped optional-bundle policy](../process/2026-09-15-shipped-optional-bund ## Consequences -Registry delivery requires a reachable registry; development delivery requires a prepared, built checkout and normal rebuild/restart discipline. Equal source version strings do not certify identical build outputs. Off only deselects; Remove remains separate and respects retained preset modules. Activation failure can retain the saved dependency and selection; there is no rollback. Offline metadata, release pins, source-target selection, same-version source mismatches, clean installed artifacts, and release ordering have dedicated checks. Native-provider authentication is not part of catalog discovery. +Registry delivery requires a reachable registry; development delivery requires a prepared, built checkout and normal rebuild/restart discipline. Equal source version strings do not certify identical build outputs. Off only deselects; Remove remains separate and refuses while the bundle's rows are in use. Activation failure can retain the saved dependency and selection; there is no rollback. Offline metadata, release pins, source-target selection, same-version source mismatches, clean installed artifacts, and release ordering have dedicated checks. Native-provider authentication is not part of catalog discovery. diff --git a/.agents/notes/implemented/architecture/2026-10-05-official-on-demand-bundles.zh.md b/.agents/notes/implemented/architecture/2026-10-05-official-on-demand-bundles.zh.md index 6fbdaa6e8f..0949f6b72c 100644 --- a/.agents/notes/implemented/architecture/2026-10-05-official-on-demand-bundles.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-05-official-on-demand-bundles.zh.md @@ -12,13 +12,13 @@ Status: implemented `ON_DEMAND_BUNDLES` 将 Claude Code 和 Codex bundle 纳入安装方维护的目录。目录内嵌包自身拥有的本地化元信息和图标,因此发现过程离线可用,无需解析或导入这两个包。Official 表示项目维护;可选交付与实验成熟度仍是独立属性。 -选择操作复用普通第三方 bundle 的安装器、profile 依赖、作用域 patch、兼容性判断、进度、取消、注册表回退和构建脚本审批。原生认证与配置仍由提供方拥有。 +选择操作复用普通第三方 bundle 的安装器、profile 依赖、Host 行 patch、兼容性判断、进度、取消、注册表回退和构建脚本审批。原生认证与配置仍由提供方拥有。 当前运行的安装决定目标。已发布应用提供精确的 DSH 发布版本,并保存精确的注册表依赖版本。源码 Web 和开发 Desktop 提供指向当前 CLI 所在 checkout 的普通 `link:` 依赖,使用其中已准备好的工作区依赖和 peer。源码目标跟随实际安装位置,不由当前工作目录或预发布版本后缀决定;不完整的 checkout 不回退到注册表。开发 checkout 可以与内容不同的已发布代码共用版本字符串,因此替换已安装的注册表副本或其他 checkout 的链接时,同时比较来源和版本。替换需显式触发,保留选择状态,并报告是否需要重启;启动时不下载提供方。[插件管理器](../../../../packages/boot/plugin-manager/README.zh.md#use-this-package)拥有操作细节。 所有 Official 包仍属于 DSH 发布家族。打包后的 DSH 依赖、可选依赖与 peer 均使用家族精确版本。发布前置关系要求先发布目录包,再发布宣传它们的 DSH 包,同时不把这些运行时加入 DSH 生产依赖。目录校验拒绝缺失的元信息、不受支持的成员和过期生成内容。 -[随附可选 bundle 策略](../process/2026-09-15-shipped-optional-bundles.zh.md)仍管理安装随附的轻量 bundle。[可选组合决策](2026-09-21-experimental-capabilities-as-optional-bundles.zh.md)管理共享 patch 与预设代际行为。原生 bundle 要求完整 Web 预设目标存在;自定义 profile 显式挂载提供方和工具。[身份兼容决策](2026-10-06-web-desktop-plugin-identity-compatibility.zh.md)管理保留名称、选择器和暂缓的命名清理。 +[随附可选 bundle 策略](../process/2026-09-15-shipped-optional-bundles.zh.md)仍管理安装随附的轻量 bundle。[可选组合决策](2026-09-21-experimental-capabilities-as-optional-bundles.zh.md)管理共享 patch 行为与全局可选工具。原生 bundle 插入普通 Host 行,因此任何 profile 都可以选择它们;保留包但不选择其 bundle 的 profile 显式挂载相同的行。[身份兼容决策](2026-10-06-web-desktop-plugin-identity-compatibility.zh.md)管理保留名称、选择器和暂缓的命名清理。 ## 考虑过的替代方案 @@ -34,4 +34,4 @@ Status: implemented ## 后果 -注册表交付要求注册表可达;开发交付要求准备并构建 checkout,遵循正常的重新构建和重启流程。源码版本字符串相同不证明构建输出相同。关闭仅取消选择;移除保持独立,并尊重预设仍保留的模块。激活失败可以保留已保存的依赖和选择,不加入回滚。离线元信息、发布版本锁定、源码目标选择、同版本来源差异、干净安装产物和发布顺序有专门检查。原生提供方认证不属于目录发现过程。 +注册表交付要求注册表可达;开发交付要求准备并构建 checkout,遵循正常的重新构建和重启流程。源码版本字符串相同不证明构建输出相同。关闭仅取消选择;移除保持独立,并在 bundle 的行仍在使用时拒绝执行。激活失败可以保留已保存的依赖和选择,不加入回滚。离线元信息、发布版本锁定、源码目标选择、同版本来源差异、干净安装产物和发布顺序有专门检查。原生提供方认证不属于目录发现过程。 diff --git a/.agents/notes/implemented/architecture/2026-10-06-web-desktop-plugin-identity-compatibility.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-06-web-desktop-plugin-identity-compatibility.i18n.yaml index bab272d8e1..b22fc768ec 100644 --- a/.agents/notes/implemented/architecture/2026-10-06-web-desktop-plugin-identity-compatibility.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-06-web-desktop-plugin-identity-compatibility.i18n.yaml @@ -9,14 +9,14 @@ en: 8112c1c059d1cf10 zh: 852d23c56a93a555 /agent-note-preserve-web-and-desktop-plugin-identities-across-experimental-consolidation/decision: - en: ac725c281d7dfb41 - zh: 5adcaa6ca6eab384 + en: 90d74300f045bf6e + zh: 088e88944478ca2a /agent-note-preserve-web-and-desktop-plugin-identities-across-experimental-consolidation/deferred-naming-cleanup: en: 4c428f65ef611d07 zh: 1fdc5467b0203d08 /agent-note-preserve-web-and-desktop-plugin-identities-across-experimental-consolidation/alternatives-considered: - en: 1bf03723fea6c9a4 - zh: 2d0d2fc997f7c022 + en: 65af55b5775c9bc5 + zh: 2ea75b3fd33ac0c2 /agent-note-preserve-web-and-desktop-plugin-identities-across-experimental-consolidation/consequences: - en: 60f7c823b5d2ed6f - zh: 75f375487cab3c56 + en: e8e96b0354f1a3c6 + zh: ad1bfe3600e14ff1 diff --git a/.agents/notes/implemented/architecture/2026-10-06-web-desktop-plugin-identity-compatibility.md b/.agents/notes/implemented/architecture/2026-10-06-web-desktop-plugin-identity-compatibility.md index def042e26a..c39f289a39 100644 --- a/.agents/notes/implemented/architecture/2026-10-06-web-desktop-plugin-identity-compatibility.md +++ b/.agents/notes/implemented/architecture/2026-10-06-web-desktop-plugin-identity-compatibility.md @@ -12,9 +12,9 @@ Moving a capability into the experimental directory changes its ownership and su The moved packages retain the published names declared by the [experimental naming policy](../../../../scripts/experimental-package-policy.ts). That typed directory-to-name map is the sole maintained inventory of naming exceptions. Package manifests, consumers, installation checks, and bundler checks agree with it; a missing, moved, or duplicated exception is rejected. [Experimental status](../../../../packages/experimental/README.md#status) remains independent of spelling, Official discovery, and explicit selection. -Existing badge, Ralph, and native delegation row IDs remain valid selectors inside their applicable Host or preset scope. New isolation groups and newly introduced capabilities retain their new IDs. Later user layers still replace configuration or disable rows, and a complete preset replacement remains authoritative. Selecting an optional bundle is still explicit: a patch targeting an absent row does not select its bundle. +Existing badge, Ralph, and native delegation row IDs remain valid Host row selectors. New isolation groups and newly introduced capabilities retain their new IDs. Later user layers still replace configuration or disable rows. Selecting an optional bundle is still explicit: a patch targeting an absent row does not select its bundle. -Compatibility protection covers Web and Desktop profiles, including existing native provider package identities, selections, configuration, and authentication. Headless, SDK, and ACP compositions may require changes. Native bundles use the ordinary shared patch operation and require the full preset targets; separate provider-only compatibility wrappers are unnecessary for the protected profiles. Public APIs remain pre-stable, and new output metadata stays required unless an actual consumer needs an accommodation. +Compatibility protection covers Web and Desktop profiles, including existing native provider package identities, selections, configuration, and authentication. Native bundles insert ordinary Host rows, so Headless, SDK, and ACP compositions can select them too; separate provider-only compatibility wrappers are unnecessary. Public APIs remain pre-stable, and new output metadata stays required unless an actual consumer needs an accommodation. ## Deferred naming cleanup @@ -31,10 +31,10 @@ These naming changes are deferred, not prerequisites for experimental classifica **Publish aliases or keep duplicate compatibility rows.** Parallel identities need continuing resolution and removal rules and can register the same capability twice. Retaining the established identity avoids that additional mechanism. -**Keep provider-only bundles through additional wrapper packages.** Web and Desktop already provide the required presets. Extra delivery packages would preserve compositions outside the selected compatibility scope and increase catalog and release maintenance. +**Keep provider-only bundles through additional wrapper packages.** Native bundles insert ordinary Host rows that compose into any profile. Extra delivery packages would preserve compositions outside the selected compatibility scope and increase catalog and release maintenance. ## Consequences -The repository carries a bounded naming-exception map and tests that classify retained names through direct imports, aliases, transitive dependencies, and packed or bundled artifacts. An unprefixed name does not grant admission to the default product. Existing row identities have Web/Desktop composition coverage for user overrides, disabled state, and preset replacement. No general alias or automatic profile migration mechanism is introduced. +The repository carries a bounded naming-exception map and tests that classify retained names through direct imports, aliases, transitive dependencies, and packed or bundled artifacts. An unprefixed name does not grant admission to the default product. Existing row identities have Web/Desktop composition coverage for user overrides and disabled state. No general alias or automatic profile migration mechanism is introduced. The [classification decision](../process/2026-10-05-product-package-classification.md), [optional-composition decision](2026-09-21-experimental-capabilities-as-optional-bundles.md), and [on-demand discovery decision](2026-10-05-official-on-demand-bundles.md) retain their separate responsibilities. Released Session generations and persisted hook event names remain protected independently of this profile compatibility scope. diff --git a/.agents/notes/implemented/architecture/2026-10-06-web-desktop-plugin-identity-compatibility.zh.md b/.agents/notes/implemented/architecture/2026-10-06-web-desktop-plugin-identity-compatibility.zh.md index 1f513060ea..4b58743cb5 100644 --- a/.agents/notes/implemented/architecture/2026-10-06-web-desktop-plugin-identity-compatibility.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-06-web-desktop-plugin-identity-compatibility.zh.md @@ -12,9 +12,9 @@ Status: implemented 迁移的包保留[实验包命名策略](../../../../scripts/experimental-package-policy.ts)声明的已发布名称。这个带类型的目录到包名映射是命名例外唯一手工维护的清单。包清单、消费者、安装检查和打包检查与其保持一致;缺失、迁移到其他位置或重复归属的例外会被拒绝。[实验状态](../../../../packages/experimental/README.zh.md#status)仍独立于名称拼写、Official 发现和显式选择。 -既有徽章、Ralph 和原生委派行 ID 在对应的 Host 或预设作用域中保持有效。新增隔离组和新引入的能力保留各自的新 ID。后续用户层仍可替换配置或禁用行,完整预设替换仍具有决定权。可选 bundle 仍须显式选择:指向缺失行的 patch 不会自动选择其 bundle。 +既有徽章、Ralph 和原生委派行 ID 作为 Host 行选择器保持有效。新增隔离组和新引入的能力保留各自的新 ID。后续用户层仍可替换配置或禁用行。可选 bundle 仍须显式选择:指向缺失行的 patch 不会自动选择其 bundle。 -兼容性保护覆盖 Web 和 Desktop profile,包括既有原生提供方的包身份、选择状态、配置和认证。Headless、SDK 和 ACP 组合可以要求修改。原生 bundle 使用普通的共享 patch 操作并要求完整预设目标存在;受保护的 profile 不需要单独的仅提供方兼容包装包。公共 API 仍处于稳定前阶段,新增输出元信息保持必填,除非实际消费者需要适配。 +兼容性保护覆盖 Web 和 Desktop profile,包括既有原生提供方的包身份、选择状态、配置和认证。原生 bundle 插入普通 Host 行,因此 Headless、SDK 和 ACP 组合也可以选择它们;不需要单独的仅提供方兼容包装包。公共 API 仍处于稳定前阶段,新增输出元信息保持必填,除非实际消费者需要适配。 ## 暂缓的命名清理 @@ -31,10 +31,10 @@ Status: implemented **发布别名或保留重复兼容行。** 并行身份需要持续维护解析和移除规则,还可能重复注册同一能力。保留既有身份可以避免增加这种机制。 -**通过额外包装包保留仅提供方 bundle。** Web 和 Desktop 已提供所需预设。额外交付包会保留选定兼容范围之外的组合,并增加目录和发布维护成本。 +**通过额外包装包保留仅提供方 bundle。** 原生 bundle 插入普通 Host 行,可组合到任何 profile。额外交付包会保留选定兼容范围之外的组合,并增加目录和发布维护成本。 ## 后果 -仓库维护范围明确的命名例外映射,并测试通过直接导入、别名、传递依赖及打包产物识别这些保留名称。没有实验前缀的名称不因此获准进入默认产品。既有行身份具有覆盖用户配置、禁用状态和预设替换的 Web/Desktop 组合测试。不引入通用别名或自动 profile 迁移机制。 +仓库维护范围明确的命名例外映射,并测试通过直接导入、别名、传递依赖及打包产物识别这些保留名称。没有实验前缀的名称不因此获准进入默认产品。既有行身份具有覆盖用户配置和禁用状态的 Web/Desktop 组合测试。不引入通用别名或自动 profile 迁移机制。 [分类决策](../process/2026-10-05-product-package-classification.zh.md)、[可选组合决策](2026-09-21-experimental-capabilities-as-optional-bundles.zh.md)和[按需发现决策](2026-10-05-official-on-demand-bundles.zh.md)继续承担各自独立的职责。已发布 Session 代际和持久化 hook 事件名的保护独立于此 profile 兼容范围。 diff --git a/.agents/notes/implemented/architecture/2026-10-08-desktop-shell-configuration.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-08-desktop-shell-configuration.i18n.yaml new file mode 100644 index 0000000000..7bd206e1f8 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-08-desktop-shell-configuration.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-08-desktop-shell-configuration.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-desktop-shell-configuration.md +/agent-note-desktop-shell-configuration-independent-of-the-host: + en: 860c8afa57227b89 + zh: bec6a19319050aed +/agent-note-desktop-shell-configuration-independent-of-the-host/problem: + en: 9f652292b62cd015 + zh: 14a97b5a4884c008 +/agent-note-desktop-shell-configuration-independent-of-the-host/decision: + en: e58311d3d5ebb6b6 + zh: b4c791fcfde7b986 +/agent-note-desktop-shell-configuration-independent-of-the-host/alternatives-considered: + en: 349210f3cf5f168b + zh: 019acfc3c3d71b4b +/agent-note-desktop-shell-configuration-independent-of-the-host/consequences: + en: a523f43819051d4b + zh: 69926bc3761195ea diff --git a/.agents/notes/implemented/architecture/2026-10-08-desktop-shell-configuration.md b/.agents/notes/implemented/architecture/2026-10-08-desktop-shell-configuration.md new file mode 100644 index 0000000000..9531ff4bff --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-08-desktop-shell-configuration.md @@ -0,0 +1,29 @@ +# Agent Note: Desktop shell configuration independent of the Host + +Status: implemented + +English | [中文](2026-10-08-desktop-shell-configuration.zh.md) + +## Problem + +Desktop updates and native recovery can run before the Host starts or while it is unavailable. Depending on Host configuration prevents these functions from resolving their preferences when needed. A shared settings page does not identify which process owns each preference. + +## Decision + +Electron main owns `userData/desktop/settings.json` independently of Host startup and Cordis evaluation. The test authentication popup switch uses this file; the [Desktop reference](../../../../apps/desktop/README.md#local-desktop-settings) owns its fields and behavior. + +Ownership follows runtime dependencies: Electron-owned functions needing configuration before Host startup or while the Host is unavailable use shell configuration. Host plugin settings, including shared Web/Desktop preferences, continue to use Cordis. Displaying a setting in Desktop alone does not justify shell ownership. A unified settings interface can use separate storage owners. + +The `desktop` subdirectory groups shell configuration without relocating existing files. The [shortcut decision](2026-09-20-device-local-shortcut-preferences.md) retains ownership of `userData/keybindings.json` and its persistence semantics. The [shared Web application decision](2026-09-10-desktop-web-wrapper.md) still governs Host composition and profile configuration. + +## Alternatives considered + +**Put every preference in Cordis.** This requires a working Host. Reading `cordis.patch.yml` directly in Electron duplicates configuration evaluation; a patch alone omits plugin defaults and other configuration layers. + +**Move every setting shown in Desktop.** Interface placement does not imply a Host-independent requirement. This splits shared Web/Desktop preferences and moves configuration away from its consuming plugins. + +## Consequences + +Shell and Host configuration have separate owners. Each setting needs documented ownership and effective timing. Independent shell configuration supports additional Host-independent functions without introducing a second application backend. + +Existing settings are candidates for individual evaluation when their functionality changes or a Host-independent use is required. This is an evaluation direction, not a scheduled migration or predefined list. A migration must identify a single authoritative source, transfer existing values and define when changes take effect, without ambiguous precedence between two stores. Shared Host-managed settings remain in Cordis unless their ownership requirements change. diff --git a/.agents/notes/implemented/architecture/2026-10-08-desktop-shell-configuration.zh.md b/.agents/notes/implemented/architecture/2026-10-08-desktop-shell-configuration.zh.md new file mode 100644 index 0000000000..3dac97f51a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-08-desktop-shell-configuration.zh.md @@ -0,0 +1,29 @@ +# Agent Note: Desktop 壳层配置独立于 Host + +Status: implemented + +[English](2026-10-08-desktop-shell-configuration.md) | 中文 + +## Problem + +Desktop 更新和原生恢复可以在 Host 启动前或不可用时运行。依赖 Host 配置会使这些功能无法在需要时解析偏好。统一设置页面不能决定每项偏好由哪个进程负责。 + +## Decision + +Electron 主进程负责 `userData/desktop/settings.json`,不依赖 Host 启动或 Cordis 求值。测试鉴权弹窗开关使用此文件;[Desktop 参考文档](../../../../apps/desktop/README.zh.md#local-desktop-settings)统一说明字段和行为。 + +配置归属按运行依赖划分:由 Electron 负责且需要在 Host 启动前或不可用时读取配置的功能,使用壳层配置。Host 插件设置,包括 Web/Desktop 共用偏好,继续使用 Cordis。仅仅展示在 Desktop 中,不构成归属壳层的理由。统一设置界面可以使用不同的存储归属。 + +`desktop` 子目录集中存放壳层配置,不迁移已有文件。[快捷键决策](2026-09-20-device-local-shortcut-preferences.zh.md)继续负责 `userData/keybindings.json` 及其持久化语义。[共享 Web 应用决策](2026-09-10-desktop-web-wrapper.zh.md)仍约束 Host 组合和 profile 配置。 + +## Alternatives considered + +**所有偏好都放入 Cordis。** 这需要可用的 Host。由 Electron 直接读取 `cordis.patch.yml` 会重复实现配置求值;单独的 patch 不包含插件默认值和其他配置层。 + +**迁移所有在 Desktop 展示的设置。** 界面位置不意味着需要独立于 Host。这会拆分 Web/Desktop 共用偏好,并让配置脱离实际使用它的插件。 + +## Consequences + +壳层与 Host 配置分别有自己的归属。每项设置需说明归属和生效时机。独立壳层配置支持更多不依赖 Host 的功能,但不引入第二套应用后端。 + +现有设置在功能调整或需要独立于 Host 使用时,可逐项评估。这是评估方向,不是已排期的迁移计划或预设清单。实际迁移需明确唯一配置来源、迁移已有值并定义生效时机,避免两套存储间存在含糊的优先级。共用的 Host 设置在归属要求不变时继续使用 Cordis。 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-09-reasoning-content-slot-factory.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-09-reasoning-content-slot-factory.i18n.yaml new file mode 100644 index 0000000000..ba86de4f69 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-09-reasoning-content-slot-factory.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for 2026-10-09-reasoning-content-slot-factory.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-reasoning-content-slot-factory.md +/agent-note-standard-reasoning-body-slot-and-reusable-content-factory: + en: 55862b96f6731c81 + zh: 425ab1ff7043a606 +/agent-note-standard-reasoning-body-slot-and-reusable-content-factory/problem: + en: 91000d9dd4a47647 + zh: 6146424ac5c3987b +/agent-note-standard-reasoning-body-slot-and-reusable-content-factory/decision: + en: 0a45affd1b125113 + zh: 3af28a27b7721bc7 +/agent-note-standard-reasoning-body-slot-and-reusable-content-factory/decision/registration-and-rendering: + en: 0af348d91eedc16e + zh: a06d6f59cc271e94 +/agent-note-standard-reasoning-body-slot-and-reusable-content-factory/decision/data-state-and-lifecycle: + en: e220ebf28a113e0b + zh: dfedd85ac5d76ccb +/agent-note-standard-reasoning-body-slot-and-reusable-content-factory/decision/translation-plugin-integration: + en: 145a1ae617a49f43 + zh: b2eb8443bb1515a7 +/agent-note-standard-reasoning-body-slot-and-reusable-content-factory/alternatives-considered: + en: 89adfc6fbad716f3 + zh: 098cca9e73c5eeaf +/agent-note-standard-reasoning-body-slot-and-reusable-content-factory/verification: + en: 23e6e98d176f08f4 + zh: 2b89720b8914552b +/agent-note-standard-reasoning-body-slot-and-reusable-content-factory/consequences: + en: 60a32f46ff947154 + zh: 6498e791d4c2c166 diff --git a/.agents/notes/implemented/architecture/2026-10-09-reasoning-content-slot-factory.md b/.agents/notes/implemented/architecture/2026-10-09-reasoning-content-slot-factory.md new file mode 100644 index 0000000000..b1c3f5c7d6 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-09-reasoning-content-slot-factory.md @@ -0,0 +1,102 @@ +# Agent Note: Standard reasoning Body Slot and reusable Content Factory + +Status: implemented + +English | [中文](2026-10-09-reasoning-content-slot-factory.zh.md) + +## Problem + +Reasoning bodies need to let third parties replace or wrap their presentation while reusing the official Markdown renderer, localized labels, and compact typography. An optional renderer parameter that makes the host choose between direct rendering and a chain fallback leaves the default body outside the registration system and forces plugins to maintain another Markdown call. + +The render position and the base implementation serve different purposes: the position accepts plugin registrations and lets the framework select one, while any component can call the implementation directly. Calling the base implementation must not repeat plugin selection for that position or require a Session. + +## Decision + +The design uses existing [Component Factories](2026-09-10-component-factories-and-local-slots.md) and ordinary Slots without adding framework dispatch machinery. + +| Name | Type | Owner and responsibility | +| --- | --- | --- | +| `conversation.chat.reasoning.body` | `single`, `session` Slot | Body position declared by the Assistant node registration; receives only original text and streaming state when expanded. | +| `conversation.chat.reasoning.content` | `root` Factory | Standard reasoning content provided by `ui-chat`; accepts text, streaming state, and optional labels, supplies default labels, and fixes `variant="compact"`. | + +The Factory receives no Session identity, reads no Session, and owns no translation state. The current Factory API requires `scope`; `root` expresses the absence of a Session dependency, while each render position still has an independent React instance. The Chat plugin registers the Factory independently of any Body occupant, so replacing a body does not remove the base implementation. + +### Registration and rendering + +1. `ui-chat` registers the Content Factory with component props derived through `FactoryComponentPropsOf`. When the caller omits labels, the Factory constructs stable defaults from Chat's locale seat. +2. The Assistant node registration declares the Body Slot. An expanded `ReasoningRow` only calls `renderSlot`; it accepts no optional renderer, supplies no inline fallback, and does not check whether a plugin is enabled. +3. The official default Body is an ordinary registration with `priority: 100`. It forwards only `text` and `running` to the Content Factory. +4. Third parties wait for the Body declaration through `slots.inject` and register their Body with a smaller priority value. They may call the Content Factory directly and add their own controls around it without importing private official React components. +5. When a third party unregisters, the framework selects the official default registration again. Multiple third-party registrations follow existing single-slot priorities; they do not form middleware or render multiple bodies together. + +```text +ReasoningRow + └─ conversation.chat.reasoning.body + ├─ 官方默认 Body ───────────┐ + └─ 第三方 Body → 自有控件 ─┤ + └─ conversation.chat.reasoning.content + └─ MarkdownText +``` + +The body render position: + +```tsx ignore-check +
+ {renderSlot('conversation.chat.reasoning.body', { text, running })} +
+``` + +The default Body and third-party wrappers use the same reusable implementation; a third party passes labels when it needs custom copy: + +```tsx ignore-check +renderFactorySlot('conversation.chat.reasoning.content', { + text: displayText, + running, + labels, +}) +``` + +### Data, state, and lifecycle + +- `ReasoningBodyOwnerProps` contains only readonly `text: string` and `running: boolean`. `ReasoningContentInput` also accepts `labels?: MarkdownLabels`; supplied labels are used unchanged without field-level merging, and omission selects the official defaults. Callers own the localization and reference stability of custom labels. +- The Body's `text` is always the original reasoning. A third party selects original or derived display text and passes that value to the Factory without rewriting the Session or Chat projection. +- `ReasoningRow` retains its existing disclosure state, summary, shimmer, and title behavior. Plugin-specific selection state, buttons, and styles stay inside the plugin's Body wrapper; the official implementation supplies no `setHeaderAction`, header-action type, or corresponding state. +- Registrations follow Cordis effect lifetimes. Collapsing the Body declaration removes its contributions through `slots.inject`; unloading the Chat plugin removes the Content Factory. +- Factory components and the default Body have stable module-level identities. Text changes update props instead of rebuilding component types or keys. Plugin replacement or HMR may remount components according to existing framework semantics; unmounted components have no state-retention guarantee. + +### Translation plugin integration + +The [anonymous translation design](2026-10-05-anonymous-reasoning-translation.md) retains its external-request, privacy, failure, and cancellation decisions; this design supersedes its body composition mechanism. The translation plugin registers in the standard Body Slot, renders original/translation selection, status, and retry controls in its own toolbar, and wraps the official Content Factory with its own state and optional custom labels rather than calling `MarkdownText` directly. + +Translation requests, splitting, caching, persistence, and settings remain unchanged. The translation toggle belongs to the plugin body rather than the official Think title. The design adds no Slot outside the body, does not handle user-message masking, and does not change the general Markdown parser. + +## Alternatives considered + +**Translation-specific chain and host fallback.** The default content is not an ordinary registration, the host maintains a second render path, and third parties cannot directly reuse the complete official body implementation. + +**Expose only the Body Slot.** This permits replacement, but wrapping plugins still have to copy the official Markdown call, labels, and variant. + +**Provide only the Content Factory.** This permits implementation reuse but supplies no actual body position for third-party replacement registrations. + +**Export React components across plugins.** This bypasses existing Factory loading, lifecycle, and type derivation and adds feature-plugin runtime dependencies. + +**Name the Factory as general Markdown.** This implementation fixes reasoning-specific compact typography and supplies Chat defaults; it is not a general entry point for all Markdown uses. + +**Make the official implementation maintain plugin header actions.** The default body has no such requirement; a dedicated setter makes the host own plugin state, cleanup, and button styles. + +**Force official labels in the Factory.** Default copy must not prevent caller customization; an optional parameter provides an override without replacing the whole body implementation. + +## Verification + +- The body host only calls `conversation.chat.reasoning.body`, with no old `reasoning-body` chain, optional renderer, or inline Markdown fallback. +- Both the default Body and translation Body render through `conversation.chat.reasoning.content`; omitted labels use official defaults, and custom labels reach Markdown unchanged. +- The Factory works without a Session Provider, and two render positions do not share component-local state. +- The official implementation has no header-action type, setter, state, or dedicated styles; the translation wrapper supplies its own selection and retry controls. +- Enabling, disabling, or hot-reloading the translation plugin selects the corresponding Body; default output, original-text access, streaming, disclosure, and cancellation behavior remain consistent. +- Unit and assembly tests cover registration disposal, a Session-independent Factory, default and custom labels, shared implementation reuse, and independent occurrences; existing browser replay covers default bodies and translation switching. + +## Consequences + +The old Slot name, chain-selector registrations, and header-action callback are unsupported, so third parties must migrate. Test fixtures and the Client inspect catalog must follow the new declarations rather than offer obsolete registration examples. + +The Body remains an exclusive replacement position. This design does not automatically compose multiple text-transformation plugins or turn display transformations into redaction or model-input modification. diff --git a/.agents/notes/implemented/architecture/2026-10-09-reasoning-content-slot-factory.zh.md b/.agents/notes/implemented/architecture/2026-10-09-reasoning-content-slot-factory.zh.md new file mode 100644 index 0000000000..73986249ef --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-09-reasoning-content-slot-factory.zh.md @@ -0,0 +1,102 @@ +# Agent Note: 思考正文的标准 Slot 与可复用 Content Factory + +Status: implemented + +[English](2026-10-09-reasoning-content-slot-factory.md) | 中文 + +## 问题 + +思考正文需要允许第三方替换或包装展示,同时复用官方的 Markdown、本地化文案和紧凑排版。将扩展做成可选的 renderer 参数,再由宿主选择直接渲染或 chain fallback,会让默认正文存在于注册体系之外,插件也只能另行维护 Markdown 调用。 + +渲染位置与基础实现是两种不同的能力:位置允许多个插件注册并由框架选中一个,实现则应允许任何组件直接调用。调用基础实现不应再次触发该位置的插件选择,也不应要求 Session。 + +## 决策 + +沿用现有 [Component Factory](2026-09-10-component-factories-and-local-slots.zh.md) 和普通 Slot,不增加框架分发机制。 + +| 名称 | 类型 | 所有者与职责 | +| --- | --- | --- | +| `conversation.chat.reasoning.body` | `single`、`session` Slot | Assistant 节点注册声明的正文位置;展开时只接收原始文本与流式状态。 | +| `conversation.chat.reasoning.content` | `root` Factory | `ui-chat` 提供的标准思考正文;接收文本、流式状态及可选 labels,提供默认文案并固定 `variant="compact"`。 | + +Factory 不接收 Session 身份,不读取 Session,不持有翻译状态。现有 Factory API 要求填写 `scope`,使用 `root` 表达无 Session 依赖;每个调用位置仍有独立的 React 实例。Factory 由 Chat 插件注册,而非依附于某个 Body occupant,第三方替换正文不会撤掉基础实现。 + +### 注册与调用 + +1. `ui-chat` 注册 Content Factory,组件 props 由 `FactoryComponentPropsOf` 推导。调用者未传 labels 时,Factory 使用 Chat 的 locale seat 构造稳定的默认文案。 +2. Assistant 节点注册声明 Body Slot。`ReasoningRow` 展开时只调用 `renderSlot`,不接收可选 renderer,不提供内联 fallback,也不判断插件是否启用。 +3. 官方以 `priority: 100` 注册普通默认 Body。该组件只将 `text`、`running` 传给 Content Factory。 +4. 第三方通过 `slots.inject` 等待 Body 声明,以较小的 priority 注册自己的 Body。第三方可直接调用 Content Factory,并在外层增加自己的控件;无需导入官方私有 React 组件。 +5. 第三方注销后,框架重新选中官方默认注册项。多个第三方注册遵循现有 single 优先级,不形成 middleware,也不同时渲染多份正文。 + +```text +ReasoningRow + └─ conversation.chat.reasoning.body + ├─ 官方默认 Body ───────────┐ + └─ 第三方 Body → 自有控件 ─┤ + └─ conversation.chat.reasoning.content + └─ MarkdownText +``` + +正文调用位置: + +```tsx ignore-check +
+ {renderSlot('conversation.chat.reasoning.body', { text, running })} +
+``` + +默认 Body 与第三方包装都使用同一个可复用实现;第三方需要自定义文案时传入 labels: + +```tsx ignore-check +renderFactorySlot('conversation.chat.reasoning.content', { + text: displayText, + running, + labels, +}) +``` + +### 数据、状态与生命周期 + +- `ReasoningBodyOwnerProps` 仅包含只读的 `text: string` 与 `running: boolean`。`ReasoningContentInput` 另外允许 `labels?: MarkdownLabels`;传入的文案原样使用,不做字段级合并,省略时才使用官方默认文案。调用者负责自定义文案的本地化与引用稳定性。 +- Body 的 `text` 始终是原始思考。第三方选择原文或派生显示文本后,只将该值交给 Factory,不改写 Session 或 Chat projection。 +- 折叠状态、摘要、流光和标题由 `ReasoningRow` 保持现有行为。插件自己的切换状态、按钮及样式留在其 Body 包装中;官方不提供 `setHeaderAction`、标题动作类型或相应状态。 +- 注册沿用 Cordis effect 生命周期。Body 声明撤销时,其贡献随 `slots.inject` 清理;Content Factory 在 Chat 插件卸载时撤销。 +- Factory 组件与默认 Body 使用模块级稳定身份,文本变化作为 props 更新,不以文本重建组件类型或 key。插件替换或 HMR 可按现有框架语义重新挂载,不承诺保留被卸载组件的本地状态。 + +### 翻译插件接入 + +[免登录翻译设计](2026-10-05-anonymous-reasoning-translation.zh.md)保留外部请求、隐私、失败与取消决策;其正文组合方式由本方案取代。翻译插件注册到标准 Body Slot,在自己的工具栏内渲染原文/译文切换、状态及重试按钮,使用自己的状态和可选自定义 labels 包装官方 Content Factory,不直接调用 `MarkdownText`。 + +翻译请求、分片、缓存、持久化和设置保持不变。翻译切换按钮属于插件正文,不再由官方思考标题承载;不增加正文外的 Slot,不处理用户消息遮挡,也不改动通用 Markdown 解析器。 + +## 考虑过的替代方案 + +**翻译专用 chain 与宿主 fallback。** 默认内容不是普通注册项,宿主需要维护第二条渲染路径,第三方无法直接复用完整的官方正文实现。 + +**只开放 Body Slot。** 可以替换正文,但第三方包装时仍需复制官方 Markdown 调用、labels 与 variant。 + +**只提供 Content Factory。** 可以复用实现,但缺少允许第三方注册替换的实际正文位置。 + +**跨插件导出 React 组件。** 绕过现有 Factory 的加载、生命周期与类型推导,增加 feature-plugin 运行时依赖。 + +**将 Factory 命名为通用 Markdown。** 该实现固定思考正文的紧凑排版,并提供 Chat 默认文案,不是所有 Markdown 场景的通用入口。 + +**官方替插件维护标题动作。** 官方默认正文没有该需求;保留专用 setter 会让宿主承担插件的状态、清理与按钮样式。 + +**Factory 强制使用官方 labels。** 默认文案不应阻止调用者定制;可选参数即可表达覆盖,无需替换整套正文实现。 + +## 验证 + +- 正文宿主只调用 `conversation.chat.reasoning.body`,没有旧 `reasoning-body` chain、可选 renderer 或内联 Markdown fallback。 +- 官方默认 Body 和翻译 Body 都通过 `conversation.chat.reasoning.content` 渲染;未传 labels 使用官方默认文案,传入自定义 labels 则原样交给 Markdown。 +- Factory 在没有 Session Provider 的调用位置也能使用;两个调用位置不共享组件本地状态。 +- 官方不存在标题动作类型、setter、状态或专用样式;翻译包装自行提供切换与重试控件。 +- 翻译插件启用、停用及 HMR 后,框架选中对应 Body;默认输出、原文访问、流式展示、折叠和取消行为保持一致。 +- 单元与装配测试覆盖注册撤销、无 Session Factory、labels 缺省与覆盖、默认与第三方共用实现及双实例;已有浏览器回放覆盖默认正文和翻译切换。 + +## 后果 + +旧 Slot 名称、chain selector 注册及标题动作回调不再受支持,第三方需要迁移。测试夹具与 Client inspect catalog 必须同步到新声明,避免仍向插件开发者提供旧注册方式。 + +Body 仍是独占替换位置。此方案不解决多个正文转换插件的自动组合,也不将显示变换提升为脱敏或模型输入修改能力。 diff --git a/.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.i18n.yaml new file mode 100644 index 0000000000..544d0c2c04 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-09-stored-credential-precedence.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-stored-credential-precedence.md +/agent-note-stored-credentials-take-precedence-over-the-launch-environment: + en: 5253af6605ba0fac + zh: 160ac751c664a502 +/agent-note-stored-credentials-take-precedence-over-the-launch-environment/problem: + en: 878c68dcfe5b3771 + zh: 8a24d16118155245 +/agent-note-stored-credentials-take-precedence-over-the-launch-environment/decision: + en: 7cd89bda9f793431 + zh: 93d26a948eea63f3 +/agent-note-stored-credentials-take-precedence-over-the-launch-environment/per-run-overrides: + en: 7479ffc82280a1fb + zh: ce3d42489191ab2b +/agent-note-stored-credentials-take-precedence-over-the-launch-environment/alternatives-considered: + en: 268add7fd8415280 + zh: 0765cbfd3fc7b57c +/agent-note-stored-credentials-take-precedence-over-the-launch-environment/consequences: + en: 2d71fd527b3060c4 + zh: fafed884315b9782 diff --git a/.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.md b/.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.md new file mode 100644 index 0000000000..75997d9db0 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.md @@ -0,0 +1,45 @@ +# Agent Note: Stored credentials take precedence over the launch environment + +Status: implemented + +English | [中文](2026-10-09-stored-credential-precedence.zh.md) + +The [headless environment authentication](2026-10-12-headless-environment-auth.md) decision partially supersedes this note's per-run override policy: the shipped headless profile omits the store. The ordering below remains the store's contract when mounted. + +## Problem + +[Configuration source ownership](2026-08-04-configuration-source-ownership.md) ranked the inherited process environment above `$DSH_HOME/.credentials.yaml`, and `credentials-local` refused `set` and `unset` for a name the launching shell exported. Two kinds of stored credential then had opposite precedence. pi-ai's resolvers read the credential record stored under `llm-pi-ai/` before any environment variable, so a stored OAuth grant or `api-key` record won over an exported key. A key that the Models page stored under a reference lost to the same exported name. Which credential a request used therefore depended on the provider family, and the Models page disabled its key field whenever the name was exported (#5527). + +## Decision + +**A stored credential wins for every provider.** `LocalCredentialProvider` resolves a reference in this order: + +```text +$DSH_HOME/.credentials.yaml (provider-managed, written by set/unset) +> inherited process environment (fallback; the provider never writes it) +> /.env (fallback; the provider never writes it) +> $DSH_HOME/.env (fallback; the provider never writes it) +``` + +A save always writes the winning layer, so `describe` reports `writable: true` for every reference, and `set` and `unset` never refuse a name because it is exported. `resolve` and `describe` still report the supplying layer as `source` (`file`, `env`, `project-env`, or `user-env`). `authContextFrom` in `llm-pi-ai` answers pi-ai's `env()` from the credential seam before the launch environment, so a pi-ai resolver reads its stored record first, then a stored reference, then the fallbacks in the order above. + +The non-secret ordering and the environment restrictions in configuration source ownership are unchanged. This note supersedes only its credential ordering. + +## Per-run overrides + +The previous order existed so that CI, containers, and a one-shot `DEEPSEEK_API_KEY=… dsh` could override a credential without editing machine state. A fresh CI or container harness home has no `.credentials.yaml`, so its exported secret is still the effective value. A harness home holds a stored key only because someone saved it there, through the Models page or by editing the file. To use an exported value for that name, the user deletes the `refs` entry, or launches with a separate `DSH_HOME`. + +## Alternatives considered + +**Keep the launch environment on top.** It keeps per-run overrides without touching the store, but it keeps the opposite precedence of stored records and stored references, and the Models page cannot save or replace a key while the launching shell exports the name. + +**Refuse a write while only the launch environment supplies the name.** Under the new order such a write takes effect, because the stored value outranks the environment. Refusing it would block the first save of a key for every exported name, and it would keep the read-only field state that the new order removes. + +**Warn when a stored value hides an exported variable.** The provider would compare layers on every resolution and report the result for users who keep both values on purpose, such as a shell profile that exports a key for other tools. The Models page help text states the order, and `describe` reports the supplying layer. + +## Consequences + +- A key left in `.credentials.yaml` overrides an exported variable with the same name, including a CI secret on a machine whose harness home stores a value for that name. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.md) tells affected users how to keep the exported account. +- The Models page can always save, replace, or remove a key, and it does not disable the key field for an exported name. +- There is no per-run flag above the store. A one-run override takes a separate `DSH_HOME`. +- `packages/credentials/credentials-local/tests/local.spec.ts` covers a store over a launch environment value and its return after `unset`; `packages/llm/llm-pi-ai/tests/auth.spec.ts` covers a stored credential that wins over every launch layer. diff --git a/.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.zh.md b/.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.zh.md new file mode 100644 index 0000000000..3846944c8d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.zh.md @@ -0,0 +1,45 @@ +# Agent Note: 存储的凭据优先于启动环境 + +Status: implemented + +[English](2026-10-09-stored-credential-precedence.md) | 中文 + +[Headless 环境认证](2026-10-12-headless-environment-auth.zh.md)决策部分取代本文的单次覆盖策略:随附 headless profile 不挂载存储。存储挂载时仍遵循下述顺序。 + +## 问题 + +[配置来源所有权](2026-08-04-configuration-source-ownership.zh.md) 把继承的进程环境排在 `$DSH_HOME/.credentials.yaml` 之前,并且 `credentials-local` 会拒绝对启动 shell 已导出的名字执行 `set` 和 `unset`。于是两类存储的凭据具有相反的优先级。pi-ai 的解析器先读取存储在 `llm-pi-ai/` 下的凭据记录,再读取任何环境变量,因此存储的 OAuth 授权或 `api-key` 记录会压过导出的密钥;而 Models 页面以引用形式存储的密钥会输给同名的导出变量。一次请求使用哪个凭据因此取决于提供方类别,而且只要该名字被导出,Models 页面就会禁用其密钥输入框(#5527)。 + +## 决策 + +**存储的凭据对每个提供方都优先。** `LocalCredentialProvider` 按以下顺序解析引用: + +```text +$DSH_HOME/.credentials.yaml (provider-managed, written by set/unset) +> inherited process environment (fallback; the provider never writes it) +> /.env (fallback; the provider never writes it) +> $DSH_HOME/.env (fallback; the provider never writes it) +``` + +保存总是写入胜出的那一层,因此 `describe` 对每个引用都报告 `writable: true`,`set` 与 `unset` 也不会因为名字已被导出而拒绝。`resolve` 与 `describe` 仍以 `source`(`file`、`env`、`project-env` 或 `user-env`)报告提供值的层。`llm-pi-ai` 中的 `authContextFrom` 先从凭据 seam、再从启动环境回答 pi-ai 的 `env()`,因此 pi-ai 解析器依次读取其存储的记录、存储的引用,再按上面的顺序读取后备来源。 + +配置来源所有权中的非秘密顺序与环境限制保持不变。本 Note 只替代其中的凭据优先级。 + +## 按次覆盖 + +之前的顺序让 CI、容器和一次性的 `DEEPSEEK_API_KEY=… dsh` 无需修改机器状态就能覆盖凭据。全新的 CI 或容器 harness home 中没有 `.credentials.yaml`,因此其导出的机密仍是生效值。harness home 中存有密钥,只可能是有人通过 Models 页面或直接编辑该文件存入的。要对该名字使用导出的值,用户应删除对应的 `refs` 条目,或使用单独的 `DSH_HOME` 启动。 + +## 考虑过的替代方案 + +**保持启动环境在最上层。** 它无需改动存储就能保留按次覆盖,但会保留存储记录与存储引用之间相反的优先级,而且只要启动 shell 导出了该名字,Models 页面就无法保存或替换密钥。 + +**只有启动环境提供该名字时拒绝写入。** 在新顺序下这样的写入会生效,因为存储值优先于环境。拒绝它会阻止为每个已导出的名字首次保存密钥,也会保留新顺序已经去掉的只读输入框状态。 + +**存储值遮蔽导出变量时发出警告。** 提供方需要在每次解析时比较各层,并向有意同时保留两个值的用户报告结果,例如在 shell 配置文件中为其他工具导出密钥的用户。Models 页面的帮助文本说明了该顺序,`describe` 也会报告提供值的层。 + +## 后果 + +- 留在 `.credentials.yaml` 中的密钥会覆盖同名的导出变量,包括在 harness home 存有该名字的机器上运行的 CI 机密。[升级指南](../../../../docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.zh.md)说明受影响的用户如何继续使用导出的账户。 +- Models 页面总能保存、替换或删除密钥,也不会因名字被导出而禁用密钥输入框。 +- 存储之上没有按次生效的标志。一次运行的覆盖需要使用单独的 `DSH_HOME`。 +- `packages/credentials/credentials-local/tests/local.spec.ts` 覆盖在启动环境值之上存储、以及 `unset` 后恢复该值;`packages/llm/llm-pi-ai/tests/auth.spec.ts` 覆盖存储的凭据压过每个启动层。 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..b34903faef --- /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: ca3153ae96994baa + zh: de6c7d925559efbb +/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: fd9152c3f5edb035 + zh: 259337cdcc5969a5 +/agent-note-chat-group-tree-positions-and-exchanges/consequences: + en: 2a98bb21bb1315d1 + zh: be4a320e9b427a79 +/agent-note-chat-group-tree-positions-and-exchanges/testing: + en: e2e3982718e16ef4 + zh: 4f3802946e51c55c 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..0fffb84e71 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-11-chat-group-tree-exchanges.md @@ -0,0 +1,56 @@ +# 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' | 'input' | 'turn' | 'process'` and ordered outermost first; a Node at a position also has the effect of every inner position. `exchange` opens an exchange. `input` makes the Node an input of its Turn: before the Turn's process it is the opening input, after it an interleaved input that keeps the whole Turn open. `turn` keeps the Node outside the Turn's process disclosure, `process` keeps it inside the disclosure but outside step runs, and a Node without a position joins the surrounding step run. `isAtOrOutside(node, position)` is the single reader of that order: process grouping reads `process`, whole-Turn folding reads `turn`, Turn-input detection reads `input`, and exchanges read `exchange`. +- **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`; later human input and trigger notices stand at `input` and never open an exchange. +- **Built-in positions.** `turn-error`, `turn-max-tokens`, `turn-tail`, and the `turn-process` control stand at `turn`; `model-retry` stands at `process`. Two placement rules stay with ui-chat's own `assistant-step` Node: its reasoning row joins the step run while its reply row stands outside it, and the Turn's process specification keeps the finalized answer's reply outside the disclosure because which step answers changes as later steps arrive. +- **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. Folds caused by human input without an echo on this page are handled by [one fold motion for collapsing on the next message](2026-10-13-chat-single-fold-motion.md). + +**Read Turn inputs at `turn`.** Terminal errors, max-token notices, and the completed-turn footer also stand outside the process disclosure, so reading `turn` would treat them as opening input; Turn inputs need their own position. + +**Derive the exchange from an `input` in Step 1.** A trigger notice is its Turn's opening input but must not open an exchange. Deriving the exchange would drop trigger notices from `input` and change how notice-woken Turns order their process rows. + +## Consequences + +- Notice-woken Turns no longer cause a fold, reserved room, or blank space. +- External Definitions place their Chat rows through `groupTree`. Apart from the two `assistant-step` rules, ui-chat names no kind when it groups, folds, or detects Turn inputs, and built-in kinds keep the placement their former kind lists gave them. +- 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; its landing follows [one fold motion for collapsing on the next message](2026-10-13-chat-single-fold-motion.md). + +## 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, with non-opening inputs at `input`. +- `packages/client/ui-chat/tests/process-groups.client.spec.ts`: a Node at any position splits the step run regardless of its kind, and a position change regroups. +- `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..395faed58b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-11-chat-group-tree-exchanges.zh.md @@ -0,0 +1,56 @@ +# 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' | 'input' | 'turn' | 'process'`,由外到内有序;站在某个位置的节点同时具有所有内层位置的效果。`exchange` 开启一个交互段。`input` 表示节点是所在 Turn 的输入:出现在该轮过程之前即为开场输入,之后出现即为中途输入,使整个 Turn 保持展开。`turn` 让节点留在 Turn 的整轮折叠之外,`process` 让节点留在整轮折叠之内、步骤组之外,没有位置的节点并入相邻的步骤组。`isAtOrOutside(node, position)` 是读取这一顺序的唯一入口:过程分组读 `process`,整轮折叠读 `turn`,轮次输入判断读 `input`,交互段读 `exchange`。 +- **交互段。** 含 `exchange` 节点的 Turn 开启一个交互段,交互段持续到下一个开启 Turn。业务层的 message Definition 只给 Step 1 中被认领的真人输入(`user` 或 `steering`)标 `exchange`;之后的真人输入和触发通知位于 `input`,不开启交互段。 +- **内置位置。** `turn-error`、`turn-max-tokens`、`turn-tail` 与 `turn-process` 控件位于 `turn`;`model-retry` 位于 `process`。ui-chat 自己的 `assistant-step` 节点保留两条放置规则:推理行并入步骤组、回复行在步骤组之外;该轮的过程规格让最终答案的回复留在整轮折叠之外,因为哪一步是最终答案会随后续步骤到来而变化。 +- **机制。** `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 自行决定位置。 + +**修正非自身输入折叠时的滚动补白。** 通知本来就不应触发折叠,修补白不能消除这次不必要的折叠。本页没有回显的真人输入引起的折叠,由[「下条消息时收起」只用一条折叠动画](2026-10-13-chat-single-fold-motion.zh.md)处理。 + +**在 `turn` 位置上判断轮次输入。** 终止错误、最大 token 提示和已完成轮次页脚同样在整轮折叠之外,读 `turn` 会把它们误当作开场输入;轮次输入需要自己的位置。 + +**由 Step 1 中的 `input` 推导交互段。** 触发通知是所在 Turn 的开场输入,却不能开启交互段。推导交互段就得把触发通知移出 `input`,从而改变通知唤醒的 Turn 中过程行的排列。 + +## Consequences + +- 通知唤醒的 Turn 不再产生折叠、补白和空白。 +- 外部 Definition 通过 `groupTree` 放置自己的 Chat 行。除 `assistant-step` 的两条规则外,ui-chat 在分组、折叠和判断轮次输入时不点名任何 kind,内置 kind 保持原 kind 名单给出的放置。 +- 「下次发送时收起」下,一长串通知唤醒的 Turn(抽样会话中 Goal 模式最长 31 轮)会一直展开,直到真人再次输入。 +- 已加载窗口里没有开启 Turn 时,所有已加载 Turn 都属于最新交互段。 +- 另一个标签页里的真人输入在它的 `user/message` 到达时才折叠,比原来在 `turn/start` 时晚约 200 ms;其落点按[「下条消息时收起」只用一条折叠动画](2026-10-13-chat-single-fold-motion.zh.md)决定。 + +## 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,非开启输入位于 `input`。 +- `packages/client/ui-chat/tests/process-groups.client.spec.ts`:任意位置上的节点不论 kind 都会切开步骤组,位置变化会触发重新分组。 +- `apps/web/tests/notice-wake-tail.e2e.ts`:长 Turn 之后由通知唤醒,在 Step 1 前的间隔和通知回复之后,上一轮都保持展开,跟尾读者看到通知与回复。 diff --git a/.agents/notes/implemented/architecture/2026-10-12-exclusive-conversation-matches.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-12-exclusive-conversation-matches.i18n.yaml new file mode 100644 index 0000000000..e1f4c7c1e9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-exclusive-conversation-matches.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-12-exclusive-conversation-matches.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-12-exclusive-conversation-matches.md +/agent-note-exclusive-conversation-matches: + en: 6f78605cc85cf7f2 + zh: f73e26bb3f9d1896 +/agent-note-exclusive-conversation-matches/problem: + en: 38ed7541d4cb7019 + zh: 98ed08f8c0c7c5ba +/agent-note-exclusive-conversation-matches/decision: + en: f2bfa3d0cc6b429a + zh: c1dd501c79086d71 +/agent-note-exclusive-conversation-matches/alternatives-considered: + en: efd209a2c0e97381 + zh: 8b6f10ff4de49449 +/agent-note-exclusive-conversation-matches/consequences: + en: 414ae7349bd4cc03 + zh: 9861b3e72bdfc548 +/agent-note-exclusive-conversation-matches/testing: + en: a88ed18065da4d28 + zh: 5bf4448a8b1f4763 diff --git a/.agents/notes/implemented/architecture/2026-10-12-exclusive-conversation-matches.md b/.agents/notes/implemented/architecture/2026-10-12-exclusive-conversation-matches.md new file mode 100644 index 0000000000..5dc353f598 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-exclusive-conversation-matches.md @@ -0,0 +1,52 @@ +# Agent Note: Exclusive Conversation matches + +Status: implemented + +English | [中文](2026-10-12-exclusive-conversation-matches.zh.md) + +## Problem + +Every event Definition matches each event independently, and a target may hold a generic Definition that presents a whole event family. When a business Definition presents one kind of that family itself, both Definitions match the same event and each builds a Context and a Node. Nothing let the business Definition say that the event belongs to it on that target. + +The late question reply is the shipped case. Chat's generic `input-message` Definition matches every appended `user/message`, and the questions UI's `question-reply` Definition matches the reply message it presents. Chat process grouping therefore dropped the duplicate `turn-trigger` presentation by message id, in both the Turn-owned and unscoped paths, and anchored the Turn control to the first group member so it stayed above the reply. The duplicate Node remained in the Node Store, and the generic Definition kept treating the reply as context or a trigger notice. + +## Decision + +A match result may claim its event on the Definition's target: + +```ts +interface ConversationMatchResult { + readonly id: string + readonly role: 'start' | 'update' + readonly exclusive?: true +} +``` + +- **Dispatch.** `ConversationNodeAssembler.dispatchInput()` evaluates every match of one event into two reused arrays before accepting any, then settles claims. Other Definitions of a claimed target build no Context for the event, and that target's unmatched-event fallback does not run. Definitions of other targets and Definitions without a target still receive it. The outcome is independent of registration order. Live append and window collection share this dispatch. +- **Failures.** Two claims on one target, or a claim from a Definition without a target, throw during dispatch and name the event, its `seq`, and the claiming Definition kinds. +- **Scope.** A claim belongs to one event and comes from `match()`, so a Definition claims only the events it recognizes. The generic Definition declares nothing. +- **Current use.** `question-reply` returns `exclusive: true` for a recorded `user-question-reply` message. Chat no longer aggregates by message id, and the reply's placement is unchanged. + +## Alternatives considered + +**Definition precedence (`specific` / `default`).** A generic Definition would declare itself overridable, and dispatch would become a priority order rather than a statement of which Definition presents an event. A claim needs no change to the generic Definition, and two claims fail instead of silently ranking. + +**Declare human sources in a registry and render the reply through user-text rules.** The reply would stay a generic message Node with customized text. Chat's message and Inbox Definitions would need a service-backed predicate, registry changes would have to reassemble every bound Conversation, and the text rule would need the message source as a fact. A claim keeps the reply in its owning Definition. + +**Mark human-authored sources in durable data.** A generic field on the message source would let the generic Definition classify the reply, but it changes a persisted type, and replies recorded by released builds do not carry it. + +**Skip the reply kind in `input-message`.** The generic Chat Definition would name a plugin's source kind. + +**Deduplicate in the grouping output.** This is the replaced mechanism: the duplicate Node stays stored and visible to every other Chat reader, and each grouping path repeats the aggregation. + +## Consequences + +- A claimed event has exactly one Context per claimed target, so no hidden duplicate remains in the Node Store. +- A conflicting claim fails at dispatch rather than at registration, because claims are decided per event from event data. +- Dispatch makes one extra pass over an event's matches, usually one to three, and allocates nothing for events without a claim. +- A plugin that presents part of a generic Definition's event family on one target uses a claim; it does not need the generic Definition's cooperation. + +## Testing + +- `packages/client/ui-conversation/tests/conversation-assembler.client.spec.ts` ("exclusive matches"): a claim withholds the event from other Definitions of its target in either registration order and on live append; other targets, target-less Definitions, and no fallback; two claims and a target-less claim throw. +- `packages/client/ui-user-questions/tests/question-reply.client.spec.ts`: the reply match claims its event, and an assembler holding both message Definitions produces one Chat Node for the reply. diff --git a/.agents/notes/implemented/architecture/2026-10-12-exclusive-conversation-matches.zh.md b/.agents/notes/implemented/architecture/2026-10-12-exclusive-conversation-matches.zh.md new file mode 100644 index 0000000000..021b1cc918 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-exclusive-conversation-matches.zh.md @@ -0,0 +1,52 @@ +# Agent Note: Conversation 独占匹配 + +Status: implemented + +[English](2026-10-12-exclusive-conversation-matches.md) | 中文 + +## Problem + +每个事件 Definition 各自独立地匹配每个事件,同一个 target 上可能有一个呈现整类事件的通用 Definition。业务 Definition 自己呈现这类事件中的一种时,两个 Definition 会命中同一个事件,各自建立 Context 和 Node。业务 Definition 没有办法声明这个事件在该 target 上归它呈现。 + +迟到的问题回答是已上线的实例。Chat 的通用 `input-message` Definition 匹配每条追加的 `user/message`,问题 UI 的 `question-reply` Definition 也匹配它要呈现的回答消息。Chat 过程分组因此在有轮次归属和无轮次归属两条路径上都按消息 id 丢掉重复的 `turn-trigger` 呈现,并把整轮控件锚到组首成员,让它留在回答之上。重复的 Node 仍留在 Node Store 中,通用 Definition 也仍把回答当作 context 或触发通知。 + +## Decision + +match 结果可以在 Definition 的 target 上认领它的事件: + +```ts +interface ConversationMatchResult { + readonly id: string + readonly role: 'start' | 'update' + readonly exclusive?: true +} +``` + +- **派发。** `ConversationNodeAssembler.dispatchInput()` 先把一个事件的全部 match 求入两个复用数组,再结算认领,之后才逐个接收。被认领 target 上的其他 Definition 不为该事件建立 Context,该 target 的未匹配事件 fallback 也不运行;其他 target 的 Definition 与没有 target 的 Definition 照常接收。结果与注册顺序无关。实时追加和窗口收集共用这一派发。 +- **失败。** 同一 target 被认领两次,或没有 target 的 Definition 发起认领,都会在派发时抛错,错误信息包含事件、其 `seq` 与认领方 Definition 的 kind。 +- **范围。** 认领只对一个事件生效,由 `match()` 返回,因此 Definition 只认领它识别出的事件;通用 Definition 不需要声明任何东西。 +- **当前用法。** `question-reply` 对已记录的 `user-question-reply` 消息返回 `exclusive: true`。Chat 不再按消息 id 聚合,回答的放置不变。 + +## Alternatives considered + +**Definition 优先级(`specific` / `default`)。** 通用 Definition 得声明自己可被覆盖,派发也变成优先级排序,而不是声明由哪个 Definition 呈现事件。认领不要求改动通用 Definition,两个认领冲突时直接失败,而不是静默排序。 + +**用注册表声明真人来源,并通过用户文本规则渲染回答。** 回答会保持为通用消息 Node,只定制文本。Chat 的 message 与 Inbox Definition 需要一个依赖 service 的判断函数,注册表变化必须重新组装所有已绑定的 Conversation,文本规则还要把消息来源当作 fact 读取。认领让回答留在它自己的 Definition 中。 + +**在持久数据中标记真人撰写的来源。** 消息来源上的通用字段可以让通用 Definition 自行分类回答,但这会改动持久化类型,已发布版本记录的回答也不带这个字段。 + +**在 `input-message` 中跳过回答的 kind。** 通用的 Chat Definition 会点名插件的来源 kind。 + +**在分组输出层去重。** 这是被替换的机制:重复 Node 仍留在存储里,对其他所有 Chat 读取方可见,每条分组路径都要重复这一聚合。 + +## Consequences + +- 被认领的事件在每个被认领 target 上恰好只有一个 Context,Node Store 中不再残留隐藏的重复节点。 +- 认领冲突在派发时失败,而不是在注册时失败,因为认领由事件数据逐个决定。 +- 派发对每个事件的 match 多遍历一次,通常一到三个;没有认领的事件不产生额外分配。 +- 插件在一个 target 上呈现通用 Definition 事件族中的一部分时,使用认领即可,不需要通用 Definition 配合。 + +## Testing + +- `packages/client/ui-conversation/tests/conversation-assembler.client.spec.ts`("exclusive matches"):两种注册顺序与实时追加下,认领都会对同 target 的其他 Definition 屏蔽该事件;其他 target 与无 target 的 Definition 照常接收,fallback 不运行;两次认领与无 target 认领会抛错。 +- `packages/client/ui-user-questions/tests/question-reply.client.spec.ts`:回答的 match 认领其事件;同时持有两个消息 Definition 的 assembler 只为回答产生一个 Chat Node。 diff --git a/.agents/notes/implemented/architecture/2026-10-12-headless-environment-auth.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-12-headless-environment-auth.i18n.yaml new file mode 100644 index 0000000000..df5212392d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-headless-environment-auth.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-12-headless-environment-auth.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-12-headless-environment-auth.md +/agent-note-headless-jobs-omit-the-interactive-credential-store: + en: c768db5a7e821bf0 + zh: 423b3e423d071ddc +/agent-note-headless-jobs-omit-the-interactive-credential-store/problem: + en: 829df36d87975148 + zh: 171d29ef2f2e5079 +/agent-note-headless-jobs-omit-the-interactive-credential-store/decision: + en: af275ffea713f76b + zh: 12a3bacfcb147df7 +/agent-note-headless-jobs-omit-the-interactive-credential-store/alternatives-considered: + en: f6f8dfde4789adc8 + zh: ced62f3d1ec402e6 +/agent-note-headless-jobs-omit-the-interactive-credential-store/consequences: + en: 1c1a699dc9f5681f + zh: 4a72b09d24f9a005 diff --git a/.agents/notes/implemented/architecture/2026-10-12-headless-environment-auth.md b/.agents/notes/implemented/architecture/2026-10-12-headless-environment-auth.md new file mode 100644 index 0000000000..0a497c44e7 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-headless-environment-auth.md @@ -0,0 +1,30 @@ +# Agent Note: Headless jobs omit the interactive credential store + +Status: implemented + +English | [中文](2026-10-12-headless-environment-auth.zh.md) + +## Problem + +The [stored credential precedence](2026-10-09-stored-credential-precedence.md) decision makes GUI saves effective even when the shell exports a key for another application. A headless job sharing that Harness home can then use the GUI account instead of the key explicitly supplied to the job. Changing reference precedence alone would leave pi-ai provider records and saved grants ahead of the environment. + +## Decision + +The shipped headless bundle disables the base `credentials`, `authorization` and `deepseek-account` rows. API-key adapters already support compositions without the credentials service and resolve through the launch snapshot: process environment, invocation-directory `.env`, then Harness-home `.env`. The profile does not read, migrate, write or delete `.credentials.yaml`. Dependent authorization and account rows are disabled explicitly so ordinary jobs do not emit pending-service warnings. + +This partially supersedes the per-run override policy in stored credential precedence for the shipped headless profile. Other profiles and an explicitly restored headless store retain stored-first resolution. The headless [README](../../../../packages/bundle/headless/README.md#credentials) owns the restoration patch. + +## Alternatives considered + +**Put the environment first in every profile.** It prevents a GUI save from replacing a key left in the launching environment and restores inconsistent reference and provider-record precedence. + +**Disable only the credentials row.** It achieves environment selection but leaves authorization and the account provider pending, producing warnings on every launch. + +**Add a second precedence mode to the store.** It introduces configuration and record-handling policy into the shared provider when existing adapter fallbacks and profile overrides already supply the required behavior. + +## Consequences + +- Headless ignores saved API keys, provider records and grants. A provider requiring stored sign-in or the DeepSeek account route fails until the user restores stored authentication; restoring it also restores saved-first precedence. +- Environment and external provider credential chains remain available. Sessions, settings and tools stay composed; omission of the store does not deny filesystem reads by tools. +- Web, SDK and ACP retain the credential store. Their authentication, login and refresh implementations are unchanged. +- Profile-level process tests cover all three environment layers, named and native pi-ai authentication, missing keys, ignored malformed storage, restoration and preservation of the document. Existing headless transcripts and real-model workspace tests cover the remaining composition. diff --git a/.agents/notes/implemented/architecture/2026-10-12-headless-environment-auth.zh.md b/.agents/notes/implemented/architecture/2026-10-12-headless-environment-auth.zh.md new file mode 100644 index 0000000000..e6e0b8b870 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-headless-environment-auth.zh.md @@ -0,0 +1,30 @@ +# Agent Note: Headless 任务不挂载交互式凭据存储 + +Status: implemented + +[English](2026-10-12-headless-environment-auth.md) | 中文 + +## 问题 + +[已保存凭据优先级](2026-10-09-stored-credential-precedence.zh.md)的决策保证 GUI 保存的密钥生效,即使 shell 为其他应用导出了密钥。共享同一个 Harness home 的 headless 任务可能因此使用 GUI 的账户,而不是显式传给任务的密钥。只调整引用优先级仍会让 pi-ai 提供方记录和已保存 grant 排在环境变量之前。 + +## 决策 + +随附 headless 组合包禁用 base 中的 `credentials`、`authorization` 和 `deepseek-account` 行。API 密钥适配器已经支持不挂载凭据服务的组合,按启动快照解析:进程环境、运行命令的目录 `.env`、Harness home `.env`。该 profile 不读取、迁移、写入或删除 `.credentials.yaml`。显式禁用依赖它的 authorization 和 account 行,避免普通任务输出等待服务的警告。 + +这部分取代了已保存凭据优先级中针对随附 headless profile 的单次覆盖策略。其他 profile,以及显式恢复存储的 headless,仍按已保存凭据优先解析。headless [README](../../../../packages/bundle/headless/README.zh.md#credentials)负责恢复 patch 的用法。 + +## 考虑过的替代方案 + +**在所有 profile 中让环境变量优先。** 这会使 GUI 保存的密钥无法替换启动环境中遗留的密钥,并恢复引用与提供方记录之间不一致的优先级。 + +**只禁用 credentials 行。** 这能选用环境变量,但 authorization 与 account 提供方会保持 pending,每次启动都产生警告。 + +**给存储增加第二种优先级模式。** 现有适配器后备与 profile 覆盖已经满足需求;这种做法却会把额外配置和记录处理策略引入共享提供方。 + +## 后果 + +- Headless 忽略已保存 API 密钥、提供方记录和 grant。依赖已保存登录凭据的提供方或 DeepSeek account 路由会失败,直到用户恢复存储认证;恢复后也恢复已保存凭据优先。 +- 环境变量与提供方外部凭据链仍然可用。会话、settings 与工具继续组合;不挂载存储不会禁止工具读取文件系统。 +- Web、SDK 与 ACP 保留凭据存储;其认证、登录和刷新实现不变。 +- Profile 进程测试覆盖三个环境层、具名与原生 pi-ai 认证、缺失密钥、忽略畸形存储、恢复存储,以及文件保持原样。现有 headless 录制与真实模型工作区测试覆盖组合中的其余行为。 diff --git a/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.i18n.yaml new file mode 100644 index 0000000000..363cc2fb3c --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.i18n.yaml @@ -0,0 +1,91 @@ +# Bilingual-pair consistency record for 2026-10-12-peer-principal-and-remote-access.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-12-peer-principal-and-remote-access.md +/agent-note-peer-principals-and-method-level-remote-access-control: + en: 0c0fd0f567bd5c89 + zh: 464e34d05737a7bc +/agent-note-peer-principals-and-method-level-remote-access-control/problem: + en: f5b70ee2c0a3e32a + zh: 68776a916cb41f11 +/agent-note-peer-principals-and-method-level-remote-access-control/decision: + en: a15c7c13f167e5ac + zh: 63bcc2ef60c2f344 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/scope: + en: 86061e5578d06871 + zh: 08eb605fcd38329d +/agent-note-peer-principals-and-method-level-remote-access-control/decision/two-layers-principal-and-peer: + en: 6663ea33561eee82 + zh: 722fd3b8fae0ef90 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/peer-model: + en: db5b0cf33679e5ed + zh: 1b04328268a95abc +/agent-note-peer-principals-and-method-level-remote-access-control/decision/identity-types: + en: 31430c5b95295ead + zh: 8f4ba35b4406558d +/agent-note-peer-principals-and-method-level-remote-access-control/decision/peer-lifetime-and-revocation: + en: a01ac57fc71a84f0 + zh: 3e488ef3da5e4b8c +/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control: + en: a55516339b0d49dd + zh: 3281df9ea7878fc0 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/correspondence-with-rbac: + en: a78a2410eb52f777 + zh: a868bf1b0e690c9f +/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/resources-and-resource-readers-deepseek-ai-dsh-typert-protocol-deepseek-ai-dsh-typert-registry: + en: 625b20552962e268 + zh: 1136c0fd7cdc6901 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/endpoint-resources: + en: ec1677d8e338e115 + zh: 6bedd163f208eaa9 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/roles-bindings-and-policies-deepseek-ai-dsh-api-remote-access: + en: e57f396239ea9f56 + zh: ddb26278b1521ceb +/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/example-share-viewer: + en: 3c911f57f0f6ca4b + zh: 1509781eeda4c922 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/host-access-check-order: + en: 6c58dc8777e107ef + zh: bc14605c96e4d8f3 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/forwarded-events: + en: 5fe34ee5ec31942a + zh: ef39b020b0539b8f +/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/list-and-aggregate-methods: + en: 7865e159528e2d30 + zh: 1399d54632f4d926 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/access-snapshot-stream: + en: 41d7ac1faf2448d7 + zh: 6d523895a9abae68 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/client-face: + en: 7be28cd7e19e5377 + zh: 30b5aee957271d6c +/agent-note-peer-principals-and-method-level-remote-access-control/decision/security-invariants: + en: 2094587c320b6ccc + zh: 3a1d2a6b343500f4 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/recording-the-message-source: + en: 2ee3abed24d418f4 + zh: 25653dd24b95c220 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/code-review-rule-and-documentation: + en: e9a2e0d1534b8fe7 + zh: 085813c0b2b3c0d8 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/out-of-scope-and-future-work: + en: 4bb0314c20e4f25c + zh: 6ede1dd2193a01d7 +/agent-note-peer-principals-and-method-level-remote-access-control/decision/relation-to-existing-notes: + en: 305ec45a7cd85ed7 + zh: d2cd4209a56b1d0c +/agent-note-peer-principals-and-method-level-remote-access-control/alternatives-considered: + en: 130df2981ba550df + zh: e9a0a89af6fb50a3 +/agent-note-peer-principals-and-method-level-remote-access-control/consequences: + en: 89452c3c3f042e75 + zh: 9bcad00a60c65303 +/agent-note-peer-principals-and-method-level-remote-access-control/consequences/verification: + en: 048067eb02e6bf8a + zh: 12508b59f6b206b8 +/agent-note-peer-principals-and-method-level-remote-access-control/consequences/costs-and-limits: + en: 1e254cec680b1a37 + zh: 06a31e057ba965aa +/agent-note-peer-principals-and-method-level-remote-access-control/consequences/migration-list-for-pr-5945: + en: f904c62b68d46bb5 + zh: 34eb45b97302badb diff --git a/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md b/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md new file mode 100644 index 0000000000..a62f0a5e74 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md @@ -0,0 +1,672 @@ +# Agent Note: Peer principals and method-level Remote access control + +Status: implemented + +English | [中文](2026-10-12-peer-principal-and-remote-access.zh.md) + +## Problem + +A Remote method on the Host could not tell whom one call spoke for, and could not restrict callable methods by caller. The [`PeerScope`](../../../../packages/typert/protocol/src/types.ts) contract stated "Who the Peer is and what it may do are not recorded here"; [Connection](../../../../packages/client/connection/src/rpc-host.ts) had a single operator Peer, `admit()` returned it for every authenticated request, and the `/api` route and the interceptor's Fetch handler used it unconditionally instead of the admission result; [Gateway](../../../../packages/api/gateway/src/index.ts) silently fell back to `operatorPeer()` when a caller named no Peer. + +The first non-owner caller is a liveshare viewer. Viewer requests reach the owner's liveshare Host plugin through the Relay, and the plugin dispatched them in the owner's process as the operator, so the owner's Session treated a viewer's prompt as the owner's own input. PR #3854 pushed liveshare semantics into session-controller for this: the request body carries `origin`, every prompt writes a required `prompt/origin` event correlated by requestId, the controller folds origins, `serializeAdmission` extends to every prompt, and a new `api-session/external-admission` hook appears; liveshare maintains its own `READ_ENDPOINTS` allowlist and trims list/follow results; the frontend `clientWritePolicy` lives in ui-conversation, with three ways of reading it across five packages and seven places that hide UI by whether a callback was injected. + +One general mechanism is needed: + +- In-process Host code assigns the caller identity; no wire field can set or override it. +- Every call path names its Peer explicitly; there is no implicit fallback. +- Method-level permission is computed and enforced in one place on the Host; the frontend reads the same result to show or hide entries and follows rule changes automatically. +- A prompt records its caller with the user message, so a later check can tell who initiated each turn. + +## Decision + +### Scope + +| Part | Content | +|---|---| +| Peer identity | `PeerScope.principal` and `PeerScope.signal`; one Peer implementation `Peer` (renamed from `OperatorPeer`) with an options constructor; removal of the operator concept and every implicit Peer fallback; `connection.browserPeer`, `connection.createPeer()`, and `fetch(request, peer)`; a disposed Peer is always refused with `gateway/peer-disposed`; the `user-rpc` source records `principal?` | +| Method-level access control | `resources` readers on `@Remote`, `TypertResourceMap` resource kinds, and the `typert.resources` registry (typert-protocol, typert-registry); Gateway resolution of calls and forwarded events to resources; new package `@deepseek-ai/dsh-api-remote-access` (Host and Client faces): RBAC decisions over roles, bindings, and policies through `decide(request)`, list filtering through `allows()`, the first snapshot in the index and the access snapshot stream, and access hooks | +| Documentation | One code-review rule and terminology | + +### Two layers: principal and peer + +| Layer | Concept | Example | Cardinality | +|---|---|---|---| +| Authorization | principal: the caller identity that permission decisions read | `share-viewer{shareId, actor}` proven by a share token; the local user `{ kind: 'owner' }` | one principal has N peers | +| Connection | peer: the lifetime scope of one connection | a browser connection, one connection of a liveshare viewer | one peer per connection | + +| Concern | Layer | +|---|---| +| Method-level decisions, access hooks, access snapshots | principal | +| Recording `source.principal` | principal | +| Subscriptions, streams, connection-lifetime registrations (`peer.ctx`) | peer | +| Revocation | both: after revocation the policy gives that principal no binding, so its calls are all refused; the creator disposes every peer under it | + +The creator owns the principal→peers table; liveshare, for example, keeps one object per share grant that records every peer opened under it. + +### Peer model + +There is one Peer concept and one implementation; the operator concept is removed. + +```text +// @deepseek-ai/dsh-typert-protocol +export interface PeerScope { + readonly id: PeerId + /** Connection-lifetime registrations; disposed with the Peer. */ + readonly ctx: Context + /** Caller identity fixed at creation by in-process Host code; no wire field can set it. */ + readonly principal: Principal + /** Aborted once the Peer is disposed; Remote streams that speak for the Peer end with it. */ + readonly signal: AbortSignal + dispose(): Promise +} + +// @deepseek-ai/dsh-client-connection +export class Peer implements PeerScope { + constructor(owner: Context, options: { readonly principal: Principal }) +} + +interface HostConnectionHandle { + /** The Peer every authenticated browser connection shares; principal { kind: 'owner' }. */ + readonly browserPeer: PeerScope + /** Network admission: the admitted Peer or the refusal status. */ + admit(request: ConnectionTrustRequest): PeerAdmission + /** In-process only; disposed with the Context that read `ctx.connection`, or earlier by dispose(). */ + createPeer(options: { readonly principal: Principal }): PeerScope +} + +interface ConnectionFetchHandler { + fetch(request: Request, peer: PeerScope): Promise +} +bridge(req, res, apiHandler, peer, maxRequestBodyBytes?) + +// @deepseek-ai/dsh-api-gateway +interface InvokeRemoteRequest { …; readonly peer: PeerScope } // was `peer?` +wireStream.open(endpoint, payload, uplink, peer: PeerScope, signal) // was `PeerScope | undefined` +``` + +| Rule | Detail | +|---|---| +| Every path names its Peer | Network paths take it from `admit()`; in-process paths receive it from the caller. Gateway deletes `operatorPeer()` and `request.peer ?? …` and never creates a Peer | +| Browser connections share `browserPeer` | Every browser connection shares one Peer, and every use site names `connection.browserPeer` explicitly; there is no fallback variable. The in-page Host (webworker-runtime) also passes `browserPeer` explicitly | +| In-process Host automation | Code that calls Remote methods creates its own Peer with `createPeer({ principal })`. No production caller exists yet, so no fixed Host Peer is pre-provisioned | +| Multiple Peers | Each `createPeer()` returns an independent Peer; liveshare is to create one per viewer connection (wired on the #3854 side) | +| Exact Fetch routes | Exact routes such as file-upload, present-open, media-references, session-log-export, and inspector bypass the Gateway; the shared Fetch handler answers 403 to every non-owner Peer | + +### Identity types + +```text +// @deepseek-ai/dsh-typert-protocol + +/** + * Merge-extensible caller identities. Each driver declares its own entry. + * Every entry is a JSON value with a unique literal `kind`, carries no + * credential, and is safe to persist in a Session log. + */ +export interface PrincipalMap { + owner: { readonly kind: 'owner' } +} +export type Principal = PrincipalMap[keyof PrincipalMap] + +/** + * @param invocation - `ctx.invocation`; `undefined` outside a Remote call. + * @returns the caller's principal when it is not the owner; `undefined` for the + * owner and for trusted in-process code outside a Remote call. + */ +export function principalOf(invocation: RemoteInvocation | undefined): Principal | undefined +``` + +The single read point is `this.ctx.invocation.peer.principal`; an owner test is written inline as `principal.kind === 'owner'`, and an unknown kind is never the owner. External drivers extend `PrincipalMap` by declaration merging in their own package; liveshare's `share-viewer{ shareId, actor }` is declared on the #3854 side, and liveshare itself is unchanged here. + +### Peer lifetime and revocation + +| Event | Behavior | +|---|---| +| Gateway dispatch | The first step checks `peer.signal.aborted` and refuses a disposed Peer with `gateway/peer-disposed`, on HTTP, WebSocket, and in-process paths alike; wire paths check before they read the payload, so a malformed payload from a disposed Peer gets the same code | +| Streams when a Peer is disposed | The signal a Remote stream method observes joins `peer.signal`, and so does the `$events` stream lifetime; a WebSocket still closes with 1001 | +| Unary calls when a Peer is disposed | A unary call already running is not cancelled; later calls are refused | +| Revocation | After a business package revokes a grant, its policy gives that principal no binding, and the business package calls `invalidate(principal)`; the creator disposes every peer in its principal→peers table | + +### Method-level access control + +Resource types and the `resources` readers of `@Remote` live in `@deepseek-ai/dsh-typert-protocol`; resource kinds live in typert beside lookups and Contexts: `TypertResourceMap` declares the kinds, `typert.resources` holds each kind's default wire field, and lookups and Host Context adapters declare the resource kind their wire identity names. The Gateway resolves one call or forwarded event to the resources it touches. Decisions, list filtering, and the access snapshot live in the new package `@deepseek-ai/dsh-api-remote-access` (`packages/api/remote-access`), which reads no argument field. The Gateway and domain packages depend on remote-access only for types and inject `remoteAccess`; their only value dependency is `dsh-typert-protocol`, so `package-dependency-policy` gains no remote-access entry. Business packages define and register roles, bindings, and policies; liveshare is the first user. Apart from the built-in `global`, no resource-kind name appears in remote-access or the Gateway, which follows the [`packages/api` carries generic orchestration only](../../../../docs/defensive-patterns/remote-and-api.md) review rule. + +#### Correspondence with RBAC + +| This design | RBAC / IAM term | Meaning | +|---|---|---| +| principal | Subject / Principal | The caller identity, one entry of `PrincipalMap` | +| Peer | Session (RBAC session) | One connection of a principal; one principal has N Peers | +| owner | Superuser | Skips every check | +| action | Action / Permission | A Remote endpoint `ns/method`, or a forwarded event `event:`; the Gateway still calls it an endpoint internally | +| resource | Resource / Object | `{ kind: 'global' }`, or `{ kind, id }` of a declared resource kind | +| role | Role | An action set over one resource kind; a plain value of the business package | +| binding | RoleBinding (role assignment) | The principal holds a role on a resource, optionally with a condition | +| condition | Condition (IAM Conditions) | Attached to a binding; allows by the request's action, resource, and arguments, or refuses with a reason | +| policy | Allow policy | The bindings and optional `explain` a business package gives for one non-owner principal kind | +| explain | Denial explanation | Names a refusal reason when no binding allows; never changes the decision | +| Gateway | PEP (Policy Enforcement Point) | Resolves resources and enforces the decision | +| remote-access | PDP (Policy Decision Point) | Computes decisions, list filtering, and access snapshots | + +| Rule | Content | +|---|---| +| Default deny | A non-owner is allowed only when the role of some binding explicitly lists the action; an action no role lists, a resource without a binding, and a principal kind without a policy are all refused. Every Remote method is under access control; there is no separate accessibility marker | +| No inheritance between resources | `global` is not a parent of other resources: a grant on `global` implies no grant on any Session or Workspace, and a grant on a Workspace implies no grant on its Sessions | +| A `global` grant is an explicit global grant | A call that resolves to no resource touches `global`. Putting an action in a `global` role lets that principal call it without resource restriction, which is a high-risk grant; once the method is allowed, it can still decide each item inside with `allows(resource)` | + +#### Resources and resource readers (`@deepseek-ai/dsh-typert-protocol`, `@deepseek-ai/dsh-typert-registry`) + +```text +/** Merge-extensible resource kinds: the key is the kind, the value declares its identity type. */ +export interface TypertResourceMap {} +// @deepseek-ai/dsh-session/types: session: TypertResource +// @deepseek-ai/dsh-workspace/types: workspace: TypertResource + +// Runtime registries in typert +ctx.typert.resources.register(kind, { field }): TypertDisposer +ctx.typert.lookups.register(key, { parameter, wire, resource?, … }) // resource: the kind its wire id names +ctx.typert.contexts.registerHost(key, { wire, resource?, … }) // a TypertHostContextAdapter + +export interface TypertHostContextAdapter { + readonly wire: string + readonly wireTypeSymbol: string + /** Resource kind the wire identity names; access checks read the identity from args before resolve(). */ + readonly resource?: TypertResourceKind + resolve(id: Wire): Context | undefined | Promise +} + +export type RemoteAccessResourceKind = 'global' | TypertResourceKind +export type RemoteAccessResource = + | { readonly kind: 'global' } + | { readonly kind: K; readonly id: TypertResourceId } // for each declared kind K +export type RemoteAccessResourceOf = Extract + +/** Per-kind readers, called with the method's positional wire arguments. */ +export type TypertResourceReaders = { + readonly [K in TypertResourceKind]?: (...args: WireArgs) => Id | readonly Id[] | undefined // Id = TypertResourceId +} + +export interface RemoteMethodOptions { + readonly name?: string + readonly mode?: 'stream' + readonly resources?: TypertResourceReaders +} + +export function Remote( + option: string | RemoteMethodOptions>>, +): (method: (this: This, ...args: Args) => Result, + context: ClassMethodDecoratorContext Result>) => void + +export interface RemoteScopeOptions { + readonly name?: string + readonly resources?: TypertResourceReaders +} + +export function RemoteScope( + key: Extract, + option?: string | RemoteScopeOptions>>, +): (method: (this: This, ...args: Args) => Result, + context: ClassMethodDecoratorContext Result>) => void +``` + +| Rule | Content | +|---|---| +| Syntax | `@Remote({ name: 'page', resources: { session: (request) => request.address.kind === 'session' ? request.address.sessionId : request.address.childSessionId } })`; a Context method writes `@RemoteScope('agent')` and gets its Session resource from the Agent Context's `resource: 'session'`, and writes `@RemoteScope('agent', { resources: { workspace: (request) => request.workspaceId } })` when it needs another resource. Most methods write no `resources` and get their resources from automatic resolution | +| Resource kinds | The lower-level packages that declare the identity types merge the resource kinds: `session: TypertResource` in `@deepseek-ai/dsh-session/types` and `workspace: TypertResource` in `@deepseek-ai/dsh-workspace/types`. session-controller references the commands package, so a merge in session-controller would make commands reference session-controller and form a project-reference cycle. remote-access builds in `global`, which has no id and stays out of `TypertResourceMap`; typert reserves the name, and `typert.resources.register('global', …)` throws | +| Default fields and declarations | The domain that owns a kind registers its default wire field when its controller is constructed: the `SessionController` constructor calls `typert.resources.register('session', { field: 'sessionId' })` and the `WorkspaceController` constructor registers `workspace` → `workspaceId`; registering a kind twice throws. The Agent, Session, and `workspaceFileScope` lookups declare `resource: 'session'`, and the agent package's Agent Context declares `resource: 'session'` | +| Resolution precedence | Each resource kind takes, in order: ① that kind's reader in the method's `resources`; ② every lookup parameter that declares that kind as its `resource` contributes its wire identity, and an omitted optional lookup parameter contributes none; when the Context of a Context method declares that kind as its `resource`, the Context's wire identity contributes too; ③ that kind's default field: a top-level named argument of that name when one exists, otherwise that field of the first object argument. A default field names one identity, so an array there is an invalid value | +| Argument values | Resource resolution and the `args` of `decide()` read the named arguments validated against their Typert-compiled types: each JSON argument is decoded once by its codec, which drops object fields its type does not declare, and dispatch reuses that value, so a caller cannot change the resources with an undeclared field; lookup parameters and the Context identity keep their wire identities, and no lookup or Agent is resolved at that point | +| Resolution result | The resources of every kind together are the resources the call touches; with none, the call touches `[global]`; when resources resolve, only those are used and `global` is not added | +| Readers | Called with the method's positional arguments: the named arguments mapped by the descriptor back to the method's parameter order (the validated value in a JSON position, the wire identity in a lookup position, and the call's signal in the cancellation position); return one id, an id array (every one must be allowed), or `undefined` (no resource of that kind) | +| Invalid values | A reader that throws or returns an empty array, or a read value (including a Context's wire identity) that is not a non-empty string, makes the resources invalid: the Gateway refuses the call with `remote-access/denied` (reason `resource-invalid`) without asking `decide()` | +| Completeness | `resources` and automatic resolution must cover every resource the method touches. A call that resolves no resource falls to `global`, which only a `global` role can allow, so it is refused by default; when only some resources resolve, the rest go unchecked and a principal granted on the resolved resources can reach them, which the method author must prevent | +| Type inference | The parameter types of `@Remote` and `@RemoteScope` readers are inferred from the decorated method: the factory parameter uses `NoInfer`, so `Args` is inferred only from the returned decorator; lookup parameters map to wire types through `TypertLookupMap` (for a method whose first parameter is `agent: Agent`, the reader's first parameter is `SessionId`). A missing property, more parameters than the method has, and a `global` key fail compilation | +| Storage | `resources` readers live on the class prototype with the other `@Remote` / `@RemoteScope` metadata, are recorded on instance construction, and are safe across duplicate installations; they do not enter Typert artifacts | +| Context methods | `@RemoteScope(key, option?)` matches `@Remote`: a string is the export name and an object is `{ name?, resources? }`. A Context's wire identity takes part in resolution like a lookup parameter that declares a `resource`, with the same precedence, and a `resources` reader for that kind overrides it; the Gateway reads that identity directly from args before `resolveReceiverContext`, so no Agent is activated. A Context that declares no `resource` contributes no resource from its identity, and the method resolves by the ordinary rules | + +#### Endpoint resources + +The table lists the endpoints #3854 viewers use and where their resources come from. Only `session/page` and `session/follow` need explicit `resources`; the rest rely on a lookup's `resource` or the default field: + +| Endpoint | Resource | Resolution source | Filtering inside the method | +|---|---|---|---| +| `workspace/follow` | `global` | no resource | yes: Workspaces and Sessions | +| `session/control` | `global` | no resource | yes: Sessions | +| `session/list` | `global` (`_request` has no `sessionId`) | no resource | yes: Session rows | +| `session/modelCatalog` | `global` | no resource | no | +| `session/canOpenWorkspacePath` | `global` | no resource | no | +| `llm/listConfigurableProviders` | `global` | no resource | no | +| `llm/listProviders` | `global` | no resource | no | +| `commands/list` | session: `args.agentId` (the Agent lookup's wire field) | Agent lookup `resource: 'session'` | no | +| `goals/get` | session: `args.agentId` | Agent lookup `resource: 'session'` | no | +| `session/attachment` | session: `args.request.sessionId` | default field | no | +| `skills/list` | session: `args.request.sessionId` | default field | no | +| `session/fork` | session: `args.request.sessionId` | default field | no | +| `session/prompt` | session: `args.request.sessionId` | default field | no | +| `session/cancel` | session: `args.request.sessionId` | default field | no | +| `session/projections` | session: `args.request.sessionId` | default field | no | +| `session/page` | session: `args.request.address.sessionId` for a Session address; `args.request.address.childSessionId` for a subagent address | `resources` | no | +| `session/follow` | same as above | `resources` | no | +| `remoteAccess/follow` | `global` | no resource; remote-access allows it for every principal | no | + +A subagent address reads the child transcript, so its resource is the child Session. A Client rereads the projections of known Sessions after a reconnect, including the parent of a subagent Session; a reader without a grant on that parent has its projection read refused. Whether a grant on a parent Session covers its subagent children is the policy's decision, that is, whether it gives a binding for the child Session; the generic layer derives no parent resource. + +Methods that need no non-owner access declare nothing, and a method no role lists is refused. The request fields of subagent `prompt` are `parentSessionId` / `childSessionId`, so automatic resolution finds no Session and resolves it to `global`; it must therefore stay out of every `global` role. `session/search` filters its hits per Session inside the method. `subagents/list` is not a Remote endpoint (`SubagentRuntime.list()` carries no `@Remote`). + +#### Roles, bindings, and policies (`@deepseek-ai/dsh-api-remote-access`) + +```text +/** Remote endpoint `ns/method`, or `event:` for one forwarded event; endpoint segments never contain `:`. */ +export type RemoteAccessAction = RemoteAccessEndpoint | `event:${string}` + +/** A named action set over one resource kind; a plain value owned by the business package. */ +export interface RemoteAccessRole { + readonly name: string + readonly resource: K + readonly actions: readonly RemoteAccessAction[] +} + +/** Answer of decide() and of a condition. */ +export type RemoteAccessDecision = + | { readonly kind: 'allow' } + | { readonly kind: 'deny'; readonly reason: string } + +/** Refines one binding for one action on its resource; `args` only for a concrete call. */ +export type RemoteAccessCondition = (request: { + readonly action: RemoteAccessAction + readonly resource: RemoteAccessResourceOf + readonly args?: Readonly> +}) => RemoteAccessDecision + +/** One role on one resource of the role's kind; the resource type follows from the role. */ +export type RemoteAccessBinding = { + [K in RemoteAccessResourceKind]: { + readonly role: RemoteAccessRole + readonly resource: RemoteAccessResourceOf + readonly condition?: RemoteAccessCondition + } +}[RemoteAccessResourceKind] + +/** One access question; the Gateway passes only valid resources, [global] when none. */ +export interface RemoteAccessRequest

{ + readonly principal: P + readonly action: RemoteAccessAction + /** Allow only when the action is allowed on every listed resource. */ + readonly resources: readonly RemoteAccessResource[] + /** Named arguments of a concrete call, validated against their Typert-compiled types with lookup parameters as wire identities; absent for events, snapshots, and list filtering. */ + readonly args?: Readonly> +} + +/** Business rules for one non-owner principal kind; synchronous over in-memory state. */ +export interface RemoteAccessPolicy

{ + bindings(principal: P): readonly RemoteAccessBinding[] + /** Reason for a request no binding allows; never changes the decision. */ + explain?(request: RemoteAccessRequest

): string | undefined +} + +/** details of `remote-access/denied` */ +export interface RemoteAccessDeniedDetails { + readonly action: string + readonly reason: string +} + +class RemoteAccessService { // ctx.remoteAccess; Remote namespace remoteAccess + registerPolicy>(kind: K, policy: RemoteAccessPolicy): () => void + invalidate(principal?: Principal): void + decide(request: RemoteAccessRequest): RemoteAccessDecision // Gateway-only + allows(resource: RemoteAccessResource): boolean // reads the accessing ctx's invocation + snapshotFor(principal: Principal): RemoteAccessBaseline // a page's opening baseline + follow(signal): AsyncIterable // remoteAccess/follow +} +``` + +| Rule | Content | +|---|---| +| Owner | The Gateway does not resolve resources or call `decide()` for the owner, and reads no policy | +| Registration | `registerPolicy(kind, policy)` returns a disposer, and a business package calls it inside `ctx.effect()`. Each non-owner principal kind has at most one policy, and a second registration for the same kind throws; `bindings()` and `explain()` receive principals typed by the kind | +| Built-in allow | `remoteAccess/follow` is allowed for every principal, so every Peer can read its own snapshot | +| Decision | A principal kind without a policy is refused with `no-allow`. Otherwise `bindings(principal)` is read, and a linear scan finds for each requested resource one binding whose resource is equal (the same `kind` and, for a non-`global` resource, the same `id`), whose role's `actions` contains the action, and that has no condition or whose condition allows; the request is allowed only when every resource has one (AND). A condition runs only for a binding whose resource is equal and whose role contains the action | +| Refusal reason | The first resource not allowed decides the reason, in this precedence: when matching bindings exist on that resource but all their conditions refuse, the first condition's reason; otherwise the return value of `explain(request)`; without `explain`, or when it returns `undefined`, `no-allow`. `explain` runs only after the decision is already a refusal and never changes it | +| Failure isolation | When `bindings()`, a condition, or `explain()` throws, the decision is refused with `policy-failed`; in a snapshot computation, a throwing `bindings()` leaves that principal no grant and a throwing condition excludes that action. A faulty rule therefore never breaks the shared `$events` source, a snapshot stream, or page rendering; after each `invalidate()` or policy change, the first failure of each policy is logged once | +| Synchronous | `bindings()`, conditions, and `explain()` return synchronously from state the business package preloads in memory, so list filtering can decide per item and snapshots can be computed | +| Evaluation timing | Each `decide()`, each `allows()`, and each snapshot computation calls `bindings()` once, with no caching; time-dependent state (such as expiry) applies immediately, and a long stream (such as `workspace/follow` or `session/control`) reflects added or removed bindings at its next per-item decision; snapshots are recomputed only after `invalidate()`, so a business package also calls `invalidate()` when a time event such as expiry happens | +| Notification | When a business state change (grant, revocation, mode switch) alters a binding or a condition's answer, the business package must call `invalidate(principal?)`; snapshots are recomputed only after `invalidate()` and policy registration or removal | +| `remote-access/denied` | Only a call refusal becomes an error, with details `{ action, reason }`, where reason is the reason a condition or `explain` gave, `no-allow`, `policy-failed`, or the `resource-invalid` the Gateway gives for invalid resources; a refused event is simply not pushed | +| Required service | The Gateway declares `static inject = ['typert', 'remoteAccess']`; a composition that mounts the Gateway mounts remote-access, which [`bundle/base`](../../../../packages/bundle/base/cordis.patch.yml) assembles right after `typert-gateway`; the plugin manager protects it like the Gateway, so it cannot be disabled from the Plugins page | + +#### Example: share viewer + +The `share-viewer` principal that liveshare declares shows that the derivation from business state to bindings stays in the business package; `shares` in the example stands for the share state the business package holds in memory: + +```text +const globalReader = { name: 'share:global-reader', resource: 'global', actions: ['session/list', 'session/control', 'workspace/follow', 'session/modelCatalog', 'llm/listProviders', 'commands/list'] } +const sessionReader = { name: 'share:session-reader', resource: 'session', actions: ['session/page', 'session/follow', 'session/list', 'session/control', 'workspace/follow', 'commands/list', 'event:api-session/status', 'event:api-session/added'] } +const workspaceReader = { name: 'share:workspace-reader', resource: 'workspace', actions: ['workspace/follow'] } +const forker = { name: 'share:forker', resource: 'session', actions: ['session/fork'] } +const writer = { name: 'share:writer', resource: 'session', actions: ['session/prompt', 'session/cancel'] } + +ctx.effect(() => ctx.remoteAccess.registerPolicy('share-viewer', { + bindings(viewer) { + const share = shares.serving(viewer) // undefined once stopped, expired, or no longer admitted + if (share === undefined) return [] + const source = { kind: 'session', id: share.sessionId } + return [ + { role: globalReader, resource: { kind: 'global' } }, + { role: sessionReader, resource: source }, + ...(share.allowsFork ? [{ role: forker, resource: source }] : []), + ...(share.mode === 'write' ? [{ role: writer, resource: source, condition: sourceWrite(share) }] : []), + ...shares.forksOf(viewer).flatMap(child => [ + { role: sessionReader, resource: { kind: 'session', id: child.id } }, + ...(child.revoked ? [] : [{ role: writer, resource: { kind: 'session', id: child.id }, condition: childPrompt(child) }]), + ]), + ...shares.workspacesShowing(viewer).map(id => ({ role: workspaceReader, resource: { kind: 'workspace', id } })), + ] + }, + explain({ principal, action }) { + return shares.refusal(principal) // 'share-expired', 'share-stopped', … + ?? (action === 'session/prompt' ? 'share-not-writable' : undefined) + }, +})) + +// Without args (snapshots, list filtering) a condition answers for the action alone. +const sourceWrite = share => () => share.confined ? allow : deny('source-write-unavailable') +const childPrompt = child => ({ action, args }) => + action === 'session/prompt' && args !== undefined && !child.allowsPrompt() ? deny('fork-prompt-refused') : allow +``` + +| Owned by | Content | +|---|---| +| Business package | The action lists of roles; the derivation from share state to bindings (stop, expiry, admission, mode, the viewer's own forks, revocation, Workspaces containing visible Sessions); per-request conditions; refusal reasons for the viewer page | +| Generic layer | Resource resolution, AND across resources, role and action matching, condition calls, reason precedence, list filtering, snapshot computation, and failure isolation | + +That viewer's snapshot contains grants on `global`, the source Session, each of its own forks, and each visible Workspace; `session/list` appears in both a `global` role and a session role, see [List and aggregate methods](#list-and-aggregate-methods). + +#### Host access-check order + +Every call path (HTTP `/api`, WebSocket streams, in-process `fetch(request, peer)` / `invoke` / `stream` / `wireStream.open`) passes through one Gateway sequence: + +| Step | Action | Failure | +|---|---|---| +| 1 | Admission yields the Peer: network paths from Connection `admit()` (`browserPeer`), in-process paths from the caller. The Gateway checks `peer.signal` before it reads the wire payload | Failed network admission answers HTTP 401 / 403 without entering the Gateway; a disposed Peer: `gateway/peer-disposed` | +| 2 | Resolve the endpoint and validate the argument field set (`resolveDescriptor`, `assertExactArguments`), then validate the JSON arguments against their Typert-compiled types, decoding each once | `gateway/invocation-unavailable`, `gateway/ambiguous-endpoint`, `gateway/definition-unavailable`; extra or missing fields: `gateway/arguments-invalid`; a JSON argument failing validation: `gateway/input-invalid` (for owners and non-owners alike, before the access check) | +| 3 | Owner pass-through: for `principal.kind === 'owner'` go straight to step 5 | — | +| 4 | Non-owner: the Gateway resolves resources from the arguments validated in step 2 (`resources` readers, then lookup parameters and the `resource` a Context declares, then default fields; lookup and Context identities are wire identities, and neither a lookup nor the Context is resolved), then asks `remoteAccess.decide({ principal, action: endpoint, resources, args })` with the validated arguments as `args`; invalid resources are refused with `resource-invalid` without asking `decide()`; a `deny` decision becomes the thrown error | `remote-access/denied` with details `{ action, reason }` | +| 5 | Dispatch: `resolveReceiverContext` (which can activate an Agent), lookup resolution (JSON arguments reuse the step 2 values), and the method call | Existing codes unchanged, such as `gateway/lookup-not-found`, `gateway/context-not-found`, `gateway/input-invalid`, `gateway/service-unavailable`, `gateway/method-unavailable`, and business errors | + +The access check (steps 3–4) precedes lookup and Context resolution, so a refused call activates no Session and causes no other side effect. The only new Gateway error code is `gateway/peer-disposed`; remote-access declares the refusal code `remote-access/denied`. + +Gateway-owned endpoints: a non-owner may subscribe to `$events` but never receives waterfall frames it could answer; `$events/result` from a non-owner is refused with the existing `gateway/invocation-unavailable`; both run the step-1 check. + +#### Forwarded events + +An `emit` entry of `API_REMOTE_FORWARDED_EVENTS` may declare `resources`: readers keyed by resource kind and typed by that event's own parameters through `TypertForwardableEventEntry`, for example `{ event: 'api-session/added', mode: 'emit', resources: { session: (summary) => summary.sessionId } }`. API Remotes attaches the readers to each forwarded frame; for every non-owner `$events` stream the Gateway resolves the resources once per frame and pushes the frame only when `remoteAccess.decide({ principal, action: 'event:', resources })` allows it. + +| Rule | Content | +|---|---| +| Declared events | `api-session/activity`, `api-session/added`, `api-session/error`, `api-session/removed`, and `api-session/status` declare their Session | +| Undeclared resources | An event without `resources`, or with an empty `resources: {}`, touches `global` and reaches a non-owner only when a `global` role lists `event:` | +| Missing resource | An event carries every resource it declares, so a reader returning `undefined` makes the event's resources invalid, and the Gateway delivers it to no non-owner without asking `decide()`; a call missing a resource touches `global` instead | +| Whole or nothing | An allowed event arrives with its payload unchanged; no payload is trimmed or projected per Peer | +| One resource per event | A notification carries at most one resource; collection changes travel on follow streams (`session/follow`, `session/control`, `workspace/follow`), whose methods decide each item inline through `allows()` | +| Waterfalls | Non-owners never receive waterfall frames, and no policy decides them | +| Non-owner stream facts | A non-owner `$events` stream opens with the same `host` as an owner stream, including `home`; `hasLiveClient()` counts only owner streams, the ones that can answer waterfalls | + + +#### List and aggregate methods + +Calls of list, paging, and aggregate methods resolve to `global` and are allowed by a `global` role; inside, the method calls `this.ctx.remoteAccess.allows(resource)` for every item to decide whether the current call's action is granted on that resource (without args). A list action therefore appears both in a `global` role (allowing the call) and in resource roles (allowing each item): `session/list` must be granted on `global` to be called, and each Session row also requires `session/list` granted on that Session. `allows()` reads the invocation on the Context that accessed the service; it is always true for the owner and for in-process code outside a Remote call, which are not filtered. + +| Method | Filtered items | +|---|---| +| `session/list` | Session rows (`session` resource) | +| `session/search` | search hits (`session` resource) | +| `session/control` | baseline projections and projection increments (`session` resource) | +| `workspace/follow` | Workspaces in the baseline, `upsert` frames, and `order` ids (`workspace` resource), the Sessions inside Workspaces, and the archived / pinned Session sets (`session` resource). The stream tracks the Workspaces it delivered; when one is no longer allowed at its next change or in a new order, it sends a `replace` increment with the complete filtered state instead of a `remove`, because the Client never resurrects a removed id, and the Workspace reappears through an ordinary `upsert` once access returns. A `remove` frame reports a deletion and reaches only a caller that received that Workspace | + +#### Access snapshot stream + +```text +// Remote: remoteAccess/follow (stream; every Peer may read its own snapshot) +type RemoteAccessFrame = + | { readonly type: 'baseline'; readonly owner: true } + | { readonly type: 'baseline'; readonly owner: false; readonly grants: readonly RemoteAccessGrant[] } + | { readonly type: 'upsert'; readonly grant: RemoteAccessGrant } + | { readonly type: 'remove'; readonly resource: RemoteAccessResource } + +interface RemoteAccessGrant { + readonly resource: RemoteAccessResource // global, or one declared-kind resource + readonly actions: readonly string[] // endpoint actions allowed on this resource without args, sorted +} + +/** Window global carrying a page's opening baseline. */ +export const REMOTE_ACCESS_SNAPSHOT_KEY = '__DSH_REMOTE_ACCESS__' +``` + +| Behavior | Detail | +|---|---| +| First snapshot | `snapshotFor(principal)` computes a page's opening baseline. remote-access adds the global `REMOTE_ACCESS_SNAPSHOT_KEY`, set to the owner baseline `{ type: 'baseline', owner: true }`, to every index the webServer renders, through `webserver/index-inject`. A business package that renders a non-owner page (such as liveshare on the owner Host) places an assignment of that global to `snapshotFor(principal)` after every index injection row; the later assignment wins, and the Client reads the global when it mounts | +| Subscription | Each Peer subscribes to one access snapshot stream, whose baseline replaces the injected one | +| Computation | All bindings of the policy for the principal's kind are merged by equal resource; each resource's `actions` are the endpoint actions of those bindings' roles that the same decision as a call allows (one resource, without args, conditions called without args); only a resource with at least one allowed endpoint action gets a grant. Decisions and snapshots share one source: for the same principal, action, and resource (without arguments), the snapshot answer equals `decide()` | +| Endpoint actions only | `event:` actions do not enter the snapshot; the frontend decides entry visibility from endpoint actions only | +| Increments | `invalidate()` or a policy registration or removal recomputes and pushes `upsert` / `remove`, and a resource whose allowed set becomes empty pushes `remove`; unchanged resources push nothing | +| Lifetime | A generation ends when its signal aborts or when the remote-access service unloads, so a reloaded service answers every reader from a fresh baseline; the Client treats the end as a carrier loss and reconnects | +| Owner | Receives only `{ owner: true }`, so every frontend answer is true | +| Wire type | `actions` is `readonly string[]`: Typert cannot generate a codec for template-literal types | + +Access hooks judge only by action and resource and never look at call arguments; at call time a condition may also read args for a finer decision, and the Host result prevails. + +#### Client face + +The Client uses framework standard-hook injection and no React context. Components receive hooks only through props and import no remote-access value. + +```text +// @deepseek-ai/dsh-api-remote-access/client +interface ClientRemoteAccess { // Client service ctx.remoteAccess + source(kind: TypertResourceKind, id: string, action: string): HostObservable +} +GlobalStandardProps.useRemoteAccess: (action: RemoteEndpoint) => boolean // remote-access; the global resource + +// @deepseek-ai/dsh-client-ui-session (injects remoteAccess) +GlobalStandardProps.useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean +SessionStandardProps.useAccess: (action: RemoteEndpoint) => boolean +SessionMaybeStandardProps.useAccess: (action: RemoteEndpoint) => boolean | undefined + +// @deepseek-ai/dsh-client-ui-workspace (injects remoteAccess) +GlobalStandardProps.useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean + +// RemoteEndpoint = Extract +``` + +| Concern | Decision | +|---|---| +| Snapshot and mount | The remote-access Client plugin starts from the baseline the index injected (read synchronously at startup and validated), follows the snapshot stream, applies each baseline in one pass, provides the Client service `ctx.remoteAccess.source(kind, id, action)` (an identity-stable boolean source), and injects `useRemoteAccess` on the `global` resource. The entry module imports the generated `/remote` contribution and hands it with the injected baseline to `mountAccess(ctx, contribution, initial)`, which mounts it through `ctx.remote.$mount` (unit specs pass a fake contribution), following experimental client-ui-cot-translation, voice-input, and claude-code-mods; a central mount in api/remotes would form the project-reference cycle ui-session → api/remotes → remote-access → ui-session | +| Session resource | ui-session gives the bound Session's answer through `uiSession.provide({ keyedHooks: ['access'], resolve })`; the framework binds the Session as it does for `useProjection`. `useSessionAccess` is injected through `provideRoot` | +| Workspace resource | ui-workspace injects `useWorkspaceAccess` through `provideRoot` | +| Distinct names | The `global` answer is `useRemoteAccess` and the Session answer is `useAccess`, so neither shadows the other; in a session-maybe scope without a Session, `useAccess` is `undefined`, which callers treat as not allowed, and a `global` decision reads `useRemoteAccess` | +| Two-argument calls | Framework keyed hooks take a standard second argument: `KeyedStandardSource` is `(key, member?) => source`; a string second argument makes the hook read the resolver's `(key, member)` source without a selector, and the resolver returns the same source for the same arguments. Existing `(key, selector?, equal?)` and `(selector, equal?)` calls are unchanged. Curried forms are forbidden | +| Return value | Every answer on a resource is a boolean; action types come from the `ctx.remote` namespaces and methods | +| No fallback | Asking a Session resource about a non-session method (such as `useAccess('session/create')`) reads the decision on that Session resource and never falls back to the `global` answer | +| No snapshot | True for the owner, also after its stream fails terminally; a non-owner page without an injected baseline, or whose stream fails terminally, answers false, and the terminal failure is reported with its error and the advice to reload; a reconnect keeps the last snapshot; a malformed injected baseline fails the mount; the Host still checks every call. Hooks never issue requests | +| Example consumers | The ui-workspace Session row menu's fork entry reads `useSessionAccess(sessionId, 'session/fork')` and is not rendered when it is false; the ui-chat turn tail's branch button reads `useAccess('session/fork')` on the Session resource and is not rendered when it is false. Replacing #3854's `clientWritePolicy` stays with #3854 | +| Tests | `@deepseek-ai/dsh-client-test-runtime` exports `allowAllAccess` props and `allowAllAccessPlugin`; TestClient drops the remote-access row as it drops api-remotes and installs the allow-all service, and SlotTestRuntime installs it before ui-session | + +### Security invariants + +| Invariant | Basis and enforcement point | +|---|---| +| Only in-process Host code supplies a principal, when it creates a Peer | `PeerScope.principal` is read-only; `createPeer()` has no route | +| No wire field can set or override a principal | Principals never come from args, the envelope, headers, the query, or cookies. Extra top-level args fields fail `assertExactArguments`; the payload must be exactly `{ args }`; [`clientRequestSchema`](../../../../packages/client/connection/src/rpc-schema.ts) drops unknown envelope fields; a same-named field inside a request body is business data | +| Browser network admission yields the owner | Connections that pass [browser token authentication](../../implemented/architecture/2026-08-24-browser-token-authentication.md) receive `browserPeer` | +| No implicit Peer | Neither the Gateway nor Connection supplies a default Peer; required parameters expose a missing Peer at compile time | +| A disposed Peer cannot dispatch | `gateway/peer-disposed` | +| A non-owner cannot call without authorization | A call is allowed only when a binding's role explicitly lists the action and its resource matches; a kind without a policy is refused; the Gateway depends on `remoteAccess` and does not start without it | +| A `global` grant implies no resource grant | Resources do not inherit; `allows()` inside a method decides each item independently | +| An unknown principal kind is not the owner | Only `kind === 'owner'` is the owner | +| Non-owners answer no waterfall | `$events` gives non-owners no waterfall frame, and `$events/result` refuses them | +| A non-owner receives only authorized notifications | Each forwarded frame is decided by `event:` and its resources, and reaches a non-owner only when allowed | + +### Recording the message source + +The `MessageSourceMap` entry in the [session-controller types](../../../../packages/api/session-controller/src/types.ts) gains an optional field: + +```text +'user-rpc': { + kind: 'user' + rpcId: SessionRequestId + clientTimeZone?: string + /** Non-owner caller that submitted this prompt; absent means the owner. */ + principal?: Principal +} +``` + +Two producers build a `kind: 'user'` + `rpcId` user-message source inside a Remote call. Both call `principalOf(this.ctx.invocation)` in the Remote method and write `principal` only when it is defined: + +| Producer | Location | +|---|---| +| `SessionController.prompt()` builds the source and `SessionCommandController.prompt(request, source)` only delivers it | [`session-controller/src/index.ts`](../../../../packages/api/session-controller/src/index.ts), [`commands.ts`](../../../../packages/api/session-controller/src/commands.ts) | +| subagent `prompt()` (`BrowserPromptSource`); no role lists it, so a non-owner reaches it only through in-process Host code, not through the Gateway | [`subagent/src/index.ts`](../../../../packages/subagent/subagent/src/index.ts) | + +Business code does not pass a principal down as a function parameter: the identity is read once from the invocation in the Remote method, and the built source travels down. The Agent inbox has no interception point that could add the field on enqueue (`followup` / `steer` accept built messages, and in-process producers such as the SDK and scheduling run outside Remote calls), so each producer records it, and the code-review rule covers new producers. + +| Fact | Detail | +|---|---| +| `kind` is unchanged | Still `'user'`; existing `kind === 'user'` checks are unaffected | +| Owner messages are unchanged | An owner call writes no field, so its source is byte-identical to the source before principals existed; a message without the field (including every older Session) is the owner's | +| Not part of model requests | LLM adapters read only the model source ([`llm-deepseek/src/replay.ts`](../../../../packages/llm/llm-deepseek/src/replay.ts)) | +| Session format | `SESSION_FORMAT_VERSION` is not bumped; per the [persistence type-change cookbook](../../../../docs/cookbook/reviewing-persistence-type-changes.md) the change records an acknowledgement | + +Example consumer use, outside this Note's scope: tool guards and pre-step rechecks read `source.principal` of the user messages in a turn and judge by the non-owner caller when any message carries one; a turn mixing owner and viewer messages takes the strictest. + +### Code-review rule and documentation + +The review rule's home is the "`@Remote` marks capability methods" section of [Remote and API rules](../../../../docs/defensive-patterns/remote-and-api.md): `@Remote({ resources })` and automatic resolution must cover every resource a method touches; aggregate results filter every item through `allows()`; the caller identity is read only from `invocation.peer.principal`, never from arguments; every call path names its Peer explicitly; business code does not pass a principal as a function parameter. + +| Document | Content | +|---|---| +| [`docs/subsystems/typert.md`](../../../../docs/subsystems/typert.md), [`docs/api-gateway.md`](../../../../docs/api-gateway.md) | `PeerScope`, `RemoteInvocation`, `InvokeRemoteRequest`, explicit Peers, `resources` on `@Remote`, and the access-check order | +| READMEs of connection, gateway, typert-protocol, typert-registry, api-remotes, remote-access, session-controller, workspace-controller, ui-session, ui-workspace, ui-slots, and client-test-runtime | Peer / `browserPeer` in place of the operator; the remote-access role, binding, and policy contract; access hooks | + +### Out of scope and future work + +- The `/connect` handshake, API cookies, one Peer per API connection, and WebSocket lifetimes belong to pr-5945. +- Multiple browser Peers (such as one per tab): every browser connection shares `browserPeer`. +- Interaction participation (interactions) and approval isolation by principal come with later work; non-owners currently receive only authorized `$events` broadcast frames. +- `agent-preset/selected` and the other forwarded events declare no resources and are decided on `global`; when its viewers need a Session event, #3854 declares that event's resources and lists `event:` in a role. +- Liveshare integration (declaring `share-viewer`, one Peer per viewer connection, defining roles and registering a policy, removing `origin` / `prompt/origin` / `READ_ENDPOINTS`) happens on the #3854 side. +- `session/cancel` ownership checks, the fork `childSessionId`, and `ToolExecutionInput.turn` do not change. +- Precise resource recognition (for example, the Typert generator locating request fields by branded id type and writing them into descriptors): this change uses the `resource` that lookups and Contexts declare, default fields, and `resources` readers, and resource resolution can later be replaced without changing the policy interface. +- Answering 403 to every non-owner on exact Fetch routes is temporary; each route is to declare its own access rule later. +- The resource declaration of subagent `prompt` is open: its request fields are `parentSessionId` / `childSessionId`, so it currently resolves to `global`. The producer records `source.principal` for in-process callers; no role lists it, so non-owners cannot reach it through the Gateway. +- Predefined and aggregate roles: when a second non-owner principal kind appears, domain packages declare the generic roles a method belongs to (such as `session:viewer`) with `@Remote({ roles })`, and each policy binds those roles; roles are currently defined by the business package as explicit action lists. + +### Relation to existing Notes + +- [Remote duplex stream](../../implemented/architecture/2026-09-19-remote-duplex-stream.md): partially superseded. The replaced parts are "the Peer records no identity or permission", "this Host has exactly one Peer, the operator", "an in-process carrier without a Peer means the operator", and its alternative stating that "the Access mechanism is business semantics"; the rest (the duplex stream, uplink, and `ctx.invocation` binding) stands. Both Notes stay active and cross-linked, and that Note's current facts are updated. +- [Browser token authentication](../../implemented/architecture/2026-08-24-browser-token-authentication.md): unaffected. Its rejection of per-method privilege concerns owner authentication; an authenticated browser is still the owner and is not checked per method. +- [Typert Remote method calls](../../implemented/architecture/2026-08-02-typert-remote-method-calls.md): unaffected; `@Remote` and `@RemoteScope` gain optional `resources` readers (the second argument of `@RemoteScope` may be `{ name?, resources? }`), read only by the Gateway's access check, and change neither endpoint naming, call modes, nor generated artifacts. +- [Producer-owned message sources](../../implemented/architecture/2026-09-09-producer-owned-message-sources.md): unaffected; the producer that builds a source writes `principal`. + +## Alternatives considered + +**A separate `prompt/origin` event correlated by requestId (the #3854 approach).** Every prompt writes a required event, so even ordinary Sessions become unreadable by older versions; correlation serializes every prompt and maintains an origin fold, and messages outside the fold window lose their initiator. + +**Principal and peer as parallel invocation fields.** One caller's identity would have two sources; every admission point would have to produce and pass both, and a path that passes only one would mismatch them. + +**Keep "the Peer records no identity".** When business plugins attach identity through `peer.ctx`, every reader must know who attached it and how to read it, and the wire admission path cannot guarantee the attachment happened. + +**Keep a default-Peer fallback (`request.peer ?? …`).** An implicit default silently grants owner identity to a call that forgot its Peer; a required parameter turns the omission into a compile error. + +**A new source kind.** Every existing `kind === 'user'` check would need review, and one miss makes viewer messages disappear from titles, outlines, queues, or chat rendering. + +**Identity in a request-body field.** Any caller able to build a request body could forge or override it. + +**React context for frontend resources.** Business components read no React context; the framework binds standard hooks per resource, and components receive them only through props. + +**Driver-maintained endpoint allowlists that trim results (the #3854 approach).** The allowlist and the result trimming both live in the driver, the Gateway does not enforce them, and the snapshot and the frontend each derive their own; the generic layer enforces role action lists, and `allows()` inside the method performs list filtering. + +**Business packages implement `decide()` / `abstain` providers whose answers are merged.** Each business package hand-writes action × resource branches plus a separate resource list for snapshots, and the two stay consistent only by hand; a policy gives only bindings, decisions and snapshots are computed from the same bindings, and each principal kind has one policy, so no merge rule is needed. + +**A separate `@RemoteAccess` marker.** Role action lists already guarantee default deny, so a marker is only a second consent; a method that resolves no resource falls to `global`, and only an explicit global grant allows it. Resource readers describe the method, so they live on `@Remote`. + +**Calling resource-less calls `page` or `host`.** `page` describes a frontend location, not a resource; `host` reads easily as the parent of every resource on this Host. `global` means a grant tied to no resource. + +**Resource inheritance (GCP style: a grant on `global` or on a Workspace covers lower resources).** List methods allowed by a `global` grant must decide each item, and inheritance would make any `global` grant imply every Session; without inheritance, a binding grants each resource explicitly. + +**A role registry and predefined aggregate roles.** The only non-owner principal today is managed by one business package, so roles can be plain values of that package; aggregate roles would let methods a new package declares enter a share viewer's reach automatically, so they wait for a second non-owner principal kind. + +**Conditions attached to a role's actions.** A role stays reusable plain data; a refinement by business state belongs to the binding that grants the role to a principal. + +**Refusal reasons from conditions only.** Without a binding there is no condition to give a reason, so a viewer page could not tell "share expired" from "share not writable"; `explain` gives a reason only after the decision is already a refusal and never changes it. + +**A global resource-resolver registry (domain packages register recognizers by field name).** Field recognition separates from the method, nothing flags a method signature change, and same-named fields in other packages are misread; resource resolution uses a default convention on the method plus per-method `resources`, and a domain package registers only its own kind's default field. + +**Dot-path resource declarations (`'request.address.sessionId'`).** Types cannot constrain a path; the parameter types of `resources` readers are inferred from the decorated method, so a typo fails compilation. + +**Generator recognition of resource fields by branded id type.** Requires changing Typert artifacts and the descriptor format, and SRC descriptors carry no types; kept as future work. + +**A central mount of the remote-access generated contribution in api/remotes.** The remote-access Client depends on ui-session and ui-session depends on api/remotes, so a central mount forms a project-reference cycle; remote-access mounts its own contribution instead. + +**Decisions inside the Gateway (a `check()` with rules written in the Gateway).** The Gateway would carry access-control semantics and extra error codes; it resolves resources as it resolves lookups and calls `remoteAccess.decide()` before dispatch, and the rules and refusal code belong to remote-access. + +**Asynchronous policy decisions.** List filtering and snapshot computation need synchronous answers; business packages preload asynchronous state into memory. + +**On-demand permission queries from the frontend.** Request volume grows with the number of entries and cannot follow rule changes; the Host pushes a snapshot stream and the frontend reads it synchronously. + +**An access check after lookup resolution.** A lookup can activate an Agent, so an unauthorized call would cause side effects first. + +**Resource fields registered in remote-access (`registerScope`).** The access package would recognize argument fields although lookups already know which wire field names a Session; typert holds resource kinds beside lookups and Contexts, so the Gateway resolves calls and events in one place and remote-access reads no argument field. + +**Trimming forwarded event payloads per Peer.** A per-event projection would repeat list filtering inside every notification; an event carries at most one resource and is delivered whole or not at all, while collection changes travel on follow streams that filter inline. + +**Answering true until the first snapshot arrives.** A non-owner page would briefly show entries it cannot use; the index carries the first snapshot, so a page without one has no access. + +## Consequences + +### Verification + +| Case | Behavior | Test location | +|---|---|---| +| The wire tries to set a principal (top-level args, a payload sibling, the envelope, inside the request body) | The first two fail argument or payload validation; the rest are dropped or treated as business data; `invocation.peer` remains the admitted Peer | Gateway host spec | +| Every call path names its Peer | `InvokeRemoteRequest.peer`, the `wireStream.open` peer, `fetch(request, peer)`, and the `bridge` peer are required; the Gateway has no fallback; the `/api` route passes `admission.peer` | typecheck, Connection host spec | +| Browser connections and `createPeer()` | `browserPeer` has the owner principal; each `createPeer()` returns an independent Peer released with the Context that read Connection; exact routes answer 403 to non-owners | Connection host spec | +| Disposed Peers | Later unary, stream, and `$events` dispatches fail with `gateway/peer-disposed`, also when the wire payload is malformed; its streams end; a running unary call completes; other Peers are unaffected | Gateway host spec | +| Check order | The owner calls any method normally without reading a policy; a method no role lists refuses non-owners with `remote-access/denied` (`no-allow`); the access check precedes lookups, so a refused call activates no Session | Gateway host spec | +| Policy registration | One policy per non-owner principal kind, and a second registration throws; once the disposer withdraws it, that kind is refused with `no-allow`; it is withdrawn with its fiber | remote-access host spec | +| Decisions | Every resource needs a matching binding (AND); a role without the action, an unequal resource, or a refusing condition does not allow; the refusal reason follows condition > `explain` > `no-allow`; `explain` never changes the decision; conditions receive args for calls but not for snapshots and list filtering; a throwing `bindings()`, condition, or `explain()` refuses with `policy-failed`, each policy is logged once between `invalidate()` calls, and on the event path the owner stream and the shared event source continue; `remoteAccess/follow` is allowed for every principal | remote-access host spec, Gateway host spec | +| Resource resolution | A default field (top-level or first object argument) yields its resource; a lookup parameter that declares that kind as its `resource` yields its wire identity; a Context method gets its Session resource from the Agent Context identity in args without activating the Agent, and may declare other resources through `resources`; a `resources` reader overrides its kind, an array yields several resources, and `undefined` none; with nothing the call is `[global]`; a throw, an empty array, or a value that is not a non-empty string (including a Context identity) is invalid, refused by the Gateway with `resource-invalid` without asking `decide()`; a Context that declares no `resource` resolves by the ordinary rules; resources and `args` read the validated arguments, so an undeclared nested field changes no resource and no condition sees it, and a JSON argument failing validation returns `gateway/input-invalid` before the access check | Gateway host spec (gateway-access) | +| Resource registry | `typert.resources` registers one default field per kind, rejects a second registration and `global`, and withdraws the registration with its fiber; a configured lookup resolver keeps the provider's `resource`; a Host Context adapter keeps its `resource` | typert-registry spec | +| Forwarded events | A non-owner `$events` stream receives an event, whole, only when `event:` is granted on its resources; an event that declares no resources is decided on `global`; an event whose reader returns `undefined` does not reach non-owners, and `decide()` is not asked; the owner receives all | Gateway host spec (gateway-access) | +| First snapshot | `snapshotFor()` returns the owner baseline or the principal's grants; remote-access injects the owner baseline into every rendered index; the Client starts from the injected baseline and rejects a malformed one | remote-access host and client specs | +| Type inference | The parameter types of `resources` readers are inferred from the method; lookup positions have wire types; a missing property, more parameters than the method has, and a `global` key fail compilation; a binding whose resource kind differs from its role's fails compilation | typert-protocol spec, remote-access spec (type tests) | +| List filtering | `session/list`, `session/search`, `session/control`, and `workspace/follow` return non-owners only items for which `allows()` is true; `workspace/follow` sends a `replace` increment when a delivered Workspace loses visibility, and the Workspace reappears once access returns; owner results are unchanged | session-controller / workspace-controller host spec | +| Access snapshots | The allowed set in a snapshot equals the Host decision for the same principal, action, and resource without arguments; it contains endpoint actions only; a resource with no allowed action gets no grant, and one whose allowed set becomes empty is removed; `invalidate()` and policy registration or removal push increments; a wait that a change ends leaves no abort listener behind; unloading the service ends every open snapshot stream; the owner receives only `{ owner: true }` | remote-access host spec | +| Access hooks | `source()`, `useRemoteAccess`, `useAccess`, `useSessionAccess`, and `useWorkspaceAccess` follow the snapshot; `useAccess` on a Session resource reads that Session's answer; the owner answers true; a non-owner without a snapshot or after its snapshot stream fails answers false; hooks issue no requests | remote-access client spec, ui-session / ui-workspace client spec | +| Two-argument keyed hooks | A string second argument reads the `(key, member)` source; existing call forms are unchanged | ui-renderer client spec | +| A non-owner dispatches `session/prompt` | The recorded user message's `source.principal` equals that principal, and a cold restore reads the same value | session-controller host spec | +| An in-process non-owner invocation of subagent `prompt` | The child Session's recorded user message has `source.principal` equal to that principal | subagent host spec | +| Owner messages | The source is byte-identical to the source before this change; existing keyless recorded-session snapshots are unchanged | `pnpm run test:snapshot` needs no re-recording | +| Persistence record | `verify-persistence-changes` passes | doc-sync | + +The SDK projections are unaffected: the TypeScript SDK server builds its own `{ kind: 'user' }` messages ([`sdk/server/src/server.ts`](../../../../packages/sdk/server/src/server.ts)) outside the Gateway and does not project the source; the Python SDK does not read the user source. + +### Costs and limits + +- The change spans protocol, Connection, Gateway, two domain controllers, subagent, a new package, and the frontend, with breaking API renames; it necessarily conflicts with pr-5945 in Connection and the Gateway, handled by the migration list. +- The Gateway depends on `remoteAccess`: a custom composition that mounts the Gateway without remote-access leaves the Gateway waiting. +- Session logs store viewer identities and travel with exported or shared Sessions, so no principal kind may carry a credential. +- Every browser connection shares one Peer, so disposal cannot distinguish tabs until multiple browser Peers exist. +- The default field convention reads by field name: a method that gains a same-named field touches that resource, which review must watch; precise recognition is future work. +- A method that resolves only some resources lets a principal exceed its grant: unresolved resources go unchecked, and the method author ensures `resources` is complete. +- Role actions are strings and are not checked against loaded endpoints: a misspelled or renamed action never matches and shows up as a refusal. +- `api-session/added` carries the whole `SessionSummary`, so a non-owner allowed to receive it also learns the Session's `parentSessionId`. +- A granted Session's cwd and tool paths already contain the owner's absolute paths, so the Gateway does not hide `home` from non-owner `$events` streams separately. +- `workspace/follow` notices a Workspace whose visibility a policy revoked only at that Workspace's next change or the next order change, and then sends the non-owner a `replace` increment; an access change alone sends no frame. + +### Migration list for pr-5945 + +| File | Migration | +|---|---| +| `packages/client/connection/src/peer.ts` | Replaces `operator-peer.ts`; construct `OperatorPeer` as `new Peer(owner, { principal })` | +| `packages/client/connection/src/rpc-host.ts` | `this.operator` becomes `browserPeer` with principal `{ kind: 'owner' }` | +| `packages/client/connection/src/rpc.ts` | `HostConnectionHandle` merges `admitConnection` with `browserPeer` / `createPeer` | +| `packages/api/gateway/src/index.ts` | Replace `peer ?? this.operatorPeer()` where `$events` opens with an explicit Peer; reuse `gateway/peer-disposed` | +| The operator-connect Note, upgrade guide, and subsystem changes | Rewrite operator terms as Peer / `browserPeer`; an API connection's Peer has principal `{ kind: 'owner' }` | diff --git a/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md b/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md new file mode 100644 index 0000000000..30d47c9ccb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md @@ -0,0 +1,672 @@ +# Agent Note: Peer 身份属性与 Remote 方法级访问控制 + +Status: implemented + +[English](2026-10-12-peer-principal-and-remote-access.md) | 中文 + +## 问题 + +Host 上的 Remote 方法此前无法得知本次调用代表谁,也无法按调用方限制可调用的方法。[`PeerScope`](../../../../packages/typert/protocol/src/types.ts) 的契约曾写明「Who the Peer is and what it may do are not recorded here」;[Connection](../../../../packages/client/connection/src/rpc-host.ts) 只有一个 operator Peer,`admit()` 对每个通过认证的请求都返回它,`/api` 路由与 interceptor 的 Fetch handler 固定使用它而不使用准入结果;[Gateway](../../../../packages/api/gateway/src/index.ts) 在调用方未给出 Peer 时隐式回退到 `operatorPeer()`。 + +首个非 owner 调用方是 liveshare 读者。读者请求经 Relay 到达 owner 的 liveshare Host 插件,插件此前在 owner 进程内以 operator 身份分派,owner 的 Session 因此把读者的 prompt 当作 owner 本人的输入。PR #3854 为此把 liveshare 语义塞进 session-controller:请求体携带 `origin`,每条 prompt 都写 required 的 `prompt/origin` 事件并按 requestId 关联,controller 内做来源 fold,`serializeAdmission` 扩到全部 prompt,新增 `api-session/external-admission` 钩子;liveshare 自己维护接口白名单 `READ_ENDPOINTS` 并裁剪 list/follow 结果;前端的 `clientWritePolicy` 定义在 ui-conversation,5 个包三种读法,7 处靠「是否注入某回调」隐藏界面。 + +需要一套通用机制: + +- 调用方身份由 Host 进程内代码赋予,wire 上任何字段都无法设置或覆盖。 +- 每条调用路径都显式给出 Peer,不存在隐式兜底。 +- 方法级权限在后端一处计算、一处把关;前端读同一份结果决定入口显隐,规则变化时自动同步。 +- prompt 投递时身份随用户消息落盘,供之后按 turn 判定发起者。 + +## 决策 + +### 范围 + +| 部分 | 内容 | +|---|---| +| Peer 身份 | `PeerScope.principal` 与 `PeerScope.signal`;唯一 Peer 实现 `Peer`(`OperatorPeer` 改名)与 options 构造;删除 operator 概念与所有隐式 Peer 兜底;`connection.browserPeer`、`connection.createPeer()` 与 `fetch(request, peer)`;已 dispose 的 Peer 一律以 `gateway/peer-disposed` 拒绝;`user-rpc` source 落盘 `principal?` | +| 方法级访问控制 | `@Remote` 的 `resources` 读取函数、`TypertResourceMap` 资源种类与 `typert.resources` 注册表(typert-protocol、typert-registry);Gateway 把调用与转发事件解析为资源;新包 `@deepseek-ai/dsh-api-remote-access`(Host 面 + Client 面):按 role、binding 与 policy 的 RBAC 判定 `decide(request)`、列表过滤 `allows()`、index 中的首份快照与访问快照流、access hooks | +| 文档 | 一条代码评审标准与术语 | + +### 两层概念:principal 与 peer + +| 层 | 概念 | 例子 | 数量关系 | +|---|---|---|---| +| 授权层 | principal:调用方身份,权限判定的依据 | 一份分享授权 token 证明的 `share-viewer{shareId, actor}`;本机用户 `{ kind: 'owner' }` | 一个 principal 对应 N 个 peer | +| 连接层 | peer:一条连接的生命周期作用域 | 浏览器连接、liveshare 读者的一条连接 | 每条连接一个 peer | + +| 事项 | 归属层 | +|---|---| +| 方法级权限判定、access hooks、访问快照 | principal | +| `source.principal` 落盘 | principal | +| 订阅、stream、连接期注册(`peer.ctx`) | peer | +| 撤销授权 | 两层:撤权后 policy 不为该 principal 给出 binding,其调用一律被拒;创建方 dispose 其名下全部 peer | + +principal→peers 的对应表由创建方持有,例如 liveshare 每份授权一个对象,记录该授权下建立的全部 peer。 + +### Peer 模型 + +只有 Peer 一个概念、一个实现,删除 operator 概念。 + +```text +// @deepseek-ai/dsh-typert-protocol +export interface PeerScope { + readonly id: PeerId + /** Connection-lifetime registrations; disposed with the Peer. */ + readonly ctx: Context + /** Caller identity fixed at creation by in-process Host code; no wire field can set it. */ + readonly principal: Principal + /** Aborted once the Peer is disposed; Remote streams that speak for the Peer end with it. */ + readonly signal: AbortSignal + dispose(): Promise +} + +// @deepseek-ai/dsh-client-connection +export class Peer implements PeerScope { + constructor(owner: Context, options: { readonly principal: Principal }) +} + +interface HostConnectionHandle { + /** The Peer every authenticated browser connection shares; principal { kind: 'owner' }. */ + readonly browserPeer: PeerScope + /** Network admission: the admitted Peer or the refusal status. */ + admit(request: ConnectionTrustRequest): PeerAdmission + /** In-process only; disposed with the Context that read `ctx.connection`, or earlier by dispose(). */ + createPeer(options: { readonly principal: Principal }): PeerScope +} + +interface ConnectionFetchHandler { + fetch(request: Request, peer: PeerScope): Promise +} +bridge(req, res, apiHandler, peer, maxRequestBodyBytes?) + +// @deepseek-ai/dsh-api-gateway +interface InvokeRemoteRequest { …; readonly peer: PeerScope } // was `peer?` +wireStream.open(endpoint, payload, uplink, peer: PeerScope, signal) // was `PeerScope | undefined` +``` + +| 规则 | 说明 | +|---|---| +| 每条路径显式给出 Peer | 网络路径由 `admit()` 的结果给出;进程内路径由调用方传入。Gateway 删除 `operatorPeer()` 与 `request.peer ?? …`,不再自建 Peer | +| 浏览器连接共享 `browserPeer` | 所有浏览器连接共享一个 Peer,每个使用处都显式引用 `connection.browserPeer`,不存在兜底变量;页内 Host(webworker-runtime)同样显式传 `browserPeer` | +| Host 进程内自动化 | 需要调用 Remote 方法时用 `createPeer({ principal })` 创建自己的 Peer。目前没有这类生产调用方,因此不预置固定的 Host Peer | +| 多 Peer | `createPeer()` 每次返回独立 Peer;liveshare 将用它为读者的每条连接建一个 Peer(在 #3854 侧接入) | +| exact Fetch route | file-upload、present-open、media-references、session-log-export、inspector 等 exact route 不经 Gateway;共享 Fetch handler 对非 owner Peer 一律返回 403 | + +### 身份类型 + +```text +// @deepseek-ai/dsh-typert-protocol + +/** + * Merge-extensible caller identities. Each driver declares its own entry. + * Every entry is a JSON value with a unique literal `kind`, carries no + * credential, and is safe to persist in a Session log. + */ +export interface PrincipalMap { + owner: { readonly kind: 'owner' } +} +export type Principal = PrincipalMap[keyof PrincipalMap] + +/** + * @param invocation - `ctx.invocation`; `undefined` outside a Remote call. + * @returns the caller's principal when it is not the owner; `undefined` for the + * owner and for trusted in-process code outside a Remote call. + */ +export function principalOf(invocation: RemoteInvocation | undefined): Principal | undefined +``` + +读取入口统一为 `this.ctx.invocation.peer.principal`;owner 判断就地写 `principal.kind === 'owner'`,未知 kind 永远不是 owner。外部 driver 在自己的包内用声明合并扩展 `PrincipalMap`;liveshare 的 `share-viewer{ shareId, actor }` 在 #3854 侧声明,此处不改 liveshare。 + +### Peer 生命周期与撤权 + +| 事件 | 行为 | +|---|---| +| Gateway 分派 | 第一步检查 `peer.signal.aborted`,已 dispose 即以 `gateway/peer-disposed` 拒绝。对 HTTP、WebSocket 与进程内路径都生效;wire 路径在读取 payload 之前检查,已 dispose 的 Peer 携带畸形 payload 也得到同一错误码 | +| Peer dispose 时的 stream | Remote stream 方法看到的 signal 并入 `peer.signal`,`$events` 流的生命周期同样并入;WebSocket 照旧以 1001 关闭 | +| Peer dispose 时的 unary | 已在执行的 unary 调用不被取消;之后的调用被拒绝 | +| 撤销授权 | 业务包撤权后 policy 不为该 principal 给出 binding,业务包调用 `invalidate(principal)`;创建方按 principal→peers 表 dispose 全部 peer | + +### 方法级访问控制 + +资源类型与 `@Remote` 的 `resources` 读取函数在 `@deepseek-ai/dsh-typert-protocol`;资源种类在 typert 中与 lookups、Contexts 并列:`TypertResourceMap` 声明种类,`typert.resources` 保存每个种类的默认 wire 字段,lookup 与 Host Context adapter 声明其 wire 身份所属的资源种类。Gateway 把一次调用或一个转发事件解析为它访问的资源。判定、列表过滤与访问快照在新包 `@deepseek-ai/dsh-api-remote-access`(`packages/api/remote-access`),该包不读取任何参数字段。Gateway 与领域包对 remote-access 只做 type-only 依赖并 inject `remoteAccess`,值依赖只有 `dsh-typert-protocol`,不为 remote-access 新增 `package-dependency-policy` 条目。role、binding 与 policy 由业务包定义和注册,liveshare 为首个使用方。除内置的 `global` 外,remote-access 与 Gateway 中不出现任何资源种类名,符合 [`packages/api` 只承载通用编排](../../../../docs/defensive-patterns/remote-and-api.zh.md) 的评审规则。 + +#### 与 RBAC 的对应 + +| 本设计 | RBAC / IAM 术语 | 含义 | +|---|---|---| +| principal | Subject / Principal | 调用方身份,`PrincipalMap` 的一个条目 | +| Peer | Session(RBAC 会话) | principal 的一条连接;一个 principal 对应 N 个 Peer | +| owner | 超级用户 | 跳过全部检查 | +| action | Action / Permission | Remote 端点 `ns/method`,或转发事件 `event:`;Gateway 内部仍称端点 | +| resource | Resource / Object | `{ kind: 'global' }`,或某个已声明资源种类的 `{ kind, id }` | +| role | Role | 限定一种资源种类的 action 集合,是业务包的普通值 | +| binding | RoleBinding(角色指派) | principal 在某个资源上拥有某个 role,可附 condition | +| condition | Condition(IAM Conditions) | 挂在 binding 上,按请求的 action、资源与参数放行或带原因拒绝 | +| policy | Allow policy | 业务包为一种非 owner principal kind 给出 binding 与可选 `explain` | +| explain | 拒绝说明 | 没有 binding 放行时给出拒绝原因,不改变结论 | +| Gateway | PEP(Policy Enforcement Point) | 解析资源、执行结论 | +| remote-access | PDP(Policy Decision Point) | 计算结论、列表过滤与访问快照 | + +| 规则 | 内容 | +|---|---| +| 默认拒绝 | 非 owner 只有在某个 binding 的 role 显式列出该 action 时才被放行;role 未列出的 action、没有 binding 的资源、没有 policy 的 principal kind 一律被拒。所有 Remote 方法都受访问控制,没有单独的可访问标记 | +| 资源之间无继承 | `global` 不是其他资源的上级:`global` 上的授权不蕴含任何会话或工作区上的授权,工作区上的授权也不蕴含其中会话的授权 | +| `global` 授权即显式全局授权 | 调用解析不出任何资源即访问 `global`。把某个 action 放进 `global` 级 role,等于允许该 principal 不受资源限制地调用它,属高危授权;方法被放行后仍可在内部用 `allows(resource)` 逐项细判 | + +#### 资源与资源读取(`@deepseek-ai/dsh-typert-protocol`、`@deepseek-ai/dsh-typert-registry`) + +```text +/** Merge-extensible resource kinds: the key is the kind, the value declares its identity type. */ +export interface TypertResourceMap {} +// @deepseek-ai/dsh-session/types: session: TypertResource +// @deepseek-ai/dsh-workspace/types: workspace: TypertResource + +// Runtime registries in typert +ctx.typert.resources.register(kind, { field }): TypertDisposer +ctx.typert.lookups.register(key, { parameter, wire, resource?, … }) // resource: the kind its wire id names +ctx.typert.contexts.registerHost(key, { wire, resource?, … }) // a TypertHostContextAdapter + +export interface TypertHostContextAdapter { + readonly wire: string + readonly wireTypeSymbol: string + /** Resource kind the wire identity names; access checks read the identity from args before resolve(). */ + readonly resource?: TypertResourceKind + resolve(id: Wire): Context | undefined | Promise +} + +export type RemoteAccessResourceKind = 'global' | TypertResourceKind +export type RemoteAccessResource = + | { readonly kind: 'global' } + | { readonly kind: K; readonly id: TypertResourceId } // for each declared kind K +export type RemoteAccessResourceOf = Extract + +/** Per-kind readers, called with the method's positional wire arguments. */ +export type TypertResourceReaders = { + readonly [K in TypertResourceKind]?: (...args: WireArgs) => Id | readonly Id[] | undefined // Id = TypertResourceId +} + +export interface RemoteMethodOptions { + readonly name?: string + readonly mode?: 'stream' + readonly resources?: TypertResourceReaders +} + +export function Remote( + option: string | RemoteMethodOptions>>, +): (method: (this: This, ...args: Args) => Result, + context: ClassMethodDecoratorContext Result>) => void + +export interface RemoteScopeOptions { + readonly name?: string + readonly resources?: TypertResourceReaders +} + +export function RemoteScope( + key: Extract, + option?: string | RemoteScopeOptions>>, +): (method: (this: This, ...args: Args) => Result, + context: ClassMethodDecoratorContext Result>) => void +``` + +| 规则 | 内容 | +|---|---| +| 写法 | `@Remote({ name: 'page', resources: { session: (request) => request.address.kind === 'session' ? request.address.sessionId : request.address.childSessionId } })`;Context 方法写 `@RemoteScope('agent')`,由 Agent Context 的 `resource: 'session'` 得到会话资源,需要其他资源时写 `@RemoteScope('agent', { resources: { workspace: (request) => request.workspaceId } })`。多数方法不写 `resources`,由自动解析得到资源 | +| 资源种类 | 资源种类由声明 id 类型的底层包合并:`session: TypertResource` 在 `@deepseek-ai/dsh-session/types`,`workspace: TypertResource` 在 `@deepseek-ai/dsh-workspace/types`。session-controller 引用 commands 包,若在 session-controller 合并,commands 要引用 session-controller,形成 project reference 环。`global` 由 remote-access 内置,没有 id,不进 `TypertResourceMap`;typert 保留该名,`typert.resources.register('global', …)` 抛错 | +| 默认字段与声明 | 拥有该种类的领域在控制器构造时登记默认 wire 字段:`SessionController` 构造函数调用 `typert.resources.register('session', { field: 'sessionId' })`,`WorkspaceController` 构造函数登记 `workspace` → `workspaceId`;同一种类重复登记即抛错。Agent、Session 与 `workspaceFileScope` lookup 声明 `resource: 'session'`,agent 包的 Agent Context 声明 `resource: 'session'` | +| 解析优先级 | 对每个资源种类依次取:① 该方法 `resources` 中该种类的读取函数;② 声明了该种类 `resource` 的每个 lookup 参数贡献其 wire 身份,省略的可选 lookup 参数不贡献;Context 方法的 Context 声明了该种类 `resource` 时,其 wire 身份同样贡献;③ 该种类的默认字段:命名参数中有同名顶层参数就读它,否则读第一个对象参数的同名字段。默认字段只表示一个身份,读到数组即为非法值 | +| 参数来源 | 资源解析与 `decide()` 的 `args` 读取经 Typert 编译类型校验后的命名参数:每个 JSON 参数由其 codec 解码一次,类型未声明的对象字段被移除,分派复用该值,因此调用方无法用未声明字段改变资源;lookup 参数与 Context 身份取 wire 身份,此时不解析 lookup、不激活 Agent | +| 解析结果 | 各种类的资源合在一起即本次调用访问的资源;一个都没有即 `[global]`;解析出资源时只用这些资源,不附加 `global` | +| 读取函数 | 以方法的位置参数调用:按描述符把命名参数映射回方法参数顺序(JSON 位为校验后的值,lookup 位为 wire 身份,取消参数位为调用的 signal);返回一个 id、id 数组(每个都须被允许)或 `undefined`(该种类无资源) | +| 非法值 | 读取函数抛错或返回空数组,或读到的值(含 Context 的 wire 身份)不是非空字符串即资源非法:Gateway 不询问 `decide()`,直接以 `remote-access/denied`(reason `resource-invalid`)拒绝调用 | +| 完整性 | `resources` 与自动解析必须覆盖方法访问的全部资源。一个资源都没解析出的调用落到 `global`,只有 `global` 级 role 能放行,因而默认被拒;只解析出部分资源时,其余资源不受检查,持有已解析资源授权的 principal 可越权访问它们,由方法作者负责避免 | +| 类型推断 | `@Remote` 与 `@RemoteScope` 读取函数的参数类型从被装饰方法自动推断:工厂参数用 `NoInfer`,`Args` 只从返回的装饰器推断;lookup 参数按 `TypertLookupMap` 映射为 wire 类型(首个参数为 `agent: Agent` 的方法,其读取函数的第一个参数为 `SessionId`)。访问不存在的属性、参数多于方法参数与 `global` 键均为编译错误 | +| 存放 | `resources` 读取函数与 `@Remote` / `@RemoteScope` 的其他元数据一同存在类原型上,随实例构造登记,跨重复安装安全;不进入 Typert 生成物 | +| Context 方法 | `@RemoteScope(key, option?)` 与 `@Remote` 一致:字符串为导出名,对象为 `{ name?, resources? }`。Context 的 wire 身份按声明了 `resource` 的 lookup 参数参与解析,优先级与 lookup 相同,该种类有 `resources` 读取函数时被覆盖;Gateway 在 `resolveReceiverContext` 之前直接从 args 读取该身份,不激活 Agent。Context 未声明 `resource` 时其身份不贡献资源,方法按普通规则解析 | + +#### 端点的资源 + +下表列出 #3854 读者用到的端点及其资源来源。只有 `session/page` 与 `session/follow` 需要显式 `resources`,其余靠 lookup 的 `resource` 或默认字段: + +| 端点 | 资源 | 解析来源 | 方法内过滤 | +|---|---|---|---| +| `workspace/follow` | `global` | 无资源 | 是:工作区与会话 | +| `session/control` | `global` | 无资源 | 是:会话 | +| `session/list` | `global`(`_request` 无 `sessionId`) | 无资源 | 是:会话行 | +| `session/modelCatalog` | `global` | 无资源 | 否 | +| `session/canOpenWorkspacePath` | `global` | 无资源 | 否 | +| `llm/listConfigurableProviders` | `global` | 无资源 | 否 | +| `llm/listProviders` | `global` | 无资源 | 否 | +| `commands/list` | session:`args.agentId`(Agent lookup 的 wire 字段) | Agent lookup `resource: 'session'` | 否 | +| `goals/get` | session:`args.agentId` | Agent lookup `resource: 'session'` | 否 | +| `session/attachment` | session:`args.request.sessionId` | 默认字段 | 否 | +| `skills/list` | session:`args.request.sessionId` | 默认字段 | 否 | +| `session/fork` | session:`args.request.sessionId` | 默认字段 | 否 | +| `session/prompt` | session:`args.request.sessionId` | 默认字段 | 否 | +| `session/cancel` | session:`args.request.sessionId` | 默认字段 | 否 | +| `session/projections` | session:`args.request.sessionId` | 默认字段 | 否 | +| `session/page` | session:Session 地址读 `args.request.address.sessionId`;subagent 地址读 `args.request.address.childSessionId` | `resources` | 否 | +| `session/follow` | 同上 | `resources` | 否 | +| `remoteAccess/follow` | `global` | 无资源;remote-access 对任何 principal 放行 | 否 | + +subagent 地址读取的是子会话转录,因此其资源是子会话。Client 在重连后会重新读取已知会话的 projections,其中包括 subagent 会话的父会话;没有该父会话授权的读者,其 projection 读取被拒。父会话的授权是否覆盖其 subagent 子会话由 policy 决定,即是否为子会话给出 binding;通用层不推导父资源。 + +不需要非 owner 访问的方法不做任何声明,没有 role 列出它即被拒。subagent `prompt` 的请求字段为 `parentSessionId` / `childSessionId`,自动解析不到会话,解析为 `global`,因此不得放进任何 `global` 级 role;`session/search` 在方法内按会话逐项过滤命中。`subagents/list` 不是 Remote 端点(`SubagentRuntime.list()` 未标 `@Remote`)。 + +#### role、binding 与 policy(`@deepseek-ai/dsh-api-remote-access`) + +```text +/** Remote endpoint `ns/method`, or `event:` for one forwarded event; endpoint segments never contain `:`. */ +export type RemoteAccessAction = RemoteAccessEndpoint | `event:${string}` + +/** A named action set over one resource kind; a plain value owned by the business package. */ +export interface RemoteAccessRole { + readonly name: string + readonly resource: K + readonly actions: readonly RemoteAccessAction[] +} + +/** Answer of decide() and of a condition. */ +export type RemoteAccessDecision = + | { readonly kind: 'allow' } + | { readonly kind: 'deny'; readonly reason: string } + +/** Refines one binding for one action on its resource; `args` only for a concrete call. */ +export type RemoteAccessCondition = (request: { + readonly action: RemoteAccessAction + readonly resource: RemoteAccessResourceOf + readonly args?: Readonly> +}) => RemoteAccessDecision + +/** One role on one resource of the role's kind; the resource type follows from the role. */ +export type RemoteAccessBinding = { + [K in RemoteAccessResourceKind]: { + readonly role: RemoteAccessRole + readonly resource: RemoteAccessResourceOf + readonly condition?: RemoteAccessCondition + } +}[RemoteAccessResourceKind] + +/** One access question; the Gateway passes only valid resources, [global] when none. */ +export interface RemoteAccessRequest

{ + readonly principal: P + readonly action: RemoteAccessAction + /** Allow only when the action is allowed on every listed resource. */ + readonly resources: readonly RemoteAccessResource[] + /** Named arguments of a concrete call, validated against their Typert-compiled types with lookup parameters as wire identities; absent for events, snapshots, and list filtering. */ + readonly args?: Readonly> +} + +/** Business rules for one non-owner principal kind; synchronous over in-memory state. */ +export interface RemoteAccessPolicy

{ + bindings(principal: P): readonly RemoteAccessBinding[] + /** Reason for a request no binding allows; never changes the decision. */ + explain?(request: RemoteAccessRequest

): string | undefined +} + +/** details of `remote-access/denied` */ +export interface RemoteAccessDeniedDetails { + readonly action: string + readonly reason: string +} + +class RemoteAccessService { // ctx.remoteAccess; Remote namespace remoteAccess + registerPolicy>(kind: K, policy: RemoteAccessPolicy): () => void + invalidate(principal?: Principal): void + decide(request: RemoteAccessRequest): RemoteAccessDecision // Gateway-only + allows(resource: RemoteAccessResource): boolean // reads the accessing ctx's invocation + snapshotFor(principal: Principal): RemoteAccessBaseline // a page's opening baseline + follow(signal): AsyncIterable // remoteAccess/follow +} +``` + +| 规则 | 内容 | +|---|---| +| owner | Gateway 对 owner 不解析资源、不调用 `decide()`,也不读取任何 policy | +| 注册 | `registerPolicy(kind, policy)` 返回 disposer,业务包在 `ctx.effect()` 中调用。每个非 owner principal kind 至多一个 policy,同一 kind 重复注册抛错;`bindings()` 与 `explain()` 收到的 principal 按 kind 定型 | +| 内置放行 | `remoteAccess/follow` 对任何 principal 放行,每个 Peer 都能读自己的快照 | +| 判定 | 没有该 principal kind 的 policy 以 `no-allow` 拒绝。否则取 `bindings(principal)`,对请求的每个资源线性扫描找一个 binding:资源相等(`kind` 相同,且非 `global` 时 `id` 相同)、role 的 `actions` 含该 action、没有 condition 或 condition 放行;每个资源都找到才放行(AND)。condition 只对资源相等且 role 含该 action 的 binding 调用 | +| 拒绝原因 | 第一个未被放行的资源决定原因,优先级为:该资源上存在匹配 binding 但其 condition 全部拒绝时,取第一个 condition 的原因;否则取 `explain(request)` 的返回值;没有 `explain` 或其返回 `undefined` 时为 `no-allow`。`explain` 只在结论已为拒绝后调用,不改变结论 | +| 失败隔离 | `bindings()`、condition 或 `explain()` 抛错时,本次判定以 `policy-failed` 拒绝;计算快照时 `bindings()` 抛错即该 principal 没有 grant,condition 抛错即该 action 不放行。有问题的规则因此不会破坏共享的 `$events` 事件源、快照流或页面渲染;每次 `invalidate()` 或 policy 变更之后,每个 policy 的第一次失败只记录一次日志 | +| 同步 | `bindings()`、condition 与 `explain()` 同步返回,状态由业务包预先载入内存,以便列表逐项过滤与快照计算 | +| 求值时机 | 每次 `decide()`、`allows()` 与快照计算都调用一次 `bindings()`,不缓存;依赖时间的状态(如过期)即时生效,长流(如 `workspace/follow`、`session/control`)在 binding 增删后的下一次逐项判定即反映;快照只在 `invalidate()` 后重算,业务包在过期等时间事件发生时也须调用 `invalidate()` | +| 通知 | 业务状态变化(授权、撤权、模式切换)改变 binding 或 condition 的结论时,业务包必须调用 `invalidate(principal?)`;快照只在 `invalidate()` 与 policy 注册、撤回后重算 | +| `remote-access/denied` | 只有调用的拒绝变成错误,details `{ action, reason }`,reason 为 condition 或 `explain` 给出的原因、`no-allow`、`policy-failed`,或 Gateway 对非法资源给出的 `resource-invalid`;被拒的事件只是不推送 | +| 必需服务 | Gateway `static inject = ['typert', 'remoteAccess']`;挂载 Gateway 的组合必须挂载 remote-access,[`bundle/base`](../../../../packages/bundle/base/cordis.patch.yml) 紧随 `typert-gateway` 装配;plugin manager 像保护 Gateway 一样保护它,插件页面无法禁用 | + +#### 示例:分享读者 + +以 liveshare 声明的 `share-viewer` principal 为例,说明业务状态到 binding 的推导留在业务包;示例中的 `shares` 代表业务包在内存中持有的分享状态: + +```text +const globalReader = { name: 'share:global-reader', resource: 'global', actions: ['session/list', 'session/control', 'workspace/follow', 'session/modelCatalog', 'llm/listProviders', 'commands/list'] } +const sessionReader = { name: 'share:session-reader', resource: 'session', actions: ['session/page', 'session/follow', 'session/list', 'session/control', 'workspace/follow', 'commands/list', 'event:api-session/status', 'event:api-session/added'] } +const workspaceReader = { name: 'share:workspace-reader', resource: 'workspace', actions: ['workspace/follow'] } +const forker = { name: 'share:forker', resource: 'session', actions: ['session/fork'] } +const writer = { name: 'share:writer', resource: 'session', actions: ['session/prompt', 'session/cancel'] } + +ctx.effect(() => ctx.remoteAccess.registerPolicy('share-viewer', { + bindings(viewer) { + const share = shares.serving(viewer) // undefined once stopped, expired, or no longer admitted + if (share === undefined) return [] + const source = { kind: 'session', id: share.sessionId } + return [ + { role: globalReader, resource: { kind: 'global' } }, + { role: sessionReader, resource: source }, + ...(share.allowsFork ? [{ role: forker, resource: source }] : []), + ...(share.mode === 'write' ? [{ role: writer, resource: source, condition: sourceWrite(share) }] : []), + ...shares.forksOf(viewer).flatMap(child => [ + { role: sessionReader, resource: { kind: 'session', id: child.id } }, + ...(child.revoked ? [] : [{ role: writer, resource: { kind: 'session', id: child.id }, condition: childPrompt(child) }]), + ]), + ...shares.workspacesShowing(viewer).map(id => ({ role: workspaceReader, resource: { kind: 'workspace', id } })), + ] + }, + explain({ principal, action }) { + return shares.refusal(principal) // 'share-expired', 'share-stopped', … + ?? (action === 'session/prompt' ? 'share-not-writable' : undefined) + }, +})) + +// Without args (snapshots, list filtering) a condition answers for the action alone. +const sourceWrite = share => () => share.confined ? allow : deny('source-write-unavailable') +const childPrompt = child => ({ action, args }) => + action === 'session/prompt' && args !== undefined && !child.allowsPrompt() ? deny('fork-prompt-refused') : allow +``` + +| 归属 | 内容 | +|---|---| +| 业务包 | role 的 action 清单;分享状态到 binding 的推导(停止、过期、准入、模式、读者自己的分支、撤销、包含可见会话的工作区);按请求细化的 condition;面向读者页面的拒绝原因 | +| 通用层 | 资源解析、按资源 AND、role 与 action 匹配、condition 调用、原因优先级、列表过滤、快照计算与失败隔离 | + +该读者的快照包含 `global`、源会话、自己的每个分支与每个可见工作区上的 grant;`session/list` 同时出现在 `global` 级与 session 级 role 中,见[列表与聚合方法](#list-and-aggregate-methods)。 + +#### Host 侧鉴权调用顺序 + +所有调用路径(HTTP `/api`、WebSocket stream、进程内 `fetch(request, peer)` / `invoke` / `stream` / `wireStream.open`)都经过同一段 Gateway 逻辑: + +| 步 | 动作 | 失败结果 | +|---|---|---| +| 1 | 准入得到 Peer:网络路径由 Connection `admit()` 给出(`browserPeer`);进程内路径由调用方传入。Gateway 在读取 wire payload 之前检查 `peer.signal` | 网络准入失败返回 HTTP 401 / 403(不进入 Gateway);Peer 已 dispose:`gateway/peer-disposed` | +| 2 | 解析端点并做参数字段集校验(`resolveDescriptor`、`assertExactArguments`),再按 Typert 编译类型校验 JSON 参数,每个参数解码一次 | `gateway/invocation-unavailable`、`gateway/ambiguous-endpoint`、`gateway/definition-unavailable`;字段多余或缺失:`gateway/arguments-invalid`;JSON 参数校验失败:`gateway/input-invalid`(owner 与非 owner 相同,先于访问检查) | +| 3 | owner 直通:`principal.kind === 'owner'` 时直接进入第 5 步 | — | +| 4 | 非 owner:Gateway 从第 2 步校验后的参数解析资源(`resources` 读取函数、其次 lookup 参数与 Context 声明的 `resource`、再次默认字段;lookup 与 Context 身份取 wire 身份,不解析 lookup 与 Context),再以校验后的参数为 `args` 询问 `remoteAccess.decide({ principal, action: endpoint, resources, args })`;资源非法时不询问 `decide()`,直接以 `resource-invalid` 拒绝;`deny` 结论变为抛出的错误 | `remote-access/denied`,details `{ action, reason }` | +| 5 | 分派:`resolveReceiverContext`(可能激活 Agent)、lookup 解析(JSON 参数复用第 2 步的值)、调用方法 | 既有错误码不变,如 `gateway/lookup-not-found`、`gateway/context-not-found`、`gateway/input-invalid`、`gateway/service-unavailable`、`gateway/method-unavailable` 与业务错误 | + +鉴权(第 3–4 步)位于 lookup 与 Context 解析之前,未授权调用不会激活会话或产生其他副作用。Gateway 新增的错误码只有 `gateway/peer-disposed`;拒绝码 `remote-access/denied` 由 remote-access 声明。 + +Gateway 自有端点:非 owner 可订阅 `$events`,但从不收到需要回答的 waterfall 帧;`$events/result` 对非 owner 以既有的 `gateway/invocation-unavailable` 拒绝;两者都做第 1 步的检查。 + +#### 转发事件 + +`API_REMOTE_FORWARDED_EVENTS` 的 `emit` 条目可以声明 `resources`:以资源种类为键、经 `TypertForwardableEventEntry` 按该事件自身参数定型的读取函数,例如 `{ event: 'api-session/added', mode: 'emit', resources: { session: (summary) => summary.sessionId } }`。API Remotes 把读取函数附在每个转发帧上;对每条非 owner 的 `$events` 流,Gateway 每帧解析一次资源,只有 `remoteAccess.decide({ principal, action: 'event:', resources })` 允许时才推送。 + +| 规则 | 内容 | +|---|---| +| 已声明事件 | `api-session/activity`、`api-session/added`、`api-session/error`、`api-session/removed` 与 `api-session/status` 声明其 Session | +| 未声明资源 | 未声明 `resources` 或声明为空 `resources: {}` 的事件访问 `global`,只有 `global` 级 role 列出 `event:` 时才送达非 owner | +| 缺失资源 | 事件携带其声明的每个资源,因此读取函数返回 `undefined` 时该事件的资源非法,Gateway 不询问 `decide()`,不送达任何非 owner;调用缺少资源时则为 `global` | +| 整条放行或拒绝 | 允许的事件 payload 原样送达;不按 Peer 裁剪或投影 payload | +| 每个事件一个资源 | 通知至多携带一个资源;集合类变化走 follow 类流(`session/follow`、`session/control`、`workspace/follow`),由这些方法内联经 `allows()` 逐项判定 | +| waterfall | 非 owner 从不收到 waterfall 帧,不经 policy 判定 | +| 非 owner 流的 Host 信息 | 非 owner 的 `$events` 流与 owner 流一样以完整 `host`(含 `home`)打开;`hasLiveClient()` 只统计能回答 waterfall 的 owner 流 | + + +#### 列表与聚合方法 + +列表、分页与聚合类方法的调用解析为 `global`,由 `global` 级 role 放行;方法内部对每一项调用 `this.ctx.remoteAccess.allows(resource)`,判定当前调用的 action 在该资源上是否被授权(不带 args)。因此列表类 action 同时出现在 `global` 级 role(放行调用)与资源级 role(放行逐项)中:`session/list` 在 `global` 上被授权才能调用,每个会话行还要求 `session/list` 在该会话上被授权。`allows()` 读访问该服务的 Context 上的 invocation,owner 与 Remote 调用之外的进程内代码恒为 true,不过滤。 + +| 方法 | 过滤对象 | +|---|---| +| `session/list` | 会话行(`session` 资源) | +| `session/search` | 搜索命中(`session` 资源) | +| `session/control` | baseline 的 projections 与 projection 增量(`session` 资源) | +| `workspace/follow` | baseline、`upsert` 帧与 `order` id 中的工作区(`workspace` 资源)、工作区内会话、archived / pinned 会话集合(`session` 资源)。流记录已下发的工作区;某个工作区在下一次变化或新顺序中已不被允许时,发送一个携带完整过滤后状态的 `replace` 增量帧而不是 `remove`,因为 Client 不会复活已移除的 id,访问恢复后该工作区经普通 `upsert` 重新出现。`remove` 帧表示删除,只发给收到过该工作区的调用方 | + +#### 访问快照流 + +```text +// Remote: remoteAccess/follow (stream; every Peer may read its own snapshot) +type RemoteAccessFrame = + | { readonly type: 'baseline'; readonly owner: true } + | { readonly type: 'baseline'; readonly owner: false; readonly grants: readonly RemoteAccessGrant[] } + | { readonly type: 'upsert'; readonly grant: RemoteAccessGrant } + | { readonly type: 'remove'; readonly resource: RemoteAccessResource } + +interface RemoteAccessGrant { + readonly resource: RemoteAccessResource // global, or one declared-kind resource + readonly actions: readonly string[] // endpoint actions allowed on this resource without args, sorted +} + +/** Window global carrying a page's opening baseline. */ +export const REMOTE_ACCESS_SNAPSHOT_KEY = '__DSH_REMOTE_ACCESS__' +``` + +| 行为 | 说明 | +|---|---| +| 首份快照 | `snapshotFor(principal)` 计算页面打开时的 baseline。remote-access 经 `webserver/index-inject` 为 webServer 渲染的每个 index 加入全局变量 `REMOTE_ACCESS_SNAPSHOT_KEY`,值为 owner baseline `{ type: 'baseline', owner: true }`。渲染非 owner 页面的业务包(例如 owner Host 上的 liveshare)在所有 index 注入行之后放置一条把该全局变量赋值为 `snapshotFor(principal)` 的语句;后写的赋值生效,Client 在挂载时读取该全局变量 | +| 订阅 | 每个 Peer 订阅一条访问快照流,其 baseline 取代注入的快照 | +| 计算 | 取该 principal kind 的 policy 的全部 binding,按资源相等归并;每个资源的 `actions` 为这些 binding 的 role 中、经与调用相同的判定(单个资源、不带 args,condition 以无 args 调用)放行的端点 action;只为至少放行一个端点 action 的资源给出 grant。判定与快照同源:同一 principal、action 与资源(不带参数)上,快照答案与 `decide()` 一致 | +| 只含端点 action | `event:` action 不进入快照;前端只据端点 action 决定入口显隐 | +| 增量 | `invalidate()` 或 policy 注册、撤回时重算并推送 `upsert` / `remove`,放行集合变空的资源推送 `remove`;未变化的资源不推送 | +| 生命周期 | 一代快照流在其 signal abort 或 remote-access 服务卸载时结束,因此重载后的服务从新的 baseline 回答每个读者;Client 把结束视为载体中断并重连 | +| owner | 只推送 `{ owner: true }`,前端全部为 true | +| wire 类型 | `actions` 为 `readonly string[]`:Typert 无法为模板字面量类型生成 codec | + +access hooks 只按 action 与资源判断,不看调用参数;调用时 condition 可额外读取 args 做更细判断,以服务端结果为准。 + +#### Client 面 + +Client 面走框架标准 hook 注入,不引入 React context。组件只经 props 拿到 hook,不 import remote-access 的值。 + +```text +// @deepseek-ai/dsh-api-remote-access/client +interface ClientRemoteAccess { // Client service ctx.remoteAccess + source(kind: TypertResourceKind, id: string, action: string): HostObservable +} +GlobalStandardProps.useRemoteAccess: (action: RemoteEndpoint) => boolean // remote-access; the global resource + +// @deepseek-ai/dsh-client-ui-session (injects remoteAccess) +GlobalStandardProps.useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean +SessionStandardProps.useAccess: (action: RemoteEndpoint) => boolean +SessionMaybeStandardProps.useAccess: (action: RemoteEndpoint) => boolean | undefined + +// @deepseek-ai/dsh-client-ui-workspace (injects remoteAccess) +GlobalStandardProps.useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean + +// RemoteEndpoint = Extract +``` + +| 事项 | 定稿 | +|---|---| +| 快照与挂载 | remote-access Client 插件从 index 注入的 baseline 起步(启动时同步读取并校验),订阅快照流,对每个 baseline 一次构建完成,提供 Client 服务 `ctx.remoteAccess.source(kind, id, action)`(身份稳定的布尔 source)并注入 `global` 资源上的 `useRemoteAccess`。入口模块 import 生成的 `/remote` contribution,连同注入的 baseline 交给 `mountAccess(ctx, contribution, initial)` 经 `ctx.remote.$mount` 自行挂载(单测传入假 contribution),先例为 experimental client-ui-cot-translation、voice-input、claude-code-mods;若由 api/remotes 集中挂载,会形成 ui-session → api/remotes → remote-access → ui-session 的 project reference 环 | +| 会话资源 | ui-session 经 `uiSession.provide({ keyedHooks: ['access'], resolve })` 给出本会话答案,会话由框架绑定,与 `useProjection` 相同;`useSessionAccess` 经 `provideRoot` 注入 | +| 工作区资源 | ui-workspace 经 `provideRoot` 注入 `useWorkspaceAccess` | +| 名称区分 | `global` 答案是 `useRemoteAccess`,会话答案是 `useAccess`,两者互不遮蔽;session-maybe 无会话时 `useAccess` 为 `undefined`,调用方按不允许处理,需要 `global` 判断时读 `useRemoteAccess` | +| 双参数调用 | 框架 keyed hook 的标准双参数:`KeyedStandardSource` 为 `(key, member?) => source`;第二个参数为字符串时 hook 读取 resolver 对 `(key, member)` 返回的 source,不带 selector;resolver 对同一参数返回同一 source。既有 `(key, selector?, equal?)` 与 `(selector, equal?)` 调用不变。禁止柯里化形式 | +| 返回值 | 有资源的答案均为布尔值;action 类型来自 `ctx.remote` 的 namespace 与方法 | +| 不回退 | 会话资源上查询非会话方法(如 `useAccess('session/create')`)读该会话资源上的判定结果,不回退 `global` 答案 | +| 无快照 | owner 为 true,快照流终止失败后亦然;没有注入 baseline 或快照流终止失败的非 owner 页面为 false,终止失败会连同错误与“刷新页面”的提示一并报告;断线重连期间保留上次快照;注入的 baseline 格式错误时挂载失败;Host 仍对每次调用执行检查。hook 从不发请求 | +| 示例消费方 | ui-workspace 会话行菜单的 fork 入口读 `useSessionAccess(sessionId, 'session/fork')`,不允许时不渲染;ui-chat turn tail 的分叉按钮读会话资源上的 `useAccess('session/fork')`,不允许时不渲染。替换 #3854 的 `clientWritePolicy` 留给 #3854 | +| 测试 | `@deepseek-ai/dsh-client-test-runtime` 导出 `allowAllAccess` props 与 `allowAllAccessPlugin`;TestClient 像 api-remotes 一样去掉 remote-access 行并装入全允许服务,SlotTestRuntime 在 ui-session 之前装入 | + +### 安全不变量 + +| 不变量 | 依据与落点 | +|---|---| +| principal 只能由进程内 Host 代码在创建 Peer 时给出 | `PeerScope.principal` 只读;`createPeer()` 不对应任何路由 | +| wire 上任何字段都不能设置或覆盖 principal | principal 不来自 args、envelope、header、query 或 cookie。args 顶层多余字段被 `assertExactArguments` 拒绝;payload 必须恰为 `{ args }`;envelope 未知字段被 [`clientRequestSchema`](../../../../packages/client/connection/src/rpc-schema.ts) 丢弃;请求体内同名字段只是业务数据 | +| 浏览器网络准入为 owner | 通过[浏览器 token 认证](../../implemented/architecture/2026-08-24-browser-token-authentication.zh.md)的连接得到 `browserPeer` | +| 没有隐式 Peer | Gateway 与 Connection 都不补默认 Peer;required 参数让漏传在编译期暴露 | +| 已 dispose 的 Peer 不能再分派 | `gateway/peer-disposed` | +| 非 owner 未经授权不能调用 | 只有 binding 的 role 显式列出该 action 且资源匹配时才放行;没有该 kind 的 policy 即拒;Gateway 依赖 `remoteAccess`,缺失时 Gateway 不启动 | +| `global` 授权不蕴含资源授权 | 资源之间无继承;方法内 `allows()` 对每一项独立判定 | +| 未知 principal kind 不是 owner | 只有 `kind === 'owner'` 是 owner | +| 非 owner 不回答 waterfall | `$events` 不给非 owner waterfall 帧,`$events/result` 拒绝非 owner | +| 非 owner 只收到被授权的通知 | 每个转发帧按 `event:` 与其资源判定,被允许才转发给非 owner | + +### 消息来源落盘 + +[session-controller 类型](../../../../packages/api/session-controller/src/types.ts) 的 `MessageSourceMap` 条目增加可选字段: + +```text +'user-rpc': { + kind: 'user' + rpcId: SessionRequestId + clientTimeZone?: string + /** Non-owner caller that submitted this prompt; absent means the owner. */ + principal?: Principal +} +``` + +在 Remote 调用中构造 `kind: 'user'` + `rpcId` 用户消息 source 的生产者共两处,都在 Remote 方法内调用 `principalOf(this.ctx.invocation)`,返回值非 `undefined` 才写 `principal`: + +| 生产者 | 位置 | +|---|---| +| `SessionController.prompt()` 构造 source,`SessionCommandController.prompt(request, source)` 只负责投递 | [`session-controller/src/index.ts`](../../../../packages/api/session-controller/src/index.ts)、[`commands.ts`](../../../../packages/api/session-controller/src/commands.ts) | +| subagent `prompt()`(`BrowserPromptSource`);没有 role 列出它,非 owner 只能经进程内 Host 代码到达,不能经 Gateway 到达 | [`subagent/src/index.ts`](../../../../packages/subagent/subagent/src/index.ts) | + +业务代码不把 principal 当函数参数逐层传递:身份只在 Remote 方法内从 invocation 读一次,向下传的是已构造的 source。Agent inbox 没有可在消息入队时统一补字段的拦截点(`followup` / `steer` 接受已构造的消息,SDK、调度等进程内生产者不在 Remote 调用中),因此按生产者落实,并由代码评审标准约束新增的生产者。 + +| 事实 | 说明 | +|---|---| +| `kind` 不变 | 仍为 `'user'`;现有 `kind === 'user'` 判断不受影响 | +| owner 消息不变 | owner 调用时不写字段,source 与引入 principal 之前逐字节相同;没有该字段的消息(含全部旧会话)即为 owner | +| 不进入模型请求 | llm 适配器只读 model source([`llm-deepseek/src/replay.ts`](../../../../packages/llm/llm-deepseek/src/replay.ts)) | +| 会话格式 | 不 bump `SESSION_FORMAT_VERSION`;按 [persistence 类型变更 cookbook](../../../../docs/cookbook/reviewing-persistence-type-changes.zh.md) 为该持久化类型变更记录 acknowledgement | + +消费方用法示例(不在本 Note 范围内实现):工具守卫与 pre-step 复检按 turn 读取该 turn 内用户消息的 `source.principal`,任一条带非 owner principal 即按该调用方判定;同一 turn 混有 owner 与读者消息时取最严格者。 + +### 代码评审标准与文档 + +评审标准的正家为 [Remote and API rules](../../../../docs/defensive-patterns/remote-and-api.zh.md) 的「`@Remote` 标在能力方法上」一节:`@Remote({ resources })` 与自动解析必须覆盖方法访问的全部资源;聚合结果逐项经 `allows()` 过滤;调用方身份只读 `invocation.peer.principal`,不从参数读取;每条调用路径显式给出 Peer;业务代码不把 principal 当函数参数传递。 + +| 文档 | 内容 | +|---|---| +| [`docs/subsystems/typert.md`](../../../../docs/subsystems/typert.zh.md)、[`docs/api-gateway.md`](../../../../docs/api-gateway.zh.md) | `PeerScope`、`RemoteInvocation`、`InvokeRemoteRequest`、显式 Peer、`@Remote` 的 `resources`、访问检查顺序 | +| connection、gateway、typert-protocol、typert-registry、api-remotes、remote-access、session-controller、workspace-controller、ui-session、ui-workspace、ui-slots、client-test-runtime 的 README | 以 Peer / `browserPeer` 取代 operator;remote-access 的 role、binding、policy 契约;access hooks | + +### 不在范围与 Future work + +- `/connect` 握手、API Cookie、每条 API 连接一个 Peer、WebSocket 生命周期:归 pr-5945。 +- 浏览器多 Peer(如每标签页一个):所有浏览器连接共享 `browserPeer`。 +- 交互参与(interactions)与按 principal 隔离审批由后续工作引入;目前非 owner 只收被授权的 `$events` 广播帧。 +- `agent-preset/selected` 等其余转发事件未声明资源,按 `global` 判定;读者需要某个会话事件时,#3854 为其声明资源并在 role 中列出 `event:`。 +- liveshare 接入(声明 `share-viewer`、每条读者连接一个 Peer、定义 role 并注册 policy、删除 `origin` / `prompt/origin` / `READ_ENDPOINTS`):#3854 侧。 +- `session/cancel` 归属检查、fork 的 `childSessionId`、`ToolExecutionInput.turn`:不改。 +- 资源识别的精确方式(例如 Typert 生成器按 branded id 类型在请求对象中定位字段并写入描述符):目前用 lookup 与 Context 声明的 `resource`、默认字段加 `resources` 读取函数,以后可替换资源解析而不改 policy 接口。 +- exact Fetch route 对非 owner 一律 403 是临时处理;以后由各路由声明访问规则。 +- subagent `prompt` 的资源声明待定:其请求字段为 `parentSessionId` / `childSessionId`,目前解析为 `global`。生产者为进程内调用方记录 `source.principal`;没有 role 列出它,非 owner 不能经 Gateway 到达。 +- 预定义与聚合 role:出现第二种非 owner principal kind 时,由各领域包以 `@Remote({ roles })` 声明方法所属的通用 role(如 `session:viewer`),各 policy 绑定这些 role;目前 role 由业务包以显式 action 清单定义。 + +### 与现有 Note 的关系 + +- [Remote 双工流](../../implemented/architecture/2026-09-19-remote-duplex-stream.zh.md):部分 supersede。被替换的部分包括:「Peer 不记录身份与权限」「本 Host 只有一个 Peer:operator」「in-process carrier 不给 Peer 即 operator」,以及其替代方案中「Access 机制属于业务语义」的表述;其余(双工流、uplink、`ctx.invocation` 绑定)保持。两篇保持 active 并互链,该 Note 的现行事实已同步更新。 +- [浏览器 token 认证](../../implemented/architecture/2026-08-24-browser-token-authentication.zh.md):不受影响。该 Note 否决「按方法区分特权」针对的是 owner 的认证;通过认证的浏览器仍是 owner 且不受方法级检查。 +- [Typert Remote 方法调用](../../implemented/architecture/2026-08-02-typert-remote-method-calls.zh.md):不受影响;`@Remote` 与 `@RemoteScope` 增加可选的 `resources` 读取函数(`@RemoteScope` 的第二个参数可为 `{ name?, resources? }`),只供 Gateway 的访问检查读取,不改变端点命名、调用模式与生成物。 +- [生产方拥有的消息来源](../../implemented/architecture/2026-09-09-producer-owned-message-sources.zh.md):不受影响;`principal` 由构造 source 的生产者写入。 + +## 考虑过的替代方案 + +**独立 `prompt/origin` 事件并按 requestId 关联(#3854 做法)。** 每条 prompt 都写 required 事件,普通会话也无法被旧版本读取;关联要求全部 prompt 串行并维护来源 fold,fold 窗口外的消息失去发起者。 + +**principal 与 peer 并列挂在 invocation 上。** 同一调用方的身份拆成两处来源,准入点要同时产出并传递两者,任一路径只传其一就会错配。 + +**保留「Peer 不记录身份」的原约定。** 身份由业务插件经 `peer.ctx` 附加时,每个读取方都要知道由谁附加、如何读取,wire 准入路径也无法保证附加发生。 + +**保留默认 Peer 兜底(`request.peer ?? …`)。** 隐式默认让漏传 Peer 的调用静默获得 owner 身份;required 参数把漏传变成编译错误。 + +**新开 source kind。** 现有 `kind === 'user'` 判断都要逐个审视,漏一处就让读者消息在标题、大纲、队列或聊天渲染中消失。 + +**请求体字段携带身份。** 任何能构造请求体的调用方都能伪造或覆盖它。 + +**前端 React context 提供资源。** 业务组件不得读 React context;标准 hook 由框架按资源绑定,组件只经 props 拿到。 + +**由驱动方自行维护端点白名单并裁剪结果(#3854 做法)。** 白名单与结果裁剪都在驱动方内,Gateway 不执行,快照与前端各自推导;role 的 action 清单由通用层执行,列表过滤由方法内的 `allows()` 完成。 + +**业务包实现 `decide()` / `abstain` 的 provider,并合并多个 provider 的答案。** 每个业务包手写 action × 资源的判别分支,另写一份资源列表供快照,两者靠人工保持一致;policy 只给出 binding,判定与快照由同一份 binding 算出,每种 principal kind 只有一个 policy,不需要合并规则。 + +**独立的 `@RemoteAccess` 标记。** 默认拒绝已由 role 的显式 action 清单保证,标记只是第二道同意;一个资源都没解析出的方法落到 `global`,只有显式的全局授权能放行。资源读取函数是方法描述信息,放在 `@Remote` 上。 + +**把无资源的调用称为 `page` 或 `host`。** `page` 描述前端位置而不是资源;`host` 容易被读作这台 Host 上全部资源的上级。`global` 表示不关联任何资源的授权。 + +**资源继承(GCP 式:`global` 或工作区上的授权覆盖下级资源)。** 列表方法被 `global` 授权放行后需要逐项细判,继承会让任何 `global` 授权蕴含全部会话;无继承时每个资源的授权都由 binding 显式给出。 + +**role 注册表与预定义聚合 role。** 目前唯一的非 owner principal 由一个业务包管理,role 作为该包的普通值即可;聚合 role 会让新包声明的方法自动进入分享读者的可访问范围,推迟到出现第二种非 owner principal。 + +**condition 挂在 role 的 action 上。** role 保持为可复用的纯数据;按业务状态细化的判断属于把 role 授予某个 principal 的 binding。 + +**拒绝原因只由 condition 给出。** 没有 binding 时没有 condition 可以给出原因,读者页面无法区分「分享已过期」「分享不允许写入」等情况;`explain` 只在结论已为拒绝后给出原因,不改变结论。 + +**全局资源 resolver 注册表(领域包按字段名注册识别函数)。** 字段识别与方法分离,方法改签名时无人提醒,跨包同名字段也会被误认;资源解析采用方法上的默认约定加 per-method `resources`,领域包只登记自己种类的默认字段。 + +**按点路径声明资源(`'request.address.sessionId'`)。** 路径无法由类型推导约束;`resources` 读取函数的参数类型从被装饰方法推断,拼错即编译失败。 + +**由生成器按 branded id 类型识别资源字段。** 需要改 Typert 生成物与描述符格式,SRC 描述符没有类型信息;留作 Future work。 + +**由 api/remotes 集中挂载 remote-access 的 generated contribution。** remote-access Client 依赖 ui-session,ui-session 依赖 api/remotes,集中挂载形成 project reference 环;改为自挂载。 + +**在 Gateway 内实现判定(带规则的 `check()` 写在 Gateway)。** Gateway 会承载访问控制语义并多出错误码;Gateway 像解析 lookup 一样解析资源,在分派前调用 `remoteAccess.decide()`,规则与拒绝码归 remote-access。 + +**policy 异步判定。** 列表逐项过滤与快照计算需要同步答案;异步状态由业务包预先载入内存。 + +**前端按需查询权限。** 请求量随入口数增长,且与规则变化无法同步;快照流由 Host 主动推送,前端同步读取。 + +**访问检查放在 lookup 解析之后。** lookup 可能激活 Agent,未授权调用会先产生副作用。 + +**在 remote-access 中登记资源字段(`registerScope`)。** 访问控制包要识别参数字段,而 lookup 本已知道哪个 wire 字段指向 Session;typert 把资源种类与 lookups、Contexts 并列保存,Gateway 在一处解析调用与事件,remote-access 不读取任何参数字段。 + +**按 Peer 裁剪转发事件的 payload。** 逐事件投影会在每个通知里重复一遍列表过滤;一个事件至多携带一个资源,整条放行或拒绝,集合类变化走内联过滤的 follow 类流。 + +**首份快照到达前一律回答 true。** 非 owner 页面会短暂显示无权使用的入口;index 携带首份快照,没有快照的页面即无权限。 + +## 后果 + +### 验证 + +| 用例 | 行为 | 测试落点 | +|---|---|---| +| wire 试图设置 principal(args 顶层、payload 并列、envelope、请求体内) | 前两种以参数或 payload 校验拒绝;其余被丢弃或当作业务数据;`invocation.peer` 仍为准入给出的 Peer | Gateway host spec | +| 所有调用路径显式给出 Peer | `InvokeRemoteRequest.peer`、`wireStream.open` 的 peer、`fetch(request, peer)`、`bridge` 的 peer 为 required;Gateway 中不存在兜底;`/api` 路由传递 `admission.peer` | typecheck、Connection host spec | +| 浏览器连接与 `createPeer()` | `browserPeer` 的 principal 为 owner;`createPeer()` 每次返回独立 Peer,随读取 Connection 的 Context 释放;exact route 对非 owner 返回 403 | Connection host spec | +| 已 dispose 的 Peer | 之后的 unary、stream 与 `$events` 分派以 `gateway/peer-disposed` 拒绝,wire payload 畸形时亦然;其名下 stream 结束;运行中的 unary 完成;不影响其他 Peer | Gateway host spec | +| 鉴权顺序 | owner 调用任何方法照常分派且不读取 policy;没有 role 列出的方法对非 owner 以 `remote-access/denied`(`no-allow`)拒绝;访问检查早于 lookup,被拒调用不激活会话 | Gateway host spec | +| policy 注册 | 每个非 owner principal kind 一个 policy,重复注册抛错;disposer 撤回后该 kind 以 `no-allow` 拒绝;随 fiber 撤回 | remote-access host spec | +| 判定 | 每个资源都需要匹配的 binding(AND);role 不含该 action、资源不相等或 condition 拒绝都不放行;拒绝原因按 condition > `explain` > `no-allow` 取;`explain` 不改变结论;condition 在调用时收到 args,在快照与列表过滤时不收;`bindings()`、condition 或 `explain()` 抛错以 `policy-failed` 拒绝,每个 policy 在两次 `invalidate()` 之间只记录一次日志,事件路径上 owner 流与共享事件源照常;`remoteAccess/follow` 对任何 principal 放行 | remote-access host spec、Gateway host spec | +| 资源解析 | 默认字段(顶层或首个对象参数)得到对应资源;声明了该种类 `resource` 的 lookup 参数得到其 wire 身份;Context 方法从 args 中的 Agent Context 身份得到其 session 资源且不激活 Agent,另可经 `resources` 声明其他资源;`resources` 读取函数覆盖该种类,数组为多个资源,`undefined` 为无;都没有为 `[global]`;抛错、空数组或非非空字符串(含 Context 身份)为非法,Gateway 以 `resource-invalid` 拒绝且不询问 `decide()`;未声明 `resource` 的 Context 按普通规则解析;资源与 `args` 读取校验后的参数,未声明的嵌套字段不改变资源、condition 也读不到它,JSON 参数校验失败在访问检查前返回 `gateway/input-invalid` | Gateway host spec(gateway-access) | +| 资源注册表 | `typert.resources` 每个种类登记一个默认字段,拒绝重复登记与 `global`,并随 fiber 撤回;配置的 lookup resolver 保留 provider 的 `resource`;Host Context adapter 保留其 `resource` | typert-registry spec | +| 转发事件 | 非 owner 的 `$events` 流只在 `event:` 于其资源上被授权时整条收到事件;未声明资源的事件按 `global` 判定;读取函数返回 `undefined` 的事件不送达非 owner,且不询问 `decide()`;owner 全部收到 | Gateway host spec(gateway-access) | +| 首份快照 | `snapshotFor()` 返回 owner baseline 或该 principal 的 grant;remote-access 为渲染的每个 index 注入 owner baseline;Client 从注入的 baseline 起步并拒绝格式错误的快照 | remote-access host 与 client spec | +| 类型推断 | `resources` 读取函数的参数类型从方法推断;lookup 位为 wire 类型;访问不存在的属性、参数多于方法参数与 `global` 键编译失败;binding 的资源种类与 role 不符编译失败 | typert-protocol spec、remote-access spec(类型测试) | +| 列表过滤 | `session/list`、`session/search`、`session/control`、`workspace/follow` 对非 owner 只返回 `allows()` 为 true 的项;已下发工作区失去可见性时 `workspace/follow` 发送 `replace` 增量帧,访问恢复后该工作区重新出现;owner 结果不变 | session-controller / workspace-controller host spec | +| 访问快照 | 快照中的允许集合与 Host 对同一 principal、action、资源(不带参数)的判定一致;只含端点 action;没有放行 action 的资源不出 grant,放行集合变空时推送 `remove`;`invalidate()` 与 policy 注册、撤回后推送增量;被变化结束的等待不残留 abort 监听器;卸载服务即结束所有打开的快照流;owner 只收 `{ owner: true }` | remote-access host spec | +| access hooks | `source()`、`useRemoteAccess`、`useAccess`、`useSessionAccess`、`useWorkspaceAccess` 与快照一致;会话资源上的 `useAccess` 读本会话答案;owner 为 true;没有快照或快照流失败的非 owner 为 false;hook 不发请求 | remote-access client spec、ui-session / ui-workspace client spec | +| keyed hook 双参数 | 第二个参数为字符串时读取 `(key, member)` source;既有调用形式不变 | ui-renderer client spec | +| 非 owner 分派 `session/prompt` | 落盘 user 消息 `source.principal` 等于该 principal;冷恢复后仍读到同一值 | session-controller host spec | +| 进程内以非 owner invocation 调用 subagent `prompt` | 子会话落盘的 user 消息 `source.principal` 等于该 principal | subagent host spec | +| owner 消息 | source 与本变更之前逐字节相同;现有 keyless recorded-session snapshot 不变 | `pnpm run test:snapshot` 不需要重录 | +| 持久化记录 | `verify-persistence-changes` 通过 | doc-sync | + +SDK 投影不受影响:TypeScript SDK server 自行构造 `{ kind: 'user' }` 消息([`sdk/server/src/server.ts`](../../../../packages/sdk/server/src/server.ts)),不经 Gateway,也不投影 source;Python SDK 不读取 user source。 + +### 代价与限制 + +- 改动面横跨 protocol、Connection、Gateway、两个领域控制器、subagent、新包与前端,并带破坏性 API 改名;与 pr-5945 在 Connection 与 Gateway 上必然冲突,按迁移清单处理。 +- Gateway 依赖 `remoteAccess`:自建组合若挂载 Gateway 而不挂载 remote-access,Gateway 停在等待状态。 +- Session 日志会保存读者身份;导出或分享会话时随之外传,每个 principal 种类不得携带凭据。 +- 浏览器所有连接共享一个 Peer:dispose 无法按标签页区分,直到浏览器多 Peer 落地。 +- 默认字段约定按字段名读取:方法新增同名字段即访问对应资源,评审需留意;精确识别列为 Future work。 +- 只解析出部分资源的方法会放行越权:未解析的资源不受检查,由方法作者保证 `resources` 完整。 +- role 的 action 是字符串,不与已加载端点核对:拼错或改名后的 action 永不匹配,表现为拒绝。 +- `api-session/added` 携带完整的 `SessionSummary`,因此被允许接收它的非 owner 也会得知该会话的 `parentSessionId`。 +- 被授权会话的 cwd 与工具路径本就包含 owner 的绝对路径,因此 Gateway 不对非 owner 的 `$events` 流单独隐藏 `home`。 +- policy 撤销某个工作区的可见性后,`workspace/follow` 只在该工作区下一次变化或顺序下一次变化时察觉并向非 owner 发送 `replace` 增量帧;仅访问变化不会发送帧。 + +### 留给 pr-5945 的迁移清单 + +| 文件 | 迁移 | +|---|---| +| `packages/client/connection/src/peer.ts` | 取代 `operator-peer.ts`;`OperatorPeer` 构造改为 `new Peer(owner, { principal })` | +| `packages/client/connection/src/rpc-host.ts` | `this.operator` 改为 `browserPeer`,principal 为 `{ kind: 'owner' }` | +| `packages/client/connection/src/rpc.ts` | `HostConnectionHandle` 合并 `admitConnection` 与 `browserPeer` / `createPeer` | +| `packages/api/gateway/src/index.ts` | `$events` 打开处的 `peer ?? this.operatorPeer()` 改为显式 Peer;复用 `gateway/peer-disposed` | +| operator-connect 的 Note、升级指南与 subsystems 改动 | operator 术语改写为 Peer / `browserPeer`;API 连接的 Peer 为 `{ kind: 'owner' }` | diff --git a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.i18n.yaml new file mode 100644 index 0000000000..be7bf32098 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for 2026-10-13-chat-single-fold-motion.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-13-chat-single-fold-motion.md +/agent-note-one-fold-motion-for-collapsing-on-the-next-message: + en: 45594545dabfaa78 + zh: a1eac669647b2bac +/agent-note-one-fold-motion-for-collapsing-on-the-next-message/problem: + en: 88faaf0c589e12cb + zh: dda7efc5eaed2788 +/agent-note-one-fold-motion-for-collapsing-on-the-next-message/decision: + en: 972bbe45fe8ac28e + zh: 593b851c142894e1 +/agent-note-one-fold-motion-for-collapsing-on-the-next-message/decision/batches: + en: f44b784545c6d9a2 + zh: 3eb6fcb9f348dec4 +/agent-note-one-fold-motion-for-collapsing-on-the-next-message/decision/landings: + en: b8278678170f1507 + zh: 113a51ba5cf27de1 +/agent-note-one-fold-motion-for-collapsing-on-the-next-message/decision/own-input: + en: ca6a5c372bb3cad1 + zh: 1cd5028269b58c65 +/agent-note-one-fold-motion-for-collapsing-on-the-next-message/testing: + en: 0423a607ee0589b5 + zh: 61df892a01c5aa43 +/agent-note-one-fold-motion-for-collapsing-on-the-next-message/alternatives-considered: + en: d8e1ea66e293cd93 + zh: 0aaa9e693f441673 +/agent-note-one-fold-motion-for-collapsing-on-the-next-message/consequences: + en: 89148df30a9a1772 + zh: d484cc7c9e0cc3f1 diff --git a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.md b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.md new file mode 100644 index 0000000000..8c279abb34 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.md @@ -0,0 +1,92 @@ +# Agent Note: One fold motion for collapsing on the next message + +Status: implemented + +English | [中文](2026-10-13-chat-single-fold-motion.zh.md) + +## Problem + +When "When to Collapse Work Details" is "On next message", the previous exchange's process rows close when the next human input arrives. The scroll layer had two fold paths and chose one by `ownInput` ([use-chat-scroll.ts](../../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts)): + +- **Input fold path:** when the fold starts, it measures the closing rows, computes the final landing and the required bottom room, and moves the rows and the scrollport on one frame clock to a single landing. +- **Generic path:** scrollTop stays put, the closing height is reserved as bottom room in one block, and following scrolls once more after the fold ends. This holds only when the fold happens below the reader. When the folding region is above the reader, the content the reader is looking at moves up as a whole and the viewport shows only the room. + +`ownInput` holds for three signals only: a local echo in the transcript (`submissionId`), a steer echo (`steeringId`), or a user message as the last list row (`lastIsUser`). In the commit where the Host records the opening input, the Turn's process control is ordered after that input, so `lastIsUser` does not hold. Every human input without a transcript echo on this page therefore took the generic path: + +| Source | Echo on this page | Reader at the bottom | Reader in the middle of the body | +|---|---|---|---| +| Idle send from the main composer | Yes, in the transcript | Correct | Correct | +| Main-Session queued message delivered after the previous Turn | Yes, but in the queue, not consulted | Whole viewport blank | Whole viewport blank | +| Send from another tab | No | Whole viewport blank | Whole viewport blank | +| Send from a subagent child's composer in the right Sidebar | No (the composer skipped `beginSubmission`) | Whole viewport blank | Whole viewport blank | +| Human send after parent messages woke several child Turns | No | Whole viewport blank (about 6000 px of room) | — | + +Notice-woken Turns no longer fold anything ([group-tree positions and exchanges](2026-10-11-chat-group-tree-exchanges.md)); the table above covers the human input that still folded through the generic path. The data comes from [fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts). + +Subagent children showed no local echo because, when echoes were introduced, `subagents.prompt` carried no request id, so an echo could not be matched with the message the child recorded. Subagent control later moved to Remote, and the Host now records `SubagentPromptRequest.requestId` as the child message's `source.rpcId`; the client's `Session.prompt` still minted a separate id. + +## Decision + +"On next message" keeps a single fold motion: [flow-motion.ts](../../../../packages/client/ui-chat/src/client/chat/flow-motion.ts) hands every batch of closing rows to the `InputFoldDriver` that the viewport supplies, and [use-chat-viewport.ts](../../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts) chooses one of two landings when the batch begins. + +### Batches + +- Rows that start closing in one commit, together with rows that start revealing in it, form one batch. The driver's four steps are: + - `begin`: measure the boxes and choose the landing; + - `prepare`: grow the room before box writes so the browser does not clamp an intermediate frame; + - `frame`: write box heights and scrollTop together; + - `finish`: install the final room. + + Content added during the batch updates the remaining movement by starting a new segment. +- A row that starts closing or revealing while a batch runs keeps its current size, without a transition of its own, until that batch settles; the next flush drives it in a new batch, or starts a held revealing row's own transition when nothing closes. Rows therefore never change outside a batch while following continues, which would follow the bottom room without the growth that should have consumed it. A batch takes over every member at its current size: a closing row shrinks from the height it has now, and a revealing row grows from the height its own transition already reached, so only the remaining growth enters the landing; a closing row with no size left finishes without animation. +- A batch with only revealing rows needs no room and keeps CSS transitions. When the viewport has no reading policy attached, closing rows also keep CSS transitions, and held rows finish immediately; under reduced motion closing rows finish immediately. +- Closing rows commit their hidden state first, the driver then installs the final geometry, and only then are fold-idle listeners notified (for example, clearing room after a display-mode change). +- The generic path is removed: the `reserve` callback, the `pendingReserve` and `pendingGrowth` reservation arithmetic, `reserveBelow`, and the post-fold `followAfterFold`. `reclaimBelow` (returning room after new content or reader scrolling) and `resetBelow` (clearing room after a display-mode change) remain. + +### Landings + +Let `start` be the scrollTop when the batch begins, `above` the height of closing rows above the viewport top minus revealing rows there, `base = max(0, start − above)`, and `bottom` the floor after the fold. + +| Landing | When | Target scrollTop | After the batch | +|---|---|---|---| +| **Tail** | This client's own input, or the reader was following the tail when the batch began and had no reading movement awaiting sampling | `max(base, bottom)` | Commit follow ownership | +| **Reader content still** | Otherwise | `base` | Keep the reader's reading state and acknowledge the new position | + +- Both landings install only the exact deficit as room: `max(0, target + viewport height − folded height)`. The tail landing reads the committed layout when it finishes: it lands at the larger of the target and the real floor, and keeps only the room that target needs. +- Content never slides back down: content already above the viewport top does not return. When the retained body and the new message cannot fill the viewport, the deficit remains as room until new content fills it. +- Own input during a running batch starts a new segment from the current position toward the tail; it takes over even when a reading gesture cancelled the automatic target. A tail request counts only while a batch runs or is scheduled; rows still closing on CSS transitions after a batch leave own input to ordinary following. +- A reading gesture cancels a tail landing's automatic target and keeps the reader's position. During a reader-content-still landing, the reader's own scrolling between frames moves the position the batch keeps still. +- For the reader-content-still landing, the driver takes the first visible top-level row outside the batch as a reference, found by binary search over the ordered top-level rows. Neighbouring spacing changes instantly when the batch begins and when closing rows commit their hidden state; the driver measures the reference's displacement at those two points and offsets scrollTop by it. +- When a tail landing scrolls forward past closing rows that start below the viewport top, those rows stay opaque, scroll with the content, and clip while they shrink; nested closing rows keep their size until the batch ends. Other closing rows fade in place. A newer tail request that takes over a running batch adds the closing rows still below the viewport top; a row that has already faded becomes opaque again for its remaining height. Scrolling forward therefore never crosses space that is already transparent but not yet closed. + +### Own input + +| Source | Determination | Landing | +|---|---|---| +| Idle send from the main composer | Transcript echo | Tail | +| Idle send from a subagent child's composer | The child also registers a local echo; `subagents.prompt` uses the echo's `requestId` | Tail | +| Queued while running, delivered after the previous Turn | Not own input | Tail when following, otherwise reader content still | +| Send from another tab | Not own input | Same as above | +| Parent Agent messages a child | The notice opens no exchange and folds nothing | — | + +"On completion" is outside the motion scope; its folds apply immediately and are unaffected. + +## Testing + +[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) covers 19 main-Session cases and 8 right-Sidebar child cases across reader position (bottom, middle of the body, top of the body, inside the steps, previous Turn), input source (composer, Turn failing before its message is recorded, another tab, queued delivery, steer, parent message, several Turns folding at once), body length, and Standard and "On completion" controls. The layout gap is the tallest band between the scrollport top and the composer that no visible row's box covers: at most 120 px once settled, and over that for at most one animation frame. It counts boxes, so a closing row that has faded but not finished shrinking still covers its space. Tail cases assert the floor landing; reader-content-still cases assert that the reader's anchor row moves at most 2 px on screen. Short-body cases assert only that no room remains after the reply arrives. + +## Alternatives considered + +**Keep the generic path and fix only own-input detection.** The two paths keep diverging geometry rules; for input that is not own input, a reader in the middle is either pulled to the bottom or still sees a blank. + +**Compensate the generic path by reader position but implement it separately from the input path.** The compensation and room geometry would exist twice and could diverge again. + +**Detect own input from the exchange-opening human node and keep children without echoes.** Input from another tab would count as own input and pull a reader in the middle to the bottom; child sends still would not show the sender's message immediately. + +**Let content slide back to fill the deficit a short body leaves.** Content would move up and then down within one animation. + +## Consequences + +- Benefit: the source of whole-viewport blanks (the generic path) no longer exists; the landing depends only on whether the input is own input and whether the reader was following, not on which page sent the message or when it was delivered. Child sends show the sender's message immediately. +- Cost: with a short body, content never sliding back still leaves the deficit until new content fills it. +- When focus is inside a closing row, focus protection keeps that row open. If it is a height-capped process group, its body shrinks to the cap immediately. That shrink happens before the batch begins, so the reader-content-still landing cannot measure it and the reader's content moves once. diff --git a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md new file mode 100644 index 0000000000..96e36590e7 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md @@ -0,0 +1,92 @@ +# Agent Note: 「下条消息时收起」只用一条折叠动画 + +Status: implemented + +[English](2026-10-13-chat-single-fold-motion.md) | 中文 + +## Problem + +「何时收起工作详情」选「下条消息时收起」时,上一个交互段的过程行在下一条人类输入到来时收起。滚动层原本有两条折叠路径,按 `ownInput`([use-chat-scroll.ts](../../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts))二选一: + +- **输入折叠路径**:折叠开始时测量收起行,算出最终落点和所需的底部补白,收起与滚动在同一个帧时钟上推进,一次落定。 +- **通用路径**:scrollTop 不动,把收起的高度整块预留为底部补白,折叠结束后再按跟随状态补滚一次。它只对折叠发生在读者下方的情况成立。折叠区在读者上方时,读者正在看的内容整体上移,视口里只剩补白。 + +`ownInput` 只在三种信号下成立:对话流里的本地回显(`submissionId`)、steer 回显(`steeringId`)、列表最后一行是用户消息(`lastIsUser`)。Host 写回开场输入的那次提交里,该轮的过程控制行排在输入之后,`lastIsUser` 不成立。于是,凡是不经过本页对话流回显的人类输入都走通用路径: + +| 来源 | 本页回显 | 读者在底部 | 读者在正文中段 | +|---|---|---|---| +| 主会话输入框空闲发送 | 有,在对话流 | 正常 | 正常 | +| 主会话排队消息在上一轮结束后自动投递 | 有,但在排队区,不参与判定 | 整屏空白 | 整屏空白 | +| 另一个标签页发送 | 无 | 整屏空白 | 整屏空白 | +| 右侧栏子会话输入框发送 | 无(composer 跳过 `beginSubmission`) | 整屏空白 | 整屏空白 | +| 子会话里父消息唤醒多轮后人类发送 | 无 | 整屏空白(补白约 6000 px) | — | + +通知唤醒的 Turn 已不再触发折叠([分组树位置与交互段](2026-10-11-chat-group-tree-exchanges.zh.md));上表是仍经由通用路径折叠的人类输入。数据来自 [fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts)。 + +子会话不显示本地回显,是因为引入回显时 `subagents.prompt` 不携带 request id,回显无法与子会话写回的消息对应。此后子 agent 控制迁到 Remote,`SubagentPromptRequest.requestId` 已被 Host 写入子会话用户消息的 `source.rpcId`;客户端 `Session.prompt` 却仍另行生成 id。 + +## Decision + +「下条消息时收起」只保留一条折叠动画:[flow-motion.ts](../../../../packages/client/ui-chat/src/client/chat/flow-motion.ts) 把每一批收起交给 viewport 提供的 `InputFoldDriver`,[use-chat-viewport.ts](../../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts) 在批次开始时选择两种落点之一。 + +### 批次 + +- 同一次提交中开始收起的行,连同同批开始展开的行,组成一个批次。驱动器的四步依次为: + - `begin`:测量这些盒子,选定落点; + - `prepare`:在写盒子之前扩大补白,避免中间帧被浏览器截断; + - `frame`:同步写盒子高度和 scrollTop; + - `finish`:安装最终补白。 + + 批次中途新增的内容按分段规则更新剩余运动。 +- 批次运行期间开始收起或展开的行保持当前尺寸、不走自己的过渡,等当前批次落定后由下一次刷新处理:有收起行时进入新批次,只剩展开行时启动它自己的过渡。因此不会出现「批次之外有行在变化、同时跟随照常进行」的情况;否则跟随会把底部空间整块跟进去,而本该抵扣它的新内容没有被计入。批次按每个成员的当前尺寸接管:收起行从现有高度收缩,展开行从它自己的过渡已达到的高度继续增长,只有剩余的增长量计入落点;已无尺寸的收起行直接完成、不做动画。 +- 只含展开行的批次不需要补白,仍用 CSS 过渡。viewport 未挂载阅读策略时,收起行也用 CSS 过渡、被挂起的行立即完成;减少动态效果时收起行立即完成。 +- 收起行先提交 hidden,驱动器再安装最终几何,之后才通知 fold-idle 监听者(例如切换展示模式后清空补白)。 +- 通用路径已删除:`reserve` 回调、`pendingReserve` 与 `pendingGrowth` 的预留计算、`reserveBelow`、折叠结束后再跟随的 `followAfterFold`。保留 `reclaimBelow`(新内容到来或读者滚动后归还补白)与 `resetBelow`(切换展示模式后清空补白)。 + +### 落点 + +记 `start` 为批次开始时的 scrollTop,`above` 为视口顶部以上收起行的高度减去展开行的高度,`base = max(0, start − above)`,`bottom` 为折叠后的底部位置。 + +| 落点 | 何时 | 目标 scrollTop | 结束后 | +|---|---|---|---| +| **到底部** | 本客户端的自己输入,或批次开始时读者正在跟随底部、且没有尚待采样的阅读滚动 | `max(base, bottom)` | 提交跟随状态 | +| **读者内容不动** | 其余情况 | `base` | 保持读者的阅读状态,确认新位置 | + +- 两种落点都只安装精确差额作为补白:`max(0, 目标 + 视口高 − 折叠后高度)`。到底部落点在结束时读取已提交的实际排版:落在目标与真实底部中较大的位置,只保留该目标所需的空间。 +- 「内容只上不下」:已经在视口顶部以上的内容不会回滑。保留的正文和新消息不足一屏时留出差额,新内容到来后填满。 +- 批次进行中出现自己输入时,从当前位置开新段,改为到底部;即使阅读手势已取消自动目标,也由新输入接管。只有批次正在运行或已排定时才接受到底部请求;批次结束后仍在用 CSS 过渡收起的行,不接管自己的输入,交给普通跟随。 +- 读者的滚动手势会取消「到底部」的自动目标,保留读者位置。「读者内容不动」时,帧间读者自己的滚动会并入批次保持的位置。 +- 「读者内容不动」时,驱动器对有序的顶层行二分查找,选取视口里第一行不属于本批次的可见顶层行作为参照。批次开始和收起行提交 hidden 时,相邻行的间距会瞬间改变;驱动器在这两处测量参照行的位移,抵消到 scrollTop 上。 +- 「到底部」且需要向前滚过视口顶部以下的收起行时,这些行保持不透明、随内容滚动,在收缩中裁剪显示,嵌套的收起行在批次结束前保持原尺寸。其余收起行原地淡出。新的到底部请求接管运行中的批次时,会把仍在视口顶部以下的收起行加入随行;已经淡出的行会以剩余高度重新变为不透明。这样向前滚动不会穿过一片已经透明、还没收完的空位。 + +### 自己输入的判定 + +| 来源 | 判定 | 落点 | +|---|---|---| +| 主会话输入框空闲发送 | 对话流回显 | 到底部 | +| 子会话输入框空闲发送 | 子会话同样注册本地回显;`subagents.prompt` 使用回显的 `requestId` | 到底部 | +| 运行中排队、上一轮结束后自动投递 | 不是自己输入 | 跟随底部时到底部,否则内容不动 | +| 另一个标签页发送 | 不是自己输入 | 同上 | +| 父 agent 给子会话发消息 | 通知不开启交互段,不折叠 | — | + +「完成时收起」不在动画作用域内,折叠立即生效,不受影响。 + +## Testing + +[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) 覆盖主会话 19 例与右侧栏子会话 8 例,维度包括读者位置(底部、正文中段、正文开头、步骤中间、上一轮)、输入来源(输入框、回合在写入消息前失败、另一个标签页、排队投递、steer、父消息、一次折叠多轮)、正文长短,以及 Standard 与「完成时收起」对照。布局空洞指视口顶部到输入框之间没有任何可见行的盒子覆盖的最大连续高度:落定后不超过 120 px,动画中至多 1 帧超过。它按盒子计算,已经淡出但尚未收完的收起行仍算作覆盖。「到底部」的用例断言落到底部;「内容不动」的用例断言读者锚定行的屏幕位置变化不超过 2 px。正文很短的用例只断言回复到达后不再留空。 + +## Alternatives considered + +**保留通用路径,只修自己输入的识别。** 两条路径的几何规则继续分叉;非自己输入时,中段读者要么被拉到底部,要么仍然看到空白。 + +**通用路径改为按读者位置补偿,但与输入路径分开实现。** 补偿与补白的几何代码重复一份,两边容易再次不一致。 + +**用开启交互段的人类输入节点识别自己输入,子会话不补回显。** 另一个标签页的输入会被当成自己输入,把中段读者拉到底部;子会话发送后仍然不能立即看到自己的消息。 + +**允许内容回滑,以填满短正文留下的差额。** 同一次动画里内容先上后下。 + +## Consequences + +- 收益:整屏空白的来源(通用路径)不再存在;落点只看「是不是自己的输入」和「读者是否在跟随」,与消息从哪个页面、何时投递无关。子会话发送立即显示自己的消息。 +- 代价:正文很短时,「内容只上不下」仍会留出差额,直到新内容填满。 +- 焦点停在正在收起的行里时,焦点保护会让该行保持展开。若它是被封顶高度的过程组,正文会立即缩到封顶高度。这次缩小发生在批次开始之前,「读者内容不动」的落点测不到,读者内容会移动一次。 diff --git a/.agents/notes/implemented/architecture/2026-10-13-context-breakdown-system-prompt-state.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-context-breakdown-system-prompt-state.i18n.yaml new file mode 100644 index 0000000000..a5dc5cf3f9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-13-context-breakdown-system-prompt-state.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-13-context-breakdown-system-prompt-state.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-13-context-breakdown-system-prompt-state.md +/agent-note-context-breakdown-retains-only-system-prompts: + en: 9b155f87202e037e + zh: 8d4190c00412b892 +/agent-note-context-breakdown-retains-only-system-prompts/problem: + en: 7cbbdfbe7da9ae7a + zh: 50368b272d7b5ebc +/agent-note-context-breakdown-retains-only-system-prompts/decision: + en: 52d5c42112c5c6dc + zh: 744dbbcc52193300 +/agent-note-context-breakdown-retains-only-system-prompts/verification: + en: 68a7375ca7fe99e8 + zh: e3c7d108740e8952 +/agent-note-context-breakdown-retains-only-system-prompts/alternatives-considered: + en: 2bd0e83c5298da2b + zh: 336259b6985eb7b5 +/agent-note-context-breakdown-retains-only-system-prompts/consequences: + en: 839a919ff16bc53c + zh: bf0d4f3a783ead1d diff --git a/.agents/notes/implemented/architecture/2026-10-13-context-breakdown-system-prompt-state.md b/.agents/notes/implemented/architecture/2026-10-13-context-breakdown-system-prompt-state.md new file mode 100644 index 0000000000..7d4e69bd0f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-13-context-breakdown-system-prompt-state.md @@ -0,0 +1,36 @@ +# Agent Note: Context breakdown retains only system prompts + +Status: implemented + +English | [中文](2026-10-13-context-breakdown-system-prompt-state.zh.md) + +## Problem + +`contextBreakdown` kept one `{ seq, heuristicTokens, system }` entry per retained surface node so that any replacement could subtract the exact price of its range and re-select the last nonempty system prompt. Its checkpoint therefore grew with the number of messages in the model context. In a local corpus of 836 Sessions, 151,122 entries made the unit's rows 7.13 MB of the projection cache and up to 103 KB for one Session, and every cached Session listing validated all of them. Long tool-heavy runs below the compaction threshold kept about 2,000 entries each. + +## Decision + +[`breakdown-projection.ts`](../../../../packages/llm/token-meter/src/breakdown-projection.ts) retains the surviving `system/message` nodes in surface order with their heuristic prices, one running surface total, and at most one armed shadow-price claim. State version 6 discards version-5 rows; other projection keys keep their rows. + +- An append adds its price; a `system/message` append also joins the end of the system list. +- `compaction/summary` and `compaction/prune` arm a claim from `shadowedRange`, `shadowedTokenCount`, and the retained system prompts named by `shadowedSeqs`. The next event consumes or expires it. A replacement over the claimed range subtracts the claim price and drops those prompts; a replacement naming another range, or putting a `system/message` in place of a metered range, throws. +- An unmetered replacement of one retained system prompt subtracts that prompt's own price. A `system/message` replacement keeps its position; any other replacement removes it. +- Any other unmetered replacement folds at zero delta, the rule `contextPressure` already applies. + +`systemTokens` is the last retained prompt with a positive price, and `messageTokens` is the surface total minus it; both are floored at zero. `shadowedSeqs` is the authoritative set of shadowed nodes, so membership decides which prompts leave without locating non-system endpoints in surface order. + +## Verification + +Folding all 836 stored logs with the version-5 and version-6 definitions produced identical breakdowns after every event. The logs held 2,206 metered replacements, 106 system-prompt rewrites, and no other replacement. Retained state fell from 7.13 MB to 110 KB, with at most five surviving system prompts in one Session. + +## Alternatives considered + +**Keep per-node entries with a faster validator.** A hand-written node check cut listing validation from 75 ms to 4.5 ms but kept 7.13 MB of rows, an O(surface) array copy per surface event, and checkpoint writes proportional to the message count. + +**Columnar per-node entries.** Parallel arrays shrink rows about 5.7 times but keep O(surface) state for information the shadow-price events already carry. + +**Exact pricing of unmetered non-system replacements.** That requires per-node prices. Current producers meter every non-system replacement, and released formats from v0 carry the shadow-price fields, so the remaining case is a log that breaks producer adjacency; it drifts like `contextPressure`. + +## Consequences + +Checkpoint size and per-event cost follow the number of surviving system prompts rather than messages, and cached listings no longer validate per-message entries. The figures stay exact for metered replacements and system-prompt rewrites, and their sum equals the `measure()` heuristic total under those producers. An unmetered non-system replacement leaves the figures off by that replacement's price difference. A future range replacement that inserts a system prompt is rejected until the fold can order it among the retained prompts. This supersedes the positional-entry choice for this unit in the [in-history system-prompt replacement](../feature/2026-09-02-in-history-system-prompt-replacement.md) note; `measure()` keeps positional nodes for route pricing. diff --git a/.agents/notes/implemented/architecture/2026-10-13-context-breakdown-system-prompt-state.zh.md b/.agents/notes/implemented/architecture/2026-10-13-context-breakdown-system-prompt-state.zh.md new file mode 100644 index 0000000000..bab33f441d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-13-context-breakdown-system-prompt-state.zh.md @@ -0,0 +1,36 @@ +# Agent Note: 上下文构成只保留系统提示词 + +Status: implemented + +[English](2026-10-13-context-breakdown-system-prompt-state.md) | 中文 + +## Problem + +`contextBreakdown` 曾为每个保留的 surface 节点存一条 `{ seq, heuristicTokens, system }`,以便任意替换都能减去其范围的精确价格,并重新选出最后一个非空系统提示词。因此它的检查点随模型上下文中的消息数增长。在一个包含 836 个 Session 的本地语料中,151,122 条条目让该单元的行占用 projection cache 的 7.13 MB,单个 Session 最多 103 KB,而每次缓存会话列表都要校验全部条目。低于压缩阈值、工具调用密集的长时间运行各自保留约 2,000 条条目。 + +## Decision + +[`breakdown-projection.ts`](../../../../packages/llm/token-meter/src/breakdown-projection.ts) 按 surface 顺序保留存活的 `system/message` 节点及其启发式价格、一个 surface 运行总量,以及至多一个已武装的影子价 claim。状态版本 6 丢弃版本 5 的行;其他 projection key 保留各自的行。 + +- 追加加上其价格;`system/message` 追加还会加入系统列表末尾。 +- `compaction/summary` 和 `compaction/prune` 依据 `shadowedRange`、`shadowedTokenCount` 以及 `shadowedSeqs` 中列出的已保留系统提示词武装 claim。下一个事件消费或使其失效。覆盖所 claim 范围的替换减去 claim 价格并移除这些提示词;指向其他范围的替换,或以 `system/message` 取代已计量范围的替换,会抛出错误。 +- 对单个已保留系统提示词的未计量替换减去该提示词自身的价格。`system/message` 替换保持其位置;其他替换将其移除。 +- 其他未计量替换以零增量折叠,这与 `contextPressure` 已采用的规则相同。 + +`systemTokens` 是最后一个价格为正的保留提示词,`messageTokens` 是 surface 总量减去它;两者都不低于零。`shadowedSeqs` 是被遮蔽节点的权威集合,因此由成员关系决定哪些提示词离开,无需在 surface 顺序中定位非系统端点。 + +## Verification + +用版本 5 和版本 6 的定义折叠全部 836 份已存日志,每个事件之后的构成数字都完全相同。这些日志包含 2,206 次已计量替换、106 次系统提示词改写,没有其他替换。保留状态从 7.13 MB 降到 110 KB,单个 Session 最多有五个存活的系统提示词。 + +## Alternatives considered + +**保留逐节点条目,换用更快的校验器。** 手写节点检查把列表校验从 75 ms 降到 4.5 ms,但仍保留 7.13 MB 的行、每个 surface 事件一次 O(surface) 数组复制,以及与消息数成正比的检查点写入。 + +**列式逐节点条目。** 并行数组让行缩小约 5.7 倍,但仍为影子价事件已经携带的信息保留 O(surface) 状态。 + +**精确定价未计量的非系统替换。** 这需要逐节点价格。当前生产方会计量每一次非系统替换,自 v0 起的已发布格式都携带影子价字段,因此剩余情况只是破坏生产方相邻性的日志;它像 `contextPressure` 一样产生偏差。 + +## Consequences + +检查点大小和每个事件的成本取决于存活系统提示词的数量而不是消息数,缓存列表也不再校验逐消息条目。对已计量替换和系统提示词改写,数字保持精确,其和在这些生产方下等于 `measure()` 的启发式总量。未计量的非系统替换会让数字偏离该替换的价格差。未来插入系统提示词的范围替换会被拒绝,直到折叠能确定它在已保留提示词中的顺序。这取代了 [历史内系统提示词替换](../feature/2026-09-02-in-history-system-prompt-replacement.zh.md) 说明中针对该单元的位置条目选择;`measure()` 仍为路由定价保留位置节点。 diff --git a/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.i18n.yaml new file mode 100644 index 0000000000..65205260c3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-13-team-identity-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/architecture/2026-10-13-team-identity-runtime-context.md +/agent-note-team-identity-in-required-runtime-context: + en: 8c88759320ae8481 + zh: 4068b18723907eb9 +/agent-note-team-identity-in-required-runtime-context/problem: + en: c9a81cb731ddf7b2 + zh: 428c0e6f8937d7c5 +/agent-note-team-identity-in-required-runtime-context/decision: + en: 6c73479973c1e378 + zh: 98677c77f77f8d81 +/agent-note-team-identity-in-required-runtime-context/alternatives-considered: + en: 774566ffbf9e9db8 + zh: ea761d876af462f2 +/agent-note-team-identity-in-required-runtime-context/consequences: + en: 18d1aa67936f1227 + zh: 7e06c1f51553ecdd diff --git a/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.md b/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.md new file mode 100644 index 0000000000..39794f02d3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.md @@ -0,0 +1,31 @@ +# Agent Note: Team identity in required runtime context + +Status: implemented + +English | [中文](2026-10-13-team-identity-runtime-context.zh.md) + +## Problem + +A teammate identity embedded in its initial task depends on ordinary history retention. Compaction can remove it, and an ordinary fork from that teammate can retain the old role even though the fork is an independent Lead. Identity must reflect current membership while keeping shared system instructions uniform. + +## Decision + +`tool-agent-team` contributes `team:identity` through the Agent-scoped `systemPrompt.context()` registry with `required: true`. Its provider reads the existing Team membership and renders the member's role, name, and addressing instructions. Optional-context suppression cannot remove it. Fixed collaboration policy stays in the system prompt; roster and task state remain tool queries. Initial tasks contain only their supplied content. + +The loop owns logging, retained-snapshot comparison, and re-admission after compaction. A changed role appends the current full runtime-context snapshot after inherited history; unchanged retained context adds no message. No Team-specific retention state, event type, or log migration is introduced. Existing recorded reminders remain historical messages. + +This supersedes only the initial-task identity decision in [Agent Teams](../feature/2026-08-05-agent-teams.md#team-identity); its roster, mailbox, and task decisions remain active. + +## Alternatives considered + +**Keep identity in the initial task.** Preserves a uniform system prompt but cannot restore removed identity or correct a fork's inherited role without another mechanism. + +**Put identity in the system prompt.** Makes system text differ across members and can rewrite the inherited request prefix on routes without in-history system updates. + +**Add custom reminder retention and reinjection.** Duplicates the loop's existing runtime-context projection and recovery responsibilities. + +## Consequences + +Members pay for identity within the full runtime-context snapshot. Other context changes repeat it, while stable retained context adds no new message. Forks preserve inherited history and append current identity; actual provider cache hits remain best-effort. Existing Team authorization remains in tool execution. + +Verification covers fresh and fork teammates, an independent fork from a teammate, optional-context suppression, compaction restoration, cold resume, and registration disposal. The recorded `team-targets` scenario pins Lead context; the keyless headless Team workflow pins teammate context through the shipped profile. diff --git a/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.zh.md b/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.zh.md new file mode 100644 index 0000000000..d0e333a71e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 必需 runtime context 中的 Team 身份 + +Status: implemented + +[English](2026-10-13-team-identity-runtime-context.md) | 中文 + +## Problem + +嵌入初始任务的 teammate 身份依赖普通历史保留。压缩可能移除它;从 teammate 创建的普通 fork 即使已成为独立 Lead,也可能保留旧角色。身份必须反映当前 membership,同时保持共享系统指令一致。 + +## Decision + +`tool-agent-team` 通过 Agent 作用域的 `systemPrompt.context()` 注册 `team:identity`,并设置 `required: true`。提供方读取现有 Team membership,渲染成员角色、名字与寻址说明。关闭可选 context 不能移除它。固定协作策略保留在 system prompt;roster 和 task 状态仍通过工具查询。初始任务只包含传入的正文。 + +Loop 负责日志记录、保留快照比较和压缩后的重新接纳。角色变化会在继承历史之后追加当前完整 runtime-context 快照;保留的 context 未变化时不追加消息。不引入 Team 专属的保留状态、事件类型或日志迁移。已有身份提醒仍作为历史消息保留。 + +本决策仅取代 [Agent Teams](../feature/2026-08-05-agent-teams.zh.md#team-identity) 中的初始任务身份决策;其 roster、mailbox 和 task 决策仍然有效。 + +## Alternatives considered + +**身份留在初始任务中。** 保持 system prompt 一致,但恢复被移除的身份或纠正 fork 继承的角色需要额外机制。 + +**身份放进 system prompt。** 成员之间的 system 文本会不同;不支持历史内 system 更新的路由可能重写继承的请求前缀。 + +**添加自定义提醒保留与重新注入。** 重复了 loop 已有的 runtime-context 投影和恢复职责。 + +## Consequences + +成员承担完整 runtime-context 快照中的身份 token 成本。其他 context 变化会重复身份,保留的 context 稳定时则不追加消息。Fork 保留继承历史并追加当前身份;提供方实际缓存命中仍为尽力而为。现有 Team 授权仍在工具执行时落实。 + +验证覆盖 fresh 和 fork teammate、从 teammate 创建的独立 fork、关闭可选 context、压缩后恢复、冷恢复和注册释放。录制的 `team-targets` 场景固定 Lead context;无密钥 headless Team 工作流通过内置 profile 固定 teammate context。 diff --git a/.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.i18n.yaml new file mode 100644 index 0000000000..1fe1553059 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-09-15-authenticated-browser-host-preferences.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-15-authenticated-browser-host-preferences.md +/agent-note-share-host-preferences-with-every-authenticated-browser: + en: f4b8b4500f8dca9c + zh: bf27ded54fba703b +/agent-note-share-host-preferences-with-every-authenticated-browser/problem: + en: 22bf57b616581253 + zh: d1108a4042646e21 +/agent-note-share-host-preferences-with-every-authenticated-browser/decision: + en: 2d54784b8b3558cf + zh: 31190a9b284867b7 +/agent-note-share-host-preferences-with-every-authenticated-browser/alternatives-considered: + en: 299105745b084fc0 + zh: 8c2d82de44ac2aad +/agent-note-share-host-preferences-with-every-authenticated-browser/consequences: + en: 520028b8c4031009 + zh: 8c130624261538cc +/agent-note-share-host-preferences-with-every-authenticated-browser/testing: + en: e433f139fe72e69f + zh: 279cc8b1cd3d5377 diff --git a/.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.md b/.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.md new file mode 100644 index 0000000000..120903b88d --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.md @@ -0,0 +1,29 @@ +# Agent Note: Share Host preferences with every authenticated browser + +Status: implemented + +English | [中文](2026-09-15-authenticated-browser-host-preferences.zh.md) + +## Problem + +[Persist Web user preferences through Host settings](../../archived/bug-fix/2026-08-06-host-backed-web-preferences.md) chose the preference store by page locality, so a non-loopback page kept Appearance, Language, busy-Enter, and the welcome acknowledgement in a process-local copy. A trusted remote host, and a deployment published behind the configured public URL, therefore lost every choice on reload even though Connection authenticates the complete settings API. The second mode also split the shared runtime: theme, locale, the settings shell, the Models page, and the welcome notice each rendered a durable row that could never persist for a remote page. + +## Decision + +Locality selects nothing. One `settings.describe` mirror, one `ctx.configForms.get(entryId)` per namespace derived from it, and the `settings.mutate` write path serve every authenticated browser. Browser token authentication of the Connection API is the identity boundary; the fixed `remote.$host` locality facts are request-routing evidence that no store selector consults. The mirror's state space is `idle`, `loading`, and `ready`, a form snapshot carries no mode, and a form reports `unavailable` only for a namespace the Host did not register. + +The settings shell keeps one locality-dependent UI element: it builds its document controller from `ctx.remote.$host.isLoopback`, so only a loopback page renders **Open configuration file** and issues the `hasDocument` read behind it. The `settings/openSettingsDocument` Remote itself stays browser-authenticated like every other Host method; the omission is a presentation choice for pages that cannot see the Host's native editor, not a persistence rule. + +## Alternatives considered + +**Keep the memory-branch locality gate.** Rejected: browser token authentication already covers every Host method for remote pages, so the gate protected nothing, and locality is request-routing evidence rather than identity. It also made every Host-backed row inert on trusted remote and public deployments. + +## Consequences + +Every authenticated browser reaching one Host shares one preference document. Two browsers on the same deployment observe each other's Appearance, Language, busy-Enter, and welcome-acknowledgement choices, and a value written remotely is the value a loopback browser loads next. Preference access is governed by API authentication and `settings.describe.writable`. + +A remote page omits the **Open configuration file** action, the one locality-dependent UI element that remains. Concurrent writers on one document resolve through the namespace revision each form sends as `expectedRevision`. + +## Testing + +Focused unit coverage pins the contract: the ui-settings mirror and configuration-form suites construct both objects with no persistence selector, the theme apply spec persists from a non-loopback bench and asserts the Host write, the ui-settings-general apply spec keeps the shared describe read and the Host write path off-loopback while asserting the native document action stays unregistered, and the welcome store retains its acknowledgement across a settings-plugin recreation. The keyless Web settings scenario `apps/web/tests/remote-settings.e2e.ts` acknowledges the welcome notice, configures a model provider, and selects the dark Appearance from a trusted remote page, reloads after each, and re-asserts the welcome, model, and Appearance state from the Host settings document. diff --git a/.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.zh.md b/.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.zh.md new file mode 100644 index 0000000000..10aa7af847 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.zh.md @@ -0,0 +1,29 @@ +# Agent Note: 每个已认证浏览器共用 Host 偏好 + +Status: implemented + +[English](2026-09-15-authenticated-browser-host-preferences.md) | 中文 + +## 问题 + +[通过 Host settings 持久化 Web 用户偏好](../../archived/bug-fix/2026-08-06-host-backed-web-preferences.md)按页面本地性选择偏好存储,因此非回环页面把 Appearance、Language、繁忙态 Enter 与欢迎提示的确认留在一份进程内副本中。可信远程主机,以及配置了公共 URL 的部署,因而在重新加载时丢失全部选择,尽管 Connection 认证完整的 settings API。这套第二种模式也割裂了共享运行时:主题、语言、设置外壳、Models 页面与欢迎提示各自都在渲染一行对远程页面永远无法持久化的界面。 + +## 决策 + +本地性不选择任何东西。一个 `settings.describe` 镜像、由它派生的逐 namespace `ctx.configForms.get(entryId)`,以及 `settings.mutate` 写入路径服务每个已认证浏览器。Connection API 的浏览器令牌认证是身份边界;固定的 `remote.$host` 本地性事实只是请求路由的依据,没有任何存储选择器会读取它。镜像的状态空间只有 `idle`、`loading` 与 `ready`,表单快照不携带 mode,表单也只有在 Host 未注册该 namespace 时才报告 `unavailable`。 + +settings 外壳保留唯一一个依赖本地性的 UI 元素:它依据 `ctx.remote.$host.isLoopback` 构造文档控制器,因此只有回环页面会渲染**打开配置文件**并发出其背后的 `hasDocument` 读取。`settings/openSettingsDocument` Remote 本身与其他 Host 方法一样保持浏览器认证;省略该操作是面向看不到 Host 原生编辑器的页面的展示选择,而非持久化规则。 + +## 曾考虑的替代方案 + +**保留内存分支的本地性门禁。** 已否决:浏览器令牌认证已覆盖远程页面的每个 Host 方法,该门禁保护不了任何东西,而本地性只是请求路由的依据而非身份。它还会让受信远程与公共部署上每一行依赖 Host 的界面失效。 + +## 后果 + +每个访问同一 Host 的已认证浏览器共用一份偏好文档。同一部署上的两个浏览器会看到彼此选择的 Appearance、Language、繁忙态 Enter 与欢迎提示确认,远程写入的值就是回环浏览器下一次加载的值。偏好可访问性由 API 认证与 `settings.describe.writable` 决定。 + +远程页面省略**打开配置文件**操作,这是仍依赖本地性的唯一 UI 元素。同一文档上的并发写入由各表单作为 `expectedRevision` 发送的 namespace revision 裁决。 + +## 测试 + +聚焦的单元测试固定当前契约:ui-settings 的镜像与配置表单测试在构造这两个对象时不传持久化选择器,主题 apply 测试从非回环 bench 持久化并断言 Host 写入,ui-settings-general 的 apply 测试在非回环下保留共享 describe 读取与 Host 写入路径、同时断言原生文档操作保持未注册,欢迎 store 则在 settings 插件重建后保留其确认。无密钥 Web settings 场景 `apps/web/tests/remote-settings.e2e.ts` 从可信远程页面确认欢迎通知、配置一个模型提供商并选择深色 Appearance,每步之后重新加载,并从 Host settings 文档重新确认欢迎提示、模型与 Appearance 状态。 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-09-30-job-session-lifecycle.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-30-job-session-lifecycle.i18n.yaml new file mode 100644 index 0000000000..a46ef9740b --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-30-job-session-lifecycle.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-09-30-job-session-lifecycle.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-30-job-session-lifecycle.md +/agent-note-persist-owned-job-lifecycle-facts: + en: 79d83b765acf6e24 + zh: afe6ea9af6d96d10 +/agent-note-persist-owned-job-lifecycle-facts/problem: + en: b3d0591cc559e466 + zh: aa4c385e84f7eaa1 +/agent-note-persist-owned-job-lifecycle-facts/decision: + en: c982a59cbe5202d3 + zh: 9315962d2e4b8f0a +/agent-note-persist-owned-job-lifecycle-facts/alternatives-considered: + en: 140cf7152a35bb27 + zh: 001aa96687836914 +/agent-note-persist-owned-job-lifecycle-facts/consequences: + en: 3761af53744aa0c7 + zh: 876cb056c248c43c diff --git a/.agents/notes/implemented/bug-fix/2026-09-30-job-session-lifecycle.md b/.agents/notes/implemented/bug-fix/2026-09-30-job-session-lifecycle.md new file mode 100644 index 0000000000..0edf7deeef --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-30-job-session-lifecycle.md @@ -0,0 +1,37 @@ +# Agent Note: Persist owned job lifecycle facts + +Status: implemented + +English | [中文](2026-09-30-job-session-lifecycle.zh.md) + +## Problem + +SDK consumers receive Session events, while job registration and settlement previously existed only in the live registry. A background tool can return before work finishes, and output collection can happen much later or never. Tool invocation times therefore cannot reconstruct a job's execution interval. Runtime-local ids also repeat after a registry restart. + +## Decision + +The local provider captures `job/registered` and `job/settled` facts for owned jobs, retaining the registry's epoch-millisecond timestamps, original owner, producer kind, label, and optional creating tool call. A UUID-backed `JobId` identifies both live controls and historical records across registry restarts and copied history. Unowned work has no Session journal. + +The terminal record distinguishes a producer report from forced bookkeeping: `producerReported` is true when `JobHooks.done` fulfills, and false when that promise rejects or teardown cancellation throws. It reports fulfillment, not independently confirmed resource release. Missing terminal records remain incomplete and are not reconstructed from later reads or process restart. + +Facts are appended synchronously at the registry commit before live hub reactions and completion waiters resume. Recording errors warn independently: already-started work still has its control id, and a failed journal append cannot prevent cleanup or release of waiters. The Session's ordinary persistence and SDK notification paths own delivery after append. SDK `run()` results cover bounded observation windows and can receive a settlement whose registration belongs to an earlier run; settlement records retain the registration facts for that consumer. + +The [registry contract](../../../../packages/jobs/jobs/README.md) and [seam consolidation note](../architecture/2026-09-03-jobs-seam-consolidation.md) own live execution, resource ownership, and event routing. This journal adds durable observations without replacing those responsibilities. + +## Alternatives considered + +**Add timestamps only to `job_output`.** A model may never collect a job or may collect it after a long delay. Logging lifecycle commits records both cases without additional model calls or consuming output. + +**Keep a reusable control id alongside an execution UUID.** Both values would identify one job. A unique `JobId` serves live controls and historical pairing. + +**Add a launcher cleanup registry.** A separate pre-exit disposer path duplicates Cordis resource ownership and adds a launcher requirement to headless. Keeping persistence available through the final job teardown requires a separate cross-fiber lifecycle change; this journal retains the existing disposal mechanism. + +**Defer publication or propagate recording errors.** Deferral lets a synchronous hub subscriber journal a completion notice before the settlement that caused it. Throwing after the starter succeeds can hide an already-running job from its caller. Synchronous, contained recording preserves causal order without abandoning execution. + +## Consequences + +Application teardown can stop Session routing or close its writer before the final job settlement reaches storage. Normal one-shot completion and signal shutdown can therefore leave incomplete history, as can hard process loss. This change does not enforce cross-fiber disposal order or synthesize a missing terminal record. + +The log and both SDKs expose execution intervals without changing tool schemas, output cursors, or job scheduling. Model-facing controls and notices carry the unique JobId; a bounded notice points to job_list when the full id cannot fit. These intervals run from registration commit through registry settlement, including the producer work and cleanup between those points; they are neither CPU time nor a directly additive rollout-latency metric. An append failure can also leave incomplete history. Persisted facts do not resume an external process or its output ring. + +Focused tests cover original timestamps, nested call identity, output preservation, delayed cancellation, producer rejection, forced teardown, late completion, unique control ids, causal publication order, and recording-failure containment. SDK snapshots cover the durable and protocol projections. diff --git a/.agents/notes/implemented/bug-fix/2026-09-30-job-session-lifecycle.zh.md b/.agents/notes/implemented/bug-fix/2026-09-30-job-session-lifecycle.zh.md new file mode 100644 index 0000000000..25cd83d922 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-30-job-session-lifecycle.zh.md @@ -0,0 +1,37 @@ +# Agent Note: 持久化有所有者 job 的生命周期事实 + +Status: implemented + +[English](2026-09-30-job-session-lifecycle.md) | 中文 + +## Problem + +SDK 消费方接收 Session 事件,而 job 注册和结算此前只存在于运行期注册表中。后台工具可能在工作结束前返回,输出收集则可能晚得多,甚至永远不发生。因此工具调用时间无法重建 job 的执行区间。运行期 id 也会在注册表重启后重复。 + +## Decision + +本地提供方为有所有者的 job 捕获 `job/registered` 与 `job/settled` 事实,保留注册表的 Unix 毫秒时间戳、原始所有者、生产方 kind、label 和可选的创建工具调用。由 UUID 构成的 `JobId` 在注册表重启和历史复制后同时标识运行中的控制对象和历史记录。无主工作没有 Session 日志。 + +终态记录区分生产方报告与强制记账:`producerReported` 在 `JobHooks.done` 兑现时为 true,在该 promise 拒绝或销毁取消抛错时为 false。它记录兑现情况,不独立确认资源已释放。缺少终态记录时保持不完整,不根据较晚的读取或进程重启重建。 + +事实在注册表提交时同步追加,先于运行期 hub 的反应和完成等待方恢复。记录错误单独发出警告:已启动的工作仍有可控制的 id,日志追加失败不能阻止清理或释放等待方。追加后的投递由 Session 既有的持久化和 SDK 通知路径负责。SDK `run()` 结果只覆盖有界观察窗口,可能收到注册属于更早运行的结算;结算记录为这个消费方保留注册事实。 + +[注册表约定](../../../../packages/jobs/jobs/README.zh.md)和[seam 收敛说明](../architecture/2026-09-03-jobs-seam-consolidation.zh.md)负责运行期执行、资源归属和事件路由。本日志增加持久化观测,不替代这些职责。 + +## Alternatives considered + +**仅向 `job_output` 添加时间戳。** 模型可能永远不收集某个 job,也可能很晚才收集。记录生命周期提交能覆盖这两种情况,无需额外模型调用或消费输出。 + +**保留可重用的控制 id,另设执行 UUID。** 两个值会标识同一个 job。唯一的 `JobId` 同时服务运行期控制和历史配对。 + +**增加启动器清理注册表。** 独立的退出前 disposer 路径会重复 Cordis 的资源归属机制,并增加 headless 对启动器的要求。让持久化持续可用直至最后一个 job 销毁,需要单独修改跨 fiber 生命周期;本日志保留既有销毁机制。 + +**延后发布或传播记录错误。** 延后发布让同步 hub 订阅者可能先记录完成通知、后记录产生通知的结算事实。starter 成功后抛错可能使调用方拿不到已运行 job 的 id。同步并隔离记录错误既保留因果顺序,也不会放弃执行。 + +## Consequences + +应用销毁可能在最后一条 job 结算写入存储前停止 Session 路由或关闭写句柄。因此正常的一次性运行结束、信号关停和进程硬退出都可能留下不完整历史。本次变更不强制跨 fiber 的销毁顺序,也不虚构缺失的终态记录。 + +日志与两种 SDK 暴露执行区间,不改变工具 schema、输出游标或 job 调度。模型侧控制和通知使用唯一的 JobId;有界通知无法容纳完整 id 时指向 job_list。区间从注册提交延续到注册表结算,包含这两个时刻之间的生产方工作与清理;它既不是 CPU 时间,也不是可直接相加的 rollout 延迟指标。追加失败也可能留下不完整历史。持久化事实不会恢复外部进程或其输出环。 + +定向测试覆盖原始时间戳、嵌套调用标识、输出保留、延后取消、生产方拒绝、强制销毁、较晚完成、唯一控制 id、因果发布顺序,以及记录错误隔离。SDK 快照覆盖持久化与协议投影。 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/feature/2026-07-12-subagent-persona-tool-filter-and-depth.i18n.yaml b/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.i18n.yaml index 431d5f60ec..529c16087a 100644 --- a/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.i18n.yaml @@ -9,29 +9,29 @@ en: 311bc04b9c36ab53 zh: 0c52e6493e9350a5 /agent-note-configure-subagent-persona-tool-visibility-and-depth/decision: - en: 79b3fcfaaaaccf9e - zh: 0287bfb41c7b9707 + en: 45111f900708aaf9 + zh: e75bed4951516963 /agent-note-configure-subagent-persona-tool-visibility-and-depth/decision/persona-is-a-scoped-shadow: - en: 8b299c99d26aa5c3 - zh: 6956efbd236cef8e + en: f9ee31a1fdcdd38f + zh: c9d05721cef80659 /agent-note-configure-subagent-persona-tool-visibility-and-depth/decision/tool-filtering-is-one-live-global-view-rule: en: a9fe46283ea28722 zh: 7b7d1be7c070b893 /agent-note-configure-subagent-persona-tool-visibility-and-depth/decision/depth-is-an-absolute-tree-cap: - en: 9145bec4e3f7eb5b - zh: 986276925cb064d9 + en: c1d92ec60342c8b7 + zh: 063c9eaba331312b /agent-note-configure-subagent-persona-tool-visibility-and-depth/decision/capability-gating-keeps-providers-honest: - en: 5334afafefdb0f59 - zh: 7e96c9a08bbc3d1a + en: 1669c3372b728fc8 + zh: 349ee461c9307811 /agent-note-configure-subagent-persona-tool-visibility-and-depth/decision/unpublished-setup-makes-the-first-request-correct: - en: 3c988dfff07c8da3 - zh: 8ce2fbcc438e7dd8 + en: 32b0648b901c49ad + zh: b72f29a8be987479 /agent-note-configure-subagent-persona-tool-visibility-and-depth/visibility-is-not-authority: en: d0db5310a87ff8e4 zh: 4b9f502238cd4bae /agent-note-configure-subagent-persona-tool-visibility-and-depth/alternatives-considered: - en: 78ae41331d8fcc3e - zh: a93ee10b3e30c267 + en: cf5006aa2b345a37 + zh: f26a9a1ab9a83a46 /agent-note-configure-subagent-persona-tool-visibility-and-depth/consequences: - en: d5f05d63b7a01dd8 - zh: f0be1e88b06d8cc9 + en: 58a53e46a6ce8307 + zh: 6e552d8b6ff4b186 diff --git a/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md b/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md index f848b92a7a..fabcb81393 100644 --- a/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md +++ b/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.md @@ -12,7 +12,7 @@ These controls affect the child's first model request and therefore cannot be in ## Decision -Subagent starts have three independent composition controls: `persona`, `toolFilter`, and `maxDepth`. A provider advertises support for each control, the service rejects unsupported requests before starting a run, and an in-process provider installs the requested composition while the child is still unpublished. +This note retains the depth policy and the persona/tool-filter semantics needed to restore historical child descriptors. New children use [preset-owned composition](../simplification/2026-10-09-preset-owned-subagent-composition.md); new requests do not accept persona or tool filters. Historical overrides are applied while a resumed child is unpublished. The controls answer different questions: @@ -22,16 +22,18 @@ The controls answer different questions: | `toolFilter` | Which deployment-global tools enter this child's visible tool view? | A scoped restriction filters globals before child-local tools are added | | `maxDepth` | How deep may this delegation tree grow? | A start whose child depth exceeds the absolute cap is rejected | -`dsh-tool-subagent` exposes the controls as plugin configuration and copies them into each request it creates. Direct `SubagentRuntime` callers may choose them per request. The provider capability descriptor remains the source of truth for whether a backend can honor each field. +`dsh-tool-subagent` and direct `SubagentRuntime` callers expose `maxDepth`. Its provider capability determines whether a backend can enforce the cap. Persona and tool-filter values come only from historical descriptors during cold resume. ### Persona is a scoped shadow -The persona control changes one child without changing deployment-wide prompt assembly. During unpublished setup, an in-process provider registers a child-scoped section named `deployment:persona-prefix`; ordinary most-specific-wins resolution replaces the global section only in that child's assemblies. +A historical persona changes one resumed child without changing deployment-wide prompt assembly. During unpublished setup, the manager registers a child-scoped section named `deployment:persona-prefix`; ordinary most-specific-wins resolution replaces the inherited section only in that child’s assemblies. -The value has the same strict template semantics as the deployment persona. Omitting it inherits the deployment section through the global layer; an explicit empty string shadows the global persona with an empty section. Parent and sibling personas never enter the child's flat scope. +The value has the same strict template semantics as the deployment persona. Omitting it preserves the composed persona; an explicit empty string shadows that persona with an empty section. This uses the normal system-prompt registration mechanism rather than a second persona channel. The first prompt therefore sees the same named contribution that later prompts and prompt-inspection tools see. + + ### Tool filtering is one live global-view rule The tool filter controls capability visibility and executable lookup together. An in-process provider installs `ToolRuntime.restrict()` in the child's scope before publication, and the registry's single resolver applies the same result to wire tool schemas, lookup, execution, and PTC mode SDK generation. Independently registered system-prompt sections remain owned by their plugins. The filesystem, search, and web tool plugins use the existing `PromptSection.text({ scope })` callback and `ctx.tools.get(name, scope)` to omit guidance for unavailable tools and select applicable cross-tool text. This keeps the original wording and ordering for a supported tool set and works for any agent scope, including underlying PTC capabilities whose wire presentation is `run_code`. It adds no section-ownership metadata or assembly pass; unrelated static prose is not automatically rewritten by `restrict()`. @@ -53,19 +55,19 @@ The depth limit bounds recursive delegation independently of tool visibility. A The effective parent depth is the greater of durable `SessionHeader.delegationDepth` and runtime `AgentOptions.subagentDepth`. An in-process child records its derived depth in the session header, and resume restores that header, so a restart cannot lower the recursion count. -Every public entry validates the domain rather than relying on one model-facing configuration path. Negative values, fractions, negative zero, non-finite values, unsafe integers, malformed stored parent depth, and derived overflow all reject. A direct `SubagentStartRequest` may omit the cap to leave depth unbounded; loader-resolved `dsh-tool-subagent` configuration instead defaults to `3`, accepts a numeric override, and uses explicit `'provider-managed'` to omit the cap for an out-of-process provider whose deployment owns its recursion budget. Three is a small finite default that still permits a root plus three descendant generations, and the [base profile](../../../../packages/bundle/base/cordis.patch.yml) uses that general policy. A numeric tool cap fails at provider mount when the provider lacks `depthLimit`. +Every public entry validates the domain rather than relying on one model-facing configuration path. Negative values, fractions, negative zero, non-finite values, unsafe integers, malformed stored parent depth, and derived overflow all reject. A direct `SubagentStartRequest` may omit the cap to leave depth unbounded; `dsh-tool-subagent` instead reads the live Host depth setting (initially `1`), accepts a numeric override, and uses explicit `'provider-managed'` to omit the cap for an out-of-process provider whose deployment owns its recursion budget. The [base profile](../../../../packages/bundle/base/cordis.patch.yml) uses the Host setting. A numeric tool cap fails at provider mount when the provider lacks `depthLimit`. -A deployment can combine depth and filtering, but the numeric cap does not synthesize a filter. The delegation tool stays visible at the cap because authorization may depend on runtime state; every attempted start checks the calling agent's current durable and runtime depth, and a rejected start returns an errored tool result without publishing a child. A deployment may separately deny delegation tools in children when its visibility policy is static. Neither choice changes the provider's conversation-history behavior. +The numeric cap does not synthesize a filter. The delegation tool stays visible at the cap because authorization may depend on runtime state; every attempted start checks the calling agent’s current durable and runtime depth, and a rejected start returns an errored tool result without publishing a child. A preset can omit delegation tool plugins independently of the depth policy. At the cap, the tool contributes an optional runtime-context notice telling the model to work directly. `includeRuntimeContext: false` suppresses this advisory notice; the runtime depth guard remains active. When enabled, the notice reads the live cap and durable depth at request time to keep resumed and reconfigured agents informed without changing their system prompt or tool schemas; unchanged context is not repeatedly appended. ### Capability gating keeps providers honest -Capabilities separate a requested feature from a provider implementation. `SubagentCapabilities` advertises `persona`, `toolFilter`, and `depthLimit`; `SubagentRuntime.start()` checks every present request field against those flags before calling the provider. +Capabilities separate a requested feature from a provider implementation. `SubagentCapabilities.depthLimit` advertises depth enforcement; `SubagentRuntime.startActivation()` checks a requested cap before calling the provider. This lets spawn and fork providers share the in-process implementation while external providers advertise only what they can enforce. A request never degrades silently: selecting an unsupported control produces `UNSUPPORTED_CAPABILITY`, and no run or lifecycle event exists. ### Unpublished setup makes the first request correct -All child-local composition is complete before the child becomes observable. The in-process provider supplies one setup callback to agent creation; that callback installs persona, tool restriction, and structured-output contributions in the child's scope. Only after setup succeeds does creation publish the session and agent and allow the driver to start. +All child-local composition is complete before the child becomes observable. The manager supplies a setup callback to agent creation that composes the preset, restores historical persona and tool restrictions on cold resume, and installs structured output. Only after setup succeeds does creation publish the session and agent and allow the driver to start. A setup failure rolls back the private child. No observer can acquire a child whose first prompt used the deployment persona or unfiltered tool set and whose later prompts use the requested configuration. @@ -79,7 +81,7 @@ A security design would need a separate authority representation, propagation ru ## Alternatives considered -**Create one provider per persona or tool set.** This multiplies providers that share the same transport and lifecycle implementation, makes dynamic deployment configuration awkward, and still needs a recursion mechanism. Providers remain about execution transport; requests carry per-child composition. +**Create one provider per persona or tool set.** This multiplies providers that share the same transport and lifecycle implementation and still needs a recursion mechanism. Providers remain about execution transport; presets own new child composition, while descriptors retain historical overrides. **Copy the parent's complete tool view.** Registration scope is flat by design, and lifetime ownership does not imply visibility inheritance. Copying a resolved view would also freeze dynamic global registrations and conflate composition with authority without defining either contract fully. @@ -91,6 +93,6 @@ A security design would need a separate authority representation, propagation ru ## Consequences -Contributors can configure child role, visible global tools, and recursion without defining new providers. Capability checks fail before ownership starts, unpublished setup makes the first request consistent, and one tool resolver prevents presentation/execution drift. +Historical child composition survives cold resume without defining new providers. Capability checks fail before ownership starts, unpublished setup makes the first request consistent, and one tool resolver prevents presentation/execution drift. The cost is that deployments must understand live allow/deny behavior and the distinction between visibility and authority. A model may call a visible delegation tool after the current depth policy forbids another child and receive an error. Provider authors must advertise each supported control accurately, and in-process providers must install every requested contribution before publication. The controls deliberately do not solve security confinement or parent-to-child non-escalation. diff --git a/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.zh.md b/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.zh.md index 3360b27c9f..8993d0dc73 100644 --- a/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.zh.md +++ b/.agents/notes/implemented/feature/2026-07-12-subagent-persona-tool-filter-and-depth.zh.md @@ -12,7 +12,7 @@ Status: implemented ## 决策 -subagent 启动有三个独立的组合控制:`persona`、`toolFilter` 和 `maxDepth`。提供方声明对每个控制的支持情况,服务在启动运行之前拒绝不受支持的请求,进程内提供方在子 agent 尚未发布时安装所请求的组合。 +本记录保留深度策略,以及恢复历史子级 descriptor 所需的 persona/工具过滤语义。新子级使用 [preset 拥有的组装](../simplification/2026-10-09-preset-owned-subagent-composition.zh.md);新请求不接受 persona 或工具过滤。历史覆盖在恢复的子级尚未发布时应用。 这些控制回答不同的问题: @@ -22,13 +22,13 @@ subagent 启动有三个独立的组合控制:`persona`、`toolFilter` 和 `ma | `toolFilter` | 部署全局工具中哪些进入该子 agent 的可见工具视图? | 一个有作用域的限制在添加子 agent 局部工具之前过滤全局工具 | | `maxDepth` | 这棵委派树最深可以长到多少层? | 子 agent 深度超过绝对上限时,启动请求被拒绝 | -`dsh-tool-subagent` 将这些控制作为插件配置暴露,并复制到它创建的每个请求中。直接调用 `SubagentRuntime` 的调用方可以按请求选择这些控制。提供方的能力描述符仍然是后端能否兑现各字段的真源。 +`dsh-tool-subagent` 和直接调用 `SubagentRuntime` 的调用方公开 `maxDepth`。对应的提供方能力决定后端是否能强制执行上限。persona 和工具过滤值仅在冷恢复时来自历史 descriptor。 ### 人设是有作用域的遮蔽 -人设控制改变一个子 agent 的行为,而不改变部署级的提示词组装。在未发布的设置阶段,进程内提供方在子 agent 作用域中注册一个名为 `deployment:persona-prefix` 的段落;普通的最具体者优先解析规则仅在该子 agent 的组装中替换全局段落。 +历史 persona 改变一个恢复子级的行为,而不改变部署级提示词组装。在未发布的设置阶段,管理器注册子级作用域中名为 `deployment:persona-prefix` 的段落;普通的最具体者优先解析规则只在该子级的组装中替换继承段落。 -其值与部署人设具有相同的严格模板语义。省略时通过全局层继承部署段落;显式空字符串则以空段落遮蔽全局人设。父级和兄弟级的人设永远不会进入子 agent 的扁平作用域。 +该值与部署 persona 具有相同的严格模板语义。省略时保留组装的 persona;显式空字符串则以空段落遮蔽该 persona。 这使用的是常规的系统提示词注册机制,而非第二条人设通道。因此第一次提示词看到的命名贡献与后续提示词和提示词检查工具看到的一致。 @@ -55,19 +55,19 @@ subagent 启动有三个独立的组合控制:`persona`、`toolFilter` 和 `ma 有效父级深度取持久 `SessionHeader.delegationDepth` 与运行时 `AgentOptions.subagentDepth` 中的较大值。进程内子 agent 把推导出的深度记录在会话 header 中,恢复时会重新载入该 header,因此重启无法降低递归计数。 -每个公开入口都自行验证值域,而非依赖单一的面向模型配置路径。负值、小数、负零、非有限值、不安全整数、格式错误的存储父级深度以及推导溢出均被拒绝。直接的 `SubagentStartRequest` 可以省略上限,让此机制不约束深度;经 loader 解析的 `dsh-tool-subagent` 配置则默认值为 `3`、接受数值覆盖,并使用显式的 `'provider-managed'` 来省略由进程外提供方部署拥有递归预算时的上限。三是一个较小的有限默认值,仍允许 root 加三代后代,[base profile](../../../../packages/bundle/base/cordis.patch.yml)采用这项通用策略。提供方缺少 `depthLimit` 时,数值工具上限会在提供方挂载阶段失败。 +每个公开入口都自行验证值域,而非依赖单一的面向模型配置路径。负值、小数、负零、非有限值、不安全整数、格式错误的存储父级深度以及推导溢出均被拒绝。直接的 `SubagentStartRequest` 可以省略上限,让此机制不约束深度;`dsh-tool-subagent` 则读取实时 Host 深度设置(初始值为 `1`)、接受数值覆盖,并使用显式的 `'provider-managed'` 来省略由进程外提供方部署拥有递归预算时的上限。[base profile](../../../../packages/bundle/base/cordis.patch.yml)采用 Host 设置。提供方缺少 `depthLimit` 时,数值工具上限会在提供方挂载阶段失败。 -部署可以组合深度与过滤,但数值上限不会合成过滤器。委派工具在上限处仍然可见,因为授权可能依赖运行时状态;每次尝试启动都会检查调用方 agent 当前的持久与运行时深度,被拒绝的启动返回错误工具结果,且不发布子 agent。可见性策略固定的部署可以另外在子 agent 中 deny 委派工具。两种选择都不改变提供方的对话历史行为。 +数值上限不会合成过滤器。委派工具在上限处仍然可见,因为授权可能依赖运行时状态;每次尝试启动都会检查调用方 agent 当前的持久与运行时深度,被拒绝的启动返回错误工具结果,且不发布子 agent。preset 可独立于深度策略省略委派工具插件。达到上限时,工具贡献一条可选的运行时上下文提示,让模型直接完成工作。`includeRuntimeContext: false` 会抑制这条建议性提示;运行时的深度拦截仍然生效。提示启用时,每次请求读取实时上限与持久深度,使恢复会话或调整配置后的 agent 获知当前限制,同时不改变其系统提示词或工具 schema;未变化的上下文不会重复追加。 ### 能力门控保持提供方诚实 -能力将请求的功能与提供方实现分离。`SubagentCapabilities` 声明 `persona`、`toolFilter` 和 `depthLimit`;`SubagentRuntime.start()` 在调用提供方之前,对照这些标志检查请求中每个存在的字段。 +能力将请求的功能与提供方实现分离。`SubagentCapabilities.depthLimit` 声明深度强制执行能力;`SubagentRuntime.startActivation()` 在调用提供方前检查请求的上限。 这使 spawn 和 fork 提供方可以共享进程内实现,而外部提供方只声明自己能强制执行的部分。请求永远不会静默降级:选择不受支持的控制会产生 `UNSUPPORTED_CAPABILITY`,不会有运行或生命周期事件存在。 ### 未发布设置使第一次请求正确 -所有子 agent 局部的组合在子 agent 变得可观察之前完成。进程内提供方向 agent 创建提供一个设置回调;该回调在子 agent 作用域中安装人设、工具限制和结构化输出贡献。只有设置成功后,创建才发布会话和 agent 并允许驱动器启动。 +所有子级局部组装均在子级可观察前完成。管理器向 agent 创建提供设置回调,组装 preset,在冷恢复时恢复历史 persona 和工具限制,并安装结构化输出。只有设置成功后才发布会话和 agent,并允许驱动器启动。 设置失败会回滚私有子 agent。没有观察者能获取到一个「第一次提示词使用了部署人设或未过滤工具集、后续提示词才使用所请求配置」的子 agent。 @@ -81,7 +81,7 @@ subagent 启动有三个独立的组合控制:`persona`、`toolFilter` 和 `ma ## 曾考虑的替代方案 -**为每种人设或工具集创建一个提供方。** 这会使共享相同传输和生命周期实现的提供方成倍增加,使动态部署配置变得笨拙,且仍需要递归机制。提供方的职责是执行传输;请求承载每个子 agent 的组合。 +**为每种 persona 或工具集创建一个提供方。** 这会使共享同一传输和生命周期实现的提供方成倍增加,且仍需要递归机制。提供方负责执行传输;preset 拥有新子级组装,descriptor 保留历史覆盖。 **复制父级的完整工具视图。** 注册作用域设计上是扁平的,生命周期所有权不意味着可见性继承。复制已解析视图还会冻结动态全局注册,并在未完整定义任一约定的情况下混淆组合与授权。 @@ -93,6 +93,6 @@ subagent 启动有三个独立的组合控制:`persona`、`toolFilter` 和 `ma ## 后果 -贡献者可以配置子 agent 的角色、可见全局工具和递归深度,而无需定义新的提供方。能力检查在所有权开始之前失败,未发布设置使第一次请求一致,单一工具解析器防止呈现/执行漂移。 +历史子级组装在冷恢复后保留,无需定义新的提供方。能力检查在所有权开始前失败,未发布设置使第一次请求一致,单一工具解析器防止呈现与执行不一致。 代价是部署方必须理解活跃的 allow/deny 行为以及可见性与授权的区别。当前深度策略禁止再创建子 agent 后,模型仍可能调用可见的委派工具并收到错误。提供方作者必须准确声明每个受支持的控制,进程内提供方必须在发布前安装所有请求的贡献。这些控制有意不解决安全隔离或父到子的非升权问题。 diff --git a/.agents/notes/implemented/feature/2026-08-05-agent-teams.i18n.yaml b/.agents/notes/implemented/feature/2026-08-05-agent-teams.i18n.yaml index a38c0852ba..3ef2bd6bfb 100644 --- a/.agents/notes/implemented/feature/2026-08-05-agent-teams.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-05-agent-teams.i18n.yaml @@ -12,17 +12,17 @@ en: 95e7d723d6b00930 zh: d18fdf9b2bf69bdb /agent-note-durable-agent-teams-over-continuable-children/profile-delegation: - en: 3a66308576f74247 - zh: 3453f0bcce88033d + en: 4835fb8c0c0d8a0d + zh: 5f9438a0d58104c4 /agent-note-durable-agent-teams-over-continuable-children/team-identity: - en: 83e446c928a20c47 - zh: b0a2bd24419dd815 + en: f82812d6ac0ac78d + zh: 7dd80a6ad13674ca /agent-note-durable-agent-teams-over-continuable-children/provisioning-and-recovery: - en: 085846d0078c0898 - zh: 40b2ca3ae6864451 + en: 4345ac9a6ac7ad04 + zh: 1d19ecbb128a75a3 /agent-note-durable-agent-teams-over-continuable-children/mailbox-and-task-transactions: - en: ab2ad55021eb34e0 - zh: 2d1996df7a69201d + en: bfc3063536837c0e + zh: 6b8e69ba85cc2bb1 /agent-note-durable-agent-teams-over-continuable-children/shared-checkout-boundary: en: 34920da68b5763e0 zh: 7604392594e4b8a8 @@ -30,11 +30,11 @@ en: e6348054f024725b zh: 8740636e99940308 /agent-note-durable-agent-teams-over-continuable-children/alternatives-considered: - en: bb266fe7a97f0828 - zh: 7c86c2d6d11ba02a + en: 8cb2fd8839f5f8b7 + zh: e302ca03e569de65 /agent-note-durable-agent-teams-over-continuable-children/testing: - en: 35ce199351d8b63d - zh: 332f0520e27e3309 + en: 092ac3c2b6f552aa + zh: c688c1bec5ad8a07 /agent-note-durable-agent-teams-over-continuable-children/consequences: - en: c3740ae56809e537 - zh: 76a1e77d14cb6f26 + en: da9cd22b1185a793 + zh: e20d7ef9226f237f diff --git a/.agents/notes/implemented/feature/2026-08-05-agent-teams.md b/.agents/notes/implemented/feature/2026-08-05-agent-teams.md index 74556d041f..82864e2552 100644 --- a/.agents/notes/implemented/feature/2026-08-05-agent-teams.md +++ b/.agents/notes/implemented/feature/2026-08-05-agent-teams.md @@ -22,15 +22,15 @@ The Lead must wait for required work before its final answer. Process teardown r ## Profile delegation -The [Team profile](../../../../packages/experimental/agent-team-profile/README.md) disables `subagent` and `subagent_fork` together with the overlapping global controls. Direct model delegation uses `spawn_teammate` with fresh or fork context, keeping those children in the durable roster. Workflow remains available through the base profile’s fresh `spawn` provider for scripted orchestration; it cannot inherit a teammate’s conversation identity through the model tool. The Subagent services and providers remain shared infrastructure. Ordinary Session forks retain their history without identity correction. Provider-owned child tool visibility remains a [documented limitation](../../../../packages/experimental/tool-agent-team/README.md#known-limitations-and-deferred-work). +The [Team profile](../../../../packages/experimental/agent-team-profile/README.md) disables `subagent` and `subagent_fork` together with the overlapping global controls. Direct model delegation uses `spawn_teammate` with fresh or fork context, keeping those children in the durable roster. Workflow remains available through the base profile’s fresh `spawn` provider for scripted orchestration; it cannot inherit a teammate’s conversation identity through the model tool. The Subagent services and providers remain shared infrastructure. Ordinary Session forks retain their history; [current identity handling](../architecture/2026-10-13-team-identity-runtime-context.md) supplies the fork’s own role. ## Team identity -The `spawn_teammate` tool prefixes the initial task with a user-role `` stating `You are teammate "".`. Identity and task enter the same durable inbox message. Shared system policy and all tool schemas stay uniform across members; execution owns role restrictions. Team tools resolve the caller’s Team and accept member names, so the model needs no Team id. Identity follows ordinary history through cold recovery and compaction; the plugin does not inspect reminder retention or add replacement messages. Forks inherit the recorded text without a Lead identity correction. Putting identity in the system prompt changes the prefix before inherited history; keeping it in the initial task preserves that prefix without per-step identity bookkeeping. Existing system-embedded identities may require a one-time prompt reconciliation; retained event generations are unchanged. +Shared system policy and all tool schemas stay uniform across members; execution owns role restrictions. Team tools resolve the caller’s Team and accept member names, so the model needs no Team id. [Required runtime-context identity](../architecture/2026-10-13-team-identity-runtime-context.md) owns identity injection, retention, and fork handling. ## Provisioning and recovery -Creation first appends and flushes a `team/member` provisioning snapshot in the Lead Session, then starts the reserved continuable child through the selected fresh or fork provider. Failure before initial inbox acceptance appends a failed snapshot. Success flushes the child's accepted inbox item before appending active. Recovery recognizes that initial message while it is still pending or after it enters user-message history. Names are reserved by the first provisioning record and never reused, including after failure. Disposal closes admission, aborts and awaits admitted creation and mailbox-dispatch transactions, then stops every live child recorded by the roster; a failed child remains cleanup-owned until its Activation exits, and cleanup rejection fails disposal. +Creation first appends and flushes a `team/member` provisioning snapshot in the Lead Session, then starts the reserved continuable child through the selected fresh or fork provider. Failure before initial inbox acceptance appends a failed snapshot. Success flushes the child's accepted inbox item before appending active. Recovery recognizes that initial message while it is still pending or after it enters user-message history. Names are reserved by the first provisioning record and never reused, including after failure. Disposal closes admission, aborts and awaits admitted creation and send operations, then stops every live child recorded by the roster; a failed child remains cleanup-owned until its Activation exits, and cleanup rejection fails disposal. A root recovery reconciles an unterminated provisioning record against the child's independently persisted Session. Matching direct-parent and continuable descriptors plus a recorded initial user message prove successful admission and produce active; absence, corruption, mismatched provider/lineage, or a missing admitted message produces failed. The creator re-reads the terminal phase under the same Lead-log serializer; if recovery marked failed while creation succeeded, it drains the child and reports a provisioning conflict instead of retaining an orphan. This avoids reconstructing an initial prompt that was never retained in the Team log and contains plugin-reload races. @@ -38,11 +38,11 @@ Fresh children have no inherited conversation. Fork children capture the Lead's ## Mailbox and task transactions -Peer communication is a Lead-log mailbox. `team/message/queued` is appended and flushed before delivery. The target message carries the stable message id and sender identity in both durable source metadata and a short model-visible prefix. A target receipt is acknowledged with `team/message/delivered` only after its pending inbox item or recorded user message is flushed. Immediate admission is serialized per target in queued-log order, recovery retries queued-minus-delivered in the same order, and delivery folds live or persisted target inbox/history state before cold resume. Every current-version Team payload is runtime-validated before entering replay state. The Team runtime tracks dispatch and asynchronous acknowledgement work from synchronous admission until settlement; disposal closes admission and awaits both before removing the service. Current waiters wake only after the owning Team event flush succeeds. +The historical Lead-log mailbox remains a readable format: queued and delivered records keep their stable identity and sender, and Team payload validation still applies to them. Team no longer delivers or acknowledges them; new sends follow the [direct inbox decision](../simplification/2026-09-26-team-direct-inbox.md). Unknown mailbox content stays as decoded JSON during event projection and checkpoint admission. Validation inspects its type without rebuilding its fields, because generic object parsing can omit a valid own `__proto__` key. Locally declared content variants undergo structural validation; opaque plugin fields do not gain Team semantics. Cache invalidation is necessary because parser correction alone cannot recover keys omitted from cached state. The [Team documentation](../../../../packages/experimental/agent-team/README.md) owns the restore behavior. -`send_message` always attempts Steer delivery. A running target receives the message at the nearest step boundary; an inactive target starts a turn if loaded or cold-resumes otherwise. Success means the message is already durable even when temporary delivery failure leaves it queued. The mechanism provides process-local retry and target-Session de-duplication, not a cross-process exactly-once claim. The [Team Steer messaging decision](../../archived/simplification/2026-08-30-team-send-message-steer.md) owns the single-tool scheduling rationale. +`send_message` uses Steer for running, idle, and cold targets. New sends return inbox acceptance. The [Team Steer messaging decision](../../archived/simplification/2026-08-30-team-send-message-steer.md) records the single-tool scheduling rationale. Shared tasks are complete snapshots with Team-local ids and monotonic revisions. Every mutation carries `expectedRevision`. Any member creates, reads, or claims a ready unowned task; the owner or Lead edits and transitions it, while only the Lead assigns another member. Numeric task ids remain within the safe-integer allocation range, and exhaustion fails without reusing an id. Dependencies must name non-deleted tasks and form a complete DAG. Deleted tasks are retained tombstones. `writeScopes` are normalized path prefixes that produce overlap diagnostics but never block claim or authorize a write. @@ -74,20 +74,20 @@ Publication requires `apply` to return a new state object per applied Team event **Enable Teams in the default catalog.** Rejected because scoped Team controls would shadow same-named legacy globals and unsolicited delegation would add latency and token cost to simple tasks. An opt-in profile bundle inserts Team and disables the legacy controls without adding Team packages to shipped dependency graphs. -**Use an in-memory board and mailbox.** Rejected because child settlement, HMR, and process interruption would lose accepted coordination state and make retries ambiguous. +**Use an in-memory board and mailbox.** Roster and task state must survive settlement, HMR, and interruption. Historical mailbox records stay readable; message ownership follows the target inbox. **Return Team tool results as untyped JSON.** Rejected because an undeclared result type lets `execute` drift from the value the model is promised without a compiler error, and it invites indentation that costs tokens on every roster, task, and receipt. Each Team tool therefore declares its complete result schema and one shared helper renders it compactly. ## Testing -Package tests cover identity, name and authority checks, provider selection, reserved-id persistence collisions, child-before-Lead flush ordering, durable provisioning failure and pending-inbox JSONL reconciliation, concurrent target-local ordering, pending/history de-duplication, mailbox limits, post-flush notification, bounded disposal with in-flight creation and dispatch cancellation, failed-member cleanup, task CAS and DAG validation, write-scope warnings, wait cancellation/timeout, inbox-preserving interruption, ordinary-fork isolation, legacy-control shadowing, compact declared-schema result rendering, and scoped registration HMR at per-file 100% coverage. A keyless product snapshot loads the Agent Teams profile bundle through `dsh --profile headless` and pins its complete model-visible tool list, Team policy, and durable workflow projection for two teammates, dependent tasks, peer delivery, waiting, completion, and aggregation. A CLI e2e reuses the same deterministic adapter and verifies normal process exit with persisted Team and child logs. +Package tests cover Team authority, provisioning durability, task transitions, direct inbox acceptance, sender attribution, lifecycle cancellation, and historical mailbox readability. The keyless Team profile snapshot pins the policy, tools, and workflow; the CLI composition test checks persisted Team and child logs. Model-facing member identities and availability follow the [tool projection reference](../../../../packages/experimental/tool-agent-team/README.md); service residency and durable identity remain distinct. ## Consequences -The Lead Session grows with whole task/member snapshots and mailbox acknowledgements. This favors independently inspectable recovery over compact deltas; configured task and pending-mail bounds cap active state, while deleted and delivered history remains append-only until broader Session retention applies. +The Lead Session retains whole task/member snapshots and historical mailbox records. This favors inspectable recovery over compact deltas; deleted and delivered history remains append-only until broader Session retention applies. -An active roster member can be non-resident, so `inactive` is not failure and a send can incur cold-resume latency. Temporary inspection, resume, or inbox-admission failure can leave a durable message queued for recovery. A failed member permanently consumes its name and member slot, making provisioning failures visible instead of silently recycling identity. +An active roster member can be non-resident, so `inactive` is not failure and sends can incur cold-resume latency. Admission failures reject new sends. Historical pending mail is never delivered. Failed provisioning permanently consumes its name and member slot. Coordination reduces likely checkout conflicts but cannot eliminate writes outside filesystem compare-and-set tools. The final diff and tests remain the Lead's integration boundary. diff --git a/.agents/notes/implemented/feature/2026-08-05-agent-teams.zh.md b/.agents/notes/implemented/feature/2026-08-05-agent-teams.zh.md index d7c2bd7d7e..7a292f2d7e 100644 --- a/.agents/notes/implemented/feature/2026-08-05-agent-teams.zh.md +++ b/.agents/notes/implemented/feature/2026-08-05-agent-teams.zh.md @@ -22,15 +22,15 @@ Lead 必须等待所需工作后才能给出最终答案。进程 teardown 仍 ## Profile delegation -[Team profile](../../../../packages/experimental/agent-team-profile/README.zh.md) 禁用 `subagent`、`subagent_fork` 以及名称重叠的全局控件。模型直接委派使用支持 fresh 或 fork 上下文的 `spawn_teammate`,使这些子代理进入持久 roster。Workflow 仍通过 base profile 的 fresh `spawn` 提供方执行脚本编排;经模型工具创建的 workflow 子代理不会继承 teammate 的对话身份。Subagent 服务和提供方仍是共享基础设施。普通 Session fork 保留历史,不纠正身份。提供方所拥有的子代理工具可见性仍是[已记录的限制](../../../../packages/experimental/tool-agent-team/README.zh.md#known-limitations-and-deferred-work)。 +[Team profile](../../../../packages/experimental/agent-team-profile/README.zh.md) 禁用 `subagent`、`subagent_fork` 以及名称重叠的全局控件。模型直接委派使用支持 fresh 或 fork 上下文的 `spawn_teammate`,使这些子代理进入持久 roster。Workflow 仍通过 base profile 的 fresh `spawn` 提供方执行脚本编排;经模型工具创建的 workflow 子代理不会继承 teammate 的对话身份。Subagent 服务和提供方仍是共享基础设施。普通 Session fork 保留历史;[当前身份处理](../architecture/2026-10-13-team-identity-runtime-context.zh.md)提供 fork 自己的角色。 ## Team identity -工具 `spawn_teammate` 在初始任务前加上 user-role ``,声明 `You are teammate "".`。身份和任务进入同一条持久化收件箱消息。共享 system 策略和全部工具 schema 在成员间保持一致;执行时检查角色权限。Team 工具根据调用者确定 Team,并接受成员名字,因此模型不需要 Team id。身份随普通历史经历冷恢复和压缩;插件不检查提醒是否保留,也不添加替代消息。fork 继承已记录文本,不补发 Lead 身份修正。把身份放进 system prompt 会在继承历史之前改变前缀;把它留在初始任务中既保留此前缀,也无需每步维护身份提醒。已有的 system 内嵌身份可能需要一次提示词协调;保留的事件格式代际保持不变。 +共享 system 策略和全部工具 schema 在成员间保持一致;执行时检查角色权限。Team 工具根据调用者确定 Team,并接受成员名字,因此模型不需要 Team id。[必需 runtime-context 身份](../architecture/2026-10-13-team-identity-runtime-context.zh.md)负责身份注入、保留与 fork 处理。 ## Provisioning and recovery -创建操作先在 Lead Session 中追加并 flush `team/member` provisioning 快照,再通过选定 fresh 或 fork provider 启动预留的 continuable child。初始 inbox 获准前的失败会追加 failed 快照;成功会先 flush child 中已接受的 inbox 条目,再追加 active。恢复会在初始消息仍处于 pending 或已进入用户消息历史时识别它。名字由第一条 provisioning 记录永久保留,包括失败后也不能复用。dispose 会关闭准入,中止并等待已获准的创建与 mailbox dispatch 事务,再停止 roster 记录的所有 live child;failed child 在 Activation 退出前仍由 cleanup 拥有,cleanup 拒绝会让 dispose 失败。 +创建操作先在 Lead Session 中追加并 flush `team/member` provisioning 快照,再通过选定 fresh 或 fork provider 启动预留的 continuable child。初始 inbox 获准前的失败会追加 failed 快照;成功会先 flush child 中已接受的 inbox 条目,再追加 active。恢复会在初始消息仍处于 pending 或已进入用户消息历史时识别它。名字由第一条 provisioning 记录永久保留,包括失败后也不能复用。dispose 会关闭准入,中止并等待已获准的创建与发送操作,再停止 roster 记录的所有 live child;failed child 在 Activation 退出前仍由 cleanup 拥有,cleanup 拒绝会让 dispose 失败。 Root 恢复时会把未终结 provisioning 记录与独立持久 child Session 对账。直接 parent 与 continuable descriptor 匹配,并且已经记录初始用户消息,才能证明准入成功并转为 active;缺失、损坏、provider/lineage 不匹配或缺少已准入消息都会转为 failed。creator 会在同一 Lead 日志 serializer 内重读终态;如果 recovery 在创建成功时先标记 failed,creator 会 drain child 并报告 provisioning conflict,而不是遗留孤儿。这样既无需重建从未保存在 Team 日志中的初始 prompt,也能约束插件 reload 竞争。 @@ -38,11 +38,11 @@ fresh child 不继承对话。fork child 只捕获一次 Lead 已完成 turn 前 ## Mailbox and task transactions -Peer 通讯使用 Lead 日志 mailbox。投递前先追加并 flush `team/message/queued`。target message 会在持久 source metadata 与短模型可见前缀中同时携带稳定 message id 和 sender identity。只有 pending inbox 条目或已记录用户消息完成 flush,Lead 日志才写入 `team/message/delivered` acknowledgement。即时准入按 target 和 queued 日志顺序串行化,恢复按同一顺序重试 queued-minus-delivered,并在冷恢复前折叠 live 或 persisted target 的 inbox/历史状态。每个当前版本 Team payload 都会经过运行时验证后才进入 replay state。Team runtime 从同步准入到 settlement 全程跟踪 dispatch 与异步 acknowledgement 工作;dispose 会关闭准入,并在移除服务前等待两者。当前 waiter 只在所属 Team event flush 成功后被唤醒。 +历史 Lead-log mailbox 仍是可读格式:queued 与 delivered 记录保留稳定身份与发送者,Team payload 校验仍适用于它们。Team 不再投递或确认这些记录;新发送遵循[直接 inbox 决策](../simplification/2026-09-26-team-direct-inbox.zh.md)。 事件投影和 checkpoint 准入期间,未知 mailbox 内容保持为已解码 JSON。校验只检查其 type,不重建字段,因为通用对象解析可能省略有效的自有 `__proto__` 键。本地声明的内容变体接受结构校验;不透明的插件字段不获得 Team 语义。缓存失效是必要的,因为只修正解析器无法恢复缓存状态中省略的键。[Team 文档](../../../../packages/experimental/agent-team/README.zh.md)拥有恢复行为的说明。 -`send_message` 始终尝试 Steer 投递。running target 在最近的步骤边界收到消息,inactive target 在已加载时启动一个轮次,否则冷恢复。即使临时投递失败让消息保持 queued,成功也表示消息已经持久化。该机制提供进程内重试与 target Session 去重,不宣称跨进程 exactly-once。[Team Steer 消息决策](../../archived/simplification/2026-08-30-team-send-message-steer.md)负责单工具调度的理由。 +`send_message` 对 running、idle 和 cold target 使用 Steer。新发送返回 inbox 接收结果。[Team Steer 消息决策](../../archived/simplification/2026-08-30-team-send-message-steer.md)记录单一工具调度的理由。 共享 task 是带 Team-local id 与单调 revision 的完整快照。每次变更都携带 `expectedRevision`。任意 member 可以创建、读取或 claim ready 且无 owner 的任务;Owner 或 Lead 可以编辑和转换;只有 Lead 可以分配给另一个 member。数字 task id 保持在安全整数分配范围内;该范围耗尽时会失败,不会复用 id。依赖必须指向未删除任务,并形成完整 DAG。删除任务保留为 tombstone。`writeScopes` 是规范化路径前缀,只产生重叠诊断,绝不会阻止 claim 或授予写权限。 @@ -74,20 +74,20 @@ Web panel 读取 Lead Session 的 `agentTeam` 传输投影,因为现有投影 **在默认工具目录中启用 Team。** 拒绝,因为 scoped Team control 会覆盖同名旧全局工具,主动 delegation 也会给简单任务增加延迟和 token 成本。opt-in profile bundle 会插入 Team 并禁用旧 control,同时不向随附依赖图添加 Team 包。 -**使用内存 task board 与 mailbox。** 拒绝,因为 child settlement、HMR 与进程中断会丢失已接受协调状态,并让重试变得含糊。 +**使用内存 board 与 mailbox。** roster 与任务状态必须经受 settlement、HMR 与中断。历史 mailbox 记录保持可读;消息归属目标 inbox。 **让 Team 工具返回未类型化 JSON。** 拒绝,因为未声明的结果类型会让 `execute` 在没有编译错误的情况下偏离对模型的承诺,也会引入在每份 roster、task 与回执上都消耗 token 的缩进。因此每个 Team 工具都声明完整的结果 schema,并由一个共享 helper 紧凑渲染。 ## Testing -Package test 以逐文件 100% coverage 覆盖身份、名字与权限检查、provider 选择、预留 id 持久化冲突、child-before-Lead flush 顺序、持久 provisioning 失败与 pending-inbox JSONL 对账、target-local 并发顺序、pending/history 去重、mailbox 限额、flush 后 notification、取消在途创建与 dispatch 的有界 dispose、failed member cleanup、task CAS 与 DAG 校验、write-scope warning、wait cancel/timeout、保留 inbox 的 interrupt、普通 fork 隔离、旧 control shadowing、声明 schema 的紧凑结果渲染与 scoped registration HMR。一条 keyless 产品快照会通过 `dsh --profile headless` 加载 Agent Teams profile bundle,并为两个 teammate、依赖任务、peer 投递、等待、完成和汇总固定完整的面向模型工具列表、Team policy 与持久 workflow 投影。CLI e2e 会复用同一个确定性 adapter,并验证带持久 Team 与 child 日志的正常退出。 +包测试覆盖 Team 权限、provisioning 持久性、任务转换、直接 inbox 接收、发送者归属、生命周期取消和历史 mailbox 可读性。无密钥 Team profile 快照固定 policy、工具与工作流;CLI 组合测试检查持久 Team 和 child 日志。 模型可见的成员身份与可用状态遵循[工具投影说明](../../../../packages/experimental/tool-agent-team/README.zh.md);服务驻留状态和持久身份仍保持区分。 ## Consequences -Lead Session 会随着完整 task/member 快照与 mailbox acknowledgement 增长。该设计用可独立检查的恢复能力换取更紧凑的 delta;配置的 task 与 pending-mail 限额限制 active state,而 deleted 与 delivered 历史会保持 append-only,直到更广泛的 Session retention 生效。 +Lead Session 保留完整 task/member 快照和历史 mailbox 记录。这优先支持可检查的恢复,而不是紧凑增量;deleted 与 delivered 历史在更广泛的 Session 保留策略生效前仍只追加。 -active roster member 可以不驻留,因此 `inactive` 不表示失败,send 可能产生 cold-resume 延迟。临时 inspection、resume 或 inbox 准入失败可能留下持久 queued 消息等待恢复。failed member 会永久占用名字与 member slot,使 provisioning failure 保持可见而不是静默回收身份。 +active roster 成员可能不驻留,因此 `inactive` 不表示失败,发送可能产生冷恢复延迟。准入失败会拒绝新发送。历史 pending 邮件永远不会被投递。provisioning 失败永久占用其名称和成员槽位。 协调可以降低 checkout 冲突概率,但无法消除文件系统 CAS 工具之外的写入。最终 diff 与测试仍是 Lead 的集成边界。 diff --git a/.agents/notes/implemented/feature/2026-08-28-auto-review.i18n.yaml b/.agents/notes/implemented/feature/2026-08-28-auto-review.i18n.yaml index f985dfc4a3..787ac9d839 100644 --- a/.agents/notes/implemented/feature/2026-08-28-auto-review.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-28-auto-review.i18n.yaml @@ -21,8 +21,8 @@ en: 237018634b5f9dcf zh: cbc49d9c1b794065 /agent-note-experimental-auto-review-before-each-tool-call/decision/process-catalog-and-children: - en: 6ebe6f90241fd322 - zh: eafdebc5277e83a1 + en: 0042c645360c8361 + zh: 5dba39466d376559 /agent-note-experimental-auto-review-before-each-tool-call/alternatives-considered: en: fe97128ed05b9e43 zh: 4aaa344933fa89b4 diff --git a/.agents/notes/implemented/feature/2026-08-28-auto-review.md b/.agents/notes/implemented/feature/2026-08-28-auto-review.md index c19e780d01..ff54f9d927 100644 --- a/.agents/notes/implemented/feature/2026-08-28-auto-review.md +++ b/.agents/notes/implemented/feature/2026-08-28-auto-review.md @@ -58,7 +58,7 @@ A persisted Auto Session cannot publish when the complete integration is absent The permission owner publishes one complete process catalog through generated `permissionPresets` Remote methods; the BFF explicitly mounts it and forwards a payload-free invalidation event. One browser directory subscribes before reading and serves both pickers. Epoch and connection-generation checks publish only the winning complete result. A winning failure or connection reset clears the previous snapshot; only a later existing read, notification, or reset retries. Disposed or stale settlements cannot publish. Each catalog invalidation dismisses the slash picker and its pending confirmation through the command owner while preserving the draft, so a picker waiting on its own read keeps its failure and retry state; reopening loads the current catalog. Session projection carries current selection only, so catalog installation or removal writes no Session event or sequence. -Auto appears with a superscript `EXP` badge. Both visible current-session pickers require the experimental confirmation; explicit `/permission auto` is already consent. The composer uses the generic Menu's existing portal placement to stay within the viewport while keeping its 218–360px bounds. The slash popup keeps `min(220px, 100%)` with `max-width: 100%`, including when a narrow composer collapses its trigger. +Auto appears with an `EXP` badge in picker options; the selected composer control omits it. Both visible current-session pickers require the experimental confirmation; explicit `/permission auto` is already consent. The composer uses the generic Menu's existing portal placement to stay within the viewport while keeping its 218–360px bounds. The slash popup keeps `min(220px, 100%)` with `max-width: 100%`, including when a narrow composer collapses its trigger. The [delegation-time policy capture](../../../../packages/subagent/subagent/README.md) records Auto or Full access before the first await and appends that existing preset event after fork seeding and sandbox/approval overrides. One-shot and continuable creation share the rule; cold resume reads only the child log. Later parent switches do not alter that child, while a later child switch can win. Read Only and Workspace Write retain sandbox inheritance plus `approval: never` and may therefore remain `custom`. Auto children classify each call independently using the existing lineage and messages, without parent call metadata, delegation records, receipts, Header/descriptor additions, or a Session-format change. Out-of-process children retain their own permission systems after the parent delegation is allowed. diff --git a/.agents/notes/implemented/feature/2026-08-28-auto-review.zh.md b/.agents/notes/implemented/feature/2026-08-28-auto-review.zh.md index bd99839132..a77aec0259 100644 --- a/.agents/notes/implemented/feature/2026-08-28-auto-review.zh.md +++ b/.agents/notes/implemented/feature/2026-08-28-auto-review.zh.md @@ -58,7 +58,7 @@ Reviewer 可以输出 reasoning blocks,随后恰好一个 JSON text block 和 Permission owner 通过生成的 `permissionPresets` Remote 方法发布一份完整进程目录;BFF 显式挂载它,并转发无 payload 的失效事件。一个浏览器目录在读取前订阅,为两个选择器提供数据。Epoch 与 connection-generation 检查只发布胜出的完整结果。胜出读取失败或 connection reset 会清空旧快照;只有后续既有读取、通知或 reset 才重试。已 dispose 或陈旧的结算不能发布。每次目录失效都通过命令 owner 关闭 slash 选择器与待确认对话框,同时保留草稿,因此等待自身读取的选择器仍保留失败与重试状态;重新打开时加载当前目录。Session 投影只携带当前选择,因此目录安装或移除不写 Session 事件或序号。 -Auto 带右上标 `EXP`。两个可见当前会话选择器都要求实验确认;显式 `/permission auto` 已构成同意。Composer 使用通用 Menu 既有 portal 定位保持在视口内,同时保留 218–360px 边界。Slash popup 保留 `min(220px, 100%)` 与 `max-width: 100%`,窄 composer 将 trigger 折叠时也一样。 +Auto 在选择器选项中带 `EXP` 标记;选中后的 composer 控件不显示该标记。两个可见当前会话选择器都要求实验确认;显式 `/permission auto` 已构成同意。Composer 使用通用 Menu 既有 portal 定位保持在视口内,同时保留 218–360px 边界。Slash popup 保留 `min(220px, 100%)` 与 `max-width: 100%`,窄 composer 将 trigger 折叠时也一样。 [委派时权限捕获](../../../../packages/subagent/subagent/README.zh.md)在首次 await 前记录 Auto 或 Full access,并在 fork seed 与 sandbox/approval override 之后追加该既有 preset event。单次与可继续创建共用此规则;cold resume 只读取 child 日志。后续 parent 切换不改变该 child,后续 child 自己的切换仍可胜出。Read Only 与 Workspace Write 保留 sandbox 继承加 `approval: never`,因此可能保持 `custom`。Auto child 使用既有 lineage 与消息独立分类每次调用,不增加父 call metadata、委派记录、receipt、Header/descriptor 字段或 Session format。进程外 child 在父委派获准后保留自己的权限系统。 diff --git a/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.i18n.yaml b/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.i18n.yaml index b8b63582e2..379e4f0ad9 100644 --- a/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.i18n.yaml @@ -18,14 +18,14 @@ en: 554d01427ebebee1 zh: 664c9bf0a9337a04 /agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/decision/presentation-and-accounting: - en: 00a91b4fb592e1e4 - zh: dac2e4f0a3ee9ecf + en: 800d579e2fcf2cce + zh: 1e92354d9161c50a /agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/decision/compaction: en: c21a3e7a773860e5 zh: 566669e245ccdbaf /agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/alternatives-considered: - en: f3dec242b2550529 - zh: 0397fa07cc1806bb + en: 02b49911bc4601d0 + zh: bfa19fd7c4337812 /agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/consequences: en: beda064bcd194a2a zh: 8a3bb81d5edcd60a diff --git a/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.md b/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.md index 644592d2a1..82402feff9 100644 --- a/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.md +++ b/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.md @@ -43,7 +43,7 @@ An empty head with no active later system node represents no prompt. Dormant emp Web presents an appended in-history node at its own position. `SystemPromptNode` carries `{ seq, time, turn, step, text, update }`, `update` being true for an appended `system/message` that follows an earlier system node in the loaded window. Chat renders a non-empty update as a collapsed `system-prompt` card titled by the locale key `message.systemPromptUpdate`, and a `request/header` in the same turn and step does not repeat the prompt card; `inspectRequestPrompt` reports no system change for a header that follows an update. Trajectory folds an update following a loaded request header into a synthetic request-header fact with `promptChange.kind = 'system'`, so later requests show the effective prompt without a real header change. When the loaded window lacks the earlier system node, the update is presented as an initial prompt. Transcript projections skip it like every `system/message`. -`dsh-token-meter` prices the last nonempty surviving system node in surface order as `contextBreakdown.systemTokens`; every other visible node, including superseded prompts, contributes to `messageTokens`. Empty dormant nodes are ignored. The sum equals the fixed-heuristic surface total after every replacement, whether or not a shadow-price claim exists. Compact retained entries reuse the measurement surface planner: state and transitions cost O(current retained surface), not O(1) or O(total historical log). Replaced entries and message bodies are discarded, and state version 4 rejects scalar checkpoints. `cacheReadTokens` on subsequent assistant usage remains the observable provider-cache effect. +`dsh-token-meter` prices the last nonempty surviving system node in surface order as `contextBreakdown.systemTokens`; every other visible node, including superseded prompts, contributes to `messageTokens`. Empty dormant nodes are ignored. The unit retains only the surviving system prompts and a running surface total, and prices replacements from the adjacent shadow-price event ([system-prompt state](../architecture/2026-10-13-context-breakdown-system-prompt-state.md)). `cacheReadTokens` on subsequent assistant usage remains the observable provider-cache effect. Trajectory chooses the newer of the preceding real header and the preceding synthetic system header as the comparison state. A real header owns configuration and tools; an appended prompt can advance that state without another real header. Comparing only real headers would report A rather than B as the previous prompt for an A → B → C sequence. @@ -73,7 +73,7 @@ Chat and Trajectory interpret the effective prompt through the pure `uiConversat **Clear only the latest system node.** Empty nodes project to no message, so an older prompt would become effective again. Clearing all active versions preserves the meaning of an empty rendering without deleting conversation history. Rejected. -**Keep only scalar totals or prompt ancestry.** A scalar shadow price cannot identify which bucket lost the newest prompt or restore its predecessor. Prompt-only entries cannot locate arbitrary nonprompt replacement endpoints; `sourceEventSeqs` may also cite surviving prompts, and event sequence order differs from surface order after rewrites. Retaining compact current surface entries reuses the existing planner without full-log access, a second validator, or consumer-specific durable events. Summing all surviving prompts as system tokens would change the intended effective-prompt meaning rather than fix classification. +**Keep only scalar totals.** A scalar shadow price cannot identify which bucket lost the newest prompt or restore its predecessor. Summing all surviving prompts as system tokens would change the intended effective-prompt meaning rather than fix classification. Retained system prompts with the shadow-price event's `shadowedSeqs` answer both questions; [the system-prompt state note](../architecture/2026-10-13-context-breakdown-system-prompt-state.md) records that choice over positional entries. ## Consequences diff --git a/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.zh.md b/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.zh.md index b734bc74f7..a2c8c60bbf 100644 --- a/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.zh.md +++ b/.agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.zh.md @@ -43,7 +43,7 @@ Status: implemented Web 在追加的历史内节点自己的位置呈现它。`SystemPromptNode` 携带 `{ seq, time, turn, step, text, update }`,其中 `update` 对已加载窗口内跟在更早系统节点之后的追加 `system/message` 为真。Chat 把非空的更新渲染为一张折叠的 `system-prompt` 卡片,标题取自 locale 键 `message.systemPromptUpdate`,同一 turn 与 step 内的 `request/header` 不会重复提示词卡片;`inspectRequestPrompt` 对跟在更新之后的 header 不报告系统变更。Trajectory 把跟在已加载请求 header 之后的更新折叠为一条合成的请求 header 事实,`promptChange.kind = 'system'`,因此之后的请求无需真实的 header 变更就能显示有效提示词。已加载窗口缺少更早的系统节点时,更新按初始提示词呈现。转录投影像对待所有 `system/message` 一样跳过它。 -`dsh-token-meter` 把 surface 顺序中最后一个非空且存活的系统节点计入 `contextBreakdown.systemTokens`;其余可见节点(包括被取代的提示词)计入 `messageTokens`。休眠空节点被忽略。每次替换后,两者之和都等于固定启发式 surface 总量,无论是否存在影子价 claim。紧凑的保留条目复用测量服务的 surface 规划器:状态和转换成本为 O(当前保留 surface),不是 O(1) 或 O(完整历史日志)。被替换条目和消息正文被丢弃,状态版本 4 拒绝标量检查点。后续 assistant 用量中的 `cacheReadTokens` 仍是可观察的提供方缓存效果。 +`dsh-token-meter` 把 surface 顺序中最后一个非空且存活的系统节点计入 `contextBreakdown.systemTokens`;其余可见节点(包括被取代的提示词)计入 `messageTokens`。休眠空节点被忽略。该单元只保留存活的系统提示词和一个 surface 运行总量,并依据紧邻的影子价事件为替换定价([系统提示词状态](../architecture/2026-10-13-context-breakdown-system-prompt-state.zh.md))。后续 assistant 用量中的 `cacheReadTokens` 仍是可观察的提供方缓存效果。 Trajectory 选择前一条真实 header 与前一条合成系统 header 中较新的一个作为比较状态。真实 header 拥有配置与工具;追加的提示词可以在没有另一条真实 header 时推进该状态。只比较真实 header 会在 A → B → C 序列中把 A 而不是 B 报告为先前提示词。 @@ -73,7 +73,7 @@ Chat 与 Trajectory 通过纯操作 `uiConversation.inspectSystemPrompt` 解释 **仅清除最新系统节点。** 空节点不投影为消息,因此更早的提示词会重新生效。清除所有生效版本才能保留空渲染文本的含义,同时不删除对话历史。被否决。 -**只保留标量总量或提示词祖先链。** 标量影子价无法判断最新提示词从哪个分类消失,也无法恢复其前一个版本。仅有提示词条目无法定位任意非提示词替换端点;`sourceEventSeqs` 还可能引用存活提示词,改写后的事件序号顺序也不同于 surface 顺序。保留紧凑的当前 surface 条目可以复用现有规划器,无需完整日志访问、第二套验证器或消费方专用持久事件。把所有存活提示词之和归入系统数字会改变有效提示词的含义,而不是修复分类。 +**只保留标量总量。** 标量影子价无法判断最新提示词从哪个分类消失,也无法恢复其前一个版本。把所有存活提示词之和归入系统数字会改变有效提示词的含义,而不是修复分类。保留系统提示词并结合影子价事件的 `shadowedSeqs` 可以回答这两个问题;[系统提示词状态说明](../architecture/2026-10-13-context-breakdown-system-prompt-state.zh.md)记录了为何以这种方式取代位置条目。 ## Consequences diff --git a/.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.i18n.yaml b/.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.i18n.yaml index d74aa0ba75..75bfe1d654 100644 --- a/.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.i18n.yaml @@ -9,8 +9,8 @@ en: 71813b1cb1f750ba zh: 64d2b999933ccd98 /agent-note-web-sidebar-terminals/decision: - en: 8d28949572d990ef - zh: f6e26790415134d2 + en: ef54b8ca31bb71de + zh: 0c05685c25010e8c /agent-note-web-sidebar-terminals/alternatives-considered: en: b0ffb94cd5033e9c zh: 9294bb76503c858a @@ -18,5 +18,5 @@ en: d710787595b5dc89 zh: 4df9518c32698f85 /agent-note-web-sidebar-terminals/related: - en: 94540c743da01fc4 - zh: 53e3d9d2268153d1 + en: 2ae8d413f928803f + zh: 3075efb83112b130 diff --git a/.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.md b/.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.md index 448bcf84c1..39a0a5fff8 100644 --- a/.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.md +++ b/.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.md @@ -22,7 +22,7 @@ Close and replacement remove the tab synchronously and run process cleanup in th The caller retains a terminal ID before creating it. Repeating create with the same Session and open ID does not allocate a second process. Closing an uncertain create uses that ID even when no creation response arrived. The Host records closed IDs before awaiting allocation, preventing a delayed create from reviving a closed terminal. Each attachment begins with a consistent, bounded serialized xterm screen; ordered output follows through the Gateway's existing multiplexed Remote stream. Output and screen snapshots share one operation queue. Followers retain final output on normal closure and fail explicitly on buffer overflow. Browser render acknowledgement prevents React batching from dropping increments. -The latest attachment controls input and dimensions; other attachments remain read-only. Every physical stream opening gets a fresh input attachment identity, including automatic transport recovery. Input RPCs are serialized, and results from a superseded attachment cannot downgrade a replacement connection. Terminal output creates no model input, Agent tool result or Session event. The existing [persistent Agent terminal decision](2026-07-16-persistent-pty-sessions.md) continues to govern model-owned sessions; this feature extends the [portable subprocess provider](../architecture/2026-07-28-portable-execution-world-consumers.md) with terminal environment facts and resize. Control-transfer and process-exit refusals only disable input, preserving the healthy output view. Client-owned error identifiers are translated by the terminal UI, including guidance to close retained exited terminals when the quota is full. +The latest attachment controls input and dimensions; other attachments remain read-only. Each physical `attach` stream owns its input and resize commands, including after automatic transport recovery. The Host orders commands and acknowledges provider acceptance; the Client bounds raw input and complete encoded frames, queues commands when the advertised carrier window is full, and resumes on acknowledgements. Superseded streams cannot write through their replacements, and unacknowledged input is never replayed. Terminal output creates no model input, Agent tool result or Session event. The existing [persistent Agent terminal decision](2026-07-16-persistent-pty-sessions.md) continues to govern model-owned sessions; this feature extends the [portable subprocess provider](../architecture/2026-07-28-portable-execution-world-consumers.md) with terminal environment facts and resize. Control-transfer and process-exit refusals only disable input, preserving the healthy output view. Client-owned error identifiers are translated by the terminal UI, including guidance to close retained exited terminals when the quota is full. ## Alternatives considered @@ -52,4 +52,4 @@ The [two-hour unattended-terminal reclamation](2026-09-14-unattended-browser-ter ## Related -- [Remote duplex stream](../architecture/2026-09-19-remote-duplex-stream.md): the transport-layer uplink under which one `attach` stream replaces the unary `write` and `resize` calls and the `attachmentId` correlation; that terminal change is listed under its Deferred section. +- [Remote duplex stream](../architecture/2026-09-19-remote-duplex-stream.md): the transport-layer uplink carrying terminal input and output under one physical attachment lifetime. diff --git a/.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.zh.md b/.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.zh.md index 81bdf81ed9..6f1249e181 100644 --- a/.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.zh.md +++ b/.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.zh.md @@ -22,7 +22,7 @@ Web 用户需要在 Session 旁使用交互式 shell 检查工作区和运行命 调用者在创建之前保留终端 ID。相同 Session 和未关闭 ID 的重复 create 不再分配进程。创建结果不确定时,关闭仍使用该 ID,即使没有收到创建响应。Host 在等待分配完成前记录已关闭 ID,防止迟到的 create 复活已关闭终端。每次连接先接收一致、有界的 xterm 序列化屏幕,后续有序输出使用 Gateway 已有的复用 Remote stream。输出和屏幕快照共享操作队列。订阅者正常关闭时保留末尾输出,缓存超限时明确失败。浏览器在完成渲染后确认帧,避免 React 批处理丢失增量。 -最新连接控制输入和尺寸,其他连接保持只读。每次物理流建立都创建新的输入连接标识,包括传输自动恢复。输入 RPC 按序发送,旧连接的结果不能把新连接降级为失败。终端输出不产生模型输入、Agent 工具结果或 Session 事件。[Agent 持久终端决策](2026-07-16-persistent-pty-sessions.zh.md)仍约束模型拥有的终端;此功能为[可移植 subprocess provider](../architecture/2026-07-28-portable-execution-world-consumers.zh.md)增加执行环境事实和 resize。 控制权转移和进程退出导致的拒绝只禁用输入,保留健康的输出视图。Client 自产错误标识由终端 UI 翻译,包括名额用满时关闭已保留的退出终端的提示。 +最新连接控制输入和尺寸,其他连接保持只读。每条物理 `attach` 流拥有自己的输入和尺寸命令,传输自动恢复后亦如此。Host 按序执行命令并确认提供者已接受操作;Client 限制原始输入和完整编码帧,在公布的载体窗口满时排队,并在收到确认后继续发送。旧流不能借用新流写入,未确认输入绝不重放。终端输出不产生模型输入、Agent 工具结果或 Session 事件。[Agent 持久终端决策](2026-07-16-persistent-pty-sessions.zh.md)仍约束模型拥有的终端;此功能为[可移植 subprocess provider](../architecture/2026-07-28-portable-execution-world-consumers.zh.md)增加执行环境事实和 resize。 控制权转移和进程退出导致的拒绝只禁用输入,保留健康的输出视图。Client 自产错误标识由终端 UI 翻译,包括名额用满时关闭已保留的退出终端的提示。 ## 考虑过的替代方案 @@ -52,4 +52,4 @@ Agent 终端和可移植执行环境两篇记录仍保留,其所有权与 prov ## 相关 -- [Remote 双工流](../architecture/2026-09-19-remote-duplex-stream.zh.md):传输层上行,让一条 `attach` 流取代 unary `write`、`resize` 与 `attachmentId` 关联;该终端改动列在其「后续」中。 +- [Remote 双工流](../architecture/2026-09-19-remote-duplex-stream.zh.md):传输层上行在同一物理附件生命周期内承载终端输入和输出。 diff --git a/.agents/notes/implemented/feature/2026-09-20-spawn-agent-preset-selection.i18n.yaml b/.agents/notes/implemented/feature/2026-09-20-spawn-agent-preset-selection.i18n.yaml new file mode 100644 index 0000000000..be693bf4cb --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-20-spawn-agent-preset-selection.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-09-20-spawn-agent-preset-selection.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/feature/2026-09-20-spawn-agent-preset-selection.md +/agent-note-independent-spawn-preset-selection-and-restoration: + en: 2c57fd9b420af1cc + zh: 8d0d7a53fc85f746 +/agent-note-independent-spawn-preset-selection-and-restoration/problem: + en: 62fa53e4befdf947 + zh: 99956ba40cbda1ab +/agent-note-independent-spawn-preset-selection-and-restoration/decision: + en: a321ee6871ef14c0 + zh: 599093af0657a675 +/agent-note-independent-spawn-preset-selection-and-restoration/alternatives-considered: + en: 82fa00b86c8d375b + zh: eb00a537a854dfe4 +/agent-note-independent-spawn-preset-selection-and-restoration/consequences: + en: 57531f2f2eb7da5b + zh: 206564a73e8d7193 diff --git a/.agents/notes/implemented/feature/2026-09-20-spawn-agent-preset-selection.md b/.agents/notes/implemented/feature/2026-09-20-spawn-agent-preset-selection.md new file mode 100644 index 0000000000..e59975ca16 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-20-spawn-agent-preset-selection.md @@ -0,0 +1,33 @@ +# Agent Note: Independent spawn preset selection and restoration + +Status: implemented + +English | [中文](2026-09-20-spawn-agent-preset-selection.zh.md) + +## Problem + +Spawned agents need reusable combinations of persona, tools, and skills without replacing the [implicit parent-preset join](../../archived/bug-fix/2026-08-10-child-agents-join-their-parent-preset.md). Restoration must distinguish an independent selection from historical child logs without changing the Session format or fork behavior. + +## Decision + +An explicit spawn preset id resolves the currently registered definition, even when it equals the parent's id. Omission joins the parent's exact live revision. Selecting a named configuration accepts its current declaration and resolution failures; inheriting an active composition preserves its plugin instances even after that declaration changes or is removed. + +An independently selected child records the existing `agent-preset/selected` event before its first own `subagent/descriptor`. Cold restoration excludes the inherited fork prefix and uses that ordering to identify independent selection, then reads the selected id from the existing `agentPreset` projection. A missing projection rejects restoration rather than silently switching to the parent's composition. + +Historical children without this ordering retain the implicit join. A creation header can contain an inherited preset id, while a fork's seed can contain an ancestor's selection and an old child can record a selection after its descriptor. None of these facts establishes independent selection at child creation. The ordering marker preserves those histories without adding a descriptor field or another event type. + +## Alternatives considered + +**Resolve every child by preset id.** This would make an omitted selection observe an updated definition or fail after its removal, changing the implicit join and historical restoration behavior. + +**Infer independent selection from the header or projection alone.** Both can carry inherited values. A last-value projection also loses the ordering needed to distinguish a creation-time selection from later selections in historical logs. + +**Store a preset id in a new descriptor version.** The existing selection event and projection already persist the id. Another field would duplicate it and require a descriptor migration for a distinction the existing event order can express. + +**Support a nested preset object.** A second configuration spelling adds precedence and validation rules without serving an existing caller. A flat preset id selects composition; fork does not accept independent preset selection. + +## Consequences + +Independent restoration resolves the selected id against the registered definition; it does not preserve a historical revision across restarts. Missing or invalid presets fail explicitly. Implicit children and fork retain their existing composition and cold-restoration behavior. + +Focused continuation tests cover event ordering, inherited prefixes, historical logs, and missing projections. The recorded-session preset scenario covers independent persona and tool selection through the shipped headless composition. diff --git a/.agents/notes/implemented/feature/2026-09-20-spawn-agent-preset-selection.zh.md b/.agents/notes/implemented/feature/2026-09-20-spawn-agent-preset-selection.zh.md new file mode 100644 index 0000000000..8b5e8dbff4 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-20-spawn-agent-preset-selection.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 独立 spawn preset 选择与恢复 + +Status: implemented + +[English](2026-09-20-spawn-agent-preset-selection.md) | 中文 + +## 问题 + +spawn 子 Agent 需要可复用的 persona、工具和技能组合,同时保留[隐式加入父方 preset](../../archived/bug-fix/2026-08-10-child-agents-join-their-parent-preset.md) 的行为。恢复时必须区分独立选择与历史子会话日志,不改变 Session 格式或 fork 行为。 + +## 决策 + +显式指定 spawn preset id 时解析当前注册的定义,即使该 id 与父方相同;省略时加入父方正在运行的确切代际。选择具名配置意味着接受当前声明及其解析失败;继承活跃组装则保留它的插件实例,即使声明已经修改或移除。 + +独立选择的子 Agent 在首条自有 `subagent/descriptor` 之前记录已有的 `agent-preset/selected` 事件。冷恢复排除继承的 fork 前缀,用此顺序识别独立选择,再从已有 `agentPreset` 投影读取所选 id。投影缺失时拒绝恢复,避免静默切换到父方组装。 + +不具备此顺序的历史子会话继续隐式加入父方。创建 header 可能包含继承的 preset id,fork 种子可能包含祖先的选择,旧子会话也可能在 descriptor 之后记录选择;这些事实都不能证明子会话创建时作过独立选择。事件顺序标记保留这些历史语义,无须增加 descriptor 字段或新的事件类型。 + +## 考虑过的替代方案 + +**所有子 Agent 都按 preset id 解析。** 这会让省略选择的子 Agent 读到更新后的定义,或因定义移除而失败,改变隐式加入及历史恢复行为。 + +**仅从 header 或投影推断独立选择。** 两者都可能携带继承值。末值投影还会丢失事件顺序,无法区分创建时选择与历史日志中的后续选择。 + +**在新版本 descriptor 中存储 preset id。** 已有选择事件和投影已经持久化该 id。增加字段会重复存储,并为现有事件顺序已能表达的区别引入 descriptor 迁移。 + +**支持嵌套 preset 对象。** 第二种配置写法会增加优先级与校验规则,却不服务于现有调用方。扁平的 preset id 选择组装;fork 不接受独立 preset 选择。 + +## 后果 + +独立恢复按所选 id 解析已注册定义,不跨重启保存历史代际。preset 缺失或无效时明确失败。隐式子 Agent 与 fork 保留原有组装和冷恢复行为。 + +针对性 continuation 测试覆盖事件顺序、继承前缀、历史日志和缺失投影。会话录制快照通过 shipped headless 组装覆盖独立 persona 与工具选择。 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-09-11-persistence-type-history.i18n.yaml b/.agents/notes/implemented/process/2026-09-11-persistence-type-history.i18n.yaml index 126601f6e3..246e224b7f 100644 --- a/.agents/notes/implemented/process/2026-09-11-persistence-type-history.i18n.yaml +++ b/.agents/notes/implemented/process/2026-09-11-persistence-type-history.i18n.yaml @@ -9,14 +9,14 @@ en: c8e926bfc65d7195 zh: e0e007960b68fe80 /agent-note-in-tree-persistence-type-history/decision: - en: 0d6257a57763ad48 - zh: 6ce3cb7228bba27a + en: 94be3d6c7df3063b + zh: 7e8fb08d7fd95f85 /agent-note-in-tree-persistence-type-history/decision/finalized-checkpoints: - en: 7dd42139850de3bf - zh: 0783bff2f0084f71 + en: b508035a163340a3 + zh: ba5b2b7e8cef4b2f /agent-note-in-tree-persistence-type-history/alternatives-considered: - en: 5cdac1b3f15f89f6 - zh: 36cda3b92d31c916 + en: 1cf6d0a5555ae50a + zh: 70ea1ba535e09442 /agent-note-in-tree-persistence-type-history/consequences: en: 672c8cb59d291dc2 zh: cbec90fbca92320a diff --git a/.agents/notes/implemented/process/2026-09-11-persistence-type-history.md b/.agents/notes/implemented/process/2026-09-11-persistence-type-history.md index 87e87041dd..add0904f42 100644 --- a/.agents/notes/implemented/process/2026-09-11-persistence-type-history.md +++ b/.agents/notes/implemented/process/2026-09-11-persistence-type-history.md @@ -10,13 +10,15 @@ A persisted event can retain the same payload type expression while a referenced ## Decision +The [reader-compatibility review decision](2026-10-08-session-reader-compatibility-review.md) supersedes the automatic version floor. This note owns normalized type history, per-root acknowledgements, and accepted checkpoint preservation. + One normalized type model supplies the readable persistence catalog, the complete schema inventory, and transitive per-root digests. Roots identify the logical Session header, the physical JSONL header line, the event envelope, and every repository-declared event. Source locations, alias names, ordinary comments, and property order are presentation details outside the digest. Explicit compatibility annotations carry fingerprinted policy data under the [source-attribution policy](2026-09-17-persistence-schema-review.md). Historical records retain source file paths without line numbers because their selected source trees differ from the current checkout. Referenced and recursive types participate in structural comparison; opaque values retain explicit coverage limits. The dedicated [persistence-change records](../../../../docs/persistence-changes/README.md) bind acknowledgement to the after digest of each affected root. A generated companion stores complete after schemas. The initial record covers all roots; later records name each root's predecessor. A predecessor's after schema supplies the next before schema. Verification rejects ambiguous history and requires current source to match the terminal recorded state without consulting Git history or remote services. -Automatic classification permits optional body additions, required-to-optional body changes, and ordinary event additions within one version. The scoped [source-attribution policy](2026-09-17-persistence-schema-review.md) also permits qualified new producer kinds when both saved schemas opt in. The [event-payload version rule](../../../../docs/persistence-changes/README.md#compatibility-rules) admits higher numeric payload versions when every old alternative remains unchanged and records the older-reader limitation. Other structural changes require a version-bump decision that includes an increasing header version in that record. The [format-version procedure](../../../../docs/cookbook/adding-a-session-format-version.md) continues to own adjacent migration work. Every structural difference requires an explicit record, including additions allowed within the same version. +Automatic classification permits optional body additions, required-to-optional body changes, and ordinary event additions within one version. The scoped [source-attribution policy](2026-09-17-persistence-schema-review.md) also permits qualified new producer kinds when both saved schemas opt in. The [event-payload version rule](../../../../docs/persistence-changes/README.md#compatibility-rules) admits higher numeric payload versions when every old alternative remains readable and records the older-reader limitation. Other structural changes require an explicit same-version choice in the recording CLI or an increasing header version. Every structural difference needs an acknowledgement; its Compatibility and Verification sections explain both reader directions and executed checks. CI validates saved decisions without inferring how they were authored. The [format-version procedure](../../../../docs/cookbook/adding-a-session-format-version.md) owns adjacent migration work when a bump is required. -The new document kind preserves the compatibility reasoning and evidence for a historical type transition. Agent Notes retain mechanism-level decisions; they do not become a growing inventory of individual acknowledgements. Machine declarations remain identical across the bilingual pair and are parsed once. +The persistence-change document kind preserves compatibility reasoning and evidence for a historical type transition. Agent Notes retain mechanism-level decisions; they do not become a growing inventory of individual acknowledgements. Machine declarations remain identical across the bilingual pair and are parsed once. Retrospective [release comparisons](../../../../docs/persistence-changes/releases/README.md) use a separate `persistence-release` kind and pinned tag manifest. They retain changed after schemas and reconstruct adjacent releases, including unchanged tags. Earlier releases predate these acknowledgement rules, so their classifications are informational and their observed versions are not rewritten to satisfy a modern version floor. Historical parsing preserves optional surface operations; the current parser and acknowledgement chain remain strict. This separation permits approximate backfills without turning them into authorization for current changes. @@ -28,7 +30,7 @@ Explicit update refreshes an unaccepted terminal record without deleting its aut ### Finalized checkpoints -Finalization records acceptance independently of publication. A terminal record must not reuse its original header increase to authorize another breaking change to already-written data. The [status record](../../../../docs/session-format-status.md#finalization-record) therefore requires a complete compatibility checkpoint: accepted record semantics remain locked, while compatible current-source changes proceed through new records and breaking changes require a higher writer. The existing classifier and unknown-event protocol are unchanged. This adds no runtime field and cannot detect behavior changes hidden behind unchanged declarations. Coordinated edits to the in-tree authority and checkpoint still require review. +Finalization records acceptance independently of publication. The [status record](../../../../docs/session-format-status.md#finalization-record) requires a complete compatibility checkpoint that locks accepted machine declarations and after schemas. Further schema changes need new acknowledgements; an explicit version-bump decision must contain its own header increase and cannot reuse an accepted transition. The checkpoint adds no runtime field, does not change unknown-event handling, and cannot detect behavior changes hidden behind unchanged declarations. Coordinated edits to the in-tree authority and checkpoint still require review. ## Alternatives considered @@ -40,7 +42,7 @@ Finalization records acceptance independently of publication. A terminal record **Treat every changed digest as a version bump.** Optional body additions, required-to-optional changes, and ordinary event additions do not always require a new persistence version. Conservative classification distinguishes these cases and leaves the compatibility explanation to review. -**Infer behavior from types or permit arbitrary compatibility overrides.** A type graph cannot prove replay semantics. The checker confines itself to detectable structure and rejects decisions below the mechanical classification; it does not claim to detect behavior-only changes. +**Infer behavior from types or require proof of human review.** A type graph cannot establish replay semantics, and a recorded choice cannot establish how it was authored. The checker validates declared transitions and header-version constraints. Reviewers inspect actual reader behavior and the acknowledgement’s explanation independently. ## Consequences diff --git a/.agents/notes/implemented/process/2026-09-11-persistence-type-history.zh.md b/.agents/notes/implemented/process/2026-09-11-persistence-type-history.zh.md index cfe5c4f7bd..fade8ff41b 100644 --- a/.agents/notes/implemented/process/2026-09-11-persistence-type-history.zh.md +++ b/.agents/notes/implemented/process/2026-09-11-persistence-type-history.zh.md @@ -10,13 +10,15 @@ Status: implemented ## 决策 +[读取器兼容性评审决策](2026-10-08-session-reader-compatibility-review.zh.md)取代自动最低版本要求。本说明负责规范化类型历史、逐根确认与已接受检查点保留。 + 一个规范化类型模型提供可读持久化目录、完整 schema 清单和包含传递引用的逐根摘要。根标识逻辑会话头、物理 JSONL 头行、事件封装以及每个仓库内声明的事件。源码位置、别名名称、普通注释和属性顺序属于摘要之外的展示细节。历史记录保留源码文件路径而不包含行号,因为其选定的源码树与当前工作树不同。被引用类型和递归类型参与结构比较;不透明值保留明确的覆盖限制。显式兼容性标记依照[消息源归属策略](2026-09-17-persistence-schema-review.zh.md)携带纳入指纹的策略数据。 专用的[持久化变更记录](../../../../docs/persistence-changes/README.zh.md)将确认绑定到每个受影响根的变更后摘要。生成的伴随文件保存完整的变更后 schema。初始记录覆盖所有根;后续记录为每个根指定前驱。前驱的变更后 schema 提供下一次的变更前 schema。验证拒绝有歧义的历史,并要求当前源码匹配最终记录状态,无需查询 Git 历史或远端服务。 -自动分类允许可选事件体新增、事件体属性从必选改为可选,以及普通事件新增保持同一版本。当双方保存的 schema 均声明支持时,受限的[消息源归属策略](2026-09-17-persistence-schema-review.zh.md)也允许添加符合条件的生产者 kind。[事件载荷版本规则](../../../../docs/persistence-changes/README.zh.md#compatibility-rules) 允许在原样保留所有旧分支时增加更高的数字载荷版本,并记录旧读取器限制。其他结构变更需要升版本决策,并在该记录中包含递增的头部版本。[格式版本流程](../../../../docs/cookbook/adding-a-session-format-version.zh.md)继续负责相邻迁移工作。每个结构差异都需要显式记录,包括允许保持同一版本的新增。 +自动分类允许可选事件体新增、事件体属性从必选改为可选,以及普通事件新增保持同一版本。当双方保存的 schema 均声明支持时,受限的[消息源归属策略](2026-09-17-persistence-schema-review.zh.md)也允许添加符合条件的生产者 kind。[事件载荷版本规则](../../../../docs/persistence-changes/README.zh.md#compatibility-rules)允许在每个旧分支仍可读取时增加更高的数字载荷版本,并记录旧读取器限制。其他结构变更要求在记录 CLI 中显式选择同版本,或递增头版本。每个结构差异都需要确认;其兼容性与验证部分说明两个方向的读取器行为及已执行检查。CI 验证保存的决策,不推断其编写方式。需要升版本时,[格式版本流程](../../../../docs/cookbook/adding-a-session-format-version.zh.md)负责相邻迁移工作。 -新文档类型保留历史类型转换的兼容性说明和证据。Agent Note 保留机制层面的决策,不积累单次确认清单。双语对中的机器声明保持相同,且只解析一次。 +持久化变更文档类型保留历史类型转换的兼容性说明和证据。Agent Note 保留机制层面的决策,不积累单次确认清单。双语对中的机器声明保持相同,且只解析一次。 回溯性的[发行版本比较](../../../../docs/persistence-changes/releases/README.zh.md)使用独立的 `persistence-release` 类型和固定 tag 清单。它们保留变化后的 schema,并重建相邻版本,包括未变的 tag。早期版本先于这些确认规则,因此其分类只提供信息,观察到的版本号不会为满足当前最低版本要求而被改写。历史解析保留可选的 surface 操作;当前解析器和确认链仍保持严格。这一区分允许近似回填,同时不会将其变成当前变更的授权。 @@ -28,7 +30,7 @@ Status: implemented ### 定稿检查点 -定稿独立于发布事实记录接受状态。末端记录不能复用原有头版本递增,继续授权对已写入数据进行破坏性变更。因此,[状态记录](../../../../docs/session-format-status.zh.md#finalization-record)要求完整兼容性检查点:已接受记录的语义保持锁定,当前源码的兼容变更通过新记录继续,破坏性变更要求更高的写入器版本。现有分类器与未知事件协议保持不变。这不会添加运行时字段,也不能检测未变声明后隐藏的行为变化。对目录内真源与检查点的协同修改仍须审阅。 +定稿独立于发布事实记录接受状态。[状态记录](../../../../docs/session-format-status.zh.md#finalization-record)要求完整兼容性检查点,锁定已接受的机器声明与变更后 schema。后续 schema 变化需要新的确认;显式升版本决策必须包含自身的头版本递增,不能复用已接受转换。检查点不添加运行时字段,不改变未知事件处理,也不能检测未变声明后隐藏的行为变化。对目录内真源与检查点的协同修改仍须审阅。 ## 考虑过的替代方案 @@ -40,7 +42,7 @@ Status: implemented **把每次摘要变化都视为升版本。** 可选事件体新增、必选改可选,以及普通事件新增不一定需要新的持久化版本。保守分类区分这些情况,并将兼容性说明交给审阅。 -**从类型推断行为,或允许任意兼容性豁免。** 类型图无法证明回放语义。检查器仅覆盖可检测结构,并拒绝低于机械分类要求的决策;它不声称能够检测纯行为变更。 +**从类型推断行为,或要求人类评审证明。** 类型图无法证明回放语义,所记录的选择也无法证明其编写方式。检查器验证声明的转换与头版本约束。评审者独立检查实际读取器行为与确认说明。 ## 影响 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-08-session-reader-compatibility-review.i18n.yaml b/.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.i18n.yaml new file mode 100644 index 0000000000..45e17bc0e6 --- /dev/null +++ b/.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-08-session-reader-compatibility-review.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-08-session-reader-compatibility-review.md +/agent-note-session-versions-follow-reader-compatibility: + en: b27e6ad9824a02e4 + zh: 034a5dc50838db3d +/agent-note-session-versions-follow-reader-compatibility/problem: + en: fa4f3e56f3b22e07 + zh: a8010ab822474c2c +/agent-note-session-versions-follow-reader-compatibility/decision: + en: ab45f42c587793e8 + zh: b1c2eab9e8642824 +/agent-note-session-versions-follow-reader-compatibility/migration-obligations: + en: b218b28f19c41f33 + zh: 7e99314983707984 +/agent-note-session-versions-follow-reader-compatibility/alternatives-considered: + en: be63c3e727b18cd3 + zh: 91b4e2ffaa42bdb9 +/agent-note-session-versions-follow-reader-compatibility/consequences: + en: 0ee67db581e8e03d + zh: ece4f775c8008f8a diff --git a/.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.md b/.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.md new file mode 100644 index 0000000000..194bc39632 --- /dev/null +++ b/.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.md @@ -0,0 +1,39 @@ +# Agent Note: Session versions follow reader compatibility + +Status: implemented + +English | [中文](2026-10-08-session-reader-compatibility-review.zh.md) + +## Problem + +A structural schema difference does not establish that a Session needs a new integer version. An optional environment header field illustrates the cost: sessions that omit the feature can retain identical logs, while sessions that require it can be refused by older readers. A global bump also excludes feature-free sessions and requires a new generation and adjacent migration. Conversely, an unknown field or value does not establish safe refusal: permissive readers can ignore required meaning, and recovery can mistake unsupported records for damaged tails. + +## Decision + +The user chose reader behavior as the version criterion. A same-version change is permitted when older readers either resume correctly, safely ignore optional features while preserving their records, or refuse required features before execution, mutation, or tail repair. Feature absence must preserve existing behavior. Required-feature refusal needs an upgrade diagnostic; already released binaries retain their existing diagnostics, so review identifies any limitation explicitly. + +New readers preserve the meaning of supported historical records and accept valid mixtures of old and new representations within one Session. Removing a required field or changing its representation is not automatically a bump: the replacement must remain distinguishable, and released-reader behavior must satisfy the same admission requirements. A version increase is required when no effective existing discriminator prevents unsafe interpretation. Reusing a logged value with a different meaning is one example; missing admission checks are another. + +The schema classifier identifies structural changes requiring compatibility review instead of declaring them inherently version-breaking. Every schema difference still needs an acknowledgement. Established safe cases infer same-version; other same-version changes require an explicit decision when recording or updating. The existing Compatibility and Verification sections record reader behavior and executed checks. The checker validates the decision and recorded schemas; it cannot prove that the explanation matches runtime behavior. An explicit version-bump decision still requires its own increasing `SessionHeader.version`. Accepted machine records and checkpoints remain immutable; prose remains outside checkpoint hashes. + +The user treats a recorded `same-version` decision as explicit regardless of whether the CLI or an editor produced it. The CLI requires `--decision same-version` for flagged record and update operations; CI validates the saved decision against history, schemas, and header-version constraints. Neither mechanism attests that a human reviewed the transition. Reviewers use base/head inventory comparison rather than current-tree consistency checks to inspect already acknowledged changes. + +This decision partially supersedes the structural bump criterion in the [version-mechanism note](../architecture/2026-08-10-session-log-version-mechanism.md) and the automatic version floor in the [persistence-type-history note](2026-09-11-persistence-type-history.md). Their monotonic integer, required unknown-event default, type history, and immutable generation decisions remain active. The [review procedure](../../../../docs/cookbook/reviewing-persistence-type-changes.md) owns authoring and validation details. + +## Migration obligations + +One codec per integer version and one migration per adjacent pair remain sufficient. A version's reader supports its released representations without changing established meanings; an eventual successor migration accepts that same historical range, including mixed records. Historical conversion can keep producing a valid older representation within the target version. Same-version reads do not run an adjacent migration, so a compatibility claim cannot depend on an unimplemented normalization step. Header and payload extensions still need feature-specific admission and preservation through their actual consumers. + +## Alternatives considered + +**Require bumps for header changes and other structural edits.** This mechanically excludes safe refusal and optional features, imposing migration work even when existing discriminators already protect readers. + +**Treat every unknown field or value as a refusal mechanism.** Released readers do not uniformly reject unknown values before recovery. Compatibility evidence must inspect the actual admission and mutation paths; a changed schema alone supplies no guarantee. + +**Permit same-version changes without recorded reader evidence.** A schema graph cannot establish safe execution, lossless retention, historical interpretation, or mixed-record behavior. Explicit review preserves these obligations without making the classifier pretend to prove them. + +**Add a separate JSON review object and hash its evidence.** The user rejected duplicating the existing Compatibility and Verification prose. Extra input fields and renewal rules add authoring work without establishing semantic safety. An explicit same-version choice and the existing acknowledgement keep the decision visible without a second evidence format. + +## Consequences + +The rule reduces unnecessary version transitions while making old-reader and new-reader evidence explicit. It changes review and acknowledgement enforcement, not runtime admission, diagnostics, codecs, or migration behavior. The environment example motivates the policy; it does not add an `env` field. Unsupported-feature detection, payload readers, and any necessary migration work remain obligations of each feature change. Focused verification must cover feature absence, optional retention or required refusal, historical input, and mixed representations as applicable; a written review is not a substitute for those results. diff --git a/.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.zh.md b/.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.zh.md new file mode 100644 index 0000000000..212db349f3 --- /dev/null +++ b/.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.zh.md @@ -0,0 +1,39 @@ +# Agent Note: Session 版本取决于读取器兼容性 + +Status: implemented + +[English](2026-10-08-session-reader-compatibility-review.md) | 中文 + +## 问题 + +schema 的结构差异不能证明 Session 需要新的整数版本。可选的环境头字段体现了这一成本:未使用该特性的会话可以保留完全相同的日志,需要该特性的会话则可以被旧读取器拒绝。全局升版本也会排除未使用特性的会话,并要求新的代际和相邻迁移。反过来,未知字段或值不能证明拒绝是安全的:宽松读取器可能忽略必需的含义,而恢复流程可能把不支持的记录误判为损坏的尾部。 + +## 决策 + +用户选择以读取器行为作为版本标准。当旧读取器能够正确恢复、安全忽略可选特性并保留其记录,或在执行、修改及尾部修复之前拒绝必需特性时,允许保持同一版本。未使用特性时必须保留现有行为。拒绝必需特性需要升级提示;已发布二进制保留其现有诊断,因此评审明确标出相关限制。 + +新读取器保留受支持历史记录的含义,并接受同一 Session 中新旧表示的有效混合。删除必需字段或改变其表示不自动要求升版本:替代表示必须可区分,已发布读取器的行为必须满足相同的准入要求。当不存在能够阻止不安全解释的有效既有判别标记时,必须升版本。将日志值复用于不同含义是一例;缺少准入检查是另一例。 + +schema 分类器标识需要兼容性评审的结构变更,而不将其直接判定为版本破坏。每项 schema 差异仍须确认。已明确安全的情形推断为同版本;其他同版本变更在记录或更新时要求显式决策。已有的兼容性与验证部分记录读取器行为和已执行检查。检查器验证决策与所记录的 schema,但无法证明说明与运行时行为一致。显式升版本决策仍须包含其自身递增的 `SessionHeader.version`。已接受的机器记录与检查点保持不可变;说明文字不参与检查点哈希。 + +用户将记录中的 `same-version` 决策视为显式选择,无论它由 CLI 还是编辑器产生。CLI 对被标记的记录与更新操作要求 `--decision same-version`;CI 按历史、schema 和头版本约束验证保存的决策。两种机制都不证明人类已评审转换。评审者使用 base/head 清单比较,而非当前目录一致性检查,来检查已确认的变更。 + +本决策部分取代[版本机制说明](../architecture/2026-08-10-session-log-version-mechanism.zh.md)中的结构性升版本标准,以及[持久化类型历史说明](2026-09-11-persistence-type-history.zh.md)中的自动最低版本要求。它们的单调整数、未知事件默认必需、类型历史与不可变代际决策仍然有效。[评审流程](../../../../docs/cookbook/reviewing-persistence-type-changes.zh.md)负责记录编写与验证细节。 + +## 迁移义务 + +每个整数版本一个 codec、每组相邻版本一个迁移仍然足够。一个版本的读取器支持其已发布表示,且不改变已确立的含义;后继迁移接受相同的历史范围,包括混合记录。历史转换可以继续产生目标版本内有效的旧表示。同版本读取不运行相邻迁移,因此兼容性声明不能依赖尚未实现的规范化步骤。头部与载荷扩展仍须在实际消费方中实现各自的准入与保留。 + +## 考虑过的替代方案 + +**对头部变更及其他结构编辑要求升版本。** 这会机械地排除安全拒绝和可选特性,即使既有判别标记已能保护读取器,也强加迁移工作。 + +**把每个未知字段或值都当作拒绝机制。** 已发布读取器并不统一在恢复前拒绝未知值。兼容性证据必须检查实际准入与修改路径;schema 变化本身不提供保证。 + +**允许同版本变更而不记录读取器证据。** schema 图无法证明安全执行、无损保留、历史解释或混合记录行为。明确评审保留这些义务,同时不让分类器假装已证明它们。 + +**添加独立的 JSON 评审对象并对证据做哈希。** 用户拒绝重复已有兼容性与验证说明。额外输入字段与更新规则增加编写工作,却不能证明语义安全性。显式同版本选择与已有确认记录使决策可见,无需第二种证据格式。 + +## 影响 + +该规则减少不必要的版本转换,同时明确要求旧读取器与新读取器的证据。它改变评审与确认校验,不改变运行时准入、诊断、codec 或迁移行为。环境示例说明政策动机,并未添加 `env` 字段。不支持特性的检测、载荷读取器及必要迁移仍由各项特性变更负责。针对性验证必须按需覆盖特性未使用、可选记录保留或必需特性拒绝、历史输入与混合表示;书面评审不能替代这些结果。 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/simplification/2026-09-26-team-direct-inbox.i18n.yaml b/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.i18n.yaml new file mode 100644 index 0000000000..f830391e86 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-09-26-team-direct-inbox.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/simplification/2026-09-26-team-direct-inbox.md +/agent-note-team-messages-use-the-target-inbox: + en: ae17b789652784b5 + zh: fa462ace95c8cdaa +/agent-note-team-messages-use-the-target-inbox/problem: + en: 83296699f94c77d3 + zh: e681a426bf0a703a +/agent-note-team-messages-use-the-target-inbox/decision: + en: 8d5fed34f19c7302 + zh: 25417793d3797775 +/agent-note-team-messages-use-the-target-inbox/alternatives-considered: + en: e847556d8e9f1071 + zh: bf1abe2f0e201eac +/agent-note-team-messages-use-the-target-inbox/consequences: + en: 24085acb09438dc8 + zh: 27c92e8de8cf7dbe diff --git a/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.md b/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.md new file mode 100644 index 0000000000..58d18d0ecf --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.md @@ -0,0 +1,27 @@ +# Agent Note: Team messages use the target inbox + +Status: implemented + +English | [中文](2026-09-26-team-direct-inbox.zh.md) + +## Problem + +A second Team outbox duplicates Agent inbox ownership with separate identities, acknowledgements, persistence checkpoints, and retry ordering. Callers need an explicit admission result while the continuation owner already provides target locking, lifecycle authorization, and cold recovery. + +## Decision + +New Team sends return the accepted inbox `MessageId` or throw. They use live Lead Steer or the host-only subagent Steer adapter, retaining the actual sender through the existing `agent-message` source and the member name in content. Acceptance follows ordinary Agent persistence; it neither confirms model processing nor adds a synchronous flush guarantee. Team does not retain unaccepted intent, retry it after restart, or deduplicate explicit resends. + +Historical mailbox records stay decodable and projected so existing Lead logs replay, but Team never delivers or acknowledges them. The package is experimental with no stability promise, and a second dispatch path with receipt inspection, per-target ordering, and its own disposal wait costs more than the undelivered old messages it would recover. This partially supersedes the mailbox decision in [Agent Teams](../feature/2026-08-05-agent-teams.md); roster and task decisions remain there. The [package reference](../../../../packages/experimental/agent-team/README.md#understand-the-implementation) owns the resulting limitation. + +## Alternatives considered + +**Keep the Team outbox for all sends.** This preserves a stronger retry promise but duplicates coordination and requires maintaining two acceptance states. Reintroduce it only for a concrete durable send-intent requirement that the Agent inbox cannot serve. + +**Expand public sibling messaging permissions.** Team membership is separate from subagent parent authority. The host adapter authorizes the exact Lead without misattributing the sender or broadening public child controls. + +**Drain historical pending items after restart.** This honors old accepted intent, but it keeps a second delivery owner beside the Agent inbox for data that only an experimental opt-in composition wrote. Removing the decoder as well is also rejected, because Lead logs containing mailbox records would then fail to replay. + +## Consequences + +New attempts have one identity and one inbox owner. A failed attempt is visible to its caller and has no Team retry promise. Historical logs still cost decoder and projection code. A historical message that its target had not recorded before the upgrade is never delivered. Tests cover direct Lead/peer acceptance, cold recovery, sender attribution, failures, cancellation, disposal, and that historical queued mail stays readable and undelivered after restart. diff --git a/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.zh.md b/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.zh.md new file mode 100644 index 0000000000..6928631c8f --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.zh.md @@ -0,0 +1,27 @@ +# Agent Note: Team 消息使用目标 inbox + +Status: implemented + +[English](2026-09-26-team-direct-inbox.md) | 中文 + +## 问题 + +第二套 Team outbox 通过独立身份、确认、持久化检查点和重试排序重复了 Agent inbox 的职责。调用方需要明确的准入结果,而 continuation owner 已提供目标锁、生命周期授权和冷恢复。 + +## 决策 + +新的 Team 发送返回获准 inbox 的 `MessageId` 或抛出错误。它们使用 live Lead Steer 或 host-only subagent Steer adapter,通过现有 `agent-message` source 保留真实发送者,并在正文中保留成员名称。接收遵循普通 Agent 的持久化策略,既不确认模型已处理,也不增加同步 flush 保证。Team 不保留尚未接收的发送意图,不在重启后重试,也不对显式重发去重。 + +历史 mailbox 记录继续可解码并参与投影,使现有 Lead 日志能够回放,但 Team 不再投递或确认它们。该包是实验性的,没有稳定性承诺;另设一条带回执检查、同目标排序和独立 dispose 等待的投递路径,其代价高于它能补回的未投递旧消息。这部分取代了 [Agent Teams](../feature/2026-08-05-agent-teams.zh.md) 的 mailbox 决策;roster 和任务决策仍由原记录负责。[包参考](../../../../packages/experimental/agent-team/README.zh.md#understand-the-implementation)定义由此产生的限制。 + +## 考虑过的替代方案 + +**为所有发送保留 Team outbox。** 这保留了更强的重试承诺,但重复协调职责,并要求维护两个接收状态。只有具体的持久发送意图需求无法由 Agent inbox 满足时,才重新引入它。 + +**扩大公开的 sibling 消息权限。** Team 成员关系与 subagent parent 权限不同。host adapter 授权确切的 Lead,不会错误归属发送者,也不会扩大公开 child control 权限。 + +**重启后补送历史 pending 项。** 这能兑现已接收的旧意图,但会在 Agent inbox 之外保留第二个投递 owner,而这些数据只由实验性的可选组合写入。同时删除 decoder 的方案也被否决,因为包含 mailbox 记录的 Lead 日志将无法回放。 + +## 后果 + +新尝试只有一个身份和一个 inbox owner。失败尝试会向调用方报告,且没有 Team 重试承诺。历史日志仍需要 decoder 与投影代码。升级前目标尚未记录的历史消息永远不会被投递。测试覆盖直接 Lead/peer 接收、冷恢复、发送者归属、失败、取消、dispose(资源释放),以及重启后历史排队消息仍可读取且不被投递。 diff --git a/.agents/notes/implemented/simplification/2026-10-09-preset-owned-subagent-composition.i18n.yaml b/.agents/notes/implemented/simplification/2026-10-09-preset-owned-subagent-composition.i18n.yaml new file mode 100644 index 0000000000..4b3621d217 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-10-09-preset-owned-subagent-composition.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-09-preset-owned-subagent-composition.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/simplification/2026-10-09-preset-owned-subagent-composition.md +/agent-note-preset-owned-subagent-composition: + en: 08d7745426af0373 + zh: 26f9afb3cc941a9a +/agent-note-preset-owned-subagent-composition/problem: + en: 97cd4f941fe8eaa5 + zh: b3dabbd7020a8991 +/agent-note-preset-owned-subagent-composition/decision: + en: 7dfefd4689562847 + zh: 0bbfd0a8ce41c9ac +/agent-note-preset-owned-subagent-composition/alternatives-considered: + en: c87c4638a36cc45d + zh: ee2c8e044108f0eb +/agent-note-preset-owned-subagent-composition/consequences: + en: a7404d17d0a62ad9 + zh: 783a490d3aafc5ca diff --git a/.agents/notes/implemented/simplification/2026-10-09-preset-owned-subagent-composition.md b/.agents/notes/implemented/simplification/2026-10-09-preset-owned-subagent-composition.md new file mode 100644 index 0000000000..88f2b5ab9d --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-10-09-preset-owned-subagent-composition.md @@ -0,0 +1,31 @@ +# Agent Note: Preset-owned subagent composition + +Status: implemented + +English | [中文](2026-10-09-preset-owned-subagent-composition.zh.md) + +## Problem + +Agent Presets already compose persona and tool plugins. Independent child persona and tool-filter inputs create a second place to configure that composition. The shipped consumers of child filtering are the six schedule deny lists in the spawn and fork rows of the standard, PTC, and Cordis presets; reminder executors already refuse delegated callers. + +## Decision + +New subagent requests select an Agent Preset where the provider supports it. Persona and tools come from its plugin list. Fork inherits the parent's preset revision; model and effort selection keep their existing configuration. No preset-level filter or finer plugin split is added without a concrete consumer. + +`dsh-tool-subagent` rejects removed `persona` and `toolFilter` keys at load, including empty values, because deleting Schemastery fields alone does not reject unknown configuration. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.md) states the lost independent override capability and the migration. + +Released child descriptors keep their persona and filter fields, parsing, and cold-resume application. The [original composition note](../feature/2026-07-12-subagent-persona-tool-filter-and-depth.md) remains active for these historical semantics and the independent depth policy. The [spawn preset decision](../feature/2026-09-20-spawn-agent-preset-selection.md) continues to own selection and restoration identity. + +The shipped child schedule deny lists are absent. Reminder schemas remain visible when inherited from the preset; each executor rejects delegated callers. This avoids that source of parent/fork schema differences. Children receive four reminder schemas whose executors always refuse them. Neither their prompt cost nor a provider cache-hit improvement has been measured; other request inputs can still differ. + +## Alternatives considered + +**Move the filter into each preset.** This preserves the schedule deny lists and independent fork tool trimming, but retains two configuration mechanisms for tool availability. New children use plugin composition; fork deliberately inherits the parent's tools. + +**Keep per-request overrides alongside presets.** This retains independent fork overrides, their precedence rules, and provider capability flags. A single composition mechanism is preferred over that flexibility for new children. + +**Delete historical descriptor fields with the request fields.** This would change or reject restored sessions. New-request simplification does not authorize rewriting released Session data. + +## Consequences + +Preset selection owns new child persona and tools. Fork cannot independently replace persona or trim inherited tools, and JavaScript configuration with the removed keys fails explicitly. Historical restoration retains its previous semantics. Focused tests cover removed-key diagnostics, historical persona/filter restoration, inherited reminder schemas and executor refusal; recorded sessions cover preset-owned tool availability, fork reminder refusals, and messaging guidance. diff --git a/.agents/notes/implemented/simplification/2026-10-09-preset-owned-subagent-composition.zh.md b/.agents/notes/implemented/simplification/2026-10-09-preset-owned-subagent-composition.zh.md new file mode 100644 index 0000000000..c81919e7d8 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-10-09-preset-owned-subagent-composition.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 由 preset 拥有 subagent 组装 + +Status: implemented + +[English](2026-10-09-preset-owned-subagent-composition.md) | 中文 + +## 问题 + +Agent Preset 已经组合 persona 和工具插件。独立的子级 persona 和工具过滤输入又增加了一处组装配置。已交付的子级过滤消费者是 standard、PTC 和 Cordis preset 中 spawn 与 fork 配置行的六份 schedule deny 列表;提醒执行器已经拒绝委派调用方。 + +## 决策 + +新 subagent 请求在提供方支持时选择 Agent Preset。persona 和工具来自其插件列表。fork 继承父级的 preset 代际;model 和 effort 选择保留现有配置。没有具体消费者时,不添加 preset 级过滤器或更细的插件拆分。 + +`dsh-tool-subagent` 在加载时拒绝已删除的 `persona` 和 `toolFilter` 键,包括空值,因为仅删除 Schemastery 字段不会拒绝未知配置。[升级指南](../../../../docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.zh.md)说明失去的独立覆盖能力及迁移方法。 + +已发布的子级 descriptor 保留 persona 和 filter 字段、解析及冷恢复应用。[原组装记录](../feature/2026-07-12-subagent-persona-tool-filter-and-depth.zh.md)继续保留,以说明这些历史语义及独立的深度策略。[spawn preset 决策](../feature/2026-09-20-spawn-agent-preset-selection.zh.md)继续拥有选择与恢复身份的依据。 + +已交付配置中不含子级 schedule deny 列表。从 preset 继承的提醒 schema 仍然可见;每个执行器拒绝委派调用方。这消除了一处父级与 fork 子级 schema 差异的来源。子级会收到四个始终拒绝其调用的提醒 schema;尚未测量它们的提示成本或提供方缓存命中率改善,其他请求输入仍可能不同。 + +## 曾考虑的替代方案 + +**把过滤器移入各 preset。** 这保留了 schedule deny 列表和独立裁剪 fork 工具的能力,但仍有两种配置工具可用性的机制。新子级使用插件组装;fork 明确继承父级工具。 + +**在 preset 之外保留逐请求覆盖。** 这保留独立的 fork 覆盖、覆盖优先级规则和提供方能力标志。对新子级选择单一组装机制,放弃这项灵活性。 + +**随请求字段一起删除历史 descriptor 字段。** 这会改变或拒绝恢复的会话。简化新请求不意味着可以重写已发布的 Session 数据。 + +## 后果 + +preset 选择拥有新子级的 persona 和工具。fork 不能独立替换 persona 或裁剪继承工具,含已删除键的 JavaScript 配置会明确报错。历史恢复保留原有语义。针对性测试覆盖删除键的诊断、历史 persona/filter 恢复、继承的提醒 schema 及执行器拒绝;会话录制覆盖由 preset 控制的工具可用性、fork 提醒拒绝及消息指引。 diff --git a/.agents/notes/implemented/testing/2026-09-14-desktop-installed-update-materials.i18n.yaml b/.agents/notes/implemented/testing/2026-09-14-desktop-installed-update-materials.i18n.yaml index e5f30837c8..9f7d9ba29e 100644 --- a/.agents/notes/implemented/testing/2026-09-14-desktop-installed-update-materials.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-09-14-desktop-installed-update-materials.i18n.yaml @@ -9,8 +9,8 @@ en: 8d63b992ff6d3161 zh: 86d333255a5400d3 /agent-note-isolate-installed-update-materials-from-releases-and-user-data/decision: - en: 815a1c062134d958 - zh: 05d7d89099e6911c + en: 4b2464efa4292cfd + zh: 449d6ea0d903d7e7 /agent-note-isolate-installed-update-materials-from-releases-and-user-data/alternatives-considered: en: c608f186cc94a9d3 zh: 39750c8347e8bece diff --git a/.agents/notes/implemented/testing/2026-09-14-desktop-installed-update-materials.md b/.agents/notes/implemented/testing/2026-09-14-desktop-installed-update-materials.md index 24209c1cce..88129f2cc2 100644 --- a/.agents/notes/implemented/testing/2026-09-14-desktop-installed-update-materials.md +++ b/.agents/notes/implemented/testing/2026-09-14-desktop-installed-update-materials.md @@ -10,7 +10,7 @@ An installed-update walkthrough needs two increasing versions with a shared appl ## Decision -Version derivation follows the [release version reference](../../../../apps/desktop/README.md); this record continues to govern material, application identity, and user-data isolation. +Version derivation follows the [release version reference](../../../../apps/desktop/packaging/README.md#release-versions); this record continues to govern material, application identity, and user-data isolation. The [material preparer](../../../../apps/desktop/scripts/prepare-installed-update-runtime.ts) accepts a retained test-only manifest with a random identity and distribution namespace. It copies a verified source runtime into separate derived test versions, changes only release-family versions and matching dependency references, and seals and verifies both inventories. The original runtime is verified again and its descriptor hash must remain unchanged. Existing output directories are not overwritten; a failed copy retains a failure record and cannot create a completion receipt. diff --git a/.agents/notes/implemented/testing/2026-09-14-desktop-installed-update-materials.zh.md b/.agents/notes/implemented/testing/2026-09-14-desktop-installed-update-materials.zh.md index 22ceec3f7b..d0f9aa2bae 100644 --- a/.agents/notes/implemented/testing/2026-09-14-desktop-installed-update-materials.zh.md +++ b/.agents/notes/implemented/testing/2026-09-14-desktop-installed-update-materials.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -版本派生遵循[发布版本说明](../../../../apps/desktop/README.zh.md);本记录继续规定物料、应用身份和用户数据的隔离。 +版本派生遵循[发布版本说明](../../../../apps/desktop/packaging/README.zh.md#release-versions);本记录继续规定物料、应用身份和用户数据的隔离。 [物料准备器](../../../../apps/desktop/scripts/prepare-installed-update-runtime.ts)接受保留的 test 专用清单,其中包含随机身份和分发命名空间。它将已验证的原始运行时复制为独立的派生测试版本,仅修改发布家族版本和匹配的依赖引用,再生成并验证两个完整性清单。原始运行时再次验证,其描述文件哈希必须保持不变。已有输出目录不被覆盖;复制失败保留失败记录,不能生成完成回执。 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..b25c6213ba --- /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: 29b8f8c1ad73c77b + zh: 8293b21ec08d3896 +/agent-note-linear-credential-matching-and-performance-gates-for-user-text/alternatives-considered: + en: 7600c1671b5dc73c + zh: b38e3ae76a5a32d1 +/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..b8bcd21b3a --- /dev/null +++ b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.md @@ -0,0 +1,70 @@ +# 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 | Ten unmeasured pairs warm each workload with the same evaluation count as measured pairs. Five measured pairs alternate baseline-first and matcher-first order; each evaluation builds a fresh registry, document, and matcher instance and times evaluation only. A single-document sample averages twenty evaluations; a 5,000-message sample evaluates the batch once. Each side selects its minimum sample mean, with the mean process CPU time from that sample. The worker JSON in CI logs includes every measured pair and averaging count; the HTML report shows the selected with-credential mean. Registry disposal completes outside the timer before the next evaluation, preventing cleanup and retained registries from accumulating. Warm-up retains no matcher memo | +| 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 | Cold code compilation, 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. + +The reference constants are calibrated for minima of five single evaluations. Minimum-of-five sample means use the existing absolute headroom without recalibration. Averaging can move the ratio of independently selected minima in either direction; a threefold matcher-work negative control verifies that the JSON ratio limit still rejects extra scanning. + +## Alternatives considered + +- **Unwarmed, separate baseline and matcher batches**: sub-millisecond baseline measurements can reach optimized code before the matcher’s newly exercised paths do, and separate batches amplify clock-speed drift. Per-workload warm-up, adjacent pairs, and fixed batches compare warmed code while limiting noise in short intervals and preserving fresh documents and matcher state. +- **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..96307eb19b --- /dev/null +++ b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.zh.md @@ -0,0 +1,70 @@ +# 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` 密钥。对抗:针对每种格式的前缀、长度与分隔规则构造的重复输入,两种长度。全部由常量生成,凭据样本运行时拼接 | +| 计时 | 每个负载先用十组未计入结果的配对预热,每组的求值次数与测量配对相同。五组测量交替以基线或凭据匹配器开头;每次求值新建注册表、文档和匹配器实例,只计求值。单文档样本取二十次求值的平均值,5,000 条消息的样本则整批求值一次。两侧各取样本均值的最小值,并保留对应样本的平均进程 CPU 时间。CI 日志中的 worker JSON 包含全部测量配对和求平均值的次数,HTML 报告展示选中的带凭据匹配器均值。每次求值在计时结束后等待注册表清理完成,再开始下一次,避免清理工作和未释放注册表积累。预热不保留匹配器记忆 | +| 分配 | 单独进程,`--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)),并对每个查询起点单独比较。 + +参考常量按五次单独求值的最小值校准;五组样本均值的最小值使用既有绝对耗时余量,不重新校准。求平均值可能使两侧独立最小值的比值向任一方向变化;将匹配器工作量增至三倍的负对照验证 JSON 比值上限仍能拒绝额外扫描。 + +## 考虑过的替代方案 + +- **不预热、分批测量基线和匹配器**:亚毫秒基线测量可能先进入优化后的代码,而匹配器新触及的路径还未完成优化;分批测量也会放大时钟频率漂移。逐负载预热、相邻配对和固定批次比较预热后的代码,降低短区间测量的噪声,同时保持文档和匹配器状态全新。 +- **每次查询对每个格式各跑一个带量词的正则**:没有命中的正则每次都扫到文末,凭据多时平方增长;长度量词在失败时回溯。 +- **把全部格式合成一个带量词的大正则**:一次扫描能找到最左匹配,但各分支的量词失败时仍回溯。 +- **先找稀有字符再回看前缀**:普通文本扫描更快,但成本取决于字符分布,`-`、`_` 密集的文本明显变慢。 +- **纯 JavaScript 的 Aho–Corasick 自动机**:可以零分配,但逐字符查表有状态依赖,比原生字面量扫描慢,最常见的无凭据文本反而变慢。 +- **每次查询新建记忆**:被接受的 token 之间夹着无数字的 `sk-` 时,每次查询的数字查找都扫到文末,平方增长。 +- **用 `TextDecoder` 从缓冲区一次生成私钥遮挡串**:每块只分配一个字符串,但每次解码的固定开销高于共享串切片。 +- **用 `exec` 取命中、用 `for…of` 遍历记忆槽**:分别分配匹配数组和迭代器结果。 + +## 影响 + +- 无凭据文本的额外成本是一遍原生扫描加字面量处的校验;不依赖字符分布就无法再降。 +- 新增格式要在格式表里加字面量和只向前的校验;续扫位置与命中识别表自动生成。字面量正则的单测拒绝量词,benchmark 拒绝超线性扫描和多余分配。 +- 匹配器实例由插件在 `apply` 中创建并持有;测试和 benchmark 每个样本新建实例,不共享记忆。 diff --git a/.agents/notes/proposed/architecture/2026-09-20-unified-typert-remote-metadata.i18n.yaml b/.agents/notes/proposed/architecture/2026-09-20-unified-typert-remote-metadata.i18n.yaml new file mode 100644 index 0000000000..e780a00501 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-09-20-unified-typert-remote-metadata.i18n.yaml @@ -0,0 +1,34 @@ +# Bilingual-pair consistency record for 2026-09-20-unified-typert-remote-metadata.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/proposed/architecture/2026-09-20-unified-typert-remote-metadata.md +/agent-note-unified-typert-remote-metadata: + en: 463246d8c8732192 + zh: cdb9f8ca8cfe4635 +/agent-note-unified-typert-remote-metadata/problem: + en: 3aa575e4c0778df1 + zh: 5277fc49b040da50 +/agent-note-unified-typert-remote-metadata/technical-architecture: + en: eb12e56cdcc7c76b + zh: bebff68d354c1ba7 +/agent-note-unified-typert-remote-metadata/proposal: + en: f5dcecbcae90a898 + zh: 923cf3a3074a3a2d +/agent-note-unified-typert-remote-metadata/proposal/shared-generation-two-access-modes: + en: 733398b2346d7438 + zh: d4e827b9dbd16d67 +/agent-note-unified-typert-remote-metadata/proposal/downstream-migration-targets: + en: 261dab3eb480a0c0 + zh: 13c3226d316d8d5e +/agent-note-unified-typert-remote-metadata/proposal/paired-usage-examples: + en: 7ef7dd38e2015801 + zh: b97cd179bf828406 +/agent-note-unified-typert-remote-metadata/alternatives-considered: + en: 151b1f66af030bc5 + zh: 44fea0898acfbdcb +/agent-note-unified-typert-remote-metadata/acceptance-criteria: + en: d011ec1516706b20 + zh: 945c6e3eba101368 +/agent-note-unified-typert-remote-metadata/risks: + en: a770478eac8f5fd1 + zh: f24aa378f875f47f diff --git a/.agents/notes/proposed/architecture/2026-09-20-unified-typert-remote-metadata.md b/.agents/notes/proposed/architecture/2026-09-20-unified-typert-remote-metadata.md new file mode 100644 index 0000000000..c99fd9effd --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-09-20-unified-typert-remote-metadata.md @@ -0,0 +1,191 @@ +# Agent Note: Unified Typert/Remote metadata + +Status: proposed + +English | [中文](2026-09-20-unified-typert-remote-metadata.zh.md) + +## Problem + +CLI help, argument parsing, and MCP tool discovery need local method descriptions, named-input parsers, tool JSON Schemas, and result metadata before connecting to a controlled Host. Browser, Node, and independent consumers also need typed invocations. Tool consumers need stricter input-object validation without changing ordinary Host dispatch. These requirements do not imply runtime TypeScript analysis, Host Service activation, or another business schema maintained by each consumer. + +The original #4644 source-definition decision delivered this information through `emitSourceDef`, committed generated files, and `./remote-source`. Host bindings carried those definitions; source generation had its own inventory, freshness, publication, and exclusion rules. This note replaces that delivery mechanism and makes input strictness consumer-owned. + +Both delivery paths derive from the same [compiler-independent model](../../implemented/architecture/2026-07-27-compiler-independent-typert-model.md). Separate Host and Client Programs require generated cross-face declarations, not committed generated source. An explicit prebuild is acceptable when exact schemas are needed; ordinary ESM artifacts can supply offline metadata without a live Host. The [targeted-call decision](../../implemented/architecture/2026-08-02-typert-remote-method-calls.md) still owns receiver lookup, Gateway dispatch, and contribution lifetimes. + +## Technical architecture + +| Export | Responsibility | Registration | +|---|---|---| +| Host `./typert` | `TYPERT`: local reflection, schemas, and an `invocations` getter exposing a private info instance's descriptors. | Loader imports and validates the contribution, then calls `ctx.typert.register(TYPERT)`. | +| Host-for-consumer `./remote` | Default export and `TYPERT_REMOTE`: a `TypertRemoteInfo` with descriptors and typed `methods`, plus generated Remote declarations/maps. | Harness metadata consumers call `ctx.typert.remotes.register(TYPERT_REMOTE)`; live consumers use `ctx.remote.$mount(TYPERT_REMOTE)`, which already registers it. Independent readers need no Registry. | +| Client `./client/typert` | The Client face's own local reflection and schemas. | Its local Registry; this is not the Host Remote projection. | + +[Registry](../../../../packages/typert/registry/src/service.ts) instances belong to their Cordis Context and process. Host and Client entries share implementation, not state. Existing local/Remote `get()` and `list()` preserve the registered descriptor objects; registration retains atomic duplicate checks, notifications, tombstones, and fiber-owned disposal. No Registry API, store, subscription, metadata RPC, or cross-process synchronization is added. Separate Programs and processes do not share object identity. + +The [emitter](../../../../packages/typert/generator/src/emitter.ts) writes one static `TypertRemoteMethodSpec` per endpoint and calls `createTypertRemoteInfo({ package, methods }, z)` from the published pure `@deepseek-ai/dsh-typert-protocol/remote-info` entry. The endpoint key supplies `namespace` and `method`, and `id` combines it with the package. Each spec keeps the service, receiver, ordered parameters, single `result` codec, and optional stream, scope, uplink, cancellation, documentation, and source-location fields. Every parameter has both `codec` and `strictCodec` from the same checker-resolved type model, with no per-method policy in the analyzer or model. Parameter `wire` defaults to `name`; parameter documentation stays on `parameters[].description`. There is no nested `metadata`, separate `output` or `parameterDescriptions`, or top-level `REMOTE_METHODS` export. + +The [factory](../../../../packages/typert/protocol/src/remote-info.ts) returns an actual class instance, not a class constructor or eager object literal. Construction retains only the spec and the Zod runtime explicitly supplied by the generated artifact, without constructing schemas. The first `descriptors` or `methods` read, including mounting or querying, builds and caches one shared index. Each `methods[endpoint]` aliases the exact direct descriptor object; Context-only receivers remain in descriptors and scoped declarations. Direct methods with scoped projections retain their scope fields but their generic named invoker requires an unscoped Remote. + +A direct method's `input(options?: TypertRemoteInputOptions)` returns a cached `TypertRemoteValue`; `strict?: boolean` is the only option. `method.input()` and `{ strict: false }` use normal codecs: declared objects accept and strip unknown fields. `{ strict: true }` rejects undeclared fields recursively. Both named-argument envelopes reject extra arguments; explicit JSON and dictionary keys stay open, and constrained dictionary values still validate. Consumers select one view for matching `input.create().parse(raw)` and `input.jsonSchema`. Host dispatch and the single `result` codec retain normal behavior, including binary `encode`/`decode`. + +Each input-policy view, its named parser, and its JSON Schema projection are independently lazy and cached. Individual generated Zod factories are also lazy and success-cached. The raw spec requires Zod factories internally, while consumer-facing `TypertSchema` promises only `parse(value: unknown): T`. JSON Schema remains an optional generator projection, not runtime `z.toJSONSchema()` conversion. Generated artifacts import and supply Zod, including Remote endpoints without parameters or exported schemas. The pure leaf retains only Zod type imports and has no runtime module dependencies; the protocol root re-exports the factory and imports Cordis without adding Zod to every protocol consumer's static module graph. Imports and metadata/schema access never invoke the network. + +Registry queries return base descriptors. `isTypertRemoteMethod(descriptor)` from the pure leaf or protocol root narrows direct capabilities with `object`/`unknown` types; exact endpoint types come from `TYPERT_REMOTE.methods`, not dynamic lookup. Unary `mode` is omitted; streaming `mode` is `'stream'`. `invoke(remote, input, signal?)` resolves the mounted namespace method at call time, preserving its `this`, optional positional holes, and signal. It forwards the same full `Promise>` or `RemoteStreamHandle` without an async wrapper; stream iteration, `send`, `end`, and `dispose` remain available. The fifth `TypertRemoteMethod` generic retains the carrier-decoded unary byte type independently of the result parser's authored output. + +Documentation and JSON Schema are optional. Each unsupported input variant or result projection records its own `jsonSchemaError` while preserving parsers and independent documentation; only the dedicated projection error is caught. A consumer explicitly selecting a tool requires its description and supported input JSON Schema. Output parsing remains required even when optional output JSON Schema is absent. Native `dsh-tools` registration additionally requires `output.schema`: a parser alone does not satisfy it. These consumer requirements must not prevent an otherwise valid Remote method from being generated. + +## Proposal + +Complete the ordinary-artifact migration in the downstream Session-client, CLI, MCP, and native-tool packages. This note remains proposed because that migration is not complete. + +### Shared generation, two access modes + +Framework consumers load ordinary metadata into their own Registry. Independent consumers may import `./remote` directly without Cordis, Host Service activation, or a connection. Both read the same generated business definition. Keep separate Host/Client Programs and analyze all contributors of each face so focused emission retains external declaration augmentations. Registration does not expose every reflected method as a callable endpoint or tool. + +Strict source startup explicitly prebuilds and loads ordinary `./typert` through Loader. Limited descriptor-free fallback still supports basic arguments, signals, cancellation, streams, JSON conversion, and unary byte attachments, but cannot recover erased fields, constraints, or tool documentation. Once a strict local descriptor has been observed, its withdrawal must refuse invocation rather than downgrade to fallback. `@Remote` accepts only `name` and `mode`; consumers choose input policy without a separate developer annotation. + +Host metadata readiness remains composition-owned. A Host requiring strict validation must await local registration before serving calls; `hasSeen()` does not protect an endpoint before its first registration. Returning a lazy info instance neither completes asynchronous Loader discovery nor establishes readiness. Loader validates static codec specs and callable `input`/`invoke` without calling the selector, parser factories, or projections to register a contribution. + +### Downstream migration targets + +The inspected #4111 tree contains Session-client, CLI, MCP, and native-tool consumers that are not present as complete packages on this branch. Its Session client selects 13 Session methods plus Workspace listing from source exports. Migrating that tree requires updating selection, connection-time mounts, offline CLI initialization, MCP presentation, and native-tool registration together; deleting source exports alone is insufficient. + +| Consumer | Metadata adaptation | Execution retained | +|---|---|---| +| Browser / Node Remote callers | Import ordinary `./remote`; mount once in the live Context. | Generated namespaces, Gateway, authenticated Connection, and target controllers. | +| Offline CLI help / parsing | Register before target discovery in the CLI profile's metadata Context; select `input({ strict: true })`. | No connection for help; a separate live Context mounts when calling. | +| MCP discovery / calls | Read selected Registry entries with `input({ strict: true })`; retain consumer-owned tool descriptions and envelopes. | `tools/list` is offline; `tools/call` uses the same Session client. External MCP clients receive protocol JSON, not Registry modules. | +| Native tools | Read Host local method info; require the tool registration's `output.schema`. | Parse at the tool boundary, then call same-process controllers directly. | +| Independent adapters | Read typed `TYPERT_REMOTE.methods` directly. | Use their chosen Remote runtime only when invoking. | + +Current-session selection and attachment preparation remain consumer-owned; CLI/MCP intake validates completed business arguments with the same strict input view used during selection. The downstream `follow` adapter's `activate: false` policy applies where that API exists; this branch's current `follow` has no such option. Aborting observation does not cancel accepted Session work. + +### Paired usage examples + +The old examples are historical comparisons of source-export consumers in the dependent changes. The new examples use ordinary artifacts. These fragments omit surrounding plugin declarations and include removed APIs. `raw`, `request`, `signal`, and an authenticated, mounted, unscoped `remote` are caller inputs, not new framework APIs. + +**Operation owner and strict Host.** Preserve the business signature; leave generated registration to ordinary Typert Loader instead of the Service constructor. + +```text +// Old source delivery. +import { TYPERT_REMOTE } from './remote.generated.ts' +// Constructor: super(ctx, 'sessionController', { namespace: 'session', definitions: TYPERT_REMOTE }) +@Remote({ name: 'page', emitSourceDef: true, rejectUnknownFields: true }) +page(request: SessionPageRequest, signal: AbortSignal): Promise { + return this.history.page(request, signal) +} + +// Ordinary delivery; no generated-source import or constructor definitions. +// Constructor: super(ctx, 'sessionController', { namespace: 'session' }) +@Remote({ name: 'page' }) +page(request: SessionPageRequest, signal: AbortSignal): Promise { + return this.history.page(request, signal) +} +``` + +**Browser and Node invocation.** A source-export consumer changes `/remote-source` to `/remote`; existing ordinary consumers already use this path. The live Context mounts once, without separate Registry registration. + +```text +import { TYPERT_REMOTE } from '@deepseek-ai/dsh-api-session-controller/remote' +await ctx.remote.$mount(TYPERT_REMOTE) +const result = await ctx.remote.session.page(request, signal) +const stream = ctx.remote.session.follow(followRequest, signal) +try { + for await (const frame of stream) consume(frame) +} finally { + await stream.dispose() +} +``` + +**Offline CLI and framework metadata.** The old selection reads a source table; the replacement reads the profile-owned Registry before target discovery. The two snippets are alternatives, not simultaneous declarations. + +```text +// Old selection. +import { REMOTE_METHODS } from '@deepseek-ai/dsh-api-session-controller/remote-source' +const page = REMOTE_METHODS['session/page'] +``` + +```text +// Metadata plugin: inject: ['typert']; no Gateway, Connection, or Host controller. +import { TYPERT_REMOTE } from '@deepseek-ai/dsh-api-session-controller/remote' +import { isTypertRemoteMethod } from '@deepseek-ai/dsh-typert-protocol/remote-info' +ctx.typert.remotes.register(TYPERT_REMOTE) +const page = ctx.typert.remotes.get('session/page') +if (page === undefined || !isTypertRemoteMethod(page)) { + throw new Error('session/page generated direct method is not loaded') +} +``` + +The registration belongs to that plugin's fiber. Help uses `description` and `input({ strict: true })`; the typed facade can retain type-only imports from ordinary generated declarations. Explicit tool selection does not mutate registered metadata. + +**CLI input and dispatch.** After local `current` resolution and attachment preparation, either metadata access path uses the same invocation sequence: + +```text +if (page.mode === 'stream') throw new Error('session/page must be unary') +const input = page.input({ strict: true }) +const arguments_ = input.create().parse(raw) +const result = await page.invoke(remote, arguments_, signal) +if (!result.ok) throw result.error +const output = page.result.create().parse(result.value) +``` + +**MCP discovery and calls.** Selection validates tool-specific requirements; generation itself does not require them. + +```text +const input = page.input({ strict: true }) +if (!page.description) throw new Error('session/page has no tool description') +if (input.jsonSchema === undefined) throw new Error('session/page has no supported tool input schema') +const tool = { + name: 'remote_session_page', + description: page.description, + inputSchema: input.jsonSchema, + ...(page.result.jsonSchema === undefined ? {} : { outputSchema: page.result.jsonSchema }), +} +``` + +This compact object shows only the metadata dependency. The real MCP adapter retains its `{ arguments, current, content }` input and `{ ok, value }` / failure output envelopes. Listing requires no connection; calling performs intake, local preparation, parsing through `input.create()`, invocation, and output parsing. Optional output projection does not remove output validation. + +**Native tools.** Query `ctx.typert.local.get('session/page')` and narrow it with `isTypertRemoteMethod` instead of reading the source table. Native tools can select `method.input({ strict: true })` for matching parsing and input projection. Native registration still requires supported input and result projections, including core Tool's mandatory `output.schema`; optional MCP output projection is not sufficient here. Once the facade obtains a typed request, both designs execute the same local call: + +```text +const value = await ctx.sessionController.page(request, signal) +``` + +**Independent consumers.** Read the ordinary info instance's typed index; no Registry is required: + +```text +import { TYPERT_REMOTE } from '@deepseek-ai/dsh-api-session-controller/remote' +const page = TYPERT_REMOTE.methods['session/page'] +const arguments_ = page.input().create().parse(raw) +const result = await page.invoke(remote, arguments_, signal) +``` + +**Strict source startup.** Build ordinary artifacts, then use the supported source launcher: + +```sh +pnpm run build +pnpm dsh --profile +``` + +## Alternatives considered + +- **Committed source:** meets offline needs but adds a redundant delivery and maintenance path; explicit ordinary prebuild is sufficient. +- **Nested descriptor metadata and a separate method table:** duplicate result and parameter facts and add another identity to track. One spec derives direct helpers on the descriptor itself; `TypertRemoteInfo` extends the existing contribution and retains `descriptors` so Gateway and Registry keep their current registration APIs. +- **Mandatory Registry for every importer:** adds lifecycle requirements without information for standalone consumers. +- **Fallback only:** cannot supply erased validation or tool documentation; retain it only for its supported subset. +- **Handwritten adapter schemas or runtime TypeScript analysis:** duplicate ownership or introduce runtime compiler requirements already handled by build-time extraction. + +## Acceptance criteria + +- Ordinary artifacts emit one static method spec per endpoint and return lazy class instances; direct method indexes alias descriptor objects, with full stream/binary typing, separate compiler faces, and full-face augmentation retention. +- Descriptor indexes and each input-policy view, parser, and projection are independently lazy and cached; Loader validates static specs and callable helpers without calling selectors, parsers, or projections. +- Every input parameter emits normal and strict codecs from the same model; consumers select policy without a method annotation. Both envelopes reject extra named arguments; strict input recursively closes declared objects without closing JSON or dictionary keys or changing Host dispatch and results. +- Protocol source and built entries have no Zod runtime dependency; generated artifacts explicitly supply Zod, zero-argument endpoints create empty inputs that reject extra fields, and the [production headless-profile Loader regression](<../../../../packages/context/time-context/tests/time-context.e2e.ts>) asserts actual Session events. +- Registry identity, atomic registration, withdrawal, and disposal remain intact. +- Missing documentation or unsupported optional projection does not disable generation; selected tools reject missing requirements and still parse outputs. +- Strict source/artifact invocation and limited fallback have separate tests; a withdrawn strict descriptor never enables fallback. +- Source static checks do not consume stale generated declarations; artifact checks declare and rebuild their inputs. No source-definition opt-in, source export, inventory, or freshness rule remains in production. + +## Risks + +Full downstream profile composition remains follow-up work in those packages; the generated metadata is not evidence that every #4111 operation or CLI/MCP application has migrated. The deliberate trade-off is an explicit prebuild for full source-runtime metadata. Missing or stale artifacts require regeneration, not a validation downgrade or a second handwritten schema. diff --git a/.agents/notes/proposed/architecture/2026-09-20-unified-typert-remote-metadata.zh.md b/.agents/notes/proposed/architecture/2026-09-20-unified-typert-remote-metadata.zh.md new file mode 100644 index 0000000000..9370060e1e --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-09-20-unified-typert-remote-metadata.zh.md @@ -0,0 +1,191 @@ +# Agent Note: 统一 Typert/Remote 元数据 + +Status: proposed + +[English](2026-09-20-unified-typert-remote-metadata.md) | 中文 + +## Problem + +CLI 帮助、参数解析和 MCP 工具发现需要在连接受控 Host 前取得本地方法说明、具名输入解析器、工具 JSON Schema 和结果元数据。Browser、Node 与独立消费方还需要类型化调用。工具消费方需要更严格的输入对象校验,但不能改变普通 Host 分发。这些需求不意味着运行时 TypeScript 分析、Host Service 激活,或每个消费方另行维护业务 schema。 + +#4644 原有的源码定义决策通过 `emitSourceDef`、提交的生成文件和 `./remote-source` 交付这些信息;Host 绑定携带定义,源码生成另有清单、新鲜度、发布和排除规则。本 note 替代该交付机制,并将输入严格性改为由消费方选择。 + +两种交付路径均来自同一个[编译器无关模型](../../implemented/architecture/2026-07-27-compiler-independent-typert-model.zh.md)。独立的 Host 与 Client Program 要求生成跨编译面声明,而非提交生成源码。需要精确 schema 时,显式预构建是可接受的;普通 ESM 产物无需运行中的 Host 即可提供离线元数据。[定向调用决策](../../implemented/architecture/2026-08-02-typert-remote-method-calls.zh.md)仍负责接收者查找、Gateway 分发和贡献生命周期。 + +## 技术架构 + +| 导出 | 职责 | 注册方式 | +|---|---|---| +| Host `./typert` | `TYPERT`:本地反射、schema,以及暴露私有 info 实例描述符的 `invocations` getter。 | Loader 导入并验证 contribution,再调用 `ctx.typert.register(TYPERT)`。 | +| 面向消费方的 Host `./remote` | 默认导出和 `TYPERT_REMOTE`:带有描述符和类型化 `methods` 的 `TypertRemoteInfo`,以及生成的 Remote 声明/映射。 | Harness 元数据消费方调用 `ctx.typert.remotes.register(TYPERT_REMOTE)`;实际调用方使用 `ctx.remote.$mount(TYPERT_REMOTE)`,它已经包含注册。独立读取方无需 Registry。 | +| Client `./client/typert` | Client 编译面自己的本地反射与 schema。 | 本地 Registry;这不是 Host Remote 投影。 | + +[Registry](../../../../packages/typert/registry/src/service.ts) 实例属于各自的 Cordis Context 和进程。Host 与 Client 入口共享实现,而非状态。既有本地/Remote `get()` 与 `list()` 保留已注册的描述符对象;注册保留原子重复检查、通知、tombstone 和 fiber 管理的释放。不新增 Registry API、存储、订阅、元数据 RPC 或跨进程同步。独立 Program 和进程不共享对象身份。 + +[发射器](../../../../packages/typert/generator/src/emitter.ts)为每个端点写入一份静态 `TypertRemoteMethodSpec`,并调用已发布纯入口 `@deepseek-ai/dsh-typert-protocol/remote-info` 提供的 `createTypertRemoteInfo({ package, methods }, z)`。端点键提供 `namespace` 和 `method`,`id` 由包名与端点键组合。每份 spec 保留 service、接收者、有序参数、唯一的 `result` codec,以及可选的流模式、scope、uplink、取消、文档和源码位置字段。每个参数都有从同一 checker 解析后类型模型派生的 `codec` 和 `strictCodec`,分析器与模型不携带逐方法策略。参数 `wire` 默认使用 `name`;参数文档保留在 `parameters[].description`。不存在嵌套 `metadata`、独立 `output` 或 `parameterDescriptions`,也不导出顶层 `REMOTE_METHODS`。 + +[factory](../../../../packages/typert/protocol/src/remote-info.ts)返回真正的类实例,而非类构造函数或立即求值的对象字面量。构造时只保留 spec 和生成产物显式传入的 Zod 运行时,不构造 schema。首次读取 `descriptors` 或 `methods` 时(包括挂载或查询时)才构建并缓存一个共享索引。每个 `methods[endpoint]` 就是同一个直接方法描述符对象;仅使用 Context 接收者的方法保留在描述符和作用域声明中。带作用域投影的直接方法保留 scope 字段,但其通用具名调用器要求无作用域 Remote。 + +直接方法的 `input(options?: TypertRemoteInputOptions)` 返回缓存的 `TypertRemoteValue`;唯一选项是 `strict?: boolean`。`method.input()` 与 `{ strict: false }` 使用普通 codec:已声明对象接受并剥离未知字段。`{ strict: true }` 递归拒绝未声明字段。两种具名参数封装都拒绝额外参数;显式 JSON 与字典键保持开放,有约束的字典值仍然校验。消费方选择一个视图,通过 `input.create().parse(raw)` 与 `input.jsonSchema` 取得匹配的解析和投影。Host 分发与唯一的 `result` codec 保留普通行为,包括二进制 `encode`/`decode`。 + +每种输入策略的视图、具名解析器及 JSON Schema 投影都独立惰性求值并缓存。生成的独立 Zod factory 同样惰性求值且只缓存成功结果。原始 spec 内部要求 Zod factory,而面向消费方的 `TypertSchema` 只承诺 `parse(value: unknown): T`。JSON Schema 仍是可选的生成器投影,而非运行时 `z.toJSONSchema()` 转换。生成产物导入并传入 Zod,包括没有参数或导出 schema的 Remote 端点。纯叶入口只保留 Zod 类型导入,没有运行时模块依赖;协议根入口重新导出 factory 并导入 Cordis,但不会因此将 Zod 加入所有协议消费方的静态模块图。导入和元数据/schema 读取绝不发起网络调用。 + +Registry 查询返回基础描述符。纯叶入口或协议根入口的 `isTypertRemoteMethod(descriptor)` 以 `object`/`unknown` 类型收窄直接调用能力;精确端点类型来自 `TYPERT_REMOTE.methods`,而非动态查询。一元 `mode` 省略;流式 `mode` 为 `'stream'`。`invoke(remote, input, signal?)` 在调用时解析已挂载的命名空间方法,保留其 `this`、可选位置参数空位和 signal。它不使用 async 包装,直接转发同一个完整 `Promise>` 或 `RemoteStreamHandle`;流迭代、`send`、`end` 和 `dispose` 均保留。`TypertRemoteMethod` 的第五个泛型参数独立于结果解析器的原始输出,保留载体解码后的一元字节类型。 + +文档和 JSON Schema 可选。每个不受支持的输入变体或结果投影记录各自的 `jsonSchemaError`,同时保留解析器及独立文档;只捕获专用投影错误。显式选择工具的消费方要求工具说明和受支持的输入 JSON Schema。即使缺少可选输出 JSON Schema,输出解析仍然必需。原生 `dsh-tools` 注册额外要求 `output.schema`:仅有解析器并不满足要求。这些消费方要求不得阻止本来有效的 Remote 方法生成。 + +## Proposal + +在下游 Session-client、CLI、MCP 和原生工具包中完成普通产物迁移。本 note 保持 proposed,因为该迁移尚未完成。 + +### 共享生成,两种访问方式 + +框架消费方将普通元数据加载到自己的 Registry。独立消费方可以直接导入 `./remote`,无需 Cordis、Host Service 激活或连接。两者读取同一份生成业务定义。保留独立的 Host/Client Program,并分析每个编译面的所有贡献方,使局部生成保留外部声明合并。注册不会将每个反射方法都暴露为可调用 endpoint 或工具。 + +严格源码启动显式预构建,并通过 Loader 加载普通 `./typert`。有限的无 descriptor fallback 仍支持基本参数、signal、取消、流式调用、JSON 转换和一元字节附件,但无法恢复被擦除的字段、约束或工具文档。一旦观察到严格的本地 descriptor,撤销后必须拒绝调用,而不是降级到 fallback。`@Remote` 只接受 `name` 和 `mode`;消费方选择输入策略,无需另加开发者注解。 + +Host 元数据就绪仍由组合负责。要求严格校验的 Host 必须等待本地注册完成后再接受调用;`hasSeen()` 不会保护首次注册之前的端点。返回惰性 info 实例既不完成异步 Loader 发现,也不建立就绪保证。Loader 校验静态 codec spec 及可调用的 `input`/`invoke`,注册贡献时不调用选择器、解析器 factory 或投影。 + +### 下游迁移目标 + +已检查的 #4111 树包含 Session-client、CLI、MCP 和原生工具消费方,当前分支并不包含这些完整 package。其 Session client 从源码导出选择 13 个 Session 方法及 Workspace 列举。迁移该树需要一并更新选择、连接时挂载、离线 CLI 初始化、MCP 呈现及原生工具注册;仅删除源码导出并不足够。 + +| 消费方 | 元数据适配 | 保留的执行方式 | +|---|---|---| +| Browser / Node Remote 调用方 | 导入普通 `./remote`;在实际调用 Context 中挂载一次。 | 生成 namespace、Gateway、认证 Connection 和目标 controller。 | +| 离线 CLI 帮助 / 解析 | 在 CLI profile 的元数据 Context 中,于目标发现之前注册;选择 `input({ strict: true })`。 | 帮助不连接;调用时由独立的实际调用 Context 挂载。 | +| MCP 发现 / 调用 | 读取选中的 Registry 条目并选择 `input({ strict: true })`;保留消费方自有工具说明和 envelope。 | `tools/list` 离线;`tools/call` 使用相同 Session client。外部 MCP 客户端收到协议 JSON,而不是 Registry 模块。 | +| 原生工具 | 读取 Host 本地方法信息;要求工具注册的 `output.schema`。 | 在工具边界解析,然后直接调用同进程 controller。 | +| 独立适配器 | 直接读取类型化 `TYPERT_REMOTE.methods`。 | 仅调用时使用其选择的 Remote 运行时。 | + +当前 Session 选择和附件准备仍由消费方拥有;CLI/MCP 输入接收使用选择时的同一严格输入视图验证补全后的业务参数。下游 `follow` 适配器的 `activate: false` 策略只适用于具有该 API 的版本;当前分支的 `follow` 没有此选项。中止观察不等于取消已接受的 Session 工作。 + +### 新旧接入示例 + +旧示例是依赖改动中源码导出消费方的历史对照。新示例使用普通产物。这些片段省略外围插件声明,且包含已移除的 API。`raw`、`request`、`signal` 和已认证、已挂载、无作用域的 `remote` 是调用方输入,不是新增框架 API。 + +**操作拥有者与严格 Host。** 保留业务签名;将生成定义注册交给普通 Typert Loader,而非 Service 构造函数。 + +```text +// Old source delivery. +import { TYPERT_REMOTE } from './remote.generated.ts' +// Constructor: super(ctx, 'sessionController', { namespace: 'session', definitions: TYPERT_REMOTE }) +@Remote({ name: 'page', emitSourceDef: true, rejectUnknownFields: true }) +page(request: SessionPageRequest, signal: AbortSignal): Promise { + return this.history.page(request, signal) +} + +// Ordinary delivery; no generated-source import or constructor definitions. +// Constructor: super(ctx, 'sessionController', { namespace: 'session' }) +@Remote({ name: 'page' }) +page(request: SessionPageRequest, signal: AbortSignal): Promise { + return this.history.page(request, signal) +} +``` + +**Browser 与 Node 调用。** 源码导出消费方将 `/remote-source` 改为 `/remote`;已有普通消费方本来就使用此路径。实际调用 Context 挂载一次,不额外向 Registry 注册。 + +```text +import { TYPERT_REMOTE } from '@deepseek-ai/dsh-api-session-controller/remote' +await ctx.remote.$mount(TYPERT_REMOTE) +const result = await ctx.remote.session.page(request, signal) +const stream = ctx.remote.session.follow(followRequest, signal) +try { + for await (const frame of stream) consume(frame) +} finally { + await stream.dispose() +} +``` + +**离线 CLI 与框架元数据。** 旧选择读取源码方法表;替代方式在目标发现之前读取 profile 拥有的 Registry。两个片段是不同选择,不是同时声明。 + +```text +// Old selection. +import { REMOTE_METHODS } from '@deepseek-ai/dsh-api-session-controller/remote-source' +const page = REMOTE_METHODS['session/page'] +``` + +```text +// Metadata plugin: inject: ['typert']; no Gateway, Connection, or Host controller. +import { TYPERT_REMOTE } from '@deepseek-ai/dsh-api-session-controller/remote' +import { isTypertRemoteMethod } from '@deepseek-ai/dsh-typert-protocol/remote-info' +ctx.typert.remotes.register(TYPERT_REMOTE) +const page = ctx.typert.remotes.get('session/page') +if (page === undefined || !isTypertRemoteMethod(page)) { + throw new Error('session/page generated direct method is not loaded') +} +``` + +注册属于该插件的 fiber。帮助使用 `description` 和 `input({ strict: true })`;类型化 facade 可以保留对普通生成声明的 type-only 导入。显式工具选择不修改已注册元数据。 + +**CLI 输入与分发。** 本地 `current` 解析和附件准备之后,两种元数据访问方式使用同样的调用步骤: + +```text +if (page.mode === 'stream') throw new Error('session/page must be unary') +const input = page.input({ strict: true }) +const arguments_ = input.create().parse(raw) +const result = await page.invoke(remote, arguments_, signal) +if (!result.ok) throw result.error +const output = page.result.create().parse(result.value) +``` + +**MCP 发现与调用。** 选择时验证工具特有要求;生成过程本身不要求它们。 + +```text +const input = page.input({ strict: true }) +if (!page.description) throw new Error('session/page has no tool description') +if (input.jsonSchema === undefined) throw new Error('session/page has no supported tool input schema') +const tool = { + name: 'remote_session_page', + description: page.description, + inputSchema: input.jsonSchema, + ...(page.result.jsonSchema === undefined ? {} : { outputSchema: page.result.jsonSchema }), +} +``` + +这个简化对象只展示元数据依赖。真实 MCP 适配器保留 `{ arguments, current, content }` 输入及 `{ ok, value }` / 失败输出 envelope。列举无需连接;调用执行输入接收、本地准备、通过 `input.create()` 解析、调用及输出解析。可选输出投影不会移除输出验证。 + +**原生工具。** 查询 `ctx.typert.local.get('session/page')`,并用 `isTypertRemoteMethod` 收窄,而非读取源码方法表。原生工具可以选择 `method.input({ strict: true })`,取得匹配的解析与输入投影。原生注册仍要求受支持的输入与结果投影,包括 core Tool 必需的 `output.schema`;MCP 的可选输出投影在这里并不足够。facade 取得类型化请求后,两种设计执行同样的本地调用: + +```text +const value = await ctx.sessionController.page(request, signal) +``` + +**独立消费方。** 读取普通 info 实例的类型化索引,不要求 Registry: + +```text +import { TYPERT_REMOTE } from '@deepseek-ai/dsh-api-session-controller/remote' +const page = TYPERT_REMOTE.methods['session/page'] +const arguments_ = page.input().create().parse(raw) +const result = await page.invoke(remote, arguments_, signal) +``` + +**严格源码启动。** 构建普通产物,再使用受支持的源码启动器: + +```sh +pnpm run build +pnpm dsh --profile +``` + +## Alternatives considered + +- **提交源码:** 满足离线需求,但增加冗余交付和维护路径;显式普通预构建已经足够。 +- **嵌套描述符元数据与独立方法表:** 重复结果和参数事实,并增加需要跟踪的对象身份。一份 spec 直接在描述符上派生调用辅助能力;`TypertRemoteInfo` 扩展既有 contribution 并保留 `descriptors`,让 Gateway 与 Registry 沿用现有注册 API。 +- **所有导入方强制使用 Registry:** 为独立消费方增加生命周期要求,却不增加信息。 +- **仅用 fallback:** 无法提供被擦除的验证或工具文档;仅为受支持子集保留。 +- **手写适配器 schema 或运行时 TypeScript 分析:** 重复承担所有权,或引入构建期提取已解决的运行时编译器要求。 + +## Acceptance criteria + +- 普通产物为每个端点生成一份静态方法 spec,并返回惰性类实例;直接方法索引引用描述符对象,保留完整流式/二进制类型、独立编译面及完整编译面的声明合并。 +- 描述符索引与每种输入策略的视图、解析器和投影都独立惰性求值并缓存;Loader 校验静态 spec 及可调用辅助能力,不调用选择器、解析器或投影。 +- 每个输入参数从同一模型生成普通与严格 codec;消费方无需方法注解即可选择策略。两种封装都拒绝额外具名参数;严格输入递归关闭已声明对象,但不关闭 JSON 或字典键,也不改变 Host 分发和结果。 +- 协议源码与构建入口没有 Zod 运行时依赖;生成产物显式提供 Zod,无参端点也能创建拒绝额外字段的空输入对象;[生产 headless profile 的 Loader 回归](<../../../../packages/context/time-context/tests/time-context.e2e.ts>)断言真实 Session 事件。 +- Registry 身份、原子注册、撤销和释放保持不变。 +- 缺少文档或不支持可选投影不阻止生成;选中的工具拒绝缺少必需信息的条目,并仍然解析输出。 +- 严格源码/产物调用与有限 fallback 分别测试;撤销严格 descriptor 绝不启用 fallback。 +- 源码静态检查不消费过期生成声明;产物检查声明并重建输入。生产代码不保留源码定义 opt-in、源码导出、清单或新鲜度规则。 + +## Risks + +完整下游 profile 组合仍需在相应 package 中继续完成;生成的元数据不代表每个 #4111 操作或 CLI/MCP 应用都已迁移。明确接受的取舍是完整源码运行时元数据需要显式预构建。缺失或过期产物要求重新生成,而不是降低验证或另建一套手写 schema。 diff --git a/.agents/notes/proposed/architecture/2026-09-29-session-migration-follow-redirect.i18n.yaml b/.agents/notes/proposed/architecture/2026-09-29-session-migration-follow-redirect.i18n.yaml new file mode 100644 index 0000000000..29a80e39fa --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-09-29-session-migration-follow-redirect.i18n.yaml @@ -0,0 +1,25 @@ +# Bilingual-pair consistency record for 2026-09-29-session-migration-follow-redirect.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/proposed/architecture/2026-09-29-session-migration-follow-redirect.md +/agent-note-present-single-session-migration-through-follow-redirection: + en: 294f1872bbef5f59 + zh: c4bf2852374fbba4 +/agent-note-present-single-session-migration-through-follow-redirection/problem: + en: 8d019bda1e854df3 + zh: 49cbd8b8d869e406 +/agent-note-present-single-session-migration-through-follow-redirection/proposal: + en: b5d43cb845d165ed + zh: c5b3aa8eb7799134 +/agent-note-present-single-session-migration-through-follow-redirection/proposal/completion-milestone-remains-open: + en: 2281727adab80d51 + zh: 4795be5613b37ede +/agent-note-present-single-session-migration-through-follow-redirection/alternatives-considered: + en: bfc5d2325e710601 + zh: 4f285a9f317cd6af +/agent-note-present-single-session-migration-through-follow-redirection/acceptance-criteria: + en: e5d810300cec5f99 + zh: 7bcef7a5ef99501e +/agent-note-present-single-session-migration-through-follow-redirection/risks: + en: 1704cb15dc3c0b5e + zh: cc4576d6e47c3b22 diff --git a/.agents/notes/proposed/architecture/2026-09-29-session-migration-follow-redirect.md b/.agents/notes/proposed/architecture/2026-09-29-session-migration-follow-redirect.md new file mode 100644 index 0000000000..282722f2eb --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-09-29-session-migration-follow-redirect.md @@ -0,0 +1,43 @@ +# Agent Note: Present single-Session migration through follow redirection + +Status: proposed + +English | [中文](2026-09-29-session-migration-follow-redirect.zh.md) + +## Problem + +Opening historical Sessions can wait for lengthy format conversion. Ordinary loading cannot explain the current phase or show migration failure; placing progress inside history events would contaminate the model log and change journal sequence semantics. + +## Proposal + +Add a typed business redirect to single-Session history reads: page or follow returns a migration reference when preparation is required, the Client follows that migration for its current phase and subsequent progress, then returns to the original history read after success. “302” denotes a business result, not a browser HTTP redirect, and accepts no arbitrary URL. + +The Session object layer owns redirection, waiting, failure, and reopening. React must observe an explicit migration state and render a dedicated component; failure retains its cause and retry action. Migration success returns only to history loading, and a valid snapshot establishes history readiness. Paging and reconnect retain existing history and drafts. + +The actual persistence preparation owner retains migration ownership; multiple waiters share work and late joiners receive current state immediately. Closing one view releases only its waiter. Started durable publication retains its run-to-settlement policy. Progress enters neither the Session log nor `session.control` for this flow. + +Create/adopt and full-text search keep automatic processing; fork and catalog reads use the [migration prerequisite](../../implemented/architecture/2026-09-29-explicit-session-history-preparation.md). + +### Completion milestone remains open + +Read-open currently produces validated in-memory history; write-open encodes, verifies, and publishes a new generation. If redirection waits only for read preparation, its reference must retain the prepared result until the original follow takes ownership rather than relying on an evictable short-lived cache. Waiting for publication instead adds write-permission and publication-time requirements to opening old history. Implementation must choose this behavior rather than using an ambiguous done state for both milestones. + +## Alternatives considered + +**Push migration progress through global control.** One history-opening operation can own its waiting, failure, and retry without independent global progress synchronization. + +**Insert progress before the ordinary history journal's opening frame.** The generic journal remains snapshot-first; the Session adapter consumes redirection and migration frames, forwarding only ordinary history to the journal. + +**Automatically replay every RPC that encounters migration.** Commands with committed effects cannot be replayed safely. This proposal covers recoverable history reads rather than a general command-retry platform. + +## Acceptance criteria + +- The Client shows actual migration phases before receiving the history snapshot; failure remains visible without an automatic retry loop. +- Concurrent joiners, independent waiter cancellation, and reconnect observe the same operation's current state; an old attempt cannot overwrite a new one. +- The resumed history read cannot restart the same migration after cache eviction; cancellation never rolls back a published generation. +- Unknown totals produce no fabricated percentages. Unrelated lightweight requests and progress frames receive execution time during migration, with responsiveness measured separately. +- Create/search, fork/catalog policies, and existing Session data retain their respective guarantees. + +## Risks + +Redirection spans two requests and needs explicit retention and cancellation ownership. Progress alone does not remove synchronous Host parsing and validation stalls; scheduling changes require measurements. The choice between read preparation and write publication remains an implementation prerequisite. diff --git a/.agents/notes/proposed/architecture/2026-09-29-session-migration-follow-redirect.zh.md b/.agents/notes/proposed/architecture/2026-09-29-session-migration-follow-redirect.zh.md new file mode 100644 index 0000000000..5dbc213167 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-09-29-session-migration-follow-redirect.zh.md @@ -0,0 +1,43 @@ +# Agent Note: 单会话迁移通过 follow 重定向呈现 + +Status: proposed + +[English](2026-09-29-session-migration-follow-redirect.md) | 中文 + +## 问题 + +打开历史会话可能等待较长的格式转换。普通 loading 无法解释当前阶段或显示迁移失败;把进度放入历史事件又会污染模型日志,并改变历史流的序号语义。 + +## 提案 + +对单会话历史读取增加 typed 业务重定向:page 或 follow 在需要迁移时返回迁移引用,Client 转到迁移 follow,接收当前阶段和后续进度;成功后回到原历史读取。这里的“302”是业务结果,不是浏览器 HTTP 跳转,也不接受任意 URL。 + +Session 对象层编排跳转、等待、失败和重新读取。React 必须看到迁移中的明确状态并显示专门组件;失败保留原因和重试入口。迁移成功只回到历史加载态,收到有效 snapshot 才表示历史就绪。分页或重连已经拥有的历史与草稿保留。 + +迁移操作仍由实际持久化准备入口拥有;多个等待者共享任务,后加入者立即取得当前状态。关闭一个视图只释放其等待,不取消其他等待者。已开始的 durable publication 遵守既有运行至结算规则。进度不写入 Session log,不使用 `session.control` 作为本流程的进度通道。 + +create/adopt 和全文搜索保持自动处理;fork 和目录读取采用[迁移前置检查](../../implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md)。 + +### 完成里程碑仍待确定 + +现有 read-open 只生成经验证的内存结果;write-open 才编码、校验并发布新 generation。若重定向只等待读准备,迁移引用必须将准备结果保留到原 follow 接手,不能依赖可淘汰的短期缓存。若等待完整发布,则打开旧历史会额外要求写权限并等待发布。实现前必须确定这一行为,不以一个模糊的 done 混用两种里程碑。 + +## 考虑过的替代方案 + +**通过全局 control 推送迁移进度。** 单次打开历史的等待、错误与重试更适合由该读取流程拥有,不需要增加独立的全局进度状态同步。 + +**直接在普通 history journal 首帧前插入进度。** 通用 journal 保持 snapshot-first;Session 适配层消费重定向和迁移流,只把正常历史交给 journal。 + +**所有 RPC 遇到迁移都自动重发。** 已执行副作用的命令不能安全重放。此提案限定可安全恢复的历史读取,不扩展成通用命令重试平台。 + +## 验收条件 + +- 迁移等待开始后,Client 在收到历史 snapshot 前显示真实阶段;失败保持可见且不会自动循环重试。 +- 并发加入、单等待者取消和重连均取得同一操作的当前状态;旧尝试的通知不覆盖新尝试。 +- 完成后的历史读取不会因为缓存淘汰重新启动同一迁移;已发布 generation 不因取消而回滚。 +- 未知总量不显示伪造百分比。迁移时无关轻量请求和进度帧仍能得到执行机会,响应性单独测量。 +- create/search、fork/catalog 策略及已有 Session 数据保持各自约定。 + +## 风险 + +重定向跨越两次请求,需要明确保活与取消所有权。迁移进度并不会消除 Host 主线程的同步解析和验证暂停;相关调度调整必须依据实测。只读准备与写入发布的完成定义仍是实施前置选择。 diff --git a/.agents/notes/proposed/feature/2026-10-02-plugin-market-index-format.i18n.yaml b/.agents/notes/proposed/feature/2026-10-02-plugin-market-index-format.i18n.yaml new file mode 100644 index 0000000000..4aad229581 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-10-02-plugin-market-index-format.i18n.yaml @@ -0,0 +1,46 @@ +# Bilingual-pair consistency record for 2026-10-02-plugin-market-index-format.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/proposed/feature/2026-10-02-plugin-market-index-format.md +/agent-note-plugin-market-index-format: + en: 8da20a8601d7cb29 + zh: 74368eed4d4b8e7c +/agent-note-plugin-market-index-format/problem: + en: ce5e4a362f558af6 + zh: 29d93e0655b99217 +/agent-note-plugin-market-index-format/proposal: + en: ed9148e95b2ad7c2 + zh: 25a7add3c56fd681 +/agent-note-plugin-market-index-format/proposal/example: + en: 1b1c960c966cf912 + zh: 97be87cb14893c26 +/agent-note-plugin-market-index-format/proposal/root-fields: + en: 4fac5a9b8261342d + zh: f9168a8a4209feab +/agent-note-plugin-market-index-format/proposal/plugin-fields: + en: 19d743bd04dc65b3 + zh: 810a7f98c4fe8301 +/agent-note-plugin-market-index-format/proposal/version-fields: + en: d6c0fa99e1cbb068 + zh: 3d2a7b85299c679a +/agent-note-plugin-market-index-format/proposal/install-arguments: + en: c748cdc4d8ce349a + zh: 5740fa0d6106e637 +/agent-note-plugin-market-index-format/proposal/dsh-compatibility: + en: 00fe507b9b5dfea7 + zh: 55de6aaeb3865e84 +/agent-note-plugin-market-index-format/proposal/generator-obligations: + en: 8e848a102fe9d86e + zh: feff226ef8321e00 +/agent-note-plugin-market-index-format/proposal/reader-rules: + en: 92903cbe87d9c0ca + zh: 54af6cb33e9da252 +/agent-note-plugin-market-index-format/alternatives-considered: + en: 3d7cf519bc8e0593 + zh: 328dc0747836eaa8 +/agent-note-plugin-market-index-format/acceptance-criteria: + en: 753abee6adf39812 + zh: 1102bcfdd48f7e90 +/agent-note-plugin-market-index-format/risks: + en: 41170d483b17df80 + zh: 1bfd8f44e0f09036 diff --git a/.agents/notes/proposed/feature/2026-10-02-plugin-market-index-format.md b/.agents/notes/proposed/feature/2026-10-02-plugin-market-index-format.md new file mode 100644 index 0000000000..6ab05ec875 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-10-02-plugin-market-index-format.md @@ -0,0 +1,234 @@ +# Agent Note: Plugin market index format + +Status: proposed + +English | [中文](2026-10-02-plugin-market-index-format.zh.md) + +## Problem + +DSH installs third-party bundles only from a spec the user already knows: an npm name, a Git URL, a tarball, or a local path. Nothing lets a user browse installable bundles. No official market exists, and one may be added later, so a market mechanism must work with indexes that third parties publish. + +The smallest possible index is a list of npm names or Git repository URLs, one per line. It identifies every plugin, but a client rendering it must fetch each package's manifest, locale files, and icon before it can show a list. A list page that issues one or more requests per row is slow, fails partially, and puts metadata resolution in every client. + +An index must therefore carry everything a list page displays: localized title and description, icon, author, available versions, compatibility, and publish time. Markets also want to publish their own data, such as categories, tags, downloads, and ratings, without DSH knowing what those values mean. + +## Proposal + +Separate the **index** from the **index generator**. DSH defines and reads one JSON index format. How an index is produced, and from which source list, belongs to the generator. DSH's reader, its Discover page, and a reference generator are separate changes that consume this format. Indexes list [profile plugin bundles](../../implemented/architecture/2026-08-05-profile-plugin-bundles.md) and install them through [guided plugin installation](../../implemented/architecture/2026-09-15-guided-plugin-installation.md). + +The market reuses npm's package names, versions, ranges, distribution tags, and person declarations. Readers and generators use maintained npm parsers and validators. Additional fields or changed meanings require a plugin-market requirement that npm does not meet. + +### Example + +```json +{ + "format": 1, + "title": { "en": "Example Market", "zh": "示例市场" }, + "description": { "en": "Community DSH bundles", "zh": "社区 DSH bundle" }, + "metadata": { + "categories": { + "productivity": { "title": { "en": "Productivity", "zh": "效率" } } + }, + "labels": { + "official": { "title": { "en": "Official", "zh": "官方" } } + }, + "sortKeys": { + "downloads": { "title": { "en": "Downloads", "zh": "下载量" }, "order": "desc" }, + "rating": { "title": { "en": "Rating", "zh": "评分" }, "order": "desc" } + } + }, + "plugins": [ + { + "name": "@example/dsh-auto-review", + "title": { "en": "Auto Review", "zh": "自动审查" }, + "description": { "en": "Per-tool LLM authorization review", "zh": "逐工具 LLM 授权审查" }, + "icon": "icons/auto-review.svg", + "author": "Example Labs", + "homepage": "https://example.com/dsh-auto-review", + "metadata": { + "category": "productivity", + "labels": ["official"], + "keywords": ["review", "authorization"], + "sortKeys": { "downloads": 12034, "rating": 4.6 } + }, + "dist-tags": { "latest": "0.2.0-rc.1", "next": "0.2.0-rc.2" }, + "versions": [ + { + "version": "0.2.0-rc.2", + "publishTimestamp": 1790476800, + "source": { "type": "npm" }, + "engines": { "dsh": ">=0.2.0 <0.3.0" } + }, + { + "version": "0.2.0-rc.1", + "publishTimestamp": 1789872000, + "source": { "type": "npm" }, + "engines": { "dsh": "0.2.0 - 0.2.4 || >=0.3.0 <0.4.0" } + } + ] + }, + { + "name": "dsh-plugin-foo", + "title": "Foo", + "icon": "https://example.com/foo.png", + "dist-tags": { "latest": "1.0.0" }, + "versions": [ + { + "version": "1.0.0", + "publishTimestamp": 1788000000, + "source": { + "type": "git", + "url": "https://github.com/author/dsh-plugins", + "commit": "3f9c2e1d8a4b6c0e7f1a2b3c4d5e6f708192a3b4", + "path": "packages/foo" + }, + "engines": { "dsh": "*" } + } + ] + } + ] +} +``` + +`LocalizedText` below is the `LocalizedText` type of [`dsh-package-manifest`](../../../../packages/util/package-manifest/src/types.ts), a string or an object of strings that contains `en`, with two additional rules: object keys are lowercase language ids matching `^[a-z]{2,8}(-[a-z0-9]{1,8})*$`, and every string contains at least one non-whitespace character. + +### Root fields + +| Field | Required | Rule | +|---|---|---| +| `format` | yes | Integer `1`. | +| `title` | yes | `LocalizedText` naming the market. | +| `description` | no | `LocalizedText`. | +| `metadata` | no | Object holding the three declaration maps below. | +| `metadata.categories` | no | Object mapping category id → `{ title: LocalizedText }`. | +| `metadata.labels` | no | Object mapping label id → `{ title: LocalizedText }`. | +| `metadata.sortKeys` | no | Object mapping sort-key id → `{ title: LocalizedText, order: "asc" \| "desc" }`; `order` is the initial sort direction. | +| `plugins` | yes | Array of plugins, possibly empty; its order is the index's default ordering. | + +Category, label, and sort-key ids are non-empty strings. Readers look ids up as own properties, so ids such as `constructor` have no special meaning. + +### Plugin fields + +| Field | Required | Rule | +|---|---|---| +| `name` | yes | Package name accepted by npm's maintained package-name validator for new packages; unique within the index. | +| `title` | no | `LocalizedText`; a reader displays `name` when absent. | +| `description` | no | `LocalizedText`. | +| `icon` | no | Either `data:;base64,`, where `` is `image/svg+xml`, `image/png`, `image/jpeg`, or `image/webp`, `` is canonically padded base64, and the decoded payload is at most 256 KiB; or a URL reference whose resolution against the index URL is an `https:` URL or has the index URL's origin. | +| `author` | no | String with at least one non-whitespace character. | +| `homepage` | no | Absolute `https:` or `http:` URL of a page about the plugin. | +| `metadata` | no | Object holding the values below. | +| `metadata.category` | no | One declared category id. | +| `metadata.labels` | no | Array of distinct declared label ids. | +| `metadata.keywords` | no | Array of free-form strings; no root declaration required. | +| `metadata.sortKeys` | no | Object mapping a declared sort-key id → finite number. | +| `dist-tags` | no | Object mapping npm distribution-tag names to exact listed version strings; absent means no recorded channels. | +| `versions` | yes | Non-empty array of versions; see below. Array order does not select the installation version. | + +`metadata.keywords` conventionally comes from npm `package.json` `keywords`, but generators may use another source, add strings, or adjust values. Neither presence nor equality with the package manifest is required. Readers preserve the strings and their order; an empty array is valid. + +### Version fields + +| Field | Required | Rule | +|---|---|---| +| `version` | yes | Exact version parsed by npm's `node-semver`; preserve the complete string, including Git build metadata. The exact string is unique within the plugin. | +| `publishTimestamp` | yes | Integer Unix timestamp in seconds, in `[0, 10^11)`. | +| `source` | yes | Where `version` is installed from; see below. | +| `engines` | yes | Object containing `dsh`. | +| `engines.dsh` | yes | Non-blank valid npm SemVer range declared in the source manifest; copied unchanged. `*` explicitly declares support for any DSH version. | + +A relative `icon` reference resolves against the index URL, as an HTML image reference resolves against its page. For an index at `https://market.example/dsh/index.json`, `"icon": "icons/foo.svg"` names `https://market.example/dsh/icons/foo.svg`. A generator can therefore publish the index and its icon files as one directory on any static host without knowing the final URL. Absolute icon URLs on other origins must use `https:`; the same-origin allowance lets an `http:` index on a loopback or intranet host serve its own icons. Readers resolve the reference when they read the index, so clients receive absolute URLs. + +`source` takes one of two forms, and readers reject any other `type`: + +- `{ "type": "npm", "registry"?: string }`. `registry` is an `http:` or `https:` URL without credentials, query, or fragment; `http:` is admitted for intranet mirrors, as in DSH's [install registries](../../implemented/architecture/2026-09-18-plugin-install-registries.md). +- `{ "type": "git", "url": string, "commit": string, "path"?: string }`. `url` is a canonical `https:` URL (equal to its WHATWG URL serialization) with at least two non-empty path segments and no trailing slash, without credentials, query, or fragment, and not ending in `.tgz` or `.tar.gz`. `commit` is a lowercase 40-hex-digit SHA. `path` is a `/`-separated relative directory whose segments contain only ASCII letters, digits, and `._@+-`, and are neither `.` nor `..`; absent means the repository root. + +### Install arguments + +A client installs one version with exactly these pnpm arguments: + +- npm: the spec `@`. Without `registry`, the client asks its configured registries as it does for any install. With `registry`, the client follows DSH's [registry plan](../../implemented/architecture/2026-09-18-plugin-install-registries.md): it asks `registry` first and falls back to its other configured registries only when `registry` is one of them; any other `registry` is asked alone, so a private registry never falls through to a public one that may publish a different package under the same name and version. +- git: the spec `git+.git#`, without doubling a trailing `.git`, followed by `&path:/` when `path` is present. The `git+` prefix makes pnpm treat URLs with more than two path segments, such as GitLab subgroups, as Git repositories. + +### DSH compatibility + +Every market-listed version must declare valid `engines.dsh`. The reader and market-origin installation evaluate that range against the running DSH version with npm's `node-semver` and `includePrerelease: true`. There is no peer fallback or range synthesis. npm package peer resolution remains outside market host compatibility. + +Installation rechecks the source manifest before accepting a market-origin package. An exact local `name@version` exemption may permit a valid range that rejects the runtime; it cannot make a missing or invalid declaration eligible. Exemptions are not published in the index. + +### Generator obligations + +A reader cannot verify these rules; a generator that violates them publishes a misleading index. + +- `name` and each `version` equal the package manifest of the installed source. +- `publishTimestamp` is the registry publish time of `version` for npm sources and the committer time of `commit` for Git sources. +- `engines.dsh` copies the manifest's declared range unchanged. A version with a missing, blank, or invalid range is omitted with a diagnostic. A plugin with no eligible version is omitted. +- `dist-tags` snapshots npm's [distribution tags](https://docs.npmjs.com/cli/v11/commands/npm-dist-tag/), retaining only targets present among the eligible listed versions. For Git sources, the publisher or market supplies the same exact tag-to-version mapping. +- Each listed version declares `dsh.bundle`. Installation independently refuses a package without a bundle patch. +- `title`, `description`, and `icon` come from the highest listed version's locale metadata, manifest fields, and icon under the installed-plugin display rules. Use npm's `node-semver.rsort()` order, retaining input order for ties. This metadata choice does not select the installation version. `homepage` copies that version's manifest `homepage` and is absent without one. +- `author` comes from the same highest listed version's npm author declaration. Copy an object's `name`; parse shorthand strings with a maintained npm person normalizer. Omit an absent or whitespace-only name and contact fields. Normalize a fresh projection, leaving the source manifest untouched. + +### Reader rules + +A reader rejects the whole index when the document violates any rule in Root fields, Plugin fields, Version fields, or the `source` forms, including an undeclared category, label, or sort-key reference, an unlisted distribution-tag target, a duplicate `name` or exact `version` string, or a `format` other than `1`. Each such defect is a generator bug, and dropping entries silently would hide it. Readers may bound the document size. + +A reader ignores members that this note does not define, at every level; an unknown `source.type` value is rejected. Format 1 can then gain optional members without breaking existing readers; a change that existing readers would misinterpret uses a new `format` value. + +Tag names must parse as registry tag specs under npm's maintained `npm-package-arg`; targets are exact listed version strings. npm sources use canonical published identifiers (`node-semver.valid(version) === version`); Git sources retain build metadata and pin their exact source by commit. + +Categories, labels, and sort keys are opaque: a reader filters and sorts by them, displays their `title`, and never interprets an id. Readers display declarations in the order of their localized `title`. When sorting plugins, a plugin without a value for the selected sort key follows all plugins with a value in either direction, and equal values keep the index order. Sorting by publish time uses a plugin's greatest `publishTimestamp`. + +A reader evaluates the required `engines.dsh` range under DSH compatibility. Versions use npm's `node-semver.rsort()` order, retaining index order for ties. Exact tag targets, not this display order, select installation versions. + +The initial channel is `latest`. Its exact target is the publisher- or market-selected version. Clients install that recorded version or commit, never `name@latest`. Missing or incompatible `latest` requires explicit version or channel selection; clients do not switch automatically. Installation confirmation identifies the version, selected channel if any, prerelease status, index URL, and source. + +## Alternatives considered + +**A plain list of npm names or repository URLs.** It identifies every plugin but forces one or more requests per row before a list renders, which is the cost this format removes. + +**One opaque install spec string per version.** A reader cannot verify that a free-form spec is pinned. A structured `source` with an exact `version`, or a `commit`, lets the reader verify pinning and lets the client build the spec it installs. + +**Installing the latest version instead of a pinned one.** The installed build could then differ from the metadata the list displayed, and a package release would change what an unchanged index installs. + +**One entry per version.** Every version would repeat the title, description, icon, author, and market metadata, and readers would group entries by `name` to show one plugin. + +**One `source` per plugin, with only the pin per version.** A plugin that moves to another repository, directory, or registry between releases could not list its older versions. + +**Display fields per version.** A list shows one row per plugin, so older display text, icons, authors, and homepages would cost index size without a reader that shows them. + +**Inline icons only.** A list without extra requests needs inline icons, but 256 KiB of raw bytes is about 341 KiB as base64, so a 100-plugin index could reach about 35 MB. URL icons trade extra requests, and disclosure of the user's IP address to the image host, for a small index. + +**Inferring host compatibility from peer dependencies.** The market defines a new standard requiring an author-declared `engines.dsh`. Existing packages must add that declaration before listing; no fallback, workspace mapping, or range intersection is needed. + +**Copying the complete npm person object into the display field.** The list needs a name. The generator supports npm's original declaration while omitting unused contact fields. + +**Opaque sort values for time, including ISO date strings.** Publish time has fixed semantics that clients format and sort, so it is a typed field. Without time, sort values can be numbers only, which needs no per-key value-type rule. + +**Root-level `labels` and `sortKeys`, and a plugin field named `sort`.** Grouping market-defined declarations and values under `metadata` at both levels, with matching member names except the single-valued `category`, separates them from fields that clients interpret. + +**Declaration order as display order.** JavaScript reorders integer-like object keys, so declaration order would need either an id pattern or array declarations. Clients sort declarations by their localized title instead. + +**Selecting the greatest compatible version.** npm's `latest` can name an older release. Inferring a target from SemVer ranking loses the recorded channel choice and is ambiguous for equally ranked builds. + +**Automatic prerelease fallback.** Missing or incompatible channel targets do not mean that the user selected a prerelease. + +**Rejecting unknown members.** Every optional addition would then require a new `format` value and break every deployed reader. + +## Acceptance criteria + +- A validator accepts the example above and rejects one violation of each rule in Root fields, Plugin fields, Version fields, and the `source` forms, with a diagnostic naming the JSON path. +- Install arguments built from every example version are accepted by DSH's install-spec parser and by pnpm. +- A validator ignores unknown members at every level. +- Generator and validator refuse missing, blank, and invalid `engines.dsh`; omitted versions leave no dangling tag target. Index and market-origin installation agree on valid ranges, including hyphen ranges, prereleases, and valid ranges that reject the runtime. Exemptions never bypass the declaration requirement. +- Exact tag targets select the same source after equally ranked Git build versions are reordered. Missing targets are rejected; absent or incompatible `latest` causes no automatic switch. +- npm author objects and shorthand strings produce the declared name without contact fields or mutation of source identity. + +## Risks + +- An index is unsigned. Titles, authors, labels, and scores are market claims; an `official` label is not DSH verification. Clients must show the index URL and each version's `source`. +- A Git version's `name`, `version`, and `engines.dsh` are claims about the repository. A repository can claim any name, including an `@deepseek-ai/dsh-` name, and the installed manifest decides what is actually installed. +- An npm version's `source.registry` is equally a claim: it directs the install of any `name`, including an `@deepseek-ai/dsh-` name, to a registry the market chooses, and that registry decides what is installed. +- URL icons disclose the user's IP address to image hosts. +- Pinned versions and distribution tags stay stale until the index is regenerated. +- Market text reaches users, and models through any client tool that lists plugins, without review by DSH. diff --git a/.agents/notes/proposed/feature/2026-10-02-plugin-market-index-format.zh.md b/.agents/notes/proposed/feature/2026-10-02-plugin-market-index-format.zh.md new file mode 100644 index 0000000000..12608c767b --- /dev/null +++ b/.agents/notes/proposed/feature/2026-10-02-plugin-market-index-format.zh.md @@ -0,0 +1,234 @@ +# Agent Note: 插件市场索引格式 + +Status: proposed + +[English](2026-10-02-plugin-market-index-format.md) | 中文 + +## 问题 + +DSH 只能从用户已知的 spec 安装第三方组合包(bundle):npm 包名、Git URL、tarball 或本地路径。用户无法浏览可安装的组合包。目前没有官方市场,以后可能会增加官方市场,因此市场机制必须支持第三方发布的索引。 + +最小的索引是一份 npm 包名或 Git 仓库 URL 列表,每行一项。它能标识每个插件,但客户端渲染列表前必须为每个包获取 manifest(元数据清单)、语言文件和图标。列表页面每行发出一个或多个请求时,加载慢、可能部分失败,并且每个客户端都要实现元数据解析。 + +因此,索引必须包含列表页面显示的全部内容:本地化标题和描述、图标、作者、可用版本、兼容性和发布时间。市场还需要发布自己的数据,例如分类、标签、下载量和评分,而 DSH 不需要理解这些值的含义。 + +## 提案 + +将**索引**与**索引生成器**分开。DSH 定义并读取一种 JSON 索引格式。索引如何生成、基于哪份源列表生成,由生成器负责。DSH 的读取器、Discover 页面和参考生成器是使用此格式的独立变更。索引列出[profile 插件组合包](../../implemented/architecture/2026-08-05-profile-plugin-bundles.zh.md),并通过[引导式插件安装](../../implemented/architecture/2026-09-15-guided-plugin-installation.zh.md)安装它们。 + +市场复用 npm 的包名、版本、范围、发布标签和 person 声明。读取器与生成器使用维护中的 npm 解析器和校验器。新增字段或改变含义需要 npm 无法满足的插件市场需求。 + +### 示例 + +```json +{ + "format": 1, + "title": { "en": "Example Market", "zh": "示例市场" }, + "description": { "en": "Community DSH bundles", "zh": "社区 DSH bundle" }, + "metadata": { + "categories": { + "productivity": { "title": { "en": "Productivity", "zh": "效率" } } + }, + "labels": { + "official": { "title": { "en": "Official", "zh": "官方" } } + }, + "sortKeys": { + "downloads": { "title": { "en": "Downloads", "zh": "下载量" }, "order": "desc" }, + "rating": { "title": { "en": "Rating", "zh": "评分" }, "order": "desc" } + } + }, + "plugins": [ + { + "name": "@example/dsh-auto-review", + "title": { "en": "Auto Review", "zh": "自动审查" }, + "description": { "en": "Per-tool LLM authorization review", "zh": "逐工具 LLM 授权审查" }, + "icon": "icons/auto-review.svg", + "author": "Example Labs", + "homepage": "https://example.com/dsh-auto-review", + "metadata": { + "category": "productivity", + "labels": ["official"], + "keywords": ["review", "authorization"], + "sortKeys": { "downloads": 12034, "rating": 4.6 } + }, + "dist-tags": { "latest": "0.2.0-rc.1", "next": "0.2.0-rc.2" }, + "versions": [ + { + "version": "0.2.0-rc.2", + "publishTimestamp": 1790476800, + "source": { "type": "npm" }, + "engines": { "dsh": ">=0.2.0 <0.3.0" } + }, + { + "version": "0.2.0-rc.1", + "publishTimestamp": 1789872000, + "source": { "type": "npm" }, + "engines": { "dsh": "0.2.0 - 0.2.4 || >=0.3.0 <0.4.0" } + } + ] + }, + { + "name": "dsh-plugin-foo", + "title": "Foo", + "icon": "https://example.com/foo.png", + "dist-tags": { "latest": "1.0.0" }, + "versions": [ + { + "version": "1.0.0", + "publishTimestamp": 1788000000, + "source": { + "type": "git", + "url": "https://github.com/author/dsh-plugins", + "commit": "3f9c2e1d8a4b6c0e7f1a2b3c4d5e6f708192a3b4", + "path": "packages/foo" + }, + "engines": { "dsh": "*" } + } + ] + } + ] +} +``` + +下文中的 `LocalizedText` 即 [`dsh-package-manifest`](../../../../packages/util/package-manifest/src/types.ts) 中的 `LocalizedText` 类型,即字符串或包含 `en` 的字符串对象,并附加两条规则:对象的键是匹配 `^[a-z]{2,8}(-[a-z0-9]{1,8})*$` 的小写语言 id,每个字符串至少包含一个非空白字符。 + +### 根字段 + +| 字段 | 必填 | 规则 | +|---|---|---| +| `format` | 是 | 整数 `1`。 | +| `title` | 是 | 市场名称,类型为 `LocalizedText`。 | +| `description` | 否 | `LocalizedText`。 | +| `metadata` | 否 | 包含下列三个声明映射的对象。 | +| `metadata.categories` | 否 | 对象,将分类 id 映射为 `{ title: LocalizedText }`。 | +| `metadata.labels` | 否 | 对象,将标签 id 映射为 `{ title: LocalizedText }`。 | +| `metadata.sortKeys` | 否 | 对象,将排序键 id 映射为 `{ title: LocalizedText, order: "asc" \| "desc" }`;`order` 是初始排序方向。 | +| `plugins` | 是 | 插件数组,可以为空;数组顺序即索引的默认排序。 | + +分类、标签和排序键的 id 均为非空字符串。读取器按自有属性查找 id,因此 `constructor` 等 id 没有特殊含义。 + +### 插件字段 + +| 字段 | 必填 | 规则 | +|---|---|---| +| `name` | 是 | npm 维护的包名校验器接受的新包名称;在索引内唯一。 | +| `title` | 否 | `LocalizedText`;缺省时读取器显示 `name`。 | +| `description` | 否 | `LocalizedText`。 | +| `icon` | 否 | 以下两种形式之一:`data:;base64,`,其中 `` 为 `image/svg+xml`、`image/png`、`image/jpeg` 或 `image/webp`,`` 是按规范填充的 base64,解码后的载荷不超过 256 KiB;或者 URL 引用,它相对于索引 URL 解析的结果是 `https:` URL,或与索引 URL 同源。 | +| `author` | 否 | 至少包含一个非空白字符的字符串。 | +| `homepage` | 否 | 介绍该插件的页面的绝对 `https:` 或 `http:` URL。 | +| `metadata` | 否 | 包含下列值的对象。 | +| `metadata.category` | 否 | 一个已声明的分类 id。 | +| `metadata.labels` | 否 | 由互不相同的已声明标签 id 组成的数组。 | +| `metadata.keywords` | 否 | 自由字符串数组;无需在根部声明。 | +| `metadata.sortKeys` | 否 | 对象,将已声明的排序键 id 映射为有限数值。 | +| `dist-tags` | 否 | 将 npm 发布标签名称映射为已列出的精确版本字符串的对象;缺省表示未记录发布渠道。 | +| `versions` | 是 | 非空的版本数组;见下文。数组顺序不选择安装版本。 | + +`metadata.keywords` 按约定来自 npm `package.json` 的 `keywords`,但生成器可以使用其他来源、添加字符串或调整值。不要求提供此字段,也不要求它与包 manifest 一致。读取器保留字符串及其顺序;允许空数组。 + +### 版本字段 + +| 字段 | 必填 | 规则 | +|---|---|---| +| `version` | 是 | npm 的 `node-semver` 解析的精确版本;保留完整字符串,包括 Git 版本编译信息。精确字符串在插件内唯一。 | +| `publishTimestamp` | 是 | 以秒为单位的整数 Unix 时间戳,取值范围为 `[0, 10^11)`。 | +| `source` | 是 | `version` 的安装来源;见下文。 | +| `engines` | 是 | 包含 `dsh` 的对象。 | +| `engines.dsh` | 是 | 源 manifest 声明的非空白、有效 npm SemVer 范围;原样复制。`*` 显式声明支持任意 DSH 版本。 | + +相对的 `icon` 引用相对于索引 URL 解析,与 HTML 图片引用相对于所在页面解析的方式相同。对于位于 `https://market.example/dsh/index.json` 的索引,`"icon": "icons/foo.svg"` 指向 `https://market.example/dsh/icons/foo.svg`。因此,生成器可以把索引和图标文件作为一个目录发布到任意静态主机,无需知道最终 URL。指向其他源的绝对图标 URL 必须使用 `https:`;同源规则允许位于 loopback 或内网主机上的 `http:` 索引提供自己的图标。读取器在读取索引时解析该引用,因此客户端收到的是绝对 URL。 + +`source` 采用以下两种形式之一,读取器拒绝其他任何 `type`: + +- `{ "type": "npm", "registry"?: string }`。`registry` 是不含凭据、查询或片段的 `http:` 或 `https:` URL;允许 `http:` 是为了支持内网镜像,与 DSH 的[安装 registry](../../implemented/architecture/2026-09-18-plugin-install-registries.zh.md) 一致。 +- `{ "type": "git", "url": string, "commit": string, "path"?: string }`。`url` 是规范的 `https:` URL(等于其 WHATWG URL 序列化结果),至少包含两个非空路径段且不以斜杠结尾,不含凭据、查询或片段,且不以 `.tgz` 或 `.tar.gz` 结尾。`commit` 是 40 位小写十六进制 SHA。`path` 是以 `/` 分隔的相对目录,各段只包含 ASCII 字母、数字和 `._@+-`,且不是 `.` 或 `..`;缺省表示仓库根目录。 + +### 安装参数 + +客户端安装某个版本时恰好使用以下 pnpm 参数: + +- npm:spec 为 `@`。没有 `registry` 时,客户端像任何安装一样询问它配置的 registry。存在 `registry` 时,客户端遵循 DSH 的 [registry 计划](../../implemented/architecture/2026-09-18-plugin-install-registries.zh.md):先询问 `registry`,仅当它属于客户端配置的 registry 之一时才回退到其他已配置 registry;其他 `registry` 单独询问,因此私有 registry 不会回退到可能以相同名称和版本发布不同包的公共 registry。 +- git:spec 为 `git+.git#`,`url` 已以 `.git` 结尾时不重复添加;存在 `path` 时在其后追加 `&path:/`。`git+` 前缀使 pnpm 将路径段多于两个的 URL(例如 GitLab 子组)视为 Git 仓库。 + +### DSH 兼容性 + +市场列出的每个版本都必须声明有效的 `engines.dsh`。读取器与市场来源的安装使用 npm 的 `node-semver` 和 `includePrerelease: true`,根据当前运行的 DSH 版本求值。不存在对等依赖回退或范围合成。npm 包的对等依赖解析不属于市场宿主兼容性检查。 + +安装接受市场来源的包前,会重新检查源 manifest。精确的本地 `name@version` 豁免可以允许有效范围拒绝当前运行时的情况,但不能使缺失或无效声明符合列出条件。豁免不发布在索引中。 + +### 生成器义务 + +读取器无法验证以下规则;违反这些规则的生成器会发布误导性的索引。 + +- `name` 和每个 `version` 与所安装来源中的包 manifest 一致。 +- 对于 npm 来源,`publishTimestamp` 是 `version` 在 registry 中的发布时间;对于 Git 来源,它是 `commit` 的提交者时间。 +- `engines.dsh` 原样复制 manifest 声明的范围。缺失、空白或无效范围的版本会被省略并给出诊断。没有合格版本的插件会被省略。 +- `dist-tags` 是 npm [发布标签](https://docs.npmjs.com/cli/v11/commands/npm-dist-tag/)的快照,只保留指向合格且已列出版本的目标。对于 Git 来源,发布者或市场提供同样的精确标签到版本映射。 +- 列出的每个版本都声明了 `dsh.bundle`。安装时也会独立拒绝没有组合包 patch 的包。 +- `title`、`description` 和 `icon` 来自所列最高版本的语言元数据、manifest 字段和图标,采用已安装插件的显示规则。使用 npm 的 `node-semver.rsort()` 顺序,相等时保留输入顺序。元数据选择不选择安装版本。`homepage` 复制该版本 manifest 的 `homepage`,manifest 没有该字段时省略。 +- `author` 来自同一最高版本的 npm 作者声明。复制对象的 `name`;使用维护中的 npm person 归一化器解析简写字符串。省略缺失或全空白的名称以及联系字段。归一化新建的投影,不修改源 manifest。 + +### 读取器规则 + +文档违反根字段、插件字段、版本字段或 `source` 形式中的任何规则时,读取器拒绝整个索引,包括引用了未声明的分类、标签或排序键,发布标签指向未列出的目标,`name` 或精确的 `version` 字符串重复,以及 `format` 不是 `1`。每个此类缺陷都是生成器 bug,静默丢弃条目会掩盖它。读取器可以限制文档大小。 + +读取器在每一层都忽略本 Agent Note 未定义的成员;未知的 `source.type` 值会被拒绝。这样格式 1 可以增加可选成员而不破坏现有读取器;现有读取器会误解的变更使用新的 `format` 值。 + +标签名称必须能被 npm 维护的 `npm-package-arg` 解析为 registry 标签 spec;目标是已列出的精确版本字符串。npm 来源使用规范发布标识(`node-semver.valid(version) === version`);Git 来源保留版本编译信息并用提交固定精确来源。 + +分类、标签和排序键对读取器不透明:读取器按它们筛选和排序,显示其 `title`,从不解释 id 的含义。读取器按本地化 `title` 对声明排序后显示。对插件排序时,无论排序方向如何,没有所选排序键值的插件都排在所有有值的插件之后,值相同的插件保持索引顺序。按发布时间排序时使用插件最大的 `publishTimestamp`。 + +读取器按 DSH 兼容性一节的规则求值必填的 `engines.dsh` 范围。版本使用 npm 的 `node-semver.rsort()` 顺序,相等时保留索引顺序。安装版本由精确的标签目标选择,而不是此显示顺序。 + +初始渠道是 `latest`。它的精确目标是发布者或市场选择的版本。客户端安装记录的版本或提交,绝不安装 `name@latest`。缺失或不兼容的 `latest` 需要显式选择版本或渠道;客户端不会自动切换。安装确认标明版本、所选渠道(如果有)、先行版本状态、索引 URL 和来源。 + +## 考虑过的替代方案 + +**纯 npm 包名或仓库 URL 列表。** 它能标识每个插件,但列表渲染前每行需要一个或多个请求,而此格式正是为消除这一开销而设计。 + +**每个版本使用一个不透明的安装 spec 字符串。** 读取器无法验证自由格式的 spec 是否固定了版本。结构化的 `source` 配合精确的 `version` 或 `commit`,读取器可以验证版本固定,客户端可以构建要安装的 spec。 + +**安装最新版本而不是固定版本。** 这样安装的构建可能与列表显示的元数据不一致,并且包发布新版本会改变未修改的索引所安装的内容。 + +**每个版本一个条目。** 每个版本都会重复标题、描述、图标、作者和市场元数据,读取器还要按 `name` 分组才能显示一个插件。 + +**每个插件一个 `source`,每个版本只记录固定点。** 在两次发布之间换了仓库、目录或 registry 的插件将无法列出旧版本。 + +**每个版本各有显示字段。** 列表每个插件只显示一行,旧的显示文本、图标、作者和主页会增加索引大小,却没有读取器显示它们。 + +**只允许内联图标。** 不发额外请求的列表需要内联图标,但 256 KiB 原始字节编码为 base64 后约为 341 KiB,因此 100 个插件的索引可能达到约 35 MB。URL 图标以额外请求和向图片主机暴露用户 IP 地址为代价,换取较小的索引。 + +**从对等依赖推断宿主兼容性。** 市场定义要求作者声明 `engines.dsh` 的新标准。现有包必须添加此声明才能列出;不需要回退、workspace 映射或范围求交。 + +**将完整 npm person 对象复制到显示字段。** 列表需要名称。生成器支持 npm 的原始声明,同时省略不用的联系字段。 + +**用不透明排序值表示时间,包括 ISO 日期字符串。** 发布时间具有固定语义,客户端会对其格式化和排序,因此它是一个有类型的字段。排除时间后,排序值可以只用数值,无需为每个键规定值类型。 + +**根级 `labels` 和 `sortKeys`,以及名为 `sort` 的插件字段。** 在两个层级都把市场定义的声明和值归入 `metadata`,并使用对应的成员名(单值的 `category` 除外),可以将它们与客户端解释的字段区分开。 + +**以声明顺序作为显示顺序。** JavaScript 会重排类整数的对象键,因此要保留声明顺序,就需要限定 id 格式或改用数组声明。客户端改为按本地化标题对声明排序。 + +**选择最高兼容版本。** npm 的 `latest` 可以指向较旧的发布版本。从 SemVer 排名推断目标会丢失记录的渠道选择,而且在构建排名相等时存在歧义。 + +**自动回退到先行版本。** 渠道目标缺失或不兼容,不表示用户选择了先行版本。 + +**拒绝未知成员。** 这样每次增加可选成员都需要新的 `format` 值,并会破坏所有已部署的读取器。 + +## 验收标准 + +- 校验器接受上面的示例,并对根字段、插件字段、版本字段和 `source` 形式中的每条规则各拒绝一个违例,诊断信息给出对应的 JSON 路径。 +- 根据每个示例版本构建的安装参数可被 DSH 的安装 spec 解析器和 pnpm 接受。 +- 校验器在每一层都忽略未知成员。 +- 生成器和校验器拒绝缺失、空白和无效的 `engines.dsh`;省略版本后不留下悬空的标签目标。索引和市场来源的安装对有效范围结果一致,包括连字符范围、先行版本以及拒绝当前运行时的有效范围。豁免绝不绕过声明要求。 +- 排名相等的 Git 构建版本重新排序后,精确标签目标仍选择同一来源。缺失的目标被拒绝;`latest` 缺省或不兼容时不自动切换。 +- npm 作者对象与简写字符串产生声明的名称,不包含联系字段,也不修改源身份。 + +## 风险 + +- 索引没有签名。标题、作者、标签和评分是市场的声明;`official` 标签不是 DSH 验证。客户端必须显示索引 URL 以及每个版本的 `source`。 +- Git 版本的 `name`、`version` 和 `engines.dsh` 是关于仓库的声明。仓库可以声明任意名称,包括 `@deepseek-ai/dsh-` 名称,实际安装的内容由已安装的 manifest 决定。 +- npm 版本的 `source.registry` 同样是一种声明:它把任意 `name`(包括 `@deepseek-ai/dsh-` 名称)的安装引向市场选择的 registry,由该 registry 决定实际安装的内容。 +- URL 图标会向图片主机暴露用户的 IP 地址。 +- 固定版本和发布标签在索引重新生成之前一直保持陈旧。 +- 市场文本未经 DSH 审核即到达用户,并通过任何列出插件的客户端工具到达模型。 diff --git a/.agents/skills/dsh-ci-test-reliability/SKILL.md b/.agents/skills/dsh-ci-test-reliability/SKILL.md index d9fd0f1700..ba97a37745 100644 --- a/.agents/skills/dsh-ci-test-reliability/SKILL.md +++ b/.agents/skills/dsh-ci-test-reliability/SKILL.md @@ -10,7 +10,7 @@ Build tests that remain correct under the repository's real CI topology, not onl ## Read the owning rules - Use [the testing policy](../../../docs/testing.md) to select unit, coverage, expected-output, snapshot, browser, or real-API evidence. -- Use [the defensive patterns](../../../docs/defensive-patterns.md) for lifecycle, subprocess, cancellation, and teardown behavior. +- Use [the defensive patterns](../../../docs/defensive-patterns/general.md) for lifecycle, subprocess, cancellation, and teardown behavior. - Read the active Vitest config and GitHub workflow when their worker or job topology affects the test. - For recorded-session scenarios, also follow [the snapshot instructions](../../../snapshots/AGENTS.md). - Use [dsh-pre-push-checks](../dsh-pre-push-checks/SKILL.md) after the test design is sound to select outgoing validation. diff --git a/.agents/skills/dsh-client-ui-ux/SKILL.md b/.agents/skills/dsh-client-ui-ux/SKILL.md index de63792f72..4fbfa1a876 100644 --- a/.agents/skills/dsh-client-ui-ux/SKILL.md +++ b/.agents/skills/dsh-client-ui-ux/SKILL.md @@ -7,6 +7,13 @@ description: Design and review DeepSeek Harness client UI changes — visual tok This skill is guidance, not a complete checklist. It covers judgment calls that lint, typecheck, and the i18n gate cannot make: where feedback appears, what gets reused, and how surfaces behave at window edges and across platforms. Copy quality itself follows [dsh-prose-standard](../dsh-prose-standard/SKILL.md); locale ownership follows the [locale-owned copy decision](../../notes/implemented/architecture/2026-08-23-locale-owned-client-ui-copy.md); styling ownership and token rules live in [docs/web-styling.md](../../../docs/web-styling.md) and the [ui-primitives component catalog](../../../packages/client/ui-primitives/README.md#component-catalog) — this skill adds judgment on top of those rules, not a second copy of them. +## Architecture prerequisites + +Component structure, state flow, and effect usage follow the architecture rules; read them before redesigning a component: + +- [packages/client/AGENTS.md](../../../packages/client/AGENTS.md) — Slot and props discipline, reactive read, export, ctx, and layering rules. +- [Client component rules](../../../docs/defensive-patterns/client-components.md) — those requirements stated with the defects they prevent. + ## Visual foundation - **Use existing tokens for color, radius, and spacing.** Before introducing a literal value, search the target page and its nearest established sibling (the Plugins page is the usual reference for full-page surfaces) for the token or value already in use, and adopt it. The same applies to whole treatments — toasts, menus, in-message artifact previews, sidebar tab layout, colors, clearance rules, page padding: reuse the established component or rule wherever one exists instead of inventing a parallel one. @@ -24,7 +31,7 @@ This skill is guidance, not a complete checklist. It covers judgment calls that ## Feedback surfaces -Choose the surface by the lifetime of the message relative to the surface that produced it: +Apply [dsh-error-handling](../dsh-error-handling/SKILL.md#localized-actionable-visible-reports) to failure reports. Choose the surface by the lifetime of the message relative to the surface that produced it: - **Transient operation outcomes use the app-wide Toast primitive**, not in-place notices, and the toast's state and rendering live in a host that outlives the reporting surface (a `shell.overlay` entry, as RowActionToast does) — a toast rendered by the panel itself unmounts with that panel. A deletion can close the panel or tab that requested it; only a toast held outside that surface survives the close. Report success and failure; do not report still-pending states. - **A failed operation keeps the data visible.** A failed deletion keeps its row; the toast announces the failure. Never blank content to show an error for a transient operation. @@ -47,6 +54,10 @@ Every menu, popover, and tooltip must be verified for all three before merge: Scrollbars stay inside their container: use the shared scrollbar styles rather than component-specific selectors, and verify the bar neither overflows the container nor gets clipped by its rounded corners or edges — keep a small inset instead of letting it sit flush against the container edge. +## Responsive layouts + +Use [dsh-responsive-ui](../dsh-responsive-ui/SKILL.md) for responsive layouts, text truncation, title wrapping, icon-only controls, and focus during width changes. + ## Platform window adaptation - Any new header element or full page must account for macOS and Windows window chrome. On macOS the titlebar clearance is `--dsh-frame-top-clearance`, consumed by Menu, Modal, and overlay primitives as their top safe margin — **never change the global variable to fix one page**. Add a scoped `[data-platform='darwin']` override on the page's own inset instead, and assert the override in the page's stylesheet spec. diff --git a/.agents/skills/dsh-code-review/SKILL.md b/.agents/skills/dsh-code-review/SKILL.md index 484cd1c288..ff242b4819 100644 --- a/.agents/skills/dsh-code-review/SKILL.md +++ b/.agents/skills/dsh-code-review/SKILL.md @@ -7,14 +7,22 @@ description: Use when reviewing a pull request in the deepseek-harness repo — **This skill is guidance, not a complete checklist.** Verify and fetch the PR's live base and exact head, then run `pnpm --silent run change-scope --base --head ` before reading the diff and enough surrounding code to understand the design. The report identifies paths and dirty layers but does not replace semantic review. Re-establish the base and rerun it after a retarget or merge. Prioritize correctness, lifecycle, security, and broken required behavior over style; a short review with one substantiated blocker is better than a list of nits. +**Read the requirements before judging the diff.** Map the changed paths to the artifacts below, open each owning page from [Sources of truth](#sources-of-truth), and only then read the diff against those requirements. Judging a diff against memory of the rules is how a violation passes review. + ## Sources of truth - [AGENTS.md](../../../AGENTS.md) and [packages/AGENTS.md](../../../packages/AGENTS.md): standing repository and package authoring rules. -- [docs/defensive-patterns.md](../../../docs/defensive-patterns.md): subprocess, callback, async-state, and disposal bug classes. +- [docs/defensive-patterns/](../../../docs/defensive-patterns/README.md): the architecture requirements a change must satisfy and the habits behind them. Each page owns one artifact; read every page the diff touches: + - [general.md](../../../docs/defensive-patterns/general.md) — timing, async state, value representation, shared ownership, decentralization, refactors, migrations, performance evidence, disposal, callbacks, subprocesses. + - [package-surface.md](../../../docs/defensive-patterns/package-surface.md) — exports, package shape, build faces, dependency declarations, resolve hooks. + - [remote-and-api.md](../../../docs/defensive-patterns/remote-and-api.md) — remote services, `@Remote` methods, API dispatch, business ownership in `packages/api`. + - [client-components.md](../../../docs/defensive-patterns/client-components.md) — client components, slots, stores, hooks, effects, shared base packages. + - [conversation-and-session.md](../../../docs/defensive-patterns/conversation-and-session.md) — projection reads, Session retention, conversation nodes, renderers. - [docs/AGENTS.md](../../../docs/AGENTS.md): documentation placement and prose discipline. - [dsh-prose-standard](../dsh-prose-standard/SKILL.md): required coverage and editorial judgment for comments, docs, prompts, and visible strings. - [dsh-ci-test-reliability](../dsh-ci-test-reliability/SKILL.md): isolation and regression-proof rules for resource-owning, asynchronous, or flaky tests and fixtures. - [dsh-client-ui-ux](../dsh-client-ui-ux/SKILL.md): feedback-surface choice, overlay safety, platform window adaptation, and visual token discipline for product-user-visible GUI changes. +- [dsh-error-handling](../dsh-error-handling/SKILL.md): failure classification, handling ownership, containment, state guarantees, and actionable reports. - [docs/testing.md](../../../docs/testing.md) and the [quality-gates reference](../../../docs/testing.md): required test tiers and gates. - [Agent Notes](../../notes/README.md): design rationale. Treat disagreement with an Agent Note as a design discussion, not an automatic veto. - For bilingual changes, read [translation-rules.md](../../../docs/i18n/translation-rules.md) and [terminology.md](../../../docs/i18n/terminology.md); the extended translation skill is outside automatic review and runs only on explicit user invocation. @@ -31,7 +39,8 @@ description: Use when reviewing a pull request in the deepseek-harness repo — ## Manual checks - **Intent and interface contracts:** trace both sides of every changed interface. Confirm the implementation matches the PR and any Agent Note, including errors, cancellation, ownership, and disposal. -- **Lifecycle and concurrency:** for async setup, callbacks, processes, or teardown, apply [defensive-patterns.md](../../../docs/defensive-patterns.md). Check races before publication, cancellation during awaits, independent error reporting, callback containment, ownership before reentry, complete detach cleanup, and quiescent disposal. +- **Error handling:** apply [dsh-error-handling](../dsh-error-handling/SKILL.md) to changed failure paths, including their state guarantees and final user-visible reports. Reject catch-and-continue unless the state owner establishes that subsequent work's preconditions hold, including after recovery. +- **Lifecycle and concurrency:** for async setup, callbacks, processes, or teardown, apply [defensive-patterns/general.md](../../../docs/defensive-patterns/general.md). Check races before publication, cancellation during awaits, independent error reporting, callback containment, ownership before reentry, complete detach cleanup, and quiescent disposal. - **Capability and consumer fit:** trace every current consumer, then flag consumer-specific behavior leaking into the interface under [the package rules](../../../packages/AGENTS.md). Flag the inverse too: a new public method on a generic service (registry, session, agent) whose only caller is one internal consumer is an unnecessary API expansion — require a private capability closure handed to that consumer at construction instead. - **Scope, ownership, and necessity:** map each abstraction, state machine, option, defensive copy, and compatibility path to its current contract, production consumer, and owning plugin or service. Challenge unrelated features and speculative generality, then test the PR against [the root rules](../../../AGENTS.md#conventions). - **Configuration and public choices:** ask what current-consumer evidence or prior art supports each default, public operation set, format, or imported external concept. Require an explicit choice or deferral when that evidence is absent. diff --git a/.agents/skills/dsh-doc/templates/persistence-change.md b/.agents/skills/dsh-doc/templates/persistence-change.md index 4d5e720254..f31867aaaf 100644 --- a/.agents/skills/dsh-doc/templates/persistence-change.md +++ b/.agents/skills/dsh-doc/templates/persistence-change.md @@ -13,7 +13,7 @@ kind: persistence-change ## Skeleton -The generator fills the machine declaration, schema companion, and consistency records, inferring the minimum version decision from the fixed rules. Supply `--prose` JSON with `en` and `zh` objects, each containing authored `summary`, `compatibility`, and `verification` strings; the [cookbook](../../../../docs/cookbook/reviewing-persistence-type-changes.md) shows the complete operation. The following values illustrate the document fields; use the actual generated root names, record ids, and digests. +The generator fills the machine declaration, schema companion, and consistency records. Structural changes outside the established same-version cases require an explicit compatibility decision. Supply `--prose` JSON with `en` and `zh` objects, each containing authored `summary`, `compatibility`, and `verification` strings. Use Compatibility to explain both reader directions and Verification to record executed checks. The [cookbook](../../../../docs/cookbook/reviewing-persistence-type-changes.md) shows the operation. Use the actual generated root names, record ids, and digests in the following fields. ````markdown # Persistence change: @@ -48,7 +48,7 @@ changes: ## Compatibility -Explain the declared decision for the detected paths. For an optional addition, explain why existing records can omit it and older readers can ignore it without changing replay. For required-to-optional changes, explain how readers handle absence. For a version bump, link the adjacent migration and its verification owner. +Explain the declared decision for every detected path: how older readers preserve meaning, safely ignore optional data, or refuse required features before execution or recovery; and how new readers preserve historical meaning and mixed representations. Feature absence retains existing behavior. For a version bump, link the adjacent migration and its verification owner. ## Verification @@ -66,8 +66,8 @@ None. - Keep exactly one `yaml persistence-change` block. The English and Chinese blocks are byte-identical; the verifier parses the English record once and checks its counterpart. - The filename stem and `id` agree. A root's `previous` identifies its predecessor record; `null` introduces a root. Its `after` matches the generated companion schema digest; `null` records deletion. - One initial `baseline: true` record covers the complete inventory. Routine changes use `baseline: false` and preserve accepted predecessors. A version-bump record carries its own increasing `SessionHeader.version` transition. -- Omit `--decision` in the ordinary authoring flow. An explicit value asserts the decision and cannot bypass classification or the required header increase. The command supplies no source changes or validation claims. +- Structural differences alone do not infer a bump. A same-version change requiring review needs explicit `--decision same-version`; a changed header version infers `version-bump`. An explicit decision cannot waive the required header increase. The command supplies no source changes or validation claims. - Explain only the detected persistence-type changes. This kind permits the before/after facts and historical evidence needed for that transition; behavior-only changes remain out of scope. - Record creation and terminal-record update generate the catalog pair and consistency sidecars. Review both languages and retain the generated companions. Direct prose edits still require re-recording pairing; do not hand-maintain schema nodes or digests. -- Use explicit `--update` only for an unaccepted terminal record. It rejects baselines and depended-on records; `--prose` replaces its authored explanations, while omission preserves them. Accepted records receive successors. +- Use explicit `--update` only for an unaccepted terminal record. It rejects baselines and depended-on records; `--prose` replaces its authored explanations, while omission preserves them. A flagged same-version update requires explicit `--decision same-version`; reassess the explanation against the complete transition. Accepted records receive successors. - The [folder reference](../../../../docs/persistence-changes/README.md) owns compatibility rules; the [cookbook](../../../../docs/cookbook/reviewing-persistence-type-changes.md) owns commands and recovery. diff --git a/.agents/skills/dsh-error-handling/SKILL.md b/.agents/skills/dsh-error-handling/SKILL.md new file mode 100644 index 0000000000..f9dd7fd809 --- /dev/null +++ b/.agents/skills/dsh-error-handling/SKILL.md @@ -0,0 +1,30 @@ +--- +name: dsh-error-handling +description: Apply error-handling principles when designing or reviewing failures, recovery, retries, background tasks, and user-visible error reports. +--- + +# DeepSeek Harness Error Handling + +Define failures, their owners, and what remains safe after failure. + +## Typed, structured failures + +Expected failures need declared types, stable discriminants, and handling-relevant details. Reuse package error conventions, preserve causes, and separate machine identity from display text. Never route handling by parsing messages. Unexpected defects such as `assertNever` may remain plain `Error`; containment must never turn them into success. + +## Catch, recover, or stop + +For each failure, define handling and reporting owners, containment, and guarantees in the owning API documentation: valid invariants, absent/partial/committed/unknown effects, and cleanup responsibility. Background work retains these obligations. + +Catching limits exception propagation, not mutations. Only the affected state's owner can establish safe continuation. Otherwise stop dependent work, discard invalid state or instances, or escalate. Logging alone is not recovery. Retries require safe repetition, cancellation, and an explicit owner; finite operations need budgets, while continuing supervision needs lifecycle ownership and observable degradation. + +## Localized, actionable, visible reports + +Every final report needs a readable summary, affected operation, and safe next action. Localize through the receiving application's locale mechanism where one exists; other diagnostics use their existing output language. Keep sensitive internal details out of user-facing text. + +Untrusted state or unknown outcomes must be visible through UI or default-enabled, accessible logs: report the impact, uncertainty, system disposition, and safe next step. Persistent invalid state needs persistent visibility. Never claim success, rollback, or safe retry without guarantees. Reporting failures need an independent fallback. + +Verify resulting state and visible outcomes, not merely that an exception was caught. + +## Foundations + +Meyer's *Object-Oriented Software Construction* (1997): contracts and invariants; Sutter's *Exceptional C++* (1999): exception safety guarantees; Armstrong's [thesis](https://www.erlang.org/download/armstrong_thesis_2003.pdf) (2003): isolation and supervision. diff --git a/.agents/skills/dsh-find-simplifications/SKILL.md b/.agents/skills/dsh-find-simplifications/SKILL.md index fe98baba29..46955d8abd 100644 --- a/.agents/skills/dsh-find-simplifications/SKILL.md +++ b/.agents/skills/dsh-find-simplifications/SKILL.md @@ -9,7 +9,7 @@ Find changes that remove maintained obligations: APIs, representations, lifecycl ## Establish scope and constraints -Read `AGENTS.md`, [architecture](../../../docs/architecture.md) before judging packages, [defensive patterns](../../../docs/defensive-patterns.md), and [testing policy](../../../docs/testing.md). Consult the relevant active Agent Notes for intentional decisions; use the [note rules](../../notes/README.md) for new records. Archived notes are historical examples, not current authority: never inspect, verify, or repair their outbound links. +Read `AGENTS.md`, [architecture](../../../docs/architecture.md) before judging packages, [defensive patterns](../../../docs/defensive-patterns/README.md), and [testing policy](../../../docs/testing.md). Consult the relevant active Agent Notes for intentional decisions; use the [note rules](../../notes/README.md) for new records. Archived notes are historical examples, not current authority: never inspect, verify, or repair their outbound links. The two LLM adapters are intentional. JSONL is the sole first-party Session persistence provider, while the backend-neutral Service Definition supports out-of-tree providers. Do not propose deleting an LLM twin or the persistence seam unless the user explicitly overrides that constraint. Unused members within a protected design remain candidates when their removal preserves its purpose. diff --git a/.agents/skills/dsh-official-plugin-artwork/SKILL.md b/.agents/skills/dsh-official-plugin-artwork/SKILL.md new file mode 100644 index 0000000000..2336c7dbc5 --- /dev/null +++ b/.agents/skills/dsh-official-plugin-artwork/SKILL.md @@ -0,0 +1,37 @@ +--- +name: dsh-official-plugin-artwork +description: Draw and review official DeepSeek Harness plugin icons, including experimental plugins. Use for package icon.svg assets and PluginArtwork glyphs; covers semantic references, proportions, lettering, transparency, package metadata, and designer review. Not for toolbar or action icons. +--- + +# Official plugin artwork + +Draw recognizable artwork that belongs beside the existing official icons. Official and official experimental plugins share this visual language; the UI label communicates experimental status. This guidance does not replace designer approval. + +## Establish the subject + +- Inspect the actual feature, its output, and its owning manifest before drawing. A badge-producing skill may need a tag, not a medal. Reuse designer-supplied assets; do not invent a brand mark or change product names, identifiers, or unrelated icons without approval. +- Read the [existing artwork](../../../packages/client/ui-primitives/src/plugin-artwork.tsx) and the nearest relevant package SVGs. Borrow one coherent treatment, not every reference's effects. Action icons remain with [dsh-client-ui-ux](../dsh-client-ui-ux/SKILL.md#reuse-before-adding). +- Check every affected entry, list, detail, and component row. Bundle artwork and a component's name and icon can have separate metadata owners; changing one does not update the other. + +## Draw and refine + +1. **Start simple.** Use one dominant subject and only the detail needed to explain it. Related capabilities can share a metaphor; distinguish them through proportions, silhouette, or palette rather than extra panels, symbols, or badges. +2. **Judge optical size.** Use `width="36" height="36" viewBox="0 0 36 36"`. Center the artwork with deliberate margins; 18–22 units is a useful starting extent, not a requirement for every silhouette or wide text tag. The [page renderer](../../../packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx) owns display sizes and outer tile framing. Do not bake that tile into the SVG or enlarge a toolbar glyph to fill it. +3. **Keep geometry consistent.** Balance the main subject and secondary element. Align repeated marks and corners; keep tails and handles intentional. Refine one requested dimension at a time without changing approved parts. +4. **Use restrained color by default.** Balance saturation and brightness with neighboring icons; prefer existing palettes such as [Auto Authorization Review](../../../packages/experimental/auto-review/icon.svg) and [Codex subagent](../../../packages/subagent/subagent-codex/icon.svg). Reserve unusually vivid, bright, or neon colors for approved brand requirements, essential contrast, or explicit designer direction. Tune saturation separately from hue and lightness; do not make artwork gray or muddy merely to reduce saturation. Keep flat fills or short gradients and limited layering; avoid glow, drop shadows, glossy highlights, and emoji. Page CSS still uses semantic theme tokens. +5. **Align lettering by visible ink.** Use consistent letterforms, cap height, baseline, weight, and spacing. Compare rendered stroke edges, not just path coordinates: stroke caps and joins can make equal coordinates appear unequal. Export lettering as paths without a font dependency, and keep it readable at actual size. +6. **Make empty areas genuinely transparent.** A hollow lens must reveal the background, including where it overlaps another shape. Remove the underlying fill with a local mask or cutout; do not substitute a white or dark disk. Check both themes. + +## Export at the owner + +- Use the manifest's `icon` path and publish its resources. Update intentional bundle/component copies together; verify localized display names and descriptions when those are in scope. Do not change the feature's produced assets merely to change its plugin icon. +- Package images render through ``: export self-contained SVG geometry with local, uniquely named gradient, mask, and clip references. No scripts, event handlers, animation, external images/styles, fonts, or `foreignObject`. Inline React artwork needs per-instance IDs; separate image documents do not share IDs. +- Keep the asset change local. Do not add runtime dependencies, primitive exports, or renderer special cases just to display it. + +## Review and verify + +1. Show a few numbered alternatives before polishing uncertain geometry. Preserve their labels through review and apply the chosen version; an existing file or generated draft does not establish designer approval. Keep comparison artifacts in a gitignored directory, not the product package. +2. Compare old and new artwork beside unchanged references in light and dark themes, at actual row/card sizes as well as enlarged. Check balance, lettering, empty space, clipping, and image decoding. +3. Run `pnpm run verify-package-meta` for [package metadata and SVG artwork](../../../scripts/verify-package-meta.ts), `pnpm run constraints` for the canonical package payload, and `pnpm run verify-official-bundle-catalog`. Regenerate a stale catalog with `pnpm run gen-official-bundle-catalog`, never by hand. Structural checks do not replace visual review. +4. Build affected artifacts and inspect the real page through `dsh web`. Batch approved refinements before restarting a metadata-caching Host, then verify the entry and nested component rows in both themes. +5. Follow the repository's UI testing policy and [record-browser-gif](../record-browser-gif/SKILL.md) for a GUI PR. Obtain designer approval before landing new glyphs. Record reusable drawing principles here, not the history of rejected drafts. 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/.agents/skills/dsh-responsive-ui/SKILL.md b/.agents/skills/dsh-responsive-ui/SKILL.md new file mode 100644 index 0000000000..a9ee2f3a37 --- /dev/null +++ b/.agents/skills/dsh-responsive-ui/SKILL.md @@ -0,0 +1,54 @@ +--- +name: dsh-responsive-ui +description: Use when designing, implementing, or reviewing responsive client layouts, text truncation, title wrapping, icon-only controls, mobile hover, tooltips and keyboard behavior, and focus during width changes in DeepSeek Harness. +--- + +# Responsive client UI + +## 1. Minimum viewport + +Use a viewport width of 390 CSS px as the primary acceptance minimum. There must be no unintended overlap, clipping, page-wide horizontal scrolling, or inaccessible primary actions. Below 390px, layout requirements may be relaxed. + +## 2. Decision order + +1. First adjust space allocation or wrap elements onto another line; then consider text truncation, icon-only controls, or moving icons into the More menu. +2. Primary actions and primary states must not be omitted. +3. Do not hide conflicts through global clipping, reducing all font sizes, or shrinking click targets. +4. Reduce font sizes only when specifically required by product design. + +## 3. Text truncation + +1. Truncated content must be fully available on a secondary page or by opening a menu. Example: Session statistics below the input box. +2. Truncation must not lose errors or other key information. +3. Prefer single-line truncation for tab navigation, visible selectors, buttons, tags, and similar components. +4. Important information that is not available on another page must be displayed in full without truncation. + +## 4. Titles + +1. Prefer displaying page titles in full. Move the action area onto another line when necessary. Example: the Plugins page's title wrapping behavior. +2. Prefer natural wrapping for card titles. If the number of lines is limited, the full title must remain available to view. + +## 5. Icon-only controls + +1. Reducing a control to an icon requires both: + - The icon clearly conveys its meaning, or the operation is familiar to users. + - A tooltip appears on hover; add one if needed. +2. Do not reduce “More account information” to an icon, because it navigates to a separate page. +3. The model selector in the input box can be reduced to an icon because users see it frequently and can open its menu to switch models. +4. Another example is the linked conversation in an automation task. + +## 6. Mobile hover behavior + +1. Enable mouse-hover effects only on devices that support hovering. Use `@media (hover: hover)`, not viewport width, to determine this. +2. Tapping on a phone must not leave behind backgrounds, highlights, or action-button visibility intended only for hover. +3. Preserve normal selected, enabled, and pressed states, as well as focus indicators for keyboard interaction. +4. Try to preserve focus when the width changes, unless the focused element disappears from the page as a result. + +## 7. Mobile tooltips + +1. Do not show tooltips that only provide auxiliary information such as action names or keyboard shortcuts on mobile. For example, omit the “Copy” tooltip on a copy button; tapping still performs the original action directly. +2. Tooltips that provide supplementary explanations must support tap-to-show on mobile. For example, the information tooltip beside the Plugins page description. + +## 8. Mobile keyboard + +On mobile, do not raise the input keyboard automatically unless it is explicitly intended. diff --git a/.agents/skills/dsh-speed-up-perf/SKILL.md b/.agents/skills/dsh-speed-up-perf/SKILL.md index f8b5eb6141..491e39f81c 100644 --- a/.agents/skills/dsh-speed-up-perf/SKILL.md +++ b/.agents/skills/dsh-speed-up-perf/SKILL.md @@ -9,7 +9,7 @@ Turn a broad “make it faster” request into reproducible user-path measuremen ## Establish scope and current authority -Read [AGENTS.md](../../../AGENTS.md), [architecture](../../../docs/architecture.md), [testing policy](../../../docs/testing.md), [defensive patterns](../../../docs/defensive-patterns.md), and the affected packages’ instructions and Agent Notes. Use [CI test reliability](../dsh-ci-test-reliability/SKILL.md) for processes, clocks, browser tests, and asynchronous cleanup. +Read [AGENTS.md](../../../AGENTS.md), [architecture](../../../docs/architecture.md), [testing policy](../../../docs/testing.md), [defensive patterns](../../../docs/defensive-patterns/README.md), and the affected packages’ instructions and Agent Notes. Use [CI test reliability](../dsh-ci-test-reliability/SKILL.md) for processes, clocks, browser tests, and asynchronous cleanup. Agree on the user-visible endpoint, workload range, resource constraints, acceptable minor behavior differences, and stopping rule. Keep backend and browser end-to-end measurements separate: a fast history iterator or Client fold does not prove fast transport, paint, scrolling, or input response. Exclude model/network latency when measuring local overhead, and state that exclusion rather than calling the result complete product latency. diff --git a/.github/AGENTS.md b/.github/AGENTS.md index 7cc2946f53..cb71142444 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -1,3 +1,7 @@ # AGENTS.md — GitHub Actions Run jobs on Windows runners (`windows-*` labels) under native `pwsh`. Native Windows build and process checks contribute to the pull-request `all checks passed` verdict; Wine runs Windows Node on hosted Linux only in `ci-master.yml`. Python runtime CI checks Linux/Windows x64 on pull requests and Linux ARM64 plus both macOS architectures on master pushes; releases retain all five targets ([platform policy](workflows/ci-master.yml)). `ci.yml` is pull-request-only. Master-only platform checks, Linux/Windows self-hosted standbys, and manual runner benchmarks live in `ci-master.yml`, which listens to master pushes and `workflow_dispatch`, not `pull_request`; separating workflow triggers keeps master-only jobs out of PR check panels. The master standbys validate the self-hosted failover targets; preserve the existing per-platform switches (values `selfhosted` for the in-house standbys and `blacksmith` for Blacksmith's hosted runners) and the Dependabot hosted fallback under the `selfhosted` values ([failover runbook](../.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md), [blacksmith failover leg note](../.agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.md)). + +The manual [Windows packaging workflow](workflows/windows-package.yml) uses the dedicated self-hosted Windows x64 label `dsh-win-package-trial` under native `pwsh`; preserve this routing separately from the automatic CI lanes. + +The Desktop publication workflow routes each retained build through `DESKTOP_PUBLISH_RUNNERS` to its original machine's unique label. Keep Windows run steps on native PowerShell and Mac run steps on the default POSIX shell; shared entrypoints are Node scripts. Test and production jobs use separate `desktop-test` and `desktop-production` approval Environments after a credential-free preparation job. 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-exe-for-ssh-helper.yml b/.github/workflows/build-exe-for-ssh-helper.yml new file mode 100644 index 0000000000..15455ddda2 --- /dev/null +++ b/.github/workflows/build-exe-for-ssh-helper.yml @@ -0,0 +1,127 @@ +name: Build SSH helper + +on: + workflow_call: + inputs: + targets: + description: Comma-separated native Node 24 targets; empty builds all four. + type: string + default: '' + release: + description: Retain a complete release build when another run starts. + type: boolean + default: false + workflow_dispatch: + inputs: + targets: + description: Linux/macOS x64/arm64 pkg targets; empty builds all four. + type: string + default: '' + +permissions: + contents: read + +concurrency: + group: ssh-helper-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ !inputs.release }} + +env: + DSH_TELEMETRY_DISABLED: '1' + +jobs: + plan: + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + matrix: ${{ steps.targets.outputs.matrix }} + steps: + - name: Validate native targets + id: targets + env: + REQUESTED_TARGETS: ${{ inputs.targets }} + run: | + node --input-type=module <<'JS' + import { appendFileSync } from 'node:fs'; + const runners = { + 'node24-linux-x64': 'ubuntu-24.04', + 'node24-linux-arm64': 'ubuntu-24.04-arm', + 'node24-macos-arm64': 'macos-latest', + 'node24-macos-x64': 'macos-15-intel', + }; + const raw = process.env.REQUESTED_TARGETS; + const targets = raw ? raw.split(',').map(value => value.trim()) : Object.keys(runners); + if (new Set(targets).size !== targets.length || targets.some(target => !Object.hasOwn(runners, target))) throw new Error('Invalid or duplicate SSH helper target'); + appendFileSync(process.env.GITHUB_OUTPUT, `matrix=${JSON.stringify(targets.map(target => ({target, runner: runners[target]})))}\n`); + JS + + build: + needs: plan + name: ${{ matrix.target }} + runs-on: ${{ matrix.runner }} + timeout-minutes: 40 + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.plan.outputs.matrix) }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + - uses: actions/setup-node@v6 + with: + node-version: 24 + cache: pnpm + - uses: actions/cache@v4 + with: + path: ~/.pkg-cache + key: ssh-pkg-${{ matrix.target }}-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: ssh-pkg-${{ matrix.target }}- + - name: Install dependencies + run: pnpm install --frozen-lockfile + - name: Prepare Linux compiler and sandbox + if: runner.os == 'Linux' + run: | + sudo apt-get update -q + sudo apt-get install -yq musl-tools bubblewrap + if sysctl kernel.apparmor_restrict_unprivileged_userns >/dev/null 2>&1; then + sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + fi + bwrap --ro-bind / / --dev /dev --unshare-pid --proc /proc --die-with-parent -- true + - name: Build compatible Linux PTY addon + if: runner.os == 'Linux' + run: bash scripts/prepare-linux-node-pty.sh + - name: Build native release archive + env: + HELPER_TARGET: ${{ matrix.target }} + run: pnpm exec tsx scripts/build-exe-for-ssh-helper.ts --target="$HELPER_TARGET" + - name: Verify relocated executable and confinement + env: + HELPER_TARGET: ${{ matrix.target }} + run: | + archives=(dist-exe/ssh-helper/*.tar.gz) + test "${#archives[@]}" -eq 1 + pnpm exec tsx scripts/verify-ssh-helper-artifact.ts --archive="${archives[0]}" --sandbox=required --report="dist-exe/ssh-helper/$HELPER_TARGET.json" + - name: Verify the packaged Landlock backend + if: runner.os == 'Linux' + env: + HELPER_TARGET: ${{ matrix.target }} + run: | + archives=(dist-exe/ssh-helper/*.tar.gz) + pnpm exec tsx scripts/verify-ssh-helper-artifact.ts --archive="${archives[0]}" --sandbox=required --backend=landlock-run --report="dist-exe/ssh-helper/$HELPER_TARGET.landlock.json" + - name: Verify OpenSSH on glibc 2.28 without Node + if: runner.os == 'Linux' + env: + HELPER_TARGET: ${{ matrix.target }} + run: | + archives=(dist-exe/ssh-helper/*.tar.gz) + test "${#archives[@]}" -eq 1 + pnpm exec tsx scripts/verify-ssh-helper-ssh.ts --archive="${archives[0]}" --report="dist-exe/ssh-helper/$HELPER_TARGET.ssh.json" + - name: Upload verified archive and evidence + uses: actions/upload-artifact@v7 + with: + name: ssh-helper-${{ matrix.target }} + path: dist-exe/ssh-helper/* + if-no-files-found: error 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/ci-master.yml b/.github/workflows/ci-master.yml index 5feb9fb33c..5620e6af63 100644 --- a/.github/workflows/ci-master.yml +++ b/.github/workflows/ci-master.yml @@ -13,6 +13,7 @@ on: options: - larger-runner-benchmark - consolidated-runner-benchmark + - ssh-helper # New master pushes and manual runs replace obsolete checks in this workflow/ref. # Standby drills share cancellation; use completed runs as readiness evidence. @@ -30,6 +31,13 @@ env: DSH_TELEMETRY_DISABLED: '1' jobs: + ssh-helper: + if: github.event_name == 'workflow_dispatch' && inputs.suite == 'ssh-helper' + name: ssh helper / native artifacts + uses: ./.github/workflows/build-exe-for-ssh-helper.yml + with: + targets: node24-linux-x64,node24-linux-arm64,node24-macos-arm64,node24-macos-x64 + # These native runtime carriers are post-merge checks; release keeps all targets. python-runtime: if: github.event_name == 'push' && github.ref == 'refs/heads/master' diff --git a/.github/workflows/desktop-publish.yml b/.github/workflows/desktop-publish.yml new file mode 100644 index 0000000000..8e494386e2 --- /dev/null +++ b/.github/workflows/desktop-publish.yml @@ -0,0 +1,131 @@ +name: Publish Desktop · COS + +on: + workflow_run: + workflows: ['Package Desktop · macOS', 'Package Desktop · Windows'] + types: [completed] + +permissions: + contents: read + actions: read + +jobs: + route: + if: github.event.workflow_run.conclusion == 'success' + runs-on: ubuntu-latest + outputs: + publish: ${{ steps.route.outputs.publish }} + route: ${{ steps.route.outputs.route }} + runner: ${{ steps.route.outputs.runner }} + preset: ${{ steps.route.outputs.preset }} + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - uses: pnpm/action-setup@v5.0.0 + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - run: pnpm install --frozen-lockfile + - name: Resolve original package and machine + id: route + env: + GH_TOKEN: ${{ github.token }} + DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }} + run: node --import tsx apps/desktop/scripts/resolve-desktop-publish-ci.ts + + prepare: + needs: route + if: needs.route.outputs.publish == 'true' + runs-on: [self-hosted, '${{ needs.route.outputs.runner }}'] + timeout-minutes: 30 + outputs: + approval: ${{ steps.check.outputs.approval }} + label: ${{ steps.check.outputs.label }} + env: + DESKTOP_PUBLISH_ROUTE: ${{ needs.route.outputs.route }} + DSH_TELEMETRY_DISABLED: '1' + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + clean: false + path: desktop-publisher + - uses: pnpm/action-setup@v5.0.0 + with: + package_json_file: desktop-publisher/package.json + dest: ${{ runner.temp }}/publish-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - run: pnpm install --frozen-lockfile + working-directory: desktop-publisher + - name: Verify local package without upload credentials + id: check + working-directory: desktop-publisher + run: node --import tsx apps/desktop/scripts/publish-desktop-ci.ts --check + + publish: + name: Approve ${{ needs.prepare.outputs.label }} + needs: [route, prepare] + if: needs.route.outputs.publish == 'true' + runs-on: [self-hosted, '${{ needs.route.outputs.runner }}'] + environment: ${{ needs.route.outputs.preset == 'production' && 'desktop-production' || 'desktop-test' }} + concurrency: + group: desktop-publish-${{ needs.route.outputs.runner }}-${{ needs.route.outputs.preset }} + cancel-in-progress: false + timeout-minutes: 90 + env: + DESKTOP_APPROVED_PACKAGE: ${{ needs.prepare.outputs.approval }} + DESKTOP_PUBLISH_ROUTE: ${{ needs.route.outputs.route }} + DSH_TELEMETRY_DISABLED: '1' + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + clean: false + path: desktop-publisher + - uses: pnpm/action-setup@v5.0.0 + with: + package_json_file: desktop-publisher/package.json + dest: ${{ runner.temp }}/publish-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - run: pnpm install --frozen-lockfile + working-directory: desktop-publisher + - name: Verify local package without upload credentials + id: check + working-directory: desktop-publisher + run: node --import tsx apps/desktop/scripts/publish-desktop-ci.ts --check + - name: Read machine GitHub App key + if: needs.route.outputs.preset == 'production' + id: key + env: + APP_KEY_FILE: ${{ steps.check.outputs.app-key-file }} + working-directory: desktop-publisher + run: node apps/desktop/scripts/read-desktop-app-key.mjs + - name: Create short-lived tag token + if: needs.route.outputs.preset == 'production' + id: app + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 + with: + client-id: ${{ steps.check.outputs.app-client-id }} + private-key: ${{ steps.key.outputs.private-key }} + owner: ${{ github.repository_owner }} + repositories: ${{ github.event.repository.name }} + permission-contents: write + - name: Publish files, update feeds and record release tag + id: publish + working-directory: desktop-publisher + env: + DESKTOP_TAG_TOKEN: ${{ steps.app.outputs.token }} + run: node --import tsx apps/desktop/scripts/publish-desktop-ci.ts --publish + - name: Retain publication audit + if: always() && steps.publish.outputs.record != '' + uses: actions/upload-artifact@v7.0.1 + with: + name: desktop-publication-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ steps.publish.outputs.record }}/ + if-no-files-found: error + retention-days: 30 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/macos-package.yml b/.github/workflows/macos-package.yml new file mode 100644 index 0000000000..c88de36c66 --- /dev/null +++ b/.github/workflows/macos-package.yml @@ -0,0 +1,145 @@ +name: Package Desktop · macOS + +on: + workflow_dispatch: + inputs: + preset: + description: 'Machine preset (configured on the packaging runner)' + type: choice + options: [test, production] + default: test + required: true + skip_notarization: + description: 'Skip notarization/stapling: internal debugging only, not for distribution or updates' + type: boolean + default: false + required: true + publish: + description: 'Publish successful signed packages and update the feed; test and production require approval' + type: boolean + default: false + required: true + test_release_id: + description: '测试环境的前缀,用于隔离外部用户访问,留空使用默认配置;测试连续升级时需使用相同值;建议定期轮换默认值。' + type: string + default: '' + required: false + source_ref: + description: 'Source: master or a dsh-v* tag containing the Desktop CI adapters' + type: string + default: master + required: true + update_channel: + description: 'Installer update channel; automatic updates stay on this channel' + type: choice + options: [nightly, latest] + default: nightly + required: true + version_mode: + description: 'default: production follows product, test auto; manual uses build_version' + type: choice + options: [default, product, auto, manual] + default: default + required: true + build_version: + description: 'Manual version only: product version or its supported prerelease suffix' + type: string + default: '' + required: false + +permissions: + contents: read + +concurrency: + group: macos-desktop-package + cancel-in-progress: false + +jobs: + package: + runs-on: [self-hosted, macOS, ARM64, dsh-mac-package-trial] + timeout-minutes: 180 + defaults: + run: + shell: bash + env: + PACKAGE_SKIP_NOTARIZATION: ${{ inputs.skip_notarization }} + PACKAGE_SOURCE_REF: ${{ inputs.source_ref }} + PACKAGE_VERSION_MODE: ${{ inputs.version_mode }} + DSH_DESKTOP_UPDATE_CHANNEL: ${{ inputs.update_channel }} + DSH_TELEMETRY_DISABLED: '1' + DSH_PACKAGING_PRESET: ${{ inputs.preset }} + PACKAGE_PUBLISH: ${{ inputs.publish }} + PACKAGE_TEST_RELEASE_ID: ${{ inputs.test_release_id }} + steps: + - uses: actions/checkout@v7.0.1 + id: checkout + with: + persist-credentials: false + clean: true + ref: ${{ inputs.source_ref }} + - name: Validate selected source and adapter support + run: >- + node -e "const fs=require('node:fs'); const ref=process.env.PACKAGE_SOURCE_REF; + if(ref!=='master' && !/^dsh-v[0-9][0-9A-Za-z.-]*$/.test(ref)) throw Error('Select master or dsh-v*'); + const v=JSON.parse(fs.readFileSync('package.json','utf8')).version; + if(ref!=='master' && ref!=='dsh-v'+v) throw Error('Source tag must match product version'); + if(!fs.readFileSync('apps/desktop/scripts/desktop-ci-version.mjs','utf8').includes('PACKAGE_VERSION_MODE')) throw Error('Source lacks Desktop channel/version CI support; select a newer release');" + - uses: pnpm/action-setup@v5.0.0 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - name: Install locked dependencies + run: pnpm install --frozen-lockfile + - name: Validate preset and resolve build version + id: settings + env: + PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} + run: node apps/desktop/scripts/prepare-macos-ci.mjs + - name: Check packaging configuration and toolchain + env: + PACKAGE_VERSION: ${{ steps.settings.outputs.version }} + run: | + args=() + if [[ "$PACKAGE_SKIP_NOTARIZATION" = true ]]; then args+=(--skip-notarization); fi + pnpm run package:desktop:mac:arm64 --check --build-version "$PACKAGE_VERSION" "${args[@]}" + - name: Build signed installers + env: + PACKAGE_VERSION: ${{ steps.settings.outputs.version }} + run: | + args=() + if [[ "$PACKAGE_SKIP_NOTARIZATION" = true ]]; then args+=(--skip-notarization); fi + pnpm run package:desktop:mac:arm64 --build-version "$PACKAGE_VERSION" "${args[@]}" + - name: Retain complete package outside the checkout + id: retained + env: + PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} + PACKAGE_VERSION: ${{ steps.settings.outputs.version }} + run: node --import tsx apps/desktop/scripts/retain-desktop-ci.ts + - name: Retain packaging diagnostics + if: always() && steps.checkout.outcome == 'success' + uses: actions/upload-artifact@v7.0.1 + with: + name: macos-package-logs-${{ github.run_id }}-${{ github.run_attempt }} + include-hidden-files: true + path: apps/desktop/.desktop-build/packaging-runs/ + if-no-files-found: warn + retention-days: 14 + - name: Retain installers for the selected mode + if: success() + uses: actions/upload-artifact@v7.0.1 + with: + name: macos-arm64-${{ steps.settings.outputs.mode }}-${{ steps.settings.outputs.version }}-${{ github.run_id }}-${{ github.run_attempt }} + include-hidden-files: true + path: ${{ steps.retained.outputs.directory }}/* + if-no-files-found: error + retention-days: 14 + - name: Retain publication request + if: success() && inputs.publish + uses: actions/upload-artifact@v7.0.1 + with: + name: desktop-publish-request-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ steps.retained.outputs.directory }}/manifest.json + if-no-files-found: error + retention-days: 14 diff --git a/.github/workflows/publish-ssh-helper.yml b/.github/workflows/publish-ssh-helper.yml new file mode 100644 index 0000000000..f6740f210c --- /dev/null +++ b/.github/workflows/publish-ssh-helper.yml @@ -0,0 +1,101 @@ +name: Release (SSH helper) + +# Validation accepts any ref; publication requires the matching dsh-v tag. +on: + workflow_dispatch: + inputs: + publish: + description: Publish verified archives to GitHub Release. Must run from the matching dsh-v tag. + type: boolean + required: true + default: false + +permissions: + contents: read + +concurrency: + group: publish-ssh-helper-${{ github.ref }} + cancel-in-progress: false + +jobs: + validate: + runs-on: ubuntu-latest + outputs: + version: ${{ steps.source.outputs.version }} + commit: ${{ steps.source.outputs.commit }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - name: Resolve source and validate publication tag + id: source + env: + PUBLISH: ${{ inputs.publish }} + run: | + node --input-type=module <<'JS' + import { readFileSync, appendFileSync } from 'node:fs'; + import { execFileSync } from 'node:child_process'; + const {version} = JSON.parse(readFileSync('package.json', 'utf8')); + if (process.env.PUBLISH === 'true' && (process.env.GITHUB_REF_TYPE !== 'tag' || process.env.GITHUB_REF_NAME !== `dsh-v${version}`)) throw new Error('Publication requires the matching dsh-v tag'); + const commit = execFileSync('git', ['rev-parse', 'HEAD'], {encoding:'utf8'}).trim(); + appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\ncommit=${commit}\n`); + JS + build: + needs: validate + uses: ./.github/workflows/build-exe-for-ssh-helper.yml + with: + release: true + verify: + needs: [validate, build] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + - uses: actions/setup-node@v6 + with: + node-version: 24 + cache: pnpm + - run: pnpm install --frozen-lockfile + - uses: actions/download-artifact@v8 + with: + pattern: ssh-helper-node24-* + path: dist-exe/ssh-helper + merge-multiple: true + - name: Require complete evidence from the selected source commit + env: + RELEASE_VERSION: ${{ needs.validate.outputs.version }} + SOURCE_COMMIT: ${{ needs.validate.outputs.commit }} + run: pnpm exec tsx scripts/ssh-helper/release.ts --directory=dist-exe/ssh-helper --version="$RELEASE_VERSION" --commit="$SOURCE_COMMIT" + - name: Upload verified release checksums + uses: actions/upload-artifact@v7 + with: + name: ssh-helper-release-checksums + path: dist-exe/ssh-helper/SHA256SUMS + if-no-files-found: error + + publish: + if: inputs.publish + needs: [validate, verify] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@v8 + with: + pattern: ssh-helper-* + path: dist-exe/ssh-helper + merge-multiple: true + - name: Attach the verified archives to the GitHub release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RELEASE_TAG: ${{ github.ref_name }} + run: | + if ! gh release view "$RELEASE_TAG" >/dev/null 2>&1; then + gh release create "$RELEASE_TAG" --verify-tag --draft --title "$RELEASE_TAG" --notes 'SSH helper executables for Linux and macOS.' + fi + gh release upload "$RELEASE_TAG" dist-exe/ssh-helper/*.tar.gz dist-exe/ssh-helper/SHA256SUMS 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 new file mode 100644 index 0000000000..320f77265b --- /dev/null +++ b/.github/workflows/windows-package.yml @@ -0,0 +1,170 @@ +name: Package Desktop · Windows + +on: + workflow_dispatch: + inputs: + preset: + description: 'Machine preset (configured on the packaging runner)' + type: choice + options: [test, production] + default: test + required: true + signing: + description: 'unsigned: test installer; signed: use the configured EV hardware token' + type: choice + options: [unsigned, signed] + default: unsigned + required: true + publish: + description: 'Publish successful signed packages and update the feed; test and production require approval' + type: boolean + default: false + required: true + test_release_id: + description: '测试环境的前缀,用于隔离外部用户访问,留空使用默认配置;测试连续升级时需使用相同值;建议定期轮换默认值。' + type: string + default: '' + required: false + source_ref: + description: 'Source: master or a dsh-v* tag containing the Desktop CI adapters' + type: string + default: master + required: true + update_channel: + description: 'Installer update channel; automatic updates stay on this channel' + type: choice + options: [nightly, latest] + default: nightly + required: true + version_mode: + description: 'default: production follows product, test auto; manual uses build_version' + type: choice + options: [default, product, auto, manual] + default: default + required: true + build_version: + description: 'Manual version only: product version or its supported prerelease suffix' + type: string + default: '' + required: false + +permissions: + contents: read + +concurrency: + group: windows-desktop-package + cancel-in-progress: false + +jobs: + package: + runs-on: dsh-win-package-trial + timeout-minutes: 120 + defaults: + run: + shell: pwsh + env: + PACKAGE_SOURCE_REF: ${{ inputs.source_ref }} + PACKAGE_VERSION_MODE: ${{ inputs.version_mode }} + DSH_DESKTOP_UPDATE_CHANNEL: ${{ inputs.update_channel }} + DSH_TELEMETRY_DISABLED: '1' + DSH_PACKAGING_PRESET: ${{ inputs.preset }} + PACKAGE_PUBLISH: ${{ inputs.publish }} + PACKAGE_TEST_RELEASE_ID: ${{ inputs.test_release_id }} + 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: + persist-credentials: false + clean: true + ref: ${{ inputs.source_ref }} + - name: Validate selected source and adapter support + run: >- + node -e "const fs=require('node:fs'); const ref=process.env.PACKAGE_SOURCE_REF; + if(ref!=='master' && !/^dsh-v[0-9][0-9A-Za-z.-]*$/.test(ref)) throw Error('Select master or dsh-v*'); + const v=JSON.parse(fs.readFileSync('package.json','utf8')).version; + if(ref!=='master' && ref!=='dsh-v'+v) throw Error('Source tag must match product version'); + if(!fs.readFileSync('apps/desktop/scripts/desktop-ci-version.mjs','utf8').includes('PACKAGE_VERSION_MODE')) throw Error('Source lacks Desktop channel/version CI support; select a newer release');" + - uses: pnpm/action-setup@v5.0.0 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - name: Install locked dependencies + run: | + pnpm install --frozen-lockfile + exit $LASTEXITCODE + - name: Validate preset and resolve build version + id: settings + env: + PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} + run: node apps/desktop/scripts/prepare-windows-ci.mjs + - name: Check packaging configuration and toolchain + env: + PACKAGE_VERSION: ${{ steps.settings.outputs.version }} + run: | + $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: | + $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 complete package outside the checkout + id: retained + env: + PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} + PACKAGE_VERSION: ${{ steps.settings.outputs.version }} + run: node --import tsx apps/desktop/scripts/retain-desktop-ci.ts + - name: Retain packaging diagnostics + if: always() && steps.checkout.outcome == 'success' + uses: actions/upload-artifact@v7.0.1 + with: + name: windows-package-logs-${{ github.run_id }}-${{ github.run_attempt }} + include-hidden-files: true + path: apps/desktop/.desktop-build/packaging-runs/ + if-no-files-found: warn + retention-days: 14 + - 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 }} + include-hidden-files: true + path: ${{ steps.retained.outputs.directory }}/* + if-no-files-found: error + retention-days: 14 + - 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: ${{ steps.retained.outputs.directory }}/* + if-no-files-found: error + retention-days: 14 + - name: Retain publication request + if: success() && inputs.publish + uses: actions/upload-artifact@v7.0.1 + with: + name: desktop-publish-request-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ steps.retained.outputs.directory }}/manifest.json + if-no-files-found: error + retention-days: 14 diff --git a/AGENTS.md b/AGENTS.md index 38e5ae46cf..7bae0a79c1 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,11 +117,12 @@ 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 -Windows packaging/signing: [required reading](apps/desktop/README.md#windows-ev-signing). +Windows packaging/signing: [required reading](apps/desktop/windows-signing/README.md). Real-API tests/demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, and root `.env`. cordis.yml allows `!!js` (never `!js`) under plugin `config` and entry `disabled`; other metadata stays literal, so conditional composition also uses overlays ([primer](docs/cordis-primer.md#loader-configuration)). Never commit credentials. CI e2e skips without a key; [testing.md](docs/testing.md) owns key policy. @@ -128,7 +131,7 @@ Real-API tests/demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, and - Packages use `@deepseek-ai/dsh-`; vendor is [rescoped](docs/rescope.md) and `private: true`. Harness packages declare `@deepseek-ai/cordis` in `peerDependencies`/`devDependencies`. Workspace dependency sections use DSH `workspace:*`, vendor/native `workspace:~` ([rules](.agents/notes/implemented/process/2026-08-10-npm-release-sequences.md)). - ESM everywhere (`"type": "module"`). Use package names across packages and `.ts` in local relative imports. Config subprocesses run built `lib/` under plain Node; source regressions use their declared launcher ([testing policy](docs/testing.md#test-subprocess-launch-modes)). The `dsh` CLI source launch runs through tsx's ESM-only hook (`node --import tsx/esm`); modules it reaches must stay ESM (no CJS-only exports) — Node's native TypeScript modes are unavailable across the engines range ([source-launch contract](.agents/notes/implemented/architecture/2026-07-29-dsh-source-launch-tsx-esm.md)). Raw/Web `cordis.yml` bare plugins must appear in their resolver manifest's `dependencies`; `verify-cordis-config` enforces it. - **Registrations are effects**: every contribution goes through `ctx.effect()` / `ctx.on()`; a registry's `register()` returns the disposer. -- **Typed events use declaration merging** and merge-extensible maps. Event JSDoc needs `@mode` and payload `@param`. Public service methods document parameters and non-void returns. `SessionEventMap` members are required-on-read by default — builds that do not know a type refuse the log unless the event carries the envelope's `ignorable: true`; only structural format changes bump `SESSION_FORMAT_VERSION` ([mechanism](.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md)). +- **Typed events use declaration merging** and merge-extensible maps. Event JSDoc needs `@mode` and payload `@param`. Public service methods document parameters and non-void returns. `SessionEventMap` members are required-on-read unless the envelope carries `ignorable: true`. Bump `SESSION_FORMAT_VERSION` only when existing discriminators cannot prevent unsafe interpretation; same-version changes require safe reader behavior ([review](.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.md)). - **Switch on discriminant tags.** Closed unions end in `assertNever`; merge-extensible unions fall through a documented default. - **Waterfall listeners MUST call `next()`** to delegate; returning without it short-circuits the chain ([semantics](docs/cordis-primer.md#cordis-waterfall-semantics)). - **Model-visible ⟺ logged**: anything that reaches a model request must be reconstructable from the session log; a new model-visible input requires a session event. @@ -143,12 +146,14 @@ Real-API tests/demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, and - **No new assertions to `unknown`** (`as unknown` or ``). Preserve or reduce the exact legacy baseline; use typed values or validation for replacements ([rule](.agents/notes/implemented/process/2026-09-19-no-unknown-casts.md)). - **Source plane vs artifact plane, never mixed.** Static gates and tests resolve workspace imports through tsconfig `paths` to `src` and pass on a clean tree; gates consuming built `lib/` declare that dependency ([layout](docs/development.md#typescript-project-layout)). - **Keep compiler faces explicit.** A package with both Host and Client programs exposes face-specific leaf configs and a solution-only root; repo-wide programs seed a face config, never the root solution ([layout](docs/development.md#typescript-project-layout)). +- **Error handling:** use typed, structured failures and localized, actionable reports. Define handling ownership, containment, and failure guarantees; stop dependent work and visibly report untrusted state or unknown outcomes. Follow [dsh-error-handling](.agents/skills/dsh-error-handling/SKILL.md). - **An empty `catch` names the error** and why; keep its `try` to one statement. - **Keep comments local.** Do not restate code, expand unrelated comments, or explain distant behavior without local need ([rationale](.agents/skills/dsh-prose-standard/SKILL.md)). - **Ban `prove` + `nance`** ([rule](.agents/notes/implemented/process/2026-08-26-ban-ambiguous-origin-label.md)). - **Prefer symmetry for parallel values**; unexplained asymmetry usually signals a missed extraction. - **Tests describe behavior, not correctness.** Change obsolete behavior with its tests; explain why in the PR. - **Create Agent Notes only for durable decision rationale;** mechanical/local edits are exempt, including local UI changes ([scope](.agents/notes/README.md#when-to-write-one)). Archived notes are frozen: never edit or treat them as current authority ([archive policy](.agents/notes/README.md#archiving-and-deletion)). +- **Official plugin artwork:** use [dsh-official-plugin-artwork](.agents/skills/dsh-official-plugin-artwork/SKILL.md) for official and official experimental plugin icons; obtain designer approval before landing new glyphs. - **Client UI copy is locale-owned.** Route product text through typed dictionaries and `t` or localized primitive props; `verify-client-ui-i18n` rejects hardcoded copy ([decision](.agents/notes/implemented/architecture/2026-08-23-locale-owned-client-ui-copy.md)). - **Testing policy** — [docs/testing.md](docs/testing.md). Every non-trivial model- or product-user-visible change updates a keyless recorded-session snapshot; [snapshot ownership](snapshots/AGENTS.md) reserves the top-level tree for session-driven cases and keeps other expected output owner-local. Fixtures replay on macOS/Linux; fix fixtures, not normalizers. - **Design each tool's UI presentation up front.** Host presenters stay pure; Web cards derive from raw events and persisted result metadata ([cookbook](docs/cookbook/adding-a-tool.md)). @@ -161,7 +166,7 @@ Real-API tests/demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, and ## Defensive patterns -Read [docs/defensive-patterns.md](docs/defensive-patterns.md) before lifecycle, concurrency, subprocess, or teardown work. +Read [docs/defensive-patterns/README.md](docs/defensive-patterns/README.md) before changing a package surface, remote service, client component or state, conversation or Session behavior, or lifecycle, concurrency, subprocess, and teardown code. Its [review principles](docs/defensive-patterns/README.md#why-these-rules) apply per artifact. ## Type safety and documentation diff --git a/Makefile b/Makefile index 4b95df6766..0836489ef8 100644 --- a/Makefile +++ b/Makefile @@ -1,13 +1,14 @@ # Short names for the Web and Desktop application commands. The package.json # scripts they call stay the source of truth; docs/development.md documents both. .DEFAULT_GOAL := help -.PHONY: help build web desktop dev-web dev-desktop +.PHONY: help build clean web desktop dev-web dev-desktop PNPM ?= pnpm ARGS ?= help: @echo "make build pnpm run build complete repository build" + @echo "make clean pnpm run clean remove build outputs and safe deleted-package residue" @echo "make web pnpm run start:web serve the built Web artifacts from source" @echo "make desktop pnpm run start:desktop launch the built Desktop artifacts" @echo "make dev-web pnpm run dev:web build, serve, and rebuild Web on source edits" @@ -18,6 +19,9 @@ help: build: $(PNPM) run build +clean: + $(PNPM) run clean + web: $(PNPM) run start:web $(ARGS) diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 741c98db08..6a2fbda5eb 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). @@ -114,6 +114,7 @@ External packages installed for runtime use or distributed inside the prebuilt b | [`node-addon-require-builtin`](https://www.npmjs.com/package/node-addon-require-builtin) | MIT | | [`node-pty`](https://github.com/microsoft/node-pty) | MIT | | [`open`](https://github.com/sindresorhus/open) | MIT | +| [`p-limit`](https://github.com/sindresorhus/p-limit) | MIT | | [`papaparse`](https://github.com/mholt/PapaParse) | MIT | | [`pdfjs-dist`](https://github.com/mozilla/pdf.js) | Apache-2.0 | | [`picomatch`](https://github.com/micromatch/picomatch) | MIT | @@ -141,11 +142,12 @@ External packages installed for runtime use or distributed inside the prebuilt b pnpm applies local patches to the following packages at install time, so shipped artifacts carry modified copies; each patch file is the complete record of the modification: -- `@earendil-works/pi-ai@1.0.2` — [`patches/@earendil-works__pi-ai@1.0.2.patch`](patches/@earendil-works__pi-ai@1.0.2.patch) +- `@earendil-works/pi-ai@1.1.0` — [`patches/@earendil-works__pi-ai@1.1.0.patch`](patches/@earendil-works__pi-ai@1.1.0.patch) - `@electron/osx-sign@1.3.3` — [`patches/@electron__osx-sign@1.3.3.patch`](patches/@electron__osx-sign@1.3.3.patch) - `@fortune-sheet/core@1.0.4` — [`patches/@fortune-sheet__core@1.0.4.patch`](patches/@fortune-sheet__core@1.0.4.patch) - `@fortune-sheet/react@1.0.4` — [`patches/@fortune-sheet__react@1.0.4.patch`](patches/@fortune-sheet__react@1.0.4.patch) - `@yao-pkg/pkg@6.21.0` — [`patches/@yao-pkg__pkg@6.21.0.patch`](patches/@yao-pkg__pkg@6.21.0.patch) +- `app-builder-lib@26.17.0` — [`patches/app-builder-lib@26.17.0.patch`](patches/app-builder-lib@26.17.0.patch) - `exceljs@4.4.0` — [`patches/exceljs@4.4.0.patch`](patches/exceljs@4.4.0.patch) - `node-pty@1.2.0-beta.15` — [`patches/node-pty@1.2.0-beta.15.patch`](patches/node-pty@1.2.0-beta.15.patch) @@ -247,6 +249,7 @@ External packages **directly declared** for development, tests, types, or toolin | [`playwright`](https://github.com/microsoft/playwright) | Apache-2.0 | | [`pnpm`](https://github.com/pnpm/pnpm) | MIT | | [`publint`](https://github.com/publint/publint) | MIT | +| [`selfsigned`](https://github.com/jfromaniello/selfsigned) | MIT | | [`smol-toml`](https://github.com/squirrelchat/smol-toml) | BSD-3-Clause | | [`spdx-expression-parse`](https://github.com/jslicense/spdx-expression-parse.js) | MIT | | [`tar`](https://github.com/isaacs/node-tar) | BlueOak-1.0.0 | @@ -268,6 +271,7 @@ Direct dependencies of the `pyproject.toml` manifests, plus `uv` as the developm | Package | License | Role | | --- | --- | --- | | [`hatchling`](https://github.com/pypa/hatch) | MIT | build backend | +| [`pillow`](https://github.com/python-pillow/Pillow) | MIT-CMU | Python project dependency | | [`pydantic`](https://github.com/pydantic/pydantic) | MIT | runtime dependency of `deepseek-harness-sdk` | | [`pytest`](https://github.com/pytest-dev/pytest) | MIT | test-only | | [`uv`](https://github.com/astral-sh/uv) | MIT / Apache-2.0 | development workflow tool | diff --git a/apps/cli/composition.md b/apps/cli/composition.md index 9888602296..8b2cfb83ab 100644 --- a/apps/cli/composition.md +++ b/apps/cli/composition.md @@ -30,6 +30,8 @@ flowchart LR cfg --> plugin_dsh_base_typert_loader plugin_dsh_base_typert_gateway["typert-gateway
@deepseek-ai/dsh-api-gateway"] cfg --> plugin_dsh_base_typert_gateway + plugin_dsh_base_remote_access["remote-access
@deepseek-ai/dsh-api-remote-access"] + cfg --> plugin_dsh_base_remote_access plugin_dsh_base_session_title["session-title
@deepseek-ai/dsh-session-title"] cfg --> plugin_dsh_base_session_title plugin_dsh_base_session_title_llm["session-title-llm
@deepseek-ai/dsh-session-title-first-prompt-llm"] @@ -211,6 +213,7 @@ flowchart LR | `typert` | `@deepseek-ai/dsh-typert-registry` | | `typert-loader` | `@deepseek-ai/dsh-typert-loader` | | `typert-gateway` | `@deepseek-ai/dsh-api-gateway` | +| `remote-access` | `@deepseek-ai/dsh-api-remote-access` | | `session-title` | `@deepseek-ai/dsh-session-title` | | `session-title-llm` | `@deepseek-ai/dsh-session-title-first-prompt-llm` | | `user-questions` | `@deepseek-ai/dsh-user-questions` | diff --git a/apps/cli/package.json b/apps/cli/package.json index c3dc7d18d3..e51df93791 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh", "description": "dsh CLI: profile launch, plugin management, and configuration inspection", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -98,7 +98,7 @@ "@deepseek-ai/schemastery": "workspace:~", "commander": "^15.0.0", "js-yaml": "^4.3.2", - "node-addon-require-builtin": "^0.1.6", + "node-addon-require-builtin": "^0.1.9", "@deepseek-ai/dsh-http-proxy": "workspace:*", "@deepseek-ai/dsh-mcp-resources": "workspace:*", "@deepseek-ai/dsh-plugin-manager": "workspace:*", diff --git a/apps/cli/reference/README.i18n.yaml b/apps/cli/reference/README.i18n.yaml index da6e0863ff..7cc7f2a17a 100644 --- a/apps/cli/reference/README.i18n.yaml +++ b/apps/cli/reference/README.i18n.yaml @@ -9,8 +9,8 @@ en: e3a159750f5f9ed3 zh: e02d9004fcc239f9 /dsh-cli-behavior-reference/profile-boot/app-arguments: - en: be06f11a3b585d0f - zh: 28c7ee6e0d86dc3b + en: 3d2f4cf6a0afc3cd + zh: 9fe7e8f6a4acb596 /dsh-cli-behavior-reference/profile-boot/config-schema-dump: en: a356f8a68f3b3685 zh: c718713b5d709295 @@ -21,8 +21,8 @@ en: 8d2cfff9bab7327f zh: 21515ab6e6798504 /dsh-cli-behavior-reference/web-profile: - en: 536c6883a0d54b14 - zh: 6dd2469b71189c87 + en: d768b6213e75a890 + zh: 731791b496ce14ef /dsh-cli-behavior-reference/shared-deployment-behavior: en: 6a7abc9339e8f37f zh: 133adb834c8e195d diff --git a/apps/cli/reference/README.md b/apps/cli/reference/README.md index e8105bab78..8195b3e5c5 100644 --- a/apps/cli/reference/README.md +++ b/apps/cli/reference/README.md @@ -35,7 +35,7 @@ The shipped apps own these command lines: | Profile | Arguments | |---|---| -| `web` | `--host`, `--port`, `--public-url`, repeatable `--trusted-host`, `--no-open` | +| `web` | `--host`, `--port`, `--tls-cert`, `--tls-key`, `--public-url`, repeatable `--trusted-host`, `--no-open` | | `headless` | the task text, as the positional argument | | `sdk` | no options; stdio carries the JSON-RPC protocol | | `sdk-minimal` | no options; stdio carries the same JSON-RPC protocol | @@ -106,27 +106,31 @@ Git-hosted plugins that ship sources build during install through their `prepare ## Web profile -`dsh web` uses the profile shorthand. Launcher flags are parsed first; the remaining flags belong to the web app, whose ordinary bundle provider parses them. `--host` and `--port` override the composed values of the rows that carry them, repeatable `--trusted-host` contributes invocation authorities through `ctx.webRuntime.trustedHosts` (a deployment expression concatenates its own authorities), and `--no-open` disables the default-browser handoff for this invocation. The client-plugin HMR receiver is always mounted and stays idle until `pnpm run dev:web` rebuilds client bundles; that command builds once, starts this same launcher, and keeps client bundles rebuilt, or with `--no-serve` runs only the watchers beside a `dsh web` started elsewhere. +`dsh web` uses the profile shorthand. Launcher flags are parsed first; the remaining flags belong to the web app, whose ordinary bundle provider parses them. `--host` and `--port` override the composed listener values, and `--tls-cert`/`--tls-key` set the listener's `tls` pair. The host must name one concrete local address, not a wildcard (`--host 0.0.0.0` exits with a usage error); `hostname -i` may list several, so pass one. Repeatable `--trusted-host` values are collected in `ctx.webStartup.trustedHosts`; a deployment expression may add its own authorities. `--no-open` disables the default-browser handoff for this invocation. The client-plugin HMR receiver is always mounted and stays idle until `pnpm run dev:web` rebuilds client bundles; that command builds once, starts this same launcher, and keeps client bundles rebuilt, or with `--no-serve` runs only the watchers beside a `dsh web` started elsewhere. -`--public-url ` advertises one HTTP(S) application root — with an optional forwarding prefix — in place of the listener's loopback URL. It grants no trust, so the browser-visible authority still has to be named with `--trusted-host`; [Publish the Web UI behind a reverse proxy](../../../docs/user/guide/public-deployments.md) lists what the proxy in front must provide. +`--public-url ` advertises one HTTP(S) application root — with an optional forwarding prefix — in place of the listener's bind-address URL (loopback for a loopback bind). It grants no trust, so the browser-visible authority still has to be named with `--trusted-host`; [Publish the Web UI behind a reverse proxy](../../../docs/user/guide/public-deployments.md) lists what the proxy in front must provide. + +`--tls-cert ` and `--tls-key ` make the listener serve HTTPS in place of plain HTTP. They are one setting: both or neither, and each names a file resolved against the process working directory. The certificate file holds the full chain, including intermediates; the key file holds an unencrypted PEM private key. A missing, unreadable, empty, or invalid pair fails startup, which never falls back to HTTP, and a replacement pair takes effect only after a listener reload or a process restart because the carrier reads the files once and nothing obtains, renews, or watches certificates. HTTPS also grants no trust: the browser must trust the certificate and open an authority its names cover, Connection still authenticates each request and checks Host/Origin, and the session cookie is `Secure` because the receiving listener serves HTTPS. The default port stays 3080, and `--public-url` remains an independent advertisement. ```sh dsh web +dsh web --host "$(hostname -i | awk '{print $1}')" --public-url https://app.example/ --trusted-host app.example +dsh web --tls-cert ./server-chain.pem --tls-key ./server-key.pem dsh web --no-open dsh web --patch ./extra.cordis.yml dsh web --dump-config dsh web --help ``` -The production Web runner needs built package and frontend artifacts (`pnpm run build`). It serves `http://127.0.0.1:3080` by default and, for a local launch, opens that canonical host URL — the advertised root when `--public-url` names one — only after the complete Loader tree settles. A non-empty inherited `SSH_CONNECTION` or `SSH_TTY` suppresses the browser handoff because the SSH client or editor owns the local forwarded address; the host URL is still printed. The CLI intentionally does not support `--host 0.0.0.0` and exits with a usage error. Immediately before a local handoff it prints `dsh web: opening the default browser; pass --no-open to disable`; if the operating-system handoff fails, a diagnostic on stderr states the reason, leaves the server running, and names the URL for manual use. `--trusted-host` adds named authorities accepted by the `/api` browser-trust fence. +The production Web runner needs built package and frontend artifacts (`pnpm run build`). It prints the advertised `--public-url` when configured, otherwise the listener's bind-address URL with the listener's scheme (default `http://127.0.0.1:3080`, or `https://` when TLS is configured). The Host/Origin fence accepts the bind IP directly; a proxy or DNS authority still needs `--trusted-host`. The startup line and default-browser handoff wait for the complete Loader tree. A non-empty inherited `SSH_CONNECTION` or `SSH_TTY` suppresses browser opening, not the startup line. Immediately before a browser handoff it prints `dsh web: opening the default browser; pass --no-open to disable`; if the operating-system handoff fails, stderr names the reason and points to the startup URL while the server keeps running. Process shutdown gives the plugin tree up to five seconds to dispose. The first `SIGINT`/`SIGTERM` starts that graceful drain — `SIGTERM` is a supervisor's ordinary stop request and exits 0 on every surface, `SIGINT` reports 130; a second signal forces immediate exit. If one-shot normal completion is already stuck in disposal, the first `Ctrl+C` is the escalation and exits immediately instead of being swallowed. -The base-backed modes treat the invoking directory as the default workspace root, load applicable `AGENTS.md` or `CLAUDE.md` instructions with a 65,536-byte render budget, and use an in-memory SQLite session content index. The standalone `sdk-minimal` profile uses the invoking directory as its sandbox-policy root but intentionally omits filesystem tools, instruction discovery, and SQLite. An enabled HMR plugin watches both `cordis.patch.yml` layers (profile and home) and reapplies valid edits transactionally; without HMR, the process applies them once. A one-shot surface exits through its bounded shutdown, which disposes any live watchers. +The base-backed modes treat the invoking directory as the default workspace root, load applicable `AGENTS.md` or `CLAUDE.md` instructions with a 65,536-byte render budget, and use an in-memory SQLite session content index. The standalone `sdk-minimal` profile uses the invoking directory as its sandbox-policy root and includes `read_image`, but omits text filesystem tools, instruction discovery, and SQLite. An enabled HMR plugin watches both `cordis.patch.yml` layers (profile and home) and reapplies valid edits transactionally; without HMR, the process applies them once. A one-shot surface exits through its bounded shutdown, which disposes any live watchers. New sessions in base-backed profiles default to the `workspace-write` permission preset. Bash and filesystem mutations are restricted to the session workspace and platform temporary roots; reads and network access are not confined, while process visibility depends on the selected sandbox backend — bwrap runs commands in a private PID namespace that hides host processes, and Landlock and Seatbelt leave host process visibility unchanged. `DSH_PERMISSION_MODE` changes the process fallback. Stored General-settings permissions affect later Web sessions, not an already-open one. The standalone `sdk-minimal` tree instead pins `danger-full-access` and mounts no approval or permission-settings service. -`DSH_TOOLS_MODE` selects `native` or `ptc` for the process; another value fails at boot. The shipped `minimal` agent preset keeps that deployment presentation, fixes the complete system prompt to `You are a helpful software engineer assistant.`, and composes only the platform-selected persistent shell. Select 极简模式 when creating a Web session; every other prompt section and model-facing plugin remains absent from that agent while the shared browser, workspace, persistence, sandbox, and permission host stays in place. +`DSH_TOOLS_MODE` selects `native` or `ptc` for the process; another value fails at boot. The shipped `minimal` agent preset keeps that deployment presentation, fixes the complete system prompt to `You are a helpful software engineer assistant.`, and provides the platform-selected persistent shell, `read_image`, and `working_directory`. It supports automatic context compaction and the human `/compact` command. Select 极简模式 when creating a Web session; the shared browser, workspace, persistence, sandbox, and permission host remains in place. ## Shared deployment behavior diff --git a/apps/cli/reference/README.zh.md b/apps/cli/reference/README.zh.md index 2471de196e..e1dbf1ffe8 100644 --- a/apps/cli/reference/README.zh.md +++ b/apps/cli/reference/README.zh.md @@ -37,7 +37,7 @@ dsh rescue | Profile | 参数 | |---|---| -| `web` | `--host`、`--port`、`--public-url`、可重复的 `--trusted-host`、`--no-open` | +| `web` | `--host`、`--port`、`--tls-cert`、`--tls-key`、`--public-url`、可重复的 `--trusted-host`、`--no-open` | | `headless` | 任务文本,作为位置参数 | | `sdk` | 无选项;stdio 携带 JSON-RPC 协议 | | `sdk-minimal` | 无选项;stdio 携带相同的 JSON-RPC 协议 | @@ -108,27 +108,31 @@ dsh --profile tui ## Web Profile -`dsh web` 使用 profile 简写。启动器先解析自身的 flag,其余 flag 属于 web 应用,由组合包中的普通提供方解析。`--host` 和 `--port` 覆盖承载它们的那些行的组合取值,可重复的 `--trusted-host` 通过 `ctx.webRuntime.trustedHosts` 提供本次调用的 authority(部署表达式会拼接自己的 authority),`--no-open` 则只对本次调用关闭默认浏览器交接。客户端插件 HMR(热模块替换)接收器始终挂载,在 `pnpm run dev:web` 重建客户端 bundle 之前保持空闲;该命令先构建一次,再启动这同一个启动器并持续重建客户端 bundle,加 `--no-serve` 则只运行 watcher、配合别处启动的 `dsh web`。 +`dsh web` 使用 profile 简写。启动器先解析自身的 flag,其余 flag 属于 web 应用,由组合包中的普通提供方解析。`--host` 与 `--port` 覆盖组合的监听器取值,`--tls-cert`/`--tls-key` 则设置监听器的 `tls` 证书对。host 必须指名一个具体的本机地址,不能是通配地址(`--host 0.0.0.0` 会以用法错误退出);`hostname -i` 可能列出多个,请只传一个。可重复的 `--trusted-host` 值会收集到 `ctx.webStartup.trustedHosts`;部署表达式可以添加自己的 authority。`--no-open` 只对本次调用关闭默认浏览器交接。客户端插件 HMR(热模块替换)接收器始终挂载,在 `pnpm run dev:web` 重建客户端 bundle 之前保持空闲;该命令先构建一次,再启动这同一个启动器并持续重建客户端 bundle,加 `--no-serve` 则只运行 watcher、配合别处启动的 `dsh web`。 -`--public-url ` 公告唯一的 HTTP(S) 应用根——可带转发前缀——替代监听器的 loopback URL。它不授予信任,因此浏览器可见的 authority 仍需用 `--trusted-host` 点名;[在反向代理之后发布 Web UI](../../../docs/user/guide/public-deployments.zh.md)列出了前置代理必须提供的内容。 +`--public-url ` 公告唯一的 HTTP(S) 应用根——可带转发前缀——替代监听器的绑定地址 URL(回环绑定时为回环地址)。它不授予信任,因此浏览器可见的 authority 仍需用 `--trusted-host` 点名;[在反向代理之后发布 Web UI](../../../docs/user/guide/public-deployments.zh.md)列出了前置代理必须提供的内容。 + +`--tls-cert ` 与 `--tls-key ` 让监听器以 HTTPS 取代明文 HTTP 提供服务。它们属于同一个设置:要么都给,要么都不给;两者各是相对进程工作目录解析的路径。证书文件包含完整证书链(含中间证书),密钥文件为不带口令的 PEM 私钥。文件缺失、不可读、为空或无效时启动失败,且绝不回退到 HTTP;由于载体只读取一次文件,且既不获取、不续期也不监视证书,替换后的证书对只有在重新加载监听器或重启进程后才生效。HTTPS 同样不授予信任:浏览器必须信任该证书并访问其名称覆盖的 authority,Connection 仍认证每个请求并校验 Host/Origin,而由于接收请求的监听器提供 HTTPS,会话 cookie 带 `Secure`。默认端口仍为 3080,`--public-url` 仍是相互独立的公告。 ```sh dsh web +dsh web --host "$(hostname -i | awk '{print $1}')" --public-url https://app.example/ --trusted-host app.example +dsh web --tls-cert ./server-chain.pem --tls-key ./server-key.pem dsh web --no-open dsh web --patch ./extra.cordis.yml dsh web --dump-config dsh web --help ``` -生产 Web 运行器需要已构建的包和前端产物(`pnpm run build`)。默认服务地址是 `http://127.0.0.1:3080`;本机启动时,只在完整 Loader 配置树结算后才用默认浏览器打开该规范宿主机 URL(配置了 `--public-url` 时即为公告根)。继承的 `SSH_CONNECTION` 或 `SSH_TTY` 非空时会跳过浏览器交接,因为本地转发地址由 SSH 客户端或编辑器持有;宿主机 URL 仍会打印。CLI 有意不支持 `--host 0.0.0.0`,并会以用法错误退出。本机交接前会打印英文提示 `dsh web: opening the default browser; pass --no-open to disable`;若操作系统交接失败,stderr 诊断会说明原因、给出 URL 供手动访问,服务器仍继续运行。`--trusted-host` 可添加 `/api` 浏览器信任围栏接受的具名 authority。 +生产 Web 运行器需要已构建的包和前端产物(`pnpm run build`)。配置了 `--public-url` 时打印公告地址,否则打印采用监听器协议的绑定地址 URL(默认为 `http://127.0.0.1:3080`,配置 TLS 时为 `https://`)。Host/Origin 栅栏直接接受绑定 IP;代理或 DNS authority 仍需 `--trusted-host`。启动日志与默认浏览器交接都会等待完整 Loader 配置树结算。继承的 `SSH_CONNECTION` 或 `SSH_TTY` 非空时会抑制浏览器打开,但仍打印启动 URL。浏览器交接前会打印 `dsh web: opening the default browser; pass --no-open to disable`;若操作系统交接失败,stderr 会说明原因并指向启动 URL,服务器仍继续运行。 进程关闭时,插件树最多有 5 秒完成 dispose。首次收到 `SIGINT` 或 `SIGTERM` 时会开始优雅排空:`SIGTERM` 是监督进程发出的常规停止请求,在所有运行模式下都以 0 退出;`SIGINT` 则报告 130。第二次收到信号时会立即强制退出。如果一次性运行在正常结束时已经卡在 dispose 阶段,第一次按下 `Ctrl+C` 就会直接升级为强制退出,而不会被忽略。 -基于 base 的模式都将运行命令时所在的目录作为默认 workspace 根目录,以 65,536 字节渲染预算加载适用的 `AGENTS.md` 或 `CLAUDE.md` 指令,并使用内存 SQLite 会话内容索引。独立的 `sdk-minimal` profile 把运行命令时所在的目录作为沙箱策略根目录,但刻意省略文件系统工具、指令发现与 SQLite。启用的 HMR 插件会监视 profile 与 home 两个 `cordis.patch.yml` 配置层的有效变更,并以事务方式重新应用;未启用 HMR 时只应用一次。一次性运行模式通过有界关闭流程退出,该流程会 dispose 所有实时监视器。 +基于 base 的模式都将运行命令时所在的目录作为默认 workspace 根目录,以 65,536 字节渲染预算加载适用的 `AGENTS.md` 或 `CLAUDE.md` 指令,并使用内存 SQLite 会话内容索引。独立的 `sdk-minimal` profile 把运行命令时所在的目录作为沙箱策略根目录并包含 `read_image`,但省略文本文件系统工具、指令发现与 SQLite。启用的 HMR 插件会监视 profile 与 home 两个 `cordis.patch.yml` 配置层的有效变更,并以事务方式重新应用;未启用 HMR 时只应用一次。一次性运行模式通过有界关闭流程退出,该流程会 dispose 所有实时监视器。 基于 base 的 profile 中,新会话默认使用 `workspace-write` 权限预设。Bash 和文件系统修改仅限于会话 workspace 与平台临时根目录;读取和网络访问不受限制,进程可见性则取决于所选沙箱后端——bwrap 在私有 PID 命名空间中运行命令并隐藏宿主进程,Landlock 与 Seatbelt 保持宿主进程可见性不变。`DSH_PERMISSION_MODE` 更改进程后备值。General settings 中存储的权限影响后续 Web 会话,不改变已打开的会话。独立的 `sdk-minimal` 配置树则固定为 `danger-full-access`,且不挂载 approval 或权限 settings 服务。 -`DSH_TOOLS_MODE` 为进程选择 `native` 或 `ptc`;其他值会导致启动失败。随附的 `minimal` agent preset 会保留该部署的呈现方式,将完整系统提示词固定为 `You are a helpful software engineer assistant.`,并且仅组合按平台选择的持久 shell。创建 Web 会话时请选择极简模式;该 agent 不包含任何其他提示词段落或面向模型的插件,而共享的浏览器、workspace、持久化、沙箱与权限宿主保持不变。 +`DSH_TOOLS_MODE` 为进程选择 `native` 或 `ptc`;其他值会导致启动失败。随附的 `minimal` agent preset 会保留该部署的呈现方式,将完整系统提示词固定为 `You are a helpful software engineer assistant.`,并提供按平台选择的持久 shell、`read_image` 和 `working_directory`。它支持自动上下文压缩和用户 `/compact` 命令。创建 Web 会话时请选择极简模式;共享的浏览器、workspace、持久化、沙箱与权限宿主保持不变。 ## 共享部署行为 diff --git a/apps/cli/tests/agent-team-headless.e2e.ts b/apps/cli/tests/agent-team-headless.e2e.ts index 45e954e40f..dd4e456252 100644 --- a/apps/cli/tests/agent-team-headless.e2e.ts +++ b/apps/cli/tests/agent-team-headless.e2e.ts @@ -17,7 +17,7 @@ function records(content: string): Record[] { } describe('dsh run with Agent Teams enabled', () => { - it('runs two teammates, durable peer mail, dependent tasks, waiting, and final aggregation', async () => { + it('runs two teammates, direct peer messages, dependent tasks, waiting, and final aggregation', async () => { const cwd = await mkdtemp(join(tmpdir(), 'dsh-agent-team-headless-')) try { const home = join(cwd, '.dsh') @@ -103,8 +103,11 @@ describe('dsh run with Agent Teams enabled', () => { expect(root).toBeDefined() const eventTypes = root!.map(record => record.type) expect(eventTypes.filter(type => type === 'team/member')).toHaveLength(4) - expect(eventTypes).toContain('team/message/queued') - expect(eventTypes).toContain('team/message/delivered') + expect(eventTypes).not.toContain('team/message/queued') + expect(eventTypes).not.toContain('team/message/delivered') + const peerMessages = parsed.flatMap(log => log.filter(record => record.type === 'user/message' + && (record.data as { source: { kind: string } }).source.kind === 'agent-message')) + expect(peerMessages).toHaveLength(2) const taskEvents = root!.filter(record => record.type === 'team/task') expect(taskEvents.filter((record) => { const data = record.data as { task?: { status?: string } } | undefined diff --git a/apps/cli/tests/built-bin.e2e.ts b/apps/cli/tests/built-bin.e2e.ts index 09a0f39b1f..0b92215c86 100644 --- a/apps/cli/tests/built-bin.e2e.ts +++ b/apps/cli/tests/built-bin.e2e.ts @@ -381,7 +381,6 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', }) expect(wildcardHost.code).toBe(1) expect(wildcardHost.stdout).toBe('') - expect(wildcardHost.stderr).toContain('--host 0.0.0.0 is intentionally not supported yet for safety: it would expose remote code execution to the network; use 127.0.0.1 instead') expect(wildcardHost.stderr).not.toContain('dsh web: http://') const headlessHelp = await runBuiltBin(['headless', '--help'], { @@ -1250,9 +1249,14 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', ['llm-deepseek', '@deepseek-ai/dsh-llm-deepseek-api-key'], ['sandbox', '@deepseek-ai/dsh-sandbox-local'], ['filesystem', '@deepseek-ai/dsh-fs-local'], + ['attachment-local', '@deepseek-ai/dsh-attachment-local'], + ['tool-fs', '@deepseek-ai/dsh-tool-fs'], ['working-directory', '@deepseek-ai/dsh-working-directory'], ['tool-working-directory', '@deepseek-ai/dsh-tool-working-directory'], ['session-projection', '@deepseek-ai/dsh-session-projection'], + ['token-meter', '@deepseek-ai/dsh-token-meter'], + ['compaction-basic', '@deepseek-ai/dsh-compaction-basic'], + ['image-offload', '@deepseek-ai/dsh-compaction-image-offload'], ['sandbox-policy', '@deepseek-ai/dsh-sandbox-policy'], ['subprocess', '@deepseek-ai/dsh-subprocess-local'], ['pty', '@deepseek-ai/dsh-terminal'], diff --git a/apps/cli/tests/expected/dump-config-schema.json b/apps/cli/tests/expected/dump-config-schema.json index 29f03673a0..ce57b82073 100644 --- a/apps/cli/tests/expected/dump-config-schema.json +++ b/apps/cli/tests/expected/dump-config-schema.json @@ -445,13 +445,6 @@ ] } }, - { - "not": { - "required": [ - "preset" - ] - } - }, { "anyOf": [ { @@ -501,13 +494,6 @@ ] } }, - { - "not": { - "required": [ - "preset" - ] - } - }, { "anyOf": [ { @@ -557,13 +543,6 @@ ] } }, - { - "not": { - "required": [ - "preset" - ] - } - }, { "anyOf": [ { @@ -599,11 +578,6 @@ "properties": { "insert": { "$ref": "#/$defs/entryList" - }, - "preset": { - "type": "string", - "pattern": "\\S", - "description": "Outer preset row id. The remaining patch fields apply to its current config.plugins list; a missing or unaddressable preset fails composition." } }, "description": "An insert appends entries, optionally inside the group identified by id. Other patches replace supplied fields; config is replaced wholesale, not deep-merged. A truthy name asserts the existing plugin name rather than renaming it. Unknown targets and non-insert patches without a nonempty id are warned and skipped." diff --git a/apps/cli/tests/fixtures/agent-shutdown.mjs b/apps/cli/tests/fixtures/agent-shutdown.mjs new file mode 100644 index 0000000000..22064e0e55 --- /dev/null +++ b/apps/cli/tests/fixtures/agent-shutdown.mjs @@ -0,0 +1,83 @@ +/** Scope-owned cancellation during shutdown of the shipped Web profile. */ +import { existsSync, writeFileSync } from 'node:fs' +import { setImmediate } from 'node:timers/promises' +import { createUserMessage, LlmAdapter } from '@deepseek-ai/dsh-llm' + +export const name = 'agent-shutdown-fixture' +export const inject = ['agents', 'llm', 'appReady', 'appExit'] + +class Adapter extends LlmAdapter { + async resolveModel(provider, model) { + return { provider, id: model, name: model } + } + + async *stream() { + throw new Error('The cancelled request must not reach the adapter.') + } +} + +/** Hold one turn until cancellation and report the state seen by scope cleanup. */ +export function apply(ctx, config) { + ctx.llm.registerAdapter(['shutdown-fixture'], new Adapter()) + const exit = ctx.appExit + ctx.effect(() => ctx.appReady.onReady(() => { + void start(ctx, config).catch(error => { console.error(error); exit(1) }) + })) + if (process.platform === 'win32') { + const timer = setInterval(() => { + if (!existsSync(config.interrupt)) return + clearInterval(timer) + process.emit('SIGTERM') + }, 20) + ctx.effect(() => () => { clearInterval(timer) }) + } +} + +async function start(ctx, config) { + const { agent } = await ctx.agents.create({ + sessionId: 'shutdown-fixture', + agentOptions: { provider: 'shutdown-fixture', model: 'shutdown-fixture' }, + meta: { cwd: config.root }, + }) + const controller = new AbortController() + let abortHandled = 0 + controller.signal.addEventListener('abort', () => { + agent.cancel({ kind: 'parent' }) + agent.cancel({ kind: 'parent' }) + abortHandled++ + }, { once: true }) + agent.ctx.effect(() => () => { + controller.abort() + controller.abort() + const events = agent.session.snapshotEvents() + writeFileSync(config.result, JSON.stringify({ + abortHandled, + status: agent.status, + nextStep: agent.inbox.nextStep, + nextTurn: agent.inbox.nextTurn, + lastEvent: events.at(-1), + cancelled: events.filter(event => event.type === 'agent/inbox/spliced' && event.data.outcome === 'canceled'), + })) + }) + const message = text => createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }) + if (config.running) { + const entered = Promise.withResolvers() + agent.ctx.on('agent/request', async ({ signal }, next) => { + const aborted = Promise.withResolvers() + signal.addEventListener('abort', () => { aborted.resolve() }, { once: true }) + entered.resolve() + await aborted.promise + await setImmediate() + return next() + }) + agent.followup(message('active')) + await entered.promise + } + agent.send(message('pending step'), 'next-step', false) + agent.send(message('pending turn'), 'next-turn', false) + if (config.cancelFirst) { + controller.abort() + await agent.whenIdle() + } + console.log('agent-shutdown: ready') +} diff --git a/apps/cli/tests/optional-bundle-transitions.e2e.ts b/apps/cli/tests/optional-bundle-transitions.e2e.ts index 78d0e45813..f084cb29cb 100644 --- a/apps/cli/tests/optional-bundle-transitions.e2e.ts +++ b/apps/cli/tests/optional-bundle-transitions.e2e.ts @@ -171,7 +171,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option const minimal = await agent('minimal') const standard = await agent() expect(names()).toEqual(['working_directory']) - expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'working_directory']) + expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'read_image', 'working_directory']) for (const name of ['str_replace_editor', 'session_search', 'terminal_open', 'ralph']) expect(names(standard.agent)).not.toContain(name) expect((await ctx.skills.list({ cwd: workspace, scope: standard.agent })).some(skill => skill.name === 'dsh-badge')).toBe(false) }) @@ -185,7 +185,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option expect(assembly.tools.map(tool => tool.name)).toEqual(['run_code']) expect(assembly.sections.find(section => section.name === 'tools:sdk')?.text).toContain('session_trace') expect(names(native.agent)).toContain('session_search') - expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'working_directory']) + expect(names(minimal.agent)).toContain('session_search') await turn(coded.agent, 'Read this session lineage through run_code.', [ toolCallResponse('ptc-search', 'run_code', { code: 'console.log(await tools.session_trace({}));', @@ -210,7 +210,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option const foreign = await agent('standard', otherWorkspace) await turn(foreign.agent, 'Keep OPTIONAL_SEARCH_MARKER in the other workspace.', [textResponse('Other marker recorded.')]) await select(bundles.search, true) - expect(names(live.agent)).not.toContain('session_search') + expect(names(live.agent)).toContain('session_search') const searcher = await agent() await turn(searcher.agent, 'Find the previous marker in session history.', [ toolCallResponse('search-history', 'session_search', { query: 'OPTIONAL_SEARCH_MARKER' }), textResponse('SEARCH_DONE'), @@ -220,11 +220,8 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option expect(toolResult(searcher.agent, 'search-history')).not.toContain(foreign.agent.session.id) expect(toolResult(searcher.agent, 'search-history')).toContain('OPTIONAL_SEARCH_MARKER') await select(bundles.search, false) + expect(names(searcher.agent)).not.toContain('session_search') expect(names((await agent()).agent)).not.toContain('session_search') - await turn(searcher.agent, 'Search the marker again using the retained capability.', [ - toolCallResponse('search-retained', 'session_search', { query: 'OPTIONAL_SEARCH_MARKER' }), textResponse('RETAINED_SEARCH_DONE'), - ]) - expect(toolResult(searcher.agent, 'search-retained')).toContain(seedId) const sessionId = searcher.agent.session.id await searcher.dispose() handles.delete(searcher) @@ -248,7 +245,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option expect(toolResult(owner.agent, 'badge-on')).toContain('dsh-badge.png') const minimal = await agent('minimal') expect((await ctx.skills.list({ cwd: workspace, scope: minimal.agent })).map(skill => skill.name)).toContain('dsh-badge') - expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'working_directory']) + expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'read_image', 'working_directory']) await select(bundles.badge, false) expect((await load('badge-after')).isError).toBe(true) }) @@ -311,9 +308,15 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option await expect.poll(() => titleRequests(following.agent).length).toBe(1) expect(titleRequests(following.agent)[0]?.data.titleProvider).toBe('session-title-all-prompts-llm') await expect.poll(() => ctx.sessionTitle.get(following.agent.session)?.source.kind).toBe('provider') + const currentTitle = ctx.sessionTitle.get(following.agent.session)?.title + const firstInput = titleRequests(following.agent)[0]?.data.messages[0]?.content[0] + expect(firstInput?.type === 'text' && firstInput.text).toContain('Generate the session title from this JSON array') await turn(following.agent, 'Continue the growing conversation.', [textResponse('TWO')]) await expect.poll(() => titleRequests(following.agent).length).toBe(2) expect(titleRequests(following.agent).every(event => event.data.titleProvider === 'session-title-all-prompts-llm')).toBe(true) + const followingInput = titleRequests(following.agent)[1]?.data.messages[0]?.content[0] + expect(followingInput?.type === 'text' && followingInput.text) + .toContain(`Update the session title from this JSON object:\n{"currentTitle":${JSON.stringify(currentTitle)},`) await select(bundles.titles, false) const restored = await agent() await turn(restored.agent, 'Restore first-prompt titles.', [textResponse('ONE')]) @@ -323,10 +326,10 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option expect(titleRequests(restored.agent)[0]?.data.titleProvider).toBe('session-title-first-prompt-llm') }) - it('composes all five bundles while leaving minimal and host tools unchanged', async () => { + it('composes all five bundles as global tools across every preset', async () => { for (const name of Object.values(bundles)) await select(name, true) let coded: Agent | undefined - for (const preset of ['standard', 'cordis', 'ptc']) { + for (const preset of ['standard', 'cordis', 'ptc', 'minimal']) { const owner = await agent(preset) expect(names(owner.agent)).toEqual(expect.arrayContaining(['session_search', 'terminal_open', 'ralph'])) if (preset === 'ptc') coded = owner.agent @@ -340,9 +343,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option ]) expect(toolResult(coded, 'combined-program')).toContain(coded.session.id) expect(toolResult(coded, 'combined-program')).toContain('dsh-badge') - const minimal = await agent('minimal') - expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'working_directory']) - expect(names()).toEqual(['working_directory']) + expect(names()).toEqual(expect.arrayContaining(['session_search', 'terminal_open', 'ralph', 'working_directory'])) for (const name of [...Object.values(bundles)].reverse()) await select(name, false) expect(names((await agent()).agent)).not.toContain('session_search') }) diff --git a/apps/cli/tests/profiles/headless/team-snapshot.patch.yml b/apps/cli/tests/profiles/headless/team-snapshot.patch.yml index c7048d2406..290714194e 100644 --- a/apps/cli/tests/profiles/headless/team-snapshot.patch.yml +++ b/apps/cli/tests/profiles/headless/team-snapshot.patch.yml @@ -42,7 +42,6 @@ config: maxMembers: 8 maxTasks: 256 - maxPendingMessagesPerMember: 64 maxMessageBytes: 65536 disposalTimeoutMs: 5000 diff --git a/apps/cli/tests/profiles/headless/tests/credentials.e2e.ts b/apps/cli/tests/profiles/headless/tests/credentials.e2e.ts new file mode 100644 index 0000000000..f1323add9e --- /dev/null +++ b/apps/cli/tests/profiles/headless/tests/credentials.e2e.ts @@ -0,0 +1,203 @@ +/** Credential selection through the shipped headless profile and real HTTP adapters. */ +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { createServer } from 'node:http' +import { once } from 'node:events' +import type { AddressInfo } from 'node:net' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server' +import { runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke' +import { describe, expect, it } from 'vitest' + +const binScript = fileURLToPath(new URL('../../../../../../apps/cli/src/bin.ts', import.meta.url)) +const tsconfigPath = fileURLToPath(new URL('../../../../../../tsconfig.json', import.meta.url)) +const savedKey = 'headless-saved-key' +const launchKey = 'headless-launch-key' +const projectKey = 'headless-project-key' +const homeKey = 'headless-home-key' +const processTimeoutMs = 60_000 + +/** Anthropic SDK events require the SSE event name beside the JSON payload. */ +async function startAnthropicServer() { + const keys: Array = [] + const server = createServer((request, response) => { + keys.push(request.headers['x-api-key']) + request.resume() + response.writeHead(200, { 'content-type': 'text/event-stream' }) + for (const event of [ + { type: 'message_start', message: { id: 'auth-test', type: 'message', role: 'assistant', model: 'headless-auth-model', content: [], usage: { input_tokens: 1, output_tokens: 0 } } }, + { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }, + { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'mock response recovered' } }, + { type: 'content_block_stop', index: 0 }, + { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 1 } }, + { type: 'message_stop' }, + ]) response.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`) + response.end() + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + return { + keys, + baseURL: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + async close() { + server.closeAllConnections() + await new Promise((resolve, reject) => server.close((error) => { + if (error === undefined) resolve() + else reject(error) + })) + }, + } +} + +const credentials = JSON.stringify({ + version: 1, + refs: { DEEPSEEK_API_KEY: savedKey, ANTHROPIC_API_KEY: savedKey }, + records: { + 'llm-pi-ai/anthropic': { kind: 'api-key', key: savedKey }, + 'llm-pi-ai/openai-codex': { + kind: 'grant', payload: { type: 'oauth', access: 'headless-saved-access', refresh: 'headless-saved-refresh', expires: 1 }, + }, + }, +}) + '\n' + +describe('headless credential policy', { retry: 0 }, () => { + it.each([ + { name: 'launch environment', launch: launchKey, project: projectKey, home: homeKey, expected: launchKey }, + { name: 'project .env', launch: undefined, project: projectKey, home: homeKey, expected: projectKey }, + { name: 'home .env', launch: undefined, project: undefined, home: homeKey, expected: homeKey }, + ])('uses $name instead of saved credentials', async (scenario) => { + const server = await startMockLlmServer({ sequence: ['success'], repeatLast: true, apiKey: scenario.expected }) + try { + const result = await runLoaderSmoke({ + label: `headless credentials: ${scenario.name}`, + tempDirPrefix: 'headless-credentials-', binScript, tsconfigPath, sourceImport: 'tsx/esm', + configPath: '', binArgs: ['headless', 'Reply briefly.'], processTimeoutMs, + env: { + DEEPSEEK_API_KEY: scenario.launch, DEEPSEEK_BASE_URL: server.baseURL, DSH_TELEMETRY_DISABLED: '1', + }, + prepare: async (cwd) => { + await mkdir(join(cwd, '.dsh'), { recursive: true }) + await writeFile(join(cwd, '.dsh', '.credentials.yaml'), credentials, { mode: 0o600 }) + if (scenario.project !== undefined) await writeFile(join(cwd, '.env'), `DEEPSEEK_API_KEY=${scenario.project}\n`) + if (scenario.home !== undefined) await writeFile(join(cwd, '.dsh', '.env'), `DEEPSEEK_API_KEY=${scenario.home}\n`) + }, + inspect: async (cwd) => { + expect(await readFile(join(cwd, '.dsh', '.credentials.yaml'), 'utf8')).toBe(credentials) + }, + }) + expect(result.stdout.trim()).toBe('mock response recovered') + expect(result.stderr).toBe('') + expect(server.requests.length).toBeGreaterThan(0) + expect(server.requests.every(request => request.headers['x-api-key'] === scenario.expected)).toBe(true) + } finally { + await server.close() + } + }, processTimeoutMs + 15_000) + + it.each(['named reference', 'native discovery'] as const)('uses launch credentials for pi-ai %s', async (mode) => { + const server = await startAnthropicServer() + try { + const result = await runLoaderSmoke({ + label: `headless pi-ai credentials: ${mode}`, + tempDirPrefix: 'headless-pi-credentials-', binScript, tsconfigPath, sourceImport: 'tsx/esm', + configPath: '', binArgs: ['headless', '--patch', './auth.patch.json', 'Reply briefly.'], processTimeoutMs, + env: { + ANTHROPIC_API_KEY: launchKey, ANTHROPIC_AUTH_TOKEN: undefined, ANTHROPIC_OAUTH_TOKEN: undefined, + ANTHROPIC_FEDERATION_RULE_ID: undefined, ANTHROPIC_ORGANIZATION_ID: undefined, + ANTHROPIC_IDENTITY_TOKEN_FILE: undefined, ANTHROPIC_SERVICE_ACCOUNT_ID: undefined, ANTHROPIC_WORKSPACE_ID: undefined, + DEEPSEEK_API_KEY: undefined, DSH_TELEMETRY_DISABLED: '1', + }, + prepare: async (cwd) => { + await mkdir(join(cwd, '.dsh'), { recursive: true }) + await writeFile(join(cwd, '.dsh', '.credentials.yaml'), credentials, { mode: 0o600 }) + await writeFile(join(cwd, 'auth.patch.json'), JSON.stringify([ + { id: 'agent-default-model', config: { provider: 'anthropic', model: 'headless-auth-model' } }, + { id: 'llm-pi-ai', config: { providers: { anthropic: { + ...mode === 'named reference' ? { apiKeyEnv: 'ANTHROPIC_API_KEY' } : {}, + baseURL: server.baseURL, + models: [{ id: 'headless-auth-model', contextWindow: 32_768, maxTokens: 1024 }], + } } } }, + ])) + }, + inspect: async (cwd) => { + expect(await readFile(join(cwd, '.dsh', '.credentials.yaml'), 'utf8')).toBe(credentials) + }, + }) + expect(result.stdout.trim()).toBe('mock response recovered') + expect(result.stderr).toBe('') + expect(server.keys.length).toBeGreaterThan(0) + expect(server.keys.every(key => key === launchKey)).toBe(true) + } finally { + await server.close() + } + }, processTimeoutMs + 15_000) + + it.each(['no environment key', 'empty environment key', 'invalid stored document', 'restore stored credentials'] as const)('%s', async (mode) => { + const restoring = mode === 'restore stored credentials' + const empty = mode === 'empty environment key' + const missing = mode === 'no environment key' || empty + const document = mode === 'invalid stored document' ? 'invalid: [\n' : credentials + const server = await startMockLlmServer({ sequence: ['success'], repeatLast: true, apiKey: restoring ? savedKey : launchKey }) + try { + const result = await runLoaderSmoke({ + label: `headless credential boundary: ${mode}`, + tempDirPrefix: 'headless-credential-boundary-', binScript, tsconfigPath, sourceImport: 'tsx/esm', + configPath: '', + binArgs: ['headless', ...restoring ? ['--patch', './auth.patch.json'] : [], 'Reply briefly.'], + processTimeoutMs, expectedExitCode: missing ? 1 : 0, + env: { DEEPSEEK_API_KEY: empty ? '' : missing ? undefined : launchKey, DEEPSEEK_BASE_URL: server.baseURL, DSH_TELEMETRY_DISABLED: '1' }, + prepare: async (cwd) => { + await mkdir(join(cwd, '.dsh'), { recursive: true }) + await writeFile(join(cwd, '.dsh', '.credentials.yaml'), document, { mode: 0o600 }) + if (empty) await writeFile(join(cwd, '.env'), `DEEPSEEK_API_KEY=${projectKey}\n`) + if (restoring) await writeFile(join(cwd, 'auth.patch.json'), JSON.stringify( + ['credentials', 'authorization', 'deepseek-account'].map(id => ({ id, disabled: false })), + )) + }, + inspect: async (cwd) => { + expect(await readFile(join(cwd, '.dsh', '.credentials.yaml'), 'utf8')).toBe(document) + }, + }) + if (missing) { + expect(result.stdout).toBe('\n') + expect(result.stderr).toContain('MISSING_CREDENTIAL') + expect(server.requests).toHaveLength(0) + } else { + expect(result.stdout.trim()).toBe('mock response recovered') + expect(result.stderr).toBe('') + expect(server.requests.length).toBeGreaterThan(0) + } + } finally { + await server.close() + } + }, processTimeoutMs + 15_000) + + it.each([ + { provider: 'deepseek-account', model: 'deepseek-v4-flash', code: 'ACCOUNT_SIGN_IN_REQUIRED' }, + { provider: 'openai-codex', model: 'gpt-5.4', code: 'PI_AI_ERROR: Provider is not configured: openai-codex' }, + ])('fails without saved sign-in for $provider', async ({ provider, model, code }) => { + const result = await runLoaderSmoke({ + label: `headless saved sign-in: ${provider}`, + tempDirPrefix: 'headless-saved-sign-in-', binScript, tsconfigPath, sourceImport: 'tsx/esm', + configPath: '', binArgs: ['headless', '--patch', './auth.patch.json', 'Reply briefly.'], + processTimeoutMs, expectedExitCode: 1, + env: { DEEPSEEK_API_KEY: undefined, OPENAI_API_KEY: undefined, DSH_TELEMETRY_DISABLED: '1' }, + prepare: async (cwd) => { + await mkdir(join(cwd, '.dsh'), { recursive: true }) + await writeFile(join(cwd, '.dsh', '.credentials.yaml'), credentials, { mode: 0o600 }) + await writeFile(join(cwd, 'auth.patch.json'), JSON.stringify([ + { id: 'agent-default-model', config: { provider, model } }, + ...provider === 'openai-codex' ? [{ id: 'llm-pi-ai', config: { providers: { + [provider]: { models: [{ id: model, contextWindow: 32_768, maxTokens: 1024 }] }, + } } }] : [], + ])) + }, + inspect: async (cwd) => { + expect(await readFile(join(cwd, '.dsh', '.credentials.yaml'), 'utf8')).toBe(credentials) + }, + }) + expect(result.stdout).toBe('\n') + expect(result.stderr).toContain(code) + expect(result.stderr).not.toContain('pending') + }, processTimeoutMs + 15_000) +}) diff --git a/apps/cli/tests/profiles/headless/tests/expected/headless-profile/session.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/headless-profile/session.expected.jsonl index 904ee65726..bfcfc3ca75 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/headless-profile/session.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/headless-profile/session.expected.jsonl @@ -15,6 +15,8 @@ {"type":"session/title-llm-request","data":{"titleProvider":"session-title-first-prompt-llm","messageSeqs":[8],"route":{"provider":"cli-mock","model":"cli-mock"},"system":"Create a concise title for an AI coding-assistant session from the supplied human messages.\nReturn only the title on one line, **in plain text of natural language**, with no quotes, prefix, explanation, Markdown, XML, or terminal control codes. No code is allowed.\nUse the language of the messages.\nAim for about 5 words in non-CJK languages or 10 CJK characters.\nIf the messages give little to name, still return a short best-effort title, such as Greeting, instead of explaining.","messages":[{"content":[{"type":"text","text":"Generate the session title from this JSON array of human messages:\n[{\"seq\":8,\"text\":\"Prove the product headless profile path with one real tool round trip.\"}]"}],"source":{"kind":"dsh-session-title-llm"},"role":"user","id":"{{sessionId}}"}],"maxTokens":4096,"reasoningEffort":"off"}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"Inspecting the task before the tool call."},{"type":"tool-call","id":"cli-smoke-call","name":"bash","arguments":"{\"command\":\"printf CLI_TOOL_ROUND_TRIP\",\"description\":\"Prove the CLI tool round trip.\"}"}],"source":{"kind":"model","provider":"cli-mock","model":"cli-mock"},"id":"{{sessionId}}"},"usage":{"inputTokens":11,"outputTokens":3,"cacheReadTokens":2},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":0,"dt":[],"texts":["Inspecting the task before the tool call."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"Inspecting the task before the tool call."}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":1,"dt":[],"id":"cli-smoke-call","name":"bash","args":["{\"command\":\"printf CLI_TOOL_ROUND_TRIP\",\"description\":\"Prove the CLI tool round trip.\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"cli-smoke-call","name":"bash","arguments":"{\"command\":\"printf CLI_TOOL_ROUND_TRIP\",\"description\":\"Prove the CLI tool round trip.\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":11,"outputTokens":3,"cacheReadTokens":2}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cli-smoke-call","name":"bash","arguments":"{\"command\":\"printf CLI_TOOL_ROUND_TRIP\",\"description\":\"Prove the CLI tool round trip.\"}"}} +{"type":"job/registered","data":{"jobId":"{{id:1}}","owner":"{{sessionId}}","kind":"bash","label":"printf CLI_TOOL_ROUND_TRIP","startedAt":0,"toolCall":{"callId":"cli-smoke-call","rootCallId":"cli-smoke-call"}}} +{"type":"job/settled","data":{"jobId":"{{id:1}}","owner":"{{sessionId}}","kind":"bash","label":"printf CLI_TOOL_ROUND_TRIP","startedAt":0,"toolCall":{"callId":"cli-smoke-call","rootCallId":"cli-smoke-call"},"finishedAt":0,"status":"completed","cause":"producer","producerReported":true,"detail":"exit code: 0"}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cli-smoke-call"},"toolCallId":"cli-smoke-call","content":[{"type":"text","text":"CLI_TOOL_ROUND_TRIP"}],"isError":false,"id":"{{sessionId}}"},"meta":{"cwd":"{{cwd}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl index 00868634d4..b0372d96c6 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your parent agent id is \"{{sessionId}}\". Before you finish, send your result to that agent with send_message({ agent_id: \"{{sessionId}}\", message: \"\" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Use the write tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl index 1b82a99cf0..c07532bd7d 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your parent agent id is \"{{sessionId}}\". Before you finish, send your result to that agent with send_message({ agent_id: \"{{sessionId}}\", message: \"\" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly CHILD_RESULT and","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/fixtures/pi-ai-conversation-updates.patch.yml b/apps/cli/tests/profiles/headless/tests/fixtures/pi-ai-conversation-updates.patch.yml new file mode 100644 index 0000000000..6d2a8dde06 --- /dev/null +++ b/apps/cli/tests/profiles/headless/tests/fixtures/pi-ai-conversation-updates.patch.yml @@ -0,0 +1,36 @@ +# pi-ai Kimi route with dynamic prompt and tool updates over the shipped headless profile. +- id: headless-startup + disabled: true + +- id: headless-runner + disabled: true + +- id: llm-deepseek + disabled: true + +- id: llm-pi-ai + config: + providers: + moonshotai: + apiKeyEnv: MOONSHOT_API_KEY + baseURL: !!js process.env.DSH_SNAPSHOT_BASE_URL + streamIdleTimeoutMs: 1000 + +- id: agent-loop + config: + agents: + - id: main + provider: moonshotai + model: kimi-k3 + cwd: !!js process.cwd() + +- id: agent-instructions + disabled: true + +# The fixture counts every model request, so title generation stays off. +- id: session-title-llm + disabled: true + +- insert: + - id: dynamic-tool-prompt-updates + name: '../../../../../../../packages/test-support/session-snapshot/tests/fixtures/dynamic-tool-prompt-updates.ts' diff --git a/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs b/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs index 119380327b..9c1bedd00e 100644 --- a/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs +++ b/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs @@ -183,17 +183,18 @@ class TeamFixtureAdapter extends LlmAdapter { throw new Error('Team profile exposes a direct subagent tool') } const initial = options.messages.findLast(message => message.role === 'user' && message.source.kind === 'user') - const identity = initial?.content[0]?.text?.trimEnd() - if (identity !== 'TEAM_WORKFLOW_CHILD' && (!tools.includes('spawn_teammate') || !tools.includes('workflow'))) { + const workflowChild = initial?.content[0]?.text === 'TEAM_WORKFLOW_CHILD' + const context = options.messages.findLast(message => message.source?.kind === 'runtime-context') + const identity = context?.source.sections?.find(section => section.name === 'team:identity')?.text + if (!workflowChild && (!tools.includes('spawn_teammate') || !tools.includes('workflow'))) { throw new Error('Team profile is missing teammate or workflow tools') } - const chunks = identity === 'TEAM_WORKFLOW_CHILD' - ? textChunks('Fresh workflow child complete.') - : identity === '\nYou are teammate "researcher".\nYour Team Lead is named "lead".\nUse list_agents({}) to find your teammates and their names.\nTo message your Team Lead, use send_message({ target: "lead", message: "..." }).\nTo message another teammate, use send_message({ target: "", message: "..." }).\n' - ? researcher(options.messages) - : identity === '\nYou are teammate "implementer".\nYour Team Lead is named "lead".\nUse list_agents({}) to find your teammates and their names.\nTo message your Team Lead, use send_message({ target: "lead", message: "..." }).\nTo message another teammate, use send_message({ target: "", message: "..." }).\n' - ? implementer(options.messages) - : lead(options.messages) + let chunks + if (workflowChild) chunks = textChunks('Fresh workflow child complete.') + else if (identity?.startsWith('You are teammate "researcher".')) chunks = researcher(options.messages) + else if (identity?.startsWith('You are teammate "implementer".')) chunks = implementer(options.messages) + else if (identity?.startsWith('You are the Team Lead named "lead".')) chunks = lead(options.messages) + else throw new Error('Team runtime context is missing a recognized identity') for (const chunk of chunks) { options.signal?.throwIfAborted() yield chunk diff --git a/apps/cli/tests/profiles/headless/tests/harness.ts b/apps/cli/tests/profiles/headless/tests/harness.ts index cf51dc23a6..43164c9d7b 100644 --- a/apps/cli/tests/profiles/headless/tests/harness.ts +++ b/apps/cli/tests/profiles/headless/tests/harness.ts @@ -11,7 +11,7 @@ import * as ToolTodo from '@deepseek-ai/dsh-tool-todo' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key' import TokenMeter from '@deepseek-ai/dsh-token-meter' import ToolResultPruner from '@deepseek-ai/dsh-compaction-tool-result-pruner' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import * as SessionCheckpointPolicy from '@deepseek-ai/dsh-session-checkpoint-policy' import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic' import type { BasicCompactionConfig } from '@deepseek-ai/dsh-compaction-basic' diff --git a/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts b/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts index 7a46b1dc89..2e45acbb6c 100644 --- a/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts @@ -42,6 +42,7 @@ const tsconfigPath = fileURLToPath(new URL('../../../../../../tsconfig.json', im const reasoningConfigPath = fileURLToPath(new URL('./fixtures/cli.patch.yml', import.meta.url)) const deepseekDefaultsConfigPath = fileURLToPath(new URL('./fixtures/deepseek-defaults.patch.yml', import.meta.url)) const piAiDefaultsConfigPath = fileURLToPath(new URL('./fixtures/pi-ai-defaults.patch.yml', import.meta.url)) +const piAiConversationUpdatesConfigPath = fileURLToPath(new URL('./fixtures/pi-ai-conversation-updates.patch.yml', import.meta.url)) const headlessOverlayPath = fileURLToPath(new URL('./fixtures/headless-profile.patch.yml', import.meta.url)) const headlessSessionExpected = join(goldensDir, 'headless-profile', 'session.expected.jsonl') const headlessReasoningExpected = join(goldensDir, 'headless-profile', 'reasoning.stderr.expected.txt') @@ -148,6 +149,58 @@ async function deepseekDefaultsServer( } } +/** Script Chat Completions responses in request order: `read`, then `snapshot_ping`, then text. */ +async function piAiConversationServer(): Promise { + const requests: JsonObject[] = [] + const agentReplies = [ + { tool_calls: [{ index: 0, id: 'call_read', type: 'function', function: { name: 'read', arguments: '{"file_path":"task.txt"}' } }] }, + { tool_calls: [{ index: 0, id: 'call_ping', type: 'function', function: { name: 'snapshot_ping', arguments: '{}' } }] }, + { content: 'DONE' }, + ] + const server = createServer((request: IncomingMessage, response: ServerResponse) => { + let body = '' + request.setEncoding('utf8') + request.on('data', (chunk: string) => { body += chunk }) + request.on('end', () => { + requests.push(JSON.parse(body) as JsonObject) + const delta = agentReplies[requests.length - 1] ?? { content: 'UNEXPECTED' } + const finish = 'tool_calls' in delta ? 'tool_calls' : 'stop' + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.end([ + `data: ${JSON.stringify({ choices: [{ delta }] })}`, + `data: ${JSON.stringify({ choices: [{ delta: {}, finish_reason: finish }], usage: { prompt_tokens: 3, completion_tokens: 1 } })}`, + 'data: [DONE]', + '', + ].join('\n\n')) + }) + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('pi-ai conversation snapshot server has no port') + return { + url: `http://127.0.0.1:${address.port}`, + requests, + paths: [], + close: () => new Promise(resolve => server.close(() => { resolve() })), + } +} + +/** Project one Chat Completions request to its fixture-owned declarations and message roles, tools, and prompt markers. */ +function piAiTranscript(request: JsonObject): JsonObject { + const names = (tools: unknown): string[] => Array.isArray(tools) + ? tools.map(tool => ((tool as { function: { name: string } }).function.name)) + : [] + return { + // Profile tools change independently of this scenario; only the fixture's tool is recorded. + tools: names(request.tools).filter(name => name === 'snapshot_ping'), + messages: (request.messages as JsonObject[]).map(message => ({ + role: message.role, + ...message.tools === undefined ? {} : { tools: names(message.tools) }, + ...typeof message.content === 'string' && message.content.includes('Dynamic tool guidance') ? { guidance: true } : {}, + })), + } +} + function parseJsonl(content: string): JsonObject[] { return content.split('\n') .filter(line => line.trim().length > 0) @@ -745,6 +798,113 @@ describe('headless stream-json snapshots', () => { } }, LOADER_SMOKE_TEST_TIMEOUT_MS) + it('sends pi-ai Kimi prompt and tool updates in conversation history', async () => { + const server = await piAiConversationServer() + try { + const result = await runLoaderSmoke({ + label: 'pi-ai Kimi conversation updates headless stream-json snapshot', + tempDirPrefix: 'headless-snapshot-pi-ai-conversation-updates-', + binScript, + libBinScript: binScript, + configPath: piAiConversationUpdatesConfigPath, + binArgs: [ + piAiConversationUpdatesConfigPath, + 'read task.txt and follow it', + ], + tsconfigPath, + prepare: cwd => writeFile(join(cwd, 'task.txt'), 'Call snapshot_ping once.\n'), + env: { + MOONSHOT_API_KEY: 'snapshot-key', + DSH_SNAPSHOT_BASE_URL: server.url, + NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '), + }, + }) + + expect(result.stderr).toBe('') + expect(parseJsonl(result.stdout).at(-1)).toMatchObject({ type: 'result', output: 'DONE' }) + expect(server.requests.map(piAiTranscript)).toMatchInlineSnapshot(` + [ + { + "messages": [ + { + "role": "system", + }, + { + "role": "user", + }, + { + "role": "user", + }, + ], + "tools": [], + }, + { + "messages": [ + { + "role": "system", + }, + { + "role": "user", + }, + { + "role": "user", + }, + { + "role": "assistant", + }, + { + "role": "tool", + }, + { + "guidance": true, + "role": "system", + }, + { + "role": "system", + "tools": [ + "snapshot_ping", + ], + }, + ], + "tools": [], + }, + { + "messages": [ + { + "role": "system", + }, + { + "role": "user", + }, + { + "role": "user", + }, + { + "role": "assistant", + }, + { + "role": "tool", + }, + { + "guidance": true, + "role": "system", + }, + { + "role": "assistant", + }, + { + "role": "tool", + }, + ], + "tools": [], + }, + ] + `) + } finally { + await server.close() + } + }, LOADER_SMOKE_TEST_TIMEOUT_MS) + it('runs a keyless Agent Team with peer mail, dependent tasks, waiting, and Lead aggregation', async () => { let projection: unknown const result = await runLoaderSmoke({ @@ -804,14 +964,14 @@ describe('headless stream-json snapshots', () => { if (typeof message !== 'object' || message === null || Array.isArray(message)) return false const source = (message as JsonObject).source return typeof source === 'object' && source !== null && !Array.isArray(source) - && (source as JsonObject).kind === 'team-message' + && (source as JsonObject).kind === 'agent-message' }) }) const steeredMessageIndex = implementerRows.findIndex((row) => { if (row.type !== 'user/message') return false const source = (row.data as JsonObject).source return typeof source === 'object' && source !== null && !Array.isArray(source) - && (source as JsonObject).kind === 'team-message' + && (source as JsonObject).kind === 'agent-message' }) const openTurnStart = implementerRows.findLastIndex((row, index) => ( index < steeredMessageIndex && row.type === 'turn/start' @@ -825,22 +985,26 @@ describe('headless stream-json snapshots', () => { if (data.name !== 'team_task_update' || typeof data.arguments !== 'string') return false return (JSON.parse(data.arguments) as JsonObject).action === 'complete' }) - const identityReminders = logs.flatMap((log) => { + const identities = logs.flatMap((log) => { if (log === parent || log === workflowChild) return [] const initial = parseJsonl(log.content).find(row => row.type === 'user/message' && ((row.data as JsonObject).source as JsonObject).kind === 'user') if (initial === undefined) throw new Error('Teammate Session has no initial task') const content = (initial.data as JsonObject).content as JsonObject[] - expect(content).toHaveLength(2) - const identity = content[0]!.text - if (typeof identity !== 'string') throw new Error('Teammate initial task has no identity text') - return [identity.trimEnd()] + expect(content).toHaveLength(1) + const context = parseJsonl(log.content).find(row => row.type === 'user/message' + && ((row.data as JsonObject).source as JsonObject).kind === 'runtime-context') + const source = (context?.data as JsonObject)?.source as JsonObject + const sections = source?.sections as JsonObject[] | undefined + const identity = sections?.find(section => section.name === 'team:identity')?.text + if (typeof identity !== 'string') throw new Error('Teammate runtime context has no identity') + return [identity] }).sort() projection = { sessions: logs.length, workflowStopReason: (rows.find(row => row.type === 'tool-workflow/run-end')?.data as JsonObject)?.stopReason, memberEdges: members.length, - identityReminders, + identities, activeMembers: members.filter(member => member.phase === 'active').map(member => member.name).sort(), tasks: latestTasks.map(task => ({ subject: task.subject, @@ -874,25 +1038,21 @@ describe('headless stream-json snapshots', () => { "researcher", ], "checkedRoster": true, - "deliveredMessages": 2, - "identityReminders": [ - " - You are teammate "implementer". + "deliveredMessages": 0, + "identities": [ + "You are teammate "implementer". Your Team Lead is named "lead". - Use list_agents({}) to find your teammates and their names. To message your Team Lead, use send_message({ target: "lead", message: "..." }). - To message another teammate, use send_message({ target: "", message: "..." }). - ", - " - You are teammate "researcher". + Use list_agents({}) to find your teammates and their names. + To message another teammate, use send_message({ target: "", message: "..." }).", + "You are teammate "researcher". Your Team Lead is named "lead". - Use list_agents({}) to find your teammates and their names. To message your Team Lead, use send_message({ target: "lead", message: "..." }). - To message another teammate, use send_message({ target: "", message: "..." }). - ", + Use list_agents({}) to find your teammates and their names. + To message another teammate, use send_message({ target: "", message: "..." }).", ], "memberEdges": 4, - "queuedMessages": 2, + "queuedMessages": 0, "sessions": 4, "steerEvidence": { "completedAfterMessage": true, diff --git a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts index 806f081a77..cce567d62e 100644 --- a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts @@ -212,7 +212,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => { }); return started.jobId; `)) - expect(jobId).toBe('bash-1') + expect(jobId).toMatch(/^bash-[0-9a-f]{16}$/) const polled = completion(await runCode(ctx, ` return await tools.job_output({ job_id: ${JSON.stringify(jobId)}, wait: true, timeout_ms: 5000 }); @@ -257,7 +257,8 @@ describe('PTC mode typed values: keyless real-process contracts', () => { }), ]) const job = ctx.jobs.list()[0] - expect(job).toMatchObject({ id: 'bash-1', status: 'running' }) + expect(job).toMatchObject({ status: 'running' }) + expect(job?.id).toMatch(/^bash-[0-9a-f]{16}$/) afterPublication.abort('outer-call-cancelled') expect((await running).isError).toBe(true) expect(ctx.jobs.list()[0]).toMatchObject({ id: job!.id, status: 'running' }) @@ -293,9 +294,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/cli/tests/profiles/headless/tests/semantic-checkpoint.expected.e2e.ts b/apps/cli/tests/profiles/headless/tests/semantic-checkpoint.expected.e2e.ts index e2815248f0..6ef2b9b331 100644 --- a/apps/cli/tests/profiles/headless/tests/semantic-checkpoint.expected.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/semantic-checkpoint.expected.e2e.ts @@ -11,7 +11,7 @@ import { import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke' import { createUserMessage, ToolCallId, createMessage } from '@deepseek-ai/dsh-llm' import { SessionSeq, SESSION_FORMAT_VERSION, SessionId, type SessionEvent, type SessionHeader } from '@deepseek-ai/dsh-session' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import { logPath } from '../../../../../../packages/session/session-persistence-jsonl/src/format.ts' import { describe, expect, it } from 'vitest' diff --git a/apps/cli/tests/profiles/headless/tests/session-format-guard.expected.e2e.ts b/apps/cli/tests/profiles/headless/tests/session-format-guard.expected.e2e.ts index 1574c2cab1..e5a66ed914 100644 --- a/apps/cli/tests/profiles/headless/tests/session-format-guard.expected.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/session-format-guard.expected.e2e.ts @@ -17,7 +17,7 @@ import { type SessionEvent, type SessionHeader, } from '@deepseek-ai/dsh-session' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import { generationLogFilename, generationLogPath, diff --git a/apps/cli/tests/profiles/headless/tests/subagent-diagnostic.expected.e2e.ts b/apps/cli/tests/profiles/headless/tests/subagent-diagnostic.expected.e2e.ts index cec8642309..941d95c31d 100644 --- a/apps/cli/tests/profiles/headless/tests/subagent-diagnostic.expected.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/subagent-diagnostic.expected.e2e.ts @@ -16,7 +16,7 @@ import { import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke' import { createMessage, createUserMessage } from '@deepseek-ai/dsh-llm' import { SessionSeq, SESSION_FORMAT_VERSION, SessionId, type SessionEvent, type SessionHeader } from '@deepseek-ai/dsh-session' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import { describe, expect, it } from 'vitest' const fixtureDir = fileURLToPath(new URL('./expected/subagent-diagnostic', import.meta.url)) diff --git a/apps/cli/tests/profiles/headless/tests/subagent-inheritance.expected.e2e.ts b/apps/cli/tests/profiles/headless/tests/subagent-inheritance.expected.e2e.ts index 52df6db0d9..adaf678278 100644 --- a/apps/cli/tests/profiles/headless/tests/subagent-inheritance.expected.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/subagent-inheritance.expected.e2e.ts @@ -16,7 +16,7 @@ import { import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke' import { createMessage, createUserMessage, ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { SessionSeq, SESSION_FORMAT_VERSION, SessionId, type SessionEvent, type SessionHeader } from '@deepseek-ai/dsh-session' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import { describe, expect, it } from 'vitest' const fixtureDir = fileURLToPath(new URL('./expected/subagent-inheritance', import.meta.url)) diff --git a/apps/cli/tests/profiles/headless/tests/workspace-context-resume.expected.e2e.ts b/apps/cli/tests/profiles/headless/tests/workspace-context-resume.expected.e2e.ts index aa6da3ad23..6dcc842cf9 100644 --- a/apps/cli/tests/profiles/headless/tests/workspace-context-resume.expected.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/workspace-context-resume.expected.e2e.ts @@ -23,7 +23,7 @@ import { type SessionEvent, type SessionHeader, } from '@deepseek-ai/dsh-session' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import { logPath } from '../../../../../../packages/session/session-persistence-jsonl/src/format.ts' import { renderAgentInstructions } from '@deepseek-ai/dsh-agent-instructions' import { resolveConfig, workspaceBaselineIdentity } from '@deepseek-ai/dsh-agent-instructions/src/config.ts' diff --git a/apps/cli/tests/profiles/official-installer-packed.e2e.ts b/apps/cli/tests/profiles/official-installer-packed.e2e.ts index 3062b5c5b8..e9039e8a5a 100644 --- a/apps/cli/tests/profiles/official-installer-packed.e2e.ts +++ b/apps/cli/tests/profiles/official-installer-packed.e2e.ts @@ -158,8 +158,8 @@ it.skipIf(!built)('installs the exported registry\'s local closure and switches expect(step.install, JSON.stringify(step.install)).toMatchObject({ application: 'applied', enabled: true, version }) expect(step.savedVersion).toBe(version) expect(step.installed).toMatchObject({ official: true, availability: 'profile', enabled: true, installed: true, version }) - expect(step.installed.rows.filter(row => row.preset !== undefined).map(row => row.preset).sort()) - .toEqual(['preset-cordis', 'preset-ptc', 'preset-standard']) + const product = step.name.replace('@deepseek-ai/dsh-subagent-', '') + expect(step.installed.rows.map(row => row.rowId)).toEqual([`subagent-${product}`, `tool-subagent-${product}`]) expect(step.providerEnabled).toBe(true) expect(step.nativeArtifact).toBe(true) // A transitive repository package the closure needs can only have come from this run's artifacts. diff --git a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts index 64c1c20ab3..5c51bd36ae 100644 --- a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts +++ b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts @@ -202,10 +202,14 @@ describe('Python SDK dsh profile keyless smoke', () => { }, 40_000) it.each([ - { label: 'boots the standalone minimal profile through its generated manifest', editorEnabled: false }, - { label: 'executes the documented editor opt-in patch with sdk-minimal', editorEnabled: true }, - ])('$label', async ({ editorEnabled }) => { + { label: 'boots the standalone minimal profile through its generated manifest', editorEnabled: false, imageEnabled: false, optOut: false, offloadEnabled: false }, + { label: 'executes the documented editor opt-in patch with sdk-minimal', editorEnabled: true, imageEnabled: false, optOut: false, offloadEnabled: false }, + { label: 'sends a read_image result to the model with sdk-minimal', editorEnabled: false, imageEnabled: true, optOut: false, offloadEnabled: false }, + { label: 'offloads an over-budget image and continues with sdk-minimal', editorEnabled: false, imageEnabled: true, optOut: false, offloadEnabled: true }, + { label: 'retains the previous tools through the documented opt-out patch', editorEnabled: false, imageEnabled: false, optOut: true, offloadEnabled: false }, + ])('$label', async ({ editorEnabled, imageEnabled, optOut, offloadEnabled }) => { const root = await mkdtemp(join(tmpdir(), 'dsh-python-sdk-minimal-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) const editorPatch = join(root, 'editor.patch.yml') if (editorEnabled) { const guide = await readFile(join(repoRoot, 'docs/user/guide/python-sdk.md'), 'utf8') @@ -214,7 +218,24 @@ describe('Python SDK dsh profile keyless smoke', () => { expect(yaml).toBeDefined() await writeFile(editorPatch, yaml!) } + if (optOut) { + const guide = await readFile(join(repoRoot, 'docs/upgrade-guide/v0.2.1-alpha.2/sdk-minimal-image-compaction/guide.md'), 'utf8') + const yaml = guide.match(/```yaml\n([\s\S]*?)```/)?.[1] + expect(yaml).toBeDefined() + await writeFile(editorPatch, yaml!) + } + if (offloadEnabled) await writeFile(editorPatch, [ + '- id: llm-deepseek', + ' config:', + ' apiKeyEnv: DEEPSEEK_API_KEY', + ' maxRequestFilesBytes: 1', + ' imageOffloadByteQuantum: 1', + '', + ].join('\n')) const editorFile = join(root, 'editor.txt') + if (imageEnabled) await writeFile(join(root, 'red.png'), Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC', 'base64', + )) const editorContent = 'sdk-minimal editor opt-in\n' const editorCalls = editorEnabled ? [ { command: 'create', path: editorFile, file_text: editorContent }, @@ -222,17 +243,29 @@ describe('Python SDK dsh profile keyless smoke', () => { ] : [] const modelRequests: Record[] = [] const modelServer = createServer((request, response) => { + if (imageEnabled && request.url?.endsWith('/files')) { + request.resume() + response.writeHead(200, { 'content-type': 'application/json' }) + response.end(JSON.stringify({ + id: 'file-minimal-image', type: 'file', size_bytes: 69, + created_at: new Date().toISOString(), + filename: 'red.png', mime_type: 'image/png', + })) + return + } let body = '' request.setEncoding('utf8') request.on('data', (chunk: string) => { body += chunk }) request.on('end', () => { modelRequests.push(JSON.parse(body) as Record) response.writeHead(200, { 'content-type': 'text/event-stream' }) - const toolCall = editorCalls[modelRequests.length - 1] + const toolCall = imageEnabled && modelRequests.length === 1 + ? { file_path: 'red.png' } + : editorCalls[modelRequests.length - 1] response.end(messagesResponse(toolCall ? { type: 'tool_use', - id: `editor-${toolCall.command}`, - name: 'str_replace_editor', + id: imageEnabled ? 'minimal-image-read' : `editor-${editorCalls[modelRequests.length - 1]?.command}`, + name: imageEnabled ? 'read_image' : 'str_replace_editor', input: toolCall, } : { type: 'text', text: 'done' }, toolCall ? 'tool_use' : 'end_turn')) }) @@ -244,7 +277,7 @@ describe('Python SDK dsh profile keyless smoke', () => { ...launch.args, '--profile', 'sdk-minimal', - ...(editorEnabled ? ['--patch', editorPatch] : []), + ...(editorEnabled || optOut || offloadEnabled ? ['--patch', editorPatch] : []), ], { cwd: repoRoot, env: { @@ -274,7 +307,7 @@ describe('Python SDK dsh profile keyless smoke', () => { jsonrpc: '2.0', id: 1, method: 'initialize', - params: { cwd: root, provider: 'deepseek-official', model: 'deepseek-v4-pro' }, + params: { cwd: root, provider: 'deepseek-official', model: imageEnabled ? 'deepseek-flash' : 'deepseek-v4-pro' }, })}\n`) await waitForLine(lines, value => value.id === 1, () => stderr) child.stdin.write(`${JSON.stringify({ @@ -283,9 +316,11 @@ describe('Python SDK dsh profile keyless smoke', () => { method: 'session/prompt', params: { sessionId: 'minimal', contentBlocks: [{ type: 'text', text: 'inspect tools' }] }, })}\n`) + const offloads: Record[] = [] const turnEnd = await waitForLine(lines, (value) => { const params = value.params as Record | undefined const event = params?.event as Record | undefined + if (params?.sessionId === 'minimal' && event?.type === 'image/offload') offloads.push(event) return params?.sessionId === 'minimal' && event?.type === 'turn/end' }, () => stderr) expect(turnEnd, `${JSON.stringify(turnEnd)}\n${stderr}`).toMatchObject({ @@ -302,10 +337,31 @@ describe('Python SDK dsh profile keyless smoke', () => { const tools = modelRequests[0]?.tools as { name?: string }[] expect(tools.map(tool => tool.name)).toEqual([ process.platform === 'win32' ? 'pwsh' : 'bash', + ...(optOut ? [] : ['read_image']), ...(editorEnabled ? ['str_replace_editor'] : []), 'working_directory', ]) - expect(modelRequests).toHaveLength(editorEnabled ? 3 : 1) + expect(modelRequests).toHaveLength(editorEnabled ? 3 : imageEnabled ? 2 : 1) + if (imageEnabled) { + const messages = modelRequests[1]?.messages as { + content: { type: string; tool_use_id?: string; content?: { type: string; source?: { type: string; file_id: string } }[] }[] + }[] + const imageResult = messages.flatMap(message => message.content) + .find(block => block.type === 'tool_result' && block.tool_use_id === 'minimal-image-read') + if (offloadEnabled) { + expect(offloads).toHaveLength(1) + expect(offloads[0]).toMatchObject({ data: { targets: [{ imageIndexes: [0] }] } }) + expect(imageResult?.content?.some(block => block.type === 'image')).toBe(false) + expect(JSON.stringify(imageResult?.content)).toContain('red.png') + } else { + expect(offloads).toEqual([]) + expect(imageResult?.content).toEqual(expect.arrayContaining([ + { type: 'image', source: { type: 'file', file_id: 'file-minimal-image' } }, + ])) + } + const stored = await readdir(join(root, '.dsh', 'attachments', 'v1', 'objects'), { recursive: true }) + expect(stored.some(file => /[a-f0-9]{64}$/u.test(file))).toBe(true) + } if (editorEnabled) { expect(await readFile(editorFile, 'utf8')).toBe(editorContent) expect(modelRequests[2]?.messages).toEqual(expect.arrayContaining([ @@ -334,7 +390,6 @@ describe('Python SDK dsh profile keyless smoke', () => { child.kill('SIGKILL') await child await new Promise(resolve => modelServer.close(() => { resolve() })) - await rm(root, { recursive: true, force: true }) } }, 40_000) @@ -494,8 +549,11 @@ it.each(['unset', 'empty', 'bundled', 'full', 'python-only', 'python-only-no-cli }, () => stderr) const names = (requests[0]!.tools as { name: string }[]).map(value => value.name) expect(names.includes('load_workspace_dependencies')).toBe(enabled) + expect(JSON.stringify(requests[0]!.messages).includes('`office`')).toBe(enabled && mode !== 'missing-assets') + expect(names).not.toContain('office_tools') + expect(names).not.toContain('render_document') for (const name of ['office-docx', 'office-pptx', 'office-xlsx']) { - expect(JSON.stringify(requests[0]!.messages).includes(name)).toBe(enabled && mode !== 'missing-assets' && mode !== 'python-only') + expect(JSON.stringify(requests[0]!.messages).includes(name)).toBe(enabled && mode !== 'missing-assets') } if (mode === 'wrong-type') { expect(requests).toHaveLength(2) @@ -524,8 +582,8 @@ it.each(['unset', 'empty', 'bundled', 'full', 'python-only', 'python-only-no-cli expect.objectContaining({ role: 'user', content }), ])) } - if (mode === 'python-only') expect(stderr).toContain('node') - if (mode === 'missing-assets') expect(stderr).toContain('check_office.py') + if (mode === 'python-only') expect(stderr).not.toContain('ENOENT') + if (mode === 'missing-assets') expect(stderr).toContain('SKILL.md') await send(3, 'shutdown') const exit = await child expect(exit.timedOut).toBe(false) diff --git a/apps/cli/tests/profiles/sdk/office-cli.e2e.ts b/apps/cli/tests/profiles/sdk/office-cli.e2e.ts index d94a88a304..2c90e5fc6e 100644 --- a/apps/cli/tests/profiles/sdk/office-cli.e2e.ts +++ b/apps/cli/tests/profiles/sdk/office-cli.e2e.ts @@ -2,7 +2,7 @@ * Agent discovery of the installed Office CLI through the shipped SDK profile. * Defaults to built Node packages. DSH_OFFICE_TEST_EXECUTABLE/ENTRY select a * relocated Node or Electron carrier; CARRIER=sdk selects the standalone executable. - * NODE/CLI/ASSETS under the same prefix supply Desktop resources outside ASAR. + * NODE/CLI/ASSETS under the same prefix select Desktop command and skill resources outside ASAR. * API=openai-completions selects a development gateway instead of the default Messages API. */ import { access, mkdir, mkdtemp, readFile, rm, symlink, writeFile, chmod } from 'node:fs/promises' @@ -29,16 +29,13 @@ it.skipIf(!process.env.DEEPSEEK_API_KEY || process.platform === 'win32')(`agent 'word/document.xml': strToU8('Office CLI discovery'), })) const patch = join(root, 'office.patch.yml') + const node = process.env.DSH_OFFICE_TEST_NODE, cli = process.env.DSH_OFFICE_TEST_CLI + const assetRoot = process.env.DSH_OFFICE_TEST_ASSETS await writeFile(patch, JSON.stringify([ ...(process.env.DSH_OFFICE_TEST_API === 'openai-completions' ? [{ id: 'llm-deepseek', disabled: true }, { id: 'llm-pi-ai', config: { providers: { 'office-test': { api: 'openai-completions', apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: process.env.DEEPSEEK_BASE_URL, compat: { thinkingFormat: 'deepseek' }, models: [{ id: process.env.MODEL_NAME ?? 'deepseek-v4-flash', contextWindow: 128000, maxTokens: 8000 }] } } } }] : []), { id: 'session-persistence-jsonl', config: { root: join(root, 'sessions'), compression: 'none' } }, - ...carrier === 'sdk' ? [] : [{ insert: [{ - id: 'office-cli-discovery', name: '@deepseek-ai/dsh-skill-office', config: { - ...(process.env.DSH_OFFICE_TEST_NODE ? { node: process.env.DSH_OFFICE_TEST_NODE } : {}), - ...(process.env.DSH_OFFICE_TEST_CLI ? { cli: process.env.DSH_OFFICE_TEST_CLI } : {}), - ...(process.env.DSH_OFFICE_TEST_ASSETS ? { assetRoot: process.env.DSH_OFFICE_TEST_ASSETS } : {}), - }, - }] }], + { id: 'skill-office', disabled: false }, + { id: 'skill-office', config: { ...assetRoot === undefined ? {} : { assetRoot }, ...node === undefined ? {} : { node }, ...cli === undefined ? {} : { cli } } }, ])) // A private POSIX tool directory also excludes /usr/bin/node on Linux. const path = join(root, 'bin') @@ -54,7 +51,7 @@ it.skipIf(!process.env.DEEPSEEK_API_KEY || process.platform === 'win32')(`agent await writeFile(decoy, '#!/bin/sh\nprintf invoked > ' + "'" + decoyMarker.replaceAll("'", "'\\''") + "'" + '\nexit 86\n') await chmod(decoy, 0o755) } - const lookup = await execa('/bin/sh', ['-c', 'command -v node || command -v libreoffice-kit'], { env: { PATH: path }, reject: false }) + const lookup = await execa('/bin/sh', ['-c', 'command -v node || command -v dsoffice'], { env: { PATH: path }, reject: false }) expect(lookup.exitCode, 'the fixture must not expose Node or the Office CLI through PATH').not.toBe(0) const child = execa(executable, [ ...carrier === 'sdk' ? [] : [entry], '--profile', 'sdk', '--patch', patch, @@ -103,10 +100,12 @@ it.skipIf(!process.env.DEEPSEEK_API_KEY || process.platform === 'win32')(`agent const commands = calls.filter(call => call.name === 'bash') expect(commands.length, diagnostic).toBeGreaterThan(0) expect(calls.findIndex(call => call.name === 'skill'), diagnostic).toBeLessThan(calls.findIndex(call => call.name === 'bash')) - const commandText = JSON.stringify(commands) - for (const fragment of ['cli.js', 'capabilities', 'convert']) expect(commandText, diagnostic).toContain(fragment) + const commandText = commands.map((call) => { + if (typeof call.arguments !== 'string') throw new Error('Shell tool call did not contain serialized arguments') + return (JSON.parse(call.arguments) as { command: string }).command + }).join('\n') + for (const operation of ['capabilities', 'convert']) expect(commandText, diagnostic).toMatch(new RegExp(`\\s${operation}\\b`, 'u')) expect(existsSync(decoyMarker), 'the agent must not invoke system Office when the bundled CLI is supplied').toBe(false) - expect(commandText, 'the skill supplies an entry; searching for other Office binaries is unnecessary').not.toMatch(/(?:which|whereis|command -v|find).{0,100}(?:libreoffice|soffice)/iu) const capabilities = JSON.parse(await readFile(join(root, 'capabilities.json'), 'utf8')) as { runtime: { version: string; cliPath: string } } expect(capabilities.runtime.version).toBe('0.1.5') expect(capabilities.runtime.cliPath).toMatch(/lib[/\\]cli\.js$/u) diff --git a/apps/cli/tests/profiles/web/tests/office.expected.e2e.ts b/apps/cli/tests/profiles/web/tests/office.expected.e2e.ts new file mode 100644 index 0000000000..9c47584c49 --- /dev/null +++ b/apps/cli/tests/profiles/web/tests/office.expected.e2e.ts @@ -0,0 +1,12 @@ +/** Ordinary Web leaves Office authoring composition to its carrier. */ +import { expect, it } from 'vitest' +import { withDefaultWeb } from './default-web-process.ts' + +it('does not mount Office skills, commands, or authoring dependencies in ordinary Web', async (test) => { + await withDefaultWeb(test, async ({ request }) => { + const roster = await request('roster') + for (const name of ['skill-office', 'office-commands', 'tool-workspace-dependencies']) { + expect(roster.plugins.some(plugin => plugin.name === name)).toBe(false) + } + }) +}) diff --git a/apps/cli/tests/profiles/web/tests/public-url.expected.e2e.ts b/apps/cli/tests/profiles/web/tests/public-url.expected.e2e.ts index 5ed381e1d0..b596f4e943 100644 --- a/apps/cli/tests/profiles/web/tests/public-url.expected.e2e.ts +++ b/apps/cli/tests/profiles/web/tests/public-url.expected.e2e.ts @@ -1,7 +1,8 @@ -/** Built Web-profile acceptance for the advertised public root and browser authentication behind a prefix-stripping proxy. */ +/** Built Web-profile acceptance for concrete bind addresses, the advertised public root, and browser authentication. */ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { request as httpRequest, type IncomingMessage } from 'node:http' +import { request as httpsRequest } from 'node:https' import { tmpdir } from 'node:os' import { join } from 'node:path' import { createInterface } from 'node:readline' @@ -9,8 +10,10 @@ import { Readable } from 'node:stream' import { fileURLToPath, pathToFileURL } from 'node:url' import { execa } from 'execa' import { describe, expect, it } from 'vitest' +import { probeNonLoopbackIpv4, probeZonedLoopback } from '../../../../../../scripts/test-non-loopback-address.ts' import { startPrefixProxy } from '../../../../../../apps/web/tests/prefix-proxy.ts' import { PROCESS_SHUTDOWN_TIMEOUT_MS } from '../../../../src/process-shutdown.ts' +import { materializeTlsFixture } from '../../../../../../packages/host/webserver/tests/tls-fixture.ts' const repoRoot = fileURLToPath(new URL('../../../../../../', import.meta.url)) const dshBin = join(repoRoot, 'apps/cli/lib/bin.js') @@ -19,6 +22,18 @@ const builtArtifactsExist = existsSync(dshBin) /** Browser-facing mount the reference proxy serves and strips. */ const MOUNT = '/tools/dsh/' +const NON_LOOPBACK_IPV4 = builtArtifactsExist ? await probeNonLoopbackIpv4() : undefined + +const ZONED_LOOPBACK = builtArtifactsExist ? await probeZonedLoopback() : undefined + +/** + * Every spelling that binds IPv6 loopback. `::0.0.0.1` is the same address as + * `::1`, and the zoned rows reuse the probed scope on that same address. + */ +const IPV6_LOOPBACKS = ZONED_LOOPBACK === undefined + ? ['::1', '::0.0.0.1'] + : ['::1', '::0.0.0.1', ZONED_LOOPBACK, ZONED_LOOPBACK.replace('::1%', '::0.0.0.1%')] + /** One live Web child, as `execa` types it. */ type WebChild = ReturnType @@ -155,16 +170,22 @@ function expectCleanExit(stopped: StoppedWeb): void { } /** - * One HTTP request that connects to an explicit transport address while - * presenting an explicit browser-facing authority, as a proxy would. + * One request to an explicit transport address with a browser-facing authority. + * HTTPS verifies the certificate and hostname against the supplied CA or system roots. */ async function request( - dial: string, port: number, path: string, host: string, method: 'GET' | 'POST', cookie?: string, + protocol: 'http:' | 'https:', + dial: string, port: number, path: string, host: string, method: 'GET' | 'POST', cookie?: string, ca?: string, ): Promise { const { promise, resolve, reject } = Promise.withResolvers() - const req = httpRequest({ + const req = (protocol === 'http:' ? httpRequest : httpsRequest)({ host: dial, port, path, method, - headers: { host, 'content-type': 'application/json', ...cookie === undefined ? {} : { cookie } }, + ...ca === undefined ? {} : { ca }, + headers: { + host, 'content-type': 'application/json', + ...protocol === 'http:' ? {} : { origin: `https://${host}` }, + ...cookie === undefined ? {} : { cookie }, + }, }, resolve) req.once('error', reject) req.setTimeout(10_000, () => { req.destroy(new Error('HTTP request timed out')) }) @@ -181,16 +202,45 @@ async function request( /** Establish the browser session needed by the protected API, keeping the minted cookie's own attributes. */ async function exchange( - dial: string, port: number, path: string, host: string, + protocol: 'http:' | 'https:', + dial: string, port: number, path: string, host: string, ca?: string, ): Promise<{ cookie: string; setCookie: string }> { - const response = await request(dial, port, path, host, 'GET') + const response = await request(protocol, dial, port, path, host, 'GET', undefined, ca) const setCookie = response.headers.get('set-cookie') await response.arrayBuffer() if (setCookie === null) throw new Error(`entry returned ${String(response.status)} without a browser cookie`) return { cookie: setCookie.split(';', 1)[0]!, setCookie } } -describe.skipIf(!builtArtifactsExist)('dsh Web profile advertised public root', () => { +describe.skipIf(!builtArtifactsExist)('dsh Web profile bind address and advertised root', () => { + it('serves the default advertised URL over verified TLS with Secure browser authentication', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-web-tls-')) + try { + const tls = await materializeTlsFixture(root) + await withWeb(['--tls-cert', tls.certFile, '--tls-key', tls.keyFile], async (web) => { + expect(web.startup.origin).toBe(`https://127.0.0.1:${String(web.port)}`) + await expect(request('https:', '127.0.0.1', web.port, '/', web.startup.host, 'GET')) + .rejects.toThrow(/self-signed certificate/i) + const { cookie, setCookie } = await exchange( + 'https:', '127.0.0.1', web.port, `${web.startup.pathname}${web.startup.search}`, web.startup.host, tls.ca, + ) + expect(setCookie).toContain('; Secure') + const index = await request('https:', '127.0.0.1', web.port, '/', web.startup.host, 'GET', cookie, tls.ca) + expect(index.status).toBe(200) + expect(await index.text()).toContain(' { await withWeb(['--public-url', `http://gateway.example${MOUNT.slice(0, -1)}`, '--trusted-host', 'gateway.example'], async (web) => { expect(web.startup.origin).toBe('http://gateway.example') @@ -204,12 +254,12 @@ describe.skipIf(!builtArtifactsExist)('dsh Web profile advertised public root', { dial: '127.0.0.1', port: web.port, prefix: '/', host: `127.0.0.1:${String(web.port)}` }, ] for (const entry of entries) { - const { cookie } = await exchange(entry.dial, entry.port, `${entry.prefix}${web.startup.search}`, entry.host) - const response = await request(entry.dial, entry.port, `${entry.prefix}api/session/create`, entry.host, 'POST', cookie) + const { cookie } = await exchange('http:', entry.dial, entry.port, `${entry.prefix}${web.startup.search}`, entry.host) + const response = await request('http:', entry.dial, entry.port, `${entry.prefix}api/session/create`, entry.host, 'POST', cookie) expect(response.status).toBe(200) expect(await response.json()).toMatchObject({ result: { ok: true } }) } - const foreign = await request('127.0.0.1', proxy.port, `${MOUNT}api/session/create`, 'evil.example', 'POST') + const foreign = await request('http:', '127.0.0.1', proxy.port, `${MOUNT}api/session/create`, 'evil.example', 'POST') expect(foreign.status).toBe(403) await foreign.arrayBuffer() } finally { @@ -218,4 +268,89 @@ describe.skipIf(!builtArtifactsExist)('dsh Web profile advertised public root', expectCleanExit(await web.stop()) }) }) + + it.skipIf(NON_LOOPBACK_IPV4 === undefined)('serves the bound address and a declared authority, refusing any other name', async () => { + const trustedHost = 'dsh-direct.example' + await withWeb(['--host', NON_LOOPBACK_IPV4!, '--trusted-host', trustedHost], async (web) => { + expect(web.startup.origin).toBe(`http://${NON_LOOPBACK_IPV4!}:${String(web.port)}`) + expect(web.startup.pathname).toBe('/') + const token = web.startup.searchParams.get('token') + expect(token).not.toBeNull() + const authority = `${NON_LOOPBACK_IPV4!}:${String(web.port)}` + const { cookie, setCookie } = await exchange('http:', NON_LOOPBACK_IPV4!, web.port, `/${web.startup.search}`, authority) + // The carrier is plain HTTP, where a browser never returns a Secure cookie. + expect(setCookie).not.toContain('; Secure') + const authenticated = await request('http:', NON_LOOPBACK_IPV4!, web.port, '/api/session/create', authority, 'POST', cookie) + expect(authenticated.status).toBe(200) + expect(await authenticated.json()).toMatchObject({ result: { ok: true } }) + + // A declared authority is admitted without being advertised; any other + // name for the same socket is a rebound Host. + const declared = `${trustedHost}:${String(web.port)}` + const declaredSession = await exchange('http:', NON_LOOPBACK_IPV4!, web.port, `/${web.startup.search}`, declared) + const viaDeclared = await request('http:', NON_LOOPBACK_IPV4!, web.port, '/api/session/create', declared, 'POST', declaredSession.cookie) + expect(viaDeclared.status).toBe(200) + await viaDeclared.arrayBuffer() + const rebound = await request('http:', NON_LOOPBACK_IPV4!, web.port, '/api/session/create', `evil.example:${String(web.port)}`, 'POST', cookie) + expect(rebound.status).toBe(403) + await rebound.arrayBuffer() + + const stopped = await web.stop() + expectCleanExit(stopped) + expect(stopped.stderr).toContain(`listening on ${NON_LOOPBACK_IPV4!} over plain HTTP`) + expect(stopped.stderr).not.toContain(token!) + }) + }) + + + it.skipIf(NON_LOOPBACK_IPV4 === undefined)('warns about the plain-HTTP bind even when an HTTPS root is advertised', async () => { + await withWeb(['--host', NON_LOOPBACK_IPV4!, '--public-url', 'https://app.example/', '--trusted-host', 'app.example'], async (web) => { + expect(web.startup.origin).toBe('https://app.example') + expect(web.startup.host).toBe('app.example') + const token = web.startup.searchParams.get('token') + expect(token).not.toBeNull() + const { cookie } = await exchange('http:', NON_LOOPBACK_IPV4!, web.port, `/${web.startup.search}`, 'app.example') + const authenticated = await request('http:', NON_LOOPBACK_IPV4!, web.port, '/api/session/create', 'app.example', 'POST', cookie) + expect(authenticated.status).toBe(200) + expect(await authenticated.json()).toMatchObject({ result: { ok: true } }) + + const stopped = await web.stop() + expectCleanExit(stopped) + expect(stopped.stderr).toContain(`listening on ${NON_LOOPBACK_IPV4!} over plain HTTP`) + }) + }) + + it.each([ + '::ffff:127.0.0.1', + '::ffff:7f00:1', + ])('prints an IPv4 root for mapped loopback %s and serves it', async (host) => { + await withWeb(['--host', host], async (web) => { + expect(web.startup.origin).toBe(`http://127.0.0.1:${String(web.port)}`) + const { cookie } = await exchange('http:', web.startup.hostname, web.port, `/${web.startup.search}`, web.startup.host) + const authenticated = await request( + 'http:', web.startup.hostname, web.port, '/api/session/create', web.startup.host, 'POST', cookie, + ) + expect(authenticated.status).toBe(200) + expect(await authenticated.json()).toMatchObject({ result: { ok: true } }) + + const stopped = await web.stop() + expectCleanExit(stopped) + expect(stopped.stderr).not.toContain('plain HTTP') + }) + }) + + it.each(IPV6_LOOPBACKS)('prints the IPv6 loopback root for %s and serves it', async (host) => { + await withWeb(['--host', host], async (web) => { + expect(web.startup.origin).toBe(`http://[::1]:${String(web.port)}`) + const authority = `[::1]:${String(web.port)}` + const { cookie } = await exchange('http:', '::1', web.port, `/${web.startup.search}`, authority) + const authenticated = await request('http:', '::1', web.port, '/api/session/create', authority, 'POST', cookie) + expect(authenticated.status).toBe(200) + expect(await authenticated.json()).toMatchObject({ result: { ok: true } }) + + const stopped = await web.stop() + expectCleanExit(stopped) + expect(stopped.stderr).not.toContain('plain HTTP') + }) + }) }) diff --git a/apps/cli/tests/profiles/web/tests/web-best-effort-startup.expected.e2e.ts b/apps/cli/tests/profiles/web/tests/web-best-effort-startup.expected.e2e.ts index fa7d64a0e9..115c163d24 100644 --- a/apps/cli/tests/profiles/web/tests/web-best-effort-startup.expected.e2e.ts +++ b/apps/cli/tests/profiles/web/tests/web-best-effort-startup.expected.e2e.ts @@ -296,7 +296,7 @@ describe.skipIf(!builtArtifactsExist)('dsh Web profile best-effort startup', () expect(result.stderr).toContain('Failed plugins (1):') expect(result.stderr).toContain(' webserver (required)\n Package: @deepseek-ai/dsh-host-webserver') expect(result.stderr).toContain('Plugins waiting for services (') - expect(result.stderr).toMatch(/connection \(required\) +webRuntime/u) + expect(result.stderr).toMatch(/web-runtime \(required\) +webServer/u) expect(result.stderr).toContain('at Server.setupListenHandle') const summary = result.stderr.split(/\n\n(?:Full diagnostics:|dsh: warning:)/u)[0]! expect(summary.match(/EADDRINUSE/gu)).toHaveLength(1) @@ -319,7 +319,7 @@ describe.skipIf(!builtArtifactsExist)('dsh Web profile best-effort startup', () expect(report).toContain('configurationPath:') expect(report).toContain("code: 'EADDRINUSE'") expect(report).toContain(`port: ${String(address.port)}`) - expect(report).toContain("module: '@deepseek-ai/dsh-client-connection'") + expect(report).toContain("module: '@deepseek-ai/dsh-web-app'") expect(report).toContain('at auditStartupEntries') } finally { await new Promise((resolve, reject) => { diff --git a/apps/cli/tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts b/apps/cli/tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts index b1f89c11d1..64ab162454 100644 --- a/apps/cli/tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts +++ b/apps/cli/tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts @@ -59,8 +59,13 @@ function fixture() { ' }, 20)', ' ctx.effect(() => () => { clearInterval(timer) })', ' ctx.inject(["webServer", "connection"], scope => {', - ' writeFileSync(config.url, scope.connection.authenticatedUrl(`http://127.0.0.1:${scope.webServer.port}`))', - ' scope.effect(() => () => { rmSync(config.url, { force: true }) })', + ' let disposed = false', + ' scope.effect(() => () => { disposed = true; rmSync(config.url, { force: true }) })', + // A recovery URL is a readiness signal; sibling HMR work must settle first. + ' void scope.get("loader").await().then(() => {', + ' if (disposed || !scope.get("webServer") || !scope.get("connection")) return', + ' writeFileSync(config.url, scope.connection.authenticatedUrl(`http://127.0.0.1:${scope.webServer.port}`))', + ' })', ' })', '}', '', @@ -107,8 +112,8 @@ function fixture() { return { root, home, events, diagnostics, serverUrl, states, observer, stop, patch, watcher, render, url, config, witness, target } } -function start(f: ReturnType, extra: string[] = []) { - const child = execa(process.execPath, [bin, '--profile', 'web', '--patch', f.watcher, ...extra, '--no-open', '--port', '0'], { +function start(f: ReturnType, extra: string[] = [], nodeArgs: string[] = []) { + const child = execa(process.execPath, [...nodeArgs, bin, '--profile', 'web', '--patch', f.watcher, ...extra, '--no-open', '--port', '0'], { cwd: f.root, env: { ...process.env, DSH_HOME: f.home, DSH_AGENTS_HOME: join(f.root, '.agents'), DSH_TELEMETRY_DISABLED: '1', DEEPSEEK_API_KEY: 'keyless-matrix-no-call', NODE_NO_WARNINGS: '1' }, input: '', reject: false, timeout: 110_000, killSignal: 'SIGKILL', @@ -167,6 +172,64 @@ function exit(result: { timedOut: boolean; signal?: string | undefined; exitCode } describe.skipIf(!built)('Web process failure matrix', () => { + it('exits on unreadable TLS material without opening a listener', async () => { + const f = fixture() + const missingCert = join(f.root, 'missing-cert.pem') + const listenerProbe = join(f.root, 'listen-probe.mjs') + const listening = join(f.root, 'listening') + writeFileSync(listenerProbe, [ + "import { Server } from 'node:net'", + "import { appendFileSync } from 'node:fs'", + 'const listen = Server.prototype.listen', + 'Server.prototype.listen = function (...args) {', + ` this.once('listening', () => appendFileSync(${JSON.stringify(listening)}, 'listening\\n'))`, + ' return Reflect.apply(listen, this, args)', + '}', + '', + ].join('\n')) + const app = start(f, ['--tls-cert', missingCert, '--tls-key', missingCert], ['--import', pathToFileURL(listenerProbe).href]) + try { + const result = await app.child + exit(result, 1) + expect(result.stderr).toContain(missingCert) + expect(existsSync(listening)).toBe(false) + } finally { + exit(await app.close(), 1) + } + }) + + it('rejects a non-loopback zone bind through the required Web runtime before readiness', async () => { + const f = fixture() + const host = 'fe80::1%dsh-test' + const network = join(f.root, 'zone-listen.mjs') + // Mock only the OS bind: the real WebServer retains its configured zone, + // and the shipped runtime row, Loader dependencies, and boot audit stay real. + writeFileSync(network, [ + "import { Server } from 'node:net'", + 'const listen = Server.prototype.listen', + 'Server.prototype.listen = function (...args) {', + ` if (args[1] === ${JSON.stringify(host)}) {`, + ' args[1] = "127.0.0.1"', + ' }', + ' return Reflect.apply(listen, this, args)', + '}', + '', + ].join('\n')) + const app = start(f, ['--host', host], ['--import', pathToFileURL(network).href]) + try { + const result = await app.child + exit(result, 1) + expect(result.stderr).toContain('dsh: startup failed: 1 required plugin did not activate') + expect(result.stderr).toContain(' web-runtime (required)\n Package: @deepseek-ai/dsh-web-app') + expect(result.stderr).toContain(`bind address "${host}" carries an interface zone id`) + expect(result.stderr).toContain('pass --public-url') + expect(result.stdout).not.toContain('dsh web: http') + expect(app.events()).toBe('witness apply 0\nwitness dispose 0\n') + } finally { + exit(await app.close(), 1) + } + }) + for (const required of [false, true]) { const id = required ? 'acp' : 'matrix-optional' it.each(failures)(`${required ? 'required' : 'optional'} startup %s`, async (failure, diagnostic) => { @@ -408,7 +471,7 @@ export function apply(ctx, config) { // Entry-level injection requirements are captured when the fiber is created. writeFileSync(f.patch, f.render('matrix-optional') + `- id: ${id}\n disabled: true\n`) await app.wait(() => app.state(id) === FiberState.DISPOSED) - const inject = id === 'connection' ? ['webRuntime', 'matrixMissingWebDependency'] : ['matrixMissingWebDependency'] + const inject = id === 'connection' ? ['webStartup', 'matrixMissingWebDependency'] : ['matrixMissingWebDependency'] const pending = f.render('matrix-optional', undefined, 2) + `- id: ${id}\n inject: ${JSON.stringify(inject)}\n` writeFileSync(f.patch, pending) await app.wait(() => app.state(id) === FiberState.PENDING && app.events().includes('witness apply 2\n')) diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index 6fa2861ce0..4d1f9210a2 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -1,6 +1,6 @@ import { createRequire } from 'node:module' import { randomUUID } from 'node:crypto' -import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' @@ -13,22 +13,20 @@ import { loadProfile, PluginPackages, type Profile, - type ProfilePatch, } from '@deepseek-ai/dsh-app-boot' import { provideCmdline } from '@deepseek-ai/dsh-cmdline' import { SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' import type { Agent } from '@deepseek-ai/dsh-agent' import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include' import { afterAll, beforeAll, describe, expect, it, onTestFinished, vi } from 'vitest' -import { dump, load } from 'js-yaml' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' import { bundlePatchPaths, composeEntries } from '@deepseek-ai/dsh-app-boot' import { createPluginProfile } from '../../desktop/src/project-manager.ts' /** Profile entry ids whose volatile fields these scenarios edit through Settings. */ const SETTINGS_NAMESPACE = 'agent-preset-registry' const SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE = 'subagent-model-selection-settings' import { applyChildComposition, childSessionMeta } from '@deepseek-ai/dsh-subagent' -import { ToolCallId } from '@deepseek-ai/dsh-llm' +import { ToolCallId, LlmAdapter, createUserMessage } from '@deepseek-ai/dsh-llm' +import type { GenerateOptions, LlmResolvedModelInfo, StreamChunk } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-compaction-basic' import type {} from '@deepseek-ai/dsh-skill' import type {} from '@deepseek-ai/dsh-tools' @@ -48,6 +46,48 @@ const CLAUDE_CODE_PACKAGE_DIR = join(REPO_ROOT, 'packages/subagent/subagent-clau /** The installation anchor whose dependency surface the runtime resolution mirrors. */ const INSTALL_ANCHOR = join(REPO_ROOT, 'apps/cli/package.json') const MINIMAL_PROMPT = 'You are a helpful software engineer assistant.' +/** Deterministic model responses for the shipped minimal compaction path. */ +class MinimalCompactionAdapter extends LlmAdapter { + readonly requests: GenerateOptions[] = [] + + override resolveModel(provider: string, model: string): Promise { + return Promise.resolve({ provider, id: model, name: model, context: { contextWindow: 100_000 } }) + } + + override async * stream(options: GenerateOptions): AsyncIterable { + this.requests.push(options) + yield { type: 'block-start', index: 0, blockType: 'text' } + yield { type: 'block-end', index: 0, block: { + type: 'text', text: options.purpose === 'compaction' ? 'Preserve the requested project task.' : 'Ready.', + } } + yield { type: 'finish', reason: { kind: 'stop' } } + } +} +/** Emits one image read, then retains the request carrying its settled result. */ +class MinimalImageAdapter extends LlmAdapter { + readonly requests: GenerateOptions[] = [] + + override resolveModel(provider: string, model: string): Promise { + return Promise.resolve({ provider, id: model, name: model, context: { contextWindow: 1_000_000 }, + inputModalities: ['text', 'image'] }) + } + + override async * stream(options: GenerateOptions): AsyncIterable { + if (options.purpose !== undefined) { + yield { type: 'block-start', index: 0, blockType: 'text' } + yield { type: 'block-end', index: 0, block: { type: 'text', text: 'Image inspection' } } + yield { type: 'finish', reason: { kind: 'stop' } } + return + } + this.requests.push(options) + const first = this.requests.length === 1 + yield { type: 'block-start', index: 0, blockType: first ? 'tool-call' : 'text' } + yield { type: 'block-end', index: 0, block: first + ? { type: 'tool-call', id: ToolCallId('minimal-image-read'), name: 'read_image', arguments: '{"file_path":"red.png"}' } + : { type: 'text', text: 'Image inspected.' } } + yield { type: 'finish', reason: { kind: first ? 'tool-calls' : 'stop' } } + } +} const MINIMAL_BASH_DESCRIPTION = `Run commands in a bash shell * When invoking this tool, the contents of the "command" parameter does NOT need to be XML-escaped. * Network access depends on the task environment. Prefer configured mirrors/proxies when they are available. @@ -63,7 +103,7 @@ const MINIMAL_BASH_DESCRIPTION = `Run commands in a bash shell */ async function bootWeb( profileHome: string, - extra: ProfilePatch[] = [], + extra: PatchOptions[] = [], profilePackages: readonly string[] = [], profileBundles?: readonly string[], surface: 'web' | 'desktop' | 'spec' = 'spec', @@ -77,6 +117,7 @@ async function bootWeb( { id: 'storage-json', config: { root: storageRoot } }, // Fixed Session IDs must stay inside this boot's temporary profile root. { id: 'session-persistence-jsonl', config: { root: join(profileHome, 'sessions') } }, + { id: 'attachment-local', config: { dshHome: profileHome } }, // Host rows with side effects outside this process: a bound port, a served // asset tree, a telemetry exporter. `api-gateway` and `directory-picker` // stay ENABLED on purpose — the api-proxy is the host row that injects @@ -313,15 +354,112 @@ describe('the shipped Web composition', () => { expect(assembly.sections).toEqual([ { name: 'deployment:persona-prefix', text: MINIMAL_PROMPT }, ]) - expect(assembly.tools.map(tool => tool.name)).toEqual(['bash', 'working_directory']) + expect(assembly.tools.map(tool => tool.name)).toEqual(['bash', 'read_image', 'working_directory']) expect(assembly.tools.find(tool => tool.name === 'bash')?.description).toBe(MINIMAL_BASH_DESCRIPTION) expect(ctx.commands.find(handle.agent, 'goal')).toBeUndefined() // serviceFor reports preset-owned providers; unisolated consumers inherit the host fs. expect(ctx.agentPresets.serviceFor(handle.agent, 'fs')).toBeUndefined() expect(ctx.get('fs')?.sandboxMode).toBeDefined() expect(handle.agent.ctx.get('fs')?.sandboxMode).toBe(ctx.get('fs')?.sandboxMode) - expect(ctx.agentPresets.serviceFor(handle.agent, 'compaction')).toBeUndefined() + expect(ctx.agentPresets.serviceFor(handle.agent, 'compaction')).toBeDefined() expect(handle.agent.ctx.get('compaction')).toBeUndefined() + expect(ctx.commands.find(handle.agent, 'compact')).toBeDefined() + expect(await ctx.commands.execute(handle.agent, '/compact', [], new AbortController().signal)) + .toMatchObject({ result: { kind: 'success', text: 'No compactable history yet.' } }) + expect(handle.agent.session.snapshotEvents().some(event => event.type === 'compaction/start')).toBe(false) + } finally { + await handle.dispose() + } + }) + + it('reads an image in minimal mode and carries its durable reference into the next request', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'dsh-minimal-image-')) + onTestFinished(() => rm(cwd, { recursive: true, force: true })) + await writeFile(join(cwd, 'red.png'), Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC', 'base64')) + const adapter = new MinimalImageAdapter() + const unregister = ctx.llm.registerAdapter(['minimal-image-test'], adapter) + onTestFinished(unregister) + const handle = await ctx.agents.create({ + sessionId: SessionId('preset-minimal-image'), meta: { cwd }, + agentOptions: { provider: 'minimal-image-test', model: 'minimal-image-test' }, + setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined), + }) + try { + handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Inspect red.png.' }], source: { kind: 'user' } })) + await handle.agent.whenIdle() + expect(adapter.requests).toHaveLength(2) + const result = handle.agent.session.snapshotEvents().find(event => event.type === 'tool/result') + expect(result?.data.message.isError, JSON.stringify(result?.data.message.content)).toBe(false) + const image = handle.agent.session.deriveMessages().flatMap(message => message.content) + .find(block => block.type === 'image') + expect(image?.type).toBe('image') + if (image?.type !== 'image') throw new Error('minimal image read produced no durable image') + expect((await ctx.attachments.readImage(image.attachment)).data.byteLength).toBe(image.attachment.bytes) + expect(JSON.stringify(adapter.requests[1]?.messages)).toContain(image.attachment.attachmentId) + expect(adapter.requests[0]?.tools?.map(tool => tool.name)).toEqual(['bash', 'read_image', 'working_directory']) + expect(result?.data.meta).toMatchObject({ path: await realpath(join(cwd, 'red.png')) }) + } finally { + await handle.dispose() + } + }) + + it('compacts minimal history through /compact and continues from the checkpoint', async () => { + const adapter = new MinimalCompactionAdapter() + const unregister = ctx.llm.registerAdapter(['minimal-compaction-test'], adapter) + onTestFinished(unregister) + const handle = await ctx.agents.create({ + sessionId: SessionId('preset-minimal-compaction'), + agentOptions: { provider: 'minimal-compaction-test', model: 'minimal-compaction-test' }, + setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined), + }) + try { + handle.agent.followup(createUserMessage({ + content: [{ type: 'text', text: 'Remember the project requirements. '.repeat(200) }], source: { kind: 'user' }, + })) + await handle.agent.whenIdle() + const before = handle.agent.session.surface.replaceGeneration + const execution = await ctx.commands.execute(handle.agent, '/compact', [], new AbortController().signal) + expect(execution?.result.kind).toBe('success') + expect(handle.agent.session.surface.replaceGeneration).toBeGreaterThan(before) + const summary = handle.agent.session.snapshotEvents().find(event => event.type === 'compaction/summary') + expect(summary?.data.sourceCommandId).toBe(execution?.commandId) + expect(adapter.requests.filter(request => request.purpose === 'compaction')).toHaveLength(1) + handle.agent.followup(createUserMessage({ + content: [{ type: 'text', text: 'Continue the project task.' }], source: { kind: 'user' }, + })) + await handle.agent.whenIdle() + const last = adapter.requests.at(-1) + expect(last?.messages.flatMap(message => message.content) + .some(block => block.type === 'text' && block.text.includes('Preserve the requested project task.'))).toBe(true) + expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'working_directory']) + } finally { + await handle.dispose() + } + }) + + it('automatically compacts minimal history under context pressure', async () => { + const adapter = new MinimalCompactionAdapter() + const unregister = ctx.llm.registerAdapter(['minimal-pressure-test'], adapter) + onTestFinished(unregister) + const handle = await ctx.agents.create({ + sessionId: SessionId('preset-minimal-pressure'), + agentOptions: { provider: 'minimal-pressure-test', model: 'minimal-pressure-test' }, + setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined), + }) + try { + for (let turn = 0; turn < 3; turn++) { + handle.agent.followup(createUserMessage({ + content: [{ type: 'text', text: 'Remember the project requirements. '.repeat(6000) }], + source: { kind: 'user' }, + })) + await handle.agent.whenIdle() + } + const summaries = handle.agent.session.snapshotEvents().filter(event => event.type === 'compaction/summary') + expect(summaries.length).toBeGreaterThan(0) + expect(summaries.every(event => event.data.sourceCommandId === undefined)).toBe(true) + expect(handle.agent.session.snapshotEvents().some(event => event.type === 'compaction/start' + && event.data.turn !== null)).toBe(true) + expect(adapter.requests.some(request => request.purpose === 'compaction')).toBe(true) } finally { await handle.dispose() } @@ -337,8 +475,10 @@ describe('the shipped Web composition', () => { setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined), }) try { - expect(toolNames(ctx, minimal.agent)).toEqual(['bash', 'working_directory']) + expect(toolNames(ctx, minimal.agent)).toEqual(['bash', 'read_image', 'working_directory']) expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10) + expect(ctx.agentPresets.serviceFor(minimal.agent, 'compaction')) + .not.toBe(ctx.agentPresets.serviceFor(full.agent, 'compaction')) await minimal.dispose() @@ -503,7 +643,7 @@ describe('the shipped Web composition', () => { // stays the preset's choice — minimal mounts no `tool-skill`, so its // tool table has no loader even though the global layer is readable. expect((await ctx.skills.list({ scope: handle.agent })).map(skill => skill.name)).toContain('dsh-badge') - expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'working_directory']) + expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'working_directory']) } finally { await handle.dispose() } @@ -532,165 +672,74 @@ describe('the shipped Web composition', () => { }) }) -describe('product Bundle and user-preset intersection', () => { - const presetIds = ['products-none', 'products-codex', 'products-claude', 'products-both'] as const - type Product = 'codex' | 'claude-code' - type PresetId = typeof presetIds[number] +describe.each(['web', 'desktop'] as const)('%s native subagent bundles', (surface) => { + const products = ['codex', 'claude-code'] as const + type Product = typeof products[number] + const packageDir = (product: Product): string => (product === 'codex' ? CODEX_PACKAGE_DIR : CLAUDE_CODE_PACKAGE_DIR) + const toolName = (product: Product): string => `subagent_${product.replaceAll('-', '_')}` - async function bootProducts(installed: readonly Product[]): Promise { - const root = await mkdtemp(join(tmpdir(), 'dsh-product-presets-')) - const definitions: import('@deepseek-ai/cordis-plugin-loader').EntryOptions[] = [] - const standardConfig = composeEntries([webPatches('test')]).find(row => row.id === 'preset-standard')!.config as import('@deepseek-ai/dsh-agent-preset-registry').PresetDefinition - const standard = dump(standardConfig.plugins, { schema: entryListSchema }) - for (const id of presetIds) { - const plugins = load(standard, { schema: entryListSchema }) as import('@deepseek-ai/cordis-plugin-loader').EntryOptions[] - // User presets declare their own delegation rows; provider bundles target only the three full shipped presets. - if (id === 'products-codex' || id === 'products-both') { - plugins.push({ id: 'custom-tool-subagent-codex', name: '@deepseek-ai/dsh-tool-subagent', config: { - provider: 'codex', toolName: 'subagent_codex', maxDepth: 'provider-managed', - } }) - } - if (id === 'products-claude' || id === 'products-both') { - plugins.push({ id: 'custom-tool-subagent-claude-code', name: '@deepseek-ai/dsh-tool-subagent', config: { - provider: 'claude-code', toolName: 'subagent_claude_code', maxDepth: 'provider-managed', - } }) - } - definitions.push({ id: `preset-${id}`, name: '@deepseek-ai/dsh-agent-preset', config: { id, plugins } }) - } - const packageDir = (product: Product): string => ( - product === 'codex' ? CODEX_PACKAGE_DIR : CLAUDE_CODE_PACKAGE_DIR - ) - const packageName = (product: Product): string => ( - product === 'codex' - ? '@deepseek-ai/dsh-subagent-codex' - : '@deepseek-ai/dsh-subagent-claude-code' - ) - return await bootWeb(root, [{ insert: definitions }], installed.map(packageDir), [ - '@deepseek-ai/dsh-base', - '@deepseek-ai/dsh-web-app', - ...installed.map(packageName), - ]) + async function bootSelected(installed: readonly Product[], extra: PatchOptions[] = []): Promise { + const root = await mkdtemp(join(tmpdir(), `dsh-${surface}-native-bundles-`)) + onTestFinished(async () => { await rm(root, { recursive: true, force: true }) }) + return await bootWeb(root, extra, installed.map(packageDir), [ + '@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', ...installed.map(product => `@deepseek-ai/dsh-subagent-${product}`), + ], surface) } - it('composes the intersection of installed Bundles and enabled preset rows', async () => { - const enabledByPreset: Record = { - 'products-none': [], - 'products-codex': ['codex'], - 'products-claude': ['claude-code'], - 'products-both': ['codex', 'claude-code'], - } - const scenarios: Array<{ installed: Product[]; presets: readonly PresetId[] }> = [ - { installed: [], presets: ['products-both'] }, - { installed: ['codex'], presets: ['products-both'] }, - { installed: ['claude-code'], presets: ['products-both'] }, - { installed: ['codex', 'claude-code'], presets: presetIds }, - ] + async function presetTools(productCtx: Context, preset: string): Promise { + const handle = await productCtx.agents.create({ + sessionId: SessionId(`native-${surface}-${preset}-${randomUUID()}`), + setup: owner => productCtx.agentPresets.mount(owner, preset).then(() => undefined), + }) + try { + return toolNames(productCtx, handle.agent).filter(name => /(?:subagent|custom)_(?:codex|claude_code)$/.test(name)) + } finally { await handle.dispose() } + } - for (const { installed, presets } of scenarios) { - const productCtx = await bootProducts(installed) + it.each([[[]], [['codex']], [['claude-code']], [['codex', 'claude-code']]] as Array<[Product[]]>)( + 'adds the selected %j delegation tools to every preset as global tools', async (installed) => { + const productCtx = await bootSelected(installed) const spawn = vi.spyOn(productCtx.subprocess, 'spawn') try { - expect(productCtx.subagents.list() - .filter(name => name === 'codex' || name === 'claude-code') - .sort()) + expect(productCtx.subagents.list().filter(name => (products as readonly string[]).includes(name)).sort()) .toEqual([...installed].sort()) - for (const id of presets) { - const handle = await productCtx.agents.create({ - sessionId: SessionId(`preset-${id}-${installed.join('-') || 'none'}-${randomUUID()}`), - setup: agentCtx => productCtx.agentPresets.mount(agentCtx, id).then(() => undefined), - }) - try { - const productTools = enabledByPreset[id] - .filter(product => installed.includes(product)) - .map(product => product === 'codex' ? 'subagent_codex' : 'subagent_claude_code') - .sort() - const tools = toolNames(productCtx, handle.agent) - expect(tools.filter(name => name === 'subagent_codex' || name === 'subagent_claude_code')) - .toEqual(productTools) - expect(tools).toEqual(expect.arrayContaining(['job_kill', 'job_list', 'job_output'])) - for (const productTool of productTools) { - expect(toolParameterNames(productCtx, handle.agent, productTool)).toEqual([ - 'cwd', 'description', 'prompt', - ]) - } - } finally { - await handle.dispose() - } + const expected = installed.map(toolName).sort() + for (const preset of ['standard', 'cordis', 'ptc', 'minimal']) { + expect(await presetTools(productCtx, preset)).toEqual(expected) } + const handle = await productCtx.agents.create({ + sessionId: SessionId(`native-${surface}-params-${randomUUID()}`), + setup: owner => productCtx.agentPresets.mount(owner, 'standard').then(() => undefined), + }) + try { + for (const product of installed) { + expect(toolParameterNames(productCtx, handle.agent, toolName(product))).toEqual(['cwd', 'description', 'prompt']) + } + } finally { await handle.dispose() } expect(spawn).not.toHaveBeenCalled() } finally { spawn.mockRestore() await productCtx.fiber.dispose() } - } - }, 120_000) -}) + }, 120_000) -describe.each(['web', 'desktop'] as const)('%s native bundle adoption', (surface) => { - const products = ['codex', 'claude-code'] as const - const bundleNames = products.map(product => `@deepseek-ai/dsh-subagent-${product}`) - - async function bootSelected(extra: ProfilePatch[]): Promise { - const root = await mkdtemp(join(tmpdir(), `dsh-${surface}-native-adoption-`)) - onTestFinished(async () => { await rm(root, { recursive: true, force: true }) }) - return await bootWeb(root, extra, [CODEX_PACKAGE_DIR, CLAUDE_CODE_PACKAGE_DIR], [ - '@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', ...bundleNames, - ], surface) - } - - it('keeps selected provider identities and later tool overrides without duplicating custom preset tools', async () => { - const definition = composeEntries([webPatches('adoption')]).find(row => row.id === 'preset-cordis')! - .config as import('@deepseek-ai/dsh-agent-preset-registry').PresetDefinition - const config = { ...definition, plugins: [...definition.plugins, ...products.map(product => ({ - id: `tool-subagent-${product}`, name: '@deepseek-ai/dsh-tool-subagent', disabled: product === 'codex', - config: { provider: product, toolName: `custom_${product.replaceAll('-', '_')}`, maxDepth: 'provider-managed' }, - }))] } + it('keeps provider identities and applies later Host row overrides', async () => { const providerConfig = { model: 'adoption-model', env: { DSH_NATIVE_ADOPTION: 'preserved' } } - const productCtx = await bootSelected([ + const productCtx = await bootSelected(products, [ ...products.map(product => ({ id: `subagent-${product}`, config: providerConfig })), - { preset: 'preset-standard', id: 'tool-subagent-codex', disabled: true }, - { preset: 'preset-standard', id: 'tool-subagent-claude-code', config: { + { id: 'tool-subagent-codex', disabled: true }, + { id: 'tool-subagent-claude-code', config: { provider: 'claude-code', toolName: 'custom_claude_code', maxDepth: 'provider-managed', } }, - { id: 'preset-cordis', config }, ]) - const spawn = vi.spyOn(productCtx.subprocess, 'spawn') try { - expect(productCtx.subagents.list()).toEqual(expect.arrayContaining([...products])) for (const product of products) { expect([...productCtx.loader.entries()].find(entry => entry.options.id === `subagent-${product}`)?.options.config) .toMatchObject(providerConfig) } - for (const [preset, expected] of [ - ['standard', ['custom_claude_code']], ['cordis', ['custom_claude_code']], - ['ptc', ['subagent_claude_code', 'subagent_codex']], ['minimal', []], - ] as const) { - const handle = await productCtx.agents.create({ - sessionId: SessionId(`adoption-${surface}-${preset}-${randomUUID()}`), - setup: owner => productCtx.agentPresets.mount(owner, preset).then(() => undefined), - }) - try { - expect(toolNames(productCtx, handle.agent).filter(name => /(?:subagent|custom)_(?:codex|claude_code)/.test(name))) - .toEqual(expected) - } finally { await handle.dispose() } + for (const preset of ['standard', 'ptc', 'minimal']) { + expect(await presetTools(productCtx, preset)).toEqual(['custom_claude_code']) } - expect(spawn).not.toHaveBeenCalled() - } finally { - spawn.mockRestore() - await productCtx.fiber.dispose() - } - }, 120_000) - - it('reports a redundant manual tool instead of silently replacing the bundle contribution', async () => { - const productCtx = await bootSelected([{ preset: 'preset-standard', insert: [{ - id: 'manual-codex', name: '@deepseek-ai/dsh-tool-subagent', config: { - provider: 'codex', toolName: 'subagent_codex', maxDepth: 'provider-managed', - }, - }] }]) - try { - expect((await productCtx.agentPresets.list()).find(preset => preset.id === 'standard')?.broken) - .toContain('already registered') - expect(productCtx.profileContext.startedBundles).toEqual(expect.arrayContaining(bundleNames)) } finally { await productCtx.fiber.dispose() } }, 120_000) }) @@ -865,18 +914,19 @@ describe('a forked session', () => { }) describe('a delegated child', () => { - it('runs on the composition its parent runs on', async () => { + it.each([false, true])('inherits preset tools with seeded=%s and refuses child reminders', async (seeded) => { const parent = await ctx.agents.create({ - sessionId: SessionId('preset-child-parent'), + sessionId: SessionId(`preset-child-parent-${seeded}`), meta: { agentPreset: 'standard' }, setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined), }) // Exactly what an in-process subagent driver's creation window does. const child = await parent.agent.ctx.agents.create({ - sessionId: SessionId('preset-child'), - meta: childSessionMeta(parent.agent, 1, false), + sessionId: SessionId(`preset-child-${seeded}`), + meta: childSessionMeta(parent.agent, 1, seeded), + ...(seeded ? { seed: [], inheritedEventCount: SessionLogOffset(0) } : {}), setup: (agentCtx) => { - applyChildComposition(agentCtx, parent.agent, {}) + return applyChildComposition(agentCtx, parent.agent, {}) }, }) try { @@ -884,6 +934,21 @@ describe('a delegated child', () => { // The shipped `standard` preset is the whole coding agent; an empty // child here is the defect, and equality alone would not catch it. expect(toolNames(ctx, child.agent)).toContain('bash') + expect(ctx.tools.schemas(child.agent)).toEqual(ctx.tools.schemas(parent.agent)) + const calls = [ + ['schedule_create', { prompt: 'Check', after_seconds: 60, title: 'Check' }], + ['schedule_list', {}], + ['schedule_delete', { id: 'task-1' }], + ['schedule_update', { id: 'task-1', title: 'Check' }], + ] as const + for (const [name, args] of calls) { + expect(toolNames(ctx, child.agent)).toContain(name) + const result = await ctx.tools.execute({ + callId: ToolCallId(`child-${name}`), signal: new AbortController().signal, + name, arguments: args, agent: child.agent, + }) + expect(result.value).toEqual({ code: 'subagent_session', message: 'A delegated subagent cannot use reminders.' }) + } expect(child.agent.session.header.agentPreset).toBe('standard') } finally { await child.dispose() @@ -902,7 +967,7 @@ describe('a delegated child', () => { sessionId: SessionId('preset-child-switch'), meta: childSessionMeta(parent.agent, 1, false), setup: (agentCtx) => { - applyChildComposition(agentCtx, parent.agent, {}) + return applyChildComposition(agentCtx, parent.agent, {}) }, }) try { @@ -931,7 +996,7 @@ describe('the default preset as a user setting', () => { }) try { // An omitted preset id resolves the stored default instead of the composed default. - expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'working_directory']) + expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'working_directory']) } finally { await handle.dispose() } @@ -977,7 +1042,7 @@ describe('a profile patch stored before Developer tools owned preset selection', setup: agentCtx => legacy.agentPresets.mount(agentCtx).then(() => undefined), }) try { - expect(toolNames(legacy, handle.agent)).toEqual(['bash', 'working_directory']) + expect(toolNames(legacy, handle.agent)).toEqual(['bash', 'read_image', 'working_directory']) } finally { await handle.dispose() } diff --git a/apps/cli/tests/web-agent-shutdown.e2e.ts b/apps/cli/tests/web-agent-shutdown.e2e.ts new file mode 100644 index 0000000000..86ecaa5c75 --- /dev/null +++ b/apps/cli/tests/web-agent-shutdown.e2e.ts @@ -0,0 +1,87 @@ +/** Keyless SIGTERM regression for Agent cancellation during Web teardown. */ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createInterface } from 'node:readline' +import { fileURLToPath } from 'node:url' +import { execa } from 'execa' +import { expect, it } from 'vitest' +import { resolveExampleLaunch } from '@deepseek-ai/dsh-loader-smoke' + +it.each([ + { state: 'idle', cancelFirst: false }, + { state: 'running', cancelFirst: false }, + { state: 'idle', cancelFirst: true }, + { state: 'running', cancelFirst: true }, +])('preserves Agent cleanup during Web shutdown ($state, cancel first: $cancelFirst)', { retry: 0 }, async ({ state, cancelFirst }) => { + const root = await mkdtemp(join(tmpdir(), 'dsh-web-agent-shutdown-')) + try { + const patch = join(root, 'shutdown.patch.yml') + const resultPath = join(root, 'result.json') + const interrupt = join(root, 'interrupt') + await writeFile(patch, [ + '- id: hmr', + ' disabled: true', + '- id: session-title-llm', + ' disabled: true', + '- insert:', + ` - name: ${JSON.stringify(new URL('./fixtures/agent-shutdown.mjs', import.meta.url).href)}`, + ` config: ${JSON.stringify({ root, result: resultPath, interrupt, running: state === 'running', cancelFirst })}`, + '', + ].join('\n')) + const launch = resolveExampleLaunch({ + srcBin: fileURLToPath(new URL('../src/bin.ts', import.meta.url)), + tsconfigPath: fileURLToPath(new URL('../../../tsconfig.json', import.meta.url)), + configArgs: ['--profile', 'web', '--patch', patch, '--no-open', '--port', '0'], + env: { + DSH_HOME: join(root, '.dsh'), + DSH_AGENTS_HOME: join(root, '.agents'), + DSH_TELEMETRY_DISABLED: '1', + }, + }) + const child = execa(launch.command, launch.args, { + cwd: root, env: launch.env, stdin: 'pipe', + timeout: 90_000, killSignal: 'SIGKILL', reject: false, + }) + const lines = createInterface({ input: child.stdout }) + try { + const ready = Promise.withResolvers() + lines.on('line', (line) => { + if (line === 'agent-shutdown: ready') ready.resolve(undefined) + }) + await Promise.race([ + ready.promise, + child.then((result) => { throw new Error(`Web exited before readiness: ${result.stderr}`) }), + ]) + if (process.platform === 'win32') await writeFile(interrupt, '') + else child.kill('SIGTERM') + const result = await child + expect(result.timedOut, result.stderr).toBe(false) + expect(result.signal, result.stderr).toBeUndefined() + expect(result.exitCode, result.stderr).toBe(0) + expect(result.stderr).not.toMatch(/dsh: fatal|projection registration is not active/u) + const evidence: unknown = JSON.parse(await readFile(resultPath, 'utf8')) + expect(evidence).toMatchObject({ + abortHandled: 1, + status: 'idle', + nextStep: [], + nextTurn: [], + cancelled: [ + { data: { target: 'next-step', removedCount: 1 } }, + { data: { target: 'next-turn', removedCount: 1 } }, + ], + }) + if (state === 'running') { + expect(evidence).toMatchObject({ + lastEvent: { type: 'turn/end', data: { reason: { kind: 'aborted', reason: { kind: cancelFirst ? 'parent' : 'disposed' } } } }, + }) + } + } finally { + lines.close() + child.kill('SIGKILL') + await child + } + } finally { + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/apps/desktop-host/package.json b/apps/desktop-host/package.json index f2a75bfa51..c442c84f56 100644 --- a/apps/desktop-host/package.json +++ b/apps/desktop-host/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-desktop-host", "description": "Private Node-mode host process for the Electron desktop application", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "private": true, "license": "MIT", "type": "module", @@ -11,7 +11,7 @@ "lib/cli.js" ], "dependencies": { - "koffi": "^3.1.0", + "koffi": "3.1.1", "@deepseek-ai/libreoffice-kit": "^0.1.5", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh": "workspace:*", diff --git a/apps/desktop-host/src/cli.ts b/apps/desktop-host/src/cli.ts index 97a23b88a2..6c890f8990 100644 --- a/apps/desktop-host/src/cli.ts +++ b/apps/desktop-host/src/cli.ts @@ -7,7 +7,7 @@ import { installOfficeEngineResolution, runtimeArchivePath } from './office-engi /** * Run the ordinary CLI with Desktop's bundled package manager and reserved-profile plugin access. * @param runtimeDir - Prepared or ASAR-contained production DSH package tree. - * @param supportDir - Physical Desktop runtime directory containing pnpm. + * @param supportDir - Physical Desktop runtime directory containing the primary-runtime payload and Node launchers. * @returns Completion of the selected CLI command; profile plugins own their process lifetime. */ export async function runDesktopCli(runtimeDir: string, supportDir: string): Promise { @@ -16,7 +16,7 @@ export async function runDesktopCli(runtimeDir: string, supportDir: string): Pro manageDesktopProfile: true, packageManager: { command: process.execPath, - args: ['--expose-internals', join(supportDir, 'pnpm', 'bin', 'pnpm.mjs')], + args: ['--expose-internals', join(supportDir, 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs')], env: { ELECTRON_RUN_AS_NODE: '1', DSH_DESKTOP_NODE_EXECUTABLE: process.execPath, diff --git a/apps/desktop-host/src/index.ts b/apps/desktop-host/src/index.ts index dd8f57c54c..3086755b0b 100644 --- a/apps/desktop-host/src/index.ts +++ b/apps/desktop-host/src/index.ts @@ -27,7 +27,7 @@ async function main(): Promise { profile: 'desktop', resolvedProfile: { profile, installAnchor }, patchFiles: [], - args: ['--no-open', '--port', '0'], + args: ['--no-open', '--host', '127.0.0.1', '--port', '0'], ...(process.argv[5] === undefined ? {} : { packageManager: { command: process.execPath, @@ -100,7 +100,7 @@ async function main(): Promise { installPlatformSessionPublisher(ctx, (session) => { if (process.connected) process.send?.({ type: 'platform-session', session }) }) - const url = ctx.connection.authenticatedUrl(`http://127.0.0.1:${String(ctx.webServer.port)}`) + const url = ctx.connection.authenticatedUrl(`${ctx.webServer.protocol}//127.0.0.1:${String(ctx.webServer.port)}`) if (process.connected) process.send?.({ type: 'ready', url, injections: ctx.webServer.collectIndexInjections() }, (error) => { if (error !== null) console.error(error) }) } diff --git a/apps/desktop-host/tests/office.spec.ts b/apps/desktop-host/tests/office.spec.ts index 862f832029..02e741d4ce 100644 --- a/apps/desktop-host/tests/office.spec.ts +++ b/apps/desktop-host/tests/office.spec.ts @@ -1,6 +1,6 @@ import { cp, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { join, sep } from 'node:path' import { pathToFileURL } from 'node:url' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' @@ -9,12 +9,14 @@ import AgentRegistry from '@deepseek-ai/dsh-agent' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import SkillRegistry from '@deepseek-ai/dsh-skill' import ToolRuntime from '@deepseek-ai/dsh-tools' -import { expect, it } from 'vitest' +import { expect, it, vi } from 'vitest' import * as desktopOffice from '../src/office.ts' it('loads Desktop Office CLI paths and removes them on disposal', async () => { const root = await mkdtemp(join(tmpdir(), 'desktop-office-')) + vi.stubEnv('DSH_HOME', root) const ctx = new Context() + try { const assets = join(root, 'runtime', 'office-skills') await cp(new URL('../../../packages/skill/skill-office/assets/', import.meta.url), assets, { recursive: true }) @@ -47,10 +49,10 @@ it('loads Desktop Office CLI paths and removes them on disposal', async () => { await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(config).href } }) await ctx.loader.await() for (const entry of ctx.loader.entries()) await entry.fiber?.await() - expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['office-docx', 'office-pptx', 'office-xlsx']) - expect((await ctx.skills.get('office-pptx'))?.resourceBase).toEqual({ kind: 'directory', path: join(assets, 'office-pptx') }) - expect((await ctx.skills.get('office-pptx'))?.content).toContain('libreofficeKit') - expect((await ctx.skills.get('office-pptx'))?.content).toContain(JSON.stringify(nodeDirectory).slice(1, -1)) + expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['office', 'office-docx', 'office-export-pdf', 'office-pptx', 'office-recalculate', 'office-render', 'office-xlsx']) + expect((await ctx.skills.get('office-pptx'))?.resourceBase).toEqual({ kind: 'directory', path: join(assets, 'office-pptx').split(sep).join('/') }) + expect((await ctx.skills.get('office-pptx'))?.content).toContain('office-render') + expect((await ctx.skills.get('office-pptx'))?.content).not.toContain(nodeDirectory) expect(ctx.tools.schemas().map(tool => tool.name)).toEqual(['load_workspace_dependencies']) const entry = [...ctx.loader.entries()].find(entry => entry.options.name === 'office') expect(entry).toBeDefined() @@ -58,7 +60,10 @@ it('loads Desktop Office CLI paths and removes them on disposal', async () => { expect(await ctx.skills.list()).toEqual([]) expect(ctx.tools.schemas()).toEqual([]) } finally { - await ctx.fiber.dispose() - await rm(root, { recursive: true, force: true }) + try { await ctx.fiber.dispose() } + finally { + vi.unstubAllEnvs() + await rm(root, { recursive: true, force: true }) + } } }) diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 9c95cd3111..6060f79da9 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -2,24 +2,36 @@ # 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 apps/desktop/README.md +/: + en: 0d36989eb614345d + zh: a0a1a18c07621393 /deepseek-harness-desktop: - en: 0f0f6ea914eff51e - zh: 4934245b04e9f1c0 + en: 69a6e0c6712e463b + zh: 84e1d0b09c803704 +/deepseek-harness-desktop/summary: + en: 7bc8bf30de693222 + zh: e85993d8852b6cab +/deepseek-harness-desktop/table-of-contents: + en: 05fd227f99ee535a + zh: 60d7d62bc0026973 +/deepseek-harness-desktop/application-overview: + en: e9b22f232837e131 + zh: fc5f3834b969d2d2 /deepseek-harness-desktop/terminal-command: - en: bef92953c237363f - zh: d21d6effd21b8c00 + en: 5f2d25a1d8472647 + zh: 2acb5c5d7d1917e2 /deepseek-harness-desktop/closing-the-window-and-quitting: - en: c323e02e3f0305fe - zh: 3c730db632136443 + en: 24387a07ae4eb8e7 + zh: 0119352685cf273c /deepseek-harness-desktop/key-technical-decisions: - en: 069fdfd72d2ea26a + en: 3724c53da4f7647b zh: 76ae549d43c99bb4 /deepseek-harness-desktop/key-technical-decisions/bundled-workspace-dependencies: - en: 0f9b6c1d6761d108 - zh: 77127063f244c361 + en: 3368ff9b955ada69 + zh: e9209ef6ad4fd305 /deepseek-harness-desktop/bundled-command-runtime: - en: 09f0b75af9f0ed14 - zh: 60bbc2e67d5e87a8 + en: 372297005b57a08b + zh: 074a635ac17e4362 /deepseek-harness-desktop/installation-ownership: en: 22153a298a6662e1 zh: 3600803c8c9d0274 @@ -27,8 +39,8 @@ en: a1a47b09f4a72ba4 zh: 7b1cf27f0b72cf31 /deepseek-harness-desktop/installation-ownership/host-environment: - en: 84a9cc7ca9455aa8 - zh: 4091b8aa8231b74a + en: 98cf848762482d48 + zh: 74f9100a39ec8c2f /deepseek-harness-desktop/develop: en: fe6d23e6a3d3bc66 zh: d60c8d3a55747916 @@ -36,50 +48,32 @@ en: a51346b8d880ddba zh: 7913214c1c66063c /deepseek-harness-desktop/develop/welcome-window-appearance: - en: ae319a496639b38d - zh: ef044103240ac9da + en: 617a89aeb28131b9 + zh: 4d84bd5d86501c86 /deepseek-harness-desktop/package: - en: 4cd8a8da6977928d - zh: 9f624855a2edac37 -/deepseek-harness-desktop/package/release-versions: - en: 99607dc36badb7f1 - zh: 5df47873fe8cdea8 -/deepseek-harness-desktop/package/local-macos-dmg-without-release-signing: - en: 57869a5e3885f843 - zh: 7cfc01b2dcbebd78 -/deepseek-harness-desktop/package/local-official-bundles-from-a-loopback-registry: - en: 5f05072ec82cc62d - zh: a3d63b58d1ef2db7 -/deepseek-harness-desktop/package/runtime-file-selection: - en: e7c1eb8e78fe46e3 - zh: b7ea497dd75be524 -/deepseek-harness-desktop/package/upload-updates: - en: f48baa680e841b0d - zh: 25ded1aeaac6dad1 -/deepseek-harness-desktop/package/unsigned-windows-test-installer: - en: cfd5780dd26a8e46 - zh: f7a16b1ede793b7b -/deepseek-harness-desktop/package/windows-installer-interface: - en: 1fc1db8f54475c8f - zh: dd834ed206070396 -/deepseek-harness-desktop/package/windows-ev-signing: - en: be1379e4b4703e14 - zh: 244ccd2874bb155a + en: ac31ebdd9de54f34 + zh: 921e534d5c4b3a16 +/deepseek-harness-desktop/windows-installer-interface: + en: 8cb4b7babbd8714d + zh: b4aebc1d2d152e01 /deepseek-harness-desktop/updates: - en: 10d58aa5bbffbd67 - zh: d9c2476e744a6537 + en: 4788b6b60489ef92 + zh: 6312c5590efa27f1 +/deepseek-harness-desktop/updates/local-desktop-settings: + en: 2e57457c44c85b5f + zh: 5b8510a3dc4c6c9d /deepseek-harness-desktop/updates/mandatory-update-policy: - en: 1527dceec540649e - zh: 543782c36f91f893 + en: 54596bef0706d305 + zh: 48737302dcf3c939 /deepseek-harness-desktop/updates/local-updater-qualification: - en: bc50fd8a4d96c227 - zh: fb0a6ce80c31cda6 + en: 68ec2f8bd5763ea6 + zh: 23b932dfe8503602 /deepseek-harness-desktop/low-level-development-overrides: - en: 0b225f914142ef0b - zh: 9ffd07768d37824e + en: 8264b135871e8978 + zh: 0939aafb1b2961fc /deepseek-harness-desktop/known-limitations: - en: 5b77213c86bbcfb6 - zh: b34bf21773bb852b + en: c63d4dc7a9104954 + zh: a4c676e5b46a6ac0 /deepseek-harness-desktop/dev-note: en: 8e26b460ba31f21b zh: fbcd0307b3867125 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 57eb2cb333..e0bb92c5b7 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -1,16 +1,46 @@ +--- +description: "Desktop runs the Harness workspace in a native application. This reference covers application behavior, development and integration; the packaging, Windows signing and publication guides own build and release operations." +--- + # DeepSeek Harness Desktop English | [中文](README.zh.md) +## Summary + +Desktop runs the Harness workspace in a native application. This reference covers application behavior, development and integration; the packaging, Windows signing and publication guides own build and release operations. + +## Table of Contents + +- [Application overview](#application-overview) +- [Terminal command](#terminal-command) +- [Closing the window and quitting](#closing-the-window-and-quitting) +- [Key technical decisions](#key-technical-decisions) +- [Bundled command runtime](#bundled-command-runtime) +- [Installation ownership](#installation-ownership) +- [Develop](#develop) +- [Package](#package) +- [Windows installer interface](#windows-installer-interface) +- [Updates](#updates) +- [Low-level development overrides](#low-level-development-overrides) +- [Known limitations](#known-limitations) +- [Dev Note](#dev-note) + + + +## Application overview + Desktop analytics follows the [product collection policy](../../packages/client/product-analytics/README.md), including its live application setting. Web usage is excluded. Update installation waits for its local analytics intake before locking API admission and stopping the Host. Intake has a one-second deadline; failure does not prevent installation, and collector delivery is not awaited. The desktop application is an Electron shell around the complete dsh Web application. An Electron RunAsNode child starts the shared profile runner, and Electron immediately loads the packaged Web entry at `dsh-app://app/`. Its shared loading page waits for Host boot injections, then starts the client without navigating to another document. Electron forwards application HTTP requests to the authenticated Web Host, dropping connection-level response headers (`transfer-encoding`, `connection`, `keep-alive`) that describe the Node fetch rather than the resource, and marking plugin bundle responses `no-store` because their per-launch revisions would only accumulate in Chromium's disk cache; WebSocket streams connect to that Host with credentials attached only for the owned application window. Node IPC carries boot injections, readiness, and shutdown. Desktop listens on an OS-assigned port by default, so it cannot collide with Web’s `3080` or a reserved port; a `webserver.config.port` patch can override it. +Desktop binds `127.0.0.1`, the address Electron dials for the ready URL and the WebSocket credential filter. WebSocket streams use `ws:` or `wss:` according to the Host listener; credentials require matching authority and scheme. + The first application-menu command, **About DeepSeek Harness**, opens Electron's native About panel with the application icon, product name, and installed release version. The menu follows the Desktop shell locale. On macOS, Hide, Hide Others, Show All, and Quit use localized labels; Hide and Quit include the DeepSeek Harness product name. These commands retain their native actions and shortcuts. macOS reads the icon from its application bundle, so an unpackaged development launch displays Electron's icon; Windows receives the packaged PNG. Desktop’s local native directory flow opens an Electron folder dialog attached to the application window, restoring, showing, and focusing that window first. Concurrent requests share one dialog; cancellation returns no path and failures remain retryable. Ordinary Web uses the Host chooser. Browse mode lists Host directories. On Linux without zenity or kdialog, automatic selection uses browse instead of the Electron dialog. -Creator and the Web Plugin Manager use Desktop’s bundled pnpm under Electron Node mode without requiring pnpm on PATH. The private Node launcher environment applies only to package operations. +Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/dependencies/pnpm`. Build-time production installation, the installed `dsh` CLI, Creator and the Web Plugin Manager execute its `bin/pnpm.mjs` with Electron Node mode; package operations do not require pnpm on PATH. The private Node launcher environment applies only to package operations. Agent workspace dependencies copy the same self-contained primary-runtime payload into the Harness home and execute pnpm with its standalone Node. Embedded Platform documents use a persistent WebContentsView partition keyed by a hash of the Platform origin and stable account ID. localStorage preferences, including dismissed notices, survive view closure and application restart; different accounts and origins use separate storage. The Host supplies the account ID from its latest successful profile read; while no ID is known, the document opens in a disposable partition that keeps no preference across opens. Opening a persistent partition clears cookies, filesystem, IndexedDB, Cache Storage, the HTTP and shader caches, service workers, and HTTP authentication before the document loads; a disposable partition clears all of its storage. Closing a view destroys the document, removes its request interceptors, and schedules the same cleanup, so authentication left by an unclean exit is cleared before the next document loads. The next open and application shutdown await that cleanup, and an update install waits for it before the installer takes over the exit. A failed cleanup rejects that open and blocks the same account until a later cleanup succeeds; other accounts keep opening. Sign-out destroys the document but retains account-scoped preferences for the next sign-in. A document already open in a disposable partition stays mounted when the account ID arrives for the same credential; the next open uses the account-scoped partition. The [storage decision](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.md) describes the retention policy. Host sends account credentials through private Node IPC; account RPC and the Harness renderer receive no token. Before page scripts execute, the Platform preload performs one synchronous IPC to read the prepared main-process credential. It exposes displayMode, synchronous getAuthToken() and getLocale() getters, and onLocaleChange(listener), which returns an unsubscribe function. Both getters read preload memory without further IPC. The bootstrap includes the resolved Desktop language (`zh_CN` or `en_US`); Settings language changes update the preload cache and notify the open Platform document without reloading. Platform applies this language before its first render and does not persist it as a browser preference. The main-process handler performs only sender validation and an in-memory read; it never waits for Host, disk, or network. Trusted-page initialization failures retain embedded mode and make the getter throw, preventing browser-credential fallback. Only the owned Platform main frame on the configured issuer origin can initialize. Sign-out, credential replacement, Host shutdown, and view closure destroy the document. Cross-origin document navigation is blocked. HTTPS links requesting a new window open in the system browser without the embedded session or token; other schemes and URL credentials are rejected. Native views occupy the viewport below the Account feature’s return bar. @@ -22,6 +52,8 @@ Desktop microphone access is restricted to audio requests from the primary `dsh- Press F12 (Fn+F12 on media-key keyboards), Command+Option+I on macOS, or Ctrl+Shift+I on Windows to toggle DevTools for the focused application page, including in packaged builds. These native shortcuts use hidden application-menu items. Update overlays and packaged embedded browser guests disable DevTools. + + ## Terminal command The application menu's **Manage dsh Command…** entry, immediately below **Check for Updates…**, shows the current command and offers Install, Repair, and Remove. The command uses Desktop's installed runtime and the ordinary [dsh CLI](../cli/README.md), including when the Desktop application is closed. Open a new terminal after installation and run `dsh --version`. @@ -30,6 +62,8 @@ On macOS, installation creates `/usr/local/bin/dsh` and requests administrator a Command registration is optional after installing Desktop. Use **Manage dsh Command… → Remove** before uninstalling Desktop to remove its CLI registration; the application uninstaller does not remove it. Finish CLI commands before updating or uninstalling Desktop. The CLI runtime version follows the installed Desktop release. See [bundled command runtime](#bundled-command-runtime) for Desktop plugin commands and runtime limitations. + + ## Closing the window and quitting Closing the main window (macOS close button and ⌘W; Windows ×, Alt+F4, and the taskbar Close window command) hides it; Windows asks for acknowledgement before the first hide. The page and the Host keep running, tasks continue, and the next show presents the same document with its session, drafts, and scroll position; a fullscreen macOS window leaves fullscreen before hiding. The window returns through the Dock icon, a second launch, or `dsh://open` on macOS, and through the tray on Windows. Minimize is unchanged. Closing the welcome window before the workspace opens quits on Windows and, on macOS, keeps the application in the Dock without a window. @@ -44,6 +78,8 @@ The confirmation is skipped when the installer restart already confirmed task in The tray renderer enlarges the whale by 20% around the tile center while preserving the background and aspect ratio; application and installer icons retain their original proportions. + + ## Key technical decisions The original artwork lives in `resources/icon.png` and `resources/icon.svg`; platform adaptations retain the whale and gradients in `resources/icon-windows.*` and `resources/icon-macos.*`. Export each platform SVG as a transparent 1024×1024 PNG. Electron-builder generates the multi-size ICO for the Windows application, installer, and uninstaller ([Windows icon requirements](https://learn.microsoft.com/en-us/windows/apps/design/iconography/app-icon-construction)). The installation pages use matching artwork in both themes; the uninstaller's welcome and finish pages share `installer/assets/uninstaller-sidebar.png`, converted to a 164×314 BMP during preparation. @@ -54,21 +90,25 @@ The macOS File menu displays the accepted single-key binding, including arrow ke The macOS PNG uses an inset rounded background for legacy ICNS packaging, with representations up to 1024 pixels. It is a flattened icon, not an Icon Composer document. Apple's [app icon guidance](https://developer.apple.com/design/human-interface-guidelines/app-icons) describes unmasked layers for Icon Composer; those inputs require a separate macOS export and must not reuse the rounded ICNS artwork. Verify Finder and Dock appearance on supported macOS versions before release. + + ### Bundled workspace dependencies electron-builder copies only the manifest's `dependencies` into `app.asar/node_modules`, so the Electron main bundle `lib/main.js` inlines its workspace devDependencies and leaves `electron`, Node builtins, and those `dependencies` as its only bare imports; a sandboxed preload may leave only `electron`, `events`, `timers`, and `url`, the modules its `require` polyfill resolves. The main bundle resolves the inlined packages from their `lib/` output, so the root `build:lib:host` bundles `apps/desktop` after the concurrent workspace tsdown pass, and [`desktop-bundle-imports`](scripts/desktop-bundle-imports.mjs) fails any Desktop bundle whose static, dynamic, or `require()` import the packaged application cannot resolve. Without that check an import rolldown could not resolve ships as an external specifier and fails at launch with `ERR_MODULE_NOT_FOUND`. The [archived bundle-order decision](../../.agents/notes/archived/process/2026-09-22-desktop-main-bundle-after-workspace-tsdown.md) records the alternatives. -Signed Windows packaging scans the primary runtime and application production dependencies for PE content, including files without a conventional extension. The final scan covers the entire unpacked application. Directory links, malformed `MZ` files and non-PE `.exe`, `.dll` or `.pyd` files stop packaging; data files beginning with `MZ` are also rejected unless they contain a valid PE header. It preserves valid vendor signatures and signs unsigned code before sealing runtime hashes or executing smoke checks. Public-key inspection uses batches of 32 files with at most four processes; hardware-token signing remains serial, and each new signature must match the configured certificate and carry a timestamp. Hardware signing and verification failures stop the run; isolated timestamp requests follow the bounded policy below. Electron-builder preserves copied runtime executables only after signature and exact-byte verification. A final PE-signature audit and a fresh-cache ASAR payload and Host smoke must pass before the release completion record is written. Development, preparation-only and unsigned builds do not use the hardware token and can be blocked by Windows code-integrity policy; no build mode disables that policy. Passing smoke checks does not establish compatibility with every enterprise policy. +Signed Windows packaging scans the primary runtime and application production dependencies for PE content, including files without a conventional extension. The final scan covers the entire unpacked application. Directory links, malformed `MZ` files and non-PE `.exe`, `.dll` or `.pyd` files stop packaging; data files beginning with `MZ` are also rejected unless they contain a valid PE header. It preserves valid vendor signatures and signs unsigned code before sealing runtime hashes or executing smoke checks. Public-key inspection uses batches of 32 files with at most four processes; hardware-token signing remains serial, and each new signature must match the configured certificate and carry a timestamp. Hardware signing and verification failures stop the run; isolated timestamp requests follow the [bounded retry policy](windows-signing/README.md#windows-ev-signing). Electron-builder preserves copied runtime executables only after signature and exact-byte verification. A final PE-signature audit and a fresh-cache ASAR payload and Host smoke must pass before the release completion record is written. Development, preparation-only and unsigned builds do not use the hardware token and can be blocked by Windows code-integrity policy; no build mode disables that policy. Passing smoke checks does not establish compatibility with every enterprise policy. Desktop carries independent Python, Node.js and pnpm distributions. Python includes numpy, pandas, python-docx, python-pptx, openpyxl, Pillow, lxml and XlsxWriter with their complete dependencies. The `load_workspace_dependencies` tool installs this payload offline on first use under `$DSH_HOME/dsh-runtimes/dsh-primary-runtime` (normally `~/.dsh/dsh-runtimes/dsh-primary-runtime`) and returns absolute interpreter, pnpm script and library paths plus `pythonDistributions`, the bundled distribution names and versions. The version report excludes user-installed additions. Office tasks prefer these libraries unless user or workspace instructions select another environment. Execute the pnpm script with the returned Node executable. The returned Node library directory is reserved for bundled libraries, not pnpm's global installation directory. -Desktop registers `office-docx`, `office-pptx`, and `office-xlsx` by default. The skills use the bundled Python libraries for creation and focused edits, then reopen the files and run a shared structural checker before delivery. PowerPoint creation and editing use python-pptx. Skill resources are copied to `runtime/office-skills` outside ASAR so Python can read the checker. An available `render_document` tool can add visual inspection; its absence does not prevent authoring or delivery. See the [Office skill package](../../packages/skill/skill-office/README.md) for checks and limitations. +Desktop exposes the compact `office` router and named authoring/operation subskills. Authoring uses bundled Python libraries; operation skills invoke the configured Node and CLI paths. Skills live in `runtime/office-skills` outside ASAR. See the [Office skill package](../../packages/skill/skill-office/README.md) for progressive loading and limitations. The payload follows the Desktop release. `runtime.json` records the Desktop version, target, top-level interpreter/package-manager versions and the Python distribution map, and a digest of the selected target’s locked payload inputs and assembly format. Distribution names use PEP 503 normalization; duplicate normalized names reject the manifest. Legacy `components` manifests remain readable through normalization, with their existing library-version consistency checks. Matching installations are reused; a dependency or archive change replaces the directory after a complete staged copy even when the Desktop version stays unchanged. Older manifests without a digest are replaced on their next installation. User-added Python packages remain only while the payload identity matches. A failed directory replacement retains the previous installation; Windows may refuse replacement while an interpreter is still running. 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. | Decision | Why | Direct consequence | |---|---|---| @@ -94,6 +134,8 @@ To manage Desktop's plugins, launch Desktop once to initialize its profile, full Finish CLI commands before updating or uninstalling Desktop; the installer does not coordinate with running commands. The CLI does not supply Office authoring-skill resource paths. Desktop's existing Office setup and Web attachment conversion retain their own resource configuration. `prepare:runtime` copies the launch scripts without compiling a native CLI launcher. + + ## Installation ownership Electron owns `$DSH_HOME/profiles/desktop`. Its `dependencies` contains packages installed by pnpm; `dsh.profile.bundles` contains the built-in bundles followed by enabled plugins. The signed application supplies dsh, the private Desktop Host, and their production packages from `resources/app.asar/dsh`. Packaged applications select runtime profile resolution without creating package links; development profiles use filesystem links. Both host and plugins execute in the same Electron Node-mode process; Desktop does not enable `--preserve-symlinks`. The CLI cannot boot this profile. The Desktop-installed command can manage its plugins while the application is quit; npm-installed dsh cannot mutate it. @@ -140,6 +182,8 @@ Recovery waits for Host shutdown before changing plugin activation. The native r macOS and Linux GUI launches inherit only the session manager's environment, without variables exported by shell startup files. Before the first Host starts, Desktop runs the account's login shell (from the user database, not `$SHELL`) once as ` -ilc` and reads its `env -0` output between delimiters, so `~/.zprofile` and `~/.zshrc` (or the shell's equivalents) take effect for the Host, agent shells, terminals, and profile configuration. Reading runs in parallel with profile preparation. The probe has no terminal input and sets `DISABLE_AUTO_UPDATE=true`, `ZSH_TMUX_AUTOSTARTED=true`, and `ZSH_TMUX_AUTOSTART=false` to keep oh-my-zsh and tmux plugins from blocking. Shell values replace inherited values except `PWD`, `OLDPWD`, `SHLVL`, `_`, those probe variables, and launcher-owned `DSH_*` and `ELECTRON_*` names; Desktop resolves paths such as `DSH_HOME` before the read, so the Host keeps the same values. The read completes at the closing delimiter, so background processes started by startup files may keep running with their output discarded. A candidate that fails to start, exits nonzero, prints no delimited output, or exceeds `DSH_DESKTOP_LOGIN_SHELL_TIMEOUT_MS` (integer milliseconds from 1000 through 2147483647, default `10000`; its process group is killed) is logged as a warning, and Desktop tries `/bin/zsh`, `/bin/bash`, and `/bin/sh` in turn; when all fail the Host uses the inherited environment. The dump command uses POSIX syntax, so an account shell such as csh, tcsh, or nushell fails and the Host receives the environment from the first system shell's startup files instead. Quitting Desktop during the read kills the running probe's process group. The result is read once per application process, so changes to shell startup files apply after quitting and reopening Desktop. Windows GUI launches already inherit the user and system environment variables from the registry, so Windows skips this step. + + ## Develop The development application menu offers Reload Page (Cmd+R on macOS, Ctrl+R elsewhere) and Restart App and Host. Restart waits for Host shutdown before relaunching Electron and starting a new Host; neither action rebuilds source files. @@ -180,254 +224,44 @@ The browser-login waiting page offers a copy-link action for the current pending The welcome window follows system appearance with the design’s Platform light/dark colors and shows the 600 × 700 entry layout and the API-key form, with native window controls, a draggable title area, a local brand SVG, system sans-serif fallbacks, and locally bundled Montserrat Light for non-button text. The window uses macOS menu vibrancy or Windows acrylic with the onboarding window tint: 40% white in light mode and 50% rgb(24 25 28) in dark mode. The local React welcome entry bundles React and the shared `StateDot` loading indicator with its CSS; it uses the isolated preload without loading the main Web application. The entry, sign-in status and API-key pages share a fixed bottom action row; the back-to-sign-in link sits below it. Buttons share the platform motion timings, and Reduce Motion disables their transitions. The OS owns blur strength and outer corners. macOS Reduce Transparency suppresses translucency, and Increase Contrast forces that setting on. Save and continue writes to the development credential store; Set up later opens the real workspace without saving a key or completion flag. The generated project links the declared workspace dependency closure as well as pnpm’s hoisted packages, so unhoisted configured plugins remain resolvable. [The window note](../../.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.md) owns the material and onboarding decisions. + + ## Package - -### Release versions - -Before each Desktop packaging run, first confirm the complete version string with the current user. Check the selected deployment, dsh base version, retained release records, and published objects, then propose the exact version for approval. Do not start packaging until the user confirms that version; the deployment setting alone does not authorize a version choice. - -Record the current dsh version as the base. A production Desktop release uses that exact version, including any `alpha`, `beta`, or `rc` identifiers. A test release preserves the complete prerelease base and appends `.YYYYMMDD.index`; a stable base uses `-test.YYYYMMDD.index` instead. - -| dsh base | Production Desktop | Test Desktop example | -|---|---|---| -| `0.1.6-alpha.1` | `0.1.6-alpha.1` | `0.1.6-alpha.1.20260916.1` | -| `0.1.6-beta.2` | `0.1.6-beta.2` | `0.1.6-beta.2.20260916.1` | -| `0.1.6-rc.3` | `0.1.6-rc.3` | `0.1.6-rc.3.20260916.1` | -| `0.1.6` | `0.1.6` | `0.1.6-test.20260916.1` | - -Use the actual creation date in Asia/Shanghai. For each base and date, start the index at 1 and increment after checking retained release records and published objects; never reuse a published version. Test distribution does not publish the corresponding unsuffixed base. - -Pass the confirmed version to the packaging command as `--build-version`, which reaches the artifact names, the update feed, and the upload validation as one value. The manifests keep the product version, so a test build no longer rewrites the release family and leaves nothing to revert: - -```sh -pnpm --dir apps/desktop run package:win:x64 --build-version 0.1.6-alpha.1.20260916.1 -``` - -`--build-version auto` proposes the next index for today, reading the published objects in the destination bucket and falling back to this target's local output directory when no bucket is configured or the listing cannot finish within its deadline. Confirm the proposal it prints before an upload; a run script forwards `--` on its own, and the packaging entry accepts it either way. - -A production release publishes the product version and takes no `--build-version`. Uploading one tags the packaged commit as `desktop-v` once the artifacts are public; a build from a modified checkout is not tagged, and a tagging failure prints the command to run by hand rather than failing a completed upload. Test and local builds are deliberately left untagged, and every artifact records `dshBuildCommit` and `dshBuildDirty` in its manifest so a build handed over directly remains traceable. - -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. - -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: - -```sh -pnpm --dir apps/desktop run check:package -``` - -`prepare:desktop` is not a prerequisite: - -```sh -pnpm run package:desktop -``` - -Release automation uses fixed target commands so runtime preparation, dsh preparation, and electron-builder receive the same platform and architecture: - -```sh -pnpm run package:desktop:mac:arm64 -pnpm run package:desktop:mac:x64 -pnpm run package:desktop:win:x64 -``` - -The macOS arm64 command requires Apple Silicon. The macOS x64 command runs on Intel macOS or Apple Silicon with Rosetta. The Windows x64 command requires Windows x64. Linux is not a supported Desktop release target. - -Each target owns its packed package inputs, prepared runtime, package set, dsh tree, pnpm preparation state, unpacked application, update metadata, and final artifacts under `apps/desktop/.desktop-build/targets//`. The Electron archive cache remains shared under `.desktop-build/downloads` because every archive name includes its version, platform, and architecture and is verified before extraction. A target build never consumes another target's mutable preparation state. - -### Local macOS DMG without release signing - -After `pnpm install`, run one command from the repository root. No `.env.macos`, Apple account, certificate, or update service configuration is required: - -```sh -pnpm run package:desktop:mac:arm64:unsigned -pnpm run package:desktop:mac:x64:unsigned -``` - -Add `--check` to validate local configuration and tools without building, or `--dir` to stop at the unpacked application. The DMG is `apps/desktop/.desktop-build/targets//unsigned-artifacts/deepseek-harness--mac--unsigned.dmg`. After all checks pass, the command prints `DMG:` followed by its absolute path. Open it and copy the application to a local test directory. - -These commands ignore `.env.macos` and inherited release settings, use `com.deepseek.harness` as the app ID, and omit automatic-update and mandatory-update configuration. Build tools, standard network proxies, and `DSH_DESKTOP_NPM_REGISTRY` remain available from the shell. They skip Developer ID signing, Apple notarization, temporary signing keychains, and notarization proxy changes. Electron receives a local ad-hoc signature without certificates so the modified executable can run; the DMG is unsigned. Both preparation and the assembled application still run runtime integrity and smoke checks. Local builds omit update feeds, ZIPs, and release completion records, and the upload commands cannot publish them. macOS may require approval in System Settings → Privacy & Security to open an unnotarized application. - -### Local Official bundles from a loopback registry - -The test DMG excludes the provider runtimes the Official on-demand catalog advertises, and a release publishes matching bundle versions to npm. To install locally built bundles before that release, start a loopback registry that packs and serves the catalog's complete local dependency closure: - -```sh -pnpm run dev:bundle-registry -``` - -The command validates the catalog and the workspace inventory, runs `pnpm run build:official`, packs the closure into a new `dist/test-bundles//` directory, writes `bundle-registry.json` last as the completion marker, and only then prints the artifact path, the registry URL, and the exact `name@version` specs. It serves `127.0.0.1` on an allocated port under a fresh namespace until Ctrl+C or SIGTERM, and stopping it leaves both the artifacts and the installed packages on disk. It needs no `.env.macos`, Apple credentials, or npm credentials, and it does not change `pnpm run package:desktop:unsigned`. - -In the packaged application, open Plugins → Add plugin, paste one printed spec, choose **Custom address**, paste the printed registry URL, and install. A custom registry is asked alone, so this process must answer every dependency: repository-owned packages come from the run's own archives, and third-party packages keep npm's real metadata and bytes through a fixed redirect to `registry.npmjs.org`, which still requires network access. The installed entry stays Official because its package name is in the catalog. The registry choice is remembered in this browser; choose an offered registry again to switch back. - -A run's artifacts are immutable, so a rebuild serves a new namespace and a new URL, and the Official **Update** control does not appear while the installed and running versions match. The profile records the previous run's tarball URL in `pnpm-lock.yaml`, and pnpm verifies recorded entries, so installing or reinstalling that bundle against a new URL is refused with `ERR_PNPM_TARBALL_URL_MISMATCH` and can leave the earlier files in place. To test changed code at the same version, clear the stale resolution first — `pnpm clean --lockfile` in `$DSH_HOME/profiles/`, or install into a fresh profile — then install again from the new URL. `bundle-registry.json` records each archive's version, filename, size, and SHA-512 integrity together with the packing checkout's commit and dirty flag. - -The served `time` is the real packing time, so pnpm 11's default 24-hour `minimumReleaseAge` records the exemption it granted in the profile's `pnpm-workspace.yaml` (`minimumReleaseAgeExclude`); an explicitly stricter policy there fails the installation with pnpm's own message instead of being overridden. A `@scope:registry` route in `~/.npmrc` or the profile's `.npmrc` overrides `--registry` for that scope, so it must not route the served scope. - -### 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. It preserves runtime JavaScript, 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 [Office conversion provider](../../packages/document/office-to-pdf/README.md) carries the target’s declared native engine, or WASM when the kit declares no matching native target. Preparation rejects a missing target engine before packaging. The complete Office dependencies, including CLI, JavaScript libraries, and the selected engine’s executables, data, licenses, and notices, are unpacked under `resources/app.asar.unpacked/dsh/node_modules/`. The Desktop Host resolves engine manifests to these physical directories and supplies loaded skills with absolute standalone Node and unpacked CLI paths. Node lives in `resources/runtime/primary-runtime/dependencies/node/bin/`; the CLI is the unpacked `@deepseek-ai/libreoffice-kit/lib/cli.js`. On macOS, the native helper receives the JIT entitlement required by [LibreOffice’s UNO bridge](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in). - -The packaged application runs compiled JavaScript and pre-generated Typert metadata; it does not compile TypeScript plugins. Source-level debugger navigation and editor declarations remain available in development packages. [Copy-policy tests](tests/runtime-file-policy.spec.ts) cover exclusions and retained assets; The [payload smoke](tests/fixtures/runtime-payload-smoke.mjs) runs under Electron RunAsNode before the Host smoke and final inventory verification. The payload smoke resolves the search tool’s ripgrep executable and verifies text search and file enumeration. Signed Windows builds run these checks after dependency signing; other builds run them during `prepare:dsh`. The [Host smoke](scripts/smoke-runtime.ts) creates DOCX, XLSX, and PPTX inputs with bundled Python, converts each through the real Office provider, and checks PDF output. Every assembled application, including directory and unsigned builds, repeats the payload and Host checks against ASAR. Archive integrity checks compare the complete archived descriptor with preparation, file bytes and membership in both archive and unpacked trees, recorded executable flags for archived files, and physical permissions for unpacked files. The Host smoke also obtains CLI paths from the loaded skill and runs capabilities and DOCX conversion with an empty PATH. Conversion failures stop packaging before a release record is written; macOS DMG/ZIP builds run these checks before notarization. - -Windows release qualification also runs [directory and replacement checks](scripts/smoke-windows.ps1) manually after the Desktop build. Set `$Makensis`, `$SevenZip`, and `$PluginDir` to the pinned builder’s NSIS compiler, 7-Zip executable, and x86-unicode NSIS plugin directory; pass the prepared `window-frame.dll` as `-FrameLibrary` to exercise the native extraction path and its failure report as well. From the repository root, run the command below. It verifies directory replacement and rollback, and both locked-file replacement modes; it is not part of the unit-test lane. - -```powershell -pwsh -NoProfile -File apps/desktop/scripts/smoke-windows.ps1 -Makensis $Makensis -SevenZip $SevenZip -PluginDir $PluginDir -FrameLibrary apps/desktop/.desktop-build/targets/win-x64/installer-ui/window-frame.dll -``` - -The Windows installer checks for a running application at startup and after destination selection, before extracting the new version beside the installation directory. It checks again before replacing directories through same-volume renames. A running application blocks installation; update launches allow up to ten seconds for it to exit. Same-path upgrades preserve the old directory until promotion succeeds; extraction failure leaves it intact, and promotion failure attempts to restore it. The installer removes the old backup before launch. Forced termination or power loss can leave `.new-*` or `.old-*` directories; installation-location and scope migrations retain electron-builder's old-uninstaller flow. - -When extraction fails, the installer writes a report with the 7-Zip result and its complete error output to the updater cache directory as `%LOCALAPPDATA%\-updater\installer-logs\extract-failure-.log` (currently `@deepseek-aidsh-desktop-updater`) and shows the first error line with a **Copy error details** button; silent installs write only the report. Unsigned Windows builds (`DSH_DESKTOP_UNSIGNED=1`) name their installer `deepseek-harness--win-x64-unsigned.exe` so they cannot be mistaken for release artifacts. - + + + + + + -### Upload updates +Use the dedicated guides for build and release operations. Shared Windows runners have accepted credential and device isolation limits; read them before signing or executing branch code. -Fixed installer downloads use `pnpm run upload:latest:mac:arm64`, `pnpm run upload:latest:mac:x64`, or `pnpm run upload:latest:win:x64` from the repository root. They upload the completed target's DMG or EXE to `desktop/dsh-latest-macos-arm64.dmg`, `desktop/dsh-latest-macos-x64.dmg`, or `desktop/dsh-latest-windows-x64.exe`. Production URLs start with `https://download.deepseek.com/`; test URLs use `DOWNLOAD_TEST_ORIGIN`. Both deployments reuse the target dotenv's deployment, bucket, and credentials, all normal release validation, and the upload audit below. Each command replaces one fixed object without publishing feeds, blockmaps, or release tags. Test fixed downloads are shared across release IDs in the test bucket; the packaged update URL still requires its original release ID. Publication is explicit, including prerelease versions. Deployment infrastructure must configure revalidation or purge cached fixed downloads after replacement. Local loopback tests cover the upload; release operators own real COS and CDN acceptance. +- [Desktop packaging](packaging/README.md): local and Actions builds, versions, deployment settings, artifacts, logs and verification. +- [Windows signing and runner operations](windows-signing/README.md): machine setup, accepted isolation risks, signing credentials, token failures and cache maintenance. +- [Desktop publication](publishing/README.md): upload credentials, release identity, fixed downloads, update feeds and upload recovery. -Test and production uploads through `upload:*` retain a fresh `.desktop-build/upload-records/--*` directory after release preflight. `plan.json` records destination, version, every file's size/SHA-512, and published YAML bytes; flushed `events.jsonl` records PUT intent and available response status/request ID; `result.json` records completion or the last failed stage. A missing final result means interruption or unavailable storage, not success. No credential values, authorization headers, or raw SDK errors are recorded. Audit-write failures stop later PUTs. Every object is one streamed Tencent COS PUT with an explicit length and Content-MD5; the COS SDK repeats a request only when its body is not a stream, and this uploader does not retry either. Retain partial records and inspect remote state before another operation: a timeout or failed receipt write does not prove that the object was not stored. These records are local, not tamper-proof or automatically backed up; archive each release's records with its build evidence in controlled storage. Public CDN readback remains separate release qualification, explicitly marked `not-performed` in the upload result. + -Windows operators can keep a CLIXML object with DPAPI-encrypted `SecretId` and `SecretKey` SecureString fields outside the repository. The [credential launcher](scripts/upload-with-credentials.ps1) requires an explicit `-CredentialFile` and `-Environment production` or `test`; without `-Upload`, it only verifies decryption and injection into a local Node child, with no network request. It requires Node on `PATH` and the Windows user and machine that encrypted the file. Plaintext, empty, and whitespace-only fields fail. The parent environment is unchanged; the child receives only the selected COS pair after unrelated secrets and Node preload options are removed. Raw child stderr is suppressed and credential values in stdout are redacted. This check does not prove COS authorization. An explicit upload additionally requires `-Upload -Target -Bucket ` and the normal completed-release prerequisites below; actual cloud upload remains release-operator qualification. Add `-Latest` to that upload invocation to replace the fixed installer without publishing update feeds or a release tag. This launcher supports permanent keys, not STS credentials. An explicit upload requires the selected deployment and bucket to match the target dotenv and completed package record before network writes; it uses the DPAPI credential pair even if the dotenv contains other COS keys. + -`DSH_DESKTOP_AUTO_UPDATE_ENV` selects `test` or `production` for both the URL embedded during packaging and the later COS upload; an absent value selects `test`. Test packaging requires its HTTPS origin in `DOWNLOAD_TEST_ORIGIN`; production uses `https://download.deepseek.com`. Upload requires the selected bucket in `DOWNLOAD_TEST_COS_BUCKET` or `DOWNLOAD_PROD_COS_BUCKET`. Production feeds use `dsh-desk/feeds//` and binaries use `dsh-desk/bin//`. Test releases require `DOWNLOAD_TEST_RELEASE_ID`: 32 lowercase hexadecimal characters inserted as `dsh-desk//feeds//` and `dsh-desk//bin//`. YAML references, stable-channel aliases, and blockmaps stay inside that release directory. Targets are `mac-arm64`, `mac-x64`, and `win-x64`. - -The update destination and upload credentials follow the selected deployment: - -| Environment | Public origin | COS bucket | COS credentials | -|---|---|---|---| -| `test` or unset | `DOWNLOAD_TEST_ORIGIN` | `DOWNLOAD_TEST_COS_BUCKET` | `DOWNLOAD_TEST_COS_SECRET_ID`, `DOWNLOAD_TEST_COS_SECRET_KEY` | -| `production` | `https://download.deepseek.com` | `DOWNLOAD_PROD_COS_BUCKET` | `DOWNLOAD_PROD_COS_SECRET_ID`, `DOWNLOAD_PROD_COS_SECRET_KEY` | - -Generate a fresh ID for each test release batch with the command below and copy its output into `DOWNLOAD_TEST_RELEASE_ID` in `.env.macos` or `.env.windows`. These Git-ignored platform files own the value; shell variables do not override it, and dotenv values are not shell-expanded. Keep the ID through packaging, upload, and retries; upload rejects a completion record with a different update URL. To test an upgrade between versions, reuse the installed client’s ID for the later version. Production does not use this field. - -```sh -node --input-type=module -e "import { randomBytes } from 'node:crypto'; console.log(randomBytes(16).toString('hex'))" -``` - -Distribute each test batch through its complete download links. Installed test clients retain their batch feed and do not discover a new ID automatically. Format validation cannot establish randomness; use the generator output. Random paths reduce guessing, not access by link holders; withdrawing a batch requires deleting its COS objects and purging its CDN directory. - -Configure the update origin and selected COS bucket, SecretId, and SecretKey in the target dotenv file, then package and upload the same target: - -```sh -pnpm run package:desktop:mac:arm64 -pnpm run upload:mac:arm64 -``` - -The target dotenv file for internal-test packaging explicitly sets `DSH_DESKTOP_AUTO_UPDATE_ENV=test` and `DOWNLOAD_TEST_ORIGIN=https://download-test.deepseek.com`; uploads use `DOWNLOAD_TEST_COS_BUCKET=bj-toc-download-test-1320056602` and separate test credentials. Both test and production use the fixed Nightly channel; deployment selection does not enable channel switching. - -Early internal-test packages use the `test` deployment. Select `production` explicitly only for a production release; changing upload credentials does not retarget an existing package. Packaging requires no COS credentials, disables electron-builder publishing, strips COS credentials from child processes, and records completion only after signing and notarization succeed. Upload validates this record, deployment, target, shared version, filenames, sizes, and SHA-512 before reading credentials. Packages and blockmaps upload before YAML; historical objects are retained. Every release publishes `nightly.yml` or `nightly-mac.yml`; stable releases also publish `latest.yml` or `latest-mac.yml` pointing at the same artifacts. Published YAML uses absolute binary URLs. The uploader leaves Cache-Control unset, including the empty header the COS SDK would otherwise add: deployment infrastructure owns cache policy, with uncached feeds and separately configurable binary caching. Serialize publication per target and verify public artifacts and feed contents before release qualification. - -The signed macOS configuration uses the required release environment instead of accepting whichever certificate appears first in a keychain. It rejects empty values, a malformed Team ID, a signing identity that includes electron-builder's unsupported `Developer ID Application:` prefix, and incomplete notarization credentials. Signed macOS packaging requires the configured identity and its private key. Runtime preparation applies that identity, a secure timestamp, and hardened runtime to every embedded Mach-O file; after signing the application, a deep strict check rejects any other leaf authority or Team ID before artifact creation. The signed fixed-target macOS installer commands create separate copies of the signed application and run two artifact lanes concurrently. One lane notarizes and staples the App before generating the ZIP and its update metadata. The other encloses its signed App copy in a signed DMG, then notarizes, staples, and verifies the DMG; its inner App has no individually stapled ticket. Both lanes must finish successfully before their artifacts reach the final directory and the release completion record is written. Signed directory-only commands also require notarization credentials and wait for Apple notarization and App stapling. The [parallel notarization decision](../../.agents/notes/implemented/process/2026-09-09-parallel-macos-notarization.md) owns copy isolation and container ticket semantics. `CSC_LINK` must name a local p12 containing the Developer ID Application certificate and private key; URLs and Base64 inputs are not supported. `CSC_KEY_PASSWORD` is its export password, not an Apple account or login password; an explicitly empty value supports an unencrypted p12. Before building, packaging creates and unlocks a private temporary keychain, imports the p12, authorizes signing, and signs a small probe. Runtime and App signing use this keychain explicitly; existing login keychains require no setup or manual unlocking. Child processes receive its path without the p12 password. The keychain is deleted after success or ordinary failure; CI must clean temporary credentials after forced termination. CI writes the certificate and `.env.macos` from its secret store, restricts file access, and deletes both after the job. Ambient `CSC_NAME` and certificate discovery order do not select the release owner. Notary credentials may instead use electron-builder's complete Apple ID or keychain-profile strategy. The two macOS identity variables are also required when repeating the application check manually with `pnpm --dir apps/desktop run verify:mac-signature -- `. - -macOS signing visits real files without following Framework symlink aliases. PAK resources retain all shipped languages and are sealed by the enclosing Framework or application signature instead of receiving individual signatures. The [release policy](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md) owns the dependency patch and verification requirements. - -macOS runtime preparation caches verified single-architecture Mach-O signatures in `.desktop-build/targets//signature-cache`. Keys include input bytes and permissions, the signing probe’s actual leaf certificate, identifier, entitlement bytes, macOS version, and signing tools and policy. Git commits do not determine reuse: uncommitted byte changes invalidate the affected file. Every hit verifies cached bytes, the strict signature, certificate, identifier, entitlements, secure timestamp and hardened runtime before replacing an unchanged input. Universal binaries are signed each time. Runtime integrity and smoke checks, App signing, and Apple notarization still run. The cache requires trusted local build storage. Cache corruption or unsafe links fail the build; stop packaging before deleting the affected cache directory and retrying. Successful signing stages prune complete entries to a one-GiB payload budget; interrupted temporary entries require manual removal. Concurrent eviction can fail a reader safely. Logs report hit, miss and uncached counts. - -Mac package commands print `DESKTOP_PACKAGING_RECORD` with a unique directory under `apps/desktop/.desktop-build/packaging-runs/`. After reading local configuration, each run retains `run.json` (published version, product version, Git commit, dirty-worktree flag, target and Node version), `events.jsonl` (timestamped phases, durations, parallel output attribution and proxy restoration), redacted child `stdout.log` / `stderr.log`, and `result.json` (overall outcome, stage results and artifact directory). Events also record pack concurrency and whether each proxy is configured. Logs survive failures and later builds; no automatic deletion runs. Missing `result.json` means completion is unconfirmed. Known credential values are redacted; environments and notarytool authentication arguments are not recorded. Runtime preparation records package staging, installation, materialization, signing, manifests, smoke checks, descriptor verification and cleanup separately. Nested phase durations overlap and must not be added together. - -App and DMG notarization each record a submission ID and separate `notarytool:upload:*` and `notarytool:wait:*` durations. Upload uses `submit --no-wait` and includes authentication, local validation, transfer and server acceptance; it is not pure transfer time. Waiting starts after that command returns and includes polling and remaining Apple processing; Apple can start processing before upload submission returns. Apple status and diagnostic logs are retained, including rejection; signature checks, acceptance checks and stapling remain owned by `@electron/notarize`. Directory-only package commands use this same measured App notarization path. Individual subprocess output remains live in the terminal, while phase failures and nested errors are retained in the journal. Both platforms record parent-process packaging failures and print redacted diagnostics, including proxy recovery instructions, to the terminal. The configuration-only `check:package` command creates no run log. - -Mac packaging reads three tuning fields from `.env.macos`: - -| Setting | Default | Scope | -|---|---|---| -| `DSH_DESKTOP_MACOS_PACK_CONCURRENCY` | `4` | Workers for first-party and vendor workspace tarballs; requires a positive integer. | -| `DSH_DESKTOP_MACOS_DOWNLOAD_PROXY` | Empty | HTTP/HTTPS proxy origin for Electron, runtime assets, pnpm installation and builder downloads. | -| `DSH_DESKTOP_MACOS_NOTARIZATION_PROXY` | Empty | HTTP proxy origin for Apple tools through temporary system proxy settings. | - -The proxy fields are independent and reject URL credentials, paths, queries and fragments. Empty values preserve inherited networking. An explicit download proxy replaces child-process proxy variables and bypasses local hosts only; it does not change system settings. Windows and standalone `release:pack` retain their existing concurrency defaults. Company proxy addresses belong in the ignored local file; see internal documentation for addresses. - -Apple tooling uses the active macOS network service's HTTP/HTTPS proxies. Configured notarization routing checks proxy reachability, saves that service's settings, enables the proxy around both artifact lanes, and restores the saved settings after both lanes settle. An originally disabled proxy with an empty server and port zero is restored by disabling it; the temporary server and port may remain stored but inactive. Directory-only builds apply it to App notarization after the signed directory build. This temporarily affects other applications and requires permission to change system proxies; PAC, auto-discovery, SOCKS and authenticated proxy configurations must be disabled first. Packaging and recovery acquire the same per-user POSIX file lock before reading recovery data or changing proxies; process exit releases ownership, while the lock file remains in place. The lock loads `@deepseek-ai/node-addon-system/flock` at first use rather than at script start, so `check:package` and the packaging entry load on a checkout that has not built `native/system`; when the host addon binary or the entry's JavaScript is missing at lock time, the loader runs `pnpm run build:native-system` and `pnpm --dir native/system run build:ts` before locking, so recovery works on such a checkout as well. This prevents overlapping proxy transactions across checkouts; other users and network-setting tools must not change these settings concurrently. SIGINT/SIGTERM wait for active work before restoration. After forced termination or a restoration error, stop any remaining notarization processes and run `pnpm --dir apps/desktop run restore:mac-proxy`; the saved record remains until restoration succeeds. Configuration checks validate URL syntax without changing system settings or contacting the proxy. - -### Unsigned Windows test installer - -On Windows x64, use the complete unsigned packaging command for local installation testing: - -```sh -pnpm run package:desktop:win:x64:unsigned -``` - -The command requires `DSH_DESKTOP_APP_ID` and the normal build dependencies, including Python and Visual C++ build tools for native modules. Set `PYTHON` to the Python executable when it is absent from `PATH`. It writes the installer to `.desktop-build/targets/win-x64/unsigned-artifacts/`, omits automatic-update configuration, strips signing credentials, and creates no release completion record. It does not require EV credentials or an update origin. The signed packaging and upload commands retain their release requirements. - -### Windows installer interface +## Windows installer interface The Windows installer uses native NSIS pages with light and dark palettes, system shadows, an editable installation directory, and a finish page whose launch checkbox is selected by default. Installation is restricted to the current user. Clicking Install or pressing Enter validates the current path; drive roots remain invalid after normalization, including repeated trailing separators. New destinations must be empty, and nonempty destinations must be registered installations. Running executables at the affected installation path produce a native prompt and remain running; same-named applications in other directories do not block installation. Silent updates wait up to ten seconds for the affected application to exit, then stop with exit code 2 if it is still running. -The theme follows Windows at startup; `/THEME=light`, `/THEME=dark`, and `/THEME=auto` select a palette explicitly. The window appears after its branded controls are ready. When the welcome page first appears, the installer moves above ordinary windows once and flashes its taskbar button if another window has focus; it does not remain always on top. Progress reads the pinned 7-Zip extractor’s percentage; directory promotion, registration, and cleanup retain bounded estimates. The weighted percentage does not predict remaining time. After NSIS reports success, the bar fills over 600 ms and displays 100% briefly before the finish page appears; the transition targets 750 ms. The finish page preserves the window position. Finish dismisses the installer before launching the installed executable; a launch failure restores the page for retry. Directory replacement and failure recovery follow the installation flow described above. First-launch profile preparation remains a separate Desktop operation. +The theme follows Windows at startup; `/THEME=light`, `/THEME=dark`, and `/THEME=auto` select a palette explicitly. The window appears after its branded controls are ready. When the welcome page first appears, the installer moves above ordinary windows once and flashes its taskbar button if another window has focus; it does not remain always on top. Progress reads the pinned 7-Zip extractor’s percentage; directory promotion, registration, and cleanup retain bounded estimates. The weighted percentage does not predict remaining time. After NSIS reports success, the bar fills over 600 ms and displays 100% briefly before the finish page appears; the transition targets 750 ms. The finish page preserves the window position. Finish dismisses the installer before launching the installed executable; a launch failure restores the page for retry. Directory replacement and failure recovery follow the [installation checks](packaging/README.md#runtime-file-selection). First-launch profile preparation remains a separate Desktop operation. Windows packaging compiles an x86 Win32/GDI+ helper with Visual C++ Build Tools and a Windows SDK; signed builds sign this helper through the configured Windows signer. The preparation hook leaves production dependency collection to electron-builder on every platform. -Run `pnpm --dir apps/desktop run test:installer` from the repository root on an interactive Windows x64 desktop to build and exercise a small native test payload through the production installer configuration. Each run uses a unique product identity and sequentially exercises English-only and Chinese-only installer variants, selecting test labels from the displayed welcome button. Both variants install into private directories and uninstall after testing; screenshots and results remain under `.desktop-build/installer-tests/`. The checks include upgrades to registered paths with trailing separators and rejection of drive roots. The optional `--signed` flag uses the Windows EV configuration below to sign test executables and the helper before embedding them; it does not enable an update feed. +Run `pnpm --dir apps/desktop run test:installer` from the repository root on an interactive Windows x64 desktop to build and exercise a small native test payload through the production installer configuration. Each run uses a unique product identity and sequentially exercises English-only and Chinese-only installer variants, selecting test labels from the displayed welcome button. Both variants install into private directories and uninstall after testing; screenshots and results remain under `.desktop-build/installer-tests/`. The checks include upgrades to registered paths with trailing separators and rejection of drive roots. The optional `--signed` flag uses the [Windows EV configuration](windows-signing/README.md#signing-configuration) to sign test executables and the helper before embedding them; it does not enable an update feed. The Windows uninstaller removes the Electron user-data directory (browser storage and caches under `%APPDATA%`, nested under the package scope), the `%APPDATA%` product directory, and the updater download cache under `%LOCALAPPDATA%` together with the application, then removes ordinary empty scope directories below `%APPDATA%`. The Harness home (`~/.dsh` or `DSH_HOME`: sessions, settings, credentials, plugins) is never touched, and a `DSH_HOME` published as a Windows environment variable additionally protects any target overlapping it. Silent uninstalls remove the same data; an uninstaller started with `--updated` or `/KEEP_APP_DATA`, as electron-builder does for in-place updates and for replacing an older installation from another directory, retains it. Removal runs through the native helper, which refuses protected Windows folders and paths overlapping the installation or the home, requires a fixed local drive, leaves a linked root or ancestor in place, unlinks reparse points without entering their targets, clears read-only attributes, and keeps deleting siblings after a locked file; residue never stops uninstallation and is not reported. Installation records `InstallLocation` on the Windows uninstall entry as standard inventory metadata; on Windows 11, Uninstall in the Start menu context menu opens the installed-apps list for every Win32 application, and only MSIX packages uninstall directly from there. The uninstaller declares DPI awareness and uses Microsoft YaHei UI for Chinese. This behavior is Windows-only. Use `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` to compile isolated English and Chinese fixtures with a per-run scoped package name. Omit `--compile-only` to run the native remover regression and the interactive, silent, `--updated`, `/KEEP_APP_DATA` and `DSH_HOME`-inside-Electron-data checks against seeded data. Compilation does not establish installed-uninstall behavior. -### Windows EV signing - -Runtime signing shares complete signed files across the current Windows account's worktrees. `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR` in `.env.windows` selects an absolute fixed-drive directory; the default is `%USERPROFILE%\.dsh-desktop-signing\signature-cache\v1`. Cache directories must belong to the current account and exclude other ordinary accounts from their access permissions; linked paths are rejected. Entries identify the original bytes, public certificate and signing toolchain. Every restoration checks the digest, Windows trust, timestamp and certificate before replacing the unsigned file; invalid entries stop packaging without hardware fallback. Cache age alone does not trigger signing. The cache trusts programs running as the same account and does not defend against administrators. The [runtime signature cache decision](../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md) owns qualification and design limits. - -Preflight, primary-runtime signing, application-runtime signing and artifact creation each hold the account's signing-stage lock until their supervised child processes settle. Other builds wait before entering those stages; compilation and preparation do not hold the lock. Runtime signing workers own their locks, so terminating only the outer packaging process does not unlock a surviving cache user. Migration and maintenance acquire the same lock; older or external signing commands do not participate and must be scheduled separately. Stage waiting is outside the preflight deadline. Closing the stage handle releases ordinary contention without removing the separate hardware-attempt interlock; a retained hardware failure still requires operator recovery. - -Cache-hit copying, hashing and per-file trust checks run with `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY` workers from `.env.windows` (default `4`, integer `1`–`8`). All restores and their post-verification finish before cache misses enter serial hardware signing. A restore or verification failure stops new dispatch and drains active work before releasing the stage lock; hardware signing, runtime smoke checks and final integrity validation remain required. - -Each runtime stage writes `SIGNATURE_CACHE_SUMMARY` to stdout and its packaging journal, including the actual directory, policy identity, hit/miss counts, newly published and retained entries, signing requests, avoided signing requests and validation failures. Timings distinguish signing, trust verification of restored and newly signed files, and restoration; restoration includes its trust check and staging cleanup. These counters exclude preflight, final artifact signing and the outer runtime signature checks. Stage lock events record waiting separately. Concurrent timings sum per-file work rather than stage wall time. - -Use `pnpm --dir apps/desktop run cache:windows-signatures --usage` to inspect structurally complete-entry bytes and counts, or `--from ` to import an explicitly selected cache owned by the same account. Migration leaves the source unchanged, skips staging names, rejects corrupt entries and retains valid existing entries even when their timestamp bytes differ. `--clear` explicitly removes complete entries under the stage lock; no automatic capacity eviction runs. `--directory ` selects a maintenance destination without loading release credentials. Incomplete staging entries remain untouched and are counted separately; inspect them only after all builds have stopped. These commands never clear hardware failure evidence. Default storage is outside AppData so MSIX launcher virtualization does not split the account's cache; redirected overrides fail explicitly. - -Signed Windows builds run a supervised signing preflight before compilation or dependency preparation. Static configuration, certificate validity, audit storage, compiler availability and any retained signing interlock are checked without token access. The local .NET Framework C# compiler creates a small private probe; the production signer signs it once, and verification requires the configured certificate and a timestamp before building continues. The probe is never executed. The overall 60-second preflight deadline includes timestamp attempts; deadline expiry, hardware signing errors and verification failures stop the run without another hardware attempt. Success proves the current signing path works, not that the PIN was independently authenticated: SafeNet may reuse login state. Do not log out or repeat authentication to test the PIN. `--check`, preparation-only and `--unsigned` modes do not run this hardware preflight; unsigned artifacts remain ineligible for release upload. Automated regression tests use a fake signer; release operators qualify real hardware separately. - -Windows NSIS uploads require the generated, nonempty `.exe.blockmap` beside the installer. The blockmap is uploaded before channel YAML; NSIS installer metadata does not require the embedded `blockMapSize` used by the separate web-installer format. File-plan tests use the pinned builder's blockmap generator, not a hand-authored embedded-map field. - -Signed Windows configuration derives the updater's `publisherName` from the same public certificate's `CN`, `O`, and `C` attributes. Each must be present, nonempty, and single-valued. These identity attributes allow certificate renewal without pinning a leaf thumbprint. The installed application's `app-update.yml` carries the expected publisher; the downloaded feed does not choose it. Unsigned test builds omit updater configuration. See the [signature qualification record](tests/README.md) for real-file verification and its limits. - -For this project's SafeNet token, `SignTool Error: No private key is available.` indicates an incorrect PIN. Stop all signing attempts immediately and wait for the user to correct the PIN before continuing. Five incorrect PIN attempts lock the token. Do not retry packaging or signing probes after this error. The signer serializes token operations and rejects all queued tasks after the first failure. - -Windows package commands print `DESKTOP_PACKAGING_RECORD` with a unique directory under `.desktop-build/packaging-runs/`. Each run retains `run.json`, timestamped `events.jsonl`, redacted `stdout.log` and `stderr.log`, and `result.json`. A signing failure also writes `fatal.json` and notifies the parent through stderr; the supervisor immediately requests termination of its stage process tree and waits for exit. Failed stages cannot start subsequent stages or create a release completion record. Journal failures also stop the run. Termination errors remain failures and require operator inspection; a missing final record means completion was not established. - -Hardware signing requires a supervised run. Before invoking the command interpreter, the signer atomically acquires `%USERPROFILE%/.dsh-desktop-signing/attempt.json` and records the attempt. Only successful signing followed by verification of the configured primary signature releases that file; timestamps are completed afterward without hardware access. Failure, interruption, an existing interlock, or unavailable audit storage prevents further hardware access, including from another signer instance, process, or checkout under the same Windows account. There is no timed recovery or automatic retry. An administrator must inspect the retained evidence and token state before explicitly authorizing interlock recovery; logging into the token or replacing a PIN file does not clear it. The records distinguish signing intent, command-interpreter PID, and completion; they do not measure internal CSP/token authentication attempts. Command arguments, PINs, and credential environments are not recorded. Independent Windows accounts and unrelated signing programs are outside this interlock. - -Windows packaging fixes the 7-Zip filter to `BCJ` for compatibility with the bundled NSIS decoder. This preserves ARM64 binaries carried by dependencies in x64 installers; automatic ARM64 filtering produces entries that this decoder cannot extract. - -NSIS removes its temporary extraction tree during installation, before the completion page or an automatic launch. The installed production packages remain ordinary files; startup does not extract them again. Installation still writes the complete application tree. - -Fill in `.env.windows` with `DSH_DESKTOP_WINDOWS_CER_FILE` (public EV leaf certificate), `DSH_DESKTOP_WINDOWS_SIGNTOOL` (SafeNet-compatible SignTool), `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` (matching private-key container), and `DSH_DESKTOP_WINDOWS_TOKEN_PIN` (Token Password). The private key stays on the USB token; keep the certificate and local credential file out of Git. - -```sh -pnpm run package:desktop:win:x64 -``` - -Insert and unlock the token before packaging. The electron-builder hook passes each artifact to the CRLF `scripts/windows-sign.cmd`, which invokes the configured SignTool once with `/f`, SafeNet `/kc "[{{PIN}}]=container"`, `/csp "eToken Base Cryptographic Provider"`, a SHA-256 file digest, without a timestamp. The hook then completes a DigiCert SHA-256 RFC 3161 timestamp on isolated copies without signing credentials. The hook never substitutes electron-builder's bundled SignTool and never retries a failed signing request. Windows release packaging fails instead of emitting unsigned artifacts when the SignTool, certificate, container, PIN, token, or signature is unavailable. - -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. - -Create a runnable application directory instead of an installer by using the matching `:dir` command, such as: - -```sh -pnpm run package:desktop:dir -pnpm run package:desktop:mac:arm64:dir -``` - -To inspect or troubleshoot the prepared host-target resources without invoking electron-builder, stop the same pipeline after preparation: - -```sh -pnpm run prepare:desktop -``` - -This diagnostic command is an alternative stopping point, not the first half of a two-command build. A later `package:desktop*` command repeats the official build and preparation so it cannot consume stale dsh packages, runtime files, or dsh content. - -Every package command builds the repository, packs the first-party production closures rooted at dsh and the private Desktop Host, and prepares the target Electron distribution and pnpm CLI. `prepare:dsh` installs the production graph once at build time, prepares materialized packages for electron-builder to archive under `app.asar/dsh`, removes package-manager metadata, and writes `desktop-runtime.json` with shared package versions and final file hashes. Signed macOS builds sign and verify native files before inventory generation; electron-builder excludes this already-signed tree from nested re-signing. Resource mappings explicitly include `dsh/node_modules`, which the default root-directory filter omits; the prepared runtime inventory is checked after native signing. Native executables and libraries are unpacked beside ASAR; Python, standalone Node and pnpm remain in external runtime resources. Windows packaging checks every prepared PE against its ASAR unpacked entry and byte-identical disk copy, including unsigned builds. Builder glob rules match braces in PE filenames as single-character wildcards, so a matching neighboring file may also be unpacked. Prepared runtime smoke uses the verified target descriptor rather than the build host architecture. Signed installer, notarization, installed upgrade, and target-specific native-module qualification require the release environment. - -Signed macOS packaging writes `Contents/Resources/app-update.yml` while assembling the App and before code signing, including the directory build that feeds the parallel ZIP and DMG lanes. The signing hook verifies the exact feed and updater cache directory. Both lane copies and the promoted App are checked again before the release completion record is written; a missing or mismatched configuration prevents artifact promotion and therefore prevents upload. - -An unpacked artifact contains Electron, the materialized dsh production tree, pnpm, and the shell application. Installer size and filesystem size differ; release qualification measures both, plus the profile’s plugin storage and first-launch latency. The runtime trades more application files for eliminating core package installation on the user’s machine. + ## Updates @@ -435,7 +269,7 @@ On Windows, the downloaded-update confirmation explains that the application clo Native update overlays wait for a ready document and a visible parent, and reappear when that parent is shown again. Closing an overlay releases its input interception and parent listeners. The [local window qualification](tests/README.md#verification-overlay) exercises these transitions without starting a workspace. -Packaged applications check fixed Nightly asynchronously at startup. Ordinary polling uses a ten-minute base interval with independently sampled ±20% jitter. Each check failure doubles the base delay up to one hour; success resets it. The randomized delay is bounded by that cap and starts after all joined callers settle. Foreground and system-resume checks respect the same monotonic deadline; the localized Check for Updates menu item, including in the Windows caption's Application menu, runs immediately and joins an in-flight check. A newly received mandatory policy also requests an immediate feed check. Automatic checks never open dialogs or download packages. Manual checks display checking, failure, or no-update feedback with the installed version. Ordinary update dialogs fade in and out in place; consecutive prompts replace the card content and reset its scroll position while retaining the dark translucent backdrop without blurring the parent page. +Packaged applications check fixed Nightly asynchronously at startup. Ordinary polling uses a ten-minute base interval with independently sampled ±20% jitter. Each check failure doubles the base delay up to one hour; success resets it. The randomized delay is bounded by that cap and starts after all joined callers settle. Foreground and system-resume checks respect the same monotonic deadline; the localized Check for Updates menu item, including in the Windows caption's Application menu, runs immediately and joins an in-flight check. A newly received mandatory policy also requests an immediate feed check. Automatic checks never open dialogs or download packages. Manual checks display checking, failure, or no-update feedback with the installed version. Ordinary update dialogs fade in and out in place; consecutive prompts replace the card content and reset its scroll position while retaining the dark translucent backdrop without blurring the parent page. On Windows, dismissal hides the modal before destroying it so the parent is enabled before native window activation changes. `DSH_DESKTOP_UPDATE_CHECK_INTERVAL_MS` configures the ordinary base interval, and `DSH_DESKTOP_UPDATE_CHECK_MAX_BACKOFF_MS` configures the cap; both accept integer milliseconds from 1000 through 2147483647, with the cap at least the interval. An omitted cap defaults to the larger of one hour and the interval. `DSH_DESKTOP_UPDATE_CHECK_JITTER` sets the fractional jitter from 0 through 1, defaulting to `0.2`; the final delay is at least one second and never exceeds the cap. These settings do not change mandatory-policy polling or authorize download retries. @@ -445,6 +279,26 @@ If task teardown fails after confirmed Host exit, installation is refused and th Confirmed Host exit without successful task teardown displays localized recovery guidance in both ordinary and mandatory update dialogs. A typed preparation cause selects that guidance in each locale; changing translated wording cannot reclassify the failure. “View technical details” is collapsed by default and exposes only exit status, signal, shutdown acknowledgement, and deadline facts, not plugin stderr. Expanding it neither retries nor authorizes installation. + + +### Local desktop settings + +The [shell configuration decision](../../.agents/notes/implemented/architecture/2026-10-08-desktop-shell-configuration.md) defines Host-independent ownership and the criteria for evaluating existing settings for migration. + +The Electron main process reads `app.getPath('userData')/desktop/settings.json` once at startup, independently of Host and Cordis configuration. The default packaged paths are `%APPDATA%\@deepseek-ai\dsh-desktop\desktop\settings.json` on Windows and `~/Library/Application Support/@deepseek-ai/dsh-desktop/desktop/settings.json` on macOS. Development uses the `userData` path printed by its launcher. `DSH_HOME` does not relocate this file. + +On first launch, including after an upgrade, Desktop creates this document if it is absent: + +```json +{ + "updates": { + "allowTestAuthPopupWindow": false + } +} +``` + +Existing documents are never overwritten; an omitted `updates` object or field resolves to `false`. Set the field to `true` to permit test authentication dialogs, then fully quit and restart the application. Set it back to `false` and restart to suppress them again. Creation, read, or validation failures use the default `false` without blocking startup. Desktop attempts to warn through the Electron console with the file path; unavailable logging does not block startup. Correct the file and restart to apply an explicit setting. Unknown fields are preserved. Installation updates retain this user-data file; Windows uninstallation removes it under the [uninstall rules](#windows-uninstall-rules). + ### Mandatory update policy @@ -466,7 +320,9 @@ Packaging reads `.env.windows` or `.env.macos`: `DSH_DESKTOP_AUTO_UPDATE_ENV=tes Durations are integers from 1000 through 2147483647 milliseconds. Startup and scheduled polling are independent of business requests; foreground/resume checks respect the next due time, while manual checks bypass it and join any request in flight. The client sends the installed platform, architecture, DSH_CLIENT_VERSION, bundled dsh version, current locale and UTC offset, an empty bundle ID, and fixed Nightly. It uses no business login credentials or installation ID. -With `feishu-test`, an HTTP 401 JSON response containing `error.code: "UNAUTHENTICATED"` offers login during user-initiated checks and the packaged application's initial startup check, without waiting for the local backend. A localized explanation identifies the test build, the need for Feishu authentication, and that login neither downloads nor installs updates. Confirmation closes the explanation before opening a sandboxed window at the configured origin’s root, not a response-provided login URL. Concurrent checks reuse the entire confirmation/login operation and focus its existing window. Press F12 in the test login window to open detached DevTools for diagnosis. Cancellation does not trigger repeated prompts from periodic or foreground checks; users can retry manually. +With `feishu-test`, an HTTP 401 JSON response containing `error.code: "UNAUTHENTICATED"` offers login only when the local `updates.allowTestAuthPopupWindow` setting is `true`. It defaults to `false`, suppressing the entire authentication dialog flow during startup, manual update checks, mandatory-update refreshes, and deferred or repeated failures. Test gateway cookies are process-local. With popups disabled at startup, a gateway requiring authentication cannot provide new mandatory-update decisions during that process; enable the setting, restart and sign in to obtain them. Policy requests still enforce gateway authentication, and an authentication failure never clears a known mandatory block. Ordinary updates and product account authentication remain independent. Production keeps its anonymous policy requests regardless of this setting. + +When permitted, login is offered during user-initiated checks and the packaged application's initial startup check, without waiting for the local backend. A localized explanation identifies the test build, the need for Feishu authentication, and that login neither downloads nor installs updates. Confirmation closes the explanation before opening a sandboxed window at the configured origin’s root, not a response-provided login URL. Concurrent checks reuse the entire confirmation/login operation and focus its existing window. Press F12 in the test login window to open detached DevTools for diagnosis. Cancellation does not trigger repeated prompts from periodic or foreground checks; users can retry manually. Login and policy requests share an in-memory Session, separate from product windows and the updater; restarting requires a new login. Closing cancels login, and navigation failure provides localized retry guidance. Returning to the service triggers a fresh policy query; a redirect, cookie, or HTTP 422 is not a valid policy decision. Cancellation, expiry, and invalid responses retain any known mandatory block. Fixed login outcomes appear in process diagnostics and the optional update journal; cookies, OAuth parameters, and remote error text are not recorded by the login controller. Live Harness gateway/API integration and macOS login qualification remain unverified. @@ -490,10 +346,14 @@ The command builds the Desktop shell and runs its coordinator with real Electron The downloaded bytes are inert, and the installation call is recorded rather than executed. The test substitutes browser opening and clipboard writing to avoid external navigation and clipboard changes. It does not boot the full product workspace, qualify a real installer or restart, verify publisher signatures, or exercise differential updates or macOS. Stalled policy requests, feed requests, and payload transfers exercise real deadlines and recovery. The actual ordinary dialog verifies isolated preload loading, card geometry, an unfiltered parent page, cancellation, task-warning choices, and explicit installation approval; account-row component tests provide separate evidence. The [local qualification decision](../../.agents/notes/implemented/testing/2026-09-10-desktop-local-updater-qualification.md) and [verification record](tests/README.md) preserve these limits; production release requirements remain unchanged. + + ## Low-level development overrides An unpackaged Electron process uses `.desktop-build/development/project` under its application directory as its development project. `DSH_DESKTOP_PNPM_ENTRY` and `DSH_DESKTOP_DSH_DIR` are optional overrides with application-path defaults. `DSH_DESKTOP_PRIMARY_RUNTIME_DIR` is required for every unpackaged launch: the development launchers (`dev:desktop`, `start:desktop`, and the workspace-update qualification runner) set it to the primary-runtime directory of the target they prepared, and a launch without it fails with the fatal startup dialog. The launcher must set it because the shell cannot derive that directory from `process.arch`: the build target fixes Windows to x64 while the host may be arm64. Packaged applications ignore these variables, resolve signed resources from `process.resourcesPath`, and use the managed Desktop profile. + + ## Known limitations - Account sign-in is not connected; the Sign in button is disabled. Windows material rendering still requires platform QA. @@ -517,6 +377,8 @@ Private Platform deployment headers are injected by the embedded browser session The account provider’s `embeddedPageDist` configuration adds a `dist` query parameter to embedded Usage and Top-up URLs. Its default is empty; private frontend branch selectors belong in the local profile patch. It does not change API URLs or credential delivery. + + ## Dev Note Pre-launch CDN and capacity decisions are tracked in the [Desktop update proposal](../../.agents/notes/proposed/feature/2026-09-08-desktop-update-policy-and-installation.md#cdn-and-capacity-qualification). diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index d8256885dc..430ac4ad3d 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -1,16 +1,46 @@ +--- +description: "Desktop 在原生应用中运行 Harness 工作区。本参考文档说明应用行为、开发与集成;打包、Windows 签名和发布指南分别维护构建与发布操作。" +--- + # DeepSeek Harness 桌面端 [English](README.md) | 中文 +## 概述 + +Desktop 在原生应用中运行 Harness 工作区。本参考文档说明应用行为、开发与集成;打包、Windows 签名和发布指南分别维护构建与发布操作。 + +## 目录 + +- [应用概览](#application-overview) +- [终端命令](#terminal-command) +- [关闭窗口与退出](#closing-the-window-and-quitting) +- [关键技术决策](#key-technical-decisions) +- [内置命令运行时](#bundled-command-runtime) +- [安装归属](#installation-ownership) +- [开发](#develop) +- [打包](#package) +- [Windows 安装界面](#windows-installer-interface) +- [更新](#updates) +- [底层开发覆盖项](#low-level-development-overrides) +- [已知限制](#known-limitations) +- [开发备注](#dev-note) + + + +## 应用概览 + 桌面埋点遵循[产品采集策略](../../packages/client/product-analytics/README.zh.md)及其动态应用配置,不包含 Web 使用情况。安装更新会等待该操作的本地埋点接收请求结束,再锁定 API 准入并停止 Host。接收请求的时限为一秒,失败不会阻止安装,也不等待收集端完成发送。 桌面应用是完整 dsh Web 应用外的一层 Electron 壳。Electron RunAsNode 子进程启动共享 profile runner,Electron 立即从 `dsh-app://app/` 加载打包内的 Web 入口。共享加载页等待 Host 启动注入,然后在同一文档中启动客户端。Electron 将应用 HTTP 请求转发给已认证的 Web Host,转发时丢弃描述 Node fetch 连接而非资源本身的响应头(`transfer-encoding`、`connection`、`keep-alive`),并把插件 bundle 响应标记为 `no-store`,因为其每次启动都变化的 revision 只会在 Chromium 磁盘缓存中累积;WebSocket 流连接到该 Host,仅为归属的应用窗口附加凭据。Node IPC 承载启动注入、就绪与关闭。Desktop 默认监听系统分配的端口,因此不会与 Web 的 `3080` 或系统保留端口冲突;可通过 `webserver.config.port` patch 覆盖。 +Desktop 绑定 `127.0.0.1`,即 Electron 为就绪 URL 与 WebSocket 凭据过滤器拨号的地址。WebSocket 流按 Host 监听器使用 `ws:` 或 `wss:`;附加凭据要求 authority 与 scheme 均匹配。 + 应用菜单第一项“**关于 DeepSeek Harness**”打开 Electron 原生关于面板,展示应用图标、产品名称和当前安装的发布版本。菜单文案跟随桌面壳的语言。macOS 的隐藏、隐藏其他、显示全部和退出条目使用本地化文案,隐藏和退出条目包含 DeepSeek Harness 产品名称。这些条目保留原生动作和快捷键。macOS 从应用包读取图标,因此未打包的开发启动会显示 Electron 图标;Windows 使用随包分发的 PNG。 Desktop 的本地原生目录流程打开绑定应用窗口的 Electron 文件夹对话框,并先恢复、显示和聚焦该窗口。并发请求共用一个对话框;取消不返回路径,失败后可以重试。普通 Web 使用 Host 选择器。浏览模式列出 Host 目录。Linux 缺少 zenity 或 kdialog 时,自动选择使用浏览模式,不使用 Electron 对话框。 -Creator 和 Web Plugin Manager 在 Electron Node 模式下使用 Desktop 内置 pnpm,无需 PATH 中存在 pnpm。私有 Node 启动器环境仅应用于包操作。 +Desktop 在 `resources/runtime/primary-runtime/dependencies/pnpm` 中携带一份 pnpm 分发包。构建时的生产依赖安装、安装版 `dsh` CLI、Creator 和 Web 插件管理器通过 Electron Node 模式执行其中的 `bin/pnpm.mjs`;包操作不要求 PATH 上存在 pnpm。私有 Node 启动器环境仅用于包操作。agent(智能体)的工作区依赖将同一份完整 primary-runtime 复制到 Harness 主目录,并使用其中的独立 Node 执行 pnpm。 Platform 内嵌文档使用持久化 WebContentsView 分区,分区名由 Platform 来源和稳定账号 ID 的哈希决定。localStorage 中的页面偏好(包括已关闭的通知)在关闭视图和重启应用后保留;不同账号和来源使用独立存储。账号 ID 来自 Host 最近一次成功的资料读取;尚无该 ID 时,文档在一次性分区中打开,该分区不跨次保留偏好。打开持久分区会先清理 Cookie、文件系统、IndexedDB、Cache Storage、HTTP 与着色器缓存、Service Worker 及 HTTP 认证状态;一次性分区则清理其全部存储。关闭视图会销毁文档、移除请求拦截器并安排相同的清理,因此异常退出遗留的认证会在下一个文档加载前被清除。下次打开和应用退出都会等待该清理完成,更新安装也会在安装器接管退出前等待。清理失败会使该次打开失败,并在后续清理成功前阻止同一账号打开;其他账号不受影响。退出登录会销毁文档,但保留账号偏好供下次登录使用。同一凭证下账号 ID 迟到时,已以一次性分区打开的文档保持挂载;下次打开使用账号分区。[存储决策](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.zh.md)说明保留策略。Host 通过私有 Node IPC 发送账号凭证;账号 RPC 和 Harness 渲染进程不接收 token。Platform preload 在页面脚本执行前通过一次同步 IPC 读取主进程中已准备的凭证。它暴露 displayMode、同步的 getAuthToken() 和 getLocale() getter,以及返回取消订阅函数的 onLocaleChange(listener)。两个 getter 都只读取 preload 内存,不再调用 IPC。bootstrap 包含 Desktop 已解析的语言(`zh_CN` 或 `en_US`);Settings 语言变更会更新 preload 缓存并通知已打开的 Platform 文档,无需重载。Platform 在首屏渲染前应用该语言,且不将其持久化为浏览器偏好。主进程处理器仅校验调用来源并读取内存,不等待 Host、磁盘或网络。可信页面初始化失败时保留内嵌模式,由 getter 抛错,避免回退到浏览器凭证。只有受控 Platform 页面中、位于所配置签发来源的主 frame 能完成初始化。退登、凭证替换、Host 关闭及视图关闭都会销毁文档。跨来源文档导航被阻止。请求新窗口的 HTTPS 链接在系统浏览器中打开,不携带内嵌会话或 token;其他协议及带 URL 凭证的链接被拒绝。原生视图占据 Account 功能返回栏下方的视口。 @@ -22,6 +52,8 @@ Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 按 F12(多媒体功能键键盘上为 Fn+F12)、macOS 的 Command+Option+I 或 Windows 的 Ctrl+Shift+I,可切换当前获得焦点的应用页面的 DevTools,打包版本同样支持。这些原生快捷键通过隐藏的应用菜单项注册。更新遮罩和打包版本的内嵌浏览器禁用 DevTools。 + + ## 终端命令 应用菜单中的**管理 dsh 命令…**位于**检查更新…**下方,显示当前命令,并提供安装、修复和移除操作。命令复用 Desktop 已安装的运行时和普通 [dsh CLI](../cli/README.zh.md),Desktop 应用关闭后也可以使用。安装后打开新终端,运行 `dsh --version`。 @@ -30,6 +62,8 @@ macOS 安装会创建 `/usr/local/bin/dsh`;目录权限需要时,系统会 命令注册是安装 Desktop 后的可选操作。卸载 Desktop 前,请通过**管理 dsh 命令… → 移除**删除其 CLI 注册;应用卸载程序不会移除该注册。更新或卸载 Desktop 前请结束 CLI 命令。CLI 运行时版本随已安装的 Desktop 版本变化。Desktop 插件命令与运行时限制见[内置命令运行时](#bundled-command-runtime)。 + + ## 关闭窗口与退出 关闭主窗口(macOS 的关闭按钮和 ⌘W;Windows 的 ×、Alt+F4 和任务栏"关闭窗口")会隐藏窗口;Windows 首次隐藏前需要确认。页面和 Host 继续运行,任务不受影响,下次显示时仍是原来的文档,会话、草稿和滚动位置都保留;macOS 全屏窗口先退出全屏再隐藏。macOS 通过 Dock 图标、再次启动或 `dsh://open` 找回窗口,Windows 通过托盘找回。最小化行为不变。进入工作区前关闭欢迎窗口,Windows 上走退出流程,macOS 上应用留在 Dock 中且没有窗口。 @@ -44,6 +78,8 @@ Windows 在整个运行期间常驻托盘图标。悬停提示为产品名,单 托盘渲染器以底板中心为基准将鲸鱼放大 20%,保留背景和宽高比;应用和安装器图标保持原有比例。 + + ## 关键技术决策 设计师原稿位于 `resources/icon.png` 和 `resources/icon.svg`;平台适配保留鲸鱼与渐变,分别位于 `resources/icon-windows.*` 和 `resources/icon-macos.*`。将各平台 SVG 导出为透明的 1024×1024 PNG。electron-builder 为 Windows 应用、安装程序和卸载程序生成多尺寸 ICO([Windows 图标要求](https://learn.microsoft.com/en-us/windows/apps/design/iconography/app-icon-construction))。安装页面在两种主题下使用匹配的图案;卸载程序的欢迎和完成页共用 `installer/assets/uninstaller-sidebar.png`,准备阶段将其转换为 164×314 BMP。 @@ -60,17 +96,19 @@ macOS PNG 使用带留白的圆角底板,供传统 ICNS 打包使用,包含 electron-builder 只把清单中的 `dependencies` 复制进 `app.asar/node_modules`,因此 Electron 主进程 bundle `lib/main.js` 内联其工作区 devDependencies,裸导入只剩 `electron`、Node 内置模块与这些 `dependencies`;沙箱 preload 只能留下 `electron`、`events`、`timers` 与 `url`,即其 `require` polyfill 能解析的模块。主进程 bundle 从被内联包的 `lib/` 产物解析它们,所以根 `build:lib:host` 在并发的工作区 tsdown 阶段之后才为 `apps/desktop` 打 bundle,并由 [`desktop-bundle-imports`](scripts/desktop-bundle-imports.mjs) 让任何静态、动态或 `require()` 导入无法在打包应用内解析的 Desktop bundle 直接失败。没有这项检查时,rolldown 无法解析的导入会作为外部说明符进入产物,并在启动时以 `ERR_MODULE_NOT_FOUND` 失败。[已归档的bundle 顺序决策](../../.agents/notes/archived/process/2026-09-22-desktop-main-bundle-after-workspace-tsdown.md)记录了备选方案。 -Windows 签名打包按 PE 文件内容扫描第一方运行时和应用生产依赖,包括没有常规扩展名的文件。最终扫描覆盖整个解包应用。目录链接、格式错误的 `MZ` 文件以及非 PE 的 `.exe`、`.dll` 或 `.pyd` 文件会使打包停止;以 `MZ` 开头的数据文件也会被拒绝,除非包含有效 PE 头。它保留有效的上游签名,并在记录运行时哈希或执行冒烟检查前为未签名代码补签。公钥验签每个进程处理最多 32 个文件,同时最多运行四个进程;硬件令牌签名仍串行执行,每个新签名必须匹配配置的证书且带时间戳。硬件签名或验签失败会停止本轮执行;独立的时间戳请求遵循下文的有界重试规则。electron-builder 只有在验签和逐字节比对通过后,才保留复制后运行时可执行文件的签名。写入发布完成记录前,必须通过最终 PE 签名检查,以及使用全新缓存的 ASAR 载荷和 Host 冒烟检查。开发、仅准备和未签名构建不使用硬件令牌,可能被 Windows 代码完整性策略阻止;任何构建模式都不会关闭该策略。冒烟检查通过不代表兼容所有企业策略。 +Windows 签名打包按 PE 文件内容扫描第一方运行时和应用生产依赖,包括没有常规扩展名的文件。最终扫描覆盖整个解包应用。目录链接、格式错误的 `MZ` 文件以及非 PE 的 `.exe`、`.dll` 或 `.pyd` 文件会使打包停止;以 `MZ` 开头的数据文件也会被拒绝,除非包含有效 PE 头。它保留有效的上游签名,并在记录运行时哈希或执行冒烟检查前为未签名代码补签。公钥验签每个进程处理最多 32 个文件,同时最多运行四个进程;硬件令牌签名仍串行执行,每个新签名必须匹配配置的证书且带时间戳。硬件签名或验签失败会停止本轮执行;独立的时间戳请求遵循[有界重试规则](windows-signing/README.zh.md#windows-ev-signing)。electron-builder 只有在验签和逐字节比对通过后,才保留复制后运行时可执行文件的签名。写入发布完成记录前,必须通过最终 PE 签名检查,以及使用全新缓存的 ASAR 载荷和 Host 冒烟检查。开发、仅准备和未签名构建不使用硬件令牌,可能被 Windows 代码完整性策略阻止;任何构建模式都不会关闭该策略。冒烟检查通过不代表兼容所有企业策略。 Desktop 携带独立的 Python、Node.js 和 pnpm 分发包。Python 包含 numpy、pandas、python-docx、python-pptx、openpyxl、Pillow、lxml、XlsxWriter 及其完整依赖。`load_workspace_dependencies` 工具首次使用时,将该产物离线安装到 `$DSH_HOME/dsh-runtimes/dsh-primary-runtime`(通常为 `~/.dsh/dsh-runtimes/dsh-primary-runtime`),并返回解释器、pnpm 脚本和库目录的绝对路径,以及记录内置分发包名称与版本的 `pythonDistributions`。版本报告不包含用户自行安装的包。Office 任务默认使用这些库,用户或工作区指令指定其他环境时遵循其要求。pnpm 脚本通过返回的 Node 可执行文件运行。返回的 Node 库目录为随包交付的库预留,不是 pnpm 的全局安装目录。 -Desktop 默认注册 `office-docx`、`office-pptx` 和 `office-xlsx`。这些技能使用内置 Python 库创建文件和进行定点编辑,随后重新打开文件,并在交付前运行共享结构检查器。PowerPoint 的创建和编辑使用 python-pptx。技能资源复制到 ASAR 外的 `runtime/office-skills`,让 Python 可以读取检查器。可用的 `render_document` 工具可以补充视觉检查;缺少该工具不妨碍创作或交付。检查范围与限制见 [Office 技能包](../../packages/skill/skill-office/README.zh.md)。 +Desktop 展示精简的 `office` 路由及可具名调用的创作/操作子技能。创作使用内置 Python 库;操作技能调用配置的 Node 和 CLI 路径。技能位于 ASAR 外的 `runtime/office-skills`。渐进加载与限制见 [Office 技能包](../../packages/skill/skill-office/README.zh.md)。 该产物随 Desktop 版本发布。`runtime.json` 记录 Desktop 版本、目标平台、顶层解释器和包管理器版本及 Python 分发包版本表,以及所选目标的锁定产物输入与组装格式的摘要。分发包名称按 PEP 503 归一化;名称归一化后重复时,清单会被拒绝。旧 `components` 清单通过归一化继续可读,并保留其原有库版本一致性校验。匹配的安装会被复用;依赖或压缩包变化后,即使 Desktop 版本不变,也会在完整暂存副本完成后替换目录。不含摘要的旧清单会在下次安装时被替换。用户自行添加的 Python 包仅在产物身份一致时保留。目录替换失败时保留之前的安装;解释器仍在运行时,Windows 可能拒绝替换。 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、测试目录已移除,以及清单所列文件存在。 | 决策 | 原因 | 直接结果 | |---|---|---| @@ -96,6 +134,8 @@ Welcome 加载共享 Toast 的配色和阴影变量,挂载在 body 下的通 更新或卸载 Desktop 前请结束 CLI 命令;安装程序不与运行中的命令协调。CLI 不提供 Office 创作 skill 的资源路径。Desktop 现有 Office 设置与 Web 附件转换保留各自的资源配置。`prepare:runtime` 复制启动脚本,无需编译原生 CLI 启动器。 + + ## 安装归属 Electron 拥有 `$DSH_HOME/profiles/desktop`。其 `dependencies` 包含 pnpm 安装的包;`dsh.profile.bundles` 包含内置 bundle,后接已启用插件。签名应用从 `resources/app.asar/dsh` 提供 dsh、私有 Desktop Host 及其生产依赖。打包应用选择 runtime profile 解析,不创建包链接;开发 profile 使用文件系统链接。宿主与插件在同一个 Electron Node 模式进程中执行;Desktop 不启用 `--preserve-symlinks`。CLI 不能启动此 profile。Desktop 内置命令可在应用退出后管理其插件;npm 安装的 dsh 不能修改它。 @@ -142,6 +182,8 @@ macOS 上自定义菜单保留 Electron 的标准 Window 菜单及应用隐藏 macOS 和 Linux 从图形界面启动的程序只继承会话管理器提供的环境,不包含 shell 启动文件导出的变量。第一个 Host 启动之前,Desktop 以 ` -ilc` 运行一次账户的登录 shell(取自用户数据库,不看 `$SHELL`),读取定界符之间的 `env -0` 输出,使 `~/.zprofile` 和 `~/.zshrc`(或该 shell 的对应文件)对 Host、agent shell、终端和 profile 配置生效。读取与 profile 准备并行进行。读取进程没有终端输入,并设置 `DISABLE_AUTO_UPDATE=true`、`ZSH_TMUX_AUTOSTARTED=true` 和 `ZSH_TMUX_AUTOSTART=false`,避免 oh-my-zsh 和 tmux 插件阻塞。shell 的值覆盖继承的值,但 `PWD`、`OLDPWD`、`SHLVL`、`_`、上述读取变量以及启动方自有的 `DSH_*` 和 `ELECTRON_*` 除外;Desktop 在读取之前已按 `DSH_HOME` 等变量解析路径,因此 Host 保持相同的值。读取在结束定界符出现时完成,因此启动文件启动的后台进程可以继续运行,其输出被丢弃。候选 shell 无法启动、以非零状态退出、没有输出定界内容或超过 `DSH_DESKTOP_LOGIN_SHELL_TIMEOUT_MS`(1000 到 2147483647 的整数毫秒,默认 `10000`;超时会结束其进程组)时,Desktop 记录一条警告,并依次尝试 `/bin/zsh`、`/bin/bash` 和 `/bin/sh`;全部失败时 Host 使用继承的环境。读取命令使用 POSIX 语法,因此 csh、tcsh 或 nushell 等账户 shell 会失败,Host 改为获得第一个系统 shell 的启动文件所设置的环境。读取期间退出 Desktop 会结束正在运行的读取进程组。每个应用进程只读取一次,因此修改 shell 启动文件后需要退出并重新打开 Desktop。Windows 从图形界面启动的程序已经从注册表继承用户和系统环境变量,因此 Windows 跳过这一步。 + + ## 开发 开发环境应用菜单提供“刷新页面”(macOS 为 Cmd+R,其他平台为 Ctrl+R)和“重启应用与 Host”。重启会等待 Host 关闭,再重新启动 Electron 和新的 Host;这两项操作都不会重新构建源码。 @@ -182,254 +224,44 @@ Desktop 在 Host 启动后、打开工作区前检查模型 API Key 引用是否 欢迎窗口使用设计稿的 Platform light/dark 颜色跟随系统外观,展示 600 × 700 的入口布局和 API Key 表单,包含原生窗口控件、可拖动标题区域、本地品牌 SVG、系统无衬线字体回退,以及非按钮文字使用的本地 Montserrat Light 字体。窗口使用 macOS menu vibrancy 或 Windows acrylic,叠加 onboarding 的窗口背景色:浅色模式为 40% 白色,深色模式为 50% rgb(24 25 28)。本地 React 欢迎入口将 React、公共 `StateDot` 加载指示器及其 CSS 一起打包;它通过隔离 preload 工作,不加载主 Web 应用。入口、登录状态和 API Key 页面共用固定的底部操作行;“返回登录”链接位于操作行下方。按钮共用平台的过渡时序,开启“减少动态效果”会禁用过渡。操作系统控制模糊强度和外部圆角。macOS 的“降低透明度”会抑制半透明效果,“增强对比度”会强制开启该设置。“保存并继续”写入开发环境的凭证存储;“稍后配置”打开真实工作区,不保存密钥或完成标记。生成的开发项目同时链接已声明的 workspace 依赖闭包和 pnpm 提升的包,因此未提升的配置插件仍能解析。[窗口记录](../../.agents/notes/implemented/architecture/2026-09-08-desktop-welcome-window-material.zh.md)负责材质与引导决策。 + + ## 打包 - -### 发布版本 - -每次 Desktop 打包前,第一步都要与当前用户确认完整版本号。检查所选部署环境、dsh 基础版本、保留的发布记录和已发布对象,再提出准确版本供用户确认。用户确认前不得启动打包;仅选择部署环境不代表用户已认可版本号。 - -记录当前 dsh 版本作为基础版本。production Desktop 使用完全相同的版本,包括其中的 `alpha`、`beta` 或 `rc` 标识。test 发布保留完整的预发布基础版本并追加 `.YYYYMMDD.index`;稳定基础版本则追加 `-test.YYYYMMDD.index`。 - -| dsh 基础版本 | production Desktop | test Desktop 示例 | -|---|---|---| -| `0.1.6-alpha.1` | `0.1.6-alpha.1` | `0.1.6-alpha.1.20260916.1` | -| `0.1.6-beta.2` | `0.1.6-beta.2` | `0.1.6-beta.2.20260916.1` | -| `0.1.6-rc.3` | `0.1.6-rc.3` | `0.1.6-rc.3.20260916.1` | -| `0.1.6` | `0.1.6` | `0.1.6-test.20260916.1` | - -日期使用实际创建时的 Asia/Shanghai 日期。每个基础版本、每天的序号从 1 开始,检查保留的发布记录与已发布对象后递增;绝不复用已发布版本。test 分发不发布对应的无后缀基础版本。 - -把确认后的版本通过 `--build-version` 传给打包命令,该值同时决定产物文件名、更新 feed 与上传校验。清单保留产品版本,因此 test 打包不再改写发布家族,也不留下需要还原的改动: - -```sh -pnpm --dir apps/desktop run package:win:x64 --build-version 0.1.6-alpha.1.20260916.1 -``` - -`--build-version auto` 会给出当天的下一个序号:读取目标 bucket 中已发布的对象,未配置 bucket 或列举未能在期限内完成时回退到本目标的本地输出目录。上传前请确认它打印的版本号;run script 会自行透传 `--`,打包入口两种写法都接受。 - -production 发布使用产品版本本身,不传 `--build-version`。其上传成功后会把打包所用 commit 打成 `desktop-v<版本>` 标签;来自有改动工作区的构建不打标签,打标签失败也只打印手工命令,不会让已完成的上传变成失败。test 与本地构建有意不留标签,而所有产物的清单都记录 `dshBuildCommit` 与 `dshBuildDirty`,直接分发的构建同样可溯源。 - -版本派生不改变固定更新通道,也不改变 `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 同样在运行前生成目标文件。 - -每条打包命令在构建与下载前检查应用 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` 下同样如此。单独运行相同检查: - -```sh -pnpm --dir apps/desktop run check:package -``` - -无需提前执行 `prepare:desktop`: - -```sh -pnpm run package:desktop -``` - -发布自动化使用固定目标命令,确保运行时准备、dsh 准备与 electron-builder 接收相同的平台和架构: - -```sh -pnpm run package:desktop:mac:arm64 -pnpm run package:desktop:mac:x64 -pnpm run package:desktop:win:x64 -``` - -macOS arm64 命令要求 Apple Silicon。macOS x64 命令可以在 Intel macOS 或带 Rosetta 的 Apple Silicon 上运行。Windows x64 命令要求 Windows x64。Linux 不是受支持的 Desktop 发布目标。 - -每个目标都在 `apps/desktop/.desktop-build/targets//` 下持有自己的打包输入、已准备运行时、包集合、dsh 依赖树、pnpm 准备状态、未打包应用、更新元数据和最终产物。Electron 归档缓存继续由 `.desktop-build/downloads` 共享,因为每个归档文件名都包含版本、平台和架构,并且在解包前经过验证。目标构建绝不读取其他目标的可变准备状态。 - -### 无发布签名的本地 macOS DMG - -执行 `pnpm install` 后,在仓库根目录运行一条命令即可,无需 `.env.macos`、Apple 账号、证书或更新服务配置: - -```sh -pnpm run package:desktop:mac:arm64:unsigned -pnpm run package:desktop:mac:x64:unsigned -``` - -添加 `--check` 仅验证本地配置和工具而不构建,或添加 `--dir` 只生成解包应用。DMG 路径为 `apps/desktop/.desktop-build/targets//unsigned-artifacts/deepseek-harness--mac--unsigned.dmg`。所有检查通过后,命令打印 `DMG:` 及其绝对路径。打开后将应用复制到本地测试目录。 - -这些命令忽略 `.env.macos` 和继承的发布配置,使用 `com.deepseek.harness` 作为应用 ID,并省略自动更新和强制更新配置。构建工具、标准网络代理与 `DSH_DESKTOP_NPM_REGISTRY` 仍可从 shell 提供。它们跳过 Developer ID 签名、Apple 公证、临时签名钥匙串和公证代理修改。Electron 使用无需证书的本地 ad-hoc 签名,以便修改后的可执行文件能够运行;DMG 不签名。准备阶段和组装后的应用仍执行运行时完整性与冒烟检查。本地构建不生成更新源、ZIP 或发布完成记录,上传命令无法发布这些产物。macOS 可能要求在“系统设置 → 隐私与安全性”中批准打开未经公证的应用。 - -### 用回环 registry 安装本地 Official 包 - -测试 DMG 不包含 Official 按需目录所宣传的 provider 运行时,而正式发布才会把对应版本的 bundle 发到 npm。要在发布前安装本地构建的 bundle,请启动一个回环 registry,它会打包并提供该目录的完整本地依赖闭包: - -```sh -pnpm run dev:bundle-registry -``` - -该命令先校验目录与 workspace 清单,运行 `pnpm run build:official`,把闭包打包进新的 `dist/test-bundles//` 目录,最后写入 `bundle-registry.json` 作为完成标记,然后才打印产物路径、registry URL 和精确的 `name@version` 规格。它在分配到的端口上只监听 `127.0.0.1`,使用一次性的命名空间提供服务,直到 Ctrl+C 或 SIGTERM;停止后产物和已安装的包都保留在磁盘上。它不需要 `.env.macos`、Apple 凭据或 npm 凭据,也不改变 `pnpm run package:desktop:unsigned`。 - -在打包应用中打开“插件 → 添加插件”,粘贴一条打印出的规格,选择**自定义地址**,粘贴打印出的 registry URL 后安装。自定义 registry 会被单独询问,因此必须由本进程回答每一个依赖:仓库自有的包取自本次运行的产物,第三方包则通过固定重定向到 `registry.npmjs.org` 保留 npm 的真实元数据与字节,因此仍需要网络访问。安装后的条目仍归类为 Official,因为它的包名在目录中。registry 选择会在此浏览器中记住;再次选择某个提供的 registry 即可切回。 - -一次运行的产物是不可变的,所以重新构建会提供新的命名空间和新 URL;当已安装版本与运行版本一致时,Official 的**更新**控件不会出现。profile 会在 `pnpm-lock.yaml` 中记录上一次运行的 tarball URL,而 pnpm 会校验已记录的条目,因此用新 URL 再次安装或重装该 bundle 会被 `ERR_PNPM_TARBALL_URL_MISMATCH` 拒绝,并且可能继续保留旧文件。要在同一版本上验证改动后的代码,请先清除过期的解析结果——在 `$DSH_HOME/profiles/` 中运行 `pnpm clean --lockfile`,或改用全新的 profile——然后再从新 URL 安装。`bundle-registry.json` 记录每个归档的版本、文件名、大小和 SHA-512 完整性,以及打包所用 checkout 的 commit 和 dirty 标记。 - -所提供的 `time` 是真实的打包时间,因此 pnpm 11 默认的 24 小时 `minimumReleaseAge` 会在 profile 的 `pnpm-workspace.yaml` 中记录它授予的豁免(`minimumReleaseAgeExclude`);如果那里显式配置了更严格的策略,安装会以 pnpm 自己的报错失败,而不会被覆盖。`~/.npmrc` 或 profile 的 `.npmrc` 中的 `@scope:registry` 路由会覆盖该 scope 的 `--registry`,因此不能让它们指向正在提供服务的 scope。 - -### 运行时文件筛选 - -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 预构建文件。它保留运行时 JavaScript、原生模块及其 DLL/EXE 辅助文件、WASM、未知资源、许可证和 notices。依赖清单在完整性封装前经过 electron-builder 的元数据清理,确保归档保持已记录的字节。该策略不修改 npm tarball、捆绑的包管理器或用户安装的插件文件。 - -[Office 转换提供方](../../packages/document/office-to-pdf/README.zh.md)携带目标已声明的原生引擎;kit 未声明匹配原生目标时携带 WASM 引擎。准备阶段在打包前拒绝缺少目标引擎的情况。完整 Office 依赖(CLI、JavaScript 库和选定引擎的可执行文件、数据、许可证及 notices)解包到 `resources/app.asar.unpacked/dsh/node_modules/` 下。Desktop Host 将引擎清单解析到这些物理目录,并向加载的技能提供独立 Node 和解包后 CLI 的绝对路径。Node 位于 `resources/runtime/primary-runtime/dependencies/node/bin/`;CLI 位于解包后的 `@deepseek-ai/libreoffice-kit/lib/cli.js`。macOS 上的原生辅助程序获得 [LibreOffice UNO 桥](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in)所需的 JIT entitlement。 - -打包应用运行编译后的 JavaScript 和预生成的 Typert 元数据,不编译 TypeScript 插件。源码级调试导航和编辑器声明仍可从开发包中获取。[复制规则测试](tests/runtime-file-policy.spec.ts)覆盖排除项和保留资源;[产物 smoke](tests/fixtures/runtime-payload-smoke.mjs) 在 Host smoke 和最终清单验证之前,使用 Electron RunAsNode 执行。产物 smoke 解析搜索工具使用的 ripgrep 可执行文件,并验证文本搜索和文件枚举。Windows 签名构建在依赖签名后运行这些检查;其他构建在 `prepare:dsh` 中运行。[Host smoke](scripts/smoke-runtime.ts) 使用捆绑的 Python 创建 DOCX、XLSX 和 PPTX 输入,通过真实 Office 提供方逐一转换并检查 PDF 输出。每个组装后的应用(包括目录包和未签名构建)都会针对 ASAR 重复产物和 Host 检查。归档完整性检查将归档内完整描述符与准备结果比对,并核对归档和解包目录中的文件内容与清单、归档内文件记录的执行标志,以及解包文件的物理权限。转换失败会在写入发布记录前终止打包;macOS DMG/ZIP 构建在公证前执行这些检查。 - -Windows 发布验收还需在 Desktop 构建后手动运行[目录和替换检查](scripts/smoke-windows.ps1)。将 `$Makensis`、`$SevenZip` 和 `$PluginDir` 分别设为锁定版本构建器的 NSIS 编译器、7-Zip 可执行文件和 x86-unicode NSIS 插件目录;通过 `-FrameLibrary` 传入已准备好的 `window-frame.dll`,即可同时覆盖原生解压路径及其失败报告。从仓库根目录运行以下命令。它验证 目录替换与回滚和两种文件占用替换方式;不属于单元测试通道。 - -```powershell -pwsh -NoProfile -File apps/desktop/scripts/smoke-windows.ps1 -Makensis $Makensis -SevenZip $SevenZip -PluginDir $PluginDir -FrameLibrary apps/desktop/.desktop-build/targets/win-x64/installer-ui/window-frame.dll -``` - -Windows 安装器在启动时和选定目标目录后检查应用是否正在运行,通过检查后才将新版本解压到安装目录旁边。通过同卷目录改名替换前,安装器会再次检查。运行中的应用会阻止安装;更新启动允许等待应用退出,最长十秒。同路径升级在替换成功前保留旧目录;解压失败时旧版不变,替换失败时尝试恢复旧目录。安装器在启动前清理旧版备份。强制结束安装器或断电可能留下 `.new-*` 或 `.old-*` 目录;不同安装位置或安装范围迁移仍使用 electron-builder 的旧卸载器流程。 - -解压失败时,安装器会把 7-Zip 的结果和完整错误输出写入更新缓存目录 `%LOCALAPPDATA%\<按包名派生>-updater\installer-logs\extract-failure-<时间戳>.log`(当前为 `@deepseek-aidsh-desktop-updater`),并在弹窗中显示首条错误行和 **复制错误信息** 按钮;静默安装只写入报告。未签名的 Windows 构建(`DSH_DESKTOP_UNSIGNED=1`)会将安装包命名为 `deepseek-harness-<版本>-win-x64-unsigned.exe`,以免被误当作发布产物。 - + + + + + + -### 上传更新 +构建与发布操作请使用独立指南。共享 Windows runner 存在已接受的凭据和设备隔离限制;签名或执行分支代码前必须阅读。 -固定安装包下载在仓库根目录使用 `pnpm run upload:latest:mac:arm64`、`pnpm run upload:latest:mac:x64` 或 `pnpm run upload:latest:win:x64`。它们把已完成目标的 DMG 或 EXE 上传到 `desktop/dsh-latest-macos-arm64.dmg`、`desktop/dsh-latest-macos-x64.dmg` 或 `desktop/dsh-latest-windows-x64.exe`。生产 URL 以 `https://download.deepseek.com/` 开头;测试 URL 使用 `DOWNLOAD_TEST_ORIGIN`。两个部署环境均复用目标 dotenv 中的部署、bucket 和凭据、全部常规发布校验以及下述上传审计。每个命令覆盖一个固定对象,不发布更新清单、blockmap 或发布标签。测试固定下载在测试 bucket 中跨发布 ID 共享;包内更新 URL 仍要求原有发布 ID。发布由操作人员显式执行,也允许预发布版本。部署基础设施必须配置重新验证,或在覆盖后清除固定下载的缓存。本地回环测试覆盖上传行为;真实 COS 和 CDN 验收由发布操作人员负责。 +- [Desktop 打包](packaging/README.zh.md):本地与 Actions 构建、版本、部署配置、产物、日志和验收。 +- [Windows 签名与 runner 运维](windows-signing/README.zh.md):机器部署、已接受的隔离风险、签名凭据、Token 失败与缓存维护。 +- [Desktop 发布](publishing/README.zh.md):上传凭据、发布标识、固定下载、更新清单和上传恢复。 -test 与 production 的 `upload:*` 上传在发布前置检查通过后,分别保留新的 `.desktop-build/upload-records/--*` 目录。`plan.json` 记录目标、版本、每个文件的大小/SHA-512 和发布的 YAML 字节;刷盘的 `events.jsonl` 记录 PUT 意图及可用的响应状态/请求 ID;`result.json` 记录完成结果或最后失败阶段。缺少最终结果表示中断或存储不可用,不表示成功。不记录凭据值、认证头或原始 SDK 错误。审计写入失败即停止后续 PUT。每个对象都以一次流式腾讯 COS PUT 上传,并携带显式长度与 Content-MD5;COS SDK 仅在请求体不是流时才会重发请求,上传器自身也不重试。保留部分记录,检查远端状态后再执行下一次操作:超时或回执写入失败不能证明对象未存储。这些记录仅在本地,不防篡改,也不会自动备份;每次发布应将它们与构建证据一同归档到受控存储。公网 CDN 回读仍是单独的发布验收,上传结果明确标记为 `not-performed`。 + -Windows 操作人员可以在仓库外保存 CLIXML 对象,其中 `SecretId` 和 `SecretKey` 是经 DPAPI 加密的 SecureString 字段。[凭据启动器](scripts/upload-with-credentials.ps1)要求显式提供 `-CredentialFile` 和 `-Environment production` 或 `test`;不指定 `-Upload` 时,只验证解密以及向本地 Node 子进程注入凭据,不发起网络请求。它要求 `PATH` 中有 Node,并使用加密该文件时的 Windows 用户和机器。明文、空字段及纯空白字段都会失败。父进程环境保持不变;子进程先清除无关密钥与 Node 预加载选项,再仅接收所选 COS 凭据对。原始子进程 stderr 不会显示,stdout 中的凭据值会被遮盖。此检查不能证明 COS 授权有效。显式上传还要求 `-Upload -Target -Bucket ` 及下述常规发布完成前提;真实云端上传仍需发布操作人员验收。在该上传调用中添加 `-Latest`,即可替换固定安装包,而不发布更新清单或发布标签。此启动器支持长期密钥,不支持 STS 凭据。显式上传要求所选部署环境和 bucket 与目标 dotenv 文件及已完成的打包记录一致,才会发起网络写入;即使 dotenv 文件含有其他 COS 密钥,也使用 DPAPI 凭据对。 + -`DSH_DESKTOP_AUTO_UPDATE_ENV` 同时选择打包写入的 URL 与后续 COS 上传环境,可取 `test` 或 `production`;缺省为 `test`。测试打包通过 `DOWNLOAD_TEST_ORIGIN` 提供 HTTPS origin;生产使用 `https://download.deepseek.com`。上传通过 `DOWNLOAD_TEST_COS_BUCKET` 或 `DOWNLOAD_PROD_COS_BUCKET` 提供所选 bucket。生产清单位于 `dsh-desk/feeds//`,安装包位于 `dsh-desk/bin//`。测试发布必须配置 `DOWNLOAD_TEST_RELEASE_ID`:32 位小写十六进制字符,分别插入路径 `dsh-desk//feeds//` 和 `dsh-desk//bin//`。YAML 引用、稳定通道别名和 blockmap 都位于该发布目录内。目标为 `mac-arm64`、`mac-x64` 和 `win-x64`。 - -更新目标与上传凭据都与所选环境对应: - -| 环境 | 公开 origin | COS bucket | COS 凭据 | -|---|---|---|---| -| `test` 或未设置 | `DOWNLOAD_TEST_ORIGIN` | `DOWNLOAD_TEST_COS_BUCKET` | `DOWNLOAD_TEST_COS_SECRET_ID`、`DOWNLOAD_TEST_COS_SECRET_KEY` | -| `production` | `https://download.deepseek.com` | `DOWNLOAD_PROD_COS_BUCKET` | `DOWNLOAD_PROD_COS_SECRET_ID`、`DOWNLOAD_PROD_COS_SECRET_KEY` | - -每个测试发布批次用下方命令生成新 ID,将输出填入 `.env.macos` 或 `.env.windows` 的 `DOWNLOAD_TEST_RELEASE_ID`。这两个被 Git 忽略的平台文件管理该值,shell 变量不能覆盖它,dotenv 值也不会进行 shell 展开。打包、上传和重试必须沿用同一个 ID;上传会拒绝更新 URL 不一致的完成记录。需要验证跨版本升级时,后续版本沿用已安装客户端的 ID。生产环境不使用该字段。 - -```sh -node --input-type=module -e "import { randomBytes } from 'node:crypto'; console.log(randomBytes(16).toString('hex'))" -``` - -通过完整下载链接分发每个测试批次。已安装的测试客户端保留当前批次的清单地址,不会自动发现新 ID。格式校验无法判断随机性,请使用生成器的输出。随机路径降低被猜中的概率,不限制持有链接者访问;撤下批次需要删除其 COS 对象并清除对应 CDN 目录缓存。 - -在目标 `.env` 中配置更新地址与所选 COS bucket、SecretId、SecretKey,再打包并上传同一个目标: - -```sh -pnpm run package:desktop:mac:arm64 -pnpm run upload:mac:arm64 -``` - -内测打包在目标 `.env` 中显式设置 `DSH_DESKTOP_AUTO_UPDATE_ENV=test` 和 `DOWNLOAD_TEST_ORIGIN=https://download-test.deepseek.com`;上传使用 `DOWNLOAD_TEST_COS_BUCKET=bj-toc-download-test-1320056602` 及独立测试凭据。test 和 production 都使用固定 Nightly 通道,部署选择不提供通道切换。 - -前期内测包使用 `test` 部署。只有正式发布才显式选择 `production`;更换上传凭据不会改变已有安装包的更新目标。打包不需要 COS 凭据,会禁用 electron-builder 发布、移除子进程的 COS 凭据,并且仅在签名与公证成功后记录完成状态。上传在读取凭据前验证该记录、部署、目标、共同版本号、文件名、大小与 SHA-512。安装包和 blockmap 先于 YAML 上传;历史对象继续保留。每个版本发布 `nightly.yml` 或 `nightly-mac.yml`;稳定版本还发布指向相同产物的 `latest.yml` 或 `latest-mac.yml`。发布的 YAML 使用安装包绝对 URL。上传器不设置 Cache-Control,包括 COS SDK 否则会添加的空头部:缓存策略由部署基础设施负责,清单不缓存,安装包缓存单独配置。同一目标应串行发布,并在发布验收前验证公网产物与清单内容。 - -macOS 签名配置使用必填发布环境,不会接受钥匙串中最先发现的证书。空值、格式错误的 Team ID、包含 electron-builder 不支持的 `Developer ID Application:` 前缀的签名身份,以及不完整的公证凭据都会被拒绝。macOS 签名打包要求已配置的身份及其私钥可用。运行时准备会把该身份、安全时间戳与 hardened runtime 应用到每个内嵌 Mach-O 文件;应用签名完成后,深度严格检查会拒绝其他叶证书 Authority 或 Team ID,验证通过才生成发布产物。macOS 签名固定目标安装包命令为已签名应用创建独立副本,并发执行两条产物流。一路先公证 App 并钉票,再生成 ZIP 及其更新元数据。另一路把已签名 App 副本封装进签名 DMG,再公证 DMG、钉票并验证;其中的 App 不单独附加票据。只有两路均成功结束,产物才会移入最终目录并写入发布完成记录。签名的仅目录命令同样需要公证凭据,并等待 Apple 公证和 App 钉票完成。[并行公证决策](../../.agents/notes/implemented/process/2026-09-09-parallel-macos-notarization.zh.md)负责副本隔离与容器票据语义。`CSC_LINK` 必须指向包含 Developer ID Application 证书及私钥的本地 p12,不支持 URL 或 Base64 输入。`CSC_KEY_PASSWORD` 是其导出密码,不是 Apple 账号或登录密码;未加密的 p12 可显式填写空值。构建前,打包流程自动创建并解锁私有临时钥匙串、导入 p12、授权签名并签署小型探针。运行时与 App 签名显式使用该钥匙串,无需预先配置或手动解锁登录钥匙串。子进程只接收钥匙串路径,不接收 p12 密码。成功或普通失败后删除临时钥匙串;强制终止后由 CI 清理临时凭据。CI 从密钥存储生成证书文件和 `.env.macos`,限制文件访问权限,并在作业结束后删除二者。环境中的 `CSC_NAME` 与证书发现顺序都不能选择发布所有者。公证凭据也可以使用 electron-builder 支持的完整 Apple ID 或钥匙串 profile 方式。手动执行 `pnpm --dir apps/desktop run verify:mac-signature -- ` 重复应用检查时,也必须提供两个 macOS 身份变量。 - -macOS 签名遍历真实文件,不跟随 Framework 的软链接别名。PAK 资源保留全部随附语言,由外层 Framework 或应用签名记录完整性,不逐个签名。[发布策略](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)负责依赖补丁和验证要求。 - -macOS 运行时准备将已验证的单架构 Mach-O 签名缓存在 `.desktop-build/targets//signature-cache`。缓存键包含输入字节与权限、签名探针实际使用的叶证书、签名标识、entitlement 字节、macOS 版本,以及签名工具与策略。复用不取决于 Git 提交:未提交的字节变更会使对应文件失效。每次命中都验证缓存字节、严格签名、证书、标识、entitlements、安全时间戳和 hardened runtime,再替换未被并发修改的输入。通用二进制每次重新签名。运行时完整性与 smoke 检查、App 签名和 Apple 公证仍会执行。缓存要求受信任的本地构建存储。缓存损坏或不安全链接会令构建失败;停止打包后删除对应缓存目录再重试。成功的签名阶段会将完整缓存条目的内容总量裁剪至一 GiB;中断留下的临时条目需手动清理。并发淘汰可能使读取方安全失败。日志记录命中、未命中及未缓存数量。 - -Mac 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `apps/desktop/.desktop-build/packaging-runs/` 下的唯一目录。读取本地配置后,每次运行保留 `run.json`(发布版本、产品版本、Git 提交、工作区是否有改动、目标及 Node 版本)、`events.jsonl`(带时间戳的阶段、耗时、并行输出归属及代理恢复状态)、脱敏后的子进程 `stdout.log` / `stderr.log`,以及 `result.json`(整体结果、阶段结果和产物目录)。事件还记录打包并发数及各代理是否配置。失败和后续打包不会清除日志;没有自动删除流程。缺少 `result.json` 表示完成状态未经确认。已知凭据值会被遮盖;不记录环境变量全集或 notarytool 认证参数。运行时准备分别记录包暂存、安装、依赖树复制、签名、清单生成、smoke 检查、描述文件校验和清理。嵌套阶段的耗时存在重叠,不能直接相加。 - -App 和 DMG 公证分别记录 submission ID,以及独立的 `notarytool:upload:*` 和 `notarytool:wait:*` 耗时。上传使用 `submit --no-wait`,包含认证、本地校验、传输和服务端受理,并非纯传输时间。等待从该命令返回后开始,包含轮询及剩余的 Apple 处理时间;Apple 可能在上传提交命令返回前已开始处理。日志保留 Apple 状态与诊断信息,包括拒绝结果;签名检查、接受状态校验和 stapling 仍由 `@electron/notarize` 负责。仅生成目录的打包命令也使用同一条可计时的 App 公证路径。各子进程输出仍实时显示在终端,阶段失败及嵌套错误保留在事件日志中。两个平台均记录父进程打包失败,并在终端显示脱敏诊断,包括代理恢复操作指引。仅检查配置的 `check:package` 命令不创建运行日志。 - -Mac 打包从 `.env.macos` 读取三个调优字段: - -| 设置 | 默认值 | 作用范围 | -|---|---|---| -| `DSH_DESKTOP_MACOS_PACK_CONCURRENCY` | `4` | 第一方与 vendor workspace tarball 的打包 worker 数;必须是正整数。 | -| `DSH_DESKTOP_MACOS_DOWNLOAD_PROXY` | 空 | Electron、运行时资源、pnpm 安装及 builder 下载使用的 HTTP/HTTPS 代理 origin。 | -| `DSH_DESKTOP_MACOS_NOTARIZATION_PROXY` | 空 | 通过临时系统代理设置供 Apple 工具使用的 HTTP 代理 origin。 | - -两个代理字段互相独立,拒绝 URL 中的凭证、路径、查询参数和片段。空值沿用继承的网络设置。显式下载代理会替换子进程的代理变量,仅绕过本地主机;它不修改系统设置。Windows 与独立 `release:pack` 保持现有并发默认值。公司代理地址仅写入 Git 忽略的本地文件;具体地址参见内部文档。 - -Apple 工具使用 macOS 当前活动网络服务的 HTTP/HTTPS 代理。配置公证代理后,打包会检查代理可达性、保存该服务的设置,在两条产物任务期间启用代理,并在两条任务均结束后恢复原设置。对于原本关闭、服务器为空且端口为零的代理,恢复时仅关闭代理;临时服务器和端口可能保留,但不生效。仅生成目录的打包会在签名目录构建完成后的 App 公证期间启用代理。这会临时影响其他应用,并要求修改系统代理的权限;必须先禁用 PAC、自动发现、SOCKS 及需要认证的代理配置。打包和恢复在读取恢复记录或修改代理前获取同一个用户级 POSIX 文件锁;进程退出会释放锁的持有权,锁文件保留。该锁在首次使用时才加载 `@deepseek-ai/node-addon-system/flock`,而不是在脚本启动时加载,因此 `check:package` 和打包入口在未构建 `native/system` 的 checkout 上也能加载;加锁时若宿主 addon 二进制或入口的 JavaScript 缺失,加载器会先运行 `pnpm run build:native-system` 和 `pnpm --dir native/system run build:ts` 再加锁,因此恢复命令在这样的 checkout 上同样可用。这会阻止不同 checkout 的代理事务重叠;其他用户及网络设置工具不得同时修改这些设置。SIGINT/SIGTERM 会等待活动任务结束后恢复。强制终止或恢复失败后,先停止残留公证进程,再运行 `pnpm --dir apps/desktop run restore:mac-proxy`;保存的记录会保留到恢复成功。配置检查仅验证 URL 语法,不修改系统设置或连接代理。 - -### 未签名 Windows 测试安装包 - -在 Windows x64 上,使用完整的未签名打包命令进行本地安装测试: - -```sh -pnpm run package:desktop:win:x64:unsigned -``` - -该命令要求设置 `DSH_DESKTOP_APP_ID` 并具备常规构建依赖,包括编译原生模块所需的 Python 和 Visual C++ 构建工具。Python 不在 `PATH` 中时,将 `PYTHON` 设置为其可执行文件路径。命令将安装包写入 `.desktop-build/targets/win-x64/unsigned-artifacts/`,省略自动更新配置,清除签名凭据,且不生成发布完成记录。它不需要 EV 凭据或更新源地址。签名打包和上传命令仍遵循正式发布要求。 - -### Windows 安装界面 +## Windows 安装界面 Windows 安装程序使用原生 NSIS 页面,提供亮暗配色、系统阴影、可编辑的安装目录,以及默认勾选立即启动的完成页。安装仅面向当前用户。点击安装或按 Enter 均校验当前路径;路径规范化后仍拒绝磁盘根目录,包括带重复末尾分隔符的写法。新安装位置必须为空,非空位置必须是已登记的安装目录。受影响安装路径中的程序运行时显示系统提示,并保持应用运行;其他目录中的同名应用不阻止安装。静默更新最多等待受影响应用退出十秒,若仍在运行则以退出码 2 结束。 -主题在启动时跟随 Windows;可用 `/THEME=light`、`/THEME=dark` 和 `/THEME=auto` 显式选择配色。窗口在品牌控件准备完成后显示。欢迎页首次出现时,安装窗口会一次性移到普通窗口前方;若焦点在其他窗口,任务栏按钮会闪烁提示,但安装窗口不会始终置顶。进度读取锁定版本的 7-Zip 解压器百分比;目录替换、注册和清理仍使用有界估算。加权百分比不代表剩余时间。NSIS 报告成功后,进度条用 600 毫秒补满并短暂显示 100%,再显示完成页;切换目标时长为 750 毫秒。完成页保留窗口位置。点击完成后,安装程序先隐藏窗口,再启动已安装的可执行文件;启动失败会恢复页面以供重试。目录替换和失败恢复遵循上文描述的安装流程。首次启动的配置档案准备仍属于独立的 Desktop 操作。 +主题在启动时跟随 Windows;可用 `/THEME=light`、`/THEME=dark` 和 `/THEME=auto` 显式选择配色。窗口在品牌控件准备完成后显示。欢迎页首次出现时,安装窗口会一次性移到普通窗口前方;若焦点在其他窗口,任务栏按钮会闪烁提示,但安装窗口不会始终置顶。进度读取锁定版本的 7-Zip 解压器百分比;目录替换、注册和清理仍使用有界估算。加权百分比不代表剩余时间。NSIS 报告成功后,进度条用 600 毫秒补满并短暂显示 100%,再显示完成页;切换目标时长为 750 毫秒。完成页保留窗口位置。点击完成后,安装程序先隐藏窗口,再启动已安装的可执行文件;启动失败会恢复页面以供重试。目录替换和失败恢复遵循[安装检查](packaging/README.zh.md#runtime-file-selection)。首次启动的配置档案准备仍属于独立的 Desktop 操作。 Windows 打包使用 Visual C++ Build Tools 和 Windows SDK 编译 x86 Win32/GDI+ 辅助库;签名构建通过已配置的 Windows 签名器对该库签名。准备钩子在所有平台上均由 electron-builder 继续负责收集生产依赖。 -在有交互式桌面的 Windows x64 上,从仓库根目录运行 `pnpm --dir apps/desktop run test:installer`,可将小型原生测试载荷接入正式安装配置并执行验证。每次运行使用独立产品身份,依次验证仅英文和仅中文的安装器变体,并根据实际显示的欢迎页按钮选择测试文案。两个变体均安装到私有目录并在测试后卸载;截图和结果保留在 `.desktop-build/installer-tests/` 下。检查包含末尾带分隔符的已登记路径升级,以及磁盘根目录拒绝。可选的 `--signed` 标志使用下文的 Windows EV 配置,在嵌入前对测试程序和辅助库签名;它不会启用更新源。 +在有交互式桌面的 Windows x64 上,从仓库根目录运行 `pnpm --dir apps/desktop run test:installer`,可将小型原生测试载荷接入正式安装配置并执行验证。每次运行使用独立产品身份,依次验证仅英文和仅中文的安装器变体,并根据实际显示的欢迎页按钮选择测试文案。两个变体均安装到私有目录并在测试后卸载;截图和结果保留在 `.desktop-build/installer-tests/` 下。检查包含末尾带分隔符的已登记路径升级,以及磁盘根目录拒绝。可选的 `--signed` 标志使用[Windows EV 配置](windows-signing/README.zh.md#signing-configuration),在嵌入前对测试程序和辅助库签名;它不会启用更新源。 Windows 卸载程序会随应用一起删除 Electron 用户数据目录(`%APPDATA%` 下按包作用域嵌套的浏览器存储与缓存)、`%APPDATA%` 下的产品目录,以及 `%LOCALAPPDATA%` 下的更新下载缓存,随后移除 `%APPDATA%` 之下普通且已空的作用域目录。Harness 主目录(`~/.dsh` 或 `DSH_HOME`:会话、设置、凭据、插件)不会被触碰;以 Windows 环境变量发布的 `DSH_HOME` 还会保护所有与其重叠的目标。静默卸载删除相同的数据;以 `--updated` 或 `/KEEP_APP_DATA` 启动的卸载程序保留数据,electron-builder 在原地更新和从其他目录替换旧安装时正是这样启动它。删除通过原生辅助程序执行:它拒绝受保护的 Windows 目录以及与安装目录或主目录重叠的路径,要求固定的本地驱动器,链接的根目录或祖先目录原样保留,遇到重解析点只解除链接而不进入目标,清除只读属性,并在遇到被占用文件后继续删除其余兄弟项;残余不会中止卸载,也不会提示。安装时在 Windows 卸载注册项上记录 `InstallLocation` 作为标准的清单元数据;在 Windows 11 上,开始菜单右键菜单中的“卸载”对所有 Win32 应用都会打开已安装应用列表,只有 MSIX 包能从那里直接卸载。卸载程序声明 DPI 感知,中文使用微软雅黑 UI。此行为仅适用于 Windows。 使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译独立的中英文夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 和 `DSH_HOME` 位于 Electron 数据内的检查。编译本身不能证明已安装卸载行为。 -### Windows EV 签名 - -运行时签名在当前 Windows 账户的各 worktree 间共享完整的已签名文件。`.env.windows` 中的 `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR` 指定固定本地磁盘上的绝对目录;默认值为 `%USERPROFILE%\.dsh-desktop-signing\signature-cache\v1`。缓存目录必须属于当前账户,访问权限不得向其他普通账户开放;带链接的路径会被拒绝。缓存项标识原始字节、公钥证书和签名工具链。每次恢复都检查摘要、Windows 信任状态、时间戳和证书,再替换未签名文件;缓存项无效会停止打包,不回退到硬件签名。不会仅因缓存较旧而重新签名。缓存信任同账户运行的程序,不防御管理员。[运行时签名缓存决策](../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md)定义验收要求和设计限制。 - -预检、主要运行时签名、应用运行时签名和产物生成分别持有账户级签名阶段锁,直到受监督的子进程结束。其他构建进入这些阶段前等待;编译和准备步骤不持锁。运行时签名进程自行持锁,因此仅终止外层打包进程不会释放仍在访问缓存的阶段锁。迁移及维护获取同一把锁;旧版或外部签名命令不参与排队,应另行避免并发。阶段等待不计入预检期限。关闭阶段句柄会释放普通竞争锁,不删除独立的硬件尝试互锁;遗留硬件失败仍需操作人员恢复。 - -缓存命中的复制、摘要和逐文件信任检查使用 `.env.windows` 中的 `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY` 个工作任务(默认 `4`,整数 `1`–`8`)。所有恢复及后置验签完成后,未命中项才进入串行硬件签名。恢复或验签失败会停止派发新任务,并在释放阶段锁前等待在途工作结束;硬件签名、运行时 smoke 检查和最终完整性校验仍须执行。 - -每个运行时阶段向标准输出及打包日志写入 `SIGNATURE_CACHE_SUMMARY`,包含实际目录、策略标识、命中及未命中数、新发布及保留项数、签名请求数、省去的签名请求数和验证失败数。计时区分签名、恢复文件和新签名文件的信任验证及恢复;恢复耗时包含其信任检查和暂存清理。这些统计不包含预检、最终产物签名及外层运行时验签。阶段锁事件单独记录等待时间。 并发计时累加逐文件工作耗时,不代表阶段墙钟时间。 - -使用 `pnpm --dir apps/desktop run cache:windows-signatures --usage` 查看结构完整的缓存项字节数和数量,或用 `--from ` 导入显式指定、属于同账户的旧缓存。迁移不修改源目录,跳过暂存名称,拒绝损坏项,并保留已有有效项,即使它们的时间戳字节不同。`--clear` 在阶段锁保护下显式删除完整缓存项;不执行自动容量淘汰。`--directory ` 指定维护目标目录,无需加载发布凭据。不完整暂存项保持原状并单独计数;仅在所有构建停止后检查它们。这些命令绝不清除硬件失败证据。默认存储位于 AppData 之外,避免 MSIX 启动器虚拟化将账户缓存拆开;被重定向的覆盖目录会明确失败。 - -Windows 签名构建在编译或准备依赖前执行受监督的签名预检。静态配置、证书有效期、审计存储、编译器可用性及遗留签名锁的检查不访问 Token。本地 .NET Framework C# 编译器生成一个专用小探针,由正式签名器仅签名一次,随后必须验出配置的证书和时间戳才能继续构建。探针绝不执行。预检的整体 60 秒期限包含时间戳尝试;超时、硬件签名报错或验签失败都会停止本轮流程,不再次调用硬件。成功只证明当前签名路径可用,不证明 PIN 已独立认证:SafeNet 可能复用登录状态。不要为了验证 PIN 而注销或重复认证。`--check`、仅准备和 `--unsigned` 模式不执行此硬件预检;未签名产物仍不能发布上传。自动回归测试使用假签名器,真实硬件由发布操作人员单独验收。 - -Windows NSIS 上传要求安装包旁存在生成的非空 `.exe.blockmap`。blockmap 先于通道 YAML 上传;NSIS 安装包元数据不要求另一种 web-installer 格式使用的内嵌 `blockMapSize`。文件清单测试使用固定版本构建器的 blockmap 生成器,而不是手工编造内嵌映射字段。 - -签名 Windows 配置从同一份公开证书的 `CN`、`O` 和 `C` 属性生成 updater 的 `publisherName`。每个属性都必须存在、非空且只有一个值。这些身份属性允许证书续期,无需固定叶证书指纹。已安装应用的 `app-update.yml` 保存预期发布者,下载的清单不能选择该身份。未签名测试构建省略 updater 配置。真实文件验证及其限制见[签名验收记录](tests/README.zh.md)。 - -本项目使用的 SafeNet Token 出现 `SignTool Error: No private key is available.` 时,说明 PIN(密码)错误。立即停止所有签名尝试,等待用户处理 PIN 后再继续。PIN 输错达到五次会锁定 Token。遇到该错误后,不得重试打包或签名探针。签名器串行执行 Token 操作,首次失败后拒绝所有排队任务。 - -Windows 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `.desktop-build/packaging-runs/` 下的唯一目录。每次运行保留 `run.json`、带时间戳的 `events.jsonl`、脱敏后的 `stdout.log` 和 `stderr.log`,以及 `result.json`。签名失败还会写入 `fatal.json` 并通过 stderr 通知父进程;监督程序立即请求终止当前阶段的进程树并等待退出。失败阶段不能启动后续阶段或生成发布完成记录。日志写入失败也会停止运行。终止错误仍按失败处理,需要操作者检查;缺少最终记录表示尚未确认完成。 - -硬件签名必须属于受监督的打包运行。调用命令解释器前,签名器原子获取 `%USERPROFILE%/.dsh-desktop-signing/attempt.json` 并记录本次尝试。只有签名成功且配置证书的主签名通过验证后才释放该文件;随后完成时间戳,不再访问硬件。失败、中断、已有锁定文件或审计存储不可用都会阻止再次访问硬件,包括同一 Windows 账户下的另一个签名器实例、进程或代码检出目录。没有定时恢复或自动重试。管理员必须检查保留的证据及令牌状态,再明确授权恢复锁定状态;登录令牌或替换 PIN 文件不会清除它。记录区分签名意图、命令解释器 PID 和完成结果,不计量 CSP/令牌内部的认证次数。不记录命令参数、PIN 或凭据环境。其他 Windows 账户及无关签名程序不在此锁定机制的保护范围内。 - -Windows 打包将 7-Zip 过滤器固定为 `BCJ`,以兼容内置的 NSIS 解码器。这样可以保留 x64 安装包中由依赖携带的 ARM64 二进制文件;自动 ARM64 过滤会生成该解码器无法解压的条目。 - -NSIS 在安装阶段清理临时解压目录,完成后才显示完成页或自动启动应用。已安装的生产依赖保持为普通文件;启动时不会再次解压。安装仍会写入完整的应用目录树。 - -在 `.env.windows` 中填写 `DSH_DESKTOP_WINDOWS_CER_FILE`(公开 EV 叶证书)、`DSH_DESKTOP_WINDOWS_SIGNTOOL`(SafeNet 兼容的 SignTool)、`DSH_DESKTOP_WINDOWS_KEY_CONTAINER`(匹配的私钥容器)和 `DSH_DESKTOP_WINDOWS_TOKEN_PIN`(Token Password)。私钥仍保留在 USB Token;不要把证书或本地凭据文件提交到 Git。 - -```sh -pnpm run package:desktop:win:x64 -``` - -打包前插入并解锁 Token。electron-builder 钩子把每个产物交给采用 CRLF 的 `scripts/windows-sign.cmd`;该 CMD 只调用一次已配置的 SignTool,并指定 `/f`、SafeNet `/kc "[{{PIN}}]=容器"`、`/csp "eToken Base Cryptographic Provider"`和 SHA-256 文件摘要,不请求时间戳。随后钩子在隔离副本上完成 DigiCert SHA-256 RFC 3161 时间戳,不传递签名凭据。钩子不会改用 electron-builder 内置的 SignTool,也不会重试失败的签名请求。SignTool、证书、容器、PIN、Token 或签名不可用时,Windows 发布打包会失败,不会生成未签名产物。 - -时间戳处理仅对正常退出但返回失败或警告的时间戳命令重试,最多尝试三次,间隔为一秒和两秒。每次均从同一份已验证的主签名开始。启动错误、终止状态不确定或验签失败会立即停止。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 尝试次数;签名仍在首次失败后停止整批任务。 - -使用对应的 `:dir` 命令可以生成可直接运行的应用目录,而不是安装包,例如: - -```sh -pnpm run package:desktop:dir -pnpm run package:desktop:mac:arm64:dir -``` - -需要检查或诊断为宿主目标准备的资源而不调用 electron-builder 时,可以让同一流水线在准备完成后停止: - -```sh -pnpm run prepare:desktop -``` - -这条诊断命令是另一种停止位置,并非两条命令构建流程的前半段。之后执行 `package:desktop*` 时仍会重新完成正式构建与准备,避免使用陈旧的 dsh 包、运行时文件或 dsh 内容。 - -每条打包命令都会构建仓库,打包以 dsh 和私有 Desktop Host 为根的第一方生产依赖闭包,并准备目标专用的 Electron 分发包与 pnpm CLI。`prepare:dsh` 在构建时安装一次生产依赖图,准备物化包供 electron-builder 归档到 `app.asar/dsh`,移除包管理器元数据,并生成包含共享包版本和最终文件哈希的 `desktop-runtime.json`。macOS 签名构建先签名并验证原生文件,再生成清单;electron-builder 不对已签名的此目录重复进行嵌套签名。资源映射明确包含默认根目录过滤器会忽略的 `dsh/node_modules`;准备完成的运行时清单在原生签名后检查。原生可执行文件及库解包到 ASAR 旁;Python、独立 Node 和 pnpm 保留在外部 runtime 资源中。Windows 打包逐项检查准备好的 PE,确认其 ASAR 条目已标记为解包,且磁盘副本字节一致;未签名构建也执行此检查。Builder glob 规则用单字符通配符匹配 PE 文件名中的花括号,因此同目录中名称匹配的文件也可能被解包。准备好的运行时 smoke 沿用已验证的目标描述符,不使用构建宿主的架构。签名安装包、公证、已安装应用升级和各目标原生模块的验收需要发布环境。 - -macOS 签名打包在组装 App 时、代码签名前写入 `Contents/Resources/app-update.yml`,供并行 ZIP 与 DMG 路线使用的目录构建也执行此操作。签名钩子验证准确的更新源和 updater 缓存目录。写入发布完成记录前,流程会再次检查两条路线的副本和最终移入的 App;配置缺失或不匹配会阻止移入产物,因而也会阻止上传。 - -未压缩产物包含 Electron、物化后的 dsh 生产依赖树、pnpm,以及壳应用。安装包大小与文件系统占用不同;发布验收需要测量两者,以及 profile 插件存储和首次启动耗时。此布局用更多应用内文件换取消除用户机器上的核心包安装过程。 + ## 更新 @@ -437,7 +269,7 @@ Windows 下载完成后的更新确认说明应用会在安装期间关闭、完 原生更新浮层在文档就绪且父窗口可见时显示,并在父窗口再次显示时恢复。关闭浮层会释放输入拦截和父窗口监听。[本地窗口验证](tests/README.zh.md#verification-overlay)无需启动工作区即可检查这些切换。 -打包应用在启动后异步检查固定 Nightly。常规轮询以十分钟为基础间隔,每次独立采样 ±20% 的随机抖动。每次检查失败将基础延迟翻倍,上限为一小时;成功后重置。随机延迟不超过该上限,并从全部复用调用结算后开始计时。本地化的“检查更新…”菜单项(Windows 可从顶栏的“应用”菜单进入)立即执行,并复用正在进行的检查。回到前台和系统恢复时遵守相同的单调时钟截止时间。新收到的强更策略也会立即请求检查更新清单。自动检查从不弹窗或下载安装包。手动检查显示正在检查、失败或包含已安装版本号的无更新反馈。常规更新弹窗原位渐入渐出;连续弹窗替换卡片内容并重置其滚动位置,保留黑色半透明蒙层,不模糊父页面。 +打包应用在启动后异步检查固定 Nightly。常规轮询以十分钟为基础间隔,每次独立采样 ±20% 的随机抖动。每次检查失败将基础延迟翻倍,上限为一小时;成功后重置。随机延迟不超过该上限,并从全部复用调用结算后开始计时。本地化的“检查更新…”菜单项(Windows 可从顶栏的“应用”菜单进入)立即执行,并复用正在进行的检查。回到前台和系统恢复时遵守相同的单调时钟截止时间。新收到的强更策略也会立即请求检查更新清单。自动检查从不弹窗或下载安装包。手动检查显示正在检查、失败或包含已安装版本号的无更新反馈。常规更新弹窗原位渐入渐出;连续弹窗替换卡片内容并重置其滚动位置,保留黑色半透明蒙层,不模糊父页面。Windows 在销毁模态窗口前先隐藏它,确保原生窗口激活切换前父窗口已恢复启用。 `DSH_DESKTOP_UPDATE_CHECK_INTERVAL_MS` 配置常规基础间隔,`DSH_DESKTOP_UPDATE_CHECK_MAX_BACKOFF_MS` 配置上限;两者均接受 1000 至 2147483647 的整数毫秒数,且上限不能小于间隔。省略上限时取一小时与间隔中的较大值。`DSH_DESKTOP_UPDATE_CHECK_JITTER` 配置 0 至 1 的抖动比例,默认 `0.2`;最终延迟至少一秒,且不超过上限。这些配置不改变强更策略轮询,也不授权下载重试。 @@ -447,6 +279,26 @@ Windows 下载完成后的更新确认说明应用会在安装期间关闭、完 已确认 Host 退出但任务未成功收尾时,常规与强更弹窗均展示本地化恢复提示。两种语言都根据类型化的准备失败原因选择提示,翻译文案变化不会改变失败分类。“查看技术详情”默认折叠,仅展示退出状态、信号、关闭确认和截止时间事实,不展示插件 stderr。展开详情既不重试,也不授权安装。 + + +### 本地桌面设置 + +[壳层配置决策](../../.agents/notes/implemented/architecture/2026-10-08-desktop-shell-configuration.zh.md)说明独立于 Host 的配置归属,以及评估现有设置迁移的标准。 + +Electron 主进程在启动时读取一次 `app.getPath('userData')/desktop/settings.json`,独立于 Host 和 Cordis 配置。打包应用默认路径为 Windows 的 `%APPDATA%\@deepseek-ai\dsh-desktop\desktop\settings.json` 和 macOS 的 `~/Library/Application Support/@deepseek-ai/dsh-desktop/desktop/settings.json`。开发模式使用启动器打印的 `userData` 路径。`DSH_HOME` 不改变此文件的位置。 + +首次启动(包括升级后首次启动)时,Desktop 会在文件缺失时创建以下内容: + +```json +{ + "updates": { + "allowTestAuthPopupWindow": false + } +} +``` + +已有文件不会被覆盖;缺少 `updates` 对象或该字段时均按 `false` 处理。将字段设为 `true` 后完全退出并重启应用,即可允许测试鉴权弹窗。改回 `false` 并重启即可再次禁止。创建、读取或校验失败时使用默认值 `false`,不阻止启动。Desktop 尝试在 Electron 控制台记录包含文件路径的警告;日志不可用也不阻止启动。修正文件并重启后才会应用显式设置。未知字段会保留。安装更新保留此用户数据文件;Windows 卸载按[卸载规则](#windows-uninstall-rules)删除它。 + ### 强制更新策略 @@ -468,7 +320,9 @@ Windows 下载完成后的更新确认说明应用会在安装期间关闭、完 时长必须是 1000 至 2147483647 毫秒的整数。启动与定时轮询独立于业务请求;前台/恢复检查遵守下次到期时间,手动检查绕过该时间并复用在途请求。客户端发送已安装平台、架构、DSH_CLIENT_VERSION、内置 dsh 版本、当前语言与 UTC 偏移、空 bundle ID 和固定 Nightly。不使用业务登录凭据或安装 ID。 -启用 `feishu-test` 时,包含 `error.code: "UNAUTHENTICATED"` 的 HTTP 401 JSON 响应会在用户主动检查和打包应用首次启动检查时提供登录入口,不等待本地后端就绪。本地化说明指出这是测试版、需要飞书鉴权,且登录不会下载或安装更新。确认后先关闭说明,再打开配置源站根路径的沙箱窗口,不使用响应中的登录 URL。并发检查复用整个确认/登录流程,并聚焦已有窗口。在测试环境登录窗口按 F12 可打开独立的 DevTools 进行排查。取消后,定时或前台检查不会反复弹窗;用户可手动重试。 +启用 `feishu-test` 时,包含 `error.code: "UNAUTHENTICATED"` 的 HTTP 401 JSON 响应仅在本地 `updates.allowTestAuthPopupWindow` 为 `true` 时提供登录入口。该字段默认为 `false`,禁止启动、手动检查更新、强更刷新以及延迟或重复失败触发的整个鉴权弹窗流程。测试网关 Cookie 仅在当前进程有效。启动时关闭弹窗后,需要鉴权的网关无法在本次进程中提供新的强更决策;需开启设置、重启并登录后才能获取。策略请求仍需网关鉴权,鉴权失败不会解除已知强更阻塞。常规更新和产品账号鉴权保持独立。正式环境始终使用原有匿名策略请求,不受此设置影响。 + +允许弹窗时,用户主动检查和打包应用首次启动检查会提供登录入口,不等待本地后端就绪。本地化说明指出这是测试版、需要飞书鉴权,且登录不会下载或安装更新。确认后先关闭说明,再打开配置源站根路径的沙箱窗口,不使用响应中的登录 URL。并发检查复用整个确认/登录流程,并聚焦已有窗口。在测试环境登录窗口按 F12 可打开独立的 DevTools 进行排查。取消后,定时或前台检查不会反复弹窗;用户可手动重试。 登录和策略请求共用内存 Session,与产品窗口及 updater 隔离;应用重启后需要重新登录。关闭窗口取消登录,导航失败提供本地化重试提示。返回服务后重新查询策略;重定向、Cookie 或 HTTP 422 都不是有效策略决定。取消、登录过期及无效响应均保留已知强更阻塞。固定登录结果写入进程诊断及可选更新日志;登录控制器不记录 Cookie、OAuth 参数或远程错误原文。真实 Harness 网关/API 联调及 macOS 登录验收仍未完成。 @@ -492,10 +346,14 @@ node apps/desktop/node_modules/pnpm/bin/pnpm.mjs --dir apps/desktop run test:upd 下载内容是不可执行的测试字节,安装调用仅记录而不执行。测试替换浏览器打开与剪贴板写入,避免外部导航和剪贴板修改。它不启动完整产品工作区,不验证真实安装器或重启,不验证发布者签名,也不覆盖差分更新或 macOS。停滞的策略请求、清单请求和负载传输会执行真实截止时间及恢复。真实常规弹窗验证隔离预加载、卡片尺寸、未施加模糊的父页面、取消、任务警告选项与显式安装批准;账户行组件测试另行提供证据。[本地验证决策](../../.agents/notes/implemented/testing/2026-09-10-desktop-local-updater-qualification.zh.md)和[验证记录](tests/README.zh.md)保留这些限制;生产发布要求保持不变。 + + ## 底层开发覆盖项 未打包的 Electron 进程使用应用目录下的 `.desktop-build/development/project` 作为开发项目。`DSH_DESKTOP_PNPM_ENTRY` 和 `DSH_DESKTOP_DSH_DIR` 是带应用路径默认值的可选覆盖项。每次未打包启动都必须设置 `DSH_DESKTOP_PRIMARY_RUNTIME_DIR`:开发启动器(`dev:desktop`、`start:desktop` 及工作区更新验证运行器)会把它设置为自己已准备目标的 primary-runtime 目录;缺少该变量的启动会以致命启动对话框失败。启动器必须设置它,因为壳无法从 `process.arch` 推导该目录:构建目标将 Windows 固定为 x64,而宿主可能是 arm64。打包应用会忽略这些变量,从 `process.resourcesPath` 解析签名资源,并使用受管 Desktop profile。 + + ## 已知限制 - 账号登录尚未接入;登录按钮禁用。Windows 材质效果仍需平台验证。 @@ -519,6 +377,8 @@ node apps/desktop/node_modules/pnpm/bin/pnpm.mjs --dir apps/desktop run test:upd 账号提供者的 `embeddedPageDist` 配置为内嵌用量和充值页面 URL 添加 `dist` 查询参数。默认值为空;私有前端分支选择值应写在本地 profile patch 中。此配置不改变 API 地址或凭证传递方式。 + + ## 开发备注 上线前 CDN 与容量决策见[桌面更新提案](../../.agents/notes/proposed/feature/2026-09-08-desktop-update-policy-and-installation.zh.md#cdn-and-capacity-qualification)。 diff --git a/apps/desktop/config/macos-packaging/macos-signing.env.example b/apps/desktop/config/macos-packaging/macos-signing.env.example new file mode 100644 index 0000000000..b4ec0dbe3f --- /dev/null +++ b/apps/desktop/config/macos-packaging/macos-signing.env.example @@ -0,0 +1,9 @@ +# Copy to macos-signing.env with mode 0600; keep this directory outside the runner checkout. +DSH_DESKTOP_MACOS_SIGNING_IDENTITY= +DSH_DESKTOP_MACOS_TEAM_ID= +CSC_LINK=../certificates/developer-id.p12 +CSC_KEY_PASSWORD= +# Configure exactly one notarization strategy; this template uses an App Store Connect API key. +APPLE_API_KEY=../certificates/notarization.p8 +APPLE_API_KEY_ID= +APPLE_API_ISSUER= diff --git a/apps/desktop/config/macos-packaging/production.env.example b/apps/desktop/config/macos-packaging/production.env.example new file mode 100644 index 0000000000..18360eadef --- /dev/null +++ b/apps/desktop/config/macos-packaging/production.env.example @@ -0,0 +1,9 @@ +# Copy to production.env and configure the production service before selecting this preset. +DSH_DESKTOP_APP_ID=com.deepseek.harness +DSH_DESKTOP_AUTO_UPDATE_ENV=production +DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN= +DSH_DESKTOP_MACOS_PACK_CONCURRENCY=4 +DSH_DESKTOP_MACOS_DOWNLOAD_PROXY= +DSH_DESKTOP_MACOS_NOTARIZATION_PROXY= +# Optional absolute private directory; setup fills this in for machine presets. Omit to use checkout-local storage. +# DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR= diff --git a/apps/desktop/config/macos-packaging/test.env.example b/apps/desktop/config/macos-packaging/test.env.example new file mode 100644 index 0000000000..aa40a119ce --- /dev/null +++ b/apps/desktop/config/macos-packaging/test.env.example @@ -0,0 +1,14 @@ +# Copy to test.env; paths in secret configuration resolve beside macos-signing.env. +DSH_DESKTOP_APP_ID=com.deepseek.harness +DSH_DESKTOP_AUTO_UPDATE_ENV=test +DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN= +DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{"allowedAuthOrigins":["https://login.example.com"]}' +DOWNLOAD_TEST_ORIGIN= +# Generate a 32-character lowercase hexadecimal release ID; retain it for upgrade testing. +DOWNLOAD_TEST_RELEASE_ID= +DSH_DESKTOP_MACOS_PACK_CONCURRENCY=4 +DSH_DESKTOP_MACOS_DOWNLOAD_PROXY= +# Temporarily changes the active network service's system HTTP/HTTPS proxies. +DSH_DESKTOP_MACOS_NOTARIZATION_PROXY= +# Optional absolute private directory; setup fills this in for machine presets. Omit to use checkout-local storage. +# DSH_DESKTOP_MACOS_SIGNATURE_CACHE_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/electron-builder.config.d.mts b/apps/desktop/electron-builder.config.d.mts index 4e978ec00f..0682e6e9ad 100644 --- a/apps/desktop/electron-builder.config.d.mts +++ b/apps/desktop/electron-builder.config.d.mts @@ -9,10 +9,7 @@ export interface DesktopElectronBuilderConfig { readonly output: string } readonly files: readonly [ - string, - string, - string, - string, + ...string[], { readonly from: string, readonly to: 'dsh', readonly filter: readonly ['**/*'] }, { readonly from: string, readonly to: 'dsh/node_modules', readonly filter: readonly ['**/*'] }, ] @@ -33,6 +30,7 @@ export interface DesktopElectronBuilderConfig { readonly signIgnore: readonly string[] } readonly dmg: { + readonly format: 'ULMO' readonly sign: boolean readonly writeUpdateInfo: boolean } diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 0a84d09e6f..34e859cd20 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-desktop", "description": "Electron desktop shell for a bundled dsh runtime and external plugins", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "private": true, "license": "MIT", "type": "module", @@ -60,23 +60,21 @@ "@types/js-yaml": "^4.0.9", "@types/node": "^22.20.1", "@types/semver": "^7.8.0", - "app-builder-lib": "26.15.3", + "app-builder-lib": "26.17.0", "cos-nodejs-sdk-v5": "3.0.0", - "electron": "^44.0.0", - "electron-builder": "^26.15.3", + "electron": "^44.7.0", + "electron-builder": "^26.17.0", "extract-zip": "^2.0.1", "js-yaml": "^4.3.2", "koffi": "3.1.1", "pnpm": "11.28.5", - "sharp": "^0.35.5", + "sharp": "0.35.5", "typescript": "^6.0.3", "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@types/ws": "^8.18.1", "@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/packaging/README.i18n.yaml b/apps/desktop/packaging/README.i18n.yaml new file mode 100644 index 0000000000..40103064d6 --- /dev/null +++ b/apps/desktop/packaging/README.i18n.yaml @@ -0,0 +1,58 @@ +# 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 apps/desktop/packaging/README.md +/: + en: 9bc7767fc1bced33 + zh: 4f6198337a573cf4 +/desktop-packaging: + en: b35e10c88ade04fe + zh: a2d09add03407b91 +/desktop-packaging/summary: + en: e98e516b9e1bd0f4 + zh: 1a2abd7d89ef78a1 +/desktop-packaging/table-of-contents: + en: a6203dc2e690c7e1 + zh: 07b516549b8e3328 +/desktop-packaging/choose-a-build-path: + en: 17c6bcdefa05a8f8 + zh: 4ee18f832276144d +/desktop-packaging/release-versions: + en: 3f38ab26ee195b39 + zh: f00eddafa8f3b9ca +/desktop-packaging/configuration-and-local-builds: + en: f5dc36baf414ecc5 + zh: 8984741b356ac1d3 +/desktop-packaging/windows-actions-packaging: + en: e3f51e7130a0fe05 + zh: 70fd6a40d5899871 +/desktop-packaging/macos-self-hosted-packaging: + en: a3af9523fdc60036 + zh: 5e18d4740e9b7f57 +/desktop-packaging/unsigned-windows-test-installer: + en: 6843a0fdc03ead58 + zh: 957f92fc8126e23e +/desktop-packaging/local-macos-dmg-without-release-signing: + en: 2feaa0412247d81f + zh: 461dde8e13fd4734 +/desktop-packaging/macos-release-signing-and-diagnostics: + en: 62c125856aa03c26 + zh: 9fc00a43c8b1e8e2 +/desktop-packaging/directory-builds-and-preparation: + en: 30d58517c9c2044f + zh: 16d26bdc923fc4ba +/desktop-packaging/local-official-bundles-from-a-loopback-registry: + en: b42f103358d0dfd7 + zh: a534164ad9eb00da +/desktop-packaging/runtime-file-selection-and-installation-checks: + en: 06d5c666a3e7f2e4 + zh: c1d4a55cc29e11e3 +/desktop-packaging/desktop-runtime-preparation: + en: a7aa3066e649ffe8 + zh: 4334637910058c09 +/desktop-packaging/installation-and-release-verification: + en: 0006b6b1ae4998f4 + zh: 2bab6918b0c37b25 +/desktop-packaging/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/apps/desktop/packaging/README.md b/apps/desktop/packaging/README.md new file mode 100644 index 0000000000..9cf46b68e1 --- /dev/null +++ b/apps/desktop/packaging/README.md @@ -0,0 +1,275 @@ +--- +description: "Build Desktop installers locally or through Windows or macOS Actions, choose deployment and signing mode, and retrieve artifacts and diagnostics. This guide keeps build operations separate from publishing and installed-application qualification. Platform signing details and shared-runner risks must be checked before using hardware credentials." +--- + +# Desktop packaging + +English | [中文](README.zh.md) + +## Summary + +Build Desktop installers locally or through Windows or macOS Actions, choose deployment and signing mode, and retrieve artifacts and diagnostics. This guide keeps build operations separate from publishing and installed-application qualification. Platform signing details and shared-runner risks must be checked before using hardware credentials. + +## Table of Contents + +- [Choose a build path](#choose-a-build) +- [Release versions](#release-versions) +- [Configuration and local builds](#configuration-and-local-builds) +- [Windows Actions packaging](#windows-actions) +- [macOS self-hosted packaging](#macos-actions) +- [Unsigned Windows test installer](#unsigned-windows-test-installer) +- [Local macOS DMG without release signing](#local-macos-dmg-without-release-signing) +- [macOS release signing and diagnostics](#macos-release-signing) +- [Directory builds and preparation](#directory-and-preparation) +- [Local Official bundles from a loopback registry](#local-official-bundles-from-a-loopback-registry) +- [Runtime file selection and installation checks](#runtime-file-selection) +- [Desktop runtime preparation](#desktop-runtime-preparation) +- [Installation and release verification](#verification) + + + +## Choose a build path + +Run local commands from the repository root after installing locked dependencies. Use platform-specific commands for a local build, or platform Actions for the registered self-hosted runner. Choose test or production deployment independently from signed or unsigned mode. Read [Windows signing and runner operations](../windows-signing/README.md#trust-and-isolation) before any Windows signed build or shared-runner use. Installation is separate from packaging; [publication](../publishing/README.md) is a further explicit operation. + + + +## Release versions + +Before each Desktop packaging run, first confirm the complete version string with the current user. Check the selected deployment, dsh base version, retained release records, and published objects, then propose the exact version for approval. Do not start packaging until the user confirms that version; the deployment setting alone does not authorize a version choice. + +Record the current dsh version as the base. A production Desktop release uses that exact version, including any `alpha`, `beta`, or `rc` identifiers. A test release preserves the complete prerelease base and appends `.YYYYMMDD.index`; a stable base uses `-test.YYYYMMDD.index` instead. + +| dsh base | Production Desktop | Test Desktop example | +|---|---|---| +| `0.1.6-alpha.1` | `0.1.6-alpha.1` | `0.1.6-alpha.1.20260916.1` | +| `0.1.6-beta.2` | `0.1.6-beta.2` | `0.1.6-beta.2.20260916.1` | +| `0.1.6-rc.3` | `0.1.6-rc.3` | `0.1.6-rc.3.20260916.1` | +| `0.1.6` | `0.1.6` | `0.1.6-test.20260916.1` | + +Use the actual creation date in Asia/Shanghai. For each base and date, start the index at 1 and increment after checking retained release records and published objects; never reuse a published version. Test distribution does not publish the corresponding unsuffixed base. + +Manual Desktop CI uses a separate unpublished build identifier: `auto` appends the UTC date, workflow run number and attempt (`.YYYYMMDD.run.attempt`, with `-test` for a stable base). For example, `0.2.1-alpha.1.20261008.42.2`. These numbers are not reserved release sequence numbers. + +Pass the confirmed version to the packaging command as `--build-version`, which reaches the artifact names, the update feed, and the upload validation as one value. The manifests keep the product version, so a test build no longer rewrites the release family and leaves nothing to revert: + +```sh +pnpm --dir apps/desktop run package:win:x64 --build-version 0.1.6-alpha.1.20260916.1 +``` + +`--build-version auto` proposes the next index for today, reading the published objects in the destination bucket and falling back to this target's local output directory when no bucket is configured or the listing cannot finish within its deadline. Confirm the proposal it prints before an upload; a run script forwards `--` on its own, and the packaging entry accepts it either way. + +A production release publishes the product version and takes no `--build-version`. Uploading one tags the packaged commit as `desktop-v` once the artifacts are public; a build from a modified checkout is not tagged, and a tagging failure prints the command to run by hand rather than failing a completed upload. Test and local builds are deliberately left untagged, and every artifact records `dshBuildCommit` and `dshBuildDirty` in its manifest so a build handed over directly remains traceable. + +The installer embeds `DSH_DESKTOP_UPDATE_CHANNEL` (`nightly` by default, or `latest`) independently of version and deployment. Automatic updates remain on that channel even for a stable version; manually installing the other channel switches it. Latest packages reject prerelease versions. A stable product can produce a nightly `-test..` build, but that version ranks below the stable base and cannot upgrade an already installed higher version. Keep automatic downgrade disabled; stable corrective releases require a product version bump. CI version selection and publication are documented in [CI publication](../publishing/ci/README.md#package-and-publish). + + + +## Configuration and local builds + +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. + +Both manual packaging workflows accept `test_release_id`. Blank uses the machine preset; a nonblank value must contain 32 lowercase hexadecimal characters and requires the test preset. The loader applies it through `PACKAGE_TEST_RELEASE_ID` without changing the preset file. Keep the same value for successive upgrade tests on that platform. Rotating the default affects future builds only: installed clients retain their original update address, and old objects remain accessible until separately removed. A random prefix reduces discoverability but does not authenticate downloads. + +Outside machine-preset mode, packaging, upload, and manual macOS signature verification (except local unsigned macOS builds) 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 the same machine presets. + +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 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 +``` + +`prepare:desktop` is not a prerequisite: + +```sh +pnpm run package:desktop +``` + +Release automation uses fixed target commands so runtime preparation, dsh preparation, and electron-builder receive the same platform and architecture: + +```sh +pnpm run package:desktop:mac:arm64 +pnpm run package:desktop:mac:x64 +pnpm run package:desktop:win:x64 +``` + +The macOS arm64 command requires Apple Silicon. The macOS x64 command runs on Intel macOS or Apple Silicon with Rosetta. The Windows x64 command requires Windows x64. Linux is not a supported Desktop release target. + +Both release and local unsigned macOS DMGs use LZMA compression (`dmg.format: 'ULMO'`) in [the electron-builder configuration](../scripts/electron-builder-config.mjs). A [build-time patch](../../../patches/app-builder-lib@26.17.0.patch) adds this format to the pinned builder's validation and TypeScript declarations. + +Each target owns its packed package inputs, prepared runtime, package set, dsh tree, pnpm preparation state, unpacked application, update metadata, and final artifacts under `apps/desktop/.desktop-build/targets//`. The Electron archive cache remains shared under `.desktop-build/downloads` because every archive name includes its version, platform, and architecture and is verified before extraction. A target build never consumes another target's mutable preparation state. + + + +## Windows Actions packaging + +The `Package Desktop · Windows` [manual 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. + +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. + +Open the completed run in Actions and download its Artifacts. `windows-x64-signed---` and `windows-x64-unsigned---` contain the corresponding EXE; `windows-package-logs--` contains packaging diagnostics. The upload steps are `Retain verified signed installer`, `Retain verified unsigned installer`, and `Retain packaging diagnostics`; their step durations and timestamped logs show upload time. These artifacts are not a Release or download-site publication. + + + +## macOS self-hosted packaging + +The `Package Desktop · macOS` [manual workflow](../../../.github/workflows/macos-package.yml) targets an Apple Silicon runner labeled `dsh-mac-package-trial`. It selects `test` or `production`, resolves `build_version=auto` from the UTC date, run number and attempt, and uses the existing signing, notarization and packaged-runtime checks. Successful DMG/ZIP files and diagnostic logs are retained for 14 days; this workflow does not publish a release. The operator must register the runner and verify a complete Actions run before relying on it. + +Run `node apps/desktop/scripts/setup-macos-packaging.mjs "$HOME/dsh-ci"` to prepare private `runner/`, `packaging/{presets,secrets,certificates}` and `cache/macos-signatures` directories without overwriting existing files; append `--check` to inspect them. Fill the [preset](../config/macos-packaging/test.env.example) and [signing](../config/macos-packaging/macos-signing.env.example) templates outside the checkout. Set secret and certificate files to mode `0600`. `DSH_PACKAGING_CONFIG_DIR` selects the absolute `packaging` directory and `DSH_PACKAGING_PRESET` selects its preset; missing files fail without falling back to `.env.macos`. Signed and preparation-only Mac builds read `secrets/macos-signing.env`; relative credential paths resolve beside that file. Public presets reject signing credentials, and signing files cannot override public settings. Local unsigned Mac builds retain their configuration-free behavior. + +Run `bash apps/desktop/scripts/start-macos-packaging-runner.sh "$HOME/dsh-ci/runner" "$HOME/dsh-ci/packaging" --check` to check the host tools and configuration files. The script selects the active Xcode and its macOS SDK together and compiles a small linker probe. After registration, omit `--check` to run in the foreground with a cleared inherited environment and prevent idle sleep while the runner is alive. Stop it with Ctrl-C before installing the service below. The runner owns its `_work` checkout, separate from daily development. The account can read its signing files, so run only trusted code. The existing notarization proxy restoration rules apply; after forced termination, inspect retained recovery records before another build. New setup templates set `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` to the absolute `cache/macos-signatures` directory outside checkout. For existing installations, rerun setup and add that field to each preset; existing files are preserved. This retains signatures across clean checkouts; cache verification and limits are described under [macOS signing](#macos-release-signing). + + +The `skip_notarization` workflow option defaults to `false`; the equivalent CLI flag is `--skip-notarization`. It retains Developer ID signing, DMG signature verification and packaged-runtime verification, but omits Apple notarization and stapling and does not require Apple notarization credentials. DMG/ZIP filenames carry `-unnotarized`, are stored under `.desktop-build/targets//unnotarized-artifacts/`, and are uploaded with an `unnotarized-debug` label. These artifacts are for internal debugging only: Gatekeeper may block downloaded copies, and they are not qualified for distribution or update publishing. No release completion record is written. The flag rejects unsigned, Windows and preparation-only builds. + +Install the user service from the checkout as the same account that registered the runner, without `sudo`: + +```sh +bash apps/desktop/scripts/macos-runner-service.sh install "$HOME/dsh-ci/runner" "$HOME/dsh-ci/packaging" /opt/homebrew/opt/node@24/bin +bash apps/desktop/scripts/macos-runner-service.sh start "$HOME/dsh-ci/runner" +bash apps/desktop/scripts/macos-runner-service.sh status "$HOME/dsh-ci/runner" +``` + +The installer copies its startup script into `runner/dsh-service`, sets the service PATH to Node 24 plus system tools, and uses GitHub's `svc.sh` and `runsvc.sh`. The LaunchAgent survives SSH disconnection, but requires that account's desktop login after reboot and stops on desktop logout. FileVault disk unlock remains an operator step; this does not provide unattended boot. Logs are `runner/dsh-service/stdout.log` and `stderr.log`; verify `Connected to GitHub` and `Listening for Jobs`. To update installed startup code or tool paths, wait until the runner is idle, run `stop`, then `uninstall`, and repeat installation. Neither action unregisters the runner or removes packaging credentials. Uninstall retains `runner/dsh-service` (including logs) and the explicit `.path`; reinstall replaces the startup snapshot and PATH. + + + +## Unsigned Windows test installer + +On Windows x64, use the complete unsigned packaging command for local installation testing: + +```sh +pnpm run package:desktop:win:x64:unsigned +``` + +The command reads `.env.windows` and requires `DSH_DESKTOP_APP_ID` and the [mandatory-update policy settings](../README.md#mandatory-update-policy), including a real HTTPS service origin. The local run and CI use Node 24; the remaining tools are the root `packageManager` version of pnpm, Git, PowerShell, tar, Python, Visual C++ Build Tools and a Windows SDK. Set `PYTHON` when Python is absent from `PATH`. It writes the installer to `.desktop-build/targets/win-x64/unsigned-artifacts/`, omits ordinary automatic-update configuration, strips signing credentials, and creates no release completion record. EV and upload credentials are unnecessary. Signed packaging and upload retain their release requirements. + +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. + + + +## Local macOS DMG without release signing + +After `pnpm install`, run one command from the repository root. No `.env.macos`, Apple account, certificate, or update service configuration is required: + +```sh +pnpm run package:desktop:mac:arm64:unsigned +pnpm run package:desktop:mac:x64:unsigned +``` + +Add `--check` to validate local configuration and tools without building, or `--dir` to stop at the unpacked application. The DMG is `apps/desktop/.desktop-build/targets//unsigned-artifacts/deepseek-harness--mac--unsigned.dmg`. After all checks pass, the command prints `DMG:` followed by its absolute path. Open it and copy the application to a local test directory. + +These commands ignore `.env.macos` and inherited release settings, use `com.deepseek.harness` as the app ID, and omit automatic-update and mandatory-update configuration. Build tools, standard network proxies, and `DSH_DESKTOP_NPM_REGISTRY` remain available from the shell. They skip Developer ID signing, Apple notarization, temporary signing keychains, and notarization proxy changes. Electron receives a local ad-hoc signature without certificates so the modified executable can run; the DMG is unsigned. Both preparation and the assembled application still run runtime integrity and smoke checks. Local builds omit update feeds, ZIPs, and release completion records, and the upload commands cannot publish them. macOS may require approval in System Settings → Privacy & Security to open an unnotarized application. + + + +## macOS release signing and diagnostics + +The signed macOS configuration uses the required release environment instead of accepting whichever certificate appears first in a keychain. It rejects empty values, a malformed Team ID, a signing identity that includes electron-builder's unsupported `Developer ID Application:` prefix, and incomplete notarization credentials. Signed macOS packaging requires the configured identity and its private key. Runtime preparation applies that identity, a secure timestamp, and hardened runtime to every embedded Mach-O file; after signing the application, a deep strict check rejects any other leaf authority or Team ID before artifact creation. The signed fixed-target macOS installer commands create separate copies of the signed application and run two artifact lanes concurrently. One lane notarizes and staples the App before generating the ZIP and its update metadata. The other encloses its signed App copy in a signed DMG, then notarizes, staples, and verifies the DMG; its inner App has no individually stapled ticket. Both lanes must finish successfully before their artifacts reach the final directory and the release completion record is written. Signed directory-only commands also require notarization credentials and wait for Apple notarization and App stapling. The [parallel notarization decision](../../../.agents/notes/implemented/process/2026-09-09-parallel-macos-notarization.md) owns copy isolation and container ticket semantics. `CSC_LINK` must name a local p12 containing the Developer ID Application certificate and private key; URLs and Base64 inputs are not supported. `CSC_KEY_PASSWORD` is its export password, not an Apple account or login password; an explicitly empty value supports an unencrypted p12. Before building, packaging creates and unlocks a private temporary keychain, imports the p12, authorizes signing, and signs a small probe. Runtime and App signing use this keychain explicitly; existing login keychains require no setup or manual unlocking. Child processes receive its path without the p12 password. The keychain is deleted after success or ordinary failure; CI must clean temporary credentials after forced termination. Ephemeral CI writes the certificate and `.env.macos` from its secret store, restricts file access, and deletes both after the job; self-hosted machine presets retain private files outside the checkout. Ambient `CSC_NAME` and certificate discovery order do not select the release owner. Notary credentials may instead use electron-builder's complete Apple ID or keychain-profile strategy. The two macOS identity variables are also required when repeating the application check manually with `pnpm --dir apps/desktop run verify:mac-signature -- `. + +macOS signing visits real files without following Framework symlink aliases. PAK resources retain all shipped languages and are sealed by the enclosing Framework or application signature instead of receiving individual signatures. The [release policy](../../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md) owns the dependency patch and verification requirements. + +macOS runtime preparation caches verified single-architecture Mach-O signatures in `.desktop-build/targets//signature-cache` unless `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` selects external storage. An explicit path must be absolute and already exist, contain no linked ancestors, and be owned by the current account with mode `0700` and read/write/search access; invalid or empty settings fail preflight without fallback. Omit the field to retain target-local storage. Keys include input bytes and permissions, the signing probe’s actual leaf certificate, identifier, entitlement bytes, macOS version, and signing tools and policy. Git commits do not determine reuse: uncommitted byte changes invalidate the affected file. Every hit verifies cached bytes, the strict signature, certificate, identifier, entitlements, secure timestamp and hardened runtime before replacing an unchanged input. Universal binaries are signed each time. Runtime integrity and smoke checks, App signing, and Apple notarization still run. The cache requires trusted local build storage. Cache corruption or unsafe links fail the build; stop packaging before deleting the affected cache directory and retrying. Successful signing stages prune complete entries to a one-GiB payload budget; interrupted temporary entries require manual removal. Concurrent eviction can fail a reader safely. Logs report hit, miss and uncached counts. + +Mac package commands print `DESKTOP_PACKAGING_RECORD` with a unique directory under `apps/desktop/.desktop-build/packaging-runs/`. After reading local configuration, each run retains `run.json` (published version, product version, Git commit, dirty-worktree flag, target and Node version), `events.jsonl` (timestamped phases, durations, parallel output attribution and proxy restoration), redacted child `stdout.log` / `stderr.log`, and `result.json` (overall outcome, stage results and artifact directory). Events also record pack concurrency and whether each proxy is configured. Logs survive failures and later builds; no automatic deletion runs. Missing `result.json` means completion is unconfirmed. Known credential values are redacted; environments and notarytool authentication arguments are not recorded. Runtime preparation records package staging, installation, materialization, signing, manifests, smoke checks, descriptor verification and cleanup separately. Nested phase durations overlap and must not be added together. + +App and DMG notarization each record a submission ID and separate `notarytool:upload:*` and `notarytool:wait:*` durations. Upload uses `submit --no-wait` and includes authentication, local validation, transfer and server acceptance; it is not pure transfer time. Waiting starts after that command returns and includes polling and remaining Apple processing; Apple can start processing before upload submission returns. Apple status and diagnostic logs are retained, including rejection; signature checks, acceptance checks and stapling remain owned by `@electron/notarize`. Directory-only package commands use this same measured App notarization path. Individual subprocess output remains live in the terminal, while phase failures and nested errors are retained in the journal. Both platforms record parent-process packaging failures and print redacted diagnostics, including proxy recovery instructions, to the terminal. The configuration-only `check:package` command creates no run log. + +Mac packaging reads three tuning fields from `.env.macos`: + +| Setting | Default | Scope | +|---|---|---| +| `DSH_DESKTOP_MACOS_PACK_CONCURRENCY` | `4` | Workers for first-party and vendor workspace tarballs; requires a positive integer. | +| `DSH_DESKTOP_MACOS_DOWNLOAD_PROXY` | Empty | HTTP/HTTPS proxy origin for Electron, runtime assets, pnpm installation and builder downloads. | +| `DSH_DESKTOP_MACOS_NOTARIZATION_PROXY` | Empty | HTTP proxy origin for Apple tools through temporary system proxy settings. | + +The proxy fields are independent and reject URL credentials, paths, queries and fragments. Empty values preserve inherited networking. An explicit download proxy replaces child-process proxy variables and bypasses local hosts only; it does not change system settings. Windows and standalone `release:pack` retain their existing concurrency defaults. Company proxy addresses belong in the ignored local file; see internal documentation for addresses. + +Apple tooling uses the active macOS network service's HTTP/HTTPS proxies. Configured notarization routing checks proxy reachability, saves that service's settings, enables the proxy around both artifact lanes, and restores the saved settings after both lanes settle. An originally disabled proxy with an empty server and port zero is restored by disabling it; the temporary server and port may remain stored but inactive. Directory-only builds apply it to App notarization after the signed directory build. This temporarily affects other applications and requires permission to change system proxies; PAC, auto-discovery, SOCKS and authenticated proxy configurations must be disabled first. Packaging and recovery acquire the same per-user POSIX file lock before reading recovery data or changing proxies; process exit releases ownership, while the lock file remains in place. The lock loads `@deepseek-ai/node-addon-system/flock` at first use rather than at script start, so `check:package` and the packaging entry load on a checkout that has not built `native/system`; when the host addon binary or the entry's JavaScript is missing at lock time, the loader runs `pnpm run build:native-system` and `pnpm --dir native/system run build:ts` before locking, so recovery works on such a checkout as well. This prevents overlapping proxy transactions across checkouts; other users and network-setting tools must not change these settings concurrently. SIGINT/SIGTERM wait for active work before restoration. After forced termination or a restoration error, stop any remaining notarization processes and run `pnpm --dir apps/desktop run restore:mac-proxy`; the saved record remains until restoration succeeds. Configuration checks validate URL syntax without changing system settings or contacting the proxy. + + + +## Directory builds and preparation + +Create a runnable application directory instead of an installer by using the matching `:dir` command, such as: + +```sh +pnpm run package:desktop:dir +pnpm run package:desktop:mac:arm64:dir +``` + +To inspect or troubleshoot the prepared host-target resources without invoking electron-builder, stop the same pipeline after preparation: + +```sh +pnpm run prepare:desktop +``` + +This diagnostic command is an alternative stopping point, not the first half of a two-command build. A later `package:desktop*` command repeats the official build and preparation so it cannot consume stale dsh packages, runtime files, or dsh content. + + + +## Local Official bundles from a loopback registry + +The test DMG excludes the provider runtimes the Official on-demand catalog advertises, and a release publishes matching bundle versions to npm. To install locally built bundles before that release, start a loopback registry that packs and serves the catalog's complete local dependency closure: + +```sh +pnpm run dev:bundle-registry +``` + +The command validates the catalog and the workspace inventory, runs `pnpm run build:official`, packs the closure into a new `dist/test-bundles//` directory, writes `bundle-registry.json` last as the completion marker, and only then prints the artifact path, the registry URL, and the exact `name@version` specs. It serves `127.0.0.1` on an allocated port under a fresh namespace until Ctrl+C or SIGTERM, and stopping it leaves both the artifacts and the installed packages on disk. It needs no `.env.macos`, Apple credentials, or npm credentials, and it does not change `pnpm run package:desktop:unsigned`. + +In the packaged application, open Plugins → Add plugin, paste one printed spec, choose **Custom address**, paste the printed registry URL, and install. A custom registry is asked alone, so this process must answer every dependency: repository-owned packages come from the run's own archives, and third-party packages keep npm's real metadata and bytes through a fixed redirect to `registry.npmjs.org`, which still requires network access. The installed entry stays Official because its package name is in the catalog. The registry choice is remembered in this browser; choose an offered registry again to switch back. + +A run's artifacts are immutable, so a rebuild serves a new namespace and a new URL, and the Official **Update** control does not appear while the installed and running versions match. The profile records the previous run's tarball URL in `pnpm-lock.yaml`, and pnpm verifies recorded entries, so installing or reinstalling that bundle against a new URL is refused with `ERR_PNPM_TARBALL_URL_MISMATCH` and can leave the earlier files in place. To test changed code at the same version, clear the stale resolution first — `pnpm clean --lockfile` in `$DSH_HOME/profiles/`, or install into a fresh profile — then install again from the new URL. `bundle-registry.json` records each archive's version, filename, size, and SHA-512 integrity together with the packing checkout's commit and dirty flag. + +The served `time` is the real packing time, so pnpm 11's default 24-hour `minimumReleaseAge` records the exemption it granted in the profile's `pnpm-workspace.yaml` (`minimumReleaseAgeExclude`); an explicitly stricter policy there fails the installation with pnpm's own message instead of being overridden. A `@scope:registry` route in `~/.npmrc` or the profile's `.npmrc` overrides `--registry` for that scope, so it must not route the served scope. + + + +## Runtime file selection and installation checks + +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. + +The [Office conversion provider](../../../packages/document/office-to-pdf/README.md) carries the target’s declared native engine, or WASM when the kit declares no matching native target. Preparation rejects a missing target engine before packaging. The complete Office dependencies, including CLI, JavaScript libraries, and the selected engine’s executables, data, licenses, and notices, are unpacked under `resources/app.asar.unpacked/dsh/node_modules/`. The Desktop Host resolves engine manifests to these physical directories and supplies loaded skills with absolute standalone Node and unpacked CLI paths. Node lives in `resources/runtime/primary-runtime/dependencies/node/bin/`; the CLI is the unpacked `@deepseek-ai/libreoffice-kit/lib/cli.js`. On macOS, the native helper receives the JIT entitlement required by [LibreOffice’s UNO bridge](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in). + +The packaged application runs compiled JavaScript and pre-generated Typert metadata; it does not compile TypeScript plugins. Source-level debugger navigation and editor declarations remain available in development packages. [Copy-policy tests](../tests/runtime-file-policy.spec.ts) cover exclusions and retained assets; The [payload smoke](../tests/fixtures/runtime-payload-smoke.mjs) runs under Electron RunAsNode before the Host smoke and final inventory verification. The payload smoke resolves the search tool’s ripgrep executable and verifies text search and file enumeration. Signed Windows builds run these checks after dependency signing; other builds run them during `prepare:dsh`. The [Host smoke](../scripts/smoke-runtime.ts) creates DOCX, XLSX, and PPTX inputs with bundled Python, converts each through the real Office provider, and checks PDF output. Every assembled application, including directory and unsigned builds, repeats the payload and Host checks against ASAR. Archive integrity checks compare the complete archived descriptor with preparation, file bytes and membership in both archive and unpacked trees, recorded executable flags for archived files, and physical permissions for unpacked files. The Host smoke also obtains CLI paths from the loaded skill and runs capabilities and DOCX conversion with an empty PATH. Conversion failures stop packaging before a release record is written; macOS DMG/ZIP builds run these checks before notarization. + +Windows release qualification also runs [directory and replacement checks](../scripts/smoke-windows.ps1) manually after the Desktop build. Set `$Makensis`, `$SevenZip`, and `$PluginDir` to the pinned builder’s NSIS compiler, 7-Zip executable, and x86-unicode NSIS plugin directory; pass the prepared `window-frame.dll` as `-FrameLibrary` to exercise the native extraction path and its failure report as well. From the repository root, run the command below. It verifies directory replacement and rollback, and both locked-file replacement modes; it is not part of the unit-test lane. + +```powershell +pwsh -NoProfile -File apps/desktop/scripts/smoke-windows.ps1 -Makensis $Makensis -SevenZip $SevenZip -PluginDir $PluginDir -FrameLibrary apps/desktop/.desktop-build/targets/win-x64/installer-ui/window-frame.dll +``` + +The Windows installer checks for a running application at startup and after destination selection, before extracting the new version beside the installation directory. It checks again before replacing directories through same-volume renames. A running application blocks installation; update launches allow up to ten seconds for it to exit. Same-path upgrades preserve the old directory until promotion succeeds; extraction failure leaves it intact, and promotion failure attempts to restore it. The installer removes the old backup before launch. Forced termination or power loss can leave `.new-*` or `.old-*` directories; installation-location and scope migrations retain electron-builder's old-uninstaller flow. + +When extraction fails, the installer writes a report with the 7-Zip result and its complete error output to the updater cache directory as `%LOCALAPPDATA%\-updater\installer-logs\extract-failure-.log` (currently `@deepseek-aidsh-desktop-updater`) and shows the first error line with a **Copy error details** button; silent installs write only the report. Unsigned Windows builds (`DSH_DESKTOP_UNSIGNED=1`) name their installer `deepseek-harness--win-x64-unsigned.exe` so they cannot be mistaken for release artifacts. + +Windows packaging fixes the 7-Zip filter to `BCJ` for compatibility with the bundled NSIS decoder. This preserves ARM64 binaries carried by dependencies in x64 installers; automatic ARM64 filtering produces entries that this decoder cannot extract. + +NSIS removes its temporary extraction tree during installation, before the completion page or an automatic launch. The installed production packages remain ordinary files; startup does not extract them again. Installation still writes the complete application tree. + + + +## Desktop runtime preparation + +Desktop [patch policy](../scripts/runtime-patch-policy.ts) explicitly classifies every workspace patch as shared, workspace-only, or runtime-only. Shared entries reuse the root patch bytes and verify their hash against the root lockfile; runtime-only entries use separate repository files without changing workspace installation. Workspace-only patches belong to build tools or dependencies already embedded in client bundles. Unclassified or stale entries, missing files, changed hashes, incompatible resolved versions, and workspace-only packages entering the runtime stop packaging. The [preparation script](../scripts/prepare-runtime-patches.ts) writes only to the temporary project; pnpm applies the selected patches and rejects application failures. + +Desktop dependency overrides are declared separately in the patch-policy module, not inferred from patch versions. The pi-ai constraint keeps its runtime version at the version qualified by the shared patch. Desktop still resolves a fresh runtime lockfile for each build, then installs with `--frozen-lockfile`; dependency resolution across separate builds is not yet reproducible. CLI packed-installation tests and other distribution flows retain their own configuration. + +Every package command builds the repository, packs the first-party production closures rooted at dsh and the private Desktop Host, and prepares the target Electron distribution plus primary-runtime with its shared pnpm CLI. `prepare:dsh` installs the production graph once at build time, prepares materialized packages for electron-builder to archive under `app.asar/dsh`, removes package-manager metadata, and writes `desktop-runtime.json` with shared package versions and final file hashes. Signed macOS builds sign and verify native files before inventory generation; electron-builder excludes this already-signed tree from nested re-signing. Resource mappings explicitly include `dsh/node_modules`, which the default root-directory filter omits; the prepared runtime inventory is checked after native signing. Native executables and libraries are unpacked beside ASAR; Python, standalone Node and pnpm remain in external runtime resources. Windows packaging checks every prepared PE against its ASAR unpacked entry and byte-identical disk copy, including unsigned builds. Builder glob rules match braces in PE filenames as single-character wildcards, so a matching neighboring file may also be unpacked. Prepared runtime smoke uses the verified target descriptor rather than the build host architecture. Signed installer, notarization, installed upgrade, and target-specific native-module qualification require the release environment. + +Signed macOS packaging writes `Contents/Resources/app-update.yml` while assembling the App and before code signing, including the directory build that feeds the parallel ZIP and DMG lanes. The signing hook verifies the exact feed and updater cache directory. Both lane copies and the promoted App are checked again before the release completion record is written; a missing or mismatched configuration prevents artifact promotion and therefore prevents upload. + +An unpacked artifact contains Electron, the materialized dsh production tree, pnpm, and the shell application. Installer size and filesystem size differ; release qualification measures both, plus the profile’s plugin storage and first-launch latency. The runtime trades more application files for eliminating core package installation on the user’s machine. + + + +## Installation and release verification + +Keep the generated installer, its version and packaging records together. Review signatures and runtime checks before installation, then follow the [installed-update qualification procedure](../tests/installed-update/README.md) for installed launch and upgrade evidence. The [Desktop test record](../tests/README.md) owns verification limits; a successful workflow alone does not establish production preset, new-workstation or installed-upgrade acceptance. + +## Dev Note + +None. diff --git a/apps/desktop/packaging/README.zh.md b/apps/desktop/packaging/README.zh.md new file mode 100644 index 0000000000..125b480ce5 --- /dev/null +++ b/apps/desktop/packaging/README.zh.md @@ -0,0 +1,275 @@ +--- +description: "在本地或 Windows/macOS Actions 中生成 Desktop 安装包,选择部署与签名模式,并获取产物和诊断。本指南区分构建操作、发布与已安装应用验收。使用硬件凭据前,必须检查平台签名要求与共享 runner 风险。" +--- + +# Desktop 打包 + +[English](README.md) | 中文 + +## 概述 + +在本地或 Windows/macOS Actions 中生成 Desktop 安装包,选择部署与签名模式,并获取产物和诊断。本指南区分构建操作、发布与已安装应用验收。使用硬件凭据前,必须检查平台签名要求与共享 runner 风险。 + +## 目录 + +- [选择打包方式](#choose-a-build) +- [发布版本](#release-versions) +- [配置与本地构建](#configuration-and-local-builds) +- [Windows Actions 打包](#windows-actions) +- [macOS 自托管打包](#macos-actions) +- [未签名 Windows 测试安装包](#unsigned-windows-test-installer) +- [无发布签名的本地 macOS DMG](#local-macos-dmg-without-release-signing) +- [macOS 发布签名与诊断](#macos-release-signing) +- [目录构建与准备](#directory-and-preparation) +- [用回环 registry 安装本地 Official 包](#local-official-bundles-from-a-loopback-registry) +- [运行时文件筛选与安装检查](#runtime-file-selection) +- [Desktop 运行时准备](#desktop-runtime-preparation) +- [安装与发布验收](#verification) + + + +## 选择打包方式 + +安装锁定依赖后,从仓库根目录运行本地命令。本地构建使用平台命令,已注册的自托管 runner 使用对应平台的 Actions。test/production 部署与 signed/unsigned 模式分别选择。任何 Windows 签名构建或共享 runner 使用前,先阅读 [Windows 签名与 runner 运维](../windows-signing/README.zh.md#trust-and-isolation)。安装与打包分开进行;[发布](../publishing/README.zh.md)还需要单独的显式操作。 + + + +## 发布版本 + +每次 Desktop 打包前,第一步都要与当前用户确认完整版本号。检查所选部署环境、dsh 基础版本、保留的发布记录和已发布对象,再提出准确版本供用户确认。用户确认前不得启动打包;仅选择部署环境不代表用户已认可版本号。 + +记录当前 dsh 版本作为基础版本。production Desktop 使用完全相同的版本,包括其中的 `alpha`、`beta` 或 `rc` 标识。test 发布保留完整的预发布基础版本并追加 `.YYYYMMDD.index`;稳定基础版本则追加 `-test.YYYYMMDD.index`。 + +| dsh 基础版本 | production Desktop | test Desktop 示例 | +|---|---|---| +| `0.1.6-alpha.1` | `0.1.6-alpha.1` | `0.1.6-alpha.1.20260916.1` | +| `0.1.6-beta.2` | `0.1.6-beta.2` | `0.1.6-beta.2.20260916.1` | +| `0.1.6-rc.3` | `0.1.6-rc.3` | `0.1.6-rc.3.20260916.1` | +| `0.1.6` | `0.1.6` | `0.1.6-test.20260916.1` | + +日期使用实际创建时的 Asia/Shanghai 日期。每个基础版本、每天的序号从 1 开始,检查保留的发布记录与已发布对象后递增;绝不复用已发布版本。test 分发不发布对应的无后缀基础版本。 + +Desktop 手动 CI 使用独立的未发布构建标识:`auto` 追加 UTC 日期、工作流运行编号和尝试次数(`.YYYYMMDD.run.attempt`,稳定基础版本使用 `-test`)。例如 `0.2.1-alpha.1.20261008.42.2`。这些编号不是预留的发布序号。 + +把确认后的版本通过 `--build-version` 传给打包命令,该值同时决定产物文件名、更新 feed 与上传校验。清单保留产品版本,因此 test 打包不再改写发布家族,也不留下需要还原的改动: + +```sh +pnpm --dir apps/desktop run package:win:x64 --build-version 0.1.6-alpha.1.20260916.1 +``` + +`--build-version auto` 会给出当天的下一个序号:读取目标 bucket 中已发布的对象,未配置 bucket 或列举未能在期限内完成时回退到本目标的本地输出目录。上传前请确认它打印的版本号;run script 会自行透传 `--`,打包入口两种写法都接受。 + +production 发布使用产品版本本身,不传 `--build-version`。其上传成功后会把打包所用 commit 打成 `desktop-v<版本>` 标签;来自有改动工作区的构建不打标签,打标签失败也只打印手工命令,不会让已完成的上传变成失败。test 与本地构建有意不留标签,而所有产物的清单都记录 `dshBuildCommit` 与 `dshBuildDirty`,直接分发的构建同样可溯源。 + +安装包独立于版本和发布环境内置 `DSH_DESKTOP_UPDATE_CHANNEL`(默认 `nightly`,也可选择 `latest`)。自动更新始终保留该通道,即使安装的是稳定版本;手动安装另一通道的包才会切换。latest 包拒绝预发布版本。稳定产品可生成 nightly 的 `-test..` 构建,但该版本低于稳定基准,不能升级已安装的更高版本。保持自动降级关闭;稳定修复版需要提升产品版本。CI 版本选择与发布见 [CI 发布](../publishing/ci/README.zh.md#package-and-publish)。 + + + +## 配置与本地构建 + +本地 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 使用运行编号和重试次数。 + +两个手动打包工作流都接受 `test_release_id`。留空沿用机器 preset;非空值必须是 32 位小写十六进制字符串,且仅允许 test preset。加载器通过 `PACKAGE_TEST_RELEASE_ID` 应用覆盖值,不修改 preset 文件。同一平台连续升级测试需使用相同值。轮换默认值只影响后续构建:已安装客户端保留原更新地址,旧对象仍可访问,除非另行删除。随机前缀降低地址的可发现性,但不提供下载身份认证。 + +不选择机器 preset 时,打包、上传以及手动 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 是否接受凭据;实际签名与公证负责这些检查。未选择机器 preset 时,`--build-version auto` 会访问目标 bucket,`--check` 下同样如此。单独运行相同检查: + +```sh +pnpm --dir apps/desktop run check:package +``` + +无需提前执行 `prepare:desktop`: + +```sh +pnpm run package:desktop +``` + +发布自动化使用固定目标命令,确保运行时准备、dsh 准备与 electron-builder 接收相同的平台和架构: + +```sh +pnpm run package:desktop:mac:arm64 +pnpm run package:desktop:mac:x64 +pnpm run package:desktop:win:x64 +``` + +macOS arm64 命令要求 Apple Silicon。macOS x64 命令可以在 Intel macOS 或带 Rosetta 的 Apple Silicon 上运行。Windows x64 命令要求 Windows x64。Linux 不是受支持的 Desktop 发布目标。 + +macOS 正式发布和本地未签名 DMG 都通过 [electron-builder 配置](../scripts/electron-builder-config.mjs)中的 `dmg.format: 'ULMO'` 使用 LZMA 压缩。[构建时补丁](../../../patches/app-builder-lib@26.17.0.patch)为固定版本 builder 的校验规则和 TypeScript 声明添加此格式。 + +每个目标都在 `apps/desktop/.desktop-build/targets//` 下持有自己的打包输入、已准备运行时、包集合、dsh 依赖树、pnpm 准备状态、未打包应用、更新元数据和最终产物。Electron 归档缓存继续由 `.desktop-build/downloads` 共享,因为每个归档文件名都包含版本、平台和架构,并且在解包前经过验证。目标构建绝不读取其他目标的可变准备状态。 + + + +## Windows Actions 打包 + +`Package Desktop · 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 选择工作流、源码分支、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 之外,不作为产物上传。 + +在 Actions 打开完成的运行并下载 Artifacts。`windows-x64-signed---` 与 `windows-x64-unsigned---` 包含对应 EXE;`windows-package-logs--` 包含打包诊断。上传步骤名为 `Retain verified signed installer`、`Retain verified unsigned installer` 和 `Retain packaging diagnostics`;步骤耗时与带时间戳的日志显示上传用时。这些产物不等于发布 Release 或下载站内容。 + + + +## macOS 自托管打包 + +`Package Desktop · macOS` [手动工作流](../../../.github/workflows/macos-package.yml) 使用带有 `dsh-mac-package-trial` 标签的 Apple Silicon runner。它选择 `test` 或 `production`,以 UTC 日期、运行编号和重试次数解析 `build_version=auto`,并复用现有签名、公证和打包运行时检查。成功的 DMG/ZIP 与诊断日志保留 14 天;工作流不发布 release。操作人员须注册 runner,并验收完整 Actions 运行后再依赖该流程。 + +运行 `node apps/desktop/scripts/setup-macos-packaging.mjs "$HOME/dsh-ci"` 创建私有 `runner/`、`packaging/{presets,secrets,certificates}` 和 `cache/macos-signatures` 目录,不覆盖已有文件;追加 `--check` 仅检查。在 checkout 外填写 [preset](../config/macos-packaging/test.env.example) 和[签名](../config/macos-packaging/macos-signing.env.example)模板,将秘密和证书文件权限设为 `0600`。`DSH_PACKAGING_CONFIG_DIR` 指定 `packaging` 的绝对目录,`DSH_PACKAGING_PRESET` 选择其中的 preset;缺少文件立即失败,不回退到 `.env.macos`。Mac 签名和仅准备构建读取 `secrets/macos-signing.env`,相对凭据路径以该文件所在目录为基准。公开 preset 拒绝签名凭据,签名文件不能覆盖公开配置。本地未签名 Mac 构建保留无需配置的行为。 + +运行 `bash apps/desktop/scripts/start-macos-packaging-runner.sh "$HOME/dsh-ci/runner" "$HOME/dsh-ci/packaging" --check` 检查宿主工具和配置文件。脚本同时选择当前 Xcode 及其 macOS SDK,并编译小型链接探针。注册后省略 `--check`,清理继承环境并在前台启动 runner,存活期间阻止空闲睡眠。安装下方服务前,先用 Ctrl-C 停止。runner 拥有 `_work` 下的源码目录,与日常开发分开。该账户可读取签名文件,因此只执行可信代码。沿用现有公证代理恢复规则;强制终止后,先检查保留的恢复记录再构建。新建模板将 `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` 设为 checkout 外 `cache/macos-signatures` 的绝对路径。已有部署重新运行 setup 后,在各 preset 中补上该字段;已有文件保持不变。这样可跨干净检出保留签名;缓存验证和容量限制见 [macOS 签名](#macos-release-signing)。 + + +工作流选项 `skip_notarization` 默认为 `false`;对应 CLI 参数是 `--skip-notarization`。该模式保留 Developer ID 签名、DMG 签名验证和打包运行时验证,跳过 Apple 公证和 stapling,不要求 Apple 公证凭据。DMG/ZIP 文件名带 `-unnotarized`,存放于 `.desktop-build/targets//unnotarized-artifacts/`,上传产物标为 `unnotarized-debug`。这些产物仅供内部调试:Gatekeeper 可能阻止下载副本运行,不能视为可分发包或用于更新发布。该模式不写入发布完成记录,不能与未签名、Windows 或仅准备构建组合。 + +在 checkout 中,以注册 runner 的同一账户安装用户服务,不使用 `sudo`: + +```sh +bash apps/desktop/scripts/macos-runner-service.sh install "$HOME/dsh-ci/runner" "$HOME/dsh-ci/packaging" /opt/homebrew/opt/node@24/bin +bash apps/desktop/scripts/macos-runner-service.sh start "$HOME/dsh-ci/runner" +bash apps/desktop/scripts/macos-runner-service.sh status "$HOME/dsh-ci/runner" +``` + +安装脚本将启动脚本复制到 `runner/dsh-service`,将服务 PATH 设为 Node 24 和系统工具,并使用 GitHub 的 `svc.sh` 与 `runsvc.sh`。LaunchAgent 在 SSH 断开后继续运行,但重启后需要该账户登录桌面,注销桌面时停止。FileVault 磁盘解锁仍由操作人员完成,这不提供无人值守开机。日志位于 `runner/dsh-service/stdout.log` 和 `stderr.log`;验收时确认出现 `Connected to GitHub` 与 `Listening for Jobs`。更新已安装的启动脚本或工具路径时,等待 runner 空闲,依次执行 `stop`、`uninstall`,再重新安装。这两个操作都不会注销 runner 或删除打包凭据。卸载保留 `runner/dsh-service`(包括日志)和显式 `.path`;重新安装会替换启动快照和 PATH。 + + + +## 未签名 Windows 测试安装包 + +在 Windows x64 上,使用完整的未签名打包命令进行本地安装测试: + +```sh +pnpm run package:desktop:win:x64:unsigned +``` + +该命令读取 `.env.windows`,要求设置 `DSH_DESKTOP_APP_ID` 和[强制更新策略配置](../README.zh.md#mandatory-update-policy),包括真实的 HTTPS 服务 origin。本机验收和 CI 使用 Node 24;其他工具为根 `packageManager` 固定版本的 pnpm、Git、PowerShell、tar、Python、Visual C++ Build Tools 和 Windows SDK。Python 不在 `PATH` 中时设置 `PYTHON`。命令将安装包写入 `.desktop-build/targets/win-x64/unsigned-artifacts/`,省略普通自动更新配置,清除签名凭据,且不生成发布完成记录。无需 EV 或上传凭据。签名打包和上传仍遵循正式发布要求。 + +先运行 `pnpm install --frozen-lockfile`,再运行 `pnpm run package:desktop:win:x64:unsigned --check` 校验配置和工具,最后执行上面的完整命令。打包自行执行完整构建和隔离的运行时 smoke,不调用在线模型。阶段日志保留在 `.desktop-build/packaging-runs/`;仅构建成功不代表安装包验证通过。依赖安装和运行时准备需要访问 npm、GitHub release 资源和 nodejs.org;网络需要时使用现有 registry 和代理配置。缓存与工具位置属于构建机器配置,不在跟踪文件中固定个人路径。 + + + +## 无发布签名的本地 macOS DMG + +执行 `pnpm install` 后,在仓库根目录运行一条命令即可,无需 `.env.macos`、Apple 账号、证书或更新服务配置: + +```sh +pnpm run package:desktop:mac:arm64:unsigned +pnpm run package:desktop:mac:x64:unsigned +``` + +添加 `--check` 仅验证本地配置和工具而不构建,或添加 `--dir` 只生成解包应用。DMG 路径为 `apps/desktop/.desktop-build/targets//unsigned-artifacts/deepseek-harness--mac--unsigned.dmg`。所有检查通过后,命令打印 `DMG:` 及其绝对路径。打开后将应用复制到本地测试目录。 + +这些命令忽略 `.env.macos` 和继承的发布配置,使用 `com.deepseek.harness` 作为应用 ID,并省略自动更新和强制更新配置。构建工具、标准网络代理与 `DSH_DESKTOP_NPM_REGISTRY` 仍可从 shell 提供。它们跳过 Developer ID 签名、Apple 公证、临时签名钥匙串和公证代理修改。Electron 使用无需证书的本地 ad-hoc 签名,以便修改后的可执行文件能够运行;DMG 不签名。准备阶段和组装后的应用仍执行运行时完整性与冒烟检查。本地构建不生成更新源、ZIP 或发布完成记录,上传命令无法发布这些产物。macOS 可能要求在“系统设置 → 隐私与安全性”中批准打开未经公证的应用。 + + + +## macOS 发布签名与诊断 + +macOS 签名配置使用必填发布环境,不会接受钥匙串中最先发现的证书。空值、格式错误的 Team ID、包含 electron-builder 不支持的 `Developer ID Application:` 前缀的签名身份,以及不完整的公证凭据都会被拒绝。macOS 签名打包要求已配置的身份及其私钥可用。运行时准备会把该身份、安全时间戳与 hardened runtime 应用到每个内嵌 Mach-O 文件;应用签名完成后,深度严格检查会拒绝其他叶证书 Authority 或 Team ID,验证通过才生成发布产物。macOS 签名固定目标安装包命令为已签名应用创建独立副本,并发执行两条产物流。一路先公证 App 并钉票,再生成 ZIP 及其更新元数据。另一路把已签名 App 副本封装进签名 DMG,再公证 DMG、钉票并验证;其中的 App 不单独附加票据。只有两路均成功结束,产物才会移入最终目录并写入发布完成记录。签名的仅目录命令同样需要公证凭据,并等待 Apple 公证和 App 钉票完成。[并行公证决策](../../../.agents/notes/implemented/process/2026-09-09-parallel-macos-notarization.zh.md)负责副本隔离与容器票据语义。`CSC_LINK` 必须指向包含 Developer ID Application 证书及私钥的本地 p12,不支持 URL 或 Base64 输入。`CSC_KEY_PASSWORD` 是其导出密码,不是 Apple 账号或登录密码;未加密的 p12 可显式填写空值。构建前,打包流程自动创建并解锁私有临时钥匙串、导入 p12、授权签名并签署小型探针。运行时与 App 签名显式使用该钥匙串,无需预先配置或手动解锁登录钥匙串。子进程只接收钥匙串路径,不接收 p12 密码。成功或普通失败后删除临时钥匙串;强制终止后由 CI 清理临时凭据。临时 CI 从密钥存储生成证书文件和 `.env.macos`,限制文件访问权限,并在作业结束后删除二者;自托管机器 preset 在 checkout 外保留私有文件。环境中的 `CSC_NAME` 与证书发现顺序都不能选择发布所有者。公证凭据也可以使用 electron-builder 支持的完整 Apple ID 或钥匙串 profile 方式。手动执行 `pnpm --dir apps/desktop run verify:mac-signature -- ` 重复应用检查时,也必须提供两个 macOS 身份变量。 + +macOS 签名遍历真实文件,不跟随 Framework 的软链接别名。PAK 资源保留全部随附语言,由外层 Framework 或应用签名记录完整性,不逐个签名。[发布策略](../../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)负责依赖补丁和验证要求。 + +macOS 运行时准备将已验证的单架构 Mach-O 签名缓存在 `.desktop-build/targets//signature-cache`,除非通过 `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` 选择外置存储。显式路径必须是已存在的绝对目录,祖先路径不能包含链接,目录须归当前账户所有、权限为 `0700` 且可读写及遍历;非法或空配置在预检时失败,不回退。省略该字段保留目标本地缓存。缓存键包含输入字节与权限、签名探针实际使用的叶证书、签名标识、entitlement 字节、macOS 版本,以及签名工具与策略。复用不取决于 Git 提交:未提交的字节变更会使对应文件失效。每次命中都验证缓存字节、严格签名、证书、标识、entitlements、安全时间戳和 hardened runtime,再替换未被并发修改的输入。通用二进制每次重新签名。运行时完整性与 smoke 检查、App 签名和 Apple 公证仍会执行。缓存要求受信任的本地构建存储。缓存损坏或不安全链接会令构建失败;停止打包后删除对应缓存目录再重试。成功的签名阶段会将完整缓存条目的内容总量裁剪至一 GiB;中断留下的临时条目需手动清理。并发淘汰可能使读取方安全失败。日志记录命中、未命中及未缓存数量。 + +Mac 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `apps/desktop/.desktop-build/packaging-runs/` 下的唯一目录。读取本地配置后,每次运行保留 `run.json`(发布版本、产品版本、Git 提交、工作区是否有改动、目标及 Node 版本)、`events.jsonl`(带时间戳的阶段、耗时、并行输出归属及代理恢复状态)、脱敏后的子进程 `stdout.log` / `stderr.log`,以及 `result.json`(整体结果、阶段结果和产物目录)。事件还记录打包并发数及各代理是否配置。失败和后续打包不会清除日志;没有自动删除流程。缺少 `result.json` 表示完成状态未经确认。已知凭据值会被遮盖;不记录环境变量全集或 notarytool 认证参数。运行时准备分别记录包暂存、安装、依赖树复制、签名、清单生成、smoke 检查、描述文件校验和清理。嵌套阶段的耗时存在重叠,不能直接相加。 + +App 和 DMG 公证分别记录 submission ID,以及独立的 `notarytool:upload:*` 和 `notarytool:wait:*` 耗时。上传使用 `submit --no-wait`,包含认证、本地校验、传输和服务端受理,并非纯传输时间。等待从该命令返回后开始,包含轮询及剩余的 Apple 处理时间;Apple 可能在上传提交命令返回前已开始处理。日志保留 Apple 状态与诊断信息,包括拒绝结果;签名检查、接受状态校验和 stapling 仍由 `@electron/notarize` 负责。仅生成目录的打包命令也使用同一条可计时的 App 公证路径。各子进程输出仍实时显示在终端,阶段失败及嵌套错误保留在事件日志中。两个平台均记录父进程打包失败,并在终端显示脱敏诊断,包括代理恢复操作指引。仅检查配置的 `check:package` 命令不创建运行日志。 + +Mac 打包从 `.env.macos` 读取三个调优字段: + +| 设置 | 默认值 | 作用范围 | +|---|---|---| +| `DSH_DESKTOP_MACOS_PACK_CONCURRENCY` | `4` | 第一方与 vendor workspace tarball 的打包 worker 数;必须是正整数。 | +| `DSH_DESKTOP_MACOS_DOWNLOAD_PROXY` | 空 | Electron、运行时资源、pnpm 安装及 builder 下载使用的 HTTP/HTTPS 代理 origin。 | +| `DSH_DESKTOP_MACOS_NOTARIZATION_PROXY` | 空 | 通过临时系统代理设置供 Apple 工具使用的 HTTP 代理 origin。 | + +两个代理字段互相独立,拒绝 URL 中的凭证、路径、查询参数和片段。空值沿用继承的网络设置。显式下载代理会替换子进程的代理变量,仅绕过本地主机;它不修改系统设置。Windows 与独立 `release:pack` 保持现有并发默认值。公司代理地址仅写入 Git 忽略的本地文件;具体地址参见内部文档。 + +Apple 工具使用 macOS 当前活动网络服务的 HTTP/HTTPS 代理。配置公证代理后,打包会检查代理可达性、保存该服务的设置,在两条产物任务期间启用代理,并在两条任务均结束后恢复原设置。对于原本关闭、服务器为空且端口为零的代理,恢复时仅关闭代理;临时服务器和端口可能保留,但不生效。仅生成目录的打包会在签名目录构建完成后的 App 公证期间启用代理。这会临时影响其他应用,并要求修改系统代理的权限;必须先禁用 PAC、自动发现、SOCKS 及需要认证的代理配置。打包和恢复在读取恢复记录或修改代理前获取同一个用户级 POSIX 文件锁;进程退出会释放锁的持有权,锁文件保留。该锁在首次使用时才加载 `@deepseek-ai/node-addon-system/flock`,而不是在脚本启动时加载,因此 `check:package` 和打包入口在未构建 `native/system` 的 checkout 上也能加载;加锁时若宿主 addon 二进制或入口的 JavaScript 缺失,加载器会先运行 `pnpm run build:native-system` 和 `pnpm --dir native/system run build:ts` 再加锁,因此恢复命令在这样的 checkout 上同样可用。这会阻止不同 checkout 的代理事务重叠;其他用户及网络设置工具不得同时修改这些设置。SIGINT/SIGTERM 会等待活动任务结束后恢复。强制终止或恢复失败后,先停止残留公证进程,再运行 `pnpm --dir apps/desktop run restore:mac-proxy`;保存的记录会保留到恢复成功。配置检查仅验证 URL 语法,不修改系统设置或连接代理。 + + + +## 目录构建与准备 + +使用对应的 `:dir` 命令可以生成可直接运行的应用目录,而不是安装包,例如: + +```sh +pnpm run package:desktop:dir +pnpm run package:desktop:mac:arm64:dir +``` + +需要检查或诊断为宿主目标准备的资源而不调用 electron-builder 时,可以让同一流水线在准备完成后停止: + +```sh +pnpm run prepare:desktop +``` + +这条诊断命令是另一种停止位置,并非两条命令构建流程的前半段。之后执行 `package:desktop*` 时仍会重新完成正式构建与准备,避免使用陈旧的 dsh 包、运行时文件或 dsh 内容。 + + + +## 用回环 registry 安装本地 Official 包 + +测试 DMG 不包含 Official 按需目录所宣传的 provider 运行时,而正式发布才会把对应版本的 bundle 发到 npm。要在发布前安装本地构建的 bundle,请启动一个回环 registry,它会打包并提供该目录的完整本地依赖闭包: + +```sh +pnpm run dev:bundle-registry +``` + +该命令先校验目录与 workspace 清单,运行 `pnpm run build:official`,把闭包打包进新的 `dist/test-bundles//` 目录,最后写入 `bundle-registry.json` 作为完成标记,然后才打印产物路径、registry URL 和精确的 `name@version` 规格。它在分配到的端口上只监听 `127.0.0.1`,使用一次性的命名空间提供服务,直到 Ctrl+C 或 SIGTERM;停止后产物和已安装的包都保留在磁盘上。它不需要 `.env.macos`、Apple 凭据或 npm 凭据,也不改变 `pnpm run package:desktop:unsigned`。 + +在打包应用中打开“插件 → 添加插件”,粘贴一条打印出的规格,选择**自定义地址**,粘贴打印出的 registry URL 后安装。自定义 registry 会被单独询问,因此必须由本进程回答每一个依赖:仓库自有的包取自本次运行的产物,第三方包则通过固定重定向到 `registry.npmjs.org` 保留 npm 的真实元数据与字节,因此仍需要网络访问。安装后的条目仍归类为 Official,因为它的包名在目录中。registry 选择会在此浏览器中记住;再次选择某个提供的 registry 即可切回。 + +一次运行的产物是不可变的,所以重新构建会提供新的命名空间和新 URL;当已安装版本与运行版本一致时,Official 的**更新**控件不会出现。profile 会在 `pnpm-lock.yaml` 中记录上一次运行的 tarball URL,而 pnpm 会校验已记录的条目,因此用新 URL 再次安装或重装该 bundle 会被 `ERR_PNPM_TARBALL_URL_MISMATCH` 拒绝,并且可能继续保留旧文件。要在同一版本上验证改动后的代码,请先清除过期的解析结果——在 `$DSH_HOME/profiles/` 中运行 `pnpm clean --lockfile`,或改用全新的 profile——然后再从新 URL 安装。`bundle-registry.json` 记录每个归档的版本、文件名、大小和 SHA-512 完整性,以及打包所用 checkout 的 commit 和 dirty 标记。 + +所提供的 `time` 是真实的打包时间,因此 pnpm 11 默认的 24 小时 `minimumReleaseAge` 会在 profile 的 `pnpm-workspace.yaml` 中记录它授予的豁免(`minimumReleaseAgeExclude`);如果那里显式配置了更严格的策略,安装会以 pnpm 自己的报错失败,而不会被覆盖。`~/.npmrc` 或 profile 的 `.npmrc` 中的 `@scope:registry` 路由会覆盖该 scope 的 `--registry`,因此不能让它们指向正在提供服务的 scope。 + + + +## 运行时文件筛选与安装检查 + +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)检查保留文件的字节和排除项。 + +[Office 转换提供方](../../../packages/document/office-to-pdf/README.zh.md)携带目标已声明的原生引擎;kit 未声明匹配原生目标时携带 WASM 引擎。准备阶段在打包前拒绝缺少目标引擎的情况。完整 Office 依赖(CLI、JavaScript 库和选定引擎的可执行文件、数据、许可证及 notices)解包到 `resources/app.asar.unpacked/dsh/node_modules/` 下。Desktop Host 将引擎清单解析到这些物理目录,并向加载的技能提供独立 Node 和解包后 CLI 的绝对路径。Node 位于 `resources/runtime/primary-runtime/dependencies/node/bin/`;CLI 位于解包后的 `@deepseek-ai/libreoffice-kit/lib/cli.js`。macOS 上的原生辅助程序获得 [LibreOffice UNO 桥](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in)所需的 JIT entitlement。 + +打包应用运行编译后的 JavaScript 和预生成的 Typert 元数据,不编译 TypeScript 插件。源码级调试导航和编辑器声明仍可从开发包中获取。[复制规则测试](../tests/runtime-file-policy.spec.ts)覆盖排除项和保留资源;[产物 smoke](../tests/fixtures/runtime-payload-smoke.mjs) 在 Host smoke 和最终清单验证之前,使用 Electron RunAsNode 执行。产物 smoke 解析搜索工具使用的 ripgrep 可执行文件,并验证文本搜索和文件枚举。Windows 签名构建在依赖签名后运行这些检查;其他构建在 `prepare:dsh` 中运行。[Host smoke](../scripts/smoke-runtime.ts) 使用捆绑的 Python 创建 DOCX、XLSX 和 PPTX 输入,通过真实 Office 提供方逐一转换并检查 PDF 输出。每个组装后的应用(包括目录包和未签名构建)都会针对 ASAR 重复产物和 Host 检查。归档完整性检查将归档内完整描述符与准备结果比对,并核对归档和解包目录中的文件内容与清单、归档内文件记录的执行标志,以及解包文件的物理权限。转换失败会在写入发布记录前终止打包;macOS DMG/ZIP 构建在公证前执行这些检查。 + +Windows 发布验收还需在 Desktop 构建后手动运行[目录和替换检查](../scripts/smoke-windows.ps1)。将 `$Makensis`、`$SevenZip` 和 `$PluginDir` 分别设为锁定版本构建器的 NSIS 编译器、7-Zip 可执行文件和 x86-unicode NSIS 插件目录;通过 `-FrameLibrary` 传入已准备好的 `window-frame.dll`,即可同时覆盖原生解压路径及其失败报告。从仓库根目录运行以下命令。它验证 目录替换与回滚和两种文件占用替换方式;不属于单元测试通道。 + +```powershell +pwsh -NoProfile -File apps/desktop/scripts/smoke-windows.ps1 -Makensis $Makensis -SevenZip $SevenZip -PluginDir $PluginDir -FrameLibrary apps/desktop/.desktop-build/targets/win-x64/installer-ui/window-frame.dll +``` + +Windows 安装器在启动时和选定目标目录后检查应用是否正在运行,通过检查后才将新版本解压到安装目录旁边。通过同卷目录改名替换前,安装器会再次检查。运行中的应用会阻止安装;更新启动允许等待应用退出,最长十秒。同路径升级在替换成功前保留旧目录;解压失败时旧版不变,替换失败时尝试恢复旧目录。安装器在启动前清理旧版备份。强制结束安装器或断电可能留下 `.new-*` 或 `.old-*` 目录;不同安装位置或安装范围迁移仍使用 electron-builder 的旧卸载器流程。 + +解压失败时,安装器会把 7-Zip 的结果和完整错误输出写入更新缓存目录 `%LOCALAPPDATA%\<按包名派生>-updater\installer-logs\extract-failure-<时间戳>.log`(当前为 `@deepseek-aidsh-desktop-updater`),并在弹窗中显示首条错误行和 **复制错误信息** 按钮;静默安装只写入报告。未签名的 Windows 构建(`DSH_DESKTOP_UNSIGNED=1`)会将安装包命名为 `deepseek-harness-<版本>-win-x64-unsigned.exe`,以免被误当作发布产物。 + +Windows 打包将 7-Zip 过滤器固定为 `BCJ`,以兼容内置的 NSIS 解码器。这样可以保留 x64 安装包中由依赖携带的 ARM64 二进制文件;自动 ARM64 过滤会生成该解码器无法解压的条目。 + +NSIS 在安装阶段清理临时解压目录,完成后才显示完成页或自动启动应用。已安装的生产依赖保持为普通文件;启动时不会再次解压。安装仍会写入完整的应用目录树。 + + + +## Desktop 运行时准备 + +Desktop [补丁策略](../scripts/runtime-patch-policy.ts) 将每份工作区补丁明确归为共享、仅工作区或仅运行时。共享项复用根目录补丁字节,并对照根锁文件校验 hash;仅运行时项使用仓库内的独立文件,不改变工作区安装。仅工作区补丁用于构建工具或已嵌入客户端 bundle 的依赖。未分类或过期的条目、文件缺失、hash 改变、解析版本不兼容,以及仅工作区包进入运行时,都会阻止打包。[准备脚本](../scripts/prepare-runtime-patches.ts) 只写入临时项目;pnpm 负责应用选中的补丁,应用失败时会报错。 + +Desktop 依赖 overrides 在补丁策略模块中单独声明,不从补丁版本推导。pi-ai 约束使运行时版本保持在共享补丁已验证的版本。Desktop 仍会在每次构建时重新解析运行时锁文件,再通过 `--frozen-lockfile` 安装;不同构建之间的依赖解析尚不保证可复现。CLI 打包安装测试及其他交付流程保留各自的配置。 + +每条打包命令都会构建仓库,打包以 dsh 和私有 Desktop Host 为根的第一方生产依赖闭包,并准备目标专用的 Electron 分发包和包含共享 pnpm CLI 的 primary-runtime。`prepare:dsh` 在构建时安装一次生产依赖图,准备物化包供 electron-builder 归档到 `app.asar/dsh`,移除包管理器元数据,并生成包含共享包版本和最终文件哈希的 `desktop-runtime.json`。macOS 签名构建先签名并验证原生文件,再生成清单;electron-builder 不对已签名的此目录重复进行嵌套签名。资源映射明确包含默认根目录过滤器会忽略的 `dsh/node_modules`;准备完成的运行时清单在原生签名后检查。原生可执行文件及库解包到 ASAR 旁;Python、独立 Node 和 pnpm 保留在外部 runtime 资源中。Windows 打包逐项检查准备好的 PE,确认其 ASAR 条目已标记为解包,且磁盘副本字节一致;未签名构建也执行此检查。Builder glob 规则用单字符通配符匹配 PE 文件名中的花括号,因此同目录中名称匹配的文件也可能被解包。准备好的运行时 smoke 沿用已验证的目标描述符,不使用构建宿主的架构。签名安装包、公证、已安装应用升级和各目标原生模块的验收需要发布环境。 + +macOS 签名打包在组装 App 时、代码签名前写入 `Contents/Resources/app-update.yml`,供并行 ZIP 与 DMG 路线使用的目录构建也执行此操作。签名钩子验证准确的更新源和 updater 缓存目录。写入发布完成记录前,流程会再次检查两条路线的副本和最终移入的 App;配置缺失或不匹配会阻止移入产物,因而也会阻止上传。 + +未压缩产物包含 Electron、物化后的 dsh 生产依赖树、pnpm,以及壳应用。安装包大小与文件系统占用不同;发布验收需要测量两者,以及 profile 插件存储和首次启动耗时。此布局用更多应用内文件换取消除用户机器上的核心包安装过程。 + + + +## 安装与发布验收 + +一起保留生成的安装包、版本和打包记录。安装前检查签名与运行时验证结果,再按[已安装更新验收流程](../tests/installed-update/README.zh.md)记录安装后启动及升级证据。[Desktop 测试记录](../tests/README.zh.md)维护验证限制;工作流成功本身不代表 production preset、新工作站或已安装升级验收通过。 + +## 开发备注 + +无。 diff --git a/apps/desktop/publishing/README.i18n.yaml b/apps/desktop/publishing/README.i18n.yaml new file mode 100644 index 0000000000..9483eaff54 --- /dev/null +++ b/apps/desktop/publishing/README.i18n.yaml @@ -0,0 +1,37 @@ +# 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 apps/desktop/publishing/README.md +/: + en: 32f414f3e27d5afd + zh: e16c49177f708c47 +/desktop-publication: + en: 03551b589405750e + zh: ccbf7e38dcf5d452 +/desktop-publication/summary: + en: 722633597f74ace6 + zh: 5303bcf5567a8511 +/desktop-publication/table-of-contents: + en: 6217df1d38ff46aa + zh: 22375410c0816130 +/desktop-publication/publication-prerequisites: + en: b407de63118c9bf9 + zh: de19f1ba9feacbbf +/desktop-publication/deployment-and-test-release-identity: + en: 405588e021bcfb60 + zh: d9f9700b0b6db6f8 +/desktop-publication/publish-installers-and-update-feeds: + en: 3c3e3a09573c4386 + zh: c851ae6a94f2284a +/desktop-publication/fixed-installer-downloads: + en: 38054a5f89590cfa + zh: 9e115f9bdeeab213 +/desktop-publication/upload-credentials: + en: 1c5689525753b08d + zh: 93089de765806733 +/desktop-publication/upload-audit-and-recovery: + en: ec85f43ece09a5e3 + zh: 2de5bf801c9c9e39 +/desktop-publication/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/apps/desktop/publishing/README.md b/apps/desktop/publishing/README.md new file mode 100644 index 0000000000..71c52c1d75 --- /dev/null +++ b/apps/desktop/publishing/README.md @@ -0,0 +1,88 @@ +--- +description: "Publish completed Desktop installers and update feeds to the selected download service. This reference covers deployment identity, upload credentials, fixed downloads and audit records. Build configuration and signing operations have separate owners." +--- + +# Desktop publication + +English | [中文](README.zh.md) + +## Summary + +Publish completed Desktop installers and update feeds to the selected download service. This reference covers deployment identity, upload credentials, fixed downloads and audit records. Build configuration and signing operations have separate owners. + +## Table of Contents + +- [Publication prerequisites](#prerequisites) +- [Deployment and test release identity](#upload-updates) +- [Publish installers and update feeds](#publish-feeds) +- [Fixed installer downloads](#fixed-downloads) +- [Upload credentials](#credentials) +- [Upload audit and recovery](#audit-and-recovery) + +For retained self-hosted builds, use the [CI publication workflow](ci/README.md), which keeps installers on their original machine and supports resumable publication. The commands below remain the existing manually authorized local uploader: they retain checkout-local audit records and use the operator's Git identity. They do not share the CI publisher's locks, approval or tag-only recovery. Do not run both writers against one channel concurrently. Both use the same upload-plan validation; separate orchestration preserves existing manual commands while adding immutable-attempt recovery for CI. Consolidating or retiring the manual commands is separate work. + + + +## Publication prerequisites + +Publication requires completed release artifacts and explicit operator authorization. Building an installer or downloading an Actions artifact does not publish it. Read the [release version rules](../packaging/README.md#release-versions) and retain the packaging evidence. Machine presets are for packaging, not upload/COS commands: unset `DSH_PACKAGING_PRESET` and provide the existing target dotenv upload configuration. The configuration and actual COS/CDN acceptance must be verified by the release operator. + + + +## Deployment and test release identity + +`DSH_DESKTOP_AUTO_UPDATE_ENV` selects `test` or `production` for both the URL embedded during packaging and the later COS upload; an absent value selects `test`. Test packaging requires its HTTPS origin in `DOWNLOAD_TEST_ORIGIN`; production uses `https://download.deepseek.com`. Upload requires the selected bucket in `DOWNLOAD_TEST_COS_BUCKET` or `DOWNLOAD_PROD_COS_BUCKET`. Production feeds use `dsh-desk/feeds//` and binaries use `dsh-desk/bin//`. Test releases require `DOWNLOAD_TEST_RELEASE_ID`: 32 lowercase hexadecimal characters inserted as `dsh-desk//feeds//` and `dsh-desk//bin//`. YAML references, stable-channel aliases, and blockmaps stay inside that release directory. Targets are `mac-arm64`, `mac-x64`, and `win-x64`. + +The update destination and upload credentials follow the selected deployment: + +| Environment | Public origin | COS bucket | COS credentials | +|---|---|---|---| +| `test` or unset | `DOWNLOAD_TEST_ORIGIN` | `DOWNLOAD_TEST_COS_BUCKET` | `DOWNLOAD_TEST_COS_SECRET_ID`, `DOWNLOAD_TEST_COS_SECRET_KEY` | +| `production` | `https://download.deepseek.com` | `DOWNLOAD_PROD_COS_BUCKET` | `DOWNLOAD_PROD_COS_SECRET_ID`, `DOWNLOAD_PROD_COS_SECRET_KEY` | + +Generate a fresh ID for each test release batch with the command below and copy its output into `DOWNLOAD_TEST_RELEASE_ID` in `.env.macos` or `.env.windows`. These Git-ignored platform files own the value; shell variables do not override it, and dotenv values are not shell-expanded. Keep the ID through packaging, upload, and retries; upload rejects a completion record with a different update URL. To test an upgrade between versions, reuse the installed client’s ID for the later version. Production does not use this field. + +```sh +node --input-type=module -e "import { randomBytes } from 'node:crypto'; console.log(randomBytes(16).toString('hex'))" +``` + +Distribute each test batch through its complete download links. Installed test clients retain their batch feed and do not discover a new ID automatically. Format validation cannot establish randomness; use the generator output. Random paths reduce guessing, not access by link holders; withdrawing a batch requires deleting its COS objects and purging its CDN directory. + + + +## Publish installers and update feeds + +Configure the update origin and selected COS bucket, SecretId, and SecretKey in the target dotenv file, then package and upload the same target: + +```sh +pnpm run package:desktop:mac:arm64 +pnpm run upload:mac:arm64 +``` + +The target dotenv file for internal-test packaging explicitly sets `DSH_DESKTOP_AUTO_UPDATE_ENV=test` and `DOWNLOAD_TEST_ORIGIN=https://download-test.deepseek.com`; uploads use `DOWNLOAD_TEST_COS_BUCKET=bj-toc-download-test-1320056602` and separate test credentials. Both test and production use the fixed Nightly channel; deployment selection does not enable channel switching. + +Early internal-test packages use the `test` deployment. Select `production` explicitly only for a production release; changing upload credentials does not retarget an existing package. Packaging requires no COS credentials, disables electron-builder publishing, strips COS credentials from child processes, and records completion only after signing and notarization succeed. Upload validates this record, deployment, target, shared version, filenames, sizes, and SHA-512 before reading credentials. Packages and blockmaps upload before YAML; historical objects are retained. Every release publishes `nightly.yml` or `nightly-mac.yml`; stable releases also publish `latest.yml` or `latest-mac.yml` pointing at the same artifacts. Published YAML uses absolute binary URLs. The uploader leaves Cache-Control unset, including the empty header the COS SDK would otherwise add: deployment infrastructure owns cache policy, with uncached feeds and separately configurable binary caching. Serialize publication per target and verify public artifacts and feed contents before release qualification. + +Windows NSIS uploads require the generated, nonempty `.exe.blockmap` beside the installer. The blockmap is uploaded before channel YAML; NSIS installer metadata does not require the embedded `blockMapSize` used by the separate web-installer format. File-plan tests use the pinned builder's blockmap generator, not a hand-authored embedded-map field. + + + +## Fixed installer downloads + +Fixed installer downloads use `pnpm run upload:latest:mac:arm64`, `pnpm run upload:latest:mac:x64`, or `pnpm run upload:latest:win:x64` from the repository root. They upload the completed target's DMG or EXE to `desktop/dsh-latest-macos-arm64.dmg`, `desktop/dsh-latest-macos-x64.dmg`, or `desktop/dsh-latest-windows-x64.exe`. Production URLs start with `https://download.deepseek.com/`; test URLs use `DOWNLOAD_TEST_ORIGIN`. Both deployments reuse the target dotenv's deployment, bucket, and credentials, all normal release validation, and the upload audit below. Each command replaces one fixed object without publishing feeds, blockmaps, or release tags. Test fixed downloads are shared across release IDs in the test bucket; the packaged update URL still requires its original release ID. Publication is explicit, including prerelease versions. Deployment infrastructure must configure revalidation or purge cached fixed downloads after replacement. Local loopback tests cover the upload; release operators own real COS and CDN acceptance. + + + +## Upload credentials + +Windows operators can keep a CLIXML object with DPAPI-encrypted `SecretId` and `SecretKey` SecureString fields outside the repository. The [credential launcher](../scripts/upload-with-credentials.ps1) requires an explicit `-CredentialFile` and `-Environment production` or `test`; without `-Upload`, it only verifies decryption and injection into a local Node child, with no network request. It requires Node on `PATH` and the Windows user and machine that encrypted the file. Plaintext, empty, and whitespace-only fields fail. The parent environment is unchanged; the child receives only the selected COS pair after unrelated secrets and Node preload options are removed. Raw child stderr is suppressed and credential values in stdout are redacted. This check does not prove COS authorization. An explicit upload additionally requires `-Upload -Target -Bucket ` and the normal completed-release prerequisites below; actual cloud upload remains release-operator qualification. Add `-Latest` to that upload invocation to replace the fixed installer without publishing update feeds or a release tag. This launcher supports permanent keys, not STS credentials. An explicit upload requires the selected deployment and bucket to match the target dotenv and completed package record before network writes; it uses the DPAPI credential pair even if the dotenv contains other COS keys. + + + +## Upload audit and recovery + +Test and production uploads through `upload:*` retain a fresh `.desktop-build/upload-records/--*` directory after release preflight. `plan.json` records destination, version, every file's size/SHA-512, and published YAML bytes; flushed `events.jsonl` records PUT intent and available response status/request ID; `result.json` records completion or the last failed stage. A missing final result means interruption or unavailable storage, not success. No credential values, authorization headers, or raw SDK errors are recorded. Audit-write failures stop later PUTs. Every object is one streamed Tencent COS PUT with an explicit length and Content-MD5; the COS SDK repeats a request only when its body is not a stream, and this uploader does not retry either. Retain partial records and inspect remote state before another operation: a timeout or failed receipt write does not prove that the object was not stored. These records are local, not tamper-proof or automatically backed up; archive each release's records with its build evidence in controlled storage. Public CDN readback remains separate release qualification, explicitly marked `not-performed` in the upload result. + +## Dev Note + +None. diff --git a/apps/desktop/publishing/README.zh.md b/apps/desktop/publishing/README.zh.md new file mode 100644 index 0000000000..22952efae4 --- /dev/null +++ b/apps/desktop/publishing/README.zh.md @@ -0,0 +1,88 @@ +--- +description: "将完整 Desktop 安装包与更新清单发布到选定下载服务。本参考文档说明部署标识、上传凭据、固定下载和审计记录。打包配置与签名操作由独立文档维护。" +--- + +# Desktop 发布 + +[English](README.md) | 中文 + +## 概述 + +将完整 Desktop 安装包与更新清单发布到选定下载服务。本参考文档说明部署标识、上传凭据、固定下载和审计记录。打包配置与签名操作由独立文档维护。 + +## 目录 + +- [发布前提](#prerequisites) +- [部署环境与测试发布标识](#upload-updates) +- [发布安装包与更新清单](#publish-feeds) +- [固定安装包下载](#fixed-downloads) +- [上传凭据](#credentials) +- [上传审计与恢复](#audit-and-recovery) + +自托管留存构建使用 [CI 发布工作流](ci/README.zh.md),在原机器保留安装包并支持恢复发布。 以下命令继续作为现有人工授权的本地上传器使用:它们保留 checkout 内的审计记录,并使用操作员的 Git 身份,不共享 CI 发布器的锁、审批或仅补 tag 恢复机制。不要让两种上传器并发写入同一频道。两者复用相同的上传计划校验;分开编排可保留现有手动命令,同时为 CI 增加不可变 attempt 恢复能力。统一或退役手动命令属于独立工作。 + + + +## 发布前提 + +发布需要完整的 release 产物和操作者明确授权。生成安装包或下载 Actions 产物不会发布它。先阅读[发布版本规则](../packaging/README.zh.md#release-versions)并保留打包证据。机器 preset 用于打包,不支持 upload/COS 命令:取消设置 `DSH_PACKAGING_PRESET`,并提供既有目标 dotenv 上传配置。配置以及真实 COS/CDN 验收由发布操作者验证。 + + + +## 部署环境与测试发布标识 + +`DSH_DESKTOP_AUTO_UPDATE_ENV` 同时选择打包写入的 URL 与后续 COS 上传环境,可取 `test` 或 `production`;缺省为 `test`。测试打包通过 `DOWNLOAD_TEST_ORIGIN` 提供 HTTPS origin;生产使用 `https://download.deepseek.com`。上传通过 `DOWNLOAD_TEST_COS_BUCKET` 或 `DOWNLOAD_PROD_COS_BUCKET` 提供所选 bucket。生产清单位于 `dsh-desk/feeds//`,安装包位于 `dsh-desk/bin//`。测试发布必须配置 `DOWNLOAD_TEST_RELEASE_ID`:32 位小写十六进制字符,分别插入路径 `dsh-desk//feeds//` 和 `dsh-desk//bin//`。YAML 引用、稳定通道别名和 blockmap 都位于该发布目录内。目标为 `mac-arm64`、`mac-x64` 和 `win-x64`。 + +更新目标与上传凭据都与所选环境对应: + +| 环境 | 公开 origin | COS bucket | COS 凭据 | +|---|---|---|---| +| `test` 或未设置 | `DOWNLOAD_TEST_ORIGIN` | `DOWNLOAD_TEST_COS_BUCKET` | `DOWNLOAD_TEST_COS_SECRET_ID`、`DOWNLOAD_TEST_COS_SECRET_KEY` | +| `production` | `https://download.deepseek.com` | `DOWNLOAD_PROD_COS_BUCKET` | `DOWNLOAD_PROD_COS_SECRET_ID`、`DOWNLOAD_PROD_COS_SECRET_KEY` | + +每个测试发布批次用下方命令生成新 ID,将输出填入 `.env.macos` 或 `.env.windows` 的 `DOWNLOAD_TEST_RELEASE_ID`。这两个被 Git 忽略的平台文件管理该值,shell 变量不能覆盖它,dotenv 值也不会进行 shell 展开。打包、上传和重试必须沿用同一个 ID;上传会拒绝更新 URL 不一致的完成记录。需要验证跨版本升级时,后续版本沿用已安装客户端的 ID。生产环境不使用该字段。 + +```sh +node --input-type=module -e "import { randomBytes } from 'node:crypto'; console.log(randomBytes(16).toString('hex'))" +``` + +通过完整下载链接分发每个测试批次。已安装的测试客户端保留当前批次的清单地址,不会自动发现新 ID。格式校验无法判断随机性,请使用生成器的输出。随机路径降低被猜中的概率,不限制持有链接者访问;撤下批次需要删除其 COS 对象并清除对应 CDN 目录缓存。 + + + +## 发布安装包与更新清单 + +在目标 `.env` 中配置更新地址与所选 COS bucket、SecretId、SecretKey,再打包并上传同一个目标: + +```sh +pnpm run package:desktop:mac:arm64 +pnpm run upload:mac:arm64 +``` + +内测打包在目标 `.env` 中显式设置 `DSH_DESKTOP_AUTO_UPDATE_ENV=test` 和 `DOWNLOAD_TEST_ORIGIN=https://download-test.deepseek.com`;上传使用 `DOWNLOAD_TEST_COS_BUCKET=bj-toc-download-test-1320056602` 及独立测试凭据。test 和 production 都使用固定 Nightly 通道,部署选择不提供通道切换。 + +前期内测包使用 `test` 部署。只有正式发布才显式选择 `production`;更换上传凭据不会改变已有安装包的更新目标。打包不需要 COS 凭据,会禁用 electron-builder 发布、移除子进程的 COS 凭据,并且仅在签名与公证成功后记录完成状态。上传在读取凭据前验证该记录、部署、目标、共同版本号、文件名、大小与 SHA-512。安装包和 blockmap 先于 YAML 上传;历史对象继续保留。每个版本发布 `nightly.yml` 或 `nightly-mac.yml`;稳定版本还发布指向相同产物的 `latest.yml` 或 `latest-mac.yml`。发布的 YAML 使用安装包绝对 URL。上传器不设置 Cache-Control,包括 COS SDK 否则会添加的空头部:缓存策略由部署基础设施负责,清单不缓存,安装包缓存单独配置。同一目标应串行发布,并在发布验收前验证公网产物与清单内容。 + +Windows NSIS 上传要求安装包旁存在生成的非空 `.exe.blockmap`。blockmap 先于通道 YAML 上传;NSIS 安装包元数据不要求另一种 web-installer 格式使用的内嵌 `blockMapSize`。文件清单测试使用固定版本构建器的 blockmap 生成器,而不是手工编造内嵌映射字段。 + + + +## 固定安装包下载 + +固定安装包下载在仓库根目录使用 `pnpm run upload:latest:mac:arm64`、`pnpm run upload:latest:mac:x64` 或 `pnpm run upload:latest:win:x64`。它们把已完成目标的 DMG 或 EXE 上传到 `desktop/dsh-latest-macos-arm64.dmg`、`desktop/dsh-latest-macos-x64.dmg` 或 `desktop/dsh-latest-windows-x64.exe`。生产 URL 以 `https://download.deepseek.com/` 开头;测试 URL 使用 `DOWNLOAD_TEST_ORIGIN`。两个部署环境均复用目标 dotenv 中的部署、bucket 和凭据、全部常规发布校验以及下述上传审计。每个命令覆盖一个固定对象,不发布更新清单、blockmap 或发布标签。测试固定下载在测试 bucket 中跨发布 ID 共享;包内更新 URL 仍要求原有发布 ID。发布由操作人员显式执行,也允许预发布版本。部署基础设施必须配置重新验证,或在覆盖后清除固定下载的缓存。本地回环测试覆盖上传行为;真实 COS 和 CDN 验收由发布操作人员负责。 + + + +## 上传凭据 + +Windows 操作人员可以在仓库外保存 CLIXML 对象,其中 `SecretId` 和 `SecretKey` 是经 DPAPI 加密的 SecureString 字段。[凭据启动器](../scripts/upload-with-credentials.ps1)要求显式提供 `-CredentialFile` 和 `-Environment production` 或 `test`;不指定 `-Upload` 时,只验证解密以及向本地 Node 子进程注入凭据,不发起网络请求。它要求 `PATH` 中有 Node,并使用加密该文件时的 Windows 用户和机器。明文、空字段及纯空白字段都会失败。父进程环境保持不变;子进程先清除无关密钥与 Node 预加载选项,再仅接收所选 COS 凭据对。原始子进程 stderr 不会显示,stdout 中的凭据值会被遮盖。此检查不能证明 COS 授权有效。显式上传还要求 `-Upload -Target -Bucket ` 及下述常规发布完成前提;真实云端上传仍需发布操作人员验收。在该上传调用中添加 `-Latest`,即可替换固定安装包,而不发布更新清单或发布标签。此启动器支持长期密钥,不支持 STS 凭据。显式上传要求所选部署环境和 bucket 与目标 dotenv 文件及已完成的打包记录一致,才会发起网络写入;即使 dotenv 文件含有其他 COS 密钥,也使用 DPAPI 凭据对。 + + + +## 上传审计与恢复 + +test 与 production 的 `upload:*` 上传在发布前置检查通过后,分别保留新的 `.desktop-build/upload-records/--*` 目录。`plan.json` 记录目标、版本、每个文件的大小/SHA-512 和发布的 YAML 字节;刷盘的 `events.jsonl` 记录 PUT 意图及可用的响应状态/请求 ID;`result.json` 记录完成结果或最后失败阶段。缺少最终结果表示中断或存储不可用,不表示成功。不记录凭据值、认证头或原始 SDK 错误。审计写入失败即停止后续 PUT。每个对象都以一次流式腾讯 COS PUT 上传,并携带显式长度与 Content-MD5;COS SDK 仅在请求体不是流时才会重发请求,上传器自身也不重试。保留部分记录,检查远端状态后再执行下一次操作:超时或回执写入失败不能证明对象未存储。这些记录仅在本地,不防篡改,也不会自动备份;每次发布应将它们与构建证据一同归档到受控存储。公网 CDN 回读仍是单独的发布验收,上传结果明确标记为 `not-performed`。 + +## 开发备注 + +无。 diff --git a/apps/desktop/publishing/ci/README.i18n.yaml b/apps/desktop/publishing/ci/README.i18n.yaml new file mode 100644 index 0000000000..b5f7e587e8 --- /dev/null +++ b/apps/desktop/publishing/ci/README.i18n.yaml @@ -0,0 +1,31 @@ +# 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 apps/desktop/publishing/ci/README.md +/: + en: 5bbdeb4ea94502b4 + zh: 107894e10c74d22d +/desktop-ci-publication: + en: a610b66106849734 + zh: bc1760791f56fa28 +/desktop-ci-publication/summary: + en: 470bdf1487a739f9 + zh: cd80330eaa8f730c +/desktop-ci-publication/table-of-contents: + en: 1b6a4d7146879eec + zh: f2520fc412cd2d2a +/desktop-ci-publication/machine-setup: + en: 990ff7e56dd6005a + zh: 18f9dc23c520dc8c +/desktop-ci-publication/package-and-publish: + en: 6e29eb0dff23e2c8 + zh: 65d5d57b63b86904 +/desktop-ci-publication/recovery-and-records: + en: 370f21dc25fc1098 + zh: cf7f433b8eaa3dcd +/desktop-ci-publication/restore-a-channel: + en: d82e2ccf70cce397 + zh: d93dcb77cc4b463e +/desktop-ci-publication/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/apps/desktop/publishing/ci/README.md b/apps/desktop/publishing/ci/README.md new file mode 100644 index 0000000000..98bbb3cb3c --- /dev/null +++ b/apps/desktop/publishing/ci/README.md @@ -0,0 +1,68 @@ +--- +description: "Operate retained Desktop package publication from dedicated macOS and Windows runners." +--- + +# Desktop CI publication + +English | [中文](README.zh.md) + +## Summary + +Publish a completed package from its original machine without downloading its installer again. Both test and production publish binaries followed by update YAML. Both deployments require GitHub Environment approval; only production creates a GitHub App tag. Real COS, CDN and administrator-permission acceptance remain deployment checks; local fixtures do not establish those permissions. + +## Table of Contents + +- [Machine setup](#machine-setup) +- [Package and publish](#package-and-publish) +- [Recovery and records](#recovery-and-records) +- [Restore a channel](#restore-a-channel) + + + +## Machine setup + +Keep `DSH_PACKAGING_CONFIG_DIR` pointed at the existing machine packaging directory. Completed attempts are copied to its sibling `releases///`; `DSH_DESKTOP_RELEASES_DIR` overrides that root with an absolute path. The inventory includes installers, update archives, blockmaps, completion metadata and a credential-free manifest. Debug packages are retained but cannot publish. Copies are checked before the attempt directory becomes visible, and an existing attempt cannot be replaced. GitHub retains the same file inventory for 14 days. Local files remain until an operator removes them; do not delete an attempt while it is being verified or published. + +Create `publishing/test.json` and, when authorized, `publishing/production.json` below the configuration directory. Each declares `bucket`, HTTPS `origin` without a path, and an absolute `credentialsFile`. The credential file contains only `secretId` and `secretKey`. macOS also requires `macOS.signingIdentity` and `macOS.teamId`; Windows requires `windows.certificateThumbprint`. Production requires the exact origin `https://download.deepseek.com` and `githubApp.clientId` plus an absolute `githubApp.privateKeyFile`. These files stay outside Git. The uploader supports permanent COS credentials, not STS session credentials. Bucket versioning must be disabled for immutable binary writes. + +Set the repository variable `DESKTOP_PUBLISH_RUNNERS` to a JSON mapping of registered runner names to unique labels and targets, for example `{"mini":{"label":"dsh-mini-publish","target":"mac-arm64"}}`. Assign that label to exactly that runner. Windows uses target `win-x64`. The routing job checks the original successful job, and the publisher checks its own runner name against the recorded name. Machines need no shared filesystem or LAN connection to each other. + +An administrator must create `desktop-test` and `desktop-production`, each with required reviewers and an allowed `master` deployment branch. The workflow checks reviewers for either deployment. Test can allow self-approval. The GitHub App needs installation access to this repository and Contents write permission, plus permission under the `desktop-v*` tag ruleset to create release tags. Reviewer approval does not transfer the reviewer's tag permissions to the App. Missing configuration stops publication; there is no personal-token fallback. The App action creates and later revokes a short-lived token. Protect the local private key and COS credential files with the publishing account's filesystem permissions. The token action accepts key contents, so the masked PEM also passes through the runner's temporary `GITHUB_OUTPUT` file during the job; masking hides logs, not local file access. + +Environment approval gates this workflow, not arbitrary code running under the same machine account. Account isolation and forced source-branch restrictions are separate operational work. Keep existing release Environments unchanged. The test job uses its own reviewers and never creates a real release tag; local simulated transports exercise tag creation and recovery without verifying App permissions. + + + +## Package and publish + +Select the platform's `Package Desktop` workflow, preset, source, channel and version mode. `source_ref` accepts `master` or `dsh-v*` matching the selected product version; the selected source must contain these CI adapters, so older tags fail before dependency installation. The publisher runs from the default branch while recording the actual source commit separately. `version_mode=default` selects product for production and auto for test; product preserves the selected checkout version, auto appends date/run/attempt, and manual requires `build_version`. A latest package requires a stable version, so test/latest needs product or a stable manual version. The optional `test_release_id` is the test URL prefix: blank retains the machine default, successive upgrade tests on that platform need the same value, and defaults should be rotated periodically. It is not a GitHub run ID. See [packaging configuration](../../packaging/README.md#configuration-and-local-builds) for its validation and rotation limits. + +Select `publish` to request publication after packaging succeeds. Windows must be signed; macOS must finish notarization and stapling. The separate `Publish Desktop · COS` workflow reads the small request manifest from GitHub, binds it to the source run and attempt, and routes to the original machine. It uses the locally retained installers. A failed build or one without a publication request produces no upload. + +Before uploading, the publisher hashes all retained files, checks version and destination metadata, and rechecks the platform signatures. macOS verifies the DMG and extracts the ZIP to verify the app's ticket; Windows checks Authenticode, the configured signer thumbprint and the timestamp. Preparation writes an approval summary with version, channel, platform, deployment, source ref/SHA, package run/attempt, object keys and proposed tag. Both publishing jobs wait for **Review deployments → Approve and deploy**, then recheck the approved manifest and upload plan digest. Changed bytes or destinations reject. Approval cannot edit a version; reject and rebuild instead. Both deployments upload missing binaries, verify remote bytes, then update YAML. There is no files-only mode in this workflow. Production finally creates `desktop-v` at the recorded packaging commit; an existing tag must name the same commit. + + + +## Recovery and records + +Re-run the publishing workflow after resolving a failure; do not rebuild solely to retry an upload. Its source package run and attempt remain fixed. Missing objects are uploaded, identical objects are skipped, and conflicting same-name bytes stop the operation. Unknown write outcomes are reconciled by reading remote bytes. A newer channel version prevents a stale upload from replacing it. Each package updates only its embedded channel: nightly writes `nightly.yml` / `nightly-mac.yml`, latest writes `latest.yml` / `latest-mac.yml`. Latest binaries use a `latest/` subdirectory under the target binary prefix, separate from existing nightly objects. Publishing the same source/version to both channels requires two packages; an existing release tag is reused only for the same source commit. + +The sibling `upload-records/` directory retains an operation identity, newline-delimited events and terminal result. Feed-write intents retain both previous and requested YAML. Failures record their stage, safe error classification and diagnostic; raw provider responses are excluded. Audit initialization becomes visible only after its files are complete; abandoned `.initializing-*` directories are not scanned for completed publication. Writes and readback are recorded before proceeding; missing terminal results mean interruption, not success. Actions also keeps its operation record as a diagnostic artifact for 30 days. These local records are not tamper-proof. COS readback verifies storage bytes, not public CDN behavior; public download acceptance is separate. + +If the feed completed but tagging failed, the result is `published-tag-pending` and the job fails visibly. On retry, durable feed-completion evidence permits only tag recovery, even if a later release has advanced the channel. It never re-publishes old YAML. An existing conflicting tag requires administrator investigation and is never moved automatically. + +Normal publication and manual restoration acquire the same local channel lock. A crash can leave a lock directory under the sibling `publish-locks/`; verify no writer is running before manually removing it. A runner label alone does not coordinate writers on other machines. Keep one publishing machine per channel and preserve its records when migrating. + + + +## Restore a channel + +Run the repository script `apps/desktop/scripts/rollback-desktop-channel.ts` through `node --import tsx` on the publishing machine. Keep `GITHUB_REPOSITORY`, `RUNNER_NAME`, `DSH_PACKAGING_CONFIG_DIR` and `DESKTOP_PUBLISH_ROUTE` set to the original package context. The route JSON contains `runId`, `attempt`, `commit`, `runnerName`, `target`, `preset`, `sourceRef` and `channel`, available in the retained manifest's source fields. Pass `--record` with that successful publication's audit directory, `--expected-version` with the version currently online, and `--reason` with the operational reason. + +Without `--execute`, the script reads remote objects and prints the exact YAML change without writing. Preview requires COS read credentials. With `--execute`, it verifies historical files, preserves before/after YAML in a new audit record, checks the current channel again, and restores only YAML. It neither uploads binaries nor changes tags. A channel already matching the target bytes is skipped; other channels must match the expected current version. This permits recovery after one feed was restored before an interruption. A different current version aborts the operation. Restoration is not a multi-object transaction; inspect the audit after any partial failure before continuing. + +The Desktop client disables automatic downgrade. Restoring an old feed can stop additional clients receiving a bad release; clients already on a newer version do not downgrade. A higher-version corrective release is a separate recovery path. + +## Dev Note + +None. diff --git a/apps/desktop/publishing/ci/README.zh.md b/apps/desktop/publishing/ci/README.zh.md new file mode 100644 index 0000000000..d689d2a85e --- /dev/null +++ b/apps/desktop/publishing/ci/README.zh.md @@ -0,0 +1,68 @@ +--- +description: "在专用 macOS 和 Windows runner 上发布留存的 Desktop 安装包。" +--- + +# Desktop CI 发布 + +[English](README.md) | 中文 + +## 概述 + +在原打包机器上发布完整安装包,无需再次下载安装包。test 和 production 都先发布二进制文件,再更新 YAML。两种环境都需要 GitHub Environment 审批;只有 production 通过 GitHub App 创建 tag。真实 COS、CDN 和管理员权限仍需部署验收;本地 fixture 不证明这些权限可用。 + +## 目录 + +- [机器配置](#machine-setup) +- [打包与发布](#package-and-publish) +- [恢复与记录](#recovery-and-records) +- [恢复频道](#restore-a-channel) + + + +## 机器配置 + +保持 `DSH_PACKAGING_CONFIG_DIR` 指向现有机器打包目录。完成的构建复制到其同级 `releases///`;`DSH_DESKTOP_RELEASES_DIR` 可用绝对路径覆盖该根目录。文件清单包含安装包、更新归档、blockmap、完成记录和不含凭据的 manifest。调试包会留存,但不能发布。复制内容通过校验后才开放 attempt 目录,已有 attempt 不能被替换。GitHub 保留相同文件清单 14 天。本地文件保留到操作员删除;校验或发布期间不要删除对应 attempt。 + +在配置目录下创建 `publishing/test.json`,获得授权后再创建 `publishing/production.json`。每份配置声明 `bucket`、不带路径的 HTTPS `origin` 和绝对路径 `credentialsFile`。凭据文件只包含 `secretId` 和 `secretKey`。macOS 还需 `macOS.signingIdentity` 和 `macOS.teamId`;Windows 需要 `windows.certificateThumbprint`。production 必须使用 origin `https://download.deepseek.com`,并提供 `githubApp.clientId` 和绝对路径 `githubApp.privateKeyFile`。这些文件不进入 Git。上传器支持长期 COS 凭据,不支持 STS 会话凭据。不可覆盖的二进制写入要求 bucket 版本控制关闭。 + +将仓库变量 `DESKTOP_PUBLISH_RUNNERS` 配置为已注册 runner 名称到唯一标签和目标的 JSON 映射,例如 `{"mini":{"label":"dsh-mini-publish","target":"mac-arm64"}}`。该标签只能分配给这台 runner。Windows 使用目标 `win-x64`。路由 job 检查原构建成功的 job,发布器再检查自身 runner 名称与记录一致。机器之间不需要共享文件系统或局域网连接。 + +管理员必须创建 `desktop-test` 和 `desktop-production`,分别设置必需审批人并允许 `master` 部署分支。工作流会检查两种环境的审批人配置。test 可允许发起者自行审批。GitHub App 需要安装到本仓库、具有 Contents write 权限,并获准在 `desktop-v*` tag ruleset 下创建发布 tag。审批不会把审批人的 tag 权限传给 App。缺少配置会停止发布,不回退到个人 token。App action 创建短期 token,并在结束后撤销。使用发布账户的文件系统权限保护本机私钥及 COS 凭据文件。token action 需要密钥内容,因此已屏蔽日志的 PEM 在 job 期间也会经过 runner 临时 `GITHUB_OUTPUT` 文件;日志屏蔽不限制本地文件访问。 + +Environment 审批限制此工作流,不限制同一机器账户运行的任意代码。账户隔离和强制源分支限制属于独立运维工作。保持现有发布 Environment 不变。test job 使用自己的审批人,不创建真实发布 tag;本地模拟接口覆盖 tag 创建与恢复,但不验证 App 权限。 + + + +## 打包与发布 + +选择对应平台的 `Package Desktop` 工作流、preset、源码、通道和版本模式。`source_ref` 接受 `master` 或与所选产品版本一致的 `dsh-v*`;源码必须包含这些 CI 适配脚本,因此旧 tag 会在安装依赖前失败。发布器从默认分支运行,单独记录实际源码提交。`version_mode=default` 对 production 选择 product,对 test 选择 auto;product 保留所选源码版本,auto 追加日期/run/attempt,manual 要求填写 `build_version`。latest 包要求稳定版本,因此 test/latest 需选择 product 或稳定的手填版本。可选 `test_release_id` 是测试 URL 前缀:留空沿用机器默认值,同一平台连续升级测试需保持相同值,并应定期轮换默认值。它不是 GitHub run ID。格式校验和轮换限制见[打包配置](../../packaging/README.zh.md#configuration-and-local-builds)。 + +选中 `publish`,请求在打包成功后发布。Windows 必须签名;macOS 必须完成公证和 stapling。独立的 `Publish Desktop · COS` 工作流从 GitHub 读取小型请求 manifest,将其与原 run 和 attempt 核对,再路由到原机器。安装包使用本机留存文件。构建失败或未请求发布时不会上传。 + +上传前,发布器校验全部留存文件的哈希、版本及目标信息,再复核平台签名。macOS 校验 DMG,并解压 ZIP 校验 app 票据;Windows 校验 Authenticode、配置的签名证书指纹及时间戳。准备阶段生成审批摘要,列出版本、通道、平台、环境、源码 ref/SHA、package run/attempt、对象路径及拟创建的 tag。两种发布 job 均等待 **Review deployments → Approve and deploy**,随后重新核对已批准的 manifest 与上传计划摘要。文件或目标变化会被拒绝。审批不能修改版本;应拒绝并重新打包。两种环境都上传缺失文件、校验远端字节,再更新 YAML。此工作流没有只上传文件的模式。production 最后为记录的打包提交创建 `desktop-v`;已有 tag 必须指向同一提交。 + + + +## 恢复与记录 + +解决故障后重跑发布工作流,不要仅为重试上传而重新打包。原 package run 和 attempt 保持不变。缺失对象会上传,相同对象跳过,同名但字节不同的对象会停止操作。写入结果不明时通过读取远端字节核对。频道已有更高版本时,旧上传不能替换它。每个包只更新自身内置通道:nightly 写入 `nightly.yml` / `nightly-mac.yml`,latest 写入 `latest.yml` / `latest-mac.yml`。latest 二进制位于目标二进制前缀下的 `latest/` 子目录,与已有 nightly 对象分离。同一源码和版本发布到两个通道需要分别打包;已有发布 tag 仅在源码提交相同时复用。 + +同级 `upload-records/` 目录保留操作标识、逐行事件和最终结果。频道写入意图同时记录先前和目标 YAML。失败记录阶段、安全错误分类与诊断,不保存原始服务响应。审计初始化在文件完整后才可见;遗留的 `.initializing-*` 目录不参与已完成发布的扫描。写入和回读在继续操作前落盘;没有最终结果代表中断,不代表成功。Actions 还将操作记录保存为诊断 artifact,保留 30 天。这些本地记录不防篡改。COS 回读验证存储字节,不代表公开 CDN 行为;公开下载需单独验收。 + +频道更新完成但 tag 失败时,结果为 `published-tag-pending`,job 明确失败。重试时,已落盘的频道完成证据只允许恢复 tag,即使后来发布已推进频道,也不会重新发布旧 YAML。已有冲突 tag 需要管理员调查,不会自动移动。 + +正常发布和手动恢复获取同一把本地频道锁。崩溃可能在同级 `publish-locks/` 下留下锁目录;手动删除前确认没有写入任务运行。runner 标签本身不能协调其他机器的写入。每个频道保持单一发布机器,迁移时保留记录。 + + + +## 恢复频道 + +在发布机器上通过 `node --import tsx` 运行仓库脚本 `apps/desktop/scripts/rollback-desktop-channel.ts`。保持 `GITHUB_REPOSITORY`、`RUNNER_NAME`、`DSH_PACKAGING_CONFIG_DIR` 和 `DESKTOP_PUBLISH_ROUTE` 对应原打包上下文。route JSON 包含 `runId`、`attempt`、`commit`、`runnerName`、`target`、`preset`、`sourceRef` 和 `channel`,可从留存 manifest 的 source 字段取得。`--record` 指定该次成功发布的审计目录,`--expected-version` 指定当前线上版本,`--reason` 填写操作原因。 + +不带 `--execute` 时,脚本读取远端对象并打印确切 YAML 变更,不执行写入。预览需要 COS 读取凭据。带 `--execute` 时,脚本校验历史文件,将前后 YAML 保存在新的审计记录中,再次检查当前频道,然后仅恢复 YAML。它不上传二进制文件,也不改变 tag。已经与目标字节完全相同的频道会跳过,其余频道必须匹配预期当前版本,因此可以恢复写完一个 feed 后中断的操作。其他当前版本会中止操作。恢复不是多对象事务;部分失败后需先检查审计记录再继续。 + +Desktop 客户端禁用自动降级。恢复旧 feed 可以阻止更多客户端获得问题版本,已经安装更高版本的客户端不会降级。发布更高版本号的修正版是独立恢复方式。 + +## 开发备注 + +无。 diff --git a/apps/desktop/scripts/desktop-auto-update-environment.d.mts b/apps/desktop/scripts/desktop-auto-update-environment.d.mts index 00ebf8c5c0..f656f9baaf 100644 --- a/apps/desktop/scripts/desktop-auto-update-environment.d.mts +++ b/apps/desktop/scripts/desktop-auto-update-environment.d.mts @@ -10,6 +10,7 @@ export type DesktopAutoUpdateTarget = 'mac-arm64' | 'mac-x64' | 'win-x64' /** Public updater URL and object prefixes for one release target. */ export interface DesktopAutoUpdateConfig { readonly environment: DesktopAutoUpdateEnvironment + readonly channel: 'nightly' | 'latest' readonly target: DesktopAutoUpdateTarget readonly origin: string readonly publicUrl: string @@ -60,6 +61,7 @@ export function desktopBuildRecordFilename(target: DesktopAutoUpdateTarget): str export function desktopUpdateMetadataFilename( version: string, platform: NodeJS.Platform, + channel?: 'nightly' | 'latest', ): string /** @@ -89,3 +91,10 @@ export function resolveDesktopUploadConfig( platform: NodeJS.Platform, arch: string, ): DesktopUploadConfig + +/** + * Resolve the packaged update channel, defaulting omitted local settings to nightly. + * @param env Packaging settings. + * @returns Validated channel. + */ +export function resolveDesktopUpdateChannel(env: NodeJS.ProcessEnv): 'nightly' | 'latest' diff --git a/apps/desktop/scripts/desktop-auto-update-environment.mjs b/apps/desktop/scripts/desktop-auto-update-environment.mjs index 464d079b4d..a1973a9c64 100644 --- a/apps/desktop/scripts/desktop-auto-update-environment.mjs +++ b/apps/desktop/scripts/desktop-auto-update-environment.mjs @@ -5,6 +5,17 @@ import { valid } from 'semver' /** Environment variable that selects the Desktop update deployment. */ export const DESKTOP_AUTO_UPDATE_ENV = 'DSH_DESKTOP_AUTO_UPDATE_ENV' +/** + * Resolve the channel embedded in the installer; omitted local settings retain nightly. + * @param {NodeJS.ProcessEnv} env Packaging or upload settings. + * @returns {'nightly' | 'latest'} Validated channel. + */ +export function resolveDesktopUpdateChannel(env) { + const channel = env.DSH_DESKTOP_UPDATE_CHANNEL || 'nightly' + if (channel !== 'nightly' && channel !== 'latest') throw new Error('desktop auto-update: invalid update channel') + return channel +} + const UPDATE_ENVIRONMENTS = { test: { originEnvName: 'DOWNLOAD_TEST_ORIGIN', @@ -68,16 +79,18 @@ export function desktopBuildRecordFilename(target) { * Return the electron-builder channel metadata filename for an application version. * @param {string} version - Desktop semantic version. * @param {NodeJS.Platform} platform - Target platform. + * @param {'nightly' | 'latest'} channel - Selected channel; omitted means nightly. * @returns {string} Channel metadata filename emitted for the target. */ -export function desktopUpdateMetadataFilename(version, platform) { +export function desktopUpdateMetadataFilename(version, platform, channel = 'nightly') { if (valid(version) === null) { throw new Error(`desktop auto-update: invalid Desktop version ${JSON.stringify(version)}`) } if (platform !== 'darwin' && platform !== 'win32') { throw new Error(`desktop auto-update: unsupported metadata platform ${platform}`) } - return `nightly${platform === 'darwin' ? '-mac' : ''}.yml` + resolveDesktopUpdateChannel({ DSH_DESKTOP_UPDATE_CHANNEL: channel }) + return `${channel}${platform === 'darwin' ? '-mac' : ''}.yml` } /** @@ -124,10 +137,11 @@ function httpsOrigin(value, name) { * @param {NodeJS.ProcessEnv} env - Packaging or upload environment. * @param {NodeJS.Platform} platform - Target Node.js platform. * @param {string} arch - Target Node.js architecture. - * @returns {{ environment: 'test' | 'production', target: 'mac-arm64' | 'mac-x64' | 'win-x64', origin: string, publicUrl: string, keyPrefix: string, binaryKeyPrefix: string }} Resolved updater configuration. + * @returns {{ environment: 'test' | 'production', channel: 'nightly' | 'latest', target: 'mac-arm64' | 'mac-x64' | 'win-x64', origin: string, publicUrl: string, keyPrefix: string, binaryKeyPrefix: string }} Resolved updater configuration. * @throws {Error} When the test deployment lacks a valid HTTPS origin or a 32-character lowercase hexadecimal release ID. */ export function resolveDesktopAutoUpdateConfig(env, platform, arch) { + const channel = resolveDesktopUpdateChannel(env) const environment = resolveDesktopAutoUpdateEnvironment(env) const target = resolveDesktopAutoUpdateTarget(platform, arch) const deployment = UPDATE_ENVIRONMENTS[environment] @@ -148,10 +162,11 @@ export function resolveDesktopAutoUpdateConfig(env, platform, arch) { const keyPrefix = `${releasePrefix}/feeds/${target}` return { environment, + channel, target, origin, keyPrefix, - binaryKeyPrefix: `${releasePrefix}/bin/${target}`, + binaryKeyPrefix: `${releasePrefix}/bin/${target}${channel === 'latest' ? '/latest' : ''}`, publicUrl: `${origin}/${keyPrefix}/`, } } @@ -161,7 +176,7 @@ export function resolveDesktopAutoUpdateConfig(env, platform, arch) { * @param {NodeJS.ProcessEnv} env - Upload environment. * @param {NodeJS.Platform} platform - Target Node.js platform. * @param {string} arch - Target Node.js architecture. - * @returns {{ environment: 'test' | 'production', target: 'mac-arm64' | 'mac-x64' | 'win-x64', origin: string, publicUrl: string, keyPrefix: string, binaryKeyPrefix: string, bucket: string, secretIdEnvName: string, secretKeyEnvName: string }} Resolved upload configuration. + * @returns {{ environment: 'test' | 'production', channel: 'nightly' | 'latest', target: 'mac-arm64' | 'mac-x64' | 'win-x64', origin: string, publicUrl: string, keyPrefix: string, binaryKeyPrefix: string, bucket: string, secretIdEnvName: string, secretKeyEnvName: string }} Resolved upload configuration. * @throws {Error} When the selected deployment lacks a bucket or valid updater configuration. */ export function resolveDesktopUploadConfig(env, platform, arch) { diff --git a/apps/desktop/scripts/desktop-build-paths.d.mts b/apps/desktop/scripts/desktop-build-paths.d.mts index 9a8e408ed1..c7b8173ca1 100644 --- a/apps/desktop/scripts/desktop-build-paths.d.mts +++ b/apps/desktop/scripts/desktop-build-paths.d.mts @@ -5,6 +5,7 @@ export interface DesktopTargetBuildPaths { readonly root: string readonly artifacts: string readonly unsignedArtifacts: string + readonly unnotarizedArtifacts: string readonly runtime: string readonly packageSet: string readonly dsh: string @@ -72,3 +73,14 @@ export function developmentRuntimeDirectory( hostPlatform?: NodeJS.Platform, hostArch?: string, ): string + +/** + * Select the output directory and filename suffix for one packaging mode. + * @param paths Target artifact directories. + * @param mode Validated packaging mode. + * @returns Matching artifact destination and filename marker. + */ +export function desktopArtifactOutput( + paths: Pick, + mode: { unsigned: boolean, skipNotarization: boolean }, +): { directory: string, suffix: string } diff --git a/apps/desktop/scripts/desktop-build-paths.mjs b/apps/desktop/scripts/desktop-build-paths.mjs index 4f33e804c3..e577b1d3fe 100644 --- a/apps/desktop/scripts/desktop-build-paths.mjs +++ b/apps/desktop/scripts/desktop-build-paths.mjs @@ -38,7 +38,7 @@ function assertSupportedTarget(target) { /** * Return the mutable preparation and artifact directories owned by one release target. * @param {'mac-arm64' | 'mac-x64' | 'win-x64'} target - Supported Desktop target name. - * @returns {{ root: string, artifacts: string, unsignedArtifacts: string, runtime: string, packageSet: string, dsh: string, dshPnpm: string, electron: string, packedDsh: string, packedVendor: string, packedLandlock: string, downloads: string }} Target paths plus the shared immutable download cache. + * @returns {{ root: string, artifacts: string, unsignedArtifacts: string, unnotarizedArtifacts: string, runtime: string, packageSet: string, dsh: string, dshPnpm: string, electron: string, packedDsh: string, packedVendor: string, packedLandlock: string, downloads: string }} Target paths plus the shared immutable download cache. */ export function desktopTargetBuildPaths(target) { assertSupportedTarget(target) @@ -48,6 +48,7 @@ export function desktopTargetBuildPaths(target) { root, artifacts: join(root, 'artifacts'), unsignedArtifacts: join(root, 'unsigned-artifacts'), + unnotarizedArtifacts: join(root, 'unnotarized-artifacts'), runtime: join(root, 'runtime'), packageSet: join(root, 'package-set'), dsh: join(root, 'dsh'), @@ -105,3 +106,15 @@ export function developmentRuntimeDirectory( ) { return join(resolveDesktopTargetBuildPaths(env, hostPlatform, hostArch).runtime, 'primary-runtime') } + +/** + * Select the output directory and filename suffix for one packaging mode. + * @param {{ artifacts: string, unsignedArtifacts: string, unnotarizedArtifacts: string }} paths Target artifact directories. + * @param {{ unsigned: boolean, skipNotarization: boolean }} mode Validated packaging mode. + * @returns {{ directory: string, suffix: string }} Matching artifact destination and filename marker. + */ +export function desktopArtifactOutput(paths, mode) { + if (mode.unsigned) return { directory: paths.unsignedArtifacts, suffix: '-unsigned' } + if (mode.skipNotarization) return { directory: paths.unnotarizedArtifacts, suffix: '-unnotarized' } + return { directory: paths.artifacts, suffix: '' } +} diff --git a/apps/desktop/scripts/desktop-build-version-discovery.ts b/apps/desktop/scripts/desktop-build-version-discovery.ts index fd5a2c9e10..68291ca3b8 100644 --- a/apps/desktop/scripts/desktop-build-version-discovery.ts +++ b/apps/desktop/scripts/desktop-build-version-discovery.ts @@ -2,7 +2,7 @@ * Suggest the next build version for a product version, so the sequence number * is derived rather than remembered. * - * `apps/desktop/README.md` gives the form as `..` + * `apps/desktop/packaging/README.md#release-versions` gives the form as `..` * for a prerelease base and `-test..` for a * stable one. What makes an index correct is which ones are taken, and that is * recorded where the builds went: the update bucket for an uploaded build, the @@ -30,8 +30,8 @@ const LISTING_DEADLINE_MS = 8_000 /** Objects one listing page may return. */ const LISTING_PAGE_SIZE = 1000 -/** Artifact name electron-builder writes for one build, on either platform; unsigned builds add a suffix. */ -const ARTIFACT = /(?:^|\/)deepseek-harness-(?.+)-(?:mac|win)-(?:arm64|x64)(?:-unsigned)?\.(?:exe|dmg|zip)$/u +/** Artifact name electron-builder writes for one build, on either platform; unsigned and unnotarized builds add a suffix. */ +const ARTIFACT = /(?:^|\/)deepseek-harness-(?.+)-(?:mac|win)-(?:arm64|x64)(?:-unsigned|-unnotarized)?\.(?:exe|dmg|zip)$/u /** Inputs that decide which versions are already taken. */ export interface DesktopBuildVersionSuggestionOptions { diff --git a/apps/desktop/scripts/desktop-build-version.mjs b/apps/desktop/scripts/desktop-build-version.mjs index e2152ce0d3..bddf4ca492 100644 --- a/apps/desktop/scripts/desktop-build-version.mjs +++ b/apps/desktop/scripts/desktop-build-version.mjs @@ -2,12 +2,15 @@ * Resolve the version one build publishes, which is not always the version the * repository declares. * + * Manual Desktop CI uses UTC date, workflow run number and attempt as + * `.YYYYMMDD.run.attempt`; these identify unpublished builds, not release sequences. + * * A production release publishes the version in the manifests, aligned with the * `dsh` npm package. A test build publishes a version that appends a date and a * sequence number, so one test feed can carry several builds of a single * product version: `0.1.6-alpha.1.20260916.1` from a prerelease base and * `0.1.6-test.20260916.1` from a stable one, as the release versions table in - * `apps/desktop/README.md` gives them. Passing that version here keeps it out + * `apps/desktop/packaging/README.md#release-versions` gives them. Passing that version here keeps it out * of the manifests, so the tracked version stays the product's while the build * version reaches electron-builder, the update feed, and the upload validation * as one input. @@ -71,7 +74,8 @@ export function validateDesktopBuildVersion(buildVersion, productVersion) { && required.every((field, index) => build.prerelease[index] === field) if (!extendsProduct) { throw new Error(`desktop build version: ${buildVersion} must extend ${productVersion} as ${ - desktopBuildVersionPrefix(productVersion)}.`) + desktopBuildVersionPrefix(productVersion)}. or ${ + desktopBuildVersionPrefix(productVersion)}..`) } return build.version } diff --git a/apps/desktop/scripts/desktop-ci-version.d.mts b/apps/desktop/scripts/desktop-ci-version.d.mts new file mode 100644 index 0000000000..213e96fd1a --- /dev/null +++ b/apps/desktop/scripts/desktop-ci-version.d.mts @@ -0,0 +1,10 @@ +/** Resolve the version used by the manual Desktop packaging workflow. */ + +/** + * 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 build version. + */ +export function desktopCiVersion(environment: NodeJS.ProcessEnv, productVersion: string, now?: Date): string diff --git a/apps/desktop/scripts/desktop-ci-version.mjs b/apps/desktop/scripts/desktop-ci-version.mjs new file mode 100644 index 0000000000..8fef629287 --- /dev/null +++ b/apps/desktop/scripts/desktop-ci-version.mjs @@ -0,0 +1,34 @@ +/** Resolve manual Desktop CI build versions without release storage access. */ +import { desktopBuildVersionPrefix, validateDesktopBuildVersion } from './desktop-build-version.mjs' + +/** + * 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 {string} Validated build version. + */ +export function desktopCiVersion(environment, productVersion, now = new Date()) { + const mode = environment.PACKAGE_VERSION_MODE + const selected = mode === 'default' ? (environment.DSH_PACKAGING_PRESET === 'production' ? 'product' : 'auto') : mode + if (selected !== undefined && !['product', 'auto', 'manual'].includes(selected)) throw new Error('Invalid version mode') + const requested = selected === 'product' ? productVersion : selected === 'auto' ? 'auto' : environment.PACKAGE_BUILD_VERSION?.trim() + if (selected === 'manual' && (!requested || requested === 'auto')) throw new Error('Manual version mode requires an explicit 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`) + } + candidate = `${desktopBuildVersionPrefix(productVersion)}${date}.${environment.GITHUB_RUN_NUMBER}.${environment.GITHUB_RUN_ATTEMPT}` + } + if (environment.DSH_DESKTOP_UPDATE_CHANNEL === 'latest' && candidate.includes('-')) throw new Error('Latest channel requires a stable version; select product or manual stable version') + try { + const resolved = validateDesktopBuildVersion(candidate, productVersion) + return resolved + } catch { + throw new Error(`Invalid build version for this checkout: use auto, ${productVersion}, or e.g. ${example}`) + } +} diff --git a/apps/desktop/scripts/desktop-package-environment.d.mts b/apps/desktop/scripts/desktop-package-environment.d.mts index a49ca46eb9..995c117d07 100644 --- a/apps/desktop/scripts/desktop-package-environment.d.mts +++ b/apps/desktop/scripts/desktop-package-environment.d.mts @@ -8,16 +8,19 @@ 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 machine preset when selected, otherwise the target's required dotenv; no ambient release fallback. + * PACKAGE_TEST_RELEASE_ID overrides the test preset only; blank retains its configured ID. * @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 presets and Windows 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 /** @@ -30,5 +33,5 @@ export function loadDesktopPackageEnvironment( export function validateDesktopPackageEnvironment( environment: NodeJS.ProcessEnv, target: { platform: 'win32' | 'darwin', arch: string }, - options?: { unsigned?: boolean, prepareOnly?: boolean }, + options?: { unsigned?: boolean, prepareOnly?: boolean, skipNotarization?: boolean }, ): void diff --git a/apps/desktop/scripts/desktop-package-environment.mjs b/apps/desktop/scripts/desktop-package-environment.mjs index 51b878100a..8116dea245 100644 --- a/apps/desktop/scripts/desktop-package-environment.mjs +++ b/apps/desktop/scripts/desktop-package-environment.mjs @@ -1,13 +1,14 @@ /** 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' import { resolveDesktopAutoUpdateConfig } from './desktop-auto-update-environment.mjs' import { createWindowsTokenSigner } from './windows-sign.mjs' import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs' +import { validateMacOSSignatureCacheDirectory } from './macos-signature-cache-directory.mjs' import { resolveMacOSPackageSettings } from './macos-package-settings.mjs' import { resolveWindowsSignatureCacheDirectory } from './windows-signature-cache-directory.mjs' import { resolveWindowsPackageSettings } from './windows-package-settings.mjs' @@ -15,7 +16,7 @@ import { resolveWindowsPackageSettings } from './windows-package-settings.mjs' const APP_ROOT = fileURLToPath(new URL('..', import.meta.url)) const SHARED_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|NPM_REGISTRY|MANDATORY_UPDATE_(?:CONFIG|(?:TEST|PROD)_ORIGIN))|DOWNLOAD_TEST_RELEASE_ID|DOWNLOAD_(?:TEST|PROD)_(?:ORIGIN|COS_BUCKET|COS_SECRET_ID|COS_SECRET_KEY))$/u const WINDOWS_SETTING = /^DSH_DESKTOP_WINDOWS_(?:CER_FILE|SIGNTOOL|KEY_CONTAINER|TOKEN_PIN|SIGNATURE_CACHE_DIR|SIGNATURE_CACHE_CONCURRENCY)$/u -const MACOS_SETTING = /^(?:DSH_DESKTOP_MACOS_(?:SIGNING_IDENTITY|TEAM_ID|PACK_CONCURRENCY|DOWNLOAD_PROXY|NOTARIZATION_PROXY)|APPLE_(?:API_KEY|API_KEY_ID|API_ISSUER|ID|APP_SPECIFIC_PASSWORD|TEAM_ID|KEYCHAIN|KEYCHAIN_PROFILE)|CSC_(?:LINK|KEY_PASSWORD))$/u +const MACOS_SETTING = /^(?:DSH_DESKTOP_MACOS_(?:SIGNING_IDENTITY|TEAM_ID|SIGNATURE_CACHE_DIR|PACK_CONCURRENCY|DOWNLOAD_PROXY|NOTARIZATION_PROXY)|APPLE_(?:API_KEY|API_KEY_ID|API_ISSUER|ID|APP_SPECIFIC_PASSWORD|TEAM_ID|KEYCHAIN|KEYCHAIN_PROFILE)|CSC_(?:LINK|KEY_PASSWORD))$/u const AMBIENT_RELEASE_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|MANDATORY_UPDATE_.*|WINDOWS_.*|MACOS_.*)|APPLE_.*|(?:WIN_)?CSC_.*|DOWNLOAD_(?:TEST|PROD)_.*)$/iu const FILE_SETTINGS = ['DSH_DESKTOP_WINDOWS_CER_FILE', 'DSH_DESKTOP_WINDOWS_SIGNTOOL', 'APPLE_API_KEY', 'APPLE_KEYCHAIN', 'CSC_LINK'] @@ -33,14 +34,61 @@ 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 machine preset when selected, otherwise the target's required dotenv; no ambient release fallback. + * PACKAGE_TEST_RELEASE_ID overrides the test preset only; blank retains its configured ID. * @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 presets and Windows 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 (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 publicPlatformSetting = platform === 'win32' + ? /^DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_(?:DIR|CONCURRENCY)$/u + : /^DSH_DESKTOP_MACOS_(?:SIGNATURE_CACHE_DIR|PACK_CONCURRENCY|DOWNLOAD_PROXY|NOTARIZATION_PROXY)$/u + 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))|DOWNLOAD_TEST_(?:ORIGIN|RELEASE_ID))$/u.test(name) || publicPlatformSetting.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 && (platform === 'darwin' || !options.prepareOnly)) { + const filename = platform === 'win32' ? 'windows-signing.env' : 'macos-signing.env' + Object.assign(settings, readSettings(join(dirname(dirname(path)), 'secrets', filename), + name => platform === 'win32' + ? /^DSH_DESKTOP_WINDOWS_(?:CER_FILE|SIGNTOOL|KEY_CONTAINER|TOKEN_PIN)$/u.test(name) + : MACOS_SETTING.test(name) && !publicPlatformSetting.test(name))) + } + } + const releaseId = environment.PACKAGE_TEST_RELEASE_ID?.trim() + if (releaseId) { + if (preset !== 'test') throw new Error('desktop package: test release ID override requires the test preset') + if (!/^[a-f0-9]{32}$/u.test(releaseId)) throw new Error('desktop package: test release ID must contain 32 lowercase hexadecimal characters') + settings.DOWNLOAD_TEST_RELEASE_ID = releaseId + } + return { + ...Object.fromEntries(Object.entries(environment).filter(([name]) => !AMBIENT_RELEASE_SETTING.test(name))), + ...settings, + ...(environment.DSH_DESKTOP_UPDATE_CHANNEL === undefined ? {} : { DSH_DESKTOP_UPDATE_CHANNEL: environment.DSH_DESKTOP_UPDATE_CHANNEL }), + ...(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 +104,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 +113,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) { @@ -86,7 +130,7 @@ function requireReadableFile(environment, name) { * Validate the packaging mode before preparation without invoking a token or Apple's services. * @param {NodeJS.ProcessEnv} environment Selected local defaults or file-owned release settings. * @param {{ platform: 'win32' | 'darwin', arch: string }} target Selected release target. - * @param {{ unsigned?: boolean, prepareOnly?: boolean }} options Explicit packaging mode. + * @param {{ unsigned?: boolean, prepareOnly?: boolean, skipNotarization?: boolean }} options Explicit packaging mode. * @returns {void} */ export function validateDesktopPackageEnvironment(environment, target, options = {}) { @@ -106,18 +150,21 @@ export function validateDesktopPackageEnvironment(environment, target, options = }) if (!options.prepareOnly) resolveWindowsSignatureCacheDirectory(environment) } else { + if (environment.DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR !== undefined) validateMacOSSignatureCacheDirectory(environment.DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR) resolveMacOSSigningEnvironment(environment) - const strategies = [ - ['APPLE_ID', 'APPLE_APP_SPECIFIC_PASSWORD', 'APPLE_TEAM_ID'], - ['APPLE_API_KEY', 'APPLE_API_KEY_ID', 'APPLE_API_ISSUER'], - ['APPLE_KEYCHAIN_PROFILE', 'APPLE_KEYCHAIN'], - ] - if (strategies.filter(names => names.some(name => environment[name] !== undefined)).length > 1) { - throw new Error('desktop package: configure exactly one macOS notarization strategy; comment out the other strategies') + if (!options.skipNotarization) { + const strategies = [ + ['APPLE_ID', 'APPLE_APP_SPECIFIC_PASSWORD', 'APPLE_TEAM_ID'], + ['APPLE_API_KEY', 'APPLE_API_KEY_ID', 'APPLE_API_ISSUER'], + ['APPLE_KEYCHAIN_PROFILE', 'APPLE_KEYCHAIN'], + ] + if (strategies.filter(names => names.some(name => environment[name] !== undefined)).length > 1) { + throw new Error('desktop package: configure exactly one macOS notarization strategy; comment out the other strategies') + } + const credentials = resolveMacOSNotarizationEnvironment(environment) + if ('appleApiKey' in credentials) requireReadableFile(environment, 'APPLE_API_KEY') + if ('keychain' in credentials) requireReadableFile(environment, 'APPLE_KEYCHAIN') } - const credentials = resolveMacOSNotarizationEnvironment(environment) - if ('appleApiKey' in credentials) requireReadableFile(environment, 'APPLE_API_KEY') - if ('keychain' in credentials) requireReadableFile(environment, 'APPLE_KEYCHAIN') requireReadableFile(environment, 'CSC_LINK') if (environment.CSC_KEY_PASSWORD === undefined) { throw new Error('desktop package: CSC_KEY_PASSWORD must be set to the p12 export password (use an explicit empty value for an unencrypted p12)') diff --git a/apps/desktop/scripts/desktop-publication-failure.ts b/apps/desktop/scripts/desktop-publication-failure.ts new file mode 100644 index 0000000000..8f3e6beb55 --- /dev/null +++ b/apps/desktop/scripts/desktop-publication-failure.ts @@ -0,0 +1,30 @@ +/** Safe failure details shared by publication diagnostics and durable journals. */ +import { ZodError } from 'zod' +import { DesktopPublishError } from './desktop-publish.ts' + +const publicCodes = new Set(['AccessDenied', 'InternalError', 'NoSuchBucket', 'BadDigest', 'SignatureDoesNotMatch', + 'RequestTimeout', 'TimeoutError', 'AbortError', 'ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ENOSPC', 'EACCES', 'EPERM', 'ENOENT']) + +/** + * Keep actionable local validation details without recording SDK response bodies or credentials. + * @param error Failure from validation, filesystem, subprocess or remote transport. + * @param phase Operation stage known by the entrypoint. + * @returns Credential-free diagnostic suitable for stderr and an audit event. + */ +export function desktopPublicationFailure(error: unknown, phase: string): { phase: string; code: string; message: string } { + if (error instanceof DesktopPublishError) return { phase, code: error.code, message: error.message } + if (error instanceof ZodError) return { phase, code: 'invalid-data', + message: `Invalid fields: ${error.issues.map(issue => `${issue.path.join('.') || '(root)'} (${issue.code})`).join(', ')}` } + if (error instanceof SyntaxError) return { phase, code: 'invalid-json', message: 'Invalid JSON; check the configuration or retained record for this stage.' } + const ownedMessage = /^(desktop (?:publish|release store|retention|rollback|tag|upload|auto-update|macOS signing|build)[^\n]*:|Usage:)/u + if (error instanceof Error && ownedMessage.test(error.message)) { + return { phase, code: 'validation', message: error.message } + } + const record = typeof error === 'object' && error !== null ? error : {} + const candidate = 'code' in record ? record.code : 'name' in record ? record.name : undefined + const code = typeof candidate === 'string' && publicCodes.has(candidate) ? candidate : 'operation-failed' + const status = 'statusCode' in record && typeof record.statusCode === 'number' ? ` (HTTP ${record.statusCode})` : '' + const path = ['ENOENT', 'EACCES', 'EPERM', 'ENOSPC'].includes(code) && 'path' in record && typeof record.path === 'string' + ? `: ${record.path}` : '' + return { phase, code, message: `${code}${status}${path}. Check this stage's local files, signature verification or service permissions; raw provider output is omitted.` } +} diff --git a/apps/desktop/scripts/desktop-publish-config.ts b/apps/desktop/scripts/desktop-publish-config.ts new file mode 100644 index 0000000000..f5d9a314da --- /dev/null +++ b/apps/desktop/scripts/desktop-publish-config.ts @@ -0,0 +1,46 @@ +/** Read public deployment settings independently from upload and GitHub App secrets. */ +import { readFile } from 'node:fs/promises' +import { isAbsolute, join } from 'node:path' +import { z } from 'zod' + +const singleLine = z.string().min(1).regex(/^[^\r\n\0]+$/u, 'expected a single-line value') +const absolutePath = singleLine.refine(isAbsolute, 'expected an absolute path') +const schema = z.strictObject({ + bucket: z.string().regex(/^[a-z0-9-]+-\d+$/u), + origin: z.url().refine((value) => { const url = new URL(value); return url.protocol === 'https:' && !url.username && !url.password && url.pathname === '/' && !url.search && !url.hash }, 'expected an HTTPS origin'), + credentialsFile: absolutePath, + macOS: z.strictObject({ signingIdentity: z.string().min(1), teamId: z.string().regex(/^[A-Z0-9]{10}$/u) }).optional(), + windows: z.strictObject({ certificateThumbprint: z.string().regex(/^[A-Fa-f0-9]{40}$/u) }).optional(), + githubApp: z.strictObject({ clientId: singleLine, privateKeyFile: absolutePath }).optional(), +}) +/** Public machine configuration; all secret fields are file references. */ +export type DesktopPublishConfig = z.infer + +/** + * Read one named deployment without opening referenced credential files. + * @param configRoot Absolute machine packaging configuration directory. + * @param preset Selected deployment from the retained package. + * @returns Validated public configuration; production requires App configuration. + */ +export async function readDesktopPublishConfig(configRoot: string, preset: 'test' | 'production'): Promise { + if (!isAbsolute(configRoot)) throw new Error('desktop publish: configuration root must be absolute') + const config = schema.parse(JSON.parse(await readFile(join(configRoot, 'publishing', `${preset}.json`), 'utf8'))) + if (preset === 'production' && (config.origin !== 'https://download.deepseek.com' || !config.githubApp)) { + throw new Error('desktop publish: production requires its fixed origin and GitHub App configuration') + } + return config +} + +/** + * Read upload credentials only after authorization and local validation have passed. + * @param config Previously validated public deployment configuration. + * @returns Explicit COS credential pair; contents never enter audit records. + */ +export async function readDesktopUploadCredentials(config: DesktopPublishConfig): Promise<{ secretId: string; secretKey: string }> { + try { + return z.strictObject({ secretId: z.string().min(1), secretKey: z.string().min(1) }) + .parse(JSON.parse(await readFile(config.credentialsFile, 'utf8'))) + } catch { + throw new Error('desktop publish: cannot read valid upload credentials from the configured file') + } +} diff --git a/apps/desktop/scripts/desktop-publish-cos.ts b/apps/desktop/scripts/desktop-publish-cos.ts new file mode 100644 index 0000000000..5b89a8ef40 --- /dev/null +++ b/apps/desktop/scripts/desktop-publish-cos.ts @@ -0,0 +1,84 @@ +/** COS transport for resumable Desktop publication; callers authorize writes and own the channel lock. */ +import { createHash } from 'node:crypto' +import { createReadStream } from 'node:fs' +import { Readable, Writable } from 'node:stream' +import type COS from 'cos-nodejs-sdk-v5' +import { createDesktopCos, DESKTOP_COS_REGION, type DesktopCosCredentials } from './desktop-cos.ts' +import { cosOperation } from './cos-operation.ts' +import type { DesktopUploadPlan } from './desktop-upload-plan.ts' +import { desktopArtifactDigest, type DesktopPublishTransport } from './desktop-publish.ts' + +function missing(error: unknown): boolean { + return typeof error === 'object' && error !== null && 'code' in error && error.code === 'NoSuchKey' +} + +/** + * Create a bounded COS transport restricted to the validated plan's object keys. + * @param plan Destination and exact object inventory; arbitrary keys are rejected. + * @param credentials Credentials for this deployment only. + * @param createClient Client factory; absent uses the shared production client, tests supply a loopback client. + * @returns Streaming reads and single-attempt writes; transport construction performs no requests. + */ +export function desktopPublishCos( + plan: DesktopUploadPlan, credentials: DesktopCosCredentials, + createClient: (credentials: DesktopCosCredentials) => COS = createDesktopCos, +): DesktopPublishTransport { + const keys = new Map(plan.artifacts.map(artifact => [artifact.key, artifact.channelMetadata])) + const client = () => createClient(credentials) + const location = (key: string) => { + if (!keys.has(key)) throw new Error('desktop publish: object is outside the selected plan') + return { Bucket: plan.bucket, Region: DESKTOP_COS_REGION, Key: key } + } + return { + async read(key, channel) { + const address = location(key) + if (keys.get(key) !== channel) throw new Error('desktop publish: object role mismatch') + const sha512 = createHash('sha512') + const chunks: Buffer[] = [] + let size = 0 + const output = new Writable({ + write(bytes: Buffer, _encoding, done) { + size += bytes.length + if (channel && size > 1024 * 1024) { done(new Error('desktop publish: channel metadata exceeds 1 MiB')); return } + sha512.update(bytes) + if (channel) chunks.push(Buffer.from(bytes)) + done() + }, + }) + try { + const cos = client() + await cosOperation(cos, 900_000, () => cos.getObject({ ...address, Output: output })) + return { size, sha512: sha512.digest('base64'), ...(channel ? { contents: Buffer.concat(chunks).toString('utf8') } : {}) } + } catch (error) { + if (missing(error)) return null + throw error + } finally { output.destroy() } + }, + async put(artifact, digest, forbidOverwrite) { + const address = location(artifact.key) + if (keys.get(artifact.key) !== artifact.channelMetadata || forbidOverwrite === artifact.channelMetadata) { + throw new Error('desktop publish: object write policy mismatch') + } + const actual = await desktopArtifactDigest(artifact) + if (actual.size !== digest.size || actual.sha512 !== digest.sha512) throw new Error('desktop publish: local input changed') + const cos = client() + // COS overwrite prevention requires versioning to be absent, not enabled or suspended. + if (forbidOverwrite) { + const state = await cosOperation(cos, 30_000, () => cos.getBucketVersioning({ Bucket: plan.bucket, Region: DESKTOP_COS_REGION })) + if (state.statusCode !== 200 || state.VersioningConfiguration.Status !== undefined) { + throw new Error('desktop publish: immutable objects require bucket versioning to be disabled') + } + } + const md5 = createHash('md5') + const bytes = artifact.contents === undefined ? createReadStream(artifact.path) : [Buffer.from(artifact.contents)] + for await (const chunk of bytes) md5.update(chunk) + const body = artifact.contents === undefined ? createReadStream(artifact.path) : Readable.from([Buffer.from(artifact.contents)]) + try { + await cosOperation(cos, 900_000, () => cos.putObject({ + ...address, Body: body, ContentLength: digest.size, ContentType: artifact.contentType, + Headers: { 'Content-MD5': md5.digest('base64'), ...(forbidOverwrite ? { 'x-cos-forbid-overwrite': 'true' } : {}) }, + })) + } finally { body.destroy() } + }, + } +} diff --git a/apps/desktop/scripts/desktop-publish-record.ts b/apps/desktop/scripts/desktop-publish-record.ts new file mode 100644 index 0000000000..77ac3ca698 --- /dev/null +++ b/apps/desktop/scripts/desktop-publish-record.ts @@ -0,0 +1,110 @@ +/** Machine-local channel exclusion and durable, credential-free publication records. */ +import { createHash } from 'node:crypto' +import { appendFile, mkdir, mkdtemp, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises' +import { basename, join } from 'node:path' +import { z } from 'zod' +import type { DesktopPublishEvent } from './desktop-publish.ts' + +/** + * Execute one publication or rollback while excluding other writers of its exact destination. + * @param root Machine-owned lock directory shared by automatic and manual entrypoints. + * @param destination Bucket and channel prefix identifying the serialized destination. + * @param operation Work to finish before releasing the lock. + * @returns Operation result. A held or abandoned lock rejects; operators inspect stale locks explicitly. + */ +export async function withDesktopChannelLock(root: string, destination: string, operation: () => Promise): Promise { + await mkdir(root, { recursive: true, mode: 0o700 }) + const path = join(root, `${createHash('sha256').update(destination).digest('hex')}.lock`) + try { await mkdir(path, { mode: 0o700 }) } catch (cause) { + throw new Error(`desktop publish: channel is locked or inaccessible; inspect ${path}`, { cause }) + } + try { + await writeFile(join(path, 'owner.json'), JSON.stringify({ pid: process.pid, + startedAt: new Date().toISOString(), destination }), { flag: 'wx', mode: 0o600, flush: true }) + return await operation() + } finally { await rm(path, { recursive: true }) } +} + +/** An operation journal retained independently of disposable checkout and artifact files. */ +export interface DesktopPublicationRecord { + readonly directory: string + record(event: DesktopPublishEvent): Promise + finish(status: 'complete' | 'preview' | 'failed' | 'published-tag-pending'): Promise +} + +/** + * Allocate a private journal before performing any remote writes. + * @param root Persistent audit root, outside the build checkout. + * @param identity Public source, actor and destination metadata; never pass credentials. + * @returns Durable event writer and explicit terminal-status writer. + */ +export async function createDesktopPublicationRecord( + root: string, + identity: { repository: string; runId: string; attempt: string; actor: string; destination: string; operation: 'publish' | 'rollback'; reason: string }, +): Promise { + await mkdir(root, { recursive: true, mode: 0o700 }) + const staging = await mkdtemp(join(root, '.initializing-')) + const directory = join(root, `${identity.operation}-${basename(staging).slice('.initializing-'.length)}`) + const startedAt = new Date().toISOString() + try { + await writeFile(join(staging, 'operation.json'), `${JSON.stringify({ ...identity, + startedAt }, null, 2)}\n`, { flag: 'wx', mode: 0o600, flush: true }) + await writeFile(join(staging, 'events.jsonl'), '', { flag: 'wx', mode: 0o600, flush: true }) + await rename(staging, directory) + } catch (error) { + await rm(staging, { recursive: true, force: true }) + throw error + } + return { + directory, + async record(event) { + await appendFile(join(directory, 'events.jsonl'), `${JSON.stringify({ ...event, at: new Date().toISOString() })}\n`, { flush: true }) + }, + async finish(status) { + await writeFile(join(directory, 'result.json'), `${JSON.stringify({ status, + startedAt, finishedAt: new Date().toISOString() })}\n`, { flag: 'wx', mode: 0o600, flush: true }) + }, + } +} + +/** + * Find durable evidence that this immutable attempt finished updating its feeds. + * @param root Persistent publication journal root. + * @param expected Exact source and destination for the current retained package. + * @returns True permits tag-only recovery; false requires normal remote reconciliation. + */ +export async function wasDesktopAttemptPublished(root: string, expected: { + repository: string + runId: string + attempt: string + destination: string +}): Promise { + let entries + try { entries = await readdir(root, { withFileTypes: true }) } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return false + throw error + } + for (const entry of entries) { + if (!entry.isDirectory() || !entry.name.startsWith('publish-')) continue + const directory = join(root, entry.name) + let operation + try { operation = JSON.parse(await readFile(join(directory, 'operation.json'), 'utf8')) } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') continue + throw error + } + const parsed = z.object({ operation: z.string(), repository: z.string(), + runId: z.string(), attempt: z.string(), destination: z.string() }).parse(operation) + if (parsed.operation !== 'publish' || parsed.repository !== expected.repository || parsed.runId !== expected.runId + || parsed.attempt !== expected.attempt || parsed.destination !== expected.destination) continue + let events + try { events = await readFile(join(directory, 'events.jsonl'), 'utf8') } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') continue + throw error + } + // Only newline-terminated entries were completely appended before an interruption. + for (const line of events.split('\n').slice(0, -1)) { + if (z.object({ type: z.string() }).parse(JSON.parse(line)).type === 'feeds-complete') return true + } + } + return false +} diff --git a/apps/desktop/scripts/desktop-publish-route.ts b/apps/desktop/scripts/desktop-publish-route.ts new file mode 100644 index 0000000000..46c869c4be --- /dev/null +++ b/apps/desktop/scripts/desktop-publish-route.ts @@ -0,0 +1,66 @@ +/** Validate a completed packaging attempt and route publication back to its original runner. */ +import { z } from 'zod' + +const positive = z.number().int().positive() +const runSchema = z.object({ + id: positive, run_attempt: positive, head_sha: z.string().regex(/^[a-f0-9]{40}$/u), + path: z.string(), conclusion: z.literal('success'), event: z.literal('workflow_dispatch'), + repository: z.object({ full_name: z.string() }), +}) +const requestSchema = z.object({ source: z.object({ + repository: z.string(), runId: z.string(), attempt: z.string(), commit: z.string().regex(/^[a-f0-9]{40}$/u), + workflowCommit: z.string(), sourceRef: z.string().regex(/^(?:master|dsh-v[0-9][0-9A-Za-z.-]*)$/u), + channel: z.enum(['nightly', 'latest']), + runnerName: z.string(), target: z.enum(['mac-arm64', 'win-x64']), preset: z.enum(['test', 'production']), + publishRequested: z.literal(true), qualification: z.enum(['signed', 'notarized']), +}) }) +const jobsSchema = z.array(z.object({ runner_name: z.string().nullable(), conclusion: z.string().nullable() })) +const routesSchema = z.record(z.string(), z.object({ label: z.string().regex(/^dsh-[a-z0-9-]+$/u), target: z.enum(['mac-arm64', 'win-x64']) })) + +/** Validated values handed to the privileged publisher; no caller-selected shell fragments. */ +export interface DesktopPublishRoute { + readonly runId: string + readonly attempt: string + readonly commit: string + readonly sourceRef: string + readonly channel: 'nightly' | 'latest' + readonly runnerName: string + readonly runnerLabel: string + readonly target: 'mac-arm64' | 'win-x64' + readonly preset: 'test' | 'production' +} + +/** + * Match a public publication request to GitHub's attempt/job evidence and configured machine labels. + * @param repository Current repository, not a value selected by the artifact. + * @param runValue GitHub response for the exact packaging attempt. + * @param requestValue Retained manifest downloaded from that attempt's request artifact. + * @param jobsValue GitHub jobs for the same packaging attempt. + * @param routesValue Administrator-maintained runner-name to unique-label mapping. + * @returns Route to the original machine. Unknown runners, modes and mismatches reject. + */ +export function resolveDesktopPublishRoute( + repository: string, runValue: unknown, requestValue: unknown, jobsValue: unknown, routesValue: unknown, +): DesktopPublishRoute { + const run = runSchema.parse(runValue) + const { source } = requestSchema.parse(requestValue) + const jobs = jobsSchema.parse(jobsValue) + const routes = routesSchema.parse(routesValue) + const workflow = source.target === 'win-x64' ? '.github/workflows/windows-package.yml' : '.github/workflows/macos-package.yml' + if (run.repository.full_name !== repository || source.repository !== repository || run.path !== workflow + || source.runId !== String(run.id) || source.attempt !== String(run.run_attempt) + || source.workflowCommit !== run.head_sha + || source.qualification !== (source.target === 'win-x64' ? 'signed' : 'notarized')) { + throw new Error('desktop publish: request does not match the successful packaging attempt') + } + const route = routes[source.runnerName] + if (!route || route.target !== source.target) throw new Error('desktop publish: original machine has no configured publishing route') + if (new Set(Object.values(routes).map(value => value.label)).size !== Object.keys(routes).length) { + throw new Error('desktop publish: each configured machine needs its own unique runner label') + } + const matches = jobs.filter(job => job.runner_name === source.runnerName && job.conclusion === 'success') + if (matches.length !== 1) throw new Error('desktop publish: original job does not establish a single successful packaging runner') + return { runId: source.runId, attempt: source.attempt, commit: source.commit, sourceRef: source.sourceRef, channel: source.channel, + runnerName: source.runnerName, + runnerLabel: route.label, target: source.target, preset: source.preset } +} diff --git a/apps/desktop/scripts/desktop-publish-tag.ts b/apps/desktop/scripts/desktop-publish-tag.ts new file mode 100644 index 0000000000..f47cc698a6 --- /dev/null +++ b/apps/desktop/scripts/desktop-publish-tag.ts @@ -0,0 +1,47 @@ +/** Create immutable Desktop release tags using the explicitly supplied GitHub App installation token. */ +import { valid } from 'semver' +import { z } from 'zod' +import { desktopReleaseTag } from './desktop-release-tag.ts' + +const refSchema = z.object({ object: z.object({ type: z.string(), sha: z.string().regex(/^[a-f0-9]{40}$/u) }) }) + +/** + * Create a lightweight release tag, or verify that an existing tag names the same packaged commit. + * @param repository Owner/name of the package source repository. + * @param version Validated packaged version. + * @param commit Actual packaged commit, never the publishing workflow checkout commit. + * @param installationToken Explicit GitHub App token; no ambient authentication fallback is used. + * @param request HTTP implementation; defaults to fetch, tests inject an isolated fake. + * @returns Created or already-present status. Conflicts and unknown responses reject without updating a ref. + */ +export async function publishDesktopTag( + repository: string, version: string, commit: string, installationToken: string, + request: typeof fetch = fetch, +): Promise<'created' | 'present'> { + if (!/^[\w.-]+\/[\w.-]+$/u.test(repository) || valid(version) !== version || !/^[a-f0-9]{40}$/u.test(commit)) { + throw new Error('desktop tag: invalid repository, version or packaged commit') + } + if (!installationToken.trim()) throw new Error('desktop tag: GitHub App installation token is required') + const tag = desktopReleaseTag(version) + const base = `https://api.github.com/repos/${repository}/git` + const headers = { Authorization: `Bearer ${installationToken}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' } + const get = () => request(`${base}/ref/tags/${encodeURIComponent(tag)}`, { headers, redirect: 'error', signal: AbortSignal.timeout(30_000) }) + const matches = async (response: Response) => { + if (!response.ok) throw new Error(`desktop tag: cannot verify tag (HTTP ${response.status})`) + const ref = refSchema.parse(await response.json()) + if (ref.object.type !== 'commit') throw new Error('desktop tag: existing ref is not a lightweight commit tag; inspect it manually, refusing to replace it') + if (ref.object.sha !== commit) throw new Error('desktop tag: existing tag points to another commit; refusing to move it') + } + const existing = await get() + if (existing.status !== 404) { await matches(existing); return 'present' } + await existing.body?.cancel() + const response = await request(`${base}/refs`, { + method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, + body: JSON.stringify({ ref: `refs/tags/${tag}`, sha: commit }), redirect: 'error', signal: AbortSignal.timeout(30_000), + }) + if (response.status === 201) { await matches(response); return 'created' } + // A parallel platform release may have created the same version tag after our first read. + if (response.status === 422) { await response.body?.cancel(); await matches(await get()); return 'present' } + await response.body?.cancel() + throw new Error(`desktop tag: creation failed (HTTP ${response.status}); reconcile the tag before retrying`) +} diff --git a/apps/desktop/scripts/desktop-publish.ts b/apps/desktop/scripts/desktop-publish.ts new file mode 100644 index 0000000000..1270f7229e --- /dev/null +++ b/apps/desktop/scripts/desktop-publish.ts @@ -0,0 +1,132 @@ +/** Resume Desktop publication by reconciling object bytes before changing update feeds. */ +import { createHash } from 'node:crypto' +import { createReadStream } from 'node:fs' +import { load } from 'js-yaml' +import { gt, valid } from 'semver' +import { z } from 'zod' +import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-plan.ts' + +/** File identity computed from bytes, never inferred from COS ETags. */ +export interface DesktopObjectDigest { readonly size: number; readonly sha512: string } +/** Remote object observation; channel objects additionally carry their exact YAML. */ +export interface DesktopRemoteObject extends DesktopObjectDigest { readonly contents?: string } +/** Transport owned by the caller holding the destination channel lock. */ +export interface DesktopPublishTransport { + /** Read and hash remote bytes; only a confirmed missing object returns null. */ + read(key: string, channel: boolean): Promise + /** Write once. Immutable binaries must use COS overwrite prevention. */ + put(artifact: DesktopUploadArtifact, digest: DesktopObjectDigest, forbidOverwrite: boolean): Promise +} +/** Credential-free, durably flushed publication event. */ +export interface DesktopPublishEvent { + readonly type: 'object-present' | 'put-intent' | 'put-verified' | 'feeds-complete' | 'tag-pending' | 'complete' | 'failed' + readonly failure?: { readonly phase: string; readonly code: string; readonly message: string } + readonly key?: string + readonly before?: string | null + readonly after?: string +} +/** Caller owns audit persistence and the separately authorized GitHub App identity. */ +export interface DesktopPublishOperations { + readonly transport: DesktopPublishTransport + record(event: DesktopPublishEvent): Promise + /** Ensure the production tag names the packaged commit; never move an existing tag. */ + tag(): Promise +} +/** Published files and feeds can succeed even when tag creation remains outstanding. */ +export type DesktopPublishResult = { readonly status: 'complete' } | { readonly status: 'published-tag-pending'; readonly cause: unknown } + +/** A publication failure that requires reconciliation rather than a blind retry. */ +export class DesktopPublishError extends Error { + constructor(readonly code: 'conflict' | 'superseded' | 'invalid-plan' | 'remote-changed' | 'verification-failed', message: string) { + super(message) + this.name = 'DesktopPublishError' + } +} + +/** + * Hash exactly the file or generated metadata selected by a validated upload plan. + * @param artifact File-backed installer or in-memory channel metadata. + * @returns Byte length and SHA-512 for input reconciliation. + */ +export async function desktopArtifactDigest(artifact: DesktopUploadArtifact): Promise { + const hash = createHash('sha512') + let size = 0 + const stream = artifact.contents === undefined ? createReadStream(artifact.path) : [Buffer.from(artifact.contents)] + for await (const bytes of stream) { hash.update(bytes); size += bytes.length } + return { size, sha512: hash.digest('base64') } +} + +function same(left: DesktopObjectDigest | null, right: DesktopObjectDigest | null): boolean { + return left === null || right === null ? left === right : left.size === right.size && left.sha512 === right.sha512 +} + +function version(contents: string, remote = false): string { + try { + const parsed = z.object({ version: z.string() }).parse(load(contents)) + if (valid(parsed.version) !== null) return parsed.version + } catch (error) { /* Discard parser error details, which may include raw remote YAML. */ } + throw new DesktopPublishError(remote ? 'verification-failed' : 'invalid-plan', + `desktop publish: invalid ${remote ? 'remote' : 'planned'} channel version`) +} + +/** + * Reconcile every binary, then publish feeds, then create the production tag. + * The caller must hold the channel lock through this entire operation. No writes are retried here; + * a later invocation hashes remote bytes to recover confirmed and ambiguous earlier writes. + * @param plan Validated package plan containing both binaries and channel metadata. + * @param operations Locked transport, durable audit sink, and production tag operation. + * @returns Complete or published-with-tag-pending; other failures stop all dependent work. + */ +export async function publishDesktopRelease(plan: DesktopUploadPlan, operations: DesktopPublishOperations): Promise { + const files = plan.artifacts.filter(file => !file.channelMetadata) + const feeds = plan.artifacts.filter(file => file.channelMetadata) + if (files.length === 0 || feeds.length === 0 || new Set(plan.artifacts.map(file => file.key)).size !== plan.artifacts.length) { + throw new DesktopPublishError('invalid-plan', 'desktop publish: complete files and update feeds are required') + } + if (plan.environment === 'production' && (!plan.commit || !/^[a-f0-9]{40}$/u.test(plan.commit) || plan.dirty !== false)) { + throw new DesktopPublishError('invalid-plan', 'desktop publish: production requires a clean packaged commit') + } + const snapshots = new Map() + // Reject obsolete requests before even uploading their missing binary files. + for (const feed of feeds) { + if (feed.contents === undefined || version(feed.contents) !== plan.version) { + throw new DesktopPublishError('invalid-plan', 'desktop publish: channel version differs from package') + } + const remote = await operations.transport.read(feed.key, true) + if (remote !== null) { + if (remote.contents === undefined) throw new DesktopPublishError('verification-failed', 'desktop publish: channel bytes were not returned') + if (gt(version(remote.contents, true), plan.version)) throw new DesktopPublishError('superseded', 'desktop publish: a newer version already owns this channel') + if (version(remote.contents, true) === plan.version && !same(remote, await desktopArtifactDigest(feed))) { + throw new DesktopPublishError('conflict', 'desktop publish: same version has different channel metadata') + } + } + snapshots.set(feed.key, remote) + } + for (const artifact of [...files, ...feeds]) { + const digest = await desktopArtifactDigest(artifact) + const remote = await operations.transport.read(artifact.key, artifact.channelMetadata) + if (same(remote, digest)) { + await operations.record({ type: 'object-present', key: artifact.key }) + continue + } + if (!artifact.channelMetadata && remote !== null) throw new DesktopPublishError('conflict', `desktop publish: object differs: ${artifact.key}`) + if (artifact.channelMetadata && !same(remote, snapshots.get(artifact.key) ?? null)) { + throw new DesktopPublishError('remote-changed', 'desktop publish: channel changed after preflight; inspect before retrying') + } + await operations.record({ type: 'put-intent', key: artifact.key, + ...(artifact.channelMetadata ? { before: remote?.contents ?? null, after: artifact.contents } : {}) }) + await operations.transport.put(artifact, digest, !artifact.channelMetadata) + const actual = await operations.transport.read(artifact.key, artifact.channelMetadata) + if (!same(actual, digest)) throw new DesktopPublishError('verification-failed', `desktop publish: remote bytes differ: ${artifact.key}`) + await operations.record({ type: 'put-verified', key: artifact.key }) + } + await operations.record({ type: 'feeds-complete' }) + if (plan.environment === 'production') { + try { await operations.tag() } catch (cause) { + await operations.record({ type: 'tag-pending' }) + return { status: 'published-tag-pending', cause } + } + } + await operations.record({ type: 'complete' }) + return { status: 'complete' } +} diff --git a/apps/desktop/scripts/desktop-release-store.ts b/apps/desktop/scripts/desktop-release-store.ts new file mode 100644 index 0000000000..904d65af07 --- /dev/null +++ b/apps/desktop/scripts/desktop-release-store.ts @@ -0,0 +1,143 @@ +/** Retain immutable Desktop build files outside disposable runner checkouts. */ +import { createHash } from 'node:crypto' +import { createReadStream, constants } from 'node:fs' +import { copyFile, lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises' +import { basename, isAbsolute, join } from 'node:path' +import { z } from 'zod' + +const positiveId = z.string().regex(/^[1-9]\d*$/u) +const filename = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/u) +const sourceSchema = z.strictObject({ + repository: z.string().regex(/^[\w.-]+\/[\w.-]+$/u), + runId: positiveId, + attempt: positiveId, + commit: z.string().regex(/^[a-f0-9]{40}$/u), + workflowCommit: z.string().regex(/^[a-f0-9]{40}$/u), + sourceRef: z.string().regex(/^(?:master|dsh-v[0-9][0-9A-Za-z.-]*)$/u), + channel: z.enum(['nightly', 'latest']), + runnerName: z.string().min(1), + // Storage accepts every Desktop target; CI routing separately limits currently provisioned platforms. + target: z.enum(['mac-arm64', 'mac-x64', 'win-x64']), + preset: z.enum(['test', 'production']), + productVersion: z.string().min(1), + version: z.string().min(1), + testReleaseId: z.string().regex(/^[a-f0-9]{32}$/u).nullable(), + publishRequested: z.boolean(), + qualification: z.enum(['signed', 'notarized', 'unsigned', 'unnotarized']), +}) +const manifestSchema = z.strictObject({ + schemaVersion: z.literal(1), + source: sourceSchema, + files: z.array(z.strictObject({ name: filename, size: z.number().int().positive(), + sha512: z.string().regex(/^[A-Za-z0-9+/]{86}==$/u) })).min(1), +}) + +/** Public, credential-free identity of one packaging attempt. */ +export type DesktopRetainedSource = z.infer +/** File inventory bound to the source packaging attempt. */ +export type DesktopRetainedManifest = z.infer + +async function fingerprint(path: string) { + const info = await lstat(path) + if (!info.isFile() || info.isSymbolicLink()) throw new Error('desktop release store: expected a regular file') + const hash = createHash('sha512') + let size = 0 + for await (const bytes of createReadStream(path)) { size += bytes.length; hash.update(bytes) } + if (size === 0) throw new Error('desktop release store: empty artifact') + return { size, sha512: hash.digest('base64') } +} + +async function directory(path: string): Promise { + const info = await lstat(path) + if (!info.isDirectory() || info.isSymbolicLink()) throw new Error('desktop release store: expected a real directory') + return realpath(path) +} + +/** + * Resolve an attempt beneath an absolute, machine-owned releases root. + * @param root Persistent releases directory, outside the checkout. + * @param runId GitHub packaging run ID. + * @param attempt Packaging attempt, not the publishing attempt. + * @returns Deterministic path after validating both identifiers. + */ +export function retainedDesktopPath(root: string, runId: string, attempt: string): string { + if (!isAbsolute(root)) throw new Error('desktop release store: root must be absolute') + positiveId.parse(runId) + positiveId.parse(attempt) + return join(root, runId, attempt) +} + +/** + * Copy an explicit file inventory, verify the copies, then expose one complete attempt atomically. + * @param root Persistent releases root owned by this runner. + * @param source Packaging identity and selected public settings. + * @param paths Complete artifact and completion-record paths; directory trees are not accepted. + * @returns Published attempt directory. An existing attempt is never replaced. + */ +export async function retainDesktopRelease(root: string, source: DesktopRetainedSource, paths: readonly string[]): Promise { + sourceSchema.parse(source) + const destination = retainedDesktopPath(root, source.runId, source.attempt) + const names = paths.map(path => filename.parse(basename(path))) + if (names.length === 0 || new Set(names).size !== names.length) throw new Error('desktop release store: empty or duplicate file inventory') + await mkdir(root, { recursive: true, mode: 0o700 }) + await directory(root) + const parent = join(root, source.runId) + await mkdir(parent, { recursive: true, mode: 0o700 }) + await directory(parent) + const claim = join(parent, `${source.attempt}.lock`) + await mkdir(claim, { mode: 0o700 }) + let staging: string | undefined + try { + try { + await lstat(destination) + throw new Error('desktop release store: attempt already exists') + } catch (error) { + if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error + } + staging = await mkdtemp(join(parent, '.retaining-')) + const files = [] + for (const path of paths) { + const name = basename(path) + if (name === 'manifest.json') throw new Error('desktop release store: manifest filename is reserved') + const before = await fingerprint(path) + const copied = join(staging, name) + await copyFile(path, copied, constants.COPYFILE_EXCL) + const after = await fingerprint(copied) + if (before.size !== after.size || before.sha512 !== after.sha512) throw new Error('desktop release store: source changed during retention') + files.push({ name, ...after }) + } + const manifest: DesktopRetainedManifest = { schemaVersion: 1, source, files } + manifestSchema.parse(manifest) + await writeFile(join(staging, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, { flag: 'wx', mode: 0o600, flush: true }) + await rename(staging, destination) + staging = undefined + return destination + } finally { + if (staging !== undefined) await rm(staging, { recursive: true, force: true }) + await rm(claim, { recursive: true }) + } +} + +/** + * Read an attempt and rehash every retained file before a consumer uses it. + * @param root Persistent releases root. + * @param runId Expected source run ID. + * @param attempt Expected source attempt. + * @returns Parsed inventory; missing, linked, changed or mismatched files reject. + */ +export async function verifyRetainedDesktopRelease(root: string, runId: string, attempt: string): Promise { + const path = retainedDesktopPath(root, runId, attempt) + await directory(root) + await directory(join(root, runId)) + await directory(path) + const manifestPath = join(path, 'manifest.json') + if (!(await lstat(manifestPath)).isFile() || (await lstat(manifestPath)).isSymbolicLink()) throw new Error('desktop release store: invalid manifest file') + const manifest = manifestSchema.parse(JSON.parse(await readFile(manifestPath, 'utf8'))) + if (manifest.source.runId !== runId || manifest.source.attempt !== attempt) throw new Error('desktop release store: attempt identity mismatch') + if (new Set(manifest.files.map(file => file.name)).size !== manifest.files.length) throw new Error('desktop release store: duplicate file inventory') + for (const file of manifest.files) { + const current = await fingerprint(join(path, file.name)) + if (current.size !== file.size || current.sha512 !== file.sha512) throw new Error(`desktop release store: changed file ${file.name}`) + } + return manifest +} diff --git a/apps/desktop/scripts/desktop-rollback.ts b/apps/desktop/scripts/desktop-rollback.ts new file mode 100644 index 0000000000..a96e5d652b --- /dev/null +++ b/apps/desktop/scripts/desktop-rollback.ts @@ -0,0 +1,58 @@ +/** Restore historical update feeds without uploading binaries or moving release tags. */ +import { load } from 'js-yaml' +import { z } from 'zod' +import type { DesktopUploadPlan } from './desktop-upload-plan.ts' +import { desktopArtifactDigest, type DesktopPublishOperations, type DesktopRemoteObject } from './desktop-publish.ts' + +/** Outcome of an explicitly requested channel restoration. */ +export interface DesktopRollbackResult { + readonly status: 'preview' | 'complete' + readonly feeds: readonly { key: string; before: string; after: string }[] +} + +/** + * Verify historical binaries and restore only the selected feed YAML under a caller-held channel lock. + * @param plan Previously published release reconstructed from retained immutable files. + * @param expectedVersion Version the operator expects to find online; another version stops the operation. + * @param execute False only inspects and previews; true writes after all historical bytes are verified. + * @param operations Remote transport and audit sink. The tag operation is never called. + * @returns Before/after YAML and whether it was written. Partial writes remain recorded for reconciliation. + */ +export async function rollbackDesktopChannel( + plan: DesktopUploadPlan, expectedVersion: string, execute: boolean, operations: DesktopPublishOperations, +): Promise { + const files = plan.artifacts.filter(file => !file.channelMetadata) + const feeds = plan.artifacts.filter(file => file.channelMetadata) + if (files.length === 0 || feeds.length === 0) throw new Error('desktop rollback: a complete historical release is required') + const equal = (left: DesktopRemoteObject | null, right: { size: number; sha512: string }) => + left !== null && left.size === right.size && left.sha512 === right.sha512 + for (const file of files) { + if (!equal(await operations.transport.read(file.key, false), await desktopArtifactDigest(file))) { + throw new Error(`desktop rollback: historical object is missing or different: ${file.key}`) + } + } + const changes = [] + for (const feed of feeds) { + const before = await operations.transport.read(feed.key, true) + if (!before || before.contents === undefined || feed.contents === undefined) throw new Error('desktop rollback: channel YAML is unavailable') + if (equal(before, await desktopArtifactDigest(feed))) { + await operations.record({ type: 'object-present', key: feed.key }) + continue + } + const current = z.object({ version: z.string() }).parse(load(before.contents)).version + if (current !== expectedVersion) throw new Error('desktop rollback: current version differs from the expected version') + changes.push({ key: feed.key, before: before.contents, after: feed.contents, observed: before, artifact: feed }) + } + if (execute) { + for (const change of changes) { + if (!equal(await operations.transport.read(change.key, true), change.observed)) throw new Error('desktop rollback: channel changed after preview') + await operations.record({ type: 'put-intent', key: change.key, before: change.before, after: change.after }) + const digest = await desktopArtifactDigest(change.artifact) + await operations.transport.put(change.artifact, digest, false) + if (!equal(await operations.transport.read(change.key, true), digest)) throw new Error('desktop rollback: restored channel could not be verified') + await operations.record({ type: 'put-verified', key: change.key }) + } + await operations.record({ type: 'complete' }) + } + return { status: execute ? 'complete' : 'preview', feeds: changes.map(({ key, before, after }) => ({ key, before, after })) } +} diff --git a/apps/desktop/scripts/desktop-upload-plan.ts b/apps/desktop/scripts/desktop-upload-plan.ts index 439a4fa6e1..aa05966c4a 100644 --- a/apps/desktop/scripts/desktop-upload-plan.ts +++ b/apps/desktop/scripts/desktop-upload-plan.ts @@ -5,7 +5,6 @@ import { createReadStream } from 'node:fs' import { readFile, stat } from 'node:fs/promises' import { basename, join, resolve } from 'node:path' import { dump, load } from 'js-yaml' -import { prerelease } from 'semver' import type { DesktopPackageTargetName } from './package-target.ts' import { desktopBuildRecordFilename, @@ -63,6 +62,8 @@ export interface DesktopUploadPlanOptions { readonly repositoryRoot?: string readonly appRoot?: string readonly artifactsRoot?: string + /** Original product version from a verified retained build; absent reads the checkout manifests. */ + readonly packagedProductVersion?: string } interface UpdateFileInfo { @@ -188,8 +189,8 @@ export async function createDesktopUploadPlan( const repositoryRoot = options.repositoryRoot ?? REPOSITORY_ROOT const appRoot = options.appRoot ?? APP_ROOT const artifactsRoot = options.artifactsRoot ?? desktopTargetBuildPaths(targetName).artifacts - const dshVersion = await manifestVersion(join(repositoryRoot, 'package.json'), 'dsh package') - const desktopVersion = await manifestVersion(join(appRoot, 'package.json'), 'desktop package') + const dshVersion = options.packagedProductVersion ?? await manifestVersion(join(repositoryRoot, 'package.json'), 'dsh package') + const desktopVersion = options.packagedProductVersion ?? await manifestVersion(join(appRoot, 'package.json'), 'desktop package') if (dshVersion !== desktopVersion) { throw new Error(`desktop upload: desktop version ${desktopVersion} does not match current dsh version ${dshVersion}`) } @@ -211,12 +212,14 @@ export async function createDesktopUploadPlan( } if (buildRecord.schemaVersion !== 1 || buildRecord.target !== targetName + || (buildRecord.channel ?? 'nightly') !== update.channel || buildRecord.environment !== update.environment || buildRecord.publicUrl !== update.publicUrl) { throw new Error(`desktop upload: ${targetName} package completion record for ${buildVersion} does not match the ${update.environment} update destination`) } - const metadataFilename = desktopUpdateMetadataFilename(buildVersion, target.platform) + if (update.channel === 'latest' && buildVersion.includes('-')) throw new Error('desktop upload: latest requires a stable version') + const metadataFilename = desktopUpdateMetadataFilename(buildVersion, target.platform, update.channel) const metadataPath = join(artifactsRoot, metadataFilename) let metadataValue: unknown try { @@ -274,10 +277,6 @@ export async function createDesktopUploadPlan( contents: dump(published), } artifacts.push(channelArtifact) - if (prerelease(buildVersion) === null) { - const stableFilename = metadataFilename.replace('nightly', 'latest') - artifacts.push({ ...channelArtifact, filename: stableFilename, key: `${update.keyPrefix}/${stableFilename}` }) - } const latestFilename = `dsh-latest-${target.platform === 'darwin' ? 'macos' : 'windows'}-${target.arch}.${target.platform === 'darwin' ? 'dmg' : 'exe'}` const latestKey = `desktop/${latestFilename}` return { 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/electron-builder-config.mjs b/apps/desktop/scripts/electron-builder-config.mjs index f08b783865..4b9cd27a8d 100644 --- a/apps/desktop/scripts/electron-builder-config.mjs +++ b/apps/desktop/scripts/electron-builder-config.mjs @@ -12,7 +12,7 @@ import { resolveMacOSSigningEnvironment, } from './desktop-release-environment.mjs' import { notarizeMacOSDiskImageArtifact } from './notarize-macos-disk-images.mjs' -import { verifyMacOSSignatureAfterSign } from './verify-macos-signature.mjs' +import { verifyMacOSDiskImageSignature, verifyMacOSSignatureAfterSign } from './verify-macos-signature.mjs' import { createWindowsTokenSigner, installWindowsNsisBootstrapSigner, @@ -23,7 +23,7 @@ import { resolveDesktopAutoUpdateConfig } from './desktop-auto-update-environmen import { resolveDesktopBuildCommit } from './desktop-build-commit.mjs' import { resolveDesktopBuildVersion } from './desktop-build-version.mjs' import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs' -import { desktopTargetBuildPaths, resolveDesktopBuildTarget } from './desktop-build-paths.mjs' +import { desktopArtifactOutput, desktopTargetBuildPaths, resolveDesktopBuildTarget } from './desktop-build-paths.mjs' import { installWindowsDirectoryInstaller } from './windows-directory-installer.mjs' import { preserveWindowsRuntimeSignature, signWindowsCode } from './windows-runtime-signature.mjs' import { prepareWindowsAsarUnpack, verifyWindowsAsarUnpack } from './windows-asar-unpack.mjs' @@ -58,13 +58,19 @@ export function createElectronBuilderConfig( throw new Error('desktop package: DSH_DESKTOP_UNSIGNED must be 0 or 1') } const unsigned = env.DSH_DESKTOP_UNSIGNED === '1' + const skipNotarization = env.DSH_DESKTOP_MACOS_SKIP_NOTARIZATION === '1' + if (env.DSH_DESKTOP_MACOS_SKIP_NOTARIZATION !== undefined && !['0', '1'].includes(env.DSH_DESKTOP_MACOS_SKIP_NOTARIZATION)) { + throw new Error('desktop package: DSH_DESKTOP_MACOS_SKIP_NOTARIZATION must be 0 or 1') + } + if (skipNotarization && (unsigned || resolvedPlatform !== 'darwin')) throw new Error('Skipping notarization requires a signed macOS build') const packagesMacOS = targetPlatform === 'darwin' || (targetPlatform === undefined && hostPlatform === 'darwin') const packagesWindows = resolvedPlatform === 'win32' const policy = packagesMacOS && unsigned ? undefined : resolveDesktopPolicyEnvironment(env) if (resolvedPlatform === 'win32') installWindowsDirectoryInstaller() const macOSSigning = packagesMacOS && !unsigned ? resolveMacOSSigningEnvironment(env) : undefined - if (packagesMacOS && !unsigned) resolveMacOSNotarizationEnvironment(env) + if (packagesMacOS && !unsigned && !skipNotarization) resolveMacOSNotarizationEnvironment(env) const buildPaths = desktopTargetBuildPaths(resolveDesktopBuildTarget(env, hostPlatform, hostArch)) + const output = desktopArtifactOutput(buildPaths, { unsigned, skipNotarization }) let primaryRuntimeDestination let dshDestination let windowsCode = [] @@ -95,20 +101,22 @@ export function createElectronBuilderConfig( // the artifact names, the update feed, and the installed app.getVersion() the updater compares against. const productVersion = JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8')).version const buildVersion = resolveDesktopBuildVersion(env, productVersion) + if (update?.channel === 'latest' && buildVersion.includes('-')) throw new Error('desktop package: latest requires a stable version') const packaged = resolveDesktopBuildCommit(env) return { appId, protocols: [{ name: 'DeepSeek Harness', schemes: ['dsh'] }], extraMetadata: { dshDesktopAppId: appId, + dshDesktopUpdateChannel: update?.channel ?? 'nightly', ...(policy === undefined ? {} : { dshMandatoryUpdatePolicy: policy }), ...buildVersion === productVersion ? {} : { version: buildVersion }, ...packaged === undefined ? {} : { dshBuildCommit: packaged.commit, dshBuildDirty: packaged.dirty }, }, productName: 'DeepSeek Harness', // Unsigned builds carry their own suffix so a shared file can never pass for a release artifact. - artifactName: `deepseek-harness-\${version}-\${os}-\${arch}${unsigned ? '-unsigned' : ''}.\${ext}`, - directories: { output: unsigned ? buildPaths.unsignedArtifacts : buildPaths.artifacts }, + artifactName: `deepseek-harness-\${version}-\${os}-\${arch}${output.suffix}.\${ext}`, + directories: { output: output.directory }, asar: true, electronDist: buildPaths.electron, electronFuses: { runAsNode: true }, @@ -135,6 +143,8 @@ export function createElectronBuilderConfig( 'lib/preload-welcome.cjs', 'renderer/**/*', 'package.json', + '!node_modules/**/*.{js,cjs,mjs,ts,cts,mts,css}.map', + '!node_modules/**/*.tsbuildinfo', { from: buildPaths.dsh, to: 'dsh', filter: ['**/*'] }, // electron-builder excludes a source directory's root node_modules. { from: join(buildPaths.dsh, 'node_modules'), to: 'dsh/node_modules', filter: ['**/*'] }, @@ -160,10 +170,11 @@ export function createElectronBuilderConfig( entitlementsInherit: fileURLToPath(new URL('./macos-entitlements.plist', import.meta.url)), // Prepared runtime files retain their signatures; PAK resources are sealed by their enclosing bundle. signIgnore: ['/Contents/Resources/app\\.asar\\.unpacked/dsh(?:/|$)', '/Contents/Resources/runtime/primary-runtime(?:/|$)', '\\.pak$'], - notarize: !unsigned, + notarize: !unsigned && !skipNotarization, target: unsigned ? ['dmg'] : ['dmg', 'zip'], }, dmg: { + format: 'ULMO', sign: !unsigned, writeUpdateInfo: false, }, @@ -214,6 +225,10 @@ export function createElectronBuilderConfig( }, artifactBuildCompleted: artifact => { if (unsigned || !artifact.file.endsWith('.dmg')) return + if (skipNotarization) { + verifyMacOSDiskImageSignature(artifact.file, macOSSigning ?? resolveMacOSSigningEnvironment(env)) + return + } return notarizeMacOSDiskImageArtifact( artifact, env, @@ -246,6 +261,6 @@ export function createElectronBuilderConfig( differentialPackage: true, }, detectUpdateChannel: false, - publish: update === undefined ? null : [{ provider: 'generic', url: update.publicUrl, channel: 'nightly' }], + publish: update === undefined ? null : [{ provider: 'generic', url: update.publicUrl, channel: update.channel }], } } diff --git a/apps/desktop/scripts/installed-update-builder.ts b/apps/desktop/scripts/installed-update-builder.ts index 2f0cbefe6c..42c665c430 100644 --- a/apps/desktop/scripts/installed-update-builder.ts +++ b/apps/desktop/scripts/installed-update-builder.ts @@ -31,6 +31,7 @@ export async function createInstalledUpdateBuilderConfig(manifest: string, versi files: [ { from: application, to: '.', filter: ['lib/*.js', 'lib/*.cjs', 'renderer/**/*', 'qualification-bootstrap.mjs', 'installed-update-identity.mjs'] }, 'package.json', + ...config.files.filter((file): file is string => typeof file === 'string' && file.startsWith('!')), { from: dsh, to: 'dsh', filter: ['**/*'] }, { from: join(dsh, 'node_modules'), to: 'dsh/node_modules', filter: ['**/*'] }, ], diff --git a/apps/desktop/scripts/macos-app-update-config.d.mts b/apps/desktop/scripts/macos-app-update-config.d.mts index 624ab0d341..ce18266c48 100644 --- a/apps/desktop/scripts/macos-app-update-config.d.mts +++ b/apps/desktop/scripts/macos-app-update-config.d.mts @@ -1,13 +1,14 @@ /** Resolved fields required to embed a macOS updater feed. */ export interface MacOSAppUpdateFeed { readonly publicUrl: string + readonly channel?: 'nightly' | 'latest' } /** Packaged electron-updater configuration for macOS. */ export interface MacOSAppUpdateConfig { readonly provider: 'generic' readonly url: string - readonly channel: 'nightly' + readonly channel: 'nightly' | 'latest' readonly updaterCacheDirName: string } diff --git a/apps/desktop/scripts/macos-app-update-config.mjs b/apps/desktop/scripts/macos-app-update-config.mjs index 3b9e0019c6..d6b4132c71 100644 --- a/apps/desktop/scripts/macos-app-update-config.mjs +++ b/apps/desktop/scripts/macos-app-update-config.mjs @@ -5,7 +5,7 @@ import { join } from 'node:path' import { dump, load } from 'js-yaml' const CONFIG_FILENAME = 'app-update.yml' -const CHANNEL = 'nightly' +import { resolveDesktopUpdateChannel } from './desktop-auto-update-environment.mjs' function object(value, label) { if (typeof value !== 'object' || value === null || Array.isArray(value)) { @@ -24,30 +24,30 @@ function nonEmptyString(value, label) { /** * Resolve the one generic macOS feed from the final electron-builder configuration. * @param {unknown} publish - Final electron-builder publish setting. - * @returns {{ publicUrl: string }} Resolved feed used by the packaged App. + * @returns {{ publicUrl: string, channel?: 'nightly' | 'latest' }} Resolved feed used by the packaged App. */ export function resolveMacOSAppUpdateFeed(publish) { if (!Array.isArray(publish) || publish.length !== 1) { throw new Error('desktop macOS update config: publish must contain exactly one provider') } const provider = object(publish[0], 'publish provider') - if (provider.provider !== 'generic' || provider.channel !== CHANNEL) { - throw new Error('desktop macOS update config: publish provider must be generic Nightly') + if (provider.provider !== 'generic' || !['nightly', 'latest'].includes(provider.channel)) { + throw new Error('desktop macOS update config: publish provider must be generic with nightly or latest channel') } - return { publicUrl: nonEmptyString(provider.url, 'publish provider URL') } + return { publicUrl: nonEmptyString(provider.url, 'publish provider URL'), channel: resolveDesktopUpdateChannel({ DSH_DESKTOP_UPDATE_CHANNEL: provider.channel }) } } /** * Create the electron-updater configuration embedded before code signing. - * @param {{ publicUrl: string }} update - Resolved update feed. + * @param {{ publicUrl: string, channel?: 'nightly' | 'latest' }} update - Resolved update feed. * @param {string} updaterCacheDirName - electron-builder application cache directory. - * @returns {{ provider: 'generic', url: string, channel: 'nightly', updaterCacheDirName: string }} Packaged updater fields. + * @returns {{ provider: 'generic', url: string, channel: 'nightly' | 'latest', updaterCacheDirName: string }} Packaged updater fields. */ export function createMacOSAppUpdateConfig(update, updaterCacheDirName) { return { provider: 'generic', url: nonEmptyString(update.publicUrl, 'public URL'), - channel: CHANNEL, + channel: resolveDesktopUpdateChannel({ DSH_DESKTOP_UPDATE_CHANNEL: update.channel }), updaterCacheDirName: nonEmptyString(updaterCacheDirName, 'updater cache directory'), } } @@ -55,7 +55,7 @@ export function createMacOSAppUpdateConfig(update, updaterCacheDirName) { /** * Write the updater configuration into an assembled App before signing. * @param {string} resourcesDir - App Contents/Resources directory. - * @param {{ publicUrl: string }} update - Resolved update feed. + * @param {{ publicUrl: string, channel?: 'nightly' | 'latest' }} update - Resolved update feed. * @param {string} updaterCacheDirName - electron-builder application cache directory. * @returns {Promise} Resolves after the configuration is durable. */ @@ -67,7 +67,7 @@ export async function writeMacOSAppUpdateConfig(resourcesDir, update, updaterCac /** * Verify the updater configuration inside an assembled macOS App. * @param {string} appPath - Application bundle path. - * @param {{ publicUrl: string }} update - Expected update feed. + * @param {{ publicUrl: string, channel?: 'nightly' | 'latest' }} update - Expected update feed. * @param {string | undefined} updaterCacheDirName - Exact cache directory when known. * @returns {Promise} Resolves when the packaged configuration matches the release destination. */ @@ -81,7 +81,7 @@ export async function verifyMacOSAppUpdateConfig(appPath, update, updaterCacheDi throw new Error(`desktop macOS update config: cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`) } const config = object(parsed, CONFIG_FILENAME) - if (config.provider !== 'generic' || config.url !== update.publicUrl || config.channel !== CHANNEL) { + if (config.provider !== 'generic' || config.url !== update.publicUrl || config.channel !== resolveDesktopUpdateChannel({ DSH_DESKTOP_UPDATE_CHANNEL: update.channel })) { throw new Error(`desktop macOS update config: ${path} does not match ${update.publicUrl}`) } const actualCacheDirName = nonEmptyString(config.updaterCacheDirName, `${CONFIG_FILENAME}.updaterCacheDirName`) diff --git a/apps/desktop/scripts/macos-runner-service.sh b/apps/desktop/scripts/macos-runner-service.sh new file mode 100644 index 0000000000..f3fd74eb94 --- /dev/null +++ b/apps/desktop/scripts/macos-runner-service.sh @@ -0,0 +1,61 @@ +#!/bin/bash +# Manage a registered runner in the current user's logged-in macOS session. +set -euo pipefail +if [[ $# -lt 2 ]]; then + echo 'Usage: bash macos-runner-service.sh install RUNNER_ROOT CONFIG_ROOT NODE_BIN | start|stop|status|uninstall RUNNER_ROOT' >&2 + exit 1 +fi +action=$1 +runner_root=$2 +[[ $(uname -s) = Darwin && $EUID -ne 0 ]] || { echo 'Run as the registered macOS runner user, without sudo' >&2; exit 1; } +[[ "$runner_root" = /* && -f "$runner_root/.runner" && -x "$runner_root/svc.sh" ]] || { echo 'Provide an absolute registered runner directory' >&2; exit 1; } +source_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +cd "$runner_root" +case "$action" in + install) + [[ $# = 4 ]] || { echo 'install requires RUNNER_ROOT CONFIG_ROOT NODE_BIN' >&2; exit 1; } + config_root=$3 + node_bin=$4 + [[ ! -f .service ]] || { echo 'Service already installed; stop and uninstall it before reinstalling' >&2; exit 1; } + launchctl print "gui/$(id -u)" >/dev/null || { echo 'Log into the macOS desktop as this user first' >&2; exit 1; } + bash "$source_dir/start-macos-packaging-runner.sh" "$runner_root" "$config_root" "$node_bin" --check + umask 077 + service_dir="$runner_root/dsh-service" + mkdir -p "$service_dir" + cp "$source_dir/start-macos-packaging-runner.sh" "$service_dir/start.sh" + # runsvc.sh reloads .path; replace the interactive PATH saved by registration. + printf '%s\n' "$node_bin:/usr/bin:/bin:/usr/sbin:/sbin" > .path + "$node_bin/node" --input-type=module - "$service_dir" "$runner_root" "$config_root" "$node_bin" <<'NODE' +import { writeFileSync } from 'node:fs' +const [directory, runner, config, node] = process.argv.slice(2) +const xml = value => value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''') +// svc.sh substitutes its own placeholders with sed; prohibit template syntax in paths. +for (const value of [directory, runner, config, node]) { + if (/[\r\n]|\{\{/u.test(value)) throw new Error('Service paths cannot contain newlines or template placeholders') +} +const args = ['/bin/bash', `${directory}/start.sh`, runner, config, node, '--service'] +writeFileSync(`${directory}/service.plist.template`, ` + + +Label{{SvcName}} +ProgramArguments${args.map(arg => `${xml(arg)}`).join('')} +WorkingDirectory${xml(runner)} +RunAtLoad +StandardOutPath${xml(directory)}/stdout.log +StandardErrorPath${xml(directory)}/stderr.log +EnvironmentVariablesACTIONS_RUNNER_SVC1 +ProcessTypeInteractive +SessionCreate + +`, { mode: 0o600 }) +NODE + GITHUB_ACTIONS_RUNNER_SERVICE_TEMPLATE="$service_dir/service.plist.template" ./svc.sh install + /usr/bin/plutil -lint "$(cat .service)" + echo 'Installed. Run start, then status. This LaunchAgent requires a desktop login after reboot.' + ;; + start|stop|status|uninstall) + [[ $# = 2 && -f .service ]] || { echo 'Provide an installed runner service directory' >&2; exit 1; } + ./svc.sh "$action" + ;; + *) echo "Unknown action: $action" >&2; exit 1 ;; +esac 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/macos-signature-cache-directory.d.mts b/apps/desktop/scripts/macos-signature-cache-directory.d.mts new file mode 100644 index 0000000000..163905a886 --- /dev/null +++ b/apps/desktop/scripts/macos-signature-cache-directory.d.mts @@ -0,0 +1,15 @@ +/** Optional machine-owned macOS signature storage. */ +/** + * Require existing private storage with no linked ancestors. + * @param path Explicit absolute cache directory. + * @returns Normalized directory; throws on invalid paths, ownership, permissions or access. + */ +export function validateMacOSSignatureCacheDirectory(path: string): string + +/** + * Select machine storage or retain the target-local default when the setting is absent. + * @param environment File-owned packaging configuration. + * @param targetBuildRoot Target build location. + * @returns Validated external directory, or the default directory created later by signing. + */ +export function resolveMacOSSignatureCacheDirectory(environment: NodeJS.ProcessEnv, targetBuildRoot: string): string diff --git a/apps/desktop/scripts/macos-signature-cache-directory.mjs b/apps/desktop/scripts/macos-signature-cache-directory.mjs new file mode 100644 index 0000000000..6a78af8e13 --- /dev/null +++ b/apps/desktop/scripts/macos-signature-cache-directory.mjs @@ -0,0 +1,38 @@ +/** Resolve optional machine-owned macOS signature storage before signing begins. */ +import { accessSync, constants, lstatSync } from 'node:fs' +import { dirname, isAbsolute, join, resolve } from 'node:path' + +/** + * Require existing private storage with no linked ancestors; never create or repair it during packaging. + * @param path Explicit absolute cache directory. + * @returns Normalized directory; invalid paths, ownership, permissions and access fail before signing. + */ +export function validateMacOSSignatureCacheDirectory(path) { + if (!path || path.includes('\0') || !isAbsolute(path)) { + throw new Error('DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR must be a nonempty absolute directory') + } + const root = resolve(path) + for (let ancestor = root; ; ancestor = dirname(ancestor)) { + const info = lstatSync(ancestor) + if (!info.isDirectory() || info.isSymbolicLink()) { + throw new Error(`macOS signature cache: expected an unlinked directory: ${ancestor}`) + } + if (ancestor === root && (info.uid !== process.getuid() || (info.mode & 0o077) !== 0 || (info.mode & 0o700) !== 0o700)) { + throw new Error(`macOS signature cache: directory must be private, accessible and owned by the current account: ${root}`) + } + if (ancestor === dirname(ancestor)) break + } + accessSync(root, constants.R_OK | constants.W_OK | constants.X_OK) + return root +} + +/** + * Select validated machine storage or retain the target-local cache when the setting is absent. + * @param environment File-owned packaging configuration. + * @param targetBuildRoot Existing target build location used by local packaging. + * @returns Selected cache directory; only the default may be created later by the signer. + */ +export function resolveMacOSSignatureCacheDirectory(environment, targetBuildRoot) { + const selected = environment.DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR + return selected === undefined ? join(targetBuildRoot, 'signature-cache') : validateMacOSSignatureCacheDirectory(selected) +} 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-macos.ts b/apps/desktop/scripts/package-macos.ts index c1a2cb5c71..4ba0fd12ca 100644 --- a/apps/desktop/scripts/package-macos.ts +++ b/apps/desktop/scripts/package-macos.ts @@ -115,7 +115,7 @@ export async function packageMacOSArtifacts( [dmgOutput, `${base}.dmg`], [zipOutput, `${base}.zip`], [zipOutput, `${base}.zip.blockmap`], - [zipOutput, desktopUpdateMetadataFilename(version, 'darwin')], + [zipOutput, desktopUpdateMetadataFilename(version, 'darwin', update.channel)], ] as const for (const [output, filename] of artifacts) { const file = join(output, filename) diff --git a/apps/desktop/scripts/package-target.ts b/apps/desktop/scripts/package-target.ts index a133ccdcf8..be2f577e1b 100644 --- a/apps/desktop/scripts/package-target.ts +++ b/apps/desktop/scripts/package-target.ts @@ -8,7 +8,7 @@ import { desktopBuildRecordFilename, resolveDesktopAutoUpdateConfig, } from './desktop-auto-update-environment.mjs' -import { desktopTargetBuildPaths } from './desktop-build-paths.mjs' +import { desktopArtifactOutput, desktopTargetBuildPaths } from './desktop-build-paths.mjs' import { packageMacOSArtifacts, type DesktopPrepackagedArtifact } from './package-macos.ts' import { loadDesktopPackageEnvironment, localMacOSPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs' import { createPackagingRun, recordPackagingEvent } from './packaging-run.mjs' @@ -153,6 +153,7 @@ function writeReleaseRecord( target: target.name, version: buildVersion, environment: update.environment, + channel: update.channel, publicUrl: update.publicUrl, // Upload reads this to tag the commit a production release was packaged from. ...packaged === undefined ? {} : { commit: packaged.commit, dirty: packaged.dirty }, @@ -196,6 +197,7 @@ interface DesktopPackageInvocation { readonly directory: boolean readonly prepareOnly: boolean readonly unsigned: boolean + readonly skipNotarization: boolean readonly check: boolean /** Build identifier to publish under, when this build does not publish the product version. */ readonly requestedBuildVersion: string | undefined @@ -228,6 +230,7 @@ export function parseDesktopPackageInvocation( dir: { type: 'boolean', default: false }, 'prepare-only': { type: 'boolean', default: false }, unsigned: { type: 'boolean', default: false }, + 'skip-notarization': { type: 'boolean', default: false }, check: { type: 'boolean', default: false }, 'build-version': { type: 'string' }, }, @@ -235,6 +238,9 @@ export function parseDesktopPackageInvocation( if (positionals.length > 1) throw new Error('desktop package: expected at most one target') const name = positionals[0] ?? hostTargetName(hostPlatform, hostArch) if (values.unsigned && values['prepare-only']) throw new Error('desktop package: --unsigned cannot use --prepare-only') + if (values['skip-notarization'] && (name === 'win-x64' || values.unsigned || values['prepare-only'])) { + throw new Error('desktop package: --skip-notarization requires a signed macOS build, without --prepare-only') + } const requestedBuildVersion = values['build-version']?.trim() if (values['build-version'] !== undefined && (requestedBuildVersion === undefined || requestedBuildVersion === '')) { throw new Error('desktop package: --build-version requires a value') @@ -244,6 +250,7 @@ export function parseDesktopPackageInvocation( directory: values.dir, prepareOnly: values['prepare-only'], unsigned: values.unsigned, + skipNotarization: values['skip-notarization'], check: values.check, requestedBuildVersion, } @@ -322,20 +329,27 @@ 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, + artifactsRoot: desktopArtifactOutput(paths, invocation).directory, }) } async function main(): Promise { const invocation = parseDesktopPackageInvocation(process.argv.slice(2)) const { target } = invocation + if (invocation.skipNotarization) { + process.stdout.write('desktop package: skipping notarization and stapling; internal debugging only, not qualified for distribution or update publishing\n') + } 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 @@ -350,7 +364,8 @@ async function main(): Promise { Object.assign(environment, desktopBuildCommitEnvironment(packaged)) const secrets = Object.entries(environment).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD|APPLE_ID/iu.test(name)).map(([, value]) => value ?? '') const run = createPackagingRun(join(APP_ROOT, '.desktop-build', 'packaging-runs'), { - target: target.name, unsigned: invocation.unsigned, directory: invocation.directory, prepareOnly: invocation.prepareOnly, + target: target.name, unsigned: invocation.unsigned, skipNotarization: invocation.skipNotarization, + directory: invocation.directory, prepareOnly: invocation.prepareOnly, version: buildVersion, productVersion, node: process.version, commit: packaged.commit, dirty: packaged.dirty, @@ -385,8 +400,9 @@ async function main(): Promise { } if (success && target.platform === 'darwin' && !invocation.directory && !invocation.prepareOnly) { const paths = desktopTargetBuildPaths(target.name) - const filename = `deepseek-harness-${buildVersion}-mac-${target.arch}${invocation.unsigned ? '-unsigned' : ''}.dmg` - console.log(`DMG: ${join(invocation.unsigned ? paths.unsignedArtifacts : paths.artifacts, filename)}`) + const output = desktopArtifactOutput(paths, invocation) + const filename = `deepseek-harness-${buildVersion}-mac-${target.arch}${output.suffix}.dmg` + console.log(`DMG: ${join(output.directory, filename)}`) } } @@ -410,14 +426,16 @@ export async function packageTarget( const packArguments = mac === undefined ? [] : ['--concurrency', String(mac.packConcurrency)] const buildPaths = desktopTargetBuildPaths(target.name) const releaseRecordPath = join(buildPaths.artifacts, desktopBuildRecordFilename(target.name)) - if (!invocation.prepareOnly && !invocation.unsigned) { + if (!invocation.prepareOnly && !invocation.unsigned && !invocation.skipNotarization) { rmSync(releaseRecordPath, { force: true }) rmSync(`${releaseRecordPath}.tmp`, { force: true }) } + const artifactsRoot = desktopArtifactOutput(buildPaths, invocation).directory const buildEnv = withoutWindowsSigningEnvironment(withoutDesktopUploadCredentials( desktopElectronBuilderEnvironment(environment, invocation.unsigned))) const targetEnv: NodeJS.ProcessEnv = { ...buildEnv, + DSH_DESKTOP_MACOS_SKIP_NOTARIZATION: invocation.skipNotarization ? '1' : '0', DSH_DESKTOP_TARGET_PLATFORM: target.platform, DSH_DESKTOP_TARGET_ARCH: target.arch, } @@ -481,7 +499,7 @@ export async function packageTarget( await execute(['run', 'prepare:dsh', ...(signPrimaryRuntime ? ['--defer-runtime-smoke'] : [])], downloadEnv) if (signPrimaryRuntime) await execute(['run', 'sign:primary-runtime', '--dsh'], electronBuilderEnv) if (invocation.prepareOnly) return - if (target.platform === 'darwin' && !invocation.unsigned && !invocation.directory) { + if (target.platform === 'darwin' && !invocation.unsigned && !invocation.skipNotarization && !invocation.directory) { await execute([ ...desktopElectronBuilderArguments(target, true), '--config.mac.notarize=false', @@ -494,7 +512,7 @@ export async function packageTarget( artifactsRoot: buildPaths.artifacts, environment: electronBuilderEnv, }, artifact => execute(desktopElectronBuilderArguments(target, false, artifact), electronBuilderEnv)), undefined, undefined, proxyEvent) - } else if (target.platform === 'darwin' && !invocation.unsigned) { + } else if (target.platform === 'darwin' && !invocation.unsigned && !invocation.skipNotarization) { await execute([...desktopElectronBuilderArguments(target, true), '--config.mac.notarize=false'], electronBuilderEnv) await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts'], targetEnv) const appPath = join(buildPaths.artifacts, target.arch === 'arm64' ? 'mac-arm64' : 'mac', 'DeepSeek Harness.app') @@ -502,10 +520,13 @@ export async function packageTarget( () => notarizeMacOS({ appPath, ...resolveMacOSNotarizationEnvironment(environment) }), undefined, undefined, proxyEvent) } else { await signedStage('artifacts', () => execute(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv)) - await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts', ...(invocation.unsigned ? ['--unsigned'] : [])], targetEnv) + await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts', + ...(invocation.unsigned ? ['--unsigned'] : []), ...(invocation.skipNotarization ? ['--skip-notarization'] : [])], targetEnv) } - if (!invocation.directory && !invocation.unsigned) writeReleaseRecord(target, electronBuilderEnv, buildPaths.artifacts) - if (journal) recordPackagingEvent(journal, { type: 'artifacts', directory: invocation.unsigned ? buildPaths.unsignedArtifacts : buildPaths.artifacts }) + if (!invocation.directory && !invocation.unsigned && !invocation.skipNotarization) { + writeReleaseRecord(target, electronBuilderEnv, buildPaths.artifacts) + } + if (journal) recordPackagingEvent(journal, { type: 'artifacts', directory: artifactsRoot }) } if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) await main() diff --git a/apps/desktop/scripts/prepare-dsh.ts b/apps/desktop/scripts/prepare-dsh.ts index 4e03f763cb..9de39d3ff2 100644 --- a/apps/desktop/scripts/prepare-dsh.ts +++ b/apps/desktop/scripts/prepare-dsh.ts @@ -1,5 +1,6 @@ /** Materialize the complete production runtime before publishing Desktop resources. */ +import { resolveMacOSSignatureCacheDirectory } from './macos-signature-cache-directory.mjs' import { packagingStep } from './packaging-step.mjs' import { spawn } from 'node:child_process' import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' @@ -20,6 +21,7 @@ import { import { smokePrimaryRuntime } from './prepare-primary-runtime.ts' import { smokePreparedRuntime } from './smoke-prepared-runtime.ts' import { prepareRuntimeManifests } from './prepare-runtime-manifests.ts' +import { prepareRuntimePatches, verifyRuntimePatches } from './prepare-runtime-patches.ts' import { writeDesktopRuntime, verifyDesktopRuntime } from '../src/runtime-tree.ts' import { resolveDesktopAppId, @@ -42,7 +44,7 @@ const RUNTIME_ROOT = BUILD_PATHS.runtime const PNPM_BUILD_STATE = BUILD_PATHS.dshPnpm const PACKAGE_SET_ROOT = BUILD_PATHS.packageSet const NODE = join(BUILD_PATHS.electron, process.platform === 'win32' ? 'electron.exe' : 'Electron.app/Contents/MacOS/Electron') -const PNPM = join(RUNTIME_ROOT, 'pnpm', 'bin', 'pnpm.mjs') +const PNPM = join(RUNTIME_ROOT, 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs') function manifestVersion(path: string, subject: string): string { const manifest = JSON.parse(readFileSync(path, 'utf8')) as { version?: unknown } @@ -117,12 +119,14 @@ async function main(): Promise { mkdirSync(STORE_ROOT, { recursive: true }) }) const release = desktopRelease() - await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:stage-packages', async () => { + const patches = await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:stage-packages', async () => { copyFileSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGE_SET_FILE), join(BUILD_ROOT, DESKTOP_PACKAGE_SET_FILE)) cpSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGES_DIR), join(BUILD_ROOT, DESKTOP_PACKAGES_DIR), { recursive: true }) createRuntimeProjectMetadata(BUILD_ROOT, release) + return prepareRuntimePatches(BUILD_ROOT, resolve(APP_ROOT, '..', '..')) }) await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:lockfile', () => runPnpm(['install', '--lockfile-only'])) + verifyRuntimePatches(BUILD_ROOT, patches) verifyDesktopCoreLockfile( readFileSync(join(BUILD_ROOT, 'pnpm-lock.yaml'), 'utf8'), readDesktopCorePackageSet(BUILD_ROOT, release.version), @@ -154,8 +158,9 @@ async function main(): Promise { throw new Error(`desktop runtime: missing required LibreOffice engine ${officeEngine}`) } 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'))) + const cacheDirectory = resolveMacOSSignatureCacheDirectory(process.env, BUILD_PATHS.root) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'sign:dsh-native', () => signMacOSRuntime(DSH_OUTPUT_ROOT, resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env), target.arch, cacheDirectory)) + 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, cacheDirectory, '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-macos-ci.mjs b/apps/desktop/scripts/prepare-macos-ci.mjs new file mode 100644 index 0000000000..5b51052cb6 --- /dev/null +++ b/apps/desktop/scripts/prepare-macos-ci.mjs @@ -0,0 +1,26 @@ +/** Validate machine-owned macOS signing settings and record a manual Actions build version. */ +import { appendFileSync, readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { execFileSync } from 'node:child_process' +import { desktopCiVersion } from './desktop-ci-version.mjs' +import { loadDesktopPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs' + +const appRoot = resolve(import.meta.dirname, '..') +const product = JSON.parse(readFileSync(resolve(appRoot, 'package.json'), 'utf8')) +const version = desktopCiVersion(process.env, product.version) +if (!process.env.DSH_PACKAGING_PRESET) throw new Error('Select a machine preset') +const skipNotarization = process.env.PACKAGE_SKIP_NOTARIZATION === 'true' +if (process.env.PACKAGE_PUBLISH === 'true' && skipNotarization) throw new Error('Publishing requires notarization and stapling') +if (!['true', 'false', undefined].includes(process.env.PACKAGE_SKIP_NOTARIZATION)) throw new Error('Invalid skip notarization selection') +const environment = loadDesktopPackageEnvironment('darwin', process.env, appRoot) +for (const [name, value] of Object.entries(environment)) { + if (/KEY|TOKEN|PASSWORD|SECRET|APPLE_ID/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: 'darwin', arch: 'arm64' }, { skipNotarization }) +if (!process.env.GITHUB_OUTPUT || !process.env.GITHUB_STEP_SUMMARY) throw new Error('Run this adapter from GitHub Actions') +appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\nartifacts=${skipNotarization ? 'unnotarized-artifacts' : 'artifacts'}\nmode=${skipNotarization ? 'unnotarized-debug' : 'signed'}\n`) +appendFileSync(process.env.GITHUB_STEP_SUMMARY, `macOS arm64 signed installer\n\nVersion: ${version}\n\nCommit: ${execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()}\n\nChannel: ${process.env.DSH_DESKTOP_UPDATE_CHANNEL}\n\nSource: ${process.env.PACKAGE_SOURCE_REF}\n\nPreset: ${process.env.DSH_PACKAGING_PRESET}\n`) +if (skipNotarization) appendFileSync(process.env.GITHUB_STEP_SUMMARY, '\nWARNING: signed but NOT notarized or stapled. Internal debugging only; Gatekeeper may block downloaded copies. Not qualified for distribution or update publishing.\n') diff --git a/apps/desktop/scripts/prepare-runtime-patches.ts b/apps/desktop/scripts/prepare-runtime-patches.ts new file mode 100644 index 0000000000..83ebbbe457 --- /dev/null +++ b/apps/desktop/scripts/prepare-runtime-patches.ts @@ -0,0 +1,125 @@ +/** Stage explicitly selected Desktop patches without modifying the source workspace. */ +import { createHash } from 'node:crypto' +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { isAbsolute, join, relative, resolve } from 'node:path' +import yaml from 'js-yaml' +import { valid } from 'semver' +import { DESKTOP_RUNTIME_DEPENDENCY_OVERRIDES, DESKTOP_RUNTIME_PATCHES, type DesktopRuntimePatch } from './runtime-patch-policy.ts' + +/** Expected patch bytes and package version for one independent installation. */ +export interface PreparedRuntimePatch { + spec: string + name: string + version: string + path: string + hash: string +} + +/** Selected bytes and dependencies excluded from the Desktop runtime. */ +export interface PreparedRuntimePatches { + patches: PreparedRuntimePatch[] + workspaceOnly: string[] +} + +function patchIdentity(spec: string): { name: string; version: string } { + const separator = spec.lastIndexOf('@') + const name = spec.slice(0, separator) + const version = spec.slice(separator + 1) + if (separator <= 0 || valid(version) !== version) throw new Error(`desktop patches: expected an exact package version: ${spec}`) + return { name, version } +} + +function patchHash(bytes: Buffer): string { + return createHash('sha256').update(bytes).digest('hex') +} + +/** + * Stage selected patches and explicit overrides before Desktop resolves its temporary lockfile. + * Every root patch must be classified; shared bytes must match the root lockfile's pnpm 11 hash. + * @param projectRoot Disposable project containing pnpm-workspace.yaml, outside the repository root itself. + * @param repositoryRoot Source repository; its files remain read-only. + * @param policy Desktop patch decisions, including optional runtime-only files relative to the repository. + * @param overrides Explicit Desktop dependency constraints; patch versions never generate overrides. + * @returns Expected patch identities and hashes for lockfile and staged-file verification. + */ +export function prepareRuntimePatches( + projectRoot: string, repositoryRoot: string, + policy: Readonly> = DESKTOP_RUNTIME_PATCHES, + overrides: Readonly> = DESKTOP_RUNTIME_DEPENDENCY_OVERRIDES, +): PreparedRuntimePatches { + if (resolve(projectRoot) === resolve(repositoryRoot)) throw new Error('desktop patches: destination must not be the source workspace') + const source = yaml.load(readFileSync(join(repositoryRoot, 'pnpm-workspace.yaml'), 'utf8')) as { + patchedDependencies: Record + } + const sourceLock = yaml.load(readFileSync(join(repositoryRoot, 'pnpm-lock.yaml'), 'utf8')) as { + patchedDependencies: Record + } + for (const spec of Object.keys(source.patchedDependencies)) { + if (!Object.hasOwn(policy, spec)) throw new Error(`desktop patches: classify the workspace patch ${spec}`) + } + const selected: Array = [] + for (const [spec, rule] of Object.entries(policy)) { + const identity = patchIdentity(spec) + if (rule.scope !== 'runtime-only' && !Object.hasOwn(source.patchedDependencies, spec)) { + throw new Error(`desktop patches: stale workspace patch decision ${spec}`) + } + if (rule.scope === 'workspace-only') continue + const sourcePath = rule.scope === 'shared' ? source.patchedDependencies[spec]! : rule.path + const localPath = relative(resolve(repositoryRoot), resolve(repositoryRoot, sourcePath)) + if (isAbsolute(sourcePath) || localPath.startsWith('..') || isAbsolute(localPath)) { + throw new Error(`desktop patches: patch must be inside the repository: ${sourcePath}`) + } + const bytes = readFileSync(join(repositoryRoot, sourcePath)) + const hash = patchHash(bytes) + if (rule.scope === 'shared' && sourceLock.patchedDependencies[spec] !== hash) { + throw new Error(`desktop patches: shared patch hash differs from the root lockfile: ${spec}`) + } + selected.push({ spec, ...identity, path: `patches/desktop-${selected.length}.patch`, hash, bytes }) + } + const targetPath = join(projectRoot, 'pnpm-workspace.yaml') + const target = yaml.load(readFileSync(targetPath, 'utf8')) as Record & { overrides?: Record } + for (const [name, version] of Object.entries(overrides)) { + if (target.overrides?.[name] !== undefined && target.overrides[name] !== version) { + throw new Error(`desktop patches: conflicting dependency override for ${name}`) + } + } + mkdirSync(join(projectRoot, 'patches'), { recursive: true }) + for (const entry of selected) writeFileSync(join(projectRoot, entry.path), entry.bytes) + writeFileSync(targetPath, yaml.dump({ ...target, overrides: { ...target.overrides, ...overrides }, + patchedDependencies: Object.fromEntries(selected.map(entry => [entry.spec, entry.path])), allowUnusedPatches: false })) + return { patches: selected.map(({ bytes: _bytes, ...entry }) => entry), + workspaceOnly: Object.entries(policy).filter(([, rule]) => rule.scope === 'workspace-only').map(([spec]) => patchIdentity(spec).name) } +} + +/** + * Reject changed patch bytes, lock hashes or resolved versions before the frozen production install. + * @param projectRoot Independent Desktop installation containing its resolved lockfile. + * @param plan Expected identities and exclusions returned by patch preparation. + */ +export function verifyRuntimePatches(projectRoot: string, plan: PreparedRuntimePatches): void { + const lock = yaml.load(readFileSync(join(projectRoot, 'pnpm-lock.yaml'), 'utf8')) as { + patchedDependencies?: Record + packages?: Record + } + for (const patch of plan.patches) { + if (!Object.keys(lock.packages ?? {}).some(spec => spec.startsWith(`${patch.name}@`))) { + throw new Error(`desktop patches: selected patch has no runtime dependency: ${patch.spec}`) + } + if (patchHash(readFileSync(join(projectRoot, patch.path))) !== patch.hash) { + throw new Error(`desktop patches: staged patch bytes changed: ${patch.spec}`) + } + if (lock.patchedDependencies?.[patch.spec] !== patch.hash) { + throw new Error(`desktop patches: lockfile patch hash mismatch: ${patch.spec}`) + } + } + for (const [spec, entry] of Object.entries(lock.packages ?? {})) { + if (plan.workspaceOnly.some(name => spec.startsWith(`${name}@`))) { + throw new Error(`desktop patches: workspace-only dependency entered the runtime: ${spec}; review its patch scope`) + } + const candidates = plan.patches.filter(patch => spec.startsWith(`${patch.name}@`)) + if (candidates.length === 0) continue + if (!candidates.some(patch => (entry.version ?? spec.slice(patch.name.length + 1)) === patch.version)) { + throw new Error(`desktop patches: ${spec} has no matching patch; review its version and Desktop patch policy`) + } + } +} diff --git a/apps/desktop/scripts/prepare-runtime.ts b/apps/desktop/scripts/prepare-runtime.ts index 1b88f091bc..ba92fef0e6 100644 --- a/apps/desktop/scripts/prepare-runtime.ts +++ b/apps/desktop/scripts/prepare-runtime.ts @@ -1,14 +1,15 @@ -/** Prepare the target Electron distribution and pinned pnpm CLI. */ +/** Prepare Desktop resources and publish their versions after every preparation stage succeeds. */ -import { packagingStep } from './packaging-step.mjs' import { execFileSync } from 'node:child_process' -import { chmodSync, cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { chmodSync, cpSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' import { createRequire } from 'node:module' -import { dirname, join } from 'node:path' +import { join } from 'node:path' import { parseArgs } from 'node:util' import { downloadArtifact } from '@electron/get' import extractZip from 'extract-zip' -import { resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs' +import { readPrimaryRuntime } from '../../../packages/skill/tool-workspace-dependencies/src/index.ts' +import { desktopTargetPlatform, resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs' +import { packagingStep } from './packaging-step.mjs' import { preparePrimaryRuntime } from './prepare-primary-runtime.ts' import { prepareDesktopCli } from './prepare-cli.ts' import { prepareCommandLink } from './prepare-command-link.ts' @@ -16,23 +17,10 @@ import { prepareCommandLink } from './prepare-command-link.ts' const BUILD_PATHS = resolveDesktopTargetBuildPaths() const RUNTIME_ROOT = BUILD_PATHS.runtime -function preparePnpm(): string { - const require = createRequire(import.meta.url) - const manifestPath = require.resolve('pnpm') - const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { version?: unknown } - if (typeof manifest.version !== 'string') throw new Error('desktop runtime: pnpm manifest has no version') - const packageDir = dirname(manifestPath) - const destination = join(RUNTIME_ROOT, 'pnpm') - rmSync(destination, { recursive: true, force: true }) - cpSync(packageDir, destination, { recursive: true }) - return manifest.version -} +type DesktopTarget = ReturnType -async function main(): Promise { - const { values } = parseArgs({ options: { 'defer-primary-runtime-smoke': { type: 'boolean', default: false } } }) - const target = resolveDesktopBuildTarget() - const platform = target.startsWith('mac-') ? 'darwin' : 'win32' - const arch = target.endsWith('arm64') ? 'arm64' : 'x64' +/** Extract the target Electron distribution and return its embedded Node version. */ +async function prepareElectron({ platform, arch }: DesktopTarget): Promise { const require = createRequire(import.meta.url) const { version } = require('electron/package.json') as { version: string } const archive = await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'download:electron', @@ -40,28 +28,42 @@ async function main(): Promise { rmSync(BUILD_PATHS.electron, { recursive: true, force: true }) await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'extract:electron', () => extractZip(archive, { dir: BUILD_PATHS.electron })) const executable = join(BUILD_PATHS.electron, platform === 'win32' ? 'electron.exe' : 'Electron.app/Contents/MacOS/Electron') - const nodeVersion = execFileSync(executable, ['-p', 'process.versions.node'], { + return execFileSync(executable, ['-p', 'process.versions.node'], { encoding: 'utf8', env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, }).trim() - const macosMinimumVersion = platform === 'darwin' ? execFileSync('/usr/libexec/PlistBuddy', - ['-c', 'Print LSMinimumSystemVersion', join(BUILD_PATHS.electron, 'Electron.app', 'Contents', 'Info.plist')], { encoding: 'utf8' }).trim() : undefined - rmSync(RUNTIME_ROOT, { recursive: true, force: true }) - mkdirSync(RUNTIME_ROOT, { recursive: true }) - const pnpmVersion = preparePnpm() +} + +function prepareCli({ platform, arch }: DesktopTarget): void { cpSync(join(import.meta.dirname, 'node-bin'), join(RUNTIME_ROOT, 'bin'), { recursive: true }) chmodSync(join(RUNTIME_ROOT, 'bin', 'node'), 0o755) + const cli = join(RUNTIME_ROOT, 'cli') + prepareDesktopCli(cli, platform) + if (platform === 'darwin') { + const minimumVersion = execFileSync('/usr/libexec/PlistBuddy', [ + '-c', 'Print LSMinimumSystemVersion', join(BUILD_PATHS.electron, 'Electron.app', 'Contents', 'Info.plist'), + ], { encoding: 'utf8' }).trim() + prepareCommandLink(cli, arch, minimumVersion) + } + cpSync(join(import.meta.dirname, '..', 'lib', 'command-manager-entry.js'), join(cli, 'command-manager.js')) + cpSync(join(import.meta.dirname, 'command-path.ps1'), join(cli, 'command-path.ps1')) +} + +async function main(): Promise { + const { values } = parseArgs({ options: { 'defer-primary-runtime-smoke': { type: 'boolean', default: false } } }) + const target = desktopTargetPlatform(resolveDesktopBuildTarget()) + rmSync(RUNTIME_ROOT, { recursive: true, force: true }) + mkdirSync(RUNTIME_ROOT, { recursive: true }) + const nodeVersion = await prepareElectron(target) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'prepare:primary-runtime', + () => preparePrimaryRuntime({ deferSmoke: values['defer-primary-runtime-smoke'] })) + const { pnpm } = await readPrimaryRuntime(join(RUNTIME_ROOT, 'primary-runtime')) + if (pnpm === undefined) throw new Error('desktop runtime: primary-runtime manifest has no pnpm version') + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'prepare:cli', async () => { prepareCli(target) }) writeFileSync(join(RUNTIME_ROOT, 'versions.json'), `${JSON.stringify({ schemaVersion: 1, node: nodeVersion, - pnpm: pnpmVersion, + pnpm, }, undefined, 2)}\n`) - await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'prepare:cli', - async () => prepareDesktopCli(join(RUNTIME_ROOT, 'cli'), platform)) - if (macosMinimumVersion !== undefined) prepareCommandLink(join(RUNTIME_ROOT, 'cli'), arch, macosMinimumVersion) - cpSync(join(import.meta.dirname, '..', 'lib', 'command-manager-entry.js'), join(RUNTIME_ROOT, 'cli', 'command-manager.js')) - cpSync(join(import.meta.dirname, 'command-path.ps1'), join(RUNTIME_ROOT, 'cli', 'command-path.ps1')) - await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'prepare:primary-runtime', - () => preparePrimaryRuntime({ deferSmoke: values['defer-primary-runtime-smoke'] })) } await main() diff --git a/apps/desktop/scripts/prepare-windows-ci.d.mts b/apps/desktop/scripts/prepare-windows-ci.d.mts new file mode 100644 index 0000000000..3b0196dc57 --- /dev/null +++ b/apps/desktop/scripts/prepare-windows-ci.d.mts @@ -0,0 +1,10 @@ +/** Resolve the version used by the manual Windows packaging workflow. */ + +/** + * 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 build version. + */ +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 new file mode 100644 index 0000000000..307d9b0fcf --- /dev/null +++ b/apps/desktop/scripts/prepare-windows-ci.mjs @@ -0,0 +1,29 @@ +/** Resolve a manual Windows build version and validate the selected machine preset. */ +import { appendFileSync, readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { execFileSync } from 'node:child_process' +import { desktopCiVersion as windowsCiVersion } from './desktop-ci-version.mjs' +export { desktopCiVersion as windowsCiVersion } from './desktop-ci-version.mjs' +import { loadDesktopPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs' + +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 version = windowsCiVersion(process.env, product.version) + const mode = process.env.PACKAGE_SIGNING + if (process.env.PACKAGE_PUBLISH === 'true' && mode !== 'signed') throw new Error('Publishing requires signed Windows packages') + 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') + appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\n`) + appendFileSync(process.env.GITHUB_STEP_SUMMARY, `Windows x64 ${mode} installer\n\nVersion: ${version}\n\nCommit: ${execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()}\n\nChannel: ${process.env.DSH_DESKTOP_UPDATE_CHANNEL}\n\nSource: ${process.env.PACKAGE_SOURCE_REF}\n\nPreset: ${process.env.DSH_PACKAGING_PRESET}\n`) +} diff --git a/apps/desktop/scripts/publish-desktop-ci.ts b/apps/desktop/scripts/publish-desktop-ci.ts new file mode 100644 index 0000000000..0abc317463 --- /dev/null +++ b/apps/desktop/scripts/publish-desktop-ci.ts @@ -0,0 +1,126 @@ +/** Publish a retained package selected by the routing job; --check never reads secrets or contacts COS. */ +import { createHash } from 'node:crypto' +import { appendFile } from 'node:fs/promises' +import { dirname, join, resolve } from 'node:path' +import { z } from 'zod' +import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts' +import { desktopReleasesRoot } from './retain-desktop-ci.ts' +import { retainedDesktopPath, verifyRetainedDesktopRelease } from './desktop-release-store.ts' +import { verifyRetainedDesktopSignatures } from './verify-retained-desktop.ts' +import { createDesktopUploadPlan } from './desktop-upload-plan.ts' +import { desktopPublishCos } from './desktop-publish-cos.ts' +import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from './desktop-publish-record.ts' +import { publishDesktopRelease } from './desktop-publish.ts' +import { desktopPublicationFailure } from './desktop-publication-failure.ts' +import { publishDesktopTag } from './desktop-publish-tag.ts' + +const routeSchema = z.object({ runId: z.string(), attempt: z.string(), commit: z.string(), runnerName: z.string(), + sourceRef: z.string(), channel: z.enum(['nightly', 'latest']), + target: z.enum(['mac-arm64', 'win-x64']), preset: z.enum(['test', 'production']) }) + +/** + * Check retained bytes, original machine, destination and signatures before reading any upload secret. + * @param env Router output and machine configuration directory. + * @param verifySignatures Platform verifier; tests inject a verifier for fixture bytes. + * @returns Validated local publication context; no network operation is performed. + */ +export async function prepareDesktopPublication(env: NodeJS.ProcessEnv, verifySignatures = verifyRetainedDesktopSignatures) { + const route = routeSchema.parse(JSON.parse(env.DESKTOP_PUBLISH_ROUTE || '{}')) + if (route.runnerName !== env.RUNNER_NAME) throw new Error('desktop publish: task was dispatched to a different machine') + const root = desktopReleasesRoot(env) + const manifest = await verifyRetainedDesktopRelease(root, route.runId, route.attempt) + const source = manifest.source + if (source.repository !== env.GITHUB_REPOSITORY || source.runnerName !== route.runnerName || source.target !== route.target + || source.channel !== route.channel || source.sourceRef !== route.sourceRef || source.commit !== route.commit + || source.preset !== route.preset || !source.publishRequested) { + throw new Error('desktop publish: local package differs from the routed request') + } + if (source.qualification !== (source.target === 'win-x64' ? 'signed' : 'notarized')) throw new Error('desktop publish: debugging artifacts cannot be published') + const config = await readDesktopPublishConfig(env.DSH_PACKAGING_CONFIG_DIR!, source.preset) + const directory = retainedDesktopPath(root, route.runId, route.attempt) + const environment = source.preset === 'test' + ? { DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: config.origin, + DOWNLOAD_TEST_RELEASE_ID: source.testReleaseId ?? '', DOWNLOAD_TEST_COS_BUCKET: config.bucket } + : { DSH_DESKTOP_AUTO_UPDATE_ENV: 'production', DOWNLOAD_PROD_COS_BUCKET: config.bucket } + const plan = await createDesktopUploadPlan(source.target, { artifactsRoot: directory, + packagedProductVersion: source.productVersion, environment: { ...environment, DSH_DESKTOP_UPDATE_CHANNEL: source.channel } }) + if (plan.version !== source.version || plan.commit !== source.commit || plan.dirty !== false) throw new Error('desktop publish: completion record differs from retained source or has uncommitted changes') + await verifySignatures(directory, manifest, config) + const approval = createHash('sha256').update(JSON.stringify({ manifest, plan })).digest('hex') + if (env.DESKTOP_APPROVED_PACKAGE && env.DESKTOP_APPROVED_PACKAGE !== approval) throw new Error('desktop publish: package or destination changed after approval') + return { route, manifest, config, plan, root, approval } +} + +if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) { + let phase = 'local package, destination and signature verification' + try { + const mode = process.argv[2] + if (process.argv.length !== 3 || (mode !== '--check' && mode !== '--publish')) throw new Error('Usage: publish-desktop-ci.ts --check|--publish') + const env = process.env + const { route, manifest, config, plan, root, approval } = await prepareDesktopPublication(env) + if (mode === '--publish' && !env.DESKTOP_APPROVED_PACKAGE) throw new Error('desktop publish: approved package digest is required') + if (mode === '--check') { + if (env.GITHUB_OUTPUT) await appendFile(env.GITHUB_OUTPUT, `approval=${approval}\nlabel=${plan.version} → ${manifest.source.channel} / ${plan.target} / ${plan.environment}\n`) + if (env.GITHUB_STEP_SUMMARY) await appendFile(env.GITHUB_STEP_SUMMARY, + `\n## Confirm Desktop publication\n\nVersion: **${plan.version}**; channel: **${manifest.source.channel}**; environment: **${plan.environment}**; platform: **${plan.target}**\n\nSource: ${manifest.source.sourceRef} @ ${route.commit}\n\nPackage: ${route.runId}, attempt ${route.attempt}\n\nTag: ${plan.environment === 'production' ? `desktop-v${plan.version}` : 'none (test)'}\n\nApproved package SHA-256: ${approval}\n\n` + + plan.artifacts.map(file => `- ${file.channelMetadata ? 'Feed' : 'Artifact'}: ${file.key}`).join('\n') + '\n') + if (env.GITHUB_OUTPUT && config.githubApp) await appendFile(env.GITHUB_OUTPUT, + `app-client-id=${config.githubApp.clientId}\napp-key-file=${config.githubApp.privateKeyFile}\n`) + process.stdout.write(`desktop publish: verified ${plan.target} ${plan.version}; no credentials read or COS requests made\n`) + } else { + if (plan.environment === 'production' && !env.DESKTOP_TAG_TOKEN) throw new Error('desktop publish: GitHub App token is required before production upload') + phase = 'upload credential loading' + const credentials = await readDesktopUploadCredentials(config) + const destination = `${plan.bucket}/${plan.publicUrl}${manifest.source.channel}` + const recordsRoot = join(dirname(root), 'upload-records') + phase = 'channel lock and publication journal acquisition' + await withDesktopChannelLock(join(dirname(root), 'publish-locks'), destination, async () => { + const published = await wasDesktopAttemptPublished(recordsRoot, + { repository: manifest.source.repository, runId: route.runId, attempt: route.attempt, destination }) + const journal = await createDesktopPublicationRecord(recordsRoot, { + repository: manifest.source.repository, runId: route.runId, attempt: route.attempt, + actor: env.GITHUB_TRIGGERING_ACTOR || env.GITHUB_ACTOR || 'unknown', + destination, operation: 'publish', reason: 'Actions publication', + }) + if (env.GITHUB_OUTPUT) await appendFile(env.GITHUB_OUTPUT, `record=${journal.directory}\n`) + let status: 'complete' | 'failed' | 'published-tag-pending' = 'failed' + try { + phase = 'remote object reconciliation and publication' + const tag = async () => { await publishDesktopTag(manifest.source.repository, + plan.version, route.commit, env.DESKTOP_TAG_TOKEN || '') } + const result = published + ? await (async () => { + await journal.record({ type: 'feeds-complete' }) + if (plan.environment === 'production') { + try { await tag() } catch (cause) { + await journal.record({ type: 'tag-pending' }) + return { status: 'published-tag-pending' as const, cause } + } + } + await journal.record({ type: 'complete' }) + return { status: 'complete' as const } + })() + : await publishDesktopRelease(plan, { + transport: desktopPublishCos(plan, credentials), record: event => journal.record(event), + tag, + }) + status = result.status + if (env.GITHUB_STEP_SUMMARY) await appendFile(env.GITHUB_STEP_SUMMARY, + `\nDesktop publication: **${status}**\n\n${plan.target} ${plan.version}\n\nSource: ${route.runId}, attempt ${route.attempt}\n`) + if (result.status === 'published-tag-pending') { + const failure = desktopPublicationFailure(result.cause, 'release tag creation') + await journal.record({ type: 'failed', failure }) + process.stderr.write(`${JSON.stringify(failure)}\n`) + process.exitCode = 1 + } + } catch (error) { + await journal.record({ type: 'failed', failure: desktopPublicationFailure(error, phase) }) + throw error + } finally { await journal.finish(status) } + }) + } + } catch (error) { + process.stderr.write(`${JSON.stringify(desktopPublicationFailure(error, phase))}\n`) + process.exitCode = 1 + } +} diff --git a/apps/desktop/scripts/read-desktop-app-key.mjs b/apps/desktop/scripts/read-desktop-app-key.mjs new file mode 100644 index 0000000000..590f7898d2 --- /dev/null +++ b/apps/desktop/scripts/read-desktop-app-key.mjs @@ -0,0 +1,14 @@ +/** Hand a machine App key to the token action after Environment approval, masking before output. */ +import { readFileSync, appendFileSync } from 'node:fs' +import { randomUUID } from 'node:crypto' + +try { + if (!process.env.APP_KEY_FILE || !process.env.GITHUB_OUTPUT) throw new Error('Actions key file and output are required') + const key = readFileSync(process.env.APP_KEY_FILE, 'utf8') + console.log('::add-mask::' + key.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A')) + const delimiter = randomUUID() + appendFileSync(process.env.GITHUB_OUTPUT, `private-key<<${delimiter}\n${key}\n${delimiter}\n`) +} catch { + process.stderr.write('Desktop publication: cannot hand the configured App key to the token action.\n') + process.exitCode = 1 +} diff --git a/apps/desktop/scripts/resolve-desktop-publish-ci.ts b/apps/desktop/scripts/resolve-desktop-publish-ci.ts new file mode 100644 index 0000000000..cd1326dceb --- /dev/null +++ b/apps/desktop/scripts/resolve-desktop-publish-ci.ts @@ -0,0 +1,57 @@ +/** Resolve a workflow_run publication request without reading machine or COS credentials. */ +import { execFileSync } from 'node:child_process' +import { appendFile, mkdir, readFile } from 'node:fs/promises' +import { join, resolve } from 'node:path' +import { z } from 'zod' +import { resolveDesktopPublishRoute } from './desktop-publish-route.ts' + +const eventSchema = z.object({ workflow_run: z.object({ id: z.number().int().positive(), run_attempt: z.number().int().positive() }) }) +const artifactsSchema = z.object({ artifacts: z.array(z.object({ name: z.string(), expired: z.boolean() })) }) + +if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) { + const env = process.env + if (!env.GITHUB_EVENT_PATH || !env.GITHUB_REPOSITORY || !env.GITHUB_OUTPUT || !env.RUNNER_TEMP) throw new Error('desktop publish: Actions context required') + const event = eventSchema.parse(JSON.parse(await readFile(env.GITHUB_EVENT_PATH, 'utf8'))) + const repository = env.GITHUB_REPOSITORY + if (!/^[\w.-]+\/[\w.-]+$/u.test(repository)) throw new Error('desktop publish: invalid repository') + const { id, run_attempt: attempt } = event.workflow_run + const api = (path: string): unknown => JSON.parse(execFileSync('gh', ['api', + path], { encoding: 'utf8', timeout: 60_000, maxBuffer: 8 * 1024 * 1024 })) + const base = `repos/${repository}/actions/runs/${id}` + const name = `desktop-publish-request-${id}-${attempt}` + const pages: unknown = JSON.parse(execFileSync('gh', ['api', '--paginate', '--slurp', + `${base}/artifacts?per_page=100`], { encoding: 'utf8', timeout: 60_000, maxBuffer: 8 * 1024 * 1024 })) + const match = z.array(artifactsSchema).parse(pages).flatMap(page => page.artifacts) + .find(artifact => artifact.name === name) + if (match === undefined) { + await appendFile(env.GITHUB_OUTPUT, 'publish=false\n') + } else { + if (match.expired) throw new Error('desktop publish: request artifact expired') + const destination = join(env.RUNNER_TEMP, `desktop-request-${id}-${attempt}-${env.GITHUB_RUN_ID}-${env.GITHUB_RUN_ATTEMPT}`) + await mkdir(destination, { recursive: false, mode: 0o700 }) + execFileSync('gh', ['run', 'download', String(id), '--repo', repository, + '--name', name, '--dir', destination], { timeout: 60_000, stdio: 'pipe' }) + const request: unknown = JSON.parse(await readFile(join(destination, 'manifest.json'), 'utf8')) + const jobs = z.object({ jobs: z.array(z.unknown()) }).parse(api(`${base}/attempts/${attempt}/jobs?per_page=100`)) + const route = resolveDesktopPublishRoute(repository, api(`${base}/attempts/${attempt}`), + request, jobs.jobs, JSON.parse(env.DESKTOP_PUBLISH_RUNNERS || '{}')) + const source = z.object({ sha: z.string() }).parse(api(`repos/${repository}/commits/${route.commit}`)) + if (source.sha !== route.commit) throw new Error('desktop publish: source commit not found') + if (route.sourceRef === 'master') { + const comparison = z.object({ status: z.string() }).parse(api(`repos/${repository}/compare/${route.commit}...master`)) + if (!['ahead', 'identical'].includes(comparison.status)) throw new Error('desktop publish: source is not on master') + } else { + const tagged = z.object({ sha: z.string() }).parse(api(`repos/${repository}/commits/${route.sourceRef}`)) + if (tagged.sha !== route.commit) throw new Error('desktop publish: source tag changed') + } + { + const environment = z.object({ protection_rules: z.array(z.object({ type: z.string(), + reviewers: z.array(z.unknown()).optional() })) }) + .parse(api(`repos/${repository}/environments/desktop-${route.preset}`)) + if (!environment.protection_rules.some(rule => rule.type === 'required_reviewers' && (rule.reviewers?.length ?? 0) > 0)) { + throw new Error(`desktop publish: desktop-${route.preset} requires configured reviewers`) + } + } + await appendFile(env.GITHUB_OUTPUT, `publish=true\nroute=${JSON.stringify(route)}\nrunner=${route.runnerLabel}\npreset=${route.preset}\n`) + } +} diff --git a/apps/desktop/scripts/retain-desktop-ci.ts b/apps/desktop/scripts/retain-desktop-ci.ts new file mode 100644 index 0000000000..9fddc8d995 --- /dev/null +++ b/apps/desktop/scripts/retain-desktop-ci.ts @@ -0,0 +1,81 @@ +/** Retain completed CI packages and a credential-free request for the publishing workflow. */ +import { appendFile, readFile } from 'node:fs/promises' +import { dirname, isAbsolute, join, resolve } from 'node:path' +import { desktopTargetBuildPaths, resolveDesktopBuildTarget } from './desktop-build-paths.mjs' +import { desktopBuildRecordFilename, desktopUpdateMetadataFilename, resolveDesktopUpdateChannel } from './desktop-auto-update-environment.mjs' +import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' +import { retainDesktopRelease, type DesktopRetainedSource } from './desktop-release-store.ts' +import { validateDesktopBuildVersion } from './desktop-build-version.mjs' + +function required(env: NodeJS.ProcessEnv, name: string): string { + const value = env[name] + if (!value) throw new Error(`desktop retention: ${name} is required`) + return value +} + +/** + * Resolve the persistent release root without assuming a particular user's home directory. + * @param env Machine packaging configuration; an explicit releases directory overrides its sibling default. + * @returns Absolute directory outside the disposable checkout. + */ +export function desktopReleasesRoot(env: NodeJS.ProcessEnv): string { + const configured = required(env, 'DSH_PACKAGING_CONFIG_DIR') + const root = env.DSH_DESKTOP_RELEASES_DIR || join(dirname(configured), 'releases') + if (!isAbsolute(configured) || !isAbsolute(root)) throw new Error('desktop retention: machine directories must be absolute') + return root +} + +/** + * Save the complete installer inventory for a successful package job, without reading signing secrets. + * @param env Actions identity, resolved package version and machine preset selection. + * @param appRoot Desktop checkout directory; defaults to this script's owning app. + * @returns Retained directory. Publish requests for debugging packages reject before copying. + */ +export async function retainDesktopCi(env: NodeJS.ProcessEnv, appRoot = resolve(import.meta.dirname, '..')): Promise { + const target = resolveDesktopBuildTarget(env) + const windows = target === 'win-x64' + const platform = windows ? 'win32' : 'darwin' + const settings = loadDesktopPackageEnvironment(platform, env, appRoot, { unsigned: true }) + const preset = settings.DSH_PACKAGING_PRESET + if (preset !== 'test' && preset !== 'production') throw new Error('desktop retention: a machine preset is required') + const publish = env.PACKAGE_PUBLISH === 'true' + if (!['true', 'false', undefined].includes(env.PACKAGE_PUBLISH)) throw new Error('desktop retention: invalid publish selection') + if (windows && !['signed', 'unsigned'].includes(env.PACKAGE_SIGNING ?? '')) throw new Error('desktop retention: invalid signing selection') + if (!windows && !['true', 'false'].includes(env.PACKAGE_SKIP_NOTARIZATION ?? '')) throw new Error('desktop retention: invalid notarization selection') + const qualification = windows ? (env.PACKAGE_SIGNING === 'signed' ? 'signed' : 'unsigned') + : (env.PACKAGE_SKIP_NOTARIZATION === 'true' ? 'unnotarized' : 'notarized') + if (publish && (qualification === 'unsigned' || qualification === 'unnotarized')) { + throw new Error('desktop retention: publishing requires signed Windows or notarized macOS packages') + } + const product: { version: string } = JSON.parse(await readFile(join(appRoot, 'package.json'), 'utf8')) + const version = validateDesktopBuildVersion(required(env, 'PACKAGE_VERSION'), product.version) + const source: DesktopRetainedSource = { + repository: required(env, 'GITHUB_REPOSITORY'), runId: required(env, 'GITHUB_RUN_ID'), + attempt: required(env, 'GITHUB_RUN_ATTEMPT'), commit: required(env, 'PACKAGE_SOURCE_SHA'), + workflowCommit: required(env, 'GITHUB_SHA'), sourceRef: required(env, 'PACKAGE_SOURCE_REF'), + channel: resolveDesktopUpdateChannel(settings), + runnerName: required(env, 'RUNNER_NAME'), target, preset, productVersion: product.version, version, + testReleaseId: preset === 'test' ? (settings.DOWNLOAD_TEST_RELEASE_ID || null) : null, + publishRequested: publish, qualification, + } + const paths = desktopTargetBuildPaths(target) + // The CLI's checkout owns these paths; alternate app roots are used by fixtures. + const mode = qualification === 'unsigned' ? 'unsigned-artifacts' : qualification === 'unnotarized' ? 'unnotarized-artifacts' : 'artifacts' + const artifacts = appRoot === resolve(import.meta.dirname, '..') + ? join(paths.root, mode) : join(appRoot, '.desktop-build', 'targets', target, mode) + const base = `deepseek-harness-${version}-${windows ? 'win-x64' : target}` + const debugSuffix = qualification === 'unnotarized' ? '-unnotarized' : qualification === 'unsigned' ? '-unsigned' : '' + const names = windows ? [`${base}${debugSuffix}.exe`] : [`${base}${debugSuffix}.dmg`, `${base}${debugSuffix}.zip`] + if (qualification === 'signed' || qualification === 'notarized') { + names.push(`${base}.${windows ? 'exe' : 'zip'}.blockmap`, desktopBuildRecordFilename(target), desktopUpdateMetadataFilename(version, platform, source.channel)) + } + const retained = await retainDesktopRelease(desktopReleasesRoot(env), source, names.map(name => join(artifacts, name))) + if (env.GITHUB_OUTPUT) await appendFile(env.GITHUB_OUTPUT, `directory=${retained}\n`) + if (env.GITHUB_STEP_SUMMARY) await appendFile(env.GITHUB_STEP_SUMMARY, + `\nRetained package: ${env.GITHUB_RUN_ID}/${env.GITHUB_RUN_ATTEMPT}\n\nPublish requested: ${publish}\n`) + return retained +} + +if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) { + await retainDesktopCi(process.env) +} diff --git a/apps/desktop/scripts/rollback-desktop-channel.ts b/apps/desktop/scripts/rollback-desktop-channel.ts new file mode 100644 index 0000000000..fbefbe4f8b --- /dev/null +++ b/apps/desktop/scripts/rollback-desktop-channel.ts @@ -0,0 +1,60 @@ +/** Manual channel restoration: read-only preview unless --execute is explicitly present. */ +import { readFile } from 'node:fs/promises' +import { dirname, join, resolve } from 'node:path' +import { parseArgs } from 'node:util' +import { z } from 'zod' +import { prepareDesktopPublication } from './publish-desktop-ci.ts' +import { readDesktopUploadCredentials } from './desktop-publish-config.ts' +import { desktopPublishCos } from './desktop-publish-cos.ts' +import { createDesktopPublicationRecord, withDesktopChannelLock } from './desktop-publish-record.ts' +import { rollbackDesktopChannel } from './desktop-rollback.ts' +import { desktopPublicationFailure } from './desktop-publication-failure.ts' + +if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) { + let phase = 'rollback arguments and local publication verification' + try { + const { values } = parseArgs({ options: { + record: { type: 'string' }, 'expected-version': { type: 'string' }, + reason: { type: 'string' }, execute: { type: 'boolean', default: false }, + } }) + if (!values.record || !values['expected-version'] || !values.reason?.trim()) { + throw new Error('Usage: rollback-desktop-channel.ts --record --expected-version --reason [--execute]') + } + const operation = z.object({ repository: z.string(), runId: z.string(), + attempt: z.string(), destination: z.string(), operation: z.literal('publish') }) + .parse(JSON.parse(await readFile(join(values.record, 'operation.json'), 'utf8'))) + z.object({ status: z.enum(['complete', 'published-tag-pending']) }) + .parse(JSON.parse(await readFile(join(values.record, 'result.json'), 'utf8'))) + const { plan, config, root, manifest } = await prepareDesktopPublication(process.env) + const route = z.object({ runId: z.string(), attempt: z.string() }).parse(JSON.parse(process.env.DESKTOP_PUBLISH_ROUTE || '{}')) + const destination = `${plan.bucket}/${plan.publicUrl}${manifest.source.channel}` + if (operation.runId !== route.runId || operation.attempt !== route.attempt + || operation.repository !== process.env.GITHUB_REPOSITORY || operation.destination !== destination) { + throw new Error('desktop rollback: successful publication record does not match the selected package') + } + const credentials = await readDesktopUploadCredentials(config) + phase = 'rollback channel lock and audit creation' + await withDesktopChannelLock(join(dirname(root), 'publish-locks'), destination, async () => { + const journal = await createDesktopPublicationRecord(join(dirname(root), 'upload-records'), { + ...operation, actor: process.env.USER || process.env.USERNAME || 'unknown', operation: 'rollback', reason: values.reason!, + }) + process.stdout.write(`desktop rollback: audit ${journal.directory}\n`) + let complete = false + try { + phase = 'historical object verification and channel restoration' + const outcome = await rollbackDesktopChannel(plan, values['expected-version']!, values.execute!, { + transport: desktopPublishCos(plan, credentials), record: event => journal.record(event), + tag: async () => { throw new Error('desktop rollback never changes tags') }, + }) + process.stdout.write(`${JSON.stringify(outcome, null, 2)}\n`) + complete = true + } catch (error) { + await journal.record({ type: 'failed', failure: desktopPublicationFailure(error, phase) }) + throw error + } finally { await journal.finish(complete ? (values.execute ? 'complete' : 'preview') : 'failed') } + }) + } catch (error) { + process.stderr.write(`${JSON.stringify(desktopPublicationFailure(error, phase))}\n`) + process.exitCode = 1 + } +} diff --git a/apps/desktop/scripts/runtime-file-policy.ts b/apps/desktop/scripts/runtime-file-policy.ts index b7cbc4415c..ddb60417d9 100644 --- a/apps/desktop/scripts/runtime-file-policy.ts +++ b/apps/desktop/scripts/runtime-file-policy.ts @@ -1,7 +1,7 @@ /** Desktop-only omissions from already installed production npm packages. */ /** - * Identify build and diagnostic files omitted from the immutable Desktop runtime. + * Identify build, diagnostic and other-platform files omitted from the immutable Desktop runtime. * Unrecognized assets and target runtime binaries are retained. Paths name the copied * node_modules tree, including nested package containers. * @param path - Path relative to the production node_modules directory. @@ -16,7 +16,7 @@ export function desktopRuntimeFileExclusion( if (parts.some(part => ['.bin', '.pnpm', '.modules.yaml', '.pnpm-workspace-state-v1.json'].includes(part))) { return 'package-manager metadata' } - const file = parts.at(-1) ?? '' + const file = parts.at(-1)! if (/\.(?:[cm]?[jt]s|css)\.map$/u.test(file)) return 'source map' if (/\.d\.[cm]?ts$/u.test(file)) return 'TypeScript declaration' if (/\.tsbuildinfo$/u.test(file)) return 'TypeScript build cache' @@ -40,6 +40,10 @@ 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' + } if (name === 'node-pty' && entry.startsWith('prebuilds/')) { const platform = packageParts[nameParts + 1] if (platform !== undefined && platform !== `${target.platform}-${target.arch}`) return 'node-pty other platform' diff --git a/apps/desktop/scripts/runtime-patch-policy.ts b/apps/desktop/scripts/runtime-patch-policy.ts new file mode 100644 index 0000000000..d2ea174f2c --- /dev/null +++ b/apps/desktop/scripts/runtime-patch-policy.ts @@ -0,0 +1,25 @@ +/** Desktop-specific selection of workspace and runtime-only dependency patches. */ + +/** A patch shared with the workspace, excluded from runtime installation, or supplied only to Desktop. */ +export type DesktopRuntimePatch = + | { scope: 'shared'; reason: string } + | { scope: 'workspace-only'; reason: string } + | { scope: 'runtime-only'; path: string; reason: string } + +/** Every workspace patch requires an explicit Desktop decision; runtime-only entries may add or replace a patch. */ +export const DESKTOP_RUNTIME_PATCHES: Readonly> = { + '@earendil-works/pi-ai@1.1.0': { scope: 'shared', reason: 'Runtime providers need the streamed argument parsing fix.' }, + '@electron/osx-sign@1.3.3': { scope: 'workspace-only', reason: 'Signing executes on the build host.' }, + '@fortune-sheet/core@1.0.4': { scope: 'workspace-only', reason: 'Patched spreadsheet code is embedded in the client bundle.' }, + '@fortune-sheet/react@1.0.4': { scope: 'workspace-only', reason: 'Patched spreadsheet code is embedded in the client bundle.' }, + '@yao-pkg/pkg@6.21.0': { scope: 'workspace-only', reason: 'The executable packer executes on the build host.' }, + 'app-builder-lib@26.17.0': { scope: 'workspace-only', reason: 'DMG format validation executes on the build host.' }, + 'exceljs@4.4.0': { scope: 'workspace-only', reason: 'The patched parser is embedded in the client bundle and worker.' }, + 'node-pty@1.2.0-beta.15': { scope: 'shared', reason: 'Runtime terminals need helper resolution and Windows worker cleanup.' }, +} + +/** Reviewed Desktop dependency constraints, independent of patch selection. */ +export const DESKTOP_RUNTIME_DEPENDENCY_OVERRIDES: Readonly> = { + // The provider declares ^1.1.0; its patch is qualified against 1.1.0. + '@earendil-works/pi-ai@^1.1.0': '1.1.0', +} diff --git a/apps/desktop/scripts/setup-macos-packaging.mjs b/apps/desktop/scripts/setup-macos-packaging.mjs new file mode 100644 index 0000000000..d04200f058 --- /dev/null +++ b/apps/desktop/scripts/setup-macos-packaging.mjs @@ -0,0 +1,34 @@ +/** Prepare private machine directories and templates without registering a runner or overwriting configuration. */ +import { readFileSync, writeFileSync, existsSync, lstatSync, mkdirSync } from 'node:fs' +import { dirname, isAbsolute, join, resolve } from 'node:path' + +const [root, mode] = process.argv.slice(2) +if (process.platform !== 'darwin') throw new Error('Run macOS packaging setup on a Mac') +if (!root || !isAbsolute(root) || (mode !== undefined && mode !== '--check') || process.argv.length > 4) { + throw new Error('Usage: node setup-macos-packaging.mjs ABSOLUTE_ROOT [--check]') +} +if (/[\r\n']/u.test(root)) throw new Error('Packaging root cannot contain single quotes or newlines') +for (let path = resolve(root); ; path = dirname(path)) { + if (existsSync(path) && lstatSync(path).isSymbolicLink()) throw new Error('Packaging root ancestors cannot be links') + if (path === dirname(path)) break +} +for (const relative of ['', 'packaging', 'packaging/presets', 'packaging/secrets', 'packaging/certificates', 'runner', 'cache', 'cache/macos-signatures']) { + const path = join(root, relative) + if (!existsSync(path) && mode !== '--check') mkdirSync(path, { recursive: true, mode: 0o700 }) + const info = lstatSync(path) + if (!info.isDirectory() || info.isSymbolicLink() || info.uid !== process.getuid() || (info.mode & 0o077) !== 0) { + throw new Error(`Packaging directories must be real, private and owned by the current account: ${path}`) + } +} +if (mode !== '--check') { + for (const [name, directory] of [['test', 'presets'], ['production', 'presets'], ['macos-signing', 'secrets']]) { + const destination = join(root, 'packaging', directory, `${name}.env.example`) + if (!existsSync(destination)) { + const template = readFileSync(resolve(import.meta.dirname, '../config/macos-packaging', `${name}.env.example`), 'utf8') + const cache = join(root, 'cache/macos-signatures') + writeFileSync(destination, template.replace('# DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR=', + `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR='${cache}'`), { flag: 'wx', mode: 0o600 }) + } + } +} +process.stdout.write(`Private packaging directories verified: ${resolve(root)}\n`) 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/smoke-packaged-runtime.ts b/apps/desktop/scripts/smoke-packaged-runtime.ts index b91030008b..6c3c12c857 100644 --- a/apps/desktop/scripts/smoke-packaged-runtime.ts +++ b/apps/desktop/scripts/smoke-packaged-runtime.ts @@ -1,17 +1,17 @@ /** Validate the assembled application, including native Office conversion outside ASAR. */ import { join } from 'node:path' import { parseArgs } from 'node:util' -import { resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs' +import { desktopArtifactOutput, resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs' import { readDesktopRuntime, verifyDesktopRuntime } from '../src/runtime-tree.ts' import { verifyWindowsCode } from './windows-runtime-signature.mjs' import { smokePreparedRuntime } from './smoke-prepared-runtime.ts' import { resolveDesktopPackageTarget } from './package-target.ts' const paths = resolveDesktopTargetBuildPaths() -const { values } = parseArgs({ options: { unsigned: { type: 'boolean', default: false } }, allowPositionals: false }) +const { values } = parseArgs({ options: { unsigned: { type: 'boolean', default: false }, 'skip-notarization': { type: 'boolean', default: false } }, allowPositionals: false }) const target = resolveDesktopBuildTarget() const windows = target === 'win-x64' -const artifacts = values.unsigned ? paths.unsignedArtifacts : paths.artifacts +const artifacts = desktopArtifactOutput(paths, { unsigned: values.unsigned, skipNotarization: values['skip-notarization'] }).directory const application = windows ? join(artifacts, 'win-unpacked') : join(artifacts, target === 'mac-arm64' ? 'mac-arm64' : 'mac', 'DeepSeek Harness.app', 'Contents') const resources = join(application, windows ? 'resources' : 'Resources') diff --git a/apps/desktop/scripts/smoke-prepared-runtime.ts b/apps/desktop/scripts/smoke-prepared-runtime.ts index 697f52708e..e6afd574da 100644 --- a/apps/desktop/scripts/smoke-prepared-runtime.ts +++ b/apps/desktop/scripts/smoke-prepared-runtime.ts @@ -31,7 +31,16 @@ export async function smokePreparedRuntime( const { stdout } = await promisify(execFile)(node, [ '--expose-internals', resolve(import.meta.dirname, '../tests/fixtures/runtime-payload-smoke.mjs'), root, resourcesRuntime, ], { timeout: 120_000, windowsHide: true, - env: desktopNodeEnvironment(node, join(resourcesRuntime, 'bin'), environment) }) + env: desktopNodeEnvironment(node, join(resourcesRuntime, 'bin'), environment) }).catch((error: unknown) => { + if (error instanceof Error) { + if ('stdout' in error && typeof error.stdout === 'string') process.stdout.write(error.stdout) + if ('stderr' in error && typeof error.stderr === 'string') process.stderr.write(error.stderr) + if ('killed' in error && 'signal' in error) { + process.stderr.write(`runtime payload: killed=${String(error.killed)}, signal=${String(error.signal)}\n`) + } + } + throw error + }) process.stdout.write(stdout) await smokeDesktopRuntime(root, node, descriptor, environment, resourcesRuntime) } finally { diff --git a/apps/desktop/scripts/smoke-runtime.ts b/apps/desktop/scripts/smoke-runtime.ts index f15f10a928..bbc2d3e7ae 100644 --- a/apps/desktop/scripts/smoke-runtime.ts +++ b/apps/desktop/scripts/smoke-runtime.ts @@ -1,6 +1,7 @@ /** Boot the materialized target runtime without access to a user's Harness profile. */ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { appendFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { execFile } from 'node:child_process' @@ -12,7 +13,7 @@ import { createPluginProfile } from '../src/project-manager.ts' import type { DesktopRuntimeDescriptor } from '../src/runtime-tree.ts' /** - * Check Host startup, its matching frontend, external plugins and real Office-to-PDF conversion. + * Check CLI package operations, Host startup, its frontend, external plugins and real Office-to-PDF conversion. * @param root - Materialized dsh resources. * @param node - Prepared target Electron executable. * @param runtime - Verified resource descriptor. @@ -25,15 +26,50 @@ export async function smokeDesktopRuntime( ): Promise { const home = mkdtempSync(join(tmpdir(), 'dsh-desktop-smoke-')) const profile = join(home, 'profiles', 'desktop') - const host = new DesktopHostProcess(node, root, profile, undefined, { ...environment, DSH_HOME: home }, + const hostEnvironment = { + ...Object.fromEntries(Object.entries(environment).filter(([name]) => !/^(?:npm|pnpm|corepack)_/iu.test(name))), + DSH_HOME: home, HOME: home, USERPROFILE: home, + XDG_CONFIG_HOME: home, XDG_CACHE_HOME: home, XDG_STATE_HOME: home, + APPDATA: home, LOCALAPPDATA: home, + npm_config_userconfig: join(home, 'npmrc'), npm_config_globalconfig: join(home, 'npmrc'), + npm_config_store_dir: join(home, 'store'), npm_config_enable_global_virtual_store: 'false', + } + const host = new DesktopHostProcess(node, root, profile, undefined, hostEnvironment, undefined, join(resourcesRuntime, 'primary-runtime'), - { pnpm: join(resourcesRuntime, 'pnpm', 'bin', 'pnpm.cjs'), nodeBin: join(resourcesRuntime, 'bin') }) + { pnpm: join(resourcesRuntime, 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs'), nodeBin: join(resourcesRuntime, 'bin') }) let timer: ReturnType | undefined try { + writeFileSync(join(home, 'npmrc'), '') createPluginProfile(profile) const pluginName = 'desktop-runtime-smoke-plugin' - const plugin = join(profile, 'node_modules', pluginName) + const plugin = join(home, pluginName) mkdirSync(plugin, { recursive: true }) + const installedName = 'desktop-installed-smoke-plugin' + const installedPlugin = join(home, installedName) + mkdirSync(installedPlugin) + writeFileSync(join(installedPlugin, 'package.json'), JSON.stringify({ + name: installedName, version: '1.0.0', type: 'module', exports: './index.js', dsh: { bundle: { patch: './bundle.yml' } }, + })) + writeFileSync(join(installedPlugin, 'index.js'), ` +export function apply(ctx) { + ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/desktop-smoke-installed', + handler(_request, response) { response.end('installed plugin ready') } })) +} +`) + writeFileSync(join(installedPlugin, 'bundle.yml'), `- insert:\n - id: ${installedName}\n name: ${installedName}\n inject: [webServer]\n`) + appendFileSync(join(profile, 'pnpm-workspace.yaml'), 'offline: true\nupdateNotifier: false\n') + const cli = join(root, 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'cli.js') + const runCli = (args: string[]) => promisify(execFile)(node, + ['--expose-internals', cli, 'plugin', '--profile', 'desktop', ...args], + { cwd: home, env: { ...hostEnvironment, ELECTRON_RUN_AS_NODE: '1' }, timeout: 120_000, windowsHide: true }) + await runCli(['add', `file:${installedPlugin}`, '--offline', '--ignore-scripts']) + const installedEntry = join(profile, 'node_modules', installedName, 'index.js') + if (readFileSync(installedEntry, 'utf8') !== readFileSync(join(installedPlugin, 'index.js'), 'utf8')) { + throw new Error('desktop runtime: CLI did not install the local plugin') + } + await runCli(['remove', installedName]) + if (existsSync(installedEntry)) throw new Error('desktop runtime: CLI did not remove the local plugin') + console.log('desktop runtime: CLI offline plugin installation and removal passed') const primary = join(resourcesRuntime, 'primary-runtime') const dependencies = workspaceDependencyPaths(primary, await readPrimaryRuntime(primary)) await promisify(execFile)(dependencies.python, ['-I', '-B', @@ -56,10 +92,19 @@ export function apply(ctx) { if (!(ctx instanceof Context)) throw new Error('desktop runtime: external plugin loaded another Cordis instance') ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/desktop-smoke', handler(_request, response) { response.end('plugin route ready') } })) + ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/desktop-smoke-install', + async handler(_request, response) { + try { + response.end(JSON.stringify(await ctx.pluginManager.installBundle(${JSON.stringify(installedPlugin)}))) + } catch (error) { + response.statusCode = 500 + response.end(inspect(error, { depth: 5 })) + } + } })) ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/desktop-smoke-office-cli', async handler(_request, response) { try { - const skill = await ctx.skills.get('office-docx') + const skill = await ctx.skills.get('office-export-pdf') const json = skill?.content.match(/\\n(\\{\\n[\\s\\S]+)$/u)?.[1] if (json === undefined) throw new Error('Office skill did not supply CLI paths') const { libreofficeKit: { node, cli } } = JSON.parse(json) @@ -90,12 +135,13 @@ export function apply(ctx) { } } `) - writeFileSync(join(plugin, 'bundle.yml'), '- insert:\n - id: desktop-runtime-smoke-plugin\n name: desktop-runtime-smoke-plugin\n inject: [webServer, officeToPdf, skills]\n') + writeFileSync(join(plugin, 'bundle.yml'), '- insert:\n - id: desktop-runtime-smoke-plugin\n name: desktop-runtime-smoke-plugin\n inject: [webServer, officeToPdf, skills, pluginManager]\n') + cpSync(plugin, join(profile, 'node_modules', pluginName), { recursive: true }) const manifest = JSON.parse(readFileSync(join(profile, 'package.json'), 'utf8')) as { - dependencies: Record + dependencies?: Record dsh: { profile: { bundles: string[] } } } - manifest.dependencies[pluginName] = '1.0.0' + manifest.dependencies = { ...manifest.dependencies, [pluginName]: `file:${plugin}` } manifest.dsh.profile.bundles.push(pluginName) writeFileSync(join(profile, 'package.json'), JSON.stringify(manifest)) writeFileSync(join(profile, 'cordis.patch.yml'), '- id: webserver\n config:\n host: 127.0.0.1\n port: 0\n') @@ -111,6 +157,14 @@ export function apply(ctx) { } const pluginResponse = await fetch(new URL('/desktop-smoke', ready.url), { headers: { cookie } }) if (await pluginResponse.text() !== 'plugin route ready') throw new Error('desktop runtime: plugin HTTP route failed') + const installation = await fetch(new URL('/desktop-smoke-install', ready.url), { + headers: { cookie }, signal: AbortSignal.timeout(120_000), + }) + const installationResult = await installation.text() + const installed = await fetch(new URL('/desktop-smoke-installed', ready.url), { headers: { cookie } }) + if (!installation.ok || !installed.ok || await installed.text() !== 'installed plugin ready') { + throw new Error(`desktop runtime: bundled pnpm plugin installation failed: ${installationResult}`) + } for (const { extension } of inputs) { const converted = await fetch(new URL(`/desktop-smoke-office/${extension}`, ready.url), { headers: { cookie }, signal: AbortSignal.timeout(120_000), @@ -133,7 +187,8 @@ export function apply(ctx) { console.log('desktop runtime: DOCX, XLSX, PPTX to PDF and skill CLI discovery passed') } finally { clearTimeout(timer) - await host.stop() - rmSync(home, { recursive: true, force: true }) + try { await host.stop() } finally { + await rm(home, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 }) + } } } diff --git a/apps/desktop/scripts/start-macos-packaging-runner.sh b/apps/desktop/scripts/start-macos-packaging-runner.sh new file mode 100644 index 0000000000..a171001a4a --- /dev/null +++ b/apps/desktop/scripts/start-macos-packaging-runner.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# Run an already registered Apple Silicon runner with explicit tools and machine configuration. +set -euo pipefail +if [[ $# -lt 3 || $# -gt 4 || (${4:-} != '' && ${4:-} != '--check' && ${4:-} != '--service') ]]; then + echo 'Usage: bash start-macos-packaging-runner.sh RUNNER_ROOT CONFIG_ROOT NODE_BIN [--check|--service]' >&2 + exit 1 +fi +runner_root=$1 +config_root=$2 +node_bin=$3 +for directory in "$runner_root" "$config_root" "$node_bin"; do + [[ "$directory" = /* && -d "$directory" ]] || { echo 'All directories must exist and be absolute' >&2; exit 1; } +done +[[ $(uname -s) = Darwin && $(uname -m) = arm64 ]] || { echo 'Requires an Apple Silicon Mac' >&2; exit 1; } +[[ -x "$node_bin/node" ]] || { echo 'NODE_BIN must contain Node 24' >&2; exit 1; } +[[ $("$node_bin/node" -p 'process.versions.node.split(".")[0]') = 24 ]] || { echo 'Requires Node 24' >&2; exit 1; } +[[ -f "$config_root/presets/test.env" && -f "$config_root/secrets/macos-signing.env" ]] || { echo 'Configure the test preset and macos-signing.env before starting' >&2; exit 1; } +developer_dir=$(xcode-select -p) +sdk_root=$(DEVELOPER_DIR="$developer_dir" xcrun --sdk macosx --show-sdk-path) +xcrun --find notarytool +xcrun --find stapler +probe_dir=$(mktemp -d "${TMPDIR:-/tmp}/dsh-macos-toolchain.XXXXXX") +trap 'rm -rf "$probe_dir"' EXIT +DEVELOPER_DIR="$developer_dir" SDKROOT="$sdk_root" /usr/bin/cc -x c - -o "$probe_dir/toolchain-probe" <<<'int main(void) { return 0; }' +rm -rf "$probe_dir" +trap - EXIT +if [[ ${4:-} = '--check' ]]; then + echo 'Runner tool and configuration-file checks passed; registration and credentials were not tested.' + exit 0 +fi +[[ -f "$runner_root/.runner" && -x "$runner_root/run.sh" ]] || { echo 'Register the runner before starting' >&2; exit 1; } +entry=./run.sh +if [[ ${4:-} = '--service' ]]; then + [[ -x "$runner_root/runsvc.sh" ]] || { echo 'Install the runner service first' >&2; exit 1; } + entry=./runsvc.sh +fi +cd "$runner_root" +exec /usr/bin/env -i HOME="$HOME" USER="$(id -un)" LOGNAME="$(id -un)" \ + PATH="$node_bin:/usr/bin:/bin:/usr/sbin:/sbin" TMPDIR="${TMPDIR:-/tmp}" \ + DEVELOPER_DIR="$developer_dir" SDKROOT="$sdk_root" \ + ACTIONS_RUNNER_SVC="${ACTIONS_RUNNER_SVC:-0}" LANG=en_US.UTF-8 DSH_PACKAGING_CONFIG_DIR="$config_root" DSH_TELEMETRY_DISABLED=1 \ + /usr/bin/caffeinate -i "$entry" 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/scripts/verify-macos-signature.d.mts b/apps/desktop/scripts/verify-macos-signature.d.mts index a33c3f4213..cf1434b2d2 100644 --- a/apps/desktop/scripts/verify-macos-signature.d.mts +++ b/apps/desktop/scripts/verify-macos-signature.d.mts @@ -80,3 +80,10 @@ export function verifyMacOSSignatureAfterSign( context: MacOSAfterSignContext, expected: MacOSSigningEnvironment, ): void + +/** + * Verify a disk image's code signature and Developer ID without requiring a notarization ticket. + * @param diskImagePath Path to the packaged `.dmg` file. + * @param expected Public signing identity. + */ +export function verifyMacOSDiskImageSignature(diskImagePath: string, expected: MacOSSigningEnvironment): void diff --git a/apps/desktop/scripts/verify-macos-signature.mjs b/apps/desktop/scripts/verify-macos-signature.mjs index 6817f0962f..a906f88ab7 100644 --- a/apps/desktop/scripts/verify-macos-signature.mjs +++ b/apps/desktop/scripts/verify-macos-signature.mjs @@ -172,9 +172,7 @@ export function verifyMacOSNotarizedApplication(appPath, expected) { * @returns {void} */ export function verifyMacOSDiskImage(diskImagePath, expected) { - runCodeSign(['--verify', '--strict', '--verbose=2', diskImagePath]) - const details = runCodeSign(['--display', '--verbose=4', diskImagePath]) - assertMacOSSignatureDetails(details, expected) + verifyMacOSDiskImageSignature(diskImagePath, expected) runAppleCommand('/usr/bin/xcrun', ['stapler', 'validate', diskImagePath], 'stapler validate') runAppleCommand('/usr/sbin/spctl', ['--assess', '--type', 'install', '--verbose=4', diskImagePath], 'spctl') } @@ -202,3 +200,15 @@ if (process.argv[1] !== undefined && import.meta.filename === resolve(process.ar verifyMacOSSignature(resolve(appPath), expected) process.stdout.write(`desktop macOS signing: verified Developer ID Application: ${expected.signingIdentity} (${expected.teamId})\n`) } + +/** + * Verify a disk image's code signature and Developer ID without requiring a notarization ticket. + * @param {string} diskImagePath Path to the packaged `.dmg` file. + * @param {{ signingIdentity: string, teamId: string }} expected Public signing identity. + * @returns {void} + */ +export function verifyMacOSDiskImageSignature(diskImagePath, expected) { + runCodeSign(['--verify', '--strict', '--verbose=2', diskImagePath]) + const details = runCodeSign(['--display', '--verbose=4', diskImagePath]) + assertMacOSSignatureDetails(details, expected) +} diff --git a/apps/desktop/scripts/verify-published-windows.ps1 b/apps/desktop/scripts/verify-published-windows.ps1 new file mode 100644 index 0000000000..2e2f772451 --- /dev/null +++ b/apps/desktop/scripts/verify-published-windows.ps1 @@ -0,0 +1,16 @@ +# Verify the existing installer; never sign or access the hardware token. +param( + [Parameter(Mandatory = $true)][string]$Installer, + [Parameter(Mandatory = $true)][string]$Thumbprint +) +$ErrorActionPreference = 'Stop' +$signature = Get-AuthenticodeSignature -LiteralPath $Installer +if ($signature.Status -ne 'Valid' -or $null -eq $signature.SignerCertificate) { + throw 'Installer does not have a valid Authenticode signature.' +} +if ($signature.SignerCertificate.Thumbprint -ne $Thumbprint) { + throw 'Installer signer does not match the configured release certificate.' +} +if ($null -eq $signature.TimeStamperCertificate) { + throw 'Installer has no verified signing timestamp.' +} diff --git a/apps/desktop/scripts/verify-retained-desktop.ts b/apps/desktop/scripts/verify-retained-desktop.ts new file mode 100644 index 0000000000..613580da9a --- /dev/null +++ b/apps/desktop/scripts/verify-retained-desktop.ts @@ -0,0 +1,44 @@ +/** Recheck distribution signatures on retained installers without signing credentials. */ +import { execFileSync } from 'node:child_process' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { DesktopRetainedManifest } from './desktop-release-store.ts' +import type { DesktopPublishConfig } from './desktop-publish-config.ts' +import { verifyMacOSDiskImage, verifyMacOSNotarizedApplication } from './verify-macos-signature.mjs' + +/** + * Verify Windows Authenticode or macOS DMG and archived app notarization on the original platform. + * @param directory Retained attempt whose file hashes were already checked. + * @param manifest Validated inventory and packaging mode. + * @param config Public expected signer configuration. + * @returns Resolves after platform verification; extracted ZIP contents are removed on all exits. + */ +export async function verifyRetainedDesktopSignatures( + directory: string, manifest: DesktopRetainedManifest, config: DesktopPublishConfig, +): Promise { + const { source } = manifest + const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/KEY|SECRET|TOKEN|PASSWORD/iu.test(key))) + const run = (command: string, args: string[]) => execFileSync(command, args, { env, encoding: 'utf8', timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }) + if (source.target === 'win-x64') { + if (process.platform !== 'win32' || source.qualification !== 'signed' || !config.windows) throw new Error('desktop publish: signed Windows package and signer configuration required on Windows') + const installer = manifest.files.find(file => file.name.endsWith('.exe')) + if (!installer) throw new Error('desktop publish: installer missing') + run('pwsh', ['-NoProfile', '-NonInteractive', '-File', join(import.meta.dirname, 'verify-published-windows.ps1'), + '-Installer', join(directory, installer.name), '-Thumbprint', config.windows.certificateThumbprint]) + return + } + if (process.platform !== 'darwin' || source.qualification !== 'notarized' || !config.macOS) throw new Error('desktop publish: notarized package and signer configuration required on macOS') + const dmg = manifest.files.find(file => file.name.endsWith('.dmg')) + const zip = manifest.files.find(file => file.name.endsWith('.zip')) + if (!dmg || !zip) throw new Error('desktop publish: DMG and ZIP are required') + verifyMacOSDiskImage(join(directory, dmg.name), config.macOS) + const zipPath = join(directory, zip.name) + const listing = run('/usr/bin/unzip', ['-Z1', zipPath]).trim().split('\n') + if (listing.some(name => name.startsWith('/') || name.includes('\\') || name.split('/').includes('..'))) throw new Error('desktop publish: unsafe ZIP path') + const extracted = await mkdtemp(join(tmpdir(), 'desktop-publish-verify-')) + try { + run('/usr/bin/ditto', ['-x', '-k', zipPath, extracted]) + verifyMacOSNotarizedApplication(join(extracted, 'DeepSeek Harness.app'), config.macOS) + } finally { await rm(extracted, { recursive: true, force: true }) } +} diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index b4b8153b7f..2afdfd7194 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -33,6 +33,7 @@ import { DESKTOP_IPC, SCHEME, assertDesktopSender, type DesktopUpdateState } fro import { readDeviceInfo } from './device-info.ts' import { desktopUpdateReadyConfirmation, formatDesktopMessage, resolveDesktopLocale, resolveDesktopStartupLocale } from './locale.ts' import { claimDesktopSingleInstance } from './single-instance.ts' +import { desktopUpdateChannel } from './update-channel.ts' import { DesktopUpdateCoordinator } from './update-coordinator.ts' import { DesktopCommandManager } from './command-management.ts' import { serveWebDocument, authenticateWebHost, forwardWebRequest } from './web-document.ts' @@ -51,6 +52,7 @@ import { DesktopMandatoryUpdatePolicy, resolveDesktopPolicyConfig, type DesktopP import { desktopClientMetadata, desktopClientVersion } from './client-metadata.ts' import { DesktopMandatoryUpdateWindow } from './mandatory-update-window.ts' import { DesktopPolicyTestAuth } from './policy-test-auth.ts' +import { readDesktopSettings } from './settings.ts' import { DesktopUpdateDialog, type UpdateDialogOptions } from './update-dialog.ts' import { readDesktopRuntime } from './runtime-tree.ts' import { DesktopBrowserGuests } from './browser-guests.ts' @@ -154,7 +156,7 @@ function runtimeResources(): RuntimeResources { const nodeBin = development ? join(app.getAppPath(), 'scripts', 'node-bin') : join(process.resourcesPath, 'runtime', 'bin') const pnpm = (development ? process.env.DSH_DESKTOP_PNPM_ENTRY : undefined) ?? (development ? join(app.getAppPath(), 'node_modules', 'pnpm', 'bin', 'pnpm.mjs') - : join(process.resourcesPath, 'runtime', 'pnpm', 'bin', 'pnpm.mjs')) + : join(process.resourcesPath, 'runtime', 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs')) const dsh = (development ? process.env.DSH_DESKTOP_DSH_DIR : undefined) ?? (development ? join(app.getAppPath(), '.desktop-build', 'development', 'project') : join(app.getAppPath(), 'dsh')) return { node, nodeBin, pnpm, dsh } @@ -313,6 +315,7 @@ function createWindow(preload: string, show = false, primary = false): BrowserWi } async function main(): Promise { + const desktopSettings = readDesktopSettings(app.getPath('userData')) void pruneCrashReports(app.getPath('logs')) const journalDirectory = process.env.DSH_DESKTOP_UPDATE_JOURNAL_DIR const updateJournal = journalDirectory === undefined ? undefined : new DesktopUpdateJournal(journalDirectory, app.getVersion()) @@ -581,6 +584,8 @@ async function main(): Promise { return startup } + const manifest: unknown = JSON.parse(await readFile(join(app.getAppPath(), 'package.json'), 'utf8')) + const updateChannel = desktopUpdateChannel(manifest) const updates = new DesktopUpdateCoordinator( publishUpdate, async () => { @@ -634,7 +639,7 @@ async function main(): Promise { }, undefined, undefined, undefined, (success, reason) => { void track('desktop_upgrade_download_result', { is_success: success, ...reason === undefined ? {} : { error_reason: reason } }) }, - + updateChannel, ) const updateSchedule = new DesktopUpdateSchedule(updates, resolveDesktopUpdateScheduleConfig(process.env)) @@ -707,14 +712,14 @@ async function main(): Promise { return browserGuests.release(event.sender, lease) }) - session.defaultSession.webRequest.onBeforeSendHeaders({ urls: ['ws://127.0.0.1/*'] }, (details, callback) => { + session.defaultSession.webRequest.onBeforeSendHeaders({ urls: ['ws://127.0.0.1/*', 'wss://127.0.0.1/*'] }, (details, callback) => { if (hostUrl === undefined || hostCookie === undefined || details.webContentsId !== mainWindow?.webContents.id) { callback({}) return } const target = new URL(hostUrl) const requested = new URL(details.url) - if (requested.host !== target.host) { callback({}); return } + if (requested.host !== target.host || requested.protocol !== (target.protocol === 'https:' ? 'wss:' : 'ws:')) { callback({}); return } const headers = Object.fromEntries(Object.entries(details.requestHeaders).map(([name, value]) => [name.toLowerCase(), value])) if (headers.origin !== 'dsh-app://app') { callback({ cancel: true }); return } callback({ requestHeaders: { ...headers, origin: target.origin, cookie: hostCookie, 'sec-fetch-site': 'same-origin' } }) @@ -875,6 +880,7 @@ async function main(): Promise { void authenticatePolicy().catch((error: unknown) => { console.error(error) }) } const queuePolicyAuthentication = (): void => { + if (!desktopSettings.updates.allowTestAuthPopupWindow) return if (authenticationOperation !== undefined) { policyAuth?.focus(); updateDialog.focus() return @@ -883,7 +889,8 @@ async function main(): Promise { flushQueuedPolicyAuthentication() } const runPolicyAuthentication = async () => { - if (policyAuth === undefined || mandatoryPolicy === undefined || quitting) return undefined + if (!desktopSettings.updates.allowTestAuthPopupWindow + || policyAuth === undefined || mandatoryPolicy === undefined || quitting) return undefined const parent = mandatoryUI?.confirmationWindow ?? currentDialogWindow() if (parent === undefined) return undefined const consent = await updateDialog.show(parent, { type: 'info', title: locale.messages.policyLoginTitle, @@ -905,7 +912,7 @@ async function main(): Promise { const checkPolicyManually = async (authentication: 'immediate' | 'deferred' = 'immediate') => { if (authenticationOperation !== undefined) return authenticatePolicy() const policy = await mandatoryPolicy?.check('manual', true) - if (policy?.error !== 'authentication-required') return policy + if (policy?.error !== 'authentication-required' || !desktopSettings.updates.allowTestAuthPopupWindow) return policy if (authentication === 'immediate') return authenticatePolicy() queuePolicyAuthentication() return policy @@ -1281,7 +1288,6 @@ async function main(): Promise { }) mainWindow = createMainWindow() - const manifest: unknown = JSON.parse(await readFile(join(app.getAppPath(), 'package.json'), 'utf8')) if (typeof manifest !== 'object' || manifest === null) throw new Error('desktop policy: invalid application manifest') const developmentPolicy = app.isPackaged ? undefined : process.env.DSH_DESKTOP_MANDATORY_UPDATE_CONFIG const policyInput: unknown = app.isPackaged @@ -1298,6 +1304,7 @@ async function main(): Promise { let wasBlocking = false mandatoryPolicy = new DesktopMandatoryUpdatePolicy(policyConfig, { platform: process.platform as 'win32' | 'darwin', arch: process.arch as 'x64' | 'arm64', + channel: updateChannel, bundledDshVersion: app.isPackaged ? readDesktopRuntime(resources.dsh).release.version : app.getVersion(), }, (state) => { if (state.error !== 'authentication-required') policyAuthenticationQueued = false diff --git a/apps/desktop/src/mandatory-update-policy.ts b/apps/desktop/src/mandatory-update-policy.ts index 27fd51bd44..92168a7ea3 100644 --- a/apps/desktop/src/mandatory-update-policy.ts +++ b/apps/desktop/src/mandatory-update-policy.ts @@ -8,6 +8,7 @@ export interface DesktopPolicyIdentity { readonly platform: 'win32' | 'darwin' readonly bundledDshVersion: string readonly arch: 'x64' | 'arm64' + readonly channel: 'nightly' | 'latest' } /** Validated deployment choices; test authentication is explicitly enabled, never inferred from a redirect. */ @@ -158,7 +159,7 @@ export class DesktopMandatoryUpdatePolicy { private requestHeaders(): Record { return { ...platformClientHeaders(this.identity.platform, this.client()), - 'x-client-arch': this.identity.arch, 'x-client-update-channel': 'nightly', + 'x-client-arch': this.identity.arch, 'x-client-update-channel': this.identity.channel, 'x-client-bundled-dsh-version': this.identity.bundledDshVersion, } } diff --git a/apps/desktop/src/settings.ts b/apps/desktop/src/settings.ts new file mode 100644 index 0000000000..a4bb67b3bd --- /dev/null +++ b/apps/desktop/src/settings.ts @@ -0,0 +1,57 @@ +/** + * Local Electron shell settings, loaded once per process independently of the Host. + * Ownership: .agents/notes/implemented/architecture/2026-10-08-desktop-shell-configuration.md. + */ +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' + +/** Resolved shell preferences; absent fields use the defaults without rewriting existing files. */ +export interface DesktopSettings { + readonly updates: { + readonly allowTestAuthPopupWindow: boolean + } +} + +function record(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** + * Read shell settings, creating the default document exclusively when missing. + * @param userData - Electron's userData directory, independent of DSH_HOME. + * @returns Validated settings, or defaults when reading, creating or validating fails; changes require a restart. + */ +export function readDesktopSettings(userData: string): DesktopSettings { + const directory = join(userData, 'desktop') + const path = join(directory, 'settings.json') + const defaults: DesktopSettings = { updates: { allowTestAuthPopupWindow: false } } + try { + let raw: string + try { raw = readFileSync(path, 'utf8') } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + mkdirSync(directory, { recursive: true, mode: 0o700 }) + try { writeFileSync(path, `${JSON.stringify(defaults, null, 2)}\n`, { flag: 'wx', mode: 0o600 }) } catch (error) { + // An existing document belongs to the user, including one created during initialization. + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error + } + raw = readFileSync(path, 'utf8') + } + const value: unknown = JSON.parse(raw) + if (!record(value) || (value.updates !== undefined && !record(value.updates))) { + throw new Error('expected a JSON object with an optional updates object') + } + const allow = value.updates?.allowTestAuthPopupWindow + if (allow !== undefined && typeof allow !== 'boolean') { + throw new Error('updates.allowTestAuthPopupWindow must be true or false') + } + return { updates: { allowTestAuthPopupWindow: allow ?? false } } + } catch (error) { + try { + console.warn(`desktop settings: ${path}: using defaults because settings could not be loaded`, error) + } catch (_logError) { + // Diagnostic output is best effort; its failure must not make optional settings fatal. + // TODO: Persist settings diagnostics when console output is unavailable, without blocking startup. + } + return defaults + } +} diff --git a/apps/desktop/src/update-channel.ts b/apps/desktop/src/update-channel.ts new file mode 100644 index 0000000000..ac767ea642 --- /dev/null +++ b/apps/desktop/src/update-channel.ts @@ -0,0 +1,17 @@ +/** Resolve the update channel sealed into the installed application manifest. */ + +/** Installer-owned channel, independent of release version and upload environment. */ +export type DesktopUpdateChannel = 'nightly' | 'latest' + +/** + * Read the packaged channel; older manifests retain their existing nightly behavior. + * @param manifest Parsed application manifest. + * @returns Validated channel. Invalid explicit values reject instead of changing feeds. + */ +export function desktopUpdateChannel(manifest: unknown): DesktopUpdateChannel { + if (typeof manifest !== 'object' || manifest === null) throw new Error('desktop update: invalid application manifest') + if (!('dshDesktopUpdateChannel' in manifest)) return 'nightly' + const channel = manifest.dshDesktopUpdateChannel + if (channel !== 'nightly' && channel !== 'latest') throw new Error('desktop update: invalid packaged channel') + return channel +} diff --git a/apps/desktop/src/update-coordinator.ts b/apps/desktop/src/update-coordinator.ts index 8d6eb808e7..3b83cea08f 100644 --- a/apps/desktop/src/update-coordinator.ts +++ b/apps/desktop/src/update-coordinator.ts @@ -45,6 +45,7 @@ export class DesktopUpdateCoordinator { * @param updater - Process-owned Electron updater, replaceable at the network/platform test boundary. * @param enabled - Whether this process has a packaged update source. * @param currentVersion - Actual installed application version. + * @param channel - Installed package channel; omitted test/local callers retain nightly. * @param downloadResult - Once per completed download attempt, including platform preparation failures. */ constructor( @@ -54,6 +55,7 @@ export class DesktopUpdateCoordinator { private readonly enabled: () => boolean = () => app.isPackaged && existsSync(join(process.resourcesPath, 'app-update.yml')), private readonly currentVersion: () => string = () => app.getVersion(), private readonly downloadResult?: (success: boolean, reason?: string) => void, + private readonly channel: 'nightly' | 'latest' = 'nightly', ) { if (updater === autoUpdater) { // electron-updater omits this internal transport property from its public declarations. @@ -66,8 +68,8 @@ export class DesktopUpdateCoordinator { } this.updater.autoDownload = false this.updater.autoInstallOnAppQuit = false - this.updater.channel = 'nightly' - this.updater.allowPrerelease = true + this.updater.channel = channel + this.updater.allowPrerelease = channel === 'nightly' // Selecting a channel can enable downgrade in electron-updater. this.updater.allowDowngrade = false this.updater.on('download-progress', this.onProgress) @@ -187,6 +189,7 @@ export class DesktopUpdateCoordinator { if (result === null) throw new Error('desktop update: no check result was returned') const version = result.updateInfo.version if (valid(version) === null) throw new Error('desktop update: feed version is invalid') + if (this.channel === 'latest' && version.includes('-')) throw new Error('desktop update: latest feed contains a prerelease') this.candidate = result.isUpdateAvailable && gt(version, this.currentVersion()) ? version : undefined return this.setState(this.candidate === undefined ? { phase: 'idle' } : { phase: 'available', version }) } catch (error) { diff --git a/apps/desktop/src/update-dialog.ts b/apps/desktop/src/update-dialog.ts index 249294f8ae..8f263ca38e 100644 --- a/apps/desktop/src/update-dialog.ts +++ b/apps/desktop/src/update-dialog.ts @@ -136,7 +136,11 @@ export class DesktopUpdateDialog { const window = this.window this.window = undefined this.parent = undefined - if (window !== undefined && !window.isDestroyed()) window.destroy() + if (window !== undefined && !window.isDestroyed()) { + // Release Windows modality before destruction so another application cannot become active. + if (process.platform === 'win32' && window.isVisible()) window.hide() + window.destroy() + } } private owned(event: IpcMainInvokeEvent): void { diff --git a/apps/desktop/tests/desktop-auto-update-environment.spec.ts b/apps/desktop/tests/desktop-auto-update-environment.spec.ts index c33a9384df..9fbe629c89 100644 --- a/apps/desktop/tests/desktop-auto-update-environment.spec.ts +++ b/apps/desktop/tests/desktop-auto-update-environment.spec.ts @@ -40,7 +40,7 @@ describe('desktop auto-update environment', () => { DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com/', DOWNLOAD_TEST_RELEASE_ID: RELEASE_ID, }, 'darwin', 'arm64')).toEqual({ - environment: 'test', + environment: 'test', channel: 'nightly', target: 'mac-arm64', origin: 'https://desktop-updates.example.com', publicUrl: `https://desktop-updates.example.com/dsh-desk/${RELEASE_ID}/feeds/mac-arm64/`, diff --git a/apps/desktop/tests/desktop-build-paths.spec.ts b/apps/desktop/tests/desktop-build-paths.spec.ts index a5e9faf296..ede5c5e3d3 100644 --- a/apps/desktop/tests/desktop-build-paths.spec.ts +++ b/apps/desktop/tests/desktop-build-paths.spec.ts @@ -16,6 +16,7 @@ describe('desktop build paths', () => { 'root', 'artifacts', 'unsignedArtifacts', + 'unnotarizedArtifacts', 'runtime', 'packageSet', 'dsh', diff --git a/apps/desktop/tests/desktop-build-version-discovery.spec.ts b/apps/desktop/tests/desktop-build-version-discovery.spec.ts index 8438e076ad..0fe063d1e2 100644 --- a/apps/desktop/tests/desktop-build-version-discovery.spec.ts +++ b/apps/desktop/tests/desktop-build-version-discovery.spec.ts @@ -71,6 +71,16 @@ describe('desktop build version discovery', () => { .resolves.toBe(`${PRERELEASE}.${DATE}.4`) }) + it('numbers after existing unnotarized DMG and ZIP artifacts', async () => { + const artifactsRoot = await artifactsWith([ + `deepseek-harness-${PRERELEASE}.${DATE}.2-mac-arm64-unnotarized.dmg`, + `deepseek-harness-${PRERELEASE}.${DATE}.4-mac-arm64-unnotarized.zip`, + `deepseek-harness-${PRERELEASE}.${DATE}.9-mac-arm64-unnotarized.zip.blockmap`, + ]) + await expect(suggestDesktopBuildVersion({ productVersion: PRERELEASE, target: 'mac-arm64', environment: {}, date: DATE, artifactsRoot })) + .resolves.toBe(`${PRERELEASE}.${DATE}.5`) + }) + it('counts unsigned Windows artifacts written under their own suffix', async () => { const artifactsRoot = await artifactsWith([ `deepseek-harness-${PRERELEASE}.${DATE}.2-win-x64-unsigned.exe`, diff --git a/apps/desktop/tests/desktop-cli.spec.ts b/apps/desktop/tests/desktop-cli.spec.ts new file mode 100644 index 0000000000..e358df8657 --- /dev/null +++ b/apps/desktop/tests/desktop-cli.spec.ts @@ -0,0 +1,37 @@ +/** The installed CLI uses the shared pnpm distribution with Electron's package-operation environment. */ + +import { delimiter, join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { runCli } from '@deepseek-ai/dsh/lib/bin.js' +import { runDesktopCli } from '../../desktop-host/src/cli.ts' +import { installOfficeEngineResolution } from '../../desktop-host/src/office-engine.ts' + +vi.mock('@deepseek-ai/dsh/lib/bin.js', () => ({ runCli: vi.fn() })) +vi.mock('../../desktop-host/src/office-engine.ts', () => ({ installOfficeEngineResolution: vi.fn() })) + +afterEach(() => { + vi.unstubAllEnvs() + vi.clearAllMocks() +}) + +it.each(['system-bin', undefined])('dispatches with bundled pnpm when PATH is %s', async (path) => { + vi.stubEnv('PATH', path) + const runtime = join('Application 中文 with spaces', 'resources', 'app.asar', 'dsh') + const support = join('Application 中文 with spaces', 'resources', 'runtime') + + await runDesktopCli(runtime, support) + + expect(installOfficeEngineResolution).toHaveBeenCalledExactlyOnceWith(runtime) + expect(runCli).toHaveBeenCalledExactlyOnceWith({ + manageDesktopProfile: true, + packageManager: { + command: process.execPath, + args: ['--expose-internals', join(support, 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs')], + env: { + ELECTRON_RUN_AS_NODE: '1', + DSH_DESKTOP_NODE_EXECUTABLE: process.execPath, + PATH: `${join(support, 'bin')}${delimiter}${path ?? ''}`, + }, + }, + }) +}) diff --git a/apps/desktop/tests/desktop-package-environment.spec.ts b/apps/desktop/tests/desktop-package-environment.spec.ts index a892a8548a..1c3eb02fc0 100644 --- a/apps/desktop/tests/desktop-package-environment.spec.ts +++ b/apps/desktop/tests/desktop-package-environment.spec.ts @@ -229,3 +229,27 @@ it('owns macOS tuning in the local file and validates it before signing credenti expect(() =>{ validateDesktopPackageEnvironment({ ...RELEASE, DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: 'socks5://localhost:8080' }, MACOS) }).toThrow('NOTARIZATION_PROXY') }) }) + +it('rejects an explicit invalid macOS cache before signing while leaving unsigned builds independent', () => { + const environment = { ...RELEASE, DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR: '' } + for (const options of [{}, { prepareOnly: true }]) { + expect(() => { validateDesktopPackageEnvironment(environment, MACOS, options) }).toThrow('SIGNATURE_CACHE_DIR') + } + expect(() => { validateDesktopPackageEnvironment(environment, MACOS, { unsigned: true }) }).not.toThrow() +}) + +it('skips Apple credentials but still requires signing credentials for unnotarized packages', async () => { + await withDirectory(async (directory) => { + const certificate = join(directory, 'signing.p12') + await writeFile(certificate, 'fixture') + const environment = { ...RELEASE, ...MAC_IDENTITY, CSC_LINK: certificate, CSC_KEY_PASSWORD: '' } + expect(() => { validateDesktopPackageEnvironment(environment, MACOS, { skipNotarization: true }) }).not.toThrow() + expect(() => { validateDesktopPackageEnvironment(environment, MACOS) }).toThrow() + expect(() => { + validateDesktopPackageEnvironment({ ...environment, CSC_LINK: undefined }, MACOS, { skipNotarization: true }) + }).toThrow(/CSC_LINK/u) + expect(() => { + validateDesktopPackageEnvironment({ ...environment, CSC_KEY_PASSWORD: undefined }, MACOS, { skipNotarization: true }) + }).toThrow(/CSC_KEY_PASSWORD/u) + }) +}) diff --git a/apps/desktop/tests/desktop-publication-failure.spec.ts b/apps/desktop/tests/desktop-publication-failure.spec.ts new file mode 100644 index 0000000000..f19e1f76b5 --- /dev/null +++ b/apps/desktop/tests/desktop-publication-failure.spec.ts @@ -0,0 +1,36 @@ +import { spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { expect, it } from 'vitest' +import { z } from 'zod' +import { desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts' +import { DesktopPublishError } from '../scripts/desktop-publish.ts' + +it('preserves actionable validation and filesystem diagnostics', () => { + expect(desktopPublicationFailure(new DesktopPublishError('conflict', 'desktop publish: object differs: bin/app.exe'), 'upload')) + .toMatchObject({ code: 'conflict', message: 'desktop publish: object differs: bin/app.exe' }) + expect(desktopPublicationFailure(new Error('Usage: rollback-desktop-channel.ts --record '), 'arguments').message).toContain('Usage:') + expect(desktopPublicationFailure(Object.assign(new Error('raw'), { code: 'ENOENT', path: '/fixture/config.json' }), 'config').message) + .toContain('/fixture/config.json') +}) + +it('does not retain provider bodies, unknown messages, JSON input or invalid field contents', () => { + const result = z.object({ preset: z.enum(['test', 'production']) }).safeParse({ preset: 'fixture-secret' }) + if (result.success) throw new Error('fixture must reject') + for (const error of [result.error, new SyntaxError('fixture-secret'), new Error('fixture-secret'), + { code: 'AccessDenied', statusCode: 403, body: 'fixture-secret', message: 'fixture-secret' }]) { + expect(JSON.stringify(desktopPublicationFailure(error, 'fixture'))).not.toContain('fixture-secret') + } + expect(desktopPublicationFailure(result.error, 'config').message).toContain('preset') + expect(desktopPublicationFailure({ code: 'AccessDenied', statusCode: 403 }, 'upload').message).toContain('HTTP 403') +}) + +it('prints rollback usage through the real CLI before any audit or remote operation', () => { + const result = spawnSync(process.execPath, ['--import', 'tsx/esm', + fileURLToPath(new URL('../scripts/rollback-desktop-channel.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000 }) + expect(result.error).toBeUndefined() + expect(result.signal).toBeNull() + expect(result.status).toBe(1) + const diagnostic = z.object({ code: z.string(), message: z.string() }).parse(JSON.parse(result.stderr)) + expect(diagnostic.code).toBe('validation') + expect(diagnostic.message).toContain('Usage: rollback-desktop-channel.ts') +}) diff --git a/apps/desktop/tests/desktop-publication-preflight.spec.ts b/apps/desktop/tests/desktop-publication-preflight.spec.ts new file mode 100644 index 0000000000..bf4d4e8876 --- /dev/null +++ b/apps/desktop/tests/desktop-publication-preflight.spec.ts @@ -0,0 +1,60 @@ +import { createHash } from 'node:crypto' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { retainDesktopCi } from '../scripts/retain-desktop-ci.ts' +import { prepareDesktopPublication } from '../scripts/publish-desktop-ci.ts' + +it.each(['mac-arm64', 'win-x64'] as const)('preflights a complete retained %s build without credentials or source checkout manifests', async (target) => { + const root = await mkdtemp(join(tmpdir(), 'desktop-preflight-')) + try { + const app = join(root, 'app') + const configRoot = join(root, 'packaging') + const artifacts = join(app, '.desktop-build/targets', target, 'artifacts') + await mkdir(artifacts, { recursive: true }) + await mkdir(join(configRoot, 'presets'), { recursive: true }) + await mkdir(join(configRoot, 'publishing')) + await writeFile(join(app, 'package.json'), JSON.stringify({ version: '1.0.0' })) + const releaseId = 'a'.repeat(32) + await writeFile(join(configRoot, 'presets/test.env'), `DSH_DESKTOP_AUTO_UPDATE_ENV=test\nDOWNLOAD_TEST_RELEASE_ID=${releaseId}\n`) + await writeFile(join(configRoot, 'publishing/test.json'), JSON.stringify({ + bucket: 'fixture-1250000000', origin: 'https://example.com', credentialsFile: join(root, 'absent-credentials.json'), + })) + const commit = 'b'.repeat(40) + const base = `deepseek-harness-1.0.0-${target}` + const extension = target === 'win-x64' ? 'exe' : 'zip' + const bytes = 'fixture installer bytes' + await writeFile(join(artifacts, `${base}.${extension}`), bytes) + await writeFile(join(artifacts, `${base}.${extension}.blockmap`), 'fixture blockmap') + if (target !== 'win-x64') await writeFile(join(artifacts, `${base}.dmg`), 'fixture DMG') + await writeFile(join(artifacts, `${target}-release.json`), JSON.stringify({ + schemaVersion: 1, target, environment: 'test', version: '1.0.0', commit, dirty: false, + publicUrl: `https://example.com/dsh-desk/${releaseId}/feeds/${target}/`, + })) + await writeFile(join(artifacts, target === 'win-x64' ? 'nightly.yml' : 'nightly-mac.yml'), JSON.stringify({ + version: '1.0.0', files: [{ url: `${base}.${extension}`, size: Buffer.byteLength(bytes), + sha512: createHash('sha512').update(bytes).digest('base64') }], + })) + const env = { + DSH_PACKAGING_CONFIG_DIR: configRoot, DSH_PACKAGING_PRESET: 'test', + DSH_DESKTOP_TARGET_PLATFORM: target === 'win-x64' ? 'win32' : 'darwin', DSH_DESKTOP_TARGET_ARCH: target === 'win-x64' ? 'x64' : 'arm64', + PACKAGE_SOURCE_REF: 'master', PACKAGE_SOURCE_SHA: 'b'.repeat(40), PACKAGE_VERSION: '1.0.0', PACKAGE_PUBLISH: 'true', PACKAGE_SIGNING: 'signed', PACKAGE_SKIP_NOTARIZATION: 'false', + GITHUB_RUN_ID: '10', GITHUB_RUN_ATTEMPT: '2', GITHUB_REPOSITORY: 'owner/repo', GITHUB_SHA: commit, RUNNER_NAME: 'fixture-runner', + DESKTOP_PUBLISH_ROUTE: JSON.stringify({ sourceRef: 'master', channel: 'nightly', runId: '10', attempt: '2', commit, runnerName: 'fixture-runner', target, preset: 'test' }), + } + const retained = await retainDesktopCi(env, app) + await rm(app, { recursive: true }) + let signatureChecks = 0 + const signature = async () => { signatureChecks++ } + const prepared = await prepareDesktopPublication(env, signature) + expect(prepared.plan.version).toBe('1.0.0') + expect(prepared.plan.artifacts.every(file => file.path.startsWith(retained))).toBe(true) + expect(signatureChecks).toBe(1) + await expect(prepareDesktopPublication({ ...env, DESKTOP_APPROVED_PACKAGE: 'wrong' }, signature)).rejects.toThrow(/changed after approval/u) + await expect(prepareDesktopPublication({ ...env, RUNNER_NAME: 'other-machine' }, signature)).rejects.toThrow(/different machine/u) + await writeFile(join(retained, `${base}.${extension}`), 'changed') + await expect(prepareDesktopPublication(env, signature)).rejects.toThrow(/changed file/u) + expect(signatureChecks).toBe(2) + } finally { await rm(root, { recursive: true, force: true }) } +}) diff --git a/apps/desktop/tests/desktop-publish-config.spec.ts b/apps/desktop/tests/desktop-publish-config.spec.ts new file mode 100644 index 0000000000..9577581d82 --- /dev/null +++ b/apps/desktop/tests/desktop-publish-config.spec.ts @@ -0,0 +1,47 @@ +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 { readDesktopPublishConfig, readDesktopUploadCredentials } from '../scripts/desktop-publish-config.ts' + +it('reads public settings without opening the absent credential file and requires production App settings', async () => { + const root = await mkdtemp(join(tmpdir(), 'publish-config-')) + try { + await mkdir(join(root, 'publishing')) + const config = { bucket: 'test-1250000000', origin: 'https://example.com', credentialsFile: join(root, 'absent.json') } + await writeFile(join(root, 'publishing/test.json'), JSON.stringify(config)) + const selected = await readDesktopPublishConfig(root, 'test') + expect(selected).toEqual(config) + await expect(readDesktopUploadCredentials(selected)).rejects.toThrow(/cannot read valid upload credentials/u) + await writeFile(join(root, 'publishing/production.json'), JSON.stringify({ ...config, origin: 'https://download.deepseek.com' })) + await expect(readDesktopPublishConfig(root, 'production')).rejects.toThrow(/GitHub App configuration/u) + await writeFile(config.credentialsFile, JSON.stringify({ secretId: 'fixture', secretKey: 'fixture-only' })) + await expect(readDesktopUploadCredentials(selected)).resolves.toEqual({ secretId: 'fixture', secretKey: 'fixture-only' }) + } finally { await rm(root, { recursive: true, force: true }) } +}) + +it('does not include malformed credential contents in errors', async () => { + const root = await mkdtemp(join(tmpdir(), 'publish-config-')) + try { + const credentialsFile = join(root, 'credentials.json') + await writeFile(credentialsFile, '{secret-value-should-not-appear') + await expect(readDesktopUploadCredentials({ credentialsFile, bucket: 'test-1', origin: 'https://example.com' })) + .rejects.not.toThrow(/secret-value/u) + } finally { await rm(root, { recursive: true, force: true }) } +}) + +it('rejects multiline App outputs before writing Actions output fields', async () => { + const root = await mkdtemp(join(tmpdir(), 'publish-config-')) + try { + await mkdir(join(root, 'publishing')) + const config = { bucket: 'test-1', origin: 'https://download.deepseek.com', credentialsFile: join(root, 'absent.json'), + githubApp: { clientId: 'app-id', privateKeyFile: join(root, 'key.pem') } } + for (const githubApp of [ + { ...config.githubApp, clientId: 'app-id\nother=value' }, + { ...config.githubApp, privateKeyFile: join(root, 'key\nother=value') }, + ]) { + await writeFile(join(root, 'publishing/production.json'), JSON.stringify({ ...config, githubApp })) + await expect(readDesktopPublishConfig(root, 'production')).rejects.toThrow(/single-line/u) + } + } finally { await rm(root, { recursive: true, force: true }) } +}) diff --git a/apps/desktop/tests/desktop-publish-cos.spec.ts b/apps/desktop/tests/desktop-publish-cos.spec.ts new file mode 100644 index 0000000000..848e37f71c --- /dev/null +++ b/apps/desktop/tests/desktop-publish-cos.spec.ts @@ -0,0 +1,56 @@ +import { expect, it } from 'vitest' +import { createDesktopCos } from '../scripts/desktop-cos.ts' +import { desktopPublishCos } from '../scripts/desktop-publish-cos.ts' +import { desktopArtifactDigest } from '../scripts/desktop-publish.ts' +import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' +import { answer, cosError, startCosLoopback } from './cos-loopback.ts' + +it('uses overwrite prevention, streams verified bytes, and hashes remote readback through the SDK', async () => { + const objects = new Map() + const server = await startCosLoopback((request, response) => { + if (request.path.includes('versioning')) { answer(response, 200, ''); return } + if (request.method === 'PUT') { + expect(request.headers['x-cos-forbid-overwrite']).toBe('true') + objects.set(request.path, request.body) + answer(response) + } else { + const bytes = objects.get(request.path) + if (bytes === undefined) answer(response, 404, cosError('NoSuchKey')) + else answer(response, 200, bytes) + } + }) + try { + const artifact = { path: '', filename: 'file.exe', key: 'bin/file.exe', contents: 'fixture bytes', contentType: 'application/octet-stream', channelMetadata: false } + const plan: DesktopUploadPlan = { + environment: 'test', target: 'win-x64', version: '1.0.0', bucket: 'fixture-1250000000', publicUrl: 'https://example.com/', + secretIdEnvName: 'ID', secretKeyEnvName: 'KEY', artifacts: [artifact], + } + const transport = desktopPublishCos(plan, { secretId: 'fixture-id', secretKey: 'fixture-secret' }, (credentials) => { + const client = createDesktopCos(credentials) + server.redirect(client) + return client + }) + expect(await transport.read(artifact.key, false)).toBeNull() + const digest = await desktopArtifactDigest(artifact) + await transport.put(artifact, digest, true) + expect(await transport.read(artifact.key, false)).toEqual(digest) + await expect(transport.read('elsewhere/file.exe', false)).rejects.toThrow(/outside/u) + expect(server.requests.filter(request => request.method === 'PUT')).toHaveLength(1) + } finally { await server.close() } +}) + +it('propagates an oversized channel stream error through the SDK and closes the request', async () => { + const server = await startCosLoopback((_request, response) => { answer(response, 200, Buffer.alloc(1024 * 1024 + 1, 65)) }) + try { + const artifact = { path: '', filename: 'nightly.yml', key: 'feed/nightly.yml', contents: 'version: 1.0.0\n', contentType: 'application/yaml', channelMetadata: true } + const plan: DesktopUploadPlan = { environment: 'test', target: 'win-x64', version: '1.0.0', bucket: 'fixture-1250000000', + publicUrl: 'https://example.com/', secretIdEnvName: 'ID', secretKeyEnvName: 'KEY', artifacts: [artifact] } + const transport = desktopPublishCos(plan, { secretId: 'fixture-id', secretKey: 'fixture-secret' }, (credentials) => { + const client = createDesktopCos(credentials) + server.redirect(client) + return client + }) + await expect(transport.read(artifact.key, true)).rejects.toThrow(/exceeds 1 MiB/u) + expect(server.requests).toHaveLength(1) + } finally { await server.close() } +}) diff --git a/apps/desktop/tests/desktop-publish-record.spec.ts b/apps/desktop/tests/desktop-publish-record.spec.ts new file mode 100644 index 0000000000..87646edbe1 --- /dev/null +++ b/apps/desktop/tests/desktop-publish-record.spec.ts @@ -0,0 +1,80 @@ +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { execFile } from 'node:child_process' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { promisify } from 'node:util' +import { expect, it } from 'vitest' +import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from '../scripts/desktop-publish-record.ts' + +it('excludes another process while a channel lock is held and admits it after release', async () => { + const root = await mkdtemp(join(tmpdir(), 'desktop-process-lock-')) + const script = ` + const { withDesktopChannelLock } = await import(process.argv[1]); + try { + await withDesktopChannelLock(process.argv[2], 'bucket/mac', async () => process.stdout.write('acquired')); + } catch (error) { + if (!error.message.includes('locked')) throw error; + process.stdout.write('locked'); + } + ` + const contender = () => promisify(execFile)(process.execPath, ['--import', 'tsx/esm', '--input-type=module', '-e', script, + new URL('../scripts/desktop-publish-record.ts', import.meta.url).href, root], { encoding: 'utf8' }) + try { + await withDesktopChannelLock(root, 'bucket/mac', async () => { + expect((await contender()).stdout).toBe('locked') + }) + expect((await contender()).stdout).toBe('acquired') + } finally { await rm(root, { recursive: true, force: true }) } +}) + +it('excludes overlapping writers of one channel but permits independent channels and releases after failure', async () => { + const root = await mkdtemp(join(tmpdir(), 'desktop-lock-')) + try { + await withDesktopChannelLock(root, 'bucket/mac', async () => { + await expect(withDesktopChannelLock(root, 'bucket/mac', async () => {})).rejects.toThrow(/locked/u) + await expect(withDesktopChannelLock(root, 'bucket/win', async () => 'independent')).resolves.toBe('independent') + }) + await expect(withDesktopChannelLock(root, 'bucket/mac', async () => { throw new Error('fixture') })).rejects.toThrow('fixture') + await expect(withDesktopChannelLock(root, 'bucket/mac', async () => 'recovered')).resolves.toBe('recovered') + } finally { await rm(root, { recursive: true, force: true }) } +}) + +it('persists intent, before/after bytes and terminal state outside the checkout', async () => { + const root = await mkdtemp(join(tmpdir(), 'desktop-audit-')) + try { + const record = await createDesktopPublicationRecord(root, { repository: 'owner/repo', runId: '1', attempt: '2', + actor: 'operator', destination: 'bucket/feed/mac', operation: 'rollback', reason: 'restore previous release' }) + await record.record({ type: 'put-intent', key: 'feed/mac/nightly.yml', before: 'version: 2.0.0', after: 'version: 1.0.0' }) + await record.finish('complete') + expect(JSON.parse(await readFile(join(record.directory, 'operation.json'), 'utf8'))).toMatchObject({ actor: 'operator', operation: 'rollback' }) + expect(JSON.parse((await readFile(join(record.directory, 'events.jsonl'), 'utf8')).trim())).toMatchObject({ before: 'version: 2.0.0', after: 'version: 1.0.0' }) + expect(JSON.parse(await readFile(join(record.directory, 'result.json'), 'utf8'))).toMatchObject({ status: 'complete' }) + } finally { await rm(root, { recursive: true, force: true }) } +}) + +it('recognizes feed completion even when the later tag failed', async () => { + const root = await mkdtemp(join(tmpdir(), 'desktop-recovery-')) + try { + const identity = { repository: 'owner/repo', runId: '12', attempt: '2', destination: 'bucket/mac' } + const journal = await createDesktopPublicationRecord(root, { ...identity, actor: 'operator', operation: 'publish', reason: 'publish' }) + expect(await wasDesktopAttemptPublished(root, identity)).toBe(false) + await journal.record({ type: 'feeds-complete' }) + await journal.record({ type: 'tag-pending' }) + await journal.finish('published-tag-pending') + expect(await wasDesktopAttemptPublished(root, identity)).toBe(true) + expect(await wasDesktopAttemptPublished(root, { ...identity, attempt: '1' })).toBe(false) + } finally { await rm(root, { recursive: true, force: true }) } +}) + +it('ignores interrupted initialization before an audit directory becomes visible', async () => { + const root = await mkdtemp(join(tmpdir(), 'desktop-init-')) + try { + await mkdir(join(root, '.initializing-interrupted')) + await writeFile(join(root, '.initializing-interrupted/operation.json'), '{') + const identity = { repository: 'owner/repo', runId: '1', attempt: '1', destination: 'bucket/mac' } + expect(await wasDesktopAttemptPublished(root, identity)).toBe(false) + const record = await createDesktopPublicationRecord(root, { ...identity, actor: 'fixture', operation: 'publish', reason: 'fixture' }) + await record.record({ type: 'feeds-complete' }) + expect(await wasDesktopAttemptPublished(root, identity)).toBe(true) + } finally { await rm(root, { recursive: true, force: true }) } +}) diff --git a/apps/desktop/tests/desktop-publish-route.spec.ts b/apps/desktop/tests/desktop-publish-route.spec.ts new file mode 100644 index 0000000000..0db2cb45d6 --- /dev/null +++ b/apps/desktop/tests/desktop-publish-route.spec.ts @@ -0,0 +1,47 @@ +import { expect, it } from 'vitest' +import { resolveDesktopPublishRoute } from '../scripts/desktop-publish-route.ts' + +function fixture() { + const run = { id: 42, run_attempt: 2, head_sha: 'a'.repeat(40), path: '.github/workflows/macos-package.yml', + conclusion: 'success', event: 'workflow_dispatch', repository: { full_name: 'owner/repo' } } + const source = { repository: 'owner/repo', runId: '42', attempt: '2', commit: run.head_sha, runnerName: 'mini', + workflowCommit: run.head_sha, sourceRef: 'master', channel: 'nightly', + target: 'mac-arm64', preset: 'test', publishRequested: true, qualification: 'notarized' } + const jobs = [{ runner_name: 'mini', conclusion: 'success', labels: ['self-hosted', 'dsh-mini'] }] + const routes = { mini: { label: 'dsh-mini', target: 'mac-arm64' } } + return { run, source, jobs, routes } +} + +it('routes the exact successful attempt to its registered machine', () => { + const f = fixture() + expect(resolveDesktopPublishRoute('owner/repo', f.run, { source: f.source }, f.jobs, f.routes)) + .toMatchObject({ runId: '42', attempt: '2', runnerLabel: 'dsh-mini', preset: 'test' }) +}) + +it.each(['attempt', 'repository', 'commit', 'mode', 'request', 'runner', 'workflow'] as const)('rejects mismatched %s evidence', (field) => { + const f = fixture() + if (field === 'attempt') f.source.attempt = '1' + if (field === 'repository') f.source.repository = 'other/repo' + if (field === 'commit') f.source.workflowCommit = 'b'.repeat(40) + if (field === 'mode') f.source.qualification = 'unnotarized' + if (field === 'request') f.source.publishRequested = false + if (field === 'runner') f.jobs[0]!.runner_name = 'laptop' + if (field === 'workflow') f.run.path = '.github/workflows/ci.yml' + expect(() => resolveDesktopPublishRoute('owner/repo', f.run, { source: f.source }, f.jobs, f.routes)).toThrow() +}) + +it('fails closed when a publishing route or its unique label is missing', () => { + const f = fixture() + expect(() => resolveDesktopPublishRoute('owner/repo', f.run, { source: f.source }, f.jobs, {})).toThrow(/no configured/u) + const duplicates = { ...f.routes, laptop: { label: 'dsh-mini', target: 'mac-arm64' } } + expect(() => resolveDesktopPublishRoute('owner/repo', f.run, { source: f.source }, f.jobs, duplicates)).toThrow(/unique runner label/u) +}) + + +it('keeps the artifact source separate from the workflow commit', () => { + const f = fixture() + f.source.commit = 'b'.repeat(40) + f.source.sourceRef = 'dsh-v1.0.0' + expect(resolveDesktopPublishRoute('owner/repo', f.run, { source: f.source }, f.jobs, f.routes)) + .toMatchObject({ commit: 'b'.repeat(40), sourceRef: 'dsh-v1.0.0', channel: 'nightly' }) +}) diff --git a/apps/desktop/tests/desktop-publish-tag.spec.ts b/apps/desktop/tests/desktop-publish-tag.spec.ts new file mode 100644 index 0000000000..7a13daba54 --- /dev/null +++ b/apps/desktop/tests/desktop-publish-tag.spec.ts @@ -0,0 +1,59 @@ +import { expect, it } from 'vitest' +import { publishDesktopTag } from '../scripts/desktop-publish-tag.ts' + +const commit = 'a'.repeat(40) +const tag = (sha = commit) => ({ object: { type: 'commit', sha } }) +function transport(replies: Array<{ status: number; body?: object }>) { + const calls: Array<{ url: string; init: RequestInit | undefined }> = [] + const request: typeof fetch = async (url, init) => { + calls.push({ url: typeof url === 'string' ? url : url instanceof URL ? url.href : url.url, init }) + const reply = replies.shift() + if (!reply) throw new Error('unexpected HTTP request') + return new Response(JSON.stringify(reply.body ?? {}), { status: reply.status }) + } + return { calls, request } +} + +it('tags the packaged commit using explicit App authentication', async () => { + const http = transport([{ status: 404 }, { status: 201, body: tag() }]) + await expect(publishDesktopTag('owner/repo', '1.2.3', commit, 'fixture-token', http.request)).resolves.toBe('created') + expect(http.calls[1]?.init?.body).toBe(JSON.stringify({ ref: 'refs/tags/desktop-v1.2.3', sha: commit })) + expect(http.calls[1]?.init?.headers).toMatchObject({ Authorization: 'Bearer fixture-token' }) +}) + +it('does not write when the same release tag already exists', async () => { + const http = transport([{ status: 200, body: tag() }]) + await expect(publishDesktopTag('owner/repo', '1.2.3', commit, 'fixture-token', http.request)).resolves.toBe('present') + expect(http.calls).toHaveLength(1) +}) + +it('rejects a conflicting tag without updating or deleting it', async () => { + const http = transport([{ status: 200, body: tag('b'.repeat(40)) }]) + await expect(publishDesktopTag('owner/repo', '1.2.3', commit, 'fixture-token', http.request)).rejects.toThrow(/refusing to move/u) + expect(http.calls).toHaveLength(1) +}) + +it('reconciles a create race between two platform releases', async () => { + const http = transport([{ status: 404 }, { status: 422 }, { status: 200, body: tag() }]) + await expect(publishDesktopTag('owner/repo', '1.2.3', commit, 'fixture-token', http.request)).resolves.toBe('present') + expect(http.calls.map(call => call.init?.method ?? 'GET')).toEqual(['GET', 'POST', 'GET']) +}) + +it('does not reinterpret authorization failure as a missing tag', async () => { + const http = transport([{ status: 403 }]) + await expect(publishDesktopTag('owner/repo', '1.2.3', commit, 'fixture-token', http.request)).rejects.toThrow(/HTTP 403/u) + expect(http.calls).toHaveLength(1) +}) + +it('rejects missing credentials and malformed inputs before any request', async () => { + const http = transport([]) + await expect(publishDesktopTag('owner/repo', '1.2.3', commit, '', http.request)).rejects.toThrow(/required/u) + await expect(publishDesktopTag('owner/repo/other', '1.2.3', commit, 'fixture', http.request)).rejects.toThrow(/invalid/u) + expect(http.calls).toHaveLength(0) +}) + +it('explains an existing annotated tag without replacing it', async () => { + const http = transport([{ status: 200, body: { object: { type: 'tag', sha: commit } } }]) + await expect(publishDesktopTag('owner/repo', '1.2.3', commit, 'fixture-token', http.request)).rejects.toThrow(/not a lightweight commit tag/u) + expect(http.calls).toHaveLength(1) +}) diff --git a/apps/desktop/tests/desktop-publish.spec.ts b/apps/desktop/tests/desktop-publish.spec.ts new file mode 100644 index 0000000000..bc5cba2166 --- /dev/null +++ b/apps/desktop/tests/desktop-publish.spec.ts @@ -0,0 +1,114 @@ +import { createHash } from 'node:crypto' +import { expect, it } from 'vitest' +import { publishDesktopRelease, type DesktopPublishEvent, type DesktopPublishOperations, type DesktopRemoteObject } from '../scripts/desktop-publish.ts' +import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' + +function observed(contents: string): DesktopRemoteObject { + return { contents, size: Buffer.byteLength(contents), sha512: createHash('sha512').update(contents).digest('base64') } +} +function fixture(environment: 'test' | 'production' = 'test') { + const objects = new Map() + const writes: string[] = [] + const events: DesktopPublishEvent[] = [] + let tags = 0 + const plan: DesktopUploadPlan = { + environment, target: 'win-x64', version: '1.0.0', bucket: 'fixture', publicUrl: 'https://example.com/feed/', + secretIdEnvName: 'ID', secretKeyEnvName: 'KEY', commit: 'a'.repeat(40), dirty: false, + artifacts: [ + { path: '', filename: 'installer.exe', key: 'bin/installer.exe', contentType: 'application/octet-stream', channelMetadata: false, contents: 'installer' }, + { path: '', filename: 'installer.blockmap', key: 'bin/installer.blockmap', contentType: 'application/octet-stream', channelMetadata: false, contents: 'blockmap' }, + { path: '', filename: 'nightly.yml', key: 'feed/nightly.yml', contentType: 'application/yaml', channelMetadata: true, contents: 'version: 1.0.0\n' }, + ], + } + const operations: DesktopPublishOperations = { + transport: { + async read(key) { return objects.get(key) ?? null }, + async put(artifact, _digest, forbidOverwrite) { + if (forbidOverwrite && objects.has(artifact.key)) throw new Error('already exists') + writes.push(artifact.key) + objects.set(artifact.key, observed(artifact.contents!)) + }, + }, + async record(event) { events.push(event) }, + async tag() { tags++ }, + } + return { plan, operations, objects, writes, events, tags: () => tags } +} + +it('uploads files before the feed and skips identical bytes on a repeat invocation', async () => { + const f = fixture() + await expect(publishDesktopRelease(f.plan, f.operations)).resolves.toEqual({ status: 'complete' }) + expect(f.writes).toEqual(['bin/installer.exe', 'bin/installer.blockmap', 'feed/nightly.yml']) + await publishDesktopRelease(f.plan, f.operations) + expect(f.writes).toHaveLength(3) + expect(f.tags()).toBe(0) + expect(f.events.find(event => event.key === 'feed/nightly.yml' && event.type === 'put-intent')) + .toMatchObject({ before: null, after: 'version: 1.0.0\n' }) +}) + +it('recovers an ambiguous binary write without repeating it or publishing the feed early', async () => { + const f = fixture() + const put = f.operations.transport.put.bind(f.operations.transport) + let fail = true + f.operations.transport.put = async (...args) => { + await put(...args) + if (fail) { fail = false; throw new Error('connection lost after server stored bytes') } + } + await expect(publishDesktopRelease(f.plan, f.operations)).rejects.toThrow(/connection lost/u) + expect(f.objects.has('feed/nightly.yml')).toBe(false) + await publishDesktopRelease(f.plan, f.operations) + expect(f.writes).toEqual(['bin/installer.exe', 'bin/installer.blockmap', 'feed/nightly.yml']) +}) + +it('reports published but tag pending and retries only the tag', async () => { + const f = fixture('production') + let fail = true + const tag = f.operations.tag.bind(f.operations) + f.operations.tag = async () => { if (fail) throw new Error('GitHub unavailable'); await tag() } + await expect(publishDesktopRelease(f.plan, f.operations)).resolves.toMatchObject({ status: 'published-tag-pending' }) + expect(f.events.at(-1)?.type).toBe('tag-pending') + fail = false + await expect(publishDesktopRelease(f.plan, f.operations)).resolves.toEqual({ status: 'complete' }) + expect(f.writes).toHaveLength(3) + expect(f.tags()).toBe(1) +}) + +it.each(['binary', 'same-version-feed', 'newer-feed'] as const)('stops on %s conflict', async (kind) => { + const f = fixture() + if (kind === 'binary') f.objects.set('bin/installer.exe', observed('different')) + else f.objects.set('feed/nightly.yml', observed(kind === 'newer-feed' ? 'version: 2.0.0\n' : 'version: 1.0.0\nchanged: true\n')) + await expect(publishDesktopRelease(f.plan, f.operations)).rejects.toMatchObject({ code: kind === 'newer-feed' ? 'superseded' : 'conflict' }) + expect(f.writes).toHaveLength(0) +}) + +it('rejects a files-only plan and a production build without clean commit evidence', async () => { + const f = fixture('production') + await expect(publishDesktopRelease({ ...f.plan, artifacts: f.plan.artifacts.slice(0, 2) }, f.operations)).rejects.toMatchObject({ code: 'invalid-plan' }) + await expect(publishDesktopRelease({ ...f.plan, dirty: true }, f.operations)).rejects.toMatchObject({ code: 'invalid-plan' }) + expect(f.writes).toHaveLength(0) +}) + +it('stops when a channel changes between preflight and writing', async () => { + const f = fixture() + const put = f.operations.transport.put.bind(f.operations.transport) + f.operations.transport.put = async (...args) => { + await put(...args) + f.objects.set('feed/nightly.yml', observed('version: 3.0.0\n')) + } + await expect(publishDesktopRelease(f.plan, f.operations)).rejects.toMatchObject({ code: 'remote-changed' }) + expect(f.writes).not.toContain('feed/nightly.yml') +}) + +it('does not update the channel when readback cannot confirm a binary', async () => { + const f = fixture() + f.operations.transport.put = async () => {} + await expect(publishDesktopRelease(f.plan, f.operations)).rejects.toMatchObject({ code: 'verification-failed' }) + expect(f.events.some(event => event.type === 'feeds-complete')).toBe(false) +}) + +it('classifies corrupted remote channel metadata separately from an invalid local plan', async () => { + const f = fixture() + f.objects.set('feed/nightly.yml', observed('version: invalid\n')) + await expect(publishDesktopRelease(f.plan, f.operations)).rejects.toMatchObject({ code: 'verification-failed' }) + expect(f.writes).toEqual([]) +}) diff --git a/apps/desktop/tests/desktop-release-store.spec.ts b/apps/desktop/tests/desktop-release-store.spec.ts new file mode 100644 index 0000000000..7c717aa90e --- /dev/null +++ b/apps/desktop/tests/desktop-release-store.spec.ts @@ -0,0 +1,71 @@ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { retainDesktopRelease, retainedDesktopPath, verifyRetainedDesktopRelease, type DesktopRetainedSource } from '../scripts/desktop-release-store.ts' + +const roots: string[] = [] +afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) }) + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'desktop-release-store-')) + roots.push(root) + const file = join(root, 'installer.exe') + await writeFile(file, 'signed installer fixture') + const source: DesktopRetainedSource = { + repository: 'owner/repository', runId: '100', attempt: '1', commit: 'a'.repeat(40), runnerName: 'windows-runner', + target: 'win-x64', preset: 'test', productVersion: '1.0.0', version: '1.0.0', testReleaseId: 'b'.repeat(32), + workflowCommit: 'a'.repeat(40), sourceRef: 'master', channel: 'nightly', + publishRequested: true, qualification: 'signed', + } + return { root: join(root, 'releases'), file, source } +} + +it('retains independent attempts after source removal and rejects replacing an existing attempt', async () => { + const { root, file, source } = await fixture() + const first = await retainDesktopRelease(root, source, [file]) + const second = await retainDesktopRelease(root, { ...source, attempt: '2' }, [file]) + expect(first).not.toBe(second) + await expect(retainDesktopRelease(root, source, [file])).rejects.toThrow(/already exists/u) + await rm(file) + const manifest = await verifyRetainedDesktopRelease(root, '100', '1') + expect(manifest.source).toEqual(source) + expect(await readFile(join(first, 'installer.exe'), 'utf8')).toBe('signed installer fixture') +}) + +it('detects changed bytes even when file length is unchanged', async () => { + const { root, file, source } = await fixture() + const directory = await retainDesktopRelease(root, source, [file]) + const path = join(directory, 'installer.exe') + await writeFile(path, Buffer.alloc((await readFile(path)).length)) + await expect(verifyRetainedDesktopRelease(root, '100', '1')).rejects.toThrow(/changed file/u) +}) + +it('does not expose an incomplete copy and releases its claim after failure', async () => { + const { root, file, source } = await fixture() + await expect(retainDesktopRelease(root, source, [file, join(root, 'missing.zip')])).rejects.toThrow() + await expect(verifyRetainedDesktopRelease(root, '100', '1')).rejects.toThrow() + await retainDesktopRelease(root, source, [file]) + await expect(verifyRetainedDesktopRelease(root, '100', '1')).resolves.toMatchObject({ source }) +}) + +it('permits only one writer for a concurrently retained attempt', async () => { + const { root, file, source } = await fixture() + const results = await Promise.allSettled([ + retainDesktopRelease(root, source, [file]), retainDesktopRelease(root, source, [file]), + ]) + expect(results.filter(result => result.status === 'fulfilled')).toHaveLength(1) + await expect(verifyRetainedDesktopRelease(root, '100', '1')).resolves.toMatchObject({ source }) +}) + +it('rejects traversal and manifest identity or file inventory tampering', async () => { + const { root, file, source } = await fixture() + expect(() => retainedDesktopPath(root, '../100', '1')).toThrow() + expect(() => retainedDesktopPath(root, '100', '0')).toThrow() + const path = await retainDesktopRelease(root, source, [file]) + const manifest = await verifyRetainedDesktopRelease(root, '100', '1') + await writeFile(join(path, 'manifest.json'), JSON.stringify({ ...manifest, source: { ...source, attempt: '2' } })) + await expect(verifyRetainedDesktopRelease(root, '100', '1')).rejects.toThrow(/identity mismatch/u) + await writeFile(join(path, 'manifest.json'), JSON.stringify({ ...manifest, files: [{ ...manifest.files[0], name: '../installer.exe' }] })) + await expect(verifyRetainedDesktopRelease(root, '100', '1')).rejects.toThrow() +}) diff --git a/apps/desktop/tests/desktop-rollback.spec.ts b/apps/desktop/tests/desktop-rollback.spec.ts new file mode 100644 index 0000000000..2bf2151626 --- /dev/null +++ b/apps/desktop/tests/desktop-rollback.spec.ts @@ -0,0 +1,79 @@ +import { createHash } from 'node:crypto' +import { expect, it } from 'vitest' +import { rollbackDesktopChannel } from '../scripts/desktop-rollback.ts' +import type { DesktopPublishOperations } from '../scripts/desktop-publish.ts' +import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' + +function fixture() { + const objects = new Map([['bin/old.exe', 'old installer'], ['feed/nightly.yml', 'version: 2.0.0\n']]) + const writes: string[] = [] + const plan: DesktopUploadPlan = { + environment: 'test', target: 'win-x64', version: '1.0.0', bucket: 'fixture', publicUrl: 'https://example.com', secretIdEnvName: 'ID', secretKeyEnvName: 'KEY', + artifacts: [ + { key: 'bin/old.exe', path: '', filename: 'old.exe', contentType: 'application/octet-stream', channelMetadata: false, contents: 'old installer' }, + { key: 'feed/nightly.yml', path: '', filename: 'nightly.yml', contentType: 'application/yaml', channelMetadata: true, contents: 'version: 1.0.0\n' }, + ], + } + const operations: DesktopPublishOperations = { + transport: { + async read(key) { + const contents = objects.get(key) + return contents === undefined ? null : { contents, size: Buffer.byteLength(contents), sha512: createHash('sha512').update(contents).digest('base64') } + }, + async put(artifact, _digest, forbidOverwrite) { + expect(forbidOverwrite).toBe(false) + writes.push(artifact.key) + objects.set(artifact.key, artifact.contents!) + }, + }, + async record() {}, + async tag() { throw new Error('must not create a tag') }, + } + return { plan, operations, writes, objects } +} + +it('previews the exact YAML change without writes', async () => { + const f = fixture() + const result = await rollbackDesktopChannel(f.plan, '2.0.0', false, f.operations) + expect(result).toMatchObject({ status: 'preview', feeds: [{ before: 'version: 2.0.0\n', after: 'version: 1.0.0\n' }] }) + expect(f.writes).toEqual([]) +}) + +it('only restores the YAML after checking the historical binary', async () => { + const f = fixture() + await expect(rollbackDesktopChannel(f.plan, '2.0.0', true, f.operations)).resolves.toMatchObject({ status: 'complete' }) + expect(f.writes).toEqual(['feed/nightly.yml']) + expect(f.objects.get('bin/old.exe')).toBe('old installer') +}) + +it.each(['missing-file', 'changed-file', 'changed-channel'] as const)('rejects %s without writes', async (problem) => { + const f = fixture() + if (problem === 'missing-file') f.objects.delete('bin/old.exe') + if (problem === 'changed-file') f.objects.set('bin/old.exe', 'changed') + if (problem === 'changed-channel') f.objects.set('feed/nightly.yml', 'version: 3.0.0\n') + await expect(rollbackDesktopChannel(f.plan, '2.0.0', true, f.operations)).rejects.toThrow() + expect(f.writes).toEqual([]) +}) + +it('restores nightly when latest already matches and resumes a partially restored pair', async () => { + for (const latestAlreadyMatches of [true, false]) { + const f = fixture() + const nightly = f.plan.artifacts[1]! + const plan = { ...f.plan, artifacts: [...f.plan.artifacts, { ...nightly, key: 'feed/latest.yml', filename: 'latest.yml' }] } + f.objects.set('feed/latest.yml', latestAlreadyMatches ? nightly.contents! : 'version: 2.0.0\n') + if (!latestAlreadyMatches) { + const put = f.operations.transport.put.bind(f.operations.transport) + const interrupted = { ...f.operations, transport: { ...f.operations.transport, + async put(...args: Parameters) { + if (args[0].key === 'feed/latest.yml') throw new Error('fixture interruption') + return put(...args) + }, + } } + await expect(rollbackDesktopChannel(plan, '2.0.0', true, interrupted)).rejects.toThrow('fixture interruption') + } + await expect(rollbackDesktopChannel(plan, '2.0.0', true, f.operations)).resolves.toMatchObject({ status: 'complete' }) + expect(f.objects.get('feed/nightly.yml')).toBe(nightly.contents) + expect(f.objects.get('feed/latest.yml')).toBe(nightly.contents) + expect(f.writes.filter(key => key === 'feed/nightly.yml')).toHaveLength(1) + } +}) diff --git a/apps/desktop/tests/desktop-upload-plan.spec.ts b/apps/desktop/tests/desktop-upload-plan.spec.ts index f1e2097075..def8cb19bf 100644 --- a/apps/desktop/tests/desktop-upload-plan.spec.ts +++ b/apps/desktop/tests/desktop-upload-plan.spec.ts @@ -38,6 +38,7 @@ async function fixture( target: DesktopPackageTargetName, version = '1.2.3', environment: 'test' | 'production' = 'test', + channel: 'nightly' | 'latest' = 'nightly', ): Promise { const root = await mkdtemp(join(tmpdir(), 'dsh-desktop-upload-')) temporaryDirectories.push(root) @@ -55,6 +56,7 @@ async function fixture( : 'https://download.deepseek.com' await writeFile(join(artifactsRoot, `${target}-release.json`), `${JSON.stringify({ schemaVersion: 1, + channel, target, version, environment, @@ -66,7 +68,7 @@ async function fixture( await writeFile(join(artifactsRoot, `${base}.zip`), zip) await writeFile(join(artifactsRoot, `${base}.zip.blockmap`), 'blockmap') await writeFile(join(artifactsRoot, `${base}.dmg`), 'notarized DMG fixture') - await writeFile(join(artifactsRoot, desktopUpdateMetadataFilename(version, 'darwin')), `${JSON.stringify({ + await writeFile(join(artifactsRoot, desktopUpdateMetadataFilename(version, 'darwin', channel)), `${JSON.stringify({ version, path: `${base}.zip`, files: [{ url: `${base}.zip`, size: Buffer.byteLength(zip), sha512: digest(zip) }], @@ -78,7 +80,7 @@ async function fixture( const info = await createBlockmap(join(artifactsRoot, `${base}.exe`), {}, { info: { emitArtifactBuildCompleted: async () => {} } }, `${base}.exe`) expect(Object.hasOwn(info, 'blockMapSize')).toBe(false) - await writeFile(join(artifactsRoot, desktopUpdateMetadataFilename(version, 'win32')), `${JSON.stringify({ + await writeFile(join(artifactsRoot, desktopUpdateMetadataFilename(version, 'win32', channel)), `${JSON.stringify({ version, path: `${base}.exe`, files: [{ @@ -93,12 +95,14 @@ async function fixture( artifactsRoot, environment: environment === 'test' ? { + DSH_DESKTOP_UPDATE_CHANNEL: channel, DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: TEST_ORIGIN, DOWNLOAD_TEST_RELEASE_ID: RELEASE_ID, DOWNLOAD_TEST_COS_BUCKET: TEST_BUCKET, } : { + DSH_DESKTOP_UPDATE_CHANNEL: channel, DSH_DESKTOP_AUTO_UPDATE_ENV: 'production', DOWNLOAD_PROD_COS_BUCKET: PRODUCTION_BUCKET, }, @@ -171,6 +175,16 @@ describe('desktop upload plan', () => { .rejects.toThrow(failure === 'checksum' ? /SHA-512/u : /completion record/u) }) + it.each(['test', 'production'] as const)('isolates stable latest packages from nightly in %s', async (environment) => { + const nightly = await createDesktopUploadPlan('win-x64', await fixture('win-x64', '1.2.3', environment, 'nightly')) + const latest = await createDesktopUploadPlan('win-x64', await fixture('win-x64', '1.2.3', environment, 'latest')) + expect(latest.artifacts.filter(file => file.channelMetadata).map(file => file.filename)).toEqual(['latest.yml']) + expect(nightly.artifacts.filter(file => file.channelMetadata).map(file => file.filename)).toEqual(['nightly.yml']) + expect(latest.artifacts.every(file => !nightly.artifacts.some(other => other.key === file.key))).toBe(true) + const prerelease = await fixture('win-x64', '1.2.3-alpha.1', environment, 'latest') + await expect(createDesktopUploadPlan('win-x64', prerelease)).rejects.toThrow(/latest requires a stable version/u) + }) + it('publishes fixed feeds referencing versioned binaries without overriding CDN cache policy', async () => { const paths = await fixture('win-x64', '1.2.3', 'production') const plan = await createDesktopUploadPlan('win-x64', paths) @@ -178,7 +192,6 @@ describe('desktop upload plan', () => { 'dsh-desk/bin/win-x64/deepseek-harness-1.2.3-win-x64.exe', 'dsh-desk/bin/win-x64/deepseek-harness-1.2.3-win-x64.exe.blockmap', 'dsh-desk/feeds/win-x64/nightly.yml', - 'dsh-desk/feeds/win-x64/latest.yml', ]) expect(load(plan.artifacts[2]!.contents!)).toMatchObject({ version: '1.2.3', @@ -187,7 +200,6 @@ describe('desktop upload plan', () => { sha512: digest('signed NSIS executable fixture'), }], }) - expect(plan.artifacts[2]!.contents).toBe(plan.artifacts[3]!.contents) expect(plan.artifacts.every(artifact => !('cacheControl' in artifact))).toBe(true) }) @@ -205,7 +217,6 @@ describe('desktop upload plan', () => { 'deepseek-harness-1.2.3-mac-arm64.zip', 'deepseek-harness-1.2.3-mac-arm64.zip.blockmap', 'nightly-mac.yml', - 'latest-mac.yml', ]) expect(plan.artifacts.at(-1)).toMatchObject({ channelMetadata: true, @@ -258,7 +269,6 @@ describe('desktop upload plan', () => { 'deepseek-harness-2.0.0-win-x64.exe', 'deepseek-harness-2.0.0-win-x64.exe.blockmap', 'nightly.yml', - 'latest.yml', ]) expect(plan).toMatchObject({ publicUrl: 'https://download.deepseek.com/dsh-desk/feeds/win-x64/', @@ -292,6 +302,20 @@ describe('desktop upload plan', () => { })).rejects.toThrow(/completion record.*test/u) }) + it('validates retained builds against their original product version after the checkout advances', async () => { + const paths = await fixture('mac-arm64', '1.2.3') + await writeFile(join(paths.repositoryRoot, 'package.json'), '{"version":"2.0.0"}\n') + await writeFile(join(paths.appRoot, 'package.json'), '{"version":"2.0.0"}\n') + await expect(createDesktopUploadPlan('mac-arm64', paths)).rejects.toThrow(/completion record/u) + const plan = await createDesktopUploadPlan('mac-arm64', { ...paths, packagedProductVersion: '1.2.3' }) + expect(plan.version).toBe('1.2.3') + await expect(createDesktopUploadPlan('mac-arm64', { ...paths, packagedProductVersion: '1.2.4' })) + .rejects.toThrow(/completion record/u) + await writeFile(join(paths.artifactsRoot, 'deepseek-harness-1.2.3-mac-arm64.zip'), 'tampered') + await expect(createDesktopUploadPlan('mac-arm64', { ...paths, packagedProductVersion: '1.2.3' })) + .rejects.toThrow(/size.*metadata/u) + }) + it('rejects stale architecture metadata and modified updater bytes', async () => { const paths = await fixture('mac-arm64') const metadataPath = join(paths.artifactsRoot, 'nightly-mac.yml') diff --git a/apps/desktop/tests/expected/policy-login-en.json b/apps/desktop/tests/expected/policy-login-en.json index 822c1a0f30..4e63787b24 100644 --- a/apps/desktop/tests/expected/policy-login-en.json +++ b/apps/desktop/tests/expected/policy-login-en.json @@ -1,4 +1,8 @@ { + "disabled": [ + "Checking for updates…", + "You’re up to date!" + ], "returned": [ "Checking for updates…", "You’re up to date!", diff --git a/apps/desktop/tests/expected/test-release-upload-mac-arm64.json b/apps/desktop/tests/expected/test-release-upload-mac-arm64.json index 515f0234f9..69af29ec01 100644 --- a/apps/desktop/tests/expected/test-release-upload-mac-arm64.json +++ b/apps/desktop/tests/expected/test-release-upload-mac-arm64.json @@ -11,9 +11,5 @@ { "key": "dsh-desk/0123456789abcdef0123456789abcdef/feeds/mac-arm64/nightly-mac.yml", "contents": "version: 1.2.3\npath: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-arm64/deepseek-harness-1.2.3-mac-arm64.zip\nfiles:\n - url: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-arm64/deepseek-harness-1.2.3-mac-arm64.zip\n size: 24\n sha512: >-\n IgtiHRPFjickTxiSTW6k0ltyBNOF/gpMGj/xflzVV2iRIzUSFPY6BG45u9fR4GmAJSVtN+FMh3NZx7mddUfJLw==\n" - }, - { - "key": "dsh-desk/0123456789abcdef0123456789abcdef/feeds/mac-arm64/latest-mac.yml", - "contents": "version: 1.2.3\npath: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-arm64/deepseek-harness-1.2.3-mac-arm64.zip\nfiles:\n - url: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-arm64/deepseek-harness-1.2.3-mac-arm64.zip\n size: 24\n sha512: >-\n IgtiHRPFjickTxiSTW6k0ltyBNOF/gpMGj/xflzVV2iRIzUSFPY6BG45u9fR4GmAJSVtN+FMh3NZx7mddUfJLw==\n" } ] diff --git a/apps/desktop/tests/expected/test-release-upload-mac-x64.json b/apps/desktop/tests/expected/test-release-upload-mac-x64.json index 5039a3aede..2c085140ce 100644 --- a/apps/desktop/tests/expected/test-release-upload-mac-x64.json +++ b/apps/desktop/tests/expected/test-release-upload-mac-x64.json @@ -11,9 +11,5 @@ { "key": "dsh-desk/0123456789abcdef0123456789abcdef/feeds/mac-x64/nightly-mac.yml", "contents": "version: 1.2.3\npath: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-x64/deepseek-harness-1.2.3-mac-x64.zip\nfiles:\n - url: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-x64/deepseek-harness-1.2.3-mac-x64.zip\n size: 24\n sha512: >-\n IgtiHRPFjickTxiSTW6k0ltyBNOF/gpMGj/xflzVV2iRIzUSFPY6BG45u9fR4GmAJSVtN+FMh3NZx7mddUfJLw==\n" - }, - { - "key": "dsh-desk/0123456789abcdef0123456789abcdef/feeds/mac-x64/latest-mac.yml", - "contents": "version: 1.2.3\npath: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-x64/deepseek-harness-1.2.3-mac-x64.zip\nfiles:\n - url: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/mac-x64/deepseek-harness-1.2.3-mac-x64.zip\n size: 24\n sha512: >-\n IgtiHRPFjickTxiSTW6k0ltyBNOF/gpMGj/xflzVV2iRIzUSFPY6BG45u9fR4GmAJSVtN+FMh3NZx7mddUfJLw==\n" } ] diff --git a/apps/desktop/tests/expected/test-release-upload-win-x64.json b/apps/desktop/tests/expected/test-release-upload-win-x64.json index cb60e0ce29..9c7db67400 100644 --- a/apps/desktop/tests/expected/test-release-upload-win-x64.json +++ b/apps/desktop/tests/expected/test-release-upload-win-x64.json @@ -8,9 +8,5 @@ { "key": "dsh-desk/0123456789abcdef0123456789abcdef/feeds/win-x64/nightly.yml", "contents": "version: 1.2.3\npath: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/win-x64/deepseek-harness-1.2.3-win-x64.exe\nfiles:\n - url: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/win-x64/deepseek-harness-1.2.3-win-x64.exe\n size: 30\n sha512: >-\n eVumVOW1yvT3fAgGKUnliEzSfhmn8jUfzpNaUPufU1yekWrwJe8wRPC+JOrHH2Hmc/eLynwxjX1yIiER8tVOTA==\n" - }, - { - "key": "dsh-desk/0123456789abcdef0123456789abcdef/feeds/win-x64/latest.yml", - "contents": "version: 1.2.3\npath: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/win-x64/deepseek-harness-1.2.3-win-x64.exe\nfiles:\n - url: >-\n https://desktop-updates.example.com/dsh-desk/0123456789abcdef0123456789abcdef/bin/win-x64/deepseek-harness-1.2.3-win-x64.exe\n size: 30\n sha512: >-\n eVumVOW1yvT3fAgGKUnliEzSfhmn8jUfzpNaUPufU1yekWrwJe8wRPC+JOrHH2Hmc/eLynwxjX1yIiER8tVOTA==\n" } ] diff --git a/apps/desktop/tests/fixtures/pnpm-smoke.mjs b/apps/desktop/tests/fixtures/pnpm-smoke.mjs new file mode 100644 index 0000000000..5d16769ab4 --- /dev/null +++ b/apps/desktop/tests/fixtures/pnpm-smoke.mjs @@ -0,0 +1,69 @@ +/** Install and use a local dependency with the packaged pnpm and Electron Node launcher. */ + +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { delimiter, join } from 'node:path' + +/** + * Exercise offline installation and package scripts without a system pnpm or Node installation. + * @param {string} resourcesRuntime - Packaged runtime directory outside ASAR. + * @returns {Promise} Resolves after execution and removal of the private installation. + */ +export async function checkPnpm(resourcesRuntime) { + assert.ok(process.versions.electron, 'Run the package-manager smoke with Electron Node mode') + assert.equal(existsSync(join(resourcesRuntime, 'pnpm')), false, 'Desktop must ship only primary-runtime pnpm') + const primary = join(resourcesRuntime, 'primary-runtime') + const pnpm = join(primary, 'dependencies', 'pnpm', 'bin', 'pnpm.mjs') + const versions = JSON.parse(readFileSync(join(resourcesRuntime, 'versions.json'), 'utf8')) + const manifest = JSON.parse(readFileSync(join(primary, 'runtime.json'), 'utf8')) + assert.equal(versions.pnpm, manifest.pnpm) + const scratch = mkdtempSync(join(tmpdir(), 'desktop-pnpm-smoke-')) + try { + mkdirSync(join(scratch, 'dependency')) + writeFileSync(join(scratch, 'dependency', 'package.json'), JSON.stringify({ + name: 'desktop-pnpm-smoke-dependency', version: '1.0.0', main: 'index.cjs', + })) + writeFileSync(join(scratch, 'dependency', 'index.cjs'), 'exports.answer = 42\n') + writeFileSync(join(scratch, 'package.json'), JSON.stringify({ + name: 'desktop-node-script-smoke', private: true, + dependencies: { 'desktop-pnpm-smoke-dependency': 'file:./dependency' }, scripts: { check: 'node check.cjs' }, + })) + writeFileSync(join(scratch, 'npmrc'), '') + writeFileSync(join(scratch, 'check.cjs'), ` +const assert = require('node:assert/strict') +assert.equal(require('desktop-pnpm-smoke-dependency').answer, 42) +assert.equal(process.execPath, ${JSON.stringify(process.execPath)}) +assert.ok(process.versions.electron) +assert.ok(process.execArgv.includes('--expose-internals')) +assert.equal(typeof require('internal/modules/esm/loader').getOrInitializeCascadedLoader, 'function') +console.log('desktop-node-script-ok') +`) + const environment = Object.fromEntries(Object.entries(process.env).filter(([name]) => /^(?:systemroot|windir|comspec|LD_LIBRARY_PATH)$/iu.test(name))) + const systemBin = process.platform === 'win32' ? join(process.env.SystemRoot, 'System32') : '/usr/bin:/bin' + const run = args => execFileSync(process.execPath, ['--expose-internals', pnpm, ...args], { + cwd: scratch, encoding: 'utf8', timeout: 45_000, windowsHide: true, + env: { ...environment, pnpm_config_verify_deps_before_run: 'false', + ELECTRON_RUN_AS_NODE: '1', DSH_DESKTOP_NODE_EXECUTABLE: process.execPath, + PATH: `${join(resourcesRuntime, 'bin')}${delimiter}${systemBin}`, + HOME: scratch, USERPROFILE: scratch, TMP: scratch, TEMP: scratch, TMPDIR: scratch, + XDG_CONFIG_HOME: scratch, XDG_CACHE_HOME: scratch, XDG_STATE_HOME: scratch, + npm_config_userconfig: join(scratch, 'npmrc'), npm_config_globalconfig: join(scratch, 'npmrc'), + npm_config_store_dir: join(scratch, 'store'), npm_config_enable_global_virtual_store: 'false', + npm_config_update_notifier: 'false' }, + }) + assert.equal(run(['--version']).trim(), versions.pnpm) + run(['install', '--offline', '--ignore-scripts']) + assert.match(run(['run', 'check']), /desktop-node-script-ok/u) + } finally { + await rm(scratch, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 }) + } +} + +if (import.meta.main) { + assert.ok(process.argv[2], 'Pass the packaged runtime directory') + await checkPnpm(process.argv[2]) + console.log('desktop pnpm: offline installation and Electron Node package script passed') +} diff --git a/apps/desktop/tests/fixtures/runtime-payload-smoke.mjs b/apps/desktop/tests/fixtures/runtime-payload-smoke.mjs index 503c4bae3c..3cda38c620 100644 --- a/apps/desktop/tests/fixtures/runtime-payload-smoke.mjs +++ b/apps/desktop/tests/fixtures/runtime-payload-smoke.mjs @@ -8,6 +8,7 @@ import { createRequire } from 'node:module' import { tmpdir } from 'node:os' import { delimiter, dirname, join, resolve } from 'node:path' import { pathToFileURL } from 'node:url' +import { checkPnpm } from './pnpm-smoke.mjs' const runtime = process.argv[2] assert.ok(runtime, 'Pass the filtered resources/dsh directory') @@ -20,33 +21,6 @@ const resourcesRuntime = process.argv[3] ?? join(dirname(root), 'runtime') const requireRuntime = createRequire(join(root, 'package.json')) const scratch = mkdtempSync(join(tmpdir(), 'dsh-runtime-payload-')) -/** Run a package script with only the shipped node launcher available on PATH. */ -function checkPnpm() { - const bin = join(resourcesRuntime, 'bin') - const pnpm = join(resourcesRuntime, 'pnpm', 'bin', 'pnpm.mjs') - writeFileSync(join(scratch, 'package.json'), JSON.stringify({ - name: 'desktop-node-script-smoke', private: true, scripts: { check: 'node check.cjs' }, - })) - writeFileSync(join(scratch, 'check.cjs'), ` -const assert = require('node:assert/strict') -assert.equal(process.execPath, ${JSON.stringify(process.execPath)}) -assert.ok(process.versions.electron) -assert.ok(process.execArgv.includes('--expose-internals')) -assert.equal(typeof require('internal/modules/esm/loader').getOrInitializeCascadedLoader, 'function') -console.log('desktop-node-script-ok') -`) - const environment = Object.fromEntries(Object.entries(process.env).filter(([name]) => /^(?:systemroot|windir|comspec)$/iu.test(name))) - const systemBin = process.platform === 'win32' ? join(process.env.SystemRoot, 'System32') : '/usr/bin:/bin' - // This dependency-free fixture checks script launch, without pnpm's implicit install and update-network check. - const output = execFileSync(process.execPath, ['--expose-internals', pnpm, 'run', 'check'], { - cwd: scratch, encoding: 'utf8', timeout: 45_000, - env: { ...environment, pnpm_config_verify_deps_before_run: 'false', - ELECTRON_RUN_AS_NODE: '1', DSH_DESKTOP_NODE_EXECUTABLE: process.execPath, - PATH: `${bin}${delimiter}${systemBin}`, HOME: scratch, USERPROFILE: scratch, TMP: scratch, TEMP: scratch, TMPDIR: scratch }, - }) - assert.match(output, /desktop-node-script-ok/u) -} - /** Spawn only a fixed Node program and await the terminal's drained exit event. */ async function checkPty() { const pty = requireRuntime('node-pty') @@ -161,12 +135,19 @@ function checkHtml() { try { const builtin = requireRuntime('node-addon-require-builtin') assert.equal(typeof builtin.requireBuiltin('internal/modules/esm/loader').getOrInitializeCascadedLoader, 'function') - checkPnpm() + console.error('runtime payload: pnpm') + await checkPnpm(resourcesRuntime) + console.error('runtime payload: koffi') checkKoffi() + console.error('runtime payload: sharp') await checkSharp() + console.error('runtime payload: html') checkHtml() + console.error('runtime payload: pty') await checkPty() + console.error('runtime payload: search') await checkSearch() + console.error('runtime payload: checks complete; awaiting process exit') } finally { // This private tree contains only fixture files; Windows may release handles after terminal exit. await rm(scratch, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 }) diff --git a/apps/desktop/tests/fixtures/windows-pty-exit.cjs b/apps/desktop/tests/fixtures/windows-pty-exit.cjs new file mode 100644 index 0000000000..5aaa17a56e --- /dev/null +++ b/apps/desktop/tests/fixtures/windows-pty-exit.cjs @@ -0,0 +1,28 @@ +/** Exercise terminal cleanup in a child whose natural exit detects retained workers. */ +const assert = require('node:assert/strict') +const { createRequire } = require('node:module') +const { resolve } = require('node:path') +const pty = createRequire(resolve(__dirname, '../../../../packages/subprocess/subprocess-local/package.json'))('node-pty') +const killWhileRunning = process.argv[2] === 'kill' +const terminal = pty.spawn(process.env.ComSpec, ['/d', '/c', killWhileRunning ? 'echo pty-ready & pause >nul' : 'echo pty-complete'], { + cwd: __dirname, env: process.env, cols: 80, rows: 24, useConptyDll: true, +}) +let output = '' +let killed = false +terminal.onData(data => { + output += data + if (killWhileRunning && !killed && output.includes('pty-ready')) { + killed = true + terminal.kill() + } +}) +terminal.onExit(event => { + if (!killWhileRunning) { + assert.equal(event.exitCode, 0) + assert.match(output, /pty-complete/u) + terminal.kill() + } else { + assert.equal(killed, true) + } + process.once('beforeExit', () => console.log('pty-cleanup-complete')) +}) diff --git a/apps/desktop/tests/installed-update-builder.spec.ts b/apps/desktop/tests/installed-update-builder.spec.ts index 089b04deef..12e5a82258 100644 --- a/apps/desktop/tests/installed-update-builder.spec.ts +++ b/apps/desktop/tests/installed-update-builder.spec.ts @@ -88,8 +88,10 @@ describe('installed-update application inputs and builder configuration', () => expect(config.extraMetadata.main).toBe('qualification-bootstrap.mjs') expect(config.directories.output).toBe(join(manifest, '..', versions[index]!, 'installer')) const dsh = join(manifest, '..', versions[index]!, 'dsh') - expect(config.files[2]).toMatchObject({ from: dsh, to: 'dsh' }) - expect(config.files[3]).toMatchObject({ from: join(dsh, 'node_modules'), to: 'dsh/node_modules' }) + expect(config.files.at(-2)).toMatchObject({ from: dsh, to: 'dsh' }) + expect(config.files.at(-1)).toMatchObject({ from: join(dsh, 'node_modules'), to: 'dsh/node_modules' }) + expect(config.files).toContain('!node_modules/**/*.{js,cjs,mjs,ts,cts,mts,css}.map') + expect(config.files).toContain('!node_modules/**/*.tsbuildinfo') expect(config.win.forceCodeSigning).toBe(true) expect(config.win.signtoolOptions.publisherName).toBe('CN=Fixture,O=Fixture,C=CN') expect(typeof config.win.signtoolOptions.sign).toBe('function') diff --git a/apps/desktop/tests/installed-update/README.i18n.yaml b/apps/desktop/tests/installed-update/README.i18n.yaml index 1ac20fbb75..cfd4135420 100644 --- a/apps/desktop/tests/installed-update/README.i18n.yaml +++ b/apps/desktop/tests/installed-update/README.i18n.yaml @@ -15,8 +15,8 @@ en: bd61ff806d57cbb1 zh: 8b09719bc3b247c8 /windows-installed-update-walkthrough/prepare-materials: - en: 1f7d9426be57a23a - zh: 9f2be099d3d1a026 + en: ab2cf13a10671564 + zh: f2c944df56f1e8d7 /windows-installed-update-walkthrough/operator-sequence: en: 8a7f275812dbe11f zh: 24dbf32328f9c0dd diff --git a/apps/desktop/tests/installed-update/README.md b/apps/desktop/tests/installed-update/README.md index b847960862..77c7ae460f 100644 --- a/apps/desktop/tests/installed-update/README.md +++ b/apps/desktop/tests/installed-update/README.md @@ -23,7 +23,7 @@ Prepare a private test application and fresh test distribution namespace, then l From the repository root with dependencies installed, allocate a run with two increasing derived test versions. This writes only an ignored local manifest; it does not build, sign, upload, install, or read credentials. -The examples use base version `0.1.6-alpha.1`. Before creating new material, substitute the actual base, Asia/Shanghai date, and unused index according to the [release version rules](../../README.md#release-versions). +The examples use base version `0.1.6-alpha.1`. Before creating new material, substitute the actual base, Asia/Shanghai date, and unused index according to the [release version rules](../../packaging/README.md#release-versions). ```powershell node --import tsx apps/desktop/scripts/prepare-installed-update.ts init 0.1.6-alpha.1.20260916.1 0.1.6-alpha.1.20260916.2 @@ -44,7 +44,7 @@ Package both files from the generated `bootstrap` directory beside `lib/`, and s The `application` command copies built main/preload modules, renderer files, and the prepared bootstrap into `application/files`, with SHA-256 values in `application/result.json`. It does not copy the app's root `.env.windows` or freeze `node_modules` and build tools. The [qualification builder configuration](../../scripts/installed-update-builder.ts) verifies this inventory and the selected private runtime, selects the shared frozen files and isolated package metadata, and preserves ordinary installer and signing hooks. Its tests substitute the signer and pass the pinned builder's configuration validator; they do not produce an installer. A separately authorized supervised build must still record dependency/tool inputs and verify final package contents and signatures. -The [packaging entry](../../scripts/package-installed-update.ts) defaults to checks. A retained signing interlock rejects before credentials are loaded; it never clears that interlock. With no interlock, checks load `.env.windows`, validate prepared inputs, and launch no child. The shared builder requires a valid `DOWNLOAD_TEST_RELEASE_ID` from the [test release settings](../../README.md#upload-updates); qualification still publishes through the manifest’s separate `qualification/` paths. Run this from the repository root with one exact version: +The [packaging entry](../../scripts/package-installed-update.ts) defaults to checks. A retained signing interlock rejects before credentials are loaded; it never clears that interlock. With no interlock, checks load `.env.windows`, validate prepared inputs, and launch no child. The shared builder requires a valid `DOWNLOAD_TEST_RELEASE_ID` from the [test release settings](../../publishing/README.md#upload-updates); qualification still publishes through the manifest’s separate `qualification/` paths. Run this from the repository root with one exact version: ```powershell node --import tsx apps/desktop/scripts/package-installed-update.ts "" 0.1.6-alpha.1.20260916.1 --check @@ -52,7 +52,7 @@ node --import tsx apps/desktop/scripts/package-installed-update.ts "" Actual packaging remains unverified and requires separate hardware-recovery approval and a present operator. The `--execute` mode requires a terminal and an exact confirmation containing the version and run ID; there is no piped approval option. It rechecks the interlock and exclusively allocates that version's `packaging` directory. The supervised child builds only that version, disables publication, strips unrelated credentials, and stops on failure or a 15-minute overall deadline. This deadline does not bound individual CSP authentication attempts. Records retain source/tool hashes, redacted output, events, and artifact file hashes; an existing attempt or output refuses reuse. `builderCompleted` and a successful supervisor result do not establish package verification, signature acceptance, or installation success; `packageVerification` remains `pending` until those checks are performed independently. -Before the operator starts, supply both verified installers, generated metadata and blockmaps, packaging and signature records, the exact installed executable path, and fixed test feed URL. Both packages must use the same test identity, isolated data directories, and absolute external `DSH_DESKTOP_UPDATE_JOURNAL_DIR` on every launch, including an installer-triggered restart. A variable set only in the original launch terminal is insufficient. The [Windows signing rules](../../README.md#windows-ev-signing) still apply; a manifest never clears a signing interlock. +Before the operator starts, supply both verified installers, generated metadata and blockmaps, packaging and signature records, the exact installed executable path, and fixed test feed URL. Both packages must use the same test identity, isolated data directories, and absolute external `DSH_DESKTOP_UPDATE_JOURNAL_DIR` on every launch, including an installer-triggered restart. A variable set only in the original launch terminal is insufficient. The [Windows signing rules](../../windows-signing/README.md#windows-ev-signing) still apply; a manifest never clears a signing interlock. The Windows [read-only signature helper](../../scripts/installed-update-signature.mjs) uses the real updater verifier with a publisher derived from the trusted public certificate, then requires valid Authenticode and timestamp attributes and unchanged SHA-512. Verification children receive no inherited signing/upload secrets or PowerShell module-path overrides. The helper never loads `.env.windows`, signs a file, or executes the inspected executable. Signed-probe acceptance and unsigned-installer rejection have been observed locally; they do not certify either prepared version, package identity, or installation behavior. diff --git a/apps/desktop/tests/installed-update/README.zh.md b/apps/desktop/tests/installed-update/README.zh.md index ac2bed4e2a..618eb3c578 100644 --- a/apps/desktop/tests/installed-update/README.zh.md +++ b/apps/desktop/tests/installed-update/README.zh.md @@ -23,7 +23,7 @@ description: "Windows 已安装应用更新的人工清单,覆盖下载失败 在已安装依赖的仓库根目录中,用两个递增的派生测试版本创建批次。这只写入已忽略的本地清单,不构建、签名、上传、安装或读取凭据。 -示例以 `0.1.6-alpha.1` 为基础版本。创建新物料前,按[发布版本规则](../../README.zh.md#release-versions)替换为实际基础版本、北京时间日期和未使用的序号。 +示例以 `0.1.6-alpha.1` 为基础版本。创建新物料前,按[发布版本规则](../../packaging/README.zh.md#release-versions)替换为实际基础版本、北京时间日期和未使用的序号。 ```powershell node --import tsx apps/desktop/scripts/prepare-installed-update.ts init 0.1.6-alpha.1.20260916.1 0.1.6-alpha.1.20260916.2 @@ -44,7 +44,7 @@ node --import tsx apps/desktop/scripts/prepare-installed-update.ts application " `application` 命令将已构建的主程序/预加载模块、界面文件和准备好的启动入口复制到 `application/files`,并在 `application/result.json` 中记录 SHA-256。它不复制应用根目录的 `.env.windows`,也不冻结 `node_modules` 与构建工具。[验收打包配置](../../scripts/installed-update-builder.ts)校验该清单与选定的独立运行时,选用共享冻结文件和隔离包元数据,并保留常规安装器与签名钩子。其测试替换签名器,并通过固定版本构建器的配置校验;测试不生成安装器。另行授权的受监督构建仍须记录依赖/工具输入,并验证最终包内容及签名。 -[打包入口](../../scripts/package-installed-update.ts)默认只检查。保留的签名保护锁会在读取凭据前使其拒绝;入口绝不清除此锁。没有保护锁时,检查会加载 `.env.windows`、校验准备输入,不启动子进程。共享构建器要求[测试发布配置](../../README.zh.md#upload-updates)中有效的 `DOWNLOAD_TEST_RELEASE_ID`;资格验收仍使用清单中独立的 `qualification/` 路径发布。在仓库根目录使用一个准确版本执行: +[打包入口](../../scripts/package-installed-update.ts)默认只检查。保留的签名保护锁会在读取凭据前使其拒绝;入口绝不清除此锁。没有保护锁时,检查会加载 `.env.windows`、校验准备输入,不启动子进程。共享构建器要求[测试发布配置](../../publishing/README.zh.md#upload-updates)中有效的 `DOWNLOAD_TEST_RELEASE_ID`;资格验收仍使用清单中独立的 `qualification/` 路径发布。在仓库根目录使用一个准确版本执行: ```powershell node --import tsx apps/desktop/scripts/package-installed-update.ts "" 0.1.6-alpha.1.20260916.1 --check @@ -52,7 +52,7 @@ node --import tsx apps/desktop/scripts/package-installed-update.ts "" 实际打包仍未验证,必须另行获得硬件恢复授权并有操作者在场。`--execute` 模式要求终端和包含版本、批次 ID 的准确确认,没有管道批准选项。它再次检查保护锁,并独占创建该版本的 `packaging` 目录。受监督子进程只构建该版本、禁用发布、移除无关凭据,失败或达到 15 分钟整体期限时停止。该期限不限制单次 CSP 内部认证尝试。记录保留源码/工具哈希、脱敏输出、事件和产物文件哈希;已有尝试或输出拒绝复用。`builderCompleted` 与监督程序成功结果不证明包验证、验签或安装成功;独立完成这些检查前,`packageVerification` 保持 `pending`。 -操作者开始前,提供两个已验证安装包、生成的元数据与 blockmap、打包和签名记录、准确的安装后可执行文件路径与固定 test feed URL。两个安装包必须使用相同的测试身份、隔离数据目录,并在每次启动时设置同一个安装目录外的绝对路径 `DSH_DESKTOP_UPDATE_JOURNAL_DIR`,包括安装器触发的重启。仅在首次启动终端中设置变量是不够的。[Windows 签名规则](../../README.zh.md#windows-ev-signing)仍适用;清单绝不解除签名保护锁。 +操作者开始前,提供两个已验证安装包、生成的元数据与 blockmap、打包和签名记录、准确的安装后可执行文件路径与固定 test feed URL。两个安装包必须使用相同的测试身份、隔离数据目录,并在每次启动时设置同一个安装目录外的绝对路径 `DSH_DESKTOP_UPDATE_JOURNAL_DIR`,包括安装器触发的重启。仅在首次启动终端中设置变量是不够的。[Windows 签名规则](../../windows-signing/README.zh.md#windows-ev-signing)仍适用;清单绝不解除签名保护锁。 Windows [只读签名检查器](../../scripts/installed-update-signature.mjs)使用真实 updater 验签,发布者来自可信公钥证书,随后要求 Authenticode 与时间戳属性有效且 SHA-512 未变。验签子进程不继承签名/上传秘密或 PowerShell 模块路径覆盖。检查器绝不加载 `.env.windows`、签名文件或执行被检查的可执行文件。本地已观察到签名探针通过、未签名安装包被拒绝;这些结果不能证明任一准备版本、包身份或安装行为已验收。 diff --git a/apps/desktop/tests/macos-app-update-config.spec.ts b/apps/desktop/tests/macos-app-update-config.spec.ts index 72a003734a..bba859fa7c 100644 --- a/apps/desktop/tests/macos-app-update-config.spec.ts +++ b/apps/desktop/tests/macos-app-update-config.spec.ts @@ -28,9 +28,9 @@ afterEach(async () => { describe('macOS packaged updater configuration', () => { it('uses the final generic Nightly provider configured for the build', () => { expect(resolveMacOSAppUpdateFeed([{ provider: 'generic', url: update.publicUrl, channel: 'nightly' }])) - .toEqual(update) + .toEqual({ ...update, channel: 'nightly' }) for (const publish of [undefined, [], [{ provider: 'github', channel: 'nightly', url: update.publicUrl }], - [{ provider: 'generic', channel: 'latest', url: update.publicUrl }]]) { + [{ provider: 'generic', channel: 'invalid', url: update.publicUrl }]]) { expect(() => resolveMacOSAppUpdateFeed(publish)).toThrow(/macOS update config/u) } }) @@ -64,3 +64,12 @@ describe('macOS packaged updater configuration', () => { .rejects.toThrow(/expected deepseek-harness-updater/u) }) }) + + +it('seals latest into the macOS updater file and rejects a different expected channel', async () => { + const paths = await fixture() + const latest = resolveMacOSAppUpdateFeed([{ provider: 'generic', url: update.publicUrl, channel: 'latest' }]) + await writeMacOSAppUpdateConfig(paths.resourcesDir, latest, 'fixture-updater') + await expect(verifyMacOSAppUpdateConfig(paths.appPath, latest)).resolves.toBeUndefined() + await expect(verifyMacOSAppUpdateConfig(paths.appPath, update)).rejects.toThrow(/does not match/u) +}) diff --git a/apps/desktop/tests/macos-disk-image-signature.spec.ts b/apps/desktop/tests/macos-disk-image-signature.spec.ts new file mode 100644 index 0000000000..5aaf21f969 --- /dev/null +++ b/apps/desktop/tests/macos-disk-image-signature.spec.ts @@ -0,0 +1,58 @@ +import { spawnSync } from 'node:child_process' +import { afterEach, expect, it, vi } from 'vitest' +import { createElectronBuilderConfig } from '../scripts/electron-builder-config.mjs' +import { verifyMacOSDiskImage } from '../scripts/verify-macos-signature.mjs' + +vi.mock('node:child_process', async importOriginal => ({ + ...await importOriginal(), spawnSync: vi.fn(), +})) +afterEach(() => { vi.resetAllMocks() }) + +const signingIdentity = 'Example Company (TEAMID1234)' +const teamId = 'TEAMID1234' +const environment = { + DSH_DESKTOP_APP_ID: 'com.example.desktop', DSH_DESKTOP_AUTO_UPDATE_ENV: 'production', + DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN: 'https://policy.example.com', + DOWNLOAD_PROD_ORIGIN: 'https://updates.example.com', + DSH_DESKTOP_MACOS_SIGNING_IDENTITY: signingIdentity, DSH_DESKTOP_MACOS_TEAM_ID: teamId, + DSH_DESKTOP_MACOS_SKIP_NOTARIZATION: '1', +} + +function toolResult(details = `Authority=Developer ID Application: ${signingIdentity}\nTeamIdentifier=${teamId}`) { + vi.mocked(spawnSync).mockReturnValue({ + pid: 1, output: [null, '', details], stdout: '', stderr: details, status: 0, signal: null, + }) +} + +it('verifies an unnotarized DMG signature and identity without invoking Apple notarization tools', () => { + toolResult() + const config = createElectronBuilderConfig(environment, 'darwin', 'arm64') + expect(config.artifactBuildCompleted({ file: '/fixture/debug.dmg' })).toBeUndefined() + expect(vi.mocked(spawnSync).mock.calls.map(call => call.slice(0, 2))).toEqual([ + ['/usr/bin/codesign', ['--verify', '--strict', '--verbose=2', '/fixture/debug.dmg']], + ['/usr/bin/codesign', ['--display', '--verbose=4', '/fixture/debug.dmg']], + ]) +}) + +it('rejects an unnotarized DMG signed by another team', () => { + toolResult('Authority=Developer ID Application: Other (OTHERID123)\nTeamIdentifier=OTHERID123') + const config = createElectronBuilderConfig(environment, 'darwin', 'arm64') + expect(() => config.artifactBuildCompleted({ file: '/fixture/debug.dmg' })).toThrow(/release identity/u) +}) + +it('rejects a corrupt unnotarized DMG before inspecting its identity', () => { + toolResult() + vi.mocked(spawnSync).mockReturnValueOnce({ pid: 1, output: [null, '', 'invalid signature'], + stdout: '', stderr: 'invalid signature', status: 1, signal: null }) + const config = createElectronBuilderConfig(environment, 'darwin', 'arm64') + expect(() => config.artifactBuildCompleted({ file: '/fixture/debug.dmg' })).toThrow(/invalid signature/u) + expect(spawnSync).toHaveBeenCalledOnce() +}) + +it('still requires a stapled ticket and Gatekeeper acceptance for release DMGs', () => { + toolResult() + verifyMacOSDiskImage('/fixture/release.dmg', { signingIdentity, teamId }) + expect(vi.mocked(spawnSync).mock.calls.map(call => call[0])).toEqual([ + '/usr/bin/codesign', '/usr/bin/codesign', '/usr/bin/xcrun', '/usr/sbin/spctl', + ]) +}) diff --git a/apps/desktop/tests/macos-package-preset.spec.ts b/apps/desktop/tests/macos-package-preset.spec.ts new file mode 100644 index 0000000000..a4ab457ec0 --- /dev/null +++ b/apps/desktop/tests/macos-package-preset.spec.ts @@ -0,0 +1,101 @@ +import { spawnSync } from 'node:child_process' +import { mkdir, mkdtemp, realpath, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { parseEnv } from 'node:util' +import { expect, it } from 'vitest' +import { loadDesktopPackageEnvironment } from '../scripts/desktop-package-environment.mjs' + +it('loads machine signing credentials independently of the checkout and rejects misplaced settings', async () => { + const root = await mkdtemp(join(tmpdir(), 'macos-preset-')) + try { + await mkdir(join(root, 'presets')) + await mkdir(join(root, 'secrets')) + const preset = join(root, 'presets/test.env') + const secrets = join(root, 'secrets/macos-signing.env') + await writeFile(preset, 'DSH_DESKTOP_AUTO_UPDATE_ENV=test\nDSH_DESKTOP_MACOS_PACK_CONCURRENCY=2\nDSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR=/machine/cache\n') + await writeFile(secrets, 'CSC_LINK=../certificates/app.p12\nCSC_KEY_PASSWORD=machine-secret\nAPPLE_API_KEY=../certificates/key.p8\n') + const env = { DSH_PACKAGING_PRESET: 'test', DSH_PACKAGING_CONFIG_DIR: root, CSC_KEY_PASSWORD: 'ambient-secret' } + for (const options of [{}, { prepareOnly: true }]) { + const selected = loadDesktopPackageEnvironment('darwin', env, join(root, 'absent-checkout'), options) + expect(selected.CSC_LINK).toBe(join(root, 'certificates/app.p12')) + expect(selected.APPLE_API_KEY).toBe(join(root, 'certificates/key.p8')) + expect(selected.CSC_KEY_PASSWORD).toBe('machine-secret') + expect(selected.DSH_DESKTOP_MACOS_PACK_CONCURRENCY).toBe('2') + expect(selected.DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR).toBe('/machine/cache') + } + await rm(secrets) + expect(loadDesktopPackageEnvironment('darwin', env, root, { unsigned: true }).CSC_KEY_PASSWORD).toBeUndefined() + expect(() => loadDesktopPackageEnvironment('darwin', env)).toThrow(/cannot read/u) + await writeFile(secrets, 'DSH_DESKTOP_MACOS_DOWNLOAD_PROXY=http://localhost:1234\n') + expect(() => loadDesktopPackageEnvironment('darwin', env)).toThrow(/unsupported setting/u) + await writeFile(preset, 'DSH_DESKTOP_AUTO_UPDATE_ENV=test\nCSC_KEY_PASSWORD=private-value\n') + expect(() => loadDesktopPackageEnvironment('darwin', env)).toThrow(/unsupported setting CSC_KEY_PASSWORD/u) + expect(() => loadDesktopPackageEnvironment('darwin', env)).not.toThrow(/private-value/u) + } finally { + await rm(root, { recursive: true, force: true }) + } +}) + +it.skipIf(process.platform !== 'darwin')('prepares private machine directories without overwriting existing files', async () => { + const root = await mkdtemp(join(tmpdir(), 'macos-setup-')) + try { + const machine = join(await realpath(root), 'machine') + const run = (...args: string[]) => spawnSync(process.execPath, + [join(import.meta.dirname, '../scripts/setup-macos-packaging.mjs'), machine, ...args], { encoding: 'utf8' }) + expect(run().status).toBe(0) + const config = join(machine, 'packaging/presets/test.env.example') + expect(parseEnv(await readFile(config, 'utf8')).DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR).toBe(join(machine, 'cache/macos-signatures')) + await writeFile(config, 'keep existing configuration\n') + expect(run().status).toBe(0) + expect(await readFile(config, 'utf8')).toBe('keep existing configuration\n') + expect(run('--check').status).toBe(0) + await rm(join(machine, 'packaging/secrets'), { recursive: true }) + const missing = run('--check') + expect(missing.error).toBeUndefined() + expect(missing.signal).toBeNull() + expect(missing.status).toBe(1) + } finally { + await rm(root, { recursive: true, force: true }) + } +}) + +it('records debugging artifact paths only for an explicit CI selection without notarization credentials', async () => { + const root = await mkdtemp(join(tmpdir(), 'macos-ci-settings-')) + try { + await mkdir(join(root, 'presets')) + await mkdir(join(root, 'secrets')) + await writeFile(join(root, 'certificate.p12'), 'fixture') + await writeFile(join(root, 'presets/test.env'), [ + 'DSH_DESKTOP_APP_ID=com.example.fixture', 'DSH_DESKTOP_AUTO_UPDATE_ENV=test', + 'DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN=https://policy.example.com', + 'DSH_DESKTOP_MANDATORY_UPDATE_CONFIG={"allowedAuthOrigins":["https://login.example.com"]}', + 'DOWNLOAD_TEST_ORIGIN=https://updates.example.com', 'DOWNLOAD_TEST_RELEASE_ID=0123456789abcdef0123456789abcdef', + ].join('\n')) + await writeFile(join(root, 'secrets/macos-signing.env'), [ + 'CSC_LINK=../certificate.p12', 'CSC_KEY_PASSWORD=fixture-password', + 'DSH_DESKTOP_MACOS_SIGNING_IDENTITY=Example Company (TEAMID1234)', 'DSH_DESKTOP_MACOS_TEAM_ID=TEAMID1234', + ].join('\n')) + const output = join(root, 'output') + const summary = join(root, 'summary') + const run = (skip: string) => spawnSync(process.execPath, + [join(import.meta.dirname, '../scripts/prepare-macos-ci.mjs')], { encoding: 'utf8', env: { + ...process.env, DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test', + PACKAGE_SKIP_NOTARIZATION: skip, PACKAGE_BUILD_VERSION: 'auto', + GITHUB_RUN_NUMBER: '1', GITHUB_RUN_ATTEMPT: '1', GITHUB_OUTPUT: output, GITHUB_STEP_SUMMARY: summary, + } }) + const missingCredentials = run('false') + expect(missingCredentials.status).toBe(1) + expect(missingCredentials.stderr).toContain('macOS packaging requires APPLE_API_KEY') + const invalidSelection = run('yes') + expect(invalidSelection.status).toBe(1) + expect(invalidSelection.stderr).toContain('Invalid skip notarization selection') + const debugging = run('true') + expect(debugging.stderr).toBe('') + expect(debugging.status).toBe(0) + expect(await readFile(output, 'utf8')).toContain('artifacts=unnotarized-artifacts\nmode=unnotarized-debug\n') + expect(await readFile(summary, 'utf8')).toContain('Internal debugging only') + } finally { + await rm(root, { recursive: true, force: true }) + } +}) 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/macos-signature-cache-directory.spec.ts b/apps/desktop/tests/macos-signature-cache-directory.spec.ts new file mode 100644 index 0000000000..adefc7a060 --- /dev/null +++ b/apps/desktop/tests/macos-signature-cache-directory.spec.ts @@ -0,0 +1,63 @@ +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { resolveMacOSSignatureCacheDirectory, validateMacOSSignatureCacheDirectory } from '../scripts/macos-signature-cache-directory.mjs' +import { cachedMacOSSignature } from '../scripts/macos-signature-cache.ts' + +const roots: string[] = [] +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) +function fixture(): string { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'mac-cache-directory-'))) + roots.push(root) + return root +} + +it('retains target-local storage only when the setting is absent', () => { + expect(resolveMacOSSignatureCacheDirectory({}, '/build/mac-arm64')).toBe(join('/build/mac-arm64', 'signature-cache')) + for (const path of ['', 'relative/cache', '~/ci/cache', '/cache\0invalid']) { + expect(() => resolveMacOSSignatureCacheDirectory({ DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR: path }, '/build')).toThrow(/absolute directory/u) + } +}) + +// Machine storage requires POSIX ownership and permissions, which Windows cannot represent. +describe.skipIf(process.platform === 'win32')('private external macOS storage', () => { + it('rejects missing, non-directory, linked and non-private storage without repairing it', () => { + const root = fixture() + expect(() => validateMacOSSignatureCacheDirectory(join(root, 'absent'))).toThrow(/ENOENT/u) + const file = join(root, 'file') + writeFileSync(file, '') + expect(() => validateMacOSSignatureCacheDirectory(file)).toThrow(/unlinked directory/u) + const cache = join(root, 'cache') + mkdirSync(cache, { mode: 0o700 }) + const link = join(root, 'link') + symlinkSync(root, link) + expect(() => validateMacOSSignatureCacheDirectory(join(link, 'cache'))).toThrow(/unlinked directory/u) + for (const mode of [0o755, 0o500]) { + chmodSync(cache, mode) + expect(() => validateMacOSSignatureCacheDirectory(cache)).toThrow(/private, accessible/u) + } + chmodSync(cache, 0o700) + expect(validateMacOSSignatureCacheDirectory(cache)).toBe(cache) + }) + + it('restores a verified signature after removing and recreating the checkout', async () => { + const root = fixture() + const cache = join(root, 'machine-cache') + mkdirSync(cache, { mode: 0o700 }) + const checkout = join(root, 'checkout') + const sign = vi.fn(async (path: string) => { writeFileSync(path, 'signed bytes') }) + const verify = vi.fn((path: string) => { expect(readFileSync(path, 'utf8')).toBe('signed bytes') }) + for (const hit of [false, true]) { + mkdirSync(checkout) + const file = join(checkout, 'runtime') + writeFileSync(file, 'unsigned bytes', { mode: 0o755 }) + const selected = resolveMacOSSignatureCacheDirectory({ DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR: cache }, checkout) + expect(await cachedMacOSSignature(file, selected, { policy: 'same certificate and tools', sign, verify })).toBe(hit) + expect(readFileSync(file, 'utf8')).toBe('signed bytes') + rmSync(checkout, { recursive: true }) + } + expect(sign).toHaveBeenCalledTimes(1) + expect(verify).toHaveBeenCalledTimes(2) + }) +}) diff --git a/apps/desktop/tests/macos-signature.spec.ts b/apps/desktop/tests/macos-signature.spec.ts index d39ee99cb9..0d9f486bdd 100644 --- a/apps/desktop/tests/macos-signature.spec.ts +++ b/apps/desktop/tests/macos-signature.spec.ts @@ -1,5 +1,6 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' import type { NotarizeOptions } from '@electron/notarize' import { resolveDesktopAppId, @@ -12,6 +13,11 @@ import { assertMacOSSignatureDetails, } from '../scripts/verify-macos-signature.mjs' +const require = createRequire(import.meta.url) +const { validateConfiguration } = require('app-builder-lib/out/util/config/config.js') as { + validateConfiguration: (config: object, logger: { isEnabled: false }) => Promise +} + const RELEASE_ENVIRONMENT = { DSH_DESKTOP_APP_ID: 'com.example.desktop', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', @@ -75,6 +81,7 @@ describe('desktop macOS release signature', () => { signIgnore: ['/Contents/Resources/app\\.asar\\.unpacked/dsh(?:/|$)', '/Contents/Resources/runtime/primary-runtime(?:/|$)', '\\.pak$'], }, dmg: { + format: 'ULMO', sign: true, writeUpdateInfo: false, }, @@ -87,15 +94,32 @@ describe('desktop macOS release signature', () => { expect(typeof config.artifactBuildCompleted).toBe('function') }) + it('accepts LZMA DMGs through builder validation while rejecting unknown formats', async () => { + const { createElectronBuilderConfig } = await import('../scripts/electron-builder-config.mjs') + for (const arch of ['arm64', 'x64']) { + for (const unsigned of ['0', '1']) { + const config = createElectronBuilderConfig({ + ...RELEASE_ENVIRONMENT, + DSH_DESKTOP_TARGET_ARCH: arch, + DSH_DESKTOP_UNSIGNED: unsigned, + }, 'darwin', arch) + expect(config.dmg.format).toBe('ULMO') + await expect(validateConfiguration(config, { isEnabled: false })).resolves.toBeUndefined() + } + } + await expect(validateConfiguration({ dmg: { format: 'invalid' } }, { isEnabled: false })) + .rejects.toThrow('configuration.dmg.format') + }) + it('seals PAK resources with their enclosing bundle while signing executable code', async () => { const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs') const config = createElectronBuilderConfig(RELEASE_ENVIRONMENT, 'darwin', 'arm64') const ignored = (path: string): boolean => config.mac.signIgnore.some(pattern => new RegExp(pattern).test(path)) expect(ignored('/App.app/Contents/Frameworks/Electron.framework/Versions/A/Resources/en.lproj/locale.pak')).toBe(true) expect(ignored('/App.app/Contents/Frameworks/Electron.framework/Versions/A/Resources/resources.pak')).toBe(true) + expect(ignored('/App.app/Contents/Resources/runtime/primary-runtime/dependencies/pnpm/addon.node')).toBe(true) for (const path of [ '/App.app/Contents/Resources/runtime/node/node', - '/App.app/Contents/Resources/runtime/pnpm/addon.node', '/App.app/Contents/Frameworks/Electron.framework/Versions/A/library.dylib', '/App.app/Contents/Frameworks/Electron.framework', '/App.app', @@ -255,3 +279,19 @@ describe('desktop macOS release signature', () => { expect(verified).toEqual(['/tmp/release.dmg']) }) }) + +it('signs debugging artifacts without Apple credentials and isolates them from releases', async () => { + const { createElectronBuilderConfig } = await import('../scripts/electron-builder-config.mjs') + const config = createElectronBuilderConfig({ ...RELEASE_ENVIRONMENT, + APPLE_API_KEY: undefined, APPLE_API_KEY_ID: undefined, APPLE_API_ISSUER: undefined, + DSH_DESKTOP_MACOS_SKIP_NOTARIZATION: '1', + }, 'darwin', 'arm64') + expect(config.mac.forceCodeSigning).toBe(true) + expect(config.mac.notarize).toBe(false) + expect(config.dmg.sign).toBe(true) + expect(config.mac).toMatchObject({ target: ['dmg', 'zip'] }) + expect(config.artifactName).toContain('-unnotarized.') + expect(portablePath(config.directories.output)).toContain('/unnotarized-artifacts') + expect(() => createElectronBuilderConfig({ ...RELEASE_ENVIRONMENT, DSH_DESKTOP_MACOS_SKIP_NOTARIZATION: 'yes' }, 'darwin', 'arm64')).toThrow(/must be 0 or 1/u) + expect(() => createElectronBuilderConfig({ ...RELEASE_ENVIRONMENT, DSH_DESKTOP_MACOS_SKIP_NOTARIZATION: '1', DSH_DESKTOP_UNSIGNED: '1' }, 'darwin', 'arm64')).toThrow(/requires a signed macOS build/u) +}) diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index b6b6fd476f..d9a8f3103b 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -3,7 +3,7 @@ import { WINDOWS_TITLEBAR_HEIGHT } from '../src/windows-layout.ts' import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import type { IpcMainInvokeEvent } from 'electron' import { join } from 'node:path' -import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs' +import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import type { MenuItemConstructorOptions, MessageBoxOptions } from 'electron' import { DESKTOP_IPC, type DesktopUpdateState } from '../src/ipc.ts' @@ -371,6 +371,12 @@ vi.mock('../src/welcome-backend.ts', () => ({ }), })) +function configureTestAuthPopup(allow: boolean): void { + const directory = join(harness.app.getPath('userData'), 'desktop') + mkdirSync(directory, { recursive: true }) + writeFileSync(join(directory, 'settings.json'), JSON.stringify({ updates: { allowTestAuthPopupWindow: allow } })) +} + function invoke(channel: string, origin = channel === DESKTOP_IPC.boot ? 'app' : 'shell', ...args: unknown[]): unknown { const handler = harness.handlers.get(channel) if (handler === undefined) throw new Error(`missing handler ${channel}`) @@ -437,6 +443,34 @@ afterEach(async () => { }) describe('desktop main startup', () => { + it.each([true, false])('selects the package manager before Host startup (packaged=%s)', async (packaged) => { + harness.app.isPackaged = packaged + await readyForUpdate() + const host = harness.hosts[0]! + expect(host.node).toBe(process.execPath) + expect(host.primaryRuntime).toBe(packaged + ? join('desktop-test-resources', 'runtime', 'primary-runtime') : 'test-primary-runtime') + expect(host.packageManager).toMatchObject({ + pnpm: packaged + ? join('desktop-test-resources', 'runtime', 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs') + : 'test-pnpm', + nodeBin: packaged ? join('desktop-test-resources', 'runtime', 'bin') : join('desktop-test-app', 'scripts', 'node-bin'), + }) + }) + + it('starts the Host with authentication popups disabled when local settings are invalid', async () => { + configureTestAuthPopup(false) + const path = join(harness.app.getPath('userData'), 'desktop', 'settings.json') + const raw = '{"updates":{"allowTestAuthPopupWindow":"true"}}' + writeFileSync(path, raw) + await readyForUpdate() + expect(harness.hosts).toHaveLength(1) + expect(testAuth.login).not.toHaveBeenCalled() + expect(console.warn).toHaveBeenCalledWith(expect.stringContaining(path), expect.any(Error)) + expect(harness.dialog.showMessageBox).not.toHaveBeenCalledWith(expect.objectContaining({ title: en.startupFailed })) + expect(readFileSync(path, 'utf8')).toBe(raw) + }) + it('routes shell update documents and assets through the registered main protocol handler', async () => { const root = join(import.meta.dirname, '..') vi.spyOn(harness.app, 'getAppPath').mockReturnValue(root) @@ -531,7 +565,98 @@ describe('desktop main startup', () => { expect(console.error).toHaveBeenLastCalledWith(expect.objectContaining({ message: 'overlay unavailable' })) }) + it.each(['missing-file', 'missing-field', 'disabled'] as const)('suppresses every test auth dialog for %s while continuing update checks', async (configuration) => { + if (configuration === 'disabled') configureTestAuthPopup(false) + if (configuration === 'missing-field') { + configureTestAuthPopup(true) + writeFileSync(join(harness.app.getPath('userData'), 'desktop', 'settings.json'), '{}') + } + harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], + allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 1000, jitter: 0 } + const request = vi.fn().mockImplementation(async () => + Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 })) + vi.stubGlobal('fetch', request) + await readyForUpdate() + await vi.advanceTimersByTimeAsync(0) + expect(harness.dialog.showMessageBox).not.toHaveBeenCalled() + expect(request).toHaveBeenCalledWith(expect.any(URL), expect.objectContaining({ credentials: 'include', redirect: 'error' })) + // Editing the file cannot change the consent policy of an already running process. + configureTestAuthPopup(true) + harness.dialog.showMessageBox.mockResolvedValue({ response: 0 }) + await invoke(DESKTOP_IPC.updatesOpen, 'app') + harness.powerMonitor.emit('resume') + await vi.advanceTimersByTimeAsync(10_000) + expect(request.mock.calls.length).toBeGreaterThan(2) + expect(testAuth.login).not.toHaveBeenCalled() + expect(testAuth.focus).not.toHaveBeenCalled() + const messages = harness.dialog.showMessageBox.mock.calls.map(call => (call.at(-1) as { message: string }).message) + const expected = JSON.parse(readFileSync(new URL('./expected/policy-login-en.json', import.meta.url), 'utf8')) as Record + expect(messages).toEqual(expected.disabled) + expect(harness.updateDownload).not.toHaveBeenCalled() + }) + + it('checks updates from the application menu without offering disabled test authentication', async () => { + configureTestAuthPopup(false) + harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', + allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'] } + const request = vi.fn().mockImplementation(async () => + Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 })) + vi.stubGlobal('fetch', request) + await readyForUpdate() + await vi.advanceTimersByTimeAsync(0) + request.mockClear() + harness.updateCheck.mockClear() + const checkUpdates = applicationMenuItems().find(item => item.label === en.checkUpdatesMenu)!.click as () => void + checkUpdates() + await vi.advanceTimersByTimeAsync(10_000) + expect(request).toHaveBeenCalled() + expect(harness.updateCheck).toHaveBeenCalledWith(true) + expect(testAuth.login).not.toHaveBeenCalled() + expect(harness.dialog.showMessageBox.mock.calls.map(call => (call.at(-1) as { message: string }).message)) + .not.toContain(en.policyLoginRequired) + }) + + it.each([false, true])('retains anonymous production checks with popup permission %s', async (allow) => { + configureTestAuthPopup(allow) + harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'anonymous', + allowedPageOrigins: ['https://downloads.example.com'] } + const request = vi.fn().mockImplementation(async () => + Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 })) + vi.stubGlobal('fetch', request) + await readyForUpdate() + await invoke(DESKTOP_IPC.updatesOpen, 'app') + expect(request).toHaveBeenCalledWith(expect.any(URL), expect.objectContaining({ credentials: 'omit' })) + expect(testAuth.login).not.toHaveBeenCalled() + expect(harness.dialog.showMessageBox.mock.calls.map(call => (call.at(-1) as { message: string }).message)) + .not.toContain(en.policyLoginRequired) + }) + + it('keeps a received mandatory decision when test cookies expire with popups disabled', async () => { + configureTestAuthPopup(false) + harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], + allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 1000, jitter: 0 } + const request = vi.fn().mockImplementation(async () => + Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 })) + .mockResolvedValueOnce(Response.json({ code: 40005, data: { show_content: { title: 'Update', detail: 'Required' }, + desktop_app_link: 'https://downloads.example.com/' } })) + vi.stubGlobal('fetch', request) + const host = await readyForUpdate() + await harness.policyBlocked.promise + await vi.advanceTimersByTimeAsync(1000) + const modal = harness.windows[0]! + const owned = { sender: modal.webContents, senderFrame: modal.webContents.mainFrame } + await harness.handlers.get(MANDATORY_IPC.action)!(owned, 'refresh') + expect(harness.handlers.get(MANDATORY_IPC.status)!(owned)).toMatchObject({ + policy: { blocking: true, error: 'authentication-required' }, + }) + expect(testAuth.login).not.toHaveBeenCalled() + expect(harness.dialog.showMessageBox).not.toHaveBeenCalled() + expect(modal.isDestroyed()).toBe(false) + expect(host.stop).not.toHaveBeenCalled() + }) + it('shows one explained startup login before Host readiness and joins concurrent checks without reopening it', async () => { + configureTestAuthPopup(true) harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 1000, jitter: 0 } vi.stubGlobal('fetch', vi.fn().mockImplementation(async () => @@ -575,6 +700,7 @@ describe('desktop main startup', () => { }) it.each(['returned', 'cancelled', 'failed'] as const)('requires explicit test login and handles %s without downloading', async (outcome) => { + configureTestAuthPopup(true) harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 10_000, jitter: 0 } const request = vi.fn().mockImplementation(async () => Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 })) @@ -602,6 +728,7 @@ describe('desktop main startup', () => { }) it('does not open Feishu when the user declines test login', async () => { + configureTestAuthPopup(true) harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'] } vi.stubGlobal('fetch', vi.fn().mockImplementation(async () => Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 }))) @@ -625,6 +752,7 @@ describe('desktop main startup', () => { }) it('retains the embedded block and running Host after expired test login is cancelled', async () => { + configureTestAuthPopup(true) harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 1000, jitter: 0 } const request = vi.fn().mockImplementation(async () => @@ -906,11 +1034,12 @@ describe('desktop main startup', () => { } finally { harness.app.name = originalName } }) - it('attaches Host socket credentials only to the owned application origin and window', async () => { + it.each(['http:', 'https:'] as const)('attaches %s Host socket credentials only to the owned application origin and window', async (protocol) => { await import('../src/main.ts') await harness.preparing.promise harness.prepared.resolve() await harness.hostStarted.promise + harness.hosts[0]!.url = `${protocol}//127.0.0.1:3080/?token=test` harness.hosts[0]!.ready.resolve() await Promise.resolve(invoke(DESKTOP_IPC.boot)) const handler = harness.socketHeaders.mock.calls[0]![1] as ( @@ -918,16 +1047,19 @@ describe('desktop main startup', () => { callback: (result: unknown) => void, ) => void const callback = vi.fn() - const details = { url: 'ws://127.0.0.1:3080/api/remote.mux', webContentsId: 42, requestHeaders: { Origin: 'dsh-app://app' } } + const socketProtocol = protocol === 'https:' ? 'wss:' : 'ws:' + const details = { url: `${socketProtocol}//127.0.0.1:3080/api/remote.mux`, webContentsId: 42, requestHeaders: { Origin: 'dsh-app://app' } } handler(details, callback) expect(callback).toHaveBeenLastCalledWith({ requestHeaders: { - origin: 'http://127.0.0.1:3080', cookie: 'test-cookie', 'sec-fetch-site': 'same-origin', + origin: `${protocol}//127.0.0.1:3080`, cookie: 'test-cookie', 'sec-fetch-site': 'same-origin', } }) handler({ ...details, requestHeaders: { Origin: 'https://other.example' } }, callback) expect(callback).toHaveBeenLastCalledWith({ cancel: true }) handler({ ...details, webContentsId: 43 }, callback) expect(callback).toHaveBeenLastCalledWith({}) - handler({ ...details, url: 'ws://127.0.0.1:9999/api/remote.mux' }, callback) + handler({ ...details, url: `${socketProtocol}//127.0.0.1:9999/api/remote.mux` }, callback) + expect(callback).toHaveBeenLastCalledWith({}) + handler({ ...details, url: `${socketProtocol === 'wss:' ? 'ws:' : 'wss:'}//127.0.0.1:3080/api/remote.mux` }, callback) expect(callback).toHaveBeenLastCalledWith({}) }) @@ -1557,7 +1689,8 @@ describe('desktop main startup', () => { } }) - it('queues policy authentication until the ordinary result dialog closes', async () => { + it.each([false, true])('handles a deferred authentication failure with popup permission %s', async (allow) => { + configureTestAuthPopup(allow) harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 10_000, jitter: 0 } const request = vi.fn() @@ -1583,7 +1716,10 @@ describe('desktop main startup', () => { .not.toContain(en.policyLoginRequired) ordinaryResult.resolve({ response: 0 }) await operation - await policyShown.promise + await vi.advanceTimersByTimeAsync(0) + if (allow) await policyShown.promise + else expect(harness.dialog.showMessageBox.mock.calls.map(call => (call.at(-1) as { message: string }).message)) + .not.toContain(en.policyLoginRequired) expect(testAuth.login).not.toHaveBeenCalled() }) diff --git a/apps/desktop/tests/mandatory-update-policy.spec.ts b/apps/desktop/tests/mandatory-update-policy.spec.ts index 84a584389b..a04353810d 100644 --- a/apps/desktop/tests/mandatory-update-policy.spec.ts +++ b/apps/desktop/tests/mandatory-update-policy.spec.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account/types' import { DesktopMandatoryUpdatePolicy, desktopPolicyPage, resolveDesktopPolicyConfig, type DesktopPolicyState } from '../src/mandatory-update-policy.ts' -const identity = { platform: 'win32', arch: 'x64', bundledDshVersion: '0.1.5-rc.1' } as const +const identity = { platform: 'win32', arch: 'x64', channel: 'nightly', bundledDshVersion: '0.1.5-rc.1' } as const const client: AccountClientMetadata = { version: '1.2.3', locale: 'zh-CN', timezoneOffsetSeconds: 28_800 } const force = { code: 40005, data: { show_content: { title: 'Update', detail: 'Required upgrade' }, desktop_app_link: 'https://downloads.example.com/desktop?os=win' } } diff --git a/apps/desktop/tests/package-target-stages.spec.ts b/apps/desktop/tests/package-target-stages.spec.ts index cde1b0079d..1d8b067390 100644 --- a/apps/desktop/tests/package-target-stages.spec.ts +++ b/apps/desktop/tests/package-target-stages.spec.ts @@ -197,3 +197,27 @@ it('does not write a release completion record when Apple proxy cleanup fails', .rejects.toThrow('proxy restoration failed') expect(writeFileSync).not.toHaveBeenCalled() }) + +it.each([false, true])('keeps signing and runtime verification when notarization is skipped (directory=%s)', async (directory) => { + const { run, stages } = supervisor() + await packageTarget(parseDesktopPackageInvocation(['mac-arm64', '--skip-notarization', ...(directory ? ['--dir'] : [])], 'darwin', 'arm64'), { + ...environment, CSC_LINK: 'signing.p12', CSC_KEY_PASSWORD: 'fixture-password', + }, run) + expect(stages.at(-2)).toBe(`exec electron-builder --config electron-builder.config.mjs --mac --arm64 --publish never${directory ? ' --dir' : ''}`) + expect(stages.at(-1)).toBe('exec tsx scripts/smoke-packaged-runtime.ts --skip-notarization') + expect(run.run.mock.calls.at(-2)![3].env).toMatchObject({ + DSH_DESKTOP_UNSIGNED: '0', DSH_DESKTOP_MACOS_SKIP_NOTARIZATION: '1', CSC_LINK: 'signing.p12', + }) + expect(withMacOSNotarizationProxy).not.toHaveBeenCalled() + expect(packageMacOSArtifacts).not.toHaveBeenCalled() + expect(writeFileSync).not.toHaveBeenCalled() +}) + +it('fails debugging packages when runtime verification fails', async () => { + const failure = 'exec tsx scripts/smoke-packaged-runtime.ts --skip-notarization' + const { run, stages } = supervisor(failure) + await expect(packageTarget(parseDesktopPackageInvocation(['mac-arm64', '--skip-notarization'], 'darwin', 'arm64'), environment, run)) + .rejects.toThrow('stage refused') + expect(stages.at(-1)).toBe(failure) + expect(writeFileSync).not.toHaveBeenCalled() +}) diff --git a/apps/desktop/tests/package-target.spec.ts b/apps/desktop/tests/package-target.spec.ts index 5019841e84..ba647d76ac 100644 --- a/apps/desktop/tests/package-target.spec.ts +++ b/apps/desktop/tests/package-target.spec.ts @@ -148,3 +148,12 @@ describe('desktop package target', () => { }) }) }) + +it('allows skipping notarization only for signed macOS packages', () => { + expect(parseDesktopPackageInvocation(['mac-arm64'], 'darwin', 'arm64').skipNotarization).toBe(false) + expect(parseDesktopPackageInvocation(['mac-arm64', '--skip-notarization'], 'darwin', 'arm64').skipNotarization).toBe(true) + for (const flag of ['--unsigned', '--prepare-only']) { + expect(() => parseDesktopPackageInvocation(['mac-arm64', '--skip-notarization', flag], 'darwin', 'arm64')).toThrow(/requires a signed macOS build/u) + } + expect(() => parseDesktopPackageInvocation(['win-x64', '--skip-notarization'], 'win32', 'x64')).toThrow(/requires a signed macOS build/u) +}) diff --git a/apps/desktop/tests/prepare-runtime-patches.spec.ts b/apps/desktop/tests/prepare-runtime-patches.spec.ts new file mode 100644 index 0000000000..84c71a1884 --- /dev/null +++ b/apps/desktop/tests/prepare-runtime-patches.spec.ts @@ -0,0 +1,140 @@ +import { execFile } from 'node:child_process' +import { createHash } from 'node:crypto' +import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { promisify } from 'node:util' +import { afterEach, expect, it } from 'vitest' +import yaml from 'js-yaml' +import { pnpmCommand } from '../../../scripts/release/process.ts' +import { prepareRuntimePatches, verifyRuntimePatches } from '../scripts/prepare-runtime-patches.ts' +import type { DesktopRuntimePatch } from '../scripts/runtime-patch-policy.ts' + +const roots: string[] = [] +const shared = { scope: 'shared', reason: 'Runtime fixture.' } as const +const excluded = { scope: 'workspace-only', reason: 'Build fixture.' } as const +const patch = 'diff --git a/value.txt b/value.txt\n--- a/value.txt\n+++ b/value.txt\n@@ -1 +1 @@\n-original\n+patched\n' +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }) +}) + +function fixture(): { root: string; source: string; project: string } { + const root = mkdtempSync(join(tmpdir(), 'desktop-patch-policy-')) + roots.push(root) + const source = join(root, 'source') + const project = join(root, 'project') + mkdirSync(source) + mkdirSync(project) + writeFileSync(join(source, 'shared.patch'), patch) + writeFileSync(join(source, 'private.patch'), patch.replace('+patched', '+private')) + writeFileSync(join(source, 'pnpm-workspace.yaml'), yaml.dump({ patchedDependencies: { 'fixture@1.0.0': 'shared.patch' } })) + writeFileSync(join(source, 'pnpm-lock.yaml'), yaml.dump({ + patchedDependencies: { 'fixture@1.0.0': createHash('sha256').update(patch).digest('hex') }, + })) + writeFileSync(join(project, 'pnpm-workspace.yaml'), yaml.dump({ + packages: ['.'], nodeLinker: 'hoisted', overrides: { internal: 'file:./internal.tgz' }, allowBuilds: { fixture: false }, + })) + return { root, source, project } +} + +it('classifies the current workspace and shares only runtime patch bytes', () => { + const { project } = fixture() + const repository = resolve(import.meta.dirname, '../../..') + const before = readFileSync(join(repository, 'pnpm-lock.yaml')) + const plan = prepareRuntimePatches(project, repository) + expect(plan.patches.map(entry => entry.spec)).toEqual(['@earendil-works/pi-ai@1.1.0', 'node-pty@1.2.0-beta.15']) + expect(plan.workspaceOnly).toHaveLength(6) + const settings = yaml.load(readFileSync(join(project, 'pnpm-workspace.yaml'), 'utf8')) as { overrides: Record } + expect(settings.overrides['@earendil-works/pi-ai']).toBeUndefined() + expect(settings.overrides['@earendil-works/pi-ai@^1.1.0']).toBe('1.1.0') + expect(readFileSync(join(repository, 'pnpm-lock.yaml'))).toEqual(before) +}) + +it('does not infer version overrides from selected patches', () => { + const { source, project } = fixture() + const before = readFileSync(join(source, 'pnpm-workspace.yaml')) + prepareRuntimePatches(project, source, { 'fixture@1.0.0': shared }, {}) + expect(yaml.load(readFileSync(join(project, 'pnpm-workspace.yaml'), 'utf8'))).toMatchObject({ + overrides: { internal: 'file:./internal.tgz' }, allowBuilds: { fixture: false }, + }) + expect(readFileSync(join(source, 'pnpm-workspace.yaml'))).toEqual(before) + expect(readFileSync(join(project, 'patches/desktop-0.patch'), 'utf8')).toBe(patch) +}) + +it('supports an independent runtime patch for a package also patched in the workspace', () => { + const { source, project } = fixture() + const plan = prepareRuntimePatches(project, source, { + 'fixture@1.0.0': { scope: 'runtime-only', path: 'private.patch', reason: 'Different runtime layout.' }, + 'other@2.0.0': { scope: 'runtime-only', path: 'private.patch', reason: 'Runtime-only dependency.' }, + }, {}) + expect(plan.patches).toHaveLength(2) + expect(readFileSync(join(project, plan.patches[0]!.path), 'utf8')).toContain('+private') + expect(readFileSync(join(source, 'shared.patch'), 'utf8')).toBe(patch) +}) + +it.each([ + { policy: {}, message: 'classify the workspace patch' }, + { policy: { 'fixture@1.0.0': shared, 'absent@1.0.0': shared }, message: 'stale workspace patch decision' }, + { policy: { 'fixture@1.0.0': { scope: 'runtime-only', path: '../outside.patch', reason: 'Invalid path.' } }, message: 'inside the repository' }, + { policy: { 'fixture@1.0.0': { scope: 'runtime-only', path: 'missing.patch', reason: 'Missing file.' } }, message: 'ENOENT' }, +] satisfies Array<{ policy: Record; message: string }>)('rejects invalid selection: $message', ({ policy, message }) => { + const { source, project } = fixture() + expect(() => { prepareRuntimePatches(project, source, policy, {}) }).toThrow(message) +}) + +it('rejects shared bytes that differ from the workspace lockfile', () => { + const { source, project } = fixture() + writeFileSync(join(source, 'shared.patch'), patch + '\n') + expect(() => { prepareRuntimePatches(project, source, { 'fixture@1.0.0': shared }, {}) }).toThrow('root lockfile') +}) + +it('refuses to write to the workspace or replace an unrelated existing override', () => { + const { source, project } = fixture() + expect(() => { prepareRuntimePatches(source, source, { 'fixture@1.0.0': shared }, {}) }).toThrow('source workspace') + expect(() => { prepareRuntimePatches(project, source, { 'fixture@1.0.0': shared }, { internal: '2.0.0' }) }).toThrow('conflicting') +}) + +it.each(['version', 'lock hash', 'file bytes', 'workspace-only', 'unused'] as const)('rejects invalid resolved installation: %s', (failure) => { + const { source, project } = fixture() + const plan = prepareRuntimePatches(project, source, { 'fixture@1.0.0': failure === 'workspace-only' ? excluded : shared }, {}) + writeFileSync(join(project, 'pnpm-lock.yaml'), yaml.dump({ + patchedDependencies: Object.fromEntries(plan.patches.map(entry => [entry.spec, failure === 'lock hash' ? 'wrong' : entry.hash])), + packages: failure === 'unused' ? {} : { [failure === 'version' ? 'fixture@1.0.1' : 'fixture@1.0.0']: {} }, + })) + if (failure === 'file bytes') writeFileSync(join(project, plan.patches[0]!.path), 'changed') + expect(() => { verifyRuntimePatches(project, plan) }).toThrow(/desktop patches:/u) +}) + +it.each([false, true])('pnpm applies runtime-only bytes and rejects an inapplicable patch (invalid=%s)', async (invalid) => { + const { source, project, root } = fixture() + const packageDir = join(root, 'package') + mkdirSync(packageDir) + writeFileSync(join(packageDir, 'package.json'), JSON.stringify({ name: 'fixture', version: '1.0.0' })) + writeFileSync(join(packageDir, 'value.txt'), 'original\n') + const run = promisify(execFile) + const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => ( + /^(?:path|systemroot|windir|comspec|temp|tmp)$/iu.test(name) + ))) + await run('tar', ['-czf', 'fixture.tgz', '-C', root, 'package'], { cwd: project, env, timeout: 15_000, windowsHide: true }) + writeFileSync(join(project, 'package.json'), JSON.stringify({ private: true, dependencies: { fixture: 'file:./fixture.tgz' } })) + writeFileSync(join(project, 'npmrc'), '') + if (invalid) writeFileSync(join(source, 'private.patch'), patch.replace('-original', '-does-not-exist')) + const plan = prepareRuntimePatches(project, source, { + 'fixture@1.0.0': { scope: 'runtime-only', path: 'private.patch', reason: 'Offline install fixture.' }, + }, {}) + const [command, ...args] = pnpmCommand() + const install = run(command, [...args, 'install', '--offline', '--ignore-scripts', + `--config.userconfig=${join(project, 'npmrc')}`, `--config.store-dir=${join(project, 'store')}`, + '--config.manage-package-manager-versions=false'], { cwd: project, env: { ...env, CI: 'true' }, timeout: 30_000, windowsHide: true }) + if (invalid) { + const failure: unknown = await install.catch((error: unknown) => error) + if (!(failure instanceof Error) || !('stdout' in failure)) throw new Error('Expected a captured pnpm failure') + expect(failure).toHaveProperty('code', 1) + expect(failure.stdout).toMatch(/PATCH_FAILED/u) + } else { + await install + verifyRuntimePatches(project, plan) + expect(readFileSync(join(project, 'node_modules/fixture/value.txt'), 'utf8')).toBe('private\n') + } + expect(existsSync(join(source, 'node_modules'))).toBe(false) +}, 45_000) diff --git a/apps/desktop/tests/prepare-windows-ci.spec.ts b/apps/desktop/tests/prepare-windows-ci.spec.ts new file mode 100644 index 0000000000..f445682467 --- /dev/null +++ b/apps/desktop/tests/prepare-windows-ci.spec.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import { windowsCiVersion } from '../scripts/prepare-windows-ci.mjs' + +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 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.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.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([{ 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) + }) +}) + + +it('resolves the selected version policy independently of the update channel', () => { + expect(windowsCiVersion({ ...inputs, PACKAGE_VERSION_MODE: 'default', DSH_PACKAGING_PRESET: 'production' }, '1.2.3', now)).toBe('1.2.3') + expect(windowsCiVersion({ ...inputs, PACKAGE_VERSION_MODE: 'default', DSH_PACKAGING_PRESET: 'test' }, '1.2.3', now)).toBe('1.2.3-test.20261009.42.2') + expect(windowsCiVersion({ PACKAGE_VERSION_MODE: 'product' }, '1.2.3-alpha.1', now)).toBe('1.2.3-alpha.1') + expect(() => windowsCiVersion({ PACKAGE_VERSION_MODE: 'manual', PACKAGE_BUILD_VERSION: 'auto' }, '1.2.3', now)).toThrow(/explicit version/u) + expect(() => windowsCiVersion({ PACKAGE_VERSION_MODE: 'invalid' }, '1.2.3', now)).toThrow(/version mode/u) +}) diff --git a/apps/desktop/tests/prepared-runtime-smoke.spec.ts b/apps/desktop/tests/prepared-runtime-smoke.spec.ts index 2a2644719e..c4c840c009 100644 --- a/apps/desktop/tests/prepared-runtime-smoke.spec.ts +++ b/apps/desktop/tests/prepared-runtime-smoke.spec.ts @@ -21,6 +21,27 @@ afterEach(() => { Object.defineProperty(process, 'arch', hostArch) for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) vi.clearAllMocks() + vi.restoreAllMocks() +}) + +it('retains payload progress and termination details when the child fails', async () => { + const root = mkdtempSync(join(tmpdir(), 'prepared-runtime-failure-')) + roots.push(root) + const fixture = runtimeFixture(root) + const target = { platform: 'win32' as const, arch: 'x64' } + writeDesktopRuntime(root, fixture.release, fixture.sharedPackages.map(entry => entry.name), target) + const descriptor = await verifyDesktopRuntime(root, fixture.release.version, target) + const failure = Object.assign(new Error('payload timed out'), { + stdout: 'payload output\n', stderr: 'runtime payload: pty\n', killed: true, signal: 'SIGTERM', + }) + payload.mockRejectedValueOnce(failure) + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + await expect(smokePreparedRuntime(root, join(root, 'electron'), join(root, 'runtime'), descriptor)).rejects.toBe(failure) + expect(stdout).toHaveBeenCalledWith('payload output\n') + expect(stderr).toHaveBeenCalledWith('runtime payload: pty\n') + expect(stderr).toHaveBeenCalledWith('runtime payload: killed=true, signal=SIGTERM\n') + expect(smokeDesktopRuntime).not.toHaveBeenCalled() }) it('smokes an x64 target verified on an arm64 build host without revalidating against the host', async () => { diff --git a/apps/desktop/tests/ptc-runtime.spec.ts b/apps/desktop/tests/ptc-runtime.spec.ts index 757bfe95b2..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, { nodeExecutable: 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/read-desktop-app-key.spec.ts b/apps/desktop/tests/read-desktop-app-key.spec.ts new file mode 100644 index 0000000000..4b67345f7e --- /dev/null +++ b/apps/desktop/tests/read-desktop-app-key.spec.ts @@ -0,0 +1,26 @@ +import { execFile } from 'node:child_process' +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' +import { expect, it } from 'vitest' + +it('masks multiline key bytes and passes the exact fixture to the token action without a shell', async () => { + const root = await mkdtemp(join(tmpdir(), 'desktop-app-key-')) + try { + const path = join(root, 'fixture.pem') + const output = join(root, 'output') + const key = 'fixture%key\r\nsecond-line\n' + await writeFile(path, key) + const result = await promisify(execFile)(process.execPath, + [fileURLToPath(new URL('../scripts/read-desktop-app-key.mjs', import.meta.url))], { + env: { ...process.env, APP_KEY_FILE: path, GITHUB_OUTPUT: output }, encoding: 'utf8', + }) + expect(result.stdout).toBe('::add-mask::fixture%25key%0D%0Asecond-line%0A\n') + expect(result.stderr).toBe('') + const contents = await readFile(output, 'utf8') + const delimiter = contents.slice('private-key<<'.length, contents.indexOf('\n')) + expect(contents).toBe(`private-key<<${delimiter}\n${key}\n${delimiter}\n`) + } finally { await rm(root, { recursive: true, force: true }) } +}) diff --git a/apps/desktop/tests/retain-desktop-ci.spec.ts b/apps/desktop/tests/retain-desktop-ci.spec.ts new file mode 100644 index 0000000000..0fb2b14bc5 --- /dev/null +++ b/apps/desktop/tests/retain-desktop-ci.spec.ts @@ -0,0 +1,37 @@ +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { desktopReleasesRoot, retainDesktopCi } from '../scripts/retain-desktop-ci.ts' +import { verifyRetainedDesktopRelease } from '../scripts/desktop-release-store.ts' + +const roots: string[] = [] +afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) }) + +it.each(['mac-arm64', 'win-x64'] as const)('retains the complete %s release without signing or upload credentials', async (target) => { + const root = await mkdtemp(join(tmpdir(), 'retain-ci-')) + roots.push(root) + const appRoot = join(root, 'checkout') + const config = join(root, 'packaging') + const artifacts = join(appRoot, '.desktop-build', 'targets', target, 'artifacts') + await mkdir(artifacts, { recursive: true }) + await mkdir(join(config, 'presets'), { recursive: true }) + await writeFile(join(appRoot, 'package.json'), '{"version":"1.0.0"}') + await writeFile(join(config, 'presets/test.env'), `DSH_DESKTOP_AUTO_UPDATE_ENV=test\nDOWNLOAD_TEST_RELEASE_ID=${'a'.repeat(32)}\n`) + const names = target === 'win-x64' + ? ['deepseek-harness-1.0.0-win-x64.exe', 'deepseek-harness-1.0.0-win-x64.exe.blockmap', 'win-x64-release.json', 'nightly.yml'] + : ['deepseek-harness-1.0.0-mac-arm64.dmg', 'deepseek-harness-1.0.0-mac-arm64.zip', 'deepseek-harness-1.0.0-mac-arm64.zip.blockmap', 'mac-arm64-release.json', 'nightly-mac.yml'] + await Promise.all(names.map(name => writeFile(join(artifacts, name), 'fixture'))) + const env = { + DSH_PACKAGING_CONFIG_DIR: config, DSH_PACKAGING_PRESET: 'test', DSH_DESKTOP_TARGET_PLATFORM: target === 'win-x64' ? 'win32' : 'darwin', + DSH_DESKTOP_TARGET_ARCH: target === 'win-x64' ? 'x64' : 'arm64', PACKAGE_SOURCE_REF: 'master', PACKAGE_SOURCE_SHA: 'b'.repeat(40), PACKAGE_VERSION: '1.0.0', PACKAGE_PUBLISH: 'true', + PACKAGE_SIGNING: 'signed', PACKAGE_SKIP_NOTARIZATION: 'false', GITHUB_RUN_ID: '123', GITHUB_RUN_ATTEMPT: '2', + GITHUB_REPOSITORY: 'owner/repository', GITHUB_SHA: 'b'.repeat(40), RUNNER_NAME: 'dedicated', + } + await retainDesktopCi(env, appRoot) + const manifest = await verifyRetainedDesktopRelease(desktopReleasesRoot(env), '123', '2') + expect(manifest.files.map(file => file.name)).toEqual(names) + expect(manifest.source).toMatchObject({ target, publishRequested: true, qualification: target === 'win-x64' ? 'signed' : 'notarized' }) + await expect(retainDesktopCi({ ...env, PACKAGE_SIGNING: 'unsigned', PACKAGE_SKIP_NOTARIZATION: 'true' }, appRoot)) + .rejects.toThrow(/publishing requires/u) +}) diff --git a/apps/desktop/tests/runtime-file-policy.spec.ts b/apps/desktop/tests/runtime-file-policy.spec.ts index c113783e55..e1d8cc2e1c 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', '@deepseek-ai/dsh/src/bin.ts', '@deepseek-ai/dsh/docs/architecture.md', @@ -48,6 +50,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', @@ -78,6 +82,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() @@ -90,6 +96,62 @@ it('retains native prebuilds for the selected macOS architecture', () => { expect(desktopRuntimeFileExclusion('node-pty/prebuilds/win32-x64/conpty.node', mac, 'darwin-arm64')).toBeDefined() }) +it.each([ + ['darwin', 'arm64'], ['darwin', 'x64'], + ['linux', 'arm64'], ['linux', 'x64'], + ['win32', 'arm64'], ['win32', 'x64'], +] as const)('copies ConPTY sources only for Windows targets (%s/%s)', (platform, arch) => { + const root = mkdtempSync(join(tmpdir(), 'desktop-conpty-policy-')) + try { + const source = join(root, 'source') + const output = join(root, 'output') + const prefixes = ['', '@example/outer/node_modules/'] + const conpty = ['arm64', 'x64'].flatMap(cpu => ['conpty.dll', 'OpenConsole.exe'].map( + file => `node-pty/third_party/conpty/1.25.260303002/win10-${cpu}/${file}`, + )) + const native = platform === 'win32' + ? ['conpty.node', 'conpty_console_list.node', 'conpty/conpty.dll', 'conpty/OpenConsole.exe'] + : ['pty.node', 'spawn-helper'] + const retained = [ + ...native.map(file => `node-pty/prebuilds/${platform}-${arch}/${file}`), + ...native.map(file => `node-pty/build/Release/${file}`), + 'node-pty/lib/index.js', 'node-pty/LICENSE', + 'node-pty/third_party/conpty-notes/README.md', 'node-pty/third_party/conpty.dll', + 'other/third_party/conpty/conpty.dll', + ] + for (const prefix of prefixes) { + for (const path of [...conpty, ...retained]) { + mkdirSync(join(source, prefix, path, '..'), { recursive: true }) + writeFileSync(join(source, prefix, path), `payload:${prefix}${path}`) + } + } + cpSync(source, output, { + recursive: true, dereference: true, + filter: (path) => { + const entry = relative(source, path) + return desktopRuntimeFileExclusion( + platform === 'win32' ? entry.replaceAll('/', '\\') : entry, + { platform, arch }, `${platform}-${arch}`, + ) === undefined + }, + }) + for (const prefix of prefixes) { + expect(existsSync(join(output, prefix, 'node-pty/third_party/conpty'))).toBe(platform === 'win32') + for (const path of conpty) { + expect(existsSync(join(output, prefix, path)), `${prefix}${path}`).toBe(platform === 'win32') + } + for (const path of [...retained, ...(platform === 'win32' ? conpty : [])]) { + expect(readFileSync(join(output, prefix, path), 'utf8')).toBe(`payload:${prefix}${path}`) + } + for (const path of conpty) { + expect(readFileSync(join(source, prefix, path), 'utf8')).toBe(`payload:${prefix}${path}`) + } + } + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + it.each([ ['linux', 'x64', 'linux-x64'], ['linux', 'arm64', 'wasm'], diff --git a/apps/desktop/tests/runtime-preparation.spec.ts b/apps/desktop/tests/runtime-preparation.spec.ts new file mode 100644 index 0000000000..d16dd592c2 --- /dev/null +++ b/apps/desktop/tests/runtime-preparation.spec.ts @@ -0,0 +1,120 @@ +/** Desktop resource preparation publishes versions only for complete resources. */ + +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' + +const state = vi.hoisted(() => ({ + root: '', + target: 'mac-arm64' as 'mac-arm64' | 'mac-x64' | 'win-x64', + pnpm: '11.7.0' as string | undefined, + failure: undefined as 'electron' | 'primary' | 'cli' | undefined, + preparePrimary: vi.fn(), + commandLink: vi.fn(), +})) +vi.mock('../scripts/desktop-build-paths.mjs', async importOriginal => ({ + ...await importOriginal(), + resolveDesktopBuildTarget: () => state.target, + resolveDesktopTargetBuildPaths: () => ({ + runtime: join(state.root, 'runtime'), electron: join(state.root, 'electron'), downloads: join(state.root, 'downloads'), + }), +})) +vi.mock('@electron/get', () => ({ downloadArtifact: async () => 'electron.zip' })) +vi.mock('extract-zip', () => ({ default: async () => { + if (state.failure === 'electron') throw new Error('Electron extraction failed') +} })) +vi.mock('node:child_process', async importOriginal => ({ + ...await importOriginal(), + execFileSync: (file: string) => file === '/usr/libexec/PlistBuddy' ? '12.0\n' : '24.18.1\n', +})) +vi.mock('../scripts/prepare-command-link.ts', () => ({ prepareCommandLink: state.commandLink })) +// The compiled command manager is a build input; all source resource copies use real files. +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, cpSync: (...args: Parameters) => { + if (String(args[0]).endsWith(join('lib', 'command-manager-entry.js'))) { + if (state.failure === 'cli') throw new Error('command manager copy failed') + actual.writeFileSync(args[1], 'command manager fixture') + } else actual.cpSync(...args) + } } +}) +vi.mock('../scripts/prepare-primary-runtime.ts', () => ({ + preparePrimaryRuntime: state.preparePrimary, +})) + +const originalArgv = process.argv +beforeEach(() => { + vi.resetModules() + vi.clearAllMocks() + state.root = mkdtempSync(join(tmpdir(), 'desktop-runtime-preparation-')) + state.target = 'mac-arm64' + state.pnpm = '11.7.0' + state.failure = undefined + process.argv = [process.execPath, 'prepare-runtime.ts'] + vi.stubEnv('DSH_DESKTOP_PACKAGING_RUN_DIR', undefined) + state.preparePrimary.mockImplementation(async () => { + if (state.failure === 'primary') throw new Error('primary preparation failed') + const root = join(state.root, 'runtime', 'primary-runtime') + const pnpm = join(root, 'dependencies', 'pnpm', 'bin') + mkdirSync(pnpm, { recursive: true }) + writeFileSync(join(pnpm, 'pnpm.mjs'), '') + writeFileSync(join(root, 'runtime.json'), JSON.stringify({ + desktopVersion: '1.0.0', platform: state.target === 'win-x64' ? 'win32' : 'darwin', + arch: state.target === 'mac-arm64' ? 'arm64' : 'x64', + python: '3.12.14', node: '24.17.0', pnpm: state.pnpm, pythonPackages: { numpy: '2.3.5' }, + })) + }) +}) + +afterEach(async () => { + process.argv = originalArgv + vi.unstubAllEnvs() + await rm(state.root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 }) +}) + +it.each(['mac-arm64', 'mac-x64', 'win-x64'] as const)('prepares %s with one pnpm distribution and its CLI resources', async (target) => { + state.target = target + const windows = target === 'win-x64' + if (windows) process.argv.push('--defer-primary-runtime-smoke') + const runtime = join(state.root, 'runtime') + mkdirSync(join(runtime, 'pnpm'), { recursive: true }) + await import('../scripts/prepare-runtime.ts') + expect(existsSync(join(runtime, 'pnpm'))).toBe(false) + expect(existsSync(join(runtime, 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs'))).toBe(true) + expect(existsSync(join(runtime, 'bin', 'node'))).toBe(true) + expect(existsSync(join(runtime, 'cli', 'bin', windows ? 'dsh.cmd' : 'dsh'))).toBe(true) + expect(readFileSync(join(runtime, 'cli', 'command-manager.js'), 'utf8')).toBe('command manager fixture') + expect(existsSync(join(runtime, 'cli', 'command-path.ps1'))).toBe(true) + expect(JSON.parse(readFileSync(join(runtime, 'versions.json'), 'utf8'))).toEqual({ + schemaVersion: 1, node: '24.18.1', pnpm: '11.7.0', + }) + expect(state.preparePrimary).toHaveBeenCalledWith({ deferSmoke: windows }) + if (windows) expect(state.commandLink).not.toHaveBeenCalled() + else expect(state.commandLink).toHaveBeenCalledWith(join(runtime, 'cli'), target === 'mac-arm64' ? 'arm64' : 'x64', '12.0') +}) + +it.each([ + ['electron', 'Electron extraction failed'], + ['primary', 'primary preparation failed'], + ['cli', 'command manager copy failed'], +] as const)('does not publish versions when %s preparation fails', async (failure, error) => { + state.failure = failure + const runtime = join(state.root, 'runtime') + mkdirSync(runtime) + writeFileSync(join(runtime, 'versions.json'), 'stale versions') + await expect(import('../scripts/prepare-runtime.ts')).rejects.toThrow(error) + expect(existsSync(join(runtime, 'versions.json'))).toBe(false) +}) + +it.each([ + ['not-a-version', 'primary runtime: invalid metadata'], + [undefined, 'primary-runtime manifest has no pnpm version'], +])('rejects pnpm metadata %s even when Windows smoke is deferred', async (pnpm, error) => { + state.target = 'win-x64' + process.argv.push('--defer-primary-runtime-smoke') + state.pnpm = pnpm + await expect(import('../scripts/prepare-runtime.ts')).rejects.toThrow(error) + expect(existsSync(join(state.root, 'runtime', 'versions.json'))).toBe(false) +}) diff --git a/apps/desktop/tests/settings.spec.ts b/apps/desktop/tests/settings.spec.ts new file mode 100644 index 0000000000..b285bb98e9 --- /dev/null +++ b/apps/desktop/tests/settings.spec.ts @@ -0,0 +1,83 @@ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import * as fs from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, onTestFinished, vi } from 'vitest' +import { readDesktopSettings } from '../src/settings.ts' + +vi.mock('node:fs', async importOriginal => ({ ...await importOriginal() })) + +beforeEach(() => { vi.spyOn(console, 'warn').mockImplementation(() => {}) }) +afterEach(() => { vi.restoreAllMocks() }) + +function fixture() { + const userData = mkdtempSync(join(tmpdir(), 'dsh-desktop-settings-')) + onTestFinished(() => { rmSync(userData, { recursive: true, force: true }) }) + const directory = join(userData, 'desktop') + mkdirSync(directory) + return { userData, path: join(directory, 'settings.json') } +} + +it('creates a discoverable default file on first launch without touching other preferences', () => { + const { userData, path } = fixture() + rmSync(join(userData, 'desktop'), { recursive: true }) + writeFileSync(join(userData, 'keybindings.json'), 'existing shortcuts\n') + expect(readDesktopSettings(userData)).toEqual({ updates: { allowTestAuthPopupWindow: false } }) + expect(readFileSync(path, 'utf8')).toBe('{\n "updates": {\n "allowTestAuthPopupWindow": false\n }\n}\n') + expect(readFileSync(join(userData, 'keybindings.json'), 'utf8')).toBe('existing shortcuts\n') +}) + +it.each(['{}', '{"updates": {}}', '{"other": 1, "updates": {"other": true}}'])('defaults an older document without rewriting it: %s', (raw) => { + const { userData, path } = fixture() + writeFileSync(path, raw) + expect(readDesktopSettings(userData).updates.allowTestAuthPopupWindow).toBe(false) + expect(readFileSync(path, 'utf8')).toBe(raw) +}) + +it('loads explicit opt-in and opt-out on the next read without changing an earlier process snapshot', () => { + const { userData, path } = fixture() + for (const allow of [true, false]) { + const raw = JSON.stringify({ updates: { allowTestAuthPopupWindow: allow }, custom: 'preserve' }) + writeFileSync(path, raw) + expect(readDesktopSettings(userData).updates.allowTestAuthPopupWindow).toBe(allow) + expect(readFileSync(path, 'utf8')).toBe(raw) + } + const previous = readDesktopSettings(userData) + writeFileSync(path, '{"updates":{"allowTestAuthPopupWindow":true}}') + expect(previous.updates.allowTestAuthPopupWindow).toBe(false) + expect(readDesktopSettings(userData).updates.allowTestAuthPopupWindow).toBe(true) +}) + +it.each(['', '{', 'null', '[]', '{"updates":null}', '{"updates":[]}', + '{"updates":{"allowTestAuthPopupWindow":"false"}}', '{"updates":{"allowTestAuthPopupWindow":1}}', + '{"updates":{"allowTestAuthPopupWindow":null}}'])('reports invalid settings with their path and preserves the original: %s', (raw) => { + const { userData, path } = fixture() + writeFileSync(path, raw) + expect(readDesktopSettings(userData).updates.allowTestAuthPopupWindow).toBe(false) + expect(console.warn).toHaveBeenCalledWith(expect.stringContaining(path), expect.any(Error)) + expect(readFileSync(path, 'utf8')).toBe(raw) +}) + +it('reports filesystem errors instead of replacing unreadable settings', () => { + const { userData, path } = fixture() + mkdirSync(path) + expect(readDesktopSettings(userData).updates.allowTestAuthPopupWindow).toBe(false) + expect(console.warn).toHaveBeenCalledWith(expect.stringContaining(path), expect.any(Error)) + expect(fs.statSync(path).isDirectory()).toBe(true) +}) + +it.each(['mkdirSync', 'writeFileSync'] as const)('continues with disabled popups when %s fails', (operation) => { + const { userData, path } = fixture() + const failure = Object.assign(new Error('settings creation denied'), { code: 'EACCES' }) + vi.spyOn(fs, operation).mockImplementation(() => { throw failure }) + expect(readDesktopSettings(userData).updates.allowTestAuthPopupWindow).toBe(false) + expect(console.warn).toHaveBeenCalledWith(expect.stringContaining(path), failure) +}) + +it('continues with defaults even when warning output fails', () => { + const { userData, path } = fixture() + writeFileSync(path, '{') + vi.mocked(console.warn).mockImplementation(() => { throw new Error('output unavailable') }) + expect(readDesktopSettings(userData).updates.allowTestAuthPopupWindow).toBe(false) + expect(readFileSync(path, 'utf8')).toBe('{') +}) diff --git a/apps/desktop/tests/shell-file-selection.spec.ts b/apps/desktop/tests/shell-file-selection.spec.ts new file mode 100644 index 0000000000..115d75392a --- /dev/null +++ b/apps/desktop/tests/shell-file-selection.spec.ts @@ -0,0 +1,110 @@ +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, join, relative } from 'node:path' +import { Packager, type Configuration, type PlatformSpecificBuildOptions } from 'app-builder-lib' +import { readAsar } from 'app-builder-lib/out/asar/asar.js' +import type { FileMatcher } from 'app-builder-lib/out/fileMatcher.js' +import { MacPackager } from 'app-builder-lib/out/macPackager.js' +import { PM } from 'app-builder-lib/out/node-module-collector/index.js' +import type { PlatformPackager } from 'app-builder-lib/out/platformPackager.js' +import type { ResolvedFileSet } from 'app-builder-lib/out/util/appFileCopier.js' +import { WinPackager } from 'app-builder-lib/out/winPackager.js' +import { expect, it, onTestFinished, vi } from 'vitest' +import { createElectronBuilderConfig } from '../scripts/electron-builder-config.mjs' + +const require = createRequire(import.meta.url) +// The locked builder exports these packaging operations without declarations. +const { getNodeModuleFileMatcher } = require('app-builder-lib/out/fileMatcher.js') as { + getNodeModuleFileMatcher: (app: string, destination: string, expand: (value: string) => string, + options: PlatformSpecificBuildOptions, packager: Packager) => FileMatcher +} +const { computeNodeModuleFileSets } = require('app-builder-lib/out/util/appFileCopier.js') as { + computeNodeModuleFileSets: (packager: PlatformPackager, matcher: FileMatcher) => Promise +} +const { AsarPackager } = require('app-builder-lib/out/asar/asarUtil.js') as { + AsarPackager: new (packager: object, configuration: object) => { pack(files: ResolvedFileSet[]): Promise } +} + +it.each([ + ['darwin', 'arm64'], ['darwin', 'x64'], ['win32', 'x64'], +] as const)('omits shell build files from %s/%s ASAR while retaining runtime assets', async (platform, arch) => { + const root = await mkdtemp(join(tmpdir(), 'desktop-shell-files-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const appDir = join(root, 'app') + const resources = join(root, 'resources') + const destination = join(resources, 'app') + await mkdir(resources, { recursive: true }) + const manifest = { name: 'fixture', version: '1.0.0', dependencies: { shell: '1.0.0', '@fixture/shared': '2.0.0' } } + const packages = [ + ['node_modules/shell', { name: 'shell', version: '1.0.0', dependencies: { '@fixture/shared': '1.0.0' } }], + ['node_modules/@fixture/shared', { name: '@fixture/shared', version: '2.0.0' }], + ['node_modules/shell/node_modules/@fixture/shared', { name: '@fixture/shared', version: '1.0.0' }], + ] as const + const omitted = [ + 'index.js.map', 'lib/index.cjs.map', 'lib/index.mjs.map', 'lib/index.ts.map', + 'lib/index.cts.map', 'lib/index.mts.map', 'lib/style.css.map', 'tsconfig.tsbuildinfo', 'lib/types/tsconfig.tsbuildinfo', + ] + const retained = [ + 'index.js', 'lib/index.cjs', 'lib/index.mjs', 'lib/index.ts', 'lib/index.cts', 'lib/index.mts', + 'lib/style.css', 'lib/types/runtime.js', 'data.map', 'lib/data.map', 'lib/addon.node', 'lib/engine.wasm', 'LICENSE', 'NOTICE', + ] + const originals = new Map() + for (const [directory, metadata] of packages) { + for (const name of [...retained, ...omitted, 'package.json']) { + const file = join(appDir, directory, name) + const contents = Buffer.from(name === 'package.json' ? JSON.stringify(metadata) : `${directory}/${name}\n`) + await mkdir(dirname(file), { recursive: true }) + await writeFile(file, contents) + originals.set(file, contents) + } + } + await writeFile(join(appDir, 'package.json'), JSON.stringify(manifest)) + const desktopConfig = createElectronBuilderConfig({ + DSH_DESKTOP_APP_ID: 'com.example.shell-files', + DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', + DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }), + DSH_DESKTOP_UNSIGNED: platform === 'win32' ? '1' : '0', + DSH_DESKTOP_MACOS_SIGNING_IDENTITY: 'Example Company (TEAMID1234)', + DSH_DESKTOP_MACOS_TEAM_ID: 'TEAMID1234', + APPLE_KEYCHAIN_PROFILE: 'shell-files-test', + DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com', + DOWNLOAD_TEST_RELEASE_ID: '0123456789abcdef0123456789abcdef', + }, platform, arch) + const config: Configuration = { + files: desktopConfig.files.map(file => typeof file === 'string' ? file : { ...file, filter: [...file.filter] }), + } + const info = new Packager({ projectDir: appDir }) + onTestFinished(() => info.tempDirManager.cleanup()) + Object.defineProperties(info, { + appDir: { value: appDir }, config: { value: config }, + metadata: { value: manifest }, originalMetadata: { value: manifest }, + appInfo: { value: { type: 'commonjs' } }, + framework: { value: { name: 'electron' } }, + }) + // Traverse the installed fixture without invoking a host package manager. + vi.spyOn(info, 'getPackageManager').mockResolvedValue(PM.TRAVERSAL) + vi.spyOn(info, 'getWorkspaceRoot').mockResolvedValue(appDir) + const packager = platform === 'darwin' ? new MacPackager(info) : new WinPackager(info) + const matcher = getNodeModuleFileMatcher(appDir, destination, value => value, packager.platformSpecificBuildOptions, info) + const fileSets = await computeNodeModuleFileSets(packager, matcher) + expect(fileSets.map(set => relative(destination, set.destination).replaceAll('\\', '/')).sort()) + .toEqual(packages.map(([directory]) => directory).sort()) + const consoleLog = console.log + try { + await new AsarPackager(packager, { + defaultDestination: destination, resourcePath: resources, options: { smartUnpack: false }, + }).pack(fileSets) + } finally { + // Builder temporarily intercepts console.log while writing ASAR. + console.log = consoleLog + } + const archive = await readAsar(join(resources, 'app.asar')) + for (const [directory] of packages) { + for (const name of [...retained, 'package.json']) { + expect(await archive.readFile(join(directory, name))).toEqual(originals.get(join(appDir, directory, name))) + } + for (const name of omitted) expect(archive.getNode(join(directory, name))).toBeUndefined() + } + for (const [file, contents] of originals) expect(await readFile(file)).toEqual(contents) +}) diff --git a/apps/desktop/tests/update-channel.spec.ts b/apps/desktop/tests/update-channel.spec.ts new file mode 100644 index 0000000000..8ea7bb98a4 --- /dev/null +++ b/apps/desktop/tests/update-channel.spec.ts @@ -0,0 +1,10 @@ +import { expect, it } from 'vitest' +import { desktopUpdateChannel } from '../src/update-channel.ts' + +it('reads the installed channel independently from the current version', () => { + expect(desktopUpdateChannel({ version: '1.0.0', dshDesktopUpdateChannel: 'nightly' })).toBe('nightly') + expect(desktopUpdateChannel({ version: '1.0.0', dshDesktopUpdateChannel: 'latest' })).toBe('latest') + expect(desktopUpdateChannel({ version: '1.0.0' })).toBe('nightly') + expect(() => desktopUpdateChannel({ dshDesktopUpdateChannel: 'beta' })).toThrow(/channel/u) + expect(() => desktopUpdateChannel(null)).toThrow(/manifest/u) +}) diff --git a/apps/desktop/tests/update-coordinator.spec.ts b/apps/desktop/tests/update-coordinator.spec.ts index 790ad63fcf..1c6e9da1c7 100644 --- a/apps/desktop/tests/update-coordinator.spec.ts +++ b/apps/desktop/tests/update-coordinator.spec.ts @@ -47,7 +47,7 @@ describe('desktop release metadata', () => { const coordinators: InstanceType[] = [] afterEach(() => { for (const item of coordinators.splice(0)) item.dispose() }) -function fixture() { +function fixture(channel: 'nightly' | 'latest' = 'nightly', version = '1.1.0-alpha.1') { const events = new EventEmitter() const checkForUpdates = vi.fn(async () => ({ isUpdateAvailable: true, @@ -66,7 +66,7 @@ function fixture() { const updater = Object.assign(events, { checkForUpdates, downloadUpdate, quitAndInstall }) as unknown as AppUpdater const coordinator = new DesktopUpdateCoordinator( (state) => { states.push(state); return state }, - beforeRestart, updater, () => true, () => '1.1.0-alpha.1', downloadResult, + beforeRestart, updater, () => true, () => version, downloadResult, channel, ) coordinators.push(coordinator) return { coordinator, updater, events, states, checkForUpdates, downloadUpdate, quitAndInstall, beforeRestart, downloadResult } @@ -242,3 +242,18 @@ it.each([new DesktopUpdatePreparationError('stop-failed', 'private diagnostic'), expect(f.downloadResult).toHaveBeenCalledExactlyOnceWith(false, error instanceof DesktopUpdatePreparationError ? 'stop-failed' : 'download_failed') expect(JSON.stringify(f.downloadResult.mock.calls)).not.toContain('private') }) + + +it('keeps a stable-version nightly installation on nightly and rejects prereleases on latest', async () => { + const nightly = fixture('nightly', '1.0.0') + expect(nightly.updater.channel).toBe('nightly') + expect(nightly.updater.allowPrerelease).toBe(true) + expect((await nightly.coordinator.check()).phase).toBe('available') + expect(nightly.updater.channel).toBe('nightly') + const latest = fixture('latest', '1.0.0') + expect(latest.updater.channel).toBe('latest') + expect(latest.updater.allowPrerelease).toBe(false) + expect(latest.updater.allowDowngrade).toBe(false) + expect((await latest.coordinator.check()).phase).toBe('error') + expect(latest.downloadUpdate).not.toHaveBeenCalled() +}) diff --git a/apps/desktop/tests/update-dialog.spec.ts b/apps/desktop/tests/update-dialog.spec.ts index 5e9f26e716..16b5888e53 100644 --- a/apps/desktop/tests/update-dialog.spec.ts +++ b/apps/desktop/tests/update-dialog.spec.ts @@ -19,6 +19,7 @@ const fixture = await vi.hoisted(async () => { }) readonly focus = vi.fn() readonly show = vi.fn() + readonly hide = vi.fn() readonly setBounds = vi.fn() readonly loadURL = vi.fn(async () => {}) constructor(readonly options: unknown) { super(); windows.push(this) } @@ -79,6 +80,23 @@ it('accepts only a displayed choice from its own main frame and retains cancella expect((await next).response).toBe(0) }) +it('releases visible Windows modality before destroying a dismissed dialog', async () => { + vi.useFakeTimers() + const f = setup() + const pending = f.show() + const window = fixture.windows.at(-1)! + const destroy = vi.spyOn(window, 'destroy').mockImplementation(() => { + expect(window.hide).toHaveBeenCalledTimes(process.platform === 'win32' ? 1 : 0) + window.destroyed = true + window.emit('closed') + }) + f.invoke(UPDATE_DIALOG_IPC.respond, 0) + await pending + expect(destroy).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(150) + expect(destroy).toHaveBeenCalledOnce() +}) + it('follows the parent geometry and removes listeners when closed or replaced', async () => { const f = setup() const first = f.show() diff --git a/apps/desktop/tests/welcome-startup.spec.ts b/apps/desktop/tests/welcome-startup.spec.ts index 9848c7fb26..7915248243 100644 --- a/apps/desktop/tests/welcome-startup.spec.ts +++ b/apps/desktop/tests/welcome-startup.spec.ts @@ -102,6 +102,7 @@ vi.mock('electron', () => ({ vi.mock('../src/tray.ts', () => ({ DesktopTray: class { relabel() {} dispose() {} } })) vi.mock('../src/paths.ts', () => ({ resolveDesktopPaths: () => ({ profile: '/profile' }) })) +vi.mock('../src/settings.ts', () => ({ readDesktopSettings: () => ({ updates: { allowTestAuthPopupWindow: false } }) })) vi.mock('../src/login-shell-environment.ts', async importOriginal => ({ ...await importOriginal(), readDesktopLoginShellEnvironment: async (base: NodeJS.ProcessEnv) => ({ environment: base, failures: [] }), 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..84cb72921c --- /dev/null +++ b/apps/desktop/tests/windows-package-preset.spec.ts @@ -0,0 +1,112 @@ +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(() => 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') + }) +}) + +it.each(['win32', 'darwin'] as const)('applies an explicit test channel override on %s without changing the preset file', async (platform) => { + await withPreset(async (root) => { + const path = join(root, 'presets/test.env') + const original = 'a'.repeat(32) + await writeFile(path, `DSH_DESKTOP_AUTO_UPDATE_ENV=test\nDOWNLOAD_TEST_RELEASE_ID=${original}\n`) + const env = { DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test' } + const select = (id: string) => loadDesktopPackageEnvironment(platform, + { ...env, PACKAGE_TEST_RELEASE_ID: id }, root, { unsigned: true }) + expect(select('b'.repeat(32)).DOWNLOAD_TEST_RELEASE_ID).toBe('b'.repeat(32)) + expect(select('').DOWNLOAD_TEST_RELEASE_ID).toBe(original) + expect(select(' ').DOWNLOAD_TEST_RELEASE_ID).toBe(original) + expect(() => select('../other')).toThrow(/32 lowercase hexadecimal/u) + expect(() => select('A'.repeat(32))).toThrow(/32 lowercase hexadecimal/u) + await writeFile(join(root, 'presets/production.env'), 'DSH_DESKTOP_AUTO_UPDATE_ENV=production\n') + expect(() => loadDesktopPackageEnvironment(platform, + { ...env, DSH_PACKAGING_PRESET: 'production', PACKAGE_TEST_RELEASE_ID: original }, root, { unsigned: true })) + .toThrow(/requires the test preset/u) + }) +}) diff --git a/apps/desktop/tests/windows-pty-exit.spec.ts b/apps/desktop/tests/windows-pty-exit.spec.ts new file mode 100644 index 0000000000..d6fa3d381e --- /dev/null +++ b/apps/desktop/tests/windows-pty-exit.spec.ts @@ -0,0 +1,15 @@ +import { execFile } from 'node:child_process' +import { resolve } from 'node:path' +import { promisify } from 'node:util' +import { expect, it } from 'vitest' + +it.skipIf(process.platform !== 'win32').each(['natural', 'kill'])('releases the terminal worker after %s exit', async (mode) => { + const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => ( + /^(?:path|systemroot|windir|comspec|temp|tmp)$/iu.test(name) + ))) + const result = await promisify(execFile)(process.execPath, [resolve(import.meta.dirname, 'fixtures/windows-pty-exit.cjs'), mode], { + env, timeout: 15_000, windowsHide: true, + }) + expect(result.stderr).toBe('') + expect(result.stdout.trim()).toBe('pty-cleanup-complete') +}, 20_000) diff --git a/apps/desktop/windows-signing/README.i18n.yaml b/apps/desktop/windows-signing/README.i18n.yaml new file mode 100644 index 0000000000..c063a69c88 --- /dev/null +++ b/apps/desktop/windows-signing/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 apps/desktop/windows-signing/README.md +/: + en: 5b2af461afadb867 + zh: c7558c795a752944 +/windows-signing-and-runner-operations: + en: 65f1ac70a69830fd + zh: cd5825b41e9e30f4 +/windows-signing-and-runner-operations/summary: + en: 3eec637b807a2d4c + zh: e042992b9ea83345 +/windows-signing-and-runner-operations/table-of-contents: + en: 3a812cc5ad554fd3 + zh: 0401b5764c155c0b +/windows-signing-and-runner-operations/trust-and-isolation-limits: + en: 0c261f3948178d55 + zh: 1086cd882468ad8f +/windows-signing-and-runner-operations/machine-setup-and-runner-startup: + en: ba3de07cc9553056 + zh: 887e652c40d57091 +/windows-signing-and-runner-operations/signing-configuration: + en: 4b5548818375eb9a + zh: 8c975adbb1dca9c8 +/windows-signing-and-runner-operations/signing-and-timestamp-completion: + en: e42565e00283e3f6 + zh: 584a33f07b50fd5b +/windows-signing-and-runner-operations/failure-records-and-operator-recovery: + en: 5401b605a2f3a44e + zh: fc1f6ee667bcd20d +/windows-signing-and-runner-operations/signature-cache-and-concurrent-stages: + en: 24032af67e83a003 + zh: 76894f57a9dfed52 +/windows-signing-and-runner-operations/verification-limits: + en: 94a471410c84a1c7 + zh: 115228e4ca36581d +/windows-signing-and-runner-operations/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/apps/desktop/windows-signing/README.md b/apps/desktop/windows-signing/README.md new file mode 100644 index 0000000000..eb3fd4a76d --- /dev/null +++ b/apps/desktop/windows-signing/README.md @@ -0,0 +1,93 @@ +--- +description: "Configure and operate the Windows packaging runner, signing credentials, EV token and signature cache. Read the accepted isolation risks before running branch code or accessing the token. Hardware failures require operator inspection; packaging success does not establish installation or production readiness." +--- + +# Windows signing and runner operations + +English | [中文](README.zh.md) + +## Summary + +Configure and operate the Windows packaging runner, signing credentials, EV token and signature cache. Read the accepted isolation risks before running branch code or accessing the token. Hardware failures require operator inspection; packaging success does not establish installation or production readiness. + +## Table of Contents + +- [Trust and isolation limits](#trust-and-isolation) +- [Machine setup and runner startup](#machine-setup) +- [Signing configuration](#signing-configuration) +- [Signing and timestamp completion](#windows-ev-signing) +- [Failure records and operator recovery](#failure-and-recovery) +- [Signature cache and concurrent stages](#signature-cache) +- [Verification limits](#verification) + + + +## Trust and isolation limits + +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. + + + +## Machine setup and runner startup + +Use a runner-owned checkout and keep configuration, certificates and caches outside it. Registration and tool installation remain operator tasks. Packaging inputs and artifact retrieval are described in the [packaging guide](../packaging/README.md#windows-actions). + +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. + + + +## Signing configuration + +The [machine preset configuration](../packaging/README.md#configuration-and-local-builds) selects public settings and the signing file. Without a preset, use the target dotenv file. + +Fill in `.env.windows` with `DSH_DESKTOP_WINDOWS_CER_FILE` (public EV leaf certificate), `DSH_DESKTOP_WINDOWS_SIGNTOOL` (SafeNet-compatible SignTool), `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` (matching private-key container), and `DSH_DESKTOP_WINDOWS_TOKEN_PIN` (Token Password). The private key stays on the USB token; keep the certificate and local credential file out of Git. + +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. + +Signed Windows configuration derives the updater's `publisherName` from the same public certificate's `CN`, `O`, and `C` attributes. Each must be present, nonempty, and single-valued. These identity attributes allow certificate renewal without pinning a leaf thumbprint. The installed application's `app-update.yml` carries the expected publisher; the downloaded feed does not choose it. Unsigned test builds omit updater configuration. See the [signature qualification record](../tests/README.md) for real-file verification and its limits. + + + +## Signing and timestamp completion + +Follow the [version and build instructions](../packaging/README.md#release-versions) before starting a signed build. Configuration checks do not establish token authentication. + +Signed Windows builds run a supervised signing preflight before compilation or dependency preparation. Static configuration, certificate validity, audit storage, compiler availability and any retained signing interlock are checked without token access. The local .NET Framework C# compiler creates a small private probe; the production signer signs it once, and verification requires the configured certificate and a timestamp before building continues. The probe is never executed. The overall 60-second preflight deadline includes timestamp attempts; deadline expiry, hardware signing errors and verification failures stop the run without another hardware attempt. Success proves the current signing path works, not that the PIN was independently authenticated: SafeNet may reuse login state. Do not log out or repeat authentication to test the PIN. `--check`, preparation-only and `--unsigned` modes do not run this hardware preflight; unsigned artifacts remain ineligible for release upload. Automated regression tests use a fake signer; release operators qualify real hardware separately. + +Insert and unlock the token before packaging. The electron-builder hook passes each artifact to the CRLF `scripts/windows-sign.cmd`, which invokes the configured SignTool once with `/f`, SafeNet `/kc "[{{PIN}}]=container"`, `/csp "eToken Base Cryptographic Provider"`, a SHA-256 file digest, without a timestamp. The hook then completes a DigiCert SHA-256 RFC 3161 timestamp on isolated copies without signing credentials. The hook never substitutes electron-builder's bundled SignTool and never retries a failed signing request. Windows release packaging fails instead of emitting unsigned artifacts when the SignTool, certificate, container, PIN, token, or signature is unavailable. + +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). + + + +## Failure records and operator recovery + +Treat `SignTool Error: No private key is available.` as a signing failure: stop all signing attempts and have the operator inspect the signing configuration and token state before continuing. The device-specific PIN retry limit and remaining attempts are unverified; do not probe them with authentication attempts. Do not retry packaging or signing probes after this error. The signer serializes token operations and rejects all queued tasks after the first failure. + +Windows package commands print `DESKTOP_PACKAGING_RECORD` with a unique directory under `.desktop-build/packaging-runs/`. Each run retains `run.json`, timestamped `events.jsonl`, redacted `stdout.log` and `stderr.log`, and `result.json`. A signing failure also writes `fatal.json` and notifies the parent through stderr; the supervisor immediately requests termination of its stage process tree and waits for exit. Failed stages cannot start subsequent stages or create a release completion record. Journal failures also stop the run. Termination errors remain failures and require operator inspection; a missing final record means completion was not established. + +Hardware signing requires a supervised run. Before invoking the command interpreter, the signer atomically acquires `%USERPROFILE%/.dsh-desktop-signing/attempt.json` and records the attempt. Only successful signing followed by verification of the configured primary signature releases that file; timestamps are completed afterward without hardware access. Failure, interruption, an existing interlock, or unavailable audit storage prevents further hardware access, including from another signer instance, process, or checkout under the same Windows account. There is no timed recovery or automatic retry. An administrator must inspect the retained evidence and token state before explicitly authorizing interlock recovery; logging into the token or replacing a PIN file does not clear it. The records distinguish signing intent, command-interpreter PID, and completion; they do not measure internal CSP/token authentication attempts. Command arguments, PINs, and credential environments are not recorded. Independent Windows accounts and unrelated signing programs are outside this interlock. + + + +## Signature cache and concurrent stages + +Runtime signing shares complete signed files across the current Windows account's worktrees. `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR` in `.env.windows` selects an absolute fixed-drive directory; the default is `%USERPROFILE%\.dsh-desktop-signing\signature-cache\v1`. Cache directories must belong to the current account and exclude other ordinary accounts from their access permissions; linked paths are rejected. Entries identify the original bytes, public certificate and signing toolchain. Every restoration checks the digest, Windows trust, timestamp and certificate before replacing the unsigned file; invalid entries stop packaging without hardware fallback. Cache age alone does not trigger signing. The cache trusts programs running as the same account and does not defend against administrators. The [runtime signature cache decision](../../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md) owns qualification and design limits. + +Preflight, primary-runtime signing, application-runtime signing and artifact creation each hold the account's signing-stage lock until their supervised child processes settle. Other builds wait before entering those stages; compilation and preparation do not hold the lock. Runtime signing workers own their locks, so terminating only the outer packaging process does not unlock a surviving cache user. Migration and maintenance acquire the same lock; older or external signing commands do not participate and must be scheduled separately. Stage waiting is outside the preflight deadline. Closing the stage handle releases ordinary contention without removing the separate hardware-attempt interlock; a retained hardware failure still requires operator recovery. + +Cache-hit copying, hashing and per-file trust checks run with `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY` workers from `.env.windows` (default `4`, integer `1`–`8`). All restores and their post-verification finish before cache misses enter serial hardware signing. A restore or verification failure stops new dispatch and drains active work before releasing the stage lock; hardware signing, runtime smoke checks and final integrity validation remain required. + +Each runtime stage writes `SIGNATURE_CACHE_SUMMARY` to stdout and its packaging journal, including the actual directory, policy identity, hit/miss counts, newly published and retained entries, signing requests, avoided signing requests and validation failures. Timings distinguish signing, trust verification of restored and newly signed files, and restoration; restoration includes its trust check and staging cleanup. These counters exclude preflight, final artifact signing and the outer runtime signature checks. Stage lock events record waiting separately. Concurrent timings sum per-file work rather than stage wall time. + +Use `pnpm --dir apps/desktop run cache:windows-signatures --usage` to inspect structurally complete-entry bytes and counts, or `--from ` to import an explicitly selected cache owned by the same account. Migration leaves the source unchanged, skips staging names, rejects corrupt entries and retains valid existing entries even when their timestamp bytes differ. `--clear` explicitly removes complete entries under the stage lock; no automatic capacity eviction runs. `--directory ` selects a maintenance destination without loading release credentials. Incomplete staging entries remain untouched and are counted separately; inspect them only after all builds have stopped. These commands never clear hardware failure evidence. Default storage is outside AppData so MSIX launcher virtualization does not split the account's cache; redirected overrides fail explicitly. + + + +## Verification limits + +Real hardware and installation evidence is owned by the [Desktop qualification record](../tests/README.md) and [installed-update procedure](../tests/installed-update/README.md). This document does not authorize PIN retries, automatic interlock deletion, device initialization or changes to the accepted isolation policy. + +## Dev Note + +None. diff --git a/apps/desktop/windows-signing/README.zh.md b/apps/desktop/windows-signing/README.zh.md new file mode 100644 index 0000000000..70718a8bf7 --- /dev/null +++ b/apps/desktop/windows-signing/README.zh.md @@ -0,0 +1,93 @@ +--- +description: "配置和维护 Windows 打包 runner、签名凭据、EV Token 与签名缓存。运行分支代码或访问 Token 前,先阅读已接受的隔离风险。硬件失败需要操作者检查;打包成功不代表安装或生产发布已通过验收。" +--- + +# Windows 签名与 runner 运维 + +[English](README.md) | 中文 + +## 概述 + +配置和维护 Windows 打包 runner、签名凭据、EV Token 与签名缓存。运行分支代码或访问 Token 前,先阅读已接受的隔离风险。硬件失败需要操作者检查;打包成功不代表安装或生产发布已通过验收。 + +## 目录 + +- [信任前提与隔离缺陷](#trust-and-isolation) +- [机器配置与 runner 启动](#machine-setup) +- [签名配置](#signing-configuration) +- [签名与时间戳处理](#windows-ev-signing) +- [失败记录与人工恢复](#failure-and-recovery) +- [签名缓存与并发阶段](#signature-cache) +- [验证范围](#verification) + + + +## 信任前提与隔离缺陷 + +共享打包 runner 以内部团队代码和操作人员可信为前提。在此前提下,凭据和设备隔离暂缓实施,剩余风险按已知风险接受(由 #5973 跟踪);尚未强制限制仅 signed/master 可访问。未签名模式跳过签名文件加载,但无法阻止同一 Windows 账户下的分支代码读取这些文件或访问 Token。SafeNet Single Logon 可能复用认证状态。直接调用设备可以绕过签名脚本并耗尽 PIN 重试次数;持久失败 interlock 只保护经过这些脚本的调用。跨账户 Token 隔离和剩余重试次数尚未验证。扩大访问范围、执行不可信贡献、改变 runner 共享方式前,或出现可疑活动后,重新评估 runner、账户和设备隔离。 + + + +## 机器配置与 runner 启动 + +使用 runner 专用 checkout,并将配置、证书和缓存放在其外部。注册和工具安装由操作者负责。打包输入与产物获取见[打包指南](../packaging/README.zh.md#windows-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 缓存路径前,使用下文签名缓存维护命令迁移已有条目。 + + + +## 签名配置 + +通过[机器 preset 配置](../packaging/README.zh.md#configuration-and-local-builds)选择公开设置与签名文件;不选择 preset 时使用目标 dotenv 文件。 + +在 `.env.windows` 中填写 `DSH_DESKTOP_WINDOWS_CER_FILE`(公开 EV 叶证书)、`DSH_DESKTOP_WINDOWS_SIGNTOOL`(SafeNet 兼容的 SignTool)、`DSH_DESKTOP_WINDOWS_KEY_CONTAINER`(匹配的私钥容器)和 `DSH_DESKTOP_WINDOWS_TOKEN_PIN`(Token Password)。私钥仍保留在 USB Token;不要把证书或本地凭据文件提交到 Git。 + +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 尝试次数;签名仍在首次失败后停止整批任务。 + +签名 Windows 配置从同一份公开证书的 `CN`、`O` 和 `C` 属性生成 updater 的 `publisherName`。每个属性都必须存在、非空且只有一个值。这些身份属性允许证书续期,无需固定叶证书指纹。已安装应用的 `app-update.yml` 保存预期发布者,下载的清单不能选择该身份。未签名测试构建省略 updater 配置。真实文件验证及其限制见[签名验收记录](../tests/README.zh.md)。 + + + +## 签名与时间戳处理 + +启动签名构建前,先按[版本与打包说明](../packaging/README.zh.md#release-versions)确认输入。配置检查不代表 Token 认证成功。 + +Windows 签名构建在编译或准备依赖前执行受监督的签名预检。静态配置、证书有效期、审计存储、编译器可用性及遗留签名锁的检查不访问 Token。本地 .NET Framework C# 编译器生成一个专用小探针,由正式签名器仅签名一次,随后必须验出配置的证书和时间戳才能继续构建。探针绝不执行。预检的整体 60 秒期限包含时间戳尝试;超时、硬件签名报错或验签失败都会停止本轮流程,不再次调用硬件。成功只证明当前签名路径可用,不证明 PIN 已独立认证:SafeNet 可能复用登录状态。不要为了验证 PIN 而注销或重复认证。`--check`、仅准备和 `--unsigned` 模式不执行此硬件预检;未签名产物仍不能发布上传。自动回归测试使用假签名器,真实硬件由发布操作人员单独验收。 + +打包前插入并解锁 Token。electron-builder 钩子把每个产物交给采用 CRLF 的 `scripts/windows-sign.cmd`;该 CMD 只调用一次已配置的 SignTool,并指定 `/f`、SafeNet `/kc "[{{PIN}}]=容器"`、`/csp "eToken Base Cryptographic Provider"`和 SHA-256 文件摘要,不请求时间戳。随后钩子在隔离副本上完成 DigiCert SHA-256 RFC 3161 时间戳,不传递签名凭据。钩子不会改用 electron-builder 内置的 SignTool,也不会重试失败的签名请求。SignTool、证书、容器、PIN、Token 或签名不可用时,Windows 发布打包会失败,不会生成未签名产物。 + +时间戳处理仅对正常退出但返回失败或警告的时间戳命令重试,最多尝试三次,间隔为一秒和两秒。每次均从同一份已验证的主签名开始。启动错误、终止状态不确定或验签失败会立即停止。SignTool 使用短的私有路径;发布时先把已验证字节复制到目标卷,再原子替换。最终必须通过 Windows 信任、证书、时间戳和规范化全文件相等检查。尝试耗尽后停止打包并保留证据,不再次调用硬件。参见[签名完成决策](../../../.agents/notes/implemented/process/2026-09-17-windows-signature-completion.zh.md)。 + + + +## 失败记录与人工恢复 + +将 `SignTool Error: No private key is available.` 视为签名失败:立即停止所有签名尝试,由操作者检查签名配置和 Token 状态后再继续。设备具体的 PIN 重试上限和剩余次数尚未验证,不得通过认证尝试探测。出现此错误后不要重试打包或签名探针。签名器串行执行 Token 操作,并在首次失败后拒绝所有排队任务。 + +Windows 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `.desktop-build/packaging-runs/` 下的唯一目录。每次运行保留 `run.json`、带时间戳的 `events.jsonl`、脱敏后的 `stdout.log` 和 `stderr.log`,以及 `result.json`。签名失败还会写入 `fatal.json` 并通过 stderr 通知父进程;监督程序立即请求终止当前阶段的进程树并等待退出。失败阶段不能启动后续阶段或生成发布完成记录。日志写入失败也会停止运行。终止错误仍按失败处理,需要操作者检查;缺少最终记录表示尚未确认完成。 + +硬件签名必须属于受监督的打包运行。调用命令解释器前,签名器原子获取 `%USERPROFILE%/.dsh-desktop-signing/attempt.json` 并记录本次尝试。只有签名成功且配置证书的主签名通过验证后才释放该文件;随后完成时间戳,不再访问硬件。失败、中断、已有锁定文件或审计存储不可用都会阻止再次访问硬件,包括同一 Windows 账户下的另一个签名器实例、进程或代码检出目录。没有定时恢复或自动重试。管理员必须检查保留的证据及令牌状态,再明确授权恢复锁定状态;登录令牌或替换 PIN 文件不会清除它。记录区分签名意图、命令解释器 PID 和完成结果,不计量 CSP/令牌内部的认证次数。不记录命令参数、PIN 或凭据环境。其他 Windows 账户及无关签名程序不在此锁定机制的保护范围内。 + + + +## 签名缓存与并发阶段 + +运行时签名在当前 Windows 账户的各 worktree 间共享完整的已签名文件。`.env.windows` 中的 `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR` 指定固定本地磁盘上的绝对目录;默认值为 `%USERPROFILE%\.dsh-desktop-signing\signature-cache\v1`。缓存目录必须属于当前账户,访问权限不得向其他普通账户开放;带链接的路径会被拒绝。缓存项标识原始字节、公钥证书和签名工具链。每次恢复都检查摘要、Windows 信任状态、时间戳和证书,再替换未签名文件;缓存项无效会停止打包,不回退到硬件签名。不会仅因缓存较旧而重新签名。缓存信任同账户运行的程序,不防御管理员。[运行时签名缓存决策](../../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md)定义验收要求和设计限制。 + +预检、主要运行时签名、应用运行时签名和产物生成分别持有账户级签名阶段锁,直到受监督的子进程结束。其他构建进入这些阶段前等待;编译和准备步骤不持锁。运行时签名进程自行持锁,因此仅终止外层打包进程不会释放仍在访问缓存的阶段锁。迁移及维护获取同一把锁;旧版或外部签名命令不参与排队,应另行避免并发。阶段等待不计入预检期限。关闭阶段句柄会释放普通竞争锁,不删除独立的硬件尝试互锁;遗留硬件失败仍需操作人员恢复。 + +缓存命中的复制、摘要和逐文件信任检查使用 `.env.windows` 中的 `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY` 个工作任务(默认 `4`,整数 `1`–`8`)。所有恢复及后置验签完成后,未命中项才进入串行硬件签名。恢复或验签失败会停止派发新任务,并在释放阶段锁前等待在途工作结束;硬件签名、运行时 smoke 检查和最终完整性校验仍须执行。 + +每个运行时阶段向标准输出及打包日志写入 `SIGNATURE_CACHE_SUMMARY`,包含实际目录、策略标识、命中及未命中数、新发布及保留项数、签名请求数、省去的签名请求数和验证失败数。计时区分签名、恢复文件和新签名文件的信任验证及恢复;恢复耗时包含其信任检查和暂存清理。这些统计不包含预检、最终产物签名及外层运行时验签。阶段锁事件单独记录等待时间。 并发计时累加逐文件工作耗时,不代表阶段墙钟时间。 + +使用 `pnpm --dir apps/desktop run cache:windows-signatures --usage` 查看结构完整的缓存项字节数和数量,或用 `--from ` 导入显式指定、属于同账户的旧缓存。迁移不修改源目录,跳过暂存名称,拒绝损坏项,并保留已有有效项,即使它们的时间戳字节不同。`--clear` 在阶段锁保护下显式删除完整缓存项;不执行自动容量淘汰。`--directory ` 指定维护目标目录,无需加载发布凭据。不完整暂存项保持原状并单独计数;仅在所有构建停止后检查它们。这些命令绝不清除硬件失败证据。默认存储位于 AppData 之外,避免 MSIX 启动器虚拟化将账户缓存拆开;被重定向的覆盖目录会明确失败。 + + + +## 验证范围 + +真实硬件与安装证据由[Desktop 验证记录](../tests/README.zh.md)和[已安装更新流程](../tests/installed-update/README.zh.md)维护。本文档不授权 PIN 重试、自动删除 interlock、设备初始化或改变已接受的隔离策略。 + +## 开发备注 + +无。 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 7548471a7e..e25cb4d303 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-web-frontend", "description": "Web application entry: vite build over the @deepseek-ai/dsh-client-web shell library; dist/ served by apps/cli's dsh web", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -46,10 +46,9 @@ "@deepseek-ai/dsh-experimental-webworker-packer": "workspace:*", "@deepseek-ai/dsh-experimental-webworker-runtime": "workspace:*", "@deepseek-ai/dsh-remote-mock": "workspace:*", + "@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/access-confirmation.e2e.ts b/apps/web/tests/access-confirmation.e2e.ts index a47cad63f6..f97978d346 100644 --- a/apps/web/tests/access-confirmation.e2e.ts +++ b/apps/web/tests/access-confirmation.e2e.ts @@ -64,7 +64,7 @@ describe('web e2e: experimental Auto and Full access confirmation', () => { const currentMenu = page.getByRole('menu') await currentMenu.waitFor({ timeout: 10_000 }) expect(await currentMenu.getByRole('menuitem').allTextContents()) - .toEqual(['仅可查看', '工作区内修改', '完全权限', 'Auto reviewEXP']) + .toEqual(['仅可查看', '工作区内修改', '完全权限', '自动审查EXP']) await captureAutoReviewState(page, 'experimental-current-session-picker') const currentSnapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) await compareOrRefreshGolden(CURRENT_SESSION_PICKER_EXPECTED, currentSnapshot, MODE) @@ -77,10 +77,10 @@ describe('web e2e: experimental Auto and Full access confirmation', () => { expect(currentMenuBox!.width).toBeGreaterThan(currentTriggerBox!.width) expect(Math.abs(currentTriggerBox!.y - currentMenuBox!.y - currentMenuBox!.height - 4)).toBeLessThan(1) - await currentMenu.getByRole('menuitem', { name: 'Auto review EXP' }).click() - const autoDialog = page.getByRole('dialog', { name: '确认启用 Auto review(实验)?' }) + await currentMenu.getByRole('menuitem', { name: '自动审查 EXP' }).click() + const autoDialog = page.getByRole('dialog', { name: '确认启用自动审查(实验)?' }) await autoDialog.waitFor({ timeout: 10_000 }) - const autoEnable = autoDialog.getByRole('button', { name: '启用 Auto review' }) + const autoEnable = autoDialog.getByRole('button', { name: '启用自动审查' }) expect(await autoEnable.isDisabled()).toBe(true) expect(await autoDialog.getByText(/不使用沙箱/).count()).toBe(1) expect(await autoDialog.getByText(/误放行或误拒绝/).count()).toBe(1) @@ -105,7 +105,7 @@ describe('web e2e: experimental Auto and Full access confirmation', () => { await slashPicker.waitFor({ timeout: 10_000 }) const slashRows = slashPicker.getByRole('option') expect(await slashRows.count()).toBe(4) - expect(await slashPicker.getByRole('option', { name: 'Auto review EXP' }).count()).toBe(1) + expect(await slashPicker.getByRole('option', { name: '自动审查 EXP' }).count()).toBe(1) await captureAutoReviewState(page, 'experimental-slash-picker') const slashSnapshot = await captureStableAria(page, '[aria-label="/permission 选项"]', scaffold.workspaceCwd) await compareOrRefreshGolden(SLASH_PICKER_EXPECTED, slashSnapshot, MODE) @@ -119,15 +119,15 @@ describe('web e2e: experimental Auto and Full access confirmation', () => { expect(slashPickerBox!.x).toBeCloseTo(composerBox!.x) expect(Math.abs(composerBox!.y - slashPickerBox!.y - slashPickerBox!.height - 4)).toBeLessThan(1) - await slashPicker.getByRole('option', { name: 'Auto review EXP' }).click() - const slashDialog = page.getByRole('dialog', { name: '确认启用 Auto review(实验)?' }) + await slashPicker.getByRole('option', { name: '自动审查 EXP' }).click() + const slashDialog = page.getByRole('dialog', { name: '确认启用自动审查(实验)?' }) await slashDialog.waitFor({ timeout: 10_000 }) expect(await slashDialog.count()).toBe(1) expect(await slashPicker.count()).toBe(0) await slashDialog.getByRole('checkbox', { name: '我已了解这些风险,并愿意继续' }).check() - await slashDialog.getByRole('button', { name: '启用 Auto review' }).click() + await slashDialog.getByRole('button', { name: '启用自动审查' }).click() await expect.poll(() => access.getAttribute('aria-label'), { timeout: 10_000 }) - .toBe('访问模式,当前:Auto review EXP') + .toBe('访问模式,当前:自动审查') expect(await slashDialog.count()).toBe(0) expect(await input.textContent()).toBe('') await captureAutoReviewState(page, 'experimental-current-session') @@ -188,12 +188,18 @@ describe('web e2e: experimental Auto and Full access confirmation', () => { expect(menuBox.width).toBeLessThanOrEqual(360) expect(menuBox.x).toBeGreaterThanOrEqual(0) expect(menuBox.x + menuBox.width).toBeLessThanOrEqual(420) - for (const name of ['仅可查看', '工作区内修改', '完全权限', 'Auto review']) { + for (const name of ['仅可查看', '工作区内修改', '完全权限', '自动审查']) { expect(await menu.getByText(name, { exact: true }).evaluate(node => node.scrollWidth <= node.clientWidth)).toBe(true) } await page.keyboard.press('Escape') const input = page.locator('[data-composer-input]').first() + await writeComposerDraft(page, input, '/permission auto') + await input.press('Enter') + await expect.poll(() => access.getAttribute('aria-label')).toBe('访问模式,当前:自动审查') + expect(await access.getByText('自动审查', { exact: true }).isVisible()).toBe(false) + expect(await access.getByText('EXP', { exact: true }).count()).toBe(0) + expect(await access.getAttribute('title')).toBe('无沙箱运行;每次原生工具调用和 PTC 内层调用前由同一模型进行实验性审查。') await writeComposerDraft(page, input, '/permission') await input.press('Escape') await input.press('Enter') @@ -206,10 +212,13 @@ describe('web e2e: experimental Auto and Full access confirmation', () => { expect(slashBox.x + slashBox.width).toBeLessThanOrEqual(420) expect(await slash.evaluate(node => getComputedStyle(node).minWidth)).toBe('min(220px, 100%)') expect(await slash.evaluate(node => getComputedStyle(node).maxWidth)).toBe('100%') - for (const name of ['仅可查看', '工作区内修改', '完全权限', 'Auto review']) { + for (const name of ['仅可查看', '工作区内修改', '完全权限', '自动审查']) { expect(await slash.getByText(name, { exact: true }).evaluate(node => node.scrollWidth <= node.clientWidth)).toBe(true) } await page.keyboard.press('Escape') + await writeComposerDraft(page, input, '/permission danger-full-access') + await input.press('Enter') + await expect.poll(() => access.getAttribute('aria-label')).toBe('访问模式,当前:完全权限') expect(tripwire.pageErrors).toEqual([]) }) @@ -219,7 +228,7 @@ describe('web e2e: experimental Auto and Full access confirmation', () => { const access = page.locator('button[aria-label^="访问模式"]').first() await writeComposerDraft(page, input, '/permission auto') await input.press('Enter') - await expect.poll(() => access.getAttribute('aria-label')).toBe('访问模式,当前:Auto review EXP') + await expect.poll(() => access.getAttribute('aria-label')).toBe('访问模式,当前:自动审查') expect(await page.getByRole('dialog').count()).toBe(0) await writeComposerDraft(page, input, '/permission') await input.press('Escape') @@ -237,7 +246,7 @@ describe('web e2e: experimental Auto and Full access confirmation', () => { await input.press('Enter') await slash.waitFor() expect(await slash.getByRole('option').count()).toBe(3) - expect(await slash.getByText('Auto review', { exact: true }).count()).toBe(0) + expect(await slash.getByText('自动审查', { exact: true }).count()).toBe(0) await page.keyboard.press('Escape') await access.click() await expect.poll(() => page.getByRole('menuitem').allTextContents()) @@ -248,7 +257,7 @@ describe('web e2e: experimental Auto and Full access confirmation', () => { await scaffold.ctx.loader.await() await access.click() await expect.poll(() => page.getByRole('menuitem').allTextContents()) - .toEqual(['仅可查看', '工作区内修改', '完全权限', 'Auto reviewEXP']) + .toEqual(['仅可查看', '工作区内修改', '完全权限', '自动审查EXP']) expect(await access.getAttribute('aria-label')).toBe('访问模式,当前:完全权限') await captureAutoReviewState(page, 'reinstalled-current-session-picker') await page.keyboard.press('Escape') @@ -302,7 +311,7 @@ describe('web e2e: default permission choices', () => { const slash = page.locator('[aria-label="/permission 选项"]') await slash.waitFor() expect(await slash.getByRole('option').count()).toBe(3) - expect(await slash.getByText('Auto review', { exact: true }).count()).toBe(0) + expect(await slash.getByText('自动审查', { exact: true }).count()).toBe(0) await captureAutoReviewState(page, 'default-slash-picker') }) }) diff --git a/apps/web/tests/account-login.e2e.ts b/apps/web/tests/account-login.e2e.ts new file mode 100644 index 0000000000..e20a18c94b --- /dev/null +++ b/apps/web/tests/account-login.e2e.ts @@ -0,0 +1,136 @@ +// Real-composition acceptance for DeepSeek account sign-in from a plain browser. The +// scaffold boots the shipped Web Loader tree, so the real account provider drives +// auth_init, the loopback OAuth callback, and auth_exchange against a loopback Platform +// double, while a real Chromium follows the tab the Web UI preopens. +import { createServer, type Server } from 'node:http' +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium, type Browser } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { saveFailureShot } from './support.ts' + +const OVERLAY_TEMPLATE = fileURLToPath(new URL('./fixtures/account-login/cordis.patch.yml', import.meta.url)) +const MODE = webSnapshotMode() +const TOKEN = 'dsh_web_login_test' +const CODE = 'web-login-code' + +/** Loopback Platform double: authorization handoff, code exchange, and the signed-in profile reads. */ +async function mockPlatform() { + const inits: Record[] = [] + const pages: string[] = [] + let state: string | undefined + let redirectUri: string | undefined + const server: Server = createServer((req, res) => { + const url = new URL(req.url ?? '/', 'http://127.0.0.1') + const reply = (payload: unknown): void => { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: payload } })) + } + if (url.pathname === '/dsh/authorize') { + pages.push(url.href) + // The user approves at once: Platform returns the browser to the Host callback. + const callback = new URL(redirectUri ?? '/') + callback.searchParams.set('code', CODE) + callback.searchParams.set('state', state ?? '') + res.writeHead(302, { location: callback.href }).end() + return + } + if (url.pathname === '/dsh/authorized') { + pages.push(url.href) + res.writeHead(200, { 'content-type': 'text/html' }).end('Authorized') + return + } + if (req.method === 'POST' && url.pathname.startsWith('/auth-api/v0/dsh/')) { + let body = '' + req.setEncoding('utf8') + req.on('data', (chunk: string) => { body += chunk }) + req.on('end', () => { + const payload = JSON.parse(body) as Record + if (url.pathname === '/auth-api/v0/dsh/auth_init') { + inits.push(payload) + state = String(payload.state) + redirectUri = String(payload.redirect_uri) + reply({ authorize_url: `${origin}/dsh/authorize?authorize_id=web`, authorize_id: 'web', expires_in: 300 }) + return + } + if (url.pathname === '/auth-api/v0/dsh/auth_exchange' && payload.code === CODE) { + reply({ token: TOKEN, authorized_url: `${origin}/dsh/authorized` }) + return + } + res.writeHead(404).end() + }) + return + } + if (req.headers['x-dsh-auth-token'] !== TOKEN) { res.writeHead(401).end(); return } + if (url.pathname === '/auth-api/v0/users/current') { + // `email` is required by the provider's profile schema even when the account has none. + reply({ id: 'web-user', email: '', id_profile: { name: 'Web User', picture: null } }) + return + } + if (url.pathname === '/api/v0/users/get_user_summary') { + reply({ normal_wallets: [{ currency: 'CNY', balance: '1.00' }], bonus_wallets: [] }) + return + } + if (url.pathname === '/api/v0/users/get_unnotified_bonuses') { reply([]); return } + res.writeHead(404).end() + }) + await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve) }) + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('account login: missing mock listener') + const origin = `http://127.0.0.1:${String(address.port)}` + return { + origin, inits, pages, + close: () => new Promise((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }), + } +} + +describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain browser', () => { + let root: string | undefined + let scaffold: WebScaffold + let browser: Browser + let platform: Awaited> + + beforeAll(async () => { + platform = await mockPlatform() + root = await mkdtemp(join(tmpdir(), 'dsh-web-account-login-')) + const overlay = join(root, 'account-login.overlay.yml') + await writeFile(overlay, (await readFile(OVERLAY_TEMPLATE, 'utf8')).replaceAll('{{origin}}', platform.origin)) + scaffold = await launchWebScaffold({ extraOverlayPath: overlay }) + browser = await chromium.launch() + }) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + await platform?.close() + if (root !== undefined) await rm(root, { recursive: true, force: true }) + }) + + it('signs in through a preopened themed tab and reports the Web login source', async () => { + const context = await browser.newContext({ viewport: { width: 1440, height: 960 }, locale: 'en-US', colorScheme: 'dark' }) + const page = await context.newPage() + const console = watchConsole(page) + onTestFailed(() => saveFailureShot(page, 'web-e2e-account-login')) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + const menu = page.getByRole('button', { name: 'Account menu', exact: true }) + await menu.click() + const tab = context.waitForEvent('page') + await page.getByRole('menuitem', { name: 'Sign in', exact: true }).click() + const authorization = await tab + await authorization.waitForURL(url => url.pathname === '/dsh/authorized', { timeout: 30_000 }) + expect(await authorization.evaluate(() => window.opener === null)).toBe(true) + await expect.poll(() => menu.textContent(), { timeout: 30_000 }).toBe('Web User') + + const pageOrigin = new URL(scaffold.authenticatedUrl).origin + expect(platform.inits).toHaveLength(1) + expect(platform.inits[0]).toMatchObject({ login_source: 'web', redirect_uri: `${pageOrigin}/oauth/callback` }) + const [authorize, authorized] = platform.pages.map(href => new URL(href)) + expect(authorize?.searchParams.get('theme')).toBe('dark') + expect(authorized?.searchParams.get('login_source')).toBe('web') + expect(console.pageErrors).toEqual([]) + await context.close() + }, 90_000) +}) diff --git a/apps/web/tests/agent-preset-selection.e2e.ts b/apps/web/tests/agent-preset-selection.e2e.ts index 6fc12aba02..094047c701 100644 --- a/apps/web/tests/agent-preset-selection.e2e.ts +++ b/apps/web/tests/agent-preset-selection.e2e.ts @@ -323,7 +323,7 @@ describe('web e2e: agent-preset selection', () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-preset-slash-catalog')) const composer = page.locator('[data-composer-input][contenteditable="true"]').last() - // `minimal` mounts neither the compaction group nor plan mode nor local + // `minimal` mounts compaction, but neither plan mode nor local // skill discovery, so the catalog the composer warmed under the // deployment default must not survive the switch. await writeComposerDraft(page, composer, '/') @@ -331,7 +331,7 @@ describe('web e2e: agent-preset selection', () => { .not.toEqual(expect.arrayContaining([expect.stringContaining(SKILL_NAME)])) // Rows read as `Title Description`; the title is the capitalized command name. const onMinimal = (await menuOptions(page)).map(option => option.toLowerCase()) - expect(onMinimal.some(option => option.startsWith('compact'))).toBe(false) + expect(onMinimal.some(option => option.startsWith('compact'))).toBe(true) expect(onMinimal.some(option => option.startsWith('plan'))).toBe(false) // Preset-scoped commands follow the switch; the client's own model command // remains outside every preset. @@ -422,7 +422,7 @@ describe('web e2e: agent-preset selection', () => { await compareOrRefreshGolden(HEADER_EXPECTED, snapshot, MODE) expect(snapshot).toContain('Minimal mode') expect(snapshot).toContain('button "1 subagent"') - expect(snapshot.indexOf('button "1 subagent"')).toBeLessThan(snapshot.indexOf('Minimal mode')) + expect(snapshot.indexOf('Minimal mode')).toBeLessThan(snapshot.indexOf('button "1 subagent"')) expect(snapshot.indexOf('button "1 subagent"')).toBeLessThan(snapshot.indexOf('button "More actions"')) // Static chrome, not a control: the header can only report a composition // the host would refuse to change. @@ -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/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index 8358ef1a20..bd7dcff720 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -150,7 +150,7 @@ describe('web e2e: Agent Teams panel', () => { expect(await trigger.evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press('Enter') await panel.waitFor() - const outside = page.getByRole('button', { name: 'Settings', exact: true }) + const outside = page.getByRole('button', { name: 'Account menu', exact: true }) await outside.focus() expect(await panel.count()).toBe(1) await page.keyboard.press('Escape') diff --git a/apps/web/tests/agent-team-panel.overlay.yml b/apps/web/tests/agent-team-panel.overlay.yml index 20c49c23a1..ecca62985b 100644 --- a/apps/web/tests/agent-team-panel.overlay.yml +++ b/apps/web/tests/agent-team-panel.overlay.yml @@ -17,7 +17,6 @@ config: maxMembers: 8 maxTasks: 256 - maxPendingMessagesPerMember: 64 maxMessageBytes: 65536 disposalTimeoutMs: 5000 diff --git a/apps/web/tests/auto-review-approval.e2e.ts b/apps/web/tests/auto-review-approval.e2e.ts index b430de35f4..890ed25e0e 100644 --- a/apps/web/tests/auto-review-approval.e2e.ts +++ b/apps/web/tests/auto-review-approval.e2e.ts @@ -63,7 +63,7 @@ describe.skipIf(MODE === 'record')('web e2e: cold Auto-review user rejection and const access = page.locator('button[aria-label^="Access mode"]').first() await expect.poll(() => access.getAttribute('aria-label'), { timeout: 10_000 }) - .toBe('Access mode, current: Auto review EXP') + .toBe('Access mode, current: Auto review') const collapsed = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)) .split(SEED_ID).join('{{seededId}}') diff --git a/apps/web/tests/auto-review-denial.e2e.ts b/apps/web/tests/auto-review-denial.e2e.ts index b792361be5..58371631a9 100644 --- a/apps/web/tests/auto-review-denial.e2e.ts +++ b/apps/web/tests/auto-review-denial.e2e.ts @@ -92,7 +92,7 @@ describe.skipIf(MODE === 'record')('web e2e: cold Auto-review denial', () => { const access = page.locator('button[aria-label^="Access mode"]').first() await expect.poll(() => access.getAttribute('aria-label'), { timeout: 10_000 }) - .toBe('Access mode, current: Auto review EXP') + .toBe('Access mode, current: Auto review') await captureAutoReviewState(page, 'deny-collapsed') const collapsed = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)) diff --git a/apps/web/tests/background-job-list.e2e.ts b/apps/web/tests/background-job-list.e2e.ts index 673270ae86..f407bdb53e 100644 --- a/apps/web/tests/background-job-list.e2e.ts +++ b/apps/web/tests/background-job-list.e2e.ts @@ -95,7 +95,7 @@ describe.skipIf(MODE === 'record')('web e2e: background job list', () => { agent, }) const reported = started.content.map(block => block.type === 'text' ? block.text : '').join('') - const matched = /\bbash-\d+\b/.exec(reported) + const matched = /\bbash-[0-9a-f]{16}\b/.exec(reported) if (matched === null) throw new Error(`background bash reported no job id: ${reported}`) const jobId = JobId(matched[0]) 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/built-boot.expected.e2e.ts b/apps/web/tests/built-boot.expected.e2e.ts index f645214133..c7b7f41b65 100644 --- a/apps/web/tests/built-boot.expected.e2e.ts +++ b/apps/web/tests/built-boot.expected.e2e.ts @@ -97,6 +97,8 @@ it('boots the built plugin graph and renders a fixture session end to end', asyn fireEvent.click(waitingTitle) await waitFor(() => { expect(document.querySelector('[data-sample="bash"]')).not.toBeNull() + expect(document.querySelector('[data-chat-running]')?.parentElement?.getAttribute('data-slot')) + .toBe('conversation.chat.flow') }, { timeout: 10_000 }) // The generated bundle roster mounts the question UI before the approval UI. // Skip the resident fixture's three questions, then resolve its approval so diff --git a/apps/web/tests/chat-flow-layout.e2e.ts b/apps/web/tests/chat-flow-layout.e2e.ts new file mode 100644 index 0000000000..d3d5e999ac --- /dev/null +++ b/apps/web/tests/chat-flow-layout.e2e.ts @@ -0,0 +1,73 @@ +/** Cold history retains Chat spacing through the flow slot's display:contents anchor. */ +import { readFile, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium } from 'playwright' +import { expect, it, onTestFinished } from 'vitest' +import { launchWebScaffold, seedSession, selectedSessionFixture, watchConsole } from './scaffold.ts' +import { newEnglishPage } from './support.ts' + +it.each(['turn-tail-actions', 'goal-multi-turn-actions', 'present'] as const)( + 'preserves process and answer spacing in cold %s history', async (scenario) => { + const scaffold = await launchWebScaffold({}) + onTestFinished(() => scaffold.close()) + if (scenario === 'present') { + await writeFile(join(scaffold.workspaceCwd, 'report.txt'), 'DELIVERED_REPORT\n') + await writeFile(join(scaffold.workspaceCwd, '说明.txt'), 'DELIVERED_NOTE\n') + } + const fixture = await selectedSessionFixture(fileURLToPath( + new URL(`../../../snapshots/web/${scenario}/session.v3.jsonl`, import.meta.url), + )) + await seedSession(scaffold, await readFile(fixture, 'utf8'), `flow-layout-${scenario}`) + const browser = await chromium.launch() + onTestFinished(() => browser.close()) + const page = await newEnglishPage(browser) + const console = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.locator('[role="treeitem"]').first().click() + await page.locator('[role="treeitem"]').nth(1).click() + const controls = page.locator('[data-turn-process]') + await expect.poll(() => controls.count()).toBe(scenario === 'goal-multi-turn-actions' ? 2 : 1) + const process = controls.first() + expect(await process.getAttribute('aria-expanded')).toBe('false') + expect(await process.evaluate(element => element.closest('[data-slot="conversation.chat.flow"]') !== null)).toBe(true) + + if (scenario === 'goal-multi-turn-actions') { + const trigger = page.locator('[data-turn-trigger]').first() + await process.click() + for (const fontSize of [10, 14, 22]) { + await scaffold.ctx.settings.update('ui-theme', { fontSize }) + await expect.poll(() => page.evaluate(() => document.body.style.getPropertyValue('--dsh-content-font-size'))) + .toBe(`${String(fontSize)}px`) + const group = page.locator('[data-process-activity]:visible').first() + expect(await process.evaluate(element => element.getBoundingClientRect().top)) + .toBe(await trigger.evaluate(element => element.getBoundingClientRect().bottom) + 16) + expect(await group.evaluate(element => element.getBoundingClientRect().top)) + .toBe(await process.evaluate(element => element.getBoundingClientRect().bottom) + 16) + } + } else { + const answer = page.getByText(scenario === 'present' ? 'PRESENT_DONE' : 'DONE', { exact: true }) + await answer.waitFor() + const answerBounds = await answer.evaluate((element) => { + const seat = element.closest('[data-chat-flow-kind="assistant-step"]') + if (seat === null) throw new Error('final answer has no Chat seat') + const { top, bottom } = seat.getBoundingClientRect() + return { top, bottom } + }) + expect(answerBounds.top).toBe(await process.evaluate(element => element.getBoundingClientRect().bottom) + 16) + if (scenario === 'present') { + const geometry = await page.locator('[data-presented-files-row]').evaluate((grid) => { + const root = grid.parentElement + const tail = root?.closest('[data-turn-tail]') + const actions = tail?.querySelector('button[aria-label="Copy"]')?.parentElement + if (root === null || actions == null) throw new Error('presented files have no Turn footer') + return { top: root.getBoundingClientRect().top, bottom: root.getBoundingClientRect().bottom, + actionsTop: actions.getBoundingClientRect().top } + }) + expect(geometry.top - answerBounds.bottom).toBeCloseTo(16, 1) + expect(geometry.actionsTop - geometry.bottom).toBeCloseTo(20, 1) + } + } + expect(console.pageErrors).toEqual([]) + }, +) diff --git a/apps/web/tests/chat-scroll-contract.e2e.ts b/apps/web/tests/chat-scroll-contract.e2e.ts index 4d22e66e98..955d251ab7 100644 --- a/apps/web/tests/chat-scroll-contract.e2e.ts +++ b/apps/web/tests/chat-scroll-contract.e2e.ts @@ -2,18 +2,19 @@ // deliberately virtualizer-neutral: they assert semantic-row position, // bottom ownership, interaction state, and the real outer scroll host rather // than DOM cardinality or implementation-specific spacer markup. -import { access, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { access, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { Browser, Page } from 'playwright' +import { fileURLToPath } from 'node:url' +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, @@ -27,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 @@ -46,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' @@ -73,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 @@ -94,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 }[] @@ -189,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 }) @@ -524,6 +544,675 @@ describe('web e2e: long Chat scroll contract', () => { await browser?.close() }) + 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 } }) + } + 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() + } + await wheelTranscript(page, -600) + await page.getByRole('button', { name: 'Back to bottom', exact: true }).click() + await expectBottom(page) + await nextPaint(page) + 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 }) + await mkdir(fileURLToPath(new URL('../../../.artifacts/screenshots/chat-mode-height/', import.meta.url)), { recursive: true }) + await withScrollWorld({ + failureShot: 'screenshots/chat-mode-height/web-e2e-chat-mode-height', + replay: [replayEntry(textStream('CHAT_MODE_REPLY', 'CHAT_MODE_DONE', 2))], + seeds: [{ fixture, id: 'chat-mode-height-e2e' }], + }, async (world) => { + const { page } = world + await page.setViewportSize({ width: 1280, height: 720 }) + await page.emulateMedia({ reducedMotion: 'no-preference' }) + const selectPreference = async (title: string, choice: string): Promise => { + await openSettings(page, 'en') + const dialog = page.getByRole('dialog', { name: 'Settings', exact: true }) + const row = dialog.getByText(title, { exact: true }).locator('../..') + await row.getByRole('button').click() + await page.getByRole('menuitem', { name: choice, exact: true }).click() + await row.getByRole('button', { name: choice, exact: true }).waitFor() + if (title === 'Work details') { + await expect.poll(() => world.scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value) + .toMatchObject({ transcriptView: choice.toLowerCase() }) + } + await dialog.getByRole('button', { name: 'Close', exact: true }).click() + await expect.poll(() => page.locator('[data-chat-motion="collapse"], [data-chat-motion="reveal"]').count()).toBe(0) + await nextPaint(page) + } + const returnToBottom = async (): Promise => { + await wheelTranscript(page, -600) + await page.getByRole('button', { name: 'Back to bottom', exact: true }).click() + await expectBottom(page) + } + const geometry = () => page.locator('[data-conversation-scroll]').evaluate(host => ({ + height: host.scrollHeight, + viewport: host.clientHeight, + spacer: host.querySelector('[data-chat-turn-spacer]')!.getBoundingClientRect().height, + })) + await selectPreference('Work details', 'Standard') + await openSeed(page, fixture, fixture.markers.assistant(8)) + // Hold a live reply so preference changes exercise the same fold animation as incoming content. + const release = holdTextAfter(world, 1) + let replyStarted = false + try { + await page.locator('[data-composer-input][contenteditable="true"]').last().fill('CHAT_MODE_NEXT_INPUT') + await page.getByRole('button', { name: 'Send message', exact: true }).click() + await page.getByText('CHAT_MODE_REPLY', { exact: false }).waitFor() + replyStarted = true + await selectPreference('When to Collapse Work Details', 'On next message') + await page.locator('[data-chat-flow][data-chat-motion=""]').waitFor() + await returnToBottom() + const standard = await geometry() + expect(standard.height).toBeGreaterThan(standard.viewport) + expect(standard.spacer).toBe(0) + for (let cycle = 0; cycle < 2; cycle += 1) { + await selectPreference('Work details', 'Verbose') + await expect.poll(async () => (await geometry()).height) + .toBeGreaterThan(standard.height + GEOMETRY_TOLERANCE) + await returnToBottom() + await selectPreference('Work details', 'Standard') + await expect.poll(async () => (await geometry()).spacer).toBe(0) + await expect.poll(async () => Math.abs((await geometry()).height - standard.height)) + .toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + await expectBottom(page) + await expectMarkerAboveComposer(page, 'CHAT_MODE_REPLY') + } + } finally { + const settled = replyStarted ? world.scaffold.whenTurnSettled() : undefined + release() + await settled + } + assertClean(world) + }) + }) + + it.skipIf(MODE === 'record')('keeps a running Session stationary when returning with output held', async () => { + const fixtureA = createChatScrollFixture({ markerPrefix: 'RETURN_A', title: 'CHAT_RUNNING_RETURN_A' }) + const fixtureB = createChatScrollFixture({ markerPrefix: 'RETURN_B', title: 'CHAT_RUNNING_RETURN_B', turns: 32 }) + const heldMarker = 'CHAT_RUNNING_RETURN_HELD' + const grownMarker = 'CHAT_RUNNING_RETURN_GROWN' + const doneMarker = 'CHAT_RUNNING_RETURN_DONE' + const paragraphs = (count: number, prefix: string): string => Array.from({ length: count }, (_, index) => + `${prefix} paragraph ${index + 1}: ${'The recorded response stays readable while this Session is open. '.repeat(3)}`, + ).join('\n\n') + const parts = [ + `${paragraphs(32, 'Initial output')}\n\n${heldMarker}\n\n`, + `${paragraphs(12, 'Resumed output')}\n\n${grownMarker}\n\n`, + doneMarker, + ] + const chunks: StreamChunk[] = [ + { type: 'block-start', index: 0, blockType: 'text' }, + ...parts.map((text): StreamChunk => ({ type: 'text-delta', index: 0, text })), + { type: 'block-end', index: 0, block: { type: 'text', text: parts.join('') } }, + { type: 'usage', usage: { inputTokens: 512, outputTokens: 2_500 } }, + { type: 'finish', reason: { kind: 'stop' } }, + ] + const artifactRoot = fileURLToPath(new URL('../../../.artifacts/screenshots/chat-running-return/', import.meta.url)) + await mkdir(artifactRoot, { recursive: true }) + const evidence = await mkdtemp(join(artifactRoot, 'run-')) + await withScrollWorld({ + failureShot: 'screenshots/chat-running-return/web-e2e-chat-running-return', + replay: [replayEntry(chunks)], + seeds: [ + { fixture: fixtureA, id: 'chat-running-return-a-e2e' }, + { fixture: fixtureB, id: 'chat-running-return-b-e2e' }, + ], + }, async (world) => { + const { page } = world + await page.setViewportSize({ width: 1280, height: 720 }) + await page.emulateMedia({ reducedMotion: 'no-preference' }) + await openSettings(page, 'en') + const dialog = page.getByRole('dialog', { name: 'Settings', exact: true }) + for (const [title, choice] of [ + ['Work details', 'Standard'], + ['When to Collapse Work Details', 'On next message'], + ] as const) { + await dialog.getByText(title, { exact: true }).locator('../..').getByRole('button').click() + await page.getByRole('menuitem', { name: choice, exact: true }).click() + } + await expect.poll(() => world.scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value) + .toMatchObject({ transcriptView: 'standard' }) + await dialog.getByRole('button', { name: 'Close', exact: true }).click() + await openSeed(page, fixtureA, fixtureA.markers.assistant(fixtureA.turns)) + await expectBottom(page) + + interface ReturnFrame { + frame: number + t: number + sessionA: boolean + markerY: number | null + markerVisible: boolean + scrollTop: number + floor: number + viewportHeight: number + columnHeight: number + spacer: number + motionEnabled: boolean + motion: string[] + following: boolean + running: boolean + responseLength: number | null + } + const sampleReturn = async (marker: string): Promise => { + await openSeed(page, fixtureB, fixtureB.markers.assistant(fixtureB.turns)) + await page.getByRole('textbox', { name: 'Search session names', exact: true }).fill(fixtureA.markers.user(1)) + const result = page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem') + await expect.poll(() => result.count()).toBe(1) + // Start before the click; the first visible A frame is part of the assertion, not a setup wait. + const trace = page.evaluate(({ marker, identity }) => new Promise((resolve) => { + const samples: ReturnFrame[] = [] + let frame = 0 + let timer = 0 + let visibleFrames = 0 + let ordinal = 0 + const finish = (): void => { + cancelAnimationFrame(frame) + window.clearTimeout(timer) + document.removeEventListener('dsh-test-return-stop', finish) + document.documentElement.dataset.returnProbe = 'done' + resolve(samples) + } + const sample = (): void => { + const host = [...document.querySelectorAll('[data-conversation-scroll]')] + .find(element => !element.closest('[inert], [hidden]') && element.checkVisibility()) + const column = host?.querySelector('[data-chat-flow]:has(> [data-slot="conversation.chat.flow"])') + if (host !== undefined && column !== null && column !== undefined) { + const viewport = host.getBoundingClientRect() + const composerTop = host.querySelector('[data-composer-seat]')?.getBoundingClientRect().top ?? viewport.bottom + const node = [...column.querySelectorAll('p')] + .find(element => element.textContent?.trim() === marker) + const rect = node?.getBoundingClientRect() + const sessionA = column.textContent.includes(identity) + samples.push({ + frame: ordinal++, t: performance.now(), sessionA, + markerY: rect === undefined ? null : rect.top - viewport.top, + markerVisible: rect !== undefined && rect.bottom > viewport.top && rect.top < composerTop, + scrollTop: host.scrollTop, floor: host.scrollHeight - host.clientHeight, + viewportHeight: host.clientHeight, columnHeight: column.getBoundingClientRect().height, + spacer: host.querySelector('[data-chat-turn-spacer]')?.getBoundingClientRect().height ?? 0, + motionEnabled: column.hasAttribute('data-chat-motion'), + motion: [...column.querySelectorAll('[data-chat-motion]')] + .map(element => element.dataset.chatMotion ?? ''), + following: host.querySelector('[data-chat-following-tail]') !== null, + running: host.querySelector('[data-chat-running]') !== null, + responseLength: node?.closest('[data-chat-flow-key]')?.textContent?.length ?? null, + }) + if (sessionA) visibleFrames += 1 + } + if (visibleFrames >= 60) finish() + else frame = requestAnimationFrame(tick) + } + // A zero-delay task samples after this frame's animation callbacks, including native scrolling. + const tick = (): void => { timer = window.setTimeout(sample, 0) } + document.addEventListener('dsh-test-return-stop', finish, { once: true }) + document.documentElement.dataset.returnProbe = 'ready' + frame = requestAnimationFrame(tick) + }), { marker, identity: 'CHAT_SCROLL_RETURN_A_' }) + try { + await page.locator('html[data-return-probe="ready"]').waitFor() + await result.click() + await page.locator('html[data-return-probe="done"]').waitFor({ timeout: 15_000 }) + } finally { + await page.evaluate(() => { document.dispatchEvent(new Event('dsh-test-return-stop')) }) + await trace + await page.evaluate(() => { delete document.documentElement.dataset.returnProbe }) + } + return trace + } + const gates = [Promise.withResolvers(), Promise.withResolvers()] + const held = [false, false] + const dispose = world.scaffold.ctx.on('llm/stream', async function* (_options, next) { + let index = -1 + for await (const chunk of next()) { + if (chunk.type === 'text-delta') { + const gate = gates[index++] + if (gate !== undefined) { + held[index - 1] = true + await gate.promise + } + } + yield chunk + } + }) + let settled: ReturnType | undefined + await page.context().tracing.start({ screenshots: true, snapshots: true }) + try { + await page.locator('[data-composer-input][contenteditable="true"]').last().fill('CHAT_RUNNING_RETURN_NEXT_INPUT') + await page.getByRole('button', { name: 'Send message', exact: true }).click() + await expect.poll(() => held[0]).toBe(true) + await page.getByText(heldMarker, { exact: true }).waitFor() + await page.locator('[data-chat-running]').waitFor() + await page.locator('[data-chat-flow][data-chat-motion=""]').waitFor() + await expect.poll(() => page.locator('[data-chat-motion="collapse"], [data-chat-motion="reveal"]').count()).toBe(0) + await expectBottom(page) + const before = await scrollGeometry(page) + const chunkCount = () => world.assistantFrames.filter(frame => frame.type === 'chunk').length + const heldChunks = chunkCount() + const running = await sampleReturn(heldMarker) + const chunksAfterReturn = chunkCount() + await writeFile(join(evidence, 'running-frames.json'), JSON.stringify({ before, heldChunks, chunksAfterReturn, samples: running }, null, 2)) + await page.screenshot({ path: join(evidence, 'running-held.png') }) + expect(chunksAfterReturn).toBe(heldChunks) + expect(world.events.some(event => event.type === 'turn/end')).toBe(false) + await page.getByRole('button', { name: 'Stop generating', exact: true }).waitFor() + + const beforeGrowth = await scrollGeometry(page) + gates[0]!.resolve(undefined) + await expect.poll(() => held[1]).toBe(true) + await page.getByText(grownMarker, { exact: true }).waitFor() + await expectBottom(page) + const afterGrowth = await scrollGeometry(page) + expect(afterGrowth.scrollTop - beforeGrowth.scrollTop).toBeGreaterThan(200) + expect(await page.locator('[data-chat-following-tail]').count()).toBe(1) + await page.getByRole('button', { name: 'Stop generating', exact: true }).waitFor() + await expectMarkerAboveComposer(page, grownMarker) + settled = world.scaffold.whenTurnSettled() + gates[1]!.resolve(undefined) + await settled + await page.getByText(doneMarker, { exact: true }).waitFor() + await expect.poll(() => page.locator('[data-chat-running], [data-streaming="true"]').count()).toBe(0) + await expectBottom(page) + const completed = await sampleReturn(doneMarker) + await page.screenshot({ path: join(evidence, 'completed.png') }) + const summarize = (samples: ReturnFrame[]) => { + const visible = samples.filter(sample => sample.sessionA) + const first = visible[0]! + const markerMovement = Math.max(...visible.map(sample => + sample.markerY === null || first.markerY === null ? Infinity : Math.abs(sample.markerY - first.markerY))) + return { frames: visible.length, markerMovement, first, last: visible.at(-1)! } + } + const summary = { running: summarize(running), completed: summarize(completed) } + await writeFile(join(evidence, 'return-trace.json'), JSON.stringify({ + viewport: { width: 1280, height: 720 }, mode: 'standard', collapseTiming: 'next-input', + historyTurns: { a: fixtureA.turns, b: fixtureB.turns }, initialTextLength: parts[0]!.length, + before, heldChunks, chunksAfterReturn, beforeGrowth, afterGrowth, summary, running, completed, + }, null, 2)) + console.log(`running-return e2e: ${JSON.stringify(summary)}; evidence=${evidence}`) + for (const [name, samples] of [['completed', completed], ['running', running]] as const) { + const visible = samples.filter(sample => sample.sessionA) + expect(visible.length, `${name} return did not capture its first 60 visible frames`).toBe(60) + expect(visible.every(sample => sample.markerY !== null), `${name} return omitted the response in a visible frame`).toBe(true) + expect(visible.every(sample => sample.running === (name === 'running'))).toBe(true) + expect(new Set(visible.map(sample => sample.responseLength)).size, `${name} response changed while output was held`).toBe(1) + expect(summary[name].markerMovement, `${name} Session moved after its first visible frame; trace=${evidence}`) + .toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + } + await expectBottom(page) + assertClean(world) + } finally { + settled ??= world.events.some(event => event.type === 'turn/start') + && !world.events.some(event => event.type === 'turn/end') ? world.scaffold.whenTurnSettled() : undefined + for (const gate of gates) gate.resolve(undefined) + dispose() + try { + await settled + } finally { + await page.context().tracing.stop({ path: join(evidence, 'browser-trace.zip') }) + } + } + }) + }) + it.skipIf(MODE === 'record')('keeps floating controls anchored outside the clipped transcript', async () => { await withScrollWorld({ failureShot: 'web-e2e-chat-floating-controls', @@ -906,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 { @@ -1138,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/collapse-timing.e2e.ts b/apps/web/tests/collapse-timing.e2e.ts new file mode 100644 index 0000000000..0c6a2ecf02 --- /dev/null +++ b/apps/web/tests/collapse-timing.e2e.ts @@ -0,0 +1,191 @@ +/** Recorded work details rendered with independent completion and next-input folding. */ +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Browser, Page, Route } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { deriveReplayScript } from '@deepseek-ai/dsh-llm-replay' +import { SessionId } from '@deepseek-ai/dsh-session' +import { + assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, + launchWebScaffold, parseSeedFixture, readPersistedEvents, seedSession, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { newEnglishPage, openSettings, saveFailureShot, writeComposerDraft } from './support.ts' + +const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/collapse-timing', import.meta.url)) +const SEED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url)) +const SCREENSHOTS = 'screenshots/collapse-timing' +const SCREENSHOT_DIR = fileURLToPath(new URL(`../../../.artifacts/${SCREENSHOTS}`, import.meta.url)) +const SEED_ID = 'collapse-timing-web-e2e' +const MODE = webSnapshotMode() +const UI_WAIT = { timeout: 10_000 } +const GOLDENS = [ + 'completion.expected.md', + 'next-input.expected.md', + 'completion-restored.expected.md', + 'input-pending.expected.md', + 'next-message.expected.md', + 'verbose.expected.md', +] + +describe.skipIf(MODE === 'record')('web e2e: recorded collapse timing', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + let fixture: string + let prompt: string + let replayDir: string + + beforeAll(async () => { + fixture = await readFile(SEED, 'utf8') + const prompts = fixtureUserPrompts(fixture) + expect(prompts).toHaveLength(1) + prompt = prompts[0]! + const continuation = deriveReplayScript(parseSeedFixture(fixture).events).at(-1) + expect(continuation?.kind).toBe('chunks') + replayDir = await mkdtemp(join(tmpdir(), 'dsh-collapse-timing-replay-')) + const replayOverride = join(replayDir, 'replay.override.json') + // Reuse the recorded final reasoning and answer without repeating historical tool-call ids. + await writeFile(replayOverride, JSON.stringify([continuation])) + scaffold = await launchWebScaffold({ + replayFixture: SEED, + replayOverride, + // This rendering borrows a completed turn and replays only its final response as a continuation. + compareReplaySession: false, + }) + await seedSession(scaffold, fixture, SEED_ID) + browser = await chromium.launch({ headless: true }) + page = await newEnglishPage(browser) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.getByRole('button', { name: 'Account menu', exact: true }).waitFor() + }) + + afterAll(async () => { + const failures: unknown[] = [] + await browser?.close().catch((error: unknown) => failures.push(error)) + await scaffold?.close().catch((error: unknown) => failures.push(error)) + if (replayDir !== undefined) { + await rm(replayDir, { recursive: true, force: true }).catch((error: unknown) => failures.push(error)) + } + if (failures.length > 0) throw new AggregateError(failures, 'collapse-timing e2e cleanup failed') + }) + + async function selectPreference(title: string, choice: string): Promise { + await openSettings(page, 'en') + const dialog = page.getByRole('dialog', { name: 'Settings', exact: true }) + const row = dialog.getByText(title, { exact: true }).locator('../..') + await row.getByRole('button').click() + await page.getByRole('menuitem', { name: choice, exact: true }).click() + await row.getByRole('button', { name: choice, exact: true }).waitFor() + if (title === 'Work details') { + await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value, UI_WAIT) + .toMatchObject({ transcriptView: choice.toLowerCase() }) + } + await dialog.getByRole('button', { name: 'Close', exact: true }).click() + } + + async function capture(name: string): Promise { + await page.mouse.move(0, 0) + const aria = await captureStableAria(page, '[data-chat-flow]', scaffold.workspaceCwd) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, name), aria, MODE) + } + + async function expectDetails(turn: number, visible: boolean): Promise { + const reasoning = page.locator(`[data-chat-turn="${turn}"] [data-variant="think"]`).last() + expect(await reasoning.count()).toBe(1) + await expect.poll(() => reasoning.isVisible(), UI_WAIT).toBe(visible) + } + + async function expectProcess(turn: number, expanded: boolean): Promise { + const process = page.locator(`[data-turn-process="${turn}"]`) + await expect.poll(() => process.getAttribute('aria-expanded'), UI_WAIT).toBe(String(expanded)) + await expectDetails(turn, expanded) + } + + it('folds at completion, defers the latest process until ordinary input, and keeps Verbose open', async () => { + onTestFailed(async () => { + await mkdir(SCREENSHOT_DIR, { recursive: true }) + const directory = await mkdtemp(join(SCREENSHOT_DIR, 'recorded-')) + await saveFailureShot(page, `${SCREENSHOTS}/${basename(directory)}/failure`) + }) + // Selecting the current client default does not create a saved Host preference. + await selectPreference('Work details', 'Compact') + await selectPreference('Work details', 'Detailed') + const group = page.getByRole('treeitem').first() + await group.waitFor() + if (await group.getAttribute('aria-expanded') === 'false') await group.click() + await page.getByRole('treeitem').nth(1).click() + await page.getByText('DONE', { exact: true }).waitFor() + await expectProcess(1, false) + await capture('completion.expected.md') + + await selectPreference('When to Collapse Work Details', 'On next message') + await expectProcess(1, true) + await page.getByRole('button', { name: 'Read a.txt', exact: true }).waitFor() + await capture('next-input.expected.md') + + await selectPreference('When to Collapse Work Details', 'On completion') + await expectProcess(1, false) + await capture('completion-restored.expected.md') + + await selectPreference('When to Collapse Work Details', 'On next message') + await expectProcess(1, true) + const input = page.locator('[data-composer-input]').last() + await writeComposerDraft(page, input, prompt) + await expectProcess(1, true) + const release = Promise.withResolvers() + const promptBlocked = Promise.withResolvers() + const holdPrompt = async (route: Route): Promise => { + promptBlocked.resolve(undefined) + await release.promise + await route.continue() + } + await page.route('**/api/session/prompt', holdPrompt) + try { + await page.getByRole('button', { name: 'Send message', exact: true }).click() + const blockedTimeout = setTimeout(() => { + promptBlocked.reject(new Error('session prompt did not reach the route barrier')) + }, UI_WAIT.timeout) + try { + await promptBlocked.promise + } finally { + clearTimeout(blockedTimeout) + } + await expect.poll(() => page.locator('[data-submission-echo]').count(), UI_WAIT).toBe(1) + await expectProcess(1, false) + expect(await page.locator('[data-turn-process="2"]').count()).toBe(0) + await capture('input-pending.expected.md') + const settled = scaffold.whenTurnSettled() + release.resolve(undefined) + expect(await settled).toBe(SEED_ID) + } finally { + release.resolve(undefined) + await page.unrouteAll({ behavior: 'wait' }) + } + await expect.poll(() => page.getByText('DONE', { exact: true }).count(), UI_WAIT).toBe(2) + await expect.poll(() => page.locator('[data-streaming="true"]').count(), UI_WAIT).toBe(0) + await expectProcess(1, false) + await expectProcess(2, true) + const persisted = await readPersistedEvents(scaffold, SessionId(SEED_ID)) + expect(persisted.filter(event => event.type === 'turn/end').map(event => event.data)).toEqual([ + { turn: 1, reason: { kind: 'completed' } }, + { turn: 2, reason: { kind: 'completed' } }, + ]) + await capture('next-message.expected.md') + + await selectPreference('Work details', 'Verbose') + await selectPreference('When to Collapse Work Details', 'On completion') + await expectDetails(1, true) + await expectDetails(2, true) + expect(await page.locator('[data-turn-process]:enabled').count()).toBe(0) + await capture('verbose.expected.md') + expect(await readFile(SEED, 'utf8')).toBe(fixture) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + await assertFixtureInventory(SNAPSHOT_DIR, GOLDENS) + }) +}) diff --git a/apps/web/tests/composer-focus.e2e.ts b/apps/web/tests/composer-focus.e2e.ts new file mode 100644 index 0000000000..39c73a4937 --- /dev/null +++ b/apps/web/tests/composer-focus.e2e.ts @@ -0,0 +1,151 @@ +/** Browser selection and focus after presses in the composer's unused space. */ +import { fileURLToPath } from 'node:url' +import { join } from 'node:path' +import { chromium, type Page } from 'playwright' +import { expect, it, onTestFailed, onTestFinished } from 'vitest' +import { + assertFixtureInventory, compareOrRefreshGolden, launchWebScaffold, seedSession, watchConsole, webSnapshotMode, +} from './scaffold.ts' +import { createChatScrollFixture } from './chat-scroll-fixture.ts' +import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' + +const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/composer-focus', import.meta.url)) +const EXPECTED = join(SNAPSHOT_DIR, 'focus.expected.md') + +/** + * Observe focus and both ends of the browser selection, including its direction. + * @param page - Page containing the active composer. + * @returns The editor's focus, draft and DOM selection. + */ +async function selectionState(page: Page) { + return await page.locator('[data-composer-input]').evaluate((input) => { + const selection = window.getSelection() + return { + focused: document.activeElement === input, + draft: input.textContent, + text: selection?.toString(), + anchor: selection?.anchorOffset, + focus: selection?.focusOffset, + } + }) +} + +/** + * Format observed browser focus and selection for the golden file. + * @param state - Current browser selection. + * @returns Focus, selected text and directed offsets. + */ +function describeSelection(state: Awaited>): string { + return `${state.focused ? 'focused' : 'unfocused'}; selection ${JSON.stringify(state.text)} (${state.anchor} → ${state.focus})` +} + +/** + * Exercise the card's top, inter-row gap, toolbar gap and bottom padding. + * @param page - Page containing an editable composer. + * @returns Stable behavior observations for the expected-output file. + */ +async function exerciseComposer(page: Page): Promise { + const input = page.locator('[data-composer-input][contenteditable="true"]') + await input.click() + // Let the editor observe its insertText selection before native arrow moves; + // a coalesced first notification can otherwise be treated as its own update. + await input.evaluate((el) => { + const onSelectionChange = (): void => { + const selection = el.ownerDocument.getSelection() + if (selection === null || !el.contains(selection.anchorNode) || !el.contains(selection.focusNode)) return + if (selection.isCollapsed && selection.anchorOffset === 16 && el.textContent === 'alpha beta gamma') { + el.dataset.selectionReady = 'inserted' + return + } + if (selection.toString() !== 'beta' || selection.anchorOffset !== 10 || selection.focusOffset !== 6) return + el.dataset.selectionReady = 'selected' + el.ownerDocument.removeEventListener('selectionchange', onSelectionChange) + } + el.ownerDocument.addEventListener('selectionchange', onSelectionChange) + }) + await page.keyboard.insertText('alpha beta gamma') + await expect.poll(() => input.getAttribute('data-selection-ready')).toBe('inserted') + await page.keyboard.press('Home') + for (let index = 0; index < 10; index++) await page.keyboard.press('ArrowRight') + for (let index = 0; index < 4; index++) await page.keyboard.press('Shift+ArrowLeft') + const selected = { focused: true, draft: 'alpha beta gamma', text: 'beta', anchor: 10, focus: 6 } + await expect.poll(() => selectionState(page)).toEqual(selected) + + const points = await page.locator('[data-composer-card]').evaluate((card) => { + const box = card.getBoundingClientRect() + const scroll = card.querySelector('[data-input-scroll]')!.getBoundingClientRect() + const rowElement = card.querySelector('[data-input-scroll]')!.nextElementSibling! + const row = rowElement.getBoundingClientRect() + const tools = rowElement.firstElementChild!.getBoundingClientRect() + const trailing = rowElement.lastElementChild!.getBoundingClientRect() + if (trailing.left <= tools.right) throw new Error('Composer toolbar has no unused gap') + return [ + { name: 'top padding', x: box.x + box.width / 2, y: (box.top + scroll.top) / 2 }, + { name: 'row gap', x: box.x + box.width / 2, y: (scroll.bottom + row.top) / 2 }, + { name: 'toolbar gap', x: (tools.right + trailing.left) / 2, y: row.top + row.height / 2 }, + { name: 'bottom padding', x: box.x + box.width / 2, y: box.bottom - 2 }, + ] + }) + const observations: string[] = [] + for (const point of points) { + await page.mouse.click(point.x, point.y) + await expect.poll(() => selectionState(page)).toEqual(selected) + observations.push(`- ${point.name}: ${describeSelection(await selectionState(page))}`) + } + + await expect.poll(() => input.getAttribute('data-selection-ready')).toBe('selected') + await input.evaluate((el) => { delete el.dataset.selectionReady }) + const top = points[0]! + const cardBox = await page.locator('[data-composer-card]').boundingBox() + await page.mouse.click(cardBox!.x - 12, top.y) + await expect.poll(async () => (await selectionState(page)).focused).toBe(false) + await page.mouse.click(top.x, top.y) + await expect.poll(() => selectionState(page)).toEqual(selected) + observations.push(`- return from outside: ${describeSelection(await selectionState(page))}`) + + await page.keyboard.insertText('BETA') + await expect.poll(() => input.textContent()).toBe('alpha BETA gamma') + await page.keyboard.press('ArrowLeft') + const caret = { focused: true, draft: 'alpha BETA gamma', text: '', anchor: 9, focus: 9 } + await expect.poll(() => selectionState(page)).toEqual(caret) + await page.mouse.click(top.x, top.y) + await expect.poll(() => selectionState(page)).toEqual(caret) + await page.keyboard.insertText('!') + await expect.poll(() => input.textContent()).toBe('alpha BET!A gamma') + observations.push(`- typing replaces the restored selection and resumes at the restored caret: ${await input.textContent()}`) + return observations +} + +it('restores the previous caret or selection in fresh and existing sessions', async () => { + const scaffold = await launchWebScaffold({}) + const browserPromise = chromium.launch() + onTestFinished(async () => { + try { await (await browserPromise).close() } + finally { await scaffold.close() } + }) + const browser = await browserPromise + const fixture = createChatScrollFixture({ markerPrefix: 'COMPOSER_FOCUS', title: 'Composer focus', turns: 1 }) + await seedSession(scaffold, fixture.log, 'composer-focus-web-e2e') + const page = await newEnglishPage(browser) + onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-focus')) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspace(page, scaffold.workspaceCwd, 'composer-focus') + const hero = await exerciseComposer(page) + + await page.getByRole('button', { name: 'Search sessions' }).click() + await page.getByRole('textbox', { name: 'Search session names', exact: true }).fill(fixture.markers.user(1)) + const result = page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem') + await expect.poll(() => result.count(), { timeout: 60_000 }).toBe(1) + await result.click() + await page.getByText(fixture.markers.assistant(1), { exact: false }).last().waitFor() + const docked = await exerciseComposer(page) + + await compareOrRefreshGolden(EXPECTED, [ + '# Composer whitespace focus', '', '## Fresh session', '', ...hero, + '', '## Existing session', '', ...docked, + ].join('\n'), webSnapshotMode()) + await assertFixtureInventory(SNAPSHOT_DIR, ['focus.expected.md']) + if (webSnapshotMode() !== 'record') expect(tripwire.warnings).toEqual([]) + expect(tripwire.pageErrors).toEqual([]) +}, 180_000) diff --git a/apps/web/tests/cot-translation-paid.e2e.ts b/apps/web/tests/cot-translation-paid.e2e.ts index 235db04364..572118b7eb 100644 --- a/apps/web/tests/cot-translation-paid.e2e.ts +++ b/apps/web/tests/cot-translation-paid.e2e.ts @@ -58,6 +58,13 @@ async function messageBody(request: IncomingMessage): Promise } +/** Account model listing at the Messages origin; the version name is arbitrary because selection uses the id. */ +function listing(response: ServerResponse): void { + response.writeHead(200, { 'content-type': 'application/json' }) + response.end(JSON.stringify({ object: 'list', data: [{ id: 'deepseek-flash', name: 'Native Flash arbitrary future version', + api_capabilities: { anthropic_messages: {} } }] })) +} + /** Complete external native Messages SSE; no Host method or adapter is replaced. */ function reply(response: ServerResponse, text: string): void { response.writeHead(200, { 'content-type': 'text/event-stream' }) @@ -81,6 +88,7 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr let holdNext = false async function respond(request: IncomingMessage, response: ServerResponse): Promise { const path = new URL(request.url ?? '/', 'http://native.test').pathname + if (path === '/models') { listing(response); return } if (path !== '/anthropic/v1/messages') throw new Error(`Unexpected external translation request: ${path}`) const auditSessionId = resources.sessionId if (auditSessionId === undefined || resources.scaffold === undefined) throw new Error('Paid I/O preceded the recorded Session') @@ -123,8 +131,7 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr const origin = `http://127.0.0.1:${address.port}` const overlay = join(root, 'paid-translation.patch.yml') await writeFile(overlay, JSON.stringify([ - { id: 'llm-deepseek-account', config: { baseURL: `${origin}/anthropic`, reasoningEffort: 'high', - models: [{ id: 'deepseek-flash', name: 'Native Flash arbitrary future version' }] } }, + { id: 'llm-deepseek-account', config: { baseURL: `${origin}/anthropic`, reasoningEffort: 'high' } }, { id: 'translator', config: { bingEndpoint: `${origin}/unexpected-free`, googleEndpoint: `${origin}/unexpected-free`, deepseekTimeoutMs: 120_000 } }, ])) @@ -168,6 +175,7 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr await settings.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await settings.getByRole('button', { name: '插件', exact: true }).click() const panel = settings.locator('[data-plugin-panel]'), card = panel.locator(`[data-plugin-package="${BUNDLE_NAME}"]`) + await panel.getByRole('button', { name: '更多', exact: true }).click() const toggle = card.getByRole('switch'); await toggle.waitFor() expect(await toggle.getAttribute('aria-checked')).toBe('false') await toggle.click() @@ -192,10 +200,10 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr await expect.poll(() => translated.getAttribute('data-translation-state')).toBe('ready') expect(calls).toHaveLength(1) await compareOrRefreshGolden(join(EXPECTED, 'paid-result.expected.md'), - await captureStableAria(page, '[data-cot-translation]', scaffold.workspaceCwd), MODE) - await translated.getByRole('button', { name: '原文', exact: true }).click() + await captureStableAria(page, '[data-variant="think"]', scaffold.workspaceCwd), MODE) + await translated.getByRole('button', { name: '查看原文', exact: true }).click() await translated.getByText(ORIGINAL, { exact: true }).waitFor() - await translated.getByRole('button', { name: '译文', exact: true }).click() + await translated.getByRole('button', { name: '查看译文', exact: true }).click() expect(calls).toHaveLength(1) const saved = await readPersistedEvents(scaffold, auditSessionId) expect(saved.filter(event => !isTranslationRecord(event))).toEqual(events) diff --git a/apps/web/tests/cot-translation.e2e.ts b/apps/web/tests/cot-translation.e2e.ts index beb296eeda..9a804fe8b5 100644 --- a/apps/web/tests/cot-translation.e2e.ts +++ b/apps/web/tests/cot-translation.e2e.ts @@ -195,6 +195,7 @@ it.skipIf(MODE === 'record')('persists Bing reasoning translation across reopen await settings.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await settings.getByRole('button', { name: '插件', exact: true }).click() const panel = settings.locator('[data-plugin-panel]') + await panel.getByRole('button', { name: '更多', exact: true }).click() const card = panel.locator(`[data-plugin-package="${BUNDLE_NAME}"]`) const toggle = card.getByRole('switch') await toggle.waitFor() @@ -219,11 +220,35 @@ it.skipIf(MODE === 'record')('persists Bing reasoning translation across reopen await expect.poll(() => body.getAttribute('data-translation-state')).toBe('ready') expect(calls).toEqual([{ provider: 'bing', text: ORIGINAL, target: 'zh-Hans', hasAuthorization: false, hasCookie: false }]) await compareOrRefreshGolden(join(EXPECTED, 'bing.expected.md'), - await captureStableAria(page, '[data-cot-translation]', scaffold.workspaceCwd), MODE) - await body.getByRole('button', { name: '原文', exact: true }).click() + await captureStableAria(page, '[data-variant="think"]', scaffold.workspaceCwd), MODE) + const markdown = body.locator('[data-markdown-variant="compact"]') + const typography = () => markdown.evaluate((element) => { + const style = getComputedStyle(element) + return [style.fontFamily, style.fontSize, style.fontWeight, style.lineHeight, style.color, style.padding, style.margin] + }) + const translatedTypography = await typography() + const originalAction = body.getByRole('button', { name: '查看原文', exact: true }) + await composer.focus() + await page.mouse.move(0, 0) + await expect.poll(() => originalAction.evaluate(element => getComputedStyle(element).opacity)).toBe('1') + expect(await originalAction.evaluate(element => element.closest('[data-disclosure-header]') === null)).toBe(true) + await originalAction.focus() + await expect.poll(() => originalAction.evaluate(element => getComputedStyle(element).opacity)).toBe('1') + await originalAction.press('Enter') await body.getByText(ORIGINAL, { exact: true }).waitFor() expect(await body.getAttribute('data-translation-view')).toBe('original') - await body.getByRole('button', { name: '译文', exact: true }).click() + expect(await typography()).toEqual(translatedTypography) + await page.mouse.move(0, 0) + const translationAction = body.getByRole('button', { name: '查看译文', exact: true }) + const titleBox = await reasoning.getByRole('button', { name: '思考', exact: true }).boundingBox() + const actionBox = await translationAction.boundingBox() + if (titleBox === null || actionBox === null) throw new Error('Reasoning title and translation action must be visible') + expect(actionBox.y).toBeGreaterThanOrEqual(titleBox.y + titleBox.height) + expect(await translationAction.evaluate(element => getComputedStyle(element).opacity)).toBe('1') + await translationAction.click() + await composer.focus() + await reasoning.hover() + await expect.poll(() => originalAction.evaluate(element => getComputedStyle(element).opacity)).toBe('1') await body.getByText(BING_TRANSLATION, { exact: true }).waitFor() expect(calls).toHaveLength(1) const savedBing = await readPersistedEvents(scaffold, sessionId) @@ -275,13 +300,13 @@ it.skipIf(MODE === 'record')('persists Bing reasoning translation across reopen await save.click() await expect.poll(() => save.isDisabled()).toBe(true) await expect.poll(() => body.getAttribute('data-translation-state')).toBe('failed') - await body.getByText('翻译失败,已保留原文', { exact: true }).waitFor() + await body.getByText('翻译暂不可用,已显示原文', { exact: true }).waitFor() await body.getByText(ORIGINAL, { exact: true }).waitFor() expect(await body.getAttribute('data-translation-view')).toBe('original') expect(calls[2]).toEqual({ provider: 'google', text: ORIGINAL, target: 'ja', hasAuthorization: false, hasCookie: false }) expect(calls).toHaveLength(3) await compareOrRefreshGolden(join(EXPECTED, 'failure.expected.md'), - await captureStableAria(page, '[data-cot-translation]', scaffold.workspaceCwd), MODE) + await captureStableAria(page, '[data-variant="think"]', scaffold.workspaceCwd), MODE) fail = false await body.getByRole('button', { name: '重试', exact: true }).click() await body.getByText(JAPANESE_TRANSLATION, { exact: true }).waitFor() @@ -315,7 +340,7 @@ it.skipIf(MODE === 'record')('persists Bing reasoning translation across reopen await expect.poll(() => body.getAttribute('data-translation-state')).toBe('ready') expect(calls).toHaveLength(6) - await panel.getByRole('button', { name: '返回插件列表', exact: true }).click() + await panel.getByRole('button', { name: '返回 实验性插件', exact: true }).click() await toggle.click() await expect.poll(() => toggle.getAttribute('aria-checked'), { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toBe('false') await body.waitFor({ state: 'detached' }) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index 52a3fd09a3..225cb37062 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -39,6 +39,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett expect(scaffold.ctx.llm.listProviders()).toContainEqual({ id: 'deepseek-official', name: 'DeepSeek' }) expect(scaffold.ctx.llm.listProviders().filter(provider => provider.id === 'deepseek-official')).toHaveLength(1) expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ provider: 'deepseek-official', model: 'deepseek-flash' }) + await page.getByRole('dialog', { name: '开始使用', exact: true }).getByRole('button', { name: '添加 API Key', exact: true }).click() const onboarding = page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }) await onboarding.getByLabel('API 密钥', { exact: true }).fill('sk-messages-onboarding') await onboarding.getByRole('button', { name: '保存并继续' }).click() @@ -52,7 +53,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett const messages = dialog await messages.getByText('自定义设置', { exact: true }).click() expect(await messages.getByLabel('API 地址', { exact: true }).getAttribute('placeholder')) - .toBe('https://api.deepseek.com/anthropic') + .toBe('https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)') await compareOrRefreshGolden(join(EXPECTED, 'cards.expected.md'), await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode()) await messages.getByLabel('API 密钥', { exact: true }).fill('sk-e2e-messages') @@ -96,14 +97,18 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett await scaffold.ctx.agentDefaultModel.saveSelection({ provider: 'deepseek-official', model: 'deepseek-v4-flash' }) await page.reload({ waitUntil: 'load' }) const input = page.locator('[data-composer-input]').first() - const trigger = page.getByRole('button', { name: /^选择模型.*deepseek-official\/deepseek-v4-flash/ }) + const trigger = page.getByRole('button', { name: '请选择模型', exact: true }) await trigger.waitFor() + expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ + provider: 'deepseek-official', model: 'deepseek-v4-flash', + }) await expect.poll(() => input.getAttribute('contenteditable')).toBe('true') await trigger.click() - await page.getByRole('menuitem', { name: /模型/ }).click() await page.getByRole('menuitemradio', { name: 'Messages Flash', exact: true }).click() await expect.poll(() => input.getAttribute('contenteditable')).toBe('true') - await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().provider).toBe('deepseek-official') + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection()).toMatchObject({ + provider: 'deepseek-official', model: 'deepseek-flash', + }) const settings = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8') expect(settings).toContain('provider: deepseek-official') expect(tripwire.pageErrors).toEqual([]) diff --git a/apps/web/tests/default-model.e2e.ts b/apps/web/tests/default-model.e2e.ts index d87bf4ce4d..72ebfb69c2 100644 --- a/apps/web/tests/default-model.e2e.ts +++ b/apps/web/tests/default-model.e2e.ts @@ -487,14 +487,13 @@ describe('web e2e: the composer model switch is the default for later sessions', baseURL: 'https://gateway.origin.example/v1', models: [{ id: START_MODEL, name: 'Origin Large' }] }, } }) - const seat = page.getByRole('button', { name: new RegExp(`^选择模型.*${ROUTE}/${MODEL}`) }) + const seat = page.getByRole('button', { name: '请选择模型', exact: true }) await seat.waitFor() expect(await box.isEnabled()).toBe(true) expect(scaffold.ctx.agentDefaultModel.currentSelection()).toMatchObject({ provider: ROUTE, model: MODEL }) const aria = await captureStableAria(page, '[data-composer-card]', scaffold.workspaceCwd) await compareOrRefreshGolden(fileURLToPath(new URL('./expected/default-model/unselected.expected.md', import.meta.url)), aria, webSnapshotMode()) await seat.click() - await page.getByRole('menuitem', { name: /模型/ }).click() await page.getByRole('menuitemradio').first().click() await expect.poll(async () => box.isEnabled(), { timeout: 15_000 }).toBe(true) expect(tripwire.pageErrors).toEqual([]) diff --git a/apps/web/tests/desktop-onboarding.e2e.ts b/apps/web/tests/desktop-onboarding.e2e.ts index e512813ffc..4f0b527885 100644 --- a/apps/web/tests/desktop-onboarding.e2e.ts +++ b/apps/web/tests/desktop-onboarding.e2e.ts @@ -100,6 +100,16 @@ describe.skipIf(MODE === 'record')('web e2e: App-only desktop onboarding', () => async function snapshot(name: string): Promise { await expect.poll(() => page.locator('[data-desktop-onboarding]').getAttribute('aria-busy')).toBe('false') + const hasIllustration = name.startsWith('welcome') || name.startsWith('credit') + if (hasIllustration) { + const decoded = await page.locator('[class*="illustration"] > img').evaluateAll(async elements => + Promise.all(elements.map(async (element) => { + const image = element as HTMLImageElement + await image.decode() + return image.naturalWidth > 0 && image.naturalHeight > 0 + }))) + expect(decoded).toEqual([true, true]) + } const aria = await captureStableAria(page, '[data-desktop-onboarding]', scaffold.workspaceCwd) await mkdir(EXPECTED, { recursive: true }) await compareOrRefreshGolden(join(EXPECTED, `${name}.expected.md`), aria, MODE) @@ -171,7 +181,7 @@ describe.skipIf(MODE === 'record')('web e2e: App-only desktop onboarding', () => expect(action?.width).toBeCloseTo(240, 0) expect(action!.y - (card!.y + card!.height)).toBeCloseTo(40, 0) } - if (name === 'welcome' || name === 'credit') { + if (hasIllustration) { const illustrations = await page.locator('[class*="illustration"] > img:visible').evaluateAll(elements => elements.map((element) => { const image = element as HTMLImageElement const box = image.getBoundingClientRect() diff --git a/apps/web/tests/expected/access-confirmation/auto-confirmation.expected.md b/apps/web/tests/expected/access-confirmation/auto-confirmation.expected.md index b9967c9722..6c7320a3da 100644 --- a/apps/web/tests/expected/access-confirmation/auto-confirmation.expected.md +++ b/apps/web/tests/expected/access-confirmation/auto-confirmation.expected.md @@ -1,8 +1,8 @@ -- dialog "确认启用 Auto review(实验)?": - - heading "确认启用 Auto review(实验)?" [level=2] +- dialog "确认启用自动审查(实验)?": + - heading "确认启用自动审查(实验)?" [level=2] - button "关闭" - - paragraph: Auto review 不使用沙箱。每次原生工具调用和 PTC 内层调用前,都会由与当前 agent 相同的模型进行审查;审查拒绝的调用由你批准或拒绝。此功能仍属实验性,可能误放行或误拒绝,并会消耗额外 token。 + - paragraph: 自动审查不使用沙箱。每次原生工具调用和 PTC 内层调用前,都会由与当前 agent 相同的模型进行审查;审查拒绝的调用由你批准或拒绝。此功能仍属实验性,可能误放行或误拒绝,并会消耗额外 token。 - checkbox "我已了解这些风险,并愿意继续" - text: 我已了解这些风险,并愿意继续 - button "取消" - - button "启用 Auto review" [disabled] + - button "启用自动审查" [disabled] diff --git a/apps/web/tests/expected/access-confirmation/current-session-picker.expected.md b/apps/web/tests/expected/access-confirmation/current-session-picker.expected.md index 9e942e44b5..688540b20e 100644 --- a/apps/web/tests/expected/access-confirmation/current-session-picker.expected.md +++ b/apps/web/tests/expected/access-confirmation/current-session-picker.expected.md @@ -2,6 +2,4 @@ - menuitem "仅可查看" - menuitem "工作区内修改" - menuitem "完全权限" - - menuitem "Auto review EXP": - - text: Auto review - - superscript: EXP + - menuitem "自动审查 EXP" diff --git a/apps/web/tests/expected/access-confirmation/slash-picker.expected.md b/apps/web/tests/expected/access-confirmation/slash-picker.expected.md index f1b12d28b0..cf54b54669 100644 --- a/apps/web/tests/expected/access-confirmation/slash-picker.expected.md +++ b/apps/web/tests/expected/access-confirmation/slash-picker.expected.md @@ -4,7 +4,7 @@ - option "仅可查看" - option "工作区内修改" [selected] - option "完全权限" - - option "Auto review EXP": - - text: Auto review + - option "自动审查 EXP": + - text: 自动审查 - superscript: EXP - text: 无沙箱运行;每次原生工具调用和 PTC 内层调用前由同一模型进行实验性审查。 diff --git a/apps/web/tests/expected/agent-preset-authoring/section.expected.md b/apps/web/tests/expected/agent-preset-authoring/section.expected.md index a7d47106e1..dd8628cd57 100644 --- a/apps/web/tests/expected/agent-preset-authoring/section.expected.md +++ b/apps/web/tests/expected/agent-preset-authoring/section.expected.md @@ -31,7 +31,7 @@ - 'button "设为新任务默认: 极简模式"': - text: 极简模式 内置 - code: minimal - - text: Agent 仅使用终端工具完成任务,适合测试和对比其基础表现。 + - text: Agent 使用终端和图片读取工具,并支持上下文压缩,适合测试和对比其基础表现。 - 'button "模式说明: 极简模式"': 模式说明 - 'button "如何使用: 极简模式"': 如何使用 - 'button "查看配置: 极简模式"': 查看配置 diff --git a/apps/web/tests/expected/agent-preset-selection/header.expected.md b/apps/web/tests/expected/agent-preset-selection/header.expected.md index 81cc3c1175..2b87066124 100644 --- a/apps/web/tests/expected/agent-preset-selection/header.expected.md +++ b/apps/web/tests/expected/agent-preset-selection/header.expected.md @@ -1,5 +1,5 @@ - navigation "Session hierarchy": Seeded turn -- button "1 subagent" - text: Minimal mode +- button "1 subagent" - button "More actions" - button "Open right sidebar" diff --git a/apps/web/tests/expected/agent-preset-selection/menu.expected.md b/apps/web/tests/expected/agent-preset-selection/menu.expected.md index 2f715b99b1..4372c504c0 100644 --- a/apps/web/tests/expected/agent-preset-selection/menu.expected.md +++ b/apps/web/tests/expected/agent-preset-selection/menu.expected.md @@ -1,5 +1,5 @@ - menu: - menuitem "Standard mode Work with code, files, and information. Suitable for most tasks, with search, editing, terminal commands, and other tools available as needed." - menuitem "PTC mode Includes all Standard mode capabilities. Better suited to tasks that call tools in batches and then filter, organize, deduplicate, count, or summarize the results." - - menuitem "Minimal mode The agent works using only a terminal tool. Useful for testing and comparing its basic performance." + - menuitem "Minimal mode The agent uses a terminal and image reading, with context compaction. Useful for testing and comparing its basic performance." - menuitem "Creator mode Customize DSH through conversation. Let the agent write plugins that add features or UI, or combine tools and prompts to create your own mode." 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/composer-focus/focus.expected.md b/apps/web/tests/expected/composer-focus/focus.expected.md new file mode 100644 index 0000000000..03e7a8dbec --- /dev/null +++ b/apps/web/tests/expected/composer-focus/focus.expected.md @@ -0,0 +1,19 @@ +# Composer whitespace focus + +## Fresh session + +- top padding: focused; selection "beta" (10 → 6) +- row gap: focused; selection "beta" (10 → 6) +- toolbar gap: focused; selection "beta" (10 → 6) +- bottom padding: focused; selection "beta" (10 → 6) +- return from outside: focused; selection "beta" (10 → 6) +- typing replaces the restored selection and resumes at the restored caret: alpha BET!A gamma + +## Existing session + +- top padding: focused; selection "beta" (10 → 6) +- row gap: focused; selection "beta" (10 → 6) +- toolbar gap: focused; selection "beta" (10 → 6) +- bottom padding: focused; selection "beta" (10 → 6) +- return from outside: focused; selection "beta" (10 → 6) +- typing replaces the restored selection and resumes at the restored caret: alpha BET!A gamma diff --git a/apps/web/tests/expected/cot-translation-paid/paid-choices.expected.md b/apps/web/tests/expected/cot-translation-paid/paid-choices.expected.md index 4b5ac3b259..44be4fbdaf 100644 --- a/apps/web/tests/expected/cot-translation-paid/paid-choices.expected.md +++ b/apps/web/tests/expected/cot-translation-paid/paid-choices.expected.md @@ -1,8 +1,8 @@ -- button "返回插件列表": 插件列表 +- button "返回 实验性插件": 实验性插件 - button "卸载 思考过程机器翻译" [disabled]: 卸载 - switch "启用 思考过程机器翻译" [checked] - heading "思考过程机器翻译" [level=3] -- text: v0.2.1-alpha.1 实验性 +- text: v0.2.1-alpha.2 实验性 - paragraph: - code: "@deepseek-ai/dsh-experimental-cot-translation-bundle" - paragraph: 机器翻译展开的思考内容;原文会发送给所选服务 @@ -39,4 +39,4 @@ - term: 代码来源 - definition: 内置 - term: 当前版本 -- definition: 0.2.1-alpha.1 +- definition: 0.2.1-alpha.2 diff --git a/apps/web/tests/expected/cot-translation-paid/paid-result.expected.md b/apps/web/tests/expected/cot-translation-paid/paid-result.expected.md index 07d4103eff..314344b0e0 100644 --- a/apps/web/tests/expected/cot-translation-paid/paid-result.expected.md +++ b/apps/web/tests/expected/cot-translation-paid/paid-result.expected.md @@ -1,3 +1,3 @@ -- button "译文" [pressed] -- button "原文" +- button "思考" [expanded] +- button "查看原文" - paragraph: 用户要求只回复一个词,我会照做。 diff --git a/apps/web/tests/expected/cot-translation/bing.expected.md b/apps/web/tests/expected/cot-translation/bing.expected.md index 3e7616bb7f..0a9dc0e8a2 100644 --- a/apps/web/tests/expected/cot-translation/bing.expected.md +++ b/apps/web/tests/expected/cot-translation/bing.expected.md @@ -1,3 +1,3 @@ -- button "译文" [pressed] -- button "原文" +- button "思考" [expanded] +- button "查看原文" - paragraph: 用户要求我回复一个单词。 diff --git a/apps/web/tests/expected/cot-translation/failure.expected.md b/apps/web/tests/expected/cot-translation/failure.expected.md index 2b3e993532..b35237dbfa 100644 --- a/apps/web/tests/expected/cot-translation/failure.expected.md +++ b/apps/web/tests/expected/cot-translation/failure.expected.md @@ -1,5 +1,5 @@ -- button "译文" [disabled] -- button "原文" [pressed] -- status: 翻译失败,已保留原文 +- button "思考" [expanded] +- button "查看译文" [disabled] +- status: 翻译暂不可用,已显示原文 - button "重试" - paragraph: The user wants me to reply with a single word. Let me comply. diff --git a/apps/web/tests/expected/cot-translation/preferences.expected.md b/apps/web/tests/expected/cot-translation/preferences.expected.md index 48f64db554..14f544b50b 100644 --- a/apps/web/tests/expected/cot-translation/preferences.expected.md +++ b/apps/web/tests/expected/cot-translation/preferences.expected.md @@ -1,8 +1,8 @@ -- button "返回插件列表": 插件列表 +- button "返回 实验性插件": 实验性插件 - button "卸载 思考过程机器翻译" [disabled]: 卸载 - switch "启用 思考过程机器翻译" [checked] - heading "思考过程机器翻译" [level=3] -- text: v0.2.1-alpha.1 实验性 +- text: v0.2.1-alpha.2 实验性 - paragraph: - code: "@deepseek-ai/dsh-experimental-cot-translation-bundle" - paragraph: 机器翻译展开的思考内容;原文会发送给所选服务 @@ -36,4 +36,4 @@ - term: 代码来源 - definition: 内置 - term: 当前版本 -- definition: 0.2.1-alpha.1 +- definition: 0.2.1-alpha.2 diff --git a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md index 47440f7c24..55ebc9b91b 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md @@ -15,12 +15,14 @@ - img "API 密钥已配置" - button "编辑 DeepSeek (deepseek-official)": 编辑 - text: DeepSeek deepseek-official API 密钥 + - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 已配置——输入新值可替换 + - /placeholder: 留空时保留现有认证(DEEPSEEK_API_KEY) + - text: API 密钥来源:已保存凭据 - group: - text: 自定义设置 API 地址 - textbox "API 地址": - - /placeholder: https://api.deepseek.com/anthropic + - /placeholder: https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL) - text: 请填写兼容 Anthropic Messages 协议的 API 地址。 - region "模型目录": - text: 模型目录 正在使用适配器默认模型 @@ -29,7 +31,7 @@ - text: deepseek-flash - textbox "显示名称 1": - /placeholder: 显示名称 - - text: DeepSeek-V41-Flash + - text: DeepSeek-V4.1-Flash - button "模型选项 1" - button "删除模型 1" - textbox "模型 ID 2": diff --git a/apps/web/tests/expected/default-model/unselected.expected.md b/apps/web/tests/expected/default-model/unselected.expected.md index 8845f5196b..b5b50682be 100644 --- a/apps/web/tests/expected/default-model/unselected.expected.md +++ b/apps/web/tests/expected/default-model/unselected.expected.md @@ -1,5 +1,5 @@ - textbox "描述你想要构建的内容, / 调用指令, @ 文件或对话" - button "添加文件或调用指令" - button "访问模式,当前:工作区内修改": 工作区内修改 -- button "选择模型,当前 acme-gateway/acme-large": acme-gateway/acme-large +- button "请选择模型" - button "发送消息" [disabled] diff --git a/apps/web/tests/expected/desktop-locale/automatic.expected.md b/apps/web/tests/expected/desktop-locale/automatic.expected.md index e0e2e8a50b..b24ebca8d2 100644 --- a/apps/web/tests/expected/desktop-locale/automatic.expected.md +++ b/apps/web/tests/expected/desktop-locale/automatic.expected.md @@ -22,6 +22,8 @@ - button "更多字体设置" - text: 工作步骤展示 选择希望看到多少工具调用细节 - button "标准" + - text: 工作步骤收起时机 选择何时自动收起工作步骤 + - button "回答结束后" - text: 显示代码工作视图 开启后,显示轨迹、本轮代码差异,可选择完整的 Agent 预设切换 - switch "显示代码工作视图" [checked] - text: 快捷键 diff --git a/apps/web/tests/expected/desktop-locale/selected.expected.md b/apps/web/tests/expected/desktop-locale/selected.expected.md index fff8f92651..801a3d9a5d 100644 --- a/apps/web/tests/expected/desktop-locale/selected.expected.md +++ b/apps/web/tests/expected/desktop-locale/selected.expected.md @@ -22,6 +22,8 @@ - button "More font settings" - text: Work details Choose how much detail to show for tool calls - button "Standard" + - text: When to Collapse Work Details Choose when to automatically collapse work details + - button "On completion" - text: Show coding view Shows trajectory, code diffs, and all Agent presets - switch "Show coding view" [checked] - text: Keyboard shortcuts diff --git a/apps/web/tests/expected/jobs-menu-layering/geometry.expected.md b/apps/web/tests/expected/jobs-menu-layering/geometry.expected.md new file mode 100644 index 0000000000..446843f9dc --- /dev/null +++ b/apps/web/tests/expected/jobs-menu-layering/geometry.expected.md @@ -0,0 +1,35 @@ +# Background jobs above the Browser dock + +```json +{ + "collapsed": { + "dockMode": "push", + "bodyMounted": true, + "fixed": true, + "anchored": true, + "viewportBounded": true, + "overlapsBrowser": true, + "aboveBrowser": true + }, + "expanded": { + "dockMode": "push", + "bodyMounted": true, + "fixed": true, + "anchored": true, + "viewportBounded": true, + "overlapsBrowser": true, + "aboveBrowser": true + }, + "resized": { + "dockMode": "push", + "bodyMounted": true, + "fixed": true, + "anchored": true, + "viewportBounded": true, + "overlapsBrowser": true, + "aboveBrowser": true + }, + "escapeRestoresFocus": true, + "outsideDismisses": true +} +``` 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/models-settings/catalog-inputs.expected.md b/apps/web/tests/expected/models-settings/catalog-inputs.expected.md index d1047bfbb2..878d9eaf67 100644 --- a/apps/web/tests/expected/models-settings/catalog-inputs.expected.md +++ b/apps/web/tests/expected/models-settings/catalog-inputs.expected.md @@ -20,12 +20,13 @@ - button "编辑 openai": 编辑 - button "删除 openai": 删除 - text: openai API 密钥 + - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 输入 API 密钥,或留空使用环境认证 + - /placeholder: 留空时保留现有认证(OPENAI_API_KEY) - group: - text: 自定义设置 API 地址 - textbox "API 地址": - - /placeholder: 提供商默认 + - /placeholder: https://api.openai.com/v1 - region "模型目录": - text: 模型目录 已自定义模型目录 - button "恢复默认模型" diff --git a/apps/web/tests/expected/models-settings/declared-edit.expected.md b/apps/web/tests/expected/models-settings/declared-edit.expected.md index 6bc07d9474..e0c3479659 100644 --- a/apps/web/tests/expected/models-settings/declared-edit.expected.md +++ b/apps/web/tests/expected/models-settings/declared-edit.expected.md @@ -21,7 +21,7 @@ - button "删除 Acme Gateway (acme-gateway)": 删除 - text: Acme Gateway acme-gateway API 密钥 - textbox "API 密钥": - - /placeholder: 输入 API 密钥,或留空使用环境认证 + - /placeholder: 输入 API 密钥 - group: - text: 自定义设置 显示名称 - textbox "显示名称": diff --git a/apps/web/tests/expected/models-settings/empty.expected.md b/apps/web/tests/expected/models-settings/empty.expected.md index 5c2b5c0b72..795e2bb440 100644 --- a/apps/web/tests/expected/models-settings/empty.expected.md +++ b/apps/web/tests/expected/models-settings/empty.expected.md @@ -20,7 +20,7 @@ - option "amazon-bedrock" - option "ant-ling" - option "anthropic" - - option "azure-openai-responses" + - option "azure" - option "baseten" - option "cerebras" - option "cloudflare-ai-gateway" @@ -59,8 +59,9 @@ - option "zai" - option "zai-coding-cn" - text: API 密钥 + - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 输入 API 密钥,或留空使用环境认证 + - /placeholder: 留空时保留现有认证(MINIMAX_CN_API_KEY) - group: 自定义设置 - button "取消" - button "保存" diff --git a/apps/web/tests/expected/models-settings/image-only.expected.md b/apps/web/tests/expected/models-settings/image-only.expected.md index 55b5f103a0..ccde68253e 100644 --- a/apps/web/tests/expected/models-settings/image-only.expected.md +++ b/apps/web/tests/expected/models-settings/image-only.expected.md @@ -21,7 +21,7 @@ - button "删除 Acme 网关 (acme-gateway)": 删除 - text: Acme 网关 acme-gateway API 密钥 - textbox "API 密钥": - - /placeholder: 输入 API 密钥,或留空使用环境认证 + - /placeholder: 输入 API 密钥 - group: - text: 自定义设置 显示名称 - textbox "显示名称": diff --git a/apps/web/tests/expected/models-settings/native-keyless.expected.md b/apps/web/tests/expected/models-settings/native-keyless.expected.md new file mode 100644 index 0000000000..e8ae4de994 --- /dev/null +++ b/apps/web/tests/expected/models-settings/native-keyless.expected.md @@ -0,0 +1,63 @@ +- dialog "设置": + - navigation: + - text: 设置 + - button "通用设置" + - button "模型" + - button "内置插件" + - button "Agent 预设" + - button "打开配置文件" + - button "关闭" + - heading "模型" [level=2] + - paragraph: 填入各提供商的 API 密钥即可使用其模型。 + - list + - tablist "添加方式": + - tab "第三方模型提供商" [selected] + - tab "自定义模型 API" + - paragraph: 从内置目录中选择 OpenAI、Anthropic、Kimi 等提供商,填入其 API 密钥即可使用。 + - tabpanel "第三方模型提供商": + - text: 提供商 + - combobox "提供商": + - option "amazon-bedrock" + - option "ant-ling" + - option "anthropic" + - option "azure" + - option "baseten" + - option "cerebras" + - option "cloudflare-ai-gateway" + - option "cloudflare-workers-ai" + - option "deepseek" + - option "fireworks" + - option "github-copilot" + - option "google" + - option "google-vertex" + - option "groq" + - option "huggingface" + - option "kimi-coding" + - option "meta" + - option "minimax" + - option "minimax-cn" + - option "mistral" + - option "moonshotai" + - option "moonshotai-cn" + - option "nvidia" + - option "openai" + - option "openai-codex" [selected] + - option "opencode" + - option "opencode-go" + - option "openrouter" + - option "qwen-token-plan" + - option "qwen-token-plan-cn" + - option "qwen-token-plan-individual" + - option "radius" + - option "together" + - option "vercel-ai-gateway" + - option "xai" + - option "xiaomi" + - option "xiaomi-token-plan-ams" + - option "xiaomi-token-plan-cn" + - option "xiaomi-token-plan-sgp" + - option "zai" + - option "zai-coding-cn" + - group: 自定义设置 + - button "取消" + - button "保存" 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/onboarding-deepseek-config/default-models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md index 803e82b6f0..9e0deb4b08 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md @@ -15,12 +15,14 @@ - img "API 密钥已配置" - button "编辑 DeepSeek (deepseek-official)": 编辑 - text: DeepSeek deepseek-official API 密钥 + - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 已配置——输入新值可替换 + - /placeholder: 留空时保留现有认证(DEEPSEEK_API_KEY) + - text: API 密钥来源:已保存凭据 - group: - text: 自定义设置 API 地址 - textbox "API 地址": - - /placeholder: https://api.deepseek.com/anthropic + - /placeholder: https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL) - text: 请填写兼容 Anthropic Messages 协议的 API 地址。 - region "模型目录": - text: 模型目录 正在使用适配器默认模型 @@ -29,7 +31,7 @@ - text: deepseek-flash - textbox "显示名称 1": - /placeholder: 显示名称 - - text: DeepSeek-V41-Flash + - text: DeepSeek-V4.1-Flash - button "模型选项 1" [expanded] - button "删除模型 1" - text: 上下文窗口 diff --git a/apps/web/tests/expected/onboarding-deepseek-config/empty.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/empty.expected.md new file mode 100644 index 0000000000..c0a161b0e3 --- /dev/null +++ b/apps/web/tests/expected/onboarding-deepseek-config/empty.expected.md @@ -0,0 +1,2 @@ +- group "模型与推理等级": + - status: 暂无可用模型 diff --git a/apps/web/tests/expected/onboarding-deepseek-config/missing.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/missing.expected.md index d42cf40681..374d7be11e 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/missing.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/missing.expected.md @@ -2,7 +2,8 @@ - heading "添加一个 API Key 开始使用" [level=2] - paragraph: 配置 DeepSeek 官方模型,即可开始使用。 - text: API 密钥 + - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 输入 API 密钥 + - /placeholder: 留空时保留现有认证(DEEPSEEK_API_KEY) - button "稍后配置" - button "保存并继续" [disabled] diff --git a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md index 84a7261b65..2bf65bfc78 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md @@ -15,12 +15,14 @@ - img "API 密钥已配置" - button "编辑 DeepSeek (deepseek-official)": 编辑 - text: DeepSeek deepseek-official API 密钥 + - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 已配置——输入新值可替换 + - /placeholder: 留空时保留现有认证(DEEPSEEK_API_KEY) + - text: API 密钥来源:已保存凭据 - group: - text: 自定义设置 API 地址 - textbox "API 地址": - - /placeholder: https://api.deepseek.com/anthropic + - /placeholder: https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL) - text: 请填写兼容 Anthropic Messages 协议的 API 地址。 - region "模型目录": - text: 模型目录 已自定义模型目录 diff --git a/apps/web/tests/expected/onboarding-deepseek-config/sign-in.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/sign-in.expected.md new file mode 100644 index 0000000000..a689c62560 --- /dev/null +++ b/apps/web/tests/expected/onboarding-deepseek-config/sign-in.expected.md @@ -0,0 +1,6 @@ +- dialog "开始使用": + - heading "开始使用" [level=2] + - button "关闭" + - paragraph: 登录 DeepSeek 账号,或添加 API Key,即可开始使用。你的项目和文件保存在本地。 + - button "添加 API Key" + - button "登录" diff --git a/apps/web/tests/expected/onboarding-native/models.expected.md b/apps/web/tests/expected/onboarding-native/models.expected.md index ce149bad3e..f8503c31f1 100644 --- a/apps/web/tests/expected/onboarding-native/models.expected.md +++ b/apps/web/tests/expected/onboarding-native/models.expected.md @@ -12,8 +12,9 @@ - list: - listitem: - text: DeepSeek deepseek-official API 密钥 + - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 输入 API 密钥 + - /placeholder: 留空时保留现有认证(DEEPSEEK_API_KEY) - group: 自定义设置 - button "取消" - button "保存" diff --git a/apps/web/tests/expected/onboarding-usable-provider/dismissed.expected.md b/apps/web/tests/expected/onboarding-usable-provider/dismissed.expected.md index e65df1f213..9d9bae17dd 100644 --- a/apps/web/tests/expected/onboarding-usable-provider/dismissed.expected.md +++ b/apps/web/tests/expected/onboarding-usable-provider/dismissed.expected.md @@ -24,7 +24,7 @@ - option "amazon-bedrock" - option "ant-ling" - option "anthropic" - - option "azure-openai-responses" + - option "azure" - option "baseten" - option "cerebras" - option "cloudflare-ai-gateway" @@ -63,8 +63,9 @@ - option "zai" - option "zai-coding-cn" - text: API 密钥 + - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 输入 API 密钥,或留空使用环境认证 + - /placeholder: 留空时保留现有认证(MINIMAX_CN_API_KEY) - group: 自定义设置 - button "取消" - button "保存" diff --git a/apps/web/tests/expected/plugin-config/bundle.expected.md b/apps/web/tests/expected/plugin-config/bundle.expected.md index f71e0dad28..2e90c68ac0 100644 --- a/apps/web/tests/expected/plugin-config/bundle.expected.md +++ b/apps/web/tests/expected/plugin-config/bundle.expected.md @@ -1,4 +1,4 @@ -- button "返回插件列表": 插件列表 +- button "返回插件": 插件 - button "夹具操作" - button "卸载 @fixture/live-client": 卸载 - switch "启用 @fixture/live-client" [checked] diff --git a/apps/web/tests/expected/plugin-config/official.expected.md b/apps/web/tests/expected/plugin-config/official.expected.md index aee4cb8cdf..37d3a232b4 100644 --- a/apps/web/tests/expected/plugin-config/official.expected.md +++ b/apps/web/tests/expected/plugin-config/official.expected.md @@ -5,75 +5,40 @@ - group "添加插件": - button "添加插件" - button "选择添加插件方式" -- heading "官方" [level=3] -- text: "17" +- heading "内置插件配置" [level=3] - list: - - listitem: - - button "查看 智能体团队": 智能体团队 - - text: 实验性 启用团队协作、团队工具、成员列表和共享任务看板。 - - switch "启用 智能体团队" - - listitem: - - button "查看 自动授权审查": 自动授权审查 - - text: 实验性 提供自动审查权限模式,由模型在每次工具调用前判断是否授权。 - - switch "启用 自动授权审查" - - listitem: - - button "查看 DSH 徽章技能": DSH 徽章技能 - - text: 实验性 提供可发现的 powered-by-DSH 徽章技能。 - - switch "启用 DSH 徽章技能" - - listitem: - - button "查看 思考过程机器翻译": 思考过程机器翻译 - - text: 实验性 机器翻译展开的思考内容;原文会发送给所选服务 - - switch "启用 思考过程机器翻译" - - listitem: - - button "查看 开发者工具": 开发者工具 - - text: 实验性 查看调试会话原始数据、聊天消息分组数据,以及调试 NodeJS 后端 - - switch "启用 开发者工具" - - listitem: - - button "查看 Ralph 循环": Ralph 循环 - - text: 实验性 使用新智能体执行用户明确要求的循环工作。 - - switch "启用 Ralph 循环" - - listitem: - - button "查看 会话搜索": 会话搜索 - - text: 实验性 为智能体提供搜索和读取当前工作区历史会话的工具。 - - switch "启用 会话搜索" - - listitem: - - button "查看 随对话更新的标题": 随对话更新的标题 - - text: 实验性 在收到新的用户提示时更新会话标题。 - - switch "启用 随对话更新的标题" - - listitem: - - button "查看 持久终端": 持久终端 - - text: 实验性 让 shell 进程在多次工具调用之间保持运行。 - - switch "启用 持久终端" - - listitem: - - button "查看 Git 工作树": Git 工作树 - - text: 实验性 让智能体创建新的 Git 分支与工作树,并在其中继续工作。 - - switch "启用 Git 工作树" - - listitem: - - button "查看 语音输入": 语音输入 - - text: 实验性 在本机使用 SenseVoice 转写录音,首次使用需安装依赖。 - - switch "启用 语音输入" - - listitem: - - button "查看 Claude Code 子智能体": Claude Code 子智能体 - - text: 未安装 使用 Claude Code 原生认证和设置委派单个任务。 - - switch "启用 Claude Code 子智能体" - - listitem: - - button "查看 Codex 子智能体": Codex 子智能体 - - text: 未安装 使用 Codex 原生认证和设置委派单个任务。 - - switch "启用 Codex 子智能体" - - listitem: - - button "查看 终端": 终端 - - text: 限制每条命令最多能跑多久、最多输出多少内容。 - - listitem: - - button "查看 Agent 循环": Agent 循环 - - text: 控制 Agent 派发工具调用的方式。 - listitem: - button "查看 子智能体": 子智能体 - text: 设置子智能体的递归层级、数量和模型。 - listitem: - button "查看 网页搜索": 网页搜索 - text: 设置 DeepSeek 的搜索提供方。 -- heading "已安装" [level=3] -- text: "2" + - listitem: + - button "查看 Agent 循环": Agent 循环 + - text: 控制 Agent 派发工具调用的方式。 + - listitem: + - button "查看 终端": 终端 + - text: 限制每条命令最多能跑多久、最多输出多少内容。 +- heading "实验性插件" [level=3] +- button "更多" +- list: + - listitem: + - button "查看 智能体团队": 智能体团队 + - text: 实验性 启用团队协作、团队工具、成员列表和共享任务看板。 + - switch "启用 智能体团队" + - listitem: + - button "查看 语音输入": 语音输入 + - text: 实验性 在本机使用 SenseVoice 转写录音,首次使用需安装依赖。 + - switch "启用 语音输入" + - listitem: + - button "查看 自动授权审查": 自动授权审查 + - text: 实验性 提供自动审查权限模式,由模型在每次工具调用前判断是否授权。 + - switch "启用 自动授权审查" + - listitem: + - button "查看 开发者工具": 开发者工具 + - text: 实验性 查看调试会话原始数据、聊天消息分组数据,以及调试 NodeJS 后端 + - switch "启用 开发者工具" +- heading "已安装插件" [level=3] - list: - listitem: - button "查看 @fixture/live-client": "@fixture/live-client" diff --git a/apps/web/tests/expected/plugin-config/subagent.expected.md b/apps/web/tests/expected/plugin-config/subagent.expected.md index 1f324d7161..74bf83d3ea 100644 --- a/apps/web/tests/expected/plugin-config/subagent.expected.md +++ b/apps/web/tests/expected/plugin-config/subagent.expected.md @@ -1,4 +1,4 @@ -- button "返回插件列表": 插件列表 +- button "返回插件": 插件 - heading "子智能体" [level=3] - paragraph: 设置子智能体的递归层级、数量和模型。 - region "运行限制": diff --git a/apps/web/tests/expected/plugin-manager/exports.expected.md b/apps/web/tests/expected/plugin-manager/exports.expected.md index 2a86287511..702150c359 100644 --- a/apps/web/tests/expected/plugin-manager/exports.expected.md +++ b/apps/web/tests/expected/plugin-manager/exports.expected.md @@ -1,4 +1,4 @@ -- button "返回插件列表": 插件列表 +- button "返回插件": 插件 - button "卸载 @fixture/bundle": 卸载 - switch "启用 @fixture/bundle" - heading "@fixture/bundle" [level=3] diff --git a/apps/web/tests/expected/plugin-manager/header-responsive.expected.md b/apps/web/tests/expected/plugin-manager/header-responsive.expected.md new file mode 100644 index 0000000000..7967bfe352 --- /dev/null +++ b/apps/web/tests/expected/plugin-manager/header-responsive.expected.md @@ -0,0 +1,19 @@ +# Plugin header responsive layout + +en 1680px: actions beside the heading, single-line; contained; information follows subtitle; focus retained +en 768px: actions beside or below (according to intrinsic fit) the heading, single-line; contained; information follows subtitle; focus retained +en 520px: actions beside or below (according to intrinsic fit) the heading, single-line; contained; information follows subtitle; focus retained +en 440px: actions beside or below (according to intrinsic fit) the heading, single-line; contained; information follows subtitle; focus retained +en 390px: actions below the heading, single-line; contained; information follows subtitle; focus retained +en 430px: actions below the heading, single-line; contained; information follows subtitle; focus retained +en 1024px: actions beside the heading, single-line; contained; information follows subtitle; focus retained +zh 1680px: actions beside the heading, single-line; contained; information follows subtitle; focus retained +zh 768px: actions beside or below (according to intrinsic fit) the heading, single-line; contained; information follows subtitle; focus retained +zh 520px: actions beside or below (according to intrinsic fit) the heading, single-line; contained; information follows subtitle; focus retained +zh 440px: actions beside or below (according to intrinsic fit) the heading, single-line; contained; information follows subtitle; focus retained +zh 390px: actions below the heading, single-line; contained; information follows subtitle; focus retained +zh 430px: actions below the heading, single-line; contained; information follows subtitle; focus retained +zh 1024px: actions beside the heading, single-line; contained; information follows subtitle; focus retained + +A forced no-wrap layout at 390px fails the same measured layout check in both locales; restoring wrap passes. +Add menu dismisses on Escape and returns focus in both locales. diff --git a/apps/web/tests/expected/plugin-manager/live-enabled.expected.md b/apps/web/tests/expected/plugin-manager/live-enabled.expected.md index 975951d9eb..eab9dd48e1 100644 --- a/apps/web/tests/expected/plugin-manager/live-enabled.expected.md +++ b/apps/web/tests/expected/plugin-manager/live-enabled.expected.md @@ -5,75 +5,40 @@ - group "添加插件": - button "添加插件" - button "选择添加插件方式" -- heading "官方" [level=3] -- text: "17" +- heading "内置插件配置" [level=3] - list: - - listitem: - - button "查看 智能体团队": 智能体团队 - - text: 实验性 启用团队协作、团队工具、成员列表和共享任务看板。 - - switch "启用 智能体团队" - - listitem: - - button "查看 自动授权审查": 自动授权审查 - - text: 实验性 提供自动审查权限模式,由模型在每次工具调用前判断是否授权。 - - switch "启用 自动授权审查" - - listitem: - - button "查看 DSH 徽章技能": DSH 徽章技能 - - text: 实验性 提供可发现的 powered-by-DSH 徽章技能。 - - switch "启用 DSH 徽章技能" - - listitem: - - button "查看 思考过程机器翻译": 思考过程机器翻译 - - text: 实验性 机器翻译展开的思考内容;原文会发送给所选服务 - - switch "启用 思考过程机器翻译" - - listitem: - - button "查看 开发者工具": 开发者工具 - - text: 实验性 查看调试会话原始数据、聊天消息分组数据,以及调试 NodeJS 后端 - - switch "启用 开发者工具" - - listitem: - - button "查看 Ralph 循环": Ralph 循环 - - text: 实验性 使用新智能体执行用户明确要求的循环工作。 - - switch "启用 Ralph 循环" - - listitem: - - button "查看 会话搜索": 会话搜索 - - text: 实验性 为智能体提供搜索和读取当前工作区历史会话的工具。 - - switch "启用 会话搜索" - - listitem: - - button "查看 随对话更新的标题": 随对话更新的标题 - - text: 实验性 在收到新的用户提示时更新会话标题。 - - switch "启用 随对话更新的标题" - - listitem: - - button "查看 持久终端": 持久终端 - - text: 实验性 让 shell 进程在多次工具调用之间保持运行。 - - switch "启用 持久终端" - - listitem: - - button "查看 Git 工作树": Git 工作树 - - text: 实验性 让智能体创建新的 Git 分支与工作树,并在其中继续工作。 - - switch "启用 Git 工作树" - - listitem: - - button "查看 语音输入": 语音输入 - - text: 实验性 在本机使用 SenseVoice 转写录音,首次使用需安装依赖。 - - switch "启用 语音输入" - - listitem: - - button "查看 Claude Code 子智能体": Claude Code 子智能体 - - text: 未安装 使用 Claude Code 原生认证和设置委派单个任务。 - - switch "启用 Claude Code 子智能体" - - listitem: - - button "查看 Codex 子智能体": Codex 子智能体 - - text: 未安装 使用 Codex 原生认证和设置委派单个任务。 - - switch "启用 Codex 子智能体" - - listitem: - - button "查看 终端": 终端 - - text: 限制每条命令最多能跑多久、最多输出多少内容。 - - listitem: - - button "查看 Agent 循环": Agent 循环 - - text: 控制 Agent 派发工具调用的方式。 - listitem: - button "查看 子智能体": 子智能体 - text: 设置子智能体的递归层级、数量和模型。 - listitem: - button "查看 网页搜索": 网页搜索 - text: 设置 DeepSeek 的搜索提供方。 -- heading "已安装" [level=3] -- text: "2" + - listitem: + - button "查看 Agent 循环": Agent 循环 + - text: 控制 Agent 派发工具调用的方式。 + - listitem: + - button "查看 终端": 终端 + - text: 限制每条命令最多能跑多久、最多输出多少内容。 +- heading "实验性插件" [level=3] +- button "更多" +- list: + - listitem: + - button "查看 智能体团队": 智能体团队 + - text: 实验性 启用团队协作、团队工具、成员列表和共享任务看板。 + - switch "启用 智能体团队" + - listitem: + - button "查看 语音输入": 语音输入 + - text: 实验性 在本机使用 SenseVoice 转写录音,首次使用需安装依赖。 + - switch "启用 语音输入" + - listitem: + - button "查看 自动授权审查": 自动授权审查 + - text: 实验性 提供自动审查权限模式,由模型在每次工具调用前判断是否授权。 + - switch "启用 自动授权审查" + - listitem: + - button "查看 开发者工具": 开发者工具 + - text: 实验性 查看调试会话原始数据、聊天消息分组数据,以及调试 NodeJS 后端 + - switch "启用 开发者工具" +- heading "已安装插件" [level=3] - list: - listitem: - button "查看 @fixture/bundle": "@fixture/bundle" diff --git a/apps/web/tests/expected/plugin-manager/loading.expected.md b/apps/web/tests/expected/plugin-manager/loading.expected.md index 4cf8d9ea23..01f06171a3 100644 --- a/apps/web/tests/expected/plugin-manager/loading.expected.md +++ b/apps/web/tests/expected/plugin-manager/loading.expected.md @@ -7,8 +7,8 @@ - button "选择添加插件方式" [disabled] - status "正在读取插件…" -1680px: 4 rows; page/group headers, rows, icons, text lines and blank action spaces align within 0.1px -1000px: 4 rows; page/group headers, rows, icons, text lines and blank action spaces align within 0.1px +1680px: 4 rows; page/group headers, rows, icons and text line origins align within 0.1px +1000px: 4 rows; page/group headers, rows, icons and text line origins align within 0.1px Loading: header actions disabled; action spaces are empty 36×20 areas, with no switch placeholders Loaded: skeleton removed; header actions enabled Motion: 13 opacity-only pulses, 2000ms; reduced motion stops all pulses diff --git a/apps/web/tests/expected/plugin-manager/manager.expected.md b/apps/web/tests/expected/plugin-manager/manager.expected.md index 33570a25d2..f3dd4a7bc6 100644 --- a/apps/web/tests/expected/plugin-manager/manager.expected.md +++ b/apps/web/tests/expected/plugin-manager/manager.expected.md @@ -5,75 +5,40 @@ - group "添加插件": - button "添加插件" - button "选择添加插件方式" -- heading "官方" [level=3] -- text: "17" +- heading "内置插件配置" [level=3] - list: - - listitem: - - button "查看 智能体团队": 智能体团队 - - text: 实验性 启用团队协作、团队工具、成员列表和共享任务看板。 - - switch "启用 智能体团队" - - listitem: - - button "查看 自动授权审查": 自动授权审查 - - text: 实验性 提供自动审查权限模式,由模型在每次工具调用前判断是否授权。 - - switch "启用 自动授权审查" - - listitem: - - button "查看 DSH 徽章技能": DSH 徽章技能 - - text: 实验性 提供可发现的 powered-by-DSH 徽章技能。 - - switch "启用 DSH 徽章技能" - - listitem: - - button "查看 思考过程机器翻译": 思考过程机器翻译 - - text: 实验性 机器翻译展开的思考内容;原文会发送给所选服务 - - switch "启用 思考过程机器翻译" - - listitem: - - button "查看 开发者工具": 开发者工具 - - text: 实验性 查看调试会话原始数据、聊天消息分组数据,以及调试 NodeJS 后端 - - switch "启用 开发者工具" - - listitem: - - button "查看 Ralph 循环": Ralph 循环 - - text: 实验性 使用新智能体执行用户明确要求的循环工作。 - - switch "启用 Ralph 循环" - - listitem: - - button "查看 会话搜索": 会话搜索 - - text: 实验性 为智能体提供搜索和读取当前工作区历史会话的工具。 - - switch "启用 会话搜索" - - listitem: - - button "查看 随对话更新的标题": 随对话更新的标题 - - text: 实验性 在收到新的用户提示时更新会话标题。 - - switch "启用 随对话更新的标题" - - listitem: - - button "查看 持久终端": 持久终端 - - text: 实验性 让 shell 进程在多次工具调用之间保持运行。 - - switch "启用 持久终端" - - listitem: - - button "查看 Git 工作树": Git 工作树 - - text: 实验性 让智能体创建新的 Git 分支与工作树,并在其中继续工作。 - - switch "启用 Git 工作树" - - listitem: - - button "查看 语音输入": 语音输入 - - text: 实验性 在本机使用 SenseVoice 转写录音,首次使用需安装依赖。 - - switch "启用 语音输入" - - listitem: - - button "查看 Claude Code 子智能体": Claude Code 子智能体 - - text: 未安装 使用 Claude Code 原生认证和设置委派单个任务。 - - switch "启用 Claude Code 子智能体" - - listitem: - - button "查看 Codex 子智能体": Codex 子智能体 - - text: 未安装 使用 Codex 原生认证和设置委派单个任务。 - - switch "启用 Codex 子智能体" - - listitem: - - button "查看 终端": 终端 - - text: 限制每条命令最多能跑多久、最多输出多少内容。 - - listitem: - - button "查看 Agent 循环": Agent 循环 - - text: 控制 Agent 派发工具调用的方式。 - listitem: - button "查看 子智能体": 子智能体 - text: 设置子智能体的递归层级、数量和模型。 - listitem: - button "查看 网页搜索": 网页搜索 - text: 设置 DeepSeek 的搜索提供方。 -- heading "已安装" [level=3] -- text: "2" + - listitem: + - button "查看 Agent 循环": Agent 循环 + - text: 控制 Agent 派发工具调用的方式。 + - listitem: + - button "查看 终端": 终端 + - text: 限制每条命令最多能跑多久、最多输出多少内容。 +- heading "实验性插件" [level=3] +- button "更多" +- list: + - listitem: + - button "查看 智能体团队": 智能体团队 + - text: 实验性 启用团队协作、团队工具、成员列表和共享任务看板。 + - switch "启用 智能体团队" + - listitem: + - button "查看 语音输入": 语音输入 + - text: 实验性 在本机使用 SenseVoice 转写录音,首次使用需安装依赖。 + - switch "启用 语音输入" + - listitem: + - button "查看 自动授权审查": 自动授权审查 + - text: 实验性 提供自动审查权限模式,由模型在每次工具调用前判断是否授权。 + - switch "启用 自动授权审查" + - listitem: + - button "查看 开发者工具": 开发者工具 + - text: 实验性 查看调试会话原始数据、聊天消息分组数据,以及调试 NodeJS 后端 + - switch "启用 开发者工具" +- heading "已安装插件" [level=3] - list: - listitem: - button "查看 @fixture/bundle": "@fixture/bundle" diff --git a/apps/web/tests/expected/plugin-manager/missing-bundle.expected.md b/apps/web/tests/expected/plugin-manager/missing-bundle.expected.md index c1658e9fe2..268ad18e27 100644 --- a/apps/web/tests/expected/plugin-manager/missing-bundle.expected.md +++ b/apps/web/tests/expected/plugin-manager/missing-bundle.expected.md @@ -1,4 +1,4 @@ -- button "返回插件列表": 插件列表 +- button "返回插件": 插件 - button "卸载 @fixture/missing-bundle": 卸载 - switch "启用 @fixture/missing-bundle" [checked] - heading "@fixture/missing-bundle" [level=3] diff --git a/apps/web/tests/expected/plugin-manager/refresh.expected.md b/apps/web/tests/expected/plugin-manager/refresh.expected.md index 1ed42daaa5..75dda78845 100644 --- a/apps/web/tests/expected/plugin-manager/refresh.expected.md +++ b/apps/web/tests/expected/plugin-manager/refresh.expected.md @@ -6,7 +6,7 @@ Focus at 500ms: - tooltip "刷新" failure: pending - button "刷新" [disabled] -{"busy":"true","spinners":1,"cards":20,"skeletons":0,"alerts":[],"retry":0,"toasts":[]} +{"busy":"true","spinners":1,"cards":11,"skeletons":0,"alerts":[],"retry":0,"toasts":[]} failure: settled - button "刷新" -{"busy":"false","spinners":0,"cards":20,"skeletons":0,"alerts":[],"retry":0,"toasts":["刷新失败,请重试"]} +{"busy":"false","spinners":0,"cards":11,"skeletons":0,"alerts":[],"retry":0,"toasts":["刷新失败,请重试"]} diff --git a/apps/web/tests/expected/schedule-header.expected.md b/apps/web/tests/expected/schedule-header.expected.md new file mode 100644 index 0000000000..96bff76bee --- /dev/null +++ b/apps/web/tests/expected/schedule-header.expected.md @@ -0,0 +1,17 @@ +# Automation tasks header + +en 1680px: title and New single-line, New beside the title; contained; New retains focus +en 800px: title and New single-line, New beside the title; contained; New retains focus +en 520px: title and New single-line, New beside the title; contained; New retains focus +en 440px: title and New single-line, New beside the title; contained; New retains focus +en 390px: title and New single-line, New beside the title; contained; New retains focus +en 430px: title and New single-line, New beside the title; contained; New retains focus +en 1024px: title and New single-line, New beside the title; contained; New retains focus +en 509px with sidebar expanded: title single-line; New moves below the title +zh 1680px: title and New single-line, New beside the title; contained; New retains focus +zh 800px: title and New single-line, New beside the title; contained; New retains focus +zh 520px: title and New single-line, New beside the title; contained; New retains focus +zh 440px: title and New single-line, New beside the title; contained; New retains focus +zh 390px: title and New single-line, New beside the title; contained; New retains focus +zh 430px: title and New single-line, New beside the title; contained; New retains focus +zh 1024px: title and New single-line, New beside the title; contained; New retains focus 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/session-row-hover/actions.expected.json b/apps/web/tests/expected/session-row-hover/actions.expected.json new file mode 100644 index 0000000000..2423722518 --- /dev/null +++ b/apps/web/tests/expected/session-row-hover/actions.expected.json @@ -0,0 +1,46 @@ +[ + { + "stage": "details", + "details": true, + "tooltips": [] + }, + { + "stage": "more-hover", + "details": true, + "tooltips": [] + }, + { + "stage": "archive-before-dwell", + "details": true, + "tooltips": [] + }, + { + "stage": "archive", + "details": true, + "tooltips": [ + "Archive" + ] + }, + { + "stage": "pin", + "details": true, + "tooltips": [ + "Pin" + ] + }, + { + "stage": "back-to-title", + "details": true, + "tooltips": [] + }, + { + "stage": "menu-closed", + "details": false, + "tooltips": [] + }, + { + "stage": "row-reentered", + "details": true, + "tooltips": [] + } +] diff --git a/apps/web/tests/expected/session-row-hover/grouped.expected.json b/apps/web/tests/expected/session-row-hover/grouped.expected.json new file mode 100644 index 0000000000..185475c247 --- /dev/null +++ b/apps/web/tests/expected/session-row-hover/grouped.expected.json @@ -0,0 +1,52 @@ +[ + { + "stage": "first-before-dwell", + "first": false, + "second": false + }, + { + "stage": "first-shown", + "first": true, + "second": false + }, + { + "stage": "second-instant", + "first": false, + "second": true + }, + { + "stage": "first-instant", + "first": true, + "second": false + }, + { + "stage": "readable-portal", + "first": true, + "second": false + }, + { + "stage": "copied-portal", + "first": true, + "second": false + }, + { + "stage": "portal-return-instant", + "first": false, + "second": true + }, + { + "stage": "outside-cooled", + "first": false, + "second": false + }, + { + "stage": "list-reentry-before-dwell", + "first": false, + "second": false + }, + { + "stage": "list-reentry-shown", + "first": true, + "second": false + } +] diff --git a/apps/web/tests/expected/session-row-hover/mixed-rows.expected.json b/apps/web/tests/expected/session-row-hover/mixed-rows.expected.json new file mode 100644 index 0000000000..39a40107ad --- /dev/null +++ b/apps/web/tests/expected/session-row-hover/mixed-rows.expected.json @@ -0,0 +1,22 @@ +[ + { + "stage": "first-workspace-after-dwell", + "exclusive": true + }, + { + "stage": "workspace-to-workspace-immediate", + "exclusive": true + }, + { + "stage": "workspace-to-session-immediate", + "exclusive": true + }, + { + "stage": "session-to-workspace-immediate", + "exclusive": true + }, + { + "stage": "list-reentered-after-dwell", + "exclusive": true + } +] diff --git a/apps/web/tests/expected/settings-chrome/collapse-timing-en.expected.md b/apps/web/tests/expected/settings-chrome/collapse-timing-en.expected.md new file mode 100644 index 0000000000..f06030ef91 --- /dev/null +++ b/apps/web/tests/expected/settings-chrome/collapse-timing-en.expected.md @@ -0,0 +1,3 @@ +- menu: + - menuitem "On completion" + - menuitem "On next message" diff --git a/apps/web/tests/expected/settings-chrome/collapse-timing-zh.expected.md b/apps/web/tests/expected/settings-chrome/collapse-timing-zh.expected.md new file mode 100644 index 0000000000..e7b47ba72f --- /dev/null +++ b/apps/web/tests/expected/settings-chrome/collapse-timing-zh.expected.md @@ -0,0 +1,3 @@ +- menu: + - menuitem "回答结束后" + - menuitem "下次有新消息时" diff --git a/apps/web/tests/expected/settings-chrome/dialog-en.expected.md b/apps/web/tests/expected/settings-chrome/dialog-en.expected.md index c59d632773..13cd42f9d7 100644 --- a/apps/web/tests/expected/settings-chrome/dialog-en.expected.md +++ b/apps/web/tests/expected/settings-chrome/dialog-en.expected.md @@ -22,6 +22,8 @@ - button "More font settings" - text: Work details Choose how much detail to show for tool calls - button "Detailed" + - text: When to Collapse Work Details Choose when to automatically collapse work details + - button "On completion" - text: Show coding view Shows trajectory, code diffs, and all Agent presets - switch "Show coding view" - text: Keyboard shortcuts diff --git a/apps/web/tests/expected/settings-chrome/dialog-no-browser.expected.md b/apps/web/tests/expected/settings-chrome/dialog-no-browser.expected.md index c59d632773..13cd42f9d7 100644 --- a/apps/web/tests/expected/settings-chrome/dialog-no-browser.expected.md +++ b/apps/web/tests/expected/settings-chrome/dialog-no-browser.expected.md @@ -22,6 +22,8 @@ - button "More font settings" - text: Work details Choose how much detail to show for tool calls - button "Detailed" + - text: When to Collapse Work Details Choose when to automatically collapse work details + - button "On completion" - text: Show coding view Shows trajectory, code diffs, and all Agent presets - switch "Show coding view" - text: Keyboard shortcuts diff --git a/apps/web/tests/expected/settings-chrome/dialog.expected.md b/apps/web/tests/expected/settings-chrome/dialog.expected.md index a9705c27f8..df60e07cde 100644 --- a/apps/web/tests/expected/settings-chrome/dialog.expected.md +++ b/apps/web/tests/expected/settings-chrome/dialog.expected.md @@ -22,6 +22,8 @@ - button "更多字体设置" - text: 工作步骤展示 选择希望看到多少工具调用细节 - button "详细" + - text: 工作步骤收起时机 选择何时自动收起工作步骤 + - button "回答结束后" - text: 显示代码工作视图 开启后,显示轨迹、本轮代码差异,可选择完整的 Agent 预设切换 - switch "显示代码工作视图" - text: 快捷键 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-desktop/font-sizes.expected.md b/apps/web/tests/expected/shortcuts-desktop/font-sizes.expected.md new file mode 100644 index 0000000000..a4afd069e8 --- /dev/null +++ b/apps/web/tests/expected/shortcuts-desktop/font-sizes.expected.md @@ -0,0 +1,38 @@ +# Font sizes + +{ + "initial": { + "text": 14, + "code": 11, + "terminal": 13 + }, + "afterEqual": { + "text": 15, + "code": 12, + "terminal": 14 + }, + "afterPlus": { + "text": 16, + "code": 13, + "terminal": 15 + }, + "afterMinus": { + "text": 15, + "code": 12, + "terminal": 14 + }, + "afterReload": { + "text": 15, + "code": 12, + "terminal": 14 + }, + "restored": { + "text": 14, + "code": 11, + "terminal": 13 + }, + "referenceOrder": [ + "Increase font size", + "Decrease font size" + ] +} 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/subagent-conversation/migration-required-child.expected.md b/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md new file mode 100644 index 0000000000..0e4f8f018b --- /dev/null +++ b/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md @@ -0,0 +1,13 @@ +# Before opening the child + +- tree "Subagent sessions": + - treeitem "historical researcher Migration required · not running" [level=1]: + - text: historical researcher Migration required · not running + - button "Open historical researcher in sidebar" + +# After opening the child + +- tree "Subagent sessions": + - treeitem "historical editor Migration required · not running" [level=1]: + - text: historical editor Migration required · not running + - button "Open historical editor in sidebar" 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/expected/workspace-new-session-folding/watermark-kept.expected.md b/apps/web/tests/expected/workspace-new-session-folding/watermark-kept.expected.md new file mode 100644 index 0000000000..153f797a70 --- /dev/null +++ b/apps/web/tests/expected/workspace-new-session-folding/watermark-kept.expected.md @@ -0,0 +1,16 @@ +- tree "Sessions": + - treeitem "{{workspace}} Workspace actions for {{workspace}} New session in {{workspace}}" [expanded]: + - text: {{workspace}} + - button "Workspace actions for {{workspace}}" + - button "New session in {{workspace}}" + - treeitem "New Session" [selected] + - treeitem "Untitled 1min" + - treeitem "Untitled 1min" + - treeitem "Untitled 1min" + - treeitem "Untitled 1min" + - treeitem "Untitled 1min" + - treeitem "Untitled 1min" + - treeitem "Untitled 1min" + - treeitem "Untitled 1min" + - treeitem "Untitled 1min" + - button "Show 7 more sessions" diff --git a/apps/web/tests/fixtures/account-login/cordis.patch.yml b/apps/web/tests/fixtures/account-login/cordis.patch.yml new file mode 100644 index 0000000000..a31eac8f46 --- /dev/null +++ b/apps/web/tests/fixtures/account-login/cordis.patch.yml @@ -0,0 +1,12 @@ +# The Web account login scenario points the shipped account provider at a loopback +# Platform double. The scenario substitutes {{origin}} after the listener binds, +# so no port is ever committed here. +- id: deepseek-account + config: + platformOrigin: "{{origin}}" + allowLoopbackHttp: true +# The scenario signs in from the account menu after initial setup. +- id: ui-settings-account + config: + step: done + completion: completed 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/fold-blank-matrix.e2e.ts b/apps/web/tests/fold-blank-matrix.e2e.ts new file mode 100644 index 0000000000..3422c15238 --- /dev/null +++ b/apps/web/tests/fold-blank-matrix.e2e.ts @@ -0,0 +1,875 @@ +/** + * Blank-area matrix for "On next message" folding. A human message folds the + * previous exchange's work details; each case records the largest band between + * the scrollport top and the composer that no visible row covers, after the fold + * settles, after the Turn the message started settles, and on every animation + * frame in between. Cases cover the main Session and a subagent child Session + * hosted in the right Sidebar, across reader positions and input origins. + */ +import { 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, Route } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import type { StreamChunk } from '@deepseek-ai/dsh-llm' +import { ToolCallId, createAssistantMessage, createUserMessage } from '@deepseek-ai/dsh-llm' +import type { ReplayEntry } from '@deepseek-ai/dsh-llm-replay' +import { + SESSION_FORMAT_VERSION, SessionId, SessionLogOffset, SessionSeq, type SessionEvent, type SessionHeader, +} from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-system-prompt' +import { sessionFixtureName } from '@deepseek-ai/dsh-session-snapshot' +import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' +import { createChatScrollFixture, type ChatScrollFixture } from './chat-scroll-fixture.ts' +import { launchWebScaffold, parseSeedFixture, seedSession, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { newEnglishPage, openSettings } from './support.ts' + +declare global { + interface Window { + foldProbe?: { readonly samples: Geometry[]; stop(): void } + foldMeasure?: (root: string) => Geometry + } +} + +const MODE = webSnapshotMode() +const SEEDED_TURNS = 8 +const SEEDED_STEPS = 6 +const LIVE_STEPS = 6 +/** Live Steps the steered Turn replays before the steering message is delivered. */ +const STEER_STEPS = 3 +const BLANK_LIMIT = 120 +/** + * Frames whose layout gap may exceed {@link BLANK_LIMIT}. The gap counts rows by their boxes, so a + * closing row that has faded but not finished shrinking still covers its space. + */ +const TRANSIENT_FRAMES = 1 +const EVIDENCE = fileURLToPath(new URL('../../../.artifacts/screenshots/fold-blank-matrix/', import.meta.url)) +const MAIN_ROOT = '[data-conversation-scroll]:not([data-sidebar-chat] [data-conversation-scroll])' +const SIDE_ROOT = '[data-sidebar-chat] [data-conversation-scroll]' +const CHILD_LABEL = 'fold matrix child' +const READ_FILE = 'fold-matrix-notes.txt' +const NEXT_INPUT = 'FOLDMX_NEXT_INPUT' + +/** Where the reader stands when the message is sent. */ +type Reader = + | { readonly kind: 'bottom' } + | { readonly kind: 'marker'; readonly marker: string; readonly align: 'center' | 'top' } + +const AT_BOTTOM: Reader = { kind: 'bottom' } +const SEEDED_MID_BODY: Reader = { kind: 'marker', marker: 'FOLDMX_BODY', align: 'center' } +const SEEDED_BODY_TOP: Reader = { kind: 'marker', marker: 'FOLDMX_BODY', align: 'top' } +const SEEDED_STEPS_READER: Reader = { kind: 'marker', marker: 'FOLDMX_STEP_4', align: 'top' } +const PREVIOUS_TURN: Reader = { kind: 'marker', marker: `FOLDMX_PREVIOUS_${SEEDED_TURNS - 1}`, align: 'top' } +const LIVE_MID_BODY: Reader = { kind: 'marker', marker: 'FOLDMX_LIVE_BODY', align: 'center' } + +/** + * How the folding message arrives. + * - `composer`: this page's composer sends while the Session is idle. + * - `error`: as `composer`, but the Turn fails before its user message is recorded. + * - `other-tab`: a second page sends; this page receives it without a local echo. + * - `queued`: this page queues the message while a long live Turn runs; it is delivered after that Turn ends. + * - `steer`: as `queued`, but the queued message is steered into the running Turn. + * - `parent-message`: the live parent Agent messages the child (side chat only). + * - `big-exchange`: two parent messages wake long child Turns before the human message (side chat only). + */ +type Origin = 'composer' | 'error' | 'other-tab' | 'queued' | 'steer' | 'parent-message' | 'big-exchange' + +interface Case { + readonly id: string + readonly surface: 'main' | 'side' + readonly origin: Origin + readonly reader: Reader + readonly bodyParagraphs: number + readonly mode: 'Detailed' | 'Standard' + readonly timing: 'On next message' | 'On completion' + /** + * `tail`: the view ends at the floor. `reader`: the reader's anchor row keeps its screen position. + */ + readonly landing: 'tail' | 'reader' + /** The reader's anchor row is itself folded, so only the blank area is asserted. */ + readonly anchorFolds?: true + /** Content above the viewport never slides back down, so a short body leaves room until newer content fills it. */ + readonly roomUntilReply?: true +} + +const MAIN = { + surface: 'main', origin: 'composer', bodyParagraphs: 40, mode: 'Detailed', timing: 'On next message', landing: 'tail', +} as const +const SIDE = { ...MAIN, surface: 'side' } as const + +const CASES: readonly Case[] = [ + { ...MAIN, id: 'main/composer/bottom', reader: AT_BOTTOM }, + { ...MAIN, id: 'main/composer/mid-body', reader: SEEDED_MID_BODY }, + { ...MAIN, id: 'main/composer/body-top', reader: SEEDED_BODY_TOP }, + { ...MAIN, id: 'main/composer/steps', reader: SEEDED_STEPS_READER }, + { ...MAIN, id: 'main/composer/previous-turn', reader: PREVIOUS_TURN }, + { ...MAIN, id: 'main/composer/short-body/bottom', reader: AT_BOTTOM, bodyParagraphs: 2, roomUntilReply: true }, + { ...MAIN, id: 'main/composer/short-body/steps', reader: SEEDED_STEPS_READER, bodyParagraphs: 2, roomUntilReply: true }, + { ...MAIN, id: 'main/composer/short-body/previous-turn', reader: PREVIOUS_TURN, bodyParagraphs: 2 }, + { ...MAIN, id: 'main/error-before-message/bottom', origin: 'error', reader: AT_BOTTOM }, + { ...MAIN, id: 'main/error-before-message/mid-body', origin: 'error', reader: SEEDED_MID_BODY }, + { ...MAIN, id: 'main/other-tab/bottom', origin: 'other-tab', reader: AT_BOTTOM }, + { ...MAIN, id: 'main/other-tab/mid-body', origin: 'other-tab', reader: SEEDED_MID_BODY, landing: 'reader' }, + { ...MAIN, id: 'main/other-tab/steps', origin: 'other-tab', reader: SEEDED_STEPS_READER, landing: 'reader', anchorFolds: true }, + { ...MAIN, id: 'main/other-tab/previous-turn', origin: 'other-tab', reader: PREVIOUS_TURN, landing: 'reader' }, + { ...MAIN, id: 'main/queued/bottom', origin: 'queued', reader: AT_BOTTOM }, + { ...MAIN, id: 'main/queued/mid-body', origin: 'queued', reader: LIVE_MID_BODY, landing: 'reader' }, + // Control: steering joins the running Turn, which opens no exchange and folds nothing. + { ...MAIN, id: 'main/steer/no-fold-control', origin: 'steer', reader: AT_BOTTOM }, + { ...MAIN, id: 'main/composer/standard/mid-body', reader: SEEDED_MID_BODY, mode: 'Standard' }, + { ...MAIN, id: 'main/composer/completion/mid-body', reader: SEEDED_MID_BODY, timing: 'On completion' }, + { ...SIDE, id: 'side/composer/bottom', reader: AT_BOTTOM }, + { ...SIDE, id: 'side/composer/mid-body', reader: SEEDED_MID_BODY }, + { ...SIDE, id: 'side/composer/steps', reader: SEEDED_STEPS_READER }, + { ...SIDE, id: 'side/composer/previous-turn', reader: PREVIOUS_TURN }, + { ...SIDE, id: 'side/queued/bottom', origin: 'queued', reader: AT_BOTTOM }, + { ...SIDE, id: 'side/queued/mid-body', origin: 'queued', reader: LIVE_MID_BODY, landing: 'reader' }, + // Control: a parent message is a notice, which opens no exchange and folds nothing. + { ...SIDE, id: 'side/parent-message/no-fold-control', origin: 'parent-message', reader: SEEDED_MID_BODY, landing: 'reader' }, + { ...SIDE, id: 'side/big-exchange/bottom', origin: 'big-exchange', reader: AT_BOTTOM }, +] + +interface Geometry { + readonly top: number + readonly floor: number + readonly spacer: number + /** Largest band between the scrollport top and the composer that no visible row covers. */ + readonly maxGap: number + readonly gapAt: number + /** Empty height between the last visible row and the composer. */ + readonly tailGap: number + readonly following: boolean + /** A row was closing on this sample. */ + readonly collapsing: boolean +} + +/** Installed into each measured page before load; reads one scrollport's blank-area geometry. */ +function installMeasure(): void { + window.foldMeasure = (root) => { + const host = document.querySelector(root) + if (host === null) throw new Error(`scrollport is absent: ${root}`) + const viewport = host.getBoundingClientRect() + const composer = host.querySelector('[data-composer-seat]') + if (composer === null) throw new Error(`composer is absent: ${root}`) + const composerTop = composer.getBoundingClientRect().top + const spacer = host.querySelector('[data-chat-turn-spacer]')?.getBoundingClientRect().height ?? 0 + const intervals = [...host.querySelectorAll('[data-chat-flow-key], [data-submission-echo], [data-pending-steering], [data-streaming], [data-chat-running]')] + .filter(element => element.closest('[hidden]') === null) + .map((element) => { + const rect = element.getBoundingClientRect() + return [Math.max(rect.top, viewport.top), Math.min(rect.bottom, composerTop)] as const + }) + .filter(([top, bottom]) => bottom - top > 0.5) + .sort((left, right) => left[0] - right[0]) + let cursor = viewport.top + let maxGap = 0 + let gapAt = 0 + for (const [top, bottom] of intervals) { + if (top - cursor > maxGap) { + maxGap = top - cursor + gapAt = cursor - viewport.top + } + cursor = Math.max(cursor, bottom) + } + if (composerTop - cursor > maxGap) { + maxGap = composerTop - cursor + gapAt = cursor - viewport.top + } + return { + top: host.scrollTop, floor: Math.max(0, host.scrollHeight - host.clientHeight), spacer, + maxGap, gapAt, tailGap: composerTop - cursor, + following: host.querySelector('[data-chat-following-tail]') !== null, + collapsing: host.querySelector('[data-chat-motion="collapse"]') !== null, + } + } +} + +function paragraphs(marker: string, count: number, text: string): string { + return `${marker}\n\n${Array.from({ length: count }, (_, line) => `${text} ${line}.`).join('\n\n')}` +} + +/** Main-session log: settled Turns, then a long last Turn of expanded reasoning Steps and a final body. */ +function seededFixture(id: string, bodyParagraphs: number): ChatScrollFixture { + const base = createChatScrollFixture({ markerPrefix: 'FOLDMX', title: `FOLDMX ${id}`, turns: SEEDED_TURNS }) + const parsed = parseSeedFixture(base.log) + const boundary = parsed.events.findIndex(event => event.type === 'turn/start' && event.data.turn === SEEDED_TURNS) + const drafts: (SessionEvent | { type: string; data: object; surfaceOp?: 'append' })[] = parsed.events.slice(0, boundary) + .map((event) => { + if (event.type !== 'assistant/message' || event.data.turn !== SEEDED_TURNS - 1) return event + return { ...event, data: { ...event.data, message: createAssistantMessage({ + content: [{ type: 'text', text: paragraphs(`FOLDMX_PREVIOUS_${SEEDED_TURNS - 1}`, 6, 'Previous Turn answer paragraph') }], + source: { provider: 'fixture', model: 'fixture' }, + }) } } + }) + drafts.push( + { type: 'turn/start', data: { turn: SEEDED_TURNS } }, + { type: 'step/start', data: { turn: SEEDED_TURNS, step: 1 } }, + { type: 'user/message', data: createUserMessage({ + content: [{ type: 'text', text: 'FOLDMX_LAST_USER' }], source: { kind: 'user' }, + }), surfaceOp: 'append' }, + ) + for (let step = 1; step <= SEEDED_STEPS; step++) { + if (step > 1) drafts.push({ type: 'step/start', data: { turn: SEEDED_TURNS, step } }) + drafts.push({ type: 'assistant/message', surfaceOp: 'append', data: { + turn: SEEDED_TURNS, step, stream: [], message: createAssistantMessage({ + content: [ + { type: 'reasoning', text: paragraphs(`FOLDMX_STEP_${step}`, 18, `Reasoning stage ${step} explains an intermediate decision, paragraph`) }, + { type: 'text', text: `FOLDMX_PROGRESS_${step}` }, + ], + source: { provider: 'fixture', model: 'fixture' }, + }), + } }) + drafts.push({ type: 'step/end', data: { turn: SEEDED_TURNS, step } }) + } + drafts.push( + { type: 'step/start', data: { turn: SEEDED_TURNS, step: SEEDED_STEPS + 1 } }, + { type: 'assistant/message', surfaceOp: 'append', data: { + turn: SEEDED_TURNS, step: SEEDED_STEPS + 1, stream: [], message: createAssistantMessage({ + content: [{ type: 'text', text: paragraphs('FOLDMX_BODY', bodyParagraphs, 'Final answer paragraph that remains after the work details fold') }], + source: { provider: 'fixture', model: 'fixture' }, + }), + } }, + { type: 'step/end', data: { turn: SEEDED_TURNS, step: SEEDED_STEPS + 1 } }, + { type: 'turn/end', data: { turn: SEEDED_TURNS, reason: { kind: 'completed' } } }, + ) + return { ...base, log: [parsed.headerLine, + ...drafts.map((event, seq) => JSON.stringify({ ...event, seq, time: seq + 1 })), ''].join('\n') } +} + +function finish(kind: 'stop' | 'tool-calls'): StreamChunk[] { + return [ + { type: 'usage', usage: { inputTokens: 512, outputTokens: 64 } }, + { type: 'finish', reason: { kind } }, + ] +} + +function textChunks(text: string): StreamChunk[] { + return [ + { type: 'block-start', index: 0, blockType: 'text' }, + { type: 'text-delta', index: 0, text }, + { type: 'block-end', index: 0, block: { type: 'text', text } }, + ] +} + +function replyEntry(marker: string): ReplayEntry { + return { kind: 'chunks', chunks: [...textChunks(`${marker} short answer.`), ...finish('stop')] } +} + +/** One live Turn: Steps of narration plus a workspace read, then a long final body. */ +function liveLongTurn(prefix: string): ReplayEntry[] { + const entries: ReplayEntry[] = [] + for (let step = 1; step <= LIVE_STEPS; step++) { + const id = ToolCallId(`${prefix.toLowerCase()}-read-${step}`) + const args = JSON.stringify({ file_path: READ_FILE }) + entries.push({ kind: 'chunks', chunks: [ + ...textChunks(paragraphs(`${prefix}_STEP_${step}`, 10, `${prefix} narration for step ${step}, paragraph`)), + { type: 'block-start', index: 1, blockType: 'tool-call' }, + { type: 'tool-call-delta', index: 1, id, name: 'read', argumentsDelta: args }, + { type: 'block-end', index: 1, block: { type: 'tool-call', id, name: 'read', arguments: args } }, + ...finish('tool-calls'), + ] }) + } + entries.push({ kind: 'chunks', chunks: [ + ...textChunks(paragraphs(prefix === 'FOLDMX_LIVE' ? 'FOLDMX_LIVE_BODY' : `${prefix}_BODY`, 40, `${prefix} final answer paragraph`)), + ...finish('stop'), + ] }) + return entries +} + +function replayFor(scenario: Case): ReplayEntry[] { + switch (scenario.origin) { + case 'composer': + case 'other-tab': + return [replyEntry('FOLDMX_REPLY')] + case 'queued': + return [...liveLongTurn('FOLDMX_LIVE'), replyEntry('FOLDMX_REPLY')] + case 'steer': + return [...liveLongTurn('FOLDMX_LIVE').slice(0, STEER_STEPS), replyEntry('FOLDMX_STEERED')] + case 'parent-message': + return [replyEntry('FOLDMX_PARENT_REPLY')] + case 'error': + // The Turn fails before its model call; launchScaffold mounts only the provider catalog. + return [] + case 'big-exchange': + return [...liveLongTurn('FOLDMX_WAKE_A'), ...liveLongTurn('FOLDMX_WAKE_B'), replyEntry('FOLDMX_REPLY')] + } +} + +async function stableScroll(page: Page, root: string, timeoutMs = 20_000): Promise { + await page.evaluate(async ([selector, limit]) => { + const host = document.querySelector(selector) + if (host === null) throw new Error(`scrollport is absent: ${selector}`) + let previous = host.scrollTop + const started = performance.now() + let stableSince = started + await new Promise((resolveStable, reject) => { + const check = (): void => { + const now = performance.now() + const moving = host.querySelector('[data-chat-motion="collapse"], [data-chat-motion="reveal"]') !== null + if (Math.abs(host.scrollTop - previous) > 0.25 || moving) stableSince = now + previous = host.scrollTop + if (now - stableSince >= 300) resolveStable() + else if (now - started >= limit) reject(new Error(`scroll did not settle within ${String(limit)}ms: top ${String(host.scrollTop)}, motion ${String(moving)}`)) + else requestAnimationFrame(check) + } + requestAnimationFrame(check) + }) + }, [root, timeoutMs] as const) +} + +function measure(page: Page, root: string): Promise { + return page.evaluate((selector) => { + if (window.foldMeasure === undefined) throw new Error('fold measurement is not installed') + return window.foldMeasure(selector) + }, root) +} + +async function startTrace(page: Page, root: string): Promise { + await page.evaluate((selector) => { + const read = window.foldMeasure + if (read === undefined) throw new Error('fold measurement is not installed') + const samples: Geometry[] = [] + let frame = 0 + const tick = (): void => { + // A scrollport can remount between frames; that frame contributes no sample. + try { samples.push(read(selector)) } catch (_remounting) { /* skip this frame */ } + frame = requestAnimationFrame(tick) + } + window.foldProbe = { samples, stop: () => { cancelAnimationFrame(frame) } } + frame = requestAnimationFrame(tick) + }, root) +} + +async function stopTrace(page: Page): Promise { + return page.evaluate(() => { + const probe = window.foldProbe + if (probe === undefined) throw new Error('fold trace was not started') + probe.stop() + return probe.samples + }) +} + +/** Screen position of the smallest visible row containing a marker, relative to the scrollport top. */ +function anchorTop(page: Page, root: string, marker: string): Promise { + return page.evaluate(([selector, text]) => { + const host = document.querySelector(selector)! + const row = [...host.querySelectorAll('[data-chat-flow-key], [data-streaming]')] + .filter(candidate => candidate.closest('[hidden]') === null && (candidate.textContent ?? '').includes(text)) + .sort((left, right) => left.getBoundingClientRect().height - right.getBoundingClientRect().height)[0] + return row === undefined ? null : row.getBoundingClientRect().top - host.getBoundingClientRect().top + }, [root, marker] as const) +} + +async function toBottom(page: Page, root: string): Promise { + const button = page.locator(root).getByRole('button', { name: 'Back to bottom', exact: true }) + if (await button.count() > 0) await button.click() + await stableScroll(page, root) + await expect.poll(() => page.locator(`${root} [data-chat-following-tail]`).count()).toBe(1) +} + +async function placeReader(page: Page, root: string, reader: Reader): Promise { + if (reader.kind === 'bottom') { + await toBottom(page, root) + return + } + const delta = await page.evaluate(([selector, marker, align]) => { + const host = document.querySelector(selector)! + const viewport = host.getBoundingClientRect() + const composerTop = host.querySelector('[data-composer-seat]')!.getBoundingClientRect().top + const rows = [...host.querySelectorAll('[data-chat-flow-key], [data-streaming]')] + .filter(row => row.closest('[hidden]') === null && (row.textContent ?? '').includes(marker)) + .sort((left, right) => left.getBoundingClientRect().height - right.getBoundingClientRect().height) + const row = rows[0] + if (row === undefined) throw new Error(`reader anchor is absent: ${marker}`) + const rect = row.getBoundingClientRect() + return align === 'center' + ? rect.top + rect.height / 2 - (viewport.top + composerTop) / 2 + : rect.top - viewport.top - 24 + }, [root, reader.marker, reader.align] as const) + const box = await page.locator(root).boundingBox() + if (box === null) throw new Error('scrollport has no layout box') + await page.mouse.move(box.x + box.width / 2, box.y + Math.min(140, box.height / 3)) + await page.mouse.wheel(0, delta) + await stableScroll(page, root) + // Reader movement is sampled on scrollend or after the sampling interval. + await page.waitForTimeout(700) + expect(await page.locator(`${root} [data-chat-following-tail]`).count()).toBe(0) +} + +async function openSessionBySearch(page: Page, query: string): Promise { + await page.getByText('Ungrouped', { exact: true }).waitFor({ timeout: 30_000 }) + const searchButton = page.getByRole('button', { name: 'Search sessions' }) + if (await searchButton.getAttribute('aria-expanded') !== 'true') await searchButton.click() + await page.getByRole('textbox', { name: 'Search session names', exact: true }).fill(query) + const results = page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem') + await expect.poll(() => results.count(), { timeout: 60_000 }).toBe(1) + await results.click() +} + +async function choosePreferences(page: Page, scenario: Case): Promise { + 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: scenario.timing, exact: true }).click() + const details = dialog.getByText('Work details', { exact: true }).locator('../..') + await details.getByRole('button').click() + await page.getByRole('menuitem', { name: scenario.mode, exact: true }).click() + await dialog.getByRole('button', { name: 'Close', exact: true }).click() +} + +async function expandSeededSteps(page: Page, root: string, scenario: Case): Promise { + if (scenario.mode !== 'Detailed' || scenario.timing !== 'On next message') return + const thoughts = page.locator(`${root} [data-chat-turn="${SEEDED_TURNS}"] [data-variant="think"]`) + await expect.poll(() => thoughts.count()).toBe(SEEDED_STEPS) + for (let index = 0; index < SEEDED_STEPS; index++) { + const button = thoughts.nth(index).getByRole('button').first() + if (await button.getAttribute('aria-expanded') !== 'true') await button.click() + } + // Focus left inside a folding row keeps that row open; a reader who moved on has focused nothing there. + await page.evaluate(() => { if (document.activeElement instanceof HTMLElement) document.activeElement.blur() }) +} + +/** Model-call barrier for one live Turn. */ +interface FinishHold { + /** Resolves when the held call streams its finish; rejects after the timeout. */ + reached(timeoutMs: number): Promise + release(): void + dispose(): void + /** Model calls observed since installation and the target Session's latest event types. */ + describe(): string +} + +/** + * Hold the finish of the first model call for `session` whose streamed text contains `marker`. + * The call is identified by its replayed content, so auxiliary or reordered calls cannot shift the barrier. + */ +function holdFinishOf(scaffold: WebScaffold, session: SessionId, marker: string): FinishHold { + const gate = Promise.withResolvers() + const reached = Promise.withResolvers() + const calls: string[] = [] + let held = false + const dispose = scaffold.ctx.on('llm/stream', async function* (options, next) { + const index = calls.length + calls.push(`#${String(index)} ${options.sessionId ?? 'no-session'}/${options.purpose ?? 'turn'}`) + let matched = false + for await (const chunk of next()) { + if (chunk.type === 'block-end' && chunk.block.type === 'text' && chunk.block.text.includes(marker)) matched = true + if (chunk.type === 'finish') { + calls[index] = `${calls[index] ?? ''} finish=${chunk.reason.kind}${matched ? ` ${marker}` : ''}` + if (!held && matched && options.sessionId === session) { + held = true + reached.resolve(undefined) + await gate.promise + } + } + yield chunk + } + }) + const describe = (): string => { + const events = scaffold.ctx.agents.get(session)?.session.snapshotEvents() ?? [] + return `model calls: [${calls.join('; ')}]; ${session} event tail: ${events.slice(-12).map(event => event.type).join(', ')}` + } + return { + reached: async (timeoutMs) => { + let timer: ReturnType | undefined + const expired = new Promise((_resolve, reject) => { + timer = setTimeout(() => { reject(new Error(`no model call streamed ${marker} within ${String(timeoutMs)}ms`)) }, timeoutMs) + }) + try { + await Promise.race([reached.promise, expired]) + } finally { + clearTimeout(timer) + } + }, + release: () => { gate.resolve(undefined) }, + dispose: () => { gate.resolve(undefined); dispose() }, + describe, + } +} + +interface World { + readonly browser: Browser + readonly scaffold: WebScaffold + readonly page: Page + readonly root: string + /** Session receiving the folding message. */ + readonly target: SessionId + /** Live parent Agent for a side-chat case. */ + readonly parentId?: SessionId + readonly tripwire: ReturnType + /** Session-search text that selects the target's root Session. */ + readonly searchQuery: string +} + +function sessionKey(scenario: Case): string { + return `foldmx-${scenario.id.replaceAll('/', '-')}` +} + +async function createChild(scaffold: WebScaffold, parentId: SessionId, scenario: Case): Promise { + const childId = SessionId(`${sessionKey(scenario)}-child`) + const createdAt = Date.now() - 30_000 + const header: SessionHeader = { + version: SESSION_FORMAT_VERSION, id: childId, createdAt, isSeeded: false, cwd: scaffold.workspaceCwd, + parentSession: parentId, origin: 'subagent', delegationDepth: 1, + } + const parsed = parseSeedFixture(seededFixture(scenario.id, scenario.bodyParagraphs).log) + const firstUser = parsed.events.findIndex(event => event.type === 'user/message') + const ordered = [ + ...parsed.events.slice(0, firstUser + 1), + { type: 'subagent/descriptor', data: snapshotSubagentDescriptor({ + mode: 'continuable', provider: 'spawn', label: CHILD_LABEL, agentProvider: 'deepseek-official', agentModel: 'deepseek-v4-flash', + }) }, + ...parsed.events.slice(firstUser + 1), + ] + const events = ordered.map((event, seq) => ({ ...event, seq: SessionSeq(seq), time: createdAt + seq })) as SessionEvent[] + const handle = await scaffold.ctx.sessionPersistence.create(header) + await handle.append(events) + await handle.close() + scaffold.ctx.sessionProjectionCache.coldSnapshot(header, SessionLogOffset(0), events) + const deadline = Date.now() + 10_000 + while (scaffold.ctx.sessionProjectionCache.cachedSnapshot(header) === undefined) { + if (Date.now() >= deadline) throw new Error('child projection cache row did not land') + await new Promise(resolve => setTimeout(resolve, 10)) + } + const parent = scaffold.ctx.agents.get(parentId) + if (parent === undefined) throw new Error('parent Agent is not live') + parent.session.append('subagent/catalog', { version: 0, childId, childCreatedAt: createdAt, mode: 'continuable', label: CHILD_LABEL }) + return childId +} + +async function openWorld(browser: Browser, scenario: Case, replayDir: string): Promise { + const scaffold = await launchScaffold(scenario, replayDir) + let page: Page | undefined + try { + page = await newEnglishPage(browser, 900) + return await prepareWorld(browser, scenario, scaffold, page) + } catch (error) { + const failures: unknown[] = [error] + if (page !== undefined) await page.context().close().catch((cleanupError: unknown) => failures.push(cleanupError)) + await scaffold.close().catch((cleanupError: unknown) => failures.push(cleanupError)) + if (failures.length === 1) throw error + throw new AggregateError(failures, `${scenario.id}: world setup failed and cleanup was incomplete`) + } +} + +/** + * Launch the scaffold with the case's replay script. A Turn that fails before its model call consumes + * no script, so that case mounts only the provider catalog from a header-only fixture. + */ +async function launchScaffold(scenario: Case, replayDir: string): Promise { + if (scenario.origin === 'error') { + const header = seededFixture(scenario.id, scenario.bodyParagraphs).log.split('\n')[0] ?? '' + const fixture = join(replayDir, sessionFixtureName(0, SESSION_FORMAT_VERSION)) + await writeFile(fixture, `${header}\n`) + return launchWebScaffold({ replayFixture: fixture, replayProvidersOnly: true }) + } + await writeFile(join(replayDir, 'replay.override.json'), JSON.stringify(replayFor(scenario))) + return launchWebScaffold({ + replayFixture: join(replayDir, 'override-only.jsonl'), + replayOverride: join(replayDir, 'replay.override.json'), + paceMs: 16, + replayContextWindow: 10_000_000, + }) +} + +/** Seed the case's Sessions, open the surface, and choose the display preferences. */ +async function prepareWorld(browser: Browser, scenario: Case, scaffold: WebScaffold, page: Page): Promise { + await writeFile(join(scaffold.workspaceCwd, READ_FILE), 'fold matrix notes\n') + const tripwire = watchConsole(page) + await page.addInitScript(installMeasure) + await page.setViewportSize(scenario.surface === 'main' ? { width: 1280, height: 720 } : { width: 1680, height: 900 }) + await page.emulateMedia({ reducedMotion: 'no-preference' }) + const sessionId = SessionId(sessionKey(scenario)) + if (scenario.surface === 'main') { + const fixture = seededFixture(scenario.id, scenario.bodyParagraphs) + await seedSession(scaffold, fixture.log, sessionId) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await openSessionBySearch(page, fixture.markers.user(1)) + await page.locator(MAIN_ROOT).getByText('FOLDMX_BODY', { exact: false }).last().waitFor({ timeout: 30_000 }) + const resolved = await scaffold.ctx.sessionController.resolveAgent(sessionId) + if ('error' in resolved) throw resolved.error + scaffold.ctx.permissionPresets.set(resolved.agent.session, 'danger-full-access') + await choosePreferences(page, scenario) + return { browser, scaffold, page, root: MAIN_ROOT, target: sessionId, tripwire, searchQuery: fixture.markers.user(1) } + } + const parentFixture = createChatScrollFixture({ markerPrefix: 'FOLDMXP', title: `FOLDMX parent ${scenario.id}`, turns: 2 }) + await seedSession(scaffold, parentFixture.log, sessionId) + const resolved = await scaffold.ctx.sessionController.resolveAgent(sessionId) + if ('error' in resolved) throw resolved.error + scaffold.ctx.permissionPresets.set(resolved.agent.session, 'danger-full-access') + const childId = await createChild(scaffold, sessionId, scenario) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await openSessionBySearch(page, parentFixture.markers.user(1)) + await choosePreferences(page, scenario) + const trigger = page.getByRole('button', { name: '1 subagent', exact: true }) + await trigger.waitFor({ timeout: 15_000 }) + await trigger.hover() + await page.getByRole('treeitem', { name: new RegExp(CHILD_LABEL) }) + .getByRole('button', { name: `Open ${CHILD_LABEL} in sidebar`, exact: true }).click() + await page.locator(SIDE_ROOT).getByText('FOLDMX_BODY', { exact: false }).last().waitFor({ timeout: 30_000 }) + await page.mouse.move(0, 0) + return { + browser, scaffold, page, root: SIDE_ROOT, target: childId, parentId: sessionId, tripwire, + searchQuery: parentFixture.markers.user(1), + } +} + +function composerOf(world: World): ReturnType { + return world.page.locator(`${world.root} [data-composer-input][contenteditable="true"]`).last() +} + +async function send(world: World, text: string): Promise { + await composerOf(world).fill(text) + await world.page.locator(world.root).getByRole('button', { name: 'Send message', exact: true }).click() +} + +/** Wait until a Session's Agent ends a Turn. */ +function turnEnded(scaffold: WebScaffold, sessionId: SessionId, count = 1, timeoutMs = 60_000): Promise { + return new Promise((resolveEnded, reject) => { + let remaining = count + const timer = setTimeout(() => { off(); reject(new Error(`no turn/end for ${sessionId} within ${timeoutMs}ms`)) }, timeoutMs) + const off = scaffold.ctx.on('session/event', (session: { id: SessionId }, event: SessionEvent) => { + if (session.id !== sessionId || event.type !== 'turn/end') return + remaining -= 1 + if (remaining > 0) return + clearTimeout(timer) + off() + resolveEnded() + }) + }) +} + +async function settle(world: World): Promise { + await expect.poll(() => world.page.locator(`${world.root} [data-streaming="true"]`).count(), { timeout: 30_000 }).toBe(0) + await stableScroll(world.page, world.root) + await world.page.waitForTimeout(900) + await stableScroll(world.page, world.root) +} + +/** Drive one case from its prepared reader position through the folding message and its Turn. */ +interface RunResult { + readonly afterFold: Geometry + readonly afterTurn: Geometry + readonly samples: Geometry[] + /** Reader anchor row positions when sending, after the fold, and after the Turn. */ + readonly anchors: { before: number | null; fold: number | null; turn: number | null } +} + +async function run(world: World, scenario: Case): Promise { + const { page, root, scaffold, target } = world + const anchors: RunResult['anchors'] = { before: null, fold: null, turn: null } + const readAnchor = (): Promise => scenario.reader.kind === 'marker' + ? anchorTop(page, root, scenario.reader.marker) : Promise.resolve(null) + const begin = async (): Promise => { + anchors.before = await readAnchor() + await startTrace(page, root) + } + const folded = async (): Promise => { + await stableScroll(page, root) + anchors.fold = await readAnchor() + return measure(page, root) + } + let afterFold: Geometry + switch (scenario.origin) { + case 'composer': + case 'error': { + const disposeFailure = scenario.origin === 'error' + ? scaffold.ctx.on('system-prompt/assemble', async () => { throw new Error('FOLDMX_TURN_FAILED') }) + : () => undefined + // A subagent child's composer sends through the subagent continuation route. + const promptRoute = scenario.surface === 'side' ? '**/api/subagents/prompt' : '**/api/session/prompt' + const promptGate = Promise.withResolvers() + const promptHeld = Promise.withResolvers() + const holdPrompt = async (route: Route): Promise => { + promptHeld.resolve(undefined) + await promptGate.promise + await route.continue() + } + await page.route(promptRoute, holdPrompt) + const ended = turnEnded(scaffold, target) + try { + await expandSeededSteps(page, root, scenario) + await placeReader(page, root, scenario.reader) + await begin() + await send(world, NEXT_INPUT) + await promptHeld.promise + await page.locator(`${root} [data-submission-echo]`).waitFor() + afterFold = await folded() + promptGate.resolve(undefined) + await ended + } finally { + promptGate.resolve(undefined) + disposeFailure() + await page.unroute(promptRoute, holdPrompt) + } + break + } + case 'other-tab': { + await expandSeededSteps(page, root, scenario) + const other = await newEnglishPage(world.browser, 720) + await other.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await openSessionBySearch(other, world.searchQuery) + await other.locator(MAIN_ROOT).getByText('FOLDMX_BODY', { exact: false }).last().waitFor({ timeout: 30_000 }) + await placeReader(page, root, scenario.reader) + await begin() + const ended = turnEnded(scaffold, target) + await other.locator(`${MAIN_ROOT} [data-composer-input][contenteditable="true"]`).last().fill(NEXT_INPUT) + await other.locator(MAIN_ROOT).getByRole('button', { name: 'Send message', exact: true }).click() + await page.locator(`${root} [data-chat-flow-kind="user"]`, { hasText: NEXT_INPUT }).waitFor() + afterFold = await folded() + await ended + await other.context().close() + break + } + case 'queued': + case 'steer': { + // Queued: hold the long final body. Steer: hold the last replayed Step so the steering message lands in this Turn. + const gate = holdFinishOf(scaffold, target, scenario.origin === 'queued' ? 'FOLDMX_LIVE_BODY' : `FOLDMX_LIVE_STEP_${String(STEER_STEPS)}`) + const first = turnEnded(scaffold, target, scenario.origin === 'queued' ? 2 : 1) + // A failed earlier step reports itself; the success path still awaits and rethrows this rejection. + first.catch(() => undefined) + try { + await toBottom(page, root) + await send(world, 'FOLDMX_START_LIVE_TURN') + await gate.reached(60_000) + await stableScroll(page, root) + if (scenario.origin === 'queued' && scenario.reader.kind === 'marker') { + await page.locator(root).getByText('FOLDMX_LIVE_BODY', { exact: false }).last().waitFor() + } + await placeReader(page, root, scenario.reader) + await composerOf(world).fill(NEXT_INPUT) + await composerOf(world).press('Enter') + const steerButton = page.getByRole('button', { name: 'Steer queued message' }) + await steerButton.waitFor({ timeout: 15_000 }) + if (scenario.origin === 'steer') { + await expect.poll(() => steerButton.isEnabled(), { timeout: 10_000 }).toBe(true) + await steerButton.click() + } + await begin() + gate.release() + await page.locator(`${root} [data-chat-flow-kind="user"], ${root} [data-chat-flow-kind="steering"]`, { hasText: NEXT_INPUT }) + .first().waitFor({ timeout: 30_000 }) + afterFold = await folded() + await first + } catch (error) { + throw new Error(`${scenario.id}: ${error instanceof Error ? error.message : String(error)}\n${gate.describe()}`, { cause: error }) + } finally { + gate.dispose() + } + break + } + case 'parent-message': { + await expandSeededSteps(page, root, scenario) + await placeReader(page, root, scenario.reader) + await begin() + const parent = scaffold.ctx.agents.get(world.parentId!) + if (parent === undefined) throw new Error('parent Agent is not live') + const ended = turnEnded(scaffold, target) + await scaffold.ctx.subagents.sendMessage(parent, target, [{ type: 'text', text: 'FOLDMX_PARENT_NOTE' }], { signal: new AbortController().signal }) + await page.locator(`${root} [data-chat-turn="${SEEDED_TURNS + 1}"]`).first().waitFor({ timeout: 30_000 }) + afterFold = await folded() + await ended + break + } + case 'big-exchange': { + const parent = scaffold.ctx.agents.get(world.parentId!) + if (parent === undefined) throw new Error('parent Agent is not live') + for (const note of ['FOLDMX_WAKE_A_NOTE', 'FOLDMX_WAKE_B_NOTE']) { + const woken = turnEnded(scaffold, target) + await scaffold.ctx.subagents.sendMessage(parent, target, [{ type: 'text', text: note }], { signal: new AbortController().signal }) + await woken + } + await settle(world) + await placeReader(page, root, scenario.reader) + await begin() + const ended = turnEnded(scaffold, target) + await send(world, NEXT_INPUT) + await page.locator(`${root} [data-chat-flow-kind="user"]`, { hasText: NEXT_INPUT }).waitFor({ timeout: 30_000 }) + afterFold = await folded() + await ended + break + } + } + await settle(world) + anchors.turn = await readAnchor() + const afterTurn = await measure(page, root) + const samples = await stopTrace(page) + return { afterFold, afterTurn, samples, anchors } +} + +function rounded(geometry: Geometry): Record { + return { + top: Math.round(geometry.top), floor: Math.round(geometry.floor), spacer: Math.round(geometry.spacer), + maxGap: Math.round(geometry.maxGap), gapAt: Math.round(geometry.gapAt), following: geometry.following, + } +} + +describe.skipIf(MODE === 'record')('web e2e: blank area after next-message folding', () => { + let browser: Browser + + beforeAll(async () => { + browser = await chromium.launch() + }) + + afterAll(async () => { + await browser?.close() + }) + + for (const scenario of CASES) { + it(scenario.id, async () => { + const replayDir = await mkdtemp(join(tmpdir(), 'dsh-fold-matrix-')) + let world: World | undefined + try { + world = await openWorld(browser, scenario, replayDir) + const { afterFold, afterTurn, samples, anchors } = await run(world, scenario) + const transient = samples.filter(sample => sample.maxGap > BLANK_LIMIT) + const summary = { + id: scenario.id, landing: scenario.landing, before: samples[0] === undefined ? null : rounded(samples[0]), + afterFold: rounded(afterFold), afterTurn: rounded(afterTurn), anchors, + peakGap: Math.round(Math.max(0, ...samples.map(sample => sample.maxGap))), + framesOverLimit: transient.length, frames: samples.length, + peakSpacer: Math.round(Math.max(0, ...samples.map(sample => sample.spacer))), + } + const evidence = async (): Promise => { + await mkdir(EVIDENCE, { recursive: true }) + await writeFile(join(EVIDENCE, `${sessionKey(scenario)}.json`), JSON.stringify({ scenario, ...summary, samples }, null, 2)) + console.log(`FOLDMX ${JSON.stringify(summary)}`) + } + // Per-frame evidence is written for failures, or for every case with FOLDMX_EVIDENCE=1. + if (process.env.FOLDMX_EVIDENCE === '1') await evidence() + else onTestFailed(evidence) + if (scenario.origin === 'parent-message' || scenario.origin === 'steer') { + expect.soft(samples.some(sample => sample.collapsing), 'a control case folds nothing').toBe(false) + } + if (scenario.roomUntilReply !== true) { + expect.soft(afterFold.maxGap, 'layout gap after the fold settles').toBeLessThanOrEqual(BLANK_LIMIT) + expect.soft(transient.length, 'animation frames with a layout gap').toBeLessThanOrEqual(TRANSIENT_FRAMES) + } + expect.soft(afterTurn.maxGap, 'layout gap after the Turn settles').toBeLessThanOrEqual(BLANK_LIMIT) + if (scenario.landing === 'tail') { + expect.soft(afterFold.floor - afterFold.top, 'distance from the floor after the fold').toBeLessThanOrEqual(1) + expect.soft(afterTurn.floor - afterTurn.top, 'distance from the floor after the Turn').toBeLessThanOrEqual(1) + expect.soft(afterTurn.following, 'following after the Turn').toBe(true) + } else if (scenario.anchorFolds !== true) { + expect.soft(anchors.before).not.toBeNull() + expect.soft(Math.abs((anchors.fold ?? Infinity) - (anchors.before ?? 0)), 'anchor movement after the fold').toBeLessThanOrEqual(2) + expect.soft(Math.abs((anchors.turn ?? Infinity) - (anchors.before ?? 0)), 'anchor movement after the Turn').toBeLessThanOrEqual(2) + } + expect.soft(world.tripwire.pageErrors).toEqual([]) + } finally { + // Scaffold close also asserts that every replay entry was consumed; its failures fail the case. + const failures: unknown[] = [] + await world?.page.context().close().catch((error: unknown) => failures.push(error)) + await world?.scaffold.close().catch((error: unknown) => failures.push(error)) + await rm(replayDir, { recursive: true, force: true }).catch((error: unknown) => failures.push(error)) + if (failures.length === 1) throw failures[0] + if (failures.length > 1) throw new AggregateError(failures, `${scenario.id}: cleanup failed`) + } + }) + } +}) + +export {} diff --git a/apps/web/tests/jobs-menu-layering.e2e.ts b/apps/web/tests/jobs-menu-layering.e2e.ts new file mode 100644 index 0000000000..040531ba95 --- /dev/null +++ b/apps/web/tests/jobs-menu-layering.e2e.ts @@ -0,0 +1,199 @@ +/** Background-job menu geometry over the normal Browser dock in the shipped Web composition. */ +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import { join } from 'node:path' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { ToolCallId } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import { JobId } from '@deepseek-ai/dsh-jobs' +import { + assertFixtureInventory, compareOrRefreshGolden, launchWebScaffold, seedSession, + watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url)) +const EXPECTED_DIR = fileURLToPath(new URL('./expected/jobs-menu-layering', import.meta.url)) +const MODE = webSnapshotMode() +const SEED_ID = SessionId('jobs-menu-layering-web-e2e') +// The private scaffold cwd owns the barrier; the loop bounds an orphan's lifetime. +const RELEASE = '.jobs-menu-layering.release' +const COMMAND = `printf 'jobs-menu-%s\\n' output; for _ in $(seq 1 3000); do [ -e ${RELEASE} ] && break; sleep 0.2; done` + +/** Measure actual overlap and hit testing; ARIA alone cannot expose clipping or stacking. */ +function placement(page: Page) { + return page.evaluate(() => { + const list = document.querySelector('ul[aria-label="Background jobs"]') + const anchor = document.querySelector('button[aria-label="1 background job running"]') + const frame = document.querySelector('[data-sidebar-browser-frame]') + const dock = document.querySelector('[data-sidebar-right-panel][data-sidebar-right-open]') + if (list === null || anchor === null || frame === null || dock === null) { + throw new Error('job menu, trigger, or Browser dock is missing') + } + const menu = list.closest('[data-menu-material]') ?? list + const box = menu.getBoundingClientRect() + const trigger = anchor.getBoundingClientRect() + const browser = frame.getBoundingClientRect() + const left = Math.max(box.left, browser.left) + const right = Math.min(box.right, browser.right) + const top = Math.max(box.top, browser.top) + const bottom = Math.min(box.bottom, browser.bottom) + const overlapsBrowser = right - left > 8 && bottom - top > 8 + const aboveBrowser = overlapsBrowser && [0.25, 0.5, 0.75].every(x => + [0.25, 0.5, 0.75].every(y => menu.contains(document.elementFromPoint( + left + (right - left) * x, top + (bottom - top) * y, + )))) + const expectedLeft = Math.min(Math.max(trigger.left, 12), innerWidth - box.width - 12) + const expectedTop = Math.min(Math.max(trigger.bottom + 5, 12), innerHeight - box.height - 12) + return { + dockMode: dock.dataset.sidebarRightPanel, + bodyMounted: menu.parentElement === document.body, + fixed: getComputedStyle(menu).position === 'fixed', + anchored: Math.abs(box.left - expectedLeft) <= 1 && Math.abs(box.top - expectedTop) <= 1, + viewportBounded: box.left >= 11 && box.top >= 11 + && box.right <= innerWidth - 11 && box.bottom <= innerHeight - 11, + overlapsBrowser, + aboveBrowser, + } + }) +} + +describe.skipIf(MODE === 'record')('web e2e: jobs menu layering', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + let agent: Agent + let jobId: JobId | undefined + + beforeAll(async () => { + scaffold = await launchWebScaffold({ + extraOverlayPath: fileURLToPath(new URL('./sidebar-browser.overlay.yml', import.meta.url)), + }) + await seedSession(scaffold, await readFile(FIXTURE, 'utf8'), SEED_ID) + browser = await chromium.launch() + page = await newEnglishPage(browser) + await page.emulateMedia({ reducedMotion: 'reduce' }) + await page.route('https://browser.test/**', async route => route.fulfill({ + contentType: 'text/html', body: '

Jobs menu browser fixture

', + })) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + }) + + afterAll(async () => { + const failures: unknown[] = [] + if (scaffold !== undefined) { + try { + await writeFile(join(scaffold.workspaceCwd, RELEASE), '') + if (jobId !== undefined) { + const settled = await scaffold.ctx.jobs.wait(jobId, 15_000, agent.id) + if (settled.status === 'running' || settled.status === 'stopping') { + throw new Error('jobs menu fixture did not settle after releasing its barrier') + } + } + } catch (error) { failures.push(error) } + } + try { await browser?.close() } catch (error) { failures.push(error) } + try { await scaffold?.close() } catch (error) { failures.push(error) } + if (failures.length > 0) throw new AggregateError(failures, 'jobs menu layering teardown failed') + }) + + it('keeps the list and live output above the Browser dock while anchored and dismissable', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-jobs-menu-layering')) + const session = page.locator(`[data-row-key="session:${SEED_ID}"]`) + await expect.poll(async () => { + if (await session.isVisible()) return true + const group = page.locator('[role="treeitem"][aria-expanded]').first() + if (await group.count() > 0 && await group.getAttribute('aria-expanded') === 'false') await group.click() + return session.isVisible() + }, { timeout: 15_000 }).toBe(true) + await session.click() + await expect.poll(() => scaffold.ctx.agents.get(SEED_ID), { timeout: 30_000 }).toBeDefined() + const opened = scaffold.ctx.agents.get(SEED_ID) + if (opened === undefined) throw new Error('opened session has no live Agent') + agent = opened + const started = await scaffold.ctx.tools.execute({ + signal: new AbortController().signal, + callId: ToolCallId('jobs-menu-layering-e2e'), + name: 'bash', + arguments: { command: COMMAND, description: 'Emit output and hold the jobs menu fixture', run_in_background: true }, + agent, + }) + const reported = started.content.map(block => block.type === 'text' ? block.text : '').join('') + const matched = /\bbash-[0-9a-f]{16}\b/.exec(reported) + if (matched === null) throw new Error(`background bash reported no job id: ${reported}`) + const startedJobId = JobId(matched[0]) + jobId = startedJobId + // Registration precedes shell startup; inspect its output before depending on a live row. + await expect.poll(() => { + const job = scaffold.ctx.jobs.get(startedJobId, agent.id) + const output = scaffold.ctx.jobs.readAt(startedJobId, 0, agent.id).chunks.map(chunk => chunk.text).join('') + return job.status !== 'running' || output.includes('jobs-menu-output') + }, { timeout: 15_000 }).toBe(true) + const readyJob = scaffold.ctx.jobs.get(startedJobId, agent.id) + const readyOutput = scaffold.ctx.jobs.readAt(startedJobId, 0, agent.id).chunks.map(chunk => chunk.text).join('') + expect(readyJob.status, `${readyJob.detail ?? ''}\n${readyOutput}`).toBe('running') + + await page.locator('[data-sidebar-right-expand]').click() + const column = page.locator('[data-rightbar-col]') + await column.locator('[data-sidebar-right-guide-entry="browser"]').click() + const address = column.getByRole('textbox', { name: 'Enter an HTTP(S) address' }) + await address.fill('https://browser.test/jobs-menu') + await address.press('Enter') + await page.frameLocator('[data-sidebar-browser-frame]') + .getByRole('heading', { name: 'Jobs menu browser fixture' }).waitFor() + + const trigger = page.getByRole('button', { name: '1 background job running', exact: true }) + await trigger.waitFor({ timeout: 15_000 }) + await trigger.focus() + await page.keyboard.press('Enter') + const list = page.getByRole('list', { name: 'Background jobs' }) + await list.waitFor() + await page.keyboard.press('Tab') + expect(await list.getByRole('button', { name: /Show live output/ }) + .evaluate(element => element === document.activeElement)).toBe(true) + const expectedPlacement = { + dockMode: 'push', bodyMounted: true, fixed: true, anchored: true, + viewportBounded: true, overlapsBrowser: true, aboveBrowser: true, + } + await expect.poll(() => placement(page)).toEqual(expectedPlacement) + const collapsed = await placement(page) + + await list.getByRole('button', { name: /Show live output/ }).click() + await list.getByText('jobs-menu-output', { exact: true }).waitFor({ timeout: 15_000 }) + await expect.poll(() => placement(page)).toEqual(expectedPlacement) + const expanded = await placement(page) + + await page.setViewportSize({ width: 1280, height: 760 }) + await expect.poll(() => placement(page)).toEqual(expectedPlacement) + const resized = await placement(page) + await list.getByRole('button', { name: /Hide live output/ }).focus() + await page.keyboard.press('Escape') + await list.waitFor({ state: 'detached' }) + const escapeRestoresFocus = await trigger.evaluate(node => node === document.activeElement) + expect(escapeRestoresFocus).toBe(true) + + await trigger.click() + await list.waitFor() + await address.click() + await list.waitFor({ state: 'detached' }) + const outsideDismisses = await trigger.getAttribute('aria-expanded') === 'false' + expect(outsideDismisses).toBe(true) + expect(scaffold.ctx.jobs.get(jobId, agent.id).status).toBe('running') + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + + await mkdir(EXPECTED_DIR, { recursive: true }) + await compareOrRefreshGolden(join(EXPECTED_DIR, 'geometry.expected.md'), [ + '# Background jobs above the Browser dock', '', + '```json', + JSON.stringify({ collapsed, expanded, resized, escapeRestoresFocus, outsideDismisses }, null, 2), + '```', + ].join('\n'), MODE) + await assertFixtureInventory(EXPECTED_DIR, ['geometry.expected.md']) + }) +}) 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/lifecycle-chrome.e2e.ts b/apps/web/tests/lifecycle-chrome.e2e.ts index 4f9fba2f43..a9226b7fb7 100644 --- a/apps/web/tests/lifecycle-chrome.e2e.ts +++ b/apps/web/tests/lifecycle-chrome.e2e.ts @@ -399,14 +399,13 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () const processWasOpen = await process.getAttribute('aria-expanded') === 'true' try { await expandOwningTurnProcess(page, thinkRow) - const collapsedHeader = thinkRow.locator('[data-disclosure-row]').first() + const collapsedHeader = thinkRow.locator('[data-disclosure-header]').first() await collapsedHeader.waitFor({ timeout: 10_000 }) // Collapsed, the rule's `data-open` gate is absent and the header stays in - // flow. It is `relative` here — the row is the sweep-glare overlay anchor - // — so the assertion is the absence of `sticky`, not a specific value. + // flow, so assert the absence of `sticky`, not a specific value. expect(await collapsedHeader.evaluate(element => getComputedStyle(element).position)).not.toBe('sticky') - await collapsedHeader.click() - const openHeader = page.locator('[data-variant="think"] [data-open] [data-disclosure-row]').first() + await collapsedHeader.locator('[data-disclosure-row]').click() + const openHeader = page.locator('[data-variant="think"] [data-open] [data-disclosure-header]').first() await openHeader.waitFor({ timeout: 10_000 }) const openStyle = await openHeader.evaluate((element) => { const style = getComputedStyle(element) diff --git a/apps/web/tests/live-interactions.e2e.ts b/apps/web/tests/live-interactions.e2e.ts index 2af1c89b66..1eedb317fd 100644 --- a/apps/web/tests/live-interactions.e2e.ts +++ b/apps/web/tests/live-interactions.e2e.ts @@ -41,6 +41,7 @@ const RUNNING_DRAFT_EXPECTED = join(SNAPSHOT_DIR, 'running-draft.expected.md') const ERROR_EXPECTED = join(SNAPSHOT_DIR, 'error-auth.expected.md') const RETRY_EXPECTED = join(SNAPSHOT_DIR, 'retry.expected.md') const RETRY_EXPANDED_EXPECTED = join(SNAPSHOT_DIR, 'retry-expanded.expected.md') +const RETRY_REQUEST_EXPECTED = join(SNAPSHOT_DIR, 'retry-request.expected.md') const RETRY_EXHAUSTED_EXPECTED = join(SNAPSHOT_DIR, 'retry-exhausted.expected.md') const MODE = webSnapshotMode() const AUTH_PROVIDER_MESSAGE = 'Authentication Fails, Your api key: sk-preview-secret is invalid' @@ -342,11 +343,22 @@ describe('web e2e: live-turn interactions (cancel / error / retry)', () => { // sourced from the recording, never copied into a committed sidecar. { at: 1, entry: derived[0]! }, ], - })) + }), { + mode: 'normal', maxRetries: 5, retryableCodes: ['SERVER'], + backoff: { initialDelayMs: 25, maxDelayMs: 25, jitterRatio: 0 }, + }) onTestFailed(() => saveFailureShot(page, 'web-e2e-retry')) const releaseFailure = Promise.withResolvers() + const retryReady = Promise.withResolvers() + const releaseRetry = Promise.withResolvers() + const requestStates: string[] = [] + let attempts = 0 // Retirement must follow a visible partial, not race the first browser paint. const stopHolding = scaffold!.ctx.on('llm/stream', async function* (_request, next) { + if (++attempts === 2) { + retryReady.resolve(undefined) + await releaseRetry.promise + } for await (const chunk of next()) { yield chunk if (chunk.type === 'text-delta' && chunk.text === RETRY_PARTIAL) await releaseFailure.promise @@ -356,9 +368,20 @@ describe('web e2e: live-turn interactions (cancel / error / retry)', () => { const { settled } = await sendPrompt(60_000) await page.getByText(RETRY_PARTIAL, { exact: true }).waitFor({ timeout: 15_000 }) releaseFailure.resolve(undefined) + await retryReady.promise + await page.getByRole('tab', { name: 'Trajectory', exact: true }).click() + await page.getByRole('table').getByRole('button', { name: 'Request #1', exact: true }).click() + const overview = page.getByRole('tabpanel').locator('dl').first() + await overview.getByText('Pending', { exact: true }).waitFor() + await overview.getByText('Last attempt error', { exact: true }).waitFor() + expect(await overview.getByText('Error', { exact: true }).count()).toBe(0) + requestStates.push('# Retrying request', await overview.ariaSnapshot()) + await page.getByRole('tab', { name: 'Chat', exact: true }).click() + releaseRetry.resolve(undefined) await settled } finally { releaseFailure.resolve(undefined) + releaseRetry.resolve(undefined) stopHolding() } expect(turnEndReasons(sessionEvents).at(-1)).toBe('completed') @@ -379,6 +402,14 @@ describe('web e2e: live-turn interactions (cancel / error / retry)', () => { scaffold!.workspaceCwd, ) await compareOrRefreshGolden(RETRY_EXPANDED_EXPECTED, expanded, MODE) + await page.getByRole('tab', { name: 'Trajectory', exact: true }).click() + await page.getByRole('table').getByRole('button', { name: 'Request #1', exact: true }).click() + const overview = page.getByRole('tabpanel').locator('dl').first() + await overview.getByText('Completed', { exact: true }).waitFor() + await overview.getByText('Last attempt error', { exact: true }).waitFor() + expect(await overview.getByText('Error', { exact: true }).count()).toBe(0) + requestStates.push('# Recovered request', await overview.ariaSnapshot()) + await compareOrRefreshGolden(RETRY_REQUEST_EXPECTED, requestStates.join('\n\n'), MODE) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) }, 120_000) @@ -420,7 +451,7 @@ describe('web e2e: live-turn interactions (cancel / error / retry)', () => { await assertFixtureInventory(SNAPSHOT_DIR, [ 'session.v3.jsonl', 'cancel.expected.md', 'cancel-expanded.expected.md', 'loading.expected.md', 'running-draft.expected.md', 'error-auth.expected.md', - 'retry.expected.md', 'retry-expanded.expected.md', 'retry-exhausted.expected.md', + 'retry.expected.md', 'retry-expanded.expected.md', 'retry-request.expected.md', 'retry-exhausted.expected.md', ]) }) }) diff --git a/apps/web/tests/live-job-stream.e2e.ts b/apps/web/tests/live-job-stream.e2e.ts index c88923e8e6..2b4fb64d68 100644 --- a/apps/web/tests/live-job-stream.e2e.ts +++ b/apps/web/tests/live-job-stream.e2e.ts @@ -95,7 +95,7 @@ describe.skipIf(MODE === 'record')('web e2e: live job stream', () => { agent, }) const reported = started.content.map(block => block.type === 'text' ? block.text : '').join('') - const matched = /\bbash-\d+\b/.exec(reported) + const matched = /\bbash-[0-9a-f]{16}\b/.exec(reported) if (matched === null) throw new Error(`background bash reported no job id: ${reported}`) const jobId = JobId(matched[0]) 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/message-actions.e2e.ts b/apps/web/tests/message-actions.e2e.ts index c8b9c35b55..2254c9dafe 100644 --- a/apps/web/tests/message-actions.e2e.ts +++ b/apps/web/tests/message-actions.e2e.ts @@ -3,16 +3,17 @@ // calls) and pins the settled conversation aria after the footers are // focus-revealed — the surface package jsdom tests cannot substitute for // (docs/testing.md snapshot rule). -import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import type { Browser, Page } from 'playwright' +import { zstdCompressSync } from 'node:zlib' +import type { Browser, Page, Request as BrowserRequest } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' -import { SessionId } from '@deepseek-ai/dsh-session' +import { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session' import { acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, - launchWebScaffold, parseSeedFixture, renderSeedFixture, seedSession, watchConsole, webSnapshotMode, type WebScaffold, + launchWebScaffold, parseSeedFixture, realizeSeedFixture, renderSeedFixture, seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { openSettings, newEnglishPage, pinBrowserClock, saveFailureShot, WEB_FIXTURE_TIME } from './support.ts' @@ -22,6 +23,7 @@ const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/message-actio const SEED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url)) const UI_EXPECTED = join(SNAPSHOT_DIR, 'ui.expected.md') const FORK_EXPECTED = join(SNAPSHOT_DIR, 'fork.expected.md') +const UNOPENED_FORK_EXPECTED = join(SNAPSHOT_DIR, 'fork-unopened.expected.md') const MODE = webSnapshotMode() const SEED_ID = 'message-actions-web-e2e' @@ -192,7 +194,8 @@ describe('web e2e: message IconActions and clocks on settled history', () => { let unpinBrowserClock: (() => void) | undefined beforeAll(async () => { - scaffold = await launchWebScaffold({}) + scaffold = await launchWebScaffold() + await mkdir(fileURLToPath(new URL('../../../.artifacts/screenshots/non-migrating-session-reads', import.meta.url)), { recursive: true }) const sessionCwd = join(scaffold.workspaceCwd, 'workspace') await mkdir(sessionCwd, { recursive: true }) await writeFile(join(sessionCwd, 'a.txt'), 'alpha\n') @@ -222,7 +225,7 @@ describe('web e2e: message IconActions and clocks on settled history', () => { }) it.skipIf(MODE === 'record')('enables branch only on the completed transcript tail', async () => { - onTestFailed(() => saveFailureShot(page, 'web-e2e-message-actions')) + onTestFailed(() => saveFailureShot(page, 'screenshots/non-migrating-session-reads/web-e2e-message-actions')) const groupRow = page.locator('[role="treeitem"]').first() await groupRow.waitFor({ timeout: 15_000 }) await groupRow.click() @@ -423,9 +426,83 @@ describe('web e2e: message IconActions and clocks on settled history', () => { await compareOrRefreshGolden(FORK_EXPECTED, tree, MODE) }) + it.skipIf(MODE === 'record')('forks an unopened current-format Session from its sidebar row', async () => { + onTestFailed(() => saveFailureShot(page, 'screenshots/non-migrating-session-reads/current-cold-fork')) + const id = SessionId('message-actions-current-cold') + await seedSession(scaffold, completedTailFixture(await readFile(SEED, 'utf8')), id) + const warningStart = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + const row = page.locator(`[data-row-key="session:${id}"]`) + await row.waitFor() + acknowledgeReloadConnectionLoss(tripwire, warningStart) + expect(scaffold.ctx.agents.get(id)).toBeUndefined() + await row.hover() + await row.locator('button[aria-label^="Session actions for "]').click() + await page.getByRole('menuitem', { name: 'Fork session', exact: true }).click() + await expect.poll(() => scaffold.ctx.agents.list().some(agent => agent.session.header.parentSession === id)).toBe(true) + expect(scaffold.ctx.agents.get(id)).toBeUndefined() + expect(await row.getAttribute('aria-selected')).not.toBe('true') + }) + + it.skipIf(MODE === 'record')('guides only a migration-required sidebar fork to opening its source', async () => { + onTestFailed(() => saveFailureShot(page, 'screenshots/non-migrating-session-reads/migration-required-fork')) + const id = SessionId('message-actions-needs-migration') + const [header, ...events] = realizeSeedFixture(scaffold, await readFile(SEED, 'utf8'), id).trimEnd().split('\n') + .map((line): Record => JSON.parse(line) as Record) + expect(header?.version).toBe(3) + const projects = (await readdir(scaffold.persistenceRoot, { withFileTypes: true })).filter(entry => entry.isDirectory()) + expect(projects).toHaveLength(1) + const directory = join(scaffold.persistenceRoot, projects[0]!.name, id) + const predecessor = join(directory, 'session.v3.jsonl.zstd') + const createdAt = WEB_FIXTURE_TIME - 90_000 + const rows = [{ ...header, id, cwd: scaffold.workspaceCwd, createdAt }, + ...events.map((event, seq) => ({ ...event, seq, time: createdAt + seq + 1 }))] + const source = Buffer.concat(rows.map(row => zstdCompressSync(Buffer.from(`${JSON.stringify(row)}\n`)))) + await mkdir(directory, { recursive: true }) + await writeFile(predecessor, source) + await expect(scaffold.ctx.sessionPersistence.stat(id)).resolves.toMatchObject({ formatStatus: 'migration-required' }) + + const warningStart = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + await page.getByRole('button', { name: /^Show \d+ more sessions$/ }).click() + const row = page.locator(`[data-row-key="session:${id}"]`) + await row.waitFor() + acknowledgeReloadConnectionLoss(tripwire, warningStart) + const forkRequests: string[] = [] + const trackFork = (request: BrowserRequest): void => { + const path = new URL(request.url()).pathname + if (path === '/api/session/fork') forkRequests.push(path) + } + page.on('request', trackFork) + try { + await row.hover() + await row.locator('button[aria-label^="Session actions for "]').click() + await page.getByRole('menuitem', { name: 'Fork session', exact: true }).click() + const notice = page.getByRole('alert').filter({ hasText: 'Open the original session to complete migration before creating a branch.' }) + await notice.waitFor() + expect(await page.getByRole('menuitem', { name: 'Fork session', exact: true }).count()).toBe(0) + expect(forkRequests).toEqual(['/api/session/fork']) + expect(scaffold.ctx.agents.get(id)).toBeUndefined() + expect(await readdir(directory)).toEqual(['session.v3.jsonl.zstd']) + expect(await readFile(predecessor)).toEqual(source) + await compareOrRefreshGolden(UNOPENED_FORK_EXPECTED, + await captureStableAria(page, '[role="alert"]', scaffold.workspaceCwd), MODE) + await notice.getByRole('button', { name: 'Open original session', exact: true }).click() + await expect.poll(() => row.getAttribute('aria-selected')).toBe('true') + await expect.poll(() => scaffold.ctx.agents.get(id)).toBeDefined() + await expect(scaffold.ctx.sessionPersistence.stat(id)).resolves.toMatchObject({ formatStatus: 'current' }) + expect(await readdir(directory)).toContain(`session.v${SESSION_FORMAT_VERSION}.jsonl.zstd`) + expect(await readFile(predecessor)).toEqual(source) + expect(forkRequests).toEqual(['/api/session/fork']) + expect(scaffold.ctx.agents.list().filter(agent => agent.session.header.parentSession === id)).toEqual([]) + } finally { + page.off('request', trackFork) + } + }) + it.skipIf(MODE === 'record')('issued zero model calls and kept a closed inventory', async () => { expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) - await assertFixtureInventory(SNAPSHOT_DIR, ['compact.expected.md', 'fork.expected.md', 'ui.expected.md']) + await assertFixtureInventory(SNAPSHOT_DIR, ['compact.expected.md', 'fork.expected.md', 'fork-unopened.expected.md', 'ui.expected.md']) }) }) diff --git a/apps/web/tests/minimal-preset.snapshot.ts b/apps/web/tests/minimal-preset.snapshot.ts index 240ee39d28..16eebb7273 100644 --- a/apps/web/tests/minimal-preset.snapshot.ts +++ b/apps/web/tests/minimal-preset.snapshot.ts @@ -1,4 +1,4 @@ -import { mkdir } from 'node:fs/promises' +import { mkdir, readFile, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import type { Browser, Page } from 'playwright' @@ -6,6 +6,7 @@ import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import type { AgentHandle } from '@deepseek-ai/dsh-agent' import { ToolCallId, createUserMessage } from '@deepseek-ai/dsh-llm' +import type { GenerateOptions } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-agent-preset-registry' @@ -14,6 +15,7 @@ import { assertFixtureInventory, captureStableAria, compareOrRefreshGolden, + fixtureUserPrompts, launchWebScaffold, watchConsole, webSnapshotMode, @@ -76,7 +78,7 @@ describe('minimal agent preset', () => { if (failures.length > 1) throw new AggregateError(failures, 'minimal preset smoke teardown failed') }) - it('sends the exact RL prompt and shell schema, then executes the persistent shell', async () => { + it('sends the exact RL prompt with shell and image schemas, then executes the persistent shell', async () => { const requestHeader = agentHandle.agent.session.requestHeader() if (requestHeader === undefined) throw new Error('the minimal agent issued no model request') const systemPrompt = systemPromptText(agentHandle.agent.session) @@ -89,7 +91,8 @@ describe('minimal agent preset', () => { `Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: ${JSON.stringify(agentHandle.agent.session.header.cwd)}.`, ]) expect(scaffold.ctx.agentPresets.serviceFor(agentHandle.agent, 'fs')).toBeUndefined() - expect(scaffold.ctx.agentPresets.serviceFor(agentHandle.agent, 'compaction')).toBeUndefined() + expect(scaffold.ctx.agentPresets.serviceFor(agentHandle.agent, 'compaction')).toBeDefined() + expect(scaffold.ctx.commands.find(agentHandle.agent, 'compact')).toBeDefined() const stateDir = join(scaffold.workspaceCwd, 'persistent-state') await mkdir(stateDir) @@ -128,6 +131,7 @@ describe('minimal agent preset', () => { "prompt": "You are a helpful software engineer assistant.", "tools": [ "bash", + "read_image", "working_directory", ], } @@ -192,3 +196,199 @@ describe('minimal agent preset', () => { ]) }) }) + +describe('minimal manual compaction', () => { + const snapshotDir = fileURLToPath(new URL('../../../snapshots/web/minimal-compact', import.meta.url)) + let scaffold: WebScaffold + let handle: AgentHandle + let browser: Browser | undefined + let page: Page | undefined + const requests: GenerateOptions[] = [] + + beforeAll(async () => { + const fixture = join(snapshotDir, 'session.v4.jsonl') + const prompts = fixtureUserPrompts(await readFile(fixture, 'utf8')) + expect(prompts).toHaveLength(2) + const [initial, continuation] = prompts + if (initial === undefined || continuation === undefined) throw new Error('minimal compaction fixture requires two user prompts') + scaffold = await launchWebScaffold({ replayFixture: fixture, compareReplaySession: true, workspacePathLength: 192 }) + scaffold.ctx.on('llm/stream', async function* (options, next) { + requests.push(options) + yield* next() + }) + handle = await scaffold.ctx.agents.create({ + sessionId: SessionId('minimal-compact-smoke'), + meta: { cwd: scaffold.workspaceCwd, agentPreset: 'minimal' }, + agentOptions: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + setup: agentCtx => scaffold.ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined), + }) + handle.agent.followup(createUserMessage({ + content: [{ type: 'text', text: initial }], source: { kind: 'user' }, + })) + await handle.agent.whenIdle() + const session = handle.agent.session + expect(session.snapshotEvents().some(event => event.type === 'compaction/start')).toBe(false) + const generation = session.surface.replaceGeneration + const execution = await scaffold.ctx.commands.execute(handle.agent, '/compact', [], new AbortController().signal) + expect(execution?.result.kind).toBe('success') + expect(session.surface.replaceGeneration).toBe(generation + 1) + handle.agent.followup(createUserMessage({ + content: [{ type: 'text', text: continuation }], source: { kind: 'user' }, + })) + await handle.agent.whenIdle() + }) + + afterAll(async () => { + const failures: unknown[] = [] + await page?.close().catch((error: unknown) => failures.push(error)) + await browser?.close().catch((error: unknown) => failures.push(error)) + await handle?.dispose().catch((error: unknown) => failures.push(error)) + await scaffold?.close().catch((error: unknown) => failures.push(error)) + if (failures.length === 1) throw failures[0] + if (failures.length > 1) throw new AggregateError(failures, 'minimal compaction teardown failed') + }) + + it('records the manual command, summary, and durable history replacement', () => { + const session = handle.agent.session + const events = session.snapshotEvents() + const command = events.find(event => event.type === 'command/run') + const start = events.find(event => event.type === 'compaction/start') + const summary = events.find(event => event.type === 'compaction/summary') + const end = events.find(event => event.type === 'compaction/end') + const done = events.find(event => event.type === 'command/done') + expect(command?.data.name).toBe('compact') + expect(start?.data).toMatchObject({ turn: null, sourceCommandId: command?.data.commandId }) + expect(summary?.data).toMatchObject({ sourceCommandId: command?.data.commandId, llmStreamCall: true }) + expect(end?.data).toEqual(start?.data) + expect(done?.data).toMatchObject({ kind: 'success', sourceEventSeq: summary?.seq }) + const checkpoint = events.find(event => event.type === 'user/message' && event.data.source.kind === 'compact-checkpoint') + if (checkpoint?.type !== 'user/message') throw new Error('manual compaction produced no checkpoint') + expect(checkpoint.surfaceOp).toMatchObject({ + op: 'replace', startSeq: summary?.data.shadowedRange.start, endSeq: summary?.data.shadowedRange.end, + }) + expect(session.deriveMessages().some(message => message.id === checkpoint.data.id)).toBe(true) + const original = events.find(event => event.type === 'user/message' && event.data.source.kind === 'user') + if (original?.type !== 'user/message') throw new Error('minimal compaction has no original user message') + expect(session.deriveMessages().some(message => message.id === original.data.id)).toBe(false) + }) + + it('continues with the summary and the same minimal prompt and tools', () => { + expect(requests.map(request => request.purpose)).toEqual([undefined, 'compaction', undefined]) + const summary = handle.agent.session.snapshotEvents().find(event => event.type === 'compaction/summary') + if (summary === undefined) throw new Error('minimal compaction produced no summary') + const [initial, , continuation] = requests + if (initial === undefined || continuation === undefined) throw new Error('minimal compaction did not continue') + expect(continuation.messages.flatMap(message => message.content)).toEqual(expect.arrayContaining(summary.data.summary)) + expect(continuation.messages[0]).toEqual(initial.messages[0]) + expect(continuation.tools).toEqual(initial.tools) + expect(continuation.messages.flatMap(message => message.content) + .some(block => block.type === 'text' && block.text === 'MINIMAL_COMPACT_READY')).toBe(true) + expect(handle.agent.session.deriveMessages().at(-1)?.content) + .toEqual([{ type: 'text', text: 'MINIMAL_COMPACT_OK' }]) + }) + + it.skipIf(MODE === 'record')('renders the manual compaction card and its summary', async () => { + onTestFailed(() => { if (page !== undefined) void saveFailureShot(page, 'web-minimal-compact') }) + browser = await chromium.launch() + page = await newEnglishPage(browser) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await page.locator('[role="treeitem"]').first().click() + await page.locator('[role="treeitem"]').nth(1).click() + await page.getByText('MINIMAL_COMPACT_OK', { exact: true }).waitFor() + const card = page.getByRole('button', { name: /^compact Compacted / }) + await card.click() + await expect.poll(() => card.getAttribute('aria-expanded')).toBe('true') + await compareOrRefreshGolden(join(snapshotDir, 'ui.expected.md'), + await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) + + it('keeps its snapshot inventory closed', async () => { + await assertFixtureInventory(snapshotDir, [ + 'session.v4.jsonl', 'system-prompt.expected.md', 'tool-schemas.expected.json', 'ui.expected.md', + ]) + }) +}) + +describe('minimal image reading', () => { + const snapshotDir = fileURLToPath(new URL('../../../snapshots/web/minimal-read-image', import.meta.url)) + const prompt = 'Use read_image to inspect red.png. Then reply exactly MINIMAL_IMAGE_OK and stop.' + let scaffold: WebScaffold + let handle: AgentHandle + let browser: Browser | undefined + let page: Page | undefined + + beforeAll(async () => { + scaffold = await launchWebScaffold({ + replayFixture: join(snapshotDir, 'session.v4.jsonl'), compareReplaySession: true, paceMs: 10, + }) + await writeFile(join(scaffold.workspaceCwd, 'red.png'), Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC', 'base64', + )) + handle = await scaffold.ctx.agents.create({ + sessionId: SessionId('minimal-image-smoke'), + meta: { cwd: scaffold.workspaceCwd, agentPreset: 'minimal' }, + agentOptions: { provider: 'deepseek-official', model: 'deepseek-v4-flash-vision-exp' }, + setup: agentCtx => scaffold.ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined), + }) + handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: prompt }], source: { kind: 'user' } })) + await handle.agent.whenIdle() + }) + + afterAll(async () => { + const failures: unknown[] = [] + await page?.close().catch((error: unknown) => failures.push(error)) + await browser?.close().catch((error: unknown) => failures.push(error)) + await handle?.dispose().catch((error: unknown) => failures.push(error)) + await scaffold?.close().catch((error: unknown) => failures.push(error)) + if (failures.length === 1) throw failures[0] + if (failures.length > 1) throw new AggregateError(failures, 'minimal image teardown failed') + }) + + it('logs a durable image with the minimal tool roster', async () => { + const session = handle.agent.session + expect(session.requestHeader()?.tools?.map(tool => tool.name)).toEqual(['bash', 'read_image', 'working_directory']) + const result = session.snapshotEvents().find(event => event.type === 'tool/result') + expect(result?.data.message.isError).toBe(false) + expect(result?.data.meta).toEqual({ path: join(scaffold.workspaceCwd, 'red.png') }) + const image = session.deriveMessages().flatMap(message => message.content).find(block => block.type === 'image') + if (image?.type !== 'image') throw new Error('minimal read_image produced no durable image') + expect(image.attachment).toMatchObject({ mediaType: 'image/png', width: 1, height: 1, bytes: 69 }) + expect((await scaffold.ctx.attachments.readImage(image.attachment)).data.byteLength).toBe(69) + }) + + it.skipIf(MODE === 'record')('renders the existing image tool card and preview', async () => { + onTestFailed(() => { if (page !== undefined) void saveFailureShot(page, 'web-minimal-read-image') }) + browser = await chromium.launch() + page = await newEnglishPage(browser) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await page.locator('[role="treeitem"]').first().click() + await page.locator('[role="treeitem"]').nth(1).click() + await page.getByText('MINIMAL_IMAGE_OK', { exact: true }).waitFor() + await page.locator('[data-turn-process]').click() + const group = page.locator('[data-chat-group-key]').first() + await group.locator('[data-process-activity]').click() + const card = group.locator('[data-tool="read_image"]').first() + const row = card.locator('[data-disclosure-row]') + await row.click() + await expect.poll(() => row.getAttribute('aria-expanded')).toBe('true') + const preview = card.locator('img').first() + await preview.waitFor() + await expect.poll(() => preview.evaluate(img => img instanceof HTMLImageElement && img.naturalWidth)).toBe(1) + await compareOrRefreshGolden(join(snapshotDir, 'ui.expected.md'), + await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) + + it('keeps its snapshot inventory closed', async () => { + await assertFixtureInventory(snapshotDir, [ + 'session.v4.jsonl', 'system-prompt.expected.md', 'tool-schemas.expected.json', 'ui.expected.md', + ]) + }) +}) diff --git a/apps/web/tests/models-settings.e2e.ts b/apps/web/tests/models-settings.e2e.ts index 9cb6c5bbc2..d199b3b378 100644 --- a/apps/web/tests/models-settings.e2e.ts +++ b/apps/web/tests/models-settings.e2e.ts @@ -20,7 +20,7 @@ import { fileURLToPath } from 'node:url' import { join } from 'node:path' import type { Browser, Page, Request, Route } from 'playwright' import { chromium } from 'playwright' -import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { afterAll, beforeAll, describe, expect, it, onTestFailed, vi } from 'vitest' import { assertFixtureInventory, captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold, @@ -29,6 +29,7 @@ import { openSettings, ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/models-settings', import.meta.url)) const EMPTY_EXPECTED = join(SNAPSHOT_DIR, 'empty.expected.md') +const NATIVE_KEYLESS_EXPECTED = join(SNAPSHOT_DIR, 'native-keyless.expected.md') const CONFIGURED_EXPECTED = join(SNAPSHOT_DIR, 'configured.expected.md') const DECLARED_EXPECTED = join(SNAPSHOT_DIR, 'declared.expected.md') const DECLARED_EDIT_EXPECTED = join(SNAPSHOT_DIR, 'declared-edit.expected.md') @@ -44,6 +45,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => { let tripwire: ReturnType beforeAll(async () => { + vi.stubEnv('OPENAI_API_KEY', 'models-settings-test-key') scaffold = await launchWebScaffold({}) browser = await chromium.launch() // The scenario asserts the shipped Chinese copy, so the browser asks for it. @@ -80,6 +82,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => { }, 120_000) afterAll(async () => { + vi.unstubAllEnvs() await browser?.close() await scaffold?.close() }) @@ -120,6 +123,12 @@ describe('web e2e: Models settings page configures a dormant provider', () => { const options = await pick.locator('option').allTextContents() expect(options).toContain('anthropic') expect(options).toContain('minimax-cn') + await pick.selectOption('openai-codex') + await expect.poll(async () => dialog.getByRole('textbox', { name: 'API 密钥', exact: true }).count(), { timeout: 10_000 }).toBe(0) + expect(await dialog.getByRole('button', { name: '认证说明', exact: true }).count()).toBe(0) + expect(await dialog.textContent()).not.toMatch(/oauth/i) + const nativeSnapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) + await compareOrRefreshGolden(NATIVE_KEYLESS_EXPECTED, nativeSnapshot, MODE) await pick.selectOption('minimax-cn') await dialog.getByRole('textbox', { name: 'API 密钥', exact: true }).waitFor({ timeout: 10_000 }) const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) @@ -206,6 +215,8 @@ describe('web e2e: Models settings page configures a dormant provider', () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-models-customized')) const dialog = page.getByRole('dialog', { name: '设置' }) await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click() + await dialog.getByText('API 密钥来源:已保存凭据', { exact: true }).waitFor({ timeout: 10_000 }) + expect(await dialog.textContent()).not.toMatch(/oauth/i) await dialog.getByText('自定义设置').click() const url = dialog.getByLabel('API 地址') await url.waitFor({ timeout: 10_000 }) @@ -535,7 +546,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => { await assertFixtureInventory(SNAPSHOT_DIR, [ 'configured.expected.md', 'declared-edit.expected.md', 'declared.expected.md', 'delete.expected.md', 'empty.expected.md', 'model-picker.expected.md', - 'native-delete.expected.md', 'catalog-inputs.expected.md', + 'native-delete.expected.md', 'native-keyless.expected.md', 'catalog-inputs.expected.md', 'refreshing.expected.md', 'image-only.expected.md', ]) }) 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/official-subagent-bundle.e2e.ts b/apps/web/tests/official-subagent-bundle.e2e.ts index aab040691a..8a21671b29 100644 --- a/apps/web/tests/official-subagent-bundle.e2e.ts +++ b/apps/web/tests/official-subagent-bundle.e2e.ts @@ -100,10 +100,10 @@ describe.skipIf(MODE === 'record')('web snapshot: Official native subagent bundl }) expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === BUNDLE)) .toMatchObject({ official: true, availability: 'profile', enabled: false }) - expect((await scaffold.ctx.agentPresets.compositionInventory()).find(preset => preset.id === 'ptc')?.rows - .some(row => row.entryId === 'tool-subagent-claude-code')).toBe(false) + expect(scaffold.ctx.tools.schemas().some(tool => tool.name === 'subagent_claude_code')).toBe(false) expect(await scaffold.ctx.pluginManager.setBundleEnabled(BUNDLE, true)) .toMatchObject({ application: 'applied', changed: true }) + expect(scaffold.ctx.tools.schemas().some(tool => tool.name === 'subagent_claude_code')).toBe(true) browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index ff5f239a8c..50f6ecd61a 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -9,6 +9,7 @@ import { fileURLToPath } from 'node:url' import { join } from 'node:path' import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' +import { credentialRef } from '@deepseek-ai/dsh-credentials' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, @@ -20,6 +21,7 @@ import { openSettings, ZH_BROWSER_LOCALE, connectFreshWorkspaceZh, saveFailureSh const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/onboarding-deepseek-config', import.meta.url)) const WELCOME_EXPECTED = join(SNAPSHOT_DIR, 'welcome.expected.md') +const SIGN_IN_EXPECTED = join(SNAPSHOT_DIR, 'sign-in.expected.md') const MISSING_EXPECTED = join(SNAPSHOT_DIR, 'missing.expected.md') const MODELS_EXPECTED = join(SNAPSHOT_DIR, 'models.expected.md') const DEFAULT_MODELS_EXPECTED = join(SNAPSHOT_DIR, 'default-models.expected.md') @@ -72,10 +74,13 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await welcome.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel }).click() await welcome.waitFor({ state: 'detached', timeout: 15_000 }) + const signIn = page.getByRole('dialog', { name: '开始使用', exact: true }) + await signIn.waitFor({ timeout: 15_000 }) + await compareOrRefreshGolden(SIGN_IN_EXPECTED, + await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), MODE) + await signIn.getByRole('button', { name: '添加 API Key', exact: true }).click() const credentialStep = page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }) await credentialStep.waitFor({ timeout: 15_000 }) - expect(await page.getByRole('dialog', { name: '开始你的创作' }).count()).toBe(0) - expect(await page.getByRole('button', { name: '账号菜单', exact: true }).count()).toBe(0) const keyInput = credentialStep.getByLabel('API 密钥', { exact: true }) await keyInput.waitFor({ timeout: 10_000 }) const initial = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) @@ -110,7 +115,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect.poll( () => configuredInput.getAttribute('placeholder'), { timeout: 10_000 }, - ).toBe('已配置——输入新值可替换') + ).toBe('留空时保留现有认证(DEEPSEEK_API_KEY)') const secondReloadWarnings = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) @@ -158,7 +163,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup setInterval(() => { if (document.querySelector( '[role="dialog"][aria-label="预览版说明"], ' - + '[role="dialog"][aria-label="开始你的创作"], ' + + '[role="dialog"][aria-label="开始使用"], ' + '[role="dialog"][aria-label="添加一个 API Key 开始使用"]', ) !== null) { sightings.push('chrome') @@ -208,7 +213,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await deepSeek.locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click() await settings.getByText('自定义设置').click() expect(await settings.getByLabel('模型 ID 1').inputValue()).toBe('deepseek-flash') - expect(await settings.getByLabel('显示名称 1').inputValue()).toBe('DeepSeek-V41-Flash') + expect(await settings.getByLabel('显示名称 1').inputValue()).toBe('DeepSeek-V4.1-Flash') expect(await settings.getByLabel('模型 ID 2').inputValue()).toBe('deepseek-v4-pro') expect(await settings.getByRole('button', { name: /删除模型/ }).count()).toBe(2) await settings.getByRole('button', { name: '模型选项 1' }).click() @@ -251,7 +256,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect.poll( () => settings.getByLabel('API 密钥', { exact: true }).getAttribute('placeholder'), { timeout: 10_000 }, - ).toBe('已配置——输入新值可替换') + ).toBe('留空时保留现有认证(DEEPSEEK_API_KEY)') const modelEditor = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(MODELS_EXPECTED, modelEditor, MODE) await settings.getByRole('button', { name: '保存', exact: true }).click() @@ -278,20 +283,37 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup // trigger — on the page; the scaffold boots without one. await connectFreshWorkspaceZh(page, scaffold.workspaceCwd, 'model-fallback-e2e', false) - const modelTrigger = page.getByRole('button', { name: /^选择模型.*deepseek-official\// }) + const modelTrigger = page.getByRole('button', { name: '请选择模型', exact: true }) await modelTrigger.waitFor({ timeout: 10_000 }) await modelTrigger.click() - await page.getByRole('menuitem', { name: /模型/ }).click() expect(await page.getByText('Configured Flash', { exact: true }).count()).toBe(0) await page.getByRole('menuitemradio', { name: 'Private Preview' }).waitFor({ timeout: 10_000 }) expect(tripwire.warnings).toEqual([]) expect(tripwire.pageErrors).toEqual([]) }, 60_000) + it('shows an empty model list after removing the API key without replacing the saved default', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-model-catalog-empty')) + await page.keyboard.press('Escape') + const selection = scaffold.ctx.agentDefaultModel.currentSelection() + await scaffold.ctx.credentials.unset(credentialRef('DEEPSEEK_API_KEY')) + const seat = page.getByRole('button', { name: '请选择模型', exact: true }) + await seat.waitFor() + await seat.click() + const picker = page.getByRole('group', { name: '模型与推理等级' }) + await picker.getByText('暂无可用模型', { exact: true }).waitFor() + expect(await picker.getByRole('menuitemradio').count()).toBe(0) + expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual(selection) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'empty.expected.md'), await picker.ariaSnapshot(), MODE) + await seat.press('Escape') + await picker.waitFor({ state: 'hidden' }) + expect(tripwire.pageErrors).toEqual([]) + }) + it('keeps the fixture inventory closed', async () => { await assertFixtureInventory( SNAPSHOT_DIR, - ['welcome.expected.md', 'missing.expected.md', 'models.expected.md', 'default-models.expected.md'], + ['welcome.expected.md', 'sign-in.expected.md', 'missing.expected.md', 'models.expected.md', 'default-models.expected.md', 'empty.expected.md'], ) }) }) diff --git a/apps/web/tests/onboarding-native.e2e.ts b/apps/web/tests/onboarding-native.e2e.ts index 57f96bb8f0..75c50b8f27 100644 --- a/apps/web/tests/onboarding-native.e2e.ts +++ b/apps/web/tests/onboarding-native.e2e.ts @@ -58,40 +58,34 @@ describe.skipIf(MODE === 'record').each([false, true])('web e2e: native credenti acknowledgeReloadConnectionLoss(tripwire, warningsBefore) } const accountMenu = page.getByRole('button', { name: '账号菜单', exact: true }) - if (desktop) { - await accountMenu.waitFor() - expect(await accountMenu.textContent()).toBe('更多') - const triggerBox = (await accountMenu.boundingBox())! - expect(Math.abs(triggerBox.height - 32)).toBeLessThan(1) - await accountMenu.click() - const menu = page.getByRole('menu') - await menu.waitFor() - expect(await menu.getByRole('menuitem').count()).toBe(3) - // Shortcut hints vary by host platform; accessible names identify the three actions. - for (const name of ['设置', '意见反馈', '登录']) { - expect(await menu.getByRole('menuitem', { name, exact: true }).count()).toBe(1) - } - const menuBox = (await menu.boundingBox())! - expect(Math.abs(menuBox.width - 124)).toBeLessThan(1) - expect(Math.abs(menuBox.height - 128)).toBeLessThan(1) - expect(Math.abs(triggerBox.y - (menuBox.y + menuBox.height) - 4)).toBeLessThan(1) - for (const row of await menu.getByRole('menuitem').all()) { - const rowBox = (await row.boundingBox())! - expect(Math.abs(rowBox.height - 40)).toBeLessThan(1) - expect(Math.abs(menuBox.width - rowBox.width - 8)).toBeLessThan(1) - const glyph = (await row.locator('svg').first().boundingBox())! - expect(Math.abs(glyph.width - 16)).toBeLessThan(1) - expect(Math.abs(glyph.height - 16)).toBeLessThan(1) - } - const menuAria = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) - await compareOrRefreshGolden(SIGNED_OUT_MENU_EXPECTED, menuAria, MODE) - await page.keyboard.press('Escape') - await menu.waitFor({ state: 'detached' }) - } else { - await page.getByRole('button', { name: '设置', exact: true }).waitFor() - expect(await accountMenu.count()).toBe(0) - expect(await page.getByRole('dialog', { name: '开始你的创作' }).count()).toBe(0) + await accountMenu.waitFor() + expect(await accountMenu.textContent()).toBe('更多') + const triggerBox = (await accountMenu.boundingBox())! + expect(Math.abs(triggerBox.height - 32)).toBeLessThan(1) + await accountMenu.click() + const menu = page.getByRole('menu') + await menu.waitFor() + expect(await menu.getByRole('menuitem').count()).toBe(3) + for (const name of ['设置', '意见反馈', '登录']) { + expect(await menu.getByRole('menuitem', { name, exact: true }).count()).toBe(1) } + const menuBox = (await menu.boundingBox())! + expect(Math.abs(menuBox.width - 124)).toBeLessThan(1) + expect(Math.abs(menuBox.height - 128)).toBeLessThan(1) + expect(Math.abs(triggerBox.y - (menuBox.y + menuBox.height) - 4)).toBeLessThan(1) + for (const row of await menu.getByRole('menuitem').all()) { + const rowBox = (await row.boundingBox())! + expect(Math.abs(rowBox.height - 40)).toBeLessThan(1) + expect(Math.abs(menuBox.width - rowBox.width - 8)).toBeLessThan(1) + const glyph = (await row.locator('svg').first().boundingBox())! + expect(Math.abs(glyph.width - 16)).toBeLessThan(1) + expect(Math.abs(glyph.height - 16)).toBeLessThan(1) + } + const menuAria = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + await compareOrRefreshGolden(SIGNED_OUT_MENU_EXPECTED, menuAria, MODE) + await page.keyboard.press('Escape') + await menu.waitFor({ state: 'detached' }) + expect(await page.getByRole('dialog', { name: '开始使用', exact: true }).count()).toBe(0) await openSettings(page, 'zh') const settings = page.getByRole('dialog', { name: '设置', exact: true }) await settings.getByRole('button', { name: '模型', exact: true }).click() diff --git a/apps/web/tests/onboarding-usable-provider.e2e.ts b/apps/web/tests/onboarding-usable-provider.e2e.ts index ebddfb8e34..4c21dbd9bf 100644 --- a/apps/web/tests/onboarding-usable-provider.e2e.ts +++ b/apps/web/tests/onboarding-usable-provider.e2e.ts @@ -44,10 +44,11 @@ describe.skipIf(MODE === 'record')('web e2e: another usable provider ends first- it('closes the setup card without discarding the add card beside it', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-onboarding-setup-card-cancel')) + const signIn = page.getByRole('dialog', { name: '开始使用', exact: true }) + await signIn.waitFor({ timeout: 15_000 }) + await signIn.getByRole('button', { name: '添加 API Key', exact: true }).click() const credentialStep = page.getByRole('dialog', { name: CREDENTIAL_STEP }) await credentialStep.waitFor({ timeout: 15_000 }) - expect(await page.getByRole('dialog', { name: '开始你的创作' }).count()).toBe(0) - expect(await page.getByRole('button', { name: '账号菜单', exact: true }).count()).toBe(0) await credentialStep.getByRole('button', { name: '稍后配置' }).click() await credentialStep.waitFor({ state: 'detached', timeout: 15_000 }) diff --git a/apps/web/tests/plan-review.e2e.ts b/apps/web/tests/plan-review.e2e.ts index ea2a30d938..fd8217a2d8 100644 --- a/apps/web/tests/plan-review.e2e.ts +++ b/apps/web/tests/plan-review.e2e.ts @@ -7,12 +7,14 @@ // Replay is deterministic: the plan content arrives from replayed chunks, the // review wait is real, and the approve click is the test's own gesture (the // turn cannot complete without it, in record and replay alike). -import { readFile } from 'node:fs/promises' +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' import { fileURLToPath } from 'node:url' import { join } from 'node:path' import type { Browser, ConsoleMessage, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { deriveReplayScript, parseSessionLog } from '@deepseek-ai/dsh-llm-replay' import type { SessionEvent } from '@deepseek-ai/dsh-session' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { @@ -390,8 +392,12 @@ describe.skipIf(MODE === 'record')('web e2e: pending plan review across Sidebar describe('web e2e: dismissed plan history', () => { it.skipIf(MODE === 'record')('reopens the permanent plan card after dismissing its review', async () => { - // Replay supplies a finite continuation; the real question rejection and retained document are the assertions. - const scaffold = await launchWebScaffold({ replayFixture: FIXTURE, compareReplaySession: false, paceMs: 15 }) + // A dismissed review concludes the turn, so only the call presenting the plan replays. + const replayRoot = await mkdtemp(join(tmpdir(), 'dsh-plan-review-dismiss-replay-')) + const replayOverride = join(replayRoot, 'replay.override.json') + const script = deriveReplayScript(parseSessionLog(await readFile(FIXTURE, 'utf8'))) + await writeFile(replayOverride, JSON.stringify(script.slice(0, 1))) + const scaffold = await launchWebScaffold({ replayFixture: FIXTURE, replayOverride, compareReplaySession: false, paceMs: 15 }) let browser: Browser | undefined const events: SessionEvent[] = [] scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { events.push(event) }) @@ -417,9 +423,10 @@ describe('web e2e: dismissed plan history', () => { expect(call).toBeDefined() const results = events.filter(event => event.type === 'tool/result') const result = results.find(event => event.data.message.source.callId === call?.data.callId) - expect(result?.data.message).toMatchObject({ role: 'tool', toolCallId: call?.data.callId, isError: true }) + expect(result?.data.message).toMatchObject({ role: 'tool', toolCallId: call?.data.callId, isError: false }) expect(JSON.stringify(result)).toContain('dismissed the plan review') expect(results.some(event => JSON.stringify(event).includes('Plan approved'))).toBe(false) + expect(events.filter(event => event.type === 'assistant/message')).toHaveLength(1) const modes = events.filter(event => event.type === 'plan/mode') expect(modes).toHaveLength(1) expect(modes[0]).toMatchObject({ data: { active: true } }) @@ -443,6 +450,7 @@ describe('web e2e: dismissed plan history', () => { } finally { await browser?.close() await scaffold.close() + await rm(replayRoot, { recursive: true, force: true }) } }) }) diff --git a/apps/web/tests/plugin-config.e2e.ts b/apps/web/tests/plugin-config.e2e.ts index 3afec1b745..21eddc0fee 100644 --- a/apps/web/tests/plugin-config.e2e.ts +++ b/apps/web/tests/plugin-config.e2e.ts @@ -68,7 +68,7 @@ describe('web e2e: plugin configuration pages', () => { while (await panel.getByRole('button', { name: /^返回/ }).count() > 0) { await panel.getByRole('button', { name: /^返回/ }).first().click() } - await panel.getByRole('heading', { name: '官方', exact: true }).waitFor({ timeout: 20_000 }) + await panel.getByRole('heading', { name: '内置插件配置', exact: true }).waitFor({ timeout: 20_000 }) return panel } @@ -83,24 +83,52 @@ describe('web e2e: plugin configuration pages', () => { return readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8').catch(() => '') } - it('lists one official page per exposed host-plane namespace after the official bundles', async () => { + it('keeps configuration pages first and opens the full experimental plugin list separately', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-plugin-config-cards')) const panel = await openPlugins() // Every page the shipped web composition exposes: the shell executor, the - // agent loop, subagent selection, and the DeepSeek search provider, after - // the shipped optional bundles and offline on-demand catalog. + // agent loop, subagent selection, and the DeepSeek search provider. await panel.getByRole('button', { name: '查看 网页搜索', exact: true }).waitFor({ timeout: 20_000 }) - const official = panel.locator('[data-plugin-group="official"]') - expect(await official.locator('[data-plugin-package]').count()).toBe(OPTIONAL_BUNDLES.length + ON_DEMAND_BUNDLES.length) - expect(await official.locator('[data-plugin-item]').count()).toBe(4) - for (const title of ['终端', 'Agent 循环', '子智能体', '网页搜索']) { - expect(await official.getByRole('button', { name: `查看 ${title}`, exact: true }).count()).toBe(1) + const basic = panel.locator('[data-plugin-group="basic"]') + expect(await basic.locator('[data-plugin-item]').count()).toBe(4) + expect(await basic.locator(':scope > ul > li').evaluateAll(cards => cards.map(card => card.getAttribute('data-plugin-item')))) + .toEqual(['subagent', 'web-search', 'agent-loop', 'shell']) + for (const title of ['子智能体', '网页搜索', 'Agent 循环', '终端']) { + expect(await basic.getByRole('button', { name: `查看 ${title}`, exact: true }).count()).toBe(1) } // A card carries the one-liner; the fields wait for the page. - expect(await official.getByText('限制每条命令最多能跑多久、最多输出多少内容。', { exact: true }).count()).toBe(1) + expect(await basic.getByText('限制每条命令最多能跑多久、最多输出多少内容。', { exact: true }).count()).toBe(1) expect(await panel.getByLabel('命令超时(毫秒)').count()).toBe(0) + const extensions = panel.locator('[data-plugin-group="extensions"]') + const more = panel.getByRole('button', { name: '更多', exact: true }) + expect(await extensions.getByRole('heading', { name: '实验性插件', exact: true }).count()).toBe(1) + expect(await extensions.getByRole('button', { name: '更多', exact: true }).textContent()).toBe('更多') + expect(await extensions.getByRole('list').isVisible()).toBe(true) + expect(await panel.locator('[data-plugin-group="more"]').count()).toBe(0) + await more.focus() + await page.keyboard.press('Enter') + await panel.getByRole('heading', { name: '实验性插件', exact: true, level: 1 }).waitFor() + expect(await panel.locator('[data-plugin-group="more"] [data-plugin-package]').count()) + .toBe(OPTIONAL_BUNDLES.length + ON_DEMAND_BUNDLES.length) + expect(await basic.count()).toBe(0) + expect(await extensions.count()).toBe(0) + expect(await panel.locator('[data-plugin-group="bundles"]').count()).toBe(0) + await panel.getByRole('button', { name: '查看 Git 工作树', exact: true }).click() + await panel.locator('[data-plugin-detail]').waitFor() + await panel.getByRole('button', { name: '返回 实验性插件', exact: true }).click() + await panel.getByRole('heading', { name: '实验性插件', exact: true, level: 1 }).waitFor() + await panel.getByRole('button', { name: '返回插件', exact: true }).focus() + await page.keyboard.press('Space') + expect(await extensions.getByRole('list').isVisible()).toBe(true) + expect(await panel.locator('[data-plugin-group="more"]').count()).toBe(0) + await more.click() + await page.reload({ waitUntil: 'load' }) + await openPlugins() + expect(await extensions.getByRole('list').isVisible()).toBe(true) + expect(await panel.locator('[data-plugin-group="more"]').count()).toBe(0) + const snapshot = await captureStableAria(page, '[data-plugin-panel]', scaffold.workspaceCwd) await compareOrRefreshGolden(OFFICIAL_EXPECTED, snapshot, MODE) expect(tripwire.pageErrors).toEqual([]) @@ -136,7 +164,7 @@ describe('web e2e: plugin configuration pages', () => { await openPage(panel, '子智能体') expect(await depth.inputValue()).toBe('1') expect(await capacity.inputValue()).toBe('8') - await panel.getByRole('button', { name: '返回插件列表', exact: true }).click() + await panel.getByRole('button', { name: '返回插件', exact: true }).click() }) it('opens field explanations with the keyboard and retains unsaved edits', async () => { @@ -160,7 +188,7 @@ describe('web e2e: plugin configuration pages', () => { await panel.getByRole('button', { name: '子智能体并行数量上限说明', exact: true }).click() const capacityRules = panel.getByRole('region', { name: '子智能体并行数量上限说明', exact: true }) expect(await capacityRules.getByText('同一主 Agent 下,所有递归层级同时存活的子智能体总数,主 Agent 不计入。达到上限时,新的启动请求会被拒绝。', { exact: true }).count()).toBe(1) - await panel.getByRole('button', { name: '返回插件列表', exact: true }).click() + await panel.getByRole('button', { name: '返回插件', exact: true }).click() await openPage(panel, '子智能体') expect(await depth.inputValue()).toBe('1') }) @@ -241,8 +269,8 @@ describe('web e2e: plugin configuration pages', () => { await timeout.waitFor({ timeout: 10_000 }) await timeout.fill('7000') - await panel.getByRole('button', { name: '返回插件列表' }).click() - await panel.getByRole('heading', { name: '官方', exact: true }).waitFor({ timeout: 10_000 }) + await panel.getByRole('button', { name: '返回插件' }).click() + await panel.getByRole('heading', { name: '内置插件配置', exact: true }).waitFor({ timeout: 10_000 }) await openPage(panel, '终端') await expect.poll(() => panel.getByLabel('命令超时(毫秒)').inputValue(), { timeout: 5_000 }).toBe('12000') @@ -342,7 +370,7 @@ describe('web e2e: plugin configuration pages', () => { await bundlePage.waitFor({ timeout: 10_000 }) // An official plugin's page is another subject; the fixture's entries render nothing for it. - await panel.getByRole('button', { name: '返回插件列表' }).click() + await panel.getByRole('button', { name: '返回插件' }).click() await openPage(panel, '终端') const itemPage = panel.locator('[data-plugin-item-detail]') expect(await itemPage.locator('[data-live-action], [data-live-badge], [data-live-section]').count()).toBe(0) diff --git a/apps/web/tests/plugin-hmr-lifecycle.e2e.ts b/apps/web/tests/plugin-hmr-lifecycle.e2e.ts new file mode 100644 index 0000000000..966e60548b --- /dev/null +++ b/apps/web/tests/plugin-hmr-lifecycle.e2e.ts @@ -0,0 +1,250 @@ +// Web e2e scenario: the plugin lifecycle a user drives through the plugin manager, with real pnpm on local fixture +// packages and the live profile's HMR. The page installs, enables, disables, uninstalls, and reinstalls; upgrades go +// through the manager methods behind the agent's plugin_manager tool, removing and then installing. Every step checks which +// plugin version runs through the trace its apply and disposal append, and that a change HMR cannot apply asks for a +// restart or names its error. +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { chromium, type Browser, type Locator, type Page } from 'playwright' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import type { ChangeResult } from '@deepseek-ai/dsh-plugin-manager' +import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' +import { ZH_BROWSER_LOCALE } from './support.ts' + +const NAME = 'e2e-hmr-addon' + +/** Real pnpm with its store, cache, and metadata under a test directory and no registry access. */ +function isolatedPnpm(scratch: string) { + return { + command: 'pnpm', args: [], + // pnpm 11 reads settings from pnpm_config_* variables. + env: { pnpm_config_store_dir: join(scratch, 'pnpm-store'), pnpm_config_cache_dir: join(scratch, 'pnpm-cache'), pnpm_config_offline: 'true' }, + } +} + +/** The page's toast or inline alert whose text contains the given words. */ +function alertWith(page: Page, text: string): Locator { + return page.getByRole('alert').filter({ hasText: text }) +} + +describe('web e2e: plugin lifecycle with HMR', () => { + let scratch: string + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + let tracePath: string + + /** Write one version of the fixture bundle, whose only row is its own plugin, into a directory of its own. */ + async function version(label: string, body = ''): Promise { + const dir = join(scratch, 'sources', label) + await mkdir(dir, { recursive: true }) + await writeFile(join(dir, 'package.json'), JSON.stringify({ + name: NAME, version: `${label.replace(/\D/gu, '') || '0'}.0.0`, type: 'module', main: './index.mjs', + dsh: { bundle: { patch: './cordis.patch.yml' } }, + })) + await writeFile(join(dir, 'cordis.patch.yml'), `- insert:\n - id: ${NAME}\n name: ${NAME}\n`) + await writeFile(join(dir, 'index.mjs'), `${body} +import { appendFileSync } from 'node:fs' +export const name = '${NAME}' +export function apply(ctx) { + appendFileSync(${JSON.stringify(tracePath)}, 'start:${label}\\n') + ctx.effect(() => () => { appendFileSync(${JSON.stringify(tracePath)}, 'stop:${label}\\n') }) +} +`) + return dir + } + + /** The trace lines since the last call, after the given ones have arrived. */ + async function traced(expected: string[]): Promise { + await expect.poll(async () => (await readFile(tracePath, 'utf8')).split('\n').filter(Boolean), { timeout: 10_000 }).toEqual(expected) + await writeFile(tracePath, '') + } + + /** The running profile's manager, whose methods the agent's plugin_manager tool calls. */ + function manager() { + return scaffold.ctx.get('pluginManager')! + } + + /** Upgrade as the agent's tool does: an installed package is removed before another version is installed. */ + async function reinstall(spec: string): Promise { + const removed = await manager().removeBundle(NAME) + expect(removed.application, JSON.stringify(removed)).not.toBe('failed') + return manager().installBundle(spec) + } + + async function openPanel(): Promise { + if (await page.getByRole('dialog', { name: '设置' }).count() > 0) await page.keyboard.press('Escape') + const panel = page.locator('[data-plugin-panel]') + const list = panel.getByRole('heading', { name: '插件', exact: true }) + // The sidebar entry toggles the page, so it is pressed only while the page is closed. + if (await panel.count() === 0) { + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() + } else if (!await list.isVisible()) { + await panel.getByRole('button', { name: '返回插件', exact: true }).click() + } + await list.waitFor({ timeout: 10_000 }) + return panel + } + + /** Install a spec through the page's dialog and switch the bundle on from its finished screen. */ + async function installThroughPage(spec: string): Promise { + const panel = await openPanel() + await panel.getByRole('button', { name: '添加插件', exact: true }).click() + const dialog = page.getByRole('dialog') + await dialog.getByRole('textbox', { name: '包名或地址' }).fill(spec) + await dialog.getByRole('button', { name: '安装', exact: true }).click() + await dialog.getByRole('button', { name: '立即启用', exact: true }).click({ timeout: 30_000 }) + await dialog.waitFor({ state: 'detached', timeout: 10_000 }) + return panel + } + + async function uninstallThroughPage(panel: Locator): Promise { + await panel.getByRole('button', { name: `查看 ${NAME}`, exact: true }).click() + await panel.getByRole('button', { name: `卸载 ${NAME}`, exact: true }).click() + await page.getByRole('dialog', { name: `卸载「${NAME}」?` }).getByRole('button', { name: '卸载', exact: true }).click() + // The page leaves the removed package's details for the list. + await panel.getByRole('heading', { name: '插件', exact: true }).waitFor({ timeout: 30_000 }) + await expect.poll(() => panel.locator(`[data-plugin-package="${NAME}"]`).count(), { timeout: 30_000 }).toBe(0) + } + + async function dependency(): Promise { + const manifest = JSON.parse(await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'package.json'), 'utf8')) as { + dependencies?: Record + } + return manifest.dependencies?.[NAME] + } + + beforeAll(async () => { + scratch = await mkdtemp(join(tmpdir(), 'dsh-plugin-hmr-')) + tracePath = join(scratch, 'trace.log') + await writeFile(tracePath, '') + scaffold = await launchWebScaffold({ profile: { packages: [], packageManager: isolatedPnpm(scratch) } }) + browser = await chromium.launch() + page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, locale: ZH_BROWSER_LOCALE }) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl) + await page.waitForSelector('[class*="frame"]') + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + await rm(scratch, { recursive: true, force: true }) + }) + + it('installs, switches off and on, and upgrades without a restart', async () => { + const v1 = await version('v1') + const panel = await installThroughPage(`file:${v1}`) + await traced(['start:v1']) + const toggle = panel.getByRole('switch', { name: `启用 ${NAME}`, exact: true }) + await toggle.click() + await traced(['stop:v1']) + await toggle.click() + await traced(['start:v1']) + // Installing over the installed package is refused; the upgrade removes it first. + const v2 = await version('v2') + expect(await manager().installBundle(`file:${v2}`)).toMatchObject({ application: 'failed', error: { code: 'already-installed' } }) + const upgraded = await reinstall(`file:${v2}`) + expect(upgraded, JSON.stringify(upgraded)).toMatchObject({ application: 'applied' }) + await traced(['stop:v1', 'start:v2']) + // The page reads the upgrade from the Host's change announcement. + await panel.getByRole('button', { name: `查看 ${NAME}`, exact: true }).click() + await panel.getByText('v2.0.0', { exact: true }).waitFor({ timeout: 10_000 }) + await panel.getByRole('button', { name: '返回插件' }).click() + }, 90_000) + + it('stops the running version and names the load error when the upgrade cannot load, then applies the fix', async () => { + const broken = await version('v3', "import 'e2e-hmr-missing-dependency'\n") + const failed = await reinstall(`file:${broken}`) + expect(failed).toMatchObject({ application: 'failed', error: { code: 'operation-error' } }) + expect(failed.error?.diagnostic).toContain('e2e-hmr-missing-dependency') + await traced(['stop:v2']) + // Switching the broken plugin off and on again loads the same files, and the page names the missing dependency. + const panel = await openPanel() + const toggle = panel.getByRole('switch', { name: `启用 ${NAME}`, exact: true }) + await toggle.click() + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') + await toggle.click() + await alertWith(page, 'e2e-hmr-missing-dependency').waitFor({ timeout: 10_000 }) + expect(await alertWith(page, 'e2e-hmr-missing-dependency').textContent()).not.toContain('重启') + await traced([]) + const fixed = await version('v4') + expect(await reinstall(`file:${fixed}`)).toMatchObject({ application: 'applied' }) + await traced(['start:v4']) + }, 90_000) + + it('reports an upgrade that loads but cannot start, then recovers with a working version', async () => { + const throwing = await version('v5') + await writeFile(join(throwing, 'index.mjs'), `export const name = '${NAME}'\nexport function apply() { throw new Error('v5 cannot start') }\n`) + const failed = await reinstall(`file:${throwing}`) + expect(failed).toMatchObject({ application: 'failed', error: { code: 'operation-error' } }) + expect(failed.error?.diagnostic).toContain('v5 cannot start') + await traced(['stop:v4']) + const working = await version('v6') + expect(await reinstall(`file:${working}`)).toMatchObject({ application: 'applied' }) + await traced(['start:v6']) + }, 90_000) + + it('uninstalls and reinstalls the same package with its new code', async () => { + const panel = await openPanel() + await uninstallThroughPage(panel) + await traced(['stop:v6']) + // pnpm removes the package after its plugins stop. + await expect.poll(dependency, { timeout: 30_000 }).toBeUndefined() + const v7 = await version('v7') + await installThroughPage(`file:${v7}`) + await traced(['start:v7']) + await uninstallThroughPage(await openPanel()) + await traced(['stop:v7']) + await expect.poll(dependency, { timeout: 30_000 }).toBeUndefined() + }, 90_000) + + it('starts a plugin linked to another directory without a restart', async () => { + // A bare local path links the package to its directory, as for a plugin under development. + const first = await version('v8') + await installThroughPage(first) + await traced(['start:v8']) + expect(await dependency()).toMatch(/^link:/u) + const moved = await version('v9') + expect(await reinstall(moved)).toMatchObject({ application: 'applied' }) + await traced(['stop:v8', 'start:v9']) + expect(await alertWith(page, '重启').count()).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + }, 90_000) +}) + +describe('web e2e: plugin installation without HMR', () => { + it('asks for a restart after installing into a profile that applies changes at startup', async () => { + const scratch = await mkdtemp(join(tmpdir(), 'dsh-plugin-startup-')) + let scaffold: WebScaffold | undefined + let browser: Browser | undefined + try { + const dir = join(scratch, 'addon') + await mkdir(dir) + await writeFile(join(dir, 'package.json'), JSON.stringify({ + name: NAME, version: '1.0.0', type: 'module', main: './index.mjs', dsh: { bundle: { patch: './cordis.patch.yml' } }, + })) + await writeFile(join(dir, 'cordis.patch.yml'), `- insert:\n - id: ${NAME}\n name: ${NAME}\n`) + await writeFile(join(dir, 'index.mjs'), `export const name = '${NAME}'\nexport function apply() {}\n`) + scaffold = await launchWebScaffold({ profile: { packages: [], hmr: false, packageManager: isolatedPnpm(scratch) } }) + browser = await chromium.launch() + const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, locale: ZH_BROWSER_LOCALE }) + await page.goto(scaffold.authenticatedUrl) + await page.waitForSelector('[class*="frame"]') + if (await page.getByRole('dialog', { name: '设置' }).count() > 0) await page.keyboard.press('Escape') + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() + const panel = page.locator('[data-plugin-panel]') + await panel.getByRole('button', { name: '添加插件', exact: true }).click() + const dialog = page.getByRole('dialog') + await dialog.getByRole('textbox', { name: '包名或地址' }).fill(`file:${dir}`) + await dialog.getByRole('button', { name: '安装', exact: true }).click() + await dialog.getByText('已安装,请重启 DSH 加载它。这个 profile 只在启动时应用更改。', { exact: true }).waitFor({ timeout: 30_000 }) + } finally { + await browser?.close() + await scaffold?.close() + await rm(scratch, { recursive: true, force: true }) + } + }, 120_000) +}) diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index b0fa589d55..5502602721 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -96,6 +96,141 @@ describe('web e2e: plugin manager', () => { return readFile(join(scaffold.harnessHome, ...segments), 'utf8').catch(() => '') } + it('keeps plugin header actions on one line as the available width changes', async () => { + const facts: string[] = [] + // A dedicated scaffold keeps the measured header deterministic: an install + // task left by an earlier test swaps the toolbar's add control for the + // view-installation button, which moves the wrap threshold. + const headerScaffold = await launchWebScaffold() + try { + // Pin the extremes; at intermediate widths, the rendered font and locale + // determine whether the two intrinsic items fit beside each other. + const PINNED_PLACEMENT: Record = { 1680: 'beside', 1024: 'beside', 390: 'below', 430: 'below' } + for (const language of ['en', 'zh'] as const) { + const context = await browser.newContext({ + viewport: { width: 1680, height: 1000 }, locale: language === 'en' ? 'en-US' : ZH_BROWSER_LOCALE, + reducedMotion: 'reduce', + }) + try { + const probe = await context.newPage() + const consoleWatch = watchConsole(probe) + await probe.goto(headerScaffold.authenticatedUrl, { waitUntil: 'load' }) + const title = language === 'en' ? 'Plugins' : '插件' + await probe.getByRole('button', { name: title, exact: true }).click() + const panel = probe.locator('[data-plugin-panel]') + const header = panel.locator(':scope > header') + await header.getByRole('heading', { name: title, exact: true }).waitFor() + await probe.evaluate(() => document.fonts.ready) + const add = header.getByRole('button', { name: language === 'en' ? 'Add plugin' : '添加插件', exact: true }) + await expect.poll(() => add.isEnabled()).toBe(true) + await add.focus() + const measure = () => header.evaluate((element) => { + const heading = element.firstElementChild! + const actions = element.lastElementChild! + const headingRect = heading.getBoundingClientRect() + const actionRect = actions.getBoundingClientRect() + const headerRect = element.getBoundingClientRect() + const intrinsicHeading = heading.cloneNode(true) as HTMLElement + Object.assign(intrinsicHeading.style, { + position: 'absolute', width: 'max-content', maxWidth: 'none', visibility: 'hidden', pointerEvents: 'none', + }) + element.append(intrinsicHeading) + let intrinsicHeadingWidth: number + try { + intrinsicHeadingWidth = intrinsicHeading.getBoundingClientRect().width + } finally { + intrinsicHeading.remove() + } + const headerStyle = getComputedStyle(element) + const contentWidth = headerRect.width - Number.parseFloat(headerStyle.paddingLeft) - Number.parseFloat(headerStyle.paddingRight) + const fitsBeside = intrinsicHeadingWidth + actionRect.width + Number.parseFloat(headerStyle.columnGap) <= contentWidth + 1 + const subtitle = heading.querySelector('h1 + div > span')! + const range = document.createRange() + range.selectNodeContents(subtitle) + const lastText = Array.from(range.getClientRects()).at(-1)! + const info = heading.querySelector('button')!.getBoundingClientRect() + const buttons = Array.from(actions.querySelectorAll('button')) + const singleLine = buttons.every((button) => { + const walker = document.createTreeWalker(button, NodeFilter.SHOW_TEXT) + const tops: number[] = [] + while (walker.nextNode()) { + if (!walker.currentNode.textContent?.trim()) continue + range.selectNodeContents(walker.currentNode) + for (const rect of range.getClientRects()) tops.push(rect.top) + } + return tops.length === 0 || Math.max(...tops) - Math.min(...tops) < 1 + }) + return { + singleLine, fitsBeside, + diagnostic: { flexWrap: headerStyle.flexWrap, headingMaxWidth: getComputedStyle(heading).maxWidth, + introDisplay: getComputedStyle(heading.querySelector('h1 + div')!).display, + intrinsicHeadingWidth, headingWidth: headingRect.width, actionsWidth: actionRect.width, + contentWidth, gap: Number.parseFloat(headerStyle.columnGap), + subtitleRight: lastText.right, infoLeft: info.left, + }, + placement: actionRect.left >= headingRect.right - 1 + ? 'beside' as const + : actionRect.top >= headingRect.bottom - 1 ? 'below' as const : 'overlapping' as const, + contained: actionRect.left >= headerRect.left - 1 && actionRect.right <= headerRect.right + 1, + infoFollowsText: info.left >= lastText.right && info.left - lastText.right <= 5 + && info.top < lastText.bottom && info.bottom > lastText.top, + focused: buttons.includes(document.activeElement as HTMLButtonElement), + } + }) + const validLayout = (layout: Awaited>) => + layout.singleLine && layout.contained && layout.infoFollowsText && layout.focused + && layout.placement === (layout.fitsBeside ? 'beside' : 'below') + for (const width of [1680, 768, 520, 440, 390, 430, 1024]) { + await probe.setViewportSize({ width, height: 1000 }) + await expect.poll(async () => { + const layout = await measure() + return validLayout(layout) ? true : layout + }, { message: `${language} ${width}px plugin header geometry` }).toBe(true) + const { placement } = await measure() + const pinned = PINNED_PLACEMENT[width] + if (pinned !== undefined) expect(placement).toBe(pinned) + facts.push(`${language} ${width}px: actions ${pinned === undefined ? 'beside or below (according to intrinsic fit)' : placement} the heading, single-line; contained; information follows subtitle; focus retained`) + } + await probe.setViewportSize({ width: 390, height: 1000 }) + const previousWrap = await header.evaluate((element) => { + const style = element.style + const previous = { value: style.getPropertyValue('flex-wrap'), priority: style.getPropertyPriority('flex-wrap') } + style.setProperty('flex-wrap', 'nowrap') + return previous + }) + try { + const noWrap = await measure() + expect(noWrap.fitsBeside).toBe(false) + expect(noWrap.placement).not.toBe('below') + expect(validLayout(noWrap)).toBe(false) + } finally { + await header.evaluate((element, previous) => { + if (previous.value === '') element.style.removeProperty('flex-wrap') + else element.style.setProperty('flex-wrap', previous.value, previous.priority) + }, previousWrap) + } + await expect.poll(async () => validLayout(await measure())).toBe(true) + const menuTrigger = header.getByRole('button', { name: language === 'en' ? 'Choose how to add a plugin' : '选择添加插件方式' }) + await menuTrigger.click() + await probe.getByRole('menu').waitFor() + await probe.keyboard.press('Escape') + await expect.poll(() => probe.getByRole('menu').count()).toBe(0) + expect(await menuTrigger.evaluate(element => element === document.activeElement)).toBe(true) + expect(consoleWatch.pageErrors).toEqual([]) + } finally { + await context.close() + } + } + await compareOrRefreshGolden( + join(SNAPSHOT_DIR, 'header-responsive.expected.md'), + `# Plugin header responsive layout\n\n${facts.join('\n')}\n\nA forced no-wrap layout at 390px fails the same measured layout check in both locales; restoring wrap passes.\nAdd menu dismisses on Escape and returns focus in both locales.`, + MODE, + ) + } finally { + await headerScaffold.close() + } + }) + it('aligns the first-read skeleton with the loaded plugin cards', async () => { const facts: string[] = [] let aria = '' @@ -148,7 +283,7 @@ describe('web e2e: plugin manager', () => { return { row: rect(row), head: rect(head), icon: rect(head?.children[0]), main: rect(main), titleRow: rect(main?.children[0]), title: rect(main?.children[0]?.firstElementChild), - description: rect(main?.children[1]), actions: rect(head?.children[2]), + description: rect(main?.children[1]), } }), } @@ -184,13 +319,11 @@ describe('web e2e: plugin manager', () => { await skeleton.waitFor({ state: 'detached' }) expect(await panel.getAttribute('aria-busy')).toBe('false') for (const action of await actions.all()) expect(await action.isDisabled()).toBe(false) - const official = panel.locator('[data-plugin-group="official"]') - await official.locator('[data-plugin-package]').first().waitFor() - // The Official group lists the shipped bundles and then the - // configuration-only items; an item card carries no action cell, so the - // placeholder rows model the first four bundle cards. - const loaded = await measure(official, ':scope > ul > li[data-plugin-package]') - expect(await official.locator(':scope > ul > li[data-plugin-package]').count()).toBe(OPTIONAL_BUNDLES.length + ON_DEMAND_BUNDLES.length) + const basic = panel.locator('[data-plugin-group="basic"]') + await basic.locator('[data-plugin-item]').first().waitFor() + // Configuration cards lead the list; their absent switches give the text column more width. + const loaded = await measure(basic) + expect(await basic.locator(':scope > ul > li[data-plugin-item]').count()).toBe(4) expect(loaded.rows).toHaveLength(loading.rows.length) const compare = (name: string, a: typeof loading.pageHeader, b: typeof loaded.pageHeader, axes: readonly (keyof typeof a)[] = ['x', 'y', 'width', 'height']) => { for (const axis of axes) { @@ -202,11 +335,11 @@ describe('web e2e: plugin manager', () => { for (const [index, row] of loading.rows.entries()) { const real = loaded.rows[index] if (real === undefined) break - for (const part of ['row', 'head', 'icon', 'main', 'titleRow', 'actions'] as const) compare(`row ${index + 1} ${part}`, row[part], real[part]) + for (const part of ['row', 'head', 'icon'] as const) compare(`row ${index + 1} ${part}`, row[part], real[part]) // Painted text bars are deliberately shorter than real copy; their line origins and heights align. - for (const part of ['title', 'description'] as const) compare(`row ${index + 1} ${part}`, row[part], real[part], ['x', 'y', 'height']) + for (const part of ['main', 'titleRow', 'title', 'description'] as const) compare(`row ${index + 1} ${part}`, row[part], real[part], ['x', 'y', 'height']) } - facts.push(`${width}px: ${loaded.rows.length} rows; page/group headers, rows, icons, text lines and blank action spaces align within 0.1px`) + facts.push(`${width}px: ${loaded.rows.length} rows; page/group headers, rows, icons and text line origins align within 0.1px`) expect(consoleWatch.pageErrors).toEqual([]) } finally { release.resolve(undefined) @@ -436,25 +569,29 @@ describe('web e2e: plugin manager', () => { expect(focusRing.radius).toBe(focusRing.cardRadius) expect(focusRing.outlineStyle).toBe('solid') expect(focusRing.outlineWidth).toBeGreaterThan(0) - // The profile's own group holds its fixture bundle and the scaffold's defaults bundle; the installation's - // optional bundles open the Official group, followed by the official plugins that registered their - // configuration, and its other bundles stay off the page. + // Profile bundles stay in Installed; configuration pages and offered bundles have their own groups. expect(await panel.locator('[data-plugin-group="bundles"] [data-plugin-package]').count()).toBe(2) - expect(await panel.locator('[data-plugin-group="official"] [data-plugin-package]').count()).toBe(OPTIONAL_BUNDLES.length + ON_DEMAND_BUNDLES.length) - expect(await panel.locator('[data-plugin-group="official"] [data-plugin-item]').count()).toBe(4) - expect(await panel.getByText('实验性', { exact: true }).count()) - .toBe(OPTIONAL_BUNDLES.filter(name => name.startsWith('@deepseek-ai/dsh-experimental-')).length) + expect(await panel.locator('[data-plugin-group="basic"] [data-plugin-item]').count()).toBe(4) expect(await panel.locator('[data-plugin-package="@deepseek-ai/dsh-experimental-inspector"]').count()).toBe(0) expect(await panel.getByRole('switch', { name: '启用 语音输入', exact: true }).getAttribute('aria-checked')).toBe('false') expect(await panel.getByRole('switch', { name: '启用 开发者工具', exact: true }).getAttribute('aria-checked')).toBe('false') expect(await panel.getByText('查看调试会话原始数据、聊天消息分组数据,以及调试 NodeJS 后端', { exact: true }).count()).toBe(1) expect(await panel.getByText(/Cordis|Chrome DevTools/).count()).toBe(0) + await panel.getByRole('button', { name: '更多', exact: true }).click() + await panel.getByRole('heading', { name: '实验性插件', exact: true, level: 1 }).waitFor() + expect(await panel.locator('[data-plugin-group="more"] [data-plugin-package]').count()) + .toBe(OPTIONAL_BUNDLES.length + ON_DEMAND_BUNDLES.length) + expect(await panel.getByText('实验性', { exact: true }).count()) + .toBe(OPTIONAL_BUNDLES.filter(name => name.startsWith('@deepseek-ai/dsh-experimental-')).length) + expect(await panel.locator('[data-plugin-group="bundles"]').count()).toBe(0) + await panel.getByRole('button', { name: '返回插件', exact: true }).click() + expect(await panel.locator('[data-plugin-group="bundles"] [data-plugin-package]').count()).toBe(2) // A bundle that is off still shows the rows its patch declares, without switches. await panel.getByRole('button', { name: '查看 @fixture/bundle' }).click() await panel.locator('[data-plugin-row]', { hasText: 'fixture-row' }).waitFor({ timeout: 10_000 }) expect(await panel.getByRole('switch', { name: '启用组件 @fixture/bundle' }).count()).toBe(0) await panel.getByRole('button', { name: '卸载 @fixture/bundle' }).waitFor({ timeout: 5_000 }) - await panel.getByRole('button', { name: '返回插件列表' }).click() + await panel.getByRole('button', { name: '返回插件' }).click() await expect.poll(() => panel.getByRole('button', { name: '卸载 @fixture/bundle' }).count(), { timeout: 5_000 }).toBe(0) const snapshot = await captureStableAria(page, '[data-plugin-panel]', scaffold.workspaceCwd) @@ -538,7 +675,7 @@ describe('web e2e: plugin manager', () => { } await panel.getByRole('button', { name: '查看 智能体团队', exact: true }).click() await checkImage('[data-plugin-detail]', teamIcon, 'Agent Teams detail') - await panel.getByRole('button', { name: '返回插件列表' }).click() + await panel.getByRole('button', { name: '返回插件' }).click() await panel.getByRole('button', { name: '查看 @fixture/bundle', exact: true }).click() await checkImage('[data-plugin-detail]', fixtureIcon, 'Third-party bundle detail') await checkImage('[data-plugin-row="fixture-search"]', fallbackIcon, 'Independent search row') @@ -546,7 +683,7 @@ describe('web e2e: plugin manager', () => { expect(await panel.locator('[data-plugin-row="fixture-review"] svg').count()).toBeGreaterThan(0) images.push('Independent review row: generic artwork') await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'icons.expected.md'), images.join('\n'), MODE) - await panel.getByRole('button', { name: '返回插件列表' }).click() + await panel.getByRole('button', { name: '返回插件' }).click() expect(tripwire.pageErrors).toEqual([]) }) @@ -579,7 +716,7 @@ describe('web e2e: plugin manager', () => { } finally { await setLanguage('zh') } - await panel.getByRole('button', { name: '返回插件列表' }).click() + await panel.getByRole('button', { name: '返回插件' }).click() expect(tripwire.pageErrors).toEqual([]) }) @@ -662,9 +799,9 @@ describe('web e2e: plugin manager', () => { for (const id of ['agent-team', 'tool-agent-team', 'ui-agent-team']) { await panel.locator('[data-plugin-row]', { hasText: id }).first().waitFor() } - await panel.getByRole('button', { name: '返回插件列表' }).click() + await panel.getByRole('button', { name: '返回插件' }).click() } finally { - const back = panel.getByRole('button', { name: '返回插件列表' }) + const back = panel.getByRole('button', { name: '返回插件' }) if (await back.count() > 0) await back.click() if (await toggle.getAttribute('aria-checked') === 'true') await toggle.click() await expect.poll(() => teamRows().filter(entry => entry.fiber?.state === FiberState.ACTIVE).length, { timeout: 20_000 }).toBe(0) @@ -918,7 +1055,7 @@ describe('web e2e: plugin manager', () => { await expect.poll(() => mounted()?.fiber?.state, { timeout: 20_000 }).not.toBe(2) await rowSwitch.click() await expect.poll(() => mounted()?.fiber?.state, { timeout: 20_000 }).toBe(2) - await panel.getByRole('button', { name: '返回插件列表' }).click() + await panel.getByRole('button', { name: '返回插件' }).click() await toggle.click() await expect.poll(() => mounted()?.fiber?.state, { timeout: 20_000 }).not.toBe(2) @@ -930,7 +1067,7 @@ describe('web e2e: plugin manager', () => { expect(tripwire.warnings).toEqual([]) await assertFixtureInventory(SNAPSHOT_DIR, [ 'manager.expected.md', 'live-enabled.expected.md', 'missing-bundle.expected.md', 'exports.expected.md', 'exports-en.expected.md', 'icons.expected.md', 'loading.expected.md', 'refresh.expected.md', - 'ime-enter.expected.md', + 'ime-enter.expected.md', 'header-responsive.expected.md', ]) }) }) @@ -963,13 +1100,13 @@ describe('web e2e: startup-applied plugin management', () => { // The selection is saved and the switch turns on, but nothing mounts before the next start; a toast says so. await expect.poll(bundles, { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toEqual([...SCAFFOLD_BUNDLES, '@fixture/bundle']) await expect.poll(() => toggle.getAttribute('aria-checked'), { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toBe('true') - await page.getByText('更改将在下次启动生效', { exact: true }).waitFor({ timeout: 10_000 }) + await page.getByText('请重启 DSH 使更改生效。这个 profile 只在启动时应用更改。', { exact: true }).waitFor({ timeout: 10_000 }) expect(mounted()?.fiber?.state).toBeUndefined() // The pack's page lists its rows from their declarations, with no live entry to switch. await panel.getByRole('button', { name: '查看 @fixture/bundle' }).click() await panel.locator('[data-plugin-row]', { hasText: 'fixture-row' }).waitFor({ timeout: 10_000 }) expect(await panel.getByRole('switch', { name: '启用组件 @fixture/bundle' }).isDisabled()).toBe(true) - await panel.getByRole('button', { name: '返回插件列表' }).click() + await panel.getByRole('button', { name: '返回插件' }).click() await toggle.click() await expect.poll(bundles, { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toEqual(SCAFFOLD_BUNDLES) diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index ac2f8c72f7..cea516a9de 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' @@ -316,6 +318,7 @@ async function bootPreview(origin: string, browser: Browser): Promise { const continueButton = page.getByRole('button', { name: 'Continue' }) await continueButton.waitFor({ timeout: HERO_TIMEOUT_MS }) await continueButton.click() + await page.getByRole('button', { name: 'Add API Key', exact: true }).click() const configureLater = page.getByRole('button', { name: 'Configure later' }) await configureLater.waitFor({ timeout: 30_000 }) await configureLater.click() @@ -455,6 +458,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() @@ -530,8 +584,9 @@ async function bootEmptyPreview(origin: string, browser: Browser): Promise // has no host routes — the controller publishes an empty list and the // header renders no button, which is that surface's designed degradation. expect([...failedResponses].sort()).toEqual(['/open-in-app/apps', '/plugins/events']) + // The worker recomposes configuration but exposes no Node module caches for code replacement. expect(consoleErrors.filter(line => !line.includes('Failed to load resource: the server responded with a status of 404'))) - .toEqual([]) + .toEqual(['hmr: restart required: module-comparison']) } catch (error) { await saveFailureShot(page, 'preview-boot-empty') throw pageErrors.length === 0 diff --git a/apps/web/tests/ptc-round.e2e.ts b/apps/web/tests/ptc-round.e2e.ts index ff8b5f8f4a..575b3ad645 100644 --- a/apps/web/tests/ptc-round.e2e.ts +++ b/apps/web/tests/ptc-round.e2e.ts @@ -18,6 +18,7 @@ const UI_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/ptc-round/ui.e const TRAJECTORY_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/ptc-round/trajectory.expected.md', import.meta.url)) const CODE_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/ptc-round/code.expected.md', import.meta.url)) const PREPARING_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/ptc-round/preparing.expected.md', import.meta.url)) +const REQUEST_LIFECYCLE_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/ptc-round/request-lifecycle.expected.md', import.meta.url)) const MODE = webSnapshotMode() // Elicits the successful and failed sub-rows this scenario asserts. @@ -55,6 +56,7 @@ describe('web e2e: PTC mode round renders nested sub-calls', () => { it('drives the recorded prompt to a settled turn (all modes)', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-ptc-drive')) + const requestStates: string[] = [] if (MODE !== 'record') { expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT]) } @@ -62,7 +64,11 @@ describe('web e2e: PTC mode round renders nested sub-calls', () => { await input.waitFor({ timeout: 10_000 }) const settled = scaffold.whenTurnSettled() const gate = Promise.withResolvers() + const waiting = Promise.withResolvers() + const start = Promise.withResolvers() const dispose = scaffold.ctx.on('llm/stream', async function* (_options, next) { + waiting.resolve(undefined) + await start.promise let held = false for await (const chunk of next()) { yield chunk @@ -72,11 +78,21 @@ describe('web e2e: PTC mode round renders nested sub-calls', () => { } } }, { prepend: true }) - releasePreparation = () => { gate.resolve(undefined); dispose() } + releasePreparation = () => { start.resolve(undefined); gate.resolve(undefined); dispose() } const observePreparation = async () => { try { await input.fill(PROMPT) await input.press('Enter') + await waiting.promise + await page.getByRole('tab', { name: 'Trajectory', exact: true }).click() + const request = page.getByRole('table').getByRole('button', { name: 'Request #1', exact: true }) + await request.click() + const panel = page.getByRole('tabpanel') + await panel.locator('dl').first().getByText('Pending', { exact: true }).waitFor() + expect(await panel.getByRole('button', { name: 'Assistant Message', exact: true }).count()).toBe(0) + requestStates.push('# Waiting for output', await panel.locator('dl').first().ariaSnapshot()) + await page.getByRole('tab', { name: 'Chat', exact: true }).click() + start.resolve(undefined) const row = page.locator('[data-chat-call-id] [data-state="preparing"]').first() await row.waitFor({ state: 'attached', timeout: 30_000 }) await expandOwningTurnProcess(page, row) @@ -88,14 +104,45 @@ describe('web e2e: PTC mode round renders nested sub-calls', () => { expect(await row.locator('pre').count()).toBe(0) const group = row.locator('xpath=ancestor::*[@data-chat-group-key][1]') await compareOrRefreshGolden(PREPARING_EXPECTED, await group.ariaSnapshot(), MODE) + await page.getByRole('tab', { name: 'Trajectory', exact: true }).click() + const assistant = page.locator('tr[data-kind="message"][data-running="true"]').first() + await assistant.click() + await panel.locator('dl').first().getByText('Pending', { exact: true }).waitFor() + expect(await panel.getByText('Completed', { exact: true }).count()).toBe(0) + requestStates.push('# Streaming assistant', await panel.locator('dl').first().ariaSnapshot()) + await panel.getByRole('button', { name: 'Request Timing', exact: true }).click() + expect(await panel.getByText('Not recorded', { exact: true }).count()).toBe(0) + expect(await panel.locator('dt').filter({ hasText: /^Started$/ }).locator('..').getByRole('button').count()).toBe(1) + await request.click() + await panel.locator('dl').first().getByText('Pending', { exact: true }).waitFor() + requestStates.push('# Streaming request', await panel.locator('dl').first().ariaSnapshot()) + await page.getByRole('tab', { name: 'Chat', exact: true }).click() } finally { releasePreparation?.() } } - const [sessionId] = await Promise.all([settled, observePreparation()]) - await expect.poll(() => page.locator('[data-state="preparing"]').count(), { timeout: 15_000 }).toBe(0) - if (MODE === 'record') { - await recordFixture(scaffold, sessionId, FIXTURE) + try { + const [sessionId] = await Promise.all([settled, observePreparation()]) + expect(sessionEvents.filter(event => event.type === 'turn/end')).toMatchObject([ + { data: { reason: { kind: 'completed' } } }, + ]) + await expect.poll(() => page.locator('[data-state="preparing"]').count(), { timeout: 15_000 }).toBe(0) + if (MODE === 'record') { + await recordFixture(scaffold, sessionId, FIXTURE) + } else { + await page.getByRole('tab', { name: 'Trajectory', exact: true }).click() + await page.getByRole('table').getByRole('button', { name: 'Request #1', exact: true }).click() + const panel = page.getByRole('tabpanel') + await panel.getByText('Completed', { exact: true }).waitFor() + requestStates.push('# Settled request', await panel.locator('dl').first().ariaSnapshot()) + await panel.getByRole('button', { name: 'Assistant Message', exact: true }).click() + await panel.getByText('Completed', { exact: true }).waitFor() + requestStates.push('# Settled assistant', await panel.locator('dl').first().ariaSnapshot()) + await compareOrRefreshGolden(REQUEST_LIFECYCLE_EXPECTED, requestStates.join('\n\n'), MODE) + } + } finally { + releasePreparation?.() + await page.getByRole('tab', { name: 'Chat', exact: true }).click() } }, 200_000) diff --git a/apps/web/tests/remote-settings.e2e.ts b/apps/web/tests/remote-settings.e2e.ts new file mode 100644 index 0000000000..8f7ea86e1a --- /dev/null +++ b/apps/web/tests/remote-settings.e2e.ts @@ -0,0 +1,129 @@ +// A trusted remote browser uses the same Host settings service as loopback: +// welcome acknowledgement, model configuration and appearance persist in the +// Host profile patch across reloads and independent browser contexts. +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import type { Browser, Locator, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { + acknowledgeReloadConnectionLoss, + launchWebScaffold, watchConsole, webSnapshotMode, WELCOME_NOTICE_COPY, + type WebScaffold, +} from './scaffold.ts' +import { openSettings, ZH_BROWSER_LOCALE } from './support.ts' + +const MODE = webSnapshotMode() + +/** + * A loading welcome store hides the notice, so absence is conclusive only + * after the shared settings read has enabled the Models view. + * @param page - the loaded page. + * @returns the open settings dialog on its Models view. + */ +async function expectOnboardingSettled(page: Page): Promise { + await page.waitForSelector('#root', { timeout: 30_000 }) + await page.getByRole('textbox', { name: '选择工作区' }).waitFor({ timeout: 30_000 }) + await openSettings(page, 'zh') + const dialog = page.getByRole('dialog', { name: '设置' }) + await dialog.getByRole('button', { name: '模型', exact: true }).click() + await dialog.getByRole('button', { name: '添加模型提供商', exact: true }).waitFor({ timeout: 15_000 }) + expect(await page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title }).count()).toBe(0) + return dialog +} + +describe.skipIf(MODE === 'record')('web e2e: trusted remote host preferences', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + scaffold = await launchWebScaffold({ + remoteAuthority: 'remote.localhost', + welcomeNoticePending: true, + }) + browser = await chromium.launch() + page = await browser.newPage({ + viewport: { width: 1440, height: 960 }, + locale: ZH_BROWSER_LOCALE, + }) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('#root', { timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + /** Reload the page and absorb the one expected reload-time connection loss. */ + async function reloadPage(): Promise { + const warnings = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + acknowledgeReloadConnectionLoss(tripwire, warnings) + } + + it('persists welcome acknowledgement, model configuration, and appearance across reloads and browser contexts', async () => { + const welcome = page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title }) + await welcome.waitFor({ timeout: 15_000 }) + expect(await page.locator('#root').evaluate(root => (root as HTMLElement).inert)).toBe(true) + + await welcome.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel }).click() + await welcome.waitFor({ state: 'detached', timeout: 15_000 }) + await expect.poll( + () => page.locator('#root').evaluate(root => (root as HTMLElement).inert), + { timeout: 15_000 }, + ).toBe(false) + const settingsPath = join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml') + await expect.poll(() => readFile(settingsPath, 'utf8'), { timeout: 10_000 }) + .toContain('welcomeNoticeVersion:') + + // The acknowledged version is durable, so the notice stays away after a reload. + await reloadPage() + const dialog = await expectOnboardingSettled(page) + + await page.emulateMedia({ colorScheme: 'light' }) + await dialog.getByRole('button', { name: '添加模型提供商', exact: true }).click() + await dialog.getByLabel('提供商', { exact: true }).selectOption('minimax-cn') + await dialog.getByRole('button', { name: '保存', exact: true }).click() + await dialog.getByText('已保存 minimax-cn。', { exact: true }).waitFor({ timeout: 15_000 }) + await expect.poll(() => readFile(settingsPath, 'utf8'), { timeout: 10_000 }) + .toContain('minimax-cn: {}') + + await dialog.getByRole('button', { name: '通用设置', exact: true }).click() + await dialog.getByRole('button', { name: '深色', exact: true }).click() + await expect.poll(() => page.locator('body').getAttribute('data-ds-dark-theme')).toBe('') + await expect.poll(() => readFile(settingsPath, 'utf8'), { timeout: 10_000 }) + .toContain('preference: dark') + + await reloadPage() + await expectOnboardingSettled(page) + await dialog.getByRole('button', { name: '编辑 minimax-cn', exact: true }).waitFor({ timeout: 15_000 }) + await expect.poll(() => page.locator('body').getAttribute('data-ds-dark-theme'), { timeout: 15_000 }).toBe('') + expect(tripwire.warnings).toEqual([]) + expect(tripwire.pageErrors).toEqual([]) + + const context = await browser.newContext({ + viewport: { width: 1440, height: 960 }, + locale: ZH_BROWSER_LOCALE, + colorScheme: 'light', + }) + try { + const freshPage = await context.newPage() + const freshTripwire = watchConsole(freshPage) + await freshPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + const freshDialog = await expectOnboardingSettled(freshPage) + await freshDialog.getByRole('button', { name: '编辑 minimax-cn', exact: true }).waitFor({ timeout: 15_000 }) + await expect.poll( + () => freshPage.locator('body').getAttribute('data-ds-dark-theme'), + { timeout: 15_000 }, + ).toBe('') + expect(freshTripwire.warnings).toEqual([]) + expect(freshTripwire.pageErrors).toEqual([]) + } finally { + await context.close() + } + }, 180_000) +}) diff --git a/apps/web/tests/remote-welcome.e2e.ts b/apps/web/tests/remote-welcome.e2e.ts deleted file mode 100644 index b7b013dc2d..0000000000 --- a/apps/web/tests/remote-welcome.e2e.ts +++ /dev/null @@ -1,60 +0,0 @@ -// Trusted non-loopback Web access cannot call the loopback-only settings API; -// the notice therefore advances for this browser process and returns on reload. -import type { Browser, Page } from 'playwright' -import { chromium } from 'playwright' -import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { - acknowledgeReloadConnectionLoss, launchWebScaffold, watchConsole, webSnapshotMode, - WELCOME_NOTICE_COPY, - type WebScaffold, -} from './scaffold.ts' -import { ZH_BROWSER_LOCALE } from './support.ts' - -const MODE = webSnapshotMode() - -describe.skipIf(MODE === 'record')('web e2e: remote welcome notice', () => { - let scaffold: WebScaffold - let browser: Browser - let page: Page - let tripwire: ReturnType - - beforeAll(async () => { - scaffold = await launchWebScaffold({ - remoteAuthority: 'remote.localhost', - welcomeNoticePending: true, - }) - browser = await chromium.launch() - page = await browser.newPage({ - viewport: { width: 1440, height: 960 }, - locale: ZH_BROWSER_LOCALE, - }) - tripwire = watchConsole(page) - await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await page.waitForSelector('#root', { timeout: 30_000 }) - }, 120_000) - - afterAll(async () => { - await browser?.close() - await scaffold?.close() - }) - - it('advances process-locally and presents the notice again after reload', async () => { - const welcome = page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title }) - await welcome.waitFor({ timeout: 15_000 }) - expect(await page.locator('#root').evaluate(root => (root as HTMLElement).inert)).toBe(true) - - await welcome.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel }).click() - await welcome.waitFor({ state: 'detached', timeout: 15_000 }) - await expect.poll( - () => page.locator('#root').evaluate(root => (root as HTMLElement).inert), - { timeout: 15_000 }, - ).toBe(false) - - const reloadWarnings = tripwire.warnings.length - await page.reload({ waitUntil: 'load' }) - acknowledgeReloadConnectionLoss(tripwire, reloadWarnings) - await welcome.waitFor({ timeout: 15_000 }) - expect(tripwire.warnings).toEqual([]) - expect(tripwire.pageErrors).toEqual([]) - }, 60_000) -}) diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts index 77d9c9c54d..c5a382a55e 100644 --- a/apps/web/tests/replay-round-trip.e2e.ts +++ b/apps/web/tests/replay-round-trip.e2e.ts @@ -19,7 +19,7 @@ import type { Browser, Page, Route, WebSocketRoute } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { ToolCallId, expandAssistantStream } from '@deepseek-ai/dsh-llm' -import type { Session, SessionEvent, SessionId } from '@deepseek-ai/dsh-session' +import { SessionId, type Session, type SessionEvent } from '@deepseek-ai/dsh-session' import type { SessionListValue } from '@deepseek-ai/dsh-api-session-controller/types' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { @@ -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}}') @@ -238,22 +240,34 @@ describe('web e2e: fresh round trip through the real assembly', () => { }) it('exposes the assembled Web URL to the real bash tool', 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`) - const result = await scaffold.ctx.tools.execute({ - signal: AbortSignal.timeout(5_000), - callId: ToolCallId('web-url-probe'), - name: 'bash', - arguments: { - command: 'printf \'%s\\n\' "$DSH_WEB_URL"', - description: 'Print current Web runtime', - }, - agent, - }) - expect(result.isError).toBe(false) - expect(result.content.filter(block => block.type === 'text').map(block => block.text).join('')) - .toBe(`${scaffold.baseUrl}\n`) + // This host probe records job events too; keep it out of the shared + // conversation fixture that other browser scenarios replay. + const probe = await launchWebScaffold() + try { + const handle = await probe.ctx.agents.create({ + sessionId: SessionId('web-url-probe'), + setup: agentCtx => probe.ctx.agentPresets.mount(agentCtx).then(() => undefined), + }) + try { + const result = await probe.ctx.tools.execute({ + signal: AbortSignal.timeout(5_000), + callId: ToolCallId('web-url-probe'), + name: 'bash', + arguments: { + command: 'printf \'%s\\n\' "$DSH_WEB_URL"', + description: 'Print current Web runtime', + }, + agent: handle.agent, + }) + expect(result.isError).toBe(false) + expect(result.content.filter(block => block.type === 'text').map(block => block.text).join('')) + .toBe(`${probe.baseUrl}\n`) + } finally { + await handle.dispose() + } + } finally { + await probe.close() + } }) it.skipIf(MODE === 'record')('rendered the settled turn: markdown, tool row, composer restore', async () => { diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index 8009cf4453..593eb41d7a 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -78,7 +78,7 @@ import { type SessionEvent, type SessionHeader, } from '@deepseek-ai/dsh-session' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' // Empty type imports carry the webServer/agents/sessionPersistence Context merges. import type {} from '@deepseek-ai/dsh-host-webserver' import type {} from '@deepseek-ai/dsh-agent' @@ -310,6 +310,8 @@ export interface LaunchOptions { openInAppEnvironment?: LaunchEnvironmentSnapshot /** Compare the replayed root Session; `read-only` also forbids refresh writes to a borrowed fixture. */ compareReplaySession?: boolean | 'read-only' + /** Fixed JSON-quoted workspace path length for compaction estimates; omitted values use the ordinary prefix. */ + workspacePathLength?: number /** * Optional product overlay applied after the shipped Web surface and before * the scaffold's hermetic test patches, matching the launcher's `--patch` @@ -502,7 +504,15 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise sessionFormatCatalog.encodeCurrentEvent(event)) const header = sessionFormatCatalog.encodeCurrentHeader({ @@ -1126,6 +1138,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 } } @@ -1545,6 +1560,7 @@ function normalizeAria(snapshot: string, workspaceCwd: string, age: boolean): st .split(workspaceCwd).join('{{cwd}}') .split(base).join('{{workspace}}') .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '{{uuid}}') + .replace(/(?<=-)[0-9a-f]{16}(?![0-9a-f])/gi, '{{uuid}}') // The optional space in `\d+m ?\d+s` covers both minute spellings: the // stats line's compact `2m42s` and the message-chrome template's `2m 42s`. .replace( diff --git a/apps/web/tests/schedule-header.e2e.ts b/apps/web/tests/schedule-header.e2e.ts new file mode 100644 index 0000000000..fc79fd571c --- /dev/null +++ b/apps/web/tests/schedule-header.e2e.ts @@ -0,0 +1,97 @@ +// UI-only geometry for the Automation tasks page; no model calls or task mutations. +import { fileURLToPath } from 'node:url' +import { chromium } from 'playwright' +import { expect, it } from 'vitest' +import { compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode } from './scaffold.ts' + +it('keeps the automation title intact before moving New to another line', async () => { + const scaffold = await launchWebScaffold() + try { + const browser = await chromium.launch() + try { + const facts: string[] = [] + for (const language of ['en', 'zh'] as const) { + const context = await browser.newContext({ + viewport: { width: 1680, height: 1000 }, + locale: language === 'en' ? 'en-US' : 'zh-CN', + reducedMotion: 'reduce', + }) + try { + const page = await context.newPage() + const consoleWatch = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + const title = language === 'en' ? 'Automation tasks' : '自动化任务' + await page.getByRole('button', { name: title, exact: true }).click() + const panel = page.getByTestId('task-manager-page') + const heading = panel.getByRole('heading', { name: title, exact: true }) + await heading.waitFor() + const header = heading.locator('..') + const create = header.getByRole('button', { name: language === 'en' ? 'New' : '新建', exact: true }) + await page.evaluate(() => document.fonts.ready) + await create.focus() + for (const width of [1680, 800, 520, 440, 390, 430, 1024]) { + await page.setViewportSize({ width, height: 1000 }) + // The title keeps its natural width at every viewport width, so New + // stays beside it here; the squeeze case below is what moves it down. + await expect.poll(() => header.evaluate((element) => { + const title = element.querySelector('h1')! + const button = element.querySelector('button')! + const titleRect = title.getBoundingClientRect() + const buttonRect = button.getBoundingClientRect() + const headerRect = element.getBoundingClientRect() + const range = document.createRange() + range.selectNodeContents(title) + const titleLines = Array.from(range.getClientRects()) + return { + titleSingleLine: titleLines.length === 1, + buttonSingleLine: button.scrollHeight <= button.clientHeight, + placement: buttonRect.left >= titleRect.right - 1 + ? 'beside' as const + : buttonRect.top >= titleRect.bottom - 1 ? 'below' as const : 'overlapping' as const, + contained: titleRect.left >= headerRect.left - 1 && titleRect.right <= headerRect.right + 1 + && buttonRect.left >= headerRect.left - 1 && buttonRect.right <= headerRect.right + 1, + focused: document.activeElement === button, + } + })).toEqual({ + titleSingleLine: true, buttonSingleLine: true, placement: 'beside', contained: true, focused: true, + }) + facts.push(`${language} ${width}px: title and New single-line, New beside the title; contained; New retains focus`) + } + if (language === 'en') { + // 509px collapses the left sidebar to its rail; expanding it leaves the + // page column narrow enough (measured 172px) to force the wrap. + await page.setViewportSize({ width: 509, height: 1000 }) + await page.getByRole('button', { name: 'Open sidebar', exact: true }).first().click() + await expect.poll(() => header.evaluate((element) => { + const title = element.querySelector('h1')! + const button = element.querySelector('button')! + const titleRect = title.getBoundingClientRect() + const buttonRect = button.getBoundingClientRect() + const range = document.createRange() + range.selectNodeContents(title) + return { + titleSingleLine: range.getClientRects().length === 1, + placement: buttonRect.left >= titleRect.right - 1 + ? 'beside' as const + : buttonRect.top >= titleRect.bottom - 1 ? 'below' as const : 'overlapping' as const, + } + })).toEqual({ titleSingleLine: true, placement: 'below' }) + facts.push('en 509px with sidebar expanded: title single-line; New moves below the title') + } + expect(consoleWatch.pageErrors).toEqual([]) + } finally { + await context.close() + } + } + await compareOrRefreshGolden( + fileURLToPath(new URL('./expected/schedule-header.expected.md', import.meta.url)), + `# Automation tasks header\n\n${facts.join('\n')}`, + webSnapshotMode(), + ) + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) 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 bc6e6302e2..5155daf95c 100644 --- a/apps/web/tests/settings-chrome.e2e.ts +++ b/apps/web/tests/settings-chrome.e2e.ts @@ -8,12 +8,12 @@ // Zero model calls: everything is pure client + persistence state on a blank // frame, so there is no fixture and a stray stream would fail loud on the // open llm seam. -import { readFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' -import type { Browser, Locator, Page } from 'playwright' +import type { Browser, Locator, Page, Request } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished } from 'vitest' -import { join } from 'node:path' +import { basename, join } from 'node:path' import { SessionId } from '@deepseek-ai/dsh-session' import { acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, @@ -29,9 +29,17 @@ const PLUGIN_INSTANCES_EXPECTED = join(SNAPSHOT_DIR, 'plugin-instances.expected. const DIALOG_EN_EXPECTED = join(SNAPSHOT_DIR, 'dialog-en.expected.md') const PLUGIN_ROW_SELECTOR = '[data-plugin-scope="preset"] [data-plugin-entry="tool-subagent"]' const MODE = webSnapshotMode() +const SCREENSHOTS = 'screenshots/collapse-timing-settings' +const SCREENSHOT_DIR = fileURLToPath(new URL(`../../../.artifacts/${SCREENSHOTS}`, import.meta.url)) const { version } = JSON.parse(await readFile(new URL('../../../package.json', import.meta.url), 'utf8')) as { version: string } const versionCapture = { replacements: [[version, '{{version}}']] as const } +async function saveSettingsFailureShot(page: Page, name: string): Promise { + await mkdir(SCREENSHOT_DIR, { recursive: true }) + const directory = await mkdtemp(join(SCREENSHOT_DIR, `${name}-`)) + await saveFailureShot(page, `${SCREENSHOTS}/${basename(directory)}/failure`) +} + describe('web e2e: settings modal and General preferences', () => { let scaffold: WebScaffold let browser: Browser @@ -53,24 +61,29 @@ describe('web e2e: settings modal and General preferences', () => { }, 120_000) afterAll(async () => { - await browser?.close() - await scaffold?.close() + try { + await browser?.close() + } finally { + await scaffold?.close() + } }) it('opens the settings dialog, switches sections, and closes by every path', async () => { - onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-shell')) + onTestFailed(() => saveSettingsFailureShot(page, 'settings-shell')) onTestFinished(async () => { const dialog = page.getByRole('dialog', { name: '设置' }) if (await dialog.isVisible()) await page.keyboard.press('Escape') await dialog.waitFor({ state: 'hidden' }) }) - const trigger = page.getByRole('button', { name: '设置', exact: true }) - expect(await trigger.getAttribute('aria-haspopup')).toBe('dialog') + const trigger = page.getByRole('button', { name: '账号菜单', exact: true }) + expect(await trigger.getAttribute('aria-haspopup')).toBe('menu') expect(await trigger.getAttribute('aria-expanded')).toBe('false') await trigger.click() + expect(await trigger.getAttribute('aria-expanded')).toBe('true') + await page.getByRole('menuitem', { name: '设置', exact: true }).click() const dialog = page.getByRole('dialog', { name: '设置' }) await dialog.waitFor({ timeout: 10_000 }) - expect(await trigger.getAttribute('aria-expanded')).toBe('true') + expect(await trigger.getAttribute('aria-expanded')).toBe('false') // General is active by default; Permission, Language and Appearance are functional. expect(await dialog.getByRole('button', { name: '通用设置' }).getAttribute('aria-current')).toBe('true') await dialog.getByRole('button', { name: '工作区内修改' }).waitFor({ timeout: 10_000 }) @@ -100,10 +113,13 @@ describe('web e2e: settings modal and General preferences', () => { }), }) }) - await openDocument.click() - await expect.poll(() => openRequests, { timeout: 5_000 }).toBe(1) - await expect.poll(() => openDocument.isEnabled(), { timeout: 5_000 }).toBe(true) - await page.unroute('**/api/settings/openSettingsDocument') + try { + await openDocument.click() + await expect.poll(() => openRequests, { timeout: 5_000 }).toBe(1) + await expect.poll(() => openDocument.isEnabled(), { timeout: 5_000 }).toBe(true) + } finally { + await page.unrouteAll({ behavior: 'wait' }) + } await dialog.getByText(`当前版本:${version}`, { exact: true }).waitFor() // Golden of the freshly opened dialog (default zh, General active). const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd, versionCapture) @@ -149,8 +165,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) @@ -168,17 +184,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) } @@ -190,7 +200,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') @@ -783,7 +793,7 @@ describe('web e2e: settings modal and General preferences', () => { await page.reload({ waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) acknowledgeReloadConnectionLoss(tripwire, warningStart) - const enTrigger = page.getByRole('button', { name: 'Settings' }) + const enTrigger = page.getByRole('button', { name: 'Account menu' }) await enTrigger.waitFor({ timeout: 10_000 }) // A Chinese browser on another port still receives the explicit English @@ -864,7 +874,7 @@ describe('web e2e: settings modal and General preferences', () => { const fresh = await launchWebScaffold({ developerTools: false }) const frPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'fr-FR' }) const frTripwire = watchConsole(frPage) - onTestFailed(() => saveFailureShot(frPage, 'web-e2e-settings-unshipped-language')) + onTestFailed(() => saveSettingsFailureShot(frPage, 'settings-unshipped-language')) try { await frPage.goto(fresh.authenticatedUrl, { waitUntil: 'load' }) await frPage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) @@ -901,6 +911,7 @@ describe('web e2e: settings modal and General preferences', () => { onTestFinished(() => fresh.close()) const withoutBrowser = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'en-US' }) onTestFinished(() => withoutBrowser.close()) + onTestFailed(() => saveSettingsFailureShot(withoutBrowser, 'settings-no-browser')) const browserConsole = watchConsole(withoutBrowser) await withoutBrowser.goto(fresh.authenticatedUrl, { waitUntil: 'load' }) await openSettings(withoutBrowser, 'en') @@ -920,8 +931,218 @@ describe('web e2e: settings modal and General preferences', () => { 'dialog-en.expected.md', 'dialog-no-browser.expected.md', 'dialog.expected.md', + 'collapse-timing-en.expected.md', + 'collapse-timing-zh.expected.md', 'plugin-instances.expected.md', 'plugins.expected.md', ]) }) }) + +describe('web e2e: Host-backed collapse timing preference', () => { + let scaffold: WebScaffold + let browser: Browser + const uiWait = { timeout: 10_000 } + + beforeAll(async () => { + scaffold = await launchWebScaffold({ developerTools: false }) + browser = await chromium.launch({ headless: true }) + }) + + afterAll(async () => { + try { + await browser?.close() + } finally { + await scaffold?.close() + } + }) + + it.each([ + { + locale: 'zh', browserLocale: ZH_BROWSER_LOCALE, theme: 'dark', + settings: '设置', close: '关闭', details: '工作步骤展示', compact: '简洁', detailed: '详细', + title: '工作步骤收起时机', completion: '回答结束后', nextInput: '下次有新消息时', + description: '选择何时自动收起工作步骤', + }, + { + locale: 'en', browserLocale: 'en-US', theme: 'light', + settings: 'Settings', close: 'Close', details: 'Work details', compact: 'Compact', detailed: 'Detailed', + title: 'When to Collapse Work Details', completion: 'On completion', nextInput: 'On next message', + description: 'Choose when to automatically collapse work details', + }, + ] 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() + onTestFailed(() => saveSettingsFailureShot(page, `settings-${copy.locale}`)) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await openSettings(page, copy.locale) + const dialog = page.getByRole('dialog', { name: copy.settings, exact: true }) + const details = dialog.getByText(copy.details, { exact: true }).locator('../..') + await details.getByRole('button').click() + expect(await page.getByRole('menuitem').count()).toBe(4) + // The persistence checks require an explicit saved mode, not the client's default. + await page.getByRole('menuitem', { name: copy.compact, exact: true }).click() + await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value, uiWait) + .toMatchObject({ transcriptView: 'compact' }) + await details.getByRole('button', { name: copy.compact, exact: true }).click() + await page.getByRole('menuitem', { name: copy.detailed, exact: true }).click() + await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value, uiWait) + .toMatchObject({ transcriptView: 'detailed' }) + await expect.poll(() => page.evaluate(() => document.body.hasAttribute('data-ds-dark-theme')), uiWait) + .toBe(copy.theme === 'dark') + const timing = dialog.getByText(copy.title, { exact: true }).locator('../..') + expect(await timing.count()).toBe(1) + expect(await timing.evaluate(element => element.previousElementSibling?.textContent)).toContain(copy.details) + await timing.getByText(copy.description, { exact: true }).waitFor() + await timing.getByRole('button', { name: copy.completion, exact: true }).waitFor() + let screenshotDir: string | undefined + if (MODE !== 'record') { + await mkdir(SCREENSHOT_DIR, { recursive: true }) + screenshotDir = await mkdtemp(join(SCREENSHOT_DIR, `settings-${copy.locale}-${copy.theme}-`)) + await page.screenshot({ path: join(screenshotDir, 'panel.png'), fullPage: true }) + } + + await page.evaluate(() => { + localStorage.setItem('collapse-timing-e2e-unrelated', 'retained') + sessionStorage.setItem('collapse-timing-e2e-unrelated', 'retained') + }) + const readPersistence = async (target: Page = page) => ({ + host: await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), + settings: structuredClone(scaffold.ctx.settings.describe({ redactSecrets: true }).map(({ ns, value }) => ({ ns, value }))), + storage: await target.evaluate(() => ({ + local: Object.fromEntries(Object.entries(localStorage)), + session: Object.fromEntries(Object.entries(sessionStorage)), + })), + }) + const before = await readPersistence() + const settingsWrites: string[] = [] + const recordSettingsWrite = (request: Request): void => { + const path = new URL(request.url()).pathname + if (request.method() === 'POST' && path === '/api/settings/mutate') settingsWrites.push(path) + } + context.on('request', recordSettingsWrite) + await timing.getByRole('button', { name: copy.completion, exact: true }).click() + await page.getByRole('menuitem', { name: copy.nextInput, exact: true }).waitFor() + expect(await page.getByRole('menuitem').allTextContents()).toEqual([copy.completion, copy.nextInput]) + await compareOrRefreshGolden( + join(SNAPSHOT_DIR, `collapse-timing-${copy.locale}.expected.md`), + await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd), + MODE, + ) + if (screenshotDir !== undefined) { + await page.screenshot({ path: join(screenshotDir, 'menu.png'), fullPage: true }) + } + const menu = page.getByRole('menu') + await page.keyboard.press('Escape') + await menu.waitFor({ state: 'hidden' }) + expect(await dialog.isVisible()).toBe(true) + await timing.getByRole('button', { name: copy.completion, exact: true }).waitFor() + await timing.getByRole('button').click() + await menu.waitFor() + await timing.getByText(copy.title, { exact: true }).click() + await menu.waitFor({ state: 'hidden' }) + expect(await dialog.isVisible()).toBe(true) + await timing.getByRole('button', { name: copy.completion, exact: true }).waitFor() + + await page.setViewportSize({ width: 640, height: 480 }) + await timing.getByRole('button').click() + await menu.waitFor() + await expect.poll(() => menu.evaluate((element) => { + const rect = element.getBoundingClientRect() + return { + fits: rect.width > 0 && rect.height > 0 + && rect.left > 0 && rect.top > 0 + && rect.right < window.innerWidth && rect.bottom < window.innerHeight, + uncovered: [...element.querySelectorAll('[role="menuitem"]')].every((item) => { + const bounds = item.getBoundingClientRect() + return item.contains(document.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2)) + }), + } + }), uiWait).toEqual({ fits: true, uncovered: true }) + if (screenshotDir !== undefined) { + await page.screenshot({ path: join(screenshotDir, 'menu-compact.png'), fullPage: true }) + } + await page.getByRole('menuitem', { name: copy.nextInput, exact: true }).click() + await menu.waitFor({ state: 'hidden' }) + await page.setViewportSize({ width: 1680, height: 1000 }) + await timing.getByRole('button', { name: copy.nextInput, exact: true }).waitFor() + 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(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.nextInput, exact: true }).waitFor() + acknowledgeReloadConnectionLoss(tripwire, warningStart) + expect(await readPersistence()).toEqual(saved) + if (screenshotDir !== undefined) { + await page.screenshot({ path: join(screenshotDir, 'reloaded.png'), fullPage: true }) + } + + const sharedPage = await context.newPage() + onTestFailed(() => saveSettingsFailureShot(sharedPage, `settings-${copy.locale}-shared-tab`)) + const sharedTripwire = watchConsole(sharedPage) + await sharedPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + 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.nextInput, exact: true }).waitFor() + const sharedPersistence = await readPersistence(sharedPage) + 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 }) + } + + const isolatedContext = await browser.newContext(contextOptions) + onTestFinished(() => isolatedContext.close()) + isolatedContext.on('request', recordSettingsWrite) + const isolatedPage = await isolatedContext.newPage() + onTestFailed(() => saveSettingsFailureShot(isolatedPage, `settings-${copy.locale}-isolated-context`)) + const isolatedTripwire = watchConsole(isolatedPage) + await isolatedPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + 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.nextInput, exact: true }).waitFor() + const isolatedPersistence = await readPersistence(isolatedPage) + 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(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() + 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([]) + expect(sharedTripwire.warnings).toEqual([]) + expect(isolatedTripwire.pageErrors).toEqual([]) + expect(isolatedTripwire.warnings).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/shipped-composition.e2e.ts b/apps/web/tests/shipped-composition.e2e.ts index 6eefe81171..9c7d827aba 100644 --- a/apps/web/tests/shipped-composition.e2e.ts +++ b/apps/web/tests/shipped-composition.e2e.ts @@ -689,9 +689,13 @@ it('lets a preset producer reach the background-job registry', async () => { }, agent: handle.agent, }) + const reported = started.content.map(block => block.type === 'text' ? block.text : '').join('') + const matched = /^started background job (bash-[0-9a-f]{16})$/.exec(reported) + if (matched === null) throw new Error(`background bash reported no job id: ${reported}`) + const jobId = matched[1] expect({ isError: started.isError, content: started.content }).toEqual({ isError: false, - content: [{ type: 'text', text: 'started background job bash-1' }], + content: [{ type: 'text', text: `started background job ${jobId}` }], }) // The controller reads what the producer started: same registry, one @@ -704,9 +708,8 @@ it('lets a preset producer reach the background-job registry', async () => { agent: handle.agent, }) expect(listed.isError).toBe(false) - expect(listed.content).toEqual([ - { type: 'text', text: expect.stringContaining('bash-1 [bash]') as unknown as string }, - ]) + expect(listed.content).toHaveLength(1) + expect(listed.content[0]?.type === 'text' ? listed.content[0].text : '').toContain(`${jobId} [bash]`) // The full round trip: the output a host-plane producer wrote is collected // through a preset-plane control, which is the linkage the realm severed. @@ -714,7 +717,7 @@ it('lets a preset producer reach the background-job registry', async () => { signal, callId: ToolCallId('shipped-task-output'), name: 'job_output', - arguments: { job_id: 'bash-1', wait: true }, + arguments: { job_id: jobId, wait: true }, agent: handle.agent, }) expect(collected.isError).toBe(false) diff --git a/apps/web/tests/shortcuts-desktop.e2e.ts b/apps/web/tests/shortcuts-desktop.e2e.ts index 9609e02de8..7560831694 100644 --- a/apps/web/tests/shortcuts-desktop.e2e.ts +++ b/apps/web/tests/shortcuts-desktop.e2e.ts @@ -9,7 +9,7 @@ import { SessionId } from '@deepseek-ai/dsh-session' import { initialShortcutConfig, parseShortcutDefinitions, parseShortcutEdit } from '@deepseek-ai/dsh-client-shortcuts/protocol' import type { DesktopShortcutInput, DesktopShortcutsApi, ShortcutCommandId, ShortcutRevision } from '@deepseek-ai/dsh-client-shortcuts/protocol' import { desktopKeybindings } from '../../desktop/src/keybindings.ts' -import { compareOrRefreshGolden, launchWebScaffold, seedSession, watchConsole, webSnapshotMode } from './scaffold.ts' +import { acknowledgeReloadConnectionLoss, compareOrRefreshGolden, launchWebScaffold, seedSession, watchConsole, webSnapshotMode } from './scaffold.ts' import { writeComposerDraft } from './support.ts' declare global { @@ -63,6 +63,12 @@ it.each([ } }) }, marker) const console = watchConsole(page) + const fontMutations: unknown[][] = [] + page.on('request', (request) => { + if (new URL(request.url()).pathname !== '/api/settings/mutate' || request.method() !== 'POST') return + const input = request.postDataJSON() as { payload: { args: { ns: string; ops: unknown[] } } } + if (input.payload.args.ns === 'ui-theme') fontMutations.push(input.payload.args.ops) + }) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) const deliverPrimary = (code: string, alt = false) => page.evaluate((input) => { window.shortcutFixture.deliver(input) @@ -131,6 +137,53 @@ it.each([ expect(await composer.innerText()).toBe('Desktop focus draft') await writeComposerDraft(page, composer, '') await expect.poll(() => composer.textContent()).toBe('') + const readFontSizes = () => page.evaluate(() => { + const style = document.body.style + return { + text: Number.parseInt(style.getPropertyValue('--dsh-content-font-size'), 10), + code: Number.parseInt(style.getPropertyValue('--dsh-code-font-size'), 10), + terminal: Number.parseInt(style.getPropertyValue('--dsh-terminal-font-size'), 10), + } + }) + const defaults = { text: 14, code: 11, terminal: 13 } + const patchPath = join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml') + const stepFontSizes = async (key: string, sizes: Awaited>): Promise => { + const before = fontMutations.length + const [response] = await Promise.all([ + page.waitForResponse((reply) => { + if (new URL(reply.url()).pathname !== '/api/settings/mutate' || reply.request().method() !== 'POST') return false + const input = reply.request().postDataJSON() as { payload: { args: { ns: string } } } + return input.payload.args.ns === 'ui-theme' + }), + page.keyboard.press(key), + ]) + expect(await response.finished()).toBeNull() + const envelope = await response.json() as { result: { ok: boolean } } + expect(envelope.result.ok).toBe(true) + const fields = [['fontSize', sizes.text], ['codeFontSize', sizes.code], ['terminalFontSize', sizes.terminal]] as const + expect(fontMutations.slice(before)).toEqual([fields.map(([field, value]) => ({ op: 'set', path: [field], value }))]) + await expect.poll(readFontSizes).toEqual(sizes) + for (const [field, value] of fields) { + await expect.poll(() => readFile(patchPath, 'utf8')).toContain(`${field}: ${value}`) + } + } + const initial = await readFontSizes() + expect(initial).toEqual(defaults) + await stepFontSizes(`${primary}+Equal`, { text: 15, code: 12, terminal: 14 }) + const afterEqual = await readFontSizes() + await stepFontSizes(`${primary}+Shift+Equal`, { text: 16, code: 13, terminal: 15 }) + const afterPlus = await readFontSizes() + await stepFontSizes(`${primary}+Minus`, { text: 15, code: 12, terminal: 14 }) + const afterMinus = await readFontSizes() + const warningStart = console.warnings.length + await page.reload({ waitUntil: 'load' }) + acknowledgeReloadConnectionLoss(console, warningStart) + await page.getByText('DONE', { exact: true }).waitFor() + await expect.poll(readFontSizes).toEqual(afterMinus) + const afterReload = await readFontSizes() + await composer.focus() + await stepFontSizes(`${primary}+Minus`, defaults) + const restored = await readFontSizes() const dialog = page.getByRole('dialog', { name: 'Keyboard shortcuts', exact: true }) const settings = page.getByRole('dialog', { name: 'Settings', exact: true }) const automaticFocusStyle = () => page.evaluate(() => { @@ -187,6 +240,12 @@ it.each([ expect(await dialog.isVisible()).toBe(false) await openReference() await dialog.waitFor() + const referenceOrder = await dialog.getByRole('listitem').evaluateAll(rows => rows + .map(row => row.querySelector(':scope > span')?.textContent) + .filter(label => label === 'Increase font size' || label === 'Decrease font size')) + expect(referenceOrder).toEqual(['Increase font size', 'Decrease font size']) + await compareOrRefreshGolden(join(expected, 'font-sizes.expected.md'), + `# Font sizes\n\n${JSON.stringify({ initial, afterEqual, afterPlus, afterMinus, afterReload, restored, referenceOrder }, null, 2)}`, mode) expect(await dialog.getByRole('searchbox').evaluate(node => node === document.activeElement)).toBe(true) expect(await automaticFocusStyle()).toEqual(noFocusRing) const referenceShadow = await dialog.evaluate(node => getComputedStyle(node).boxShadow) @@ -299,7 +358,8 @@ it.each([ await expect.poll(() => recorder.isEnabled()).toBe(true) await recorder.focus() const accepted = snapshot.document - for (const key of [`${primary}+Slash`, 'Escape', 'Enter', 'ArrowUp', 'ArrowDown', 'Shift+Enter', `${primary}+Enter`, 'Slash', 'Shift+Digit2']) { + const mutationsBeforeRecording = fontMutations.length + for (const key of [`${primary}+Equal`, `${primary}+Shift+Equal`, `${primary}+Minus`, `${primary}+Slash`, 'Escape', 'Enter', 'ArrowUp', 'ArrowDown', 'Shift+Enter', `${primary}+Enter`, 'Slash', 'Shift+Digit2']) { expect(await recorder.evaluate(node => node === document.activeElement)).toBe(true) const keys = key.split('+') for (const held of keys) await page.keyboard.down(held) @@ -310,6 +370,12 @@ it.each([ if (key === `${primary}+Slash`) { await dialog.getByText('Already used by “Open keyboard shortcuts”', { exact: true }).waitFor() } + if (key.endsWith('Equal') || key.endsWith('Minus')) { + const command = key.endsWith('Minus') ? 'Decrease font size' : 'Increase font size' + await dialog.getByText(`Already used by “${command}”`, { exact: true }).waitFor() + } + expect(await readFontSizes()).toEqual(defaults) + expect(fontMutations).toHaveLength(mutationsBeforeRecording) expect(await recorder.evaluate(node => node === document.activeElement)).toBe(true) expect(snapshot.document).toEqual(accepted) expect(await dialog.getByRole('listitem').evaluateAll(rows => rows.map(row => row.getBoundingClientRect().height))) diff --git a/apps/web/tests/shortcuts-workspace.e2e.ts b/apps/web/tests/shortcuts-workspace.e2e.ts index 3b1e0db1b0..3bb20a0e96 100644 --- a/apps/web/tests/shortcuts-workspace.e2e.ts +++ b/apps/web/tests/shortcuts-workspace.e2e.ts @@ -146,8 +146,11 @@ describe.skipIf(mode === 'record')('web e2e: workspace shortcuts', () => { await workspaceRow.getByText(workspaceLabel, { exact: true }).hover() await details.waitFor() await workspaceRow.getByRole('button', { name: `New session in ${workspaceLabel}`, exact: true }).hover() - await page.getByRole('tooltip').filter({ hasText: 'New Session' }).waitFor() - await expect.poll(() => details.count()).toBe(0) + const newSessionTooltip = page.getByRole('tooltip').filter({ hasText: 'New Session' }) + await newSessionTooltip.waitFor() + expect(await details.isVisible()).toBe(true) + expect(await newSessionTooltip.evaluate(element => Number(getComputedStyle(element).zIndex))) + .toBeGreaterThan(await details.evaluate(element => Number(getComputedStyle(element).zIndex))) await workspaceRow.getByText(workspaceLabel, { exact: true }).hover() await details.waitFor() await page.mouse.move(700, 100) diff --git a/apps/web/tests/shortcuts.e2e.ts b/apps/web/tests/shortcuts.e2e.ts index 7a49455c70..eadc973bff 100644 --- a/apps/web/tests/shortcuts.e2e.ts +++ b/apps/web/tests/shortcuts.e2e.ts @@ -19,9 +19,9 @@ describe('web e2e: shortcut reference', () => { afterAll(async () => { await browser?.close(); await scaffold?.close() }) it.each([ - { locale: 'zh-CN', platform: 'MacIntel', title: '快捷键', settings: '设置', view: '编辑快捷键', search: '搜索快捷键', key: 'Meta' }, - { locale: 'en-US', platform: 'Win32', title: 'Keyboard shortcuts', settings: 'Settings', view: 'Edit shortcuts', search: 'Search shortcuts', key: 'Control' }, - ])('opens, searches, and restores nested focus in $locale', async ({ locale, platform, title, settings, view, search, key }) => { + { locale: 'zh-CN', platform: 'MacIntel', title: '快捷键', accountMenu: '账号菜单', settings: '设置', view: '编辑快捷键', search: '搜索快捷键', key: 'Meta' }, + { locale: 'en-US', platform: 'Win32', title: 'Keyboard shortcuts', accountMenu: 'Account menu', settings: 'Settings', view: 'Edit shortcuts', search: 'Search shortcuts', key: 'Control' }, + ])('opens, searches, and restores nested focus in $locale', async ({ locale, platform, title, accountMenu, settings, view, search, key }) => { const referenceKey = platform === 'Win32' ? 'Control+Slash' : 'Meta+Slash' const context = await browser.newContext({ locale, colorScheme: 'light', viewport: { width: 1440, height: 1000 } }) try { @@ -31,12 +31,12 @@ describe('web e2e: shortcut reference', () => { const console = watchConsole(page) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) - const trigger = page.getByRole('button', { name: settings, exact: true }) - expect(await trigger.getAttribute('aria-keyshortcuts')).toBe(key === 'Meta' ? 'Alt+Meta+,' : 'Control+Alt+,') - const settingsHint = `${settings} ${key === 'Meta' ? '⌥ ⌘ ,' : 'Ctrl + Alt + ,'}` - await trigger.hover() - await page.getByRole('tooltip', { name: settingsHint, exact: true }).waitFor() + const trigger = page.getByRole('button', { name: accountMenu, exact: true }) await trigger.click() + const settingsItem = page.getByRole('menuitem', { name: settings, exact: true }) + expect(await settingsItem.getAttribute('aria-keyshortcuts')).toBe(key === 'Meta' ? 'Alt+Meta+,' : 'Control+Alt+,') + expect(await settingsItem.innerText()).toMatch(key === 'Meta' ? /⌥\s*⌘\s*,$/ : /Ctrl\s*\+\s*Alt\s*\+\s*,$/) + await settingsItem.click() await page.getByRole('button', { name: view, exact: true }).click() const dialog = page.getByRole('dialog', { name: title, exact: true }) await dialog.waitFor() @@ -297,10 +297,11 @@ describe('web e2e: shortcut reference', () => { await page.keyboard.press(`${key}+Shift+Comma`) await dialog.getByRole('group').waitFor({ state: 'hidden' }) await page.keyboard.press('Escape') - expect(await trigger.getAttribute('aria-keyshortcuts')).toBe(key === 'Meta' ? 'Shift+Meta+,' : 'Control+Shift+,') - await trigger.hover() - await page.getByRole('tooltip', { name: `${settings} ${key === 'Meta' ? '⇧ ⌘ ,' : 'Ctrl + Shift + ,'}`, exact: true }).waitFor() await trigger.click() + expect(await settingsItem.getAttribute('aria-keyshortcuts')).toBe(key === 'Meta' ? 'Shift+Meta+,' : 'Control+Shift+,') + expect(await settingsItem.innerText()).toMatch(key === 'Meta' ? /⇧\s*⌘\s*,$/ : /Ctrl\s*\+?\s*Shift\s*\+?\s*,$/) + await settingsItem.click() + await page.getByRole('dialog', { name: settings, exact: true }).waitFor() await page.keyboard.press('Escape') expect(await trigger.evaluate(element => element === document.activeElement)).toBe(true) await page.keyboard.press(referenceKey) @@ -308,9 +309,10 @@ describe('web e2e: shortcut reference', () => { await dialog.getByRole('button', { name: locale === 'zh-CN' ? '恢复默认' : 'Restore default', exact: true }).click() await dialog.getByRole('group').waitFor({ state: 'hidden' }) await page.keyboard.press('Escape') - expect(await trigger.getAttribute('aria-keyshortcuts')).toBe(key === 'Meta' ? 'Alt+Meta+,' : 'Control+Alt+,') - await trigger.hover() - await page.getByRole('tooltip', { name: settingsHint, exact: true }).waitFor() + await trigger.click() + expect(await settingsItem.getAttribute('aria-keyshortcuts')).toBe(key === 'Meta' ? 'Alt+Meta+,' : 'Control+Alt+,') + await page.keyboard.press('Escape') + await settingsItem.waitFor({ state: 'detached' }) const sidebar = page.getByRole('button', { name: locale === 'zh-CN' ? '收起侧边栏' : 'Collapse sidebar', exact: true }) expect(await sidebar.getAttribute('aria-keyshortcuts')).toBe(key === 'Meta' ? 'Alt+Meta+B' : 'Control+Alt+B') await page.reload({ waitUntil: 'load' }) @@ -390,7 +392,7 @@ describe('web e2e: shortcut reference', () => { await context.addInitScript((value) => { Object.defineProperty(navigator, 'platform', { value }) }, platform) const page = await context.newPage() await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await page.getByRole('button', { name: 'Settings', exact: true }).waitFor() + await page.getByRole('button', { name: 'Account menu', exact: true }).waitFor() const referenceKey = `${modifier}+Slash` const open = async () => { await page.keyboard.press(referenceKey) @@ -412,7 +414,7 @@ describe('web e2e: shortcut reference', () => { await page.keyboard.press(sidebarKey) await page.getByRole('button', { name: 'Open sidebar', exact: true }).waitFor() await page.reload({ waitUntil: 'load' }) - await page.getByRole('button', { name: 'Settings', exact: true }).waitFor() + await page.getByRole('button', { name: 'Account menu', exact: true }).waitFor() const toggleAfterReload = page.getByRole('button', { name: /^(Open|Collapse) sidebar$/ }) await expect.poll(() => toggleAfterReload.getAttribute('aria-keyshortcuts')) .toBe(modifier === 'Meta' ? 'Shift+Meta+.' : 'Control+Shift+.') @@ -427,7 +429,7 @@ describe('web e2e: shortcut reference', () => { await editor.getByRole('button', { name: 'Press a shortcut', exact: true }).focus() const other = await context.newPage() await other.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await other.getByRole('button', { name: 'Settings', exact: true }).waitFor() + await other.getByRole('button', { name: 'Account menu', exact: true }).waitFor() await other.keyboard.press(referenceKey) await other.getByRole('button', { name: 'Edit shortcut for Toggle left sidebar', exact: true }).click() await other.getByRole('button', { name: 'Remove', exact: true }).click() diff --git a/apps/web/tests/sidebar-terminal.e2e.ts b/apps/web/tests/sidebar-terminal.e2e.ts index 80562071ad..a8173b6d27 100644 --- a/apps/web/tests/sidebar-terminal.e2e.ts +++ b/apps/web/tests/sidebar-terminal.e2e.ts @@ -286,6 +286,10 @@ describe.skipIf(process.platform === 'win32')('Web sidebar terminal', () => { it('completes commands, preserves the process through collapse and reload, resizes, and kills on tab close', async () => { onTestFailed(() => saveFailureShot(page, 'sidebar-terminal')) + const unaryInput: string[] = [] + page.on('request', (request) => { + if (/\/api\/terminal\/(write|resize|follow)$/u.test(new URL(request.url()).pathname)) unaryInput.push(request.url()) + }) await openTerminal(page) const terminal = page.locator('[data-sidebar-terminal]') await command(page, "PS1=''; printf '\\033cTERMINAL_READY\\n'") @@ -370,6 +374,7 @@ describe.skipIf(process.platform === 'win32')('Web sidebar terminal', () => { await expect.poll(() => alive(firstProcess), { timeout: 10_000 }).toBe(false) await expect.poll(() => descendants.some(alive), { timeout: 10_000 }).toBe(false) await expect.poll(() => scaffold.ctx.terminalController.list(scaffold.ctx.agents.list()[0]!.id).length).toBe(0) + expect(unaryInput).toEqual([]) expect(tripwire.pageErrors).toEqual([]) }) @@ -554,6 +559,107 @@ describe.skipIf(process.platform === 'win32')('Web sidebar terminal', () => { expect(tripwire.pageErrors).toEqual([]) }) + it('validates terminal uplink frames and keeps a read-only attachment following output', async () => { + await openTerminal(page) + const sessionId = scaffold.ctx.agents.list()[0]!.id + const terminalId = scaffold.ctx.terminalController.list(sessionId)[0]!.id + const result = await page.evaluate(async ({ sessionId, terminalId }) => { + const socket = new WebSocket(new URL('/api/remote.mux', location.href).href.replace(/^http/u, 'ws')) + const frames: { + type: string + streamId: string + value?: { + type: string + data?: string + sequence?: number + writable?: boolean + refusal?: string + inputWindow?: { maxBytes: number; frameOverheadBytes: number } + } + error?: { code: string } + }[] = [] + const waiters = new Set<() => void>() + socket.addEventListener('message', (event) => { + frames.push(JSON.parse(String(event.data)) as (typeof frames)[number]) + for (const wake of waiters) wake() + }) + const wait = async (predicate: () => boolean) => { + if (predicate()) return + await new Promise((resolve, reject) => { + const timer = setTimeout(() => { waiters.delete(inspect); reject(new Error('Terminal wire event timed out')) }, 10_000) + const inspect = () => { if (predicate()) { clearTimeout(timer); waiters.delete(inspect); resolve() } } + waiters.add(inspect) + }) + } + const send = (frame: object) => { socket.send(JSON.stringify(frame)) } + const open = (streamId: string) => { send({ type: 'open', streamId, endpoint: 'terminal/attach', payload: { args: { agentId: sessionId, id: terminalId } } }) } + await new Promise((resolve, reject) => { + socket.addEventListener('open', () => { resolve() }, { once: true }) + socket.addEventListener('error', () => { reject(new Error('Terminal socket failed')) }, { once: true }) + }) + try { + open('first') + await wait(() => frames.some(frame => frame.streamId === 'first' && frame.value?.type === 'snapshot')) + open('second') + await wait(() => frames.some(frame => frame.streamId === 'second' && frame.value?.type === 'snapshot')) + send({ type: 'item', streamId: 'first', value: { type: 'write', sequence: 1, data: 'IGNORED' } }) + await wait(() => frames.some(frame => frame.streamId === 'first' && frame.value?.type === 'ack')) + send({ type: 'item', streamId: 'second', value: { type: 'write', sequence: 1, data: "printf 'DUPLEX_%s\\n' PROOF\r" } }) + await wait(() => frames.filter(frame => frame.streamId === 'first').map(frame => frame.value?.data ?? '').join('').includes('DUPLEX_PROOF')) + send({ type: 'item', streamId: 'second', value: { type: 'write', sequence: 2, data: 42 } }) + await wait(() => frames.some(frame => frame.streamId === 'second' && frame.type === 'error')) + return frames + } finally { + socket.close() + await new Promise((resolve) => { socket.addEventListener('close', () => { resolve() }, { once: true }) }) + } + }, { sessionId, terminalId }) + const window = result.find(frame => frame.streamId === 'first' && frame.value?.type === 'snapshot')?.value?.inputWindow + expect(window).toEqual({ + maxBytes: 262_144, + frameOverheadBytes: Buffer.byteLength(JSON.stringify({ type: 'item', streamId: 'first', value: null }), 'utf8') - 'null'.length, + }) + expect(result.some(frame => frame.streamId === 'first' && frame.value?.type === 'state' && !frame.value.writable)).toBe(true) + expect(result.find(frame => frame.streamId === 'first' && frame.value?.type === 'ack')?.value) + .toEqual({ type: 'ack', sequence: 1, refusal: 'read-only' }) + expect(result.find(frame => frame.streamId === 'second' && frame.type === 'error')?.error?.code).toBe('gateway/input-invalid') + expect(handles).toHaveLength(1) + expect(tripwire.pageErrors).toEqual([]) + }) + + it('delivers a short-key burst through the real mux while the provider pauses input', async () => { + onTestFailed(() => saveFailureShot(page, 'sidebar-terminal-input-window')) + await openTerminal(page) + const handle = handles[0]! + const write = handle.write.bind(handle) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const burst = `printf 'BUFFER_%s\\n' OK # ${'a'.repeat(3000)}` + let delivered = '' + const paused = vi.spyOn(handle, 'write').mockImplementation(async (data) => { + entered.resolve(undefined) + await release.promise + await write(data) + delivered += data + }) + try { + await page.locator('.xterm-helper-textarea:visible').click() + await page.keyboard.type(burst) + await page.keyboard.press('Enter') + await entered.promise + expect(paused).toHaveBeenCalledTimes(1) + release.resolve(undefined) + // The concurrent browser lane needs separate completion waits for queued input and rendered output. + await expect.poll(() => delivered.endsWith('\r'), { timeout: 30_000, message: 'The queued Enter must reach the PTY' }).toBe(true) + expect(delivered).toBe(`${burst}\r`) + await page.locator('.xterm-rows:visible').filter({ hasText: 'BUFFER_OK' }).waitFor({ timeout: 30_000 }) + expect(handles).toHaveLength(1) + expect(tripwire.pageErrors).toEqual([]) + } finally { + release.resolve(undefined) + } + }) + it('offers reconnection after transport loss and resumes the same process without a new terminal', async () => { onTestFailed(() => saveFailureShot(page, 'sidebar-terminal-reconnect')) await openTerminal(page) diff --git a/apps/web/tests/skill-invocation-policy.e2e.ts b/apps/web/tests/skill-invocation-policy.e2e.ts index 9723ae3494..bc77481b99 100644 --- a/apps/web/tests/skill-invocation-policy.e2e.ts +++ b/apps/web/tests/skill-invocation-policy.e2e.ts @@ -140,6 +140,7 @@ describe('web e2e: skill invocation policy through the real host', () => { await option.click() const skill = input.locator('[data-composer-text-ref]').filter({ hasText: '/policy-shared' }) const file = input.locator('[data-composer-chip]') + await file.locator('span').first().waitFor({ state: 'visible' }) const draft = await input.textContent() const alignment = await input.evaluate((el) => { const skill = el.querySelector('[data-composer-text-ref]')! 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/standalone-string-editor.e2e.ts b/apps/web/tests/standalone-string-editor.e2e.ts index 79e1efed80..a04dc6e96c 100644 --- a/apps/web/tests/standalone-string-editor.e2e.ts +++ b/apps/web/tests/standalone-string-editor.e2e.ts @@ -1,4 +1,4 @@ -/** A standalone tool in a custom scoped patch reaches the PTC SDK and a persisted Session. */ +/** A standalone global tool from a custom Host patch reaches the PTC SDK and a persisted Session. */ import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { fileURLToPath } from 'node:url' @@ -32,8 +32,7 @@ describe('web snapshot: standalone string editor through PTC', () => { compareReplaySession: true, ...(MODE === 'record' ? {} : { replayFixture: FIXTURE }), }) - expect((await scaffold.ctx.agentPresets.compositionInventory()).find(preset => preset.id === 'ptc')?.rows - .some(row => row.moduleName === '@deepseek-ai/dsh-tool-str-replace-editor')).toBe(true) + expect(scaffold.ctx.tools.schemas().some(tool => tool.name === 'str_replace_editor')).toBe(true) browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) diff --git a/apps/web/tests/standalone-string-editor.overlay.yml b/apps/web/tests/standalone-string-editor.overlay.yml index 7522f1800c..78d68e1f1f 100644 --- a/apps/web/tests/standalone-string-editor.overlay.yml +++ b/apps/web/tests/standalone-string-editor.overlay.yml @@ -1,4 +1,3 @@ -- preset: preset-ptc - insert: +- insert: - id: optional-tool-str-replace-editor name: '@deepseek-ai/dsh-tool-str-replace-editor' diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index 6b6cd918b7..2324f0ae2b 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -1,10 +1,11 @@ -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { fileURLToPath } from 'node:url' -import { join } from 'node:path' +import { dirname, join } from 'node:path' +import { zstdCompressSync } from 'node:zlib' import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' -import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { afterAll, beforeAll, describe, expect, it, onTestFailed, vi } from 'vitest' import { prepareSessionSnapshotFixtureForComparison } from '@deepseek-ai/dsh-llm-replay' import { SESSION_FORMAT_VERSION, SessionId as sessionId, SessionLogOffset, SessionSeq, @@ -12,10 +13,11 @@ import { } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-agent' import { snapshotSubagentDescriptor, SUBAGENT_DESCRIPTOR_VERSION } from '@deepseek-ai/dsh-subagent' +import { checkpointRecord, projectionCacheDomainSpec } from '@deepseek-ai/dsh-session-projection-cache' import { acknowledgeReloadConnectionLoss, captureExpandedTurnProcessAria, captureStableAria, compareOrRefreshGolden, - launchWebScaffold, readPersistedEvents, selectedSessionFixture, watchConsole, + launchWebScaffold, readPersistedEvents, realizeSeedFixture, seedSession, selectedSessionFixture, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { connectFreshWorkspace, newEnglishPage, saveFailureShot, writeComposerDraft } from './support.ts' @@ -32,6 +34,9 @@ const SIDEBAR_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent- const SIDEBAR_CHAT_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/sidebar-chat.expected.md', import.meta.url)) const UNAVAILABLE_GRANDCHILD_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/nested.expected.md', import.meta.url)) const FORK_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/fork.expected.md', import.meta.url)) +const MIGRATING_CHILD_EXPECTED = fileURLToPath(new URL( + './expected/subagent-conversation/migration-required-child.expected.md', import.meta.url, +)) const MODE = webSnapshotMode() const LABEL = 'event-sourcing researcher' const ONE_SHOT_LABEL = 'event-sourcing reviewer' @@ -120,6 +125,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = paceMs: 25, }) browser = await chromium.launch() + await mkdir(fileURLToPath(new URL('../../../.artifacts/screenshots/non-migrating-session-reads', import.meta.url)), { recursive: true }) page = await newEnglishPage(browser) page.on('request', (request) => { const path = new URL(request.url()).pathname @@ -320,6 +326,13 @@ describe('web e2e: persisted subagent conversation and human continuation', () = }, ]) } + await waitForCacheRow(scaffold, childHeader) + const cache = scaffold.ctx.storageDomain.get(projectionCacheDomainSpec.name) + if (cache === undefined) throw new Error('projection cache is not open') + const table = cache.table('sessions') + const record = checkpointRecord.parse(table.get(childId)) + const { subagentCatalog: _catalog, ...rows } = record.rows + await table.put(childId, { ...record, rows }) // These two cold fixtures were authored after the page's initial // session.list and intentionally emitted no api-session/added event. Reload // to exercise the restart baseline that discovers their full lineage. @@ -362,8 +375,8 @@ describe('web e2e: persisted subagent conversation and human continuation', () = await writeComposerDraft(page, input, '') }) - it('expands a persisted grandchild progressively without activating either level', async () => { - onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-tree')) + it('recovers a current-format cold child catalog cache miss without activating either level', async () => { + onTestFailed(() => saveFailureShot(page, 'screenshots/non-migrating-session-reads/web-e2e-subagent-tree')) await page.getByRole('button', { name: '2 subagents' }).hover() const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' }) expect(await catalogTree.evaluate((element) => { @@ -379,12 +392,22 @@ describe('web e2e: persisted subagent conversation and human continuation', () = expect(await oneShotRow.locator('[data-state="done"]').count()).toBe(1) expect(await oneShotRow.getByText('~6mo 12d', { exact: true }).count()).toBe(1) expect(await oneShotRow.getAttribute('aria-label')).toContain('192d 00h 00m 00s') - await page.getByRole('button', { name: `Expand ${LABEL} descendants` }).click() + const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession') + try { + const projections = page.waitForResponse(response => new URL(response.url()).pathname === '/api/session/projections') + await page.getByRole('button', { name: `Expand ${LABEL} descendants` }).click() + await projections + await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ timeout: 15_000 }) + expect(observe.mock.calls.some(([id]) => id === childId)).toBe(true) + expect(observe.mock.calls.some(([id]) => id === grandchildId)).toBe(false) + } finally { + observe.mockRestore() + } const childRow = page.getByRole('treeitem', { name: new RegExp(LABEL) }) const childLabel = await childRow.getAttribute('aria-label') await page.waitForTimeout(1_100) expect(await childRow.getAttribute('aria-label')).toBe(childLabel) - await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ timeout: 15_000 }) + expect(await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).textContent()).toContain('continuable') expect(scaffold.ctx.agents.get(childId)).toBeUndefined() expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined() const snapshot = await captureStableAria( @@ -544,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), @@ -657,3 +680,143 @@ describe('web e2e: persisted subagent conversation and human continuation', () = await expect.poll(() => scaffold.ctx.agents.get(childId), { timeout: 10_000 }).toBeUndefined() }) }) + +describe('web e2e: migration-required subagent catalog', () => { + const parentId = sessionId('migration-catalog-parent') + const childId = sessionId('migration-catalog-child') + const grandchildId = sessionId('migration-catalog-grandchild') + const childLabel = 'historical researcher' + const grandchildLabel = 'historical editor' + const predecessors: { id: SessionId; directory: string; path: string; source: Buffer }[] = [] + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + if (MODE === 'record') throw new Error('migration-required subagent catalog is a keyless assembled snapshot') + scaffold = await launchWebScaffold() + const fixture = await readFile(BASE_FIXTURE, 'utf8') + const createdAt = 1784998084442 + await seedSession(scaffold, fixture, parentId, undefined, { createdAt }) + const parentHandle = await scaffold.ctx.sessionPersistence.open(parentId, 'write') + try { + const { events } = await parentHandle.read() + const last = events.at(-1) + if (last === undefined) throw new Error('parent seed has no events') + await parentHandle.append([{ + type: 'subagent/catalog', seq: SessionSeq(last.seq + 1), time: last.time + 1, + data: { version: 1, childId, childCreatedAt: createdAt + 1, mode: 'continuable', label: childLabel }, + }]) + } finally { + await parentHandle.close() + } + const projects = (await readdir(scaffold.persistenceRoot, { withFileTypes: true })).filter(entry => entry.isDirectory()) + expect(projects).toHaveLength(1) + const project = projects[0] + if (project === undefined) throw new Error('parent seed has no project directory') + // Keep historical bytes on disk; seeding through the writer would migrate them before the browser opens. + for (const [id, parentSession, label, depth] of [ + [childId, parentId, childLabel, 1], + [grandchildId, childId, grandchildLabel, 2], + ] as const) { + const [header, ...events] = realizeSeedFixture(scaffold, fixture, id).trimEnd().split('\n') + .map((line): Record => JSON.parse(line) as Record) + expect(header?.version).toBe(3) + const body = [ + ...events, + { type: 'subagent/descriptor', data: snapshotSubagentDescriptor({ mode: 'continuable', provider: 'spawn', label }) }, + ...id === childId ? [{ + type: 'subagent/catalog', + data: { version: 0, childId: grandchildId, childCreatedAt: createdAt + 2, mode: 'continuable', label: grandchildLabel }, + }] : [], + ] + const rows = [ + { ...header, id, createdAt: createdAt + depth, cwd: scaffold.workspaceCwd, parentSession, origin: 'subagent', delegationDepth: depth }, + ...body.map((event, seq) => ({ ...event, seq, time: createdAt + depth + seq + 1 })), + ] + const directory = join(scaffold.persistenceRoot, project.name, id) + const path = join(directory, 'session.v3.jsonl.zstd') + const source = Buffer.concat(rows.map(row => zstdCompressSync(Buffer.from(`${JSON.stringify(row)}\n`)))) + await mkdir(directory, { recursive: true }) + await writeFile(path, source) + predecessors.push({ id, directory, path, source }) + } + for (const { id } of predecessors) { + const stored = await scaffold.ctx.sessionPersistence.stat(id) + expect(stored?.formatStatus).toBe('migration-required') + if (stored === undefined) throw new Error(`historical fixture ${id} is missing`) + expect(scaffold.ctx.sessionProjectionCache.cachedSnapshot(stored.header)).toBeUndefined() + } + browser = await chromium.launch() + page = await newEnglishPage(browser) + tripwire = watchConsole(page) + }) + + afterAll(async () => { + const failures: unknown[] = [] + await browser?.close().catch((error: unknown) => failures.push(error)) + await scaffold?.close().catch((error: unknown) => failures.push(error)) + if (failures.length === 1) throw failures[0] + if (failures.length > 1) throw new AggregateError(failures, 'migration-required subagent Web teardown failed') + }) + + it('stops at a migration-required child until its history opens', async () => { + onTestFailed(() => saveFailureShot(page, 'screenshots/non-migrating-session-reads/migration-required-subagent')) + const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession') + const projections = vi.spyOn(scaffold.ctx.sessionController, 'projections') + const model = vi.spyOn(scaffold.ctx.llm, 'stream') + try { + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + const workspaceRow = page.getByRole('tree', { name: 'Sessions' }).getByRole('treeitem').first() + await workspaceRow.click() + await page.locator(`[data-row-key="session:${parentId}"]`).click() + await page.getByRole('button', { name: '1 subagent', exact: true }).hover() + const tree = page.getByRole('tree', { name: 'Subagent sessions' }) + const childRow = tree.getByRole('treeitem', { name: new RegExp(childLabel) }) + await childRow.waitFor() + await expect.poll(() => childRow.textContent()).toContain('Migration required') + await expect.poll(() => childRow.getByRole('button', { name: `Expand ${childLabel} descendants`, exact: true }).count()).toBe(0) + expect(await childRow.getAttribute('aria-expanded')).toBeNull() + expect(await childRow.textContent()).toContain('Migration required') + expect(await childRow.textContent()).not.toContain('unknown mode') + expect(await childRow.getByRole('button', { name: `Open ${childLabel} in sidebar`, exact: true }).isEnabled()).toBe(true) + expect(await tree.getByRole('treeitem').count()).toBe(1) + for (const { id, directory, path, source } of predecessors) { + expect(scaffold.ctx.agents.get(id)).toBeUndefined() + expect(await readdir(directory)).toEqual(['session.v3.jsonl.zstd']) + expect(await readFile(path)).toEqual(source) + } + const before = await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd) + expect(observe.mock.calls.some(([id]) => id === childId || id === grandchildId)).toBe(false) + expect(projections).not.toHaveBeenCalled() + + await childRow.click() + await page.getByRole('button', { name: `Switch subagent: ${childLabel}`, exact: true }).waitFor() + await page.getByRole('button', { name: '1 subagent', exact: true }).hover() + const grandchildRow = tree.getByRole('treeitem', { name: new RegExp(grandchildLabel) }) + await grandchildRow.waitFor() + expect(await grandchildRow.textContent()).toContain('Migration required') + expect(await grandchildRow.getAttribute('aria-expanded')).toBeNull() + expect(await grandchildRow.getByRole('button', { name: `Expand ${grandchildLabel} descendants`, exact: true }).count()).toBe(0) + expect(projections).not.toHaveBeenCalled() + expect(observe.mock.calls.some(([id]) => id === childId)).toBe(true) + const after = await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd) + if (MODE === 'refresh') await mkdir(dirname(MIGRATING_CHILD_EXPECTED), { recursive: true }) + await compareOrRefreshGolden(MIGRATING_CHILD_EXPECTED, + `# Before opening the child\n\n${before}\n\n# After opening the child\n\n${after}`, MODE) + for (const { id, path, source } of predecessors) { + expect(scaffold.ctx.agents.get(id)).toBeUndefined() + expect(await readFile(path)).toEqual(source) + } + expect(observe.mock.calls.some(([id]) => id === grandchildId)).toBe(false) + expect(model).not.toHaveBeenCalled() + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } finally { + projections.mockRestore() + model.mockRestore() + observe.mockRestore() + } + }) +}) diff --git a/apps/web/tests/subagent-fork-schedule.snapshot.ts b/apps/web/tests/subagent-fork-schedule.snapshot.ts new file mode 100644 index 0000000000..62f42cb69a --- /dev/null +++ b/apps/web/tests/subagent-fork-schedule.snapshot.ts @@ -0,0 +1,105 @@ +/** Forked Web agents inherit the standard preset and refuse every reminder tool. */ +import { readFile, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { expect, it } from 'vitest' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { parseSessionLog, prepareSessionSnapshotFixtureForComparison } from '@deepseek-ai/dsh-llm-replay' +import type { Session } from '@deepseek-ai/dsh-session' +import { + fixtureContext, normalizeSessionSnapshots, normalizedSystemPrompts, normalizedToolSchemas, + formatSystemPromptSnapshot, parseToolSchemasSnapshot, redactSessionSnapshotIds, refreshFixtureReplacements, + scrubSessionSnapshot, stabilizeFixtureMessageIds, stabilizeRefreshLog, tokenizeSessionFixtureCwd, +} from '@deepseek-ai/dsh-session-snapshot' +import type {} from '@deepseek-ai/dsh-api-session-controller' +import type {} from '@deepseek-ai/dsh-schedule' +import type {} from '@deepseek-ai/dsh-subagent' +import { + fixtureUserPrompts, launchWebScaffold, normalizeWebSessionVolatiles, rawSessionLog, readPersistedEvents, + recordedSessionFixturePath, selectedSessionFixture, webSnapshotMode, +} from './scaffold.ts' +import { REPO_ROOT } from './support.ts' + +const DIR = fileURLToPath(new URL('../../../snapshots/web/subagent-fork-schedule', import.meta.url)) +const PIN = join(DIR, '../fresh-round-trip') +const MODE = webSnapshotMode() + +it.skipIf(MODE === 'record')('replays inherited schedule tools and refusals in a seeded Web fork', async () => { + const paths = await Promise.all(['session.v4.jsonl', 'session.1.v4.jsonl'] + .map(file => selectedSessionFixture(join(DIR, file)))) + let expected = await Promise.all(paths.map(path => readFile(path, 'utf8'))) + const scaffold = await launchWebScaffold({ + replayFixture: paths[0]!, replayChildFixtures: [paths[1]!], compareReplaySession: false, + }) + try { + const sessions: Session[] = [] + scaffold.ctx.on('session/created', (session) => { sessions.push(session) }) + const { sessionId } = await scaffold.ctx.sessionController.create({ cwd: scaffold.workspaceCwd }) + const parent = scaffold.ctx.agents.get(sessionId) + if (parent === undefined) throw new Error('created parent has no Agent') + const prompt = fixtureUserPrompts(expected[0]!)[0] + if (prompt === undefined) throw new Error('parent fixture has no user prompt') + parent.followup(createUserMessage({ content: [{ type: 'text', text: prompt }], source: { kind: 'user' } })) + await parent.whenIdle() + + const childPrompt = parseSessionLog(expected[1]!).findLast(event => event.type === 'user/message' + && event.data.source.kind === 'user') + if (childPrompt?.type !== 'user/message') throw new Error('child fixture has no user prompt') + const activation = await scaffold.ctx.subagents.startActivation({ + provider: 'fork', label: 'Check child reminder refusal', delivery: 'caller', + signal: new AbortController().signal, + request: { parent, prompt: [...childPrompt.data.content] }, + }) + try { + await activation.result + } finally { + await activation.dispose() + } + await scaffold.ctx.sessions.flush(parent.session) + expect(sessions).toHaveLength(2) + const child = sessions[1]! + expect(child.header).toMatchObject({ parentSession: parent.id, isSeeded: true, agentPreset: 'standard' }) + expect(child.inheritedEventCount).toBeGreaterThan(0) + expect(child.requestHeader()).toEqual(parent.session.requestHeader()) + + for (const session of sessions) { + expect(await readPersistedEvents(scaffold, session.id)).toEqual(session.snapshotEvents()) + } + const raw = sessions.map(session => normalizeWebSessionVolatiles(rawSessionLog(session), scaffold.workspaceCwd)) + const context = { sessionIds: sessions.map(session => String(session.id)), cwd: scaffold.workspaceCwd } + const schemas = parseToolSchemasSnapshot(await readFile(join(PIN, 'tool-schemas.expected.json'), 'utf8')) + const promptPin = await readFile(join(PIN, 'system-prompt.expected.md'), 'utf8') + for (const log of raw) { + const headers = normalizedToolSchemas(log, context) + expect(headers.length).toBeGreaterThan(0) + for (const tools of headers) expect(tools).toEqual(schemas.initial) + for (const prompt of normalizedSystemPrompts(log, context)) { + expect(formatSystemPromptSnapshot(prompt.split(REPO_ROOT).join('{{sourceRoot}}') + .split(scaffold.baseUrl).join('{{webUrl}}'))).toBe(promptPin) + } + } + const results = child.snapshotEvents().slice(child.inheritedEventCount) + .filter(event => event.type === 'tool/result') + expect(results.map(event => event.data.message.content)).toEqual(Array.from({ length: 4 }, () => [ + { type: 'text', text: '{"code":"subagent_session","message":"A delegated subagent cannot use reminders."}' }, + ])) + expect(await scaffold.ctx.schedule.list({ sessionId: child.id })).toEqual([]) + + if (MODE === 'refresh') { + const replacements = refreshFixtureReplacements(raw.map((content, index) => ({ + id: sessions[index]!.id, createdAt: sessions[index]!.header.createdAt, content, + })), expected) + expected = redactSessionSnapshotIds(stabilizeFixtureMessageIds(raw.map((log, index) => + tokenizeSessionFixtureCwd(scrubSessionSnapshot(stabilizeRefreshLog( + prepareSessionSnapshotFixtureForComparison(log), expected[index]!, replacements, context, + ))).split(scaffold.harnessHome).join('{{harnessHome}}')), expected)) + await Promise.all(expected.map((log, index) => writeFile( + recordedSessionFixturePath(paths[index]!, sessions[index]!.header.version), log, + ))) + } + expect(normalizeSessionSnapshots(raw, context)) + .toEqual(normalizeSessionSnapshots(expected, fixtureContext(expected[0]!))) + } finally { + await scaffold.close() + } +}) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index 021b10e569..d60a81dba5 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -327,16 +327,11 @@ export function conversationContextKey(kind: string, id: string): string { return `${kind.length}:${kind}${id}` } -/** Open Settings through the Web gear or Desktop account menu. +/** Open Settings through the sidebar account menu. * @param page - browser page with the mounted sidebar. * @param locale - current UI language. */ export async function openSettings(page: Page, locale: 'en' | 'zh'): Promise { - const label = locale === 'zh' ? '设置' : 'Settings' - if (await page.evaluate(() => 'dshDesktop' in globalThis)) { - await page.getByRole('button', { name: locale === 'zh' ? '账号菜单' : 'Account menu', exact: true }).click() - await page.getByRole('menuitem', { name: label, exact: true }).click() - } else { - await page.getByRole('button', { name: label, exact: true }).click() - } + await page.getByRole('button', { name: locale === 'zh' ? '账号菜单' : 'Account menu', exact: true }).click() + await page.getByRole('menuitem', { name: locale === 'zh' ? '设置' : 'Settings', exact: true }).click() } 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..1ed57cde75 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, @@ -507,21 +507,21 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo * blank Session from a deleted Workspace may also be visible, without actions. * @returns the session row locator, already present. */ - async function seededSessionRow() { - const ungroupedRow = page.getByText('Ungrouped', { exact: true }).locator('..').locator('..') + async function seededSessionRow(target = page) { + const ungroupedRow = target.getByText('Ungrouped', { exact: true }).locator('..').locator('..') const ungroupedSection = ungroupedRow.locator('..') // Initial-current auto-expansion can race this gesture; converge on // expanded rather than assuming which update wins first. await expect.poll(async () => { if (await ungroupedRow.getAttribute('aria-expanded') !== 'true') { - await page.getByText('Ungrouped', { exact: true }).click() - await page.waitForTimeout(50) + await target.getByText('Ungrouped', { exact: true }).click() + await target.waitForTimeout(50) } return await ungroupedRow.getAttribute('aria-expanded') }, { timeout: 5_000 }).toBe('true') // CSS includes the actions button while it is hidden until row hover. const rows = ungroupedSection.locator('[role="treeitem"]') - .filter({ has: page.locator('button[aria-label^="Session actions for "]') }) + .filter({ has: target.locator('button[aria-label^="Session actions for "]') }) await expect.poll(() => rows.count(), { timeout: 10_000 }).toBe(1) return rows.first() } @@ -556,11 +556,247 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo expect(await copied.isVisible()).toBe(true) expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(rowTitle) // Leaving anchor and card together closes it after the grace. - await page.getByRole('button', { name: 'Settings' }).hover() + await page.getByRole('button', { name: 'Account menu', exact: true }).hover() await expect.poll(() => card.count(), { timeout: 5_000 }).toBe(0) expect(tripwire.pageErrors).toEqual([]) }, 60_000) + it('keeps session details beside action tooltips with the tooltips above the card', async () => { + const hoverPage = await newEnglishPage(browser) + try { + const consoleWatch = watchConsole(hoverPage) + await hoverPage.goto(scaffold.authenticatedUrl) + const row = await seededSessionRow(hoverPage) + const title = row.locator('[class*="title"]') + const card = hoverPage.getByRole('button', { name: `Copy: ${await title.innerText()}` }) + const tooltip = hoverPage.getByRole('tooltip') + const observations: { stage: string; details: boolean; tooltips: string[] }[] = [] + const observe = async (stage: string): Promise => { + observations.push({ stage, details: await card.count() > 0, tooltips: await tooltip.allTextContents() }) + } + const clockStart = Date.now() + await hoverPage.clock.install({ time: clockStart }) + await hoverPage.clock.pauseAt(clockStart + 1000) + await title.hover() + await hoverPage.clock.runFor(800) + await card.waitFor() + await observe('details') + await row.getByRole('button', { name: /^Session actions for / }).hover() + await hoverPage.clock.runFor(1000) + expect(await card.count()).toBe(1) + await observe('more-hover') + + await row.getByRole('button', { name: 'Archive session', exact: true }).hover() + await hoverPage.clock.runFor(499) + expect(await card.count()).toBe(1) + expect(await tooltip.count()).toBe(0) + await observe('archive-before-dwell') + await hoverPage.clock.runFor(1) + await tooltip.filter({ hasText: 'Archive' }).waitFor() + expect(await card.count()).toBe(1) + expect(await tooltip.evaluate(el => Number(getComputedStyle(el).zIndex))) + .toBeGreaterThan(await card.evaluate(el => Number(getComputedStyle(el).zIndex))) + await observe('archive') + await row.getByRole('button', { name: 'Pin session', exact: true }).hover() + await hoverPage.clock.runFor(500) + await tooltip.filter({ hasText: 'Pin' }).waitFor() + expect(await card.count()).toBe(1) + await observe('pin') + + await title.hover() + await tooltip.waitFor({ state: 'detached' }) + // Advance beyond both the 800ms card dwell and the 500ms action tooltip dwell. + await hoverPage.clock.runFor(1600) + expect(await card.count()).toBe(1) + await observe('back-to-title') + + const menu = row.getByRole('button', { name: /^Session actions for / }) + await menu.click() + await hoverPage.getByRole('menu').waitFor() + expect(await card.count()).toBe(0) + await hoverPage.keyboard.press('Escape') + await hoverPage.getByRole('menu').waitFor({ state: 'detached' }) + await title.hover() + await hoverPage.clock.runFor(1600) + expect(await card.count()).toBe(0) + await observe('menu-closed') + + await hoverPage.getByRole('button', { name: 'Account menu', exact: true }).hover() + await title.hover() + await hoverPage.clock.runFor(799) + expect(await card.count()).toBe(0) + await hoverPage.clock.runFor(1) + await card.waitFor() + await observe('row-reentered') + await compareOrRefreshGolden( + fileURLToPath(new URL('./expected/session-row-hover/actions.expected.json', import.meta.url)), + JSON.stringify(observations, null, 2), MODE, + ) + expect(consoleWatch.pageErrors).toEqual([]) + } finally { + await hoverPage.close() + } + }, 60_000) + + it('shares one dwell and one visible card across Workspace and Session rows', async () => { + const hoverScaffold = await launchWebScaffold({}) + let ownedPage: Page | undefined + try { + for (const title of ['gamma-ws', 'beta-ws']) { + const cwd = join(hoverScaffold.workspaceCwd, title) + await mkdir(cwd, { recursive: true }) + await hoverScaffold.ctx.workspaceRegistry.create(cwd, title) + } + const sessionId = SessionId('mixed-hover-session') + await seedSession(hoverScaffold, await readFile(SEED, 'utf8'), sessionId) + await hoverScaffold.ctx.sessionController.rename({ sessionId, title: 'Mixed hover session' }) + const hoverPage = await newEnglishPage(browser) + ownedPage = hoverPage + const consoleWatch = watchConsole(hoverPage) + await hoverPage.goto(hoverScaffold.authenticatedUrl) + const session = await seededSessionRow(hoverPage) + const sessionTitle = await session.locator('[class*="title"]').innerText() + const workspace = (title: string) => hoverPage.locator('[data-row-key^="workspace:"]') + .filter({ hasText: title }).locator('[class*="title"]') + const first = workspace('gamma-ws') + const second = workspace('beta-ws') + const card = hoverPage.getByRole('button', { name: /^Copy: / }) + const observations: { stage: string; exclusive: boolean }[] = [] + const clockStart = Date.now() + await hoverPage.clock.install({ time: clockStart }) + await hoverPage.clock.pauseAt(clockStart + 1000) + await hoverPage.getByRole('button', { name: 'Account menu', exact: true }).hover() + await hoverPage.clock.runFor(300) + await first.hover() + await hoverPage.clock.runFor(799) + expect(await card.count()).toBe(0) + await hoverPage.clock.runFor(1) + const record = async (stage: string, title: string): Promise => { + // The clock stays paused: wait for React's commit without advancing another hover dwell. + await card.getByText(title, { exact: true }).waitFor() + expect(await card.count()).toBe(1) + expect(await card.getByText(title, { exact: true }).isVisible()).toBe(true) + observations.push({ stage, exclusive: true }) + } + await record('first-workspace-after-dwell', 'gamma-ws') + await second.hover() + await record('workspace-to-workspace-immediate', 'beta-ws') + await session.locator('[class*="title"]').hover() + await record('workspace-to-session-immediate', sessionTitle) + await first.hover() + await record('session-to-workspace-immediate', 'gamma-ws') + await hoverPage.getByRole('button', { name: 'Account menu', exact: true }).hover() + await hoverPage.clock.runFor(300) + expect(await card.count()).toBe(0) + await second.hover() + await hoverPage.clock.runFor(799) + expect(await card.count()).toBe(0) + await hoverPage.clock.runFor(1) + await record('list-reentered-after-dwell', 'beta-ws') + await compareOrRefreshGolden( + fileURLToPath(new URL('./expected/session-row-hover/mixed-rows.expected.json', import.meta.url)), + JSON.stringify(observations, null, 2), MODE, + ) + expect(consoleWatch.pageErrors).toEqual([]) + } finally { + try { await ownedPage?.close() } finally { await hoverScaffold.close() } + } + }, 60_000) + + it('shares the first session dwell across each list and its active hover card', async () => { + const hoverScaffold = await launchWebScaffold({}) + try { + const seed = await readFile(SEED, 'utf8') + await seedSession(hoverScaffold, seed, 'hover-first') + await seedSession(hoverScaffold, seed, 'hover-second') + await hoverScaffold.ctx.sessionController.rename({ sessionId: SessionId('hover-first'), title: 'Hover first' }) + await hoverScaffold.ctx.sessionController.rename({ sessionId: SessionId('hover-second'), title: 'Hover second' }) + for (const layout of ['In one list', 'Workspace Tree']) { + // Each page owns a browser context, so layout preferences and paused clocks cannot leak between layouts. + const ui = await newEnglishPage(browser) + try { + const consoleWatch = watchConsole(ui) + await ui.context().grantPermissions(['clipboard-read', 'clipboard-write']) + await ui.goto(hoverScaffold.authenticatedUrl) + await ui.getByRole('button', { name: 'View options' }).click() + await ui.getByRole('menuitem', { name: layout, exact: true }).click() + if (layout !== 'In one list') { + const header = ui.getByText('Ungrouped', { exact: true }).locator('..').locator('..') + await expect.poll(async () => { + if (await header.getAttribute('aria-expanded') !== 'true') await ui.getByText('Ungrouped', { exact: true }).click() + return header.getAttribute('aria-expanded') + }).toBe('true') + } + const first = ui.locator('[data-row-key="session:hover-first"]').getByText('Hover first', { exact: true }) + const second = ui.locator('[data-row-key="session:hover-second"]').getByText('Hover second', { exact: true }) + await first.waitFor() + await second.waitFor() + const firstCard = ui.getByRole('button', { name: 'Copy: Hover first', exact: true }) + const secondCard = ui.getByRole('button', { name: 'Copy: Hover second', exact: true }) + const observations: { stage: string; first: boolean; second: boolean }[] = [] + const observe = async (stage: string): Promise => { + observations.push({ stage, first: await firstCard.count() > 0, second: await secondCard.count() > 0 }) + } + const clockStart = Date.now() + await ui.clock.install({ time: clockStart }) + await ui.clock.pauseAt(clockStart + 1000) + await first.hover() + await ui.clock.runFor(799) + expect(await firstCard.count()).toBe(0) + await observe('first-before-dwell') + await ui.clock.runFor(1) + await firstCard.waitFor() + await observe('first-shown') + await second.hover() + // Wait for React's commit with the clock paused: an immediate handoff must not need another dwell. + await secondCard.waitFor() + expect(await firstCard.count()).toBe(0) + await observe('second-instant') + await first.hover() + await firstCard.waitFor() + expect(await secondCard.count()).toBe(0) + await observe('first-instant') + + await firstCard.hover() + await ui.clock.runFor(500) + expect(await firstCard.isVisible()).toBe(true) + await observe('readable-portal') + await firstCard.click() + await ui.getByRole('status').getByText('Copied', { exact: true }).waitFor() + expect(await ui.evaluate(() => navigator.clipboard.readText())).toBe('Hover first') + await observe('copied-portal') + await second.hover() + await secondCard.waitFor() + expect(await firstCard.count()).toBe(0) + await observe('portal-return-instant') + + await secondCard.hover() + await ui.getByRole('button', { name: 'Account menu', exact: true }).hover() + await ui.clock.runFor(300) + await secondCard.waitFor({ state: 'detached' }) + expect(await firstCard.count()).toBe(0) + await observe('outside-cooled') + await first.hover() + await ui.clock.runFor(799) + expect(await firstCard.count()).toBe(0) + await observe('list-reentry-before-dwell') + await ui.clock.runFor(1) + await firstCard.waitFor() + await observe('list-reentry-shown') + await compareOrRefreshGolden( + fileURLToPath(new URL('./expected/session-row-hover/grouped.expected.json', import.meta.url)), + JSON.stringify(observations, null, 2), MODE, + ) + expect(consoleWatch.pageErrors).toEqual([]) + } finally { + await ui.close() + } + } + } finally { + await hoverScaffold.close() + } + }) + it('keeps an open row menu up while the pointer moves between trigger and list', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-ws-row-menu')) const sessionRow = await seededSessionRow() @@ -586,7 +822,7 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo await page.waitForTimeout(POINTER_HOLD_MS) expect(await page.getByRole('menuitem', { name: 'Rename' }).count()).toBe(1) // Pointer-leave dismissal still applies once the pointer genuinely leaves. - await page.getByRole('button', { name: 'Settings' }).hover() + await page.getByRole('button', { name: 'Account menu', exact: true }).hover() await expect.poll(() => page.getByRole('menuitem', { name: 'Rename' }).count(), { timeout: 5_000 }).toBe(0) expect(tripwire.pageErrors).toEqual([]) }, 60_000) @@ -779,11 +1015,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 +1029,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 +1044,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/tests/workspace-new-session-folding.e2e.ts b/apps/web/tests/workspace-new-session-folding.e2e.ts index 176af733b0..4a24a46e59 100644 --- a/apps/web/tests/workspace-new-session-folding.e2e.ts +++ b/apps/web/tests/workspace-new-session-folding.e2e.ts @@ -1,4 +1,4 @@ -/** Blank New Session folding through the shipped Web composition. */ +/** Blank New Session folding and the session watermark through the shipped Web composition. */ import { readFile } from 'node:fs/promises' import { basename, join } from 'node:path' @@ -107,7 +107,42 @@ describe('web e2e: blank New Session folding quota', () => { await expect.poll(() => sidebar.getByRole('treeitem').count()).toBe(18) await sidebar.getByRole('button', { name: 'Show less' }).click() await expect.poll(() => sidebar.getByRole('treeitem').count()).toBe(7) - await assertFixtureInventory(EXPECTED_DIR, ['sidebar.expected.md', 'first-batch.expected.md']) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) + + it('raises the watermark to the open session, keeps it after leaving, and resets it on fold', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-workspace-session-watermark')) + const sidebar = page.getByRole('tree', { name: 'Sessions' }) + const workspaceTitle = basename(scaffold.workspaceCwd) + const sessions = () => sidebar.getByText('Untitled', { exact: true }).count() + await sidebar.getByRole('button', { name: 'Show 11 more sessions' }).click() + await expect.poll(sessions).toBe(10) + await sidebar.getByText('Untitled', { exact: true }).nth(8).click() + await sidebar.getByRole('button', { name: 'Show 6 more sessions' }).click() + await sidebar.getByRole('button', { name: 'Show 1 more sessions' }).click() + await expect.poll(sessions).toBe(16) + await sidebar.getByRole('button', { name: 'Show less' }).click() + await expect.poll(sessions).toBe(9) + await sidebar.getByRole('button', { name: 'Show 7 more sessions' }).waitFor() + + const workspaceRow = sidebar.getByRole('treeitem').first() + await workspaceRow.hover() + await page.getByRole('button', { name: `New session in ${workspaceTitle}` }).click() + await sidebar.getByText('New Session', { exact: true }).waitFor() + expect(await sessions()).toBe(9) + await workspaceRow.hover() + await compareOrRefreshGolden( + join(EXPECTED_DIR, 'watermark-kept.expected.md'), + await captureStableAria(page, '[role="tree"][aria-label="Sessions"]', scaffold.workspaceCwd), + MODE, + ) + + await workspaceRow.click() + await workspaceRow.click() + await expect.poll(sessions).toBe(5) + await sidebar.getByRole('button', { name: 'Show 11 more sessions' }).waitFor() + await assertFixtureInventory(EXPECTED_DIR, ['sidebar.expected.md', 'first-batch.expected.md', 'watermark-kept.expected.md']) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) }) diff --git a/apps/web/tests/worktree-opt-in.e2e.ts b/apps/web/tests/worktree-opt-in.e2e.ts index c2f2e186a8..40d4e58857 100644 --- a/apps/web/tests/worktree-opt-in.e2e.ts +++ b/apps/web/tests/worktree-opt-in.e2e.ts @@ -65,10 +65,11 @@ it('persists the Git Worktrees switch and removes its capability while retaining await page.getByRole('navigation', { name: 'Global panels' }).getByRole('button', { name: 'Plugins', exact: true }).click() const panel = page.locator('[data-plugin-panel]') await panel.getByRole('heading', { name: 'Plugins', exact: true }).waitFor() + await panel.getByRole('button', { name: 'More', exact: true }).click() return panel } let panel = await openPlugins() - let card = panel.locator(`[data-plugin-group="official"] [data-plugin-package="${BUNDLE}"]`) + let card = panel.locator(`[data-plugin-group="more"] [data-plugin-package="${BUNDLE}"]`) await card.getByRole('button', { name: 'View Git Worktrees', exact: true }).waitFor() expect(await card.getByText('Experimental', { exact: true }).count()).toBe(1) let toggle = card.getByRole('switch', { name: 'Enable Git Worktrees', exact: true }) @@ -90,7 +91,7 @@ it('persists the Git Worktrees switch and removes its capability while retaining await page.reload({ waitUntil: 'load' }) panel = await openPlugins() - card = panel.locator(`[data-plugin-package="${BUNDLE}"]`) + card = panel.locator(`[data-plugin-group="more"] [data-plugin-package="${BUNDLE}"]`) toggle = card.getByRole('switch', { name: 'Enable Git Worktrees', exact: true }) await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') expect(tools()).toContain('create_worktree') diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 295c9d1c56..9103d289a5 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -22,6 +22,10 @@ // this client-registered project must not also hold them (one program // cannot see both sides of the cordis Context merges). "exclude": [ + "tests/collapse-timing.e2e.ts", + "tests/notice-wake-tail.e2e.ts", + "tests/fold-blank-matrix.e2e.ts", + "tests/chat-flow-layout.e2e.ts", "tests/layout-bottom.e2e.ts", "tests/shortcuts-desktop.e2e.ts", "tests/shortcuts-workspace.e2e.ts", @@ -49,6 +53,7 @@ "tests/minimal-preset.snapshot.ts", "tests/message-feedback-protocol.snapshot.ts", "tests/preset-migration.snapshot.ts", + "tests/subagent-fork-schedule.snapshot.ts", "tests/live-interactions.e2e.ts", "tests/question-composer.e2e.ts", "tests/approval-composer.e2e.ts", @@ -72,9 +77,11 @@ "tests/excel-opc.e2e.ts", "tests/office-fixture.ts", "tests/sidebar-browser.e2e.ts", + "tests/jobs-menu-layering.e2e.ts", "tests/plugin-config.e2e.ts", "tests/input-plugin-extensions.e2e.ts", "tests/plugin-manager.e2e.ts", + "tests/schedule-header.e2e.ts", "tests/worktree-opt-in.e2e.ts", "tests/session-inspector.e2e.ts", "tests/shared-inspector.e2e.ts", @@ -83,6 +90,7 @@ "tests/inspector-source-build.e2e.ts", "tests/plugin-install-cancel.e2e.ts", "tests/plugin-install-approve.e2e.ts", + "tests/plugin-hmr-lifecycle.e2e.ts", "tests/plugin-install-registry.e2e.ts", "tests/plugin-install-github.e2e.ts", "tests/client-plugin-live.e2e.ts", @@ -111,8 +119,9 @@ "tests/onboarding-native.e2e.ts", "tests/desktop-onboarding.e2e.ts", "tests/bonus-notice.e2e.ts", + "tests/account-login.e2e.ts", "tests/onboarding-usable-provider.e2e.ts", - "tests/remote-welcome.e2e.ts", + "tests/remote-settings.e2e.ts", "tests/public-mount.e2e.ts", "tests/workspace-new-session-folding.e2e.ts", "tests/workspace-management.e2e.ts", @@ -133,6 +142,7 @@ "tests/present.e2e.ts", "tests/present-svg.e2e.ts", "tests/composer-draft-scroll.e2e.ts", + "tests/composer-focus.e2e.ts", "tests/composer-placeholder.e2e.ts", "tests/context-meter.e2e.ts", "tests/cordis-tool-round.e2e.ts", @@ -144,6 +154,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", @@ -155,6 +166,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/agent-continuation/agent-continuation.worker.ts b/benchmarks/agent-continuation/agent-continuation.worker.ts index 91faa5f347..b19cc2c43c 100644 --- a/benchmarks/agent-continuation/agent-continuation.worker.ts +++ b/benchmarks/agent-continuation/agent-continuation.worker.ts @@ -9,7 +9,7 @@ import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-test import { createUserMessage, LlmAdapter } from '@deepseek-ai/dsh-llm' import type { GenerateOptions, LlmResolvedModelInfo, StreamChunk } from '@deepseek-ai/dsh-llm' import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import { defineContentToolFixture } from '@deepseek-ai/dsh-tools' import { assertBuiltBenchmarkRuntime } from '../support/built-worker.ts' import { PARENT_ID, response, resultText, syntheticHistory, TIME_ZERO, WORKLOAD } from './workload.ts' diff --git a/benchmarks/agent-continuation/child-catalog.worker.ts b/benchmarks/agent-continuation/child-catalog.worker.ts index 52e64fabf5..aedb279937 100644 --- a/benchmarks/agent-continuation/child-catalog.worker.ts +++ b/benchmarks/agent-continuation/child-catalog.worker.ts @@ -5,7 +5,7 @@ import { Context } from '@deepseek-ai/cordis' import { provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SessionQueryEngine from '@deepseek-ai/dsh-session-query' import SubagentRuntime, { SUBAGENT_DESCRIPTOR_VERSION } from '@deepseek-ai/dsh-subagent' diff --git a/benchmarks/package.json b/benchmarks/package.json index 68ce69fa23..d36d79bfdb 100644 --- a/benchmarks/package.json +++ b/benchmarks/package.json @@ -15,10 +15,12 @@ "@deepseek-ai/dsh-agent-loop": "workspace:*", "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", "@deepseek-ai/dsh-agent-preset-registry": "workspace:*", + "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/dsh-api-session-controller": "workspace:*", "@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/session-corpus/projection-list.worker.ts b/benchmarks/session-corpus/projection-list.worker.ts index 78a60b5c06..5e95356c12 100644 --- a/benchmarks/session-corpus/projection-list.worker.ts +++ b/benchmarks/session-corpus/projection-list.worker.ts @@ -7,9 +7,10 @@ import { monitorEventLoopDelay, performance } from 'node:perf_hooks' import { scheduler, setTimeout as delay } from 'node:timers/promises' import { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' +import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access' import SessionController from '@deepseek-ai/dsh-api-session-controller' import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset, type SessionHeader } from '@deepseek-ai/dsh-session' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SessionProjectionCache, { projectionCacheDomainSpec } from '@deepseek-ai/dsh-session-projection-cache' import SqliteSessionQueryEngine from '@deepseek-ai/dsh-session-query-sqlite' @@ -196,10 +197,15 @@ async function mountHost(ctx: Context, root: string, workload: typeof WORKLOADS[ await ctx.plugin(SqliteSessionQueryEngine, { path: ':memory:', openAt: 'never' }) // No Agents, uploads, model calls, or workspace actions occur on this list path. const dispose = (): void => {} - ctx.provide('typert', { lookups: { configure: () => dispose }, contexts: { configureHost: () => dispose } } as never) + ctx.provide('typert', { + lookups: { configure: () => dispose }, + contexts: { configureHost: () => dispose }, + resources: { register: () => dispose }, + } as never) ctx.provide('fileUploads', { registerAgentResolver: () => dispose } as never) ctx.provide('agentDefaultModel', { currentSelection: () => ({ provider: 'synthetic', model: 'generated-model' }) } as never) ctx.provide('workspaceRegistry', { list: () => [], archivedSessionIds: [] } as never) + new RemoteAccessService(ctx) return new SessionController(ctx, { nativeOpen: false, ...(listWorkSliceMs === undefined ? {} : { listWorkSliceMs }) }, { canOpenPath: () => false }) } diff --git a/benchmarks/session-corpus/session-corpus.worker.ts b/benchmarks/session-corpus/session-corpus.worker.ts index 8dabac10ca..2d1acd56ba 100644 --- a/benchmarks/session-corpus/session-corpus.worker.ts +++ b/benchmarks/session-corpus/session-corpus.worker.ts @@ -8,11 +8,12 @@ import { Context } from '@deepseek-ai/cordis' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-preset-registry' +import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access' import SessionController from '@deepseek-ai/dsh-api-session-controller' import { currentSessionMessageProjections } from '@deepseek-ai/dsh-session-format-catalog/message-projections' import { Session, SessionLogOffset } from '@deepseek-ai/dsh-session' import type { SessionId } from '@deepseek-ai/dsh-session' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SessionProjectionCache, { checkpointRecord, projectionCacheDomainSpec } from '@deepseek-ai/dsh-session-projection-cache' import type { CheckpointRecord } from '@deepseek-ai/dsh-session-projection-cache' import SqliteSessionQueryEngine from '@deepseek-ai/dsh-session-query-sqlite' @@ -148,10 +149,15 @@ async function mountHost(root: string): Promise<{ readonly ctx: Context; readonl await ctx.plugin(AgentLoop, { agents: [] }) // Transport, upload, model-default, and Workspace services are outside every measured path. const dispose = (): void => {} - ctx.provide('typert', { lookups: { configure: () => dispose }, contexts: { configureHost: () => dispose } } as never) + ctx.provide('typert', { + lookups: { configure: () => dispose }, + contexts: { configureHost: () => dispose }, + resources: { register: () => dispose }, + } as never) ctx.provide('fileUploads', { registerAgentResolver: () => dispose } as never) ctx.provide('agentDefaultModel', { currentSelection: () => BENCH_MODEL } as never) ctx.provide('workspaceRegistry', { list: () => [], archivedSessionIds: [] } as never) + new RemoteAccessService(ctx) const controller = new SessionController(ctx, { nativeOpen: false }, { canOpenPath: () => false }) return { ctx, controller } } diff --git a/benchmarks/session-open/session-open.bench.ts b/benchmarks/session-open/session-open.bench.ts index 9868384c0a..9595ab6c89 100644 --- a/benchmarks/session-open/session-open.bench.ts +++ b/benchmarks/session-open/session-open.bench.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { Session, SessionId, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import { runBuiltBenchmarkWorker, type BuiltBenchmarkWorkerRun, diff --git a/benchmarks/session-open/session-open.worker.ts b/benchmarks/session-open/session-open.worker.ts index b1e2bfec1d..2b6d644960 100644 --- a/benchmarks/session-open/session-open.worker.ts +++ b/benchmarks/session-open/session-open.worker.ts @@ -13,7 +13,7 @@ import SessionStore, { SessionPreparation, } from '@deepseek-ai/dsh-session' import type { AgentHandle } from '@deepseek-ai/dsh-agent' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SessionQueryEngine from '@deepseek-ai/dsh-session-query' import type { 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..b7235609ce --- /dev/null +++ b/benchmarks/user-text/user-text.bench.client.ts @@ -0,0 +1,164 @@ +/** 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 after warm-up; independent minima of adjacent pairs limit 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, + measures: `${benchmark.measures} Minimum of ${ATTEMPTS} per-sample means of ${measured.evaluationsPerSample} fresh evaluations after warm-up.`, + }, { 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..354f9b12bb --- /dev/null +++ b/benchmarks/user-text/user-text.worker.client.ts @@ -0,0 +1,395 @@ +/** 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' + +/** Adjacent baseline and credential measurements; even-indexed pairs measure the baseline first. */ +export interface UserTextTimingPair { + readonly baseMs: number + readonly baseCpuMs: number + readonly withSecretMs: number + readonly withSecretCpuMs: number +} + +/** 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 + /** Fresh evaluations averaged into each timed sample; counts and characters describe one evaluation. */ + readonly evaluationsPerSample: number + readonly secrets: number + /** Characters inside credential ranges, whose masks the matcher builds. */ + readonly maskedCharacters: number + readonly baseMs: number + /** Mean process CPU time per evaluation in the fastest baseline sample. */ + readonly baseCpuMs: number + readonly withSecretMs: number + /** Mean process CPU time per evaluation in the fastest with-credential sample. */ + readonly withSecretCpuMs: number + readonly ratio: number + /** All measured pairs in execution order, excluding warm-up. */ + readonly samples: readonly UserTextTimingPair[] +} + +/** 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 `: warmed code, fresh instances, and independent minima from adjacent sample pairs. */ +export interface UserTextTimeReport { + readonly warmupPairs: number + 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 +/** Exercise each workload's code paths before measuring sub-millisecond baseline evaluations. */ +const WARMUP_PAIRS = 10 +/** Batch every single-document workload to limit noise in its shortest evaluation intervals. */ +const SINGLE_DOCUMENT_EVALUATIONS = 20 +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 +} + +interface SamplePair { + readonly base: Sample + readonly secret: Sample +} + +/** 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()] + +/** + * Evaluate fresh documents; await registry disposal outside the measured interval before returning. + * @returns elapsed and CPU milliseconds, credential nodes produced, and their characters. + */ +async function evaluateAll(rules: RuleSet, texts: readonly string[]): Promise { + const scope = new Context() + try { + const registry = new UserTextRegistry(scope) + for (const rule of rules()) registry.register(rule) + 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) + return { ms, cpuMs: (cpu.user + cpu.system) / 1_000, secrets, maskedCharacters } + } finally { + await scope.fiber.dispose() + } +} + +async function sample(rules: RuleSet, texts: readonly string[], evaluations: number): Promise { + const first = await evaluateAll(rules, texts) + let ms = first.ms + let cpuMs = first.cpuMs + for (let index = 1; index < evaluations; index++) { + const next = await evaluateAll(rules, texts) + ms += next.ms + cpuMs += next.cpuMs + } + return { ...first, ms: ms / evaluations, cpuMs: cpuMs / evaluations } +} + +async function evaluatePair(texts: readonly string[], index: number, evaluations: number): Promise { + if (index % 2 === 0) { + const base = await sample(withoutSecret, texts, evaluations) + return { base, secret: await sample(withSecret, texts, evaluations) } + } + const secret = await sample(withSecret, texts, evaluations) + return { base: await sample(withoutSecret, texts, evaluations), secret } +} + +async function measure(texts: readonly string[], attempts: number, evaluations: number): Promise { + for (let warm = 0; warm < WARMUP_PAIRS; warm++) await evaluatePair(texts, warm, evaluations) + const pairs: SamplePair[] = [] + for (let attempt = 0; attempt < attempts; attempt++) { + pairs.push(await evaluatePair(texts, attempt, evaluations)) + } + const best = pairs.reduce((min, pair) => ({ + base: pair.base.ms < min.base.ms ? pair.base : min.base, + secret: pair.secret.ms < min.secret.ms ? pair.secret : min.secret, + })) + return { + ...best, + samples: pairs.map(pair => ({ + baseMs: pair.base.ms, baseCpuMs: pair.base.cpuMs, + withSecretMs: pair.secret.ms, withSecretCpuMs: pair.secret.cpuMs, + })), + } +} + +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 } +} + +async function timings(attempts: number): Promise { + const results: UserTextWorkloadTiming[] = [] + for (const { id, group, texts } of workloads()) { + const evaluationsPerSample = texts.length === 1 ? SINGLE_DOCUMENT_EVALUATIONS : 1 + const { base, secret, samples } = await measure(texts, attempts, evaluationsPerSample) + results.push({ + id, + group, + documents: texts.length, + characters: texts.reduce((sum, text) => sum + text.length, 0), + evaluationsPerSample, + secrets: secret.secrets, + maskedCharacters: secret.maskedCharacters, + baseMs: base.ms, + baseCpuMs: base.cpuMs, + withSecretMs: secret.ms, + withSecretCpuMs: secret.cpuMs, + ratio: secret.ms / base.ms, + samples, + }) + } + return { warmupPairs: WARMUP_PAIRS, attempts, workloads: results } +} + +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' ? await timings(positiveInteger(count, 'attempts')) : await allocations())) diff --git a/docs/AGENTS.md b/docs/AGENTS.md index d4bbea471f..39ebd5cd9c 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -23,6 +23,7 @@ Each fact has one home: the tier whose job it is; elsewhere, link there. | [architecture.md](architecture.md) | Ordered map: composition, core packages, loop, seams, extension points; read before changing `packages/` | Type definitions (→ subsystems), per-package detail (→ package READMEs), decision rationale (→ Agent Notes), implementation-status annotations | | [subsystems/](subsystems/README.md) | One reference page per subsystem: type definitions, semantics, and the generated Cordis API | Behavior narration (→ architecture.md) | | [Agent Notes](../.agents/notes/README.md) | Active decision records: the why, what-was-given-up, and required verification; `implemented/` notes describe shipped reality in present tense | Migration plans, acceptance-task checklists, fixture walkthroughs, and spec-speak ("should…") once the decision has shipped; archived notes are frozen history, never current authority | +| [defensive-patterns/](defensive-patterns/README.md) | Rules this repository enforces in review, split by artifact: one general bug-class page plus per-domain pages | Type definitions and semantics (→ subsystems), decision rationale (→ Agent Notes) | | [postmortem/](postmortem/README.md) | Incident stories — the only tier where war-story narrative belongs | — | | [Persistence history](persistence-changes/README.md) and [format references](persistence-changes/historical-formats/README.md) | Type-change acknowledgements, release comparisons, and complete historical format schemas | Behavior-only changes; current runtime contracts | | [cookbook/](cookbook/adding-a-package.md) | Step-by-step how-tos with numbered verify steps | Design rationale (→ the Agent Note each guide links) | @@ -32,7 +33,7 @@ Each fact has one home: the tier whose job it is; elsewhere, link there. | Generated reference: the per-page `cordis-surface` regions in [subsystems/](subsystems/README.md), the [Cordis core API + inherited tier](cordis-api/context.md), [tool-catalog](tool-catalog.md), [config-catalog](config-catalog.md), [persistence-catalog](persistence-catalog.md), [module-graph.md](module-graph.md), [cli-help](cli-help.md) | Exhaustive English sources regenerated from source and freshness-gated; reviewed Chinese counterparts follow the [pairing workflow](i18n/README.md#scope-and-exclusions) | Hand edits to generated English sources or regions; Chinese counterparts update through pairing only | | Skills (`.agents/skills/`) | Reusable workflows and specialized decision standards | Product and runtime contracts (→ docs or source) | -Placement: bugs → postmortems; rationale → Agent Notes; procedures → cookbooks; type definitions → subsystems; package contracts → READMEs; standing orders → root `AGENTS.md` with a rationale link. +Placement: bugs → postmortems; rationale → Agent Notes; procedures → cookbooks; type definitions → subsystems; package contracts → READMEs; standing orders → root `AGENTS.md` with a rationale link; review-enforced rules → `defensive-patterns/`. ## Writing rules @@ -55,7 +56,7 @@ When the gate goes red: 2. **Condense** content that belongs here but can be shorter. 3. **Raise** the ceiling only when the words need the space; justify the manifest diff in the PR. A too-low ceiling is a budget bug. -Ceilings are guardrails, not reduction targets. At or below target, retain at least 5% headroom; above target, freeze the ceiling until relocation or condensation brings the document under target. Lower a ceiling only when the document still has room. Targets: root `AGENTS.md` ≤ 1,960; `architecture.md` ≤ 2,400; subtree `AGENTS.md` ≤ 600, except `packages/AGENTS.md` ≤ 750 and this file ≤ 1,320; `packages/README.md` ≤ 994; plus `cordis-primer.md` 600, `defensive-patterns.md` 550, `testing.md` 1,300, `examples/AGENTS.md` 310. Review governs unbudgeted tiers. +Ceilings are guardrails, not reduction targets. At or below target, retain at least 5% headroom; above target, freeze the ceiling until relocation or condensation brings the document under target. Lower a ceiling only when the document still has room. Targets: root `AGENTS.md` ≤ 2,080; `architecture.md` ≤ 2,400; subtree `AGENTS.md` ≤ 600, except `packages/AGENTS.md` ≤ 810 and this file ≤ 1,430; `packages/README.md` ≤ 994; plus `cordis-primer.md` 600, `testing.md` 1,300, `examples/AGENTS.md` 310. Review governs unbudgeted tiers. ## The slop checklist diff --git a/docs/api-gateway.i18n.yaml b/docs/api-gateway.i18n.yaml index 1072232f44..65b0c3e196 100644 --- a/docs/api-gateway.i18n.yaml +++ b/docs/api-gateway.i18n.yaml @@ -4,25 +4,28 @@ # pnpm run verify-translation-pairing --write docs/api-gateway.md /api-gateway: en: 735eb4f22d5f6f71 - zh: 1ca2759961efdc06 + zh: 697eef269b133039 /api-gateway/programming-model: - en: ea12b64211f0d377 - zh: 032e5c0d799c7529 + en: 78eb70d6c2ce6608 + zh: 826f0ccc206b7299 /api-gateway/component-responsibilities: - en: e29f1d7026291075 - zh: 15e361e797d44fce + en: fe382a9bcc768cc2 + zh: 78e3d50d59780c3d /api-gateway/strict-generation-pipeline: - en: cb8da81a92acfa52 - zh: be5f3c268f8571df + en: 9c4a98eb0539ec7f + zh: ad2a145abd805fdd /api-gateway/runtime-invocation: - en: 2a2fed340aaa926c - zh: 46bb1f500c870a76 + en: 37b4858fa48a61b6 + zh: 9a296a2171f1ab7d /api-gateway/src-development-fallback: en: 9570ffe7a348e5ac zh: 2b70b61b1ff1fbb0 /api-gateway/development-mode: - en: ba090d76471dd663 - zh: fcddcb232de98248 + en: 23ae422bd65300da + zh: 67dd9c02f4ffec53 /api-gateway/boundaries: en: e6befc5f8c90f97b - zh: 3ade08102542a894 + zh: 4ace4a493fd2b41f +/api-gateway/boundaries/business-ownership: + en: 980ef04e501a3896 + zh: d2f6db14e5135b68 diff --git a/docs/api-gateway.md b/docs/api-gateway.md index 91f992dc5e..484b866e95 100644 --- a/docs/api-gateway.md +++ b/docs/api-gateway.md @@ -12,6 +12,8 @@ Business services use `@Remote` or `@RemoteScope` to select the methods exposed `@RemoteScope(key)` first resolves an identity to a scoped Context through `ctx.typert.contexts`, then obtains the service from that Context and invokes the method. It applies when the method itself depends on scoped composition and does not need to receive objects such as `Agent` explicitly. +`@Remote` accepts an export name or `{ name?, mode?, resources? }`, and `@RemoteScope(key, option?)` accepts an export name, as in `@RemoteScope('agent', 'current')` below, or `{ name?, resources? }` as its second argument. `resources` holds per-kind readers that return the identities of the resources one call touches for access control; each reader receives the method's wire arguments as its own parameters, with types inferred from the decorated method. Most methods declare no readers, because the Gateway also reads identities from lookup parameters and scoped Contexts that declare a `resource`, and from the default fields in `typert.resources`; the [Typert subsystem](subsystems/typert.md) owns that order. + Services normally extend `TypertRemoteService` so the constructor explicitly binds the Cordis service key and default Remote namespace. A service that already has another base class can instead declare `readonly typertRemote = bindTypertRemote(this, serviceKey)`; both forms leave an inspectable public binding and do not depend on the compiler injecting a symbol into the constructor. ```ts @@ -88,6 +90,7 @@ The `api-remotes` assembly and the `ctx.remote` contract are React-independent; | Host | `@deepseek-ai/dsh-typert-registry` and Loader | Places generated Host descriptors, schemas, and business-package registrations in `ctx.typert`, and holds lookup and Context providers | | Host | `@deepseek-ai/dsh-api-session-controller` | Owns the application Agent/Session identity policy and configures the corresponding Typert lookups | | Host | `@deepseek-ai/dsh-api-gateway` | Provides `ctx.typertGateway`, claims Remote endpoints, validates request values, resolves objects or Contexts, and invokes live Cordis services | +| Host | `@deepseek-ai/dsh-api-remote-access` | Decides which Remote methods a non-owner Peer may call through business-registered role-based policies, filters list results, and streams each Peer's access snapshot; the Gateway requires it | | Client | `@deepseek-ai/dsh-api-gateway/client` | Provides `ctx.remote` and `remote.` child Services, mounts generated descriptors as concrete methods, and initiates and cancels calls through the Connection | | Client | `@deepseek-ai/dsh-api-remotes/client` | Explicitly selects and mounts the `/remote` contributions allowed by the application and brings the corresponding declaration merges into business code | | Both | `@deepseek-ai/dsh-client-connection` | Provides the RPC carrier, request correlation, trust boundary, cancellation, response envelope, and the `/api` HTTP bridge | @@ -96,7 +99,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. @@ -124,7 +127,7 @@ Remote calls use the Connection's `/api` route. The Client Remote calls `connect The Connection performs the unified trust check for `/api` before the HTTP bridge, then dispatches inside the shared FetchHandler. The Typert Gateway claims only two-segment endpoints that have a strict descriptor or active SRC marker; it projects binary Remote fields into JSON-compatible metadata and result-relative byte attachments, which Connection frames as multipart responses. Feature-owned exact Fetch routes handle responses outside the RPC envelope, and other requests return 404. Connection owns transport, RPC ids, response envelopes, and request cancellation, while Gateway owns the Remote data protocol and business dispatch. Replacing the Connection carrier does not require changes to Remote descriptors or the Client programming interface. -For every call, the Gateway resolves the descriptor and live service from the current registries instead of caching business objects. It requires the fields in `args` to match the descriptor exactly, validates wire values with codecs, resolves objects or receivers through registered lookup or Context providers, and invokes the service method targeted by the binding. The Client Gateway validates decoded binary results with the generated result codec; ordinary JSON results retain their existing handling. A missing provider, unknown identity, binding mismatch, missing or extra argument, schema failure, or missing method fails before entering or after leaving business code. +For every call, the Gateway resolves the descriptor and live service from the current registries instead of caching business objects. Every call names the Peer it speaks for, and a disposed Peer is refused with `gateway/peer-disposed`. The Gateway requires the fields in `args` to match the descriptor exactly; for a call whose Peer principal is not the owner it then resolves the resources the call touches and asks `ctx.remoteAccess.decide()`, so a refused call resolves no lookup and activates no Agent. It validates wire values with codecs, resolves objects or receivers through registered lookup or Context providers, and invokes the service method targeted by the binding. The Client Gateway validates decoded binary results with the generated result codec; ordinary JSON results retain their existing handling. A missing provider, unknown identity, binding mismatch, missing or extra argument, schema failure, or missing method fails before entering or after leaving business code. The lookup provider's `register()` supplies both the stable declaration and the default resolver; `configure()` supplies a resolver owned by Host composition that may execute asynchronously and is scoped to an effect lifetime. Configuration may precede provider mounting; without a provider, invocation still fails with `gateway/lookup-unavailable`, and unloading the configuration restores the provider's default policy. The Session Controller owns the standard resolver semantics for `agent` and `session`: it reuses a live Agent, automatically resumes ordinary cold sessions, deduplicates concurrent resumes, and rejects identities owned by subagent routing; the `session` lookup returns that Agent's Session. A resume failure and an ownership fence raise a `RemoteError` carrying their own code, `session/not-found` or `session/agent-busy`, which the Gateway encodes onto the wire unchanged; only an unclassified throw folds into `gateway/internal`. @@ -154,7 +157,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 @@ -163,3 +166,7 @@ Remote handles unary method calls with one request and one result, and stream me The API layers are organized as `remotes → gateway → connection → webserver`. The BFF and Typert RPC layers live under `packages/api`; Connection and WebServer live at `packages/client/connection` and `packages/host/webserver`. Unary results containing `Uint8Array`, including nested fields and array entries, use [binary Remote transfer](../.agents/notes/implemented/architecture/2026-09-17-workspace-file-binary-transfer.md). A feature that needs a response outside the RPC envelope registers an exact Connection Fetch route. Lookup policy is configured per key, so all `agent` or `session` parameters share the cold-resume behavior. Accepting live objects only would require an explicit per-parameter or per-endpoint policy, which does not exist; the business method must not guess whether the object came from restoration. + +### Business ownership + +`packages/api` owns transport, call shape, and session lifecycle; a business rule belongs to an independent business package and reaches this layer through a registration surface or projected data. The requirements a change here must satisfy — the four `@Remote` disciplines, the additive-names rule, and the boundary this layer keeps — are owned by [Remote and API rules](defensive-patterns/remote-and-api.md), which is where a review checks them. diff --git a/docs/api-gateway.zh.md b/docs/api-gateway.zh.md index 4e21bafa9b..c44d6f403f 100644 --- a/docs/api-gateway.zh.md +++ b/docs/api-gateway.zh.md @@ -4,6 +4,8 @@ 本文是 Typert API Gateway 的当前状态参考。它描述业务服务如何声明一元与流式 Remote 方法、构建如何生成 Host 与 Client 约定,以及调用如何复用 Connection 的 RPC 与 `/api` 路由。会话事件、增量数据和其他流协议不属于本文范围;它们可以使用同一个 Connection,但不使用 Remote 方法描述符。 + + ## 编程模型 业务服务通过 `@Remote` 或 `@RemoteScope` 选择对 Client 开放的方法。未标记的方法不会进入生成的 Client 类型或运行时贡献,也不能通过 `ctx.remote` 调用。 @@ -12,6 +14,8 @@ `@RemoteScope(key)` 表示先通过 `ctx.typert.contexts` 把 identity 解析为一个作用域 Context,再从该 Context 取得服务并调用方法。它适用于方法本身依赖作用域组合、而不需要显式接收 `Agent` 等对象的情形。 +`@Remote` 接受导出名或 `{ name?, mode?, resources? }`;`@RemoteScope(key, option?)` 的第二个参数接受导出名(如下文的 `@RemoteScope('agent', 'current')`)或 `{ name?, resources? }`。`resources` 按资源种类给出读取函数,返回一次调用所访问资源的身份,供访问控制使用;每个读取函数以方法的 wire 参数作为自身参数,类型从被装饰方法推断。多数方法不声明读取函数,因为 Gateway 还会从声明了 `resource` 的 lookup 参数与作用域 Context 以及 `typert.resources` 中的默认字段读取身份;[Typert 子系统](subsystems/typert.zh.md)负责该顺序。 + 服务通常继承 `TypertRemoteService`,让 Cordis 服务 key 与默认 Remote namespace 在构造器中显式绑定。已有其他基类的服务可以改为声明 `readonly typertRemote = bindTypertRemote(this, serviceKey)`;两种方式都会留下可检查的公开 binding,不依赖编译器向构造函数注入 symbol。 ```ts @@ -88,6 +92,7 @@ Client 应用只装配 `@deepseek-ai/dsh-api-remotes`。该包以运行时值导 | Host | `@deepseek-ai/dsh-typert-registry` 与 Loader | 把生成的 Host 描述符、schema 及业务包注册项放入 `ctx.typert`,并持有 lookup 与 Context 提供方 | | Host | `@deepseek-ai/dsh-api-session-controller` | 负责应用的 Agent/Session 身份策略,并配置对应的 Typert lookup | | Host | `@deepseek-ai/dsh-api-gateway` | 提供 `ctx.typertGateway`,认领 Remote endpoint,校验请求值,解析对象或 Context,并调用实时 Cordis 服务 | +| Host | `@deepseek-ai/dsh-api-remote-access` | 按业务方注册的基于 role 的 policy 判定非 owner Peer 可调用哪些 Remote 方法,过滤列表结果,并为每个 Peer 推送访问快照;Gateway 依赖它 | | Client | `@deepseek-ai/dsh-api-gateway/client` | 提供 `ctx.remote` 与 `remote.` 子服务,把生成的描述符挂成具体方法,并通过 Connection 发起和取消调用 | | Client | `@deepseek-ai/dsh-api-remotes/client` | 显式选择并挂载本应用允许使用的 `/remote` 贡献,向业务代码带入对应的声明合并 | | 双侧 | `@deepseek-ai/dsh-client-connection` | 提供 RPC carrier、请求关联、信任边界、取消、响应 envelope 与 `/api` HTTP bridge | @@ -96,7 +101,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。 @@ -124,7 +129,7 @@ Remote 调用使用 Connection 的 `/api` 路由。Client Remote 调用 `connect Connection 在 HTTP bridge 之前执行 `/api` 的统一信任检查,再在共享 FetchHandler 内分发。Typert Gateway 只认领存在严格描述符或活跃 SRC marker 的两段式 endpoint;它把二进制 Remote 字段投影为 JSON 兼容元数据及相对于结果的字节附件,再由 Connection 封装为 multipart 响应。功能自有的精确 Fetch 路由处理 RPC 信封之外的响应,其他请求返回 404。Connection 拥有传输、RPC id、响应 envelope 和请求取消,Gateway 拥有 Remote 数据协议和业务分发。替换 Connection carrier 不要求改变 Remote 描述符或 Client 编程接口。 -Gateway 每次调用都从当前注册表解析描述符和实时服务,不缓存业务对象。它要求 `args` 的字段集合与描述符完全一致,先用 codec 校验 wire 值,再通过注册的 lookup 或 Context 提供方解析对象或接收者,最后调用 binding 指向的服务方法。Client Gateway 使用生成的结果 codec 校验解码后的二进制结果;普通 JSON 结果保持原有处理方式。缺少提供方、identity 未命中、binding 不一致、参数缺失或多余、schema 失败和方法不存在都会在进入业务代码前或离开业务代码后失败。 +Gateway 每次调用都从当前注册表解析描述符和实时服务,不缓存业务对象。每次调用都给出其代表的 Peer,已 dispose 的 Peer 以 `gateway/peer-disposed` 被拒。Gateway 要求 `args` 的字段集合与描述符完全一致;对 Peer principal 不是 owner 的调用,随后解析调用访问的资源并询问 `ctx.remoteAccess.decide()`,被拒的调用不解析任何 lookup,也不激活 Agent。之后它先用 codec 校验 wire 值,再通过注册的 lookup 或 Context 提供方解析对象或接收者,最后调用 binding 指向的服务方法。Client Gateway 使用生成的结果 codec 校验解码后的二进制结果;普通 JSON 结果保持原有处理方式。缺少提供方、identity 未命中、binding 不一致、参数缺失或多余、schema 失败和方法不存在都会在进入业务代码前或离开业务代码后失败。 lookup 提供方的 `register()` 同时提供稳定声明和默认 resolver;`configure()` 提供由 Host 组合拥有、可异步执行且受 effect 生命周期约束的 resolver。配置可以先于提供方挂载;没有提供方时调用仍以 `gateway/lookup-unavailable` 失败,配置卸载后则恢复提供方默认策略。Session Controller 负责 `agent` 与 `session` 的标准 resolver 语义:复用 live Agent,自动恢复普通冷会话,对并发恢复去重,并拒绝由 subagent routing 拥有的 identity;`session` lookup 返回该 Agent 的 Session。恢复失败与 ownership fence 抛出携带自有码的 `RemoteError`(`session/not-found` 或 `session/agent-busy`),Gateway 原样编码上 wire;只有未归类的 throw 才折成 `gateway/internal`。 @@ -154,7 +159,9 @@ 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 阶段生成它。 + + ## 边界 @@ -163,3 +170,9 @@ Remote 处理单请求单结果的一元方法调用,以及项沿 Host → Cli API 各层按 `remotes → gateway → connection → webserver` 组织。BFF 与 Typert RPC 层位于 `packages/api`;Connection 与 WebServer 位于 `packages/client/connection` 和 `packages/host/webserver`。包含 `Uint8Array` 的一元结果(包括嵌套字段和数组条目)使用[二进制 Remote 传输](../.agents/notes/implemented/architecture/2026-09-17-workspace-file-binary-transfer.zh.md)。需要 RPC 信封之外响应的功能注册精确的 Connection Fetch 路由。 lookup 策略按 key 配置,因此所有 `agent` 或 `session` 参数共享冷恢复行为。只接受 live 对象需要显式的逐参数或逐 endpoint 策略,而这种策略并不存在;不能通过业务方法内部猜测对象是否来自恢复。 + + + +### 业务所有权 + +`packages/api` 负责传输、调用形态与会话生命周期;业务规则归独立的业务包,经注册面或投影数据接入本层。这里改动必须满足的要求——`@Remote` 的四条纪律、存量名只增不改、以及本层保留的边界——正家是[远程与 API 规则](defensive-patterns/remote-and-api.zh.md),评审就在那里核对。 diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index 0b096186d7..8206f3e6dc 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -21,8 +21,8 @@ en: 20ef882e44b06a10 zh: c10c3934ed5570e9 /deepseek-harness-architecture/events: - en: 214c3c81c21df6f9 - zh: 75d2cdc3c9fc9930 + en: e89802f066e4955d + zh: ea2fb4bef94e086d /deepseek-harness-architecture/turn-flow: en: e6402b28c0ed15fa zh: 6c07be9047b42056 @@ -30,8 +30,8 @@ en: a2e35c43438fec6d zh: e27bdac8e9feff32 /deepseek-harness-architecture/capability-seams: - en: 93d1dc2eeda4aec2 - zh: ee7a9da89151ea17 + en: a5bc20c3f2a1b370 + zh: 91773a281410b2f4 /deepseek-harness-architecture/where-new-behavior-goes: en: 9b2eb0539a9cd0d6 zh: 4f575277b91d4e5c diff --git a/docs/architecture.md b/docs/architecture.md index 51dcfa7e0f..03d88148c7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -72,7 +72,7 @@ Events are the extension points, and picking the right domain is the first decis - **Agent events** (`agent/*`) carry a live `Agent`: inbox, step, status, request, validation, continuation. Use one to observe or intercept work in flight. - **Capability events** attach policy and adapters to a seam (`fs/*`, `tools/*`, `telemetry/*`) without importing the loop. -AgentLoop awaits serial `agent/created` initialization before starting queued work. Initialization failure rolls back creation; [agent-loop](../packages/core/agent-loop/README.md#understand-the-implementation) defines teardown ordering. +AgentLoop awaits serial `agent/created` before queued work and rolls back failed initialization. Unload retains resources through Agent teardown; [agent-loop](../packages/core/agent-loop/README.md#understand-the-implementation) defines ordering. The [event map](event-producer-consumer.md) lists every event's producers and consumers. @@ -133,7 +133,7 @@ A **seam** is a swappable capability with three roles: a **Service Definition** Seams are why one provider swap changes the whole product. Filesystem and subprocess providers share one execution world, so pointing them at a remote sandbox moves Bash, PTY, and LSP with them, with no provider forks. [Subagent providers](subsystems/subagent.md) vary just as widely behind one interface, from a fresh child agent to a delegated turn in another product. -[Experimental Agent Teams](subsystems/agent-team.md) is a published opt-in coordination seam on `ctx.agentTeams`, with a durable roster, task board, and mailbox layered over continuable subagents. +[Experimental Agent Teams](subsystems/agent-team.md) exposes opt-in `ctx.agentTeams` coordination with durable roster and task state plus direct inbox messaging over continuable subagents. ## Where new behavior goes diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 8836217bd1..870fa1c996 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -74,7 +74,7 @@ Electron 使用 Electron Node 模式启动私有 Desktop Host。Host 调用共 - **Agent 事件**(`agent/*`)携带活跃 `Agent`:inbox、步骤、状态、请求、验证、续跑。要观察或拦截进行中的工作时,使用它。 - **能力事件**无需导入循环即可向某个 seam(`fs/*`、`tools/*`、`telemetry/*`)附加策略和适配器。 -AgentLoop 在启动已排队工作前等待串行 `agent/created` 初始化。初始化失败会回滚创建;[agent-loop](../packages/core/agent-loop/README.zh.md#understand-the-implementation)定义 teardown 顺序。 +AgentLoop 在启动已排队工作前等待串行 `agent/created`,初始化失败则回滚。卸载在 Agent teardown 期间保留所需资源;[agent-loop](../packages/core/agent-loop/README.zh.md#understand-the-implementation)定义顺序。 [事件映射](event-producer-consumer.zh.md)列出每个事件的生产方与消费方。 @@ -137,7 +137,7 @@ Session 消费方只了解当前逻辑格式。仅 header 的 `stat` 与 `list` seam 正是替换一个提供方就能改变整个产品的原因。文件系统与进程提供方共享同一个执行世界,因此把它们指向远程沙箱,也就把 Bash、PTY 和 LSP 一并搬了过去,无需提供方专用 fork。[subagent 提供方](subsystems/subagent.zh.md)在同一个接口之后同样千差万别,从新建一个子 agent,到把一个轮次委派给另一个产品。 -[实验性 Agent Teams](subsystems/agent-team.zh.md) 是 `ctx.agentTeams` 上公开发布、显式启用的协作 seam,在可继续 subagent 之上提供持久 roster、任务板和 mailbox。 +[实验性 Agent Teams](subsystems/agent-team.zh.md) 通过显式启用的 `ctx.agentTeams`,在可继续 subagent 之上提供持久 roster、任务状态和直接 inbox 消息协作。 ## 新行为的归属位置 diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 1c39cb4a31..49d05c0722 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: 5bdd69045ebd8e3c - zh: f791f38cf578f9c9 + en: d7b1a50795bcac28 + zh: 68386bdbf1869342 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index f240b94937..333f570d5e 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -101,6 +101,8 @@ flowchart LR svc_typert["ctx.typert
Runtime type registry"] pkg_typert_loader["typert-loader"] svc_typertGateway["ctx.typertGateway
Typert Host invocation gateway"] + pkg_api_remote_access["api-remote-access"] + svc_remoteAccess["ctx.remoteAccess
Remote method access control"] svc_sessionPersistence["ctx.sessionPersistence
Durable session persistence seam"] pkg_session_persistence_jsonl["session-persistence-jsonl"] pkg_hooks_claude_code["hooks-claude-code"] @@ -272,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"] @@ -291,6 +296,7 @@ flowchart LR pkg_agent_preset_registry --> svc_agentPresets pkg_api_gateway --> svc_typertGateway pkg_api_job_controller --> svc_jobController + pkg_api_remote_access --> svc_remoteAccess pkg_api_session_controller --> svc_sessionController pkg_api_session_controller --> svc_sessionFileReferences pkg_api_session_controller --> svc_sessionSkillCatalog @@ -428,6 +434,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 @@ -496,6 +503,9 @@ flowchart LR svc_profileContext --> pkg_plugin_manager svc_ptcRuntime --> pkg_tools svc_ptcRuntime --> pkg_workflow_ptc + svc_remoteAccess --> pkg_api_gateway + svc_remoteAccess --> pkg_api_session_controller + svc_remoteAccess --> pkg_api_workspace_controller svc_sandbox --> pkg_bash_sandbox svc_sandbox --> pkg_terminal_bash svc_sandboxPolicy --> pkg_bash_sandbox @@ -572,6 +582,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 @@ -626,6 +637,7 @@ flowchart LR | `ctx.directoryPickerController` | `core` | [`api-workspace-controller`](../packages/api/workspace-controller) | - | - | - | Carries the picking seam onto the wire: capability gating, cancellation, and the seam-coded failures a browser directory flow discriminates on. | | `ctx.typert` | `core` | [`typert-registry`](../packages/typert/registry) | - | [`typert-loader`](../packages/typert/loader), [`api-gateway`](../packages/api/gateway) | - | Plugins register live zod contributions directly or through dsh-typert-loader; the API gateway consumes invocation descriptors and providers, while other runtime consumers query schemas and reflection metadata at their own edges. | | `ctx.typertGateway` | `core` | [`api-gateway`](../packages/api/gateway) | - | - | - | Associates generated Remote descriptors with live Cordis services, resolves registered identities, and exposes unary calls through the shared Connection RPC carrier. | +| `ctx.remoteAccess` | `core` | [`api-remote-access`](../packages/api/remote-access) | - | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller) | - | Decides which Remote methods a non-owner Peer may call through business-registered role-based policies, filters list results, and streams each Peer access snapshot. | | `ctx.sessionPersistence` | `seam` | [`session-persistence`](../packages/session/session-persistence) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | [`agent-loop`](../packages/core/agent-loop), [`tool-bash`](../packages/shell/tool-bash), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`message-feedback`](../packages/feedback/message-feedback) | - | The JSONL backend persists the SessionEvent vocabulary as one artifact per Session. | | `ctx.configEditor` | `core` | [`config-editor`](../packages/boot/config-editor) | - | [`settings`](../packages/settings/settings), [`agent-default-model`](../packages/core/agent-default-model) | - | Persists profile config patches under the application file lock and HMR queue, then reconciles Loader entries. | | `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. | @@ -674,7 +686,7 @@ flowchart LR | `ctx.compaction` | `seam` | [`compaction`](../packages/compaction/compaction) | [`compaction-basic`](../packages/compaction/compaction-basic) | [`compaction-basic`](../packages/compaction/compaction-basic) | - | The basic backend consumes post-step pressure and request-error recovery events; there is no model-facing compact tool. | | `ctx.subagents` | `seam` | [`subagent`](../packages/subagent/subagent) | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process), [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process), [`subagent-acp`](../packages/subagent/subagent-acp), [`subagent-codex`](../packages/subagent/subagent-codex), [`subagent-claude-code`](../packages/subagent/subagent-claude-code), [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control), [`tool-ralph`](../packages/experimental/tool-ralph) | - | Providers prepare local children or execute external tasks; one activation manager owns both lifecycles. The delegation tool selects a backend, control tools deliver local follow-ups, and workflows await activation results. | | `ctx.speechToText` | `seam` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | [`experimental-speech-to-text-sensevoice`](../packages/experimental/speech-to-text-sensevoice) | [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | - | Routes explicit recognizers; the browser uses the authenticated Remote and keeps transcripts in the draft until submission. | -| `ctx.agentTeams` | `core` | [`experimental-agent-team`](../packages/experimental/agent-team) | - | [`experimental-tool-agent-team`](../packages/experimental/tool-agent-team) | - | Owns the implicit-root roster, durable peer mailbox, shared task DAG, and continuable-child lifecycle; tool-agent-team contributes model controls. | +| `ctx.agentTeams` | `core` | [`experimental-agent-team`](../packages/experimental/agent-team) | - | [`experimental-tool-agent-team`](../packages/experimental/tool-agent-team) | - | Owns the implicit-root roster, direct peer inbox delivery, shared task DAG, and continuable-child lifecycle; tool-agent-team contributes model controls. | | `ctx.claudeCodeMods` | `core` | [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | - | - | - | Loads mods that defineMod plugins add, raises their hook chains from harness extension points, and draws the band above the prompt over its Remote. | | `ctx.inspector` | `core` | `inspector` | - | - | - | Owns the Worker-hosted CDP target and the transport-independent Host and Client observation and Cordis-tree query API. | | `ctx.jobs` | `seam` | [`jobs`](../packages/jobs/jobs) | [`jobs-local`](../packages/jobs/jobs-local) | [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`tool-terminal`](../packages/experimental/tool-terminal), [`tool-jobs`](../packages/jobs/tool-jobs), [`api-job-controller`](../packages/api/job-controller) | - | Producers (background bash/pwsh and PTY sends) register running work; record-declaring jobs additionally stream raw output for non-consuming observers; tool-jobs is the model-facing controller that reads, lists, and kills it; jobs-local is the process-local registry. | @@ -682,6 +694,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 17b488deeb..d810b4e900 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -103,6 +103,8 @@ flowchart LR svc_typert["ctx.typert
Runtime type registry"] pkg_typert_loader["typert-loader"] svc_typertGateway["ctx.typertGateway
Typert Host invocation gateway"] + pkg_api_remote_access["api-remote-access"] + svc_remoteAccess["ctx.remoteAccess
Remote method access control"] svc_sessionPersistence["ctx.sessionPersistence
Durable session persistence seam"] pkg_session_persistence_jsonl["session-persistence-jsonl"] pkg_hooks_claude_code["hooks-claude-code"] @@ -274,6 +276,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"] @@ -293,6 +298,7 @@ flowchart LR pkg_agent_preset_registry --> svc_agentPresets pkg_api_gateway --> svc_typertGateway pkg_api_job_controller --> svc_jobController + pkg_api_remote_access --> svc_remoteAccess pkg_api_session_controller --> svc_sessionController pkg_api_session_controller --> svc_sessionFileReferences pkg_api_session_controller --> svc_sessionSkillCatalog @@ -430,6 +436,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 @@ -498,6 +505,9 @@ flowchart LR svc_profileContext --> pkg_plugin_manager svc_ptcRuntime --> pkg_tools svc_ptcRuntime --> pkg_workflow_ptc + svc_remoteAccess --> pkg_api_gateway + svc_remoteAccess --> pkg_api_session_controller + svc_remoteAccess --> pkg_api_workspace_controller svc_sandbox --> pkg_bash_sandbox svc_sandbox --> pkg_terminal_bash svc_sandboxPolicy --> pkg_bash_sandbox @@ -574,6 +584,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 @@ -628,6 +639,7 @@ flowchart LR | `ctx.directoryPickerController` | `core` | [`api-workspace-controller`](../packages/api/workspace-controller) | - | - | - | 把选目录 seam 送上线:能力门禁、取消传播,以及浏览器目录流程用于分支判断的 seam 错误码。 | | `ctx.typert` | `core` | [`typert-registry`](../packages/typert/registry) | - | [`typert-loader`](../packages/typert/loader), [`api-gateway`](../packages/api/gateway) | - | 插件直接或通过 dsh-typert-loader 注册实时 zod 贡献;API 网关消费调用描述符和提供方,其他运行时消费方则在各自边界查询 schema 与反射元数据。 | | `ctx.typertGateway` | `core` | [`api-gateway`](../packages/api/gateway) | - | - | - | 将生成的 Remote 描述符与实时 Cordis 服务关联,解析已注册的身份,并通过共享的 Connection RPC 载体提供一元调用。 | +| `ctx.remoteAccess` | `core` | [`api-remote-access`](../packages/api/remote-access) | - | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller) | - | 通过业务方注册的基于 role 的 policy 判定非 owner Peer 可调用哪些 Remote 方法,过滤列表结果,并为每个 Peer 推送访问快照。 | | `ctx.sessionPersistence` | `seam` | [`session-persistence`](../packages/session/session-persistence) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | [`agent-loop`](../packages/core/agent-loop), [`tool-bash`](../packages/shell/tool-bash), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`message-feedback`](../packages/feedback/message-feedback) | - | JSONL backend 把 SessionEvent 词汇持久化为每个 Session 一份产物。 | | `ctx.configEditor` | `core` | [`config-editor`](../packages/boot/config-editor) | - | [`settings`](../packages/settings/settings), [`agent-default-model`](../packages/core/agent-default-model) | - | Persists profile config patches under the application file lock and HMR queue, then reconciles Loader entries. | | `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. | @@ -676,7 +688,7 @@ flowchart LR | `ctx.compaction` | `seam` | [`compaction`](../packages/compaction/compaction) | [`compaction-basic`](../packages/compaction/compaction-basic) | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 基础后端消费步骤后的压力事件和请求错误恢复事件;不存在面向模型的压缩工具。 | | `ctx.subagents` | `seam` | [`subagent`](../packages/subagent/subagent) | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process), [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process), [`subagent-acp`](../packages/subagent/subagent-acp), [`subagent-codex`](../packages/subagent/subagent-codex), [`subagent-claude-code`](../packages/subagent/subagent-claude-code), [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control), [`tool-ralph`](../packages/experimental/tool-ralph) | - | 提供方准备本地子级或执行外部任务;一个 activation 管理器持有两类生命周期。委派工具选择后端,控制工具投递本地后续消息,工作流等待 activation 结果。 | | `ctx.speechToText` | `seam` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | [`experimental-speech-to-text-sensevoice`](../packages/experimental/speech-to-text-sensevoice) | [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | - | 路由显式选择的识别器;浏览器使用带认证的 Remote,并在提交前将转写保留在草稿中。 | -| `ctx.agentTeams` | `core` | [`experimental-agent-team`](../packages/experimental/agent-team) | - | [`experimental-tool-agent-team`](../packages/experimental/tool-agent-team) | - | 负责隐式 Root roster、持久 peer mailbox、共享任务 DAG 与 continuable child 生命周期;tool-agent-team 提供模型控制工具。 | +| `ctx.agentTeams` | `core` | [`experimental-agent-team`](../packages/experimental/agent-team) | - | [`experimental-tool-agent-team`](../packages/experimental/tool-agent-team) | - | 负责隐式 Root roster、直接 peer inbox 投递、共享任务 DAG 与 continuable child 生命周期;tool-agent-team 提供模型控制工具。 | | `ctx.claudeCodeMods` | `core` | [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | - | - | - | 加载 defineMod 插件添加的模组,从 harness 扩展点触发其钩子链,并通过其 Remote 绘制提示框上方的横幅。 | | `ctx.inspector` | `core` | `inspector` | - | - | - | 负责 Worker 托管的 CDP target,以及独立于传输的 Host 和 Client observation 与 Cordis tree query API。 | | `ctx.jobs` | `seam` | [`jobs`](../packages/jobs/jobs) | [`jobs-local`](../packages/jobs/jobs-local) | [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`tool-terminal`](../packages/experimental/tool-terminal), [`tool-jobs`](../packages/jobs/tool-jobs), [`api-job-controller`](../packages/api/job-controller) | - | 生产方(后台 bash/pwsh 与 PTY 发送)登记正在运行的工作;声明 record 的 job 还为非消费观察者流式提供原始输出;tool-jobs 是面向模型的控制器,用于读取、列出和终止这些工作;jobs-local 是进程本地注册表。 | @@ -684,6 +696,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 4539636c4a..c14b06ac73 100644 --- a/docs/cli-help.md +++ b/docs/cli-help.md @@ -173,22 +173,31 @@ Usage: dsh --profile web [options] Serve the DeepSeek Harness browser UI. Options: - --host bind host + --host bind address: one concrete IPv4 or IPv6 literal + of a local interface; wildcard addresses are + rejected --no-open do not open the Web UI in the default browser --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) + --tls-cert PEM server certificate chain; requires + --tls-key + --tls-key unencrypted PEM private key; requires + --tls-cert -h, --help show this help Examples: dsh --profile web serve on the composed host and port dsh --profile web --no-open serve without opening a browser dsh --profile web --port 8080 serve on another port + dsh --profile web --host 10.0.0.7 bind one local interface address dsh --profile web --public-url https://app.example/ui/ --trusted-host app.example advertise a prefix-stripping HTTPS proxy entry and admit its authority + dsh --profile web --tls-cert ./server-chain.pem --tls-key ./server-key.pem + serve HTTPS with an existing certificate and key ``` diff --git a/docs/cli-help.zh.md b/docs/cli-help.zh.md index f875c988e1..f646eac073 100644 --- a/docs/cli-help.zh.md +++ b/docs/cli-help.zh.md @@ -175,22 +175,31 @@ Usage: dsh --profile web [options] Serve the DeepSeek Harness browser UI. Options: - --host bind host + --host bind address: one concrete IPv4 or IPv6 literal + of a local interface; wildcard addresses are + rejected --no-open do not open the Web UI in the default browser --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) + --tls-cert PEM server certificate chain; requires + --tls-key + --tls-key unencrypted PEM private key; requires + --tls-cert -h, --help show this help Examples: dsh --profile web serve on the composed host and port dsh --profile web --no-open serve without opening a browser dsh --profile web --port 8080 serve on another port + dsh --profile web --host 10.0.0.7 bind one local interface address dsh --profile web --public-url https://app.example/ui/ --trusted-host app.example advertise a prefix-stripping HTTPS proxy entry and admit its authority + dsh --profile web --tls-cert ./server-chain.pem --tls-key ./server-key.pem + serve HTTPS with an existing certificate and key ``` diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 3de445a55b..8bfae862ef 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -92,7 +92,7 @@ export interface Config { - `inject`: `agents` · `sessions` · `llm` · `tools` · `systemPrompt` · `sessionProjections` - `refs`: [`AgentOptions`](subsystems/core.md) · [`SessionId`](subsystems/core.md) · `Volatile` (`@deepseek-ai/cosmokit`) -- `source`: [`packages/core/agent-loop/src/index.ts:292`](../packages/core/agent-loop/src/index.ts) +- `source`: [`packages/core/agent-loop/src/index.ts:303`](../packages/core/agent-loop/src/index.ts) ```ts config-catalog /** Agent-loop plugin configuration. */ @@ -139,7 +139,7 @@ export type Config = PresetDefinition - `inject`: `loader` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/preset/agent-preset-registry/src/preset.ts:15`](../packages/preset/agent-preset-registry/src/preset.ts) +- `source`: [`packages/preset/agent-preset-registry/src/preset.ts:13`](../packages/preset/agent-preset-registry/src/preset.ts) ```ts config-catalog /** Registry selection policy. */ @@ -181,8 +181,8 @@ export interface Config { ## `@deepseek-ai/dsh-api-gateway` -- `inject`: `typert` -- `source`: [`packages/api/gateway/src/index.ts:146`](../packages/api/gateway/src/index.ts) +- `inject`: `typert` · `remoteAccess` +- `source`: [`packages/api/gateway/src/index.ts:155`](../packages/api/gateway/src/index.ts) ```ts config-catalog /** Gateway transport configuration. */ @@ -219,8 +219,8 @@ export interface Config { ## `@deepseek-ai/dsh-api-session-controller` -- `inject`: `agentDefaultModel` · `agents` · `attachments` · `fileUploads` · `fs` · `llm` · `sessions` · `sessionProjections` · `sessionQuery` · `typert` · `workspaceRegistry` -- `source`: [`packages/api/session-controller/src/index.ts:79`](../packages/api/session-controller/src/index.ts) +- `inject`: `agentDefaultModel` · `agents` · `attachments` · `fileUploads` · `fs` · `llm` · `remoteAccess` · `sessions` · `sessionProjections` · `sessionQuery` · `typert` · `workspaceRegistry` +- `source`: [`packages/api/session-controller/src/index.ts:94`](../packages/api/session-controller/src/index.ts) ```ts config-catalog /** Session Controller deployment policy. */ @@ -279,9 +279,9 @@ export interface Config { readonly maxRows: number /** Screen history rows retained for reconnecting clients. */ readonly scrollback: number - /** Maximum queued UTF-8 frame bytes per output follower before disconnection. */ + /** Maximum queued UTF-8 frame bytes per output follower and in the Client input buffer. */ readonly maxBufferedBytes: number - /** Maximum UTF-8 bytes in one input request. */ + /** Maximum raw UTF-8 bytes per input command and across unacknowledged Client input. */ readonly maxInputBytes: number /** Provider process-termination grace period in milliseconds. */ readonly disposeGraceMs: number @@ -300,8 +300,8 @@ export interface Config { ## `@deepseek-ai/dsh-api-workspace-controller` -- `inject`: `typert` · `workspaceRegistry` -- `source`: [`packages/api/workspace-controller/src/index.ts:33`](../packages/api/workspace-controller/src/index.ts) +- `inject`: `remoteAccess` · `typert` · `workspaceRegistry` +- `source`: [`packages/api/workspace-controller/src/index.ts:37`](../packages/api/workspace-controller/src/index.ts) ```ts config-catalog /** First-use directory policy for the Host account. */ @@ -435,7 +435,7 @@ export type Config = LocalConfig ## `@deepseek-ai/dsh-client-connection` - `inject`: `credentials` -- `source`: [`packages/client/connection/src/index.ts:92`](../packages/client/connection/src/index.ts) +- `source`: [`packages/client/connection/src/index.ts:93`](../packages/client/connection/src/index.ts) ```ts config-catalog /** Browser authentication, request limits, and connection recovery configuration. */ @@ -444,11 +444,9 @@ export interface ConnectionConfig { recovery?: ConnectionRecoveryConfig /** * Authorities this deployment serves beyond loopback: exact `host:port`, or - * port-less `host` matching any port. The /api trust fence refuses any - * request whose Host is neither loopback nor listed here, so a - * non-loopback (`0.0.0.0`) deployment must declare the names it is reached - * by; the Web runtime derives LAN IP literals from an active all-interface - * bind. An entry that is not a bare, canonical authority fails plugin load. + * port-less `host` matching any port. The fence accepts loopback and the + * listener's own bind IP independently; other remote authorities require + * an entry here. A non-canonical or non-bare authority fails plugin load. */ trustedHosts?: string[] /** Absolute browser-session lifetime in days. Default: 30. */ @@ -757,7 +755,7 @@ export interface ToolResultPruneConfig { ## `@deepseek-ai/dsh-cordis-host-runner` - `inject`: `tools` -- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:93`](../packages/extensions/cordis-host-runner/src/index.ts) +- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:103`](../packages/extensions/cordis-host-runner/src/index.ts) ```ts config-catalog /** Runner configuration. */ @@ -839,7 +837,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-agent-team` - `inject`: `agents` · `sessions` · `sessionPersistence` · `sessionProjections` · `subagents` -- `source`: [`packages/experimental/agent-team/src/types.ts:152`](../packages/experimental/agent-team/src/types.ts) +- `source`: [`packages/experimental/agent-team/src/types.ts:153`](../packages/experimental/agent-team/src/types.ts) ```ts config-catalog /** Team-service deployment limits. */ @@ -848,11 +846,9 @@ export interface Config { readonly maxMembers?: number /** Maximum non-deleted tasks retained by one Team. */ readonly maxTasks?: number - /** Maximum queued-minus-delivered messages for one target member. */ - readonly maxPendingMessagesPerMember?: number /** Maximum UTF-8 bytes in one complete sender-framed delivery. */ readonly maxMessageBytes?: number - /** Maximum milliseconds allowed for Team-owned runtime disposal. */ + /** Maximum milliseconds for shared operation settlement and for each Team child drain. */ readonly disposalTimeoutMs?: number } ``` @@ -1222,6 +1218,8 @@ export interface Config { minSpeechSeconds: number /** Silence separating two speech segments. */ minSilenceSeconds: number + /** Recording audio restored ahead of the first VAD segment, which cold start reports late; zero disables it. */ + vadOnsetPaddingSeconds: number /** Maximum decoded WAV bytes accepted by the private worker. */ maxAudioBytes: number /** Deadline for runtime preparation and cold model loading. */ @@ -1255,6 +1253,8 @@ export interface Config { ```ts config-catalog /** Tool routing configuration. */ export interface Config { + /** Register `interrupt_agent` and its policy guidance. Defaults to true; false leaves the domain API available. */ + readonly interrupt?: boolean /** Continuable-subagent provider used for fresh teammates. */ readonly freshProvider?: string /** Continuable-subagent provider used for completed-prefix fork teammates. */ @@ -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 @@ -1437,7 +1437,7 @@ export interface Config { ## `@deepseek-ai/dsh-hmr` - `refs`: `ChokidarOptions` (`chokidar`) -- `source`: [`packages/boot/hmr/src/index.ts:53`](../packages/boot/hmr/src/index.ts) +- `source`: [`packages/boot/hmr/src/index.ts:56`](../packages/boot/hmr/src/index.ts) ```ts config-catalog /** Module roots and watcher timing, with Chokidar deployment options. */ @@ -1628,15 +1628,32 @@ export interface Config { ## `@deepseek-ai/dsh-host-webserver` -- `source`: [`packages/host/webserver/src/index.ts:59`](../packages/host/webserver/src/index.ts) +- `source`: [`packages/host/webserver/src/index.ts:76`](../packages/host/webserver/src/index.ts) ```ts config-catalog -/** Web server listen and response-compression config. */ +/** Web server listen, TLS, and response-compression config. */ export interface Config { - /** Listen host; the two supported values are loopback and all-interfaces. */ - host: '127.0.0.1' | '0.0.0.0' + /** + * Listen address: a concrete IPv4 or IPv6 literal of one local interface, + * for example the container's own Pod address from `hostname -i`. A loopback + * literal (any address in 127/8, `::1`, or a mapped form of either) keeps the + * server on this machine; any other literal serves the network that address + * belongs to, over plain HTTP unless `tls` is set. The unspecified address — + * IPv4 any, IPv6 any, and the IPv4-mapped forms of IPv4 any — is rejected at + * load: it would expose the port on every interface at once. + */ + host: string /** Listen port; zero requests an OS-assigned port. */ port: number + /** + * Serve HTTPS with this certificate and key instead of plain HTTP. Both files + * are read once, before the listener binds: an unreadable or empty file, + * invalid PEM, or a key that does not match the certificate rejects + * initialization rather than falling back to HTTP. The material is never + * re-read, so replacing a certificate takes a reload. Omitted or null listens + * over plain HTTP. + */ + tls?: TlsConfig /** Response compression for socket-backed HTTP requests. @default 'none' */ compression?: 'none' | 'gzip' /** Gzip DEFLATE level from 0 through 9. @default 1 */ @@ -1644,6 +1661,18 @@ export interface Config { /** Minimum known response length eligible for gzip; unknown-length streams are eligible. @default 1024 */ compressionThresholdBytes?: number } + +/** + * TLS material for the HTTPS listener: one certificate chain file and the + * private key file it pairs with. Both hold PEM text and both resolve against + * the process working directory. + */ +export interface TlsConfig { + /** Certificate chain file, leaf certificate first, PEM, no passphrase. */ + certFile: string + /** Private key file for the chain's leaf certificate; unencrypted PEM. */ + keyFile: string +} ``` @@ -1652,7 +1681,7 @@ export interface Config { ## `@deepseek-ai/dsh-jobs-local` -- `source`: [`packages/jobs/jobs-local/src/index.ts:45`](../packages/jobs/jobs-local/src/index.ts) +- `source`: [`packages/jobs/jobs-local/src/index.ts:46`](../packages/jobs/jobs-local/src/index.ts) ```ts config-catalog /** Configuration for the process-local job registry. */ @@ -1682,12 +1711,25 @@ export interface Config { ## `@deepseek-ai/dsh-llm-deepseek-account` - `inject`: `llm` -- `refs`: [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) -- `source`: [`packages/llm/llm-deepseek-account/src/config.ts:5`](../packages/llm/llm-deepseek-account/src/config.ts) +- `refs`: [`DeepSeekCatalogModel`](../packages/llm/llm-deepseek/src/index.ts) · [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`) +- `source`: [`packages/llm/llm-deepseek-account/src/config.ts:19`](../packages/llm/llm-deepseek-account/src/config.ts) ```ts config-catalog /** Account route configuration; authentication comes exclusively from the account service. */ -export type Config = ProtocolConfig +export interface Config extends Omit { + /** Deadline of one listing request, which also bounds a first-use wait (default five seconds). */ + modelsTimeoutMs: Volatile + /** + * Listing age after which the next access refreshes it in the background; + * a failed load retries after the same age (default ten minutes). + */ + modelsMaxAgeMs: Volatile + /** Field overrides by model id, layered over the account listing and the built-in catalog. */ + modelOverrides: Volatile> +} + +/** Field overrides for one model; unset fields and empty lists inherit the underlying entry. */ +export type ModelOverride = Omit ``` @@ -2362,7 +2404,7 @@ export interface PlanModeConfig { ## `@deepseek-ai/dsh-plugin-manager` - `inject`: `loader` · `profileContext` -- `source`: [`packages/boot/plugin-manager/src/index.ts:44`](../packages/boot/plugin-manager/src/index.ts) +- `source`: [`packages/boot/plugin-manager/src/index.ts:42`](../packages/boot/plugin-manager/src/index.ts) ```ts config-catalog /** The pnpm executable, registries, and limits for diagnostics, lookups and connection checks. */ @@ -2414,11 +2456,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:26`](../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 extends LaunchConfig { +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. */ @@ -2435,12 +2481,19 @@ export interface Config extends LaunchConfig { graceMs?: number } -/** Deployment-owned Node executable and optional preinstalled built bootstrap. */ -export interface LaunchConfig { - /** Executable in the subprocess world; defaults to the current Node executable. */ - nodeExecutable?: string - /** Absolute preinstalled built bootstrap in the execution world. */ +/** Deployment-owned worker invocation in the subprocess execution world. */ +export type LaunchConfig = { + /** Start a separately installed Node executable and JavaScript bootstrap. */ + kind: 'node-script' + /** Executable name or path resolved by the subprocess provider. */ + executable: string + /** Absolute preinstalled bootstrap; omitted maps this package's bootstrap into the execution world. */ bootstrapPath?: string +} | { + /** Start the private PTC worker embedded in a packaged executable. */ + kind: 'embedded' + /** Packaged executable name or path resolved by the subprocess provider. */ + executable: string } ``` @@ -2716,10 +2769,10 @@ export type SessionLogCompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ## `@deepseek-ai/dsh-session-persistence-jsonl` -- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:90`](../packages/session/session-persistence-jsonl/src/index.ts) +- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:94`](../packages/session/session-persistence-jsonl/src/index.ts) ```ts config-catalog -/** Plugin config for the JSONL backend's root and physical encoding. */ +/** Plugin config for the JSONL backend's root, physical encoding, and listing concurrency. */ export interface Config { /** * Root directory for all session files. Required (no default): a default of @@ -2731,6 +2784,12 @@ export interface Config { root: string /** Physical encoding; defaults to checksummed Zstandard frames. */ compression?: JsonlCompression + /** + * Maximum directory, header, and stat reads in flight across all concurrent + * listings of this backend (`list()`, the root encoding check, and historical + * fingerprints). Defaults to 3. + */ + listConcurrency?: number } /** Physical encoding selected for JSONL session artifacts. */ @@ -2909,11 +2968,16 @@ export interface Config { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:15`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) +- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:28`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) ```ts config-catalog -/** Required LLM policy; this plugin adds no defaults. */ -export type Config = SessionTitleLlmConfig +/** Required execution controls plus this provider's title-length targets; no defaults. */ +export interface Config extends SessionTitleLlmConfig { + /** Target word count for non-CJK titles. */ + readonly targetWords: number + /** Target character count for Chinese, Japanese, or Korean titles. */ + readonly targetCjkCharacters: number +} ``` @@ -2924,11 +2988,16 @@ export type Config = SessionTitleLlmConfig - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:15`](../packages/session/session-title-first-prompt-llm/src/index.ts) +- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:28`](../packages/session/session-title-first-prompt-llm/src/index.ts) ```ts config-catalog -/** Required LLM policy; this plugin adds no defaults. */ -export type Config = SessionTitleLlmConfig +/** Required execution controls plus this provider's title-length targets; no defaults. */ +export interface Config extends SessionTitleLlmConfig { + /** Target word count for non-CJK titles. */ + readonly targetWords: number + /** Target character count for Chinese, Japanese, or Korean titles. */ + readonly targetCjkCharacters: number +} ``` @@ -3014,7 +3083,7 @@ export interface Config { ```ts config-catalog /** Office skill resource location. */ export interface Config { - /** Absolute assets directory containing the three skill folders and shared scripts; defaults to packaged assets. */ + /** Absolute assets directory containing skill folders; defaults to packaged assets. */ assetRoot?: string /** Standalone Node executable; defaults to the current executable outside Electron and SEA. */ node?: string @@ -3077,25 +3146,21 @@ export interface Config { ## `@deepseek-ai/dsh-ssh` -- `source`: [`packages/ssh/ssh/src/index.ts:17`](../packages/ssh/ssh/src/index.ts) +- `source`: [`packages/ssh/ssh/src/index.ts:33`](../packages/ssh/ssh/src/index.ts) ```ts config-catalog /** Deployment-owned SSH identity and installed helper; no model argument selects these values. */ export interface Config { /** OpenSSH host alias, including its existing user, key and known-host configuration. */ host: string - /** Absolute remote Node executable. */ - node: string + /** Explicit script or self-contained executable invocation. */ + launch: HelperLaunch /** Absolute path to the installed, bundled helper entry. */ helper: string /** SHA-256 of that bundled helper; mismatches refuse the connection. */ helperHash: string /** Absolute remote default workspace. */ workspace: string - /** Optional preinstalled built PTC entry, paired with its expected digest. */ - bootstrapPath?: string - /** SHA-256 of bootstrapPath; both fields must be supplied together. */ - bootstrapHash?: string /** Connection and administrative-request deadline, at most 2,147,483,647 milliseconds. */ requestTimeoutMs?: number /** Maximum JSON payload bytes per helper request or response. */ @@ -3105,6 +3170,21 @@ export interface Config { /** Remote helper lease; loss of heartbeats starts remote managed cleanup. */ leaseMs?: number } + +/** Installed helper invocation; script deployments may also install a PTC bootstrap. */ +export type HelperLaunch = { + /** Run the installed script with a separately installed Node executable. */ + kind: 'node-script' + /** Absolute remote Node executable. */ + node: string + /** Absolute remote PTC bootstrap; requires bootstrapHash. */ + bootstrapPath?: string + /** Lowercase SHA-256 of bootstrapPath; requires that path. */ + bootstrapHash?: string +} | { + /** Run the helper executable with its embedded Node and PTC worker. */ + kind: 'executable' +} ``` @@ -3202,7 +3282,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' - `inject`: `workingDirectory` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/subagent/subagent/src/index.ts:184`](../packages/subagent/subagent/src/index.ts) +- `source`: [`packages/subagent/subagent/src/index.ts:186`](../packages/subagent/subagent/src/index.ts) ```ts config-catalog /** Host configuration for continuable subagent capacity. */ @@ -3418,7 +3498,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:258`](../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). */ @@ -3640,6 +3720,14 @@ export interface Config { ```ts config-catalog /** Plugin config (all optional — `Config` supplies the defaults). */ export interface Config { + /** Register `read` and its guidance. Defaults to true. */ + read?: boolean + /** Register `read_image` while an attachment store is mounted. Defaults to true. */ + readImage?: boolean + /** Register `write` and its guidance. Defaults to true. */ + write?: boolean + /** Register `edit` and its guidance. Defaults to true. */ + edit?: boolean /** Default and maximum number of lines returned by one `read` call. */ readLimit?: number /** Maximum characters returned for a single line before truncation. */ @@ -3918,11 +4006,11 @@ export interface Config { - `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections` - `refs`: [`AgentOptions`](subsystems/core.md) -- `source`: [`packages/subagent/tool-subagent/src/index.ts:48`](../packages/subagent/tool-subagent/src/index.ts) +- `source`: [`packages/subagent/tool-subagent/src/index.ts:50`](../packages/subagent/tool-subagent/src/index.ts) ```ts config-catalog /** Config: which registered provider this tool delegates to, plus child defaults. */ -export interface Config { +export interface Config extends PresetSelectionConfig { /** The `ctx.subagents` provider name to start runs on (e.g. `spawn`, `acp`). */ provider: string /** @@ -3939,22 +4027,6 @@ export interface Config { * Agent options applied to every child; omitted fields use child-loop defaults. */ agentOptions?: AgentOptions - /** - * Per-child persona that shadows `deployment:persona-prefix`. Requires the - * provider's `persona` capability; omission preserves the deployment persona. - */ - persona?: string - /** - * Tool filter applied to every child. Filtered tools disappear from its - * prompt and reject execution. Requires the provider's `toolFilter` - * capability; unknown names fail startup. - */ - toolFilter?: { - /** Global tool names the child keeps; everything else is removed. */ - allow?: string[] - /** Global tool names removed from the child. */ - deny?: string[] - } /** * Maximum child depth: a non-negative safe integer (`0` forbids delegation), * or `'provider-managed'` to send no cap. A numeric cap @@ -3967,6 +4039,14 @@ export interface Config { */ maxDepth?: number | 'provider-managed' } + +/** Optional default and model-selectable preset ids for a spawn tool. */ +export interface PresetSelectionConfig { + /** Default independent preset; omission inherits the parent when the model makes no selection. */ + agentPreset?: string + /** Non-empty allowlist exposing agent_preset to the model; omission disables model selection. */ + allowedAgentPresets?: string[] | undefined +} ``` @@ -4207,7 +4287,7 @@ export interface WebRuntimeConfig { ## `@deepseek-ai/dsh-web-app` - `inject`: `webServer` -- `source`: [`packages/bundle/web-app/src/index.ts:46`](../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. */ @@ -4217,22 +4297,18 @@ 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 `/`. Advertisement only; - * see [public deployments](../README.md#public-deployments). Absent or YAML - * `null` advertises the loopback URL. + * `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. */ publicUrl?: string - /** Explicit `--trusted-host` authorities from this invocation. */ - trustedHosts: string[] } ``` @@ -4445,6 +4521,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-acp-app` | `cmdlineArgs` | [`packages/bundle/acp-app/src/index.ts`](../packages/bundle/acp-app/src/index.ts) | | `@deepseek-ai/dsh-agent` | — | [`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts) | | `@deepseek-ai/dsh-api-account-controller` | `deepseekAccount` · `agents` | [`packages/api/account-controller/src/index.ts`](../packages/api/account-controller/src/index.ts) | +| `@deepseek-ai/dsh-api-remote-access` | — | [`packages/api/remote-access/src/index.ts`](../packages/api/remote-access/src/index.ts) | | `@deepseek-ai/dsh-api-remotes` | `typertGateway` | [`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts) | | `@deepseek-ai/dsh-authorization` | `credentials` | [`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts) | | `@deepseek-ai/dsh-browser-use` | — | [`packages/browser-use/browser-use/src/index.ts`](../packages/browser-use/browser-use/src/index.ts) | @@ -4475,6 +4552,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) | @@ -4517,7 +4595,8 @@ 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-host-directory-picker-auto` | `webServer` · `loader` | [`packages/host/directory-picker-auto/src/index.ts`](../packages/host/directory-picker-auto/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) | | `@deepseek-ai/dsh-llm` | — | [`packages/llm/llm/src/index.ts`](../packages/llm/llm/src/index.ts) | @@ -4631,6 +4710,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. | `@deepseek-ai/dsh-session-snapshot` | — | [`packages/test-support/session-snapshot/src/index.ts`](../packages/test-support/session-snapshot/src/index.ts) | | `@deepseek-ai/dsh-session-telemetry` | — | [`packages/session/session-telemetry/src/index.ts`](../packages/session/session-telemetry/src/index.ts) | | `@deepseek-ai/dsh-session-title-llm` | — | [`packages/session/session-title-llm/src/index.ts`](../packages/session/session-title-llm/src/index.ts) | +| `@deepseek-ai/dsh-ssh-helper-runtime` | — | [`packages/ssh/ssh-helper-runtime/src/index.ts`](../packages/ssh/ssh-helper-runtime/src/index.ts) | | `@deepseek-ai/dsh-timeout` | — | [`packages/util/timeout/src/index.ts`](../packages/util/timeout/src/index.ts) | | `@deepseek-ai/dsh-typert-generator` | — | [`packages/typert/generator/src/index.ts`](../packages/typert/generator/src/index.ts) | | `@deepseek-ai/dsh-typert-protocol` | — | [`packages/typert/protocol/src/index.ts`](../packages/typert/protocol/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 6682104549..68dfbf1852 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -94,7 +94,7 @@ export interface Config { - `inject`: `agents` · `sessions` · `llm` · `tools` · `systemPrompt` · `sessionProjections` - `refs`: [`AgentOptions`](subsystems/core.zh.md) · [`SessionId`](subsystems/core.zh.md) · `Volatile` (`@deepseek-ai/cosmokit`) -- `source`: [`packages/core/agent-loop/src/index.ts:292`](../packages/core/agent-loop/src/index.ts) +- `source`: [`packages/core/agent-loop/src/index.ts:303`](../packages/core/agent-loop/src/index.ts) ```ts config-catalog /** Agent-loop plugin configuration. */ @@ -141,7 +141,7 @@ export type Config = PresetDefinition - `inject`: `loader` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/preset/agent-preset-registry/src/preset.ts:15`](../packages/preset/agent-preset-registry/src/preset.ts) +- `source`: [`packages/preset/agent-preset-registry/src/preset.ts:13`](../packages/preset/agent-preset-registry/src/preset.ts) ```ts config-catalog /** Registry selection policy. */ @@ -183,8 +183,8 @@ export interface Config { ## `@deepseek-ai/dsh-api-gateway` -- `inject`: `typert` -- `source`: [`packages/api/gateway/src/index.ts:146`](../packages/api/gateway/src/index.ts) +- `inject`: `typert` · `remoteAccess` +- `source`: [`packages/api/gateway/src/index.ts:155`](../packages/api/gateway/src/index.ts) ```ts config-catalog /** Gateway transport configuration. */ @@ -221,8 +221,8 @@ export interface Config { ## `@deepseek-ai/dsh-api-session-controller` -- `inject`: `agentDefaultModel` · `agents` · `attachments` · `fileUploads` · `fs` · `llm` · `sessions` · `sessionProjections` · `sessionQuery` · `typert` · `workspaceRegistry` -- `source`: [`packages/api/session-controller/src/index.ts:79`](../packages/api/session-controller/src/index.ts) +- `inject`: `agentDefaultModel` · `agents` · `attachments` · `fileUploads` · `fs` · `llm` · `remoteAccess` · `sessions` · `sessionProjections` · `sessionQuery` · `typert` · `workspaceRegistry` +- `source`: [`packages/api/session-controller/src/index.ts:94`](../packages/api/session-controller/src/index.ts) ```ts config-catalog /** Session Controller deployment policy. */ @@ -281,9 +281,9 @@ export interface Config { readonly maxRows: number /** Screen history rows retained for reconnecting clients. */ readonly scrollback: number - /** Maximum queued UTF-8 frame bytes per output follower before disconnection. */ + /** Maximum queued UTF-8 frame bytes per output follower and in the Client input buffer. */ readonly maxBufferedBytes: number - /** Maximum UTF-8 bytes in one input request. */ + /** Maximum raw UTF-8 bytes per input command and across unacknowledged Client input. */ readonly maxInputBytes: number /** Provider process-termination grace period in milliseconds. */ readonly disposeGraceMs: number @@ -302,8 +302,8 @@ export interface Config { ## `@deepseek-ai/dsh-api-workspace-controller` -- `inject`: `typert` · `workspaceRegistry` -- `source`: [`packages/api/workspace-controller/src/index.ts:33`](../packages/api/workspace-controller/src/index.ts) +- `inject`: `remoteAccess` · `typert` · `workspaceRegistry` +- `source`: [`packages/api/workspace-controller/src/index.ts:37`](../packages/api/workspace-controller/src/index.ts) ```ts config-catalog /** First-use directory policy for the Host account. */ @@ -437,7 +437,7 @@ export type Config = LocalConfig ## `@deepseek-ai/dsh-client-connection` - `inject`: `credentials` -- `source`: [`packages/client/connection/src/index.ts:92`](../packages/client/connection/src/index.ts) +- `source`: [`packages/client/connection/src/index.ts:93`](../packages/client/connection/src/index.ts) ```ts config-catalog /** Browser authentication, request limits, and connection recovery configuration. */ @@ -446,11 +446,9 @@ export interface ConnectionConfig { recovery?: ConnectionRecoveryConfig /** * Authorities this deployment serves beyond loopback: exact `host:port`, or - * port-less `host` matching any port. The /api trust fence refuses any - * request whose Host is neither loopback nor listed here, so a - * non-loopback (`0.0.0.0`) deployment must declare the names it is reached - * by; the Web runtime derives LAN IP literals from an active all-interface - * bind. An entry that is not a bare, canonical authority fails plugin load. + * port-less `host` matching any port. The fence accepts loopback and the + * listener's own bind IP independently; other remote authorities require + * an entry here. A non-canonical or non-bare authority fails plugin load. */ trustedHosts?: string[] /** Absolute browser-session lifetime in days. Default: 30. */ @@ -759,7 +757,7 @@ export interface ToolResultPruneConfig { ## `@deepseek-ai/dsh-cordis-host-runner` - `inject`: `tools` -- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:93`](../packages/extensions/cordis-host-runner/src/index.ts) +- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:103`](../packages/extensions/cordis-host-runner/src/index.ts) ```ts config-catalog /** Runner configuration. */ @@ -841,7 +839,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-agent-team` - `inject`: `agents` · `sessions` · `sessionPersistence` · `sessionProjections` · `subagents` -- `source`: [`packages/experimental/agent-team/src/types.ts:152`](../packages/experimental/agent-team/src/types.ts) +- `source`: [`packages/experimental/agent-team/src/types.ts:153`](../packages/experimental/agent-team/src/types.ts) ```ts config-catalog /** Team-service deployment limits. */ @@ -850,11 +848,9 @@ export interface Config { readonly maxMembers?: number /** Maximum non-deleted tasks retained by one Team. */ readonly maxTasks?: number - /** Maximum queued-minus-delivered messages for one target member. */ - readonly maxPendingMessagesPerMember?: number /** Maximum UTF-8 bytes in one complete sender-framed delivery. */ readonly maxMessageBytes?: number - /** Maximum milliseconds allowed for Team-owned runtime disposal. */ + /** Maximum milliseconds for shared operation settlement and for each Team child drain. */ readonly disposalTimeoutMs?: number } ``` @@ -1224,6 +1220,8 @@ export interface Config { minSpeechSeconds: number /** Silence separating two speech segments. */ minSilenceSeconds: number + /** Recording audio restored ahead of the first VAD segment, which cold start reports late; zero disables it. */ + vadOnsetPaddingSeconds: number /** Maximum decoded WAV bytes accepted by the private worker. */ maxAudioBytes: number /** Deadline for runtime preparation and cold model loading. */ @@ -1257,6 +1255,8 @@ export interface Config { ```ts config-catalog /** Tool routing configuration. */ export interface Config { + /** Register `interrupt_agent` and its policy guidance. Defaults to true; false leaves the domain API available. */ + readonly interrupt?: boolean /** Continuable-subagent provider used for fresh teammates. */ readonly freshProvider?: string /** Continuable-subagent provider used for completed-prefix fork teammates. */ @@ -1319,7 +1319,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 @@ -1439,7 +1439,7 @@ export interface Config { ## `@deepseek-ai/dsh-hmr` - `refs`: `ChokidarOptions` (`chokidar`) -- `source`: [`packages/boot/hmr/src/index.ts:53`](../packages/boot/hmr/src/index.ts) +- `source`: [`packages/boot/hmr/src/index.ts:56`](../packages/boot/hmr/src/index.ts) ```ts config-catalog /** Module roots and watcher timing, with Chokidar deployment options. */ @@ -1630,15 +1630,32 @@ export interface Config { ## `@deepseek-ai/dsh-host-webserver` -- `source`: [`packages/host/webserver/src/index.ts:59`](../packages/host/webserver/src/index.ts) +- `source`: [`packages/host/webserver/src/index.ts:76`](../packages/host/webserver/src/index.ts) ```ts config-catalog -/** Web server listen and response-compression config. */ +/** Web server listen, TLS, and response-compression config. */ export interface Config { - /** Listen host; the two supported values are loopback and all-interfaces. */ - host: '127.0.0.1' | '0.0.0.0' + /** + * Listen address: a concrete IPv4 or IPv6 literal of one local interface, + * for example the container's own Pod address from `hostname -i`. A loopback + * literal (any address in 127/8, `::1`, or a mapped form of either) keeps the + * server on this machine; any other literal serves the network that address + * belongs to, over plain HTTP unless `tls` is set. The unspecified address — + * IPv4 any, IPv6 any, and the IPv4-mapped forms of IPv4 any — is rejected at + * load: it would expose the port on every interface at once. + */ + host: string /** Listen port; zero requests an OS-assigned port. */ port: number + /** + * Serve HTTPS with this certificate and key instead of plain HTTP. Both files + * are read once, before the listener binds: an unreadable or empty file, + * invalid PEM, or a key that does not match the certificate rejects + * initialization rather than falling back to HTTP. The material is never + * re-read, so replacing a certificate takes a reload. Omitted or null listens + * over plain HTTP. + */ + tls?: TlsConfig /** Response compression for socket-backed HTTP requests. @default 'none' */ compression?: 'none' | 'gzip' /** Gzip DEFLATE level from 0 through 9. @default 1 */ @@ -1646,6 +1663,18 @@ export interface Config { /** Minimum known response length eligible for gzip; unknown-length streams are eligible. @default 1024 */ compressionThresholdBytes?: number } + +/** + * TLS material for the HTTPS listener: one certificate chain file and the + * private key file it pairs with. Both hold PEM text and both resolve against + * the process working directory. + */ +export interface TlsConfig { + /** Certificate chain file, leaf certificate first, PEM, no passphrase. */ + certFile: string + /** Private key file for the chain's leaf certificate; unencrypted PEM. */ + keyFile: string +} ``` @@ -1654,7 +1683,7 @@ export interface Config { ## `@deepseek-ai/dsh-jobs-local` -- `source`: [`packages/jobs/jobs-local/src/index.ts:45`](../packages/jobs/jobs-local/src/index.ts) +- `source`: [`packages/jobs/jobs-local/src/index.ts:46`](../packages/jobs/jobs-local/src/index.ts) ```ts config-catalog /** Configuration for the process-local job registry. */ @@ -1684,12 +1713,25 @@ export interface Config { ## `@deepseek-ai/dsh-llm-deepseek-account` - `inject`: `llm` -- `refs`: [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) -- `source`: [`packages/llm/llm-deepseek-account/src/config.ts:5`](../packages/llm/llm-deepseek-account/src/config.ts) +- `refs`: [`DeepSeekCatalogModel`](../packages/llm/llm-deepseek/src/index.ts) · [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`) +- `source`: [`packages/llm/llm-deepseek-account/src/config.ts:19`](../packages/llm/llm-deepseek-account/src/config.ts) ```ts config-catalog /** Account route configuration; authentication comes exclusively from the account service. */ -export type Config = ProtocolConfig +export interface Config extends Omit { + /** Deadline of one listing request, which also bounds a first-use wait (default five seconds). */ + modelsTimeoutMs: Volatile + /** + * Listing age after which the next access refreshes it in the background; + * a failed load retries after the same age (default ten minutes). + */ + modelsMaxAgeMs: Volatile + /** Field overrides by model id, layered over the account listing and the built-in catalog. */ + modelOverrides: Volatile> +} + +/** Field overrides for one model; unset fields and empty lists inherit the underlying entry. */ +export type ModelOverride = Omit ``` @@ -2364,7 +2406,7 @@ export interface PlanModeConfig { ## `@deepseek-ai/dsh-plugin-manager` - `inject`: `loader` · `profileContext` -- `source`: [`packages/boot/plugin-manager/src/index.ts:44`](../packages/boot/plugin-manager/src/index.ts) +- `source`: [`packages/boot/plugin-manager/src/index.ts:42`](../packages/boot/plugin-manager/src/index.ts) ```ts config-catalog /** The pnpm executable, registries, and limits for diagnostics, lookups and connection checks. */ @@ -2416,11 +2458,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:26`](../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 extends LaunchConfig { +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. */ @@ -2437,12 +2483,19 @@ export interface Config extends LaunchConfig { graceMs?: number } -/** Deployment-owned Node executable and optional preinstalled built bootstrap. */ -export interface LaunchConfig { - /** Executable in the subprocess world; defaults to the current Node executable. */ - nodeExecutable?: string - /** Absolute preinstalled built bootstrap in the execution world. */ +/** Deployment-owned worker invocation in the subprocess execution world. */ +export type LaunchConfig = { + /** Start a separately installed Node executable and JavaScript bootstrap. */ + kind: 'node-script' + /** Executable name or path resolved by the subprocess provider. */ + executable: string + /** Absolute preinstalled bootstrap; omitted maps this package's bootstrap into the execution world. */ bootstrapPath?: string +} | { + /** Start the private PTC worker embedded in a packaged executable. */ + kind: 'embedded' + /** Packaged executable name or path resolved by the subprocess provider. */ + executable: string } ``` @@ -2718,10 +2771,10 @@ export type SessionLogCompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ## `@deepseek-ai/dsh-session-persistence-jsonl` -- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:90`](../packages/session/session-persistence-jsonl/src/index.ts) +- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:94`](../packages/session/session-persistence-jsonl/src/index.ts) ```ts config-catalog -/** Plugin config for the JSONL backend's root and physical encoding. */ +/** Plugin config for the JSONL backend's root, physical encoding, and listing concurrency. */ export interface Config { /** * Root directory for all session files. Required (no default): a default of @@ -2733,6 +2786,12 @@ export interface Config { root: string /** Physical encoding; defaults to checksummed Zstandard frames. */ compression?: JsonlCompression + /** + * Maximum directory, header, and stat reads in flight across all concurrent + * listings of this backend (`list()`, the root encoding check, and historical + * fingerprints). Defaults to 3. + */ + listConcurrency?: number } /** Physical encoding selected for JSONL session artifacts. */ @@ -2911,11 +2970,16 @@ export interface Config { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:15`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) +- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:28`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) ```ts config-catalog -/** Required LLM policy; this plugin adds no defaults. */ -export type Config = SessionTitleLlmConfig +/** Required execution controls plus this provider's title-length targets; no defaults. */ +export interface Config extends SessionTitleLlmConfig { + /** Target word count for non-CJK titles. */ + readonly targetWords: number + /** Target character count for Chinese, Japanese, or Korean titles. */ + readonly targetCjkCharacters: number +} ``` @@ -2926,11 +2990,16 @@ export type Config = SessionTitleLlmConfig - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:15`](../packages/session/session-title-first-prompt-llm/src/index.ts) +- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:28`](../packages/session/session-title-first-prompt-llm/src/index.ts) ```ts config-catalog -/** Required LLM policy; this plugin adds no defaults. */ -export type Config = SessionTitleLlmConfig +/** Required execution controls plus this provider's title-length targets; no defaults. */ +export interface Config extends SessionTitleLlmConfig { + /** Target word count for non-CJK titles. */ + readonly targetWords: number + /** Target character count for Chinese, Japanese, or Korean titles. */ + readonly targetCjkCharacters: number +} ``` @@ -3016,7 +3085,7 @@ export interface Config { ```ts config-catalog /** Office skill resource location. */ export interface Config { - /** Absolute assets directory containing the three skill folders and shared scripts; defaults to packaged assets. */ + /** Absolute assets directory containing skill folders; defaults to packaged assets. */ assetRoot?: string /** Standalone Node executable; defaults to the current executable outside Electron and SEA. */ node?: string @@ -3079,25 +3148,21 @@ export interface Config { ## `@deepseek-ai/dsh-ssh` -- `source`: [`packages/ssh/ssh/src/index.ts:17`](../packages/ssh/ssh/src/index.ts) +- `source`: [`packages/ssh/ssh/src/index.ts:33`](../packages/ssh/ssh/src/index.ts) ```ts config-catalog /** Deployment-owned SSH identity and installed helper; no model argument selects these values. */ export interface Config { /** OpenSSH host alias, including its existing user, key and known-host configuration. */ host: string - /** Absolute remote Node executable. */ - node: string + /** Explicit script or self-contained executable invocation. */ + launch: HelperLaunch /** Absolute path to the installed, bundled helper entry. */ helper: string /** SHA-256 of that bundled helper; mismatches refuse the connection. */ helperHash: string /** Absolute remote default workspace. */ workspace: string - /** Optional preinstalled built PTC entry, paired with its expected digest. */ - bootstrapPath?: string - /** SHA-256 of bootstrapPath; both fields must be supplied together. */ - bootstrapHash?: string /** Connection and administrative-request deadline, at most 2,147,483,647 milliseconds. */ requestTimeoutMs?: number /** Maximum JSON payload bytes per helper request or response. */ @@ -3107,6 +3172,21 @@ export interface Config { /** Remote helper lease; loss of heartbeats starts remote managed cleanup. */ leaseMs?: number } + +/** Installed helper invocation; script deployments may also install a PTC bootstrap. */ +export type HelperLaunch = { + /** Run the installed script with a separately installed Node executable. */ + kind: 'node-script' + /** Absolute remote Node executable. */ + node: string + /** Absolute remote PTC bootstrap; requires bootstrapHash. */ + bootstrapPath?: string + /** Lowercase SHA-256 of bootstrapPath; requires that path. */ + bootstrapHash?: string +} | { + /** Run the helper executable with its embedded Node and PTC worker. */ + kind: 'executable' +} ``` @@ -3204,7 +3284,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' - `inject`: `workingDirectory` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/subagent/subagent/src/index.ts:184`](../packages/subagent/subagent/src/index.ts) +- `source`: [`packages/subagent/subagent/src/index.ts:186`](../packages/subagent/subagent/src/index.ts) ```ts config-catalog /** Host configuration for continuable subagent capacity. */ @@ -3420,7 +3500,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:258`](../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). */ @@ -3642,6 +3722,14 @@ export interface Config { ```ts config-catalog /** Plugin config (all optional — `Config` supplies the defaults). */ export interface Config { + /** Register `read` and its guidance. Defaults to true. */ + read?: boolean + /** Register `read_image` while an attachment store is mounted. Defaults to true. */ + readImage?: boolean + /** Register `write` and its guidance. Defaults to true. */ + write?: boolean + /** Register `edit` and its guidance. Defaults to true. */ + edit?: boolean /** Default and maximum number of lines returned by one `read` call. */ readLimit?: number /** Maximum characters returned for a single line before truncation. */ @@ -3920,11 +4008,11 @@ export interface Config { - `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections` - `refs`: [`AgentOptions`](subsystems/core.zh.md) -- `source`: [`packages/subagent/tool-subagent/src/index.ts:48`](../packages/subagent/tool-subagent/src/index.ts) +- `source`: [`packages/subagent/tool-subagent/src/index.ts:50`](../packages/subagent/tool-subagent/src/index.ts) ```ts config-catalog /** Config: which registered provider this tool delegates to, plus child defaults. */ -export interface Config { +export interface Config extends PresetSelectionConfig { /** The `ctx.subagents` provider name to start runs on (e.g. `spawn`, `acp`). */ provider: string /** @@ -3941,22 +4029,6 @@ export interface Config { * Agent options applied to every child; omitted fields use child-loop defaults. */ agentOptions?: AgentOptions - /** - * Per-child persona that shadows `deployment:persona-prefix`. Requires the - * provider's `persona` capability; omission preserves the deployment persona. - */ - persona?: string - /** - * Tool filter applied to every child. Filtered tools disappear from its - * prompt and reject execution. Requires the provider's `toolFilter` - * capability; unknown names fail startup. - */ - toolFilter?: { - /** Global tool names the child keeps; everything else is removed. */ - allow?: string[] - /** Global tool names removed from the child. */ - deny?: string[] - } /** * Maximum child depth: a non-negative safe integer (`0` forbids delegation), * or `'provider-managed'` to send no cap. A numeric cap @@ -3969,6 +4041,14 @@ export interface Config { */ maxDepth?: number | 'provider-managed' } + +/** Optional default and model-selectable preset ids for a spawn tool. */ +export interface PresetSelectionConfig { + /** Default independent preset; omission inherits the parent when the model makes no selection. */ + agentPreset?: string + /** Non-empty allowlist exposing agent_preset to the model; omission disables model selection. */ + allowedAgentPresets?: string[] | undefined +} ``` @@ -4209,7 +4289,7 @@ export interface WebRuntimeConfig { ## `@deepseek-ai/dsh-web-app` - `inject`: `webServer` -- `source`: [`packages/bundle/web-app/src/index.ts:46`](../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. */ @@ -4219,22 +4299,18 @@ 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 `/`. Advertisement only; - * see [public deployments](../README.md#public-deployments). Absent or YAML - * `null` advertises the loopback URL. + * `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. */ publicUrl?: string - /** Explicit `--trusted-host` authorities from this invocation. */ - trustedHosts: string[] } ``` @@ -4447,6 +4523,7 @@ export interface Config { | `@deepseek-ai/dsh-acp-app` | `cmdlineArgs` | [`packages/bundle/acp-app/src/index.ts`](../packages/bundle/acp-app/src/index.ts) | | `@deepseek-ai/dsh-agent` | — | [`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts) | | `@deepseek-ai/dsh-api-account-controller` | `deepseekAccount` · `agents` | [`packages/api/account-controller/src/index.ts`](../packages/api/account-controller/src/index.ts) | +| `@deepseek-ai/dsh-api-remote-access` | — | [`packages/api/remote-access/src/index.ts`](../packages/api/remote-access/src/index.ts) | | `@deepseek-ai/dsh-api-remotes` | `typertGateway` | [`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts) | | `@deepseek-ai/dsh-authorization` | `credentials` | [`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts) | | `@deepseek-ai/dsh-browser-use` | — | [`packages/browser-use/browser-use/src/index.ts`](../packages/browser-use/browser-use/src/index.ts) | @@ -4477,6 +4554,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) | @@ -4519,7 +4597,8 @@ 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-host-directory-picker-auto` | `webServer` · `loader` | [`packages/host/directory-picker-auto/src/index.ts`](../packages/host/directory-picker-auto/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) | | `@deepseek-ai/dsh-llm` | — | [`packages/llm/llm/src/index.ts`](../packages/llm/llm/src/index.ts) | @@ -4633,6 +4712,7 @@ export interface Config { | `@deepseek-ai/dsh-session-snapshot` | — | [`packages/test-support/session-snapshot/src/index.ts`](../packages/test-support/session-snapshot/src/index.ts) | | `@deepseek-ai/dsh-session-telemetry` | — | [`packages/session/session-telemetry/src/index.ts`](../packages/session/session-telemetry/src/index.ts) | | `@deepseek-ai/dsh-session-title-llm` | — | [`packages/session/session-title-llm/src/index.ts`](../packages/session/session-title-llm/src/index.ts) | +| `@deepseek-ai/dsh-ssh-helper-runtime` | — | [`packages/ssh/ssh-helper-runtime/src/index.ts`](../packages/ssh/ssh-helper-runtime/src/index.ts) | | `@deepseek-ai/dsh-timeout` | — | [`packages/util/timeout/src/index.ts`](../packages/util/timeout/src/index.ts) | | `@deepseek-ai/dsh-typert-generator` | — | [`packages/typert/generator/src/index.ts`](../packages/typert/generator/src/index.ts) | | `@deepseek-ai/dsh-typert-protocol` | — | [`packages/typert/protocol/src/index.ts`](../packages/typert/protocol/src/index.ts) | diff --git a/docs/cookbook/adding-a-session-format-version.i18n.yaml b/docs/cookbook/adding-a-session-format-version.i18n.yaml index e37df25963..56f272ecf8 100644 --- a/docs/cookbook/adding-a-session-format-version.i18n.yaml +++ b/docs/cookbook/adding-a-session-format-version.i18n.yaml @@ -6,14 +6,14 @@ en: 71132d61e41cb40b zh: 0b56ed8893bf8d0a /cookbook-adding-a-session-log-format-version/summary: - en: 76b76c19e0889ab3 - zh: 1ddc1afa5c2333f0 + en: 3dc6121d1fcef4f8 + zh: 178bcf02b63c4fbf /cookbook-adding-a-session-log-format-version/table-of-contents: en: 6977fff29f49e4a4 zh: 7ffb6f5490831dce /cookbook-adding-a-session-log-format-version/1-choose-the-version-and-release-base: - en: 3205409b918b891d - zh: 98f17c19045954d5 + en: 3e763cfbe8cd11d5 + zh: 2d4998217cbe8030 /cookbook-adding-a-session-log-format-version/2-add-an-identity-edge: en: 77c9c26d94fb33ca zh: 313c54c45cfc7dbc diff --git a/docs/cookbook/adding-a-session-format-version.md b/docs/cookbook/adding-a-session-format-version.md index 7c6d08b993..8d960af752 100644 --- a/docs/cookbook/adding-a-session-format-version.md +++ b/docs/cookbook/adding-a-session-format-version.md @@ -4,7 +4,7 @@ English | [中文](adding-a-session-format-version.zh.md) ## Summary -Use this tutorial to introduce the next structural Session log version without rewriting released data. Read the [version and release-status authority](../session-format-status.md) to identify the checkout writer and the latest released format. Let N denote that verified released format and N+1 the target; substitute numeric values for these placeholders in names and metadata. Start with a working contributor checkout and read the [package checklist](adding-a-package.md), [format library](../../packages/session/session-format/README.md), and [released-format decision](../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.md). +Use this tutorial to introduce the next Session log format version without rewriting released data. Read the [version and release-status authority](../session-format-status.md) to identify the checkout writer and the latest released format. Let N denote that verified released format and N+1 the target; substitute numeric values for these placeholders in names and metadata. Start with a working contributor checkout and read the [package checklist](adding-a-package.md), [format library](../../packages/session/session-format/README.md), and [released-format decision](../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.md). ## Table of Contents @@ -20,15 +20,15 @@ Use this tutorial to introduce the next structural Session log version without r ## 1. Choose the version and release base -Bump the format for a structural change to headers, event envelopes, core event semantics, or surface reconstruction. Backward-compatible changes can remain at the current version through new acknowledgements; follow the [versioning rule](../../.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md) and [type-change rules](../persistence-changes/README.md#compatibility-rules). Distinguish the Session format integer from package release versions, SQLite schema versions, projection-unit versions, and protocol-wrapper versions. +Bump the format only when an effective discriminator cannot prevent unsafe interpretation. A structural change to headers, event envelopes, event semantics, or reconstruction requires assessment under the [reader-compatibility rule](../../.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.md), not an automatic bump. Record safe same-version evolution through the [type-change procedure](reviewing-persistence-type-changes.md). Distinguish the Session format integer from package release versions, SQLite schema versions, projection-unit versions, and protocol-wrapper versions. -Let N be the accepted or published version in [version/status](../session-format-status.md) when planning the next breaking change. A breaking change after accepted V4 therefore needs V5 even before V4 publication is recorded; compatible additions do not require that step. +Let N be the accepted or published version in [version/status](../session-format-status.md) when a bump is required. After accepted V4, that bump needs V5 even before V4 publication is recorded; reviewed same-version evolution does not require that step. Use a shared `release/*` integration base for N+1. The base change adds the writer, codec, catalog wiring, identity migration, and verification. Create each independent child branch from that base and target its PR at the release branch, not another independent child’s branch. Each child adds its structural transformation, validators, consumers, and tests to the same adjacent migration package. Do not allocate extra versions just to represent review order. Merge reviewed children into the release branch through PRs, then validate the combined result before release. Honor release-branch force-push and deletion protections; do not force-sync it. -Released codecs and accepted target-format meanings remain stable. The N→N+1 converter may receive fixes or support additional historical cases after N+1 ships, without a version bump, if its output remains compatible with N+1. A converter fix affects subsequent conversions, not existing N+1 successors. Document changes to previously accepted mappings and how existing outputs remain supported. Changing the established target representation or interpretation incompatibly requires the next version. +Released codecs preserve accepted interpretations. A current-version codec can admit explicitly discriminated variants while retaining historical readability; do not broaden an older codec to admit a current feature. The N→N+1 converter may receive fixes or support additional historical cases after N+1 ships if its output remains compatible with N+1. A fix affects subsequent conversions, not existing N+1 successors. Document changed mappings and continued support for existing output; apply the reader-compatibility rule to any new target representation. -Use disposable, isolated Harness homes while N+1 remains open for integration. An interim N+1 file already has the target writer version, so a later edit to N→N+1 will not migrate that file again. Re-run from unchanged historical input in a fresh test home; never repair this by rewriting a committed generation or reusing a real user's home. +Same-version logs bypass adjacent migrations and can mix historical and newer record variants after resume. Each integer therefore identifies a family of supported representations, not one fixed schema. Owning readers must retain and distinguish those variants; the next outgoing migration must handle them. Do not add same-version migrations or rely on `restoreCurrent` alone for normalization: current-version JSONL reads using transformed validation bypass that hook. Use disposable, isolated Harness homes for interim integration formats; rerun changed adjacent conversions from unchanged historical input rather than rewriting a committed generation or using a real user's home. Before changing the writer, use the [archive command](../persistence-changes/historical-formats/README.md#maintenance) to preserve its complete persistence schema, then add the bilingual format reference under `docs/persistence-changes/historical-formats/vN.*`. Preserve all earlier records. The format coverage check requires every integer below the new writer to have its own document; the current generated catalog covers only the new writer. diff --git a/docs/cookbook/adding-a-session-format-version.zh.md b/docs/cookbook/adding-a-session-format-version.zh.md index bfadeab878..5cc5b3d197 100644 --- a/docs/cookbook/adding-a-session-format-version.zh.md +++ b/docs/cookbook/adding-a-session-format-version.zh.md @@ -4,7 +4,7 @@ ## 概述 -本教程介绍如何添加下一个结构性 Session 日志版本,同时不改写已发布数据。阅读[版本与发布状态真源](../session-format-status.zh.md),确定工作区写入器与最新已发布格式。令 N 表示经核实的已发布格式,N+1 表示目标版本;名称与元数据中的这些占位符须替换为数字。开始前,请准备可用的贡献者工作区,并阅读[包检查清单](adding-a-package.zh.md)、[格式库](../../packages/session/session-format/README.zh.md)和[已发布格式决策](../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.zh.md)。 +本教程介绍如何添加下一个 Session 日志格式版本,同时不改写已发布数据。阅读[版本与发布状态真源](../session-format-status.zh.md),确定工作区写入器与最新已发布格式。令 N 表示经核实的已发布格式,N+1 表示目标版本;名称与元数据中的这些占位符须替换为数字。开始前,请准备可用的贡献者工作区,并阅读[包检查清单](adding-a-package.zh.md)、[格式库](../../packages/session/session-format/README.zh.md)和[已发布格式决策](../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.zh.md)。 ## 目录 @@ -20,15 +20,15 @@ ## 1. 选择版本与发布基线 -当 header、事件信封、核心事件语义或表面重建发生结构性变更时,提升格式版本。向后兼容的变更可以通过新的确认记录保留当前版本;遵循[版本规则](../../.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.zh.md)与[类型变更规则](../persistence-changes/README.zh.md#compatibility-rules)。区分 Session 格式整数与包发布版本、SQLite schema 版本、投影单元版本及协议包装层版本。 +只有有效判别信息无法阻止不安全解释时,才提升格式版本。头、事件封装、事件语义或重建的结构变更需要按[读取器兼容性规则](../../.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.zh.md)评估,不会自动升版本。通过[类型变更流程](reviewing-persistence-type-changes.zh.md)记录安全的同版本演进。区分 Session 格式整数与包发布版本、SQLite schema 版本、投影单元版本及协议包装层版本。 -规划下一次破坏性变更时,N 取[版本/状态](../session-format-status.zh.md)中的已接受或已发布版本。因此,即使尚未记录 V4 发布,已接受 V4 之后的破坏性变更也需要 V5;兼容新增不需要这一步。 +确定需要升版本时,N 取[版本/状态](../session-format-status.zh.md)中的已接受或已发布版本。已接受 V4 之后,即使尚未记录 V4 发布,此次升版本也需要 V5;经评审的同版本演进不需要这一步。 为 N+1 使用共享的 `release/*` 集成基线。基线变更添加写入器、codec、catalog 接线、恒等迁移与验证。从该基线创建各个独立子分支,并将其 PR(Pull Request)的目标设为发布分支,而非另一个独立子分支。每个子分支在同一个相邻迁移包内添加自身的结构变换、校验器、消费方和测试。不要只为表示评审顺序而分配额外版本。通过 PR 将评审后的子分支合入发布分支,并在发布前验证组合结果。遵守发布分支的强制推送与删除保护;不要强制同步该分支。 -已发布 codec 和已接受的目标格式含义保持稳定。N+1 发布后,N→N+1 转换器仍可修复或增加历史场景支持;只要输出仍兼容 N+1,就不必提高版本。转换器修复只影响之后的转换,不会重新处理已有 N+1 后继文件。记录对原先已接纳映射的修改,以及已有输出如何继续得到支持。不兼容地改变既定目标表示或解释语义需要下一版本。 +已发布 codec 保留已接受的解释。当前版本 codec 可以接纳有明确判别信息的分支,同时保留历史可读性;不要为了接纳当前功能而放宽旧 codec。N+1 发布后,只要输出仍兼容 N+1,N→N+1 转换器就可以修复或增加历史场景支持。修复只影响之后的转换,不影响已有 N+1 后继文件。记录映射变化及已有输出如何继续得到支持;任何新的目标表示都须应用读取器兼容性规则。 -N+1 尚处于开放集成阶段时,应使用可丢弃、相互隔离的 Harness home。中间版本产生的 N+1 文件已标为目标写入器版本,因此后续对 N→N+1 的修改不会再次迁移该文件。请在全新测试 home 中从未变更的历史输入重新运行;绝不通过改写已提交代际或复用真实用户 home 来修复这个问题。 +同版本日志跳过相邻迁移,恢复后可以混合历史与较新的记录分支。因此,每个整数标识一组受支持表示,而非一个固定 schema。所属读取器必须保留并区分这些分支;下一条向外迁移必须处理它们。不要添加同版本迁移,也不要仅依赖 `restoreCurrent` 进行归一化:使用 transformed 校验的当前版本 JSONL 读取会跳过该 hook。中间集成格式使用可丢弃、相互隔离的 Harness home;相邻转换发生变化时,从未变更的历史输入重新运行,不得改写已提交代际或使用真实用户 home。 变更写入器之前,使用[归档命令](../persistence-changes/historical-formats/README.zh.md#maintenance)保留其完整持久化 schema,再在 `docs/persistence-changes/historical-formats/vN.*` 下添加双语格式参考。保留所有更早的记录。格式覆盖检查要求低于新写入器的每个整数版本都有独立文档;当前生成的目录只覆盖新写入器。 diff --git a/docs/cookbook/reviewing-persistence-type-changes.i18n.yaml b/docs/cookbook/reviewing-persistence-type-changes.i18n.yaml index efb3b93c60..eba1d60922 100644 --- a/docs/cookbook/reviewing-persistence-type-changes.i18n.yaml +++ b/docs/cookbook/reviewing-persistence-type-changes.i18n.yaml @@ -15,17 +15,17 @@ en: 5fca19ac2bb1ddac zh: 00d78fe7e80ba4f7 /cookbook-reviewing-persistence-type-changes/optional-inspect-the-change: - en: 3f85edb803afe870 - zh: 545c651b9e5ccb56 + en: 14049617e3de750d + zh: 200456cf72bef77b /cookbook-reviewing-persistence-type-changes/1-record-the-change: - en: 342bd49412db070e - zh: a8d14958e9a637d9 + en: de16b6e1ac883317 + zh: 21d367bb78e799d1 /cookbook-reviewing-persistence-type-changes/2-check-commit-and-push: en: 91d39719ec40b0f7 zh: 405116ae4c91b100 /cookbook-reviewing-persistence-type-changes/update-an-unaccepted-record: - en: 4fd3f48761f7909f - zh: 69af35c41656fa17 + en: e3872db4ec9aad7d + zh: 18de4f6ebcb4b31c /cookbook-reviewing-persistence-type-changes/dev-note: en: 5de1d6304e00c58f zh: 8d8225361cfa29e5 diff --git a/docs/cookbook/reviewing-persistence-type-changes.md b/docs/cookbook/reviewing-persistence-type-changes.md index 15b6c9fab9..56620e5a8b 100644 --- a/docs/cookbook/reviewing-persistence-type-changes.md +++ b/docs/cookbook/reviewing-persistence-type-changes.md @@ -31,7 +31,7 @@ pnpm --silent run verify-persistence-changes --json Use `--silent` when consuming JSON: pnpm otherwise appends lifecycle failure text to stdout. Failed commands still exit with code 1. -Read the reported root, path, change kind, and version requirement. A referenced type can affect several event digests; inspect every affected root. Until the history covers the new schemas, verification fails. A stale generated inventory also fails verification; the recording command refreshes it. If `changes` is empty after reordering fields or union alternatives, run `pnpm run gen-persistence-catalog` and repeat the check. An unchanged digest needs no new acknowledgement even when copied declarations or source locations produce a catalog diff. +Read the reported root, path, change kind, and compatibility-review requirement. A referenced type can affect several event digests; inspect every affected root. Until the history covers the new schemas, verification fails. A stale generated inventory also fails verification; the recording command refreshes it. If `changes` is empty after reordering fields or union alternatives, run `pnpm run gen-persistence-catalog` and repeat the check. An unchanged digest needs no new acknowledgement even when copied declarations or source locations produce a catalog diff. To review a PR independently of its acknowledgement history, save the base and head inventories as local JSON files and run: @@ -39,6 +39,8 @@ To review a PR independently of its acknowledgement history, save the base and h pnpm --silent run persistence-review --before .artifacts/base.schema.json --after docs/persistence-schema.json ``` +A recorded decision does not hide the transition from this comparison. `--check` only compares current source with acknowledged history; after recording, it cannot replace a base/head review or establish that a human reviewed the change. + Record the commits supplying those files with the report. Add `--json` for structured output. This read-only comparison groups shared changes with their affected roots and uses actual literal `kind`/`form` values instead of union positions. Ambiguous alternatives remain separate additions and removals. Its compatibility section copies every root's authoritative classifier result; the structural explanation does not replace acknowledgement checks. Current catalog labels and declaration names are descriptive metadata; structural anchors and fingerprints identify types. The current machine inventory stores complete graphs in `roots`. A `types` entry contains `digest`, `names`, and `sources`, plus an explicit `schema` when roots cannot reconstruct that graph exactly. Readers resolve omitted graphs from root subgraphs by digest and validate explicit graphs directly, preserving every type and its metadata. Historical full entries remain readable. `formatVersion` identifies normalization rules; storage compaction does not change root fingerprints or require an acknowledgement. @@ -46,7 +48,7 @@ The current machine inventory stores complete graphs in `roots`. A `types` entry ## 1. Record the change -Check the [accepted baseline](../session-format-status.md#finalization-record) first. Preserve its locked records. Record backward-compatible evolution in a new same-version acknowledgement; implement a higher writer version before recording a breaking change. +Check the [accepted baseline](../session-format-status.md#finalization-record) first and preserve its locked records. Assess both reader directions under the [compatibility rules](../persistence-changes/README.md#compatibility-rules). A structural difference can remain same-version with evidence of safe interpretation or refusal; it does not automatically require a higher writer version. Write a local JSON file containing `en` and `zh`, each with `summary`, `compatibility`, and `verification` strings. The following input describes an exercised required-to-optional hook audit field change. Replace the explanation and test evidence with facts about your change; the CLI does not establish these claims. @@ -73,9 +75,9 @@ Use a date and descriptive slug in place of this example id: pnpm --silent run persistence-changes --record 2026-09-11-poc-optional --prose .artifacts/persistence-change.prose.json --json ``` -The command validates the history and paired prose, infers the minimum version decision, and checks any required header increase before writing. It generates the record pair, complete after schemas, both catalogs, the machine inventory, and pairing records. Review the explanations and returned `changes`, `roots`, and `files` before committing. Omitting `--prose` creates unfinished drafts that verification rejects until their explanations are completed. +The command validates the history and paired prose, infers established same-version decisions, and checks explicit compatibility decisions before writing. It generates the record pair, complete after schemas, both catalogs, the machine inventory, and pairing records. Review the explanations and returned `changes`, `roots`, and `files` before committing. Omitting `--prose` creates unfinished drafts that verification rejects until their explanations are completed. -Inference follows the [fixed compatibility rules](../persistence-changes/README.md#compatibility-rules); it never changes source or relaxes them. If a bump is required, first follow [adding a Session format version](adding-a-session-format-version.md). The record must include its own increasing `SessionHeader.version` transition; an unrelated historical bump cannot authorize it. Routine changes never create another baseline. +For a change marked `requiresCompatibilityReview`, explain both reader directions in the acknowledgement’s Compatibility section and record executed checks in Verification. Supply `--decision same-version` when that evidence supports keeping the version; recording or updating a flagged change with an unchanged header version and no explicit decision fails with `decision-required`. Structural differences alone do not infer a bump. An actual header version increase can infer `version-bump`. If an effective discriminator cannot prevent unsafe interpretation, follow [adding a Session format version](adding-a-session-format-version.md) and select `--decision version-bump`. That record must include its own increasing `SessionHeader.version` transition; an unrelated historical bump cannot authorize it. Routine changes never create another baseline. ## 2. Check, commit, and push @@ -99,14 +101,14 @@ If source changes after recording, review the compatibility explanation and refr pnpm --silent run persistence-changes --update 2026-09-11-poc-optional --prose .artifacts/persistence-change.prose.json --json ``` -The command refreshes the machine declaration, schemas, catalogs, and pairing. Without `--prose`, it preserves the existing explanation. Update refuses the initial baseline, records that another record depends on, and finalized checkpoint records. Outside finalized checkpoints, the tree does not infer review acceptance: preserve accepted history and create a successor instead. +The command refreshes the machine declaration, schemas, catalogs, and pairing. Without `--prose`, it preserves the existing explanation. Reassess that explanation against the complete transition and supply `--decision same-version` for any flagged same-version update. Update refuses the initial baseline, records that another record depends on, and finalized checkpoint records. Outside finalized checkpoints, the tree does not infer review acceptance: preserve accepted history and create a successor instead. When integration creates competing terminal records, update the unaccepted record against the remaining history, then reassess the resulting diff. An unrelated root's acknowledgement does not need refreshing. The [mechanism decision](../../.agents/notes/implemented/process/2026-09-11-persistence-type-history.md) explains why complete snapshots and per-root predecessors are retained. -An explicit `--decision` remains a checked assertion. For an existing property's value-type change, the following deliberately wrong assertion fails before writing: +For an existing property value-type change requiring review, first revise the prose file’s Compatibility and Verification sections to explain the actual new transition and its executed checks. Do not reuse the earlier required-to-optional explanation for a different change. Then update the record with that prose and the explicit same-version choice: ```sh -pnpm --silent run persistence-changes --update 2026-09-11-poc-optional --decision same-version --json +pnpm --silent run persistence-changes --update 2026-09-11-poc-optional --decision same-version --prose .artifacts/persistence-change.prose.json --json ``` diff --git a/docs/cookbook/reviewing-persistence-type-changes.zh.md b/docs/cookbook/reviewing-persistence-type-changes.zh.md index ed82decae9..51d3f1b6c2 100644 --- a/docs/cookbook/reviewing-persistence-type-changes.zh.md +++ b/docs/cookbook/reviewing-persistence-type-changes.zh.md @@ -31,7 +31,7 @@ pnpm --silent run verify-persistence-changes --json 消费 JSON 时使用 `--silent`:否则 pnpm 会把生命周期失败文本追加到标准输出。失败命令仍以退出码 1 结束。 -阅读报告中的根、路径、变更种类和版本要求。被引用类型可能影响多个事件摘要;检查每个受影响的根。在历史覆盖新 schema 之前,验证会失败。陈旧生成清单也会导致验证失败;记录命令会刷新它。若重排字段或联合类型分支后 `changes` 为空,运行 `pnpm run gen-persistence-catalog` 并重新检查。即使复制的声明或源码位置产生目录 diff,未变的摘要也无需新增确认记录。 +阅读报告中的根、路径、变更种类和兼容性评审要求。被引用类型可能影响多个事件摘要;检查每个受影响的根。在历史覆盖新 schema 之前,验证会失败。陈旧生成清单也会导致验证失败;记录命令会刷新它。若重排字段或联合类型分支后 `changes` 为空,运行 `pnpm run gen-persistence-catalog` 并重新检查。即使复制的声明或源码位置产生目录 diff,未变的摘要也无需新增确认记录。 要独立于确认历史评审 PR,先将 base 和 head 的目录保存为本地 JSON 文件,再运行: @@ -39,6 +39,8 @@ pnpm --silent run verify-persistence-changes --json pnpm --silent run persistence-review --before .artifacts/base.schema.json --after docs/persistence-schema.json ``` +记录决策不会使转换从此比较中消失。`--check` 仅比较当前源码与已确认历史;记录完成后,它不能替代 base/head 评审,也不能证明人类已评审该变更。 + 在报告旁记录这些文件对应的 commit。添加 `--json` 可获取结构化输出。此只读比较将共享变更与受影响的根类型归组,使用实际字面量 `kind`/`form` 值代替联合类型位置。无法唯一匹配的候选项保留为独立的新增与删除。兼容性部分复制每个根类型的权威分类结果;结构说明不替代确认检查。当前目录标签和声明名称是描述元数据;结构锚点和指纹标识类型。 当前机器清单在 `roots` 中保存完整图。每个 `types` 条目包含 `digest`、`names` 和 `sources`;若根无法精确重建该图,条目还会保存显式 `schema`。读取器按摘要从根的子图恢复省略的图,并直接验证显式图,保留每个类型及其元数据。历史完整条目仍然可读。`formatVersion` 标识规范化规则;存储压缩不改变根指纹,也不需要确认记录。 @@ -46,7 +48,7 @@ pnpm --silent run persistence-review --before .artifacts/base.schema.json --afte ## 1. 记录变更 -先检查[已接受基线](../session-format-status.zh.md#finalization-record),保留其锁定记录。向后兼容的演进使用新的同版本确认记录;记录破坏性变更之前,先实现更高的写入器版本。 +先检查[已接受基线](../session-format-status.zh.md#finalization-record),保留其锁定记录。按[兼容性规则](../persistence-changes/README.zh.md#compatibility-rules)评估两个读取方向。若有安全解释或拒绝的证据,结构差异可以保留同一版本,不会自动要求更高的写入器版本。 编写包含 `en` 和 `zh` 的本地 JSON 文件,两者分别包含 `summary`、`compatibility` 和 `verification` 字符串。以下输入描述一个经过验证的钩子审计字段从必选改为可选的变更。用你所做变更的事实替换说明和测试证据;CLI(命令行界面)不会证明这些声明。 @@ -73,9 +75,9 @@ pnpm --silent run persistence-review --before .artifacts/base.schema.json --afte pnpm --silent run persistence-changes --record 2026-09-11-poc-optional --prose .artifacts/persistence-change.prose.json --json ``` -命令在写入前验证历史和双语说明、推断最低版本决策,并检查所需的头部版本递增。它生成记录对、完整的变更后 schema、两份目录、机器清单和配对记录。提交前审阅说明及返回的 `changes`、`roots` 和 `files`。省略 `--prose` 会创建未完成草稿,验证将拒绝它们,直到说明补齐。 +命令在写入前验证历史与双语说明、推断已明确允许的同版本决策,并检查显式兼容性决策。它生成记录对、完整的 after schema、两个目录、机器清单与配对记录。提交前检查说明及返回的 `changes`、`roots`、`files`。省略 `--prose` 会生成未完成草稿;说明填写完成前,验证会拒绝它们。 -推断遵循[固定兼容性规则](../persistence-changes/README.zh.md#compatibility-rules),不会更改源码或放宽规则。需要升版本时,先遵循[添加会话格式版本](adding-a-session-format-version.zh.md)。记录必须包含其自身的 `SessionHeader.version` 递增转换;无关的历史升版本不能授权它。日常变更不创建另一条基线。 +对于标为 `requiresCompatibilityReview` 的变更,在确认记录的兼容性部分说明两个方向的读取器行为,并在验证部分记录已执行的检查。证据支持保持版本时,提供 `--decision same-version`;记录或更新被标记的变更时,若头版本未变且缺少显式决策,会以 `decision-required` 失败。仅凭结构差异不会推断升版本。实际头版本递增可以推断出 `version-bump`。若有效判别信息无法阻止不安全解释,遵循[添加会话格式版本](adding-a-session-format-version.zh.md),并选择 `--decision version-bump`。该记录必须包含自身的 `SessionHeader.version` 递增转换;无关的历史升版本不能授权它。日常变更不创建另一条基线。 ## 2. 检查、提交并推送 @@ -99,14 +101,14 @@ pnpm run doc-sync pnpm --silent run persistence-changes --update 2026-09-11-poc-optional --prose .artifacts/persistence-change.prose.json --json ``` -命令刷新机器声明、schema、目录和配对。没有 `--prose` 时,它保留已有说明。更新会拒绝初始基线、其他记录所依赖的记录,以及已被定稿检查点锁定的记录。定稿检查点之外,目录不会推断审阅接受状态:保留已接受历史,并创建后继。 +命令刷新机器声明、schema、目录和配对。没有 `--prose` 时,它保留已有说明。根据完整转换重新评估说明,并为任何被标记的同版本更新提供 `--decision same-version`。更新会拒绝初始基线、其他记录所依赖的记录,以及已被定稿检查点锁定的记录。定稿检查点之外,目录不会推断审阅接受状态:保留已接受历史,并创建后继。 集成产生竞争末端记录时,根据剩余历史更新尚未接受的记录,再重新评估最终差异。无关根的确认无需刷新。[机制决策](../../.agents/notes/implemented/process/2026-09-11-persistence-type-history.zh.md)解释为何保留完整快照和逐根前驱。 -显式 `--decision` 仍是受检查的断言。若已有属性的值类型发生变化,下面这个故意错误的断言会在写入前失败: +若已有属性的值类型变化需要评审,先修改说明文件中的兼容性与验证部分,解释实际的新转换及已执行检查。不要为不同变更复用先前必选改可选的说明。然后使用该说明与显式同版本选择更新记录: ```sh -pnpm --silent run persistence-changes --update 2026-09-11-poc-optional --decision same-version --json +pnpm --silent run persistence-changes --update 2026-09-11-poc-optional --decision same-version --prose .artifacts/persistence-change.prose.json --json ``` diff --git a/docs/deepseek-llm-api-wire-extensions.i18n.yaml b/docs/deepseek-llm-api-wire-extensions.i18n.yaml index ca1ec47310..79b48d6dc5 100644 --- a/docs/deepseek-llm-api-wire-extensions.i18n.yaml +++ b/docs/deepseek-llm-api-wire-extensions.i18n.yaml @@ -12,8 +12,8 @@ en: 740e92e903ecb594 zh: f934d3c9e5c56bfe /official-deepseek-llm-api-wire-extensions/body-extension-transaction: - en: f0b1443c364a431c - zh: 16d16ddf5c451e8e + en: 48001cfd1281a23b + zh: d410530ae8aa2823 /official-deepseek-llm-api-wire-extensions/dsh-plugin-packages: en: f89059050613f3e8 zh: da5cf2a4eeb81b75 diff --git a/docs/deepseek-llm-api-wire-extensions.md b/docs/deepseek-llm-api-wire-extensions.md index 216725d71d..1a30f7c463 100644 --- a/docs/deepseek-llm-api-wire-extensions.md +++ b/docs/deepseek-llm-api-wire-extensions.md @@ -34,9 +34,9 @@ Credential failure happens before anonymous-user-id resolution, so an unauthoriz The adapter serializes the complete base body, including the exact `messages`, before it asks registered providers to prepare fields. A provider receives that immutable body, the request cancellation signal, and optional `sessionId` and auxiliary-call `purpose`. Returning `undefined` omits that provider's field for the request. -Prepared JSON values are detached from provider-owned state, merged as top-level siblings of the base fields, and serialized in the same HTTP body. Preparation or collision failure prevents the request. If the merged body fails to serialize, the adapter sends the base body without any extension field, skips the acceptance transaction so contributors resend their state on a later request, and logs the omitted field names. A composition without the registry sends the unextended base body. +Prepared JSON values are detached from provider-owned state, merged as top-level siblings of the base fields, and serialized in the same HTTP body. A contributor whose preparation fails is omitted from that request, with only its first failure logged, while the other fields are still sent; a field that collides with a base field prevents the request. If the merged body fails to serialize, the adapter sends the base body without any extension field, skips the acceptance transaction so contributors resend their state on a later request, and logs the omitted field names. A composition without the registry sends the unextended base body. -After the configured endpoint returns HTTP 2xx, the adapter runs the prepared `accept()` transaction before reading the SSE response body. Transport failures and non-2xx responses do not accept any contribution. An acceptance failure fails the model request even though the endpoint returned 2xx. Acceptance records endpoint-level HTTP success; it does not assert that an SSE stream completed or that the endpoint persisted an extension. +After the configured endpoint returns HTTP 2xx, the adapter runs the prepared `accept()` transaction before reading the SSE response body. Transport failures and non-2xx responses do not accept any contribution. An acceptance failure is logged and does not fail the model request; the contributor resends its unaccepted state on a later request. Acceptance records endpoint-level HTTP success; it does not assert that an SSE stream completed or that the endpoint persisted an extension. ## `dsh_plugin_packages` diff --git a/docs/deepseek-llm-api-wire-extensions.zh.md b/docs/deepseek-llm-api-wire-extensions.zh.md index 33c8908ae5..dcccecc6a7 100644 --- a/docs/deepseek-llm-api-wire-extensions.zh.md +++ b/docs/deepseek-llm-api-wire-extensions.zh.md @@ -34,9 +34,9 @@ 适配器先序列化包括确切 `messages` 在内的完整基础正文,再让已注册提供方准备字段。提供方会收到该不可变正文、请求取消信号,以及可选的 `sessionId` 和辅助调用 `purpose`。提供方返回 `undefined` 时,本次请求会省略其字段。 -系统将已准备的 JSON 值与提供方持有的状态分离,再将其作为基础字段的顶层同级成员合并,并序列化到同一个 HTTP 正文中。准备失败或冲突会阻止请求。合并后的正文无法序列化时,适配器发送不含任何扩展字段的基础正文,跳过接受事务,让贡献方在之后的请求中重发自身状态,并记录被省略的字段名。组合未挂载注册表时,适配器发送未经扩展的基础正文。 +系统将已准备的 JSON 值与提供方持有的状态分离,再将其作为基础字段的顶层同级成员合并,并序列化到同一个 HTTP 正文中。某个贡献方准备失败时,系统在该次请求中省略其字段,且只记录首次失败,其余字段照常发送;与基础字段冲突的字段会阻止请求。合并后的正文无法序列化时,适配器发送不含任何扩展字段的基础正文,跳过接受事务,让贡献方在之后的请求中重发自身状态,并记录被省略的字段名。组合未挂载注册表时,适配器发送未经扩展的基础正文。 -已配置端点返回 HTTP 2xx 后,适配器会在读取 SSE 正文之前运行已准备的 `accept()` 事务。传输失败和非 2xx 响应不会接受任何贡献。即使端点返回 2xx,接受失败仍会使模型请求失败。接受仅记录端点级 HTTP 成功,不表示 SSE 流已完整结束,也不表示端点已持久化扩展。 +已配置端点返回 HTTP 2xx 后,适配器会在读取 SSE 正文之前运行已准备的 `accept()` 事务。传输失败和非 2xx 响应不会接受任何贡献。接受失败会记录告警,但不会使模型请求失败;贡献方会在之后的请求中重发未被接受的状态。接受仅记录端点级 HTTP 成功,不表示 SSE 流已完整结束,也不表示端点已持久化扩展。 ## `dsh_plugin_packages` diff --git a/docs/defensive-patterns.i18n.yaml b/docs/defensive-patterns.i18n.yaml deleted file mode 100644 index d9a68ffae5..0000000000 --- a/docs/defensive-patterns.i18n.yaml +++ /dev/null @@ -1,28 +0,0 @@ -# Bilingual-pair consistency record for defensive-patterns.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/defensive-patterns.md -/defensive-patterns: - en: 6316b1da0ae4561b - zh: f059647429c707d5 -/defensive-patterns/report-orthogonal-outcomes-independently: - en: 09cdbaa7cf763dc9 - zh: 11e5c13d77b2a563 -/defensive-patterns/honor-public-contracts-on-both-sides: - en: 157f966db7329171 - zh: 80da311819125f36 -/defensive-patterns/async-state-is-not-synchronous-state: - en: 33085f2b58bab16c - zh: be38e69a9c7d3f0e -/defensive-patterns/dispose-must-reach-quiescence-not-just-request-it: - en: 5c906be504b88a65 - zh: 8f428f59a87bb1a8 -/defensive-patterns/contain-callback-exceptions-in-the-dispatcher: - en: ae1788e76190db2c - zh: a55ab7473bb0c8dd -/defensive-patterns/never-hand-untrusted-output-the-ambient-environment-or-predictable-paths: - en: 09ad9d6433026468 - zh: cc0ba1a52859bb08 -/defensive-patterns/unlink-link-shaped-paths: - en: 644e6b1a9bd7b7d7 - zh: 823600c76c81ead1 diff --git a/docs/defensive-patterns.md b/docs/defensive-patterns.md deleted file mode 100644 index 9db5823546..0000000000 --- a/docs/defensive-patterns.md +++ /dev/null @@ -1,33 +0,0 @@ -# Defensive patterns - -English | [中文](defensive-patterns.zh.md) - -Hard-won bug-class rules: each pattern below is a class of defect that actually shipped or nearly shipped here, stated as the rule that prevents its recurrence. Read this before writing lifecycle, concurrency, subprocess, or teardown code. Test-tier counterparts (real entry path, world-verification, resource ownership) are in [testing.md](testing.md). - -## Report orthogonal outcomes independently - -A result can be several things at once — a process can time out AND exit 0 because it trapped the signal. Surface each independent fact (`timedOut`, `signal`, `exitCode`) on its own; never nest one flag's report inside another's branch, or a caller reads a cut-short run as a clean success. - -## Honor public contracts on BOTH sides - -When an implementation receives several representations of one outcome, normalize them before returning through the public API. `LlmAdapter.stream()` implementations may throw or emit `finish {kind:'error'|'aborted'}`, but `LlmRuntime.stream()` exposes model-request failures only as terminal finish chunks; middleware and consumer defects remain thrown. This keeps consumers from guessing whether a caught exception came from the provider, a wrapper, chunk logging, or their own assembly. Document the normalized contract where the type is defined; exercise every source form through the real consumer. - -## Async state is not synchronous state - -`agent.followup()` has no per-message completion or result; a background job's completion races turn boundaries; `reader.close()` fires for both EOF and disposal. Never treat `agent/status` or `whenIdle()` as the result of one follow-up: several queued follow-ups, steering, and injected work may share one `running` interval, while cancellation or disposal can discard unstarted items. An automation caller that truly owns a run must define its interval explicitly—for example, from its message's durable inbox receipt through the next whole-agent `idle`—and describe any selected output as interval-wide rather than causally attributed to that message. The guard cuts both ways: if the awaited transition can never occur, the wait hangs, so handle the "nothing to wait for" branch explicitly. - -## Dispose must reach quiescence, not just request it - -A teardown that issues kills/aborts but returns before the work stops leaves orphans. Make cleanup async and await the children's exit (kill → await `done`), and close listener/notification registries BEFORE killing so late completions stay silent. - -## Contain callback exceptions in the dispatcher - -A user-supplied listener that throws must not reject the promise it runs inside or starve the listeners after it. Wrap the dispatch loop in try/catch and log; one bad subscriber never breaks core lifecycle. - -## Never hand untrusted output the ambient environment or predictable paths - -Spawned commands get a scrubbed env (drop `*KEY*`/`*SECRET*`/`*TOKEN*`/`*PASSWORD*`) so harness credentials cannot leak into output, `env`, or spill files. Temp/spill files use a private (0700) dir, random names, and exclusive owner-only opens (`'wx'`, `0o600`) — predictable world-readable paths invite symlink races and disclosure. - -## Unlink link-shaped paths - -A path that may be a symlink or Windows junction is removed with `lstatSync().isSymbolicLink()` then `unlinkSync`: unlink deletes only the link and refuses a real directory, so it never follows the link into its target. Windows `rmSync(link)` throws `ERR_FS_EISDIR` on a junction; recursive deletion may descend through one into its target. Reserve recursive `rmSync` for known real directories. diff --git a/docs/defensive-patterns.zh.md b/docs/defensive-patterns.zh.md deleted file mode 100644 index 11b2a34a40..0000000000 --- a/docs/defensive-patterns.zh.md +++ /dev/null @@ -1,35 +0,0 @@ -# 防御性模式 - -[English](defensive-patterns.md) | 中文 - -来之不易的缺陷类别规则:下面每条模式都是本项目实际发布或差点发布的一类缺陷,以防止其复发的规则形式陈述。在编写生命周期、并发、子进程或清理代码之前请先阅读本文。测试层面的对应规则(真实入口路径、验证实际结果、资源归属)见 [testing.md](testing.zh.md)。 - -## 正交结果独立上报 - -一个结果可以同时具有多种性质:进程可能已经超时,却仍以退出码 0 结束,因为它捕获了终止信号。每个独立事实(`timedOut`、`signal`、`exitCode`)都应单独上报;切勿把一个标志的上报嵌套在另一个标志的分支中,否则调用方可能把提前终止的运行误判为正常成功。 - -## 公共约定两侧都要遵守 - -当一个实现收到同一结果的多种表示时,应在通过公共 API 返回前将其规范化。`LlmAdapter.stream()` 的实现可以抛出异常或发出 `finish {kind:'error'|'aborted'}`,但 `LlmRuntime.stream()` 只会通过终止型 finish 分片暴露模型请求失败;middleware 缺陷与消费方缺陷仍会以异常形式抛出。这使消费方不必猜测捕获的异常究竟来自提供方、包装层、分片日志记录还是自身组装逻辑。请在类型定义处记录规范化后的约定;通过真实消费方覆盖每种来源形式。 - -## 异步状态不是同步状态 - -`agent.followup()` 没有逐消息的完成状态或结果;后台任务的完成与轮次边界存在竞争;`reader.close()` 在 EOF 和 dispose(资源释放)两种情况下都会触发。切勿把 `agent/status` 或 `whenIdle()` 当作某次 `followup()` 的结果:多条已排队的后续消息、steering(中途引导)和注入工作可能共用同一个 `running` 区间,而取消或资源释放可能丢弃尚未启动的项。真正拥有一次运行的自动化调用方必须显式定义其区间——例如从消息的持久 inbox 回执到整个 agent(智能体)下一次进入 `idle`——并将选取的任何输出描述为整个区间的输出,而不是把因果关系归于该消息。这条守则是双向的:如果等待的转换永远不会发生,等待就会挂起,因此应显式处理「无需等待」的分支。 - - - -## dispose 必须达到完全停稳,而不仅仅是请求停止 - -如果清理流程只发出终止或中止信号便返回,而不等待工作真正停止,就会留下孤儿进程。清理逻辑应采用异步流程,并等待子进程退出(发出终止信号后等待 `done`);还应在终止进程前关闭监听器注册表和通知注册表,使迟到的完成事件保持静默。 - -## 在分发器中隔离回调异常 - -用户提供的监听器如果抛出异常,不得导致它所在的 promise 被 reject,也不得饿死排在它后面的监听器。请用 try/catch 包裹分发循环并记录日志;一个行为不当的订阅者绝不能破坏核心生命周期。 - -## 绝不将环境变量或可预测路径暴露给不可信输出 - -启动的命令应使用经过清理的环境变量,移除名称匹配 `*KEY*`、`*SECRET*`、`*TOKEN*` 或 `*PASSWORD*` 的项,防止 harness 凭证通过命令输出、`env` 或 spill 文件泄漏。临时文件和 spill 文件应放在权限为 0700 的私有目录中,使用随机文件名,并以独占且仅所有者可访问的方式打开(`'wx'`、`0o600`);可预测且全局可读的路径会引发符号链接竞态和信息泄露。 - -## 用 unlink 删除链接形态的路径 - -可能是符号链接或 Windows junction 的路径,应先用 `lstatSync().isSymbolicLink()` 判断,再用 `unlinkSync` 删除:unlink 只删除链接本身并拒绝真实目录,因此绝不会跟随链接进入其目标。Windows 上对 junction 调用 `rmSync(link)` 会抛 `ERR_FS_EISDIR`;递归删除可能穿过 junction 进入其目标。真实目录才使用带 `recursive` 的 `rmSync`。 diff --git a/docs/defensive-patterns/README.i18n.yaml b/docs/defensive-patterns/README.i18n.yaml new file mode 100644 index 0000000000..79e3b6cd15 --- /dev/null +++ b/docs/defensive-patterns/README.i18n.yaml @@ -0,0 +1,10 @@ +# 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 docs/defensive-patterns/README.md +/defensive-patterns: + en: 7229c49e920aa5b3 + zh: 1dd52db6b4d84952 +/defensive-patterns/why-these-rules: + en: 7c012071b5af8c98 + zh: 298aaba83625c7a0 diff --git a/docs/defensive-patterns/README.md b/docs/defensive-patterns/README.md new file mode 100644 index 0000000000..c74d1a4c29 --- /dev/null +++ b/docs/defensive-patterns/README.md @@ -0,0 +1,25 @@ +# Defensive patterns + +English | [中文](README.zh.md) + +Hard-won rules: each pattern in this directory is a requirement this repository enforces in review, stated as the rule and the defect it prevents. Every rule states what must hold, the condition a reviewer judges it by, its boundary and who approves an exception, and a correct and a wrong example. Read the page for the artifact you are about to change, before you change it. + +## Why these rules + +Five habits cover most of what follows, and each page is their application to one artifact: + +- **Make correctness explicit.** Write it into the structure — named call points, explicit lifecycles, explicit conditions and types — rather than compensating for it afterwards with timing. +- **Keep one source of truth.** One read path for a piece of data, one home for a fact, one owner for shared state. +- **Extend through the registered seam.** A new capability registers; an existing carrier stops taking new logic instead of growing a branch inside it. +- **Keep the change face equal to the review face.** A change carries only the lines its stated behavior change needs, a migration moves code rather than rewriting it, and a performance-sensitive change carries its measurement. +- **Require evidence.** A claim is falsifiable and recomputable — measured before and after, or checked by a gate — rather than kept in sync by hand. + +| Changing | Read | +|---|---| +| Package exports, package shape, build faces, dependency declarations | [package-surface.md](package-surface.md) | +| Remote services, `@Remote` methods, API dispatch, business ownership at the API layer | [remote-and-api.md](remote-and-api.md) | +| Client components, slots, stores, hooks, effects | [client-components.md](client-components.md) | +| Session reads, retention, conversation nodes, renderers | [conversation-and-session.md](conversation-and-session.md) | +| Timing, state representation, shared ownership, decentralization, refactors, migrations, performance evidence, disposal, callbacks, subprocesses | [general.md](general.md) | + +Type definitions and per-subsystem semantics live in [subsystems/](../subsystems/README.md); this directory carries the rules, and the semantics pages carry what the types mean. [dsh-code-review](../../.agents/skills/dsh-code-review/SKILL.md) reads this directory when judging a pull request, and Development routes through the same table from [AGENTS.md](../../AGENTS.md). diff --git a/docs/defensive-patterns/README.zh.md b/docs/defensive-patterns/README.zh.md new file mode 100644 index 0000000000..38d4c617d2 --- /dev/null +++ b/docs/defensive-patterns/README.zh.md @@ -0,0 +1,27 @@ +# 防御性模式 + +[English](README.md) | 中文 + +来之不易的规则:本目录中每条模式都是本仓库在评审中执行的**要求**,以「规则 + 它所防止的缺陷」的形式陈述。每条规则都写明:必须成立什么、评审据什么判定、边界在哪、例外由谁批准,以及一个正例与一个反例。动手修改某类制品之前,先读对应那一页。 + + + +## 这些规则背后的思想 + +下面五条习惯覆盖了绝大部分内容,每一页都是它们在某类制品上的落地: + +- **把正确性显式化。** 把它写进结构——具名调用点、显式生命周期、显式条件与类型——而不是事后用时序去补偿。 +- **只留一个真相。** 一份数据一条读取路径,一个事实一个正家,共享状态一个所有者。 +- **走注册面扩展。** 新能力靠注册接入;既有载体不再承接新逻辑,而不是在它内部长出分支。 +- **把改动面压成评审面。** 改动只包含其声明的行为变化所需的行;迁移是搬代码而不是重写;涉及性能的改动附带测量。 +- **要求可证伪、可复算。** 口径能被改动前后的实测或门禁证明/否证,而不是靠人肉同步。 + +| 你在改什么 | 读哪篇 | +|---|---| +| 包导出面、包形态、构建面、依赖声明 | [package-surface.zh.md](package-surface.zh.md) | +| 远程服务、`@Remote` 方法、API 分发、API 层的业务归属 | [remote-and-api.zh.md](remote-and-api.zh.md) | +| 客户端组件、slots、store、hooks、effect | [client-components.zh.md](client-components.zh.md) | +| Session 读取、持有、会话节点、renderer | [conversation-and-session.zh.md](conversation-and-session.zh.md) | +| 时序、状态表示、共享归属、去中心化、重构、迁移、性能证据、清理、回调、子进程 | [general.zh.md](general.zh.md) | + +类型定义与各子系统语义见 [subsystems/](../subsystems/README.zh.md);本目录承载**规则**,语义页承载**类型的含义**。[dsh-code-review](../../.agents/skills/dsh-code-review/SKILL.md) 在评审 pull request 时读本目录,日常修改经 [AGENTS.md](../../AGENTS.md) 路由到同一张表。 diff --git a/docs/defensive-patterns/client-components.i18n.yaml b/docs/defensive-patterns/client-components.i18n.yaml new file mode 100644 index 0000000000..face24c503 --- /dev/null +++ b/docs/defensive-patterns/client-components.i18n.yaml @@ -0,0 +1,46 @@ +# Bilingual-pair consistency record for client-components.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/defensive-patterns/client-components.md +/client-component-rules: + en: a6e8a87976040c04 + zh: 08b59ad3c14fe250 +/client-component-rules/state-arrives-through-injection: + en: 112232a703ce472d + zh: cf42bda22d8e4da4 +/client-component-rules/props-carry-data-and-callbacks-not-react-nodes: + en: 253f05568dd7e26f + zh: fa12565ff5afb8bd +/client-component-rules/a-slot-registration-is-a-stable-function-component: + en: 784d3a4bba02f8a4 + zh: 0ccfcc1a504b135c +/client-component-rules/components-never-receive-a-cordis-context: + en: 8bb102b178615c03 + zh: 93cb177a578a1373 +/client-component-rules/context-comes-from-the-current-scope: + en: 652ec94d13ee51c9 + zh: b47c39e96c53cfac +/client-component-rules/resource-consumers-go-through-useresource: + en: 6650c772df96f935 + zh: 57fc0a564caf62a8 +/client-component-rules/store-usage-is-narrow-and-explicit: + en: 697b2e81a862e3bf + zh: 13cf31bef332a601 +/client-component-rules/identity-and-initial-state-are-deliberate: + en: a34c30b8f7c415d4 + zh: cbd0c0cf0c0db57c +/client-component-rules/uselayouteffect-is-not-a-default: + en: f53f17846a8a89b2 + zh: 94d205c4d85f1de9 +/client-component-rules/effects-never-push-render-derived-data-to-a-parent: + en: 580441bd6cce9ee9 + zh: a5f093d8e7dec2ee +/client-component-rules/build-and-style-follow-their-owners: + en: 561df1e1709a004c + zh: 89ca6eb4533648b8 +/client-component-rules/a-key-states-what-it-identifies: + en: 1d6f9bdc2b267fef + zh: cf4d579ca877c422 +/client-component-rules/each-shared-layer-keeps-its-own-isolation-level: + en: 3faec81a6a7c9fdd + zh: aa512c089b5f9afc diff --git a/docs/defensive-patterns/client-components.md b/docs/defensive-patterns/client-components.md new file mode 100644 index 0000000000..7b0ec0463a --- /dev/null +++ b/docs/defensive-patterns/client-components.md @@ -0,0 +1,493 @@ +# Client component rules + +English | [中文](client-components.zh.md) + +Rules for client components, their state, and their effects. [packages/client/AGENTS.md](../../packages/client/AGENTS.md) carries the detailed discipline; [slots.md](../subsystems/slots.md) owns the Slot design and [web-styling.md](../web-styling.md) the styling rules. Each section below states the requirement, how a reviewer judges it, where its boundary and exception sit, and a correct and a wrong example. + +## State arrives through injection + +A Slot's component receives everything it renders through the inject face of its own registration — plain data, action callbacks, and the reserved `hooks` compartment the renderer binds to `use` hooks — while the parent's render site passes owner data through the derived `renderSlot`. It never reads one large global state at the top of the tree to hand values down. Keeping every live value on that face is what makes a prop that did not change keep its identity, and what lets a component subscribe only to the sub-state it reads. Without it any unrelated field change re-renders the whole subtree, which is how a long session under streaming events loses frames while the user scrolls or types. + +- Judged by: at the registration and at its render site, the author must be able to name which sub-states the rendered component subscribes to and which of its incoming props keep a stable identity across renders. Watch the mutability of every prop: a value rebuilt each render — a fresh object, array, or inline callback — propagates re-renders even when nothing in it changed. +- Not covered: the component's own local state (`useState` for a fold, a hover, a draft) is not injection content, and a component that subscribes to nothing outside React needs no new seat. +- Exception: a new hook seat changes the Slot contract, so that change states its impact — which components subscribe to what — in review; using an existing face needs no per-component approval. +- Fix: narrow the injection to what the view renders, expose one field per read through a hook seat, and pass a narrow action set instead of a store or service handle. [Component inputs](../subsystems/slots.md#component-inputs) owns the inject factory, the standard hook seats, and how each becomes a prop. + +The registration carries plain data, a narrow action set, and one hook seat; the render site passes owner data, and the component reads only the field it renders: + +```tsx +// The inject factory returns plain data and callbacks; hooks is the reserved compartment. +ctx.slots.register( + { + name: 'sidebar.right', + inject: () => ({ + rename, + hooks: { info: infoSource }, // bound by the renderer as useInfo() + }), + }, + SidebarRight, +) + +// The parent's render site passes owner data through the derived renderSlot. +{renderSlot('sidebar.right', { id })} + +function SidebarRight({ id, useInfo, rename }: Props) { + const { title } = useInfo() // subscribes to title only + return +} +``` + +The top-level component reads the whole view store and hands it down as one prop, so the render site can no longer answer either question above: + +```tsx +function Sidebar() { + const view = useViewStore() // one top-level global read + return // the whole store travels down +} + +function SidebarRight({ view }: { view: ViewStore }) { + return {view.activePanel.title} +} +``` + +Every field change in that store re-renders the whole sidebar subtree, and the component's subscription set is invisible to the site that bound it. + +## Props carry data and callbacks, not React nodes + +A prop is data or a callback; a React node travels through a declared slot. Passing an element as a prop value or an injected member hides a second composition path that the Slot contract does not describe, moves render control from the registration surface to the call site, and lets one package assemble another package's markup. New node-valued props or injected members are never added; a location that needs host-supplied markup is declared as a child slot instead. + +- Judged by: `ReactNode`, `ReactElement`, or a `() => JSX.Element` in a component's props type, in an inject factory's return value, or in an owner-props object at a render site. +- Not covered: node-valued fields that already shipped keep working. The rule triggers when a change touches one, and that change converts it rather than extending it. +- Exception: when the conversion cannot happen in the same change, the owning domain expert confirms the deferral and the change records that confirmation; the author never self-approves. +- Fix: declare the location in the parent registration's `children`, render it with `renderSlot`, and pass data through the child's props. [Extension rules](../subsystems/slots.md#extension-rules) own which package may declare and render which slot. + +The header location is a declared child slot, so the host passes data and the registered component owns its markup: + +```tsx +// The card declares the header location; the host passes data only. +ctx.slots.register( + { + name: 'tool.call.toolview', + children: { header: { kind: 'single', scope: 'session' } }, + }, + ToolCard, +) + +function ToolCard({ title, renderSlot }: Props) { + return
{renderSlot('header', { title })}
+} +``` + +A React node crosses the boundary as a prop value, so the composition path it travels is not declared anywhere: + +```tsx +type ToolCardProps = { + header?: React.ReactNode + footer?: React.ReactNode +} + +// The call site assembles another package's markup. +} /> +``` + +The card's Slot contract stops describing what it renders, the call site keeps render control, and the badge's package becomes a runtime reference from whoever passes it. + +## A slot registration is a stable function component + +The value registered into a slot is a stable function component declared at module scope. A component function created during render is a new component type on every pass, and React treats a changed type as a different component: it unmounts the subtree and mounts a fresh one, which resets expanded rows, input focus, and scroll position. Registration-time parameters reach the component through props rather than by closing over render-time variables. + +- Judged by: where the registered value is created. An inline arrow in a registration or render call, a component defined inside a render body, and a `useCallback` wrapper around an inline component all fail; a module-scope `function` declaration passes. +- Not covered: the rule constrains the identity of the registered value, not its complexity. A stable component may still read injected props, hooks, and callbacks. +- Exception: creating a component during render is correct only when the caller wants the remount, and an ordinary change needs no separate approval; a change to the form of the Slot contract follows the injection-face review described under State arrives through injection. +- Fix: move the component to module scope, type its props from the registration's shares, and pass the varying value through the inject face instead of the closure. + +The registration holds one stable reference to a module-scope component, and the varying value arrives injected; the render site supplies the local component: + +```tsx +function PanelTitle({ title, count }: Props) { + return {title} ({count}) +} + +// Registration: the local slot's scope is declared, never a component. +ctx.slots.registerFactory( + { + name: 'panel', + scope: 'root', + slots: { title: { scope: 'root' } }, + inject: () => ({ title: 'Sessions', count: 3 }), + }, + Panel, +) + +// The render site passes the local component, keeping its identity stable. +renderFactorySlot('panel', { /* owner data */ }, { slots: { title: PanelTitle } }) +``` + +An inline arrow at the render site creates a new component type whenever that render runs: + +```tsx +// A new component type each time this render runs. +renderFactorySlot('panel', { /* owner data */ }, { slots: { title: (p) => {p.title} } }) +``` + +React sees a different type than the previous registration, remounts the seat, and resets its local state — expanded, focused, or scrolled position — on an otherwise unrelated update. + +## Components never receive a Cordis context + +`ctx` belongs to the apply world: the plugin body and the `inject` factories closed over it. A component never receives a Cordis context, never imports a service class to poke it, and never reads a React context, because business components see zero contexts — the renderer's binding contexts are internal to it. A bare observable reaches a component only after Injection wraps it in a hook; a component that subscribes directly owns a lifecycle that nothing on the Injection face releases. + +- Judged by: `ctx` or `Context` in a component's parameter or props type; a component body reading `observable.value`, calling `subscribe`, or wiring `useSyncExternalStore`; a service class imported into a feature `.tsx` module. +- Not covered: a component-internal behavioral hook that subscribes to nothing outside React (a timer, a media query) is not injection content and stays in the component. +- Exception: none. The direct subscription still present in `TabSlot` is remediation work owned by that entry's owner, not a precedent for new code. +- Fix: move the fact into the registration's `inject` — plain data and callbacks, with bare observables in the reserved `hooks` compartment — or into a declared store, and read it through the derived seat. + +Injection binds the observable, and the component reads one derived hook whose subscription the renderer owns: + +```tsx +// The inject factory is the only place that closes over ctx. +const inject = () => ({ + hooks: { tab: tabStore.observable }, + action: { openTab }, +}) + +function TabView({ useTab, action }: Props) { + const { loaded } = useTab() // the renderer owns the subscription + return +} +``` + +The whole view store is injected for the component to pick fields from, and a module-level handle takes instance lifecycle away from the framework: + +```tsx +// The component receives the store itself and picks its own fields. +const inject = () => ({ viewStore }) + +function SidebarHeader({ viewStore }: Props) { + return +} + +// Module-level handle: one identity shared by every plugin load. +export const paneStore = createPaneStore() +``` + +The component's dependency face stops being auditable, and the shared module identity outlives every scope teardown: two panes end up on one instance instead of one each. + +## Identity and initial state are deliberate + +Switching state does not remount a control or replace its DOM node: the instance and its DOM identity stay the same across a state change, so focus, selection, and an in-progress draft survive it. Initial state is ready when the first flow runs — the same path prepares the data and establishes the state — instead of being filled in later by an effect. A component receives hooks, selectors, and action callbacks rather than a whole service. + +- Judged by: after a state change, whether the control instance and its DOM node keep their identity; an unmount followed by a mount is the violation. The initialization path is judged the same way: state established inside the first flow passes, state written from an effect fails. +- Dependency face: hooks read, selectors pick a sub-state, and action callbacks write back. A whole service passed as a prop or an injected member fails. +- Scope: input and command controls that hold an internal instance and local state, and business views created by a factory. +- Exception: a genuinely required remount — switching to a data set whose instance state cannot migrate — is explained in review together with the state migration plan; the reviewer of a change that affects a control's instance lifetime accepts it. +- Fix: derive the initial value where the first flow builds its state, keep the layout node mounted and vary its props, and replace a service prop with the three narrow shares. + +The draft exists with the session and the composer node stays mounted while only its props change: + +```tsx +// The draft is built by the first flow; nothing fills it in later. +const draft = useDraftState(sessionId) +const { canSend } = useComposerSelectors(draft) + +// The node stays mounted; state changes reach it as props. +return ( +
+ {draft.text} +
+) +``` + +Initial state arrives one commit late, and the keyed control is rebuilt whenever the session changes: + +```tsx +// The draft is filled in after the first commit. +useEffect(() => { setDraftState(initialDraft) }, []) + +// The keyed composer unmounts on every session switch. + +``` + +The first frame renders an empty draft, and every session switch drops focus, selection, and whatever the user had typed. + +## `useLayoutEffect` is not a default + +`useLayoutEffect` is not used by default, and replacing it with `useEffect` is not a fix, because the two differ in timing rather than in what the code is doing. A layout measurement first answers why it happens here, why CSS cannot express it, and why it must be a pixel measurement; only then does it move into an injected measurement hook with the owning domain expert's sign-off. An effect of either kind never records state or binds logic, because that belongs in Injection. + +- Judged by purpose, not by hook name: which measurement or which binding the effect exists for. A state-recording or logic-binding effect returns to Injection as a Provider or an injected hook; only a measurement that survived the three questions stays, and its result is consumed as a declarative layout parameter. +- Not covered: the timing difference between the two effects, which `@types/react` documents for `useLayoutEffect` as synchronous after DOM mutation and before paint, is background fact and not a license to rewrite one as the other. +- Exception: any retained `useLayoutEffect` needs the owning domain expert's confirmation, and the change records that confirmation. +- Fix: express the layout in CSS — grid, `aspect-ratio`, a container query — or collect the measurement inside the injected hook and expose one value. + +Layout is declared in CSS, and the one measurement that survived the questions lives in an injected hook: + +```tsx +// Fix 1 — express the layout in CSS and delete the measurement. +// .card { display: grid; grid-template-columns: minmax(0, 1fr) auto; aspect-ratio: 16 / 9; } + +// Fix 2 — the approved measurement is injected and returns one value. +function CardBase({ useLayoutMeasurements }: Props) { + const ref = useRef(null) + const { gutterWidth } = useLayoutMeasurements(ref) + return
+} +``` + +Both of the first two effects below answer the wrong question — which effect to use — and the third parks a binding in an effect: + +```tsx +// A synchronous pixel measurement the design did not need. +useLayoutEffect(() => { setHeight(ref.current.getBoundingClientRect().height) }, []) + +// The same measurement with the hook name swapped. +useEffect(() => { setHeight(ref.current.getBoundingClientRect().height) }, []) + +// Logic binding parked in an effect instead of Injection. +useEffect(() => { bindShortcut(handler) }, []) +``` + +The rename leaves the layout problem in place, the measured height now depends on which effect was chosen, and the shortcut binds one render late instead of through Injection. + +## Effects never push render-derived data to a parent + +An effect body never calls a setter that arrived through props or slot props to push data back to a parent when that data could be decided during render from props or state the component already has. Such a push costs a second render, leaves the parent without the value on its first frame, and turns any later state change into a render cascade. The value is decided during render, the host takes it through a render-time channel, or a user gesture updates its own state in its handler. + +- Judged by: a setter from props or slot props called inside an effect, whose argument derives from the current props or state, with no external event or subscription callback driving it. A cleanup `return () => setX(undefined)` is part of the same violation. +- Consequences to name in review: the extra render pass; the parent's first frame missing the value; a dependency array that goes stale when a member is omitted; the effect → parent state → render cascade; and a child lifecycle entangled with parent state. +- Not covered: an effect that reacts to a genuine external event — a subscription callback, a socket frame, a user gesture — is not this pattern, and an event handler may update state directly. +- Exception: none by default; any exception needs the owning domain expert's confirmation. +- Fix, in order: render the UI where the state already is; if the host must render it, hand the value over during render; if the state is shared across entries, move it to the inject face or a declared store. + +The control is rendered where its state already lives, and the shared variant is read during render while the write stays in the gesture handler: + +```tsx +// 1. Render it where the state already lives; no channel is needed. +return + +// 2. The host renders it: the flag is declared state, read during render +// and written only from the gesture handler. +const { showOriginal } = useStore() +const { toggleOriginal } = actions +return +``` + +`label` and `disabled` are render-derivable, so calling the parent's setter from an effect makes the parent render twice and still lack the header on its first frame: + +```tsx +useEffect(() => { + setHeaderAction({ label, disabled, onClick }) // render-derivable data pushed up + return () => { setHeaderAction(undefined) } +}, [label, disabled, setHeaderAction]) +``` + +The parent renders twice for data it could have had on the first pass, the header appears a frame late or flashes, and the hand-written dependency list decides when it is published. + +## Build and style follow their owners + +Every build adjustment for a client package goes through the tsdown plugin for that package, and a package does not grow its own build branch. Styling goes through CSS Modules, and only images, GIFs, and SVG are inlined — inlined into CSS rather than into JSX. Large text never appears inline in TSX, and a `style` object holds only runtime-computed values, because static values and style variants belong to CSS Module class names. + +- Judged by: a new build branch inside a package instead of the tsdown plugin; a literal color, a component library, or Tailwind in feature styling; base64 data or large text in TSX; and a `style` object carrying static values or a variant switch. +- Not covered: a runtime-computed value such as a measured gutter or a progress percentage may enter `style`, and a component-local custom property may carry a layout value. [Component rules](../web-styling.md#component-rules) own the tokens, CSS Module, and class-name rules. +- Exception: a new build branch or a new inline form is explained in review before it lands, and the owning package's rules decide whether it stays. +- Fix: move the variant into a CSS Module class switched by `className`, keep base64 in CSS produced by the build chain, and delete the large text constant from the TSX module. + +The component switches class names and data attributes, and the CSS Module owns the presentation: + +```tsx +import s from './card.module.css' + +// Style variants are class names, not style-object branches. +export function Card({ active, tone, children }: Props) { + return ( +
+ {children} +
+ ) +} +``` + +Large text and inlined binary data enter the module, and the `style` object encodes a variant the theme cannot override: + +```tsx +const HUGE = '...several KB of text...' // large text inline in the module + +// A variant switch and an inlined asset both sit in the style object. +
+``` + +The bundle carries text and binary data that belong in CSS and assets, diffs carry unreadable blobs, and a theme override can no longer reach that colour. + +## A key states what it identifies + +Pass a `key` only when it names which entity or instance an element represents, and state that identity — a `turnId`, for example, is unique inside one session. Most lists already have a stable business id and need no extra key. A key invented to silence a warning or to encode render order states an identity the data does not have, and an array index is never that identity, because an insert or delete shifts every following item onto a different element. + +- Judged by: whether the item's identity can be expressed by position or by a stable id. When a key is passed, the change states what makes it unique, and `key={index}` over a mutable list fails. +- Not covered: React's own requirement that a list's items carry keys still applies; that key is the item's stable business id and not a second key beside it. +- Exception: none. An ordinary change needs no sign-off, while the key semantics of a shared component are stated in review. +- Fix: use the entity's stable id, and when two rows genuinely share one id, fix the id source instead of mixing an index into the key. + +The key is the turn's own id, whose uniqueness inside a session is the identity the element represents: + +```tsx +// turnId is unique inside a session; the id is the identity. +export function TurnList({ turns }: Props) { + return ( +
    + {turns.map((turn) => )} +
+ ) +} +``` + +The index stands in for identity, so every following row changes identity when the list changes: + +```tsx +// The index stands in for identity. +{items.map((item, index) => ( + +))} +``` + +After an insert or a delete, each following row keeps its previous state on new data, so an expanded row or an in-progress edit appears on the wrong item. + +## Each shared layer keeps its own isolation level + +A feature absorbs its requirement in its own package, and how much separation it must keep from shared code depends on which shared layer that code belongs to. The violation to look for is a feature-specific concept placed in a shared layer, because every other consumer then has to understand a concept that is not theirs and the branch is hard to withdraw. + +| Shared code | Isolation a feature keeps | +|---|---| +| `ui-primitives`, the catalogued controls | Consume the catalogued control. A new control starts in the feature package and is promoted into the shared catalog only when a second consumer needs it. | +| `ui-layout` and the shell layout | Consume it; adapt in the feature package with a wrapper, an overridden style, or an added layer. | +| `ui-renderer` and the other render machinery | No value dependency from business code; extend only through the documented registration seams — slots, provide/inject-bound hooks, declared stores. | +| Another feature plugin | No runtime import and no re-export of its values. UI crosses through slots and behavior through injected services; shared runtime code lives in a narrow static owner such as `client/store`, `ui-primitives`, or a browser-safe utility package. | +| The data object layer (`client/connection`, `session-controller/client`, `client/store`) | Read through the documented surface; a feature's own concepts do not enter these objects or their stores. | +| The feature's own package | Unrestricted — the requirement is absorbed here, including its own rows, ordering, and presentation. | + +- Judged by: whether the diff puts a feature-specific branch, field, or concept into any layer but the feature's own package. +- Not covered: code the feature owns, and a change to a shared layer that is genuinely general rather than one feature's need. +- Exception: a shared-layer change carries the owning domain expert's confirmation and regresses every consumer; a GUI change runs the minimum check in [packages/client/AGENTS.md](../../packages/client/AGENTS.md). +- Fix: absorb the requirement in the feature package, or, when the need is genuinely general, promote it to the shared layer in its own change with the owner's sign-off. + +The feature owns its row rendering and its ordering rule, and the base component is consumed unchanged: + +```tsx +// The feature owns its rows; the base is consumed, not edited. +// packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx +export function WorkspaceBrowser({ rows, onArchive }: Props) { + const ordered = [...rows].sort((a, b) => Number(b.archived) - Number(a.archived)) + return ( +
    + {ordered.map((row) => )} +
+ ) +} +``` + +A base component learns one feature's ordering rule, so every consumer inherits a concept that is not theirs: + +```tsx +// ui-layout: the base learns one feature's ordering rule. +export function BrowserList({ rows, ...rest }: Props) { + const ordered = [...rows].sort((a, b) => Number(b.archived) - Number(a.archived)) + return
    {ordered.map((row) => )}
+} +``` + +Every other consumer of `ui-layout` now has to understand an archive concept that only one feature has, and withdrawing the branch means auditing all of them. diff --git a/docs/defensive-patterns/client-components.zh.md b/docs/defensive-patterns/client-components.zh.md new file mode 100644 index 0000000000..6bd92e4e57 --- /dev/null +++ b/docs/defensive-patterns/client-components.zh.md @@ -0,0 +1,495 @@ +# 客户端组件规则 + +[English](client-components.md) | 中文 + +关于客户端组件、其状态与 effect 的规则。详细纪律见 [packages/client/AGENTS.md](../../packages/client/AGENTS.md);Slot 设计正家是 [slots.zh.md](../subsystems/slots.zh.md),样式规则正家是 [web-styling.zh.md](../web-styling.zh.md)。以下每一节给出要求、评审判定方式、边界与例外,以及一正一反两个例子。 + +## 状态经 Injection 到达 + +Slot 的组件经**自己注册项**的 inject 面获得它渲染所需的一切——普通数据、action 回调,以及渲染器绑定成 `use` hook 的保留 `hooks` 隔间——而父组件的渲染点经派生的 `renderSlot` 传 owner 数据。它绝不先在顶层读一棵大全局状态再逐层手工传下去。把每个活值都放在那个面上,props 才能在没变时保持引用不变,组件也才能只订阅自己读取的那部分子状态。缺了这条,任何一个无关字段变化都会重渲整棵子树——长会话在流式事件下的掉帧、滚动与输入卡顿就是这么来的。 + +- 判定方式:在注册项与其渲染点上,作者都必须能回答两件事——被渲染组件订阅了哪些子状态,以及它收到的哪些 props 在多次渲染之间保持引用稳定。要盯住每个 prop 的可变性:每次渲染都重建的值(新对象、新数组、内联回调)即使内容没变也会向下传播重渲。 +- 不在范围内:组件自己的局部状态(折叠、悬停、草稿用的 `useState`)不属于注入内容;不订阅 React 之外任何东西的组件也不需要新席位。 +- 例外:新增 hook 席位会改动 Slot 契约,因此该改动要在 review 中说明影响面——哪些组件订阅什么;使用既有注入面不需要逐组件批准。 +- 修法:把注入收窄到该视图真正渲染的内容,每个读取项经一个 hook 席位暴露一个字段,用窄 action 集合取代 store 或 service 句柄。[组件输入](../subsystems/slots.zh.md#component-inputs) 正家负责 inject 工厂、标准 hook 席位,以及它们各自如何成为 prop。 + +注册项承载普通数据、一组窄 action 与一个 hook 席位;渲染点只传 owner 数据,组件只读它渲染的那个字段: + +```tsx +// The inject factory returns plain data and callbacks; hooks is the reserved compartment. +ctx.slots.register( + { + name: 'sidebar.right', + inject: () => ({ + rename, + hooks: { info: infoSource }, // bound by the renderer as useInfo() + }), + }, + SidebarRight, +) + +// The parent's render site passes owner data through the derived renderSlot. +{renderSlot('sidebar.right', { id })} + +function SidebarRight({ id, useInfo, rename }: Props) { + const { title } = useInfo() // subscribes to title only + return +} +``` + +顶层组件读了整个 view store 并把它作为一个 prop 传下去,于是渲染点再也回答不了上面两个问题: + +```tsx +function Sidebar() { + const view = useViewStore() // one top-level global read + return // the whole store travels down +} + +function SidebarRight({ view }: { view: ViewStore }) { + return {view.activePanel.title} +} +``` + +该 store 里任何字段变化都会重渲整个侧栏子树,而且绑定它的渲染点完全看不到这个组件订阅了什么。 + +## props 承载数据与回调,不承载 React 节点 + +prop 是数据或回调;React 节点经声明的 slot 传递。把元素作为 prop 值或注入成员传下去,会藏起一条 Slot 契约没有描述的第二条组合路径,把渲染控制权从注册面挪到调用点,并让一个包去拼装另一个包的标记。新增的节点型 prop 或注入成员一律禁止;需要宿主提供标记的位置,改为声明一个 child slot。 + +- 判定方式:组件的 props 类型、inject 工厂的返回值、或渲染点的 owner props 对象里出现 `ReactNode`、`ReactElement` 或 `() => JSX.Element`。 +- 不在范围内:已经发布的节点型字段继续可用。规则在改动波及它时触发,该改动把它改掉,而不是继续扩展它。 +- 例外:同一改动内无法完成改造时,由对应领域专家确认延期,且改动中记录该确认;作者不得自行确认。 +- 修法:在父级注册的 `children` 中声明该位置,用 `renderSlot` 渲染它,数据经子组件的 props 传入。[扩展规则](../subsystems/slots.zh.md#extension-rules) 正家负责哪个包可以声明和渲染哪个 slot。 + +头部位置是一个声明的 child slot,因此宿主只传数据,标记由注册组件自己决定: + +```tsx +// The card declares the header location; the host passes data only. +ctx.slots.register( + { + name: 'tool.call.toolview', + children: { header: { kind: 'single', scope: 'session' } }, + }, + ToolCard, +) + +function ToolCard({ title, renderSlot }: Props) { + return
{renderSlot('header', { title })}
+} +``` + +React 节点作为 prop 值越过边界,于是它所走的组合路径没有任何地方声明过: + +```tsx +type ToolCardProps = { + header?: React.ReactNode + footer?: React.ReactNode +} + +// The call site assembles another package's markup. +} /> +``` + +卡片的 Slot 契约不再描述它渲染什么,调用点继续握着渲染控制权,而徽章所在的包变成了传节点方的运行时引用。 + +## slot 注册物是稳定的 function component + +注册进 slot 的值是在模块作用域声明的稳定 function component。渲染期创建的组件函数每一轮都是新的组件类型,而 React 把变化的类型当作另一个组件:它卸载这棵子树并挂载一棵新的,展开的行、输入焦点与滚动位置随之重置。注册期参数经 props 到达组件,而不是靠闭包捕获渲染期变量。 + +- 判定方式:注册物在哪里创建。注册调用或渲染调用里的内联箭头、渲染函数体内定义的组件、以及用 `useCallback` 包住内联组件的写法都不合格;模块作用域的 `function` 声明合格。 +- 不在范围内:本条约束的是注册物的身份,不是它的复杂度。稳定组件照样可以读取注入的 props、hooks 与回调。 +- 例外:只有调用方确实想要这次重挂载时,渲染期创建组件才是对的,普通改动无需单独批准;Slot 契约形态的变更按「状态经 Injection 到达」一节描述的注入面 review 走。 +- 修法:把组件移到模块作用域,用注册面的各个 share 给它的 props 定型,让变化的值经 inject 面传入而不是走闭包。 + +注册项持有对模块作用域组件的稳定引用,变化的值经注入到达;局部组件由渲染点传入: + +```tsx +function PanelTitle({ title, count }: Props) { + return {title} ({count}) +} + +// Registration: the local slot's scope is declared, never a component. +ctx.slots.registerFactory( + { + name: 'panel', + scope: 'root', + slots: { title: { scope: 'root' } }, + inject: () => ({ title: 'Sessions', count: 3 }), + }, + Panel, +) + +// The render site passes the local component, keeping its identity stable. +renderFactorySlot('panel', { /* owner data */ }, { slots: { title: PanelTitle } }) +``` + +渲染调用里的内联箭头会在该次渲染运行时产生新的组件类型: + +```tsx +// A new component type each time this render runs. +renderFactorySlot('panel', { /* owner data */ }, { slots: { title: (p) => {p.title} } }) +``` + +React 看到的类型与上一次注册不同,于是重挂载该席位,并在一次无关更新中重置它的局部状态——展开态、焦点或滚动位置。 + +## 组件绝不接收 Cordis context + +`ctx` 属于 apply 世界:插件主体与闭包持有它的 `inject` 工厂。组件不接收 Cordis context、不导入 service 类去戳它、也不读 React context,因为业务组件看不到任何 context——渲染器的 binding context 是它内部的。裸 observable 只有在 Injection 把它包成 hook 之后才到达组件;直接自行订阅的组件持有一份 Injection 面上无人释放的生命周期。 + +- 判定方式:组件的参数或 props 类型里出现 `ctx` 或 `Context`;组件体内读 `observable.value`、调用 `subscribe`、或接 `useSyncExternalStore`;feature 的 `.tsx` 模块里导入 service 类。 +- 不在范围内:组件内部、不订阅 React 之外任何东西的行为 hook(计时器、媒体查询)不是注入内容,留在组件里。 +- 例外:无。`TabSlot` 里现存的直接订阅是该席位 owner 的整改工作,不是新代码的先例。 +- 修法:把该事实移进注册的 `inject`——纯数据与回调,裸 observable 放进保留的 `hooks` 隔间——或移进声明的 store,再经派生的席位读取。 + +Injection 绑定 observable,组件读一个派生的 hook,订阅生命周期由渲染器持有: + +```tsx +// The inject factory is the only place that closes over ctx. +const inject = () => ({ + hooks: { tab: tabStore.observable }, + action: { openTab }, +}) + +function TabView({ useTab, action }: Props) { + const { loaded } = useTab() // the renderer owns the subscription + return +} +``` + +整个 view store 被注入给组件自行挑选字段,模块级句柄则把实例生命周期从框架手里拿走: + +```tsx +// The component receives the store itself and picks its own fields. +const inject = () => ({ viewStore }) + +function SidebarHeader({ viewStore }: Props) { + return +} + +// Module-level handle: one identity shared by every plugin load. +export const paneStore = createPaneStore() +``` + +组件的依赖面不再可审计,而共享的模块身份活得比任何一次 scope 清理都久:两个 pane 会落到同一个实例上,而不是各自一个。 + +## 身份与初始状态都是刻意的 + +状态切换不重建控件、也不替换其 DOM 节点:实例与其 DOM 身份在状态变化之间保持同一,焦点、选中与进行中的草稿因此得以保留。初始状态在首个流程运行时即就绪——同一条路径既准备数据也建立状态——而不是之后由 effect 回填。组件接收 hooks、选择器与 action 回调,而不是整个 service。 + +- 判定方式:状态变化之后,控件实例与其 DOM 节点是否保持同一身份;出现卸载再挂载即违反。初始化路径同样判定:状态在首个流程内建立合格,从 effect 写入不合格。 +- 依赖面:hooks 读取、选择器选中子状态、action 回调写回。整个 service 作为 prop 或注入成员传入即不合格。 +- 范围:带内部实例与本地状态的输入与命令控件,以及由 factory 创建的业务视图。 +- 例外:确需重挂载(切换的数据集其实例状态不可迁移)时,在 review 中连同状态迁移方案一并说明;由评审该控件实例生命周期改动的评审者接受。 +- 修法:在首个流程建立状态的地方派生初始值,保持布局节点挂载、只变化其 props,并用三个窄 share 取代 service prop。 + +草稿随会话一起建立,composer 节点保持挂载,只有 props 随状态变化: + +```tsx +// The draft is built by the first flow; nothing fills it in later. +const draft = useDraftState(sessionId) +const { canSend } = useComposerSelectors(draft) + +// The node stays mounted; state changes reach it as props. +return ( +
+ {draft.text} +
+) +``` + +初始状态迟一个提交到达,带 key 的控件在每次会话切换时被重建: + +```tsx +// The draft is filled in after the first commit. +useEffect(() => { setDraftState(initialDraft) }, []) + +// The keyed composer unmounts on every session switch. + +``` + +首帧渲染出空草稿,每次会话切换都会丢掉焦点、选中,以及用户已经输入的内容。 + +## `useLayoutEffect` 不是默认选项 + +`useLayoutEffect` 默认不用,换成 `useEffect` 也不算修好,因为二者的差别在时序,而不在代码在做什么。布局测量先回答三个问题——为何在此处发生、为何 CSS 无法表达、为何必须是像素测量;只有回答完,才收进注入的测量 hook 并取得对应领域专家的确认。两类 effect 都不承担状态记录或逻辑绑定,那是 Injection 的职责。 + +- 判定依据是用途而不是 hook 名字:这个 effect 为哪次测量或哪次绑定而存在。状态记录或逻辑绑定的 effect 回到 Injection——Provider 或注入 hook;只有通过三问的测量才留下,其结果作为声明式布局参数消费。 +- 不在范围内:两个 effect 的时序差异(`@types/react` 记载 `useLayoutEffect` 在 DOM 变更后同步触发、绘制前刷出)是背景事实,不是把其一改写为另一的许可。 +- 例外:任何保留下来的 `useLayoutEffect` 都要经对应领域专家确认,改动中记录该确认。 +- 修法:用 CSS 表达布局——grid、`aspect-ratio`、容器查询——或把测量收进注入 hook 并暴露一个值。 + +布局用 CSS 声明,唯一通过三问的测量住在注入 hook 里: + +```tsx +// Fix 1 — express the layout in CSS and delete the measurement. +// .card { display: grid; grid-template-columns: minmax(0, 1fr) auto; aspect-ratio: 16 / 9; } + +// Fix 2 — the approved measurement is injected and returns one value. +function CardBase({ useLayoutMeasurements }: Props) { + const ref = useRef(null) + const { gutterWidth } = useLayoutMeasurements(ref) + return
+} +``` + +下面前两个 effect 回答的是错的问题——该用哪个 effect——第三个把绑定停在 effect 里: + +```tsx +// A synchronous pixel measurement the design did not need. +useLayoutEffect(() => { setHeight(ref.current.getBoundingClientRect().height) }, []) + +// The same measurement with the hook name swapped. +useEffect(() => { setHeight(ref.current.getBoundingClientRect().height) }, []) + +// Logic binding parked in an effect instead of Injection. +useEffect(() => { bindShortcut(handler) }, []) +``` + +改名并不能解决布局问题,量到的高度从此取决于选了哪个 effect,而快捷键绑定迟一轮渲染生效,没有回到 Injection。 + +## effect 绝不把渲染期可派生的数据推给父层 + +effect 体内绝不调用经 props 或 slot props 传来的 setter,把本可在渲染期由组件已有的 props / state 决定的数据推回父层。这种推送要多付一轮渲染、让父层首帧拿不到值,并把之后任何一次状态抖动放大成渲染级联。该值在渲染期决定,宿主经渲染期通道取得,或由用户手势在其处理器内更新自己的状态。 + +- 判定方式:effect 体内调用了 props 或 slot props 传来的 setter,其入参由当前 props / state 派生,且没有外部事件或订阅回调驱动它。清理函数 `return () => setX(undefined)` 属于同一违规。 +- review 中要点名的后果:多一轮渲染;父层首帧缺值;依赖数组漏项即 stale;effect → 父 state → 再渲染的级联;子组件生命周期与父层状态纠缠。 +- 不在范围内:响应真实外部事件的 effect——订阅回调、socket 帧、用户手势——不是本形态;事件处理器可以直接更新状态。 +- 例外:默认无例外;任何例外都要经对应领域专家确认。 +- 修法按顺序:状态在哪里就让 UI 在哪里渲染;必须由宿主渲染时,在渲染期把值交出去;跨条目共享的状态移进注入面或声明的 store。 + +控件在状态所在处渲染,共享的开关在渲染期读取,写回只发生在手势处理器里: + +```tsx +// 1. Render it where the state already lives; no channel is needed. +return + +// 2. The host renders it: the flag is declared state, read during render +// and written only from the gesture handler. +const { showOriginal } = useStore() +const { toggleOriginal } = actions +return +``` + +`label` 与 `disabled` 都是渲染期可派生的,从 effect 调用父层 setter 让父层渲染两轮、首帧仍然没有头部动作: + +```tsx +useEffect(() => { + setHeaderAction({ label, disabled, onClick }) // render-derivable data pushed up + return () => { setHeaderAction(undefined) } +}, [label, disabled, setHeaderAction]) +``` + +父层为本来第一轮就能拿到的数据渲染两轮,头部迟一帧出现或闪烁,而发布时间由手写的依赖数组决定。 + +## 构建与样式各归其主 + +客户端包的每项构建调整都经该包的 tsdown 插件完成,包内不新开自己的构建分支。样式走 CSS Module,只有图像、GIF 与 SVG 需要内联——且内联到 CSS 而不是 JSX。TSX 里绝不内联大文本,`style` 对象只放运行期计算的值,因为静态值与多样式切换属于 CSS Module 的 class name。 + +- 判定方式:包内新开构建分支而不是走 tsdown 插件;feature 样式里出现字面颜色、组件库或 Tailwind;TSX 里出现 base64 数据或大文本;`style` 对象承载静态值或样式切换。 +- 不在范围内:运行期计算的值(量到的 gutter、进度百分比)可以进 `style`,组件局部自定义属性也可以承载布局值。[组件规则](../web-styling.zh.md#component-rules) 正家负责 token、CSS Module 与 class name 规则。 +- 例外:新增构建分支或新的内联形态在落地前于 review 中说明理由,由所属包的规则决定是否保留。 +- 修法:把样式切换移进用 `className` 切换的 CSS Module class,base64 交给构建链写进 CSS,并从 TSX 模块里删掉大文本常量。 + +组件切换 class name 与 data 属性,呈现由 CSS Module 负责: + +```tsx +import s from './card.module.css' + +// Style variants are class names, not style-object branches. +export function Card({ active, tone, children }: Props) { + return ( +
+ {children} +
+ ) +} +``` + +大文本与内联二进制数据进了模块,`style` 对象还编码了主题无法覆盖的样式切换: + +```tsx +const HUGE = '...several KB of text...' // large text inline in the module + +// A variant switch and an inlined asset both sit in the style object. +
+``` + +包里带上了本该属于 CSS 与资源的文本和二进制数据,diff 里躺着无法阅读的 blob,主题覆盖也再够不到那个颜色。 + +## 传 key 就要说明它标识什么 + +只有当 `key` 指明元素代表哪个实体或实例时才传它,并把这份身份说清楚——例如 `turnId` 在一个 session 内唯一。多数列表本就有稳定的业务 id,不需要额外的 key。为消除警告或编码渲染顺序而造的 key,声明的是一份数据并不具备的身份;数组下标从来不是这份身份,因为插入或删除会把后面每一项挪到另一个元素上。 + +- 判定方式:条目的身份能否由位置或稳定 id 表达。传 key 时,改动要说明它因何唯一,而可变列表上的 `key={index}` 不合格。 +- 不在范围内:React 要求列表项带 key 这条规则依然成立;那个 key 就是条目的稳定业务 id,不是它旁边的第二个 key。 +- 例外:无。普通改动无需批准,公共组件的 key 语义要在 review 中说明。 +- 修法:使用实体的稳定 id;两行确实共用一个 id 时,修 id 的来源,而不是往 key 里掺下标。 + +key 就是 turn 自己的 id,它在 session 内唯一,正是元素所代表的身份: + +```tsx +// turnId is unique inside a session; the id is the identity. +export function TurnList({ turns }: Props) { + return ( +
    + {turns.map((turn) => )} +
+ ) +} +``` + +下标冒充身份,于是列表一变,后面每一行的身份都跟着变: + +```tsx +// The index stands in for identity. +{items.map((item, index) => ( + +))} +``` + +插入或删除之后,后面每一行都会把先前的状态带到新数据上,展开的行或编辑中的内容会出现在错误的条目上。 + +## 每层共享代码各有自己的隔离度 + +功能把诉求吸收在自己的包里;它需要与共享代码保持多大隔离,取决于那段代码属于哪一层共享。要盯的违规形态是把业务专属概念放进共享层,因为此后每个使用方都得理解一个不属于自己的概念,而这个分支很难撤回。 + +| 共享代码 | 功能应保持的隔离度 | +|---|---| +| `ui-primitives`,目录中的控件 | 消费目录中的控件。新控件先在功能包内落地,只有出现第二个使用方时才提升进共享目录。 | +| `ui-layout` 与 shell 布局 | 消费它;在功能包内通过 wrapper、覆盖样式或加一层来适配。 | +| `ui-renderer` 及其他渲染机制 | 业务代码不产生值依赖;只经文档化的注册面扩展——slots、provide/inject 绑定的 hooks、声明的 store。 | +| 另一个功能插件 | 不运行时导入、也不重新导出它的值。UI 经 slots 跨越,行为经注入的服务跨越;共享运行时代码住在窄的静态正家,如 `client/store`、`ui-primitives` 或浏览器安全的工具包。 | +| 数据对象层(`client/connection`、`session-controller/client`、`client/store`) | 经文档化接口读取;功能自己的概念不进入这些对象及其 store。 | +| 功能自己的包 | 不受限——诉求在这里被吸收,包括它自己的行、排序与呈现。 | + +- 判定方式:diff 是否把业务专属的分支、字段或概念放进了功能自己包以外的任何一层。 +- 不在范围内:功能自己拥有的代码;以及确实属于通用需求、而不是某一个功能需要的共享层改动。 +- 例外:共享层的改动要带上所属领域专家的确认,并回归所有使用方;GUI 改动按 [packages/client/AGENTS.md](../../packages/client/AGENTS.md) 的最低检查自验。 +- 修法:把诉求吸收进功能包;确属通用需求时,在独立改动中连同 owner 的确认一起提升到共享层。 + +功能自己拥有行渲染与排序规则,基座组件按原样消费: + +```tsx +// The feature owns its rows; the base is consumed, not edited. +// packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx +export function WorkspaceBrowser({ rows, onArchive }: Props) { + const ordered = [...rows].sort((a, b) => Number(b.archived) - Number(a.archived)) + return ( +
    + {ordered.map((row) => )} +
+ ) +} +``` + +基座组件学会某一个功能的排序规则,于是每个使用方都继承了一个不属于自己的概念: + +```tsx +// ui-layout: the base learns one feature's ordering rule. +export function BrowserList({ rows, ...rest }: Props) { + const ordered = [...rows].sort((a, b) => Number(b.archived) - Number(a.archived)) + return
    {ordered.map((row) => )}
+} +``` + +`ui-layout` 的每个其他使用方从此都要理解只有那一个功能才有的归档概念,撤回该分支意味着把它们全部审一遍。 diff --git a/docs/defensive-patterns/conversation-and-session.i18n.yaml b/docs/defensive-patterns/conversation-and-session.i18n.yaml new file mode 100644 index 0000000000..210cfe8b06 --- /dev/null +++ b/docs/defensive-patterns/conversation-and-session.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for conversation-and-session.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/defensive-patterns/conversation-and-session.md +/conversation-and-session-rules: + en: 499609ba1c6822d8 + zh: 7429eabcce7d7c14 +/conversation-and-session-rules/projection-is-the-only-read-and-compute-path: + en: 9fa9a332c93ba386 + zh: ce01ccb47dfa5df7 +/conversation-and-session-rules/cold-reads-are-the-last-resort: + en: 32991da738e47f7f + zh: b138910f8c16d103 +/conversation-and-session-rules/retention-follows-one-lifecycle-rule: + en: fcb40a31d0881e84 + zh: 779bc49cce81651e +/conversation-and-session-rules/node-computation-is-incremental-and-streaming-publication-is-batched: + en: 315c7ac2186d0721 + zh: 06bb4e072b242fe1 +/conversation-and-session-rules/the-node-build-and-grouping-engine-carries-no-business-rule: + en: ebfa96408f32c3c1 + zh: fb854b2b3e37aa9b +/conversation-and-session-rules/the-node-list-and-seat-components-carry-no-business-branch: + en: f69c4c16f472adcc + zh: 4570a62aa3d934fb +/conversation-and-session-rules/the-markdown-pipeline-carries-no-business-branch: + en: b124a7515404ed9e + zh: 4b544c2d1bbb6e76 +/conversation-and-session-rules/the-user-message-model-and-rendering-carry-no-business-field: + en: 8f97bbeaba14be0d + zh: cfad05711395cbd2 diff --git a/docs/defensive-patterns/conversation-and-session.md b/docs/defensive-patterns/conversation-and-session.md new file mode 100644 index 0000000000..7b91d6a676 --- /dev/null +++ b/docs/defensive-patterns/conversation-and-session.md @@ -0,0 +1,316 @@ +# Conversation and Session rules + +English | [中文](conversation-and-session.zh.md) + +Rules for reading a Session, holding one, computing conversation nodes, and rendering them. The data model and per-type semantics live in [session-projection.md](../subsystems/session-projection.md) and [conversation.md](../subsystems/conversation.md). + +## Projection is the only read and compute path + +Session data is read and computed through Projection. A client reads a projection value instead of pulling the Session log, and a computation that belongs to the Session runs as a registered projection unit that publishes its result instead of being recomputed on demand. Two answers to the same question — one pulled, one pushed — drift apart, so a render can show a value the Session log no longer supports. + +- Judged condition: every Session-derived value a client renders arrives through a projection read at the render position, and every new in-Session computation is registered as a unit whose result reaches clients as a published value. A component that fetches Session data itself, or a computation a reader triggers on demand, is the violation. +- State and View: a unit folds host-side State and declares the client-visible View over it, and the registration states that division. The `ProjectionDefinition` fields and the registry that drives them belong to [session-projection.md](../subsystems/session-projection.md#ctxsessionprojections--sessionprojectionregistry). +- Version: `stateVersion` starts at 1 and is bumped whenever the serialized state fields or the fold semantics change, compatible or not. Prefer a compatible change where one exists, but still bump; registering one key twice with different `stateVersion` values throws instead of merging. +- Compute strategy: units compute in full by default. Narrowing what a unit computes needs the owning domain expert's confirmation, never the implementer's own decision. +- Boundary: a partial projection view may serve interface availability for individual keys, such as a cached block drawn before the connected Session answers. It never decides an externally visible result, which waits for the standard projection value. + +A component that reads at its render position, and a computation that registers instead of being pulled, both comply: + +```tsx +// The client reads the published value; it never fetches Session data itself. +function PlanChip({ useProjection }: PlanChipProps) { + const plan = useProjection('plan') + return plan === undefined ? null : +} + +// The computation is a registered unit; the registry drives it and publishes changes. +const planDefinition: ProjectionDefinition<'plan'> = { + key: 'plan', + stateVersion: 1, + init: () => emptyPlan, + apply: (state, event) => foldPlan(state, event), + wire: { viewSchema: planSchema, view: planView }, +} +``` + +A component that pulls the same value over its own request breaks the single read path: + +```tsx +function PlanChip() { + const [plan, setPlan] = useState() + useEffect(() => { + void fetchSessionPlan(sessionId).then(setPlan) // a second read path beside Projection + }, [sessionId]) + return plan === undefined ? null : +} +``` + +The pulled copy and the pushed value disagree, and no version check can tell which one the Session currently holds. + +## Cold reads are the last resort + +Read an available cache before the original log, and reach for a cold read only when no projection covers the data. The "small Session may be read in full" exception is removed and is not reconsidered. When cached and official data are not equivalent, a missing or stale row produces an explicit outcome instead of silently switching onto the slow path. + +- Judged condition: a Session read consults the projection cache first, and an absent row leaves an explicit state for the caller; a cache test whose `else` branch opens the complete log is the violation. +- Fallback semantics: the caller decides what a miss means and states it in the returned value. There is no cache-size or Session-size exception, and no approver for one. +- Boundary: this restriction is the client's. An absolute "never fork a cold read" on the host is not required, because the host may need to open a log the client cannot. + +The stored projection rows are read first, and a miss stays a state the caller renders: + +```ts ignore-check +// The listing reads stored projection rows; a miss remains an explicit state. +type ListingView = + | { kind: 'cached'; snapshot: ProjectionSnapshot } + | { kind: 'unknown' } + +function readListing(header: SessionHeader, keys: readonly ProjectionKey[]): ListingView { + const cached = ctx.sessionProjectionCache.cachedSnapshot(header, keys) + return cached === undefined ? { kind: 'unknown' } : { kind: 'cached', snapshot: cached } +} +// Opening the complete log is a separate operation the caller names, never this fallback. +``` + +A cache test that falls through to the complete log turns the slow path into the ordinary one: + +```ts ignore-check +function readListing(header: SessionHeader, session: Session): ListingView { + const cached = ctx.sessionProjectionCache.cachedSnapshot(header) + if (cached !== undefined) return { kind: 'cached', snapshot: cached } + return coldReadCompleteLog(session) // every miss pays the full-log read +} +``` + +Every miss now reads the whole log in the foreground, so a slow Session is slow on every listing rather than only on the path that asks for it. + +## Retention follows one lifecycle rule + +A client holds a Session through an explicit reference (`SessionReference`), and the reference count reaching zero releases it. Idle reclamation follows the one lifecycle rule — no references and nothing in flight — and never enumerates which Sessions may be reclaimed from business state, because that list has to be maintained by every feature that adds one. An implicit holder is invisible, so reclamation cannot tell who still uses the Session. + +- Judged condition: the predicate is `refCount == 0 && inflight == 0`. Does the code hold the Session across its acquire → use window through a reference that retain and release can be audited against? A module-level Session object or a global current id is the violation. +- Boundary: the enforced parts are the unified predicate and the absence of business-state enumeration; the release trigger itself is checked by hand, so hand-checking alone is not a rejection reason. +- Ownership: `retain`, `release`, `ready`, and teardown ordering belong to [the Session Controller's client references](../../packages/api/session-controller/README.md#client-references). A source-session mention carried in a message is a different type, owned by [session-reference.md](../subsystems/session-reference.md). + +A view that retains through an explicit reference and releases it on teardown complies: + +```ts ignore-check +class SidebarSessionView implements Disposable { + private readonly reference: SessionReference + + constructor(readonly id: SessionId, sessions: ISessions) { + this.reference = sessions.retain(id, { source: 'sidebarView' }) + void this.reference.ready.catch((error: unknown) => { console.error('opening failed:', error) }) + } + + [Symbol.dispose](): void { + this.reference.release() // the last reference releases the Session + } +} +``` + +Module state that keeps the Session object hides every holder from the reclaimer: + +```ts ignore-check +let currentSessionId: SessionId | undefined +const sessionCache = new Map() + +export function remember(session: Session): void { + currentSessionId = session.id + sessionCache.set(session.id, session) +} + +export function reclaimIdle(): void { + if (state === 'idle' || state === 'closed') reclaim() // a newly added state is missed +} +``` + +Nobody can count who still uses the Session, and the next state added to the Session escapes the enumeration and is never reclaimed. + +## Node computation is incremental and streaming publication is batched + +A new node computation states its complexity, and high-frequency streaming chunks never publish immediately and never recompute in full. A per-chunk full rebuild published at once puts the whole node collection on the frame budget, and the transcript stalls behind the stream. The append-path cost — with `D` registered Definitions, `D` matches and one constant-time Context-key lookup — and the publication vocabulary (`none`, `animation-frame`, `immediate`) are owned by [conversation.md](../subsystems/conversation.md#definition-and-typed-chat-payload). + +- Judged condition: how much one chunk computes — the increment on the affected subtree, not the event window — and when its result is published — a batching policy, not one publication per chunk. +- Boundary: this rule binds the implementation; cadence alone is not a rejection reason, so a change is judged on the cadence it states and the published path it uses. +- Forbidden on the high-frequency path: `immediate` publication, and a full recomputation per chunk. +- Boundary: a structural or terminal change may publish `immediate`, because the cadence is chosen per publication. Only the high-frequency delta path is bound to batching. + +A chunk that updates one Context and asks for a coalesced publication complies: + +```ts ignore-check +const assistantDefinition: ConversationNodeDefinition = { + kind: 'assistant-step', + target: 'chat', + match: event => matchAssistant(event), + start: (_context, match) => initialState(match), + update: (context, match) => appendChunk(context.state, match.event), // increment, not the window + publication: () => 'animation-frame', // high-frequency deltas coalesce; never immediate + buildViewNode: context => assistantNode(context), +} +``` + +Rebuilding the whole node collection for every chunk and publishing it immediately: + +```ts ignore-check +function onChunk(chunk: AssistantLiveChunk): void { + const nodes = buildNodesFromCompleteWindow(session) // full recompute per chunk + target.publish(nodes, { publication: 'immediate' }) // and an immediate publish +} +``` + +Each chunk costs a full-window rebuild inside the frame budget, so grouping and rendering stall behind the stream. + +## The node build and grouping engine carries no business rule + +Business rules never enter the grouping engine, and a business requirement never reshapes the built payload. `ProcessState`, the group product hierarchy, and the set of group semantics in `conversation-nodes/process-groups.ts` are infrastructure: the engine understands enum placement values such as grouped, standalone, and reply, and the caller computes which one applies. A special case inside the engine changes the produced structure for every consumer and puts a business condition on the group computation path. + +- Judged condition: does the engine contain a business condition? A diff that adds a `ProcessState` field, adds or removes a group level, or changes group semantics for one business fails; the placement decision belongs to the caller that computes the enum value. +- Boundary: the layering, its cost, and existing business expectations are the reason a business does not rework the grouping design. +- Boundary: a new enum value carrying a new placement meaning is the supported extension, wherever the caller computes it. +- Exception and approver: none by default. A change to this infrastructure needs the corresponding domain expert's confirmation. [conversation.md](../subsystems/conversation.md#group-definitions) owns the group Definition types. + +The caller decides the business meaning and passes the placement enum the engine places by: + +```ts ignore-check +// Business judgment stays in the caller. +function placementOf(command: CommandView): NodePlacement { + return isHandoff(command) ? 'reply' : 'grouped' +} + +// The engine consumes the enum as data; it reads no business condition. +function groupEntries(commands: readonly CommandView[]): readonly NodePlacement[] { + return commands.map(placementOf) +} +``` + +A business condition inside the engine's own computation: + +```ts ignore-check +// The grouping engine asks what a node means, not where it goes. +function placeProcessNode(node: ChatConversationViewNode): GroupPlacement { + if (node.kind === 'command' && isRagMessage(node)) return 'rag' // business special case + return 'grouped' +} +``` + +The produced structure now carries one business's meaning, so every consumer and the group computation follow that feature. + +## The node list and seat components carry no business branch + +`ChatNodeList`, `ChatNodeSeat`, and `ChatGroupSeat` are infrastructure. They carry no business condition and no business-specific field, and a single business never changes the list traversal or the seat selection. A new node shape contributes its kind to `ChatNodeDataMap` and its renderer through the kind registration surface, so the list keeps dispatching on kind while business semantics stay in the business module. A branch added for one feature makes every node's rendering depend on that feature. + +- Judged condition: a business branch in a list or seat component, a business-only field on its props, or a traversal or seat-selection change that serves one business. +- Correct outlet: the business package merges its own key into `ChatNodeDataMap` and registers a renderer for the node kind; the seat renders the registered component for the node's kind. The registration discipline is owned by [slots.md](../subsystems/slots.md#extension-rules). +- Boundary: a rendering change that applies to every business — ordering, virtualization, accessibility — is not a business modification. +- Exception and approver: none by default; the corresponding domain expert confirms any exception. + +A business package that declares its kind and registers its renderer leaves the shared list untouched: + +```tsx +// The business declares its kind and registers its renderer; the shared list is untouched. +declare module '@deepseek-ai/dsh-client-ui-chat/client' { + interface ChatNodeDataMap { handoff: HandoffData } +} + +const HandoffNodeView = memo(function HandoffNodeView({ node, t }: ChatNodeOwnerProps<'handoff'>) { + return +}) + +ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( + { name: 'conversation.chat.node', key: 'handoff', locale: NS }, HandoffNodeView)) +``` + +A business branch and a business field inside the shared seat: + +```tsx +export const ChatNodeSeat = memo(function ChatNodeSeat({ node, handoffFlag }: ChatNodeSeatProps) { + if (node.kind === 'user' && handoffFlag) return // business dispatch + return
{renderByKind(node)}
+}) +``` + +One feature's condition now decides how every node renders, and the shared seat must change again for the next feature. + +## The Markdown pipeline carries no business branch + +`AssistantMarkdown` and its rendering pipeline are infrastructure: no business condition enters the Markdown render path, and no business rewrites the node mapping or the style injection rules. A presentation need registers a renderer on the existing chain or expresses itself in the data, and the official default content participates in that same registration surface rather than existing as an optional renderer with a host-side inline fallback. A pipeline that hosts business special cases can no longer be reviewed or optimized on its own. + +- Judged condition: a business branch inside `AssistantMarkdown` or its block mapping — for example `if (isXxxBusiness) renderXxx()` — or a style injection rule keyed on one business. +- Correct outlet: a renderer registered on the existing chain, or a semantic field in the data that the generic renderer reads. The Component Factory registration is owned by the [ui-renderer README](../../packages/client/ui-renderer/README.md). +- Wrapping: a wrapper that needs the standard rendering calls the official entry and keeps its fallback; it never re-renders the slot and never imports the private React component across packages. +- Responsibility: the host owns position and invocation; the plugin owns its own state, cleanup, and controls, and the official host carries no business action for a contribution. +- `labels`: an optional complete `MarkdownLabels` object is used whole, with no field-level merge against the default; omitting it uses the official default. `variant="compact"` is fixed by the Factory. +- Boundary: generic Markdown capability — syntax support, performance — is not a business modification. +- Exception and approver: none by default; the corresponding domain expert confirms any exception. + +A contribution that registers into the existing single seat, and reuses the published Factory instead of re-rendering the standard content: + +```tsx +// The business contributes its own body into the seat the host already renders. +ctx.slots.inject('conversation.chat.reasoning.body', () => ctx.slots.register( + { name: 'conversation.chat.reasoning.body', scope: 'session', locale: NS }, + TranslatedReasoningBody, +)) + +// The contribution keeps the standard rendering by calling the published Factory. +function TranslatedReasoningBody({ text, running, renderFactorySlot, t }: ReasoningBodyProps) { + return ( + <> +

{t('reasoning.translated')}

+ {renderFactorySlot('conversation.chat.reasoning.content', { text, running })} + + ) +} +``` + +A business branch inside the shared Markdown pipeline: + +```tsx +export const AssistantMarkdown = memo(function AssistantMarkdown({ blocks, ...props }: AssistantMarkdownProps) { + return <>{blocks.map(block => ( + isHandoffBlock(block) + ? // a business special case in the pipeline + : renderBlock(block, props) + ))} +}) +``` + +Every business special case lands in one shared pipeline, and Markdown rendering can no longer change or be measured without the businesses it now carries. + +## The user message model and rendering carry no business field + +`UserMessage` and the UI's `user` kind rendering are infrastructure: no business-only field on the message model, and no business branch in the user message renderer. A business difference travels in the message payload — its own merge-extensible source kind or a content field — or through a registered renderer. A field added for one business is handled by every consumer of the model, and the next business adds another branch to the same shared renderer. + +- Judged condition: a business-named field on `UserMessage`, or a business condition in the rendering of the `user` kind. +- Correct outlet: expression in the payload. `MessageSourceMap` is declaration-merge extensible, so a producer declares its own source kind instead of widening `UserMessage`; the message model is documented in [session.md](../subsystems/session.md). +- Boundary: a generic message capability — attachments, quotes, edit state — is not a business modification. +- Exception and approver: none by default; the corresponding domain expert confirms any exception. + +A producer that declares its own source kind keeps the business difference in the payload: + +```ts ignore-check +declare module '@deepseek-ai/dsh-llm' { + interface MessageSourceMap { + handoff: { kind: 'handoff'; sessionId: SessionId } + } +} + +const message = createUserMessage({ + role: 'user', + content: [{ type: 'text', text: prompt }], + source: { kind: 'handoff', sessionId: source.id }, +}) +``` + +A business field on the shared model, and the branch it forces into the shared renderer: + +```ts ignore-check +interface UserMessage extends MessageBase { + readonly role: 'user' + readonly handoffKind?: 'handoff' | 'rag' // one business's field on the shared model +} + +// ...and the renderer branches on it. +if (message.handoffKind === 'handoff') return +``` + +Every consumer of the message model handles one business's field, and the shared renderer grows a branch for each business that follows. diff --git a/docs/defensive-patterns/conversation-and-session.zh.md b/docs/defensive-patterns/conversation-and-session.zh.md new file mode 100644 index 0000000000..855fdd876f --- /dev/null +++ b/docs/defensive-patterns/conversation-and-session.zh.md @@ -0,0 +1,316 @@ +# 会话与 Session 规则 + +[English](conversation-and-session.md) | 中文 + +关于读取 Session、持有 Session、计算会话节点与渲染它们的规则。数据模型与各类型语义见 [session-projection.zh.md](../subsystems/session-projection.zh.md) 与 [conversation.zh.md](../subsystems/conversation.zh.md)。 + +## Projection 是唯一的读取与计算路径 + +Session 数据一律经 Projection 读取与计算。客户端读投影值,而不是拉 Session 日志;属于该会话的计算以注册单元的形式运行并**推送**结果,而不是按需重算。同一个问题若有两个答案——一个拉取、一个推送——两者就会分叉,渲染可能显示出 Session 日志已不再支持的值。 + +- 判定条件:客户端渲染的每个 Session 派生值都在渲染位置经投影读取取得,每个新增的会话内计算都注册为单元、其结果以已发布值的形式到达客户端。组件自己拉取 Session 数据、或读者按需触发一次计算,都属违规。 +- State 与 View:单元折叠 host 侧 State,并在其上声明客户端可见的 View,二者分工写在注册里。`ProjectionDefinition` 的字段与驱动它们的注册表归 [session-projection.zh.md](../subsystems/session-projection.zh.md#ctxsessionprojections--sessionprojectionregistry)。 +- 版本:`stateVersion` 从 1 起,只要序列化 state 字段或折叠语义变化就自增,兼容与否都一样。存在兼容改法时优先兼容,但版本仍要自增;同一 key 以不同 `stateVersion` 注册两次会抛错,而不是合并。 +- 计算策略:单元默认全量计算。收窄某个单元的计算范围需要对应领域专家确认,绝不能由实现者自行决定。 +- 边界:非完全 projection 渲染可用于某些 key 的界面可用性展示,例如在连接中的 Session 应答之前先画缓存块。它绝不参与对外可见结果的判定,那些结果等标准 projection 值。 + +在渲染位置读取、并以注册代替拉取,两者都合规: + +```tsx +// The client reads the published value; it never fetches Session data itself. +function PlanChip({ useProjection }: PlanChipProps) { + const plan = useProjection('plan') + return plan === undefined ? null : +} + +// The computation is a registered unit; the registry drives it and publishes changes. +const planDefinition: ProjectionDefinition<'plan'> = { + key: 'plan', + stateVersion: 1, + init: () => emptyPlan, + apply: (state, event) => foldPlan(state, event), + wire: { viewSchema: planSchema, view: planView }, +} +``` + +自行发请求拉取同一个值,就破坏了唯一读面: + +```tsx +function PlanChip() { + const [plan, setPlan] = useState() + useEffect(() => { + void fetchSessionPlan(sessionId).then(setPlan) // a second read path beside Projection + }, [sessionId]) + return plan === undefined ? null : +} +``` + +拉取到的副本与推送值互相矛盾,版本检查也无法说明 Session 当前持有的是哪一个。 + +## 冷读是最后手段 + +可用的缓存要先于原始日志被读取;只有没有任何投影覆盖该数据时才走冷读。「小会话可以全读」这一例外已移除、不再考虑。当缓存与正式数据不完全对等时,缺失或过期要产出显式结果,而不是静默改走重路径。 + +- 判定条件:Session 读取先查 projection 缓存,行缺失时为调用方留下显式状态;缓存判断的 `else` 分支直接打开完整日志,即属违规。 +- 回退语义:缺失意味着什么由调用方决定,并写进返回值。不存在按缓存大小或 Session 大小开出的例外,也没有对应的批准人。 +- 边界:这条限制是前端的。host 侧「禁止 fork 冷读」的绝对化表述不成立,因为 host 可能需要打开前端打不开的日志。 + +先读已存储的投影行,缺失仍是一个由调用方渲染的状态: + +```ts ignore-check +// The listing reads stored projection rows; a miss remains an explicit state. +type ListingView = + | { kind: 'cached'; snapshot: ProjectionSnapshot } + | { kind: 'unknown' } + +function readListing(header: SessionHeader, keys: readonly ProjectionKey[]): ListingView { + const cached = ctx.sessionProjectionCache.cachedSnapshot(header, keys) + return cached === undefined ? { kind: 'unknown' } : { kind: 'cached', snapshot: cached } +} +// Opening the complete log is a separate operation the caller names, never this fallback. +``` + +缓存判断落回完整日志,就等于把慢路径变成常规路径: + +```ts ignore-check +function readListing(header: SessionHeader, session: Session): ListingView { + const cached = ctx.sessionProjectionCache.cachedSnapshot(header) + if (cached !== undefined) return { kind: 'cached', snapshot: cached } + return coldReadCompleteLog(session) // every miss pays the full-log read +} +``` + +现在每次缺失都在前台读完整日志,于是慢会话在每次列表读取时都慢,而不只是在那条主动请求它的路径上慢。 + +## 持有与回收遵循同一条生命周期判据 + +客户端经显式引用(`SessionReference`)持有 Session,引用计数归零即释放。闲置回收只看那一条生命周期判据——零引用且无在途——绝不按业务状态枚举「哪些 Session 可以回收」,因为那份清单要靠每个新增状态的业务功能自己去维护。隐式持有者不可见,回收便判断不了谁还在使用该 Session。 + +- 判定条件:判据 = `refCount == 0 && inflight == 0`。代码是否在「获取 → 使用」的时间窗口内通过一份可审计 retain / release 的引用来持有 Session?模块级 Session 对象或全局 current id 都属违规。 +- 边界:强制的是统一判据与不做业务状态枚举这两点;释放触发本身靠人工核对,因此仅凭人工核对不构成打回理由。 +- 归口:`retain`、`release`、`ready` 与 teardown 顺序归 [Session Controller 的 client references](../../packages/api/session-controller/README.zh.md#client-references)。消息里携带的 source session mention 是另一种类型,归 [session-reference.zh.md](../subsystems/session-reference.zh.md)。 + +经显式引用持有并在 teardown 释放的视图合规: + +```ts ignore-check +class SidebarSessionView implements Disposable { + private readonly reference: SessionReference + + constructor(readonly id: SessionId, sessions: ISessions) { + this.reference = sessions.retain(id, { source: 'sidebarView' }) + void this.reference.ready.catch((error: unknown) => { console.error('opening failed:', error) }) + } + + [Symbol.dispose](): void { + this.reference.release() // the last reference releases the Session + } +} +``` + +模块状态缓存 Session 对象,会把所有持有者对回收器隐藏: + +```ts ignore-check +let currentSessionId: SessionId | undefined +const sessionCache = new Map() + +export function remember(session: Session): void { + currentSessionId = session.id + sessionCache.set(session.id, session) +} + +export function reclaimIdle(): void { + if (state === 'idle' || state === 'closed') reclaim() // a newly added state is missed +} +``` + +没有人能数清谁仍在使用该 Session,下一个新增的 Session 状态也会漏出枚举、永远不被回收。 + +## 节点计算是增量的,流式发布是合批的 + +新增节点计算要说明其复杂度;高频流式 chunk 绝不立即发布、也不做全量计算。每个 chunk 全量重算并立即发布,等于把整个节点集合压进帧预算,转写区便会堵在流后面。追加速路径的开销——在 `D` 个已注册 Definition 下执行 `D` 次匹配与一次常量级 Context key 查找——以及发布节拍取值(`none`、`animation-frame`、`immediate`)归 [conversation.zh.md](../subsystems/conversation.zh.md#definition-and-typed-chat-payload)。 + +- 判定条件:单个 chunk 计算了多少——受影响子树的增量,而不是事件窗口——以及结果何时发布——合批策略,而不是每个 chunk 发布一次。 +- 边界:本条约束实现;节拍本身不构成打回理由,改动按它声明的节拍与所用的已发布路径评判。 +- 高频路径上禁止:`immediate` 发布,以及每个 chunk 做一次全量重算。 +- 边界:结构性或终态变化可以 `immediate` 发布,因为节拍是按单次发布选择的。只有高频 delta 路径受合批约束。 + +只更新一个 Context 并请求合批发布的 chunk 合规: + +```ts ignore-check +const assistantDefinition: ConversationNodeDefinition = { + kind: 'assistant-step', + target: 'chat', + match: event => matchAssistant(event), + start: (_context, match) => initialState(match), + update: (context, match) => appendChunk(context.state, match.event), // increment, not the window + publication: () => 'animation-frame', // high-frequency deltas coalesce; never immediate + buildViewNode: context => assistantNode(context), +} +``` + +每个 chunk 重建整个节点集合并立即发布: + +```ts ignore-check +function onChunk(chunk: AssistantLiveChunk): void { + const nodes = buildNodesFromCompleteWindow(session) // full recompute per chunk + target.publish(nodes, { publication: 'immediate' }) // and an immediate publish +} +``` + +每个 chunk 都要在帧预算内做一次全窗口重建,于是分组与渲染都堵在流后面。 + +## 节点构建与分组引擎不承载业务规则 + +业务规则绝不进入分组引擎,业务诉求也绝不改变构建产物的形态。`ProcessState`、分组产物层级,以及 `conversation-nodes/process-groups.ts` 里的分组语义集合都属基础设施:引擎只认枚举化的落位语义(如成组 / 独立 / 回复),由调用方算出该用哪一个。引擎内的业务特判会改变所有使用方共享的产物结构,并把业务条件带上分组计算路径。 + +- 判定条件:引擎内部是否存在业务条件?新增 `ProcessState` 字段、增删分组产物层级、为某个业务改变分组语义,都属违规;落位判定归算出枚举值的调用方。 +- 边界:架构分层、其开销与既有业务预期,就是业务不得重做分组设计的原因。 +- 边界:携带新落位含义的新枚举值才是受支持的扩展,无论调用方在哪里算出它。 +- 例外与批准人:无默认例外。改动该基础设施须经对应领域专家确认。分组 Definition 类型归 [conversation.zh.md](../subsystems/conversation.zh.md#group-definitions)。 + +调用方决定业务含义,并把引擎据以落位的枚举值传进去: + +```ts ignore-check +// Business judgment stays in the caller. +function placementOf(command: CommandView): NodePlacement { + return isHandoff(command) ? 'reply' : 'grouped' +} + +// The engine consumes the enum as data; it reads no business condition. +function groupEntries(commands: readonly CommandView[]): readonly NodePlacement[] { + return commands.map(placementOf) +} +``` + +业务条件写进引擎自己的计算过程: + +```ts ignore-check +// The grouping engine asks what a node means, not where it goes. +function placeProcessNode(node: ChatConversationViewNode): GroupPlacement { + if (node.kind === 'command' && isRagMessage(node)) return 'rag' // business special case + return 'grouped' +} +``` + +产物从此承载某一个业务的含义,所有使用方与分组计算都要跟着该功能走。 + +## 节点列表与席位组件不承载业务分支 + +`ChatNodeList`、`ChatNodeSeat` 与 `ChatGroupSeat` 属基础设施。它们不承载业务判断,也不承载业务专用字段;单一业务绝不改变列表遍历或席位选择。新的节点形态把自己的 kind 贡献给 `ChatNodeDataMap`,并经 kind 注册面注册 renderer,于是列表继续按 kind 分发,业务语义留在业务模块内。为某个功能加的分支,会让每个节点的渲染都依赖该功能。 + +- 判定条件:在列表或席位组件里加业务分支、给其 props 加业务专用字段,或为单一业务改变列表遍历与席位选择。 +- 正确出路:业务包把自己的 key merge 进 `ChatNodeDataMap`,并为该节点 kind 注册 renderer;席位渲染该 kind 已注册的组件。注册纪律归 [slots.zh.md](../subsystems/slots.zh.md#extension-rules)。 +- 边界:对所有业务生效的渲染增强——排序、虚拟化、可访问性——不属于为业务诉求修改。 +- 例外与批准人:无默认例外;任何例外须经对应领域专家确认。 + +声明自己的 kind 并注册 renderer 的业务包,不改动共享列表: + +```tsx +// The business declares its kind and registers its renderer; the shared list is untouched. +declare module '@deepseek-ai/dsh-client-ui-chat/client' { + interface ChatNodeDataMap { handoff: HandoffData } +} + +const HandoffNodeView = memo(function HandoffNodeView({ node, t }: ChatNodeOwnerProps<'handoff'>) { + return +}) + +ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( + { name: 'conversation.chat.node', key: 'handoff', locale: NS }, HandoffNodeView)) +``` + +把业务分支与业务字段写进共享席位: + +```tsx +export const ChatNodeSeat = memo(function ChatNodeSeat({ node, handoffFlag }: ChatNodeSeatProps) { + if (node.kind === 'user' && handoffFlag) return // business dispatch + return
{renderByKind(node)}
+}) +``` + +某个功能的条件从此决定每个节点怎么渲染,下一个功能还得再改一次共享席位。 + +## Markdown 管线不承载业务分支 + +`AssistantMarkdown` 及其渲染管线属基础设施:Markdown 渲染路径里不得出现业务条件,也不得按业务改写节点映射或样式注入规则。展示需求要么在既有链上注册 renderer,要么在数据里表达;官方默认内容也参与同一个注册面,而不是做成「可选 renderer + 宿主内联 fallback」。承载业务特判的管线,再也无法单独评审或单独优化。 + +- 判定条件:`AssistantMarkdown` 或其 block 映射里出现业务分支——例如 `if (isXxxBusiness) renderXxx()`——或按某个业务注入样式规则。 +- 正确出路:在既有链上注册 renderer,或在数据里带上语义字段、由通用 renderer 读取。Component Factory 的注册归 [ui-renderer README](../../packages/client/ui-renderer/README.zh.md)。 +- 包装展示:需要标准渲染的包装组件调用官方入口并保留其 fallback;绝不重复渲染 Slot,也绝不跨包导入官方私有 React 组件。 +- 权责边界:宿主只负责位置与调用;插件的状态、清理、控件归插件自己,官方宿主不为某个 contribution 承载业务动作。 +- `labels`:可选传入完整 `MarkdownLabels`,**传入即整体使用**、不与默认值做字段级合并;省略则用官方默认。`variant="compact"` 由 Factory 固定。 +- 边界:通用 Markdown 能力——语法支持、性能优化——不属于为业务诉求修改。 +- 例外与批准人:无默认例外;任何例外须经对应领域专家确认。 + +注册进既有单席位、并复用已发布 Factory(而不是自己重渲标准内容)的 contribution: + +```tsx +// The business contributes its own body into the seat the host already renders. +ctx.slots.inject('conversation.chat.reasoning.body', () => ctx.slots.register( + { name: 'conversation.chat.reasoning.body', scope: 'session', locale: NS }, + TranslatedReasoningBody, +)) + +// The contribution keeps the standard rendering by calling the published Factory. +function TranslatedReasoningBody({ text, running, renderFactorySlot, t }: ReasoningBodyProps) { + return ( + <> +

{t('reasoning.translated')}

+ {renderFactorySlot('conversation.chat.reasoning.content', { text, running })} + + ) +} +``` + +业务分支写进共享 Markdown 管线: + +```tsx +export const AssistantMarkdown = memo(function AssistantMarkdown({ blocks, ...props }: AssistantMarkdownProps) { + return <>{blocks.map(block => ( + isHandoffBlock(block) + ? // a business special case in the pipeline + : renderBlock(block, props) + ))} +}) +``` + +每个业务特判都落进同一条共享管线,Markdown 渲染再也无法脱离它如今承载的这些业务去改动或度量。 + +## 用户消息模型与渲染不承载业务字段 + +`UserMessage` 与 UI 侧 `user` kind 渲染属基础设施:消息模型上不得有业务专用字段,用户消息渲染里不得有业务分支。业务差异经消息 payload 传递——自己可 merge 扩展的 source kind 或某个 content 字段——或经注册的 renderer 表达。为某个业务加的字段,所有消息模型使用方都要处理;下一个业务还会往同一个共享 renderer 里再加一条分支。 + +- 判定条件:`UserMessage` 上出现业务命名字段,或 `user` kind 的渲染里出现业务条件。 +- 正确出路:在 payload 里表达。`MessageSourceMap` 可经 declaration merging 扩展,因此生产者声明自己的 source kind,而不是加宽 `UserMessage`;消息模型见 [session.zh.md](../subsystems/session.zh.md)。 +- 边界:通用消息能力——附件、引用、编辑态——不属于为业务诉求修改。 +- 例外与批准人:无默认例外;任何例外须经对应领域专家确认。 + +声明自己的 source kind 的生产者,把业务差异留在 payload 里: + +```ts ignore-check +declare module '@deepseek-ai/dsh-llm' { + interface MessageSourceMap { + handoff: { kind: 'handoff'; sessionId: SessionId } + } +} + +const message = createUserMessage({ + role: 'user', + content: [{ type: 'text', text: prompt }], + source: { kind: 'handoff', sessionId: source.id }, +}) +``` + +共享模型上的业务字段,以及它逼进共享 renderer 的分支: + +```ts ignore-check +interface UserMessage extends MessageBase { + readonly role: 'user' + readonly handoffKind?: 'handoff' | 'rag' // one business's field on the shared model +} + +// ...and the renderer branches on it. +if (message.handoffKind === 'handoff') return +``` + +消息模型的每个使用方都要处理某一个业务的字段,共享 renderer 则随每个后续业务再长一条分支。 diff --git a/docs/defensive-patterns/general.i18n.yaml b/docs/defensive-patterns/general.i18n.yaml new file mode 100644 index 0000000000..eccdc2015d --- /dev/null +++ b/docs/defensive-patterns/general.i18n.yaml @@ -0,0 +1,52 @@ +# Bilingual-pair consistency record for general.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/defensive-patterns/general.md +/defensive-patterns: + en: 324de84cf5239e89 + zh: b3bdfb17d01e5a6c +/defensive-patterns/report-orthogonal-outcomes-independently: + en: c16f636f8f522db4 + zh: 94c523b536df786d +/defensive-patterns/honor-public-contracts-on-both-sides: + en: 656746d485640b3a + zh: f75cd0333dc5bc9b +/defensive-patterns/async-state-is-not-synchronous-state: + en: f58b3f3fb047f434 + zh: daea224503617808 +/defensive-patterns/timing-does-not-carry-correctness: + en: 5778664b676a0079 + zh: e99aeabf0631f647 +/defensive-patterns/optional-inputs-state-both-behaviors: + en: 243e275fee74f54e + zh: a58e04b6e3ac0e7a +/defensive-patterns/one-value-states-one-fact: + en: 598d9041ccfaba7c + zh: 2ac9f98c97015f66 +/defensive-patterns/a-new-active-current-singleton-is-refused: + en: 8bf36acf96fa4c33 + zh: bb6db31a63bcf383 +/defensive-patterns/shared-state-has-one-owner: + en: 053e2c485eec2613 + zh: 2817da00572c789f +/defensive-patterns/a-business-capability-owns-itself: + en: 7588b8dba9279dac + zh: 2760468ede60220c +/defensive-patterns/changes-carry-performance-evidence: + en: 0d6855d1ae0ef4ae + zh: 0f771999398ce052 +/defensive-patterns/migrations-preserve-behavior: + en: 6213e051f51437b8 + zh: 853580b3a4fec100 +/defensive-patterns/dispose-must-reach-quiescence-not-just-request-it: + en: eeb9fe3158484618 + zh: 97187d4dbe4d75ee +/defensive-patterns/contain-callback-exceptions-in-the-dispatcher: + en: ae2332afa54cb253 + zh: db51fedb070d9a83 +/defensive-patterns/never-hand-untrusted-output-the-ambient-environment-or-predictable-paths: + en: 6fb7938f5197f520 + zh: 01eb670a852f24e6 +/defensive-patterns/unlink-link-shaped-paths: + en: 35944dc084b41ded + zh: 0e59beebd9fb6d22 diff --git a/docs/defensive-patterns/general.md b/docs/defensive-patterns/general.md new file mode 100644 index 0000000000..b1f0bba7b9 --- /dev/null +++ b/docs/defensive-patterns/general.md @@ -0,0 +1,222 @@ +# Defensive patterns + +English | [中文](general.zh.md) + +Hard-won bug-class rules: each pattern below is a class of defect that actually shipped or nearly shipped here, stated as the rule that prevents its recurrence. Read this before writing lifecycle, concurrency, subprocess, or teardown code. Test-tier counterparts (real entry path, world-verification, resource ownership) are in [testing.md](../testing.md); the type-level definitions these rules refer to live in [subsystems/](../subsystems/README.md). + +## Report orthogonal outcomes independently + +A result can be several things at once — a process can time out AND exit 0 because it trapped the signal. Surface each independent fact (`timedOut`, `signal`, `exitCode`) on its own; never nest one flag's report inside another's branch, or a caller reads a cut-short run as a clean success. + +A reviewer checks the reporting shape rather than the killing mechanism: can each fact be true independently, and is each one readable without entering another condition's branch? The boundary is the report — how the process is signalled or how long it is given is a separate decision. + +## Honor public contracts on BOTH sides + +When an implementation receives several representations of one outcome, normalize them before returning through the public API. `LlmAdapter.stream()` implementations may throw or emit `finish {kind:'error'|'aborted'}`, but `LlmRuntime.stream()` exposes model-request failures only as terminal finish chunks; middleware and consumer defects remain thrown. This keeps consumers from guessing whether a caught exception came from the provider, a wrapper, chunk logging, or their own assembly. Document the normalized contract where the type is defined; exercise every source form through the real consumer. + +The judged condition is whether a consumer can name the source of a failure from the public API alone. Internal helpers stay free to throw: the requirement binds the boundary the consumer crosses, not every function behind it. + +## Async state is not synchronous state + +`agent.followup()` has no per-message completion or result; a background job's completion races turn boundaries; `reader.close()` fires for both EOF and disposal. Never treat `agent/status` or `whenIdle()` as the result of one follow-up: several queued follow-ups, steering, and injected work may share one `running` interval, while cancellation or disposal can discard unstarted items. An automation caller that truly owns a run must define its interval explicitly—for example, from its message's durable inbox receipt through the next whole-agent `idle`—and describe any selected output as interval-wide rather than causally attributed to that message. The guard cuts both ways: if the awaited transition can never occur, the wait hangs, so handle the "nothing to wait for" branch explicitly. + +The judged condition is whether an agent can observe a per-unit completion the API does not define. Where the interval genuinely belongs to the caller, it is the caller that states the interval and the output scope; a shared `running` flag is never that statement. + +## Timing does not carry correctness + +Correctness comes from explicit call points and explicit state, never from where a callback lands in the event loop. A `microtask`, `setTimeout`, or `queueMicrotask` that decides whether work is correct races the rest of the program: it holds under a light load and silently fails under a busy one or when batching changes. React code follows the same rule — an effect never supplies a "just after render" ordering that the design should have made explicit. + +The judged condition is whether correctness depends on "that callback already ran" instead of on a named call point or state machine. Two boundaries: a test's timeout budget waits for a failure and is not timing-dependent correctness, and a deliberate delay that only paces user-visible work is not this rule. There is no developer-side exception; a genuine need for a timing technique goes to the domain owner. + +```ts +// The order is written into the code: dispose the old store, then build its successor. +declare let store: { dispose(): void } +declare function createStore(scopeKey: string): { dispose(): void } +declare const scopeKey: string + +store.dispose() +store = createStore(scopeKey) +``` + +```ts ignore-check +queueMicrotask(() => { if (!ready) refresh() }) // assumes the microtask runs before the next frame +setTimeout(() => setMounted(true), 0) // waits for a render that was never sequenced +``` + +The wrong form fails intermittently: a dropped refresh or a state that never syncs, reproducing only under load. + +## Optional inputs state both behaviors + +An optional parameter states what the callee does when it is present and when it is absent, so a caller reads both behaviors from the contract instead of inferring one from a defensive operator. Accumulating `?.` is the signal: each one substitutes for a decision about whether the field should exist at all. + +The judged condition is whether `?.` replaces a determination that a field exists rather than handling a genuinely optional hop on a known value. The requirement binds the interface contract: both branches state their return value and their side effects, and the contract is where the caller reads them. There is no exception channel — a call site that cannot state both behaviors is a review blocker, not a style preference. + +```ts +// Both behaviors are in the contract: no options object means "unknown", not "skip". +interface ResolveInput { options?: readonly string[] } +type Resolution = { kind: 'unknown' } | { kind: 'value'; value: string } + +function resolve(input: ResolveInput): Resolution { + if (input.options === undefined) return { kind: 'unknown' } + return { kind: 'value', value: input.options.join(',') } +} +``` + +```ts ignore-check +const value = a?.b?.c?.d ?? fallback // four layers of fallback hide whether d should exist +``` + +The wrong form keeps the contract vague and swallows the error, so the next caller adds another fallback on top. + +## One value states one fact + +An unknown value, an empty collection or string, and a genuinely absent field are three different facts and take three representations. One `undefined` or `null` never stands for several of them, and a consumer that must act differently on each discriminates explicitly instead of collapsing them at the boundary. + +The judged condition is whether a single "no value" carries more than one semantic: not yet queried, queried and empty, and cannot be determined. A discriminated union or an explicit enum value is the ordinary implementation, documented where the type is defined in [core.md](../subsystems/core.md#repo-wide-type-patterns). + +```ts +type ValueState = { kind: 'unknown' } | { kind: 'empty' } | { kind: 'value'; value: T } +``` + +```ts ignore-check +return null // means "not queried", "queried, nothing there", and "cannot tell", all at once +``` + +The wrong form leaves the caller unable to distinguish the cases, so UI states, cache policy, and retry decisions all go wrong. + +## A new active/current singleton is refused + +No new global `active` or `current` singleton is introduced, and existing ones are migrated out. A globally unique selection is a design statement this codebase does not make: several views of one piece of data each hold their own reference or key. + +The judged condition is whether the change introduces a globally unique selected-state field. The replacement shape is one piece of data with several views over it, each view carrying its own reference. There is no default exception; where the concept genuinely exists once per service, a service or instance field expressed through `inject` carries it, never a module-level field. + +```ts ignore-check +// Each view holds the key it renders; nothing global decides what is "current". +function ConversationView({ sessionKey }: { sessionKey: SessionKey }) { /* … */ } +``` + +```ts ignore-check +let activeTabId: TabId | undefined // module-level; every component reads the same one +``` + +The wrong form makes independent instances interfere with each other, and no reviewer can audit which view owns the focus. + +## Shared state has one owner + +Shared state hangs on a service or an instance, so its owner is a named object with a lifecycle. A module-level cache, a singleton, a global `WeakMap`, or a `Symbol.for` / `globalThis` / `window.__X__` bypass hides that owner and outlives every teardown. + +The judged condition: name the service or instance that owns the value; if no owner can be named, the owner is decided before the implementation. The boundary is that a field on a service or instance may be read by any number of injected consumers, and passing that value across domains goes through the existing interface rather than a global namespace. There is no default exception; a genuine need for a global lookup key goes to the domain owner together with its reclamation policy. + +```ts +// The shared value hangs on the session service instance; consumers inject it. +interface Sessions { readonly current: string } +declare const ctx: { get(name: 'sessions'): Sessions } + +const sessions = ctx.get('sessions') // one owner, lifetime tied to the service +``` + +```ts ignore-check +globalThis.__dshCache = new Map() // shared across instances, reclaimed never +``` + +The wrong form lets instances overwrite each other, makes reclamation timing unknowable, and leaks state between tests. + +## A business capability owns itself + +A business capability lives in its own package and attaches through a registration surface — a registry, `slots.inject`, a waterfall, or an event subscription. A runtime, controller, manager, or gateway carries generic orchestration: it may hold the registry structure and the disposal lifecycle, while the entries are written by the packages that own them, and it never hardcodes a central table of business rows. + +The judged condition is whether the capability declares and registers itself, with the center layer only forwarding and managing lifetime rather than making business decisions. The boundary is that the center layer holds the registry structure and the disposal lifecycle while the entries come from the owning packages. One exception: pure infrastructure — logging, transport, storage — does not attach through a business registration surface. A new branch in a center layer must explain why it cannot live in the owning package. + +```ts +// The business package registers its own slot and handlers in its apply. +interface Slots { + inject(name: string, register: () => void): void + register(name: string): void +} +interface Context { readonly slots: Slots } + +export function apply(ctx: Context): void { + ctx.slots.inject('conversation.footer', () => ctx.slots.register('conversation.footer')) +} +``` + +```ts ignore-check +if (pluginName === 'ui-attachment') { /* business branch inside the manager */ } +``` + +The wrong form makes every new capability edit the center layer, which becomes the change bottleneck and the conflict hotspot. + +## Changes carry performance evidence + +A change that can move the cost of a hot path measures the code it touched before and after and reports the numbers with their conditions. The three metrics are runtime, peak memory, and steady-state memory, measured in one environment on one input; the granularity is the changed path, not a whole-machine score. Reporting that "nothing got slower overall" is not evidence, and a path that improved elsewhere does not excuse a regression here — an optimised first paint still has to answer for `append`. + +The judged condition: under one environment and one input, any of the three metrics is significantly worse on the changed path. + +The baseline is the same path without the change under measurement — normally the native implementation that carries no measurement hook, not the previous implementation. Comparing old against new with the same hook attached on both sides dilutes the difference until it disappears: both sides pay the same overhead, so the measurement reports "no change" while both are slow. + +Measurement is owned by [benchmarks/](../../benchmarks/AGENTS.md), one directory per measured user path, and its scenarios are the entry point: + +```sh +# Run the owning scenario before and after the change; the numbers go into the PR. +pnpm run test:bench +``` + +Package-local diagnostics stay beside their owner with the `.perf.ts` suffix and do not join `test:bench`. The CI gate is `pnpm run check:ci:bench` (job `node 24 / benchmarks`), which publishes a scaled report — that gate is an alert, not a pass: a regression there is located by re-running the owning scenario and profiling segments locally to find which part slowed and which change introduced it. Retained-memory claims use `pnpm run test:bench:memory 4g|8g`, which reruns its listed files under an unchanged budget in a swapless cgroup. + +Boundaries: edits that touch no runtime path — comments, documentation, test-only code — need no measurement, and production performance code is not benchmark instrumentation to be deleted opportunistically (`performance.now()` and `scheduler.yield()` are part of production decode and encode chunk scheduling). An architectural change that genuinely costs performance states the measured cost and the reason, and the domain owner approves it; "the layering needed it" is not a self-service reason. Record the command, the numbers, the environment, and the input size so the baseline can be rebuilt. + +```text +CI benchmark reported green, so the change is accepted as performance-neutral. +``` + +That form ships a real regression in a path the benchmark does not model. + +## Migrations preserve behavior + +A migration or a package split keeps externally observable behavior equal: error codes, diagnostics, data-flow order, and UI timing are compared item by item. Moving code is preferred over deleting and rewriting it; a rewrite suits code whose semantics are changing anyway, and then the change lists its differences. A package or export-path change is a carrier change rather than a behavior change, and a behavior change is its own change. + +The judged condition is the item-by-item comparison of observable behavior before and after. Where full equality is impossible, the change states the differing items and how each is verified, and the domain owner approves. A defect found during a migration is fixed as its own change rather than folded into the move. + +```sh +# The move keeps paths and error codes; the reference updates are the whole diff. +git mv packages/old/src/endpoint.ts packages/new/src/endpoint.ts +``` + +```ts ignore-check +// The migration silently upgrades the error handling it was only supposed to move. +throw new EndpointError('not found') // was: return { ok: false, code: 'not_found' } +``` + +The wrong form buries behavior changes inside a move, so review cannot separate the relocation from the semantics and regressions cannot be localized. + +## Dispose must reach quiescence, not just request it + +A teardown that issues kills/aborts but returns before the work stops leaves orphans. Make cleanup async and await the children's exit (kill → await `done`), and close listener/notification registries BEFORE killing so late completions stay silent. + +The judged condition is whether teardown awaits actual quiescence or only requests it. The boundary is work with no owner to await — a detached, unobserved task — which the teardown is not obliged to track; anything the component started and can still observe must be awaited before it reports completion. + +## Contain callback exceptions in the dispatcher + +Catch and report each listener's exception without rejecting the dispatch promise or starving later listeners. The listener's owner must handle state it mutates under the [error-handling rules](../../.agents/skills/dsh-error-handling/SKILL.md#catch-recover-or-stop); catching alone does not restore state. + +The judged condition is whether a throwing listener can reject the dispatch promise or prevent later listeners from running. The boundary is the caller's own await: an error the dispatcher deliberately propagates to the operation that requested it is not a containment failure. + +```ts +async function dispatch(listeners: ((event: string) => Promise)[], event: string): Promise { + for (const listener of listeners) { + try { await listener(event) } catch (error) { console.warn('listener failed', error) } + } +} +``` + +## Never hand untrusted output the ambient environment or predictable paths + +Spawned commands get a scrubbed env (drop `*KEY*`/`*SECRET*`/`*TOKEN*`/`*PASSWORD*`) so harness credentials cannot leak into output, `env`, or spill files. Temp/spill files use a private (0700) dir, random names, and exclusive owner-only opens (`'wx'`, `0o600`) — predictable world-readable paths invite symlink races and disclosure. + +The judged condition is whether spawned processes inherit the ambient environment or write somewhere another process can predict and replace. The boundary is trusted, in-process code with no external input, which the rule does not govern. + +## Unlink link-shaped paths + +A path that may be a symlink or Windows junction is removed with `lstatSync().isSymbolicLink()` then `unlinkSync`: unlink deletes only the link and refuses a real directory, so it never follows the link into its target. Windows `rmSync(link)` throws `ERR_FS_EISDIR` on a junction; recursive deletion may descend through one into its target. Reserve recursive `rmSync` for known real directories. + +The judged condition is whether the removal primitive can follow a link into its target. The boundary is a path the code created itself in a directory it owns, where a plain recursive removal is already known to be safe. diff --git a/docs/defensive-patterns/general.zh.md b/docs/defensive-patterns/general.zh.md new file mode 100644 index 0000000000..3aa2b55038 --- /dev/null +++ b/docs/defensive-patterns/general.zh.md @@ -0,0 +1,252 @@ +# 防御性模式 + +[English](general.md) | 中文 + +来之不易的缺陷类别规则:下面每条模式都是本项目实际发布或差点发布的一类缺陷,以防止其复发的规则形式陈述。在编写生命周期、并发、子进程或清理代码之前请先阅读本文。测试层面的对应规则(真实入口路径、验证实际结果、资源归属)见 [testing.zh.md](../testing.zh.md);这些规则引用的类型定义正家见 [subsystems/](../subsystems/README.zh.md)。 + + + +## 正交结果独立上报 + +一个结果可以同时具有多种性质:进程可能已经超时,却仍以退出码 0 结束,因为它捕获了终止信号。每个独立事实(`timedOut`、`signal`、`exitCode`)都应单独上报;切勿把一个标志的上报嵌套在另一个标志的分支中,否则调用方可能把提前终止的运行误判为正常成功。 + +评审看的是**上报形态**而不是终止机制:每个事实能否独立为真,以及能否不进入另一个条件分支就读到它?边界就是这个上报本身——如何发信号、给多长时间是另一个决定。 + + + +## 公共约定两侧都要遵守 + +当一个实现收到同一结果的多种表示时,应在通过公共 API 返回前将其规范化。`LlmAdapter.stream()` 的实现可以抛出异常或发出 `finish {kind:'error'|'aborted'}`,但 `LlmRuntime.stream()` 只会通过终止型 finish 分片暴露模型请求失败;middleware 缺陷与消费方缺陷仍会以异常形式抛出。这使消费方不必猜测捕获的异常究竟来自提供方、包装层、分片日志记录还是自身组装逻辑。请在类型定义处记录规范化后的约定;通过真实消费方覆盖每种来源形式。 + +判定条件是:消费方能否仅凭公共 API 说出故障的来源。内部 helper 仍可自由抛错:这条要求约束的是消费方跨越的那个边界,而不是它背后的每个函数。 + + + +## 异步状态不是同步状态 + +`agent.followup()` 没有逐消息的完成状态或结果;后台任务的完成与轮次边界存在竞争;`reader.close()` 在 EOF 和 dispose(资源释放)两种情况下都会触发。切勿把 `agent/status` 或 `whenIdle()` 当作某次 `followup()` 的结果:多条已排队的后续消息、steering(中途引导)和注入工作可能共用同一个 `running` 区间,而取消或资源释放可能丢弃尚未启动的项。真正拥有一次运行的自动化调用方必须显式定义其区间——例如从消息的持久 inbox 回执到整个 agent(智能体)下一次进入 `idle`——并将选取的任何输出描述为整个区间的输出,而不是把因果关系归于该消息。这条守则是双向的:如果等待的转换永远不会发生,等待就会挂起,因此应显式处理「无需等待」的分支。 + +判定条件是:调用方是否观察到一个 API 并未定义的逐单元完成态。区间确实属于调用方时,就由调用方声明区间与输出范围;共享的 `running` 标志永远不是这份声明。 + + + +## 时序不承载正确性 + +正确性来自显式调用点与显式状态,而不是回调落在事件循环的哪个位置。用 `microtask`、`setTimeout` 或 `queueMicrotask` 决定某项工作是否正确,是在与程序其余部分竞争:轻负载下成立,重负载或合批行为一变就静默失效。React 代码同理——effect 绝不提供那种本应由设计显式给出的「渲染之后」次序。 + +判定条件是:正确性是否依赖「那个回调已经跑过」,而不是具名调用点或状态机。两条边界:测试的 timeout 预算是在等失败,不属于靠时序保正确性;纯粹为可见工作 pacing 的延迟也不属本条。开发者一侧没有例外通道,确需时序技巧须经对应领域专家确认。 + +```ts +// The order is written into the code: dispose the old store, then build its successor. +declare let store: { dispose(): void } +declare function createStore(scopeKey: string): { dispose(): void } +declare const scopeKey: string + +store.dispose() +store = createStore(scopeKey) +``` + +```ts ignore-check +queueMicrotask(() => { if (!ready) refresh() }) // assumes the microtask runs before the next frame +setTimeout(() => setMounted(true), 0) // waits for a render that was never sequenced +``` + +反例的失效是间歇性的:偶发丢刷新,或状态永远没同步,只在压力大时复现。 + + + +## 可选输入要写明两种行为 + +可选参数要写明被调用方在**传入**与**不传入**两种情况下各自的行为,调用方从契约里读到两种行为,而不是靠防御性运算符去猜其中一种。堆积 `?.` 就是这个信号:每一个都在替代「这个字段到底应不应该存在」的判断。 + +判定条件是:`?.` 是否被用来替代「该字段存在」的判定,而不是在处理一个已知值上真正可选的一跳。这条要求约束接口契约:两个分支都要写明返回值与副作用,并由调用方从契约处读到。没有例外通道——无法说清两种行为的调用点属于评审打回项,不是风格偏好。 + +```ts +// Both behaviors are in the contract: no options object means "unknown", not "skip". +interface ResolveInput { options?: readonly string[] } +type Resolution = { kind: 'unknown' } | { kind: 'value'; value: string } + +function resolve(input: ResolveInput): Resolution { + if (input.options === undefined) return { kind: 'unknown' } + return { kind: 'value', value: input.options.join(',') } +} +``` + +```ts ignore-check +const value = a?.b?.c?.d ?? fallback // four layers of fallback hide whether d should exist +``` + +反例让契约持续含糊、错误被静默吞掉,于是下一个调用方又叠一层兜底。 + + + +## 一个值只表达一个事实 + +未知值、空集合或空字符串、以及字段真的不存在,是三件不同的事实,用三种不同的表示。一个 `undefined` 或 `null` 绝不代表其中多个;需要在三者上分别处理的消费方显式判别,而不是在边界处把它们压平。 + +判定条件是:同一个「无值」是否承载了多种语义——**未查询**、**查到为空**、**无法判定**。通常的实现是可辨识联合或显式枚举值,并在类型定义处记录(见 [core.zh.md](../subsystems/core.zh.md#repo-wide-type-patterns))。 + +```ts +type ValueState = { kind: 'unknown' } | { kind: 'empty' } | { kind: 'value'; value: T } +``` + +```ts ignore-check +return null // means "not queried", "queried, nothing there", and "cannot tell", all at once +``` + +反例让调用方无法区分这些情况,UI 状态、缓存策略与重试判断都会跟着做错。 + + + +## 新增 active/current 单例一律禁止 + +不得新增全局的 `active` 或 `current` 单例,存量逐步迁出。全局唯一选中态是本仓库不做出的设计声明:同一份数据的多个视图各自持有自己的引用或键。 + +判定条件是:该改动是否引入了全局唯一的选中态字段。替代形态是**一份数据、多份视图**,每个视图带自己的引用。没有默认例外;确实每个服务只有一份的概念由服务或实例的字段承载并经 `inject` 取得,绝不落成模块级字段。 + +```ts ignore-check +// Each view holds the key it renders; nothing global decides what is "current". +function ConversationView({ sessionKey }: { sessionKey: SessionKey }) { /* … */ } +``` + +```ts ignore-check +let activeTabId: TabId | undefined // module-level; every component reads the same one +``` + +反例让彼此独立的实例互相串台,也没有人能审计焦点与状态归谁。 + + + +## 共享状态只有一个所有者 + +共享状态挂在服务或实例上,因此它的所有者是一个有生命周期的具名对象。模块级缓存、单例、全局 `WeakMap`,以及 `Symbol.for` / `globalThis` / `window.__X__` 旁路都会把这个所有者藏起来,并活得比任何一次清理都久。 + +判定条件:说出拥有该值的服务或实例;说不出所有者时,先定所有者再实现。边界是:服务或实例上的字段可以被任意多个注入方读取,跨域传递走既有接口而不是全局命名空间。没有默认例外;确需全局检索键时须经对应领域专家确认,并一并给出回收策略。 + +```ts +// The shared value hangs on the session service instance; consumers inject it. +interface Sessions { readonly current: string } +declare const ctx: { get(name: 'sessions'): Sessions } + +const sessions = ctx.get('sessions') // one owner, lifetime tied to the service +``` + +```ts ignore-check +globalThis.__dshCache = new Map() // shared across instances, reclaimed never +``` + +反例让实例之间互相覆盖、回收时机不可控,并让状态在测试之间泄漏。 + + + +## 业务能力自己拥有自己 + +业务能力住在自己的包里,经注册面接入——registry、`slots.inject`、waterfall 或事件订阅。runtime、controller、manager、gateway 承载通用编排:它可以持有注册表结构与 disposal 生命周期,但条目由拥有它们的包写入,且绝不硬编码一张业务中心表。 + +判定条件是:该能力是否由业务包自己声明并注册,中心层只做转发与生命周期管理、不做业务判定。边界是:中心层持有注册表结构与 disposal 生命周期,条目来自拥有它们的包。一条例外:纯基础设施能力——日志、传输、存储——不经业务注册面接入。中心层新增分支必须说明它为何无法下沉到业务包。 + +```ts +// The business package registers its own slot and handlers in its apply. +interface Slots { + inject(name: string, register: () => void): void + register(name: string): void +} +interface Context { readonly slots: Slots } + +export function apply(ctx: Context): void { + ctx.slots.inject('conversation.footer', () => ctx.slots.register('conversation.footer')) +} +``` + +```ts ignore-check +if (pluginName === 'ui-attachment') { /* business branch inside the manager */ } +``` + +反例让每个新能力都要改中心层,中心层随即成为变更瓶颈与冲突热点。 + + + +## 改动要附带性能证据 + +可能改变热点路径成本的改动,要测量它所触及的代码在改动前后的表现,并把数字与测量条件一并给出。三项指标是运行耗时、内存峰值与稳态内存,在同一环境、同一输入下测量;粒度是**被改动的那条路径**,不是整机跑分。只报「整体没变慢」不算证据,别处变快也不能抵消这里的倒退——优化了首屏,仍然要回答 `append` 是否倒退。 + +判定条件:同一环境、同一输入下,改动后那条路径的三项指标中任一项显著变差。 + +基线是被测路径**不带本次改动**的形态——通常是不挂测量 hook 的原生实现,而不是旧实现。新旧两侧挂着同一个 hook、共同开销把真实差值稀释掉,测量就会报告「没变化」,而实际上两边一起慢。 + +测量的正家是 [benchmarks/](../../benchmarks/AGENTS.md),按被测用户路径分目录,它的场景就是入口: + +```sh +# Run the owning scenario before and after the change; the numbers go into the PR. +pnpm run test:bench +``` + +包内诊断留在包旁边、用 `.perf.ts` 后缀,不进 `test:bench`。CI 门禁是 `pnpm run check:ci:bench`(作业 `node 24 / benchmarks`),产出 scaled report——该门禁只是**报警**,不是通过依据:出现退化时重跑对应场景并本地分段 profile,定位是哪一段变慢、哪次变更引入。内存留存类结论用 `pnpm run test:bench:memory 4g|8g`,它会在无 swap 的 cgroup 里以不变预算重跑其列出的文件。 + +边界:不触碰运行路径的改动——注释、文档、仅测试代码——不需要测量;生产性能代码不是可以顺手删掉的 benchmark instrumentation(`performance.now()`、`scheduler.yield()` 属于生产 decode/encode 分片调度的一部分)。架构调整确实要付出性能代价时,写明实测代价与理由,并由对应领域专家确认;「分层需要」不是自助理由。命令、数字、环境与输入规模都要落账,以便返工时重建同一基线。 + +```text +CI benchmark reported green, so the change is accepted as performance-neutral. +``` + +这种写法会把 benchmark 未建模路径上的真实退化直接放行。 + + + +## 迁移保持行为 + +迁移或拆包保持对外可观测行为全等:错误码、诊断信息、数据流顺序与 UI 时机逐项比对。优先搬运代码而不是删了重写;重写适用于本来就要改语义的代码,且此时要在改动里列出差异。包或导出路径变化属于载体变化而非行为变化,行为变化则是独立的一刀。 + +判定条件是改动前后可观测行为的逐项比对。无法做到完全全等时,改动要写明差异项与各自的验收方式,并由对应领域专家确认。迁移过程中发现的缺陷按其自身另开一刀,不并入这次搬运。 + +```sh +# The move keeps paths and error codes; the reference updates are the whole diff. +git mv packages/old/src/endpoint.ts packages/new/src/endpoint.ts +``` + +```ts ignore-check +// The migration silently upgrades the error handling it was only supposed to move. +throw new EndpointError('not found') // was: return { ok: false, code: 'not_found' } +``` + +反例把行为变化埋进搬运里,评审无法把位置移动与语义变化分开,回归也就无法定位。 + + + +## dispose 必须达到完全停稳,而不仅仅是请求停止 + +如果清理流程只发出终止或中止信号便返回,而不等待工作真正停止,就会留下孤儿进程。清理逻辑应采用异步流程,并等待子进程退出(发出终止信号后等待 `done`);还应在终止进程前关闭监听器注册表和通知注册表,使迟到的完成事件保持静默。 + +判定条件是清理是否等待到真正停稳,而不只是发出请求。边界是没有可等待归属的工作——无人观察的游离任务——清理逻辑没有义务追踪它;但组件自己启动、且仍能观察到的工作,必须在它报告完成之前等待完毕。 + + + +## 在分发器中隔离回调异常 + +逐个捕获并报告监听器的异常,不让分发 promise 被 reject,也不让后续监听器失去执行机会。监听器的所有者必须按[错误处理规范](../../.agents/skills/dsh-error-handling/SKILL.md#catch-recover-or-stop)处置其修改的状态;仅捕获异常不会恢复状态。 + +判定条件是:抛异常的监听器是否能让分发 promise 被 reject,或让其后的监听器不再运行。边界是调用方自己的 await——分发器有意抛给发起该操作的那条路径的错误,不属于隔离失败。 + +```ts +async function dispatch(listeners: ((event: string) => Promise)[], event: string): Promise { + for (const listener of listeners) { + try { await listener(event) } catch (error) { console.warn('listener failed', error) } + } +} +``` + + + +## 绝不将环境变量或可预测路径暴露给不可信输出 + +启动的命令应使用经过清理的环境变量,移除名称匹配 `*KEY*`、`*SECRET*`、`*TOKEN*` 或 `*PASSWORD*` 的项,防止 harness 凭证通过命令输出、`env` 或 spill 文件泄漏。临时文件和 spill 文件应放在权限为 0700 的私有目录中,使用随机文件名,并以独占且仅所有者可访问的方式打开(`'wx'`、`0o600`);可预测且全局可读的路径会引发符号链接竞态和信息泄露。 + +判定条件是:启动的进程是否继承环境变量,或是否写入别人可以预测并替换的位置。边界是不接受外部输入的受信进程内代码,本条不约束它。 + + + +## 用 unlink 删除链接形态的路径 + +可能是符号链接或 Windows junction 的路径,应先用 `lstatSync().isSymbolicLink()` 判断,再用 `unlinkSync` 删除:unlink 只删除链接本身并拒绝真实目录,因此绝不会跟随链接进入其目标。Windows 上对 junction 调用 `rmSync(link)` 会抛 `ERR_FS_EISDIR`;递归删除可能穿过 junction 进入其目标。真实目录才使用带 `recursive` 的 `rmSync`。 + +判定条件是:所用的删除原语是否可能跟随链接进入其目标。边界是代码在自己拥有的目录里自行创建的路径,那里已知普通递归删除是安全的。 diff --git a/docs/defensive-patterns/package-surface.i18n.yaml b/docs/defensive-patterns/package-surface.i18n.yaml new file mode 100644 index 0000000000..6d1bd9ae33 --- /dev/null +++ b/docs/defensive-patterns/package-surface.i18n.yaml @@ -0,0 +1,25 @@ +# Bilingual-pair consistency record for package-surface.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/defensive-patterns/package-surface.md +/package-surface-rules: + en: 28d4c2d7da24269f + zh: d723b807815401d7 +/package-surface-rules/a-plugin-package-exports-what-the-loader-loads: + en: 44a06f50e751f06b + zh: 339dea7be403fd0b +/package-surface-rules/two-package-shapes-and-both-are-dynamic-plugin-packages: + en: bf79c6acf35c90a5 + zh: 9f2ce6c7f6493b17 +/package-surface-rules/package-json-exports-uses-the-standard-key-set: + en: 3604bf435be1c430 + zh: 169621c8a0c2dc4c +/package-surface-rules/dependency-declarations-and-version-consistency-are-enforced-by-the-dependency-scan: + en: e68bfcde70f845b4 + zh: 73e5c4fb067c4fa1 +/package-surface-rules/internal-dependency-syntax-follows-the-package-family: + en: d6bb855545b7b05b + zh: 6c489ed5a2ed0ae5 +/package-surface-rules/a-new-resolve-hook-is-refused-outright: + en: b420ae3e228432d5 + zh: 0c49c4a9c3a5262c diff --git a/docs/defensive-patterns/package-surface.md b/docs/defensive-patterns/package-surface.md new file mode 100644 index 0000000000..9a4b772b1e --- /dev/null +++ b/docs/defensive-patterns/package-surface.md @@ -0,0 +1,224 @@ +# Package surface rules + +English | [中文](package-surface.zh.md) + +Rules for what a package exports, how it is built, and how it declares dependencies. [development.md](../development.md#typescript-project-layout) describes the layout itself; [packages/AGENTS.md](../../packages/AGENTS.md) carries the standing orders. + +## A plugin package exports what the Loader loads + +A plugin package's entry point takes one of two forms, and they are not mixed. A **function plugin** named-exports `name`, `inject`, `Config`, and `apply`: `name`, `inject`, and `apply` are lower-case, while `Config` is upper-case and appears both as an `interface` and as its Schemastery schema value. A **service plugin** default-exports its service class, which is how the Loader loads it; a default export beside the four makes the Loader discard the function plugin's namespace. Beyond those, a Host entry may export the Service Definition classes and error types that other packages extend or throw — the capability seam consumes exactly those — and never a test-convenience value. The `/client` entry of a UI plugin package is stricter, and [packages/client/AGENTS.md](../../packages/client/AGENTS.md) owns that discipline: a same-package test reaches internals through a relative `../src/...` path or the `./src/*` subpath, so a test-only need never becomes a permanent export. The rule stops a test convenience from freezing into published API. + +- The Loader four and its exact form are defined in [cordis-primer.md](../cordis-primer.md#loader-configuration). +- Judged condition: a function plugin's entry (`src/index.ts`) exports an entity beyond the four; a default export is added beside the four, or the two forms are mixed; a `/client` entry exports an implementation value or lets another feature plugin import one; a fixture reaches another package by relative path. +- Boundary: only Loader plugin entry points are constrained. Internal modules, helper functions, and hooks keep exporting values; a Host entry's Service Definition classes and error types are expected exports; and a test fixture stays inside its own package — a relative path into another package's `src` bypasses the `exports` map and the package-boundary checks. +- Exception: none by default; an exception that is genuinely needed requires the domain owner's confirmation. + +The compliant entry — the four exports, with the same-package test path recorded as a comment rather than as a fifth export. + +```ts +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' + +// The plugin entry: the Loader four, and no fifth value +export const name = 'web-app' +export const inject = ['webServer'] +export interface Config { /* … */ } +export const Config = z.object({ /* … */ }) +export function apply(ctx: Context, config: Config): void { /* … */ } + +// A same-package test imports '../src/internal/header.ts' instead of this entry +``` + +Three ways the entry gains an export it must not have; all three are visible in the diff. + +```ts ignore-check +// The entry widened so a test could reach one helper +export { isHeaderLine } from './internal/header.ts' + +// Both plugin forms on one entry: the Loader discards the four +export default class WebApp {} + +// A fixture reaching into another package by relative path +import { isSurfaceEligibleType } from '../../core/session/src/surface.ts' +``` + +## Two package shapes, and both are dynamic plugin packages + +A new package is either a Host package or a Host + Client package, and both are dynamic plugin packages; no third form is available and there is no exception. The static client libraries the shell seeds through `PLATFORM_MODULES` in [packages/client/web/src/platform.ts](../../packages/client/web/src/platform.ts) — `client-store`, `ui-slots`, `ui-primitives`, `ui-dockkit` — and the zero-dependency libraries under [packages/util/](../../packages/util/) predate this rule and are closed: they keep working as they are, and a new package never joins them. Only a genuine both-face package splits its compiler faces, build output goes to `lib`, and the `include`, `external`, and roster lists are derived by scanning the workspace rather than hand-written. A hand-written list or an invented compiler face makes build output and the manifest disagree, and every later package would have to maintain its own list. + +- Judged condition: a new package built as anything but a dynamic plugin package (static-link bundling, a hand-written all-external list); a third `tsconfig` variant; a hand-written `include`, `external`, or roster list. +- Recompute the shapes instead of trusting a number here: list the `tsconfig.json` files under `packages/*/*`, then the packages that also carry `tsconfig.client.json` and `tsconfig.host.json`, then those declaring `dsh.client`. +- Boundary: a both-face package may appear in `include` or `exclude`. +- Exception: none; there is no approval path. A change to a package's shape or compiler faces starts with the owning documents and needs the domain owner's confirmation. +- Owners: [development.md](../development.md#typescript-project-layout) for the compiler faces, [packages/README.md](../../packages/README.md) for the package groups, and [adding-a-package.md](../cookbook/adding-a-package.md) for the steps. + +A package in one of the two shapes, with the standard manifest fields and no hand-written external list. + +```json +{ + "name": "@deepseek-ai/dsh-example", + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" } + } +} +``` + +A hand-written `external` list — and a `tsconfig.foo.json` invented beside it for one package — leaves the scans nothing to derive, so build output and manifest stop agreeing. + +```json +{ "name": "@deepseek-ai/dsh-example", "external": ["@deepseek-ai/*"] } +``` + +## `package.json` `exports` uses the standard key set + +A `package.json` `exports` map uses only the standard key set, in which every key already has one meaning across the repository, and a package never opens a key for its own local purpose. A key that only a handful of packages use without a documenting owner is not a precedent: formalizing a key, including one of the undocumented keys below, means changing the owning document and the check in the same change. The small shared key set is what lets a consumer infer a key's purpose from its name and lets a scan judge the export map at all. + +- Standard keys, each with one meaning repo-wide, across `packages/*/*/package.json` and `apps/*/package.json`: `.` (the package entry), `./package.json` (toolchain access, not a semantic export), `./src/*` (source passthrough for tests and tools, whose documented status is still open), `./client` (the browser entry, paired with the `dsh.client` declaration), `./types` (the type entry), `./typert` (the typert type runtime), `./remote` (the `@Remote` call surface), `./locale/*.json` (locale resources), `./cordis.patch.yml` (the bundle patch layer declared by `dsh.bundle`). Counts are not listed here because they rot on the next package; the recompute command below prints them. +- Keys outside that set (`./brand` in 5 packages, `./worker` in 4, `./startup`, `./runner`, and `./protocol` in 2 each, plus many one-off keys) have no documented meaning; they are pending review, not a pattern to copy. +- Judged condition: does a change add an export key outside the standard set? +- Exception: none by default; a new key changes the owning document and the check first, with the domain owner's confirmation. +- Recompute the distribution: + +```sh +python3 -c "import json,glob,collections; c=collections.Counter(); [c.update(json.load(open(p)).get('exports',{}).keys()) for p in glob.glob('packages/*/*/package.json')+glob.glob('apps/*/package.json') if isinstance(json.load(open(p)).get('exports'),dict)]; print(c.most_common())" +``` + +The compliant map — three standard keys used with their repo-wide meanings, in a package that also declares its client entry. + +```json +{ + "exports": { + ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./client": { "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }, + "./types": { "types": "./lib/types/types.d.ts", "default": "./lib/types/types.js" }, + "./src/*": "./src/*", + "./package.json": "./package.json" + } +} +``` + +Keys opened for one package's local purposes — here `./brand` and `./worker`, whose documented status is pending — turn the export map into a per-package convention that neither a consumer nor a scan can read. + +```json +{ + "exports": { + ".": "./lib/index.js", + "./brand": "./lib/brand.js", + "./worker": "./lib/worker.js" + } +} +``` + +## Dependency declarations and version consistency are enforced by the dependency scan + +Dependency declarations and version consistency are guaranteed mechanically by the dependency scan; this page repeats neither the `devDependencies` and `peerDependencies` field rules nor a package admission list of its own. When the scan fails, reproduce it locally and fix the manifest it names, because the scan and its policy file own the rules. Editing the scan or relaxing its policy so that a change can land is not a normal edit and needs the domain owner's confirmation. + +- Entry point: [verify-package-dependencies.ts](../../scripts/verify-package-dependencies.ts), run as `pnpm run verify-package-dependencies`, by `scripts/run-gates.ts` as the `package-dependencies` gate, and directly by `.github/workflows/release.yml`. +- Policy owner: [package-dependency-policy.ts](../../scripts/package-dependency-policy.ts) exports `PACKAGE_DEPENDENCY_POLICY`; the declaration sections, version forms, and exemptions are defined there, with package-level context in [packages/README.md](../../packages/README.md). +- Boundary: this page lists no packages, field rules, or thresholds; it points at the owning file instead. +- Find the wiring: `grep -rn "verify-package-dependencies" package.json .github/workflows scripts/run-gates.ts`. +- Exception: a change to the scan or to the policy requires the domain owner's confirmation and the reason recorded on the change. + +The repeatable procedure: reproduce, read the diagnostic, and fix the manifest it names. + +```sh +# 1. Reproduce what CI reports +pnpm run verify-package-dependencies + +# 2. The diagnostic names the manifest, the section, the dependency, and the expected range +# packages/example/package.json: dependencies.@deepseek-ai/dsh-base must use workspace:*, found workspace:~ + +# 3. The fix goes into the manifest, never into the policy file or the scan +# "dependencies": { "@deepseek-ai/dsh-base": "workspace:*" } + +# 4. Re-run the scan until every package matches the published policy +pnpm run verify-package-dependencies +``` + +Two ways to lose the mechanical guarantee: change the check instead of the manifest, or restate the rule here so that it drifts from its owner. + +```text +Relaxing PACKAGE_DEPENDENCY_POLICY, or dropping the scanned section that fails, to go green +Restating a required-devDependency package list or the field rules on this page instead of linking the policy file +``` + +## Internal dependency syntax follows the package family + +Internal dependency syntax follows the package family: `@deepseek-ai/dsh` and `@deepseek-ai/dsh-*` use `workspace:*`, every other internal package uses `workspace:~`, and `workspace:^` has retired. The same dependency name is written the same way in every workspace, and a mismatch is a hard scan failure rather than a warning a reviewer can waive. The uniform syntax keeps one resolution path and prevents duplicate instances of a dependency and the resolution differences that follow them. + +- Judged by `workspaceRange()` in [verify-package-dependencies.ts](../../scripts/verify-package-dependencies.ts): the `@deepseek-ai/dsh` and `@deepseek-ai/dsh-*` families get `workspace:*`, every other internal package gets `workspace:~`; the scan walks the managed manifests and compares every declaration of the same dependency name. +- Boundary: a same-namespace package that is not a workspace member declares an ordinary third-party range and is outside the family rule — `@deepseek-ai/libreoffice-kit` is declared `^0.1.5` in `apps/desktop-host/package.json` (dependencies), `packages/bundle/web-app/package.json` (devDependencies), `packages/document/office-to-pdf/package.json` (dependencies), and `packages/skill/skill-office/package.json` (dependencies). +- Distribution is not restated here; the recompute command below prints the current counts of `workspace:*`, `workspace:~`, `workspace:^`, and any exact-range declaration outside the family rule. +- Exception: the scan decides mechanically; a genuine exception means changing the scan and the policy file with the domain owner's confirmation and the reason on the change. +- Recompute: + +```sh +python3 -c "import json,glob,collections; c=collections.Counter(); [c.update([r]) for p in glob.glob('apps/*/package.json')+glob.glob('packages/*/*/package.json')+glob.glob('vendor/*/package.json') for s in ('dependencies','devDependencies','optionalDependencies','peerDependencies') for n,r in (json.load(open(p)).get(s) or {}).items() if n.startswith('@deepseek-ai/')]; print(c.most_common())" +``` + +Each family in its form, with the non-member exception left as an ordinary version range. + +```json +{ + "dependencies": { + "@deepseek-ai/dsh-base": "workspace:*", + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/libreoffice-kit": "^0.1.5" + }, + "devDependencies": { + "@deepseek-ai/dsh-typert-registry": "workspace:*" + } +} +``` + +A `dsh-*` package on `workspace:~` and a workspace member pinned to an external range — each is a hard scan failure, and the retired rule of pinning exact versions is not available as an alternative. + +```json +{ + "dependencies": { + "@deepseek-ai/dsh-base": "workspace:~", + "@deepseek-ai/cordis": "^4.0.0" + } +} +``` + +## A new resolve hook is refused outright + +A new `resolve` hook is refused by default — a definite prohibition, not a preference to avoid one. A genuine need has two preconditions together: re-auditing the resolve strategy as a whole rather than patching the specifier that motivated the change, and the domain owner's confirmation before anything lands. An author's own judgment that this case is special is not a confirmation. + +- Judged condition: does the change add a `resolve` hook, including a wrapper around an existing hook that rewrites the same specifiers? +- Boundary: this rule decides whether a hook may be added at all; the separation of resolution, hot reload, and plugin management responsibilities is governed separately and does not permit a new hook. +- The one resolution path is the tsx ESM hook registered by the `dsh` source launch, whose rationale is in the [source-launch Agent Note](../../.agents/notes/implemented/architecture/2026-07-29-dsh-source-launch-tsx-esm.md). +- Exception: only the two preconditions above, both recorded on the change. + +The compliant path when new resolution behavior is genuinely needed, in order. + +```text +A new resolve hook is allowed only after both preconditions hold: + +1. Re-audit the resolve strategy as a whole — resolution, hot reload, and plugin + management responsibilities together, not only the specifier at hand. +2. Record the domain owner's confirmation on the change. +3. Only then add the hook, linking both records from the change. + +Until both hold, the answer is no; "this case is special" is the author's judgment, +not a confirmation. +``` + +A hook added so that one specifier lands where this package expects it, or the equivalent wrapper around the existing hook — the resolution path gains a branch, and what the resolver returns no longer matches `node_modules`. + +```ts ignore-check +// Added so one specifier resolves to the local source copy +export async function resolve(specifier: string, parentURL: string, importAttributes: object) { + if (specifier === '@deepseek-ai/dsh-example') return { url: localSourceUrl, shortCircuit: true } + return defaultResolve(specifier, parentURL, importAttributes) +} + +// The equivalent shape: wrapping the hook that already exists +const previous = hooks.resolve +hooks.resolve = (specifier, context, next) => + pinned.has(specifier) ? pinned.get(specifier) : previous(specifier, context, next) +``` diff --git a/docs/defensive-patterns/package-surface.zh.md b/docs/defensive-patterns/package-surface.zh.md new file mode 100644 index 0000000000..140f103264 --- /dev/null +++ b/docs/defensive-patterns/package-surface.zh.md @@ -0,0 +1,224 @@ +# 包面规则 + +[English](package-surface.md) | 中文 + +关于包导出什么、怎么构建、如何声明依赖的规则。布局本身见 [development.zh.md](../development.zh.md#typescript-project-layout);常设条款见 [packages/AGENTS.md](../../packages/AGENTS.md)。 + +## 插件包导出 Loader 所需的东西 + +插件包的入口取两种形态之一,两者不得混用。**函数插件**具名导出 `name`、`inject`、`Config`、`apply`:`name`、`inject`、`apply` 全小写,`Config` 首字母大写,且同时以 `interface` 与 Schemastery schema 值两种形态出现。**服务插件**默认导出它的服务类,Loader 就是这么加载它的;在四件套旁边再加一个默认导出,会让 Loader 丢弃函数插件的命名空间。除这两者之外,Host 入口可以导出供其他包 `extends` 或 `throw` 的 Service Definition 类与错误类型——能力接缝消费的正是这些——但绝不导出测试便利值。UI 插件包的 `/client` 入口更严,[packages/client/AGENTS.md](../../packages/client/AGENTS.md) 是那条纪律的正家:同包测试用相对 `../src/...` 路径或 `./src/*` 子路径触达内部,测试专用的需要因此永远不会变成常驻导出。 + +- Loader 四件套及其准确形态见 [cordis-primer.zh.md](../cordis-primer.zh.md#loader-configuration)。 +- 判定条件:函数插件的入口(`src/index.ts`)导出了四件套以外的实体;在四件套旁边加了默认导出,或两种形态被混用;`/client` 入口导出了实现值、或让另一个功能插件导入了实现值;fixture 用相对路径引用其他包。 +- 边界:只约束 Loader 插件入口。内部模块、工具函数与 hooks 照常导出值;Host 入口的 Service Definition 类与错误类型是应有的导出;测试 fixture 也留在本包内——用相对路径伸进别的包的 `src` 会绕过 `exports` 映射与包边界检查。 +- 例外:无默认例外;确需破例须经对应领域专家确认。 + +合规的入口——四件套,同包测试路径以注释记录,而不是加出第五个导出。 + +```ts +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' + +// The plugin entry: the Loader four, and no fifth value +export const name = 'web-app' +export const inject = ['webServer'] +export interface Config { /* … */ } +export const Config = z.object({ /* … */ }) +export function apply(ctx: Context, config: Config): void { /* … */ } + +// A same-package test imports '../src/internal/header.ts' instead of this entry +``` + +三种写法都会让入口多出不该有的导出;三种都能在 diff 里看到。 + +```ts ignore-check +// The entry widened so a test could reach one helper +export { isHeaderLine } from './internal/header.ts' + +// Both plugin forms on one entry: the Loader discards the four +export default class WebApp {} + +// A fixture reaching into another package by relative path +import { isSurfaceEligibleType } from '../../core/session/src/surface.ts' +``` + +## 包只有两类,且两类都是动态插件包 + +新增包要么是 Host 包,要么是 Host + Client 包,两类都是动态插件包;没有第三种形态可选,也没有例外。shell 经 [packages/client/web/src/platform.ts](../../packages/client/web/src/platform.ts) 的 `PLATFORM_MODULES` 播种的静态客户端库——`client-store`、`ui-slots`、`ui-primitives`、`ui-dockkit`——以及 [packages/util/](../../packages/util/) 下的零依赖库先于本条规则存在,且**已关闭**:它们照原样继续工作,新增包永不加入其中。只有真正的双面包才拆编译面,生成物进 `lib`,`include`、`external` 与 roster 清单由扫描 workspace 得出,不手写。手写清单或新造编译面会让构建产物与清单不再一致,此后每个新增包都得各自维护清单。 + +- 判定条件:新增包未按动态插件包形态构建(static link 打包、手写的全 external 清单);出现第三种 `tsconfig` 变体;手写 `include`、`external` 或 roster 清单。 +- 形态不要照抄数字,就地复算:先列 `packages/*/*` 下的 `tsconfig.json`,再列同时带 `tsconfig.client.json` 与 `tsconfig.host.json` 的包,最后列声明 `dsh.client` 的包。 +- 边界:双面包允许被 `include` 或 `exclude`。 +- 例外:无;没有审批通道。包的形态或编译面变更须先改正家文档,并须经对应领域专家确认。 +- 正家:[development.zh.md](../development.zh.md#typescript-project-layout) 管编译面,[packages/README.zh.md](../../packages/README.zh.md) 管包分组,[adding-a-package.zh.md](../cookbook/adding-a-package.zh.md) 管步骤。 + +属于两类之一的包:使用标准清单字段,没有手写 external 清单。 + +```json +{ + "name": "@deepseek-ai/dsh-example", + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" } + } +} +``` + +手写的 `external` 清单——以及在它旁边为单个包新造的 `tsconfig.foo.json`——让扫描无从推导,构建产物与清单随之不再一致。 + +```json +{ "name": "@deepseek-ai/dsh-example", "external": ["@deepseek-ai/*"] } +``` + +## `package.json` `exports` 使用标准键集合 + +`package.json` 的 `exports` 只使用标准键集合,集合中每个键在全仓已经只有一个含义,包不得为自己的局部用途开键。只有少数几个包在用、又没有文档正家的键不构成先例:把某个键正式化(包括下面那些未记录在案的键)意味着在同一次改动里改正家文档与检查。键集合小且共享,消费者才能从键名推断用途,扫描也才有可能判定导出映射。 + +- 标准键,每个键在全仓只有一个含义,统计口径是 `packages/*/*/package.json` 与 `apps/*/package.json`:`.`(包主入口)、`./package.json`(工具链访问,不是语义导出)、`./src/*`(测试与工具的源码透传,文档状态仍待定)、`./client`(浏览器入口,与 `dsh.client` 声明配对)、`./types`(类型入口)、`./typert`(typert 类型运行时)、`./remote`(`@Remote` 调用面)、`./locale/*.json`(本地化资源)、`./cordis.patch.yml`(`dsh.bundle` 声明的 bundle 补丁层)。这里不列各键的包数,因为下一个包就会让它过期;下面的复算命令会打印当前数字。 +- 集合之外的键(`./brand` 5 个包、`./worker` 4 个、`./startup`、`./runner`、`./protocol` 各 2 个,另有大量一次性键)没有文档含义,属待核项,不是可照抄的先例。 +- 判定条件:改动是否新增了标准集合以外的 export 键? +- 例外:无默认例外;新增键须先改正家文档与检查,并取得对应领域专家确认。 +- 复算分布: + +```sh +python3 -c "import json,glob,collections; c=collections.Counter(); [c.update(json.load(open(p)).get('exports',{}).keys()) for p in glob.glob('packages/*/*/package.json')+glob.glob('apps/*/package.json') if isinstance(json.load(open(p)).get('exports'),dict)]; print(c.most_common())" +``` + +合规的映射——三个标准键各按全仓含义使用,该包同时声明了 client 入口。 + +```json +{ + "exports": { + ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./client": { "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }, + "./types": { "types": "./lib/types/types.d.ts", "default": "./lib/types/types.js" }, + "./src/*": "./src/*", + "./package.json": "./package.json" + } +} +``` + +为单个包的局部用途开的键——这里是文档地位待核的 `./brand` 与 `./worker`——让导出映射退化为各包自便的约定,消费者与扫描都读不懂。 + +```json +{ + "exports": { + ".": "./lib/index.js", + "./brand": "./lib/brand.js", + "./worker": "./lib/worker.js" + } +} +``` + +## 依赖声明与版本一致性由依赖扫描门禁保证 + +依赖声明与版本一致性由依赖扫描机械保证;本页既不复述 `devDependencies` 与 `peerDependencies` 的字段规则,也不另立包准入清单。扫描失败时,在本地复现并修正它指名的清单,因为规则的正家是扫描与其策略文件。为了让改动落地而修改扫描或放宽策略不属于常规改动,须经对应领域专家确认。 + +- 入口:[verify-package-dependencies.ts](../../scripts/verify-package-dependencies.ts),以 `pnpm run verify-package-dependencies` 运行,被 `scripts/run-gates.ts` 作为 `package-dependencies` 门禁调用,`.github/workflows/release.yml` 也直接运行它。 +- 策略正家:[package-dependency-policy.ts](../../scripts/package-dependency-policy.ts) 导出 `PACKAGE_DEPENDENCY_POLICY`;声明面、版本形态与豁免都在该文件定义,包级背景见 [packages/README.zh.md](../../packages/README.zh.md)。 +- 边界:本页不列包清单、字段规则或阈值,只指向正家文件。 +- 查接线:`grep -rn "verify-package-dependencies" package.json .github/workflows scripts/run-gates.ts`。 +- 例外:修改扫描或策略须经对应领域专家确认,并在改动上记录理由。 + +可重复的流程:复现、读诊断、修正它指名的清单。 + +```sh +# 1. Reproduce what CI reports +pnpm run verify-package-dependencies + +# 2. The diagnostic names the manifest, the section, the dependency, and the expected range +# packages/example/package.json: dependencies.@deepseek-ai/dsh-base must use workspace:*, found workspace:~ + +# 3. The fix goes into the manifest, never into the policy file or the scan +# "dependencies": { "@deepseek-ai/dsh-base": "workspace:*" } + +# 4. Re-run the scan until every package matches the published policy +pnpm run verify-package-dependencies +``` + +失去机械保证的两种做法:改检查而不改清单,或者把规则复述到本页、从此与正家漂移。 + +```text +Relaxing PACKAGE_DEPENDENCY_POLICY, or dropping the scanned section that fails, to go green +Restating a required-devDependency package list or the field rules on this page instead of linking the policy file +``` + +## 内部依赖写法按包族保证 + +内部依赖写法按包族决定:`@deepseek-ai/dsh` 与 `@deepseek-ai/dsh-*` 用 `workspace:*`,其余内部包用 `workspace:~`,`workspace:^` 已退出。同一个依赖名在所有 workspace 内写法一致,不一致是扫描硬失败,不是评审可以放行的警告。写法统一才能保持一条解析路径,避免同一个依赖出现重复实例以及随之而来的解析差异。 + +- 判定在 [verify-package-dependencies.ts](../../scripts/verify-package-dependencies.ts) 的 `workspaceRange()`:`@deepseek-ai/dsh` 与 `@deepseek-ai/dsh-*` 包族取 `workspace:*`,其余内部包取 `workspace:~`;扫描遍历受管清单,比对同一依赖名的每一处声明。 +- 边界:同命名空间但不是 workspace 成员的包按普通第三方版本范围声明,不受包族规则约束——`@deepseek-ai/libreoffice-kit` 在 `apps/desktop-host/package.json`(dependencies)、`packages/bundle/web-app/package.json`(devDependencies)、`packages/document/office-to-pdf/package.json`(dependencies)、`packages/skill/skill-office/package.json`(dependencies)中声明为 `^0.1.5`。 +- 分布不在此复述;下面的复算命令会打印 `workspace:*`、`workspace:~`、`workspace:^` 的当前数量,以及族规则之外的精确版本声明。 +- 例外:门禁机械判定;确需例外意味着修改扫描与策略文件,并须经对应领域专家确认、在改动上说明理由。 +- 复算: + +```sh +python3 -c "import json,glob,collections; c=collections.Counter(); [c.update([r]) for p in glob.glob('apps/*/package.json')+glob.glob('packages/*/*/package.json')+glob.glob('vendor/*/package.json') for s in ('dependencies','devDependencies','optionalDependencies','peerDependencies') for n,r in (json.load(open(p)).get(s) or {}).items() if n.startswith('@deepseek-ai/')]; print(c.most_common())" +``` + +每个包族各用其写法,非成员的例外保持普通版本范围。 + +```json +{ + "dependencies": { + "@deepseek-ai/dsh-base": "workspace:*", + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/libreoffice-kit": "^0.1.5" + }, + "devDependencies": { + "@deepseek-ai/dsh-typert-registry": "workspace:*" + } +} +``` + +`dsh-*` 包写成 `workspace:~`,以及把 workspace 成员钉到外部版本范围——两者都是扫描硬失败,已退出的「一律钉精确版本」旧口径不能作为替代写法。 + +```json +{ + "dependencies": { + "@deepseek-ai/dsh-base": "workspace:~", + "@deepseek-ai/cordis": "^4.0.0" + } +} +``` + +## 新增 resolve 钩子直接禁止 + +新增 `resolve` 钩子默认被拒——这是确定性禁止,不是「尽量不」。确有需要时,两个前置条件必须同时成立:整体重审 resolve 策略,而不是给触发本次改动的那个 specifier 打补丁;以及在任何内容落地之前取得对应领域专家的确认。开发者自行判断「这次特殊」不构成确认。 + +- 判定条件:改动是否新增 `resolve` 钩子,包括包装既有钩子、改写同一批 specifier 的等价写法? +- 边界:本条只管能否新增钩子;解析、热更新与插件管理三者的职责划分另行治理,并不因此允许新增钩子。 +- 唯一的解析路径是 `dsh` 源码启动注册的 tsx ESM 钩子,其理由见[源码启动 Agent Note](../../.agents/notes/implemented/architecture/2026-07-29-dsh-source-launch-tsx-esm.zh.md)。 +- 例外:只有上述两个前置条件,且都要记录在改动上。 + +确有新的解析需求时的合规路径,按顺序。 + +```text +A new resolve hook is allowed only after both preconditions hold: + +1. Re-audit the resolve strategy as a whole — resolution, hot reload, and plugin + management responsibilities together, not only the specifier at hand. +2. Record the domain owner's confirmation on the change. +3. Only then add the hook, linking both records from the change. + +Until both hold, the answer is no; "this case is special" is the author's judgment, +not a confirmation. +``` + +为了让某个 specifier 落到本包期望的位置而加的钩子,或包装既有钩子达到同样效果的等价写法——解析路径多出一个分支,resolver 的返回与 `node_modules` 实况不再对应。 + +```ts ignore-check +// Added so one specifier resolves to the local source copy +export async function resolve(specifier: string, parentURL: string, importAttributes: object) { + if (specifier === '@deepseek-ai/dsh-example') return { url: localSourceUrl, shortCircuit: true } + return defaultResolve(specifier, parentURL, importAttributes) +} + +// The equivalent shape: wrapping the hook that already exists +const previous = hooks.resolve +hooks.resolve = (specifier, context, next) => + pinned.has(specifier) ? pinned.get(specifier) : previous(specifier, context, next) +``` diff --git a/docs/defensive-patterns/remote-and-api.i18n.yaml b/docs/defensive-patterns/remote-and-api.i18n.yaml new file mode 100644 index 0000000000..c16a005c98 --- /dev/null +++ b/docs/defensive-patterns/remote-and-api.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for remote-and-api.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/defensive-patterns/remote-and-api.md +/remote-and-api-rules: + en: 26fb6e92d16925b0 + zh: 72d13c0481fc61e9 +/remote-and-api-rules/a-new-remote-capability-gets-its-own-service: + en: 5759a7b0f96ea4bc + zh: 62465fbe91a4d2af +/remote-and-api-rules/remote-marks-capability-methods: + en: 86422ee69c63f339 + zh: 4a5e8d6f5d9a6ae3 +/remote-and-api-rules/packages-api-carries-generic-orchestration-only: + en: 12a964b9c04fccf9 + zh: cf804f8044535727 diff --git a/docs/defensive-patterns/remote-and-api.md b/docs/defensive-patterns/remote-and-api.md new file mode 100644 index 0000000000..7f2d0646c9 --- /dev/null +++ b/docs/defensive-patterns/remote-and-api.md @@ -0,0 +1,115 @@ +# Remote and API rules + +English | [中文](remote-and-api.zh.md) + +Rules for the `packages/api` layer and the remote methods it exposes. [api-gateway.md](../api-gateway.md) describes the call model itself. Each section below states the requirement, how a reviewer judges it, what it does not cover, which exception applies and who approves it, and a correct and a wrong example. + +## A new remote capability gets its own service + +A new remote business capability is a new service — its own package or its own object — and `@Remote` marks that service's concrete methods. Growing an existing large service one method at a time leaves one object answering for auth, Session, workspace, and event carriage at once, mixes per-domain activation policy with history pagination, and makes every later change to one capability touch all of them. Split by business boundary, not by caller count: a capability with a single caller today still gets its own service, and an endpoint that changes owners moves to its new owner instead of joining the object it is leaving. + +- Judged by: which object holds the new remote method. A method for a new business line added to a service that already owns another line is the defect; the fix is a service named for the new capability, with `@Remote` on its concrete methods. A migration is judged the same way — the moved method appears on its new owner, as `SubagentRuntime` does in `packages/subagent/subagent`, not on the object it left. +- Not covered: a service whose methods all serve one business boundary stays whole, and a new private helper of that capability belongs on it. Data that needs its own protocol does not become a Remote method on the new service either; session event streams, pagination, incremental reduce, projection, and entity substreams keep their separate registration model ([gateway boundaries](../api-gateway.md#boundaries)). +- Exception: none recorded; a single caller is not a reason to merge. Where the business boundary itself is contested, the domain owner settles it as an architecture question before the change lands. +- Fix: create the capability's own service object or package, put `@Remote` on its concrete methods, and let callers reach it through `ctx.remote.`. + +The subagent capability owns its own service, and every remote method is a concrete method of that service: + +```ts ignore-check +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' + +interface SubagentList { ids: string[] } +interface PromptRequest { text: string } +interface PromptResult { accepted: boolean } + +class SubagentRuntime extends TypertRemoteService { + @Remote list(): SubagentList { return { ids: [] } } + @Remote prompt(request: PromptRequest): PromptResult { + return { accepted: request.text !== '' } + } + @Remote interruptByParent(id: string): void { } +} +``` + +The wrong version adds the same capability to the object that already carries other domains: + +```text +class ApiProxy { + @Remote goalList(): GoalList // goal domain + @Remote subagentPrompt(request): ... // subagent domain +} +``` + +One object then answers for both domains, so a change to either capability's activation policy, pagination, or event handling lands in the same place, and neither capability can move without the other. + +## `@Remote` marks capability methods + +`@Remote` carries five disciplines that a reviewer checks separately: it marks the concrete method that performs a capability; client-facing types come from the existing definitions through the generator instead of a hand-written copy; the payload is JSON and the remote method performs no output-side decode; existing method and field names are additive; and a method names every resource it touches and reads its caller only from the invocation. Each discipline removes a different failure — a wrapper hides which operation is exposed, a second hand-written type set drifts from the generated one, an output-side decode adds a second result path beside the codec the Gateway already runs, a rename breaks every caller in the same change, and an unnamed resource, an unfiltered aggregate, or an argument-supplied caller lets a non-owner reach what no binding grants it. + +- **Capability methods.** The annotation goes on the concrete method that performs the operation (`list`, `prompt`, `interruptByParent`), never on a wrapper that forwards to the real implementation. Judged by the decorated method's body: a body that only delegates means the annotation is on the wrong method. +- **Types from inference.** Client-facing types are aliased from what the generator produces — `type SessionRemote = TypertClientRemote['session']` — instead of being written a second time. Judged by a hand-written declaration whose fields repeat a generated Client type; [typert.md](../subsystems/typert.md) owns the generated maps and their declaration merges. +- **JSON on the wire, no output-side decode.** The **wire payload** of a Remote method is JSON, with binary content expressed field-level. The Host signature keeps what the Gateway already supports — lookup arguments resolved to Host objects, a trailing `AbortSignal`, a stream declared with `@Remote({ mode: 'stream' })` — and `@Remote` performs no decode on the way out; the generated codec and the Gateway validate the result. Judged by a decode, a stream reassembly, or a whole non-JSON value in the payload of a method carrying the decorator; [programming model](../api-gateway.md#programming-model) owns what may cross a Remote method. +- **Existing names are additive.** A migration does not rename a remote method or field that a Client already calls; a new semantic gets a new entry, and a rename is its own change with its own review. Judged by a diff that renames or removes a name already exposed through `ctx.remote.`. +- **Caller identity and access.** Every Remote method is under access control: the `@Remote({ resources })` / `@RemoteScope(key, { resources })` readers and automatic resolution must name every resource the method touches, because access control never checks a resource they omit, and a method returning several resources filters each item through `this.ctx.remoteAccess.allows(resource)`. The caller is read only from `this.ctx.invocation.peer.principal`, never from arguments; a Remote method that builds a user-message source records it through `principalOf(this.ctx.invocation)` and passes the built source down instead of passing the principal as a function argument. Every call path names its Peer explicitly. Judged by a method whose resolved resources omit one it touches, an unfiltered aggregate, a principal read from wire data or threaded through helper parameters, or a user-message source built in a Remote method without `principalOf`; the [Peer principals Agent Note](../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md) owns the design. +- **Not covered.** A method without the decorator stays an ordinary service method with in-process callers; the five disciplines govern what becomes a Remote method, not what a service may implement. +- **Exception.** A rename or a new decode path states its benefit and the impact on existing callers first and needs the domain owner's confirmation; the author never self-approves. + +The generated map is the only source for Client-facing types, the decorator sits on the concrete method, and the payload stays JSON: + +```ts ignore-check +import { Remote, TypertRemoteService, type TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol' + +// Client-facing types come from the generated map, never from a second hand-written set. +type SessionRemote = TypertClientRemote['session'] + +class SessionController extends TypertRemoteService { + @Remote('search') + search(query: string): SessionSearchValue { + return this.runSearch(query) + } +} +``` + +A hand-written second type set, a rename of a shipped name, and an output-side decode each break a different discipline: + +```text +type SessionRemote = { list(): ...; rename(id: string): ... } // hand-written copy +@Remote('renameSession') rename(...) // shipped name changed +@Remote decode(payload: Uint8Array): Result // output-side decode +``` + +The hand-written copy drifts from the generated type without failing a build, the rename breaks every existing Client call at once, and the decode replaces the generated codec with a second, unchecked result path. + +## `packages/api` carries generic orchestration only + +The packages under `packages/api` — the controllers, `gateway`, and `remotes` — carry transport, call shape, Session lifecycle, and other generic orchestration. A business branch never aggregates there: a decision that depends on concrete business state, handling bound to one feature, or a per-feature filter belongs in its own package or module and reaches this layer as projected data or through a registration surface. The criterion is where the logic belongs, not where the file sits, so a branch that only makes sense for one feature is a defect even when the file holding it is generic. + +- Judged by: where the branch reads its condition. An `if` or `switch` over feature state, a per-feature filter, or a helper named for one feature inside `packages/api` is the defect; the same decision taken in the owning package and consumed here as projected data or a registered entry is not. The package census shows the impact: `packages/api` holds nine packages — `account-controller`, `gateway`, `job-controller`, `remotes`, `session-controller`, `settings-controller`, `terminal-controller`, `workspace-controller`, `workspace-files` — and `session-controller` is the largest at 34 `src` files (terminal-controller 12, gateway 11, workspace-controller 10, workspace-files 8, job-controller 8, remotes 4, settings-controller 3, account-controller 2). +- Not covered: generic Session lifecycle, transport, and storage abstraction stay — `gateway` dispatch, `remotes` selection, and shared session-list and catalog reads are infrastructure, not business logic. [Business ownership](../api-gateway.md#business-ownership) states the same split from the Gateway side. +- Exception: none by default. Adding a business branch here needs an independent-package review, and that review answers why the logic cannot live in the package that owns the feature. +- Fix: move the decision into the owning package, publish its result as projected data or register it on a registry this layer already injects, and leave only the orchestration that reads it. + +The owning package decides and registers its unit, and the controller only reads the projected value: + +```ts ignore-check +// packages/workspace//src/index.ts: the rule lives with the feature it serves. +ctx.sessionProjections.register({ + key: 'durablePage', + stateSchema: durablePageState, + init: () => ({ durable: false }), + apply: applyDurablePage, + stateVersion: 1, +}) + +// packages/api/session-controller: generic orchestration reads the projected value. +const { durable } = ctx.sessionProjections.stateOf(session, 'durablePage') +``` + +The wrong version decides the rule inside the shared layer: + +```text +// packages/api/session-controller: a feature branch inside the shared layer +if (session.page.transport === 'durable') { /* durable-transport handling */ } +``` + +The rule then has a second home, and every later change to it has to find both while the shared layer keeps carrying one feature's semantics. diff --git a/docs/defensive-patterns/remote-and-api.zh.md b/docs/defensive-patterns/remote-and-api.zh.md new file mode 100644 index 0000000000..c621109913 --- /dev/null +++ b/docs/defensive-patterns/remote-and-api.zh.md @@ -0,0 +1,115 @@ +# 远程与 API 规则 + +[English](remote-and-api.md) | 中文 + +`packages/api` 层及其对外远程方法的规则。调用模型本身见 [api-gateway.zh.md](../api-gateway.zh.md)。以下每条规则都给出要求、审查者的判定方式、不覆盖的内容、例外与批准人,以及一个正例与一个反例。 + +## 新的远程能力要有自己的 service + +新的远程业务能力就是一个新的 service——独立包或独立对象——`@Remote` 标在它的具体方法上。往既有的大 service 上一个方法一个方法地加,会让同一个对象同时承担 auth、Session、workspace 与事件载体,把逐领域的激活策略与历史分页混在一起,并让之后对任一能力的变更都要动所有这些面。按业务边界切,而不是按调用方数量切:当前只有一个调用方的能力也建独立 service;端点迁移是搬到新归属,而不是并进它正要离开的那个对象。 + +- 判定:新远程方法最终落在哪个对象上。把属于新业务线的方法加到已经承担另一条业务线的 service 上即为违反;修法是为新能力建一个以它命名的 service,并把 `@Remote` 标在它的具体方法上。迁移按同一标准判定——被搬走的方法出现在新归属上(如 `packages/subagent/subagent` 的 `SubagentRuntime`),而不是留在它离开的那个对象上。 +- 不覆盖:所有方法都服务同一条业务边界的 service 保持完整,该能力新增的私有辅助方法就属于它。需要独立协议的数据也不会变成新 service 上的 Remote 方法;会话事件流、分页、增量 reduce、projection 与实体子流保持各自独立的注册模型([gateway 边界](../api-gateway.zh.md#boundaries))。 +- 例外:无。只有一个调用方不构成合并的理由;业务边界本身有争议时,由对应领域专家作为架构问题先行裁定,再落地。 +- 修法:为新能力建独立 service 对象或包,把 `@Remote` 标在它的具体方法上,调用方经 `ctx.remote.` 使用。 + +subagent 能力拥有自己的 service,它的每个远程方法都是该 service 的具体方法: + +```ts ignore-check +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' + +interface SubagentList { ids: string[] } +interface PromptRequest { text: string } +interface PromptResult { accepted: boolean } + +class SubagentRuntime extends TypertRemoteService { + @Remote list(): SubagentList { return { ids: [] } } + @Remote prompt(request: PromptRequest): PromptResult { + return { accepted: request.text !== '' } + } + @Remote interruptByParent(id: string): void { } +} +``` + +反例把同一能力加到已经在承担其他领域的对象上: + +```text +class ApiProxy { + @Remote goalList(): GoalList // goal domain + @Remote subagentPrompt(request): ... // subagent domain +} +``` + +于是一个对象同时为两个领域作答:任一能力的激活策略、分页或事件处理变更都落在同一处,两个能力也无法各自搬迁。 + +## `@Remote` 标在能力方法上 + +`@Remote` 有五项纪律,审查者分别核对:标注执行能力的具体方法;面向 Client 的类型经生成器来自既有定义,而不是手写第二份;载荷只承载 JSON,远程方法不做输出侧 decode;既有的方法与字段名只增不改;方法指明其访问的全部资源,且只从 invocation 读取调用方。每项纪律消除一类不同的缺陷——壳方法藏起真正暴露的是哪个操作,手写的第二份类型会与生成结果漂移,输出侧 decode 在 Gateway 已有的 codec 之外再造一条结果路径,改名让所有调用方在同一次变更里一起断掉,遗漏资源、未过滤的聚合结果或按参数判定调用方则让非 owner 访问没有 binding 授予它的内容。 + +- **标能力方法。** 标注落在执行该操作的具体方法上(`list`、`prompt`、`interruptByParent`),绝不落在转发给真正实现的壳方法上。判定看被标注方法的函数体:函数体只做转发,标注就标错了方法。 +- **类型靠推断。** 面向 Client 的类型从生成结果取别名——`type SessionRemote = TypertClientRemote['session']`——而不是重写一份。判定看是否出现字段与生成的 Client 类型重复的手写声明;生成映射及其声明合并的正家是 [typert.zh.md](../subsystems/typert.zh.md)。 +- **线上载荷只承载 JSON、不做输出侧 decode。** Remote 方法的**线上载荷**是 JSON,二进制在字段级表达。Host 签名保留 Gateway 已支持的形式——经解析变成 Host 对象的 lookup 参数、末尾的 `AbortSignal`、以 `@Remote({ mode: 'stream' })` 声明的流式返回;`@Remote` 不做输出侧 decode,结果由生成的 codec 与 Gateway 校验。判定看带该标注的方法上是否出现 decode、流重组或整体非 JSON 值;可跨越 Remote 方法的内容正家是 [编程模型](../api-gateway.zh.md#programming-model)。 +- **存量名只增不改。** 迁移不改 Client 已在调用的远程方法名或字段名;新语义新增条目,改名是独立的一刀、单独评审。判定看 diff 是否改名或删除了已经经 `ctx.remote.` 暴露的名字。 +- **调用方身份与访问。** 每个 Remote 方法都受访问控制:`@Remote({ resources })` / `@RemoteScope(key, { resources })` 的读取函数与自动解析必须指明方法访问的全部资源,因为访问控制从不检查它们遗漏的资源;返回多个资源的方法对每一项经 `this.ctx.remoteAccess.allows(resource)` 过滤。调用方只从 `this.ctx.invocation.peer.principal` 读取,绝不从参数读取;在 Remote 方法内构造用户消息 source 时经 `principalOf(this.ctx.invocation)` 记录调用方,并向下传递已构造的 source,而不是把 principal 当函数参数传递。每条调用路径都显式给出 Peer。判定看方法解析出的资源是否遗漏其访问的资源、聚合结果是否未过滤、principal 是否从 wire 数据读取或经辅助函数参数逐层传递、Remote 方法内构造的用户消息 source 是否未经 `principalOf`;设计的正家是 [Peer 身份属性 Agent Note](../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md)。 +- **不覆盖。** 不带该标注的方法仍是有进程内调用者的普通 service 方法;这五项纪律约束的是什么成为 Remote 方法,而不是 service 可以实现什么。 +- **例外。** 确需改名或新增 decode 路径,须先说明收益与对既有调用方的影响,并取得对应领域专家的确认;作者不得自行批准。 + +生成的映射是面向 Client 类型的唯一来源,标注落在具体方法上,载荷保持 JSON: + +```ts ignore-check +import { Remote, TypertRemoteService, type TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol' + +// Client-facing types come from the generated map, never from a second hand-written set. +type SessionRemote = TypertClientRemote['session'] + +class SessionController extends TypertRemoteService { + @Remote('search') + search(query: string): SessionSearchValue { + return this.runSearch(query) + } +} +``` + +手写第二份类型、改名已发布的名字、在远程方法上做输出侧 decode,各自破坏一项纪律: + +```text +type SessionRemote = { list(): ...; rename(id: string): ... } // hand-written copy +@Remote('renameSession') rename(...) // shipped name changed +@Remote decode(payload: Uint8Array): Result // output-side decode +``` + +手写的副本会与生成类型漂移而不会让构建失败,改名一次性打断所有既有 Client 调用,decode 则用第二条未经校验的结果路径替换生成的 codec。 + +## `packages/api` 只承载通用编排 + +`packages/api` 下的包——各 controller、`gateway`、`remotes`——承载传输、调用形态、Session 生命周期等通用编排。业务分支绝不在其中聚合:依赖具体业务状态的判断、与单个功能绑定的处理、逐功能的过滤,都归独立包或模块,并作为投影数据或经注册面接入本层。判据是逻辑的归属,而不是文件的位置,所以只对一个功能成立的业务分支即使放在通用文件里也是缺陷。 + +- 判定:分支的条件从哪里读取。在 `packages/api` 内对功能状态做 `if` 或 `switch`、写逐功能的过滤、或以某个功能命名的辅助方法,即为缺陷;同样的判断由归属包做出、在本层作为投影数据或注册条目消费,则不是。包普查是影响面的证据:`packages/api` 共 9 个包——`account-controller`、`gateway`、`job-controller`、`remotes`、`session-controller`、`settings-controller`、`terminal-controller`、`workspace-controller`、`workspace-files`——其中 `session-controller` 以 34 个 `src` 文件为最多(terminal-controller 12、gateway 11、workspace-controller 10、workspace-files 8、job-controller 8、remotes 4、settings-controller 3、account-controller 2)。 +- 不覆盖:通用 Session 生命周期、传输与存储抽象留下——`gateway` 的分发、`remotes` 的选择、共享的会话列表与目录读取属于基础设施,不是业务逻辑。[业务所有权](../api-gateway.zh.md#business-ownership)从 Gateway 一侧给出同一个划分。 +- 例外:默认无例外。在此新增业务分支须走独立包评审,评审要回答这些逻辑为什么不能住在拥有该功能的包里。 +- 修法:把判断移进归属包,将其结果作为投影数据发布、或注册到本层本就注入的注册表上,这里只留下读取它的编排。 + +归属包做出判断并注册自己的单元,controller 只读取投影值: + +```ts ignore-check +// packages/workspace//src/index.ts: the rule lives with the feature it serves. +ctx.sessionProjections.register({ + key: 'durablePage', + stateSchema: durablePageState, + init: () => ({ durable: false }), + apply: applyDurablePage, + stateVersion: 1, +}) + +// packages/api/session-controller: generic orchestration reads the projected value. +const { durable } = ctx.sessionProjections.stateOf(session, 'durablePage') +``` + +反例把这条规则的决定放进共享层: + +```text +// packages/api/session-controller: a feature branch inside the shared layer +if (session.page.transport === 'durable') { /* durable-transport handling */ } +``` + +这条规则于是有了第二个家,之后每次变更都要同时找到两处,而共享层继续承载某一个功能的语义。 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 3154c4d988..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)。 @@ -109,6 +123,7 @@ pnpm run build `pnpm run hygiene` 包含 `publint`(用构建出的 `lib/*.js` 文件校验包入口点)和 `verify-node-next-types`(用一个临时的 NodeNext 消费方校验构建出的声明文件)。新 worktree 在 `pnpm run build` 运行之前没有打包的 JS 和声明文件;普通提交和推送无需构建,除非所选检查会使用这些产物。 + ### 环境变量 真实的 DeepSeek 适配器和需要密钥的 agent 演示从环境变量或仓库根目录一个被 gitignore 的 `.env` 文件读取凭证: @@ -126,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`。 @@ -136,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) 和工作流文件为准。 @@ -168,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 5adc51ba90..d727ee4ec8 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -8,7 +8,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | -| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:238`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | +| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:363`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:261`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | @@ -22,17 +22,17 @@ 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:611`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:591`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:618`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:597`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:56`](../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:629`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:609`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:636`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:615`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:622`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:54`](../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` | | `compaction/summary-error` | `waterfall` | [`packages/compaction/compaction/src/index.ts:106`](../packages/compaction/compaction/src/index.ts) | [`compaction-basic`](../packages/compaction/compaction-basic) (`waterfall`) | [`compaction-image-offload`](../packages/compaction/compaction-image-offload) | -| `connection/request` | `waterfall` | [`packages/client/connection/src/index.ts:67`](../packages/client/connection/src/index.ts) | `connection` (`waterfall`) | - | +| `connection/request` | `waterfall` | [`packages/client/connection/src/index.ts:68`](../packages/client/connection/src/index.ts) | `connection` (`waterfall`) | - | | `cordis/dynamic-package` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:383`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/dynamic-retract` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:389`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/inspect-query` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:395`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | @@ -51,19 +51,19 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:59`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:150`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes` | | `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | -| `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:32`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | -| `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:37`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | +| `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | +| `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:23`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:75`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | -| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:264`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:270`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:277`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:269`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:275`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:282`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | | `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:478`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | | `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`) | - | @@ -80,7 +80,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tools/src/index.ts:191`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | | `tools/result` | `emit` | [`packages/core/tools/src/index.ts:199`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`subagent`](../packages/subagent/subagent), [`tool-present`](../packages/deliverables/tool-present) | | `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:157`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | `remotes` | -| `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:34`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | +| `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:39`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `remote-access`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | | `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:79`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/agent-start` | `emit` | [`packages/workflow/workflow/src/index.ts:68`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/end` | `emit` | [`packages/workflow/workflow/src/index.ts:89`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 0133716910..fccfeea698 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -10,7 +10,7 @@ | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | -| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:238`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | +| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:363`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:261`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | @@ -24,17 +24,17 @@ | `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:611`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:591`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:618`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:597`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:56`](../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:629`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:609`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:636`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:615`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:622`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:54`](../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` | | `compaction/summary-error` | `waterfall` | [`packages/compaction/compaction/src/index.ts:106`](../packages/compaction/compaction/src/index.ts) | [`compaction-basic`](../packages/compaction/compaction-basic) (`waterfall`) | [`compaction-image-offload`](../packages/compaction/compaction-image-offload) | -| `connection/request` | `waterfall` | [`packages/client/connection/src/index.ts:67`](../packages/client/connection/src/index.ts) | `connection` (`waterfall`) | - | +| `connection/request` | `waterfall` | [`packages/client/connection/src/index.ts:68`](../packages/client/connection/src/index.ts) | `connection` (`waterfall`) | - | | `cordis/dynamic-package` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:383`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/dynamic-retract` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:389`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/inspect-query` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:395`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | @@ -53,19 +53,19 @@ | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:59`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:150`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes` | | `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | -| `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:32`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | -| `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:37`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | +| `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | +| `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:23`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:75`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | -| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:264`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:270`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:277`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:269`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:275`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:282`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | | `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:478`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | | `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`) | - | @@ -82,7 +82,7 @@ | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tools/src/index.ts:191`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | | `tools/result` | `emit` | [`packages/core/tools/src/index.ts:199`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`subagent`](../packages/subagent/subagent), [`tool-present`](../packages/deliverables/tool-present) | | `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:157`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | `remotes` | -| `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:34`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | +| `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:39`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `remote-access`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | | `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:79`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/agent-start` | `emit` | [`packages/workflow/workflow/src/index.ts:68`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/end` | `emit` | [`packages/workflow/workflow/src/index.ts:89`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`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 63a00c948d..b6df4b5e7b 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -111,6 +111,7 @@ flowchart TD pkg_api_account_controller["api-account-controller"] pkg_api_gateway["api-gateway"] pkg_api_job_controller["api-job-controller"] + pkg_api_remote_access["api-remote-access"] pkg_api_remotes["api-remotes"] pkg_api_session_controller["api-session-controller"] pkg_api_settings_controller["api-settings-controller"] @@ -175,6 +176,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 +221,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"] @@ -398,6 +401,7 @@ flowchart TD pkg_fs_ssh["fs-ssh"] pkg_sandbox_ssh["sandbox-ssh"] pkg_ssh["ssh"] + pkg_ssh_helper_runtime["ssh-helper-runtime"] pkg_subprocess_ssh["subprocess-ssh"] end subgraph group_storage["packages/storage"] @@ -449,6 +453,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 @@ -458,11 +464,6 @@ flowchart TD pkg_credentials_local --> pkg_credentials pkg_credentials_local --> pkg_home_paths pkg_credentials_local --> pkg_launch_environment - pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_browse - pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_native - pkg_host_directory_picker_auto --> pkg_host_directory_picker_browse - pkg_host_directory_picker_auto --> pkg_host_directory_picker_native - pkg_host_directory_picker_auto --> pkg_host_webserver pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths pkg_lsp --> pkg_brand @@ -484,13 +485,11 @@ flowchart TD pkg_spill --> pkg_brand pkg_spill --> pkg_llm pkg_spill --> pkg_session - pkg_api_gateway --> pkg_client_connection 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 @@ -499,6 +498,12 @@ flowchart TD pkg_experimental_webworker_runtime --> pkg_client_modules pkg_experimental_webworker_runtime --> pkg_host_webserver pkg_skill_badge --> pkg_skill + pkg_host_directory_picker_auto --> pkg_client_connection + pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_browse + pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_native + pkg_host_directory_picker_auto --> pkg_host_directory_picker_browse + pkg_host_directory_picker_auto --> pkg_host_directory_picker_native + pkg_host_directory_picker_auto --> pkg_host_webserver pkg_host_frontend_static --> pkg_client_connection pkg_host_frontend_static --> pkg_host_webserver pkg_persona --> pkg_system_prompt @@ -526,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 @@ -595,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 @@ -635,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 @@ -701,6 +708,7 @@ flowchart TD pkg_llm_deepseek_account --> pkg_launch_environment pkg_llm_deepseek_account --> pkg_llm pkg_llm_deepseek_account --> pkg_llm_deepseek + pkg_llm_deepseek_account --> pkg_timeout pkg_tools --> pkg_agent pkg_tools --> pkg_llm pkg_tools --> pkg_ptc_runtime @@ -714,10 +722,6 @@ flowchart TD pkg_command_goal --> pkg_commands pkg_command_goal --> pkg_goal pkg_command_goal --> pkg_llm - pkg_goal_round_driver --> pkg_agent - pkg_goal_round_driver --> pkg_goal - pkg_goal_round_driver --> pkg_llm - pkg_goal_round_driver --> pkg_session pkg_fs_sandbox --> pkg_fs pkg_fs_sandbox --> pkg_fs_local pkg_fs_sandbox --> pkg_sandbox @@ -1006,6 +1010,7 @@ flowchart TD pkg_ssh --> pkg_session_projection pkg_ssh --> pkg_subprocess pkg_ssh --> pkg_subprocess_local + pkg_ssh --> pkg_util_values pkg_llm_replay --> pkg_compaction pkg_llm_replay --> pkg_deepseek_llm_api_extensions pkg_llm_replay --> pkg_llm @@ -1042,7 +1047,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 @@ -1159,7 +1163,6 @@ flowchart TD pkg_acp --> pkg_session_persistence pkg_acp --> pkg_token_meter pkg_acp --> pkg_user_approval - pkg_plugin_manager --> pkg_agent_preset_registry pkg_plugin_manager --> pkg_brand pkg_plugin_manager --> pkg_hmr pkg_plugin_manager --> pkg_host_plugin_inventory @@ -1206,6 +1209,11 @@ flowchart TD pkg_webhook_github --> pkg_host_webserver pkg_webhook_github --> pkg_session pkg_webhook_github --> pkg_webhook + pkg_goal_round_driver --> pkg_agent + pkg_goal_round_driver --> pkg_goal + pkg_goal_round_driver --> pkg_llm + pkg_goal_round_driver --> pkg_session + pkg_goal_round_driver --> pkg_subagent pkg_subagent_acp --> pkg_agent pkg_subagent_acp --> pkg_llm pkg_subagent_acp --> pkg_session @@ -1227,6 +1235,7 @@ flowchart TD pkg_subagent_fork_in_process --> pkg_subagent pkg_subagent_spawn_in_process --> pkg_subagent pkg_tool_subagent --> pkg_agent + pkg_tool_subagent --> pkg_agent_preset_registry pkg_tool_subagent --> pkg_llm pkg_tool_subagent --> pkg_scope pkg_tool_subagent --> pkg_session @@ -1452,7 +1461,9 @@ flowchart TD | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | `llm` | — | | [`llm`](../packages/llm/llm) | `llm` | — | | [`scope`](../packages/core/scope) | `core` | — | +| [`api-gateway`](../packages/api/gateway) | `api` | — | | [`api-job-controller`](../packages/api/job-controller) | `api` | — | +| [`api-remote-access`](../packages/api/remote-access) | `api` | — | | [`api-workspace-files`](../packages/api/workspace-files) | `api` | — | | [`cmdline`](../packages/boot/cmdline) | `boot` | — | | [`acp-app`](../packages/bundle/acp-app) | `bundle` | — | @@ -1492,6 +1503,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` | — | @@ -1546,6 +1558,7 @@ flowchart TD | [`session-format-v1-to-v2`](../packages/session/session-format-v1-to-v2) | `session` | — | | [`session-format-v2-to-v3`](../packages/session/session-format-v2-to-v3) | `session` | — | | [`session-format-v3-to-v4`](../packages/session/session-format-v3-to-v4) | `session` | — | +| [`ssh-helper-runtime`](../packages/ssh/ssh-helper-runtime) | `ssh` | — | | [`storage`](../packages/storage/storage) | `storage` | — | | [`win32-process`](../packages/subprocess/win32-process) | `subprocess` | — | | [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | — | @@ -1558,12 +1571,12 @@ 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) | | [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) | | [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | -| [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | @@ -1577,14 +1590,14 @@ flowchart TD | [`web-search-exa`](../packages/web/web-search-exa) | `web` | [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) | | [`web-search-perplexity`](../packages/web/web-search-perplexity) | `web` | [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) | | [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`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) | | [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) | +| [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) | | [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) | | [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) | | [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | @@ -1600,7 +1613,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) | @@ -1619,7 +1632,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) | @@ -1631,6 +1643,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) | @@ -1645,10 +1658,9 @@ flowchart TD | [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | +| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`timeout`](../packages/util/timeout) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | -| [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | | [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) | @@ -1704,14 +1716,14 @@ flowchart TD | [`shell-env`](../packages/shell/shell-env) | `shell` | [`app-boot`](../packages/boot/app-boot), [`home-paths`](../packages/util/home-paths), [`shell`](../packages/shell/shell), [`tools`](../packages/core/tools) | | [`tool-bash-persistent`](../packages/shell/tool-bash-persistent) | `shell` | [`agent`](../packages/core/agent), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-pwsh-persistent`](../packages/shell/tool-pwsh-persistent) | `shell` | [`agent`](../packages/core/agent), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`ssh`](../packages/ssh/ssh) | `ssh` | [`brand`](../packages/util/brand), [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`fs-sandbox`](../packages/fs/fs-sandbox), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-local`](../packages/sandbox/sandbox-local), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session-projection`](../packages/session/session-projection), [`subprocess`](../packages/subprocess/subprocess), [`subprocess-local`](../packages/subprocess/subprocess-local) | +| [`ssh`](../packages/ssh/ssh) | `ssh` | [`brand`](../packages/util/brand), [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`fs-sandbox`](../packages/fs/fs-sandbox), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-local`](../packages/sandbox/sandbox-local), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session-projection`](../packages/session/session-projection), [`subprocess`](../packages/subprocess/subprocess), [`subprocess-local`](../packages/subprocess/subprocess-local), [`util-values`](../packages/util/values) | | [`llm-replay`](../packages/test-support/llm-replay) | `test-support` | [`compaction`](../packages/compaction/compaction), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`tool-workflow`](../packages/workflow/tool-workflow) | `workflow` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | `llm` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`session`](../packages/core/session) | | [`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) | @@ -1729,18 +1741,19 @@ flowchart TD | [`spill-policy`](../packages/spill/spill-policy) | `spill` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) | -| [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | +| [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`brand`](../packages/util/brand), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | | [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | | [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) | +| [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-acp`](../packages/subagent/subagent-acp) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`subagent-claude-code`](../packages/subagent/subagent-claude-code) | `subagent` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`subagent-codex`](../packages/subagent/subagent-codex) | `subagent` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`subagent`](../packages/subagent/subagent) | -| [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`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-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 9b3a1e2036..4c4e5e23d9 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -113,6 +113,7 @@ flowchart TD pkg_api_account_controller["api-account-controller"] pkg_api_gateway["api-gateway"] pkg_api_job_controller["api-job-controller"] + pkg_api_remote_access["api-remote-access"] pkg_api_remotes["api-remotes"] pkg_api_session_controller["api-session-controller"] pkg_api_settings_controller["api-settings-controller"] @@ -177,6 +178,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 +223,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"] @@ -400,6 +403,7 @@ flowchart TD pkg_fs_ssh["fs-ssh"] pkg_sandbox_ssh["sandbox-ssh"] pkg_ssh["ssh"] + pkg_ssh_helper_runtime["ssh-helper-runtime"] pkg_subprocess_ssh["subprocess-ssh"] end subgraph group_storage["packages/storage"] @@ -451,6 +455,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 @@ -460,11 +466,6 @@ flowchart TD pkg_credentials_local --> pkg_credentials pkg_credentials_local --> pkg_home_paths pkg_credentials_local --> pkg_launch_environment - pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_browse - pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_native - pkg_host_directory_picker_auto --> pkg_host_directory_picker_browse - pkg_host_directory_picker_auto --> pkg_host_directory_picker_native - pkg_host_directory_picker_auto --> pkg_host_webserver pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths pkg_lsp --> pkg_brand @@ -486,13 +487,11 @@ flowchart TD pkg_spill --> pkg_brand pkg_spill --> pkg_llm pkg_spill --> pkg_session - pkg_api_gateway --> pkg_client_connection 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 @@ -501,6 +500,12 @@ flowchart TD pkg_experimental_webworker_runtime --> pkg_client_modules pkg_experimental_webworker_runtime --> pkg_host_webserver pkg_skill_badge --> pkg_skill + pkg_host_directory_picker_auto --> pkg_client_connection + pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_browse + pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_native + pkg_host_directory_picker_auto --> pkg_host_directory_picker_browse + pkg_host_directory_picker_auto --> pkg_host_directory_picker_native + pkg_host_directory_picker_auto --> pkg_host_webserver pkg_host_frontend_static --> pkg_client_connection pkg_host_frontend_static --> pkg_host_webserver pkg_persona --> pkg_system_prompt @@ -528,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 @@ -597,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 @@ -637,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 @@ -703,6 +710,7 @@ flowchart TD pkg_llm_deepseek_account --> pkg_launch_environment pkg_llm_deepseek_account --> pkg_llm pkg_llm_deepseek_account --> pkg_llm_deepseek + pkg_llm_deepseek_account --> pkg_timeout pkg_tools --> pkg_agent pkg_tools --> pkg_llm pkg_tools --> pkg_ptc_runtime @@ -716,10 +724,6 @@ flowchart TD pkg_command_goal --> pkg_commands pkg_command_goal --> pkg_goal pkg_command_goal --> pkg_llm - pkg_goal_round_driver --> pkg_agent - pkg_goal_round_driver --> pkg_goal - pkg_goal_round_driver --> pkg_llm - pkg_goal_round_driver --> pkg_session pkg_fs_sandbox --> pkg_fs pkg_fs_sandbox --> pkg_fs_local pkg_fs_sandbox --> pkg_sandbox @@ -1008,6 +1012,7 @@ flowchart TD pkg_ssh --> pkg_session_projection pkg_ssh --> pkg_subprocess pkg_ssh --> pkg_subprocess_local + pkg_ssh --> pkg_util_values pkg_llm_replay --> pkg_compaction pkg_llm_replay --> pkg_deepseek_llm_api_extensions pkg_llm_replay --> pkg_llm @@ -1044,7 +1049,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 @@ -1161,7 +1165,6 @@ flowchart TD pkg_acp --> pkg_session_persistence pkg_acp --> pkg_token_meter pkg_acp --> pkg_user_approval - pkg_plugin_manager --> pkg_agent_preset_registry pkg_plugin_manager --> pkg_brand pkg_plugin_manager --> pkg_hmr pkg_plugin_manager --> pkg_host_plugin_inventory @@ -1208,6 +1211,11 @@ flowchart TD pkg_webhook_github --> pkg_host_webserver pkg_webhook_github --> pkg_session pkg_webhook_github --> pkg_webhook + pkg_goal_round_driver --> pkg_agent + pkg_goal_round_driver --> pkg_goal + pkg_goal_round_driver --> pkg_llm + pkg_goal_round_driver --> pkg_session + pkg_goal_round_driver --> pkg_subagent pkg_subagent_acp --> pkg_agent pkg_subagent_acp --> pkg_llm pkg_subagent_acp --> pkg_session @@ -1229,6 +1237,7 @@ flowchart TD pkg_subagent_fork_in_process --> pkg_subagent pkg_subagent_spawn_in_process --> pkg_subagent pkg_tool_subagent --> pkg_agent + pkg_tool_subagent --> pkg_agent_preset_registry pkg_tool_subagent --> pkg_llm pkg_tool_subagent --> pkg_scope pkg_tool_subagent --> pkg_session @@ -1454,7 +1463,9 @@ flowchart TD | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | `llm` | — | | [`llm`](../packages/llm/llm) | `llm` | — | | [`scope`](../packages/core/scope) | `core` | — | +| [`api-gateway`](../packages/api/gateway) | `api` | — | | [`api-job-controller`](../packages/api/job-controller) | `api` | — | +| [`api-remote-access`](../packages/api/remote-access) | `api` | — | | [`api-workspace-files`](../packages/api/workspace-files) | `api` | — | | [`cmdline`](../packages/boot/cmdline) | `boot` | — | | [`acp-app`](../packages/bundle/acp-app) | `bundle` | — | @@ -1494,6 +1505,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` | — | @@ -1548,6 +1560,7 @@ flowchart TD | [`session-format-v1-to-v2`](../packages/session/session-format-v1-to-v2) | `session` | — | | [`session-format-v2-to-v3`](../packages/session/session-format-v2-to-v3) | `session` | — | | [`session-format-v3-to-v4`](../packages/session/session-format-v3-to-v4) | `session` | — | +| [`ssh-helper-runtime`](../packages/ssh/ssh-helper-runtime) | `ssh` | — | | [`storage`](../packages/storage/storage) | `storage` | — | | [`win32-process`](../packages/subprocess/win32-process) | `subprocess` | — | | [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | — | @@ -1560,12 +1573,12 @@ 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) | | [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) | | [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | -| [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | @@ -1579,14 +1592,14 @@ flowchart TD | [`web-search-exa`](../packages/web/web-search-exa) | `web` | [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) | | [`web-search-perplexity`](../packages/web/web-search-perplexity) | `web` | [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) | | [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`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) | | [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) | +| [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) | | [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) | | [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) | | [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | @@ -1602,7 +1615,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) | @@ -1621,7 +1634,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) | @@ -1633,6 +1645,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) | @@ -1647,10 +1660,9 @@ flowchart TD | [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | +| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`timeout`](../packages/util/timeout) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | -| [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | | [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) | @@ -1706,14 +1718,14 @@ flowchart TD | [`shell-env`](../packages/shell/shell-env) | `shell` | [`app-boot`](../packages/boot/app-boot), [`home-paths`](../packages/util/home-paths), [`shell`](../packages/shell/shell), [`tools`](../packages/core/tools) | | [`tool-bash-persistent`](../packages/shell/tool-bash-persistent) | `shell` | [`agent`](../packages/core/agent), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-pwsh-persistent`](../packages/shell/tool-pwsh-persistent) | `shell` | [`agent`](../packages/core/agent), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`ssh`](../packages/ssh/ssh) | `ssh` | [`brand`](../packages/util/brand), [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`fs-sandbox`](../packages/fs/fs-sandbox), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-local`](../packages/sandbox/sandbox-local), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session-projection`](../packages/session/session-projection), [`subprocess`](../packages/subprocess/subprocess), [`subprocess-local`](../packages/subprocess/subprocess-local) | +| [`ssh`](../packages/ssh/ssh) | `ssh` | [`brand`](../packages/util/brand), [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`fs-sandbox`](../packages/fs/fs-sandbox), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-local`](../packages/sandbox/sandbox-local), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session-projection`](../packages/session/session-projection), [`subprocess`](../packages/subprocess/subprocess), [`subprocess-local`](../packages/subprocess/subprocess-local), [`util-values`](../packages/util/values) | | [`llm-replay`](../packages/test-support/llm-replay) | `test-support` | [`compaction`](../packages/compaction/compaction), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`tool-workflow`](../packages/workflow/tool-workflow) | `workflow` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | `llm` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`session`](../packages/core/session) | | [`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) | @@ -1731,18 +1743,19 @@ flowchart TD | [`spill-policy`](../packages/spill/spill-policy) | `spill` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) | -| [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | +| [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`brand`](../packages/util/brand), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | | [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | | [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) | +| [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-acp`](../packages/subagent/subagent-acp) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`subagent-claude-code`](../packages/subagent/subagent-claude-code) | `subagent` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`subagent-codex`](../packages/subagent/subagent-codex) | `subagent` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`subagent`](../packages/subagent/subagent) | -| [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`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-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 4e1c160841..4f88b2f226 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -9,11 +9,11 @@ en: 1387c4505dde2faf zh: 48570fa1c13d6910 /session-persistence-event-catalog/persistence-type-fingerprints: - en: d8542cb8987022e0 - zh: 38e135021cb21f20 + en: a696c43a89d5fbe8 + zh: 6855eb0239b8dcb3 /session-persistence-event-catalog/event-envelope: - en: 7ebb1a2e0dd1f916 - zh: 8946f415dda5c1b8 + en: 689f781d95689e20 + zh: 602f6a7f0835d698 /session-persistence-event-catalog/events: en: f4776ba3d0fd53ce zh: e86769f50a69055a @@ -27,8 +27,8 @@ en: 49891ca9be5ac123 zh: 49891ca9be5ac123 /session-persistence-event-catalog/events/agent-preset/agent-preset-selected-log-only: - en: 0cb4079706a5395b - zh: 9f1a0d8564c54d98 + en: 9eb4e8ec6b503d83 + zh: 6d96288a30d92b81 /session-persistence-event-catalog/events/approval: en: 9d2ec4c4c3664b9f zh: 9d2ec4c4c3664b9f @@ -45,11 +45,11 @@ en: 44426b6cd0dc01cf zh: 44426b6cd0dc01cf /session-persistence-event-catalog/events/assistant/assistant-attempt-log-only: - en: 6baf474f8c4a905e - zh: b92f1c041441ba98 + en: 5b002a8dcefbfc71 + zh: e44f53ed4bf1f929 /session-persistence-event-catalog/events/assistant/assistant-message-surface: - en: 70721b64d98f892e - zh: ad5091727753c698 + en: a0f8289f97125e4f + zh: 1ff54770086eb016 /session-persistence-event-catalog/events/command: en: 2cecb5b0ee955732 zh: 2cecb5b0ee955732 @@ -84,8 +84,8 @@ en: 3344204b1858edb1 zh: 3344204b1858edb1 /session-persistence-event-catalog/events/developer/developer-message-surface: - en: d1ef5d25c01a725e - zh: eea5a11e0c4516ee + en: cd036bde54c62690 + zh: 5a21179b33551ed5 /session-persistence-event-catalog/events/feedback: en: f50dbac6867fa64d zh: f50dbac6867fa64d @@ -119,6 +119,15 @@ /session-persistence-event-catalog/events/image/image-offload-log-only: en: 5b3bba4fc4261208 zh: 6d5f536c3ca92710 +/session-persistence-event-catalog/events/job: + en: 941358a5fef6a5b4 + zh: 941358a5fef6a5b4 +/session-persistence-event-catalog/events/job/job-registered-log-only: + en: 37ab7f962b199555 + zh: af05a3274adbe530 +/session-persistence-event-catalog/events/job/job-settled-log-only: + en: dde416e1c0d32dfb + zh: fa08197cad8acb9d /session-persistence-event-catalog/events/llm: en: 8a5c09e48ec0a6ae zh: 8a5c09e48ec0a6ae @@ -132,8 +141,8 @@ en: 9edf4ef31e60e880 zh: 9edf4ef31e60e880 /session-persistence-event-catalog/events/model/model-selection-log-only: - en: ea963e9ec025c667 - zh: f6eea77d22442cd8 + en: 0d9e20c2357ae7ac + zh: 23401d59e97d6011 /session-persistence-event-catalog/events/permission: en: 19917bc5438e60af zh: 19917bc5438e60af @@ -150,11 +159,11 @@ en: a8df82440ebdf5f8 zh: a8df82440ebdf5f8 /session-persistence-event-catalog/events/request/request-context-log-only: - en: e1a46fbd7273e666 - zh: e3390b27a540e353 + en: 799784e7cd019889 + zh: db6c59d673b4acff /session-persistence-event-catalog/events/request/request-header-log-only: - en: 897d315d9a0489d2 - zh: 98726636aa3c4ae1 + en: fb095eddad22b5f5 + zh: 49f1a3ac0a9ec57c /session-persistence-event-catalog/events/sandbox: en: ec841ab8439335b0 zh: ec841ab8439335b0 @@ -171,14 +180,14 @@ en: a1ac8f2660a4f61e zh: a1ac8f2660a4f61e /session-persistence-event-catalog/events/session/session-end-seed-log-only: - en: 53b95ea8a0fd3bd5 - zh: c5a0d2f068637efa + en: 70c3c0d6614f2d30 + zh: bb4dd52f5bcf351c /session-persistence-event-catalog/events/session/session-title-log-only: en: 6c6a27578dff5828 zh: 9a5add2bc0df2d0a /session-persistence-event-catalog/events/session/session-title-llm-request-log-only: - en: 5eb108772a8498c9 - zh: 1fbc45e377084bae + en: 50d9e29d3d2bfe52 + zh: 3ff1d959cf7776b9 /session-persistence-event-catalog/events/session-log-deepseek: en: 7b827672c80aecdd zh: 7b827672c80aecdd @@ -189,11 +198,11 @@ en: bd0dcbbc352b771a zh: bd0dcbbc352b771a /session-persistence-event-catalog/events/step/step-end-log-only: - en: e24b5dd8b2b806aa - zh: a02bc5c3d7b07168 + en: 2de61d81867d485c + zh: 21025a396ef7c88f /session-persistence-event-catalog/events/step/step-start-log-only: - en: 71b35276d634c512 - zh: b1b7f063cffac1de + en: cb8f05bf3b59adef + zh: 686b33b689c4a841 /session-persistence-event-catalog/events/subagent: en: 9630752e97ddbfbc zh: 9630752e97ddbfbc @@ -210,23 +219,23 @@ en: 8cac41d2fb575975 zh: 8cac41d2fb575975 /session-persistence-event-catalog/events/system/system-message-surface: - en: 59abc66d6a56e861 - zh: cc2d67c879079151 + en: 92b1f61ac638da71 + zh: 2d60ba9d38abda05 /session-persistence-event-catalog/events/team: en: a640800a38b3c874 zh: a640800a38b3c874 /session-persistence-event-catalog/events/team/team-member-log-only: - en: 7f6c8a45dc35091f - zh: 47060fd1344a5ea3 + en: a2fe5b8582ef5f46 + zh: 42bfffcde3f3d886 /session-persistence-event-catalog/events/team/team-message-delivered-log-only: - en: 951c0d2655ede111 - zh: 05d5c77fc656b918 + en: 4a716b14e33eab18 + zh: dcde26e4dc40b62e /session-persistence-event-catalog/events/team/team-message-queued-log-only: - en: 02ac91734cd032da - zh: 91fae1059caa59b4 + en: 05bf873244099da5 + zh: 8a0b62912087f4aa /session-persistence-event-catalog/events/team/team-task-log-only: - en: ee2efdbe3f7b8978 - zh: a3829e506d9e81d1 + en: 5ffeb64225feda2a + zh: d58129e189a726fb /session-persistence-event-catalog/events/todo: en: 308d4bb4b6b96e35 zh: 308d4bb4b6b96e35 @@ -237,8 +246,8 @@ en: 28a24430609494b2 zh: 28a24430609494b2 /session-persistence-event-catalog/events/tool/tool-call-log-only: - en: 96cc0c05d3a2d01b - zh: f6f86d5bd29db6a5 + en: 03f36237cbf9e267 + zh: 83fe2e69bbbfd3c1 /session-persistence-event-catalog/events/tool/tool-ptc-dispatch-log-only: en: 3d5d72b99e702a8c zh: e8c3b82cd5361c4a @@ -246,8 +255,8 @@ en: de38cf70d81ad7c3 zh: dd0a2a8be099271d /session-persistence-event-catalog/events/tool/tool-result-surface: - en: 2857bd718f6e7264 - zh: 61aac43cff6451b6 + en: 283e3cf1fdd57f05 + zh: 0bc3a15ae4f47aaf /session-persistence-event-catalog/events/tool-workflow: en: 1eac7deac6af15f3 zh: 1eac7deac6af15f3 @@ -267,17 +276,17 @@ en: d7e8c999a0851a0c zh: d7e8c999a0851a0c /session-persistence-event-catalog/events/turn/turn-end-log-only: - en: db0b56bc4d2959d1 - zh: 4587a42273da90d0 + en: ce5ef6916c95ea16 + zh: 9652c8d40b5dfb6d /session-persistence-event-catalog/events/turn/turn-start-log-only: - en: 09ef649bb3c92015 - zh: 69244b81c8c1f614 + en: 999ffb7ad4e600aa + zh: a8720bf8578431ae /session-persistence-event-catalog/events/user: en: d864a88c03e8971c zh: d864a88c03e8971c /session-persistence-event-catalog/events/user/user-message-surface: - en: 6d302c03787ebb1f - zh: d53f597a8b651309 + en: 55128b5458eae10f + zh: 4198ea89093484f6 /session-persistence-event-catalog/events/web: en: d278748103cf1640 zh: d278748103cf1640 @@ -540,8 +549,8 @@ en: 028791baa24a6a0a zh: 028791baa24a6a0a /session-persistence-event-catalog/resolved-persistence-types/in-history: - en: 7ee8e3e9b3947c22 - zh: 035ceca2d5031800 + en: 8bda2ac68f50953b + zh: 190a69ddd097c445 /session-persistence-event-catalog/resolved-persistence-types/in-progress: en: 61de2b0c9de8c15b zh: 61de2b0c9de8c15b @@ -555,8 +564,20 @@ en: 759b0bea643a3f2b zh: 759b0bea643a3f2b /session-persistence-event-catalog/resolved-persistence-types/interrupted: - en: 69a7a30a4e43ff35 - zh: 69a7a30a4e43ff35 + en: 9f4bd316342f65ef + zh: 9f4bd316342f65ef +/session-persistence-event-catalog/resolved-persistence-types/job-registered: + en: 19aa7833c2187c48 + zh: 19aa7833c2187c48 +/session-persistence-event-catalog/resolved-persistence-types/job-settled: + en: 0a0b96a87bf8ad25 + zh: 0a0b96a87bf8ad25 +/session-persistence-event-catalog/resolved-persistence-types/kill: + en: 0401f4463ce25ee0 + zh: 0401f4463ce25ee0 +/session-persistence-event-catalog/resolved-persistence-types/killed: + en: cf74df062715315c + zh: cf74df062715315c /session-persistence-event-catalog/resolved-persistence-types/legacy: en: 1fc6c6420d6eb307 zh: 1fc6c6420d6eb307 @@ -600,8 +621,11 @@ en: afd1613dd3d4da80 zh: afd1613dd3d4da80 /session-persistence-event-catalog/resolved-persistence-types/other: - en: 588a8f46adda6707 - zh: 588a8f46adda6707 + en: d4ae27f96b0df108 + zh: d4ae27f96b0df108 +/session-persistence-event-catalog/resolved-persistence-types/owner: + en: 5ae91798cfeb7895 + zh: 5ae91798cfeb7895 /session-persistence-event-catalog/resolved-persistence-types/parent: en: 83af3e4fc9243790 zh: 83af3e4fc9243790 @@ -624,8 +648,11 @@ en: de774562ec890a6c zh: de774562ec890a6c /session-persistence-event-catalog/resolved-persistence-types/positive: - en: 2a01e347d9604ac6 - zh: 2a01e347d9604ac6 + en: e048b2b8f8165011 + zh: e048b2b8f8165011 +/session-persistence-event-catalog/resolved-persistence-types/producer: + en: b829f105842b826c + zh: b829f105842b826c /session-persistence-event-catalog/resolved-persistence-types/product-interaction: en: 05fe435810456683 zh: 05fe435810456683 @@ -783,8 +810,11 @@ en: d683235390472024 zh: d683235390472024 /session-persistence-event-catalog/resolved-persistence-types/team-task: - en: f8a5fe2380e1a4c4 - zh: f8a5fe2380e1a4c4 + en: 7aa9286372341561 + zh: 7aa9286372341561 +/session-persistence-event-catalog/resolved-persistence-types/teardown: + en: 301cd78f24fe13c5 + zh: 301cd78f24fe13c5 /session-persistence-event-catalog/resolved-persistence-types/text: en: 20b696e15c9cf906 zh: 20b696e15c9cf906 @@ -948,8 +978,8 @@ en: e393deed01de3665 zh: 0fa98ad93c22ce79 /session-persistence-event-catalog/resolved-persistence-types/commandsource: - en: 86c7e2b4ae099661 - zh: 2ffe1bd3f25b96fd + en: 53feeeb70547e7df + zh: 99d9e901d9b4afe5 /session-persistence-event-catalog/resolved-persistence-types/compactioncheckpointsource: en: 87f2aaf2b23a5249 zh: 3d6c5ed6603bee31 @@ -972,14 +1002,14 @@ en: 586743dfeab78c55 zh: 26ccef4a02dd7a58 /session-persistence-event-catalog/resolved-persistence-types/deepseeksearchllmrequest: - en: 8bb149f81f7c2544 - zh: 7e9c410f530b7c82 + en: db71ecccc1e5409e + zh: 7b55744e022dc102 /session-persistence-event-catalog/resolved-persistence-types/developermessage: - en: da88473da1299be0 - zh: fe756703e34fcc42 + en: 997b5db27df00446 + zh: 07e5197ddd7bd59b /session-persistence-event-catalog/resolved-persistence-types/epochheader: - en: d31020fa1fda6fa4 - zh: 77984c4bf09443fb + en: 3786becd1ca9c697 + zh: ea8e6fd4f6590567 /session-persistence-event-catalog/resolved-persistence-types/everyscheduledispatchchange: en: 54c487394ce0db1d zh: 48d7c9affbe841cb @@ -1041,8 +1071,20 @@ en: a3087ab7bebe9371 zh: abf6afc2f9f5b692 /session-persistence-event-catalog/resolved-persistence-types/inboxtarget: - en: 49855060f429f597 - zh: 19d1db4ab892ba44 + en: 938113c1b01efad1 + zh: d6829dbe979e6819 +/session-persistence-event-catalog/resolved-persistence-types/jobregistereddata: + en: f604eebb973fe2cf + zh: 0c0aba1e17ecf66e +/session-persistence-event-catalog/resolved-persistence-types/jobsettlecause: + en: 748a4269d86e007a + zh: 4ce04c4451bdcfe8 +/session-persistence-event-catalog/resolved-persistence-types/jobsettleddata: + en: fc8caf270a7581f7 + zh: b467e1d4191106eb +/session-persistence-event-catalog/resolved-persistence-types/jobtoolcall: + en: 7ffee3cc96604a88 + zh: 026abfab0e46c21a /session-persistence-event-catalog/resolved-persistence-types/jsonvalue: en: c239aa9c90226c35 zh: 3561e77832c7c8b5 @@ -1074,11 +1116,11 @@ en: 6dbe099c62f7c226 zh: 6fd788f63c038c91 /session-persistence-event-catalog/resolved-persistence-types/llmretrystartedeventdata: - en: cc63fb8b8fad7d63 - zh: 2026e3da98cad54e + en: c2d9edd8d9f492b7 + zh: f59c687ac691f7ce /session-persistence-event-catalog/resolved-persistence-types/message: - en: e478c640a9c17a4f - zh: b4c6a4930a3789a1 + en: 594707e4894819a8 + zh: 268c4bfd5c4c28f2 /session-persistence-event-catalog/resolved-persistence-types/messagefeedbackdelete: en: c582953270d4ca44 zh: 966ccfe2e7660a2a @@ -1089,20 +1131,20 @@ en: f58575a1fc96df42 zh: 9f0c6ed9033e5c9d /session-persistence-event-catalog/resolved-persistence-types/messagefeedbackrating: - en: 46f4cbb41e7c053a - zh: 511e10d1be567bc5 + en: 674296d54c1914d0 + zh: 3d71ab319514be25 /session-persistence-event-catalog/resolved-persistence-types/messagesource: - en: c4ed18665fbc1e15 - zh: 6db2b051fc329408 + en: 3fab179fe8d58c31 + zh: 5328c9161ff908a9 /session-persistence-event-catalog/resolved-persistence-types/message~2: - en: 2c79aaf7cec7d9d6 - zh: 1403dd3cf9ed4a82 + en: 8bd12543fcdcda5f + zh: d4c6b17083948856 /session-persistence-event-catalog/resolved-persistence-types/modelmessagesource: en: 3b677f021d7dd4d3 zh: 2a875742b22879a2 /session-persistence-event-catalog/resolved-persistence-types/modelselection: - en: 771e9ab3e64076bc - zh: 30d5095a93549d55 + en: 6d66ffc1b393f2f2 + zh: ef6cb30b71f287e7 /session-persistence-event-catalog/resolved-persistence-types/oneshotscheduledispatchchange: en: a3300babe57b6b67 zh: 4aaf06a149b399c3 @@ -1110,14 +1152,17 @@ en: 9ba0cfd5ee9d6a38 zh: 1414fd7468c42651 /session-persistence-event-catalog/resolved-persistence-types/optionalsessionseq: - en: 7baa520fa984480e - zh: 6f809a83a720416d + en: 6d4afd6c237b50fd + zh: ec07f774c853f27b /session-persistence-event-catalog/resolved-persistence-types/presentedfile: en: 3e36e2f29ff1b506 zh: 3dcc1a1dced59d9f /session-persistence-event-catalog/resolved-persistence-types/presentedfile~2: - en: 807fde1cf42ddef3 - zh: 2ea131667b990d1e + en: bb11552744e477b8 + zh: afb881f3ebf97e68 +/session-persistence-event-catalog/resolved-persistence-types/principal: + en: d1e45e03f161dc7c + zh: 4f80af59ca4967c5 /session-persistence-event-catalog/resolved-persistence-types/ptcdispatcheventdata: en: 81e66c5a07e17dd6 zh: 0ecf3cfceba14d2b @@ -1128,14 +1173,14 @@ en: 07e04c3e336f880f zh: 6f8986ede9994fa1 /session-persistence-event-catalog/resolved-persistence-types/replayenvelope: - en: 9a80b6f5eb08eaea - zh: 061c632b8f3e4d87 + en: 3460f0c910a247fd + zh: 3990587ab01a1907 /session-persistence-event-catalog/resolved-persistence-types/requestcontext: - en: cc8bb7075d546941 - zh: 77209abf30744be0 + en: b1ade5ed2c42b1ad + zh: f1a6126bec25657b /session-persistence-event-catalog/resolved-persistence-types/requestheaderreason: - en: 93c4403f94ecdc14 - zh: 2b2eb0c400881d71 + en: 0db3aa2b122a4454 + zh: 15b6cfd8896935b8 /session-persistence-event-catalog/resolved-persistence-types/sandboxmode: en: c9fa5343ea99733b zh: d6de41351c57a73f @@ -1149,17 +1194,17 @@ en: 35c0b15c285d045e zh: 8ccce6ea60dd5742 /session-persistence-event-catalog/resolved-persistence-types/sessionheader: - en: 0f60d736cd9d6c94 - zh: 205b8833a4efc5e5 + en: 0536dab0d2eed6ad + zh: 54396338c9917818 /session-persistence-event-catalog/resolved-persistence-types/sessionreferencesource: en: 9a54c4478ad3b620 zh: 02c4c1fd7e252770 /session-persistence-event-catalog/resolved-persistence-types/sessiontitleeventdata: - en: 4ff17eae0b30056d - zh: 6642afbaa87da3ab + en: bf7325029c9338d6 + zh: e5f98271511e5318 /session-persistence-event-catalog/resolved-persistence-types/sessiontitlellmrequesteventdata: - en: 390c1daad2342ce8 - zh: 07ce68854dce8ea4 + en: 89dcb9a9b957c126 + zh: 132aeb7dfd435290 /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity: en: 9531468264499498 zh: 9da23c0ad2776563 @@ -1176,8 +1221,8 @@ en: ecc15ebadb77afdf zh: 97ac27d6a4175f6f /session-persistence-event-catalog/resolved-persistence-types/streamchunk: - en: 0d571899222eb04f - zh: de28c6d67d1763c1 + en: 12fe93a89508739b + zh: 03306c0f7b124f0d /session-persistence-event-catalog/resolved-persistence-types/subagentcatalogevent: en: 725539dcd5c335ed zh: 5ca08d3667f84ff9 @@ -1188,8 +1233,8 @@ en: d34acab659e74957 zh: 25cabc6c9fb44a7e /session-persistence-event-catalog/resolved-persistence-types/surfaceop: - en: 4f3349f21317ba18 - zh: 508c26670085953a + en: 95f8ef2fb8a7c154 + zh: 04cdad161fb88cc3 /session-persistence-event-catalog/resolved-persistence-types/systemmessage: en: 94876079d6696df9 zh: d25c7ad9f5054eb7 @@ -1197,23 +1242,23 @@ en: a3eabd0e9fc565dd zh: fa763aefdbc1bdb8 /session-persistence-event-catalog/resolved-persistence-types/teammemberphase: - en: 5457d6872347310b - zh: e0d5946902c3e933 + en: 2bf8f06fe328ab33 + zh: ded602f18e0deadf /session-persistence-event-catalog/resolved-persistence-types/teammembersnapshot: - en: f6ee72fe168139ff - zh: d28586070ab7b118 + en: 8a37845006830548 + zh: b8e7caf6189b92df /session-persistence-event-catalog/resolved-persistence-types/teammessagesnapshot: - en: 31fb7e4f07b49012 - zh: 15fd933a217dadee + en: 9b94faac43ba068f + zh: a83582be6a6a3c1a /session-persistence-event-catalog/resolved-persistence-types/teammessagesource: - en: 11bec13073c76f30 - zh: e90deecb47471c74 + en: 269f0a4fcbea1c0c + zh: 5f2c50c03c951995 /session-persistence-event-catalog/resolved-persistence-types/teamtasksnapshot: - en: 336a17d99a56859f - zh: 51c252b4f4add812 + en: cfa8230ef5d661b2 + zh: cb40ce86d6778f09 /session-persistence-event-catalog/resolved-persistence-types/teamtaskstatus: - en: 498986242f41c79a - zh: 4d219bd7d9a3ac7c + en: 9bff57038f472770 + zh: 4eec0e793ae16d53 /session-persistence-event-catalog/resolved-persistence-types/textblock: en: c5fcd2cdd37ea387 zh: 9c678fbdea0bf25c @@ -1245,8 +1290,8 @@ en: 2258683c3cfa4ce3 zh: 5663aa76c911761b /session-persistence-event-catalog/resolved-persistence-types/toolschema: - en: 6e1e6ebc7c1c38c8 - zh: e47a3ca80c4c3b71 + en: eb76c5bd050ffccd + zh: cb24780d4b5f79ac /session-persistence-event-catalog/resolved-persistence-types/toolschema~2: en: 12c14727bb7834e2 zh: b0f3c877873c36db @@ -1263,17 +1308,17 @@ en: 54090e169899c573 zh: 530ea8d0d0f8cf68 /session-persistence-event-catalog/resolved-persistence-types/turnendcancelcause: - en: 544292eddeff5faa - zh: 4e36e575a5030fb2 + en: 4dc89c072fe5d0d1 + zh: 4ed2c9e9e8b4f7e2 /session-persistence-event-catalog/resolved-persistence-types/turnendreason: - en: cdf0bbf6399a3677 - zh: f4422bf67b216bae + en: eec92deb07c000fa + zh: 666682b6f3efcfa3 /session-persistence-event-catalog/resolved-persistence-types/usermessage: - en: b1c19f6d8f6f31fc - zh: 3843640f47897934 + en: bd3aedd570ded4d2 + zh: f020d0816d3a6c1a /session-persistence-event-catalog/resolved-persistence-types/usermessage~2: - en: 2ee253b3743ee6a2 - zh: 5ee8b08850d93d8e + en: b99d66ffe277f0bc + zh: eacc9c1f62ae66c1 /session-persistence-event-catalog/resolved-persistence-types/workflowagentoutcome: en: d0a3f9aab18c3de5 zh: 76ac69a835ca4e29 @@ -1293,14 +1338,14 @@ en: bccefcfce00a211f zh: bccefcfce00a211f /session-persistence-event-catalog/resolved-persistence-types/number: - en: 5e7d82a493a1d4d8 - zh: d2d785891dd766fc + en: 0223d7ffb67ac272 + zh: c2a8221caab6d350 /session-persistence-event-catalog/resolved-persistence-types/number~2: - en: 386989934d1bb62e - zh: 69b8bc182a5acbd3 + en: 2786fef560851bb4 + zh: 5d787475356b2606 /session-persistence-event-catalog/resolved-persistence-types/string: - en: 21a0bfa3d2e4d775 - zh: e1d212b7cbc37c35 + en: 009c7ecb8c7d3bb5 + zh: 7f56d672f376b22f /session-persistence-event-catalog/resolved-persistence-types/string~2: en: 0089620bf4638263 zh: 1922bef1713094bb @@ -1329,9 +1374,12 @@ en: ab07ee7c506483d4 zh: 299e31a106d93dfe /session-persistence-event-catalog/resolved-persistence-types/union-3-variants~2: - en: faa507a889e1c476 - zh: b5f13f6f0590152f + en: 5095d352cbd90e21 + zh: e0bfa5c90e3917b6 /session-persistence-event-catalog/resolved-persistence-types/union-3-variants~3: + en: 9e296094df7462ba + zh: e7e3255a3ada9279 +/session-persistence-event-catalog/resolved-persistence-types/union-3-variants~4: en: 5fc89a7ec1cecd78 zh: dc66aa8e4aae1847 /session-persistence-event-catalog/resolved-persistence-types/union-6-variants: @@ -1350,8 +1398,8 @@ en: a3de6a6fe9672c7a zh: a357481e27b3b81f /session-persistence-event-catalog/resolved-persistence-types/agentpreset: - en: b8a0f8aac9708056 - zh: f5f004bd205b41e1 + en: 1afbe8196f161601 + zh: a320a36a8928817c /session-persistence-event-catalog/resolved-persistence-types/allowedmodels: en: 6178321110ceb69d zh: 0a9d94cab9d57487 @@ -1359,8 +1407,8 @@ en: a117573a5d58cb3c zh: d5ad59e17a3a815d /session-persistence-event-catalog/resolved-persistence-types/arguments-callid-name-step: - en: bbb8322870e4695e - zh: dc90a029bf156604 + en: 99e67b046fa9cf40 + zh: 88060ee577d02d20 /session-persistence-event-catalog/resolved-persistence-types/callid-files-turn: en: 5f4d3f66ed86a14d zh: 7c729360fa1279e6 @@ -1392,8 +1440,8 @@ en: a1f188c9058cf621 zh: eb43c0f045fb9afb /session-persistence-event-catalog/resolved-persistence-types/code-name-reason: - en: 5b7790906008fcba - zh: 3d1a6bdb82d82fde + en: 404a76066a59f3c6 + zh: ec9d510bdbac9786 /session-persistence-event-catalog/resolved-persistence-types/commandid-kind-sourceeventseq-text: en: 87b03e1c73d2a326 zh: d7b9f06863cad891 @@ -1434,14 +1482,14 @@ en: 4b7a8793663d3fef zh: 249459c825d330c3 /session-persistence-event-catalog/resolved-persistence-types/endseq-op-startseq: - en: ba27e6f100b73e81 - zh: 82a12774bf5611f8 + en: 318404925fed44c8 + zh: 6cc8b0fcd8d11540 /session-persistence-event-catalog/resolved-persistence-types/error-kind-error: - en: b24398b25f46a94f - zh: 40640447d21ba296 + en: 72572b3d4f2f0c01 + zh: 4c4234325c1713fc /session-persistence-event-catalog/resolved-persistence-types/error-message-meta-step: - en: 423077da59c080a5 - zh: ea8a92a786603279 + en: 8cc3e4d05fa25012 + zh: 2c2d1c1936dd99ce /session-persistence-event-catalog/resolved-persistence-types/failure-kind-aborted: en: 349cd90f2598fd12 zh: 1eda02d520ad5d76 @@ -1449,11 +1497,11 @@ en: 51af619ed8532a43 zh: a5ad878c63d0e046 /session-persistence-event-catalog/resolved-persistence-types/header-reason-startsseries: - en: 562fcce1a6c17ade - zh: 15828c9bf4dcbe6e + en: fe0f6163c5202da6 + zh: 98feea5f03b725e1 /session-persistence-event-catalog/resolved-persistence-types/headerseq-message-step-turn: - en: 884dda8acdf28a83 - zh: 53ef06336629743c + en: 05903e55f510fd79 + zh: 90a17b10f682abcb /session-persistence-event-catalog/resolved-persistence-types/height-width: en: a5df50710083ac25 zh: aad3ccf6f6de70e4 @@ -1470,29 +1518,29 @@ en: 41f73c58a77dfa28 zh: af77f4aee3cb4a40 /session-persistence-event-catalog/resolved-persistence-types/inherited: - en: f46de4c8d413b567 - zh: af0283688492ac43 + en: 8a9199b1784c70f5 + zh: 76c98bc74686fda0 /session-persistence-event-catalog/resolved-persistence-types/inserted-outcome-removedcount-start: - en: 62e1cb96abf41fd5 - zh: c24c03766f6790d8 + en: e77d5d524dd8b4ea + zh: 4dac28dda78a510f /session-persistence-event-catalog/resolved-persistence-types/interrupted-message-step-stream: - en: f460572284c92755 - zh: bae7561ce887b040 + en: ec10cd8e9c202a81 + zh: e08f859bcb13f0d4 /session-persistence-event-catalog/resolved-persistence-types/kind-aborted-reason: - en: c7755cbd343d67ee - zh: e00a7477cd664cb5 + en: 48424cbed3fbc269 + zh: 2ce88c04ad002104 /session-persistence-event-catalog/resolved-persistence-types/kind-blocked: - en: 46465e6fa6292ec3 - zh: b8ed143600bf51d2 + en: 2fad818b19823c48 + zh: a6b33dee21c3fdc9 /session-persistence-event-catalog/resolved-persistence-types/kind-completed: - en: 2f3ffb879c568b64 - zh: ffc7d0f2b64494fc + en: e8f76b61a39ebeb0 + zh: e61a304be00b4490 /session-persistence-event-catalog/resolved-persistence-types/kind-cordis-host-runner: en: fb7b8207a6ef3b81 zh: 9d6f112181d90701 /session-persistence-event-catalog/resolved-persistence-types/kind-disposed: - en: 70d5bdb48ced0ea9 - zh: fc950fee2c166ff0 + en: e3c9527803bc6de3 + zh: 375c82ce2ac5282b /session-persistence-event-catalog/resolved-persistence-types/kind-dsh-session-title-llm: en: 428529e5dedc761d zh: 3ca0b54c9c521ea0 @@ -1518,11 +1566,11 @@ en: 78e34e6d0d70339e zh: 072127e40cfb9686 /session-persistence-event-catalog/resolved-persistence-types/kind-forked: - en: 4b299abd1cf27c78 - zh: dce75fa13b690720 + en: dc750041126fe853 + zh: 736505cd1e57db62 /session-persistence-event-catalog/resolved-persistence-types/kind-hook: - en: 965c99cedd28afdf - zh: 15d8f9991883bd5c + en: 78278a869370695f + zh: 6cdc47f1876f3b23 /session-persistence-event-catalog/resolved-persistence-types/kind-hooks-claude-code: en: 5eb383a67f11ac4d zh: 1943747cb4995dbc @@ -1566,14 +1614,14 @@ en: a8a338be3b91008f zh: c7632c42c869c2f6 /session-persistence-event-catalog/resolved-persistence-types/kind-interrupted: - en: 9e87f168b322c617 - zh: bf81e0aa69f46c08 + en: b2dea1e08facaa40 + zh: 71c9b8d4e3d1d2b8 /session-persistence-event-catalog/resolved-persistence-types/kind-legacy: - en: 7c000bffbf0c567e - zh: b3210306a125820b + en: c6f68741f8631d4f + zh: 090b58f2b86c02d0 /session-persistence-event-catalog/resolved-persistence-types/kind-max-tokens: - en: 20433ac79d2cf7a7 - zh: 8907d87c5179fca8 + en: 4746f91df74cc1dd + zh: d0427e9191359299 /session-persistence-event-catalog/resolved-persistence-types/kind-model-selection: en: a5165486dca91116 zh: b7051ca8167806ef @@ -1596,8 +1644,8 @@ en: 509f9a91aedb2da1 zh: db1071678bfb98d1 /session-persistence-event-catalog/resolved-persistence-types/kind-parent: - en: 96dec53b9a43815a - zh: 4163af6bc636ecc9 + en: 7a3ac2238405913d + zh: b249a4d6d0508d40 /session-persistence-event-catalog/resolved-persistence-types/kind-plan-mode: en: 9758304800b717df zh: dccf14f3a5d0d861 @@ -1623,8 +1671,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 @@ -1779,11 +1827,11 @@ en: 08be4349548406a9 zh: 8e7cf9966198ef78 /session-persistence-event-catalog/resolved-persistence-types/kind-tool-registry: - en: 79db83dd2c430faf - zh: 173f568241f5ce86 + en: 809a23c25ded8497 + zh: e9cd23e281f8d31f /session-persistence-event-catalog/resolved-persistence-types/kind-user: - en: aacb77f1cead58ba - zh: e6ce9dac4bdd07b7 + en: 9b6318ab4d7eba12 + zh: f475439ef40b2681 /session-persistence-event-catalog/resolved-persistence-types/kind-user-approval: en: a52d2dfbaf844127 zh: 4c5306ca40f20873 @@ -1818,17 +1866,17 @@ en: afedf4a31a67eb14 zh: 98d3bc882f2b61c3 /session-persistence-event-catalog/resolved-persistence-types/member-teamid-version: - en: a0a3339a63f2bc4f - zh: fd6512ef11c36bde + en: 82b0989dad6bbfc0 + zh: 0789b63f1d59b2ed /session-persistence-event-catalog/resolved-persistence-types/message-step-turn: - en: 7cc30865737643f2 - zh: 512c6c81ed10a9b6 + en: dcaa676f106cfdfd + zh: e3941fea97c943fb /session-persistence-event-catalog/resolved-persistence-types/message-teamid-version: - en: 7960b689af537cf6 - zh: e5b044052e009a98 + en: f778769acb264dd5 + zh: eba9b81d04e9f57b /session-persistence-event-catalog/resolved-persistence-types/messageid-targetid-teamid-version: - en: 22665480d164fdc7 - zh: aa2c96be4a4fe468 + en: 91a948ede28ebcb5 + zh: 8a2b0ac6bb68a09e /session-persistence-event-catalog/resolved-persistence-types/mode-source: en: 3028b222670ce5ad zh: cae4c9437e560d61 @@ -1839,8 +1887,8 @@ en: f60ecbd156c6f063 zh: c9149679bbacff21 /session-persistence-event-catalog/resolved-persistence-types/reason-turn: - en: 168c2ac7db7371b4 - zh: f851223c95582eb9 + en: a4ba4d0ee1396381 + zh: b6f595f8a696d512 /session-persistence-event-catalog/resolved-persistence-types/role-user: en: 04b34b8ffe7e7764 zh: a792d5371516fd9d @@ -1851,29 +1899,29 @@ en: 7a2ab7b62244f43b zh: 1084e3f8876feebc /session-persistence-event-catalog/resolved-persistence-types/step-stream-turn: - en: 9d436c515695f35d - zh: 247a7c0bb24337d3 + en: 84004f9b9c6bf24c + zh: ce1abe27b0bc43e2 /session-persistence-event-catalog/resolved-persistence-types/step-turn: - en: 6c9cd916657e052e - zh: ed60789608cee181 + en: 989fad01cdd866ba + zh: 4f08dafda68f0c77 /session-persistence-event-catalog/resolved-persistence-types/targets: en: 5360af614fe753e3 zh: 96427c489cc71de6 /session-persistence-event-catalog/resolved-persistence-types/task-teamid-version: - en: bc6a4d5b483d4845 - zh: 839703c23f628d6b + en: a2fcd46e54b14120 + zh: d9a6e0e50bbff9ad /session-persistence-event-catalog/resolved-persistence-types/todos: en: 06e6c1837e2b5d50 zh: 37cebfe3e41294ec /session-persistence-event-catalog/resolved-persistence-types/turn: - en: a79b2ab16b9ed215 - zh: 764cd1400ee8db63 + en: c58b89cec274f956 + zh: 056a29ed1ada9690 /session-persistence-event-catalog/resolved-persistence-types/type-agent-preset-selected: - en: 52112a8633ba49e4 - zh: 95318f8c8b2d19ee + en: c8c731ee23bed85a + zh: f4ffc80f7828701d /session-persistence-event-catalog/resolved-persistence-types/type-agent-inbox-spliced: - en: 35219c983f8168c9 - zh: 5bdf2bc555cc5e1a + en: 62dfe9447efaceb1 + zh: 076454de19b5d7d7 /session-persistence-event-catalog/resolved-persistence-types/type-approval-asked: en: 9c77f18b0dad22f0 zh: 8894cf2878fe90db @@ -1890,11 +1938,11 @@ en: bb507524bcc39c53 zh: 8314898562437473 /session-persistence-event-catalog/resolved-persistence-types/type-block-end: - en: 8c5a05fa6adf3e70 - zh: 66768b25d6fb3e07 + en: c5acb63761d0cbb8 + zh: 6caad01b80c6eb0d /session-persistence-event-catalog/resolved-persistence-types/type-block-start: - en: 5caed426cab416ee - zh: 86f47f90f8c440f2 + en: c52a22b7878bde2f + zh: 42f3fae52cf09ebb /session-persistence-event-catalog/resolved-persistence-types/type-chunk: en: 2186ede3e9917aea zh: 0cfef64045dce95b @@ -1917,11 +1965,11 @@ en: ba73fb10b7e2ffc9 zh: 8d5c97e63e5f16da /session-persistence-event-catalog/resolved-persistence-types/type-deliverables-presented: - en: d69ad6b38df667d3 - zh: 72fb317a507a0b3b + en: a4d9eab2928e9b30 + zh: b36702c866518273 /session-persistence-event-catalog/resolved-persistence-types/type-developer-message: - en: 1d16681802c679ce - zh: 01c03831212dd260 + en: ed8c78af3a89ba8f + zh: 4f859687aa13c1a3 /session-persistence-event-catalog/resolved-persistence-types/type-feedback-message-delete: en: 204561e2311db97e zh: 77264396bd5e25c4 @@ -1932,8 +1980,8 @@ en: 14e4b48d856bcf57 zh: 72ba176535dc7f3f /session-persistence-event-catalog/resolved-persistence-types/type-finish: - en: 21627e72a24990ff - zh: d71375de325ee9f8 + en: 359385a004565fda + zh: 313f78d5906a3128 /session-persistence-event-catalog/resolved-persistence-types/type-goal-change: en: aad2516b62d3ee83 zh: e7204c4dc4e8e408 @@ -1944,8 +1992,14 @@ en: 8b523e0be5327519 zh: 86ec891087b8bf24 /session-persistence-event-catalog/resolved-persistence-types/type-image-offload: - en: 06230b6290fa9826 - zh: 11930bfa355b70fa + en: bf512693267d4262 + zh: 805710898b4e913a +/session-persistence-event-catalog/resolved-persistence-types/type-job-registered: + en: 734d3bb283cc6f66 + zh: 75bcb55f71673e34 +/session-persistence-event-catalog/resolved-persistence-types/type-job-settled: + en: 742c3a1543414ecb + zh: e256fb92d72b8184 /session-persistence-event-catalog/resolved-persistence-types/type-llm-retry: en: 6d026baeac30a0f1 zh: 55131683e3d5ed27 @@ -1965,8 +2019,8 @@ en: 34e5591d75322649 zh: a216839f305c9796 /session-persistence-event-catalog/resolved-persistence-types/type-reasoning-delta: - en: a18feb76be195fa0 - zh: 3db7147ee4c5c963 + en: 8b5e884e0c0ab11b + zh: 3b291d80028b6583 /session-persistence-event-catalog/resolved-persistence-types/type-request-context: en: f8addb1a01da9ca1 zh: 4ef11ebddd302c05 @@ -1986,11 +2040,11 @@ en: acf7e21e4d21ebff zh: fb83a853634d204a /session-persistence-event-catalog/resolved-persistence-types/type-session-title: - en: 203f5661ca1850b1 - zh: b3d9ec1019188df4 + en: b99fbacda0db1abd + zh: 9e75ce6b1d174d48 /session-persistence-event-catalog/resolved-persistence-types/type-session-title-llm-request: - en: 246920f06c3a2175 - zh: 56deee3b86499174 + en: 7ba30b98d8e3f653 + zh: ca68b01ab4b6ba3d /session-persistence-event-catalog/resolved-persistence-types/type-step-end: en: 7fc233c4a569dae2 zh: bc2b3fed4a397c00 @@ -2025,8 +2079,8 @@ en: 1484738718de5312 zh: 3e6fbe9c64068225 /session-persistence-event-catalog/resolved-persistence-types/type-text-delta: - en: 47ae2d57be710450 - zh: b072753349ac505e + en: bac4775a1255bbbb + zh: 834b81d203e21b7c /session-persistence-event-catalog/resolved-persistence-types/type-todo-write: en: 2fa7ba77598a95b4 zh: 50972b51d77e9155 @@ -2034,8 +2088,8 @@ en: 32f732b97739e4d2 zh: f288e48e356969c0 /session-persistence-event-catalog/resolved-persistence-types/type-tool-call-delta: - en: 1df89f427ccac815 - zh: 1bec3d025ea1f7e3 + en: a172400ce8d6dbe7 + zh: 1d6cba18564d0230 /session-persistence-event-catalog/resolved-persistence-types/type-tool-workflow-agent-end: en: 8eb5e1eb95722bc7 zh: 8dd5980029600648 @@ -2067,11 +2121,11 @@ en: 1b045de96172be4b zh: 8a15c6f35b576b37 /session-persistence-event-catalog/resolved-persistence-types/type-usage: - en: fa542ccb91698e56 - zh: 7b725c813d69588d + en: 1eabcbd128f86602 + zh: c6a2067a05f4e692 /session-persistence-event-catalog/resolved-persistence-types/type-user-message: - en: fb49c375aec5952c - zh: 19b80920c1068b86 + en: afab869c0592b46c + zh: f15874a1e728ab0d /session-persistence-event-catalog/resolved-persistence-types/type-web-deepseek-search-llm-request: en: f109997e295af37d zh: b2dcfd599f73b61c diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index e20df04e5d..67f829b9d8 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -23,7 +23,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `JsonlHeaderLine` | header | `18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f` | [`HeaderLine`](#persistence-type-sha256-18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f) | | `SessionEventEnvelope` | envelope | `5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc` | [`union (3 variants)`](#persistence-type-sha256-5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc) | | `event:agent-preset/selected` | event | `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | [`{ type: "agent-preset/selected" }`](#persistence-type-sha256-a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b) | -| `event:agent/inbox/spliced` | event | `9a36727716d0e73f681f3b725e7f28f89417c68174c8af0ff2b1ef52b08326a0` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-9a36727716d0e73f681f3b725e7f28f89417c68174c8af0ff2b1ef52b08326a0) | +| `event:agent/inbox/spliced` | event | `0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034) | | `event:approval/asked` | event | `3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1` | [`{ type: "approval/asked" }`](#persistence-type-sha256-3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1) | | `event:approval/decided` | event | `bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3` | [`{ type: "approval/decided" }`](#persistence-type-sha256-bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3) | | `event:approval/policy` | event | `26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78` | [`{ type: "approval/policy" }`](#persistence-type-sha256-26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78) | @@ -36,7 +36,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:compaction/start` | event | `db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965` | [`{ type: "compaction/start" }`](#persistence-type-sha256-db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965) | | `event:compaction/summary` | event | `e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602` | [`{ type: "compaction/summary" }`](#persistence-type-sha256-e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602) | | `event:deliverables/presented` | event | `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | [`{ type: "deliverables/presented" }`](#persistence-type-sha256-13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176) | -| `event:developer/message` | event | `ba5b10ea77d68f4a29439a9bd2a14f6a560acf55731749d57237757cc72fbc06` | [`{ type: "developer/message" }`](#persistence-type-sha256-ba5b10ea77d68f4a29439a9bd2a14f6a560acf55731749d57237757cc72fbc06) | +| `event:developer/message` | event | `97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c` | [`{ type: "developer/message" }`](#persistence-type-sha256-97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c) | | `event:feedback/message-delete` | event | `3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796` | [`{ type: "feedback/message-delete" }`](#persistence-type-sha256-3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796) | | `event:feedback/message-put` | event | `b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf` | [`{ type: "feedback/message-put" }`](#persistence-type-sha256-b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf) | | `event:feedback/record` | event | `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` | [`{ type: "feedback/record" }`](#persistence-type-sha256-b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8) | @@ -44,6 +44,8 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:hook/invoked` | event | `8a6e1ec9e8db346b0e02f027db73c07a94f067a26d40c1aef1abd09c47ce7ba0` | [`{ type: "hook/invoked" }`](#persistence-type-sha256-8a6e1ec9e8db346b0e02f027db73c07a94f067a26d40c1aef1abd09c47ce7ba0) | | `event:hook/result` | event | `e75916628f3f10c2d50658bd143052a46285fbf1a9a700ba54947614603d26b4` | [`{ type: "hook/result" }`](#persistence-type-sha256-e75916628f3f10c2d50658bd143052a46285fbf1a9a700ba54947614603d26b4) | | `event:image/offload` | event | `b222069eea2d768065161c1147b1f2c78c1b54328c84b3586ae5c8f91b8ed35e` | [`{ type: "image/offload" }`](#persistence-type-sha256-b222069eea2d768065161c1147b1f2c78c1b54328c84b3586ae5c8f91b8ed35e) | +| `event:job/registered` | event | `f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1` | [`{ type: "job/registered" }`](#persistence-type-sha256-f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1) | +| `event:job/settled` | event | `edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf` | [`{ type: "job/settled" }`](#persistence-type-sha256-edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf) | | `event:llm/retry` | event | `525254db03b1d1e6b74cf55aced52817568331ac1f96c0818728910b6692e336` | [`{ type: "llm/retry" }`](#persistence-type-sha256-525254db03b1d1e6b74cf55aced52817568331ac1f96c0818728910b6692e336) | | `event:llm/retry-started` | event | `48e5c9861f16ac07e78cb7b5ae9dabdf7bb85c58baed5a51b4ad275050ea58e3` | [`{ type: "llm/retry-started" }`](#persistence-type-sha256-48e5c9861f16ac07e78cb7b5ae9dabdf7bb85c58baed5a51b4ad275050ea58e3) | | `event:model/selection` | event | `35203ba7ad5ef6f97d556b85df20ae98f04f09c65748cecdf8eefdb8b6405ffc` | [`{ type: "model/selection" }`](#persistence-type-sha256-35203ba7ad5ef6f97d556b85df20ae98f04f09c65748cecdf8eefdb8b6405ffc) | @@ -56,7 +58,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:session-log-deepseek/delivery-accepted` | event | `d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9` | [`{ type: "session-log-deepseek/delivery-accepted" }`](#persistence-type-sha256-d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9) | | `event:session/end-seed` | event | `5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e` | [`{ type: "session/end-seed" }`](#persistence-type-sha256-5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e) | | `event:session/title` | event | `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | [`{ type: "session/title" }`](#persistence-type-sha256-1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5) | -| `event:session/title-llm-request` | event | `b33545b3244861bcbf73b407d24b53402710f5acacab7ae939537e5504a68dc6` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-b33545b3244861bcbf73b407d24b53402710f5acacab7ae939537e5504a68dc6) | +| `event:session/title-llm-request` | event | `79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056) | | `event:step/end` | event | `e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05` | [`{ type: "step/end" }`](#persistence-type-sha256-e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05) | | `event:step/start` | event | `4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986` | [`{ type: "step/start" }`](#persistence-type-sha256-4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986) | | `event:subagent/catalog` | event | `53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac` | [`{ type: "subagent/catalog" }`](#persistence-type-sha256-53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac) | @@ -78,7 +80,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:tool/result` | event | `7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397` | [`{ type: "tool/result" }`](#persistence-type-sha256-7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397) | | `event:turn/end` | event | `0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce` | [`{ type: "turn/end" }`](#persistence-type-sha256-0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce) | | `event:turn/start` | event | `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` | [`{ type: "turn/start" }`](#persistence-type-sha256-aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8) | -| `event:user/message` | event | `2ace3b8059b82b6d9837fed518ca97a99eb37c4482df7aad0e71c85489428ade` | [`{ type: "user/message" }`](#persistence-type-sha256-2ace3b8059b82b6d9837fed518ca97a99eb37c4482df7aad0e71c85489428ade) | +| `event:user/message` | event | `2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8` | [`{ type: "user/message" }`](#persistence-type-sha256-2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8) | | `event:web/deepseek-search-llm-request` | event | `cf6e3aaf1e2de6480aa0157730a41b9a492108a55304100b0f7e112711dd4331` | [`{ type: "web/deepseek-search-llm-request" }`](#persistence-type-sha256-cf6e3aaf1e2de6480aa0157730a41b9a492108a55304100b0f7e112711dd4331) | | `event:working-directory/change` | event | `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3) | | `event:workspace/changes` | event | `e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72` | [`{ type: "workspace/changes" }`](#persistence-type-sha256-e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72) | @@ -158,7 +160,7 @@ export type SessionEvent = { }[T] ``` -Sources: [`packages/core/session/src/types.ts:431`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:439`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:462`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:493`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:432`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:440`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:463`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:494`](../packages/core/session/src/types.ts) ## Events @@ -196,12 +198,15 @@ Source: [`packages/core/agent/src/types.ts:96`](../packages/core/agent/src/types * The session's agent preset was chosen after creation, while the session * was still blank. Log-only: it records the composition later turns ran * under, so a resumed or forked session rebuilds the same one instead of - * the header's creation-time value. + * the header's creation-time value. In a child Session, an occurrence + * before its first own `subagent/descriptor` marks an independent spawn + * selection that cold resume restores instead of joining the parent's + * composition (`dsh-subagent` README, "Restoring child composition"). */ 'agent-preset/selected': { agentPreset: string } ``` -Source: [`packages/preset/agent-preset-registry/src/session.ts:28`](../packages/preset/agent-preset-registry/src/session.ts) +Source: [`packages/preset/agent-preset-registry/src/session.ts:31`](../packages/preset/agent-preset-registry/src/session.ts) ### `approval/*` @@ -285,7 +290,7 @@ Source: [`packages/interaction/user-approval/src/index.ts:40`](../packages/inter 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[] } ``` -Source: [`packages/core/session/src/types.ts:355`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:356`](../packages/core/session/src/types.ts) @@ -315,7 +320,7 @@ Source: [`packages/core/session/src/types.ts:355`](../packages/core/session/src/ Types: [TokenUsage](subsystems/llm-streaming.md) -Source: [`packages/core/session/src/types.ts:341`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:342`](../packages/core/session/src/types.ts) ### `command/*` @@ -503,7 +508,7 @@ Source: [`packages/deliverables/tool-present/src/types.ts:15`](../packages/deliv } ``` -Source: [`packages/core/session/src/types.ts:311`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:312`](../packages/core/session/src/types.ts) ### `feedback/*` @@ -627,6 +632,36 @@ Source: [`packages/experimental/hook-protocol/src/types.ts:31`](../packages/expe Source: [`packages/compaction/compaction-image-offload/src/projection.ts:25`](../packages/compaction/compaction-image-offload/src/projection.ts) +### `job/*` + + + +#### `job/registered` — log-only + +```ts persistence-catalog +/** + * Log-only job registration; model output collection is not required. + * @param data - Execution identity, original owner, registration time, and creating tool call. + */ +'job/registered': JobRegisteredData +``` + +Source: [`packages/jobs/jobs/src/types.ts:59`](../packages/jobs/jobs/src/types.ts) + + + +#### `job/settled` — log-only + +```ts persistence-catalog +/** + * Log-only terminal record, paired by the same unique jobId used for live control. + * @param data - Registration facts plus settlement time, outcome, and producer acknowledgement. + */ +'job/settled': JobSettledData +``` + +Source: [`packages/jobs/jobs/src/types.ts:64`](../packages/jobs/jobs/src/types.ts) + ### `llm/*` @@ -665,7 +700,7 @@ Source: [`packages/llm/llm-retry/src/types.ts:11`](../packages/llm/llm-retry/src 'model/selection': ModelSelection ``` -Source: [`packages/api/session-controller/src/types.ts:40`](../packages/api/session-controller/src/types.ts) +Source: [`packages/api/session-controller/src/types.ts:41`](../packages/api/session-controller/src/types.ts) ### `permission/*` @@ -718,7 +753,7 @@ Source: [`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/s 'request/context': RequestContext ``` -Source: [`packages/core/session/src/types.ts:402`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:403`](../packages/core/session/src/types.ts) @@ -737,7 +772,7 @@ Source: [`packages/core/session/src/types.ts:402`](../packages/core/session/src/ } ``` -Source: [`packages/core/session/src/types.ts:390`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:391`](../packages/core/session/src/types.ts) ### `sandbox/*` @@ -814,7 +849,7 @@ Source: [`packages/schedule/schedule/src/types.ts:365`](../packages/schedule/sch 'session/end-seed': { inherited?: true } ``` -Source: [`packages/core/session/src/types.ts:427`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:428`](../packages/core/session/src/types.ts) @@ -843,7 +878,7 @@ Source: [`packages/session/session-title/src/index.ts:77`](../packages/session/s Types: [SessionTitleLlmRequestEventData](subsystems/session-title.md) -Source: [`packages/session/session-title-llm/src/index.ts:54`](../packages/session/session-title-llm/src/index.ts) +Source: [`packages/session/session-title-llm/src/index.ts:57`](../packages/session/session-title-llm/src/index.ts) ### `session-log-deepseek/*` @@ -876,7 +911,7 @@ Source: [`packages/session/session-log-deepseek/src/types.ts:81`](../packages/se 'step/end': { turn: number; step: number } ``` -Source: [`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:302`](../packages/core/session/src/types.ts) @@ -887,7 +922,7 @@ Source: [`packages/core/session/src/types.ts:301`](../packages/core/session/src/ 'step/start': { turn: number; step: number } ``` -Source: [`packages/core/session/src/types.ts:299`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:300`](../packages/core/session/src/types.ts) ### `subagent/*` @@ -963,7 +998,7 @@ Source: [`packages/subagent/tool-subagent/src/model-selection-state.ts:17`](../p 'system/message': { turn: number; step: number; message: SystemMessage } ``` -Source: [`packages/core/session/src/types.ts:330`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:331`](../packages/core/session/src/types.ts) ### `team/*` @@ -978,14 +1013,14 @@ Source: [`packages/core/session/src/types.ts:330`](../packages/core/session/src/ Types: [TeamId](subsystems/agent-team.md) · [TeamMemberSnapshot](subsystems/agent-team.md) -Source: [`packages/experimental/agent-team/src/types.ts:232`](../packages/experimental/agent-team/src/types.ts) +Source: [`packages/experimental/agent-team/src/types.ts:230`](../packages/experimental/agent-team/src/types.ts) #### `team/message/delivered` — log-only ```ts persistence-catalog -/** Durable acknowledgement that the target Session recorded the message. */ +/** Historical acknowledgement that the target Session recorded a queued message. */ 'team/message/delivered': { version: 2 teamId: TeamId @@ -996,20 +1031,20 @@ Source: [`packages/experimental/agent-team/src/types.ts:232`](../packages/experi Types: [TeamId](subsystems/agent-team.md) · [TeamMessageId](subsystems/agent-team.md) -Source: [`packages/experimental/agent-team/src/types.ts:238`](../packages/experimental/agent-team/src/types.ts) +Source: [`packages/experimental/agent-team/src/types.ts:236`](../packages/experimental/agent-team/src/types.ts) #### `team/message/queued` — log-only ```ts persistence-catalog -/** Durable mailbox enqueue, stored before delivery is attempted. */ +/** Historical mailbox enqueue; new sends use the target Agent inbox. */ 'team/message/queued': { version: 2; teamId: TeamId; message: TeamMessageSnapshot } ``` Types: [TeamId](subsystems/agent-team.md) · [TeamMessageSnapshot](subsystems/agent-team.md) -Source: [`packages/experimental/agent-team/src/types.ts:236`](../packages/experimental/agent-team/src/types.ts) +Source: [`packages/experimental/agent-team/src/types.ts:234`](../packages/experimental/agent-team/src/types.ts) @@ -1022,7 +1057,7 @@ Source: [`packages/experimental/agent-team/src/types.ts:236`](../packages/experi Types: [TeamId](subsystems/agent-team.md) · [TeamTaskSnapshot](subsystems/agent-team.md) -Source: [`packages/experimental/agent-team/src/types.ts:234`](../packages/experimental/agent-team/src/types.ts) +Source: [`packages/experimental/agent-team/src/types.ts:232`](../packages/experimental/agent-team/src/types.ts) ### `todo/*` @@ -1056,7 +1091,7 @@ Source: [`packages/todo/tool-todo/src/types.ts:31`](../packages/todo/tool-todo/s Types: [ToolCallId](subsystems/core.md) -Source: [`packages/core/session/src/types.ts:361`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:362`](../packages/core/session/src/types.ts) @@ -1137,7 +1172,7 @@ Source: [`packages/core/tools/src/types.ts:45`](../packages/core/tools/src/types } ``` -Source: [`packages/core/session/src/types.ts:375`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:376`](../packages/core/session/src/types.ts) ### `tool-workflow/*` @@ -1217,7 +1252,7 @@ Source: [`packages/workflow/tool-workflow/src/types.ts:47`](../packages/workflow Types: [TurnEndReason](subsystems/session.md) -Source: [`packages/core/session/src/types.ts:297`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:298`](../packages/core/session/src/types.ts) @@ -1233,7 +1268,7 @@ Source: [`packages/core/session/src/types.ts:297`](../packages/core/session/src/ 'turn/start': { turn: number } ``` -Source: [`packages/core/session/src/types.ts:288`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:289`](../packages/core/session/src/types.ts) ### `user/*` @@ -1252,7 +1287,7 @@ Source: [`packages/core/session/src/types.ts:288`](../packages/core/session/src/ 'user/message': UserMessage ``` -Source: [`packages/core/session/src/types.ts:309`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:310`](../packages/core/session/src/types.ts) ### `web/*` @@ -1954,7 +1989,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8` SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5` -Sources: [`packages/llm/llm/src/types.ts:396`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:412`](../packages/llm/llm/src/types.ts) `"in-history"` @@ -1998,6 +2033,38 @@ SHA-256: `69d238a6e9b08d67f601b1825962963d8d3523cb69ebf6208c697dc5d058c199` `"interrupted"` + + +### `"job/registered"` + +SHA-256: `24a8188c4d61b70a01af8cc576748765d36f132632ec55c0064f6fba482369fc` + +`"job/registered"` + + + +### `"job/settled"` + +SHA-256: `347de3380f2da308d0c74e08821f9e85559f55af4c5010795b110d00f7fc9dbd` + +`"job/settled"` + + + +### `"kill"` + +SHA-256: `bab68657940075483f086fffb711682a45bcc99c43d659fbe1c36af21ac05dd7` + +`"kill"` + + + +### `"killed"` + +SHA-256: `ef226a90ddac6cd8e631a3a337a3a3e27f9494be92befb7c718b404681d75e21` + +`"killed"` + ### `"legacy"` @@ -2118,6 +2185,14 @@ SHA-256: `9d80129e13edfb6feb03ed327e6085c6ef60b97ad074244b2f5fd4667424a6a4` `"other"` + + +### `"owner"` + +SHA-256: `95a3ffccbf3c8afcf9a2f3b355f724da8e07e98dc47ee741166dde7f9ea058bd` + +`"owner"` + ### `"parent"` @@ -2182,6 +2257,14 @@ SHA-256: `df5d9709b7db2a72510dc52052a23f0c38f39730af1504bab8bccabc14fae528` `"positive"` + + +### `"producer"` + +SHA-256: `6cf082d0fb6034dea61636787ff0ddf43b6e59aad71e644435a479bc9b83ad65` + +`"producer"` + ### `"product-interaction"` @@ -2606,6 +2689,14 @@ SHA-256: `b57ae1b37e52bee0a21cbdace168dc6a15582bcda8c306dad962c5dcc8a8e28b` `"team/task"` + + +### `"teardown"` + +SHA-256: `5cb63db9fe57dc09c3a1c2b84c3edf73ff5b62960155d8436a2377a5c43ce32c` + +`"teardown"` + ### `"text"` @@ -3123,7 +3214,7 @@ Array of [`AssistantStreamRecord`](#persistence-type-sha256-33341aac09312300de5a SHA-256: `ada310bf0bdb8fed51f3b56ea63f6ea6b18bbd587f04fccb63a14ab0b2a24e05` -Sources: [`packages/core/session/src/types.ts:190`](../packages/core/session/src/types.ts) · [`packages/interaction/commands/src/types.ts:75`](../packages/interaction/commands/src/types.ts) · [`packages/interaction/commands/src/types.ts:79`](../packages/interaction/commands/src/types.ts) · [`packages/llm/llm/src/message.ts:111`](../packages/llm/llm/src/message.ts) · [`packages/session/session-title/src/types.ts:35`](../packages/session/session-title/src/types.ts) +Sources: [`packages/core/session/src/types.ts:191`](../packages/core/session/src/types.ts) · [`packages/interaction/commands/src/types.ts:75`](../packages/interaction/commands/src/types.ts) · [`packages/interaction/commands/src/types.ts:79`](../packages/interaction/commands/src/types.ts) · [`packages/llm/llm/src/message.ts:111`](../packages/llm/llm/src/message.ts) · [`packages/session/session-title/src/types.ts:35`](../packages/session/session-title/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -3266,7 +3357,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:55`](../packages/web | `body` | required | [`{ max_tokens, messages, model, tools }`](#persistence-type-sha256-930a6567a10bb62ddd157bd8abdf4b182810c8c3b49d91309b3b009a5fed9731) | | `endpoint` | required | `string` | - + @@ -3274,7 +3365,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:55`](../packages/web ### `DeveloperMessage` -SHA-256: `af99c95d46bed802870f1ebefe0ea11f92a03cb37b8e0cbe3f94b7aaaf509b08` +SHA-256: `0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7` Sources: [`packages/llm/llm/src/message.ts:157`](../packages/llm/llm/src/message.ts) @@ -3283,7 +3374,7 @@ Sources: [`packages/llm/llm/src/message.ts:157`](../packages/llm/llm/src/message | `content` | required | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | required | `string` | | `role` | required | `"developer"` | -| `source` | required | [`MessageSource`](#persistence-type-sha256-1fa156c85450ca31063d0e0d2853028e6dac9687f2d3191fa811648210118154) | +| `source` | required | [`MessageSource`](#persistence-type-sha256-5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8) | Source compatibility: `source` — `session-source-attribution` v1; `session.developer-message.source`; `kind`; `preserve`. @@ -3299,7 +3390,7 @@ Attribution-only additions: `tmux-context`, `user-question-reply`, `working-dire SHA-256: `9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7` -Sources: [`packages/core/session/src/types.ts:240`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:241`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -3696,6 +3787,88 @@ One of: - `"next-step"` - `"next-turn"` + + + + + + +### `JobRegisteredData` + +SHA-256: `e3056e0dda3a379e895386e368c3ce42131460ea65e410e1d091cca98a347305` + +Sources: [`packages/jobs/jobs/src/types.ts:24`](../packages/jobs/jobs/src/types.ts) + +| Property | Presence | Type | +|---|---|---| +| `jobId` | required | `string` | +| `kind` | required | `string` | +| `label` | required | `string` | +| `owner` | required | `string` | +| `startedAt` | required | `number` | +| `toolCall` | optional | [`JobToolCall`](#persistence-type-sha256-39cf2d3ff8bac81c62d49ac2ba38a095b18e80f3ad700819fa1f650a4e60197f) | + + + + + + + +### `JobSettleCause` + +SHA-256: `750a2b129d67704df675c06823c20c80b65cbae89d5aaa914fd5a72e3df395b5` + +Sources: [`packages/jobs/jobs/src/types.ts:247`](../packages/jobs/jobs/src/types.ts) + +One of: + +- `"kill"` +- `"producer"` +- `"teardown"` + + + + + + + +### `JobSettledData` + +SHA-256: `611d82d2dc50df706cf08a0fc04bc8eaf78083391fe6f10313de943e615dd2da` + +Sources: [`packages/jobs/jobs/src/types.ts:40`](../packages/jobs/jobs/src/types.ts) + +| Property | Presence | Type | +|---|---|---| +| `cause` | required | [`JobSettleCause`](#persistence-type-sha256-750a2b129d67704df675c06823c20c80b65cbae89d5aaa914fd5a72e3df395b5) | +| `detail` | optional | `string` | +| `finishedAt` | required | `number` | +| `jobId` | required | `string` | +| `kind` | required | `string` | +| `label` | required | `string` | +| `owner` | required | `string` | +| `producerReported` | required | `boolean` | +| `startedAt` | required | `number` | +| `status` | required | [`union (3 variants)`](#persistence-type-sha256-c2f49004d9ae38a964e80850c87bc6849d6a872091a1d43e99eedf00c641e2a3) | +| `toolCall` | optional | [`JobToolCall`](#persistence-type-sha256-39cf2d3ff8bac81c62d49ac2ba38a095b18e80f3ad700819fa1f650a4e60197f) | + + + + + + + +### `JobToolCall` + +SHA-256: `39cf2d3ff8bac81c62d49ac2ba38a095b18e80f3ad700819fa1f650a4e60197f` + +Sources: [`packages/jobs/jobs/src/types.ts:16`](../packages/jobs/jobs/src/types.ts) + +| Property | Presence | Type | +|---|---|---| +| `callId` | required | `string` | +| `rootCallId` | required | `string` | + @@ -3900,7 +4073,7 @@ Sources: [`packages/llm/llm-retry/src/types.ts:43`](../packages/llm/llm-retry/sr | `step` | required | `number` | | `turn` | required | `number` | - + @@ -3908,17 +4081,17 @@ Sources: [`packages/llm/llm-retry/src/types.ts:43`](../packages/llm/llm-retry/sr ### `Message` -SHA-256: `d901c4f5e856591c3217af983caa15bba568d580700f0958bab56b88004eced9` +SHA-256: `040cd65423bd64264d225504f1c572d239eeb1793d0c2856ad8e42bb6e1e148b` Sources: [`packages/llm/llm/src/message.ts:196`](../packages/llm/llm/src/message.ts) One of: - [`ToolResultMessage`](#persistence-type-sha256-4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731) -- [`DeveloperMessage`](#persistence-type-sha256-af99c95d46bed802870f1ebefe0ea11f92a03cb37b8e0cbe3f94b7aaaf509b08) -- [`UserMessage`](#persistence-type-sha256-89b2edff547be1ecfcd78ef18aeeb3cf507fcbf7d6093ec04fb111ef4c8e8a97) -- [`SystemMessage`](#persistence-type-sha256-09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363) +- [`DeveloperMessage`](#persistence-type-sha256-0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7) +- [`UserMessage`](#persistence-type-sha256-2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711) - [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) +- [`SystemMessage`](#persistence-type-sha256-09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363) @@ -3993,7 +4166,7 @@ One of: - `"negative"` - `"positive"` - + @@ -4001,7 +4174,7 @@ One of: ### `MessageSource` -SHA-256: `1fa156c85450ca31063d0e0d2853028e6dac9687f2d3191fa811648210118154` +SHA-256: `5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8` Sources: [`packages/llm/llm/src/message.ts:136`](../packages/llm/llm/src/message.ts) @@ -4106,7 +4279,7 @@ Sources: [`packages/llm/llm/src/message.ts:136`](../packages/llm/llm/src/message | `tool-jobs` | `"snapshot"` | `sections`: [`ContextSnapshotSection[]`](#persistence-type-sha256-c748fb42c80a120038a8c587af80ec39924803c401364db11c8974d5bf6d0262) | [`{ kind: "tool-jobs", form: "snapshot" }`](#persistence-type-sha256-c5228b7a55498d84f529591744a0ab26e0b93ade18a70a26db1377a1ecfa6b49) | | `tool-jobs` | not declared | none | [`{ kind: "tool-jobs" }`](#persistence-type-sha256-24ce31aa528272e59f21cd26da9eca08968bcc97529756a749bfdab71746d9c8) | | `tool-registry` | not declared | none | [`{ kind: "tool-registry" }`](#persistence-type-sha256-8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543) | -| `user` | not declared | `rpcId`: `string` | [`{ kind: "user" }`](#persistence-type-sha256-6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7) | +| `user` | not declared | `rpcId`: `string` | [`{ kind: "user" }`](#persistence-type-sha256-6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def) | | `user` | not declared | none | [`CommandSource`](#persistence-type-sha256-ada310bf0bdb8fed51f3b56ea63f6ea6b18bbd587f04fccb63a14ab0b2a24e05) | | `user-approval` | `"catalog"` | none | [`{ kind: "user-approval", form: "catalog" }`](#persistence-type-sha256-825ca23416b1ea9d81442afead5cf9229a6fa05842f042135cc3aa9710a6a2d8) | | `user-approval` | `"instructions"` | none | [`{ kind: "user-approval", form: "instructions" }`](#persistence-type-sha256-aa2bf9e82b9fdeb94a42af20031fffa30e4e23f01f4ac39757427d4c64c407f0) | @@ -4119,13 +4292,13 @@ Sources: [`packages/llm/llm/src/message.ts:136`](../packages/llm/llm/src/message | `webhook` | `"notice"` | `deliveryId`: `string`; `provider`: `string`; `ruleId`: `string`; `source`: `string`; `summary`: `string` | [`{ kind: "webhook", form: "notice" }`](#persistence-type-sha256-9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94) | | `working-directory` | not declared | none | [`{ kind: "working-directory" }`](#persistence-type-sha256-2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5) | - + ### `Message[]` -SHA-256: `4be8fd28fefa5534675ea9aabd0a24efc2838b989bbc74da20a1efbd0daede8c` +SHA-256: `a927d444c928ac0efd9dd8b2e7d7d04d711c264cb71578d81e0e2fd143ff669f` -Array of [`Message`](#persistence-type-sha256-d901c4f5e856591c3217af983caa15bba568d580700f0958bab56b88004eced9). +Array of [`Message`](#persistence-type-sha256-040cd65423bd64264d225504f1c572d239eeb1793d0c2856ad8e42bb6e1e148b). @@ -4156,7 +4329,7 @@ Sources: [`packages/llm/llm/src/message.ts:24`](../packages/llm/llm/src/message. SHA-256: `f09e5e7acf5ff5ccd193ff2eeec015fa2ff7c29d98bc465f8c3302058d47e29b` -Sources: [`packages/api/session-controller/src/types.ts:100`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:101`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4211,7 +4384,7 @@ Sources: [`packages/subagent/subagent/src/descriptor.ts:61`](../packages/subagen SHA-256: `3bd652ebfa8726b3ce3937a4f1bd2759e02f86b3a08a20f9e41a8513656fbc5f` -Sources: [`packages/core/session/src/types.ts:65`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:66`](../packages/core/session/src/types.ts) One of: @@ -4243,6 +4416,22 @@ SHA-256: `1d9cb3caa96100b18b1911fa3ff8c751ef6992971a03c5f4d9aefc1a0004a345` Array of [`PresentedFile`](#persistence-type-sha256-b8fc636a2121df9d8423c242e03c9d23b7ab7c6fdce00e45746932c60b730f97). + + + + + + +### `Principal` + +SHA-256: `deebfc7c62177ea840f23c6362b8615bc78ffa93377dd5d243c04e541c413af5` + +Sources: [`packages/typert/protocol/src/types.ts:457`](../packages/typert/protocol/src/types.ts) · [`packages/typert/protocol/src/types.ts:461`](../packages/typert/protocol/src/types.ts) + +| Property | Presence | Type | +|---|---|---| +| `kind` | required | `"owner"` | + @@ -4314,7 +4503,7 @@ Sources: [`packages/llm/llm/src/types.ts:68`](../packages/llm/llm/src/types.ts) SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` -Sources: [`packages/llm/llm/src/types.ts:430`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:446`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4331,7 +4520,7 @@ Sources: [`packages/llm/llm/src/types.ts:430`](../packages/llm/llm/src/types.ts) SHA-256: `b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081` -Sources: [`packages/core/session/src/types.ts:254`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:255`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4350,7 +4539,7 @@ Sources: [`packages/core/session/src/types.ts:254`](../packages/core/session/src SHA-256: `530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6` -Sources: [`packages/core/session/src/types.ts:273`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:274`](../packages/core/session/src/types.ts) One of: @@ -4442,7 +4631,7 @@ Sources: [`packages/schedule/schedule/src/types.ts:230`](../packages/schedule/sc SHA-256: `1a3440e3577382704d42a6263aa463504eb74c566734a55e9503a63efcd02445` -Sources: [`packages/core/session/src/types.ts:94`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:95`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4493,7 +4682,7 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ | `source` | required | [`SessionTitleSource`](#persistence-type-sha256-30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f) | | `title` | required | `string` | - + @@ -4501,15 +4690,15 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ ### `SessionTitleLlmRequestEventData` -SHA-256: `045926475a46f625f84ae2be292b384817059f16927c69a9adab93717923ac19` +SHA-256: `00c054d3018c198d92f459563331edd1385e58345c677bb499791df2da0ade9f` -Sources: [`packages/session/session-title-llm/src/index.ts:34`](../packages/session/session-title-llm/src/index.ts) +Sources: [`packages/session/session-title-llm/src/index.ts:37`](../packages/session/session-title-llm/src/index.ts) | Property | Presence | Type | |---|---|---| | `maxTokens` | required | `number` | | `messageSeqs` | required | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | -| `messages` | required | [`Message[]`](#persistence-type-sha256-4be8fd28fefa5534675ea9aabd0a24efc2838b989bbc74da20a1efbd0daede8c) | +| `messages` | required | [`Message[]`](#persistence-type-sha256-a927d444c928ac0efd9dd8b2e7d7d04d711c264cb71578d81e0e2fd143ff669f) | | `reasoningEffort` | optional | `string` | | `route` | required | [`SessionTitleModelIdentity`](#persistence-type-sha256-07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235) | | `system` | required | `string` | @@ -4609,7 +4798,7 @@ Sources: [`packages/skill/skill/src/index.ts:146`](../packages/skill/skill/src/i SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180` -Sources: [`packages/llm/llm/src/types.ts:452`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:468`](../packages/llm/llm/src/types.ts) One of: @@ -4688,7 +4877,7 @@ Sources: [`packages/subagent/subagent/src/continuation-messages.ts:29`](../packa SHA-256: `335e242de1fcc17b6ca920fc420d71bec2d76e53e37955c00948b65ab77f05c5` -Sources: [`packages/core/session/src/types.ts:462`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:463`](../packages/core/session/src/types.ts) One of: @@ -4740,7 +4929,7 @@ Sources: [`packages/llm/llm/src/message.ts:35`](../packages/llm/llm/src/message. SHA-256: `dfce5db4aa42b7ebe0bb79eca92553587287e18c06b9eba85cbfb9d332e26acd` -Sources: [`packages/experimental/agent-team/src/types.ts:44`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/experimental/agent-team/src/types.ts:45`](../packages/experimental/agent-team/src/types.ts) One of: @@ -4758,7 +4947,7 @@ One of: SHA-256: `6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25` -Sources: [`packages/experimental/agent-team/src/types.ts:47`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/experimental/agent-team/src/types.ts:48`](../packages/experimental/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4780,7 +4969,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:47`](../packages/experi SHA-256: `2eafefdc6f79a4922d68a787a09eaf4dd2b2369c3777fba4c05e800b5678ac8e` -Sources: [`packages/experimental/agent-team/src/types.ts:128`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/experimental/agent-team/src/types.ts:129`](../packages/experimental/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4800,7 +4989,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:128`](../packages/exper SHA-256: `2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0` -Sources: [`packages/experimental/agent-team/src/types.ts:137`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/experimental/agent-team/src/types.ts:138`](../packages/experimental/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4820,7 +5009,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:137`](../packages/exper SHA-256: `51edec100659da3a9bd9c3f6ba1180f5e64ec9a1585e5057080df45c180bd357` -Sources: [`packages/experimental/agent-team/src/types.ts:74`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/experimental/agent-team/src/types.ts:75`](../packages/experimental/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4843,7 +5032,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:74`](../packages/experi SHA-256: `b2d2a01e51341a3bfec809198952c8c830a7899f4cb6ecd3c1dc0b5d9a2af943` -Sources: [`packages/experimental/agent-team/src/types.ts:71`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/experimental/agent-team/src/types.ts:72`](../packages/experimental/agent-team/src/types.ts) One of: @@ -5034,7 +5223,7 @@ Sources: [`packages/llm/llm/src/message.ts:173`](../packages/llm/llm/src/message SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2` -Sources: [`packages/llm/llm/src/types.ts:473`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:489`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -5133,7 +5322,7 @@ Sources: [`packages/workflow/tool-workflow/src/types.ts:14`](../packages/workflo SHA-256: `1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0` -Sources: [`packages/core/session/src/types.ts:196`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:197`](../packages/core/session/src/types.ts) | kind | Form property | Other required fields | Full definition | |---|---|---|---| @@ -5153,7 +5342,7 @@ Sources: [`packages/core/session/src/types.ts:196`](../packages/core/session/src SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` -Sources: [`packages/core/session/src/types.ts:232`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:233`](../packages/core/session/src/types.ts) | kind | Form property | Other required fields | Full definition | |---|---|---|---| @@ -5165,7 +5354,7 @@ Sources: [`packages/core/session/src/types.ts:232`](../packages/core/session/src | `interrupted` | not declared | none | [`{ kind: "interrupted" }`](#persistence-type-sha256-56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23) | | `max-tokens` | not declared | none | [`{ kind: "max-tokens" }`](#persistence-type-sha256-ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7) | - + @@ -5173,7 +5362,7 @@ Sources: [`packages/core/session/src/types.ts:232`](../packages/core/session/src ### `UserMessage` -SHA-256: `89b2edff547be1ecfcd78ef18aeeb3cf507fcbf7d6093ec04fb111ef4c8e8a97` +SHA-256: `2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711` Sources: [`packages/llm/llm/src/message.ts:162`](../packages/llm/llm/src/message.ts) @@ -5182,19 +5371,19 @@ Sources: [`packages/llm/llm/src/message.ts:162`](../packages/llm/llm/src/message | `content` | required | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | required | `string` | | `role` | required | `"user"` | -| `source` | required | [`MessageSource`](#persistence-type-sha256-1fa156c85450ca31063d0e0d2853028e6dac9687f2d3191fa811648210118154) | +| `source` | required | [`MessageSource`](#persistence-type-sha256-5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8) | Source compatibility: `source` — `session-source-attribution` v1; `session.user-message.source`; `kind`; `preserve`. Attribution-only additions: `tmux-context`, `user-question-reply`, `working-directory`. - + ### `UserMessage[]` -SHA-256: `2fef90def36aa758ca096c5f6ad0e00dbb2101943e19ca54b05618801974894a` +SHA-256: `454a0fa879e38076bdcdbd87ef561cd67d7e43e58a287cf7dbaa7b6cf7847020` -Array of [`UserMessage`](#persistence-type-sha256-89b2edff547be1ecfcd78ef18aeeb3cf507fcbf7d6093ec04fb111ef4c8e8a97). +Array of [`UserMessage`](#persistence-type-sha256-2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711). @@ -5274,7 +5463,7 @@ SHA-256: `938f7c7357bc403ea3b281a9dd016939df7a0880fc8db12612585be574d0d615` SHA-256: `0657d3ca5ac4e7bf79b00bcf860b1c7159d01a9da137497221ec2f1776e365f7` -Sources: [`packages/core/session/src/types.ts:32`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:33`](../packages/core/session/src/types.ts) `number` @@ -5298,6 +5487,8 @@ Array of `number`. + + @@ -5330,6 +5521,8 @@ Array of `number`. + + @@ -5382,7 +5575,7 @@ Array of `number`. SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -Sources: [`packages/api/session-controller/src/types.ts:398`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:20`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:32`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:8`](../packages/experimental/agent-team/src/types.ts) · [`packages/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:409`](../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:21`](../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/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.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` @@ -5491,6 +5684,18 @@ One of: - `"replace"` - `"set"` + + +### `union (3 variants)` + +SHA-256: `c2f49004d9ae38a964e80850c87bc6849d6a872091a1d43e99eedf00c641e2a3` + +One of: + +- `"completed"` +- `"failed"` +- `"killed"` + ### `union (3 variants)` @@ -5568,7 +5773,7 @@ Sources: [`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/ SHA-256: `6e52dd55a1d48954ed5464ec46fe34d9eb65f709baabc9561e7a279910b0c406` -Sources: [`packages/preset/agent-preset-registry/src/session.ts:28`](../packages/preset/agent-preset-registry/src/session.ts) +Sources: [`packages/preset/agent-preset-registry/src/session.ts:31`](../packages/preset/agent-preset-registry/src/session.ts) | Property | Presence | Type | |---|---|---| @@ -5607,7 +5812,7 @@ Sources: [`packages/interaction/commands/src/types.ts:105`](../packages/interact SHA-256: `e4c18e294232c3ba6c9f1999f168263cc55956147cfe4121720899be8e52edd1` -Sources: [`packages/core/session/src/types.ts:361`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:362`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -5766,7 +5971,7 @@ SHA-256: `cbbe8377ee744964537dbafd83607219e58ba79a13f6db0d0645c7ad3d5e8a09` SHA-256: `a81059ca06999da1e712414520c2c65e491d052fcf9640fae20aa38f0a5dc735` -Sources: [`packages/core/session/src/types.ts:383`](../packages/core/session/src/types.ts) · [`packages/core/tools/src/types.ts:27`](../packages/core/tools/src/types.ts) +Sources: [`packages/core/session/src/types.ts:384`](../packages/core/session/src/types.ts) · [`packages/core/tools/src/types.ts:27`](../packages/core/tools/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -5986,7 +6191,7 @@ Sources: [`packages/compaction/compaction/src/types.ts:38`](../packages/compacti SHA-256: `bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825` -Sources: [`packages/core/session/src/types.ts:464`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:465`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6000,7 +6205,7 @@ Sources: [`packages/core/session/src/types.ts:464`](../packages/core/session/src SHA-256: `79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985` -Sources: [`packages/core/session/src/types.ts:212`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:213`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6013,7 +6218,7 @@ Sources: [`packages/core/session/src/types.ts:212`](../packages/core/session/src SHA-256: `5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777` -Sources: [`packages/core/session/src/types.ts:375`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:376`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6055,7 +6260,7 @@ Sources: [`packages/llm/llm/src/types.ts:161`](../packages/llm/llm/src/types.ts) SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` -Sources: [`packages/core/session/src/types.ts:390`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:391`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6063,18 +6268,18 @@ Sources: [`packages/core/session/src/types.ts:390`](../packages/core/session/src | `reason` | required | [`RequestHeaderReason`](#persistence-type-sha256-530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6) | | `startsSeries` | optional | `true` | - + ### `{ headerSeq?, message, step, turn }` -SHA-256: `5b55817a403569fbb2d379496df2e3f3f71107f6c577a218028ce187c60b61e6` +SHA-256: `f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb` -Sources: [`packages/core/session/src/types.ts:311`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:312`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| | `headerSeq` | optional | `number` | -| `message` | required | [`DeveloperMessage`](#persistence-type-sha256-af99c95d46bed802870f1ebefe0ea11f92a03cb37b8e0cbe3f94b7aaaf509b08) | +| `message` | required | [`DeveloperMessage`](#persistence-type-sha256-0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7) | | `step` | required | `number` | | `turn` | required | `number` | @@ -6152,23 +6357,23 @@ SHA-256: `e3e77b26f0148755a505f5b8ea843a3be117827d4703bb5754d9dc8ddbef521f` SHA-256: `17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3` -Sources: [`packages/core/session/src/types.ts:427`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:428`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| | `inherited` | optional | `true` | - + ### `{ inserted, outcome?, removedCount?, start, … }` -SHA-256: `83a665476a9ee9af05cb1fdded12dd647d1b97b491200d7f12ef1af7cdac4428` +SHA-256: `fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42` Sources: [`packages/core/agent/src/types.ts:96`](../packages/core/agent/src/types.ts) | Property | Presence | Type | |---|---|---| -| `inserted` | required | [`UserMessage[]`](#persistence-type-sha256-2fef90def36aa758ca096c5f6ad0e00dbb2101943e19ca54b05618801974894a) | +| `inserted` | required | [`UserMessage[]`](#persistence-type-sha256-454a0fa879e38076bdcdbd87ef561cd67d7e43e58a287cf7dbaa7b6cf7847020) | | `outcome` | optional | `"canceled"` | | `removedCount` | optional | `number` | | `start` | required | `number` | @@ -6180,7 +6385,7 @@ Sources: [`packages/core/agent/src/types.ts:96`](../packages/core/agent/src/type SHA-256: `1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d` -Sources: [`packages/core/session/src/types.ts:341`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:342`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6197,7 +6402,7 @@ Sources: [`packages/core/session/src/types.ts:341`](../packages/core/session/src SHA-256: `0a30c3be336cdd4f8f34e66543a3d46d611c43986edd9b3ce6cbb9b721d3b5d3` -Sources: [`packages/core/session/src/types.ts:204`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:205`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6210,7 +6415,7 @@ Sources: [`packages/core/session/src/types.ts:204`](../packages/core/session/src SHA-256: `023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4` -Sources: [`packages/core/session/src/types.ts:206`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:207`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6222,7 +6427,7 @@ Sources: [`packages/core/session/src/types.ts:206`](../packages/core/session/src SHA-256: `b6ef9c6210be8350cd465f485cf520031fffa6bf3809c61a1e713e834c5982d0` -Sources: [`packages/core/session/src/types.ts:202`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:203`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6246,7 +6451,7 @@ Sources: [`packages/extensions/cordis-host-runner/src/index.ts:14`](../packages/ SHA-256: `4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db` -Sources: [`packages/core/session/src/types.ts:193`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:194`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6348,7 +6553,7 @@ Sources: [`packages/session/session-title/src/types.ts:29`](../packages/session/ SHA-256: `ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7` -Sources: [`packages/core/session/src/types.ts:228`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:229`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6360,7 +6565,7 @@ Sources: [`packages/core/session/src/types.ts:228`](../packages/core/session/src SHA-256: `6c5a37d42ebdb12db4410699259335f1e149e3a0260425684c00b153afc8990d` -Sources: [`packages/core/session/src/types.ts:192`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:193`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6529,7 +6734,7 @@ SHA-256: `88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa` SHA-256: `56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23` -Sources: [`packages/core/session/src/types.ts:221`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:222`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6541,7 +6746,7 @@ Sources: [`packages/core/session/src/types.ts:221`](../packages/core/session/src SHA-256: `eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c` -Sources: [`packages/core/session/src/types.ts:196`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:197`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6553,7 +6758,7 @@ Sources: [`packages/core/session/src/types.ts:196`](../packages/core/session/src SHA-256: `ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7` -Sources: [`packages/core/session/src/types.ts:214`](../packages/core/session/src/types.ts) · [`packages/llm/llm/src/types.ts:159`](../packages/llm/llm/src/types.ts) +Sources: [`packages/core/session/src/types.ts:215`](../packages/core/session/src/types.ts) · [`packages/llm/llm/src/types.ts:159`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6643,7 +6848,7 @@ SHA-256: `52c6113cb0e53f345324bf84f01928bea5d5df57ee80bc0dd65407b8bc5a3734` SHA-256: `6c03546143cdf6ae88f1745ac98c5139efa1588d1415249bbc5f3104d32ab800` -Sources: [`packages/core/session/src/types.ts:191`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:192`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6747,7 +6952,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 | |---|---|---| @@ -7335,18 +7540,19 @@ Sources: [`packages/core/tools/src/index.ts:35`](../packages/core/tools/src/inde |---|---|---| | `kind` | required | `"tool-registry"` | - + ### `{ kind: "user" }` -SHA-256: `6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7` +SHA-256: `6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def` -Sources: [`packages/api/session-controller/src/types.ts:403`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:418`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| | `clientTimeZone` | optional | `string` | | `kind` | required | `"user"` | +| `principal` | optional | [`Principal`](#persistence-type-sha256-deebfc7c62177ea840f23c6362b8615bc78ffa93377dd5d243c04e541c413af5) | | `rpcId` | required | `string` | @@ -7492,7 +7698,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:61`](../packages/web SHA-256: `b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1` -Sources: [`packages/experimental/agent-team/src/types.ts:232`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/experimental/agent-team/src/types.ts:230`](../packages/experimental/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7506,7 +7712,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:232`](../packages/exper SHA-256: `6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5` -Sources: [`packages/core/session/src/types.ts:330`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:331`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7520,7 +7726,7 @@ Sources: [`packages/core/session/src/types.ts:330`](../packages/core/session/src SHA-256: `ea08ec1df0c33108fd03345b9af199cf04dea450aa045d3c683f216311403403` -Sources: [`packages/experimental/agent-team/src/types.ts:236`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/experimental/agent-team/src/types.ts:234`](../packages/experimental/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7534,7 +7740,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:236`](../packages/exper SHA-256: `0bcfaf5566d271028429ac7b562cb59053c9d78b8ae14708c35fac835108d1b1` -Sources: [`packages/experimental/agent-team/src/types.ts:238`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/experimental/agent-team/src/types.ts:236`](../packages/experimental/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7587,7 +7793,7 @@ Sources: [`packages/interaction/permission-presets/src/index.ts:59`](../packages SHA-256: `e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654` -Sources: [`packages/core/session/src/types.ts:297`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:298`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7641,7 +7847,7 @@ Sources: [`packages/compaction/compaction/src/types.ts:82`](../packages/compacti SHA-256: `54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0` -Sources: [`packages/core/session/src/types.ts:355`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:356`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7655,7 +7861,7 @@ Sources: [`packages/core/session/src/types.ts:355`](../packages/core/session/src SHA-256: `ef11a3b7fa2033ae4279545ff8a8a2ee4e301b9b73e5b91654c48e6d08283545` -Sources: [`packages/core/session/src/types.ts:299`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:300`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:302`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7680,7 +7886,7 @@ Sources: [`packages/compaction/compaction-image-offload/src/projection.ts:25`](. SHA-256: `a40d12070f6f4a124f32fb3cc86e7857554702e32f0eda3080a25c4b9ac9b18c` -Sources: [`packages/experimental/agent-team/src/types.ts:234`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/experimental/agent-team/src/types.ts:232`](../packages/experimental/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7706,7 +7912,7 @@ Sources: [`packages/todo/tool-todo/src/types.ts:31`](../packages/todo/tool-todo/ SHA-256: `f90eb4ab2d3897bc20c521a038e3119d581f791ec974b1a0004f63a8ab9e232d` -Sources: [`packages/core/session/src/types.ts:288`](../packages/core/session/src/types.ts) · [`packages/deliverables/workspace-changes/src/types.ts:106`](../packages/deliverables/workspace-changes/src/types.ts) +Sources: [`packages/core/session/src/types.ts:289`](../packages/core/session/src/types.ts) · [`packages/deliverables/workspace-changes/src/types.ts:106`](../packages/deliverables/workspace-changes/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7728,17 +7934,17 @@ SHA-256: `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | `time` | required | `number` | | `type` | required | `"agent-preset/selected"` | - + ### `{ type: "agent/inbox/spliced" }` -SHA-256: `9a36727716d0e73f681f3b725e7f28f89417c68174c8af0ff2b1ef52b08326a0` +SHA-256: `0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-83a665476a9ee9af05cb1fdded12dd647d1b97b491200d7f12ef1af7cdac4428) | +| `data` | required | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | @@ -7831,7 +8037,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625` SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` -Sources: [`packages/llm/llm/src/types.ts:457`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:473`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7845,7 +8051,7 @@ Sources: [`packages/llm/llm/src/types.ts:457`](../packages/llm/llm/src/types.ts) SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90` -Sources: [`packages/llm/llm/src/types.ts:453`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:469`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7979,17 +8185,17 @@ SHA-256: `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | `time` | required | `number` | | `type` | required | `"deliverables/presented"` | - + ### `{ type: "developer/message" }` -SHA-256: `ba5b10ea77d68f4a29439a9bd2a14f6a560acf55731749d57237757cc72fbc06` +SHA-256: `97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-5b55817a403569fbb2d379496df2e3f3f71107f6c577a218028ce187c60b61e6) | +| `data` | required | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `sourceEventSeqs` | optional | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | @@ -8051,7 +8257,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1` -Sources: [`packages/llm/llm/src/types.ts:459`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:475`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8123,6 +8329,38 @@ SHA-256: `b222069eea2d768065161c1147b1f2c78c1b54328c84b3586ae5c8f91b8ed35e` | `time` | required | `number` | | `type` | required | `"image/offload"` | + + + + +### `{ type: "job/registered" }` + +SHA-256: `f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1` + +| Property | Presence | Type | +|---|---|---| +| `data` | required | [`JobRegisteredData`](#persistence-type-sha256-e3056e0dda3a379e895386e368c3ce42131460ea65e410e1d091cca98a347305) | +| `ignorable` | optional | `true` | +| `seq` | required | `number` | +| `time` | required | `number` | +| `type` | required | `"job/registered"` | + + + + + +### `{ type: "job/settled" }` + +SHA-256: `edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf` + +| Property | Presence | Type | +|---|---|---| +| `data` | required | [`JobSettledData`](#persistence-type-sha256-611d82d2dc50df706cf08a0fc04bc8eaf78083391fe6f10313de943e615dd2da) | +| `ignorable` | optional | `true` | +| `seq` | required | `number` | +| `time` | required | `number` | +| `type` | required | `"job/settled"` | + @@ -8225,7 +8463,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:28`](../packages/llm/llm/src SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095` -Sources: [`packages/llm/llm/src/types.ts:455`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:471`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8345,17 +8583,17 @@ SHA-256: `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | `time` | required | `number` | | `type` | required | `"session/title"` | - + ### `{ type: "session/title-llm-request" }` -SHA-256: `b33545b3244861bcbf73b407d24b53402710f5acacab7ae939537e5504a68dc6` +SHA-256: `79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056` | Property | Presence | Type | |---|---|---| -| `data` | required | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-045926475a46f625f84ae2be292b384817059f16927c69a9adab93717923ac19) | +| `data` | required | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-00c054d3018c198d92f459563331edd1385e58345c677bb499791df2da0ade9f) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | @@ -8545,7 +8783,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:21`](../packages/llm/llm/src SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65` -Sources: [`packages/llm/llm/src/types.ts:454`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:470`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8593,7 +8831,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:35`](../packages/llm/llm/src SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a` -Sources: [`packages/llm/llm/src/types.ts:456`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:472`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8771,24 +9009,24 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` -Sources: [`packages/llm/llm/src/types.ts:458`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:474`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| | `type` | required | `"usage"` | | `usage` | required | [`TokenUsage`](#persistence-type-sha256-fec5442b9ee4122e10514d81d5a43648003fe8bfb7ee2ba50c0cdbdd383ed394) | - + ### `{ type: "user/message" }` -SHA-256: `2ace3b8059b82b6d9837fed518ca97a99eb37c4482df7aad0e71c85489428ade` +SHA-256: `2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8` | Property | Presence | Type | |---|---|---| -| `data` | required | [`UserMessage`](#persistence-type-sha256-89b2edff547be1ecfcd78ef18aeeb3cf507fcbf7d6093ec04fb111ef4c8e8a97) | +| `data` | required | [`UserMessage`](#persistence-type-sha256-2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `sourceEventSeqs` | optional | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 4e8c425b73..c1eb47569f 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -25,7 +25,7 @@ | `JsonlHeaderLine` | header | `18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f` | [`HeaderLine`](#persistence-type-sha256-18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f) | | `SessionEventEnvelope` | envelope | `5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc` | [`union (3 variants)`](#persistence-type-sha256-5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc) | | `event:agent-preset/selected` | event | `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | [`{ type: "agent-preset/selected" }`](#persistence-type-sha256-a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b) | -| `event:agent/inbox/spliced` | event | `9a36727716d0e73f681f3b725e7f28f89417c68174c8af0ff2b1ef52b08326a0` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-9a36727716d0e73f681f3b725e7f28f89417c68174c8af0ff2b1ef52b08326a0) | +| `event:agent/inbox/spliced` | event | `0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034) | | `event:approval/asked` | event | `3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1` | [`{ type: "approval/asked" }`](#persistence-type-sha256-3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1) | | `event:approval/decided` | event | `bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3` | [`{ type: "approval/decided" }`](#persistence-type-sha256-bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3) | | `event:approval/policy` | event | `26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78` | [`{ type: "approval/policy" }`](#persistence-type-sha256-26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78) | @@ -38,7 +38,7 @@ | `event:compaction/start` | event | `db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965` | [`{ type: "compaction/start" }`](#persistence-type-sha256-db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965) | | `event:compaction/summary` | event | `e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602` | [`{ type: "compaction/summary" }`](#persistence-type-sha256-e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602) | | `event:deliverables/presented` | event | `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | [`{ type: "deliverables/presented" }`](#persistence-type-sha256-13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176) | -| `event:developer/message` | event | `ba5b10ea77d68f4a29439a9bd2a14f6a560acf55731749d57237757cc72fbc06` | [`{ type: "developer/message" }`](#persistence-type-sha256-ba5b10ea77d68f4a29439a9bd2a14f6a560acf55731749d57237757cc72fbc06) | +| `event:developer/message` | event | `97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c` | [`{ type: "developer/message" }`](#persistence-type-sha256-97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c) | | `event:feedback/message-delete` | event | `3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796` | [`{ type: "feedback/message-delete" }`](#persistence-type-sha256-3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796) | | `event:feedback/message-put` | event | `b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf` | [`{ type: "feedback/message-put" }`](#persistence-type-sha256-b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf) | | `event:feedback/record` | event | `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` | [`{ type: "feedback/record" }`](#persistence-type-sha256-b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8) | @@ -46,6 +46,8 @@ | `event:hook/invoked` | event | `8a6e1ec9e8db346b0e02f027db73c07a94f067a26d40c1aef1abd09c47ce7ba0` | [`{ type: "hook/invoked" }`](#persistence-type-sha256-8a6e1ec9e8db346b0e02f027db73c07a94f067a26d40c1aef1abd09c47ce7ba0) | | `event:hook/result` | event | `e75916628f3f10c2d50658bd143052a46285fbf1a9a700ba54947614603d26b4` | [`{ type: "hook/result" }`](#persistence-type-sha256-e75916628f3f10c2d50658bd143052a46285fbf1a9a700ba54947614603d26b4) | | `event:image/offload` | event | `b222069eea2d768065161c1147b1f2c78c1b54328c84b3586ae5c8f91b8ed35e` | [`{ type: "image/offload" }`](#persistence-type-sha256-b222069eea2d768065161c1147b1f2c78c1b54328c84b3586ae5c8f91b8ed35e) | +| `event:job/registered` | event | `f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1` | [`{ type: "job/registered" }`](#persistence-type-sha256-f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1) | +| `event:job/settled` | event | `edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf` | [`{ type: "job/settled" }`](#persistence-type-sha256-edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf) | | `event:llm/retry` | event | `525254db03b1d1e6b74cf55aced52817568331ac1f96c0818728910b6692e336` | [`{ type: "llm/retry" }`](#persistence-type-sha256-525254db03b1d1e6b74cf55aced52817568331ac1f96c0818728910b6692e336) | | `event:llm/retry-started` | event | `48e5c9861f16ac07e78cb7b5ae9dabdf7bb85c58baed5a51b4ad275050ea58e3` | [`{ type: "llm/retry-started" }`](#persistence-type-sha256-48e5c9861f16ac07e78cb7b5ae9dabdf7bb85c58baed5a51b4ad275050ea58e3) | | `event:model/selection` | event | `35203ba7ad5ef6f97d556b85df20ae98f04f09c65748cecdf8eefdb8b6405ffc` | [`{ type: "model/selection" }`](#persistence-type-sha256-35203ba7ad5ef6f97d556b85df20ae98f04f09c65748cecdf8eefdb8b6405ffc) | @@ -58,7 +60,7 @@ | `event:session-log-deepseek/delivery-accepted` | event | `d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9` | [`{ type: "session-log-deepseek/delivery-accepted" }`](#persistence-type-sha256-d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9) | | `event:session/end-seed` | event | `5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e` | [`{ type: "session/end-seed" }`](#persistence-type-sha256-5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e) | | `event:session/title` | event | `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | [`{ type: "session/title" }`](#persistence-type-sha256-1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5) | -| `event:session/title-llm-request` | event | `b33545b3244861bcbf73b407d24b53402710f5acacab7ae939537e5504a68dc6` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-b33545b3244861bcbf73b407d24b53402710f5acacab7ae939537e5504a68dc6) | +| `event:session/title-llm-request` | event | `79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056) | | `event:step/end` | event | `e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05` | [`{ type: "step/end" }`](#persistence-type-sha256-e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05) | | `event:step/start` | event | `4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986` | [`{ type: "step/start" }`](#persistence-type-sha256-4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986) | | `event:subagent/catalog` | event | `53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac` | [`{ type: "subagent/catalog" }`](#persistence-type-sha256-53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac) | @@ -80,7 +82,7 @@ | `event:tool/result` | event | `7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397` | [`{ type: "tool/result" }`](#persistence-type-sha256-7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397) | | `event:turn/end` | event | `0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce` | [`{ type: "turn/end" }`](#persistence-type-sha256-0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce) | | `event:turn/start` | event | `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` | [`{ type: "turn/start" }`](#persistence-type-sha256-aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8) | -| `event:user/message` | event | `2ace3b8059b82b6d9837fed518ca97a99eb37c4482df7aad0e71c85489428ade` | [`{ type: "user/message" }`](#persistence-type-sha256-2ace3b8059b82b6d9837fed518ca97a99eb37c4482df7aad0e71c85489428ade) | +| `event:user/message` | event | `2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8` | [`{ type: "user/message" }`](#persistence-type-sha256-2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8) | | `event:web/deepseek-search-llm-request` | event | `cf6e3aaf1e2de6480aa0157730a41b9a492108a55304100b0f7e112711dd4331` | [`{ type: "web/deepseek-search-llm-request" }`](#persistence-type-sha256-cf6e3aaf1e2de6480aa0157730a41b9a492108a55304100b0f7e112711dd4331) | | `event:working-directory/change` | event | `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3) | | `event:workspace/changes` | event | `e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72` | [`{ type: "workspace/changes" }`](#persistence-type-sha256-e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72) | @@ -160,7 +162,7 @@ export type SessionEvent = { }[T] ``` -来源:[`packages/core/session/src/types.ts:431`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:439`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:462`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:493`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:432`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:440`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:463`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:494`](../packages/core/session/src/types.ts) ## 事件 @@ -198,12 +200,15 @@ export type SessionEvent = { * The session's agent preset was chosen after creation, while the session * was still blank. Log-only: it records the composition later turns ran * under, so a resumed or forked session rebuilds the same one instead of - * the header's creation-time value. + * the header's creation-time value. In a child Session, an occurrence + * before its first own `subagent/descriptor` marks an independent spawn + * selection that cold resume restores instead of joining the parent's + * composition (`dsh-subagent` README, "Restoring child composition"). */ 'agent-preset/selected': { agentPreset: string } ``` -来源:[`packages/preset/agent-preset-registry/src/session.ts:28`](../packages/preset/agent-preset-registry/src/session.ts) +来源:[`packages/preset/agent-preset-registry/src/session.ts:31`](../packages/preset/agent-preset-registry/src/session.ts) ### `approval/*` @@ -287,7 +292,7 @@ export type SessionEvent = { 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[] } ``` -来源:[`packages/core/session/src/types.ts:355`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:356`](../packages/core/session/src/types.ts) @@ -317,7 +322,7 @@ export type SessionEvent = { 类型:[TokenUsage](subsystems/llm-streaming.zh.md) -来源:[`packages/core/session/src/types.ts:341`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:342`](../packages/core/session/src/types.ts) ### `command/*` @@ -505,7 +510,7 @@ export type SessionEvent = { } ``` -来源:[`packages/core/session/src/types.ts:311`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:312`](../packages/core/session/src/types.ts) ### `feedback/*` @@ -629,6 +634,36 @@ export type SessionEvent = { 来源:[`packages/compaction/compaction-image-offload/src/projection.ts:25`](../packages/compaction/compaction-image-offload/src/projection.ts) +### `job/*` + + + +#### `job/registered` — log-only + +```ts persistence-catalog +/** + * Log-only job registration; model output collection is not required. + * @param data - Execution identity, original owner, registration time, and creating tool call. + */ +'job/registered': JobRegisteredData +``` + +来源:[`packages/jobs/jobs/src/types.ts:59`](../packages/jobs/jobs/src/types.ts) + + + +#### `job/settled` — log-only + +```ts persistence-catalog +/** + * Log-only terminal record, paired by the same unique jobId used for live control. + * @param data - Registration facts plus settlement time, outcome, and producer acknowledgement. + */ +'job/settled': JobSettledData +``` + +来源:[`packages/jobs/jobs/src/types.ts:64`](../packages/jobs/jobs/src/types.ts) + ### `llm/*` @@ -667,7 +702,7 @@ export type SessionEvent = { 'model/selection': ModelSelection ``` -来源:[`packages/api/session-controller/src/types.ts:40`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:41`](../packages/api/session-controller/src/types.ts) ### `permission/*` @@ -720,7 +755,7 @@ export type SessionEvent = { 'request/context': RequestContext ``` -来源:[`packages/core/session/src/types.ts:402`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:403`](../packages/core/session/src/types.ts) @@ -739,7 +774,7 @@ export type SessionEvent = { } ``` -来源:[`packages/core/session/src/types.ts:390`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:391`](../packages/core/session/src/types.ts) ### `sandbox/*` @@ -816,7 +851,7 @@ export type SessionEvent = { 'session/end-seed': { inherited?: true } ``` -来源:[`packages/core/session/src/types.ts:427`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:428`](../packages/core/session/src/types.ts) @@ -845,7 +880,7 @@ export type SessionEvent = { 类型:[SessionTitleLlmRequestEventData](subsystems/session-title.zh.md) -来源:[`packages/session/session-title-llm/src/index.ts:54`](../packages/session/session-title-llm/src/index.ts) +来源:[`packages/session/session-title-llm/src/index.ts:57`](../packages/session/session-title-llm/src/index.ts) ### `session-log-deepseek/*` @@ -878,7 +913,7 @@ export type SessionEvent = { 'step/end': { turn: number; step: number } ``` -来源:[`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:302`](../packages/core/session/src/types.ts) @@ -889,7 +924,7 @@ export type SessionEvent = { 'step/start': { turn: number; step: number } ``` -来源:[`packages/core/session/src/types.ts:299`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:300`](../packages/core/session/src/types.ts) ### `subagent/*` @@ -965,7 +1000,7 @@ export type SessionEvent = { 'system/message': { turn: number; step: number; message: SystemMessage } ``` -来源:[`packages/core/session/src/types.ts:330`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:331`](../packages/core/session/src/types.ts) ### `team/*` @@ -980,14 +1015,14 @@ export type SessionEvent = { 类型:[TeamId](subsystems/agent-team.zh.md) · [TeamMemberSnapshot](subsystems/agent-team.zh.md) -来源:[`packages/experimental/agent-team/src/types.ts:232`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:230`](../packages/experimental/agent-team/src/types.ts) #### `team/message/delivered` — log-only ```ts persistence-catalog -/** Durable acknowledgement that the target Session recorded the message. */ +/** Historical acknowledgement that the target Session recorded a queued message. */ 'team/message/delivered': { version: 2 teamId: TeamId @@ -998,20 +1033,20 @@ export type SessionEvent = { 类型:[TeamId](subsystems/agent-team.zh.md) · [TeamMessageId](subsystems/agent-team.zh.md) -来源:[`packages/experimental/agent-team/src/types.ts:238`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:236`](../packages/experimental/agent-team/src/types.ts) #### `team/message/queued` — log-only ```ts persistence-catalog -/** Durable mailbox enqueue, stored before delivery is attempted. */ +/** Historical mailbox enqueue; new sends use the target Agent inbox. */ 'team/message/queued': { version: 2; teamId: TeamId; message: TeamMessageSnapshot } ``` 类型:[TeamId](subsystems/agent-team.zh.md) · [TeamMessageSnapshot](subsystems/agent-team.zh.md) -来源:[`packages/experimental/agent-team/src/types.ts:236`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:234`](../packages/experimental/agent-team/src/types.ts) @@ -1024,7 +1059,7 @@ export type SessionEvent = { 类型:[TeamId](subsystems/agent-team.zh.md) · [TeamTaskSnapshot](subsystems/agent-team.zh.md) -来源:[`packages/experimental/agent-team/src/types.ts:234`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:232`](../packages/experimental/agent-team/src/types.ts) ### `todo/*` @@ -1058,7 +1093,7 @@ export type SessionEvent = { 类型:[ToolCallId](subsystems/core.zh.md) -来源:[`packages/core/session/src/types.ts:361`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:362`](../packages/core/session/src/types.ts) @@ -1139,7 +1174,7 @@ export type SessionEvent = { } ``` -来源:[`packages/core/session/src/types.ts:375`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:376`](../packages/core/session/src/types.ts) ### `tool-workflow/*` @@ -1219,7 +1254,7 @@ export type SessionEvent = { 类型:[TurnEndReason](subsystems/session.zh.md) -来源:[`packages/core/session/src/types.ts:297`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:298`](../packages/core/session/src/types.ts) @@ -1235,7 +1270,7 @@ export type SessionEvent = { 'turn/start': { turn: number } ``` -来源:[`packages/core/session/src/types.ts:288`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:289`](../packages/core/session/src/types.ts) ### `user/*` @@ -1254,7 +1289,7 @@ export type SessionEvent = { 'user/message': UserMessage ``` -来源:[`packages/core/session/src/types.ts:309`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:310`](../packages/core/session/src/types.ts) ### `web/*` @@ -1956,7 +1991,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8` SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5` -来源:[`packages/llm/llm/src/types.ts:396`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:412`](../packages/llm/llm/src/types.ts) `"in-history"` @@ -2000,6 +2035,38 @@ SHA-256: `69d238a6e9b08d67f601b1825962963d8d3523cb69ebf6208c697dc5d058c199` `"interrupted"` + + +### `"job/registered"` + +SHA-256: `24a8188c4d61b70a01af8cc576748765d36f132632ec55c0064f6fba482369fc` + +`"job/registered"` + + + +### `"job/settled"` + +SHA-256: `347de3380f2da308d0c74e08821f9e85559f55af4c5010795b110d00f7fc9dbd` + +`"job/settled"` + + + +### `"kill"` + +SHA-256: `bab68657940075483f086fffb711682a45bcc99c43d659fbe1c36af21ac05dd7` + +`"kill"` + + + +### `"killed"` + +SHA-256: `ef226a90ddac6cd8e631a3a337a3a3e27f9494be92befb7c718b404681d75e21` + +`"killed"` + ### `"legacy"` @@ -2120,6 +2187,14 @@ SHA-256: `9d80129e13edfb6feb03ed327e6085c6ef60b97ad074244b2f5fd4667424a6a4` `"other"` + + +### `"owner"` + +SHA-256: `95a3ffccbf3c8afcf9a2f3b355f724da8e07e98dc47ee741166dde7f9ea058bd` + +`"owner"` + ### `"parent"` @@ -2184,6 +2259,14 @@ SHA-256: `df5d9709b7db2a72510dc52052a23f0c38f39730af1504bab8bccabc14fae528` `"positive"` + + +### `"producer"` + +SHA-256: `6cf082d0fb6034dea61636787ff0ddf43b6e59aad71e644435a479bc9b83ad65` + +`"producer"` + ### `"product-interaction"` @@ -2608,6 +2691,14 @@ SHA-256: `b57ae1b37e52bee0a21cbdace168dc6a15582bcda8c306dad962c5dcc8a8e28b` `"team/task"` + + +### `"teardown"` + +SHA-256: `5cb63db9fe57dc09c3a1c2b84c3edf73ff5b62960155d8436a2377a5c43ce32c` + +`"teardown"` + ### `"text"` @@ -3125,7 +3216,7 @@ SHA-256: `84bbfdce7d2eab5b0c53e72ff7406db856c8bfd621b965b72fd86598ba493bf7` SHA-256: `ada310bf0bdb8fed51f3b56ea63f6ea6b18bbd587f04fccb63a14ab0b2a24e05` -来源:[`packages/core/session/src/types.ts:190`](../packages/core/session/src/types.ts) · [`packages/interaction/commands/src/types.ts:75`](../packages/interaction/commands/src/types.ts) · [`packages/interaction/commands/src/types.ts:79`](../packages/interaction/commands/src/types.ts) · [`packages/llm/llm/src/message.ts:111`](../packages/llm/llm/src/message.ts) · [`packages/session/session-title/src/types.ts:35`](../packages/session/session-title/src/types.ts) +来源:[`packages/core/session/src/types.ts:191`](../packages/core/session/src/types.ts) · [`packages/interaction/commands/src/types.ts:75`](../packages/interaction/commands/src/types.ts) · [`packages/interaction/commands/src/types.ts:79`](../packages/interaction/commands/src/types.ts) · [`packages/llm/llm/src/message.ts:111`](../packages/llm/llm/src/message.ts) · [`packages/session/session-title/src/types.ts:35`](../packages/session/session-title/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -3268,7 +3359,7 @@ SHA-256: `2517ba143a271508d3ca35126d5aca8f7f1facf5aaddce4adf011832042fa2b9` | `body` | 必需 | [`{ max_tokens, messages, model, tools }`](#persistence-type-sha256-930a6567a10bb62ddd157bd8abdf4b182810c8c3b49d91309b3b009a5fed9731) | | `endpoint` | 必需 | `string` | - + @@ -3276,7 +3367,7 @@ SHA-256: `2517ba143a271508d3ca35126d5aca8f7f1facf5aaddce4adf011832042fa2b9` ### `DeveloperMessage` -SHA-256: `af99c95d46bed802870f1ebefe0ea11f92a03cb37b8e0cbe3f94b7aaaf509b08` +SHA-256: `0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7` 来源:[`packages/llm/llm/src/message.ts:157`](../packages/llm/llm/src/message.ts) @@ -3285,7 +3376,7 @@ SHA-256: `af99c95d46bed802870f1ebefe0ea11f92a03cb37b8e0cbe3f94b7aaaf509b08` | `content` | 必需 | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | 必需 | `string` | | `role` | 必需 | `"developer"` | -| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-1fa156c85450ca31063d0e0d2853028e6dac9687f2d3191fa811648210118154) | +| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8) | 消息源兼容策略:`source` — `session-source-attribution` v1; `session.developer-message.source`; `kind`; `preserve`. @@ -3301,7 +3392,7 @@ SHA-256: `af99c95d46bed802870f1ebefe0ea11f92a03cb37b8e0cbe3f94b7aaaf509b08` SHA-256: `9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7` -来源:[`packages/core/session/src/types.ts:240`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:241`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -3698,6 +3789,88 @@ SHA-256: `96f4a9c81fc0f940ef71528a8cc66731ae4cf1f40d79680c5fe3c39f96d7723c` - `"next-step"` - `"next-turn"` + + + + + + +### `JobRegisteredData` + +SHA-256: `e3056e0dda3a379e895386e368c3ce42131460ea65e410e1d091cca98a347305` + +来源:[`packages/jobs/jobs/src/types.ts:24`](../packages/jobs/jobs/src/types.ts) + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `jobId` | 必需 | `string` | +| `kind` | 必需 | `string` | +| `label` | 必需 | `string` | +| `owner` | 必需 | `string` | +| `startedAt` | 必需 | `number` | +| `toolCall` | 可选 | [`JobToolCall`](#persistence-type-sha256-39cf2d3ff8bac81c62d49ac2ba38a095b18e80f3ad700819fa1f650a4e60197f) | + + + + + + + +### `JobSettleCause` + +SHA-256: `750a2b129d67704df675c06823c20c80b65cbae89d5aaa914fd5a72e3df395b5` + +来源:[`packages/jobs/jobs/src/types.ts:247`](../packages/jobs/jobs/src/types.ts) + +以下类型之一: + +- `"kill"` +- `"producer"` +- `"teardown"` + + + + + + + +### `JobSettledData` + +SHA-256: `611d82d2dc50df706cf08a0fc04bc8eaf78083391fe6f10313de943e615dd2da` + +来源:[`packages/jobs/jobs/src/types.ts:40`](../packages/jobs/jobs/src/types.ts) + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `cause` | 必需 | [`JobSettleCause`](#persistence-type-sha256-750a2b129d67704df675c06823c20c80b65cbae89d5aaa914fd5a72e3df395b5) | +| `detail` | 可选 | `string` | +| `finishedAt` | 必需 | `number` | +| `jobId` | 必需 | `string` | +| `kind` | 必需 | `string` | +| `label` | 必需 | `string` | +| `owner` | 必需 | `string` | +| `producerReported` | 必需 | `boolean` | +| `startedAt` | 必需 | `number` | +| `status` | 必需 | [`union (3 variants)`](#persistence-type-sha256-c2f49004d9ae38a964e80850c87bc6849d6a872091a1d43e99eedf00c641e2a3) | +| `toolCall` | 可选 | [`JobToolCall`](#persistence-type-sha256-39cf2d3ff8bac81c62d49ac2ba38a095b18e80f3ad700819fa1f650a4e60197f) | + + + + + + + +### `JobToolCall` + +SHA-256: `39cf2d3ff8bac81c62d49ac2ba38a095b18e80f3ad700819fa1f650a4e60197f` + +来源:[`packages/jobs/jobs/src/types.ts:16`](../packages/jobs/jobs/src/types.ts) + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `callId` | 必需 | `string` | +| `rootCallId` | 必需 | `string` | + @@ -3902,7 +4075,7 @@ SHA-256: `6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20` | `step` | 必需 | `number` | | `turn` | 必需 | `number` | - + @@ -3910,17 +4083,17 @@ SHA-256: `6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20` ### `Message` -SHA-256: `d901c4f5e856591c3217af983caa15bba568d580700f0958bab56b88004eced9` +SHA-256: `040cd65423bd64264d225504f1c572d239eeb1793d0c2856ad8e42bb6e1e148b` 来源:[`packages/llm/llm/src/message.ts:196`](../packages/llm/llm/src/message.ts) 以下类型之一: - [`ToolResultMessage`](#persistence-type-sha256-4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731) -- [`DeveloperMessage`](#persistence-type-sha256-af99c95d46bed802870f1ebefe0ea11f92a03cb37b8e0cbe3f94b7aaaf509b08) -- [`UserMessage`](#persistence-type-sha256-89b2edff547be1ecfcd78ef18aeeb3cf507fcbf7d6093ec04fb111ef4c8e8a97) -- [`SystemMessage`](#persistence-type-sha256-09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363) +- [`DeveloperMessage`](#persistence-type-sha256-0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7) +- [`UserMessage`](#persistence-type-sha256-2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711) - [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) +- [`SystemMessage`](#persistence-type-sha256-09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363) @@ -3995,7 +4168,7 @@ SHA-256: `390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2` - `"negative"` - `"positive"` - + @@ -4003,7 +4176,7 @@ SHA-256: `390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2` ### `MessageSource` -SHA-256: `1fa156c85450ca31063d0e0d2853028e6dac9687f2d3191fa811648210118154` +SHA-256: `5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8` 来源:[`packages/llm/llm/src/message.ts:136`](../packages/llm/llm/src/message.ts) @@ -4108,7 +4281,7 @@ SHA-256: `1fa156c85450ca31063d0e0d2853028e6dac9687f2d3191fa811648210118154` | `tool-jobs` | `"snapshot"` | `sections`: [`ContextSnapshotSection[]`](#persistence-type-sha256-c748fb42c80a120038a8c587af80ec39924803c401364db11c8974d5bf6d0262) | [`{ kind: "tool-jobs", form: "snapshot" }`](#persistence-type-sha256-c5228b7a55498d84f529591744a0ab26e0b93ade18a70a26db1377a1ecfa6b49) | | `tool-jobs` | 未声明 | 无 | [`{ kind: "tool-jobs" }`](#persistence-type-sha256-24ce31aa528272e59f21cd26da9eca08968bcc97529756a749bfdab71746d9c8) | | `tool-registry` | 未声明 | 无 | [`{ kind: "tool-registry" }`](#persistence-type-sha256-8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543) | -| `user` | 未声明 | `rpcId`: `string` | [`{ kind: "user" }`](#persistence-type-sha256-6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7) | +| `user` | 未声明 | `rpcId`: `string` | [`{ kind: "user" }`](#persistence-type-sha256-6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def) | | `user` | 未声明 | 无 | [`CommandSource`](#persistence-type-sha256-ada310bf0bdb8fed51f3b56ea63f6ea6b18bbd587f04fccb63a14ab0b2a24e05) | | `user-approval` | `"catalog"` | 无 | [`{ kind: "user-approval", form: "catalog" }`](#persistence-type-sha256-825ca23416b1ea9d81442afead5cf9229a6fa05842f042135cc3aa9710a6a2d8) | | `user-approval` | `"instructions"` | 无 | [`{ kind: "user-approval", form: "instructions" }`](#persistence-type-sha256-aa2bf9e82b9fdeb94a42af20031fffa30e4e23f01f4ac39757427d4c64c407f0) | @@ -4121,13 +4294,13 @@ SHA-256: `1fa156c85450ca31063d0e0d2853028e6dac9687f2d3191fa811648210118154` | `webhook` | `"notice"` | `deliveryId`: `string`; `provider`: `string`; `ruleId`: `string`; `source`: `string`; `summary`: `string` | [`{ kind: "webhook", form: "notice" }`](#persistence-type-sha256-9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94) | | `working-directory` | 未声明 | 无 | [`{ kind: "working-directory" }`](#persistence-type-sha256-2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5) | - + ### `Message[]` -SHA-256: `4be8fd28fefa5534675ea9aabd0a24efc2838b989bbc74da20a1efbd0daede8c` +SHA-256: `a927d444c928ac0efd9dd8b2e7d7d04d711c264cb71578d81e0e2fd143ff669f` -[`Message`](#persistence-type-sha256-d901c4f5e856591c3217af983caa15bba568d580700f0958bab56b88004eced9) 的数组。 +[`Message`](#persistence-type-sha256-040cd65423bd64264d225504f1c572d239eeb1793d0c2856ad8e42bb6e1e148b) 的数组。 @@ -4158,7 +4331,7 @@ SHA-256: `719c51f67074f97034a6c94297fe1f4b5d3c8d392c57586dab732aa5398c7a91` SHA-256: `f09e5e7acf5ff5ccd193ff2eeec015fa2ff7c29d98bc465f8c3302058d47e29b` -来源:[`packages/api/session-controller/src/types.ts:100`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:101`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4213,7 +4386,7 @@ SHA-256: `5f758f3de5f00c18968a7c6d347083aac5c9ae13f6a79c78f6611b23c4973564` SHA-256: `3bd652ebfa8726b3ce3937a4f1bd2759e02f86b3a08a20f9e41a8513656fbc5f` -来源:[`packages/core/session/src/types.ts:65`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:66`](../packages/core/session/src/types.ts) 以下类型之一: @@ -4245,6 +4418,22 @@ SHA-256: `1d9cb3caa96100b18b1911fa3ff8c751ef6992971a03c5f4d9aefc1a0004a345` [`PresentedFile`](#persistence-type-sha256-b8fc636a2121df9d8423c242e03c9d23b7ab7c6fdce00e45746932c60b730f97) 的数组。 + + + + + + +### `Principal` + +SHA-256: `deebfc7c62177ea840f23c6362b8615bc78ffa93377dd5d243c04e541c413af5` + +来源:[`packages/typert/protocol/src/types.ts:457`](../packages/typert/protocol/src/types.ts) · [`packages/typert/protocol/src/types.ts:461`](../packages/typert/protocol/src/types.ts) + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `kind` | 必需 | `"owner"` | + @@ -4316,7 +4505,7 @@ SHA-256: `814d9434e1ddf9078612b3b34322f26e9363b469213335007f7e9ba7fee9464e` SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` -来源:[`packages/llm/llm/src/types.ts:430`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:446`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4333,7 +4522,7 @@ SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` SHA-256: `b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081` -来源:[`packages/core/session/src/types.ts:254`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:255`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4352,7 +4541,7 @@ SHA-256: `b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081` SHA-256: `530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6` -来源:[`packages/core/session/src/types.ts:273`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:274`](../packages/core/session/src/types.ts) 以下类型之一: @@ -4444,7 +4633,7 @@ SHA-256: `18dc21f12bbac8ade8377e6fbb54179e20c3d955d73fba3244c57fb6bf001df0` SHA-256: `1a3440e3577382704d42a6263aa463504eb74c566734a55e9503a63efcd02445` -来源:[`packages/core/session/src/types.ts:94`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:95`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4495,7 +4684,7 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` | `source` | 必需 | [`SessionTitleSource`](#persistence-type-sha256-30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f) | | `title` | 必需 | `string` | - + @@ -4503,15 +4692,15 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` ### `SessionTitleLlmRequestEventData` -SHA-256: `045926475a46f625f84ae2be292b384817059f16927c69a9adab93717923ac19` +SHA-256: `00c054d3018c198d92f459563331edd1385e58345c677bb499791df2da0ade9f` -来源:[`packages/session/session-title-llm/src/index.ts:34`](../packages/session/session-title-llm/src/index.ts) +来源:[`packages/session/session-title-llm/src/index.ts:37`](../packages/session/session-title-llm/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| | `maxTokens` | 必需 | `number` | | `messageSeqs` | 必需 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | -| `messages` | 必需 | [`Message[]`](#persistence-type-sha256-4be8fd28fefa5534675ea9aabd0a24efc2838b989bbc74da20a1efbd0daede8c) | +| `messages` | 必需 | [`Message[]`](#persistence-type-sha256-a927d444c928ac0efd9dd8b2e7d7d04d711c264cb71578d81e0e2fd143ff669f) | | `reasoningEffort` | 可选 | `string` | | `route` | 必需 | [`SessionTitleModelIdentity`](#persistence-type-sha256-07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235) | | `system` | 必需 | `string` | @@ -4611,7 +4800,7 @@ SHA-256: `672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db` SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180` -来源:[`packages/llm/llm/src/types.ts:452`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:468`](../packages/llm/llm/src/types.ts) 以下类型之一: @@ -4690,7 +4879,7 @@ SHA-256: `4e97c3d85c0fc817ee58873c38c25a2474abaaa0af4839311b50b68db3b8cf1a` SHA-256: `335e242de1fcc17b6ca920fc420d71bec2d76e53e37955c00948b65ab77f05c5` -来源:[`packages/core/session/src/types.ts:462`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:463`](../packages/core/session/src/types.ts) 以下类型之一: @@ -4742,7 +4931,7 @@ SHA-256: `65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad` SHA-256: `dfce5db4aa42b7ebe0bb79eca92553587287e18c06b9eba85cbfb9d332e26acd` -来源:[`packages/experimental/agent-team/src/types.ts:44`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:45`](../packages/experimental/agent-team/src/types.ts) 以下类型之一: @@ -4760,7 +4949,7 @@ SHA-256: `dfce5db4aa42b7ebe0bb79eca92553587287e18c06b9eba85cbfb9d332e26acd` SHA-256: `6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25` -来源:[`packages/experimental/agent-team/src/types.ts:47`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:48`](../packages/experimental/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4782,7 +4971,7 @@ SHA-256: `6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25` SHA-256: `2eafefdc6f79a4922d68a787a09eaf4dd2b2369c3777fba4c05e800b5678ac8e` -来源:[`packages/experimental/agent-team/src/types.ts:128`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:129`](../packages/experimental/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4802,7 +4991,7 @@ SHA-256: `2eafefdc6f79a4922d68a787a09eaf4dd2b2369c3777fba4c05e800b5678ac8e` SHA-256: `2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0` -来源:[`packages/experimental/agent-team/src/types.ts:137`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:138`](../packages/experimental/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4822,7 +5011,7 @@ SHA-256: `2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0` SHA-256: `51edec100659da3a9bd9c3f6ba1180f5e64ec9a1585e5057080df45c180bd357` -来源:[`packages/experimental/agent-team/src/types.ts:74`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:75`](../packages/experimental/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4845,7 +5034,7 @@ SHA-256: `51edec100659da3a9bd9c3f6ba1180f5e64ec9a1585e5057080df45c180bd357` SHA-256: `b2d2a01e51341a3bfec809198952c8c830a7899f4cb6ecd3c1dc0b5d9a2af943` -来源:[`packages/experimental/agent-team/src/types.ts:71`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:72`](../packages/experimental/agent-team/src/types.ts) 以下类型之一: @@ -5036,7 +5225,7 @@ SHA-256: `4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731` SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2` -来源:[`packages/llm/llm/src/types.ts:473`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:489`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5135,7 +5324,7 @@ SHA-256: `a6da9ad5d42ae83a6833a8288b076688e8e0801633ea36cbdd8a30a6d9f3160c` SHA-256: `1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0` -来源:[`packages/core/session/src/types.ts:196`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:197`](../packages/core/session/src/types.ts) | kind | form 属性 | 其他必需字段 | 完整定义 | |---|---|---|---| @@ -5155,7 +5344,7 @@ SHA-256: `1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0` SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` -来源:[`packages/core/session/src/types.ts:232`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:233`](../packages/core/session/src/types.ts) | kind | form 属性 | 其他必需字段 | 完整定义 | |---|---|---|---| @@ -5167,7 +5356,7 @@ SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` | `interrupted` | 未声明 | 无 | [`{ kind: "interrupted" }`](#persistence-type-sha256-56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23) | | `max-tokens` | 未声明 | 无 | [`{ kind: "max-tokens" }`](#persistence-type-sha256-ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7) | - + @@ -5175,7 +5364,7 @@ SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` ### `UserMessage` -SHA-256: `89b2edff547be1ecfcd78ef18aeeb3cf507fcbf7d6093ec04fb111ef4c8e8a97` +SHA-256: `2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711` 来源:[`packages/llm/llm/src/message.ts:162`](../packages/llm/llm/src/message.ts) @@ -5184,19 +5373,19 @@ SHA-256: `89b2edff547be1ecfcd78ef18aeeb3cf507fcbf7d6093ec04fb111ef4c8e8a97` | `content` | 必需 | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | 必需 | `string` | | `role` | 必需 | `"user"` | -| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-1fa156c85450ca31063d0e0d2853028e6dac9687f2d3191fa811648210118154) | +| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8) | 消息源兼容策略:`source` — `session-source-attribution` v1; `session.user-message.source`; `kind`; `preserve`. 仅表示归属的新增 kind:`tmux-context`, `user-question-reply`, `working-directory`. - + ### `UserMessage[]` -SHA-256: `2fef90def36aa758ca096c5f6ad0e00dbb2101943e19ca54b05618801974894a` +SHA-256: `454a0fa879e38076bdcdbd87ef561cd67d7e43e58a287cf7dbaa7b6cf7847020` -[`UserMessage`](#persistence-type-sha256-89b2edff547be1ecfcd78ef18aeeb3cf507fcbf7d6093ec04fb111ef4c8e8a97) 的数组。 +[`UserMessage`](#persistence-type-sha256-2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711) 的数组。 @@ -5276,7 +5465,7 @@ SHA-256: `938f7c7357bc403ea3b281a9dd016939df7a0880fc8db12612585be574d0d615` SHA-256: `0657d3ca5ac4e7bf79b00bcf860b1c7159d01a9da137497221ec2f1776e365f7` -来源:[`packages/core/session/src/types.ts:32`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:33`](../packages/core/session/src/types.ts) `number` @@ -5300,6 +5489,8 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` + + @@ -5332,6 +5523,8 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` + + @@ -5384,7 +5577,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -来源:[`packages/api/session-controller/src/types.ts:398`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:20`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:32`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:8`](../packages/experimental/agent-team/src/types.ts) · [`packages/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:409`](../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:21`](../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/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.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` @@ -5493,6 +5686,18 @@ SHA-256: `904bf499d98be4a3a5f836fcac533b6c4899569b018071e6604e1d32657d00fd` - `"replace"` - `"set"` + + +### `union (3 variants)` + +SHA-256: `c2f49004d9ae38a964e80850c87bc6849d6a872091a1d43e99eedf00c641e2a3` + +以下类型之一: + +- `"completed"` +- `"failed"` +- `"killed"` + ### `union (3 variants)` @@ -5570,7 +5775,7 @@ SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` SHA-256: `6e52dd55a1d48954ed5464ec46fe34d9eb65f709baabc9561e7a279910b0c406` -来源:[`packages/preset/agent-preset-registry/src/session.ts:28`](../packages/preset/agent-preset-registry/src/session.ts) +来源:[`packages/preset/agent-preset-registry/src/session.ts:31`](../packages/preset/agent-preset-registry/src/session.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5609,7 +5814,7 @@ SHA-256: `a853902cfab417b8f08aa51ad6855fea46f34ed4588a74e47403035111d0fb86` SHA-256: `e4c18e294232c3ba6c9f1999f168263cc55956147cfe4121720899be8e52edd1` -来源:[`packages/core/session/src/types.ts:361`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:362`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5768,7 +5973,7 @@ SHA-256: `cbbe8377ee744964537dbafd83607219e58ba79a13f6db0d0645c7ad3d5e8a09` SHA-256: `a81059ca06999da1e712414520c2c65e491d052fcf9640fae20aa38f0a5dc735` -来源:[`packages/core/session/src/types.ts:383`](../packages/core/session/src/types.ts) · [`packages/core/tools/src/types.ts:27`](../packages/core/tools/src/types.ts) +来源:[`packages/core/session/src/types.ts:384`](../packages/core/session/src/types.ts) · [`packages/core/tools/src/types.ts:27`](../packages/core/tools/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5988,7 +6193,7 @@ SHA-256: `9e41386b3a0c9572b0d63078492ebb3997da7d3a830d44e0259418bd02f4bcb2` SHA-256: `bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825` -来源:[`packages/core/session/src/types.ts:464`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:465`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6002,7 +6207,7 @@ SHA-256: `bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825` SHA-256: `79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985` -来源:[`packages/core/session/src/types.ts:212`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:213`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6015,7 +6220,7 @@ SHA-256: `79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985` SHA-256: `5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777` -来源:[`packages/core/session/src/types.ts:375`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:376`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6057,7 +6262,7 @@ SHA-256: `693f4952fb5565da96c06bace8924b098ac2fbc915fde0ff8019701183abc057` SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` -来源:[`packages/core/session/src/types.ts:390`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:391`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6065,18 +6270,18 @@ SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` | `reason` | 必需 | [`RequestHeaderReason`](#persistence-type-sha256-530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6) | | `startsSeries` | 可选 | `true` | - + ### `{ headerSeq?, message, step, turn }` -SHA-256: `5b55817a403569fbb2d379496df2e3f3f71107f6c577a218028ce187c60b61e6` +SHA-256: `f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb` -来源:[`packages/core/session/src/types.ts:311`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:312`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| | `headerSeq` | 可选 | `number` | -| `message` | 必需 | [`DeveloperMessage`](#persistence-type-sha256-af99c95d46bed802870f1ebefe0ea11f92a03cb37b8e0cbe3f94b7aaaf509b08) | +| `message` | 必需 | [`DeveloperMessage`](#persistence-type-sha256-0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7) | | `step` | 必需 | `number` | | `turn` | 必需 | `number` | @@ -6154,23 +6359,23 @@ SHA-256: `e3e77b26f0148755a505f5b8ea843a3be117827d4703bb5754d9dc8ddbef521f` SHA-256: `17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3` -来源:[`packages/core/session/src/types.ts:427`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:428`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| | `inherited` | 可选 | `true` | - + ### `{ inserted, outcome?, removedCount?, start, … }` -SHA-256: `83a665476a9ee9af05cb1fdded12dd647d1b97b491200d7f12ef1af7cdac4428` +SHA-256: `fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42` 来源:[`packages/core/agent/src/types.ts:96`](../packages/core/agent/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| -| `inserted` | 必需 | [`UserMessage[]`](#persistence-type-sha256-2fef90def36aa758ca096c5f6ad0e00dbb2101943e19ca54b05618801974894a) | +| `inserted` | 必需 | [`UserMessage[]`](#persistence-type-sha256-454a0fa879e38076bdcdbd87ef561cd67d7e43e58a287cf7dbaa7b6cf7847020) | | `outcome` | 可选 | `"canceled"` | | `removedCount` | 可选 | `number` | | `start` | 必需 | `number` | @@ -6182,7 +6387,7 @@ SHA-256: `83a665476a9ee9af05cb1fdded12dd647d1b97b491200d7f12ef1af7cdac4428` SHA-256: `1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d` -来源:[`packages/core/session/src/types.ts:341`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:342`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6199,7 +6404,7 @@ SHA-256: `1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d` SHA-256: `0a30c3be336cdd4f8f34e66543a3d46d611c43986edd9b3ce6cbb9b721d3b5d3` -来源:[`packages/core/session/src/types.ts:204`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:205`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6212,7 +6417,7 @@ SHA-256: `0a30c3be336cdd4f8f34e66543a3d46d611c43986edd9b3ce6cbb9b721d3b5d3` SHA-256: `023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4` -来源:[`packages/core/session/src/types.ts:206`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:207`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6224,7 +6429,7 @@ SHA-256: `023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4` SHA-256: `b6ef9c6210be8350cd465f485cf520031fffa6bf3809c61a1e713e834c5982d0` -来源:[`packages/core/session/src/types.ts:202`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:203`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6248,7 +6453,7 @@ SHA-256: `02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79` SHA-256: `4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db` -来源:[`packages/core/session/src/types.ts:193`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:194`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6350,7 +6555,7 @@ SHA-256: `1b5649238876e28811e80f10ec67a00c197ad3babd4ecc61a22b09064b88c597` SHA-256: `ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7` -来源:[`packages/core/session/src/types.ts:228`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:229`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6362,7 +6567,7 @@ SHA-256: `ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7` SHA-256: `6c5a37d42ebdb12db4410699259335f1e149e3a0260425684c00b153afc8990d` -来源:[`packages/core/session/src/types.ts:192`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:193`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6531,7 +6736,7 @@ SHA-256: `88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa` SHA-256: `56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23` -来源:[`packages/core/session/src/types.ts:221`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:222`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6543,7 +6748,7 @@ SHA-256: `56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23` SHA-256: `eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c` -来源:[`packages/core/session/src/types.ts:196`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:197`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6555,7 +6760,7 @@ SHA-256: `eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c` SHA-256: `ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7` -来源:[`packages/core/session/src/types.ts:214`](../packages/core/session/src/types.ts) · [`packages/llm/llm/src/types.ts:159`](../packages/llm/llm/src/types.ts) +来源:[`packages/core/session/src/types.ts:215`](../packages/core/session/src/types.ts) · [`packages/llm/llm/src/types.ts:159`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6645,7 +6850,7 @@ SHA-256: `52c6113cb0e53f345324bf84f01928bea5d5df57ee80bc0dd65407b8bc5a3734` SHA-256: `6c03546143cdf6ae88f1745ac98c5139efa1588d1415249bbc5f3104d32ab800` -来源:[`packages/core/session/src/types.ts:191`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:192`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6749,7 +6954,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) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7337,18 +7542,19 @@ SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543` |---|---|---| | `kind` | 必需 | `"tool-registry"` | - + ### `{ kind: "user" }` -SHA-256: `6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7` +SHA-256: `6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def` -来源:[`packages/api/session-controller/src/types.ts:403`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:418`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| | `clientTimeZone` | 可选 | `string` | | `kind` | 必需 | `"user"` | +| `principal` | 可选 | [`Principal`](#persistence-type-sha256-deebfc7c62177ea840f23c6362b8615bc78ffa93377dd5d243c04e541c413af5) | | `rpcId` | 必需 | `string` | @@ -7494,7 +7700,7 @@ SHA-256: `930a6567a10bb62ddd157bd8abdf4b182810c8c3b49d91309b3b009a5fed9731` SHA-256: `b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1` -来源:[`packages/experimental/agent-team/src/types.ts:232`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:230`](../packages/experimental/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7508,7 +7714,7 @@ SHA-256: `b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1` SHA-256: `6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5` -来源:[`packages/core/session/src/types.ts:330`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:331`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7522,7 +7728,7 @@ SHA-256: `6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5` SHA-256: `ea08ec1df0c33108fd03345b9af199cf04dea450aa045d3c683f216311403403` -来源:[`packages/experimental/agent-team/src/types.ts:236`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:234`](../packages/experimental/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7536,7 +7742,7 @@ SHA-256: `ea08ec1df0c33108fd03345b9af199cf04dea450aa045d3c683f216311403403` SHA-256: `0bcfaf5566d271028429ac7b562cb59053c9d78b8ae14708c35fac835108d1b1` -来源:[`packages/experimental/agent-team/src/types.ts:238`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:236`](../packages/experimental/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7589,7 +7795,7 @@ SHA-256: `8a9c990773f798eac10ca8878e6bcc531ee080bc589cac956730e462cc6a09ad` SHA-256: `e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654` -来源:[`packages/core/session/src/types.ts:297`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:298`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7643,7 +7849,7 @@ SHA-256: `5dd766ccd1702a1142ad8b4bd44f2242f8e8a6752669ad3de0a5d224329b1438` SHA-256: `54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0` -来源:[`packages/core/session/src/types.ts:355`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:356`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7657,7 +7863,7 @@ SHA-256: `54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0` SHA-256: `ef11a3b7fa2033ae4279545ff8a8a2ee4e301b9b73e5b91654c48e6d08283545` -来源:[`packages/core/session/src/types.ts:299`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:300`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:302`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7682,7 +7888,7 @@ SHA-256: `477614bca595a9e7adb5a1870be446b9a8684f3ba8950259d6289f2d3b74f028` SHA-256: `a40d12070f6f4a124f32fb3cc86e7857554702e32f0eda3080a25c4b9ac9b18c` -来源:[`packages/experimental/agent-team/src/types.ts:234`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/experimental/agent-team/src/types.ts:232`](../packages/experimental/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7708,7 +7914,7 @@ SHA-256: `79ddc907312f97cf9553d4841e8b3fc937097bd8d97900a790efad3c05255e99` SHA-256: `f90eb4ab2d3897bc20c521a038e3119d581f791ec974b1a0004f63a8ab9e232d` -来源:[`packages/core/session/src/types.ts:288`](../packages/core/session/src/types.ts) · [`packages/deliverables/workspace-changes/src/types.ts:106`](../packages/deliverables/workspace-changes/src/types.ts) +来源:[`packages/core/session/src/types.ts:289`](../packages/core/session/src/types.ts) · [`packages/deliverables/workspace-changes/src/types.ts:106`](../packages/deliverables/workspace-changes/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7730,17 +7936,17 @@ SHA-256: `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | `time` | 必需 | `number` | | `type` | 必需 | `"agent-preset/selected"` | - + ### `{ type: "agent/inbox/spliced" }` -SHA-256: `9a36727716d0e73f681f3b725e7f28f89417c68174c8af0ff2b1ef52b08326a0` +SHA-256: `0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-83a665476a9ee9af05cb1fdded12dd647d1b97b491200d7f12ef1af7cdac4428) | +| `data` | 必需 | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | @@ -7833,7 +8039,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625` SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` -来源:[`packages/llm/llm/src/types.ts:457`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:473`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7847,7 +8053,7 @@ SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90` -来源:[`packages/llm/llm/src/types.ts:453`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:469`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7981,17 +8187,17 @@ SHA-256: `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | `time` | 必需 | `number` | | `type` | 必需 | `"deliverables/presented"` | - + ### `{ type: "developer/message" }` -SHA-256: `ba5b10ea77d68f4a29439a9bd2a14f6a560acf55731749d57237757cc72fbc06` +SHA-256: `97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-5b55817a403569fbb2d379496df2e3f3f71107f6c577a218028ce187c60b61e6) | +| `data` | 必需 | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `sourceEventSeqs` | 可选 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | @@ -8053,7 +8259,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1` -来源:[`packages/llm/llm/src/types.ts:459`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:475`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8125,6 +8331,38 @@ SHA-256: `b222069eea2d768065161c1147b1f2c78c1b54328c84b3586ae5c8f91b8ed35e` | `time` | 必需 | `number` | | `type` | 必需 | `"image/offload"` | + + + + +### `{ type: "job/registered" }` + +SHA-256: `f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `data` | 必需 | [`JobRegisteredData`](#persistence-type-sha256-e3056e0dda3a379e895386e368c3ce42131460ea65e410e1d091cca98a347305) | +| `ignorable` | 可选 | `true` | +| `seq` | 必需 | `number` | +| `time` | 必需 | `number` | +| `type` | 必需 | `"job/registered"` | + + + + + +### `{ type: "job/settled" }` + +SHA-256: `edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `data` | 必需 | [`JobSettledData`](#persistence-type-sha256-611d82d2dc50df706cf08a0fc04bc8eaf78083391fe6f10313de943e615dd2da) | +| `ignorable` | 可选 | `true` | +| `seq` | 必需 | `number` | +| `time` | 必需 | `number` | +| `type` | 必需 | `"job/settled"` | + @@ -8227,7 +8465,7 @@ SHA-256: `71bb3254ec8f1e491ce63b762a7b5f18709de23aa4e8abcc8b886f4b6ce051dd` SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095` -来源:[`packages/llm/llm/src/types.ts:455`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:471`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8347,17 +8585,17 @@ SHA-256: `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | `time` | 必需 | `number` | | `type` | 必需 | `"session/title"` | - + ### `{ type: "session/title-llm-request" }` -SHA-256: `b33545b3244861bcbf73b407d24b53402710f5acacab7ae939537e5504a68dc6` +SHA-256: `79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-045926475a46f625f84ae2be292b384817059f16927c69a9adab93717923ac19) | +| `data` | 必需 | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-00c054d3018c198d92f459563331edd1385e58345c677bb499791df2da0ade9f) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | @@ -8547,7 +8785,7 @@ SHA-256: `e72269f931559e901e5e8fe1cfcbd0669fb795f43cc038ff39fba62f60403c33` SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65` -来源:[`packages/llm/llm/src/types.ts:454`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:470`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8595,7 +8833,7 @@ SHA-256: `3860b4757d512a2869be833acb0faf834335b1b056bf3f83df5474dce95f8fa6` SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a` -来源:[`packages/llm/llm/src/types.ts:456`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:472`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8773,24 +9011,24 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` -来源:[`packages/llm/llm/src/types.ts:458`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:474`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| | `type` | 必需 | `"usage"` | | `usage` | 必需 | [`TokenUsage`](#persistence-type-sha256-fec5442b9ee4122e10514d81d5a43648003fe8bfb7ee2ba50c0cdbdd383ed394) | - + ### `{ type: "user/message" }` -SHA-256: `2ace3b8059b82b6d9837fed518ca97a99eb37c4482df7aad0e71c85489428ade` +SHA-256: `2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`UserMessage`](#persistence-type-sha256-89b2edff547be1ecfcd78ef18aeeb3cf507fcbf7d6093ec04fb111ef4c8e8a97) | +| `data` | 必需 | [`UserMessage`](#persistence-type-sha256-2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `sourceEventSeqs` | 可选 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | diff --git a/docs/persistence-changes/2026-09-16-session-format-v4.i18n.yaml b/docs/persistence-changes/2026-09-16-session-format-v4.i18n.yaml index 22adb806b0..5bf6e8cc50 100644 --- a/docs/persistence-changes/2026-09-16-session-format-v4.i18n.yaml +++ b/docs/persistence-changes/2026-09-16-session-format-v4.i18n.yaml @@ -18,11 +18,11 @@ en: 6907136f28e48c90 zh: 02f8298485f3d8e7 /2026-09-16-session-format-v4/compatibility: - en: 62d76f6b66d04dc4 - zh: 736b1b7cc2f6084f + en: 0fc8ce7241c4ecbe + zh: d3f2c2812ecaca38 /2026-09-16-session-format-v4/verification: - en: f917c71292c98b17 - zh: 974c65afde0adb22 + en: 94b3c1b1d07bc87d + zh: af7ec37007c62ecb /2026-09-16-session-format-v4/dev-note: en: b75c8458928b72b9 zh: 003ba4e17b4b5269 diff --git a/docs/persistence-changes/2026-09-16-session-format-v4.md b/docs/persistence-changes/2026-09-16-session-format-v4.md index 187acab093..370970ccb7 100644 --- a/docs/persistence-changes/2026-09-16-session-format-v4.md +++ b/docs/persistence-changes/2026-09-16-session-format-v4.md @@ -93,7 +93,7 @@ The [native V4 validation decision](../../.agents/notes/implemented/architecture The V3-to-V4 migration lifts released user-role tool results into tool-role messages with a required toolCallId and optional isError. Tool-result wrappers leave the content-block union. The migration preserves every admitted source event and inherited cut, and appends missing parent subagent/catalog records from retained direct-child logs in the same persistence root. Historical body restoration requires an explicit child-evidence set, including an empty set when no children are available to backfill. Missing, multiple, or unknown-version child descriptors skip that child’s backfill; conflicting identities, timestamps, or modes refuse migration without publication. Existing catalog facts remain. Historical read opens prepare the result in memory. Write opens revalidate child membership and revisions before publishing the current successor beside unchanged predecessor files. Delivery-generation checks keep historical acknowledgements from becoming active V4 watermarks. V3 readers refuse the newer generation. The finalized transition adds forked to turn/end.reason; exact-cut forks append child-owned error results and closers after the inherited marker. V4 admits checked not-started fork results with deterministic branch-specific IDs and wording; released V0–V3 validators and recorded predecessor generations remain unchanged. -The `request/header` schema also records the retired `system` key as forbidden. This declaration captures the existing native-reader refusal without changing stored data or prompt reconstruction; later permitting a value requires a version bump instead of being classified as an ordinary optional-field addition. +The `request/header` schema also records the retired `system` key as forbidden. This declaration captures the existing native-reader refusal without changing stored data or prompt reconstruction; later permitting a value requires compatibility review for a same-version change, or an explicit version bump, instead of being classified as an ordinary optional-field addition. Producer-owned sources replace released plugin wrappers through the [V3-to-V4 migration](../../packages/session/session-format-v3-to-v4/README.md#v3-to-v4-specification). The frozen rename table and collision rules preserve source fields and event coordinates; unknown producer attribution retains every own JSON property. Native read and write opens validate source fields before exposing the Session. Existing V4 files do not rerun the incoming migration edge. @@ -108,7 +108,7 @@ The PTC producer writes `source.kind: 'ptc-mode'`. The V3-to-V4 edge retains `to The focused Session, agent-loop, Session Controller, V4, chat-view, and compaction suites passed 1,523 tests across 63 files after integration of exact-cut forks. V4 fork tests retain original IDs and text across encoding, decoding, and restoration, reject malformed results, and validate nested inherited cuts. The tool-role migration tests and SDK snapshot refresh also passed in the originating change; the built Python runtime sdk-snapshot scenario passed, and focused pi-ai and auto-review coverage passed 351 tests with 100% coverage of the three affected modules. -The generated request-header reservation regression and existing retired-syntax and Session surface tests pass 65 tests across three files. The generated field retains optional `never`; permitting an optional string produces a version-bump diagnostic while the native reader still refuses the retired key. +The generated request-header reservation regression and existing retired-syntax and Session surface tests passed 65 tests across three files. The generated field retains optional `never`; the current classifier marks permitting an optional string as requiring compatibility review, while the native reader still refuses the retired key. The producer-source and request-input checks pass 447 tests across 12 files, including provider equality, request-only type rejection, user-attribution retention, source migration, and native source admission. Comparing the generated inventories with the tool-role parent reports four changed roots and 447 unchanged type fingerprints. diff --git a/docs/persistence-changes/2026-09-16-session-format-v4.zh.md b/docs/persistence-changes/2026-09-16-session-format-v4.zh.md index 16a1793797..f9c25f9b32 100644 --- a/docs/persistence-changes/2026-09-16-session-format-v4.zh.md +++ b/docs/persistence-changes/2026-09-16-session-format-v4.zh.md @@ -93,7 +93,7 @@ changes: V3-to-V4 迁移将已发布的 user 角色工具结果提升为 tool 角色消息,包含必需的 toolCallId 和可选的 isError。工具结果包装不再属于内容块联合。迁移保留每个已接纳源事件和继承切分点,并根据同一持久化根目录中保留的直属子 Session 日志追加缺失的父级 subagent/catalog 记录。历史正文恢复要求显式提供子日志证据集合;没有可供补全的子日志时也须传入空集合。子日志的 descriptor 缺失、多条或版本未知时,跳过该子项的补全;身份、时间戳或模式冲突会拒绝迁移且不发布后继。已有 catalog 事实保持不变。历史读取打开在内存中准备结果。写入打开在重新校验子项成员与修订后,将当前后继发布到未修改的前代文件旁。Delivery generation 校验防止历史确认成为有效的 V4 水位。V3 读取方拒绝更新的 generation。已定稿迁移向 turn/end.reason 添加 forked。精确切点的 fork 在继承标记之后追加子会话自有的错误结果和结束事件。V4 接纳经过校验、使用确定性分支 ID 和文案的未启动 fork 结果;已发布的 V0–V3 校验器和已记录的前驱代际保持不变。 -`request/header` schema 还将退役的 `system` 键记录为禁止字段。这项声明记录已有的原生读取拒绝规则,不改变存储数据或提示词重建;以后允许该字段携带值时,必须提升格式版本,而不能归类为普通可选字段添加。 +`request/header` schema 还将退役的 `system` 键记录为禁止字段。这项声明记录已有的原生读取拒绝规则,不改变存储数据或提示词重建;以后允许该字段携带值时,同版本变更必须经过兼容性评审,或显式提升格式版本,而不能归类为普通可选字段添加。 生产者拥有的 source 通过 [V3→V4 迁移](../../packages/session/session-format-v3-to-v4/README.zh.md#v3-to-v4-specification)替代已发布的 plugin wrapper。冻结的重命名表和冲突规则保留 source 字段与事件坐标;未知生产者归属保留每个自有 JSON 属性。原生读取和写入打开在公开 Session 之前校验 source 字段。已有 V4 文件不会重新运行迁入边。 @@ -108,7 +108,7 @@ PTC 生产者写入 `source.kind: 'ptc-mode'`。V3→V4 迁入边保留 `tools-c 精确切点 fork 集成后,聚焦的 Session、agent-loop、Session Controller、V4、chat-view 和 compaction 测试共 63 个文件、1,523 个测试通过。V4 fork 测试确认编码、解码和恢复保留原始 ID 与文本,拒绝格式错误的结果,并验证嵌套继承切点。工具角色迁移测试和 SDK 快照刷新也在原始变更中通过;构建后的 Python runtime sdk-snapshot 场景通过,定向 pi-ai 与 auto-review 覆盖率检查通过 351 个测试,三个受影响模块覆盖率均为 100%。 -生成的请求头保留字段回归测试以及已有的退役语法和 Session surface 测试共通过三个文件中的 65 项测试。生成字段保留可选的 `never`;允许可选字符串会产生必须提升版本的诊断,而原生读取方仍拒绝该退役键。 +生成的请求头保留字段回归测试以及已有的退役语法和 Session surface 测试曾通过三个文件中的 65 项测试。生成字段保留可选的 `never`;当前分类器将允许可选字符串标记为需要兼容性评审,而原生读取方仍拒绝该退役键。 Producer-source 与 request-input 检查共通过 12 个文件中的 447 项测试,覆盖 provider 等价性、仅供请求使用的输入的类型拒绝、user 归属保留、source 迁移及原生 source 准入。与 tool-role 父层的生成目录相比,有四个 root 发生变化,447 个类型指纹保持不变。 diff --git a/docs/persistence-changes/2026-09-30-job-session-lifecycle.i18n.yaml b/docs/persistence-changes/2026-09-30-job-session-lifecycle.i18n.yaml new file mode 100644 index 0000000000..c8b13e6c47 --- /dev/null +++ b/docs/persistence-changes/2026-09-30-job-session-lifecycle.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-09-30-job-session-lifecycle.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/persistence-changes/2026-09-30-job-session-lifecycle.md +/: + en: 3d5a424ae7d7e46b + zh: c22a8e4a62d8cc1a +/2026-09-30-job-session-lifecycle: + en: 9be8dc8cb5ce646a + zh: 6ce0040813c36e92 +/2026-09-30-job-session-lifecycle/summary: + en: 7d98020db3395e2e + zh: abe692ef42327e49 +/2026-09-30-job-session-lifecycle/table-of-contents: + en: 6cf314a069ceb451 + zh: 9adff678e9ecab3b +/2026-09-30-job-session-lifecycle/declaration: + en: 6907136f28e48c90 + zh: 02f8298485f3d8e7 +/2026-09-30-job-session-lifecycle/compatibility: + en: 546fe003ad5293b6 + zh: 86d78c9704a03718 +/2026-09-30-job-session-lifecycle/verification: + en: e9660a31a43378fc + zh: e97fbe31ff47ea2e +/2026-09-30-job-session-lifecycle/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/docs/persistence-changes/2026-09-30-job-session-lifecycle.md b/docs/persistence-changes/2026-09-30-job-session-lifecycle.md new file mode 100644 index 0000000000..d77ccc2c87 --- /dev/null +++ b/docs/persistence-changes/2026-09-30-job-session-lifecycle.md @@ -0,0 +1,52 @@ +--- +description: "Records a persistence type transition and its compatibility acknowledgement." +kind: persistence-change +--- + +# 2026-09-30-job-session-lifecycle + +English | [中文](2026-09-30-job-session-lifecycle.zh.md) + +## Summary + +Records owned job registration and settlement with one unique JobId, original timestamps, creating tool calls, and producer completion reports. + +## Table of Contents + +- [Declaration](#declaration) +- [Compatibility](#compatibility) +- [Verification](#verification) +- [Dev Note](#dev-note) + + +## Declaration + +```yaml persistence-change +schemaVersion: 1 +id: 2026-09-30-job-session-lifecycle +baseline: false +changes: + - root: "event:job/registered" + previous: null + after: "f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1" + decision: same-version + - root: "event:job/settled" + previous: null + after: "edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf" + decision: same-version +``` + + +## Compatibility + +Adds required job event kinds without changing the Session envelope. New JobIds use a kind-prefixed UUID for both live controls and durable pairing; historical sessions receive no fabricated job history. Older builds reject unknown required events. producerReported describes completion-promise fulfillment, not verified resource release. + + +## Verification + +Registry and snapshot-normalizer tests cover causal order and unique JobIds. CLI and SDK snapshots verify registration, settlement, and notices during execution; the [job lifecycle contract](../subsystems/jobs.md#session-lifecycle-records) allows incomplete terminal history during application teardown. + + +## Dev Note + +None. diff --git a/docs/persistence-changes/2026-09-30-job-session-lifecycle.schema.json b/docs/persistence-changes/2026-09-30-job-session-lifecycle.schema.json new file mode 100644 index 0000000000..f31a0696c3 --- /dev/null +++ b/docs/persistence-changes/2026-09-30-job-session-lifecycle.schema.json @@ -0,0 +1,297 @@ +{ + "formatVersion": 2, + "roots": [ + { + "key": "event:job/registered", + "kind": "event", + "event": "job/registered", + "surface": false, + "digest": "f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1", + "schema": { + "root": 0, + "nodes": [ + { + "kind": "object", + "properties": [ + { + "name": "data", + "type": 1, + "optional": false + }, + { + "name": "ignorable", + "type": 5, + "optional": true + }, + { + "name": "seq", + "type": 3, + "optional": false + }, + { + "name": "time", + "type": 3, + "optional": false + }, + { + "name": "type", + "type": 6, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "jobId", + "type": 2, + "optional": false + }, + { + "name": "kind", + "type": 2, + "optional": false + }, + { + "name": "label", + "type": 2, + "optional": false + }, + { + "name": "owner", + "type": 2, + "optional": false + }, + { + "name": "startedAt", + "type": 3, + "optional": false + }, + { + "name": "toolCall", + "type": 4, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "string" + }, + { + "kind": "primitive", + "type": "number" + }, + { + "kind": "object", + "properties": [ + { + "name": "callId", + "type": 2, + "optional": false + }, + { + "name": "rootCallId", + "type": 2, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": true + }, + { + "kind": "literal", + "value": "job/registered" + } + ] + } + }, + { + "key": "event:job/settled", + "kind": "event", + "event": "job/settled", + "surface": false, + "digest": "edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf", + "schema": { + "root": 0, + "nodes": [ + { + "kind": "object", + "properties": [ + { + "name": "data", + "type": 1, + "optional": false + }, + { + "name": "ignorable", + "type": 14, + "optional": true + }, + { + "name": "seq", + "type": 7, + "optional": false + }, + { + "name": "time", + "type": 7, + "optional": false + }, + { + "name": "type", + "type": 15, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "cause", + "type": 2, + "optional": false + }, + { + "name": "detail", + "type": 6, + "optional": true + }, + { + "name": "finishedAt", + "type": 7, + "optional": false + }, + { + "name": "jobId", + "type": 6, + "optional": false + }, + { + "name": "kind", + "type": 6, + "optional": false + }, + { + "name": "label", + "type": 6, + "optional": false + }, + { + "name": "owner", + "type": 6, + "optional": false + }, + { + "name": "producerReported", + "type": 8, + "optional": false + }, + { + "name": "startedAt", + "type": 7, + "optional": false + }, + { + "name": "status", + "type": 9, + "optional": false + }, + { + "name": "toolCall", + "type": 13, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "union", + "types": [ + 3, + 4, + 5 + ] + }, + { + "kind": "literal", + "value": "producer" + }, + { + "kind": "literal", + "value": "teardown" + }, + { + "kind": "literal", + "value": "kill" + }, + { + "kind": "primitive", + "type": "string" + }, + { + "kind": "primitive", + "type": "number" + }, + { + "kind": "primitive", + "type": "boolean" + }, + { + "kind": "union", + "types": [ + 10, + 11, + 12 + ] + }, + { + "kind": "literal", + "value": "completed" + }, + { + "kind": "literal", + "value": "failed" + }, + { + "kind": "literal", + "value": "killed" + }, + { + "kind": "object", + "properties": [ + { + "name": "callId", + "type": 6, + "optional": false + }, + { + "name": "rootCallId", + "type": 6, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": true + }, + { + "kind": "literal", + "value": "job/settled" + } + ] + } + } + ], + "types": [] +} diff --git a/docs/persistence-changes/2026-09-30-job-session-lifecycle.zh.md b/docs/persistence-changes/2026-09-30-job-session-lifecycle.zh.md new file mode 100644 index 0000000000..b808a0e1d6 --- /dev/null +++ b/docs/persistence-changes/2026-09-30-job-session-lifecycle.zh.md @@ -0,0 +1,52 @@ +--- +description: "记录持久化类型更改及其兼容性确认。" +kind: persistence-change +--- + +# 2026-09-30-job-session-lifecycle + +[English](2026-09-30-job-session-lifecycle.md) | 中文 + +## 概述 + +以唯一 JobId 将有所有者 job 的注册与结算记录为 Session 事件,包含原始时间戳、创建工具调用和生产方完成报告。 + +## 目录 + +- [声明](#declaration) +- [兼容性](#compatibility) +- [验证](#verification) +- [开发备注](#dev-note) + + +## 声明 + +```yaml persistence-change +schemaVersion: 1 +id: 2026-09-30-job-session-lifecycle +baseline: false +changes: + - root: "event:job/registered" + previous: null + after: "f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1" + decision: same-version + - root: "event:job/settled" + previous: null + after: "edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf" + decision: same-version +``` + + +## 兼容性 + +增加必需的 job 事件类型,不改变 Session 封装。新 JobId 用带 kind 前缀的 UUID 同时进行运行期控制与持久化配对;不为历史会话补造 job 事件。旧构建拒绝未知的必需事件。producerReported 表示完成 promise 兑现,不确认资源已释放。 + + +## 验证 + +注册表和快照归一化测试覆盖因果顺序与唯一 JobId。CLI 和 SDK 快照验证运行中的注册、结算和通知;[job 生命周期约定](../subsystems/jobs.zh.md#session-lifecycle-records)允许应用销毁时留下不完整的终态历史。 + + +## 开发备注 + +无。 diff --git a/docs/persistence-changes/2026-10-05-working-directory-attribution.i18n.yaml b/docs/persistence-changes/2026-10-05-working-directory-attribution.i18n.yaml index 1ae5d09e4f..080248eabe 100644 --- a/docs/persistence-changes/2026-10-05-working-directory-attribution.i18n.yaml +++ b/docs/persistence-changes/2026-10-05-working-directory-attribution.i18n.yaml @@ -21,8 +21,8 @@ en: 39494aa3af994e6f zh: 07c2880503668176 /2026-10-05-working-directory-attribution/verification: - en: 5963942c0d87e518 - zh: 5dbb6ac0fca1f279 + en: 9b79379292881d10 + zh: 54d670c09ce1bfc7 /2026-10-05-working-directory-attribution/dev-note: en: b75c8458928b72b9 zh: 003ba4e17b4b5269 diff --git a/docs/persistence-changes/2026-10-05-working-directory-attribution.md b/docs/persistence-changes/2026-10-05-working-directory-attribution.md index 80996eee5c..6496413c37 100644 --- a/docs/persistence-changes/2026-10-05-working-directory-attribution.md +++ b/docs/persistence-changes/2026-10-05-working-directory-attribution.md @@ -52,7 +52,7 @@ Existing records remain valid. The additive working-directory source kind is att ## Verification -pnpm exec vitest run packages/session/working-directory/tests packages/shell/tool-bash/tests/tools.spec.ts packages/shell/tool-pwsh/tests/tools.spec.ts packages/subagent/subagent-in-process-driver/tests/schedule-tools.spec.ts: 4 files and 203 tests passed. +pnpm exec vitest run packages/session/working-directory/tests packages/shell/tool-bash/tests/tools.spec.ts packages/shell/tool-pwsh/tests/tools.spec.ts packages/subagent/subagent/tests/schedule-tools.spec.ts: 5 files and 207 tests passed. ## Dev Note diff --git a/docs/persistence-changes/2026-10-05-working-directory-attribution.zh.md b/docs/persistence-changes/2026-10-05-working-directory-attribution.zh.md index e7ed00e08f..56157cc7d2 100644 --- a/docs/persistence-changes/2026-10-05-working-directory-attribution.zh.md +++ b/docs/persistence-changes/2026-10-05-working-directory-attribution.zh.md @@ -52,7 +52,7 @@ changes: ## 验证 -pnpm exec vitest run packages/session/working-directory/tests packages/shell/tool-bash/tests/tools.spec.ts packages/shell/tool-pwsh/tests/tools.spec.ts packages/subagent/subagent-in-process-driver/tests/schedule-tools.spec.ts:4 个文件、203 个测试通过。 +pnpm exec vitest run packages/session/working-directory/tests packages/shell/tool-bash/tests/tools.spec.ts packages/shell/tool-pwsh/tests/tools.spec.ts packages/subagent/subagent/tests/schedule-tools.spec.ts:5 个文件、207 个测试通过。 ## 开发备注 diff --git a/docs/persistence-changes/2026-10-13-user-rpc-principal.i18n.yaml b/docs/persistence-changes/2026-10-13-user-rpc-principal.i18n.yaml new file mode 100644 index 0000000000..13e1d9e422 --- /dev/null +++ b/docs/persistence-changes/2026-10-13-user-rpc-principal.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-10-13-user-rpc-principal.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/persistence-changes/2026-10-13-user-rpc-principal.md +/: + en: 3d5a424ae7d7e46b + zh: c22a8e4a62d8cc1a +/2026-10-13-user-rpc-principal: + en: c8b8c9fe1f1fb295 + zh: 6775ad8687023eb9 +/2026-10-13-user-rpc-principal/summary: + en: 9fd17b8ef1f569d2 + zh: d1e9679296ce47a0 +/2026-10-13-user-rpc-principal/table-of-contents: + en: 6cf314a069ceb451 + zh: 9adff678e9ecab3b +/2026-10-13-user-rpc-principal/declaration: + en: 6907136f28e48c90 + zh: 02f8298485f3d8e7 +/2026-10-13-user-rpc-principal/compatibility: + en: ae44b935893f7eaa + zh: 686893a2a812570d +/2026-10-13-user-rpc-principal/verification: + en: 53e8380b9c0c63a9 + zh: 3adac787e267570d +/2026-10-13-user-rpc-principal/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/docs/persistence-changes/2026-10-13-user-rpc-principal.md b/docs/persistence-changes/2026-10-13-user-rpc-principal.md new file mode 100644 index 0000000000..cccf5c6a32 --- /dev/null +++ b/docs/persistence-changes/2026-10-13-user-rpc-principal.md @@ -0,0 +1,60 @@ +--- +description: "Records a persistence type transition and its compatibility acknowledgement." +kind: persistence-change +--- + +# 2026-10-13-user-rpc-principal + +English | [中文](2026-10-13-user-rpc-principal.zh.md) + +## Summary + +Adds an optional principal to the user-rpc message source for prompts submitted by a caller other than the owner. + +## Table of Contents + +- [Declaration](#declaration) +- [Compatibility](#compatibility) +- [Verification](#verification) +- [Dev Note](#dev-note) + + +## Declaration + +```yaml persistence-change +schemaVersion: 1 +id: 2026-10-13-user-rpc-principal +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-10-05-working-directory-attribution" + after: "0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034" + decision: same-version + - root: "event:developer/message" + previous: "2026-10-05-working-directory-attribution" + after: "97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-10-07-title-reasoning-effort" + after: "79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056" + decision: same-version + - root: "event:user/message" + previous: "2026-10-05-working-directory-attribution" + after: "2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8" + decision: same-version +``` + + +## Compatibility + +Owner prompts omit the field, so their sources and every existing Session log are unchanged; an absent principal means the owner. A reader that predates the field ignores it and treats the message as an ordinary user message, because the kind stays 'user'. A current reader of an older log finds no principal and treats every message as the owner's. The field is not part of any model request: provider adapters read only the model-visible message content. SESSION_FORMAT_VERSION does not change. + + +## Verification + +pnpm exec vitest run packages/api/session-controller/tests/remote-access.host.spec.ts packages/subagent/subagent/tests/control.spec.ts packages/api/session-controller/tests/session-cold.host.spec.ts: non-owner prompts persist source.principal in agent/inbox/spliced, owner and existing time-zone sources stay byte-identical; all tests passed. + + +## Dev Note + +None. diff --git a/docs/persistence-changes/2026-10-13-user-rpc-principal.schema.json b/docs/persistence-changes/2026-10-13-user-rpc-principal.schema.json new file mode 100644 index 0000000000..82d7ab993e --- /dev/null +++ b/docs/persistence-changes/2026-10-13-user-rpc-principal.schema.json @@ -0,0 +1,11559 @@ +{ + "formatVersion": 2, + "roots": [ + { + "key": "event:agent/inbox/spliced", + "kind": "event", + "event": "agent/inbox/spliced", + "surface": false, + "digest": "0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034", + "schema": { + "root": 0, + "nodes": [ + { + "kind": "object", + "properties": [ + { + "name": "data", + "type": 1, + "optional": false + }, + { + "name": "ignorable", + "type": 27, + "optional": true + }, + { + "name": "seq", + "type": 20, + "optional": false + }, + { + "name": "time", + "type": 20, + "optional": false + }, + { + "name": "type", + "type": 206, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "inserted", + "type": 2, + "optional": false + }, + { + "name": "outcome", + "type": 202, + "optional": true + }, + { + "name": "removedCount", + "type": 20, + "optional": true + }, + { + "name": "start", + "type": 20, + "optional": false + }, + { + "name": "target", + "type": 203, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 3 + }, + { + "kind": "object", + "properties": [ + { + "name": "content", + "type": 4, + "optional": false + }, + { + "name": "id", + "type": 7, + "optional": false + }, + { + "name": "role", + "type": 32, + "optional": false + }, + { + "name": "source", + "type": 33, + "optional": false, + "compatibility": { + "version": 1, + "policy": "session-source-attribution", + "binding": "session.user-message.source", + "discriminator": "kind", + "unknownKinds": "preserve", + "attributionKinds": [ + "tmux-context", + "user-question-reply", + "working-directory" + ] + } + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 5 + }, + { + "kind": "union", + "types": [ + 6, + 9, + 11, + 14, + 16, + 18, + 29 + ] + }, + { + "kind": "object", + "properties": [ + { + "name": "text", + "type": 7, + "optional": false + }, + { + "name": "type", + "type": 8, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "string" + }, + { + "kind": "literal", + "value": "reasoning" + }, + { + "kind": "object", + "properties": [ + { + "name": "text", + "type": 7, + "optional": false + }, + { + "name": "type", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "text" + }, + { + "kind": "object", + "properties": [ + { + "name": "tool", + "type": 12, + "optional": true + }, + { + "name": "toolName", + "type": 7, + "optional": false + }, + { + "name": "type", + "type": 13, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "never" + }, + { + "kind": "literal", + "value": "tool-addition" + }, + { + "kind": "object", + "properties": [ + { + "name": "toolName", + "type": 7, + "optional": false + }, + { + "name": "type", + "type": 15, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-removal" + }, + { + "kind": "object", + "properties": [ + { + "name": "arguments", + "type": 7, + "optional": false + }, + { + "name": "id", + "type": 7, + "optional": false + }, + { + "name": "name", + "type": 7, + "optional": false + }, + { + "name": "type", + "type": 17, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-call" + }, + { + "kind": "object", + "properties": [ + { + "name": "attachment", + "type": 19, + "optional": false + }, + { + "name": "offloaded", + "type": 27, + "optional": true + }, + { + "name": "type", + "type": 28, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "attachmentId", + "type": 7, + "optional": false + }, + { + "name": "bytes", + "type": 20, + "optional": false + }, + { + "name": "height", + "type": 20, + "optional": false + }, + { + "name": "mediaType", + "type": 21, + "optional": false + }, + { + "name": "name", + "type": 7, + "optional": true + }, + { + "name": "originalDimensions", + "type": 26, + "optional": true + }, + { + "name": "width", + "type": 20, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "number" + }, + { + "kind": "union", + "types": [ + 22, + 23, + 24, + 25 + ] + }, + { + "kind": "literal", + "value": "image/gif" + }, + { + "kind": "literal", + "value": "image/jpeg" + }, + { + "kind": "literal", + "value": "image/png" + }, + { + "kind": "literal", + "value": "image/webp" + }, + { + "kind": "object", + "properties": [ + { + "name": "height", + "type": 20, + "optional": false + }, + { + "name": "width", + "type": 20, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": true + }, + { + "kind": "literal", + "value": "image" + }, + { + "kind": "object", + "properties": [ + { + "name": "attachment", + "type": 30, + "optional": false + }, + { + "name": "type", + "type": 31, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "attachmentId", + "type": 7, + "optional": false + }, + { + "name": "bytes", + "type": 20, + "optional": false + }, + { + "name": "name", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "file" + }, + { + "kind": "literal", + "value": "user" + }, + { + "kind": "union", + "types": [ + 34, + 39, + 41, + 43, + 45, + 48, + 51, + 53, + 55, + 57, + 59, + 61, + 63, + 65, + 67, + 69, + 70, + 71, + 72, + 73, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 107, + 108, + 109, + 110, + 111, + 112, + 113, + 114, + 116, + 117, + 118, + 119, + 120, + 121, + 122, + 123, + 124, + 125, + 126, + 127, + 128, + 130, + 132, + 135, + 136, + 137, + 138, + 139, + 141, + 142, + 143, + 144, + 146, + 147, + 148, + 149, + 150, + 152, + 153, + 154, + 156, + 158, + 159, + 167, + 170, + 172, + 175, + 177, + 179, + 183, + 185, + 193, + 194, + 195, + 196, + 197, + 198, + 199, + 200, + 201 + ] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 36, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "snapshot" + }, + { + "kind": "literal", + "value": "tool-goal" + }, + { + "kind": "array", + "element": 38 + }, + { + "kind": "object", + "properties": [ + { + "name": "name", + "type": 7, + "optional": false + }, + { + "name": "text", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-jobs" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user-approval" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "dsh-session-title-llm" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 47, + "optional": false + }, + { + "name": "senderSessionId", + "type": 7, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "notice" + }, + { + "kind": "literal", + "value": "subagent-settled" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + }, + { + "name": "senderSessionId", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "relay" + }, + { + "kind": "literal", + "value": "agent-message" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "hooks-claude-code" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "hooks-codex" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 56, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "model-selection" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 58, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "plan-mode" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 60, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "repeat-tool-reminder" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 62, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "runtime-context" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 64, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "schedule" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 66, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "time-context" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 68, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tmux-context" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 36, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "instructions" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 56, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 58, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 60, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 62, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 64, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 66, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 68, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "recall" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 56, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 58, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 60, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 62, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 64, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 66, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 68, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 56, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 58, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 60, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 62, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 64, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 66, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 68, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "catalog" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 56, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 58, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 60, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 62, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 64, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 66, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 68, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "goalId", + "type": 7, + "optional": false + }, + { + "name": "kind", + "type": 129, + "optional": false + }, + { + "name": "revision", + "type": 20, + "optional": false + }, + { + "name": "round", + "type": 20, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "goal" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 131, + "optional": false + }, + { + "name": "messageId", + "type": 7, + "optional": false + }, + { + "name": "senderId", + "type": 7, + "optional": false + }, + { + "name": "senderName", + "type": 7, + "optional": false + }, + { + "name": "teamId", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "team-message" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 133, + "optional": false + }, + { + "name": "model", + "type": 7, + "optional": false + }, + { + "name": "provider", + "type": 7, + "optional": false + }, + { + "name": "replayState", + "type": 134, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "model" + }, + { + "kind": "opaque", + "reason": "unknown" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 56, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 58, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 140, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "ptc-mode" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 60, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 62, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 64, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 145, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "system-prompt" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 66, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 68, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 151, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-registry" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 32, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 155, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "working-directory" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 157, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "cordis-host-runner" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "baseline", + "type": 27, + "optional": true + }, + { + "name": "baselineIdentity", + "type": 7, + "optional": true + }, + { + "name": "changes", + "type": 160, + "optional": false + }, + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 166, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 161 + }, + { + "kind": "object", + "properties": [ + { + "name": "action", + "type": 162, + "optional": false + }, + { + "name": "digest", + "type": 7, + "optional": true + }, + { + "name": "path", + "type": 7, + "optional": false + }, + { + "name": "scope", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "union", + "types": [ + 163, + 164, + 165 + ] + }, + { + "kind": "literal", + "value": "remove" + }, + { + "kind": "literal", + "value": "replace" + }, + { + "kind": "literal", + "value": "set" + }, + { + "kind": "literal", + "value": "agent-instructions" + }, + { + "kind": "object", + "properties": [ + { + "name": "callId", + "type": 7, + "optional": false + }, + { + "name": "kind", + "type": 168, + "optional": false + }, + { + "name": "outcome", + "type": 169, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user-question-reply" + }, + { + "kind": "literal", + "value": "answered" + }, + { + "kind": "object", + "properties": [ + { + "name": "callId", + "type": 7, + "optional": false + }, + { + "name": "kind", + "type": 171, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool" + }, + { + "kind": "object", + "properties": [ + { + "name": "clientTimeZone", + "type": 7, + "optional": true + }, + { + "name": "kind", + "type": 32, + "optional": false + }, + { + "name": "principal", + "type": 173, + "optional": true + }, + { + "name": "rpcId", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 174, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "owner" + }, + { + "kind": "object", + "properties": [ + { + "name": "compactionId", + "type": 7, + "optional": false + }, + { + "name": "kind", + "type": 176, + "optional": false + }, + { + "name": "sourceCommandId", + "type": 7, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "compact-checkpoint" + }, + { + "kind": "object", + "properties": [ + { + "name": "deliveryId", + "type": 7, + "optional": false + }, + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 178, + "optional": false + }, + { + "name": "provider", + "type": 7, + "optional": false + }, + { + "name": "ruleId", + "type": 7, + "optional": false + }, + { + "name": "source", + "type": 7, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "webhook" + }, + { + "kind": "object", + "properties": [ + { + "name": "entries", + "type": 180, + "optional": false + }, + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 182, + "optional": false + }, + { + "name": "update", + "type": 27, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 181 + }, + { + "kind": "object", + "properties": [ + { + "name": "description", + "type": 7, + "optional": false + }, + { + "name": "name", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "skill-catalog" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 184, + "optional": false + }, + { + "name": "name", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "skill-invocation" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 186, + "optional": false + }, + { + "name": "references", + "type": 187, + "optional": false + }, + { + "name": "version", + "type": 192, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "session-reference" + }, + { + "kind": "array", + "element": 188 + }, + { + "kind": "object", + "properties": [ + { + "name": "capturedFormatVersion", + "type": 20, + "optional": true + }, + { + "name": "capturedThroughSeq", + "type": 189, + "optional": false + }, + { + "name": "compacted", + "type": 191, + "optional": false + }, + { + "name": "inputIndex", + "type": 20, + "optional": false + }, + { + "name": "label", + "type": 7, + "optional": false + }, + { + "name": "omittedBytes", + "type": 20, + "optional": false + }, + { + "name": "omittedMessages", + "type": 20, + "optional": false + }, + { + "name": "originalMessages", + "type": 20, + "optional": false + }, + { + "name": "retainedMessages", + "type": 20, + "optional": false + }, + { + "name": "sessionId", + "type": 7, + "optional": false + }, + { + "name": "truncated", + "type": 191, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "union", + "types": [ + 20, + 190 + ] + }, + { + "kind": "primitive", + "type": "null" + }, + { + "kind": "primitive", + "type": "boolean" + }, + { + "kind": "literal", + "value": 1 + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 56, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 58, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 60, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 62, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 64, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 66, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 68, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "canceled" + }, + { + "kind": "union", + "types": [ + 204, + 205 + ] + }, + { + "kind": "literal", + "value": "next-step" + }, + { + "kind": "literal", + "value": "next-turn" + }, + { + "kind": "literal", + "value": "agent/inbox/spliced" + } + ] + } + }, + { + "key": "event:developer/message", + "kind": "event", + "event": "developer/message", + "surface": true, + "digest": "97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c", + "schema": { + "root": 0, + "nodes": [ + { + "kind": "object", + "properties": [ + { + "name": "data", + "type": 1, + "optional": false + }, + { + "name": "ignorable", + "type": 26, + "optional": true + }, + { + "name": "seq", + "type": 2, + "optional": false + }, + { + "name": "sourceEventSeqs", + "type": 202, + "optional": true + }, + { + "name": "surfaceOp", + "type": 203, + "optional": false + }, + { + "name": "time", + "type": 2, + "optional": false + }, + { + "name": "type", + "type": 206, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "headerSeq", + "type": 2, + "optional": true + }, + { + "name": "message", + "type": 3, + "optional": false + }, + { + "name": "step", + "type": 2, + "optional": false + }, + { + "name": "turn", + "type": 2, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "number" + }, + { + "kind": "object", + "properties": [ + { + "name": "content", + "type": 4, + "optional": false + }, + { + "name": "id", + "type": 7, + "optional": false + }, + { + "name": "role", + "type": 31, + "optional": false + }, + { + "name": "source", + "type": 32, + "optional": false, + "compatibility": { + "version": 1, + "policy": "session-source-attribution", + "binding": "session.developer-message.source", + "discriminator": "kind", + "unknownKinds": "preserve", + "attributionKinds": [ + "tmux-context", + "user-question-reply", + "working-directory" + ] + } + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 5 + }, + { + "kind": "union", + "types": [ + 6, + 9, + 11, + 14, + 16, + 18, + 28 + ] + }, + { + "kind": "object", + "properties": [ + { + "name": "text", + "type": 7, + "optional": false + }, + { + "name": "type", + "type": 8, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "string" + }, + { + "kind": "literal", + "value": "reasoning" + }, + { + "kind": "object", + "properties": [ + { + "name": "text", + "type": 7, + "optional": false + }, + { + "name": "type", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "text" + }, + { + "kind": "object", + "properties": [ + { + "name": "tool", + "type": 12, + "optional": true + }, + { + "name": "toolName", + "type": 7, + "optional": false + }, + { + "name": "type", + "type": 13, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "never" + }, + { + "kind": "literal", + "value": "tool-addition" + }, + { + "kind": "object", + "properties": [ + { + "name": "toolName", + "type": 7, + "optional": false + }, + { + "name": "type", + "type": 15, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-removal" + }, + { + "kind": "object", + "properties": [ + { + "name": "arguments", + "type": 7, + "optional": false + }, + { + "name": "id", + "type": 7, + "optional": false + }, + { + "name": "name", + "type": 7, + "optional": false + }, + { + "name": "type", + "type": 17, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-call" + }, + { + "kind": "object", + "properties": [ + { + "name": "attachment", + "type": 19, + "optional": false + }, + { + "name": "offloaded", + "type": 26, + "optional": true + }, + { + "name": "type", + "type": 27, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "attachmentId", + "type": 7, + "optional": false + }, + { + "name": "bytes", + "type": 2, + "optional": false + }, + { + "name": "height", + "type": 2, + "optional": false + }, + { + "name": "mediaType", + "type": 20, + "optional": false + }, + { + "name": "name", + "type": 7, + "optional": true + }, + { + "name": "originalDimensions", + "type": 25, + "optional": true + }, + { + "name": "width", + "type": 2, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "union", + "types": [ + 21, + 22, + 23, + 24 + ] + }, + { + "kind": "literal", + "value": "image/gif" + }, + { + "kind": "literal", + "value": "image/jpeg" + }, + { + "kind": "literal", + "value": "image/png" + }, + { + "kind": "literal", + "value": "image/webp" + }, + { + "kind": "object", + "properties": [ + { + "name": "height", + "type": 2, + "optional": false + }, + { + "name": "width", + "type": 2, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": true + }, + { + "kind": "literal", + "value": "image" + }, + { + "kind": "object", + "properties": [ + { + "name": "attachment", + "type": 29, + "optional": false + }, + { + "name": "type", + "type": 30, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "attachmentId", + "type": 7, + "optional": false + }, + { + "name": "bytes", + "type": 2, + "optional": false + }, + { + "name": "name", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "file" + }, + { + "kind": "literal", + "value": "developer" + }, + { + "kind": "union", + "types": [ + 33, + 38, + 40, + 42, + 44, + 47, + 50, + 52, + 54, + 56, + 58, + 60, + 62, + 64, + 66, + 68, + 69, + 70, + 71, + 72, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 107, + 108, + 109, + 110, + 111, + 112, + 113, + 115, + 116, + 117, + 118, + 119, + 120, + 121, + 122, + 123, + 124, + 125, + 126, + 127, + 129, + 131, + 134, + 135, + 136, + 137, + 138, + 139, + 141, + 142, + 143, + 144, + 146, + 147, + 148, + 149, + 150, + 152, + 154, + 155, + 157, + 159, + 167, + 170, + 172, + 175, + 177, + 179, + 183, + 185, + 193, + 194, + 195, + 196, + 197, + 198, + 199, + 200, + 201 + ] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 35, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "snapshot" + }, + { + "kind": "literal", + "value": "tmux-context" + }, + { + "kind": "array", + "element": 37 + }, + { + "kind": "object", + "properties": [ + { + "name": "name", + "type": 7, + "optional": false + }, + { + "name": "text", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 39, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-goal" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 41, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-jobs" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 43, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user-approval" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + }, + { + "name": "senderSessionId", + "type": 7, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "notice" + }, + { + "kind": "literal", + "value": "subagent-settled" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 49, + "optional": false + }, + { + "name": "senderSessionId", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "relay" + }, + { + "kind": "literal", + "value": "agent-message" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 51, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "dsh-session-title-llm" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 53, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "hooks-claude-code" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 55, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "hooks-codex" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 57, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "model-selection" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "plan-mode" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "repeat-tool-reminder" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 63, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "runtime-context" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 65, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "schedule" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 67, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "time-context" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 35, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 39, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 41, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 43, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 51, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "instructions" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 53, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 55, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 57, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 63, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 65, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 67, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 35, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 39, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 41, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 51, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "recall" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 53, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 55, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 57, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 63, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 65, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 67, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 35, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 39, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 41, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 51, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 53, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 55, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 57, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 63, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 65, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 67, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 35, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 39, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 41, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 51, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "catalog" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 53, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 55, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 57, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 63, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 65, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 67, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 35, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 39, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 41, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "goalId", + "type": 7, + "optional": false + }, + { + "name": "kind", + "type": 128, + "optional": false + }, + { + "name": "revision", + "type": 2, + "optional": false + }, + { + "name": "round", + "type": 2, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "goal" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 130, + "optional": false + }, + { + "name": "messageId", + "type": 7, + "optional": false + }, + { + "name": "senderId", + "type": 7, + "optional": false + }, + { + "name": "senderName", + "type": 7, + "optional": false + }, + { + "name": "teamId", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "team-message" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 132, + "optional": false + }, + { + "name": "model", + "type": 7, + "optional": false + }, + { + "name": "provider", + "type": 7, + "optional": false + }, + { + "name": "replayState", + "type": 133, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "model" + }, + { + "kind": "opaque", + "reason": "unknown" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 51, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 53, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 55, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 57, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 140, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "ptc-mode" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 63, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 65, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 145, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "system-prompt" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 67, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 35, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 39, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 41, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 151, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-registry" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 153, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 156, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "working-directory" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 158, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "cordis-host-runner" + }, + { + "kind": "object", + "properties": [ + { + "name": "baseline", + "type": 26, + "optional": true + }, + { + "name": "baselineIdentity", + "type": 7, + "optional": true + }, + { + "name": "changes", + "type": 160, + "optional": false + }, + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 166, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 161 + }, + { + "kind": "object", + "properties": [ + { + "name": "action", + "type": 162, + "optional": false + }, + { + "name": "digest", + "type": 7, + "optional": true + }, + { + "name": "path", + "type": 7, + "optional": false + }, + { + "name": "scope", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "union", + "types": [ + 163, + 164, + 165 + ] + }, + { + "kind": "literal", + "value": "remove" + }, + { + "kind": "literal", + "value": "replace" + }, + { + "kind": "literal", + "value": "set" + }, + { + "kind": "literal", + "value": "agent-instructions" + }, + { + "kind": "object", + "properties": [ + { + "name": "callId", + "type": 7, + "optional": false + }, + { + "name": "kind", + "type": 168, + "optional": false + }, + { + "name": "outcome", + "type": 169, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user-question-reply" + }, + { + "kind": "literal", + "value": "answered" + }, + { + "kind": "object", + "properties": [ + { + "name": "callId", + "type": 7, + "optional": false + }, + { + "name": "kind", + "type": 171, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool" + }, + { + "kind": "object", + "properties": [ + { + "name": "clientTimeZone", + "type": 7, + "optional": true + }, + { + "name": "kind", + "type": 153, + "optional": false + }, + { + "name": "principal", + "type": 173, + "optional": true + }, + { + "name": "rpcId", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 174, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "owner" + }, + { + "kind": "object", + "properties": [ + { + "name": "compactionId", + "type": 7, + "optional": false + }, + { + "name": "kind", + "type": 176, + "optional": false + }, + { + "name": "sourceCommandId", + "type": 7, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "compact-checkpoint" + }, + { + "kind": "object", + "properties": [ + { + "name": "deliveryId", + "type": 7, + "optional": false + }, + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 178, + "optional": false + }, + { + "name": "provider", + "type": 7, + "optional": false + }, + { + "name": "ruleId", + "type": 7, + "optional": false + }, + { + "name": "source", + "type": 7, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "webhook" + }, + { + "kind": "object", + "properties": [ + { + "name": "entries", + "type": 180, + "optional": false + }, + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 182, + "optional": false + }, + { + "name": "update", + "type": 26, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 181 + }, + { + "kind": "object", + "properties": [ + { + "name": "description", + "type": 7, + "optional": false + }, + { + "name": "name", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "skill-catalog" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 184, + "optional": false + }, + { + "name": "name", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "skill-invocation" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 186, + "optional": false + }, + { + "name": "references", + "type": 187, + "optional": false + }, + { + "name": "version", + "type": 192, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "session-reference" + }, + { + "kind": "array", + "element": 188 + }, + { + "kind": "object", + "properties": [ + { + "name": "capturedFormatVersion", + "type": 2, + "optional": true + }, + { + "name": "capturedThroughSeq", + "type": 189, + "optional": false + }, + { + "name": "compacted", + "type": 191, + "optional": false + }, + { + "name": "inputIndex", + "type": 2, + "optional": false + }, + { + "name": "label", + "type": 7, + "optional": false + }, + { + "name": "omittedBytes", + "type": 2, + "optional": false + }, + { + "name": "omittedMessages", + "type": 2, + "optional": false + }, + { + "name": "originalMessages", + "type": 2, + "optional": false + }, + { + "name": "retainedMessages", + "type": 2, + "optional": false + }, + { + "name": "sessionId", + "type": 7, + "optional": false + }, + { + "name": "truncated", + "type": 191, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "union", + "types": [ + 2, + 190 + ] + }, + { + "kind": "primitive", + "type": "null" + }, + { + "kind": "primitive", + "type": "boolean" + }, + { + "kind": "literal", + "value": 1 + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 51, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 53, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 55, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 57, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 63, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 65, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 67, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 2 + }, + { + "kind": "union", + "types": [ + 204, + 205 + ] + }, + { + "kind": "literal", + "value": "append" + }, + { + "kind": "object", + "properties": [ + { + "name": "endSeq", + "type": 2, + "optional": false + }, + { + "name": "op", + "type": 164, + "optional": false + }, + { + "name": "startSeq", + "type": 2, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "developer/message" + } + ] + } + }, + { + "key": "event:session/title-llm-request", + "kind": "event", + "event": "session/title-llm-request", + "surface": false, + "digest": "79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056", + "schema": { + "root": 0, + "nodes": [ + { + "kind": "object", + "properties": [ + { + "name": "data", + "type": 1, + "optional": false + }, + { + "name": "ignorable", + "type": 29, + "optional": true + }, + { + "name": "seq", + "type": 2, + "optional": false + }, + { + "name": "time", + "type": 2, + "optional": false + }, + { + "name": "type", + "type": 212, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "maxTokens", + "type": 2, + "optional": false + }, + { + "name": "messageSeqs", + "type": 3, + "optional": false + }, + { + "name": "messages", + "type": 4, + "optional": false + }, + { + "name": "reasoningEffort", + "type": 10, + "optional": true + }, + { + "name": "route", + "type": 211, + "optional": false + }, + { + "name": "system", + "type": 10, + "optional": false + }, + { + "name": "titleProvider", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "number" + }, + { + "kind": "array", + "element": 2 + }, + { + "kind": "array", + "element": 5 + }, + { + "kind": "union", + "types": [ + 6, + 37, + 206, + 207, + 209 + ] + }, + { + "kind": "object", + "properties": [ + { + "name": "content", + "type": 7, + "optional": false + }, + { + "name": "id", + "type": 10, + "optional": false + }, + { + "name": "isError", + "type": 34, + "optional": true + }, + { + "name": "role", + "type": 35, + "optional": false + }, + { + "name": "source", + "type": 36, + "optional": false + }, + { + "name": "toolCallId", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 8 + }, + { + "kind": "union", + "types": [ + 9, + 12, + 14, + 17, + 19, + 21, + 31 + ] + }, + { + "kind": "object", + "properties": [ + { + "name": "text", + "type": 10, + "optional": false + }, + { + "name": "type", + "type": 11, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "string" + }, + { + "kind": "literal", + "value": "reasoning" + }, + { + "kind": "object", + "properties": [ + { + "name": "text", + "type": 10, + "optional": false + }, + { + "name": "type", + "type": 13, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "text" + }, + { + "kind": "object", + "properties": [ + { + "name": "tool", + "type": 15, + "optional": true + }, + { + "name": "toolName", + "type": 10, + "optional": false + }, + { + "name": "type", + "type": 16, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "never" + }, + { + "kind": "literal", + "value": "tool-addition" + }, + { + "kind": "object", + "properties": [ + { + "name": "toolName", + "type": 10, + "optional": false + }, + { + "name": "type", + "type": 18, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-removal" + }, + { + "kind": "object", + "properties": [ + { + "name": "arguments", + "type": 10, + "optional": false + }, + { + "name": "id", + "type": 10, + "optional": false + }, + { + "name": "name", + "type": 10, + "optional": false + }, + { + "name": "type", + "type": 20, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-call" + }, + { + "kind": "object", + "properties": [ + { + "name": "attachment", + "type": 22, + "optional": false + }, + { + "name": "offloaded", + "type": 29, + "optional": true + }, + { + "name": "type", + "type": 30, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "attachmentId", + "type": 10, + "optional": false + }, + { + "name": "bytes", + "type": 2, + "optional": false + }, + { + "name": "height", + "type": 2, + "optional": false + }, + { + "name": "mediaType", + "type": 23, + "optional": false + }, + { + "name": "name", + "type": 10, + "optional": true + }, + { + "name": "originalDimensions", + "type": 28, + "optional": true + }, + { + "name": "width", + "type": 2, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "union", + "types": [ + 24, + 25, + 26, + 27 + ] + }, + { + "kind": "literal", + "value": "image/gif" + }, + { + "kind": "literal", + "value": "image/jpeg" + }, + { + "kind": "literal", + "value": "image/png" + }, + { + "kind": "literal", + "value": "image/webp" + }, + { + "kind": "object", + "properties": [ + { + "name": "height", + "type": 2, + "optional": false + }, + { + "name": "width", + "type": 2, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": true + }, + { + "kind": "literal", + "value": "image" + }, + { + "kind": "object", + "properties": [ + { + "name": "attachment", + "type": 32, + "optional": false + }, + { + "name": "type", + "type": 33, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "attachmentId", + "type": 10, + "optional": false + }, + { + "name": "bytes", + "type": 2, + "optional": false + }, + { + "name": "name", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "file" + }, + { + "kind": "primitive", + "type": "boolean" + }, + { + "kind": "literal", + "value": "tool" + }, + { + "kind": "object", + "properties": [ + { + "name": "callId", + "type": 10, + "optional": false + }, + { + "name": "kind", + "type": 35, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "content", + "type": 7, + "optional": false + }, + { + "name": "id", + "type": 10, + "optional": false + }, + { + "name": "role", + "type": 38, + "optional": false + }, + { + "name": "source", + "type": 39, + "optional": false, + "compatibility": { + "version": 1, + "policy": "session-source-attribution", + "binding": "session.developer-message.source", + "discriminator": "kind", + "unknownKinds": "preserve", + "attributionKinds": [ + "tmux-context", + "user-question-reply", + "working-directory" + ] + } + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "developer" + }, + { + "kind": "union", + "types": [ + 36, + 40, + 45, + 47, + 49, + 51, + 53, + 55, + 57, + 58, + 60, + 62, + 63, + 65, + 67, + 69, + 71, + 73, + 75, + 77, + 78, + 79, + 80, + 81, + 84, + 87, + 89, + 98, + 101, + 104, + 106, + 108, + 110, + 115, + 117, + 119, + 127, + 128, + 129, + 130, + 131, + 132, + 133, + 134, + 135, + 136, + 137, + 138, + 139, + 140, + 141, + 142, + 143, + 144, + 145, + 146, + 147, + 148, + 149, + 150, + 151, + 152, + 153, + 154, + 155, + 156, + 157, + 158, + 159, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 174, + 175, + 176, + 177, + 178, + 179, + 180, + 181, + 182, + 183, + 184, + 185, + 186, + 187, + 188, + 189, + 190, + 191, + 192, + 193, + 194, + 195, + 196, + 198, + 200, + 203, + 204, + 205 + ] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "snapshot" + }, + { + "kind": "literal", + "value": "time-context" + }, + { + "kind": "array", + "element": 44 + }, + { + "kind": "object", + "properties": [ + { + "name": "name", + "type": 10, + "optional": false + }, + { + "name": "text", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 46, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "plan-mode" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 48, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "ptc-mode" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 50, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "repeat-tool-reminder" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "runtime-context" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "schedule" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 56, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "system-prompt" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tmux-context" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-goal" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 64, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-jobs" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 66, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-registry" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 68, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 70, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user-approval" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 72, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "working-directory" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 74, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "cordis-host-runner" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 76, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "dsh-session-title-llm" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 64, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 70, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 76, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 83, + "optional": false + }, + { + "name": "senderSessionId", + "type": 10, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "notice" + }, + { + "kind": "literal", + "value": "subagent-settled" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 86, + "optional": false + }, + { + "name": "senderSessionId", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "relay" + }, + { + "kind": "literal", + "value": "agent-message" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 88, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "hooks-claude-code" + }, + { + "kind": "object", + "properties": [ + { + "name": "baseline", + "type": 29, + "optional": true + }, + { + "name": "baselineIdentity", + "type": 10, + "optional": true + }, + { + "name": "changes", + "type": 90, + "optional": false + }, + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 97, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 91 + }, + { + "kind": "object", + "properties": [ + { + "name": "action", + "type": 92, + "optional": false + }, + { + "name": "digest", + "type": 10, + "optional": true + }, + { + "name": "path", + "type": 10, + "optional": false + }, + { + "name": "scope", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "union", + "types": [ + 93, + 94, + 95 + ] + }, + { + "kind": "literal", + "value": "remove" + }, + { + "kind": "literal", + "value": "replace" + }, + { + "kind": "literal", + "value": "set" + }, + { + "kind": "literal", + "value": "instructions" + }, + { + "kind": "literal", + "value": "agent-instructions" + }, + { + "kind": "object", + "properties": [ + { + "name": "callId", + "type": 10, + "optional": false + }, + { + "name": "kind", + "type": 99, + "optional": false + }, + { + "name": "outcome", + "type": 100, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user-question-reply" + }, + { + "kind": "literal", + "value": "answered" + }, + { + "kind": "object", + "properties": [ + { + "name": "clientTimeZone", + "type": 10, + "optional": true + }, + { + "name": "kind", + "type": 68, + "optional": false + }, + { + "name": "principal", + "type": 102, + "optional": true + }, + { + "name": "rpcId", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 103, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "owner" + }, + { + "kind": "object", + "properties": [ + { + "name": "compactionId", + "type": 10, + "optional": false + }, + { + "name": "kind", + "type": 105, + "optional": false + }, + { + "name": "sourceCommandId", + "type": 10, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "compact-checkpoint" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 107, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "hooks-codex" + }, + { + "kind": "object", + "properties": [ + { + "name": "deliveryId", + "type": 10, + "optional": false + }, + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 109, + "optional": false + }, + { + "name": "provider", + "type": 10, + "optional": false + }, + { + "name": "ruleId", + "type": 10, + "optional": false + }, + { + "name": "source", + "type": 10, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "webhook" + }, + { + "kind": "object", + "properties": [ + { + "name": "entries", + "type": 111, + "optional": false + }, + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 114, + "optional": false + }, + { + "name": "update", + "type": 29, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 112 + }, + { + "kind": "object", + "properties": [ + { + "name": "description", + "type": 10, + "optional": false + }, + { + "name": "name", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "catalog" + }, + { + "kind": "literal", + "value": "skill-catalog" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 116, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "model-selection" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 118, + "optional": false + }, + { + "name": "name", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "skill-invocation" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 121, + "optional": false + }, + { + "name": "references", + "type": 122, + "optional": false + }, + { + "name": "version", + "type": 126, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "recall" + }, + { + "kind": "literal", + "value": "session-reference" + }, + { + "kind": "array", + "element": 123 + }, + { + "kind": "object", + "properties": [ + { + "name": "capturedFormatVersion", + "type": 2, + "optional": true + }, + { + "name": "capturedThroughSeq", + "type": 124, + "optional": false + }, + { + "name": "compacted", + "type": 34, + "optional": false + }, + { + "name": "inputIndex", + "type": 2, + "optional": false + }, + { + "name": "label", + "type": 10, + "optional": false + }, + { + "name": "omittedBytes", + "type": 2, + "optional": false + }, + { + "name": "omittedMessages", + "type": 2, + "optional": false + }, + { + "name": "originalMessages", + "type": 2, + "optional": false + }, + { + "name": "retainedMessages", + "type": 2, + "optional": false + }, + { + "name": "sessionId", + "type": 10, + "optional": false + }, + { + "name": "truncated", + "type": 34, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "union", + "types": [ + 2, + 125 + ] + }, + { + "kind": "primitive", + "type": "null" + }, + { + "kind": "literal", + "value": 1 + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 88, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 64, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 70, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 76, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 88, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 107, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 116, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 107, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 64, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 70, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 76, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 88, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 107, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 116, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 116, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 64, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 70, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 76, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 88, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 107, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 116, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 64, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 70, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 76, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 88, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 107, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 116, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 64, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 70, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 76, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "goalId", + "type": 10, + "optional": false + }, + { + "name": "kind", + "type": 197, + "optional": false + }, + { + "name": "revision", + "type": 2, + "optional": false + }, + { + "name": "round", + "type": 2, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "goal" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 199, + "optional": false + }, + { + "name": "messageId", + "type": 10, + "optional": false + }, + { + "name": "senderId", + "type": 10, + "optional": false + }, + { + "name": "senderName", + "type": 10, + "optional": false + }, + { + "name": "teamId", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "team-message" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 201, + "optional": false + }, + { + "name": "model", + "type": 10, + "optional": false + }, + { + "name": "provider", + "type": 10, + "optional": false + }, + { + "name": "replayState", + "type": 202, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "model" + }, + { + "kind": "opaque", + "reason": "unknown" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 88, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 107, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 116, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "content", + "type": 7, + "optional": false + }, + { + "name": "id", + "type": 10, + "optional": false + }, + { + "name": "role", + "type": 68, + "optional": false + }, + { + "name": "source", + "type": 39, + "optional": false, + "compatibility": { + "version": 1, + "policy": "session-source-attribution", + "binding": "session.user-message.source", + "discriminator": "kind", + "unknownKinds": "preserve", + "attributionKinds": [ + "tmux-context", + "user-question-reply", + "working-directory" + ] + } + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "content", + "type": 7, + "optional": false + }, + { + "name": "id", + "type": 10, + "optional": false + }, + { + "name": "role", + "type": 208, + "optional": false + }, + { + "name": "source", + "type": 200, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "assistant" + }, + { + "kind": "object", + "properties": [ + { + "name": "content", + "type": 7, + "optional": false + }, + { + "name": "id", + "type": 10, + "optional": false + }, + { + "name": "role", + "type": 210, + "optional": false + }, + { + "name": "source", + "type": 55, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "system" + }, + { + "kind": "object", + "properties": [ + { + "name": "model", + "type": 10, + "optional": false + }, + { + "name": "provider", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "session/title-llm-request" + } + ] + } + }, + { + "key": "event:user/message", + "kind": "event", + "event": "user/message", + "surface": true, + "digest": "2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8", + "schema": { + "root": 0, + "nodes": [ + { + "kind": "object", + "properties": [ + { + "name": "data", + "type": 1, + "optional": false + }, + { + "name": "ignorable", + "type": 25, + "optional": true + }, + { + "name": "seq", + "type": 18, + "optional": false + }, + { + "name": "sourceEventSeqs", + "type": 200, + "optional": true + }, + { + "name": "surfaceOp", + "type": 201, + "optional": false + }, + { + "name": "time", + "type": 18, + "optional": false + }, + { + "name": "type", + "type": 204, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "content", + "type": 2, + "optional": false + }, + { + "name": "id", + "type": 5, + "optional": false + }, + { + "name": "role", + "type": 30, + "optional": false + }, + { + "name": "source", + "type": 31, + "optional": false, + "compatibility": { + "version": 1, + "policy": "session-source-attribution", + "binding": "session.user-message.source", + "discriminator": "kind", + "unknownKinds": "preserve", + "attributionKinds": [ + "tmux-context", + "user-question-reply", + "working-directory" + ] + } + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 3 + }, + { + "kind": "union", + "types": [ + 4, + 7, + 9, + 12, + 14, + 16, + 27 + ] + }, + { + "kind": "object", + "properties": [ + { + "name": "text", + "type": 5, + "optional": false + }, + { + "name": "type", + "type": 6, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "string" + }, + { + "kind": "literal", + "value": "reasoning" + }, + { + "kind": "object", + "properties": [ + { + "name": "text", + "type": 5, + "optional": false + }, + { + "name": "type", + "type": 8, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "text" + }, + { + "kind": "object", + "properties": [ + { + "name": "tool", + "type": 10, + "optional": true + }, + { + "name": "toolName", + "type": 5, + "optional": false + }, + { + "name": "type", + "type": 11, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "never" + }, + { + "kind": "literal", + "value": "tool-addition" + }, + { + "kind": "object", + "properties": [ + { + "name": "toolName", + "type": 5, + "optional": false + }, + { + "name": "type", + "type": 13, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-removal" + }, + { + "kind": "object", + "properties": [ + { + "name": "arguments", + "type": 5, + "optional": false + }, + { + "name": "id", + "type": 5, + "optional": false + }, + { + "name": "name", + "type": 5, + "optional": false + }, + { + "name": "type", + "type": 15, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-call" + }, + { + "kind": "object", + "properties": [ + { + "name": "attachment", + "type": 17, + "optional": false + }, + { + "name": "offloaded", + "type": 25, + "optional": true + }, + { + "name": "type", + "type": 26, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "attachmentId", + "type": 5, + "optional": false + }, + { + "name": "bytes", + "type": 18, + "optional": false + }, + { + "name": "height", + "type": 18, + "optional": false + }, + { + "name": "mediaType", + "type": 19, + "optional": false + }, + { + "name": "name", + "type": 5, + "optional": true + }, + { + "name": "originalDimensions", + "type": 24, + "optional": true + }, + { + "name": "width", + "type": 18, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "number" + }, + { + "kind": "union", + "types": [ + 20, + 21, + 22, + 23 + ] + }, + { + "kind": "literal", + "value": "image/gif" + }, + { + "kind": "literal", + "value": "image/jpeg" + }, + { + "kind": "literal", + "value": "image/png" + }, + { + "kind": "literal", + "value": "image/webp" + }, + { + "kind": "object", + "properties": [ + { + "name": "height", + "type": 18, + "optional": false + }, + { + "name": "width", + "type": 18, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": true + }, + { + "kind": "literal", + "value": "image" + }, + { + "kind": "object", + "properties": [ + { + "name": "attachment", + "type": 28, + "optional": false + }, + { + "name": "type", + "type": 29, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "attachmentId", + "type": 5, + "optional": false + }, + { + "name": "bytes", + "type": 18, + "optional": false + }, + { + "name": "name", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "file" + }, + { + "kind": "literal", + "value": "user" + }, + { + "kind": "union", + "types": [ + 32, + 35, + 37, + 39, + 41, + 43, + 45, + 47, + 49, + 51, + 53, + 55, + 58, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 101, + 102, + 103, + 104, + 105, + 106, + 107, + 108, + 109, + 110, + 111, + 112, + 113, + 115, + 117, + 120, + 121, + 122, + 123, + 124, + 126, + 127, + 128, + 129, + 131, + 132, + 133, + 134, + 135, + 137, + 138, + 139, + 141, + 143, + 144, + 152, + 155, + 157, + 160, + 162, + 164, + 168, + 170, + 178, + 182, + 183, + 184, + 185, + 186, + 187, + 188, + 189, + 190, + 191, + 192, + 193, + 194, + 196, + 198, + 199 + ] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 34, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "notice" + }, + { + "kind": "literal", + "value": "model-selection" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 36, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "plan-mode" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 38, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "repeat-tool-reminder" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "runtime-context" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "schedule" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "time-context" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tmux-context" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 48, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-goal" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-jobs" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user-approval" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "dsh-session-title-llm" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 57, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "instructions" + }, + { + "kind": "literal", + "value": "hooks-claude-code" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "hooks-codex" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 34, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 38, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 48, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 57, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "recall" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 34, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 38, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 48, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 57, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "relay" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 34, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 38, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 48, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 57, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "catalog" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 34, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 38, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 48, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "goalId", + "type": 5, + "optional": false + }, + { + "name": "kind", + "type": 114, + "optional": false + }, + { + "name": "revision", + "type": 18, + "optional": false + }, + { + "name": "round", + "type": 18, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "goal" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 116, + "optional": false + }, + { + "name": "messageId", + "type": 5, + "optional": false + }, + { + "name": "senderId", + "type": 5, + "optional": false + }, + { + "name": "senderName", + "type": 5, + "optional": false + }, + { + "name": "teamId", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "team-message" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 118, + "optional": false + }, + { + "name": "model", + "type": 5, + "optional": false + }, + { + "name": "provider", + "type": 5, + "optional": false + }, + { + "name": "replayState", + "type": 119, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "model" + }, + { + "kind": "opaque", + "reason": "unknown" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 57, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 59, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 34, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 125, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "ptc-mode" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 38, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 130, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "system-prompt" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 46, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 48, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 50, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 136, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-registry" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 30, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 52, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 140, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "working-directory" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 142, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "cordis-host-runner" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "baseline", + "type": 25, + "optional": true + }, + { + "name": "baselineIdentity", + "type": 5, + "optional": true + }, + { + "name": "changes", + "type": 145, + "optional": false + }, + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 151, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 146 + }, + { + "kind": "object", + "properties": [ + { + "name": "action", + "type": 147, + "optional": false + }, + { + "name": "digest", + "type": 5, + "optional": true + }, + { + "name": "path", + "type": 5, + "optional": false + }, + { + "name": "scope", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "union", + "types": [ + 148, + 149, + 150 + ] + }, + { + "kind": "literal", + "value": "remove" + }, + { + "kind": "literal", + "value": "replace" + }, + { + "kind": "literal", + "value": "set" + }, + { + "kind": "literal", + "value": "agent-instructions" + }, + { + "kind": "object", + "properties": [ + { + "name": "callId", + "type": 5, + "optional": false + }, + { + "name": "kind", + "type": 153, + "optional": false + }, + { + "name": "outcome", + "type": 154, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user-question-reply" + }, + { + "kind": "literal", + "value": "answered" + }, + { + "kind": "object", + "properties": [ + { + "name": "callId", + "type": 5, + "optional": false + }, + { + "name": "kind", + "type": 156, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool" + }, + { + "kind": "object", + "properties": [ + { + "name": "clientTimeZone", + "type": 5, + "optional": true + }, + { + "name": "kind", + "type": 30, + "optional": false + }, + { + "name": "principal", + "type": 158, + "optional": true + }, + { + "name": "rpcId", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 159, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "owner" + }, + { + "kind": "object", + "properties": [ + { + "name": "compactionId", + "type": 5, + "optional": false + }, + { + "name": "kind", + "type": 161, + "optional": false + }, + { + "name": "sourceCommandId", + "type": 5, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "compact-checkpoint" + }, + { + "kind": "object", + "properties": [ + { + "name": "deliveryId", + "type": 5, + "optional": false + }, + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 163, + "optional": false + }, + { + "name": "provider", + "type": 5, + "optional": false + }, + { + "name": "ruleId", + "type": 5, + "optional": false + }, + { + "name": "source", + "type": 5, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "webhook" + }, + { + "kind": "object", + "properties": [ + { + "name": "entries", + "type": 165, + "optional": false + }, + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 167, + "optional": false + }, + { + "name": "update", + "type": 25, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 166 + }, + { + "kind": "object", + "properties": [ + { + "name": "description", + "type": 5, + "optional": false + }, + { + "name": "name", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "skill-catalog" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 56, + "optional": false + }, + { + "name": "kind", + "type": 169, + "optional": false + }, + { + "name": "name", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "skill-invocation" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 171, + "optional": false + }, + { + "name": "references", + "type": 172, + "optional": false + }, + { + "name": "version", + "type": 177, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "session-reference" + }, + { + "kind": "array", + "element": 173 + }, + { + "kind": "object", + "properties": [ + { + "name": "capturedFormatVersion", + "type": 18, + "optional": true + }, + { + "name": "capturedThroughSeq", + "type": 174, + "optional": false + }, + { + "name": "compacted", + "type": 176, + "optional": false + }, + { + "name": "inputIndex", + "type": 18, + "optional": false + }, + { + "name": "label", + "type": 5, + "optional": false + }, + { + "name": "omittedBytes", + "type": 18, + "optional": false + }, + { + "name": "omittedMessages", + "type": 18, + "optional": false + }, + { + "name": "originalMessages", + "type": 18, + "optional": false + }, + { + "name": "retainedMessages", + "type": 18, + "optional": false + }, + { + "name": "sessionId", + "type": 5, + "optional": false + }, + { + "name": "truncated", + "type": 176, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "union", + "types": [ + 18, + 175 + ] + }, + { + "kind": "primitive", + "type": "null" + }, + { + "kind": "primitive", + "type": "boolean" + }, + { + "kind": "literal", + "value": 1 + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 57, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "snapshot" + }, + { + "kind": "array", + "element": 181 + }, + { + "kind": "object", + "properties": [ + { + "name": "name", + "type": 5, + "optional": false + }, + { + "name": "text", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 34, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 36, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 38, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 46, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 48, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 50, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + }, + { + "name": "sections", + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 195, + "optional": false + }, + { + "name": "senderSessionId", + "type": 5, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "subagent-settled" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 197, + "optional": false + }, + { + "name": "senderSessionId", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "agent-message" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 57, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 59, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "array", + "element": 18 + }, + { + "kind": "union", + "types": [ + 202, + 203 + ] + }, + { + "kind": "literal", + "value": "append" + }, + { + "kind": "object", + "properties": [ + { + "name": "endSeq", + "type": 18, + "optional": false + }, + { + "name": "op", + "type": 149, + "optional": false + }, + { + "name": "startSeq", + "type": 18, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user/message" + } + ] + } + } + ], + "types": [] +} diff --git a/docs/persistence-changes/2026-10-13-user-rpc-principal.zh.md b/docs/persistence-changes/2026-10-13-user-rpc-principal.zh.md new file mode 100644 index 0000000000..5dca79c486 --- /dev/null +++ b/docs/persistence-changes/2026-10-13-user-rpc-principal.zh.md @@ -0,0 +1,60 @@ +--- +description: "记录持久化类型更改及其兼容性确认。" +kind: persistence-change +--- + +# 2026-10-13-user-rpc-principal + +[English](2026-10-13-user-rpc-principal.md) | 中文 + +## 概述 + +为 owner 以外的调用方提交的 prompt,在 user-rpc 消息来源上增加可选的 principal。 + +## 目录 + +- [声明](#declaration) +- [兼容性](#compatibility) +- [验证](#verification) +- [开发备注](#dev-note) + + +## 声明 + +```yaml persistence-change +schemaVersion: 1 +id: 2026-10-13-user-rpc-principal +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-10-05-working-directory-attribution" + after: "0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034" + decision: same-version + - root: "event:developer/message" + previous: "2026-10-05-working-directory-attribution" + after: "97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-10-07-title-reasoning-effort" + after: "79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056" + decision: same-version + - root: "event:user/message" + previous: "2026-10-05-working-directory-attribution" + after: "2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8" + decision: same-version +``` + + +## 兼容性 + +owner 的 prompt 不写该字段,因此其来源与所有既有 Session 日志都不变;缺少 principal 即为 owner。早于该字段的读取方会忽略它,并因 kind 仍为 'user' 而把消息当作普通用户消息。当前读取方读取旧日志时找不到 principal,把每条消息都视为 owner 的消息。该字段不进入任何模型请求:provider 适配器只读取模型可见的消息内容。SESSION_FORMAT_VERSION 不变。 + + +## 验证 + +pnpm exec vitest run packages/api/session-controller/tests/remote-access.host.spec.ts packages/subagent/subagent/tests/control.spec.ts packages/api/session-controller/tests/session-cold.host.spec.ts:非 owner 的 prompt 在 agent/inbox/spliced 中持久化 source.principal,owner 与既有时区来源保持逐字节不变;全部测试通过。 + + +## 开发备注 + +无。 diff --git a/docs/persistence-changes/README.i18n.yaml b/docs/persistence-changes/README.i18n.yaml index 30537db444..aa185ca392 100644 --- a/docs/persistence-changes/README.i18n.yaml +++ b/docs/persistence-changes/README.i18n.yaml @@ -18,11 +18,11 @@ en: 6cd0f79a9455bdf2 zh: a5978b7834c0802b /persistence-type-change-records/compatibility-rules: - en: 62ce78d5618572b6 - zh: 023021d431f8a8e6 + en: 218b28a5096b5e7d + zh: 5b987c852e204893 /persistence-type-change-records/history-and-limitations: - en: 10a426d36c41548b - zh: ef03b693d9d9be26 + en: 705a215ce0dd5d82 + zh: a3b3e46231dae6ce /persistence-type-change-records/dev-note: en: 5de1d6304e00c58f zh: 8d8225361cfa29e5 diff --git a/docs/persistence-changes/README.md b/docs/persistence-changes/README.md index 4f6cf773a9..79e1401414 100644 --- a/docs/persistence-changes/README.md +++ b/docs/persistence-changes/README.md @@ -46,25 +46,27 @@ The [record template](../../.agents/skills/dsh-doc/templates/persistence-change. ## Compatibility rules -Every detected structural change requires an acknowledgement. Record creation and update infer the minimum decision from these fixed rules; an explicit `--decision` is a checked assertion. The rules apply to the complete change, so an allowed change cannot hide a simultaneous breaking change. +Every detected structural change requires an acknowledgement. Keep the Session version when older readers preserve the required meaning of accepted data, safely ignore optional features while retaining opaque records, or refuse unsupported required data before execution, mutation, or recovery truncation. New readers must preserve historical meaning and readability. Bump only when unsafe interpretation cannot be prevented by an effective discriminator. Unknown fields or values count only when existing readers actually handle them safely; type differences alone cannot establish that behavior. See the [reader-compatibility decision](../../.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.md). -| Detected change | Minimum decision | +| Detected change | Recording requirement | |---|---| | Add an optional event-body property, including its complete subtree | `same-version` | | Make a required event-body property optional | `same-version` | | Add an ordinary event type | `same-version` | | Add a higher numeric `data.version` to an ordinary event while retaining every old payload alternative under the existing compatibility rules | `same-version` | | Add an explicitly qualified attribution kind to a user/developer source slot whose before and after schemas carry the same supported policy | `same-version` | -| Make an optional property required, add a required property, change an existing type, or remove/rename a property or event | `version-bump` | -| Change the Session header or event envelope | `version-bump` | +| Make an optional property required, add a required property, change an existing type, or remove/rename a property or event | Compatibility review for `same-version`, or explicit `version-bump` | +| Change the Session header or event envelope | Compatibility review for `same-version`; a header version change requires `version-bump` | -A finalized checkpoint protects the accepted baseline without replacing these compatibility rules. At V4, optional additions, ordinary events, and qualified attribution additions can receive new same-version records. Breaking differences require a higher writer version and an acknowledgement containing its own header increase. The accepted V4 record cannot be updated to reuse its original 3→4 transition. +The classifier identifies established same-version cases and changes requiring compatibility review; it cannot decide semantic safety. The latter require an explicit `--decision same-version` when recording or updating without a version increase. The acknowledgement’s Compatibility section explains actual reader behavior in both directions, and Verification records the executed checks. Review the complete transition, including simultaneous changes. An explicit `version-bump` instead requires its own increasing `SessionHeader.version` transition; a same-version decision cannot waive a header version change. Finalized records remain immutable, so a later record cannot reuse the accepted 3→4 transition. -An ordinary event may add payload alternatives with a required, nonnegative integer `data.version` greater than every existing payload version, provided every existing alternative remains readable under the compatibility rules above. Optional property additions and required-to-optional changes may accompany the new version; each retained alternative is compared separately. The reader must retain support for the old payloads; adding variants at an existing version, dropping old versions, and changing the Session header or envelope remain breaking. Older readers may reject the new payload version. The [catalog acknowledgement](2026-09-20-unknown-child-catalog.md) records one such transition. +The CLI requires that explicit choice before generating a flagged same-version record. CI reads the recorded `decision: same-version` and accepts it when the ordinary history, schema, and header-version constraints hold, whether the record was generated or edited manually. Verification cannot establish how the record was authored or whether a human reviewed it. Reviewers compare base and head inventories with [`persistence-review`](../cookbook/reviewing-persistence-type-changes.md#generate); `--check` validates current-tree consistency and cannot reveal a transition already covered by an acknowledgement. -The extractor accepts an explicit `@persistenceSource` binding for a core-owned source property on a literal user or developer role; it does not infer a binding from an unannotated type. A producer qualifies its `MessageSourceMap` entry with `@persistenceAttribution`. Qualification promises that an unknown kind and its JSON metadata survive reading without the producer, and that the kind imposes no validation, replay, or authority requirement. A producer may inspect its own kind to resume duplicate suppression; other readers must preserve and derive the recorded messages without that projection. The recorded schema retains the binding, policy version, literal `kind` discriminator, preservation promise, and qualified kind set. Inventory format 2 stores those promises; extraction without a bound policy retains format 1. Session format versions are independent. Both compared snapshots must carry compatible policy state. Existing kind groups still receive ordinary structural comparison; removals, unmarked additions, policy changes, and unrelated breaking changes remain strict. Multiple context-form alternatives with the same wire kind form one group. +An ordinary event may add payload alternatives with a required, nonnegative integer `data.version` greater than every existing payload version, provided every existing alternative remains readable under the established same-version rules above. Optional property additions and required-to-optional changes may accompany the new version; each retained alternative is compared separately. Other payload changes require compatibility review. Older readers may reject the new payload version. The [catalog acknowledgement](2026-09-20-unknown-child-catalog.md) records one such transition. -A same-version explanation states how old records remain readable and how older readers handle new records. Optional additions explain why older readers can ignore them without changing replay; a new payload version records the older-reader rejection. For required-to-optional changes, it explains how readers handle an absent value. The checker validates the type classification; reviewers assess the explanation. A version-bump record includes the increasing header version in the same transition and follows the [Session-format procedure](../cookbook/adding-a-session-format-version.md). +The extractor accepts an explicit `@persistenceSource` binding for a core-owned source property on a literal user or developer role; it does not infer a binding from an unannotated type. A producer qualifies its `MessageSourceMap` entry with `@persistenceAttribution`. Qualification promises that an unknown kind and its JSON metadata survive reading without the producer, and that the kind imposes no validation, replay, or authority requirement. A producer may inspect its own kind to resume duplicate suppression; other readers must preserve and derive the recorded messages without that projection. The recorded schema retains the binding, policy version, literal `kind` discriminator, preservation promise, and qualified kind set. Inventory format 2 stores those promises; extraction without a bound policy retains format 1. Session format versions are independent. Both compared snapshots must carry compatible policy state. Existing kind groups still receive ordinary structural comparison; removals, unmarked additions, policy changes, and unrelated structural changes require compatibility review. Multiple context-form alternatives with the same wire kind form one group. + +Every same-version explanation states how old records remain readable and how older readers handle new records, including established cases that need no explicit CLI decision. A feature absent from a log must retain the old behavior; dispensable features must be safe to ignore; required features need an effective refusal signal. Unsupported-feature refusal must not become corruption recovery or tail truncation. For required-to-optional changes, explain how readers handle an absent value. Reviewers assess behavior and evidence; the checker validates the declaration and type classification. A version-bump record follows the [Session-format procedure](../cookbook/adding-a-session-format-version.md). When a reader rejects a JSON property by name, declare the property as optional `never` and mark it with argument-free `@persistenceReserved`. The extractor retains the forbidden field, so allowing a JSON value later requires an existing-field type change. Required or JSON-valued properties cannot carry this marker. Unmarked optional `never` and `undefined` properties retain their existing omission behavior. @@ -75,7 +77,7 @@ One baseline records the complete initial inventory. Later records use their pre Accepted records describe historical transitions; preserve their machine declarations and schema snapshots when adding a successor. An unaccepted terminal record can be refreshed explicitly; the command rejects baselines, records with dependants, and checkpoint-locked records before producing artifacts. Verification checks retained checkpoint hashes; it does not prove that the checkpoints and their authority record were never edited together. No Git ref, remote service, or released checkout supplies the baseline. -Digests describe declared persistence types, not runtime validation or behavior. Ordinary comments, source locations, alias names, and harmless declaration reordering do not affect them. Compatibility annotations are recorded policy data and do affect digests. Unannotated version-1 snapshots retain their original normalization, fingerprints, and strict classification; policy-bearing graphs use a separate fingerprint domain. Object fields, union alternatives, intersection operands, and index signatures can be reordered when their resolved types stay the same; tuple positions and numeric enum values remain significant. Catalog text and source locations may still change, so regenerate stale artifacts without adding an acknowledgement for an unchanged digest. Opaque types such as `unknown` expose no hidden structure to compare. Behavior-only changes and structures hidden inside opaque values are outside this mechanism's scope. The [decision](../../.agents/notes/implemented/process/2026-09-11-persistence-type-history.md) records these trade-offs. +Digests describe declared persistence types, not runtime validation or behavior. Ordinary comments, source locations, alias names, and harmless declaration reordering do not affect them. Compatibility annotations are recorded policy data and do affect digests. Unannotated version-1 snapshots retain their original normalization and fingerprints; policy-bearing graphs use a separate fingerprint domain. Object fields, union alternatives, intersection operands, and index signatures can be reordered when their resolved types stay the same; tuple positions and numeric enum values remain significant. Catalog text and source locations may still change, so regenerate stale artifacts without adding an acknowledgement for an unchanged digest. Opaque types such as `unknown` expose no hidden structure to compare. Behavior-only changes and structures hidden inside opaque values are outside this mechanism's scope. The [decision](../../.agents/notes/implemented/process/2026-09-11-persistence-type-history.md) records these trade-offs. ## Dev Note diff --git a/docs/persistence-changes/README.zh.md b/docs/persistence-changes/README.zh.md index 5754ff07c1..c7efb7f6cb 100644 --- a/docs/persistence-changes/README.zh.md +++ b/docs/persistence-changes/README.zh.md @@ -46,25 +46,27 @@ description: "审阅和维护已记录的会话持久化类型变更、对应 sc ## 兼容性规则 -每个检测到的结构变更都需要确认。创建和更新记录依据这些固定规则推断最低决策;显式 `--decision` 是受检查的断言。规则应用于整个变更,因此允许的变更不能掩盖同时发生的破坏性变更。 +每个检测到的结构变更都需要确认。当旧读取器保留所接受数据的必要含义、安全忽略可选功能并保留不透明记录,或在执行、修改及恢复截断前拒绝不受支持的必要数据时,可以保留 Session 版本。新读取器必须保留历史含义和可读性。只有有效判别信息无法阻止不安全解释时,才提升版本。未知字段或值只有在已有读取器实际安全处理它们时才有效;类型差异本身无法证明这种行为。参见[读取器兼容性决策](../../.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.zh.md)。 -| 检测到的变更 | 最低决策要求 | +| 检测到的变更 | 记录要求 | |---|---| | 添加可选事件体属性,包括其完整子树 | `same-version` | | 将必选事件体属性改为可选 | `same-version` | | 添加普通事件类型 | `same-version` | | 为普通事件增加更高的数字 `data.version`,并按现有兼容性规则保留所有旧载荷分支 | `same-version` | | 在前后 schema 均带有相同受支持策略的 user/developer 消息源字段中,添加显式声明为归属信息的 kind | `same-version` | -| 将可选属性改为必选、添加必选属性、更改已有类型,或删除/重命名属性或事件 | `version-bump` | -| 更改会话头或事件封装 | `version-bump` | +| 将可选属性改为必选、添加必选属性、更改已有类型,或删除/重命名属性或事件 | `same-version` 需兼容性评审,或显式 `version-bump` | +| 更改会话头或事件封装 | `same-version` 需兼容性评审;头版本变化要求 `version-bump` | -定稿检查点保护已接受基线,不替换这些兼容性规则。在 V4 中,可选新增、普通事件及符合条件的归属 kind 新增可以使用新的同版本记录。破坏性差异要求更高的写入器版本,以及包含自身头版本递增的确认记录。不能更新已接受 V4 记录以复用其原有 3→4 转换。 +分类器识别已明确允许的同版本情形及需要兼容性评审的变更,不能判定语义安全性。后者在不升版本的记录或更新操作中要求显式提供 `--decision same-version`。确认记录的兼容性部分说明两个方向上的实际读取器行为,验证部分记录已执行的检查。评审覆盖整个转换,包括同时发生的其他变更。显式 `version-bump` 则要求自身包含 `SessionHeader.version` 递增转换;同版本决策不能豁免头版本变化。定稿记录保持不可变,因此后续记录不能复用已接受的 3→4 转换。 -普通事件可增加具有必选、非负整数 `data.version` 的载荷分支,新版本必须高于所有已有载荷版本,且所有已有分支按上述兼容性规则保持可读。可选属性新增和必选改可选可以与新版本一同引入;每个保留分支均独立比较。读取器必须保留旧载荷支持;在已有版本中增加分支、移除旧版本,以及修改 Session header 或事件封装仍属于破坏性变更。旧读取器可能拒绝新载荷版本。[Catalog 确认记录](2026-09-20-unknown-child-catalog.zh.md) 记录了此类演进。 +CLI 在生成被标记的同版本记录前要求该显式选择。CI 读取所记录的 `decision: same-version`;只要通常的历史、schema 与头版本约束成立,无论记录由工具生成还是手工编辑,都会接受。验证无法确定记录的编写方式,也无法证明人类已评审。评审者使用 [`persistence-review`](../cookbook/reviewing-persistence-type-changes.zh.md#generate) 比较 base 与 head 清单;`--check` 验证当前目录一致性,无法显示已被确认记录覆盖的转换。 -提取器接受核心拥有的 source 属性上针对 user 或 developer 字面量角色的显式 `@persistenceSource` 绑定,不会从未标记类型中推断绑定。生产者用 `@persistenceAttribution` 标记其 `MessageSourceMap` 成员。该标记承诺:读取器无需生产者即可保留未知 kind 及其 JSON 元数据,且该 kind 不引入校验、回放或权限要求。生产者可以检查自身 kind 来恢复去重状态;其他读取器必须无需该投影也能保留并派生已记录的消息。记录的 schema 保存绑定、策略版本、字面量 `kind` 判别字段、保留承诺及符合条件的 kind 集合。Inventory format 2 保存这些承诺;没有绑定策略的提取仍使用 format 1。Session 格式版本独立于此。比较双方的快照必须带有兼容的策略状态。已有 kind 分组仍进行常规结构比较;删除、未标记的添加、策略更改及无关破坏性变更继续采用严格规则。同一 wire kind 的多个上下文形式分支归为一组。 +普通事件可增加具有必选、非负整数 `data.version` 的载荷分支,新版本必须高于所有已有载荷版本,且所有已有分支按上述明确允许的同版本规则保持可读。可选属性新增和必选改可选可以与新版本一同引入;每个保留分支均独立比较。其他载荷变更需要兼容性评审。旧读取器可能拒绝新载荷版本。[Catalog 确认记录](2026-09-20-unknown-child-catalog.zh.md)记录了此类演进。 -同版本说明须解释旧记录如何保持可读,以及旧读取器如何处理新记录。可选新增须说明旧读取器为何可以忽略它而不改变回放;新增载荷版本须记录旧读取器的拒绝行为。对于必选改可选的变更,说明须解释读取器如何处理缺失值。检查器验证类型分类;审阅者判断说明是否成立。升版本记录在同一转换中包含递增的头部版本,并遵循[会话格式流程](../cookbook/adding-a-session-format-version.zh.md)。 +提取器接受核心拥有的 source 属性上针对 user 或 developer 字面量角色的显式 `@persistenceSource` 绑定,不会从未标记类型中推断绑定。生产者用 `@persistenceAttribution` 标记其 `MessageSourceMap` 成员。该标记承诺:读取器无需生产者即可保留未知 kind 及其 JSON 元数据,且该 kind 不引入校验、回放或权限要求。生产者可以检查自身 kind 来恢复去重状态;其他读取器必须无需该投影也能保留并派生已记录的消息。记录的 schema 保存绑定、策略版本、字面量 `kind` 判别字段、保留承诺及符合条件的 kind 集合。Inventory format 2 保存这些承诺;没有绑定策略的提取仍使用 format 1。Session 格式版本独立于此。比较双方的快照必须带有兼容的策略状态。已有 kind 分组仍进行常规结构比较;删除、未标记的添加、策略更改及无关结构变更需要兼容性评审。同一 wire kind 的多个上下文形式分支归为一组。 + +每项同版本说明都须解释旧记录如何保持可读,以及旧读取器如何处理新记录,包括无需显式 CLI 决策的明确允许情形。日志未使用某功能时必须保留旧行为;可舍弃功能必须能安全忽略;必要功能需要有效的拒绝信号。不受支持功能的拒绝不能变成损坏恢复或尾部截断。对于必选改可选的变更,说明读取器如何处理缺失值。审阅者判断行为和证据;检查器校验声明及类型分类。升版本记录遵循[会话格式流程](../cookbook/adding-a-session-format-version.zh.md)。 当读取器按属性名拒绝 JSON 字段时,将该属性声明为可选 `never`,并添加无参数的 `@persistenceReserved` 标记。提取器保留这一禁止字段,因此后续允许 JSON 值属于已有字段类型变更。必选属性或允许 JSON 值的属性不能携带该标记。未标记的可选 `never` 和 `undefined` 属性保留现有省略行为。 @@ -75,7 +77,7 @@ description: "审阅和维护已记录的会话持久化类型变更、对应 sc 已接受记录描述历史转换;添加后继时须保留其机器声明和 schema 快照。尚未接受的末端记录可以显式刷新;命令在生成产物前拒绝基线、被依赖的记录和被检查点锁定的记录。验证检查所保留检查点的哈希,但不证明检查点及其真源记录从未被一起修改。基线不依赖 Git 引用、远端服务或已发布版本的检出目录。 -摘要描述声明的持久化类型,不描述运行时验证或行为。普通注释、源码位置、别名名称和无语义变化的声明重排不影响摘要。兼容性标记是记录的策略数据,会影响摘要。不带标记的版本 1 快照保留原有规范化、指纹和严格分类;包含策略的图使用独立的指纹域。对象字段、联合类型分支、交叉类型操作数和索引签名可以在解析类型不变时重排;元组位置和数字枚举值仍然影响摘要。目录文本和源码位置仍可能变化,因此应重新生成陈旧产物,无需为未变的摘要添加确认记录。`unknown` 等不透明类型不提供可比较的内部结构。纯行为变更以及不透明值中隐藏的结构不在本机制范围内。[决策记录](../../.agents/notes/implemented/process/2026-09-11-persistence-type-history.zh.md)说明这些取舍。 +摘要描述声明的持久化类型,不描述运行时验证或行为。普通注释、源码位置、别名名称和无语义变化的声明重排不影响摘要。兼容性标记是记录的策略数据,会影响摘要。不带标记的版本 1 快照保留原有规范化和指纹;包含策略的图使用独立的指纹域。对象字段、联合类型分支、交叉类型操作数和索引签名可以在解析类型不变时重排;元组位置和数字枚举值仍然影响摘要。目录文本和源码位置仍可能变化,因此应重新生成陈旧产物,无需为未变的摘要添加确认记录。`unknown` 等不透明类型不提供可比较的内部结构。纯行为变更以及不透明值中隐藏的结构不在本机制范围内。[决策记录](../../.agents/notes/implemented/process/2026-09-11-persistence-type-history.zh.md)说明这些取舍。 ## 开发备注 diff --git a/docs/persistence-changes/historical-formats/README.i18n.yaml b/docs/persistence-changes/historical-formats/README.i18n.yaml index a85d9e2a90..e24f17e991 100644 --- a/docs/persistence-changes/historical-formats/README.i18n.yaml +++ b/docs/persistence-changes/historical-formats/README.i18n.yaml @@ -15,8 +15,8 @@ en: 14c57f30e676f6e3 zh: b1a0ccf26fab3727 /session-persistence-formats/format-references: - en: 553fd4963cf19abe - zh: 7ca3cd5d0a88d35a + en: 43a4a6600fa37a1a + zh: 72174fab8355c344 /session-persistence-formats/scope-and-evidence: en: b220062139ddac1e zh: 7c4c0efe05dafa9c diff --git a/docs/persistence-changes/historical-formats/README.md b/docs/persistence-changes/historical-formats/README.md index 8f06d0e1ee..2bc0daa565 100644 --- a/docs/persistence-changes/historical-formats/README.md +++ b/docs/persistence-changes/historical-formats/README.md @@ -32,7 +32,7 @@ The index is generated from validated snapshots and the current writer constant. | 1 | PR #3349 | [V1](v1.md) | [JSON](v1.schema.json) | 54 / 415 | | 2 | `dsh-v0.1.3-alpha.2` | [V2](v2.md) | [JSON](v2.schema.json) | 56 / 435 | | 3 | PR #4320 | [V3](v3.md) | [JSON](v3.schema.json) | 60 / 467 | -| 4 | Current checkout | [Current catalog](../../persistence-catalog.md) | [JSON](../../persistence-schema.json) | 63 / 597 | +| 4 | Current checkout | [Current catalog](../../persistence-catalog.md) | [JSON](../../persistence-schema.json) | 65 / 612 | diff --git a/docs/persistence-changes/historical-formats/README.zh.md b/docs/persistence-changes/historical-formats/README.zh.md index f377a801aa..15b08f318d 100644 --- a/docs/persistence-changes/historical-formats/README.zh.md +++ b/docs/persistence-changes/historical-formats/README.zh.md @@ -32,7 +32,7 @@ description: "查找从 V0 到工作区写入器版本的每个 Session 格式 | 1 | PR #3349 | [V1](v1.zh.md) | [JSON](v1.schema.json) | 54 / 415 | | 2 | `dsh-v0.1.3-alpha.2` | [V2](v2.zh.md) | [JSON](v2.schema.json) | 56 / 435 | | 3 | PR #4320 | [V3](v3.zh.md) | [JSON](v3.schema.json) | 60 / 467 | -| 4 | 当前工作树 | [当前目录](../../persistence-catalog.zh.md) | [JSON](../../persistence-schema.json) | 63 / 597 | +| 4 | 当前工作树 | [当前目录](../../persistence-catalog.zh.md) | [JSON](../../persistence-schema.json) | 65 / 612 | diff --git a/docs/persistence-changes/releases/dsh-v0.0.1-rc.2.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.0.1-rc.2.i18n.yaml index 0ac31ac4ee..202343b8f7 100644 --- a/docs/persistence-changes/releases/dsh-v0.0.1-rc.2.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.0.1-rc.2.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-0-1-rc-2/structural-changes: - en: bdf6c95697ae5816 - zh: 0332dec60181ab4a + en: 7cd96972b43b0cb0 + zh: 7e61c1098f402657 /persistence-release-dsh-v0-0-1-rc-2/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.0.1-rc.2.md b/docs/persistence-changes/releases/dsh-v0.0.1-rc.2.md index f9deeccf24..621d74281c 100644 --- a/docs/persistence-changes/releases/dsh-v0.0.1-rc.2.md +++ b/docs/persistence-changes/releases/dsh-v0.0.1-rc.2.md @@ -191,58 +191,58 @@ changes: -Detected 45 changed roots and 48 structural differences. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 45 changed roots and 48 structural differences. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `SessionEventEnvelope` | `union-variants-changed` | `version-bump` | -| `event:agent-preset/selected.ignorable` | `optional-property-added` | `version-bump` | -| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `version-bump` | -| `event:agent/inbox/spliced.ignorable` | `optional-property-added` | `version-bump` | -| `event:approval/asked.ignorable` | `optional-property-added` | `version-bump` | -| `event:approval/decided.ignorable` | `optional-property-added` | `version-bump` | -| `event:approval/policy.ignorable` | `optional-property-added` | `version-bump` | -| `event:assistant/chunk.ignorable` | `optional-property-added` | `version-bump` | -| `event:assistant/message.ignorable` | `optional-property-added` | `version-bump` | -| `event:command/done.ignorable` | `optional-property-added` | `version-bump` | -| `event:command/run.ignorable` | `optional-property-added` | `version-bump` | -| `event:compact/end.ignorable` | `optional-property-added` | `version-bump` | -| `event:compact/prune.ignorable` | `optional-property-added` | `version-bump` | -| `event:compact/start.ignorable` | `optional-property-added` | `version-bump` | -| `event:compact/summary.ignorable` | `optional-property-added` | `version-bump` | -| `event:feedback/record.ignorable` | `optional-property-added` | `version-bump` | -| `event:goal/change.ignorable` | `optional-property-added` | `version-bump` | -| `event:hook/invoked.ignorable` | `optional-property-added` | `version-bump` | -| `event:hook/result.ignorable` | `optional-property-added` | `version-bump` | -| `event:llm/retry.ignorable` | `optional-property-added` | `version-bump` | -| `event:llm/retry-started.ignorable` | `optional-property-added` | `version-bump` | -| `event:permission/preset.ignorable` | `optional-property-added` | `version-bump` | -| `event:plan/mode.ignorable` | `optional-property-added` | `version-bump` | -| `event:request/context.ignorable` | `optional-property-added` | `version-bump` | -| `event:request/header.ignorable` | `optional-property-added` | `version-bump` | -| `event:sandbox/mode.ignorable` | `optional-property-added` | `version-bump` | -| `event:schedule/change` | `root-added` | `same-version` | -| `event:session/end-seed.ignorable` | `optional-property-added` | `version-bump` | -| `event:session/title.ignorable` | `optional-property-added` | `version-bump` | -| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `version-bump` | -| `event:session/title-llm-request.ignorable` | `optional-property-added` | `version-bump` | -| `event:step/end.ignorable` | `optional-property-added` | `version-bump` | -| `event:step/start.ignorable` | `optional-property-added` | `version-bump` | -| `event:subagent/descriptor.ignorable` | `optional-property-added` | `version-bump` | -| `event:todo/write.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool-workflow/agent-end` | `root-added` | `same-version` | -| `event:tool-workflow/agent-start` | `root-added` | `same-version` | -| `event:tool-workflow/run-end` | `root-added` | `same-version` | -| `event:tool-workflow/run-start` | `root-added` | `same-version` | -| `event:tool/call.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/code-dispatch.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/code-dispatch-start.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/result.ignorable` | `optional-property-added` | `version-bump` | -| `event:turn/end.ignorable` | `optional-property-added` | `version-bump` | -| `event:turn/start.ignorable` | `optional-property-added` | `version-bump` | -| `event:user/message.data.source` | `union-variants-changed` | `version-bump` | -| `event:user/message.ignorable` | `optional-property-added` | `version-bump` | -| `event:web/deepseek-search-llm-request.ignorable` | `optional-property-added` | `version-bump` | +| `SessionEventEnvelope` | `union-variants-changed` | `review-required` | +| `event:agent-preset/selected.ignorable` | `optional-property-added` | `review-required` | +| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `review-required` | +| `event:agent/inbox/spliced.ignorable` | `optional-property-added` | `review-required` | +| `event:approval/asked.ignorable` | `optional-property-added` | `review-required` | +| `event:approval/decided.ignorable` | `optional-property-added` | `review-required` | +| `event:approval/policy.ignorable` | `optional-property-added` | `review-required` | +| `event:assistant/chunk.ignorable` | `optional-property-added` | `review-required` | +| `event:assistant/message.ignorable` | `optional-property-added` | `review-required` | +| `event:command/done.ignorable` | `optional-property-added` | `review-required` | +| `event:command/run.ignorable` | `optional-property-added` | `review-required` | +| `event:compact/end.ignorable` | `optional-property-added` | `review-required` | +| `event:compact/prune.ignorable` | `optional-property-added` | `review-required` | +| `event:compact/start.ignorable` | `optional-property-added` | `review-required` | +| `event:compact/summary.ignorable` | `optional-property-added` | `review-required` | +| `event:feedback/record.ignorable` | `optional-property-added` | `review-required` | +| `event:goal/change.ignorable` | `optional-property-added` | `review-required` | +| `event:hook/invoked.ignorable` | `optional-property-added` | `review-required` | +| `event:hook/result.ignorable` | `optional-property-added` | `review-required` | +| `event:llm/retry.ignorable` | `optional-property-added` | `review-required` | +| `event:llm/retry-started.ignorable` | `optional-property-added` | `review-required` | +| `event:permission/preset.ignorable` | `optional-property-added` | `review-required` | +| `event:plan/mode.ignorable` | `optional-property-added` | `review-required` | +| `event:request/context.ignorable` | `optional-property-added` | `review-required` | +| `event:request/header.ignorable` | `optional-property-added` | `review-required` | +| `event:sandbox/mode.ignorable` | `optional-property-added` | `review-required` | +| `event:schedule/change` | `root-added` | `not-required` | +| `event:session/end-seed.ignorable` | `optional-property-added` | `review-required` | +| `event:session/title.ignorable` | `optional-property-added` | `review-required` | +| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `review-required` | +| `event:session/title-llm-request.ignorable` | `optional-property-added` | `review-required` | +| `event:step/end.ignorable` | `optional-property-added` | `review-required` | +| `event:step/start.ignorable` | `optional-property-added` | `review-required` | +| `event:subagent/descriptor.ignorable` | `optional-property-added` | `review-required` | +| `event:todo/write.ignorable` | `optional-property-added` | `review-required` | +| `event:tool-workflow/agent-end` | `root-added` | `not-required` | +| `event:tool-workflow/agent-start` | `root-added` | `not-required` | +| `event:tool-workflow/run-end` | `root-added` | `not-required` | +| `event:tool-workflow/run-start` | `root-added` | `not-required` | +| `event:tool/call.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/code-dispatch.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/code-dispatch-start.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/result.ignorable` | `optional-property-added` | `review-required` | +| `event:turn/end.ignorable` | `optional-property-added` | `review-required` | +| `event:turn/start.ignorable` | `optional-property-added` | `review-required` | +| `event:user/message.data.source` | `union-variants-changed` | `review-required` | +| `event:user/message.ignorable` | `optional-property-added` | `review-required` | +| `event:web/deepseek-search-llm-request.ignorable` | `optional-property-added` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.0.1-rc.2.zh.md b/docs/persistence-changes/releases/dsh-v0.0.1-rc.2.zh.md index 32962d394e..b0e2b58248 100644 --- a/docs/persistence-changes/releases/dsh-v0.0.1-rc.2.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.0.1-rc.2.zh.md @@ -191,58 +191,58 @@ changes: -检测到 45 个根类型变化、48 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 45 个根类型变化、48 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `SessionEventEnvelope` | `union-variants-changed` | `version-bump` | -| `event:agent-preset/selected.ignorable` | `optional-property-added` | `version-bump` | -| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `version-bump` | -| `event:agent/inbox/spliced.ignorable` | `optional-property-added` | `version-bump` | -| `event:approval/asked.ignorable` | `optional-property-added` | `version-bump` | -| `event:approval/decided.ignorable` | `optional-property-added` | `version-bump` | -| `event:approval/policy.ignorable` | `optional-property-added` | `version-bump` | -| `event:assistant/chunk.ignorable` | `optional-property-added` | `version-bump` | -| `event:assistant/message.ignorable` | `optional-property-added` | `version-bump` | -| `event:command/done.ignorable` | `optional-property-added` | `version-bump` | -| `event:command/run.ignorable` | `optional-property-added` | `version-bump` | -| `event:compact/end.ignorable` | `optional-property-added` | `version-bump` | -| `event:compact/prune.ignorable` | `optional-property-added` | `version-bump` | -| `event:compact/start.ignorable` | `optional-property-added` | `version-bump` | -| `event:compact/summary.ignorable` | `optional-property-added` | `version-bump` | -| `event:feedback/record.ignorable` | `optional-property-added` | `version-bump` | -| `event:goal/change.ignorable` | `optional-property-added` | `version-bump` | -| `event:hook/invoked.ignorable` | `optional-property-added` | `version-bump` | -| `event:hook/result.ignorable` | `optional-property-added` | `version-bump` | -| `event:llm/retry.ignorable` | `optional-property-added` | `version-bump` | -| `event:llm/retry-started.ignorable` | `optional-property-added` | `version-bump` | -| `event:permission/preset.ignorable` | `optional-property-added` | `version-bump` | -| `event:plan/mode.ignorable` | `optional-property-added` | `version-bump` | -| `event:request/context.ignorable` | `optional-property-added` | `version-bump` | -| `event:request/header.ignorable` | `optional-property-added` | `version-bump` | -| `event:sandbox/mode.ignorable` | `optional-property-added` | `version-bump` | -| `event:schedule/change` | `root-added` | `same-version` | -| `event:session/end-seed.ignorable` | `optional-property-added` | `version-bump` | -| `event:session/title.ignorable` | `optional-property-added` | `version-bump` | -| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `version-bump` | -| `event:session/title-llm-request.ignorable` | `optional-property-added` | `version-bump` | -| `event:step/end.ignorable` | `optional-property-added` | `version-bump` | -| `event:step/start.ignorable` | `optional-property-added` | `version-bump` | -| `event:subagent/descriptor.ignorable` | `optional-property-added` | `version-bump` | -| `event:todo/write.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool-workflow/agent-end` | `root-added` | `same-version` | -| `event:tool-workflow/agent-start` | `root-added` | `same-version` | -| `event:tool-workflow/run-end` | `root-added` | `same-version` | -| `event:tool-workflow/run-start` | `root-added` | `same-version` | -| `event:tool/call.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/code-dispatch.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/code-dispatch-start.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/result.ignorable` | `optional-property-added` | `version-bump` | -| `event:turn/end.ignorable` | `optional-property-added` | `version-bump` | -| `event:turn/start.ignorable` | `optional-property-added` | `version-bump` | -| `event:user/message.data.source` | `union-variants-changed` | `version-bump` | -| `event:user/message.ignorable` | `optional-property-added` | `version-bump` | -| `event:web/deepseek-search-llm-request.ignorable` | `optional-property-added` | `version-bump` | +| `SessionEventEnvelope` | `union-variants-changed` | `review-required` | +| `event:agent-preset/selected.ignorable` | `optional-property-added` | `review-required` | +| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `review-required` | +| `event:agent/inbox/spliced.ignorable` | `optional-property-added` | `review-required` | +| `event:approval/asked.ignorable` | `optional-property-added` | `review-required` | +| `event:approval/decided.ignorable` | `optional-property-added` | `review-required` | +| `event:approval/policy.ignorable` | `optional-property-added` | `review-required` | +| `event:assistant/chunk.ignorable` | `optional-property-added` | `review-required` | +| `event:assistant/message.ignorable` | `optional-property-added` | `review-required` | +| `event:command/done.ignorable` | `optional-property-added` | `review-required` | +| `event:command/run.ignorable` | `optional-property-added` | `review-required` | +| `event:compact/end.ignorable` | `optional-property-added` | `review-required` | +| `event:compact/prune.ignorable` | `optional-property-added` | `review-required` | +| `event:compact/start.ignorable` | `optional-property-added` | `review-required` | +| `event:compact/summary.ignorable` | `optional-property-added` | `review-required` | +| `event:feedback/record.ignorable` | `optional-property-added` | `review-required` | +| `event:goal/change.ignorable` | `optional-property-added` | `review-required` | +| `event:hook/invoked.ignorable` | `optional-property-added` | `review-required` | +| `event:hook/result.ignorable` | `optional-property-added` | `review-required` | +| `event:llm/retry.ignorable` | `optional-property-added` | `review-required` | +| `event:llm/retry-started.ignorable` | `optional-property-added` | `review-required` | +| `event:permission/preset.ignorable` | `optional-property-added` | `review-required` | +| `event:plan/mode.ignorable` | `optional-property-added` | `review-required` | +| `event:request/context.ignorable` | `optional-property-added` | `review-required` | +| `event:request/header.ignorable` | `optional-property-added` | `review-required` | +| `event:sandbox/mode.ignorable` | `optional-property-added` | `review-required` | +| `event:schedule/change` | `root-added` | `not-required` | +| `event:session/end-seed.ignorable` | `optional-property-added` | `review-required` | +| `event:session/title.ignorable` | `optional-property-added` | `review-required` | +| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `review-required` | +| `event:session/title-llm-request.ignorable` | `optional-property-added` | `review-required` | +| `event:step/end.ignorable` | `optional-property-added` | `review-required` | +| `event:step/start.ignorable` | `optional-property-added` | `review-required` | +| `event:subagent/descriptor.ignorable` | `optional-property-added` | `review-required` | +| `event:todo/write.ignorable` | `optional-property-added` | `review-required` | +| `event:tool-workflow/agent-end` | `root-added` | `not-required` | +| `event:tool-workflow/agent-start` | `root-added` | `not-required` | +| `event:tool-workflow/run-end` | `root-added` | `not-required` | +| `event:tool-workflow/run-start` | `root-added` | `not-required` | +| `event:tool/call.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/code-dispatch.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/code-dispatch-start.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/result.ignorable` | `optional-property-added` | `review-required` | +| `event:turn/end.ignorable` | `optional-property-added` | `review-required` | +| `event:turn/start.ignorable` | `optional-property-added` | `review-required` | +| `event:user/message.data.source` | `union-variants-changed` | `review-required` | +| `event:user/message.ignorable` | `optional-property-added` | `review-required` | +| `event:web/deepseek-search-llm-request.ignorable` | `optional-property-added` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.0.1-rc.3.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.0.1-rc.3.i18n.yaml index 9a336ac41d..6e491600da 100644 --- a/docs/persistence-changes/releases/dsh-v0.0.1-rc.3.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.0.1-rc.3.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-0-1-rc-3/structural-changes: - en: b4ded7b41999584d - zh: 49c3f355a5559cbd + en: 0fd2841ea23b8cd6 + zh: 1138a25ac478eaa8 /persistence-release-dsh-v0-0-1-rc-3/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.0.1-rc.3.md b/docs/persistence-changes/releases/dsh-v0.0.1-rc.3.md index 7201966f5e..fcede4e7bd 100644 --- a/docs/persistence-changes/releases/dsh-v0.0.1-rc.3.md +++ b/docs/persistence-changes/releases/dsh-v0.0.1-rc.3.md @@ -92,22 +92,22 @@ changes: -Detected 12 changed roots and 12 structural differences. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 12 changed roots and 12 structural differences. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `event:agent/inbox/spliced.data.inserted[].source.kind` | `type-changed` | `version-bump` | -| `event:compact/end` | `root-removed` | `version-bump` | -| `event:compact/prune` | `root-removed` | `version-bump` | -| `event:compact/start` | `root-removed` | `version-bump` | -| `event:compact/summary` | `root-removed` | `version-bump` | -| `event:compaction/end` | `root-added` | `same-version` | -| `event:compaction/prune` | `root-added` | `same-version` | -| `event:compaction/start` | `root-added` | `same-version` | -| `event:compaction/summary` | `root-added` | `same-version` | -| `event:hook/invoked.data.dialect` | `type-changed` | `version-bump` | -| `event:session/title-llm-request.data.messages[].source.kind` | `type-changed` | `version-bump` | -| `event:user/message.data.source.kind` | `type-changed` | `version-bump` | +| `event:agent/inbox/spliced.data.inserted[].source.kind` | `type-changed` | `review-required` | +| `event:compact/end` | `root-removed` | `review-required` | +| `event:compact/prune` | `root-removed` | `review-required` | +| `event:compact/start` | `root-removed` | `review-required` | +| `event:compact/summary` | `root-removed` | `review-required` | +| `event:compaction/end` | `root-added` | `not-required` | +| `event:compaction/prune` | `root-added` | `not-required` | +| `event:compaction/start` | `root-added` | `not-required` | +| `event:compaction/summary` | `root-added` | `not-required` | +| `event:hook/invoked.data.dialect` | `type-changed` | `review-required` | +| `event:session/title-llm-request.data.messages[].source.kind` | `type-changed` | `review-required` | +| `event:user/message.data.source.kind` | `type-changed` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.0.1-rc.3.zh.md b/docs/persistence-changes/releases/dsh-v0.0.1-rc.3.zh.md index a59d39a86f..3ece24837e 100644 --- a/docs/persistence-changes/releases/dsh-v0.0.1-rc.3.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.0.1-rc.3.zh.md @@ -92,22 +92,22 @@ changes: -检测到 12 个根类型变化、12 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 12 个根类型变化、12 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `event:agent/inbox/spliced.data.inserted[].source.kind` | `type-changed` | `version-bump` | -| `event:compact/end` | `root-removed` | `version-bump` | -| `event:compact/prune` | `root-removed` | `version-bump` | -| `event:compact/start` | `root-removed` | `version-bump` | -| `event:compact/summary` | `root-removed` | `version-bump` | -| `event:compaction/end` | `root-added` | `same-version` | -| `event:compaction/prune` | `root-added` | `same-version` | -| `event:compaction/start` | `root-added` | `same-version` | -| `event:compaction/summary` | `root-added` | `same-version` | -| `event:hook/invoked.data.dialect` | `type-changed` | `version-bump` | -| `event:session/title-llm-request.data.messages[].source.kind` | `type-changed` | `version-bump` | -| `event:user/message.data.source.kind` | `type-changed` | `version-bump` | +| `event:agent/inbox/spliced.data.inserted[].source.kind` | `type-changed` | `review-required` | +| `event:compact/end` | `root-removed` | `review-required` | +| `event:compact/prune` | `root-removed` | `review-required` | +| `event:compact/start` | `root-removed` | `review-required` | +| `event:compact/summary` | `root-removed` | `review-required` | +| `event:compaction/end` | `root-added` | `not-required` | +| `event:compaction/prune` | `root-added` | `not-required` | +| `event:compaction/start` | `root-added` | `not-required` | +| `event:compaction/summary` | `root-added` | `not-required` | +| `event:hook/invoked.data.dialect` | `type-changed` | `review-required` | +| `event:session/title-llm-request.data.messages[].source.kind` | `type-changed` | `review-required` | +| `event:user/message.data.source.kind` | `type-changed` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.0-rc.7.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.1.0-rc.7.i18n.yaml index 0efe3d557b..ca3647aa67 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.0-rc.7.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.1.0-rc.7.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-1-0-rc-7/structural-changes: - en: 5178d26722926711 - zh: bfe39111dd34ff48 + en: 1a08248deb5e841c + zh: b5dd3c2ac161a100 /persistence-release-dsh-v0-1-0-rc-7/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.1.0-rc.7.md b/docs/persistence-changes/releases/dsh-v0.1.0-rc.7.md index 6427da5c46..4c30b5408f 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.0-rc.7.md +++ b/docs/persistence-changes/releases/dsh-v0.1.0-rc.7.md @@ -59,11 +59,11 @@ changes: -Detected 1 changed root and 1 structural difference. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 1 changed root and 1 structural difference. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `event:assistant/chunk.data.chunk.replayState` | `type-changed` | `version-bump` | +| `event:assistant/chunk.data.chunk.replayState` | `type-changed` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.0-rc.7.zh.md b/docs/persistence-changes/releases/dsh-v0.1.0-rc.7.zh.md index 91ae3f1061..379e11e6ff 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.0-rc.7.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.1.0-rc.7.zh.md @@ -59,11 +59,11 @@ changes: -检测到 1 个根类型变化、1 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 1 个根类型变化、1 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `event:assistant/chunk.data.chunk.replayState` | `type-changed` | `version-bump` | +| `event:assistant/chunk.data.chunk.replayState` | `type-changed` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.0-rc.8.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.1.0-rc.8.i18n.yaml index d2012c1958..f55fe23514 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.0-rc.8.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.1.0-rc.8.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-1-0-rc-8/structural-changes: - en: 6c7808df4fdcbf70 - zh: 8b6d83a8adec7f51 + en: 1909dc1b62eef347 + zh: 010e53d396fc675c /persistence-release-dsh-v0-1-0-rc-8/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.1.0-rc.8.md b/docs/persistence-changes/releases/dsh-v0.1.0-rc.8.md index c52f050b82..83170d8295 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.0-rc.8.md +++ b/docs/persistence-changes/releases/dsh-v0.1.0-rc.8.md @@ -80,18 +80,18 @@ changes: -Detected 8 changed roots and 8 structural differences. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 8 changed roots and 8 structural differences. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `version-bump` | -| `event:assistant/message.data.interrupted` | `optional-property-added` | `same-version` | -| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `version-bump` | -| `event:team/member` | `root-added` | `same-version` | -| `event:team/message/delivered` | `root-added` | `same-version` | -| `event:team/message/queued` | `root-added` | `same-version` | -| `event:team/task` | `root-added` | `same-version` | -| `event:user/message.data.source` | `union-variants-changed` | `version-bump` | +| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `review-required` | +| `event:assistant/message.data.interrupted` | `optional-property-added` | `not-required` | +| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `review-required` | +| `event:team/member` | `root-added` | `not-required` | +| `event:team/message/delivered` | `root-added` | `not-required` | +| `event:team/message/queued` | `root-added` | `not-required` | +| `event:team/task` | `root-added` | `not-required` | +| `event:user/message.data.source` | `union-variants-changed` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.0-rc.8.zh.md b/docs/persistence-changes/releases/dsh-v0.1.0-rc.8.zh.md index b4fd283ede..a18e26f5fd 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.0-rc.8.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.1.0-rc.8.zh.md @@ -80,18 +80,18 @@ changes: -检测到 8 个根类型变化、8 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 8 个根类型变化、8 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `version-bump` | -| `event:assistant/message.data.interrupted` | `optional-property-added` | `same-version` | -| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `version-bump` | -| `event:team/member` | `root-added` | `same-version` | -| `event:team/message/delivered` | `root-added` | `same-version` | -| `event:team/message/queued` | `root-added` | `same-version` | -| `event:team/task` | `root-added` | `same-version` | -| `event:user/message.data.source` | `union-variants-changed` | `version-bump` | +| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `review-required` | +| `event:assistant/message.data.interrupted` | `optional-property-added` | `not-required` | +| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `review-required` | +| `event:team/member` | `root-added` | `not-required` | +| `event:team/message/delivered` | `root-added` | `not-required` | +| `event:team/message/queued` | `root-added` | `not-required` | +| `event:team/task` | `root-added` | `not-required` | +| `event:user/message.data.source` | `union-variants-changed` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.1-rc.1.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.1.1-rc.1.i18n.yaml index c5721338e9..0a07a76011 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.1-rc.1.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.1.1-rc.1.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-1-1-rc-1/structural-changes: - en: 0be3fa84192c242d - zh: 59dc45dd8e7f7594 + en: 69516d329a54a014 + zh: 16a3c770a9ba3217 /persistence-release-dsh-v0-1-1-rc-1/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.1.1-rc.1.md b/docs/persistence-changes/releases/dsh-v0.1.1-rc.1.md index 6b598f1c61..23febf967f 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.1-rc.1.md +++ b/docs/persistence-changes/releases/dsh-v0.1.1-rc.1.md @@ -59,11 +59,11 @@ changes: -Detected 1 changed root and 1 structural difference. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 1 changed root and 1 structural difference. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `event:permission/preset.data.origin` | `optional-property-added` | `same-version` | +| `event:permission/preset.data.origin` | `optional-property-added` | `not-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.1-rc.1.zh.md b/docs/persistence-changes/releases/dsh-v0.1.1-rc.1.zh.md index eca10c509e..2220cf203a 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.1-rc.1.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.1.1-rc.1.zh.md @@ -59,11 +59,11 @@ changes: -检测到 1 个根类型变化、1 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 1 个根类型变化、1 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `event:permission/preset.data.origin` | `optional-property-added` | `same-version` | +| `event:permission/preset.data.origin` | `optional-property-added` | `not-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.1-rc.2.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.1.1-rc.2.i18n.yaml index f0259c93e1..54355badb7 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.1-rc.2.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.1.1-rc.2.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-1-1-rc-2/structural-changes: - en: c03cbb0f4bfb5d83 - zh: c23900507d4111aa + en: fedf3524c654f8b3 + zh: 4df22b00a3981e60 /persistence-release-dsh-v0-1-1-rc-2/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.1.1-rc.2.md b/docs/persistence-changes/releases/dsh-v0.1.1-rc.2.md index 41cc4f0a39..694393a876 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.1-rc.2.md +++ b/docs/persistence-changes/releases/dsh-v0.1.1-rc.2.md @@ -86,21 +86,21 @@ changes: -Detected 10 changed roots and 11 structural differences. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 10 changed roots and 11 structural differences. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `event:agent/inbox/spliced.data.inserted[].content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:assistant/chunk.data.chunk.block.attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:assistant/message.data.message.content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:compaction/summary.data.rawOutput[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:compaction/summary.data.summary[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:permission/preset.data.origin` | `property-removed` | `version-bump` | -| `event:session/title-llm-request.data.messages[].content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:team/message/queued.data.message.content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:tool/code-dispatch.data.content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:tool/result.data.message.content[0].content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:user/message.data.content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | +| `event:agent/inbox/spliced.data.inserted[].content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:assistant/chunk.data.chunk.block.attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:assistant/message.data.message.content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:compaction/summary.data.rawOutput[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:compaction/summary.data.summary[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:permission/preset.data.origin` | `property-removed` | `review-required` | +| `event:session/title-llm-request.data.messages[].content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:team/message/queued.data.message.content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:tool/code-dispatch.data.content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:tool/result.data.message.content[0].content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:user/message.data.content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.1-rc.2.zh.md b/docs/persistence-changes/releases/dsh-v0.1.1-rc.2.zh.md index 5ab22efd5d..7fa7ba008f 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.1-rc.2.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.1.1-rc.2.zh.md @@ -86,21 +86,21 @@ changes: -检测到 10 个根类型变化、11 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 10 个根类型变化、11 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `event:agent/inbox/spliced.data.inserted[].content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:assistant/chunk.data.chunk.block.attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:assistant/message.data.message.content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:compaction/summary.data.rawOutput[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:compaction/summary.data.summary[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:permission/preset.data.origin` | `property-removed` | `version-bump` | -| `event:session/title-llm-request.data.messages[].content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:team/message/queued.data.message.content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:tool/code-dispatch.data.content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:tool/result.data.message.content[0].content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | -| `event:user/message.data.content[].attachment.originalDimensions` | `optional-property-added` | `same-version` | +| `event:agent/inbox/spliced.data.inserted[].content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:assistant/chunk.data.chunk.block.attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:assistant/message.data.message.content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:compaction/summary.data.rawOutput[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:compaction/summary.data.summary[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:permission/preset.data.origin` | `property-removed` | `review-required` | +| `event:session/title-llm-request.data.messages[].content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:team/message/queued.data.message.content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:tool/code-dispatch.data.content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:tool/result.data.message.content[0].content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | +| `event:user/message.data.content[].attachment.originalDimensions` | `optional-property-added` | `not-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.1.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.1.i18n.yaml index 8d25d441e9..b5891761cd 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.1.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.1.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-1-2-alpha-1/structural-changes: - en: f8e5907da99d32b9 - zh: dcd8dbc9660a20b6 + en: ebe16d1afafb4cbc + zh: d80430fa60b01c29 /persistence-release-dsh-v0-1-2-alpha-1/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.1.md b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.1.md index 3ed00447e4..5dfbc59f5f 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.1.md +++ b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.1.md @@ -212,71 +212,71 @@ changes: -Detected 52 changed roots and 61 structural differences. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 52 changed roots and 61 structural differences. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `SessionEventEnvelope` | `union-variants-changed` | `version-bump` | -| `event:agent-preset/selected.ignorable` | `property-removed` | `version-bump` | -| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `version-bump` | -| `event:agent/inbox/spliced.ignorable` | `property-removed` | `version-bump` | -| `event:approval/asked.ignorable` | `property-removed` | `version-bump` | -| `event:approval/decided.ignorable` | `property-removed` | `version-bump` | -| `event:approval/policy.ignorable` | `property-removed` | `version-bump` | -| `event:assistant/chunk.data.chunk.usage.totalTokens` | `optional-property-added` | `same-version` | -| `event:assistant/chunk.ignorable` | `property-removed` | `version-bump` | -| `event:assistant/message.data.usage.totalTokens` | `optional-property-added` | `same-version` | -| `event:assistant/message.ignorable` | `property-removed` | `version-bump` | -| `event:command/done.ignorable` | `property-removed` | `version-bump` | -| `event:command/run.ignorable` | `property-removed` | `version-bump` | -| `event:compaction/end.ignorable` | `property-removed` | `version-bump` | -| `event:compaction/prune.ignorable` | `property-removed` | `version-bump` | -| `event:compaction/start.ignorable` | `property-removed` | `version-bump` | -| `event:compaction/summary.data.usage.totalTokens` | `optional-property-added` | `same-version` | -| `event:compaction/summary.ignorable` | `property-removed` | `version-bump` | -| `event:feedback/record.ignorable` | `property-removed` | `version-bump` | -| `event:goal/change.ignorable` | `property-removed` | `version-bump` | -| `event:hook/invoked.ignorable` | `property-removed` | `version-bump` | -| `event:hook/result.ignorable` | `property-removed` | `version-bump` | -| `event:llm/retry.ignorable` | `property-removed` | `version-bump` | -| `event:llm/retry-started.ignorable` | `property-removed` | `version-bump` | -| `event:model/selection` | `root-added` | `same-version` | -| `event:permission/preset.ignorable` | `property-removed` | `version-bump` | -| `event:plan/mode.ignorable` | `property-removed` | `version-bump` | -| `event:request/context.ignorable` | `property-removed` | `version-bump` | -| `event:request/header.data.reason` | `union-variants-changed` | `version-bump` | -| `event:request/header.data.startsSeries` | `optional-property-added` | `same-version` | -| `event:request/header.ignorable` | `property-removed` | `version-bump` | -| `event:sandbox/mode.ignorable` | `property-removed` | `version-bump` | -| `event:schedule/change.ignorable` | `property-removed` | `version-bump` | -| `event:session-log-deepseek/delivery-accepted` | `root-added` | `same-version` | -| `event:session/end-seed.ignorable` | `property-removed` | `version-bump` | -| `event:session/title.ignorable` | `property-removed` | `version-bump` | -| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `version-bump` | -| `event:session/title-llm-request.ignorable` | `property-removed` | `version-bump` | -| `event:step/end.ignorable` | `property-removed` | `version-bump` | -| `event:step/start.ignorable` | `property-removed` | `version-bump` | -| `event:subagent/descriptor.data.agentReasoningEffort` | `optional-property-added` | `same-version` | -| `event:subagent/descriptor.ignorable` | `property-removed` | `version-bump` | -| `event:subagent/model-selection-policy` | `root-added` | `same-version` | -| `event:team/member.ignorable` | `property-removed` | `version-bump` | -| `event:team/message/delivered.ignorable` | `property-removed` | `version-bump` | -| `event:team/message/queued.ignorable` | `property-removed` | `version-bump` | -| `event:team/task.ignorable` | `property-removed` | `version-bump` | -| `event:todo/write.ignorable` | `property-removed` | `version-bump` | -| `event:tool-workflow/agent-end.ignorable` | `property-removed` | `version-bump` | -| `event:tool-workflow/agent-start.ignorable` | `property-removed` | `version-bump` | -| `event:tool-workflow/run-end.ignorable` | `property-removed` | `version-bump` | -| `event:tool-workflow/run-start.ignorable` | `property-removed` | `version-bump` | -| `event:tool/call.ignorable` | `property-removed` | `version-bump` | -| `event:tool/code-dispatch.ignorable` | `property-removed` | `version-bump` | -| `event:tool/code-dispatch-start.ignorable` | `property-removed` | `version-bump` | -| `event:tool/result.ignorable` | `property-removed` | `version-bump` | -| `event:turn/end.ignorable` | `property-removed` | `version-bump` | -| `event:turn/start.ignorable` | `property-removed` | `version-bump` | -| `event:user/message.data.source` | `union-variants-changed` | `version-bump` | -| `event:user/message.ignorable` | `property-removed` | `version-bump` | -| `event:web/deepseek-search-llm-request.ignorable` | `property-removed` | `version-bump` | +| `SessionEventEnvelope` | `union-variants-changed` | `review-required` | +| `event:agent-preset/selected.ignorable` | `property-removed` | `review-required` | +| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `review-required` | +| `event:agent/inbox/spliced.ignorable` | `property-removed` | `review-required` | +| `event:approval/asked.ignorable` | `property-removed` | `review-required` | +| `event:approval/decided.ignorable` | `property-removed` | `review-required` | +| `event:approval/policy.ignorable` | `property-removed` | `review-required` | +| `event:assistant/chunk.data.chunk.usage.totalTokens` | `optional-property-added` | `not-required` | +| `event:assistant/chunk.ignorable` | `property-removed` | `review-required` | +| `event:assistant/message.data.usage.totalTokens` | `optional-property-added` | `not-required` | +| `event:assistant/message.ignorable` | `property-removed` | `review-required` | +| `event:command/done.ignorable` | `property-removed` | `review-required` | +| `event:command/run.ignorable` | `property-removed` | `review-required` | +| `event:compaction/end.ignorable` | `property-removed` | `review-required` | +| `event:compaction/prune.ignorable` | `property-removed` | `review-required` | +| `event:compaction/start.ignorable` | `property-removed` | `review-required` | +| `event:compaction/summary.data.usage.totalTokens` | `optional-property-added` | `not-required` | +| `event:compaction/summary.ignorable` | `property-removed` | `review-required` | +| `event:feedback/record.ignorable` | `property-removed` | `review-required` | +| `event:goal/change.ignorable` | `property-removed` | `review-required` | +| `event:hook/invoked.ignorable` | `property-removed` | `review-required` | +| `event:hook/result.ignorable` | `property-removed` | `review-required` | +| `event:llm/retry.ignorable` | `property-removed` | `review-required` | +| `event:llm/retry-started.ignorable` | `property-removed` | `review-required` | +| `event:model/selection` | `root-added` | `not-required` | +| `event:permission/preset.ignorable` | `property-removed` | `review-required` | +| `event:plan/mode.ignorable` | `property-removed` | `review-required` | +| `event:request/context.ignorable` | `property-removed` | `review-required` | +| `event:request/header.data.reason` | `union-variants-changed` | `review-required` | +| `event:request/header.data.startsSeries` | `optional-property-added` | `not-required` | +| `event:request/header.ignorable` | `property-removed` | `review-required` | +| `event:sandbox/mode.ignorable` | `property-removed` | `review-required` | +| `event:schedule/change.ignorable` | `property-removed` | `review-required` | +| `event:session-log-deepseek/delivery-accepted` | `root-added` | `not-required` | +| `event:session/end-seed.ignorable` | `property-removed` | `review-required` | +| `event:session/title.ignorable` | `property-removed` | `review-required` | +| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `review-required` | +| `event:session/title-llm-request.ignorable` | `property-removed` | `review-required` | +| `event:step/end.ignorable` | `property-removed` | `review-required` | +| `event:step/start.ignorable` | `property-removed` | `review-required` | +| `event:subagent/descriptor.data.agentReasoningEffort` | `optional-property-added` | `not-required` | +| `event:subagent/descriptor.ignorable` | `property-removed` | `review-required` | +| `event:subagent/model-selection-policy` | `root-added` | `not-required` | +| `event:team/member.ignorable` | `property-removed` | `review-required` | +| `event:team/message/delivered.ignorable` | `property-removed` | `review-required` | +| `event:team/message/queued.ignorable` | `property-removed` | `review-required` | +| `event:team/task.ignorable` | `property-removed` | `review-required` | +| `event:todo/write.ignorable` | `property-removed` | `review-required` | +| `event:tool-workflow/agent-end.ignorable` | `property-removed` | `review-required` | +| `event:tool-workflow/agent-start.ignorable` | `property-removed` | `review-required` | +| `event:tool-workflow/run-end.ignorable` | `property-removed` | `review-required` | +| `event:tool-workflow/run-start.ignorable` | `property-removed` | `review-required` | +| `event:tool/call.ignorable` | `property-removed` | `review-required` | +| `event:tool/code-dispatch.ignorable` | `property-removed` | `review-required` | +| `event:tool/code-dispatch-start.ignorable` | `property-removed` | `review-required` | +| `event:tool/result.ignorable` | `property-removed` | `review-required` | +| `event:turn/end.ignorable` | `property-removed` | `review-required` | +| `event:turn/start.ignorable` | `property-removed` | `review-required` | +| `event:user/message.data.source` | `union-variants-changed` | `review-required` | +| `event:user/message.ignorable` | `property-removed` | `review-required` | +| `event:web/deepseek-search-llm-request.ignorable` | `property-removed` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.1.zh.md b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.1.zh.md index 09a6bf3df1..1c5abc026b 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.1.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.1.zh.md @@ -212,71 +212,71 @@ changes: -检测到 52 个根类型变化、61 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 52 个根类型变化、61 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `SessionEventEnvelope` | `union-variants-changed` | `version-bump` | -| `event:agent-preset/selected.ignorable` | `property-removed` | `version-bump` | -| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `version-bump` | -| `event:agent/inbox/spliced.ignorable` | `property-removed` | `version-bump` | -| `event:approval/asked.ignorable` | `property-removed` | `version-bump` | -| `event:approval/decided.ignorable` | `property-removed` | `version-bump` | -| `event:approval/policy.ignorable` | `property-removed` | `version-bump` | -| `event:assistant/chunk.data.chunk.usage.totalTokens` | `optional-property-added` | `same-version` | -| `event:assistant/chunk.ignorable` | `property-removed` | `version-bump` | -| `event:assistant/message.data.usage.totalTokens` | `optional-property-added` | `same-version` | -| `event:assistant/message.ignorable` | `property-removed` | `version-bump` | -| `event:command/done.ignorable` | `property-removed` | `version-bump` | -| `event:command/run.ignorable` | `property-removed` | `version-bump` | -| `event:compaction/end.ignorable` | `property-removed` | `version-bump` | -| `event:compaction/prune.ignorable` | `property-removed` | `version-bump` | -| `event:compaction/start.ignorable` | `property-removed` | `version-bump` | -| `event:compaction/summary.data.usage.totalTokens` | `optional-property-added` | `same-version` | -| `event:compaction/summary.ignorable` | `property-removed` | `version-bump` | -| `event:feedback/record.ignorable` | `property-removed` | `version-bump` | -| `event:goal/change.ignorable` | `property-removed` | `version-bump` | -| `event:hook/invoked.ignorable` | `property-removed` | `version-bump` | -| `event:hook/result.ignorable` | `property-removed` | `version-bump` | -| `event:llm/retry.ignorable` | `property-removed` | `version-bump` | -| `event:llm/retry-started.ignorable` | `property-removed` | `version-bump` | -| `event:model/selection` | `root-added` | `same-version` | -| `event:permission/preset.ignorable` | `property-removed` | `version-bump` | -| `event:plan/mode.ignorable` | `property-removed` | `version-bump` | -| `event:request/context.ignorable` | `property-removed` | `version-bump` | -| `event:request/header.data.reason` | `union-variants-changed` | `version-bump` | -| `event:request/header.data.startsSeries` | `optional-property-added` | `same-version` | -| `event:request/header.ignorable` | `property-removed` | `version-bump` | -| `event:sandbox/mode.ignorable` | `property-removed` | `version-bump` | -| `event:schedule/change.ignorable` | `property-removed` | `version-bump` | -| `event:session-log-deepseek/delivery-accepted` | `root-added` | `same-version` | -| `event:session/end-seed.ignorable` | `property-removed` | `version-bump` | -| `event:session/title.ignorable` | `property-removed` | `version-bump` | -| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `version-bump` | -| `event:session/title-llm-request.ignorable` | `property-removed` | `version-bump` | -| `event:step/end.ignorable` | `property-removed` | `version-bump` | -| `event:step/start.ignorable` | `property-removed` | `version-bump` | -| `event:subagent/descriptor.data.agentReasoningEffort` | `optional-property-added` | `same-version` | -| `event:subagent/descriptor.ignorable` | `property-removed` | `version-bump` | -| `event:subagent/model-selection-policy` | `root-added` | `same-version` | -| `event:team/member.ignorable` | `property-removed` | `version-bump` | -| `event:team/message/delivered.ignorable` | `property-removed` | `version-bump` | -| `event:team/message/queued.ignorable` | `property-removed` | `version-bump` | -| `event:team/task.ignorable` | `property-removed` | `version-bump` | -| `event:todo/write.ignorable` | `property-removed` | `version-bump` | -| `event:tool-workflow/agent-end.ignorable` | `property-removed` | `version-bump` | -| `event:tool-workflow/agent-start.ignorable` | `property-removed` | `version-bump` | -| `event:tool-workflow/run-end.ignorable` | `property-removed` | `version-bump` | -| `event:tool-workflow/run-start.ignorable` | `property-removed` | `version-bump` | -| `event:tool/call.ignorable` | `property-removed` | `version-bump` | -| `event:tool/code-dispatch.ignorable` | `property-removed` | `version-bump` | -| `event:tool/code-dispatch-start.ignorable` | `property-removed` | `version-bump` | -| `event:tool/result.ignorable` | `property-removed` | `version-bump` | -| `event:turn/end.ignorable` | `property-removed` | `version-bump` | -| `event:turn/start.ignorable` | `property-removed` | `version-bump` | -| `event:user/message.data.source` | `union-variants-changed` | `version-bump` | -| `event:user/message.ignorable` | `property-removed` | `version-bump` | -| `event:web/deepseek-search-llm-request.ignorable` | `property-removed` | `version-bump` | +| `SessionEventEnvelope` | `union-variants-changed` | `review-required` | +| `event:agent-preset/selected.ignorable` | `property-removed` | `review-required` | +| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `review-required` | +| `event:agent/inbox/spliced.ignorable` | `property-removed` | `review-required` | +| `event:approval/asked.ignorable` | `property-removed` | `review-required` | +| `event:approval/decided.ignorable` | `property-removed` | `review-required` | +| `event:approval/policy.ignorable` | `property-removed` | `review-required` | +| `event:assistant/chunk.data.chunk.usage.totalTokens` | `optional-property-added` | `not-required` | +| `event:assistant/chunk.ignorable` | `property-removed` | `review-required` | +| `event:assistant/message.data.usage.totalTokens` | `optional-property-added` | `not-required` | +| `event:assistant/message.ignorable` | `property-removed` | `review-required` | +| `event:command/done.ignorable` | `property-removed` | `review-required` | +| `event:command/run.ignorable` | `property-removed` | `review-required` | +| `event:compaction/end.ignorable` | `property-removed` | `review-required` | +| `event:compaction/prune.ignorable` | `property-removed` | `review-required` | +| `event:compaction/start.ignorable` | `property-removed` | `review-required` | +| `event:compaction/summary.data.usage.totalTokens` | `optional-property-added` | `not-required` | +| `event:compaction/summary.ignorable` | `property-removed` | `review-required` | +| `event:feedback/record.ignorable` | `property-removed` | `review-required` | +| `event:goal/change.ignorable` | `property-removed` | `review-required` | +| `event:hook/invoked.ignorable` | `property-removed` | `review-required` | +| `event:hook/result.ignorable` | `property-removed` | `review-required` | +| `event:llm/retry.ignorable` | `property-removed` | `review-required` | +| `event:llm/retry-started.ignorable` | `property-removed` | `review-required` | +| `event:model/selection` | `root-added` | `not-required` | +| `event:permission/preset.ignorable` | `property-removed` | `review-required` | +| `event:plan/mode.ignorable` | `property-removed` | `review-required` | +| `event:request/context.ignorable` | `property-removed` | `review-required` | +| `event:request/header.data.reason` | `union-variants-changed` | `review-required` | +| `event:request/header.data.startsSeries` | `optional-property-added` | `not-required` | +| `event:request/header.ignorable` | `property-removed` | `review-required` | +| `event:sandbox/mode.ignorable` | `property-removed` | `review-required` | +| `event:schedule/change.ignorable` | `property-removed` | `review-required` | +| `event:session-log-deepseek/delivery-accepted` | `root-added` | `not-required` | +| `event:session/end-seed.ignorable` | `property-removed` | `review-required` | +| `event:session/title.ignorable` | `property-removed` | `review-required` | +| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `review-required` | +| `event:session/title-llm-request.ignorable` | `property-removed` | `review-required` | +| `event:step/end.ignorable` | `property-removed` | `review-required` | +| `event:step/start.ignorable` | `property-removed` | `review-required` | +| `event:subagent/descriptor.data.agentReasoningEffort` | `optional-property-added` | `not-required` | +| `event:subagent/descriptor.ignorable` | `property-removed` | `review-required` | +| `event:subagent/model-selection-policy` | `root-added` | `not-required` | +| `event:team/member.ignorable` | `property-removed` | `review-required` | +| `event:team/message/delivered.ignorable` | `property-removed` | `review-required` | +| `event:team/message/queued.ignorable` | `property-removed` | `review-required` | +| `event:team/task.ignorable` | `property-removed` | `review-required` | +| `event:todo/write.ignorable` | `property-removed` | `review-required` | +| `event:tool-workflow/agent-end.ignorable` | `property-removed` | `review-required` | +| `event:tool-workflow/agent-start.ignorable` | `property-removed` | `review-required` | +| `event:tool-workflow/run-end.ignorable` | `property-removed` | `review-required` | +| `event:tool-workflow/run-start.ignorable` | `property-removed` | `review-required` | +| `event:tool/call.ignorable` | `property-removed` | `review-required` | +| `event:tool/code-dispatch.ignorable` | `property-removed` | `review-required` | +| `event:tool/code-dispatch-start.ignorable` | `property-removed` | `review-required` | +| `event:tool/result.ignorable` | `property-removed` | `review-required` | +| `event:turn/end.ignorable` | `property-removed` | `review-required` | +| `event:turn/start.ignorable` | `property-removed` | `review-required` | +| `event:user/message.data.source` | `union-variants-changed` | `review-required` | +| `event:user/message.ignorable` | `property-removed` | `review-required` | +| `event:web/deepseek-search-llm-request.ignorable` | `property-removed` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.2.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.2.i18n.yaml index 7bc9636a7a..da6fdae068 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.2.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.2.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-1-2-alpha-2/structural-changes: - en: 28cb9fbbfbc761af - zh: f3345b2dc10920b1 + en: aeca9db54d4a5ea4 + zh: fa2e354c039b8381 /persistence-release-dsh-v0-1-2-alpha-2/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.2.md b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.2.md index 8d4830f4b4..cfd6eb4225 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.2.md +++ b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.2.md @@ -212,62 +212,62 @@ changes: -Detected 52 changed roots and 52 structural differences. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 52 changed roots and 52 structural differences. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `SessionEventEnvelope` | `union-variants-changed` | `version-bump` | -| `event:agent-preset/selected.ignorable` | `optional-property-added` | `version-bump` | -| `event:agent/inbox/spliced.ignorable` | `optional-property-added` | `version-bump` | -| `event:approval/asked.ignorable` | `optional-property-added` | `version-bump` | -| `event:approval/decided.ignorable` | `optional-property-added` | `version-bump` | -| `event:approval/policy.ignorable` | `optional-property-added` | `version-bump` | -| `event:assistant/chunk.ignorable` | `optional-property-added` | `version-bump` | -| `event:assistant/message.ignorable` | `optional-property-added` | `version-bump` | -| `event:command/done.ignorable` | `optional-property-added` | `version-bump` | -| `event:command/run.ignorable` | `optional-property-added` | `version-bump` | -| `event:compaction/end.ignorable` | `optional-property-added` | `version-bump` | -| `event:compaction/prune.ignorable` | `optional-property-added` | `version-bump` | -| `event:compaction/start.ignorable` | `optional-property-added` | `version-bump` | -| `event:compaction/summary.ignorable` | `optional-property-added` | `version-bump` | -| `event:feedback/record.ignorable` | `optional-property-added` | `version-bump` | -| `event:goal/change.ignorable` | `optional-property-added` | `version-bump` | -| `event:hook/invoked.ignorable` | `optional-property-added` | `version-bump` | -| `event:hook/result.ignorable` | `optional-property-added` | `version-bump` | -| `event:llm/retry.ignorable` | `optional-property-added` | `version-bump` | -| `event:llm/retry-started.ignorable` | `optional-property-added` | `version-bump` | -| `event:model/selection.ignorable` | `optional-property-added` | `version-bump` | -| `event:permission/preset.ignorable` | `optional-property-added` | `version-bump` | -| `event:plan/mode.ignorable` | `optional-property-added` | `version-bump` | -| `event:request/context.ignorable` | `optional-property-added` | `version-bump` | -| `event:request/header.ignorable` | `optional-property-added` | `version-bump` | -| `event:sandbox/mode.ignorable` | `optional-property-added` | `version-bump` | -| `event:schedule/change.ignorable` | `optional-property-added` | `version-bump` | -| `event:session-log-deepseek/delivery-accepted.ignorable` | `optional-property-added` | `version-bump` | -| `event:session/end-seed.ignorable` | `optional-property-added` | `version-bump` | -| `event:session/title.ignorable` | `optional-property-added` | `version-bump` | -| `event:session/title-llm-request.ignorable` | `optional-property-added` | `version-bump` | -| `event:step/end.ignorable` | `optional-property-added` | `version-bump` | -| `event:step/start.ignorable` | `optional-property-added` | `version-bump` | -| `event:subagent/descriptor.ignorable` | `optional-property-added` | `version-bump` | -| `event:subagent/model-selection-policy.ignorable` | `optional-property-added` | `version-bump` | -| `event:team/member.ignorable` | `optional-property-added` | `version-bump` | -| `event:team/message/delivered.ignorable` | `optional-property-added` | `version-bump` | -| `event:team/message/queued.ignorable` | `optional-property-added` | `version-bump` | -| `event:team/task.ignorable` | `optional-property-added` | `version-bump` | -| `event:todo/write.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool-workflow/agent-end.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool-workflow/agent-start.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool-workflow/run-end.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool-workflow/run-start.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/call.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/code-dispatch.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/code-dispatch-start.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/result.ignorable` | `optional-property-added` | `version-bump` | -| `event:turn/end.ignorable` | `optional-property-added` | `version-bump` | -| `event:turn/start.ignorable` | `optional-property-added` | `version-bump` | -| `event:user/message.ignorable` | `optional-property-added` | `version-bump` | -| `event:web/deepseek-search-llm-request.ignorable` | `optional-property-added` | `version-bump` | +| `SessionEventEnvelope` | `union-variants-changed` | `review-required` | +| `event:agent-preset/selected.ignorable` | `optional-property-added` | `review-required` | +| `event:agent/inbox/spliced.ignorable` | `optional-property-added` | `review-required` | +| `event:approval/asked.ignorable` | `optional-property-added` | `review-required` | +| `event:approval/decided.ignorable` | `optional-property-added` | `review-required` | +| `event:approval/policy.ignorable` | `optional-property-added` | `review-required` | +| `event:assistant/chunk.ignorable` | `optional-property-added` | `review-required` | +| `event:assistant/message.ignorable` | `optional-property-added` | `review-required` | +| `event:command/done.ignorable` | `optional-property-added` | `review-required` | +| `event:command/run.ignorable` | `optional-property-added` | `review-required` | +| `event:compaction/end.ignorable` | `optional-property-added` | `review-required` | +| `event:compaction/prune.ignorable` | `optional-property-added` | `review-required` | +| `event:compaction/start.ignorable` | `optional-property-added` | `review-required` | +| `event:compaction/summary.ignorable` | `optional-property-added` | `review-required` | +| `event:feedback/record.ignorable` | `optional-property-added` | `review-required` | +| `event:goal/change.ignorable` | `optional-property-added` | `review-required` | +| `event:hook/invoked.ignorable` | `optional-property-added` | `review-required` | +| `event:hook/result.ignorable` | `optional-property-added` | `review-required` | +| `event:llm/retry.ignorable` | `optional-property-added` | `review-required` | +| `event:llm/retry-started.ignorable` | `optional-property-added` | `review-required` | +| `event:model/selection.ignorable` | `optional-property-added` | `review-required` | +| `event:permission/preset.ignorable` | `optional-property-added` | `review-required` | +| `event:plan/mode.ignorable` | `optional-property-added` | `review-required` | +| `event:request/context.ignorable` | `optional-property-added` | `review-required` | +| `event:request/header.ignorable` | `optional-property-added` | `review-required` | +| `event:sandbox/mode.ignorable` | `optional-property-added` | `review-required` | +| `event:schedule/change.ignorable` | `optional-property-added` | `review-required` | +| `event:session-log-deepseek/delivery-accepted.ignorable` | `optional-property-added` | `review-required` | +| `event:session/end-seed.ignorable` | `optional-property-added` | `review-required` | +| `event:session/title.ignorable` | `optional-property-added` | `review-required` | +| `event:session/title-llm-request.ignorable` | `optional-property-added` | `review-required` | +| `event:step/end.ignorable` | `optional-property-added` | `review-required` | +| `event:step/start.ignorable` | `optional-property-added` | `review-required` | +| `event:subagent/descriptor.ignorable` | `optional-property-added` | `review-required` | +| `event:subagent/model-selection-policy.ignorable` | `optional-property-added` | `review-required` | +| `event:team/member.ignorable` | `optional-property-added` | `review-required` | +| `event:team/message/delivered.ignorable` | `optional-property-added` | `review-required` | +| `event:team/message/queued.ignorable` | `optional-property-added` | `review-required` | +| `event:team/task.ignorable` | `optional-property-added` | `review-required` | +| `event:todo/write.ignorable` | `optional-property-added` | `review-required` | +| `event:tool-workflow/agent-end.ignorable` | `optional-property-added` | `review-required` | +| `event:tool-workflow/agent-start.ignorable` | `optional-property-added` | `review-required` | +| `event:tool-workflow/run-end.ignorable` | `optional-property-added` | `review-required` | +| `event:tool-workflow/run-start.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/call.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/code-dispatch.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/code-dispatch-start.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/result.ignorable` | `optional-property-added` | `review-required` | +| `event:turn/end.ignorable` | `optional-property-added` | `review-required` | +| `event:turn/start.ignorable` | `optional-property-added` | `review-required` | +| `event:user/message.ignorable` | `optional-property-added` | `review-required` | +| `event:web/deepseek-search-llm-request.ignorable` | `optional-property-added` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.2.zh.md b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.2.zh.md index b68ea09841..4d6b39343c 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.2.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.2.zh.md @@ -212,62 +212,62 @@ changes: -检测到 52 个根类型变化、52 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 52 个根类型变化、52 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `SessionEventEnvelope` | `union-variants-changed` | `version-bump` | -| `event:agent-preset/selected.ignorable` | `optional-property-added` | `version-bump` | -| `event:agent/inbox/spliced.ignorable` | `optional-property-added` | `version-bump` | -| `event:approval/asked.ignorable` | `optional-property-added` | `version-bump` | -| `event:approval/decided.ignorable` | `optional-property-added` | `version-bump` | -| `event:approval/policy.ignorable` | `optional-property-added` | `version-bump` | -| `event:assistant/chunk.ignorable` | `optional-property-added` | `version-bump` | -| `event:assistant/message.ignorable` | `optional-property-added` | `version-bump` | -| `event:command/done.ignorable` | `optional-property-added` | `version-bump` | -| `event:command/run.ignorable` | `optional-property-added` | `version-bump` | -| `event:compaction/end.ignorable` | `optional-property-added` | `version-bump` | -| `event:compaction/prune.ignorable` | `optional-property-added` | `version-bump` | -| `event:compaction/start.ignorable` | `optional-property-added` | `version-bump` | -| `event:compaction/summary.ignorable` | `optional-property-added` | `version-bump` | -| `event:feedback/record.ignorable` | `optional-property-added` | `version-bump` | -| `event:goal/change.ignorable` | `optional-property-added` | `version-bump` | -| `event:hook/invoked.ignorable` | `optional-property-added` | `version-bump` | -| `event:hook/result.ignorable` | `optional-property-added` | `version-bump` | -| `event:llm/retry.ignorable` | `optional-property-added` | `version-bump` | -| `event:llm/retry-started.ignorable` | `optional-property-added` | `version-bump` | -| `event:model/selection.ignorable` | `optional-property-added` | `version-bump` | -| `event:permission/preset.ignorable` | `optional-property-added` | `version-bump` | -| `event:plan/mode.ignorable` | `optional-property-added` | `version-bump` | -| `event:request/context.ignorable` | `optional-property-added` | `version-bump` | -| `event:request/header.ignorable` | `optional-property-added` | `version-bump` | -| `event:sandbox/mode.ignorable` | `optional-property-added` | `version-bump` | -| `event:schedule/change.ignorable` | `optional-property-added` | `version-bump` | -| `event:session-log-deepseek/delivery-accepted.ignorable` | `optional-property-added` | `version-bump` | -| `event:session/end-seed.ignorable` | `optional-property-added` | `version-bump` | -| `event:session/title.ignorable` | `optional-property-added` | `version-bump` | -| `event:session/title-llm-request.ignorable` | `optional-property-added` | `version-bump` | -| `event:step/end.ignorable` | `optional-property-added` | `version-bump` | -| `event:step/start.ignorable` | `optional-property-added` | `version-bump` | -| `event:subagent/descriptor.ignorable` | `optional-property-added` | `version-bump` | -| `event:subagent/model-selection-policy.ignorable` | `optional-property-added` | `version-bump` | -| `event:team/member.ignorable` | `optional-property-added` | `version-bump` | -| `event:team/message/delivered.ignorable` | `optional-property-added` | `version-bump` | -| `event:team/message/queued.ignorable` | `optional-property-added` | `version-bump` | -| `event:team/task.ignorable` | `optional-property-added` | `version-bump` | -| `event:todo/write.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool-workflow/agent-end.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool-workflow/agent-start.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool-workflow/run-end.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool-workflow/run-start.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/call.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/code-dispatch.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/code-dispatch-start.ignorable` | `optional-property-added` | `version-bump` | -| `event:tool/result.ignorable` | `optional-property-added` | `version-bump` | -| `event:turn/end.ignorable` | `optional-property-added` | `version-bump` | -| `event:turn/start.ignorable` | `optional-property-added` | `version-bump` | -| `event:user/message.ignorable` | `optional-property-added` | `version-bump` | -| `event:web/deepseek-search-llm-request.ignorable` | `optional-property-added` | `version-bump` | +| `SessionEventEnvelope` | `union-variants-changed` | `review-required` | +| `event:agent-preset/selected.ignorable` | `optional-property-added` | `review-required` | +| `event:agent/inbox/spliced.ignorable` | `optional-property-added` | `review-required` | +| `event:approval/asked.ignorable` | `optional-property-added` | `review-required` | +| `event:approval/decided.ignorable` | `optional-property-added` | `review-required` | +| `event:approval/policy.ignorable` | `optional-property-added` | `review-required` | +| `event:assistant/chunk.ignorable` | `optional-property-added` | `review-required` | +| `event:assistant/message.ignorable` | `optional-property-added` | `review-required` | +| `event:command/done.ignorable` | `optional-property-added` | `review-required` | +| `event:command/run.ignorable` | `optional-property-added` | `review-required` | +| `event:compaction/end.ignorable` | `optional-property-added` | `review-required` | +| `event:compaction/prune.ignorable` | `optional-property-added` | `review-required` | +| `event:compaction/start.ignorable` | `optional-property-added` | `review-required` | +| `event:compaction/summary.ignorable` | `optional-property-added` | `review-required` | +| `event:feedback/record.ignorable` | `optional-property-added` | `review-required` | +| `event:goal/change.ignorable` | `optional-property-added` | `review-required` | +| `event:hook/invoked.ignorable` | `optional-property-added` | `review-required` | +| `event:hook/result.ignorable` | `optional-property-added` | `review-required` | +| `event:llm/retry.ignorable` | `optional-property-added` | `review-required` | +| `event:llm/retry-started.ignorable` | `optional-property-added` | `review-required` | +| `event:model/selection.ignorable` | `optional-property-added` | `review-required` | +| `event:permission/preset.ignorable` | `optional-property-added` | `review-required` | +| `event:plan/mode.ignorable` | `optional-property-added` | `review-required` | +| `event:request/context.ignorable` | `optional-property-added` | `review-required` | +| `event:request/header.ignorable` | `optional-property-added` | `review-required` | +| `event:sandbox/mode.ignorable` | `optional-property-added` | `review-required` | +| `event:schedule/change.ignorable` | `optional-property-added` | `review-required` | +| `event:session-log-deepseek/delivery-accepted.ignorable` | `optional-property-added` | `review-required` | +| `event:session/end-seed.ignorable` | `optional-property-added` | `review-required` | +| `event:session/title.ignorable` | `optional-property-added` | `review-required` | +| `event:session/title-llm-request.ignorable` | `optional-property-added` | `review-required` | +| `event:step/end.ignorable` | `optional-property-added` | `review-required` | +| `event:step/start.ignorable` | `optional-property-added` | `review-required` | +| `event:subagent/descriptor.ignorable` | `optional-property-added` | `review-required` | +| `event:subagent/model-selection-policy.ignorable` | `optional-property-added` | `review-required` | +| `event:team/member.ignorable` | `optional-property-added` | `review-required` | +| `event:team/message/delivered.ignorable` | `optional-property-added` | `review-required` | +| `event:team/message/queued.ignorable` | `optional-property-added` | `review-required` | +| `event:team/task.ignorable` | `optional-property-added` | `review-required` | +| `event:todo/write.ignorable` | `optional-property-added` | `review-required` | +| `event:tool-workflow/agent-end.ignorable` | `optional-property-added` | `review-required` | +| `event:tool-workflow/agent-start.ignorable` | `optional-property-added` | `review-required` | +| `event:tool-workflow/run-end.ignorable` | `optional-property-added` | `review-required` | +| `event:tool-workflow/run-start.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/call.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/code-dispatch.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/code-dispatch-start.ignorable` | `optional-property-added` | `review-required` | +| `event:tool/result.ignorable` | `optional-property-added` | `review-required` | +| `event:turn/end.ignorable` | `optional-property-added` | `review-required` | +| `event:turn/start.ignorable` | `optional-property-added` | `review-required` | +| `event:user/message.ignorable` | `optional-property-added` | `review-required` | +| `event:web/deepseek-search-llm-request.ignorable` | `optional-property-added` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.4.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.4.i18n.yaml index cea2d1c259..c1f9bddfbf 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.4.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.4.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-1-2-alpha-4/structural-changes: - en: 19dc565f0446afc5 - zh: 16309465db21bd8b + en: eec8e831ff143edc + zh: 253dcaaf41ecac6f /persistence-release-dsh-v0-1-2-alpha-4/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.4.md b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.4.md index 9a6be5072c..d83a5e1bba 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.4.md +++ b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.4.md @@ -68,15 +68,15 @@ changes: -Detected 4 changed roots and 5 structural differences. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 4 changed roots and 5 structural differences. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `SessionHeader.seedLength` | `property-removed` | `version-bump` | -| `SessionHeader.isSeeded` | `required-property-added` | `version-bump` | -| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `version-bump` | -| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `version-bump` | -| `event:user/message.data.source` | `union-variants-changed` | `version-bump` | +| `SessionHeader.seedLength` | `property-removed` | `review-required` | +| `SessionHeader.isSeeded` | `required-property-added` | `review-required` | +| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `review-required` | +| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `review-required` | +| `event:user/message.data.source` | `union-variants-changed` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.4.zh.md b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.4.zh.md index a279aebe89..aedf30a137 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.2-alpha.4.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.1.2-alpha.4.zh.md @@ -68,15 +68,15 @@ changes: -检测到 4 个根类型变化、5 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 4 个根类型变化、5 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `SessionHeader.seedLength` | `property-removed` | `version-bump` | -| `SessionHeader.isSeeded` | `required-property-added` | `version-bump` | -| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `version-bump` | -| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `version-bump` | -| `event:user/message.data.source` | `union-variants-changed` | `version-bump` | +| `SessionHeader.seedLength` | `property-removed` | `review-required` | +| `SessionHeader.isSeeded` | `required-property-added` | `review-required` | +| `event:agent/inbox/spliced.data.inserted[].source` | `union-variants-changed` | `review-required` | +| `event:session/title-llm-request.data.messages[].source` | `union-variants-changed` | `review-required` | +| `event:user/message.data.source` | `union-variants-changed` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.3-alpha.1.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.1.3-alpha.1.i18n.yaml index 31145c4ef4..2e37ebb2c3 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.3-alpha.1.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.1.3-alpha.1.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-1-3-alpha-1/structural-changes: - en: 492c315af4d250aa - zh: 17a45e34aeb94791 + en: 746c20adf88325e1 + zh: e607c8b6e3dc8a3a /persistence-release-dsh-v0-1-3-alpha-1/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.1.3-alpha.1.md b/docs/persistence-changes/releases/dsh-v0.1.3-alpha.1.md index 571718ea48..ef21066705 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.3-alpha.1.md +++ b/docs/persistence-changes/releases/dsh-v0.1.3-alpha.1.md @@ -107,35 +107,35 @@ changes: -Detected 17 changed roots and 25 structural differences. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 17 changed roots and 25 structural differences. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `JsonlHeaderLine.seedLength` | `property-removed` | `version-bump` | -| `JsonlHeaderLine.isSeeded` | `required-property-added` | `version-bump` | -| `SessionHeader.version` | `type-changed` | `version-bump` | -| `event:agent/inbox/spliced.data.inserted[].content[]` | `union-variants-changed` | `version-bump` | -| `event:agent/inbox/spliced.data.inserted[].source.references[].capturedFormatVersion` | `optional-property-added` | `same-version` | -| `event:assistant/attempt` | `root-added` | `same-version` | -| `event:assistant/chunk` | `root-removed` | `version-bump` | -| `event:assistant/message.data.message.content[]` | `union-variants-changed` | `version-bump` | -| `event:assistant/message.data.stream` | `required-property-added` | `version-bump` | -| `event:compaction/summary.data` | `union-variants-changed` | `version-bump` | -| `event:session-log-deepseek/delivery-accepted.data.sessionFormatVersion` | `optional-property-added` | `same-version` | -| `event:session/end-seed.data.inherited` | `optional-property-added` | `same-version` | -| `event:session/end-seed.data` | `index-signature-changed` | `version-bump` | -| `event:session/title-llm-request.data.messages[].content[]` | `union-variants-changed` | `version-bump` | -| `event:session/title-llm-request.data.messages[].source.references[].capturedFormatVersion` | `optional-property-added` | `same-version` | -| `event:team/member.data.version` | `type-changed` | `version-bump` | -| `event:team/message/delivered.data.version` | `type-changed` | `version-bump` | -| `event:team/message/queued.data.message.content[]` | `union-variants-changed` | `version-bump` | -| `event:team/message/queued.data.message.delivery` | `property-removed` | `version-bump` | -| `event:team/message/queued.data.version` | `type-changed` | `version-bump` | -| `event:team/task.data.version` | `type-changed` | `version-bump` | -| `event:tool/code-dispatch.data.content[]` | `union-variants-changed` | `version-bump` | -| `event:tool/result.data.message.content[0].content[]` | `union-variants-changed` | `version-bump` | -| `event:user/message.data.content[]` | `union-variants-changed` | `version-bump` | -| `event:user/message.data.source.references[].capturedFormatVersion` | `optional-property-added` | `same-version` | +| `JsonlHeaderLine.seedLength` | `property-removed` | `review-required` | +| `JsonlHeaderLine.isSeeded` | `required-property-added` | `review-required` | +| `SessionHeader.version` | `type-changed` | `review-required` | +| `event:agent/inbox/spliced.data.inserted[].content[]` | `union-variants-changed` | `review-required` | +| `event:agent/inbox/spliced.data.inserted[].source.references[].capturedFormatVersion` | `optional-property-added` | `not-required` | +| `event:assistant/attempt` | `root-added` | `not-required` | +| `event:assistant/chunk` | `root-removed` | `review-required` | +| `event:assistant/message.data.message.content[]` | `union-variants-changed` | `review-required` | +| `event:assistant/message.data.stream` | `required-property-added` | `review-required` | +| `event:compaction/summary.data` | `union-variants-changed` | `review-required` | +| `event:session-log-deepseek/delivery-accepted.data.sessionFormatVersion` | `optional-property-added` | `not-required` | +| `event:session/end-seed.data.inherited` | `optional-property-added` | `not-required` | +| `event:session/end-seed.data` | `index-signature-changed` | `review-required` | +| `event:session/title-llm-request.data.messages[].content[]` | `union-variants-changed` | `review-required` | +| `event:session/title-llm-request.data.messages[].source.references[].capturedFormatVersion` | `optional-property-added` | `not-required` | +| `event:team/member.data.version` | `type-changed` | `review-required` | +| `event:team/message/delivered.data.version` | `type-changed` | `review-required` | +| `event:team/message/queued.data.message.content[]` | `union-variants-changed` | `review-required` | +| `event:team/message/queued.data.message.delivery` | `property-removed` | `review-required` | +| `event:team/message/queued.data.version` | `type-changed` | `review-required` | +| `event:team/task.data.version` | `type-changed` | `review-required` | +| `event:tool/code-dispatch.data.content[]` | `union-variants-changed` | `review-required` | +| `event:tool/result.data.message.content[0].content[]` | `union-variants-changed` | `review-required` | +| `event:user/message.data.content[]` | `union-variants-changed` | `review-required` | +| `event:user/message.data.source.references[].capturedFormatVersion` | `optional-property-added` | `not-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.3-alpha.1.zh.md b/docs/persistence-changes/releases/dsh-v0.1.3-alpha.1.zh.md index 980106910f..af0b35779e 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.3-alpha.1.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.1.3-alpha.1.zh.md @@ -107,35 +107,35 @@ changes: -检测到 17 个根类型变化、25 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 17 个根类型变化、25 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `JsonlHeaderLine.seedLength` | `property-removed` | `version-bump` | -| `JsonlHeaderLine.isSeeded` | `required-property-added` | `version-bump` | -| `SessionHeader.version` | `type-changed` | `version-bump` | -| `event:agent/inbox/spliced.data.inserted[].content[]` | `union-variants-changed` | `version-bump` | -| `event:agent/inbox/spliced.data.inserted[].source.references[].capturedFormatVersion` | `optional-property-added` | `same-version` | -| `event:assistant/attempt` | `root-added` | `same-version` | -| `event:assistant/chunk` | `root-removed` | `version-bump` | -| `event:assistant/message.data.message.content[]` | `union-variants-changed` | `version-bump` | -| `event:assistant/message.data.stream` | `required-property-added` | `version-bump` | -| `event:compaction/summary.data` | `union-variants-changed` | `version-bump` | -| `event:session-log-deepseek/delivery-accepted.data.sessionFormatVersion` | `optional-property-added` | `same-version` | -| `event:session/end-seed.data.inherited` | `optional-property-added` | `same-version` | -| `event:session/end-seed.data` | `index-signature-changed` | `version-bump` | -| `event:session/title-llm-request.data.messages[].content[]` | `union-variants-changed` | `version-bump` | -| `event:session/title-llm-request.data.messages[].source.references[].capturedFormatVersion` | `optional-property-added` | `same-version` | -| `event:team/member.data.version` | `type-changed` | `version-bump` | -| `event:team/message/delivered.data.version` | `type-changed` | `version-bump` | -| `event:team/message/queued.data.message.content[]` | `union-variants-changed` | `version-bump` | -| `event:team/message/queued.data.message.delivery` | `property-removed` | `version-bump` | -| `event:team/message/queued.data.version` | `type-changed` | `version-bump` | -| `event:team/task.data.version` | `type-changed` | `version-bump` | -| `event:tool/code-dispatch.data.content[]` | `union-variants-changed` | `version-bump` | -| `event:tool/result.data.message.content[0].content[]` | `union-variants-changed` | `version-bump` | -| `event:user/message.data.content[]` | `union-variants-changed` | `version-bump` | -| `event:user/message.data.source.references[].capturedFormatVersion` | `optional-property-added` | `same-version` | +| `JsonlHeaderLine.seedLength` | `property-removed` | `review-required` | +| `JsonlHeaderLine.isSeeded` | `required-property-added` | `review-required` | +| `SessionHeader.version` | `type-changed` | `review-required` | +| `event:agent/inbox/spliced.data.inserted[].content[]` | `union-variants-changed` | `review-required` | +| `event:agent/inbox/spliced.data.inserted[].source.references[].capturedFormatVersion` | `optional-property-added` | `not-required` | +| `event:assistant/attempt` | `root-added` | `not-required` | +| `event:assistant/chunk` | `root-removed` | `review-required` | +| `event:assistant/message.data.message.content[]` | `union-variants-changed` | `review-required` | +| `event:assistant/message.data.stream` | `required-property-added` | `review-required` | +| `event:compaction/summary.data` | `union-variants-changed` | `review-required` | +| `event:session-log-deepseek/delivery-accepted.data.sessionFormatVersion` | `optional-property-added` | `not-required` | +| `event:session/end-seed.data.inherited` | `optional-property-added` | `not-required` | +| `event:session/end-seed.data` | `index-signature-changed` | `review-required` | +| `event:session/title-llm-request.data.messages[].content[]` | `union-variants-changed` | `review-required` | +| `event:session/title-llm-request.data.messages[].source.references[].capturedFormatVersion` | `optional-property-added` | `not-required` | +| `event:team/member.data.version` | `type-changed` | `review-required` | +| `event:team/message/delivered.data.version` | `type-changed` | `review-required` | +| `event:team/message/queued.data.message.content[]` | `union-variants-changed` | `review-required` | +| `event:team/message/queued.data.message.delivery` | `property-removed` | `review-required` | +| `event:team/message/queued.data.version` | `type-changed` | `review-required` | +| `event:team/task.data.version` | `type-changed` | `review-required` | +| `event:tool/code-dispatch.data.content[]` | `union-variants-changed` | `review-required` | +| `event:tool/result.data.message.content[0].content[]` | `union-variants-changed` | `review-required` | +| `event:user/message.data.content[]` | `union-variants-changed` | `review-required` | +| `event:user/message.data.source.references[].capturedFormatVersion` | `optional-property-added` | `not-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.3-alpha.2.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.1.3-alpha.2.i18n.yaml index 934ea2566a..f3f248ee3b 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.3-alpha.2.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.1.3-alpha.2.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-1-3-alpha-2/structural-changes: - en: be5d82540eb344db - zh: 8edd0ca270019992 + en: 4b866a071a7d653e + zh: a2ffe1a9ae361e2c /persistence-release-dsh-v0-1-3-alpha-2/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.1.3-alpha.2.md b/docs/persistence-changes/releases/dsh-v0.1.3-alpha.2.md index d6b6a658c3..99407651a3 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.3-alpha.2.md +++ b/docs/persistence-changes/releases/dsh-v0.1.3-alpha.2.md @@ -62,12 +62,12 @@ changes: -Detected 2 changed roots and 2 structural differences. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 2 changed roots and 2 structural differences. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `event:feedback/message-delete` | `root-added` | `same-version` | -| `event:feedback/message-put` | `root-added` | `same-version` | +| `event:feedback/message-delete` | `root-added` | `not-required` | +| `event:feedback/message-put` | `root-added` | `not-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.3-alpha.2.zh.md b/docs/persistence-changes/releases/dsh-v0.1.3-alpha.2.zh.md index 9f6d962138..913f9cfccf 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.3-alpha.2.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.1.3-alpha.2.zh.md @@ -62,12 +62,12 @@ changes: -检测到 2 个根类型变化、2 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 2 个根类型变化、2 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `event:feedback/message-delete` | `root-added` | `same-version` | -| `event:feedback/message-put` | `root-added` | `same-version` | +| `event:feedback/message-delete` | `root-added` | `not-required` | +| `event:feedback/message-put` | `root-added` | `not-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.5-alpha.1.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.1.5-alpha.1.i18n.yaml index 5db80e034e..4896e684f0 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.5-alpha.1.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.1.5-alpha.1.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-1-5-alpha-1/structural-changes: - en: f65ce6c033426a9d - zh: 278e167343e54fef + en: b5f68991a076ac50 + zh: 4593e46ada9541e9 /persistence-release-dsh-v0-1-5-alpha-1/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.1.5-alpha.1.md b/docs/persistence-changes/releases/dsh-v0.1.5-alpha.1.md index 3dd251e6ca..d7c9dcb531 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.5-alpha.1.md +++ b/docs/persistence-changes/releases/dsh-v0.1.5-alpha.1.md @@ -92,35 +92,35 @@ changes: -Detected 12 changed roots and 25 structural differences. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 12 changed roots and 25 structural differences. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `SessionEventEnvelope` | `union-variants-changed` | `version-bump` | -| `SessionHeader.version` | `type-changed` | `version-bump` | -| `event:assistant/message.sourceEventSeqs` | `property-removed` | `version-bump` | -| `event:assistant/message.surfaceOp` | `property-made-required` | `version-bump` | -| `event:assistant/message.surfaceOp.end` | `property-removed` | `version-bump` | -| `event:assistant/message.surfaceOp.start` | `property-removed` | `version-bump` | -| `event:assistant/message.surfaceOp.endSeq` | `required-property-added` | `version-bump` | -| `event:assistant/message.surfaceOp.startSeq` | `required-property-added` | `version-bump` | -| `event:request/context.data.systemPromptUpdate` | `optional-property-added` | `same-version` | -| `event:request/header.data.header.system` | `property-removed` | `version-bump` | -| `event:system/message` | `root-added` | `version-bump` | -| `event:tool/code-dispatch` | `root-removed` | `version-bump` | -| `event:tool/code-dispatch-start` | `root-removed` | `version-bump` | -| `event:tool/ptc-dispatch` | `root-added` | `same-version` | -| `event:tool/ptc-dispatch-start` | `root-added` | `same-version` | -| `event:tool/result.surfaceOp` | `property-made-required` | `version-bump` | -| `event:tool/result.surfaceOp.end` | `property-removed` | `version-bump` | -| `event:tool/result.surfaceOp.start` | `property-removed` | `version-bump` | -| `event:tool/result.surfaceOp.endSeq` | `required-property-added` | `version-bump` | -| `event:tool/result.surfaceOp.startSeq` | `required-property-added` | `version-bump` | -| `event:user/message.surfaceOp` | `property-made-required` | `version-bump` | -| `event:user/message.surfaceOp.end` | `property-removed` | `version-bump` | -| `event:user/message.surfaceOp.start` | `property-removed` | `version-bump` | -| `event:user/message.surfaceOp.endSeq` | `required-property-added` | `version-bump` | -| `event:user/message.surfaceOp.startSeq` | `required-property-added` | `version-bump` | +| `SessionEventEnvelope` | `union-variants-changed` | `review-required` | +| `SessionHeader.version` | `type-changed` | `review-required` | +| `event:assistant/message.sourceEventSeqs` | `property-removed` | `review-required` | +| `event:assistant/message.surfaceOp` | `property-made-required` | `review-required` | +| `event:assistant/message.surfaceOp.end` | `property-removed` | `review-required` | +| `event:assistant/message.surfaceOp.start` | `property-removed` | `review-required` | +| `event:assistant/message.surfaceOp.endSeq` | `required-property-added` | `review-required` | +| `event:assistant/message.surfaceOp.startSeq` | `required-property-added` | `review-required` | +| `event:request/context.data.systemPromptUpdate` | `optional-property-added` | `not-required` | +| `event:request/header.data.header.system` | `property-removed` | `review-required` | +| `event:system/message` | `root-added` | `review-required` | +| `event:tool/code-dispatch` | `root-removed` | `review-required` | +| `event:tool/code-dispatch-start` | `root-removed` | `review-required` | +| `event:tool/ptc-dispatch` | `root-added` | `not-required` | +| `event:tool/ptc-dispatch-start` | `root-added` | `not-required` | +| `event:tool/result.surfaceOp` | `property-made-required` | `review-required` | +| `event:tool/result.surfaceOp.end` | `property-removed` | `review-required` | +| `event:tool/result.surfaceOp.start` | `property-removed` | `review-required` | +| `event:tool/result.surfaceOp.endSeq` | `required-property-added` | `review-required` | +| `event:tool/result.surfaceOp.startSeq` | `required-property-added` | `review-required` | +| `event:user/message.surfaceOp` | `property-made-required` | `review-required` | +| `event:user/message.surfaceOp.end` | `property-removed` | `review-required` | +| `event:user/message.surfaceOp.start` | `property-removed` | `review-required` | +| `event:user/message.surfaceOp.endSeq` | `required-property-added` | `review-required` | +| `event:user/message.surfaceOp.startSeq` | `required-property-added` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.5-alpha.1.zh.md b/docs/persistence-changes/releases/dsh-v0.1.5-alpha.1.zh.md index fb2e241250..1e5af66f0a 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.5-alpha.1.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.1.5-alpha.1.zh.md @@ -92,35 +92,35 @@ changes: -检测到 12 个根类型变化、25 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 12 个根类型变化、25 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `SessionEventEnvelope` | `union-variants-changed` | `version-bump` | -| `SessionHeader.version` | `type-changed` | `version-bump` | -| `event:assistant/message.sourceEventSeqs` | `property-removed` | `version-bump` | -| `event:assistant/message.surfaceOp` | `property-made-required` | `version-bump` | -| `event:assistant/message.surfaceOp.end` | `property-removed` | `version-bump` | -| `event:assistant/message.surfaceOp.start` | `property-removed` | `version-bump` | -| `event:assistant/message.surfaceOp.endSeq` | `required-property-added` | `version-bump` | -| `event:assistant/message.surfaceOp.startSeq` | `required-property-added` | `version-bump` | -| `event:request/context.data.systemPromptUpdate` | `optional-property-added` | `same-version` | -| `event:request/header.data.header.system` | `property-removed` | `version-bump` | -| `event:system/message` | `root-added` | `version-bump` | -| `event:tool/code-dispatch` | `root-removed` | `version-bump` | -| `event:tool/code-dispatch-start` | `root-removed` | `version-bump` | -| `event:tool/ptc-dispatch` | `root-added` | `same-version` | -| `event:tool/ptc-dispatch-start` | `root-added` | `same-version` | -| `event:tool/result.surfaceOp` | `property-made-required` | `version-bump` | -| `event:tool/result.surfaceOp.end` | `property-removed` | `version-bump` | -| `event:tool/result.surfaceOp.start` | `property-removed` | `version-bump` | -| `event:tool/result.surfaceOp.endSeq` | `required-property-added` | `version-bump` | -| `event:tool/result.surfaceOp.startSeq` | `required-property-added` | `version-bump` | -| `event:user/message.surfaceOp` | `property-made-required` | `version-bump` | -| `event:user/message.surfaceOp.end` | `property-removed` | `version-bump` | -| `event:user/message.surfaceOp.start` | `property-removed` | `version-bump` | -| `event:user/message.surfaceOp.endSeq` | `required-property-added` | `version-bump` | -| `event:user/message.surfaceOp.startSeq` | `required-property-added` | `version-bump` | +| `SessionEventEnvelope` | `union-variants-changed` | `review-required` | +| `SessionHeader.version` | `type-changed` | `review-required` | +| `event:assistant/message.sourceEventSeqs` | `property-removed` | `review-required` | +| `event:assistant/message.surfaceOp` | `property-made-required` | `review-required` | +| `event:assistant/message.surfaceOp.end` | `property-removed` | `review-required` | +| `event:assistant/message.surfaceOp.start` | `property-removed` | `review-required` | +| `event:assistant/message.surfaceOp.endSeq` | `required-property-added` | `review-required` | +| `event:assistant/message.surfaceOp.startSeq` | `required-property-added` | `review-required` | +| `event:request/context.data.systemPromptUpdate` | `optional-property-added` | `not-required` | +| `event:request/header.data.header.system` | `property-removed` | `review-required` | +| `event:system/message` | `root-added` | `review-required` | +| `event:tool/code-dispatch` | `root-removed` | `review-required` | +| `event:tool/code-dispatch-start` | `root-removed` | `review-required` | +| `event:tool/ptc-dispatch` | `root-added` | `not-required` | +| `event:tool/ptc-dispatch-start` | `root-added` | `not-required` | +| `event:tool/result.surfaceOp` | `property-made-required` | `review-required` | +| `event:tool/result.surfaceOp.end` | `property-removed` | `review-required` | +| `event:tool/result.surfaceOp.start` | `property-removed` | `review-required` | +| `event:tool/result.surfaceOp.endSeq` | `required-property-added` | `review-required` | +| `event:tool/result.surfaceOp.startSeq` | `required-property-added` | `review-required` | +| `event:user/message.surfaceOp` | `property-made-required` | `review-required` | +| `event:user/message.surfaceOp.end` | `property-removed` | `review-required` | +| `event:user/message.surfaceOp.start` | `property-removed` | `review-required` | +| `event:user/message.surfaceOp.endSeq` | `required-property-added` | `review-required` | +| `event:user/message.surfaceOp.startSeq` | `required-property-added` | `review-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.5-alpha.2.i18n.yaml b/docs/persistence-changes/releases/dsh-v0.1.5-alpha.2.i18n.yaml index 6aceb0a20f..03e9c9e64d 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.5-alpha.2.i18n.yaml +++ b/docs/persistence-changes/releases/dsh-v0.1.5-alpha.2.i18n.yaml @@ -21,8 +21,8 @@ en: af9cea43334ee692 zh: c6c8bd0d6a17718a /persistence-release-dsh-v0-1-5-alpha-2/structural-changes: - en: a142ebb2293bce41 - zh: 488e9e2321625d51 + en: 5a12854a5c81d51e + zh: dc924c0138b2e57a /persistence-release-dsh-v0-1-5-alpha-2/verification: en: 8ccca317964523b1 zh: 2c8b3e70a3320778 diff --git a/docs/persistence-changes/releases/dsh-v0.1.5-alpha.2.md b/docs/persistence-changes/releases/dsh-v0.1.5-alpha.2.md index 76353e3ab3..b6db727160 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.5-alpha.2.md +++ b/docs/persistence-changes/releases/dsh-v0.1.5-alpha.2.md @@ -68,15 +68,15 @@ changes: -Detected 4 changed roots and 5 structural differences. The minimum below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. +Detected 4 changed roots and 5 structural differences. The review requirement below is calculated using current rules for comparison only; it does not assert historical compliance, migration correctness, or runtime compatibility. -| Path | Change | Current minimum | +| Path | Change | Review requirement | |---|---|---| -| `event:deliverables/presented` | `root-added` | `same-version` | -| `event:feedback/message-put.data.item.category` | `optional-property-added` | `same-version` | -| `event:feedback/record.data.text` | `property-made-optional` | `same-version` | -| `event:feedback/record.data.category` | `optional-property-added` | `same-version` | -| `event:subagent/catalog` | `root-added` | `same-version` | +| `event:deliverables/presented` | `root-added` | `not-required` | +| `event:feedback/message-put.data.item.category` | `optional-property-added` | `not-required` | +| `event:feedback/record.data.text` | `property-made-optional` | `not-required` | +| `event:feedback/record.data.category` | `optional-property-added` | `not-required` | +| `event:subagent/catalog` | `root-added` | `not-required` | diff --git a/docs/persistence-changes/releases/dsh-v0.1.5-alpha.2.zh.md b/docs/persistence-changes/releases/dsh-v0.1.5-alpha.2.zh.md index 676a09c1e6..37e01ce888 100644 --- a/docs/persistence-changes/releases/dsh-v0.1.5-alpha.2.zh.md +++ b/docs/persistence-changes/releases/dsh-v0.1.5-alpha.2.zh.md @@ -68,15 +68,15 @@ changes: -检测到 4 个根类型变化、5 项结构差异。下表的最低要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 +检测到 4 个根类型变化、5 项结构差异。下表的审查要求按当前规则计算,只用于比较;不表示旧版本曾遵守这些规则,也不证明迁移或运行时兼容性。 -| 路径 | 变化 | 当前最低要求 | +| 路径 | 变化 | 审查要求 | |---|---|---| -| `event:deliverables/presented` | `root-added` | `same-version` | -| `event:feedback/message-put.data.item.category` | `optional-property-added` | `same-version` | -| `event:feedback/record.data.text` | `property-made-optional` | `same-version` | -| `event:feedback/record.data.category` | `optional-property-added` | `same-version` | -| `event:subagent/catalog` | `root-added` | `same-version` | +| `event:deliverables/presented` | `root-added` | `not-required` | +| `event:feedback/message-put.data.item.category` | `optional-property-added` | `not-required` | +| `event:feedback/record.data.text` | `property-made-optional` | `not-required` | +| `event:feedback/record.data.category` | `optional-property-added` | `not-required` | +| `event:subagent/catalog` | `root-added` | `not-required` | diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index e6b73c0fcd..04344d9b87 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -406,7 +406,7 @@ "kind": "event", "event": "agent/inbox/spliced", "surface": false, - "digest": "9a36727716d0e73f681f3b725e7f28f89417c68174c8af0ff2b1ef52b08326a0", + "digest": "0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034", "schema": { "root": 0, "nodes": [ @@ -435,7 +435,7 @@ }, { "name": "type", - "type": 204, + "type": 206, "optional": false } ], @@ -451,7 +451,7 @@ }, { "name": "outcome", - "type": 200, + "type": 202, "optional": true }, { @@ -466,7 +466,7 @@ }, { "name": "target", - "type": 201, + "type": 203, "optional": false } ], @@ -818,10 +818,10 @@ "types": [ 34, 39, - 42, + 41, + 43, 45, - 47, - 49, + 48, 51, 53, 55, @@ -833,9 +833,9 @@ 67, 69, 70, + 71, 72, 73, - 74, 75, 76, 77, @@ -846,9 +846,9 @@ 82, 83, 84, + 85, 86, 87, - 88, 89, 90, 91, @@ -872,9 +872,9 @@ 109, 110, 111, + 112, 113, 114, - 115, 116, 117, 118, @@ -885,48 +885,48 @@ 123, 124, 125, + 126, 127, - 129, + 128, + 130, 132, - 133, - 134, 135, 136, + 137, 138, 139, - 140, 141, + 142, 143, 144, - 145, 146, 147, + 148, 149, 150, - 151, + 152, 153, - 155, + 154, 156, - 164, + 158, + 159, 167, - 169, 170, 172, - 174, - 178, - 180, - 188, - 189, - 190, - 191, - 192, + 175, + 177, + 179, + 183, + 185, 193, 194, 195, 196, 197, 198, - 199 + 199, + 200, + 201 ] }, { @@ -956,7 +956,7 @@ }, { "kind": "literal", - "value": "dsh-session-title-llm" + "value": "tool-goal" }, { "kind": "array", @@ -983,12 +983,87 @@ "properties": [ { "name": "form", - "type": 40, + "type": 35, "optional": false }, { "name": "kind", - "type": 41, + "type": 40, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-jobs" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user-approval" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 35, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + }, + { + "name": "sections", + "type": 37, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "dsh-session-title-llm" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 47, "optional": false }, { @@ -1017,12 +1092,12 @@ "properties": [ { "name": "form", - "type": 43, + "type": 49, "optional": false }, { "name": "kind", - "type": 44, + "type": 50, "optional": false }, { @@ -1046,12 +1121,12 @@ "properties": [ { "name": "form", - "type": 40, + "type": 46, "optional": false }, { "name": "kind", - "type": 46, + "type": 52, "optional": false }, { @@ -1071,12 +1146,12 @@ "properties": [ { "name": "form", - "type": 40, + "type": 46, "optional": false }, { "name": "kind", - "type": 48, + "type": 54, "optional": false }, { @@ -1096,12 +1171,12 @@ "properties": [ { "name": "form", - "type": 40, + "type": 46, "optional": false }, { "name": "kind", - "type": 50, + "type": 56, "optional": false }, { @@ -1121,12 +1196,12 @@ "properties": [ { "name": "form", - "type": 40, + "type": 46, "optional": false }, { "name": "kind", - "type": 52, + "type": 58, "optional": false }, { @@ -1146,12 +1221,12 @@ "properties": [ { "name": "form", - "type": 40, + "type": 46, "optional": false }, { "name": "kind", - "type": 54, + "type": 60, "optional": false }, { @@ -1171,12 +1246,12 @@ "properties": [ { "name": "form", - "type": 40, + "type": 46, "optional": false }, { "name": "kind", - "type": 56, + "type": 62, "optional": false }, { @@ -1196,12 +1271,12 @@ "properties": [ { "name": "form", - "type": 40, + "type": 46, "optional": false }, { "name": "kind", - "type": 58, + "type": 64, "optional": false }, { @@ -1221,12 +1296,12 @@ "properties": [ { "name": "form", - "type": 40, + "type": 46, "optional": false }, { "name": "kind", - "type": 60, + "type": 66, "optional": false }, { @@ -1246,12 +1321,12 @@ "properties": [ { "name": "form", - "type": 40, + "type": 46, "optional": false }, { "name": "kind", - "type": 62, + "type": 68, "optional": false }, { @@ -1271,82 +1346,7 @@ "properties": [ { "name": "form", - "type": 40, - "optional": false - }, - { - "name": "kind", - "type": 64, - "optional": false - }, - { - "name": "summary", - "type": 7, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "tool-goal" - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 40, - "optional": false - }, - { - "name": "kind", - "type": 66, - "optional": false - }, - { - "name": "summary", - "type": 7, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "tool-jobs" - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 40, - "optional": false - }, - { - "name": "kind", - "type": 68, - "optional": false - }, - { - "name": "summary", - "type": 7, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "user-approval" - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 40, + "type": 46, "optional": false }, { @@ -1367,13 +1367,76 @@ "properties": [ { "name": "form", - "type": 71, + "type": 46, "optional": false }, { "name": "kind", + "type": 40, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", "type": 46, "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 46, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 52, + "optional": false } ], "indices": [] @@ -1387,55 +1450,7 @@ "properties": [ { "name": "form", - "type": 71, - "optional": false - }, - { - "name": "kind", - "type": 48, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 71, - "optional": false - }, - { - "name": "kind", - "type": 50, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 71, - "optional": false - }, - { - "name": "kind", - "type": 52, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 71, + "type": 74, "optional": false }, { @@ -1451,7 +1466,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 74, "optional": false }, { @@ -1467,7 +1482,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 74, "optional": false }, { @@ -1483,7 +1498,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 74, "optional": false }, { @@ -1499,7 +1514,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 74, "optional": false }, { @@ -1515,7 +1530,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 74, "optional": false }, { @@ -1531,7 +1546,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 74, "optional": false }, { @@ -1547,7 +1562,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 74, "optional": false }, { @@ -1563,7 +1578,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 74, "optional": false }, { @@ -1579,12 +1594,60 @@ "properties": [ { "name": "form", - "type": 85, + "type": 74, "optional": false }, { "name": "kind", - "type": 46, + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 74, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 88, + "optional": false + }, + { + "name": "kind", + "type": 52, "optional": false } ], @@ -1599,55 +1662,7 @@ "properties": [ { "name": "form", - "type": 85, - "optional": false - }, - { - "name": "kind", - "type": 48, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 85, - "optional": false - }, - { - "name": "kind", - "type": 50, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 85, - "optional": false - }, - { - "name": "kind", - "type": 52, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 85, + "type": 88, "optional": false }, { @@ -1663,7 +1678,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 88, "optional": false }, { @@ -1679,7 +1694,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 88, "optional": false }, { @@ -1695,7 +1710,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 88, "optional": false }, { @@ -1711,7 +1726,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 88, "optional": false }, { @@ -1727,7 +1742,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 88, "optional": false }, { @@ -1743,7 +1758,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 88, "optional": false }, { @@ -1759,7 +1774,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 88, "optional": false }, { @@ -1775,7 +1790,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 88, "optional": false }, { @@ -1791,12 +1806,12 @@ "properties": [ { "name": "form", - "type": 43, + "type": 88, "optional": false }, { "name": "kind", - "type": 46, + "type": 40, "optional": false } ], @@ -1807,12 +1822,12 @@ "properties": [ { "name": "form", - "type": 43, + "type": 88, "optional": false }, { "name": "kind", - "type": 48, + "type": 42, "optional": false } ], @@ -1823,12 +1838,12 @@ "properties": [ { "name": "form", - "type": 43, + "type": 88, "optional": false }, { "name": "kind", - "type": 50, + "type": 44, "optional": false } ], @@ -1839,7 +1854,7 @@ "properties": [ { "name": "form", - "type": 43, + "type": 49, "optional": false }, { @@ -1855,7 +1870,7 @@ "properties": [ { "name": "form", - "type": 43, + "type": 49, "optional": false }, { @@ -1871,7 +1886,7 @@ "properties": [ { "name": "form", - "type": 43, + "type": 49, "optional": false }, { @@ -1887,7 +1902,7 @@ "properties": [ { "name": "form", - "type": 43, + "type": 49, "optional": false }, { @@ -1903,7 +1918,7 @@ "properties": [ { "name": "form", - "type": 43, + "type": 49, "optional": false }, { @@ -1919,7 +1934,7 @@ "properties": [ { "name": "form", - "type": 43, + "type": 49, "optional": false }, { @@ -1935,7 +1950,7 @@ "properties": [ { "name": "form", - "type": 43, + "type": 49, "optional": false }, { @@ -1951,7 +1966,7 @@ "properties": [ { "name": "form", - "type": 43, + "type": 49, "optional": false }, { @@ -1967,7 +1982,7 @@ "properties": [ { "name": "form", - "type": 43, + "type": 49, "optional": false }, { @@ -1983,7 +1998,7 @@ "properties": [ { "name": "form", - "type": 43, + "type": 49, "optional": false }, { @@ -1999,12 +2014,60 @@ "properties": [ { "name": "form", - "type": 112, + "type": 49, "optional": false }, { "name": "kind", - "type": 46, + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 49, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 52, "optional": false } ], @@ -2019,55 +2082,7 @@ "properties": [ { "name": "form", - "type": 112, - "optional": false - }, - { - "name": "kind", - "type": 48, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 112, - "optional": false - }, - { - "name": "kind", - "type": 50, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 112, - "optional": false - }, - { - "name": "kind", - "type": 52, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 112, + "type": 115, "optional": false }, { @@ -2083,7 +2098,7 @@ "properties": [ { "name": "form", - "type": 112, + "type": 115, "optional": false }, { @@ -2099,7 +2114,7 @@ "properties": [ { "name": "form", - "type": 112, + "type": 115, "optional": false }, { @@ -2115,7 +2130,7 @@ "properties": [ { "name": "form", - "type": 112, + "type": 115, "optional": false }, { @@ -2131,7 +2146,7 @@ "properties": [ { "name": "form", - "type": 112, + "type": 115, "optional": false }, { @@ -2147,7 +2162,7 @@ "properties": [ { "name": "form", - "type": 112, + "type": 115, "optional": false }, { @@ -2163,7 +2178,7 @@ "properties": [ { "name": "form", - "type": 112, + "type": 115, "optional": false }, { @@ -2179,7 +2194,7 @@ "properties": [ { "name": "form", - "type": 112, + "type": 115, "optional": false }, { @@ -2195,7 +2210,7 @@ "properties": [ { "name": "form", - "type": 112, + "type": 115, "optional": false }, { @@ -2206,6 +2221,54 @@ ], "indices": [] }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 115, + "optional": false + }, + { + "name": "kind", + "type": 44, + "optional": false + } + ], + "indices": [] + }, { "kind": "object", "properties": [ @@ -2216,7 +2279,7 @@ }, { "name": "kind", - "type": 126, + "type": 129, "optional": false }, { @@ -2241,7 +2304,7 @@ "properties": [ { "name": "kind", - "type": 128, + "type": 131, "optional": false }, { @@ -2276,7 +2339,7 @@ "properties": [ { "name": "kind", - "type": 130, + "type": 133, "optional": false }, { @@ -2291,7 +2354,7 @@ }, { "name": "replayState", - "type": 131, + "type": 134, "optional": true } ], @@ -2305,39 +2368,6 @@ "kind": "opaque", "reason": "unknown" }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 46, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 48, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 50, - "optional": false - } - ], - "indices": [] - }, { "kind": "object", "properties": [ @@ -2349,21 +2379,6 @@ ], "indices": [] }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 137, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "ptc-mode" - }, { "kind": "object", "properties": [ @@ -2402,7 +2417,7 @@ "properties": [ { "name": "kind", - "type": 142, + "type": 140, "optional": false } ], @@ -2410,7 +2425,7 @@ }, { "kind": "literal", - "value": "system-prompt" + "value": "ptc-mode" }, { "kind": "object", @@ -2445,6 +2460,21 @@ ], "indices": [] }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 145, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "system-prompt" + }, { "kind": "object", "properties": [ @@ -2461,7 +2491,40 @@ "properties": [ { "name": "kind", - "type": 148, + "type": 68, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 40, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 151, "optional": false } ], @@ -2487,7 +2550,7 @@ "properties": [ { "name": "kind", - "type": 68, + "type": 42, "optional": false } ], @@ -2498,7 +2561,7 @@ "properties": [ { "name": "kind", - "type": 152, + "type": 155, "optional": false } ], @@ -2513,7 +2576,7 @@ "properties": [ { "name": "kind", - "type": 154, + "type": 157, "optional": false } ], @@ -2528,7 +2591,7 @@ "properties": [ { "name": "kind", - "type": 36, + "type": 44, "optional": false } ], @@ -2549,17 +2612,17 @@ }, { "name": "changes", - "type": 157, + "type": 160, "optional": false }, { "name": "form", - "type": 71, + "type": 74, "optional": false }, { "name": "kind", - "type": 163, + "type": 166, "optional": false } ], @@ -2567,14 +2630,14 @@ }, { "kind": "array", - "element": 158 + "element": 161 }, { "kind": "object", "properties": [ { "name": "action", - "type": 159, + "type": 162, "optional": false }, { @@ -2598,9 +2661,9 @@ { "kind": "union", "types": [ - 160, - 161, - 162 + 163, + 164, + 165 ] }, { @@ -2629,12 +2692,12 @@ }, { "name": "kind", - "type": 165, + "type": 168, "optional": false }, { "name": "outcome", - "type": 166, + "type": 169, "optional": false } ], @@ -2658,7 +2721,7 @@ }, { "name": "kind", - "type": 168, + "type": 171, "optional": false } ], @@ -2681,6 +2744,11 @@ "type": 32, "optional": false }, + { + "name": "principal", + "type": 173, + "optional": true + }, { "name": "rpcId", "type": 7, @@ -2689,6 +2757,21 @@ ], "indices": [] }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 174, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "owner" + }, { "kind": "object", "properties": [ @@ -2699,7 +2782,7 @@ }, { "name": "kind", - "type": 171, + "type": 176, "optional": false }, { @@ -2724,12 +2807,12 @@ }, { "name": "form", - "type": 40, + "type": 46, "optional": false }, { "name": "kind", - "type": 173, + "type": 178, "optional": false }, { @@ -2764,17 +2847,17 @@ "properties": [ { "name": "entries", - "type": 175, + "type": 180, "optional": false }, { "name": "form", - "type": 112, + "type": 115, "optional": false }, { "name": "kind", - "type": 177, + "type": 182, "optional": false }, { @@ -2787,7 +2870,7 @@ }, { "kind": "array", - "element": 176 + "element": 181 }, { "kind": "object", @@ -2814,12 +2897,12 @@ "properties": [ { "name": "form", - "type": 71, + "type": 74, "optional": false }, { "name": "kind", - "type": 179, + "type": 184, "optional": false }, { @@ -2839,22 +2922,22 @@ "properties": [ { "name": "form", - "type": 85, + "type": 88, "optional": false }, { "name": "kind", - "type": 181, + "type": 186, "optional": false }, { "name": "references", - "type": 182, + "type": 187, "optional": false }, { "name": "version", - "type": 187, + "type": 192, "optional": false } ], @@ -2866,7 +2949,7 @@ }, { "kind": "array", - "element": 183 + "element": 188 }, { "kind": "object", @@ -2878,12 +2961,12 @@ }, { "name": "capturedThroughSeq", - "type": 184, + "type": 189, "optional": false }, { "name": "compacted", - "type": 186, + "type": 191, "optional": false }, { @@ -2923,7 +3006,7 @@ }, { "name": "truncated", - "type": 186, + "type": 191, "optional": false } ], @@ -2933,7 +3016,7 @@ "kind": "union", "types": [ 20, - 185 + 190 ] }, { @@ -2948,69 +3031,6 @@ "kind": "literal", "value": 1 }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 35, - "optional": false - }, - { - "name": "kind", - "type": 46, - "optional": false - }, - { - "name": "sections", - "type": 37, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 35, - "optional": false - }, - { - "name": "kind", - "type": 48, - "optional": false - }, - { - "name": "sections", - "type": 37, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 35, - "optional": false - }, - { - "name": "kind", - "type": 50, - "optional": false - }, - { - "name": "sections", - "type": 37, - "optional": false - } - ], - "indices": [] - }, { "kind": "object", "properties": [ @@ -3207,8 +3227,8 @@ { "kind": "union", "types": [ - 202, - 203 + 204, + 205 ] }, { @@ -6571,7 +6591,7 @@ "kind": "event", "event": "developer/message", "surface": true, - "digest": "ba5b10ea77d68f4a29439a9bd2a14f6a560acf55731749d57237757cc72fbc06", + "digest": "97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c", "schema": { "root": 0, "nodes": [ @@ -6595,12 +6615,12 @@ }, { "name": "sourceEventSeqs", - "type": 200, + "type": 202, "optional": true }, { "name": "surfaceOp", - "type": 201, + "type": 203, "optional": false }, { @@ -6610,7 +6630,7 @@ }, { "name": "type", - "type": 204, + "type": 206, "optional": false } ], @@ -6984,10 +7004,10 @@ "types": [ 33, 38, - 41, + 40, + 42, 44, - 46, - 48, + 47, 50, 52, 54, @@ -6999,9 +7019,9 @@ 66, 68, 69, + 70, 71, 72, - 73, 74, 75, 76, @@ -7012,9 +7032,9 @@ 81, 82, 83, + 84, 85, 86, - 87, 88, 89, 90, @@ -7038,9 +7058,9 @@ 108, 109, 110, + 111, 112, 113, - 114, 115, 116, 117, @@ -7051,48 +7071,48 @@ 122, 123, 124, + 125, 126, - 128, + 127, + 129, 131, - 132, - 133, 134, 135, 136, + 137, 138, 139, - 140, 141, + 142, 143, 144, - 145, 146, 147, + 148, 149, - 151, + 150, 152, 154, - 156, - 164, + 155, + 157, + 159, 167, - 169, 170, 172, - 174, - 178, - 180, - 188, - 189, - 190, - 191, - 192, + 175, + 177, + 179, + 183, + 185, 193, 194, 195, 196, 197, 198, - 199 + 199, + 200, + 201 ] }, { @@ -7122,7 +7142,7 @@ }, { "kind": "literal", - "value": "user-approval" + "value": "tmux-context" }, { "kind": "array", @@ -7149,12 +7169,87 @@ "properties": [ { "name": "form", - "type": 39, + "type": 34, "optional": false }, { "name": "kind", - "type": 40, + "type": 39, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-goal" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 41, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-jobs" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 34, + "optional": false + }, + { + "name": "kind", + "type": 43, + "optional": false + }, + { + "name": "sections", + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "user-approval" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 46, "optional": false }, { @@ -7183,12 +7278,12 @@ "properties": [ { "name": "form", - "type": 42, + "type": 48, "optional": false }, { "name": "kind", - "type": 43, + "type": 49, "optional": false }, { @@ -7212,12 +7307,12 @@ "properties": [ { "name": "form", - "type": 39, + "type": 45, "optional": false }, { "name": "kind", - "type": 45, + "type": 51, "optional": false }, { @@ -7237,12 +7332,12 @@ "properties": [ { "name": "form", - "type": 39, + "type": 45, "optional": false }, { "name": "kind", - "type": 47, + "type": 53, "optional": false }, { @@ -7262,12 +7357,12 @@ "properties": [ { "name": "form", - "type": 39, + "type": 45, "optional": false }, { "name": "kind", - "type": 49, + "type": 55, "optional": false }, { @@ -7287,12 +7382,12 @@ "properties": [ { "name": "form", - "type": 39, + "type": 45, "optional": false }, { "name": "kind", - "type": 51, + "type": 57, "optional": false }, { @@ -7312,12 +7407,12 @@ "properties": [ { "name": "form", - "type": 39, + "type": 45, "optional": false }, { "name": "kind", - "type": 53, + "type": 59, "optional": false }, { @@ -7337,12 +7432,12 @@ "properties": [ { "name": "form", - "type": 39, + "type": 45, "optional": false }, { "name": "kind", - "type": 55, + "type": 61, "optional": false }, { @@ -7362,12 +7457,12 @@ "properties": [ { "name": "form", - "type": 39, + "type": 45, "optional": false }, { "name": "kind", - "type": 57, + "type": 63, "optional": false }, { @@ -7387,12 +7482,12 @@ "properties": [ { "name": "form", - "type": 39, + "type": 45, "optional": false }, { "name": "kind", - "type": 59, + "type": 65, "optional": false }, { @@ -7412,12 +7507,12 @@ "properties": [ { "name": "form", - "type": 39, + "type": 45, "optional": false }, { "name": "kind", - "type": 61, + "type": 67, "optional": false }, { @@ -7437,82 +7532,7 @@ "properties": [ { "name": "form", - "type": 39, - "optional": false - }, - { - "name": "kind", - "type": 63, - "optional": false - }, - { - "name": "summary", - "type": 7, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "tmux-context" - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 39, - "optional": false - }, - { - "name": "kind", - "type": 65, - "optional": false - }, - { - "name": "summary", - "type": 7, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "tool-goal" - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 39, - "optional": false - }, - { - "name": "kind", - "type": 67, - "optional": false - }, - { - "name": "summary", - "type": 7, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "tool-jobs" - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 39, + "type": 45, "optional": false }, { @@ -7533,13 +7553,76 @@ "properties": [ { "name": "form", - "type": 70, + "type": 45, "optional": false }, { "name": "kind", + "type": 39, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", "type": 45, "optional": false + }, + { + "name": "kind", + "type": 41, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 45, + "optional": false + }, + { + "name": "kind", + "type": 43, + "optional": false + }, + { + "name": "summary", + "type": 7, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 51, + "optional": false } ], "indices": [] @@ -7553,55 +7636,7 @@ "properties": [ { "name": "form", - "type": 70, - "optional": false - }, - { - "name": "kind", - "type": 47, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 70, - "optional": false - }, - { - "name": "kind", - "type": 49, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 70, - "optional": false - }, - { - "name": "kind", - "type": 51, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 70, + "type": 73, "optional": false }, { @@ -7617,7 +7652,7 @@ "properties": [ { "name": "form", - "type": 70, + "type": 73, "optional": false }, { @@ -7633,7 +7668,7 @@ "properties": [ { "name": "form", - "type": 70, + "type": 73, "optional": false }, { @@ -7649,7 +7684,7 @@ "properties": [ { "name": "form", - "type": 70, + "type": 73, "optional": false }, { @@ -7665,7 +7700,7 @@ "properties": [ { "name": "form", - "type": 70, + "type": 73, "optional": false }, { @@ -7681,7 +7716,7 @@ "properties": [ { "name": "form", - "type": 70, + "type": 73, "optional": false }, { @@ -7697,7 +7732,7 @@ "properties": [ { "name": "form", - "type": 70, + "type": 73, "optional": false }, { @@ -7713,7 +7748,7 @@ "properties": [ { "name": "form", - "type": 70, + "type": 73, "optional": false }, { @@ -7729,7 +7764,7 @@ "properties": [ { "name": "form", - "type": 70, + "type": 73, "optional": false }, { @@ -7745,12 +7780,60 @@ "properties": [ { "name": "form", - "type": 84, + "type": 73, "optional": false }, { "name": "kind", - "type": 45, + "type": 39, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 41, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 73, + "optional": false + }, + { + "name": "kind", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 87, + "optional": false + }, + { + "name": "kind", + "type": 51, "optional": false } ], @@ -7765,55 +7848,7 @@ "properties": [ { "name": "form", - "type": 84, - "optional": false - }, - { - "name": "kind", - "type": 47, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 84, - "optional": false - }, - { - "name": "kind", - "type": 49, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 84, - "optional": false - }, - { - "name": "kind", - "type": 51, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 84, + "type": 87, "optional": false }, { @@ -7829,7 +7864,7 @@ "properties": [ { "name": "form", - "type": 84, + "type": 87, "optional": false }, { @@ -7845,7 +7880,7 @@ "properties": [ { "name": "form", - "type": 84, + "type": 87, "optional": false }, { @@ -7861,7 +7896,7 @@ "properties": [ { "name": "form", - "type": 84, + "type": 87, "optional": false }, { @@ -7877,7 +7912,7 @@ "properties": [ { "name": "form", - "type": 84, + "type": 87, "optional": false }, { @@ -7893,7 +7928,7 @@ "properties": [ { "name": "form", - "type": 84, + "type": 87, "optional": false }, { @@ -7909,7 +7944,7 @@ "properties": [ { "name": "form", - "type": 84, + "type": 87, "optional": false }, { @@ -7925,7 +7960,7 @@ "properties": [ { "name": "form", - "type": 84, + "type": 87, "optional": false }, { @@ -7941,7 +7976,7 @@ "properties": [ { "name": "form", - "type": 84, + "type": 87, "optional": false }, { @@ -7957,12 +7992,12 @@ "properties": [ { "name": "form", - "type": 42, + "type": 87, "optional": false }, { "name": "kind", - "type": 45, + "type": 39, "optional": false } ], @@ -7973,12 +8008,12 @@ "properties": [ { "name": "form", - "type": 42, + "type": 87, "optional": false }, { "name": "kind", - "type": 47, + "type": 41, "optional": false } ], @@ -7989,12 +8024,12 @@ "properties": [ { "name": "form", - "type": 42, + "type": 87, "optional": false }, { "name": "kind", - "type": 49, + "type": 43, "optional": false } ], @@ -8005,7 +8040,7 @@ "properties": [ { "name": "form", - "type": 42, + "type": 48, "optional": false }, { @@ -8021,7 +8056,7 @@ "properties": [ { "name": "form", - "type": 42, + "type": 48, "optional": false }, { @@ -8037,7 +8072,7 @@ "properties": [ { "name": "form", - "type": 42, + "type": 48, "optional": false }, { @@ -8053,7 +8088,7 @@ "properties": [ { "name": "form", - "type": 42, + "type": 48, "optional": false }, { @@ -8069,7 +8104,7 @@ "properties": [ { "name": "form", - "type": 42, + "type": 48, "optional": false }, { @@ -8085,7 +8120,7 @@ "properties": [ { "name": "form", - "type": 42, + "type": 48, "optional": false }, { @@ -8101,7 +8136,7 @@ "properties": [ { "name": "form", - "type": 42, + "type": 48, "optional": false }, { @@ -8117,7 +8152,7 @@ "properties": [ { "name": "form", - "type": 42, + "type": 48, "optional": false }, { @@ -8133,7 +8168,7 @@ "properties": [ { "name": "form", - "type": 42, + "type": 48, "optional": false }, { @@ -8149,7 +8184,7 @@ "properties": [ { "name": "form", - "type": 42, + "type": 48, "optional": false }, { @@ -8165,12 +8200,60 @@ "properties": [ { "name": "form", - "type": 111, + "type": 48, "optional": false }, { "name": "kind", - "type": 45, + "type": 39, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 41, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 48, + "optional": false + }, + { + "name": "kind", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 51, "optional": false } ], @@ -8185,55 +8268,7 @@ "properties": [ { "name": "form", - "type": 111, - "optional": false - }, - { - "name": "kind", - "type": 47, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 111, - "optional": false - }, - { - "name": "kind", - "type": 49, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 111, - "optional": false - }, - { - "name": "kind", - "type": 51, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 111, + "type": 114, "optional": false }, { @@ -8249,7 +8284,7 @@ "properties": [ { "name": "form", - "type": 111, + "type": 114, "optional": false }, { @@ -8265,7 +8300,7 @@ "properties": [ { "name": "form", - "type": 111, + "type": 114, "optional": false }, { @@ -8281,7 +8316,7 @@ "properties": [ { "name": "form", - "type": 111, + "type": 114, "optional": false }, { @@ -8297,7 +8332,7 @@ "properties": [ { "name": "form", - "type": 111, + "type": 114, "optional": false }, { @@ -8313,7 +8348,7 @@ "properties": [ { "name": "form", - "type": 111, + "type": 114, "optional": false }, { @@ -8329,7 +8364,7 @@ "properties": [ { "name": "form", - "type": 111, + "type": 114, "optional": false }, { @@ -8345,7 +8380,7 @@ "properties": [ { "name": "form", - "type": 111, + "type": 114, "optional": false }, { @@ -8361,7 +8396,7 @@ "properties": [ { "name": "form", - "type": 111, + "type": 114, "optional": false }, { @@ -8372,6 +8407,54 @@ ], "indices": [] }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 39, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 41, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 114, + "optional": false + }, + { + "name": "kind", + "type": 43, + "optional": false + } + ], + "indices": [] + }, { "kind": "object", "properties": [ @@ -8382,7 +8465,7 @@ }, { "name": "kind", - "type": 125, + "type": 128, "optional": false }, { @@ -8407,7 +8490,7 @@ "properties": [ { "name": "kind", - "type": 127, + "type": 130, "optional": false }, { @@ -8442,7 +8525,7 @@ "properties": [ { "name": "kind", - "type": 129, + "type": 132, "optional": false }, { @@ -8457,7 +8540,7 @@ }, { "name": "replayState", - "type": 130, + "type": 133, "optional": true } ], @@ -8471,39 +8554,6 @@ "kind": "opaque", "reason": "unknown" }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 45, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 47, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 49, - "optional": false - } - ], - "indices": [] - }, { "kind": "object", "properties": [ @@ -8526,21 +8576,6 @@ ], "indices": [] }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 137, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "ptc-mode" - }, { "kind": "object", "properties": [ @@ -8579,7 +8614,7 @@ "properties": [ { "name": "kind", - "type": 142, + "type": 140, "optional": false } ], @@ -8587,7 +8622,7 @@ }, { "kind": "literal", - "value": "system-prompt" + "value": "ptc-mode" }, { "kind": "object", @@ -8622,6 +8657,21 @@ ], "indices": [] }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 145, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "system-prompt" + }, { "kind": "object", "properties": [ @@ -8633,36 +8683,6 @@ ], "indices": [] }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 148, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "tool-registry" - }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 150, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "user" - }, { "kind": "object", "properties": [ @@ -8674,6 +8694,43 @@ ], "indices": [] }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 39, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 41, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 151, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "tool-registry" + }, { "kind": "object", "properties": [ @@ -8685,6 +8742,32 @@ ], "indices": [] }, + { + "kind": "literal", + "value": "user" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 156, + "optional": false + } + ], + "indices": [] + }, { "kind": "literal", "value": "working-directory" @@ -8694,7 +8777,7 @@ "properties": [ { "name": "kind", - "type": 155, + "type": 158, "optional": false } ], @@ -8719,17 +8802,17 @@ }, { "name": "changes", - "type": 157, + "type": 160, "optional": false }, { "name": "form", - "type": 70, + "type": 73, "optional": false }, { "name": "kind", - "type": 163, + "type": 166, "optional": false } ], @@ -8737,14 +8820,14 @@ }, { "kind": "array", - "element": 158 + "element": 161 }, { "kind": "object", "properties": [ { "name": "action", - "type": 159, + "type": 162, "optional": false }, { @@ -8768,9 +8851,9 @@ { "kind": "union", "types": [ - 160, - 161, - 162 + 163, + 164, + 165 ] }, { @@ -8799,12 +8882,12 @@ }, { "name": "kind", - "type": 165, + "type": 168, "optional": false }, { "name": "outcome", - "type": 166, + "type": 169, "optional": false } ], @@ -8828,7 +8911,7 @@ }, { "name": "kind", - "type": 168, + "type": 171, "optional": false } ], @@ -8848,9 +8931,14 @@ }, { "name": "kind", - "type": 150, + "type": 153, "optional": false }, + { + "name": "principal", + "type": 173, + "optional": true + }, { "name": "rpcId", "type": 7, @@ -8859,6 +8947,21 @@ ], "indices": [] }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 174, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "owner" + }, { "kind": "object", "properties": [ @@ -8869,7 +8972,7 @@ }, { "name": "kind", - "type": 171, + "type": 176, "optional": false }, { @@ -8894,12 +8997,12 @@ }, { "name": "form", - "type": 39, + "type": 45, "optional": false }, { "name": "kind", - "type": 173, + "type": 178, "optional": false }, { @@ -8934,17 +9037,17 @@ "properties": [ { "name": "entries", - "type": 175, + "type": 180, "optional": false }, { "name": "form", - "type": 111, + "type": 114, "optional": false }, { "name": "kind", - "type": 177, + "type": 182, "optional": false }, { @@ -8957,7 +9060,7 @@ }, { "kind": "array", - "element": 176 + "element": 181 }, { "kind": "object", @@ -8984,12 +9087,12 @@ "properties": [ { "name": "form", - "type": 70, + "type": 73, "optional": false }, { "name": "kind", - "type": 179, + "type": 184, "optional": false }, { @@ -9009,22 +9112,22 @@ "properties": [ { "name": "form", - "type": 84, + "type": 87, "optional": false }, { "name": "kind", - "type": 181, + "type": 186, "optional": false }, { "name": "references", - "type": 182, + "type": 187, "optional": false }, { "name": "version", - "type": 187, + "type": 192, "optional": false } ], @@ -9036,7 +9139,7 @@ }, { "kind": "array", - "element": 183 + "element": 188 }, { "kind": "object", @@ -9048,12 +9151,12 @@ }, { "name": "capturedThroughSeq", - "type": 184, + "type": 189, "optional": false }, { "name": "compacted", - "type": 186, + "type": 191, "optional": false }, { @@ -9093,7 +9196,7 @@ }, { "name": "truncated", - "type": 186, + "type": 191, "optional": false } ], @@ -9103,7 +9206,7 @@ "kind": "union", "types": [ 2, - 185 + 190 ] }, { @@ -9118,69 +9221,6 @@ "kind": "literal", "value": 1 }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 34, - "optional": false - }, - { - "name": "kind", - "type": 45, - "optional": false - }, - { - "name": "sections", - "type": 36, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 34, - "optional": false - }, - { - "name": "kind", - "type": 47, - "optional": false - }, - { - "name": "sections", - "type": 36, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 34, - "optional": false - }, - { - "name": "kind", - "type": 49, - "optional": false - }, - { - "name": "sections", - "type": 36, - "optional": false - } - ], - "indices": [] - }, { "kind": "object", "properties": [ @@ -9377,8 +9417,8 @@ { "kind": "union", "types": [ - 202, - 203 + 204, + 205 ] }, { @@ -9395,7 +9435,7 @@ }, { "name": "op", - "type": 161, + "type": 164, "optional": false }, { @@ -10339,6 +10379,297 @@ ] } }, + { + "key": "event:job/registered", + "kind": "event", + "event": "job/registered", + "surface": false, + "digest": "f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1", + "schema": { + "root": 0, + "nodes": [ + { + "kind": "object", + "properties": [ + { + "name": "data", + "type": 1, + "optional": false + }, + { + "name": "ignorable", + "type": 5, + "optional": true + }, + { + "name": "seq", + "type": 3, + "optional": false + }, + { + "name": "time", + "type": 3, + "optional": false + }, + { + "name": "type", + "type": 6, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "jobId", + "type": 2, + "optional": false + }, + { + "name": "kind", + "type": 2, + "optional": false + }, + { + "name": "label", + "type": 2, + "optional": false + }, + { + "name": "owner", + "type": 2, + "optional": false + }, + { + "name": "startedAt", + "type": 3, + "optional": false + }, + { + "name": "toolCall", + "type": 4, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "primitive", + "type": "string" + }, + { + "kind": "primitive", + "type": "number" + }, + { + "kind": "object", + "properties": [ + { + "name": "callId", + "type": 2, + "optional": false + }, + { + "name": "rootCallId", + "type": 2, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": true + }, + { + "kind": "literal", + "value": "job/registered" + } + ] + } + }, + { + "key": "event:job/settled", + "kind": "event", + "event": "job/settled", + "surface": false, + "digest": "edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf", + "schema": { + "root": 0, + "nodes": [ + { + "kind": "object", + "properties": [ + { + "name": "data", + "type": 1, + "optional": false + }, + { + "name": "ignorable", + "type": 14, + "optional": true + }, + { + "name": "seq", + "type": 7, + "optional": false + }, + { + "name": "time", + "type": 7, + "optional": false + }, + { + "name": "type", + "type": 15, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "cause", + "type": 2, + "optional": false + }, + { + "name": "detail", + "type": 6, + "optional": true + }, + { + "name": "finishedAt", + "type": 7, + "optional": false + }, + { + "name": "jobId", + "type": 6, + "optional": false + }, + { + "name": "kind", + "type": 6, + "optional": false + }, + { + "name": "label", + "type": 6, + "optional": false + }, + { + "name": "owner", + "type": 6, + "optional": false + }, + { + "name": "producerReported", + "type": 8, + "optional": false + }, + { + "name": "startedAt", + "type": 7, + "optional": false + }, + { + "name": "status", + "type": 9, + "optional": false + }, + { + "name": "toolCall", + "type": 13, + "optional": true + } + ], + "indices": [] + }, + { + "kind": "union", + "types": [ + 3, + 4, + 5 + ] + }, + { + "kind": "literal", + "value": "producer" + }, + { + "kind": "literal", + "value": "teardown" + }, + { + "kind": "literal", + "value": "kill" + }, + { + "kind": "primitive", + "type": "string" + }, + { + "kind": "primitive", + "type": "number" + }, + { + "kind": "primitive", + "type": "boolean" + }, + { + "kind": "union", + "types": [ + 10, + 11, + 12 + ] + }, + { + "kind": "literal", + "value": "completed" + }, + { + "kind": "literal", + "value": "failed" + }, + { + "kind": "literal", + "value": "killed" + }, + { + "kind": "object", + "properties": [ + { + "name": "callId", + "type": 6, + "optional": false + }, + { + "name": "rootCallId", + "type": 6, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": true + }, + { + "kind": "literal", + "value": "job/settled" + } + ] + } + }, { "key": "event:llm/retry", "kind": "event", @@ -11890,7 +12221,7 @@ "kind": "event", "event": "session/title-llm-request", "surface": false, - "digest": "b33545b3244861bcbf73b407d24b53402710f5acacab7ae939537e5504a68dc6", + "digest": "79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056", "schema": { "root": 0, "nodes": [ @@ -11919,7 +12250,7 @@ }, { "name": "type", - "type": 210, + "type": 212, "optional": false } ], @@ -11950,7 +12281,7 @@ }, { "name": "route", - "type": 209, + "type": 211, "optional": false }, { @@ -11983,9 +12314,9 @@ "types": [ 6, 37, - 204, - 205, - 207 + 206, + 207, + 209 ] }, { @@ -12392,7 +12723,7 @@ 51, 53, 55, - 56, + 57, 58, 60, 62, @@ -12401,28 +12732,25 @@ 67, 69, 71, - 72, 73, - 76, + 75, + 77, + 78, 79, + 80, 81, - 83, - 92, - 95, - 97, + 84, + 87, + 89, 98, - 100, - 102, + 101, 104, - 109, - 111, + 106, + 108, + 110, + 115, + 117, 119, - 120, - 121, - 123, - 124, - 125, - 126, 127, 128, 129, @@ -12486,15 +12814,18 @@ 187, 188, 189, + 190, 191, 192, + 193, 194, - 197, + 195, + 196, 198, - 199, 200, - 201, - 203 + 203, + 204, + 205 ] }, { @@ -12524,7 +12855,7 @@ }, { "kind": "literal", - "value": "tool-goal" + "value": "time-context" }, { "kind": "array", @@ -12559,7 +12890,7 @@ }, { "kind": "literal", - "value": "runtime-context" + "value": "plan-mode" }, { "kind": "object", @@ -12574,7 +12905,7 @@ }, { "kind": "literal", - "value": "schedule" + "value": "ptc-mode" }, { "kind": "object", @@ -12589,7 +12920,7 @@ }, { "kind": "literal", - "value": "system-prompt" + "value": "repeat-tool-reminder" }, { "kind": "object", @@ -12604,7 +12935,7 @@ }, { "kind": "literal", - "value": "time-context" + "value": "runtime-context" }, { "kind": "object", @@ -12619,7 +12950,22 @@ }, { "kind": "literal", - "value": "tmux-context" + "value": "schedule" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 56, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "system-prompt" }, { "kind": "object", @@ -12632,21 +12978,6 @@ ], "indices": [] }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 57, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "tool-jobs" - }, { "kind": "object", "properties": [ @@ -12660,7 +12991,7 @@ }, { "kind": "literal", - "value": "tool-registry" + "value": "tmux-context" }, { "kind": "object", @@ -12675,7 +13006,7 @@ }, { "kind": "literal", - "value": "user" + "value": "tool-goal" }, { "kind": "object", @@ -12687,7 +13018,7 @@ }, { "name": "kind", - "type": 57, + "type": 59, "optional": false }, { @@ -12711,7 +13042,7 @@ }, { "kind": "literal", - "value": "user-approval" + "value": "tool-jobs" }, { "kind": "object", @@ -12726,7 +13057,7 @@ }, { "kind": "literal", - "value": "working-directory" + "value": "tool-registry" }, { "kind": "object", @@ -12741,7 +13072,7 @@ }, { "kind": "literal", - "value": "cordis-host-runner" + "value": "user" }, { "kind": "object", @@ -12754,10 +13085,76 @@ ], "indices": [] }, + { + "kind": "literal", + "value": "user-approval" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 72, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "working-directory" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 74, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "cordis-host-runner" + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 76, + "optional": false + } + ], + "indices": [] + }, { "kind": "literal", "value": "dsh-session-title-llm" }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, { "kind": "object", "properties": [ @@ -12805,12 +13202,33 @@ "properties": [ { "name": "form", - "type": 74, + "type": 41, "optional": false }, { "name": "kind", - "type": 75, + "type": 76, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 83, "optional": false }, { @@ -12839,12 +13257,12 @@ "properties": [ { "name": "form", - "type": 77, + "type": 85, "optional": false }, { "name": "kind", - "type": 78, + "type": 86, "optional": false }, { @@ -12868,12 +13286,12 @@ "properties": [ { "name": "form", - "type": 74, + "type": 82, "optional": false }, { "name": "kind", - "type": 80, + "type": 88, "optional": false }, { @@ -12888,31 +13306,6 @@ "kind": "literal", "value": "hooks-claude-code" }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 74, - "optional": false - }, - { - "name": "kind", - "type": 82, - "optional": false - }, - { - "name": "summary", - "type": 10, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "hooks-codex" - }, { "kind": "object", "properties": [ @@ -12928,17 +13321,17 @@ }, { "name": "changes", - "type": 84, - "optional": false - }, - { - "name": "form", "type": 90, "optional": false }, + { + "name": "form", + "type": 96, + "optional": false + }, { "name": "kind", - "type": 91, + "type": 97, "optional": false } ], @@ -12946,14 +13339,14 @@ }, { "kind": "array", - "element": 85 + "element": 91 }, { "kind": "object", "properties": [ { "name": "action", - "type": 86, + "type": 92, "optional": false }, { @@ -12977,9 +13370,9 @@ { "kind": "union", "types": [ - 87, - 88, - 89 + 93, + 94, + 95 ] }, { @@ -13012,12 +13405,12 @@ }, { "name": "kind", - "type": 93, + "type": 99, "optional": false }, { "name": "outcome", - "type": 94, + "type": 100, "optional": false } ], @@ -13031,31 +13424,6 @@ "kind": "literal", "value": "answered" }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 74, - "optional": false - }, - { - "name": "kind", - "type": 96, - "optional": false - }, - { - "name": "summary", - "type": 10, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "model-selection" - }, { "kind": "object", "properties": [ @@ -13066,9 +13434,14 @@ }, { "name": "kind", - "type": 61, + "type": 68, "optional": false }, + { + "name": "principal", + "type": 102, + "optional": true + }, { "name": "rpcId", "type": 10, @@ -13077,6 +13450,21 @@ ], "indices": [] }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 103, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "owner" + }, { "kind": "object", "properties": [ @@ -13087,7 +13475,7 @@ }, { "name": "kind", - "type": 99, + "type": 105, "optional": false }, { @@ -13107,12 +13495,12 @@ "properties": [ { "name": "form", - "type": 74, + "type": 82, "optional": false }, { "name": "kind", - "type": 101, + "type": 107, "optional": false }, { @@ -13125,7 +13513,7 @@ }, { "kind": "literal", - "value": "plan-mode" + "value": "hooks-codex" }, { "kind": "object", @@ -13137,12 +13525,12 @@ }, { "name": "form", - "type": 74, + "type": 82, "optional": false }, { "name": "kind", - "type": 103, + "type": 109, "optional": false }, { @@ -13177,17 +13565,17 @@ "properties": [ { "name": "entries", - "type": 105, + "type": 111, "optional": false }, { "name": "form", - "type": 107, + "type": 113, "optional": false }, { "name": "kind", - "type": 108, + "type": 114, "optional": false }, { @@ -13200,7 +13588,7 @@ }, { "kind": "array", - "element": 106 + "element": 112 }, { "kind": "object", @@ -13231,12 +13619,37 @@ "properties": [ { "name": "form", - "type": 90, + "type": 82, "optional": false }, { "name": "kind", - "type": 110, + "type": 116, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "model-selection" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 118, "optional": false }, { @@ -13256,22 +13669,22 @@ "properties": [ { "name": "form", - "type": 112, + "type": 120, "optional": false }, { "name": "kind", - "type": 113, + "type": 121, "optional": false }, { "name": "references", - "type": 114, + "type": 122, "optional": false }, { "name": "version", - "type": 118, + "type": 126, "optional": false } ], @@ -13287,7 +13700,7 @@ }, { "kind": "array", - "element": 115 + "element": 123 }, { "kind": "object", @@ -13299,7 +13712,7 @@ }, { "name": "capturedThroughSeq", - "type": 116, + "type": 124, "optional": false }, { @@ -13354,7 +13767,7 @@ "kind": "union", "types": [ 2, - 117 + 125 ] }, { @@ -13375,7 +13788,7 @@ }, { "name": "kind", - "type": 80, + "type": 88, "optional": false }, { @@ -13391,76 +13804,9 @@ "properties": [ { "name": "form", - "type": 41, - "optional": false - }, - { - "name": "kind", "type": 82, "optional": false }, - { - "name": "sections", - "type": 43, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 74, - "optional": false - }, - { - "name": "kind", - "type": 122, - "optional": false - }, - { - "name": "summary", - "type": 10, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "repeat-tool-reminder" - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 41, - "optional": false - }, - { - "name": "kind", - "type": 96, - "optional": false - }, - { - "name": "sections", - "type": 43, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 74, - "optional": false - }, { "name": "kind", "type": 46, @@ -13479,12 +13825,12 @@ "properties": [ { "name": "form", - "type": 74, + "type": 82, "optional": false }, { "name": "kind", - "type": 48, + "type": 50, "optional": false }, { @@ -13500,7 +13846,7 @@ "properties": [ { "name": "form", - "type": 74, + "type": 82, "optional": false }, { @@ -13521,7 +13867,7 @@ "properties": [ { "name": "form", - "type": 74, + "type": 82, "optional": false }, { @@ -13542,7 +13888,7 @@ "properties": [ { "name": "form", - "type": 74, + "type": 82, "optional": false }, { @@ -13563,12 +13909,12 @@ "properties": [ { "name": "form", - "type": 74, + "type": 82, "optional": false }, { "name": "kind", - "type": 57, + "type": 59, "optional": false }, { @@ -13584,7 +13930,28 @@ "properties": [ { "name": "form", - "type": 74, + "type": 82, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 82, "optional": false }, { @@ -13605,7 +13972,7 @@ "properties": [ { "name": "form", - "type": 74, + "type": 82, "optional": false }, { @@ -13626,29 +13993,18 @@ "properties": [ { "name": "form", - "type": 90, - "optional": false - }, - { - "name": "kind", - "type": 80, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 90, - "optional": false - }, - { - "name": "kind", "type": 82, "optional": false + }, + { + "name": "kind", + "type": 76, + "optional": false + }, + { + "name": "summary", + "type": 10, + "optional": false } ], "indices": [] @@ -13658,13 +14014,13 @@ "properties": [ { "name": "form", - "type": 90, - "optional": false - }, - { - "name": "kind", "type": 96, "optional": false + }, + { + "name": "kind", + "type": 88, + "optional": false } ], "indices": [] @@ -13674,12 +14030,12 @@ "properties": [ { "name": "form", - "type": 90, + "type": 96, "optional": false }, { "name": "kind", - "type": 101, + "type": 107, "optional": false } ], @@ -13690,12 +14046,12 @@ "properties": [ { "name": "form", - "type": 90, + "type": 96, "optional": false }, { "name": "kind", - "type": 122, + "type": 116, "optional": false } ], @@ -13706,7 +14062,7 @@ "properties": [ { "name": "form", - "type": 90, + "type": 96, "optional": false }, { @@ -13722,12 +14078,12 @@ "properties": [ { "name": "form", - "type": 90, + "type": 96, "optional": false }, { "name": "kind", - "type": 48, + "type": 50, "optional": false } ], @@ -13738,7 +14094,7 @@ "properties": [ { "name": "form", - "type": 90, + "type": 96, "optional": false }, { @@ -13759,7 +14115,7 @@ }, { "name": "kind", - "type": 101, + "type": 107, "optional": false }, { @@ -13775,7 +14131,7 @@ "properties": [ { "name": "form", - "type": 90, + "type": 96, "optional": false }, { @@ -13791,7 +14147,7 @@ "properties": [ { "name": "form", - "type": 90, + "type": 96, "optional": false }, { @@ -13807,12 +14163,12 @@ "properties": [ { "name": "form", - "type": 90, + "type": 96, "optional": false }, { "name": "kind", - "type": 57, + "type": 59, "optional": false } ], @@ -13823,7 +14179,23 @@ "properties": [ { "name": "form", - "type": 90, + "type": 96, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 96, "optional": false }, { @@ -13839,7 +14211,7 @@ "properties": [ { "name": "form", - "type": 90, + "type": 96, "optional": false }, { @@ -13855,45 +14227,13 @@ "properties": [ { "name": "form", - "type": 112, - "optional": false - }, - { - "name": "kind", - "type": 80, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 112, - "optional": false - }, - { - "name": "kind", - "type": 82, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 112, - "optional": false - }, - { - "name": "kind", "type": 96, "optional": false + }, + { + "name": "kind", + "type": 76, + "optional": false } ], "indices": [] @@ -13903,12 +14243,28 @@ "properties": [ { "name": "form", - "type": 112, + "type": 120, "optional": false }, { "name": "kind", - "type": 101, + "type": 88, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 107, "optional": false } ], @@ -13924,7 +14280,7 @@ }, { "name": "kind", - "type": 122, + "type": 116, "optional": false }, { @@ -13940,12 +14296,12 @@ "properties": [ { "name": "form", - "type": 112, + "type": 120, "optional": false }, { "name": "kind", - "type": 122, + "type": 116, "optional": false } ], @@ -13956,7 +14312,7 @@ "properties": [ { "name": "form", - "type": 112, + "type": 120, "optional": false }, { @@ -13972,12 +14328,12 @@ "properties": [ { "name": "form", - "type": 112, + "type": 120, "optional": false }, { "name": "kind", - "type": 48, + "type": 50, "optional": false } ], @@ -13988,7 +14344,7 @@ "properties": [ { "name": "form", - "type": 112, + "type": 120, "optional": false }, { @@ -14004,7 +14360,7 @@ "properties": [ { "name": "form", - "type": 112, + "type": 120, "optional": false }, { @@ -14020,7 +14376,7 @@ "properties": [ { "name": "form", - "type": 112, + "type": 120, "optional": false }, { @@ -14036,12 +14392,12 @@ "properties": [ { "name": "form", - "type": 112, + "type": 120, "optional": false }, { "name": "kind", - "type": 57, + "type": 59, "optional": false } ], @@ -14052,7 +14408,23 @@ "properties": [ { "name": "form", - "type": 112, + "type": 120, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 120, "optional": false }, { @@ -14063,22 +14435,6 @@ ], "indices": [] }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 112, - "optional": false - }, - { - "name": "kind", - "type": 70, - "optional": false - } - ], - "indices": [] - }, { "kind": "object", "properties": [ @@ -14105,12 +14461,12 @@ "properties": [ { "name": "form", - "type": 77, + "type": 120, "optional": false }, { "name": "kind", - "type": 80, + "type": 70, "optional": false } ], @@ -14121,12 +14477,12 @@ "properties": [ { "name": "form", - "type": 77, + "type": 120, "optional": false }, { "name": "kind", - "type": 82, + "type": 76, "optional": false } ], @@ -14137,12 +14493,12 @@ "properties": [ { "name": "form", - "type": 77, + "type": 85, "optional": false }, { "name": "kind", - "type": 96, + "type": 88, "optional": false } ], @@ -14153,12 +14509,12 @@ "properties": [ { "name": "form", - "type": 77, + "type": 85, "optional": false }, { "name": "kind", - "type": 101, + "type": 107, "optional": false } ], @@ -14169,12 +14525,12 @@ "properties": [ { "name": "form", - "type": 77, + "type": 85, "optional": false }, { "name": "kind", - "type": 122, + "type": 116, "optional": false } ], @@ -14185,7 +14541,7 @@ "properties": [ { "name": "form", - "type": 77, + "type": 85, "optional": false }, { @@ -14201,12 +14557,12 @@ "properties": [ { "name": "form", - "type": 77, + "type": 85, "optional": false }, { "name": "kind", - "type": 48, + "type": 50, "optional": false } ], @@ -14217,7 +14573,7 @@ "properties": [ { "name": "form", - "type": 77, + "type": 85, "optional": false }, { @@ -14233,7 +14589,7 @@ "properties": [ { "name": "form", - "type": 77, + "type": 85, "optional": false }, { @@ -14254,7 +14610,7 @@ }, { "name": "kind", - "type": 48, + "type": 50, "optional": false }, { @@ -14270,7 +14626,7 @@ "properties": [ { "name": "form", - "type": 77, + "type": 85, "optional": false }, { @@ -14286,12 +14642,12 @@ "properties": [ { "name": "form", - "type": 77, + "type": 85, "optional": false }, { "name": "kind", - "type": 57, + "type": 59, "optional": false } ], @@ -14302,7 +14658,23 @@ "properties": [ { "name": "form", - "type": 77, + "type": 85, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 85, "optional": false }, { @@ -14318,7 +14690,7 @@ "properties": [ { "name": "form", - "type": 77, + "type": 85, "optional": false }, { @@ -14334,12 +14706,12 @@ "properties": [ { "name": "form", - "type": 107, + "type": 85, "optional": false }, { "name": "kind", - "type": 80, + "type": 76, "optional": false } ], @@ -14350,12 +14722,12 @@ "properties": [ { "name": "form", - "type": 107, + "type": 113, "optional": false }, { "name": "kind", - "type": 82, + "type": 88, "optional": false } ], @@ -14366,12 +14738,12 @@ "properties": [ { "name": "form", - "type": 107, + "type": 113, "optional": false }, { "name": "kind", - "type": 96, + "type": 107, "optional": false } ], @@ -14382,12 +14754,12 @@ "properties": [ { "name": "form", - "type": 107, + "type": 113, "optional": false }, { "name": "kind", - "type": 101, + "type": 116, "optional": false } ], @@ -14398,23 +14770,7 @@ "properties": [ { "name": "form", - "type": 107, - "optional": false - }, - { - "name": "kind", - "type": 122, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 107, + "type": 113, "optional": false }, { @@ -14451,12 +14807,12 @@ "properties": [ { "name": "form", - "type": 107, + "type": 113, "optional": false }, { "name": "kind", - "type": 48, + "type": 50, "optional": false } ], @@ -14467,7 +14823,7 @@ "properties": [ { "name": "form", - "type": 107, + "type": 113, "optional": false }, { @@ -14483,7 +14839,7 @@ "properties": [ { "name": "form", - "type": 107, + "type": 113, "optional": false }, { @@ -14499,7 +14855,7 @@ "properties": [ { "name": "form", - "type": 107, + "type": 113, "optional": false }, { @@ -14515,12 +14871,12 @@ "properties": [ { "name": "form", - "type": 107, + "type": 113, "optional": false }, { "name": "kind", - "type": 57, + "type": 59, "optional": false } ], @@ -14531,7 +14887,23 @@ "properties": [ { "name": "form", - "type": 107, + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 61, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, "optional": false }, { @@ -14547,7 +14919,7 @@ "properties": [ { "name": "form", - "type": 107, + "type": 113, "optional": false }, { @@ -14558,6 +14930,43 @@ ], "indices": [] }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 113, + "optional": false + }, + { + "name": "kind", + "type": 76, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 41, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + }, + { + "name": "sections", + "type": 43, + "optional": false + } + ], + "indices": [] + }, { "kind": "object", "properties": [ @@ -14568,7 +14977,7 @@ }, { "name": "kind", - "type": 190, + "type": 197, "optional": false }, { @@ -14591,30 +15000,9 @@ { "kind": "object", "properties": [ - { - "name": "form", - "type": 41, - "optional": false - }, { "name": "kind", - "type": 54, - "optional": false - }, - { - "name": "sections", - "type": 43, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 193, + "type": 199, "optional": false }, { @@ -14649,7 +15037,7 @@ "properties": [ { "name": "kind", - "type": 195, + "type": 201, "optional": false }, { @@ -14664,7 +15052,7 @@ }, { "name": "replayState", - "type": 196, + "type": 202, "optional": true } ], @@ -14683,7 +15071,7 @@ "properties": [ { "name": "kind", - "type": 80, + "type": 88, "optional": false } ], @@ -14694,7 +15082,7 @@ "properties": [ { "name": "kind", - "type": 82, + "type": 107, "optional": false } ], @@ -14705,44 +15093,7 @@ "properties": [ { "name": "kind", - "type": 96, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 101, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 202, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "ptc-mode" - }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 122, + "type": 116, "optional": false } ], @@ -14763,7 +15114,7 @@ }, { "name": "role", - "type": 61, + "type": 68, "optional": false }, { @@ -14801,12 +15152,12 @@ }, { "name": "role", - "type": 206, + "type": 208, "optional": false }, { "name": "source", - "type": 194, + "type": 200, "optional": false } ], @@ -14831,12 +15182,12 @@ }, { "name": "role", - "type": 208, + "type": 210, "optional": false }, { "name": "source", - "type": 49, + "type": 55, "optional": false } ], @@ -18857,7 +19208,7 @@ "kind": "event", "event": "user/message", "surface": true, - "digest": "2ace3b8059b82b6d9837fed518ca97a99eb37c4482df7aad0e71c85489428ade", + "digest": "2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8", "schema": { "root": 0, "nodes": [ @@ -18881,12 +19232,12 @@ }, { "name": "sourceEventSeqs", - "type": 198, + "type": 200, "optional": true }, { "name": "surfaceOp", - "type": 199, + "type": 201, "optional": false }, { @@ -18896,7 +19247,7 @@ }, { "name": "type", - "type": 202, + "type": 204, "optional": false } ], @@ -19253,7 +19604,7 @@ 49, 51, 53, - 56, + 55, 58, 60, 61, @@ -19266,7 +19617,7 @@ 68, 69, 70, - 72, + 71, 73, 74, 75, @@ -19279,7 +19630,7 @@ 82, 83, 84, - 86, + 85, 87, 88, 89, @@ -19292,7 +19643,7 @@ 96, 97, 98, - 100, + 99, 101, 102, 103, @@ -19305,40 +19656,38 @@ 110, 111, 112, - 114, - 116, - 119, + 113, + 115, + 117, 120, 121, 122, 123, - 125, + 124, 126, 127, 128, - 130, + 129, 131, 132, 133, 134, - 136, + 135, 137, 138, - 140, - 142, + 139, + 141, 143, - 151, - 154, - 156, + 144, + 152, + 155, 157, - 159, - 161, - 165, - 167, - 175, - 179, - 180, - 181, + 160, + 162, + 164, + 168, + 170, + 178, 182, 183, 184, @@ -19349,10 +19698,12 @@ 189, 190, 191, + 192, 193, - 195, + 194, 196, - 197 + 198, + 199 ] }, { @@ -19382,7 +19733,7 @@ }, { "kind": "literal", - "value": "plan-mode" + "value": "model-selection" }, { "kind": "object", @@ -19405,6 +19756,31 @@ ], "indices": [] }, + { + "kind": "literal", + "value": "plan-mode" + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 33, + "optional": false + }, + { + "name": "kind", + "type": 38, + "optional": false + }, + { + "name": "summary", + "type": 5, + "optional": false + } + ], + "indices": [] + }, { "kind": "literal", "value": "repeat-tool-reminder" @@ -19419,7 +19795,7 @@ }, { "name": "kind", - "type": 38, + "type": 40, "optional": false }, { @@ -19444,7 +19820,7 @@ }, { "name": "kind", - "type": 40, + "type": 42, "optional": false }, { @@ -19469,7 +19845,7 @@ }, { "name": "kind", - "type": 42, + "type": 44, "optional": false }, { @@ -19494,7 +19870,7 @@ }, { "name": "kind", - "type": 44, + "type": 46, "optional": false }, { @@ -19519,7 +19895,7 @@ }, { "name": "kind", - "type": 46, + "type": 48, "optional": false }, { @@ -19544,7 +19920,7 @@ }, { "name": "kind", - "type": 48, + "type": 50, "optional": false }, { @@ -19569,7 +19945,7 @@ }, { "name": "kind", - "type": 50, + "type": 52, "optional": false }, { @@ -19594,7 +19970,7 @@ }, { "name": "kind", - "type": 52, + "type": 54, "optional": false }, { @@ -19614,12 +19990,12 @@ "properties": [ { "name": "form", - "type": 54, + "type": 56, "optional": false }, { "name": "kind", - "type": 55, + "type": 57, "optional": false } ], @@ -19638,12 +20014,12 @@ "properties": [ { "name": "form", - "type": 54, + "type": 56, "optional": false }, { "name": "kind", - "type": 57, + "type": 59, "optional": false } ], @@ -19658,27 +20034,7 @@ "properties": [ { "name": "form", - "type": 54, - "optional": false - }, - { - "name": "kind", - "type": 59, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "literal", - "value": "model-selection" - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 54, + "type": 56, "optional": false }, { @@ -19694,7 +20050,7 @@ "properties": [ { "name": "form", - "type": 54, + "type": 56, "optional": false }, { @@ -19710,7 +20066,7 @@ "properties": [ { "name": "form", - "type": 54, + "type": 56, "optional": false }, { @@ -19726,7 +20082,7 @@ "properties": [ { "name": "form", - "type": 54, + "type": 56, "optional": false }, { @@ -19742,7 +20098,7 @@ "properties": [ { "name": "form", - "type": 54, + "type": 56, "optional": false }, { @@ -19758,7 +20114,7 @@ "properties": [ { "name": "form", - "type": 54, + "type": 56, "optional": false }, { @@ -19774,7 +20130,7 @@ "properties": [ { "name": "form", - "type": 54, + "type": 56, "optional": false }, { @@ -19790,7 +20146,7 @@ "properties": [ { "name": "form", - "type": 54, + "type": 56, "optional": false }, { @@ -19806,7 +20162,7 @@ "properties": [ { "name": "form", - "type": 54, + "type": 56, "optional": false }, { @@ -19822,7 +20178,7 @@ "properties": [ { "name": "form", - "type": 54, + "type": 56, "optional": false }, { @@ -19838,12 +20194,28 @@ "properties": [ { "name": "form", - "type": 71, + "type": 56, "optional": false }, { "name": "kind", - "type": 55, + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 72, + "optional": false + }, + { + "name": "kind", + "type": 57, "optional": false } ], @@ -19858,23 +20230,7 @@ "properties": [ { "name": "form", - "type": 71, - "optional": false - }, - { - "name": "kind", - "type": 57, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 71, + "type": 72, "optional": false }, { @@ -19890,7 +20246,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 72, "optional": false }, { @@ -19906,7 +20262,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 72, "optional": false }, { @@ -19922,7 +20278,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 72, "optional": false }, { @@ -19938,7 +20294,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 72, "optional": false }, { @@ -19954,7 +20310,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 72, "optional": false }, { @@ -19970,7 +20326,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 72, "optional": false }, { @@ -19986,7 +20342,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 72, "optional": false }, { @@ -20002,7 +20358,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 72, "optional": false }, { @@ -20018,7 +20374,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 72, "optional": false }, { @@ -20034,7 +20390,7 @@ "properties": [ { "name": "form", - "type": 71, + "type": 72, "optional": false }, { @@ -20050,12 +20406,28 @@ "properties": [ { "name": "form", - "type": 85, + "type": 72, "optional": false }, { "name": "kind", - "type": 55, + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 86, + "optional": false + }, + { + "name": "kind", + "type": 57, "optional": false } ], @@ -20070,23 +20442,7 @@ "properties": [ { "name": "form", - "type": 85, - "optional": false - }, - { - "name": "kind", - "type": 57, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 85, + "type": 86, "optional": false }, { @@ -20102,7 +20458,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 86, "optional": false }, { @@ -20118,7 +20474,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 86, "optional": false }, { @@ -20134,7 +20490,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 86, "optional": false }, { @@ -20150,7 +20506,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 86, "optional": false }, { @@ -20166,7 +20522,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 86, "optional": false }, { @@ -20182,7 +20538,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 86, "optional": false }, { @@ -20198,7 +20554,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 86, "optional": false }, { @@ -20214,7 +20570,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 86, "optional": false }, { @@ -20230,7 +20586,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 86, "optional": false }, { @@ -20246,7 +20602,7 @@ "properties": [ { "name": "form", - "type": 85, + "type": 86, "optional": false }, { @@ -20262,12 +20618,28 @@ "properties": [ { "name": "form", - "type": 99, + "type": 86, "optional": false }, { "name": "kind", - "type": 55, + "type": 54, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 57, "optional": false } ], @@ -20282,23 +20654,7 @@ "properties": [ { "name": "form", - "type": 99, - "optional": false - }, - { - "name": "kind", - "type": 57, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 99, + "type": 100, "optional": false }, { @@ -20314,7 +20670,7 @@ "properties": [ { "name": "form", - "type": 99, + "type": 100, "optional": false }, { @@ -20330,7 +20686,7 @@ "properties": [ { "name": "form", - "type": 99, + "type": 100, "optional": false }, { @@ -20346,7 +20702,7 @@ "properties": [ { "name": "form", - "type": 99, + "type": 100, "optional": false }, { @@ -20362,7 +20718,7 @@ "properties": [ { "name": "form", - "type": 99, + "type": 100, "optional": false }, { @@ -20378,7 +20734,7 @@ "properties": [ { "name": "form", - "type": 99, + "type": 100, "optional": false }, { @@ -20394,7 +20750,7 @@ "properties": [ { "name": "form", - "type": 99, + "type": 100, "optional": false }, { @@ -20410,7 +20766,7 @@ "properties": [ { "name": "form", - "type": 99, + "type": 100, "optional": false }, { @@ -20426,7 +20782,7 @@ "properties": [ { "name": "form", - "type": 99, + "type": 100, "optional": false }, { @@ -20442,7 +20798,7 @@ "properties": [ { "name": "form", - "type": 99, + "type": 100, "optional": false }, { @@ -20458,7 +20814,7 @@ "properties": [ { "name": "form", - "type": 99, + "type": 100, "optional": false }, { @@ -20469,6 +20825,22 @@ ], "indices": [] }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 100, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + } + ], + "indices": [] + }, { "kind": "object", "properties": [ @@ -20479,7 +20851,7 @@ }, { "name": "kind", - "type": 113, + "type": 114, "optional": false }, { @@ -20504,7 +20876,7 @@ "properties": [ { "name": "kind", - "type": 115, + "type": 116, "optional": false }, { @@ -20539,7 +20911,7 @@ "properties": [ { "name": "kind", - "type": 117, + "type": 118, "optional": false }, { @@ -20554,7 +20926,7 @@ }, { "name": "replayState", - "type": 118, + "type": 119, "optional": true } ], @@ -20568,17 +20940,6 @@ "kind": "opaque", "reason": "unknown" }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 55, - "optional": false - } - ], - "indices": [] - }, { "kind": "object", "properties": [ @@ -20617,7 +20978,18 @@ "properties": [ { "name": "kind", - "type": 124, + "type": 36, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 125, "optional": false } ], @@ -20627,17 +20999,6 @@ "kind": "literal", "value": "ptc-mode" }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 36, - "optional": false - } - ], - "indices": [] - }, { "kind": "object", "properties": [ @@ -20665,7 +21026,18 @@ "properties": [ { "name": "kind", - "type": 129, + "type": 42, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 130, "optional": false } ], @@ -20675,17 +21047,6 @@ "kind": "literal", "value": "system-prompt" }, - { - "kind": "object", - "properties": [ - { - "name": "kind", - "type": 42, - "optional": false - } - ], - "indices": [] - }, { "kind": "object", "properties": [ @@ -20724,7 +21085,18 @@ "properties": [ { "name": "kind", - "type": 135, + "type": 50, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 136, "optional": false } ], @@ -20750,7 +21122,7 @@ "properties": [ { "name": "kind", - "type": 50, + "type": 52, "optional": false } ], @@ -20761,7 +21133,7 @@ "properties": [ { "name": "kind", - "type": 139, + "type": 140, "optional": false } ], @@ -20776,7 +21148,7 @@ "properties": [ { "name": "kind", - "type": 141, + "type": 142, "optional": false } ], @@ -20791,7 +21163,7 @@ "properties": [ { "name": "kind", - "type": 52, + "type": 54, "optional": false } ], @@ -20812,17 +21184,17 @@ }, { "name": "changes", - "type": 144, + "type": 145, "optional": false }, { "name": "form", - "type": 54, + "type": 56, "optional": false }, { "name": "kind", - "type": 150, + "type": 151, "optional": false } ], @@ -20830,14 +21202,14 @@ }, { "kind": "array", - "element": 145 + "element": 146 }, { "kind": "object", "properties": [ { "name": "action", - "type": 146, + "type": 147, "optional": false }, { @@ -20861,9 +21233,9 @@ { "kind": "union", "types": [ - 147, 148, - 149 + 149, + 150 ] }, { @@ -20892,12 +21264,12 @@ }, { "name": "kind", - "type": 152, + "type": 153, "optional": false }, { "name": "outcome", - "type": 153, + "type": 154, "optional": false } ], @@ -20921,7 +21293,7 @@ }, { "name": "kind", - "type": 155, + "type": 156, "optional": false } ], @@ -20944,6 +21316,11 @@ "type": 30, "optional": false }, + { + "name": "principal", + "type": 158, + "optional": true + }, { "name": "rpcId", "type": 5, @@ -20952,6 +21329,21 @@ ], "indices": [] }, + { + "kind": "object", + "properties": [ + { + "name": "kind", + "type": 159, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "literal", + "value": "owner" + }, { "kind": "object", "properties": [ @@ -20962,7 +21354,7 @@ }, { "name": "kind", - "type": 158, + "type": 161, "optional": false }, { @@ -20992,7 +21384,7 @@ }, { "name": "kind", - "type": 160, + "type": 163, "optional": false }, { @@ -21027,17 +21419,17 @@ "properties": [ { "name": "entries", - "type": 162, + "type": 165, "optional": false }, { "name": "form", - "type": 99, + "type": 100, "optional": false }, { "name": "kind", - "type": 164, + "type": 167, "optional": false }, { @@ -21050,7 +21442,7 @@ }, { "kind": "array", - "element": 163 + "element": 166 }, { "kind": "object", @@ -21077,12 +21469,12 @@ "properties": [ { "name": "form", - "type": 54, + "type": 56, "optional": false }, { "name": "kind", - "type": 166, + "type": 169, "optional": false }, { @@ -21102,22 +21494,22 @@ "properties": [ { "name": "form", - "type": 71, + "type": 72, "optional": false }, { "name": "kind", - "type": 168, + "type": 171, "optional": false }, { "name": "references", - "type": 169, + "type": 172, "optional": false }, { "name": "version", - "type": 174, + "type": 177, "optional": false } ], @@ -21129,7 +21521,7 @@ }, { "kind": "array", - "element": 170 + "element": 173 }, { "kind": "object", @@ -21141,12 +21533,12 @@ }, { "name": "capturedThroughSeq", - "type": 171, + "type": 174, "optional": false }, { "name": "compacted", - "type": 173, + "type": 176, "optional": false }, { @@ -21186,7 +21578,7 @@ }, { "name": "truncated", - "type": 173, + "type": 176, "optional": false } ], @@ -21196,7 +21588,7 @@ "kind": "union", "types": [ 18, - 172 + 175 ] }, { @@ -21216,17 +21608,17 @@ "properties": [ { "name": "form", - "type": 176, + "type": 179, "optional": false }, { "name": "kind", - "type": 55, + "type": 57, "optional": false }, { "name": "sections", - "type": 177, + "type": 180, "optional": false } ], @@ -21238,7 +21630,7 @@ }, { "kind": "array", - "element": 178 + "element": 181 }, { "kind": "object", @@ -21261,28 +21653,7 @@ "properties": [ { "name": "form", - "type": 176, - "optional": false - }, - { - "name": "kind", - "type": 57, - "optional": false - }, - { - "name": "sections", - "type": 177, - "optional": false - } - ], - "indices": [] - }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 176, + "type": 179, "optional": false }, { @@ -21292,7 +21663,7 @@ }, { "name": "sections", - "type": 177, + "type": 180, "optional": false } ], @@ -21303,7 +21674,7 @@ "properties": [ { "name": "form", - "type": 176, + "type": 179, "optional": false }, { @@ -21313,7 +21684,7 @@ }, { "name": "sections", - "type": 177, + "type": 180, "optional": false } ], @@ -21324,7 +21695,7 @@ "properties": [ { "name": "form", - "type": 176, + "type": 179, "optional": false }, { @@ -21334,7 +21705,7 @@ }, { "name": "sections", - "type": 177, + "type": 180, "optional": false } ], @@ -21345,7 +21716,7 @@ "properties": [ { "name": "form", - "type": 176, + "type": 179, "optional": false }, { @@ -21355,7 +21726,7 @@ }, { "name": "sections", - "type": 177, + "type": 180, "optional": false } ], @@ -21366,7 +21737,7 @@ "properties": [ { "name": "form", - "type": 176, + "type": 179, "optional": false }, { @@ -21376,7 +21747,7 @@ }, { "name": "sections", - "type": 177, + "type": 180, "optional": false } ], @@ -21387,7 +21758,7 @@ "properties": [ { "name": "form", - "type": 176, + "type": 179, "optional": false }, { @@ -21397,7 +21768,7 @@ }, { "name": "sections", - "type": 177, + "type": 180, "optional": false } ], @@ -21408,7 +21779,7 @@ "properties": [ { "name": "form", - "type": 176, + "type": 179, "optional": false }, { @@ -21418,7 +21789,7 @@ }, { "name": "sections", - "type": 177, + "type": 180, "optional": false } ], @@ -21429,7 +21800,7 @@ "properties": [ { "name": "form", - "type": 176, + "type": 179, "optional": false }, { @@ -21439,7 +21810,7 @@ }, { "name": "sections", - "type": 177, + "type": 180, "optional": false } ], @@ -21450,7 +21821,7 @@ "properties": [ { "name": "form", - "type": 176, + "type": 179, "optional": false }, { @@ -21460,7 +21831,7 @@ }, { "name": "sections", - "type": 177, + "type": 180, "optional": false } ], @@ -21471,7 +21842,7 @@ "properties": [ { "name": "form", - "type": 176, + "type": 179, "optional": false }, { @@ -21481,7 +21852,7 @@ }, { "name": "sections", - "type": 177, + "type": 180, "optional": false } ], @@ -21492,7 +21863,7 @@ "properties": [ { "name": "form", - "type": 176, + "type": 179, "optional": false }, { @@ -21502,7 +21873,28 @@ }, { "name": "sections", - "type": 177, + "type": 180, + "optional": false + } + ], + "indices": [] + }, + { + "kind": "object", + "properties": [ + { + "name": "form", + "type": 179, + "optional": false + }, + { + "name": "kind", + "type": 54, + "optional": false + }, + { + "name": "sections", + "type": 180, "optional": false } ], @@ -21518,7 +21910,7 @@ }, { "name": "kind", - "type": 192, + "type": 195, "optional": false }, { @@ -21543,12 +21935,12 @@ "properties": [ { "name": "form", - "type": 85, + "type": 86, "optional": false }, { "name": "kind", - "type": 194, + "type": 197, "optional": false }, { @@ -21563,27 +21955,6 @@ "kind": "literal", "value": "agent-message" }, - { - "kind": "object", - "properties": [ - { - "name": "form", - "type": 33, - "optional": false - }, - { - "name": "kind", - "type": 55, - "optional": false - }, - { - "name": "summary", - "type": 5, - "optional": false - } - ], - "indices": [] - }, { "kind": "object", "properties": [ @@ -21633,8 +22004,8 @@ { "kind": "union", "types": [ - 200, - 201 + 202, + 203 ] }, { @@ -21651,7 +22022,7 @@ }, { "name": "op", - "type": 148, + "type": 149, "optional": false }, { @@ -22012,6 +22383,15 @@ } ], "types": [ + { + "digest": "00c054d3018c198d92f459563331edd1385e58345c677bb499791df2da0ade9f", + "names": [ + "packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData" + ], + "sources": [ + "packages/session/session-title-llm/src/index.ts:37" + ] + }, { "digest": "0116b1f89c05221d56b0ba35c83d302bf4857bc7277d247e9bbaf74b27d2c66e", "names": [], @@ -22031,7 +22411,7 @@ "digest": "023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4", "names": [], "sources": [ - "packages/core/session/src/types.ts:206" + "packages/core/session/src/types.ts:207" ] }, { @@ -22047,12 +22427,12 @@ "sources": [] }, { - "digest": "045926475a46f625f84ae2be292b384817059f16927c69a9adab93717923ac19", + "digest": "040cd65423bd64264d225504f1c572d239eeb1793d0c2856ad8e42bb6e1e148b", "names": [ - "packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData" + "packages/llm/llm/src/message.ts#Message" ], "sources": [ - "packages/session/session-title-llm/src/index.ts:34" + "packages/llm/llm/src/message.ts:196" ] }, { @@ -22075,9 +22455,14 @@ "packages/core/session/src/types.ts#SessionSeq" ], "sources": [ - "packages/core/session/src/types.ts:32" + "packages/core/session/src/types.ts:33" ] }, + { + "digest": "0755b7d1128319ba2e389619cbbf2c961ad648882b4e91da7f3e9582cc8a2034", + "names": [], + "sources": [] + }, { "digest": "07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235", "names": [ @@ -22112,7 +22497,7 @@ "digest": "0a30c3be336cdd4f8f34e66543a3d46d611c43986edd9b3ce6cbb9b721d3b5d3", "names": [], "sources": [ - "packages/core/session/src/types.ts:204" + "packages/core/session/src/types.ts:205" ] }, { @@ -22131,7 +22516,7 @@ "packages/llm/llm/src/types.ts#ReplayEnvelope" ], "sources": [ - "packages/llm/llm/src/types.ts:430" + "packages/llm/llm/src/types.ts:446" ] }, { @@ -22152,7 +22537,7 @@ "digest": "0bcfaf5566d271028429ac7b562cb59053c9d78b8ae14708c35fac835108d1b1", "names": [], "sources": [ - "packages/experimental/agent-team/src/types.ts:238" + "packages/experimental/agent-team/src/types.ts:236" ] }, { @@ -22208,6 +22593,15 @@ "packages/attachment/attachment/src/types.ts:28" ] }, + { + "digest": "0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7", + "names": [ + "packages/llm/llm/src/message.ts#DeveloperMessage" + ], + "sources": [ + "packages/llm/llm/src/message.ts:157" + ] + }, { "digest": "0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce", "names": [], @@ -22327,7 +22721,7 @@ "digest": "17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3", "names": [], "sources": [ - "packages/core/session/src/types.ts:427" + "packages/core/session/src/types.ts:428" ] }, { @@ -22384,7 +22778,7 @@ "packages/core/session/src/types.ts#SessionHeader" ], "sources": [ - "packages/core/session/src/types.ts:94" + "packages/core/session/src/types.ts:95" ] }, { @@ -22418,7 +22812,7 @@ "digest": "1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d", "names": [], "sources": [ - "packages/core/session/src/types.ts:341" + "packages/core/session/src/types.ts:342" ] }, { @@ -22497,16 +22891,7 @@ "packages/core/session/src/types.ts#TurnEndCancelCause" ], "sources": [ - "packages/core/session/src/types.ts:196" - ] - }, - { - "digest": "1fa156c85450ca31063d0e0d2853028e6dac9687f2d3191fa811648210118154", - "names": [ - "packages/llm/llm/src/message.ts#MessageSource" - ], - "sources": [ - "packages/llm/llm/src/message.ts:136" + "packages/core/session/src/types.ts:197" ] }, { @@ -22532,7 +22917,7 @@ "packages/experimental/agent-team/src/types.ts#TeamMessageSource" ], "sources": [ - "packages/experimental/agent-team/src/types.ts:137" + "packages/experimental/agent-team/src/types.ts:138" ] }, { @@ -22567,6 +22952,11 @@ "names": [], "sources": [] }, + { + "digest": "24a8188c4d61b70a01af8cc576748765d36f132632ec55c0064f6fba482369fc", + "names": [], + "sources": [] + }, { "digest": "24b10f7cdae64928f89c49afc2eca0af9eb4a2f135e16f3416e6b8461fef1748", "names": [], @@ -22652,11 +23042,11 @@ "digest": "2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095", "names": [], "sources": [ - "packages/llm/llm/src/types.ts:455" + "packages/llm/llm/src/types.ts:471" ] }, { - "digest": "2ace3b8059b82b6d9837fed518ca97a99eb37c4482df7aad0e71c85489428ade", + "digest": "2ae8594a998c9862a597129e782277bcc518266712a703b5c3161bdf552d13b8", "names": [], "sources": [] }, @@ -22675,6 +23065,15 @@ "names": [], "sources": [] }, + { + "digest": "2cf075b013d363ad743b5a4982900678d108499c721bc11255137402003db711", + "names": [ + "packages/llm/llm/src/message.ts#UserMessage" + ], + "sources": [ + "packages/llm/llm/src/message.ts:162" + ] + }, { "digest": "2d11ca7b0d4493e244b74eba093227866b33249841e59a1e9bf56afed38604c3", "names": [], @@ -22707,7 +23106,7 @@ "packages/experimental/agent-team/src/types.ts#TeamMessageSnapshot" ], "sources": [ - "packages/experimental/agent-team/src/types.ts:128" + "packages/experimental/agent-team/src/types.ts:129" ] }, { @@ -22733,11 +23132,6 @@ "packages/core/tools/src/types.ts:12" ] }, - { - "digest": "2fef90def36aa758ca096c5f6ad0e00dbb2101943e19ca54b05618801974894a", - "names": [], - "sources": [] - }, { "digest": "30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f", "names": [ @@ -22790,9 +23184,14 @@ "packages/core/session/src/types.ts#SurfaceOp" ], "sources": [ - "packages/core/session/src/types.ts:462" + "packages/core/session/src/types.ts:463" ] }, + { + "digest": "347de3380f2da308d0c74e08821f9e85559f55af4c5010795b110d00f7fc9dbd", + "names": [], + "sources": [] + }, { "digest": "34d1ab5c5df378186d6054b1a1beea9a41e41965d6f336f0bc0025c441a82e66", "names": [], @@ -22851,6 +23250,15 @@ "packages/feedback/message-feedback/src/types.ts:17" ] }, + { + "digest": "39cf2d3ff8bac81c62d49ac2ba38a095b18e80f3ad700819fa1f650a4e60197f", + "names": [ + "packages/jobs/jobs/src/types.ts#JobToolCall" + ], + "sources": [ + "packages/jobs/jobs/src/types.ts:16" + ] + }, { "digest": "3b04790e08b35241ffa0d38f6d7e4f8788aa921341f6c0d7574a329397c59408", "names": [], @@ -22877,7 +23285,7 @@ "packages/core/session/src/types.ts#OptionalSessionSeq" ], "sources": [ - "packages/core/session/src/types.ts:65" + "packages/core/session/src/types.ts:66" ] }, { @@ -22889,7 +23297,7 @@ "digest": "3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90", "names": [], "sources": [ - "packages/llm/llm/src/types.ts:453" + "packages/llm/llm/src/types.ts:469" ] }, { @@ -23000,6 +23408,11 @@ "names": [], "sources": [] }, + { + "digest": "454a0fa879e38076bdcdbd87ef561cd67d7e43e58a287cf7dbaa7b6cf7847020", + "names": [], + "sources": [] + }, { "digest": "45f2a07ea94573123b6ae14db787a40062dec3834f36d8be92c523d40ba28448", "names": [], @@ -23025,7 +23438,7 @@ "packages/llm/llm/src/types.ts#StreamChunk" ], "sources": [ - "packages/llm/llm/src/types.ts:452" + "packages/llm/llm/src/types.ts:468" ] }, { @@ -23101,14 +23514,9 @@ "digest": "4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db", "names": [], "sources": [ - "packages/core/session/src/types.ts:193" + "packages/core/session/src/types.ts:194" ] }, - { - "digest": "4be8fd28fefa5534675ea9aabd0a24efc2838b989bbc74da20a1efbd0daede8c", - "names": [], - "sources": [] - }, { "digest": "4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b", "names": [ @@ -23126,6 +23534,7 @@ "packages/goal/goal/src/types.ts#GoalId", "packages/interaction/commands/src/brand.ts#CommandId", "packages/interaction/user-approval/src/types.ts#ApprovalRequestId", + "packages/jobs/jobs/src/brand.ts#JobId", "packages/llm/llm-retry/src/brand.ts#RetryId", "packages/llm/llm/src/brand.ts#MessageId", "packages/llm/llm/src/brand.ts#ProviderRequestId", @@ -23137,13 +23546,13 @@ "packages/workflow/workflow/src/types.ts#WorkflowRunId" ], "sources": [ - "packages/api/session-controller/src/types.ts:398", + "packages/api/session-controller/src/types.ts:409", "packages/attachment/attachment/src/brand.ts:6", "packages/compaction/compaction/src/brand.ts:4", - "packages/core/session/src/types.ts:20", - "packages/experimental/agent-team/src/types.ts:20", - "packages/experimental/agent-team/src/types.ts:32", - "packages/experimental/agent-team/src/types.ts:8", + "packages/core/session/src/types.ts:21", + "packages/experimental/agent-team/src/types.ts:21", + "packages/experimental/agent-team/src/types.ts:33", + "packages/experimental/agent-team/src/types.ts:9", "packages/experimental/webhook/src/brand.ts:12", "packages/experimental/webhook/src/brand.ts:6", "packages/experimental/webhook/src/brand.ts:9", @@ -23151,6 +23560,7 @@ "packages/goal/goal/src/types.ts:17", "packages/interaction/commands/src/brand.ts:31", "packages/interaction/user-approval/src/types.ts:17", + "packages/jobs/jobs/src/brand.ts:19", "packages/llm/llm-retry/src/brand.ts:4", "packages/llm/llm/src/brand.ts:16", "packages/llm/llm/src/brand.ts:31", @@ -23234,7 +23644,7 @@ "packages/experimental/agent-team/src/types.ts#TeamTaskSnapshot" ], "sources": [ - "packages/experimental/agent-team/src/types.ts:74" + "packages/experimental/agent-team/src/types.ts:75" ] }, { @@ -23258,7 +23668,7 @@ "digest": "5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777", "names": [], "sources": [ - "packages/core/session/src/types.ts:375" + "packages/core/session/src/types.ts:376" ] }, { @@ -23267,7 +23677,7 @@ "packages/core/session/src/types.ts#RequestHeaderReason" ], "sources": [ - "packages/core/session/src/types.ts:273" + "packages/core/session/src/types.ts:274" ] }, { @@ -23284,7 +23694,7 @@ "digest": "54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0", "names": [], "sources": [ - "packages/core/session/src/types.ts:355" + "packages/core/session/src/types.ts:356" ] }, { @@ -23301,7 +23711,7 @@ "digest": "56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23", "names": [], "sources": [ - "packages/core/session/src/types.ts:221" + "packages/core/session/src/types.ts:222" ] }, { @@ -23363,13 +23773,6 @@ "names": [], "sources": [] }, - { - "digest": "5b55817a403569fbb2d379496df2e3f3f71107f6c577a218028ce187c60b61e6", - "names": [], - "sources": [ - "packages/core/session/src/types.ts:311" - ] - }, { "digest": "5b6fb1f226ff56402db08a6aae82af76100b14056271875f69ec526a1ae05d51", "names": [], @@ -23382,6 +23785,15 @@ "names": [], "sources": [] }, + { + "digest": "5bc2d7f02503fc6b3e1bb7e0b7fa22c0b9e4b9841fa3175b2ad8e607ae3525a8", + "names": [ + "packages/llm/llm/src/message.ts#MessageSource" + ], + "sources": [ + "packages/llm/llm/src/message.ts:136" + ] + }, { "digest": "5bc66269cfaf614c0ecda8ecb469f23101a7609793fc2b693ac23c4aecdb575e", "names": [], @@ -23397,6 +23809,11 @@ "names": [], "sources": [] }, + { + "digest": "5cb63db9fe57dc09c3a1c2b84c3edf73ff5b62960155d8436a2377a5c43ce32c", + "names": [], + "sources": [] + }, { "digest": "5cdbf342b7748d152bc987b68f58e565e5bba4b227e076e2d2120d87662e45cd", "names": [], @@ -23472,6 +23889,15 @@ "names": [], "sources": [] }, + { + "digest": "611d82d2dc50df706cf08a0fc04bc8eaf78083391fe6f10313de943e615dd2da", + "names": [ + "packages/jobs/jobs/src/types.ts#JobSettledData" + ], + "sources": [ + "packages/jobs/jobs/src/types.ts:40" + ] + }, { "digest": "616f93a5047de668e1c30d57b1786abd76beeb4123599637ec1dc5290320ede5", "names": [], @@ -23507,7 +23933,7 @@ "packages/experimental/agent-team/src/types.ts#TeamMemberSnapshot" ], "sources": [ - "packages/experimental/agent-team/src/types.ts:47" + "packages/experimental/agent-team/src/types.ts:48" ] }, { @@ -23525,7 +23951,7 @@ "packages/llm/llm/src/types.ts#ToolSchema" ], "sources": [ - "packages/llm/llm/src/types.ts:473" + "packages/llm/llm/src/types.ts:489" ] }, { @@ -23578,13 +24004,6 @@ "names": [], "sources": [] }, - { - "digest": "6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7", - "names": [], - "sources": [ - "packages/api/session-controller/src/types.ts:403" - ] - }, { "digest": "6ab45ac76839722df912f3ba50f1c6b41f2d614bde11f1aabfae04117ccdc80d", "names": [], @@ -23608,14 +24027,14 @@ "digest": "6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5", "names": [], "sources": [ - "packages/core/session/src/types.ts:330" + "packages/core/session/src/types.ts:331" ] }, { "digest": "6c03546143cdf6ae88f1745ac98c5139efa1588d1415249bbc5f3104d32ab800", "names": [], "sources": [ - "packages/core/session/src/types.ts:191" + "packages/core/session/src/types.ts:192" ] }, { @@ -23627,7 +24046,7 @@ "digest": "6c5a37d42ebdb12db4410699259335f1e149e3a0260425684c00b153afc8990d", "names": [], "sources": [ - "packages/core/session/src/types.ts:192" + "packages/core/session/src/types.ts:193" ] }, { @@ -23640,11 +24059,23 @@ "names": [], "sources": [] }, + { + "digest": "6cf082d0fb6034dea61636787ff0ddf43b6e59aad71e644435a479bc9b83ad65", + "names": [], + "sources": [] + }, + { + "digest": "6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def", + "names": [], + "sources": [ + "packages/api/session-controller/src/types.ts:418" + ] + }, { "digest": "6e52dd55a1d48954ed5464ec46fe34d9eb65f709baabc9561e7a279910b0c406", "names": [], "sources": [ - "packages/preset/agent-preset-registry/src/session.ts:28" + "packages/preset/agent-preset-registry/src/session.ts:31" ] }, { @@ -23731,6 +24162,15 @@ "names": [], "sources": [] }, + { + "digest": "750a2b129d67704df675c06823c20c80b65cbae89d5aaa914fd5a72e3df395b5", + "names": [ + "packages/jobs/jobs/src/types.ts#JobSettleCause" + ], + "sources": [ + "packages/jobs/jobs/src/types.ts:247" + ] + }, { "digest": "7554565be416b0342053ee6a46256c9dab07c487349b4a5f10bab1edc151c619", "names": [], @@ -23765,9 +24205,14 @@ "digest": "79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985", "names": [], "sources": [ - "packages/core/session/src/types.ts:212" + "packages/core/session/src/types.ts:213" ] }, + { + "digest": "79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056", + "names": [], + "sources": [] + }, { "digest": "79ddc907312f97cf9553d4841e8b3fc937097bd8d97900a790efad3c05255e99", "names": [], @@ -23929,13 +24374,6 @@ "names": [], "sources": [] }, - { - "digest": "83a665476a9ee9af05cb1fdded12dd647d1b97b491200d7f12ef1af7cdac4428", - "names": [], - "sources": [ - "packages/core/agent/src/types.ts:96" - ] - }, { "digest": "83d6916021eede8f2d83a1872716caa1efdec39a3681890996c55147187fdd12", "names": [], @@ -24035,16 +24473,7 @@ "digest": "88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a", "names": [], "sources": [ - "packages/llm/llm/src/types.ts:456" - ] - }, - { - "digest": "89b2edff547be1ecfcd78ef18aeeb3cf507fcbf7d6093ec04fb111ef4c8e8a97", - "names": [ - "packages/llm/llm/src/message.ts#UserMessage" - ], - "sources": [ - "packages/llm/llm/src/message.ts:162" + "packages/llm/llm/src/types.ts:472" ] }, { @@ -24202,9 +24631,14 @@ "digest": "95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65", "names": [], "sources": [ - "packages/llm/llm/src/types.ts:454" + "packages/llm/llm/src/types.ts:470" ] }, + { + "digest": "95a3ffccbf3c8afcf9a2f3b355f724da8e07e98dc47ee741166dde7f9ea058bd", + "names": [], + "sources": [] + }, { "digest": "95c0e88fcf0bafb2087f912ad9e2369de6ae6530cc0c4c2772c96205b57f7f60", "names": [], @@ -24229,6 +24663,11 @@ "packages/core/agent/src/types.ts:39" ] }, + { + "digest": "97e0162f983c27456ec71269fb4976b1851588b8c1aeac5d071d43e11f95e03c", + "names": [], + "sources": [] + }, { "digest": "9890113e97dd3541787bfe6704f2b223d3a890b5325ca0acae2b0398909b413e", "names": [], @@ -24268,11 +24707,6 @@ "packages/web/web-search-deepseek/src/provider.ts:64" ] }, - { - "digest": "9a36727716d0e73f681f3b725e7f28f89417c68174c8af0ff2b1ef52b08326a0", - "names": [], - "sources": [] - }, { "digest": "9a410ddf56792b2b7cd4a224a2e54dc4dee30a8e8e6b1c2b9a1d19992b217adc", "names": [ @@ -24288,7 +24722,7 @@ "packages/core/session/src/types.ts#EpochHeader" ], "sources": [ - "packages/core/session/src/types.ts:240" + "packages/core/session/src/types.ts:241" ] }, { @@ -24390,7 +24824,7 @@ "digest": "a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1", "names": [], "sources": [ - "packages/llm/llm/src/types.ts:459" + "packages/llm/llm/src/types.ts:475" ] }, { @@ -24417,7 +24851,7 @@ "digest": "a40d12070f6f4a124f32fb3cc86e7857554702e32f0eda3080a25c4b9ac9b18c", "names": [], "sources": [ - "packages/experimental/agent-team/src/types.ts:234" + "packages/experimental/agent-team/src/types.ts:232" ] }, { @@ -24457,7 +24891,7 @@ "digest": "a81059ca06999da1e712414520c2c65e491d052fcf9640fae20aa38f0a5dc735", "names": [], "sources": [ - "packages/core/session/src/types.ts:383", + "packages/core/session/src/types.ts:384", "packages/core/tools/src/types.ts:27" ] }, @@ -24487,6 +24921,11 @@ "packages/schedule/schedule/src/types.ts:173" ] }, + { + "digest": "a927d444c928ac0efd9dd8b2e7d7d04d711c264cb71578d81e0e2fd143ff669f", + "names": [], + "sources": [] + }, { "digest": "a99ec0993c62c058e50af9f68922202a3b54f5e259bc2abf1915a73381d2316d", "names": [], @@ -24539,7 +24978,7 @@ "digest": "ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7", "names": [], "sources": [ - "packages/core/session/src/types.ts:214", + "packages/core/session/src/types.ts:215", "packages/llm/llm/src/types.ts:159" ] }, @@ -24552,7 +24991,7 @@ "digest": "ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585", "names": [], "sources": [ - "packages/core/session/src/types.ts:390" + "packages/core/session/src/types.ts:391" ] }, { @@ -24576,7 +25015,7 @@ "packages/interaction/commands/src/types.ts#CommandSource" ], "sources": [ - "packages/core/session/src/types.ts:190", + "packages/core/session/src/types.ts:191", "packages/interaction/commands/src/types.ts:75", "packages/interaction/commands/src/types.ts:79", "packages/llm/llm/src/message.ts:111", @@ -24608,15 +25047,6 @@ "names": [], "sources": [] }, - { - "digest": "af99c95d46bed802870f1ebefe0ea11f92a03cb37b8e0cbe3f94b7aaaf509b08", - "names": [ - "packages/llm/llm/src/message.ts#DeveloperMessage" - ], - "sources": [ - "packages/llm/llm/src/message.ts:157" - ] - }, { "digest": "aff60ef947c18b012644852bdd0d5bfe72065e061dd563787c76c646b4a10f6b", "names": [], @@ -24647,7 +25077,7 @@ "packages/core/session/src/types.ts#RequestContext" ], "sources": [ - "packages/core/session/src/types.ts:254" + "packages/core/session/src/types.ts:255" ] }, { @@ -24659,7 +25089,7 @@ "digest": "b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1", "names": [], "sources": [ - "packages/experimental/agent-team/src/types.ts:232" + "packages/experimental/agent-team/src/types.ts:230" ] }, { @@ -24688,14 +25118,9 @@ "packages/experimental/agent-team/src/types.ts#TeamTaskStatus" ], "sources": [ - "packages/experimental/agent-team/src/types.ts:71" + "packages/experimental/agent-team/src/types.ts:72" ] }, - { - "digest": "b33545b3244861bcbf73b407d24b53402710f5acacab7ae939537e5504a68dc6", - "names": [], - "sources": [] - }, { "digest": "b3681c026a0b98e98b103f057dfd217fbe904129c090efd668253ec9aea7fece", "names": [], @@ -24763,7 +25188,7 @@ "digest": "b6ef9c6210be8350cd465f485cf520031fffa6bf3809c61a1e713e834c5982d0", "names": [], "sources": [ - "packages/core/session/src/types.ts:202" + "packages/core/session/src/types.ts:203" ] }, { @@ -24842,12 +25267,12 @@ "sources": [] }, { - "digest": "ba5b10ea77d68f4a29439a9bd2a14f6a560acf55731749d57237757cc72fbc06", + "digest": "ba77b58995e36f14bb13886b0493d0a1a63d5db10b1a6cd9f6ac65a72cf832ec", "names": [], "sources": [] }, { - "digest": "ba77b58995e36f14bb13886b0493d0a1a63d5db10b1a6cd9f6ac65a72cf832ec", + "digest": "bab68657940075483f086fffb711682a45bcc99c43d659fbe1c36af21ac05dd7", "names": [], "sources": [] }, @@ -24880,7 +25305,7 @@ "digest": "bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825", "names": [], "sources": [ - "packages/core/session/src/types.ts:464" + "packages/core/session/src/types.ts:465" ] }, { @@ -24939,6 +25364,11 @@ "packages/workflow/workflow/src/types.ts:110" ] }, + { + "digest": "c2f49004d9ae38a964e80850c87bc6849d6a872091a1d43e99eedf00c641e2a3", + "names": [], + "sources": [] + }, { "digest": "c43b119ce579b3e9983a0d3adc4ba402ebb9ba773d89738a2dab01ecf5813943", "names": [], @@ -25076,7 +25506,7 @@ "digest": "d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d", "names": [], "sources": [ - "packages/llm/llm/src/types.ts:457" + "packages/llm/llm/src/types.ts:473" ] }, { @@ -25114,15 +25544,6 @@ "names": [], "sources": [] }, - { - "digest": "d901c4f5e856591c3217af983caa15bba568d580700f0958bab56b88004eced9", - "names": [ - "packages/llm/llm/src/message.ts#Message" - ], - "sources": [ - "packages/llm/llm/src/message.ts:196" - ] - }, { "digest": "d9196086e41e4dd5c2ce87f5c25529c8112a1731d258cf0728747d41a9ee3241", "names": [], @@ -25173,7 +25594,7 @@ "digest": "dba54c09c6e7aafc9acbed7792ecc920d99f92d0784aeeed10af55f7fe0bc8cd", "names": [], "sources": [ - "packages/core/tools/src/ptc.ts:14" + "packages/core/tools/src/ptc.ts:15" ] }, { @@ -25211,6 +25632,16 @@ "names": [], "sources": [] }, + { + "digest": "deebfc7c62177ea840f23c6362b8615bc78ffa93377dd5d243c04e541c413af5", + "names": [ + "packages/typert/protocol/src/types.ts#Principal" + ], + "sources": [ + "packages/typert/protocol/src/types.ts:457", + "packages/typert/protocol/src/types.ts:461" + ] + }, { "digest": "df5d9709b7db2a72510dc52052a23f0c38f39730af1504bab8bccabc14fae528", "names": [], @@ -25227,7 +25658,7 @@ "packages/experimental/agent-team/src/types.ts#TeamMemberPhase" ], "sources": [ - "packages/experimental/agent-team/src/types.ts:44" + "packages/experimental/agent-team/src/types.ts:45" ] }, { @@ -25250,6 +25681,15 @@ "names": [], "sources": [] }, + { + "digest": "e3056e0dda3a379e895386e368c3ce42131460ea65e410e1d091cca98a347305", + "names": [ + "packages/jobs/jobs/src/types.ts#JobRegisteredData" + ], + "sources": [ + "packages/jobs/jobs/src/types.ts:24" + ] + }, { "digest": "e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72", "names": [], @@ -25284,14 +25724,14 @@ "digest": "e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654", "names": [], "sources": [ - "packages/core/session/src/types.ts:297" + "packages/core/session/src/types.ts:298" ] }, { "digest": "e4c18e294232c3ba6c9f1999f168263cc55956147cfe4121720899be8e52edd1", "names": [], "sources": [ - "packages/core/session/src/types.ts:361" + "packages/core/session/src/types.ts:362" ] }, { @@ -25359,14 +25799,14 @@ "digest": "ea08ec1df0c33108fd03345b9af199cf04dea450aa045d3c683f216311403403", "names": [], "sources": [ - "packages/experimental/agent-team/src/types.ts:236" + "packages/experimental/agent-team/src/types.ts:234" ] }, { "digest": "eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c", "names": [], "sources": [ - "packages/core/session/src/types.ts:196" + "packages/core/session/src/types.ts:197" ] }, { @@ -25383,7 +25823,7 @@ "digest": "ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7", "names": [], "sources": [ - "packages/core/session/src/types.ts:228" + "packages/core/session/src/types.ts:229" ] }, { @@ -25391,6 +25831,11 @@ "names": [], "sources": [] }, + { + "digest": "edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf", + "names": [], + "sources": [] + }, { "digest": "ee577a0cc18664c9daee50e9455153321155604f8f1817362f8f4a4b6fb9e1ad", "names": [], @@ -25414,10 +25859,15 @@ "digest": "ef11a3b7fa2033ae4279545ff8a8a2ee4e301b9b73e5b91654c48e6d08283545", "names": [], "sources": [ - "packages/core/session/src/types.ts:299", - "packages/core/session/src/types.ts:301" + "packages/core/session/src/types.ts:300", + "packages/core/session/src/types.ts:302" ] }, + { + "digest": "ef226a90ddac6cd8e631a3a337a3a3e27f9494be92befb7c718b404681d75e21", + "names": [], + "sources": [] + }, { "digest": "ef4f00923b9edbae15c7ef05320280bf61147ca17146cf59690359bfd5e5da45", "names": [], @@ -25434,7 +25884,7 @@ "packages/api/session-controller/src/types.ts#ModelSelection" ], "sources": [ - "packages/api/session-controller/src/types.ts:100" + "packages/api/session-controller/src/types.ts:101" ] }, { @@ -25443,7 +25893,7 @@ "packages/core/session/src/types.ts#TurnEndReason" ], "sources": [ - "packages/core/session/src/types.ts:232" + "packages/core/session/src/types.ts:233" ] }, { @@ -25464,7 +25914,7 @@ "digest": "f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515", "names": [], "sources": [ - "packages/llm/llm/src/types.ts:458" + "packages/llm/llm/src/types.ts:474" ] }, { @@ -25492,7 +25942,7 @@ "packages/llm/llm/src/types.ts#SystemPromptUpdate" ], "sources": [ - "packages/llm/llm/src/types.ts:396" + "packages/llm/llm/src/types.ts:412" ] }, { @@ -25500,6 +25950,18 @@ "names": [], "sources": [] }, + { + "digest": "f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb", + "names": [], + "sources": [ + "packages/core/session/src/types.ts:312" + ] + }, + { + "digest": "f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1", + "names": [], + "sources": [] + }, { "digest": "f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f", "names": [ @@ -25567,7 +26029,7 @@ "digest": "f90eb4ab2d3897bc20c521a038e3119d581f791ec974b1a0004f63a8ab9e232d", "names": [], "sources": [ - "packages/core/session/src/types.ts:288", + "packages/core/session/src/types.ts:289", "packages/deliverables/workspace-changes/src/types.ts:106" ] }, @@ -25581,6 +26043,13 @@ "names": [], "sources": [] }, + { + "digest": "fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42", + "names": [], + "sources": [ + "packages/core/agent/src/types.ts:96" + ] + }, { "digest": "fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be", "names": [ diff --git a/docs/session-format-status.i18n.yaml b/docs/session-format-status.i18n.yaml index ef3b64d39c..0f82e86719 100644 --- a/docs/session-format-status.i18n.yaml +++ b/docs/session-format-status.i18n.yaml @@ -15,14 +15,14 @@ en: 02d18ba8a66cfb10 zh: 54b753bbcb8f8a9e /session-format-version-and-release-status/finalization-record: - en: 15b6134dcb3a09d5 - zh: 4260c82e79baa021 + en: c84a45a0489804c9 + zh: 4f4474a678c90ffe /session-format-version-and-release-status/release-record: en: 83ce79a241b630d7 zh: 53f3c461ef731f67 /session-format-version-and-release-status/updating-the-record: - en: 7eaa730a2d163bd6 - zh: 53ed7618537db2f5 + en: 0d6e8f65604b1394 + zh: 0c8dd27ad4d37649 /session-format-version-and-release-status/dev-note: en: b75c8458928b72b9 zh: 003ba4e17b4b5269 diff --git a/docs/session-format-status.md b/docs/session-format-status.md index 78b6701095..9cfc59b643 100644 --- a/docs/session-format-status.md +++ b/docs/session-format-status.md @@ -32,7 +32,7 @@ The [format references](persistence-changes/historical-formats/README.md) docume latestFinalizedVersion: 4 ``` -V4 has an accepted compatibility baseline in the [checkpoint](persistence-changes/finalized/v4.json). Backward-compatible schema changes may remain V4 through new acknowledgement records. Breaking changes require a higher writer version and their own header transition; they cannot reuse the accepted 3→4 transition. Accepted machine records and after schemas remain immutable. [Checkpoint rules](persistence-changes/README.md#compatibility-rules) define the comparison. +V4 has an accepted compatibility baseline in the [checkpoint](persistence-changes/finalized/v4.json). Schema changes may remain V4 when the [reader-compatibility rules](persistence-changes/README.md#compatibility-rules) are satisfied and the required review is recorded. A version-bump decision requires a higher writer version and its own header transition; it cannot reuse the accepted 3→4 transition. Accepted machine records and after schemas remain immutable. Finalization does not freeze every future V4 addition and does not assert publication. The release record below retains the independently verified published version. Ordinary comments, aliases, source locations, and implementation fixes preserving the accepted meaning do not change this baseline. @@ -51,7 +51,7 @@ Evidence: published product tag `dsh-v0.2.0-rc.2`; tagged writer: `packages/core ## Updating the record -When a structural writer change is implemented, update the code constant and adjacent catalog together; do not advance this release record before publication. When a product release first publishes a higher Session format, confirm publication and its tagged writer, then advance this record and the evidence tag and tagged writer path in the same bilingual update. Later product releases carrying the same format do not require changing the record. Never lower it on the development trunk. +When a Session format bump is implemented, update the code constant and adjacent catalog together; do not advance this release record before publication. When a product release first publishes a higher Session format, confirm publication and its tagged writer, then advance this record and the evidence tag and tagged writer path in the same bilingual update. Later product releases carrying the same format do not require changing the record. Never lower it on the development trunk. The [documentation-standard test](../scripts/doc-standard.spec.ts) checks record structure, bilingual equality, evidence-tag and writer-path consistency, and that the documented release does not exceed the checkout writer. This keyless check does not query GitHub or prove that the record is up to date; publication verification remains part of the release update. diff --git a/docs/session-format-status.zh.md b/docs/session-format-status.zh.md index 141917a63c..0317995c67 100644 --- a/docs/session-format-status.zh.md +++ b/docs/session-format-status.zh.md @@ -32,7 +32,7 @@ latestFinalizedVersion: 4 ``` -V4 的已接受兼容性基线保存在[检查点](persistence-changes/finalized/v4.json)中。向后兼容的 schema 变更可以通过新的确认记录保留 V4。破坏性变更要求更高的写入器版本及自身的头版本转换,不能复用已接受的 3→4 转换。已接受的机器记录与变更后 schema 保持不可变。[检查点规则](persistence-changes/README.zh.md#compatibility-rules)规定比较方法。 +V4 的已接受兼容性基线保存在[检查点](persistence-changes/finalized/v4.json)中。满足[读取器兼容性规则](persistence-changes/README.zh.md#compatibility-rules)并记录所需评审时,schema 变更可以保留 V4。升版本决策要求更高的写入器版本及自身的头版本转换,不能复用已接受的 3→4 转换。已接受的机器记录与变更后 schema 保持不可变。 定稿不冻结 V4 之后的每项新增,也不表示已发布。下方发布记录保留独立验证的已发布版本。普通注释、别名、源码位置,以及保留已接受含义的实现修复,不改变该基线。 @@ -51,7 +51,7 @@ evidenceTag: dsh-v0.2.0-rc.2 ## 更新记录 -实现结构性写入器变更时,一起更新代码常量与相邻迁移目录;不要在产品发布前推进此发布记录。当产品首次发布更高的 Session 格式时,确认发布事实及对应标签的写入器,然后在同一次双语更新中推进本记录与证据标签及该标签的写入器路径。后续携带相同格式的产品发布无需改变此记录。开发主干上的记录绝不降低。 +实现 Session 格式升版本时,一起更新代码常量与相邻迁移目录;不要在产品发布前推进此发布记录。当产品首次发布更高的 Session 格式时,确认发布事实及对应标签的写入器,然后在同一次双语更新中推进本记录与证据标签及该标签的写入器路径。后续携带相同格式的产品发布无需改变此记录。开发主干上的记录绝不降低。 [文档标准测试](../scripts/doc-standard.spec.ts)检查记录结构、双语一致性、证据标签及写入器路径一致性,以及文档中的已发布版本不高于工作区写入器。这个无密钥检查不会查询 GitHub,也不能证明记录是最新的;核实发布事实仍属于发布更新的一部分。 diff --git a/docs/subsystems/README.i18n.yaml b/docs/subsystems/README.i18n.yaml index 76288201ad..ec9d159bbb 100644 --- a/docs/subsystems/README.i18n.yaml +++ b/docs/subsystems/README.i18n.yaml @@ -3,5 +3,5 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/README.md /subsystems: - en: 34b6bc8c15b8009b - zh: 7a07e5c32b3feca1 + en: 1d4818dbb07391a7 + zh: f1e27ce66c181295 diff --git a/docs/subsystems/README.md b/docs/subsystems/README.md index 0960b21527..c2a47fb70b 100644 --- a/docs/subsystems/README.md +++ b/docs/subsystems/README.md @@ -50,7 +50,7 @@ One page per subsystem of the DeepSeek Harness: what it is, the data structures | [subagent.md](subagent.md) | the subagent seam: the named-provider registry, `SubagentStartRequest`/`Result`/`Run`, the start-time-vs-runtime capability split | | [voice-input.md](voice-input.md) | experimental named recognizers, transient audio and revision-guarded draft insertion | | [translation.md](translation.md) | experimental anonymous text translation and explicit provider requests | -| [agent-team.md](agent-team.md) | Agent Teams: implicit Lead identity, named continuable teammates, durable peer mailbox, and shared task DAG | +| [agent-team.md](agent-team.md) | Agent Teams: implicit Lead identity, named continuable teammates, direct peer inbox delivery, and shared task DAG | | [claude-code-mods.md](claude-code-mods.md) | Claude Code mods through the experimental bridge: every event, `$` member, chain rule, drawing feature, and example mod that differs from Claude Code | | [web.md](web.md) | the web access seam: `WebSearchRequest`/`Result`, `WebFetchRequest`/`Result`, `WebFetchBody`, provider availability, `WebError` | | [spill.md](spill.md) | the spill storage seam: `SaveTextSpill`, `SpillOwner`/`SpillSource`, `SpillRef`, the branded `SpillLocator` | diff --git a/docs/subsystems/README.zh.md b/docs/subsystems/README.zh.md index e5f33a3060..a1380713bc 100644 --- a/docs/subsystems/README.zh.md +++ b/docs/subsystems/README.zh.md @@ -50,7 +50,7 @@ | [subagent.md](subagent.zh.md) | subagent seam:命名提供方注册表、`SubagentStartRequest`/`Result`/`Run`、启动时与运行时能力拆分 | | [voice-input.md](voice-input.zh.md) | 实验性具名语音识别、临时音频和受版本保护的草稿插入 | | [translation.md](translation.zh.md) | 实验性免登录文本翻译与显式 Provider 请求 | -| [agent-team.md](agent-team.zh.md) | Agent Teams:隐式 Lead 身份、具名 continuable teammate、持久 peer mailbox 与共享任务 DAG | +| [agent-team.md](agent-team.zh.md) | Agent Teams:隐式 Lead 身份、具名 continuable teammate、直接 peer inbox 投递 与共享任务 DAG | | [claude-code-mods.md](claude-code-mods.zh.md) | 经实验性桥接运行的 Claude Code 模组:与 Claude Code 不同的每个事件、`$` 成员、链规则、绘制特性与示例模组 | | [web.md](web.zh.md) | Web 访问 seam:`WebSearchRequest`/`Result`、`WebFetchRequest`/`Result`、`WebFetchBody`、提供方可用性、`WebError` | | [spill.md](spill.zh.md) | spill 存储 seam:`SaveTextSpill`、`SpillOwner`/`SpillSource`、`SpillRef`、品牌类型 `SpillLocator` | diff --git a/docs/subsystems/agent-team.i18n.yaml b/docs/subsystems/agent-team.i18n.yaml index edb0d57235..a4c599562f 100644 --- a/docs/subsystems/agent-team.i18n.yaml +++ b/docs/subsystems/agent-team.i18n.yaml @@ -6,11 +6,11 @@ en: f571e223220bb616 zh: dd7e37fdf359eeae /agent-teams/identity-and-roster: - en: c6e6d2add95df5e8 - zh: 36c0b25c3f4eb80b -/agent-teams/durable-mailbox: - en: 75fb392a6ccfbdf9 - zh: f80678b84bd1ea47 + en: df72d9409b89714d + zh: 982934dd18864ca2 +/agent-teams/messages-and-historical-mailbox: + en: 2aed7dd369f47747 + zh: 4f080e50c584ad37 /agent-teams/shared-task-dag: en: 4515005d07e4d2a3 zh: 26811b31f69009d6 @@ -18,5 +18,5 @@ en: 6af99eff8036597a zh: f172f994e01f12c1 /agent-teams/replay: - en: 4adfd7bad5c0e302 - zh: 2d71ba065f44f2a1 + en: fe32f71c6d799ebc + zh: aa2b6ccddba8cfd5 diff --git a/docs/subsystems/agent-team.md b/docs/subsystems/agent-team.md index 6cb503d130..c5c6a0f775 100644 --- a/docs/subsystems/agent-team.md +++ b/docs/subsystems/agent-team.md @@ -6,7 +6,7 @@ Types shared by the experimental implicit-root Team domain, model tools, and hos ## Identity and roster -`TeamId` is the root `SessionId` under a distinct [brand](core.md#branded-ids). `TeamTaskId` is Team-local and monotonically allocated as `task-`; `TeamMessageId` is globally random. A teammate's Session id remains its persistent identity, while `name` is an immutable model/UI label. +`TeamId` is the root `SessionId` under a distinct [brand](core.md#branded-ids). `TeamTaskId` is allocated as `task-`. New sends return the target inbox `MessageId`; `TeamMessageId` is retained only for historical mailbox records. Teammate names are immutable labels. ```ts type-equiv /** Whole durable value written on every teammate lifecycle change. */ @@ -23,12 +23,12 @@ interface TeamMemberSnapshot { Every member starts in `provisioning` and reaches exactly one terminal roster phase, `active` or `failed`. Roster `running`/`inactive` status is derived separately and never rewrites this record. -## Durable mailbox +## Messages and historical mailbox -The Lead Session first stores the complete queued message. A target receipt is acknowledged only after its pending inbox item or recorded user message is durable, leaving queued-minus-delivered as the recovery mailbox. +New sends return inbox acceptance or reject. The target stores the existing `agent-message` source with the real sender Session id and a sender-name content prefix. Team has no new-message outbox or resend deduplication. The [package contract](../../packages/experimental/agent-team/README.md#understand-the-implementation) defines persistence. The following mailbox types remain readable so historical Lead logs still replay; Team does not deliver their pending records. ```ts type-equiv -/** One peer message retained until its target Session records it. */ +/** One peer message recorded by the historical Team mailbox. */ interface TeamMessageSnapshot { readonly id: TeamMessageId readonly senderId: SessionId @@ -40,10 +40,10 @@ interface TeamMessageSnapshot { Every message attempts Steer delivery. A running target receives it at the nearest step boundary; an inactive target starts a turn if loaded or cold-resumes otherwise. Scheduling is not stored in the durable record because callers cannot select another mode. -The target Session keeps message identity and sender attribution on both the pending inbox item and the eventual user message. Folding that source across inbox and history is the target-side de-duplication key; the model-visible framing repeats the id and sender. +Historical `team-message` sources retain the old message id and sender attribution; the client uses them for the message title and icon. ```ts type-equiv -/** Source retained by the target Session for durable mailbox de-duplication. */ +/** Source recorded by a target Session for one historical Team mailbox delivery. */ interface TeamMessageSource { readonly kind: 'team-message' readonly teamId: TeamId @@ -122,7 +122,7 @@ interface TeamProjection { ## Replay -The `agentTeam` Session projection replays one root Session into the roster, task board, and queued-minus-delivered mailbox that every Team operation reads. It selects records by `TeamId`, so events inherited by an ordinary fork retain the ancestor id and never enter the new root's state. Session event `seq` and `time` remain the ordering and timing record; Team snapshots do not duplicate them. Roster and task reads reach callers as views; pending mail stays internal to delivery and recovery. The package [README](../../packages/experimental/agent-team/README.md) owns operation, authorization, recovery, and limit behavior. +The `agentTeam` Session projection replays one root Session into the roster, task board, and historical queued-minus-delivered mailbox. It selects records by `TeamId`, so events inherited by an ordinary fork retain the ancestor id and never enter the new root's state. Session event `seq` and `time` remain the ordering and timing record; Team snapshots do not duplicate them. Roster and task reads reach callers as views; pending mail is not exposed to callers. The package [README](../../packages/experimental/agent-team/README.md) owns operation, authorization, recovery, and limit behavior. @@ -162,10 +162,10 @@ listMembers(agent: Agent): TeamMemberView[] async spawnTeammate(caller: Agent, request: SpawnTeammateRequest): Promise /** - * Queue one durable peer message, then attempt immediate delivery. + * Steer one peer message into the target inbox or reject the attempt. * @param caller - exact live sending Team member. - * @param request - target name, content, and pre-queue cancellation. - * @returns durable message identity and immediate-delivery observation. + * @param request - target name, content, and cancellation before acceptance. + * @returns accepted inbox identity; acceptance follows normal Agent persistence and does not await model processing. */ async sendMessage(caller: Agent, request: SendTeamMessageRequest): Promise diff --git a/docs/subsystems/agent-team.zh.md b/docs/subsystems/agent-team.zh.md index 083b9fafb6..2e3c0b040e 100644 --- a/docs/subsystems/agent-team.zh.md +++ b/docs/subsystems/agent-team.zh.md @@ -6,7 +6,7 @@ ## 身份与 roster -`TeamId` 是具有独立[品牌](core.zh.md#branded-ids)的 Root `SessionId`。`TeamTaskId` 在 Team 内按 `task-` 单调分配;`TeamMessageId` 是全局随机值。teammate 的 Session id 始终是持久身份,而 `name` 是不可变的模型/UI 标签。 +`TeamId` 是使用独立[品牌类型](core.zh.md#branded-ids)的 root `SessionId`。`TeamTaskId` 按 `task-` 分配。新发送返回目标 inbox 的 `MessageId`;`TeamMessageId` 仅供历史 mailbox 记录保留。teammate 名称是不可变标签。 ```ts type-equiv /** Whole durable value written on every teammate lifecycle change. */ @@ -23,12 +23,12 @@ interface TeamMemberSnapshot { 每个 member 都从 `provisioning` 开始,并且只到达一个终态 roster phase:`active` 或 `failed`。roster 的 `running`/`inactive` 状态单独派生,绝不会重写该记录。 -## 持久 mailbox +## 消息与历史 mailbox -Lead Session 首先存储完整 queued message。只有 target 的 pending inbox 条目或已记录用户消息完成持久化,才会写入独立 acknowledgement event,queued-minus-delivered 因而构成恢复 mailbox。 +新发送返回 inbox 接收结果或拒绝。目标保存现有 `agent-message` source,包含真实发送者 Session id 和发送者名称正文前缀。Team 不为新消息提供 outbox 或重发去重。[包约定](../../packages/experimental/agent-team/README.zh.md#understand-the-implementation)定义持久化。以下 mailbox 类型继续可读,以便历史 Lead 日志仍能回放;Team 不投递其中的 pending 记录。 ```ts type-equiv -/** One peer message retained until its target Session records it. */ +/** One peer message recorded by the historical Team mailbox. */ interface TeamMessageSnapshot { readonly id: TeamMessageId readonly senderId: SessionId @@ -40,10 +40,10 @@ interface TeamMessageSnapshot { 每条消息都会尝试 Steer 投递。running target 在最近的步骤边界收到消息,inactive target 在已加载时启动一个轮次,否则冷恢复。调用方不能选择其他模式,因此持久记录不存储调度方式。 -target Session 会在 pending inbox 条目和最终用户消息上保留消息身份与发送者归因。跨 inbox 与历史折叠该 source 构成 target 侧去重键;模型可见的 framing 会重复 id 和发送者。 +历史 `team-message` source 保留旧消息 id 与发送者归属;客户端用它们展示消息标题和图标。 ```ts type-equiv -/** Source retained by the target Session for durable mailbox de-duplication. */ +/** Source recorded by a target Session for one historical Team mailbox delivery. */ interface TeamMessageSource { readonly kind: 'team-message' readonly teamId: TeamId @@ -122,7 +122,7 @@ interface TeamProjection { ## 回放 -`agentTeam` Session 投影把一个 Root Session 回放成每个 Team 操作所读取的 roster、任务板与 queued-minus-delivered mailbox。它按 `TeamId` 选取记录,因此普通 fork 继承的 event 保留 ancestor id,绝不会进入新 Root 的状态。Session event 的 `seq` 与 `time` 继续负责顺序和时间记录,Team snapshot 不再重复保存它们。roster 与 task 读取以 view 形式到达调用方,而 pending 邮件仅供投递与恢复内部使用。包 [README](../../packages/experimental/agent-team/README.zh.md)负责 operation、authorization、recovery 和限制行为。 +`agentTeam` Session 投影把一个 Root Session 回放成roster、任务板与历史 queued-minus-delivered mailbox。它按 `TeamId` 选取记录,因此普通 fork 继承的 event 保留 ancestor id,绝不会进入新 Root 的状态。Session event 的 `seq` 与 `time` 继续负责顺序和时间记录,Team snapshot 不再重复保存它们。roster 与 task 读取以 view 形式到达调用方,而 pending 邮件不对调用方公开。包 [README](../../packages/experimental/agent-team/README.zh.md)负责 operation、authorization、recovery 和限制行为。 @@ -162,10 +162,10 @@ listMembers(agent: Agent): TeamMemberView[] async spawnTeammate(caller: Agent, request: SpawnTeammateRequest): Promise /** - * Queue one durable peer message, then attempt immediate delivery. + * Steer one peer message into the target inbox or reject the attempt. * @param caller - exact live sending Team member. - * @param request - target name, content, and pre-queue cancellation. - * @returns durable message identity and immediate-delivery observation. + * @param request - target name, content, and cancellation before acceptance. + * @returns accepted inbox identity; acceptance follows normal Agent persistence and does not await model processing. */ async sendMessage(caller: Agent, request: SendTeamMessageRequest): Promise diff --git a/docs/subsystems/boot.i18n.yaml b/docs/subsystems/boot.i18n.yaml index 52d584bd1f..f0edbcf9b4 100644 --- a/docs/subsystems/boot.i18n.yaml +++ b/docs/subsystems/boot.i18n.yaml @@ -6,5 +6,8 @@ en: 962b4398c9052959 zh: 14471c340a9f6e60 /profile-management/management-records: - en: a10d3f358e9b7c8e - zh: 28b0f44589a5020d + en: a1412da0219c2a09 + zh: b6869fd548f4c693 +/profile-management/profile-reconciliation: + en: 42a093314af774d4 + zh: 7c1784a3af02b31c diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index be79a823a3..8fb78deb28 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -6,8 +6,6 @@ The [boot package group](../../packages/boot/README.md) owns launcher-provided p ## Management records -`ProfilePatch` adds an optional literal `preset` row id to native Include patch fields; `id` then targets a child in that preset. [App-boot](../../packages/boot/app-boot/README.md#profiles) owns compilation, ordering, validation, and path resolution. - `PluginEntryId` identifies one Loader entry; callers obtain it from `listPlugins` rather than constructing a patch id. `PluginInfo` carries module identity, effective enablement, fiber phase and optional display `meta`, plus a unique `patchId` or a `readOnlyReason`. @@ -20,6 +18,37 @@ The [boot package group](../../packages/boot/README.md) owns launcher-provided p `ChangeResult.changed` reports a disk edit independently of `application`: `applied`, `restart-required`, `overridden` or `failed`. Optional `error` carries a localizable code and external diagnostic. `packageResult` records the pnpm exit code, bounded output, truncation flag and complete diagnostic log path, plus `timedOut` when the manager terminated a run that stopped printing. A terminated run is classified `timeout` whatever exit status the signal left behind, so installation and removal report failure instead of success and no further registry is asked. `pendingBuilds` lists undecided packages across the profile; `approvedBuilds` records the names granted permission by this operation; `registries` lists the registries an installation asked, in order; `bundle` and `version` name the package a finished installation added and its manifest version; `failedAt` says whether the last failed run could not reach the registry it asked or the host a git or tarball spec is fetched from. +## Profile reconciliation + + + +```ts type-equiv +/** Outcome of {@link Hmr.reconcileProfile}. */ +interface ProfileReconciliation { + /** Diagnostics for Loader entries left inactive. */ + warnings: string[] + /** Loaded modules whose files changed on disk and whose previous code keeps running until a restart. */ + pending: PendingModule[] + /** + * Why every change waits for a restart: `module-comparison` when module caches cannot be inspected or their files + * compared, even when no URLs are known; `package-moved` when the runtime resolution cannot publish a moved package. + */ + restartReason?: 'module-comparison' | 'package-moved' +} +``` + +```ts type-equiv +/** A changed module that loads only after a restart. */ +interface PendingModule { + url: string + /** + * `host-module`: the process entry point's static graph imports it. `unmanaged-plugin`: it is imported by a plugin + * that runs outside a traversable Loader entry. `module-comparison`: loaded modules could not be compared with disk. + */ + reason: 'host-module' | 'unmanaged-plugin' | 'module-comparison' +} +``` + @@ -32,7 +61,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.configEditor` — `ConfigEditor` -Persist Host entry configs without changing preset-scoped operations, then reconcile through Loader. +Persist complete raw configs and apply them through the normal Loader path. ```ts cordis-catalog /** Addressable profile rows; nested Includes have independent configuration ownership. @@ -80,6 +109,21 @@ async watchConfig(filename: string, refresh: () => Promise): Promise<() => * @returns Linked module URLs, or an empty list for an uncached module. */ async getLinked(url: string): Promise + +/** + * Recompose the profile from its manifest and patch files, replacing running plugins whose loaded files below the + * profile directory or its linked package targets changed on disk, and publishing its runtime resolution. Changed + * modules are evicted and the Loader entries running them stop; app-boot's {@link recomposeProfile} then publishes the + * resolution, applies the generation, starts the stopped entries with the current files and configuration, + * imports entries whose import failed again, and judges activation. Afterwards the modules below the mappings the + * recomposition dropped are evicted, so a removed or deselected package is imported afresh when it returns. Callers run + * inside {@link runExclusive}. + * @param requiredIds Entry ids whose inactive state is reported as a failure even when it predates this call. + * @returns Inactive-entry diagnostics, the changed modules that load after a restart, and a profile-wide restart reason. + * @throws The patch read, publication, preparation, apply, or activation failure of the recomposition, including a + * replacement plugin that fails to load or start, whose previous code no longer runs. + */ +async reconcileProfile(requiredIds: readonly string[] = []): Promise ``` Source: [`packages/boot/hmr/src/index.ts`](../../packages/boot/hmr/src/index.ts) @@ -116,7 +160,7 @@ Manage profile files and apply their declared reload lifecycle. * @returns Package versions, manifest descriptions, the installable spec of profile dependencies, rows, optional * display metadata, activation selections, whether the installation offers the bundle, and removal availability. */ -@Remote async listBundles(): Promise +@Remote listBundles(): Promise /** Read the registries this manager asks: the configured first one, its fallbacks in order, and what pnpm's own configuration names. * @returns The registries in pnpm's comparison form; null is the one pnpm's own configuration names, `resolved` as pnpm reads it now. diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index 93024b965a..20e7701f67 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -6,8 +6,6 @@ ## 管理记录 -`ProfilePatch` 在原生 Include patch 字段上增加可选的字面量 `preset` 条目 id;此时 `id` 指向该 preset 内的子条目。[App-boot](../../packages/boot/app-boot/README.zh.md#profiles) 定义编译、顺序、校验与路径解析规则。 - `PluginEntryId` 标识一个 Loader 条目;调用方从 `listPlugins` 获取,不自行拼接 patch id。 `PluginInfo` 包含模块标识、实际启停状态、fiber 阶段和可选的展示 `meta`,以及唯一的 `patchId` 或 `readOnlyReason`。 @@ -20,6 +18,37 @@ `ChangeResult.changed` 报告磁盘修改,独立于 `application`:`applied`、`restart-required`、`overridden` 或 `failed`。可选的 `error` 包含可本地化的错误码和外部诊断。`packageResult` 记录 pnpm 退出码、有界输出、截断标志及完整诊断日志路径;当管理器终止了一个停止打印的运行,还记录 `timedOut`。被终止的运行不论信号留下什么退出状态都归类为 `timeout`,因此安装与删除都报告失败而非成功,也不会再询问下一个注册表。`pendingBuilds` 列出整个 profile 尚未决定的包;`approvedBuilds` 记录本次操作授予权限的包名;`registries` 按顺序列出一次安装问过的注册表;`bundle` 与 `version` 给出完成的安装新增的包及其清单版本;`failedAt` 说明最后一次失败的运行连不上的是所问的注册表,还是 git 或 tarball spec 自身拉取的主机。 +## Profile 重新组合 + + + +```ts type-equiv +/** Outcome of {@link Hmr.reconcileProfile}. */ +interface ProfileReconciliation { + /** Diagnostics for Loader entries left inactive. */ + warnings: string[] + /** Loaded modules whose files changed on disk and whose previous code keeps running until a restart. */ + pending: PendingModule[] + /** + * Why every change waits for a restart: `module-comparison` when module caches cannot be inspected or their files + * compared, even when no URLs are known; `package-moved` when the runtime resolution cannot publish a moved package. + */ + restartReason?: 'module-comparison' | 'package-moved' +} +``` + +```ts type-equiv +/** A changed module that loads only after a restart. */ +interface PendingModule { + url: string + /** + * `host-module`: the process entry point's static graph imports it. `unmanaged-plugin`: it is imported by a plugin + * that runs outside a traversable Loader entry. `module-comparison`: loaded modules could not be compared with disk. + */ + reason: 'host-module' | 'unmanaged-plugin' | 'module-comparison' +} +``` + @@ -32,7 +61,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.configEditor` — `ConfigEditor` -Persist Host entry configs without changing preset-scoped operations, then reconcile through Loader. +Persist complete raw configs and apply them through the normal Loader path. ```ts cordis-catalog /** Addressable profile rows; nested Includes have independent configuration ownership. @@ -80,6 +109,21 @@ async watchConfig(filename: string, refresh: () => Promise): Promise<() => * @returns Linked module URLs, or an empty list for an uncached module. */ async getLinked(url: string): Promise + +/** + * Recompose the profile from its manifest and patch files, replacing running plugins whose loaded files below the + * profile directory or its linked package targets changed on disk, and publishing its runtime resolution. Changed + * modules are evicted and the Loader entries running them stop; app-boot's {@link recomposeProfile} then publishes the + * resolution, applies the generation, starts the stopped entries with the current files and configuration, + * imports entries whose import failed again, and judges activation. Afterwards the modules below the mappings the + * recomposition dropped are evicted, so a removed or deselected package is imported afresh when it returns. Callers run + * inside {@link runExclusive}. + * @param requiredIds Entry ids whose inactive state is reported as a failure even when it predates this call. + * @returns Inactive-entry diagnostics, the changed modules that load after a restart, and a profile-wide restart reason. + * @throws The patch read, publication, preparation, apply, or activation failure of the recomposition, including a + * replacement plugin that fails to load or start, whose previous code no longer runs. + */ +async reconcileProfile(requiredIds: readonly string[] = []): Promise ``` Source: [`packages/boot/hmr/src/index.ts`](../../packages/boot/hmr/src/index.ts) @@ -116,7 +160,7 @@ Manage profile files and apply their declared reload lifecycle. * @returns Package versions, manifest descriptions, the installable spec of profile dependencies, rows, optional * display metadata, activation selections, whether the installation offers the bundle, and removal availability. */ -@Remote async listBundles(): Promise +@Remote listBundles(): Promise /** Read the registries this manager asks: the configured first one, its fallbacks in order, and what pnpm's own configuration names. * @returns The registries in pnpm's comparison form; null is the one pnpm's own configuration names, `resolved` as pnpm reads it now. diff --git a/docs/subsystems/conversation.i18n.yaml b/docs/subsystems/conversation.i18n.yaml index b8f7380bbf..64ca728d7e 100644 --- a/docs/subsystems/conversation.i18n.yaml +++ b/docs/subsystems/conversation.i18n.yaml @@ -16,10 +16,10 @@ zh: 787ad4d04b79adaf /conversation-assembly/replayable-event-families: en: c216e2df128b8cb9 - zh: e61312f1f280332d + zh: c039cf84b0d86ad8 /conversation-assembly/definition-and-typed-chat-payload: - en: 5f24557a050d1df0 - zh: 47735627f802b6fa + en: d8f5e4773704c718 + zh: f3db8c0d01080dba /conversation-assembly/predecessor-reads: en: da849b3b5da81da8 zh: 37a647a439bc24b1 diff --git a/docs/subsystems/conversation.md b/docs/subsystems/conversation.md index ba4eb88102..ef6f6ffbdb 100644 --- a/docs/subsystems/conversation.md +++ b/docs/subsystems/conversation.md @@ -247,10 +247,24 @@ export function apply(ctx: ClientContext): void { `ConversationNodeDefinitionInput` accepts either this function or a read-only table from event type to matching function. Function-form registrations receive every event; table registrations receive only their listed types. The Registry copies table entries and precomputes ordered candidate Sets when registrations change, keeping candidate construction out of per-event dispatch. Replace a table by unregistering and registering again. Resolved `ConversationNodeDefinition` values retain a callable `match(event)` in both cases. +A match result with `exclusive: true` claims that event on the Definition's target. The assembler evaluates every match of the event before accepting any, so the outcome is independent of registration order: other Definitions of the claimed target build no Context for the event, and the target's unmatched-event fallback does not run. Definitions of other targets and Definitions without a target still receive it. Two claims on one target, or a claim from a Definition without a target, throw during dispatch; a claim returned by the fallback itself has no effect. A business Definition uses a claim to present one kind of message that a generic Definition of the same target would otherwise also present, such as a late question reply. + `buildLocationData(context, scope)` optionally publishes Definition-owned data onto an engine-owned Turn or Step. Use declaration merging to give each key a precise value type. Another Node in the same Location can consume that value through its constrained slot hook, such as `useTurnData(key)`, without receiving the Session or scanning `snapshot.chat.nodes`. `target` and `buildViewNode(context)` declare one target-owned rendering contribution and must appear together. Preserve `context.key` as the React-facing identity, choose `anchorSeq` from the matched event ordering, and return only renderer-ready data. Once a target Node has been published, keep returning the same key; use `visibility: 'hidden'` when it must temporarily leave the visible flow rather than withdrawing it with `null`. +A Chat Node also chooses where its row stands through `groupTree`. Positions are ordered from the outermost inward, and a Node at a position also has the effect of every inner one. Chat process grouping, whole-Turn folding, and Turn-input detection read only this position; [group-tree.ts](../../packages/client/ui-chat/src/client/contract/group-tree.ts) holds the complete contract. + +| The Node is | Declare | +|---|---| +| A person's input claimed in Step 1; its Turn opens an exchange | `exchange` | +| Another input of its Turn, such as later human input or a trigger notice; before the process it is the opening input, after it the whole Turn stays open | `input` | +| A Turn notice that stays outside whole-Turn folding, such as an error or the completed-turn footer | `turn` | +| An independent row that whole-Turn folding still hides, such as a model retry | `process` | +| Ordinary process content that joins the surrounding step run | omit `groupTree` | + +The [Chat business rules](../../packages/client/ui-chat/src/client/conversation-nodes/README.md#process-grouping) list the positions the built-in Nodes declare. When a generic Definition of the same target also matches the event your Node presents, claim the event with `exclusive: true` as described above. + ## Predecessor reads Some Definitions need the latest earlier State of another business kind. `start` receives a `ConversationContextReader`; call `reader.previous(kind)` there instead of accepting a Context collection or scanning events. The reader returns the nearest started Context before the current start `seq` as read-only data. diff --git a/docs/subsystems/conversation.zh.md b/docs/subsystems/conversation.zh.md index 7115bb90b8..a3ef583db2 100644 --- a/docs/subsystems/conversation.zh.md +++ b/docs/subsystems/conversation.zh.md @@ -71,6 +71,8 @@ Group 存储在安装前校验完整提交结果:根 Group 引用与记录一 实时 Assistant delta 作为 Client-only `assistant/live-chunk` event 到达。重连 baseline 会把活跃的进程内紧凑 stream 展开为相同的瞬态 event,持久 `assistant/message` 与 `assistant/attempt` event 则嵌入完整紧凑 stream 供历史回放。瞬态 event 可以初始化 Context。每条工具 delta 和后续 `tool/call` 都可以按同一个 callId 匹配为 start,即使名称尚未到达;只有最早的 Match 调用 `start()`,后续 Match 调用 `update()`。准备态 Tool 节点只有在名称可用后才显示。历史分页不把已结束消息展开为实时 delta。消费 Assistant 输出的 Definition 通过同一组匹配和更新接口处理 live chunk 与持久 settlement,其他 Definition 直接返回 `null`,无需展开 stream。 + + ## Definition 与类型化 Chat payload 为了完整展示关联关系,下面把生产方声明和 Client 贡献写在同一个代码块里。实际的包族中,branded id 与 `SessionEventMap` 声明留在事件生产方,Definition、Chat data 合并与 renderer 留在 Client 插件。 @@ -247,10 +249,24 @@ export function apply(ctx: ClientContext): void { `ConversationNodeDefinitionInput` 接受上述函数,或事件类型到匹配函数的只读表。函数形式的注册接收所有事件;表形式只接收列出的类型。Registry 在注册关系变化时复制表条目并预计算有序候选 Set,不在逐事件分发时构造候选集合。替换表时先注销,再重新注册。两种形式解析后的 `ConversationNodeDefinition` 都保留可调用的 `match(event)`。 +match 结果带 `exclusive: true` 时,即在该 Definition 的 target 上认领这个事件。Assembler 先求出该事件的全部 match,再逐个接收,因此结果与注册顺序无关:被认领 target 上的其他 Definition 不为该事件建立 Context,该 target 的未匹配事件 fallback 也不运行;其他 target 的 Definition 与没有 target 的 Definition 照常接收。同一 target 被认领两次,或没有 target 的 Definition 发起认领,都会在分发时抛错;fallback 自身返回的认领不起作用。业务 Definition 用认领来呈现某一类消息,而同一 target 上的通用 Definition 原本也会呈现它,例如迟到的问题回答。 + `buildLocationData(context, scope)` 可以把 Definition 拥有的数据发布到引擎拥有的 Turn 或 Step 上。通过 declaration merging 为每个 key 指定精确 value 类型。同一 Location 内的另一个 Node 可以使用受限 slot hook(例如 `useTurnData(key)`)读取该值,无须取得 Session,也无须扫描 `snapshot.chat.nodes`。 `target` 与 `buildViewNode(context)` 必须同时声明一项由 target 拥有的渲染贡献。把 `context.key` 保留为 React 侧身份,根据持久排序证据选择 `anchorSeq`,并且只返回 renderer 可以直接使用的数据。某个 target Node 一旦发布,就要继续返回同一个 key;需要暂时离开可见流时使用 `visibility: 'hidden'`,不要改为返回 `null` 撤回它。 +Chat Node 还通过 `groupTree` 选择所在行的位置。位置由外到内排列,站在某个位置的 Node 同时具有所有内层位置的效果。Chat 的过程分组、整轮折叠和轮次输入判断只读取这个位置;完整契约见 [group-tree.ts](../../packages/client/ui-chat/src/client/contract/group-tree.ts)。 + +| Node 是 | 声明 | +|---|---| +| Step 1 认领的人的输入,所在轮次开启一个交互段 | `exchange` | +| 所在轮次的其他输入,如之后的人的输入或触发通知;位于过程之前时是开场输入,之后出现时整个轮次保持展开 | `input` | +| 留在整轮折叠之外的轮次通知,如错误或已完成轮次页脚 | `turn` | +| 整轮折叠仍会隐藏的独立行,如模型重试 | `process` | +| 并入相邻步骤组的普通过程内容 | 不声明 `groupTree` | + +各内置 Node 声明的位置见 [Chat 业务规则](../../packages/client/ui-chat/src/client/conversation-nodes/README.zh.md#process-grouping)。如果同一 target 的通用 Definition 也会匹配你的 Node 所呈现的事件,按上文用 `exclusive: true` 认领该事件。 + ## Predecessor read 有些 Definition 需要另一个业务 kind 在当前位置之前的最新 State。`start` 会收到 `ConversationContextReader`;应在这里调用 `reader.previous(kind)`,不要接收 Context 集合或扫描事件。Reader 返回当前 start `seq` 之前最近一个已启动 Context 的只读数据。 diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index c4c106c066..94bed76054 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -25,7 +25,7 @@ zh: d0f66664ac85ae64 /core/tooldefinition: en: d926a9b80aada2e5 - zh: e34e6f43bdfd8920 + zh: 7e191ba5dab904df /core/repo-wide-type-patterns: en: 057db6d8bf356c0f zh: 1441b39e5142b0bf diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 665df11563..42f6d2e24a 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -497,12 +497,12 @@ async register(definition: PresetDefinition): Promise<() => Promise> /** Inspect retained revisions, or the exact revision an Agent joined. * @param ctx - optional Agent context; omission includes all retained revisions. - * @returns detached definition and module row identities, resolution bases, and isolation diagnostics; no match returns an empty list. + * @returns detached module references and isolation diagnostics; no match returns an empty list. */ inspectCompositions(ctx?: Context): AgentPresetInspection[] /** Read every declared preset, including activation failures. - * @returns Display metadata, declaring Loader row identities, and loading diagnostics. + * @returns Display metadata and loading diagnostics. */ async list(): Promise @@ -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 44ee6d3605..9714c7c62f 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -363,6 +363,8 @@ type SessionStartSource = 'startup' | 'resume' | 'clear' | 'compact' 其完整字段、`defineTool`/`ValueSchemaSpec`/`ParameterSchemaSpec` 类型化 schema DSL、`ToolExecution`/`ToolExecutionResult` waterfall 类型,以及工具展示 UI 类型都在 **[tools.md](tools.zh.md)** 中。 + + ## 全仓通用类型模式 两个模式在每个子系统中反复出现,只在此处记录一次。 @@ -507,12 +509,12 @@ async register(definition: PresetDefinition): Promise<() => Promise> /** Inspect retained revisions, or the exact revision an Agent joined. * @param ctx - optional Agent context; omission includes all retained revisions. - * @returns detached definition and module row identities, resolution bases, and isolation diagnostics; no match returns an empty list. + * @returns detached module references and isolation diagnostics; no match returns an empty list. */ inspectCompositions(ctx?: Context): AgentPresetInspection[] /** Read every declared preset, including activation failures. - * @returns Display metadata, declaring Loader row identities, and loading diagnostics. + * @returns Display metadata and loading diagnostics. */ async list(): Promise @@ -567,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/credentials.i18n.yaml b/docs/subsystems/credentials.i18n.yaml index 64722160fa..a46cfbac32 100644 --- a/docs/subsystems/credentials.i18n.yaml +++ b/docs/subsystems/credentials.i18n.yaml @@ -6,14 +6,14 @@ en: 4589c745baf092c7 zh: 3a782e6a06825201 /user-credentials/identity: - en: aba5a25c34e229cc - zh: 96493f925f60b533 + en: 0083032b9d19467d + zh: 15d7a7520bac094e /user-credentials/resolution: en: baaab4bca76bea6b zh: 54ccdc03ffd44f63 /user-credentials/description: - en: 17573160805d3014 - zh: 36a058a96f45df23 + en: f7b09588c0f34952 + zh: 1b93d673c5bf6a80 /user-credentials/change-commits: en: 464315a953330eb2 zh: d9815591f3abc2cb diff --git a/docs/subsystems/credentials.md b/docs/subsystems/credentials.md index ef0b5b04c3..70c705d94f 100644 --- a/docs/subsystems/credentials.md +++ b/docs/subsystems/credentials.md @@ -15,6 +15,7 @@ A reference names one credential as a POSIX-style environment-variable name. The type CredentialRef = Branded<'CredentialRef'> ``` + ## Resolution `resolve(ref)` returns the value with the provider-defined source layer that supplied it, or `undefined` while unconfigured. Consumers re-resolve at each operation and never cache across operations — that per-operation read is the hot-update mechanism. @@ -31,7 +32,7 @@ interface ResolvedCredential { ## Description -`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The local provider reports a reference supplied by the live process environment as `writable: false` — a write would appear to succeed while resolution kept returning the shadowing value, so the seam rejects it and the UI can render the reference read-only up front. +`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again. ```ts type-equiv /** @@ -136,7 +137,7 @@ Source: [`packages/credentials/authorization/src/index.ts`](../../packages/crede Abstract credential service over two key spaces that answer two questions. -A CredentialRef answers "what is behind this environment-variable name", layered over the process environment, the provider-managed store, and `.env` files. One seam-wide rule binds that half: an empty stored value is absent everywhere — `resolve` skips it, `describe` reports it unconfigured — so a blank never masquerades as a configured secret. +A CredentialRef answers "what is behind this environment-variable name": the provider-managed store first, then ambient fallbacks such as the process environment and `.env` files. One seam-wide rule binds that half: an empty stored value is absent everywhere — `resolve` skips it, `describe` reports it unconfigured — so a blank never masquerades as a configured secret. A CredentialKey answers "what credential does this plugin hold for this id". Nothing can layer here — an authorization grant has no environment to be read from — so presence of the record is the whole fact, and modifyRecord is the only write path because a correct write depends on the current value (a token refresh is read-decide-replace under one lock). @@ -160,10 +161,9 @@ abstract resolve(ref: CredentialRef): Promise abstract describe(ref: CredentialRef): Promise /** - * Durably store one value in the provider-managed writable source. Rejects - * while a read-only source shadows the reference — the write would appear - * to succeed while resolution keeps returning the shadowing value — and - * rejects an empty value (use {@link unset}). + * Durably store one value in the provider-managed writable source. The stored + * value takes precedence over ambient fallbacks, and empty values are + * rejected (use {@link unset}). * @param ref - the reference to store. * @param value - the non-empty secret value. */ @@ -171,8 +171,8 @@ abstract set(ref: CredentialRef, value: string): Promise /** * Remove one reference from the provider-managed writable source; removing - * an absent reference is a no-op. Rejects while a read-only source shadows - * the reference, like {@link set}. + * an absent reference is a no-op. Ambient fallback layers may become + * effective again after removal. * @param ref - the reference to remove. */ abstract unset(ref: CredentialRef): Promise diff --git a/docs/subsystems/credentials.zh.md b/docs/subsystems/credentials.zh.md index d6a8d73938..14fb73bf13 100644 --- a/docs/subsystems/credentials.zh.md +++ b/docs/subsystems/credentials.zh.md @@ -15,6 +15,7 @@ type CredentialRef = Branded<'CredentialRef'> ``` + ## 解析 `resolve(ref)` 返回值及提供该值的来源层(由提供方定义);未配置期间返回 `undefined`。消费方在每个操作中重新解析,绝不跨操作缓存——这种按操作进行的读取正是热更新机制。 @@ -31,7 +32,7 @@ interface ResolvedCredential { ## 描述 -`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。本地提供方把由当前进程环境供值的引用报告为 `writable: false`——那样的写入会表面成功而解析持续返回遮蔽值,因此 seam 直接拒绝,界面也得以提前把该引用渲染为只读。 +`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。 ```ts type-equiv /** @@ -136,7 +137,7 @@ Source: [`packages/credentials/authorization/src/index.ts`](../../packages/crede Abstract credential service over two key spaces that answer two questions. -A CredentialRef answers "what is behind this environment-variable name", layered over the process environment, the provider-managed store, and `.env` files. One seam-wide rule binds that half: an empty stored value is absent everywhere — `resolve` skips it, `describe` reports it unconfigured — so a blank never masquerades as a configured secret. +A CredentialRef answers "what is behind this environment-variable name": the provider-managed store first, then ambient fallbacks such as the process environment and `.env` files. One seam-wide rule binds that half: an empty stored value is absent everywhere — `resolve` skips it, `describe` reports it unconfigured — so a blank never masquerades as a configured secret. A CredentialKey answers "what credential does this plugin hold for this id". Nothing can layer here — an authorization grant has no environment to be read from — so presence of the record is the whole fact, and modifyRecord is the only write path because a correct write depends on the current value (a token refresh is read-decide-replace under one lock). @@ -160,10 +161,9 @@ abstract resolve(ref: CredentialRef): Promise abstract describe(ref: CredentialRef): Promise /** - * Durably store one value in the provider-managed writable source. Rejects - * while a read-only source shadows the reference — the write would appear - * to succeed while resolution keeps returning the shadowing value — and - * rejects an empty value (use {@link unset}). + * Durably store one value in the provider-managed writable source. The stored + * value takes precedence over ambient fallbacks, and empty values are + * rejected (use {@link unset}). * @param ref - the reference to store. * @param value - the non-empty secret value. */ @@ -171,8 +171,8 @@ abstract set(ref: CredentialRef, value: string): Promise /** * Remove one reference from the provider-managed writable source; removing - * an absent reference is a no-op. Rejects while a read-only source shadows - * the reference, like {@link set}. + * an absent reference is a no-op. Ambient fallback layers may become + * effective again after removal. * @param ref - the reference to remove. */ abstract unset(ref: CredentialRef): Promise diff --git a/docs/subsystems/jobs.i18n.yaml b/docs/subsystems/jobs.i18n.yaml index 17ea2f9f9e..61aa2da366 100644 --- a/docs/subsystems/jobs.i18n.yaml +++ b/docs/subsystems/jobs.i18n.yaml @@ -6,8 +6,11 @@ en: dd515d8548864a91 zh: 16a117d39989a373 /background-job-runtime/ids-and-status: - en: 529f401da4757a98 - zh: 041ff5e86b5dd8db + en: 4b286c70e4a83b99 + zh: 7edbf090e9cb6487 +/background-job-runtime/session-lifecycle-records: + en: 5fb99886e0ab2718 + zh: bdea51368c935895 /background-job-runtime/producer-contract: en: af0be338a0ba5e60 zh: fc0eefb8c31f3a98 diff --git a/docs/subsystems/jobs.md b/docs/subsystems/jobs.md index 6cc4e3e5a5..d00c691db2 100644 --- a/docs/subsystems/jobs.md +++ b/docs/subsystems/jobs.md @@ -6,7 +6,7 @@ Types shared by long-running producers, `ctx.jobs`, and job controls. The [seam ## Ids and status -`JobId` is a [branded id](core.md#branded-ids) generated as `-N`. Access control relies on owner authorization, not id secrecy. `JobKind` derives from a merge-extensible map; the registry treats kinds as opaque id namespaces. +`JobId` is a [branded id](core.md#branded-ids) generated as `-` with 16 lowercase UUID hex characters after the kind. Access control relies on owner authorization, not id secrecy. `JobKind` derives from a merge-extensible map; the registry treats kinds as opaque id namespaces. ```ts type-equiv /** @@ -20,10 +20,64 @@ interface JobKindMap { `JobStatus` is `'running' | 'stopping' | 'completed' | 'killed' | 'failed'`; producer-specific facts belong in `JobView.progress` while the job runs and in `JobView.detail` once it settled. + + +## Session lifecycle records + +Owned jobs publish `job/registered` and `job/settled` in their original owner Session. The globally unique `jobId` pairs those records and controls the live job. The SDK forwards these log-only records through `session.event`, independently of output reads. Timestamps describe registry commits, not CPU time or exact OS process boundaries; a missing settlement remains incomplete. `producerReported` means the producer fulfilled `done` with a terminal outcome; it is false for forced teardown or rejection and does not independently certify resource release. + +`job/settled` may follow `turn/end`. An SDK run result covers only its own observation window; consumers needing later settlements retain a Session subscription or read persisted history. Turn completion does not imply that every owned job stopped. + +Application teardown can stop Session event routing or close its writer before an owned job's final settlement reaches storage. This includes normal one-shot completion and signal shutdown, as well as hard process loss. A missing `job/settled` remains incomplete even if the live registry reported termination; consumers must not invent a finish timestamp. + +```ts type-equiv +/** Durable identity and registration time of one owned job execution. */ +interface JobRegisteredData { + /** Unique execution id accepted by job controls and retained in Session history. */ + readonly jobId: JobId + /** Original owner; copied history does not transfer execution ownership. */ + readonly owner: SessionId + /** Producer kind. */ + readonly kind: string + /** Producer-supplied label. */ + readonly label: string + /** Unix epoch milliseconds when registration committed. */ + readonly startedAt: number + /** Creating tool invocation, when the producer was called through a tool. */ + readonly toolCall?: JobToolCall +} +``` + +```ts type-equiv +/** Registry settlement, including whether the producer reported a terminal outcome. */ +interface JobSettledData extends JobRegisteredData { + /** Unix epoch milliseconds when the registry committed the terminal record. */ + readonly finishedAt: number + /** Recorded terminal outcome. */ + readonly status: JobOutcome['status'] + /** Source of the termination request, or producer completion. */ + readonly cause: JobSettleCause + /** True when done fulfilled; false for rejection or forced failure. Does not certify resource release. */ + readonly producerReported: boolean + /** Terminal reason, including a recorded kill reason when applicable. */ + readonly detail?: string +} +``` + ## Producer contract A `JobSpec` declares identity, the owning session, optional pull `output` sources, and a starter. The runtime finishes preflight before calling `run()` with the job's `JobHandle` and commits without a later failable step. Producers own execution resources; the runtime owns identity, access, lifecycle state, and the output ring. +```ts type-equiv +/** Tool dispatch that created a job; nested calls retain their root invocation. */ +interface JobToolCall { + /** Exact invocation, including a PTC sub-call when applicable. */ + readonly callId: SessionEventMap['tool/call']['callId'] + /** Root model-requested invocation owning this execution. */ + readonly rootCallId: SessionEventMap['tool/call']['callId'] +} +``` + ```ts type-equiv /** * Producer declaration passed to {@link JobRegistry.start}. The runtime @@ -43,6 +97,8 @@ interface JobSpec { * caller until service disposal. */ owner?: SessionId + /** Creating tool invocation, retained in the durable lifecycle records. */ + toolCall?: JobToolCall /** * Optional UTF-8 byte cap for each complete model-facing completion notice or * output read, including controller status metadata. Independent of ring @@ -76,7 +132,7 @@ interface JobSpec { * throwing, so a producer's trailing flush cannot break its own teardown path. */ interface JobHandle { - /** The registry-issued id (`-N`). */ + /** The registry-issued id (`-`). */ readonly id: JobId /** * Append one chunk to the output ring. Offsets advance by the chunk's UTF-8 @@ -219,7 +275,7 @@ interface JobOutputRead { * stream all consume this one shape. */ interface JobView { - /** The registry-issued id (`-N`). */ + /** The registry-issued id (`-`). */ readonly id: JobId /** * The producer kind the job was registered with: a Host-registered @@ -405,7 +461,7 @@ Implementations must honor these semantics: * rejection leaves no job id or execution resource. A throwing starter * leaves nothing registered; after it returns, registration cannot fail. * @param spec - job identity, owner, output sources, and synchronous starter. - * @returns the registry-issued `-N` id. + * @returns the registry-issued `-` id. */ abstract start(spec: JobSpec): JobId diff --git a/docs/subsystems/jobs.zh.md b/docs/subsystems/jobs.zh.md index b80f64fade..c592c7d996 100644 --- a/docs/subsystems/jobs.zh.md +++ b/docs/subsystems/jobs.zh.md @@ -6,7 +6,7 @@ ## ID 与状态 -`JobId` 是按 `-N` 生成的[品牌化 id](core.zh.md#branded-ids)。访问控制依赖拥有者授权,而非 id 的保密性。`JobKind` 派生自可合并扩展的 map;注册表将各个 kind 视为不透明的 id 命名空间。 +`JobId` 是按 `-` 生成的[品牌化 id](core.zh.md#branded-ids),kind 后是 UUID 的 16 位小写十六进制字符。访问控制依赖拥有者授权,而非 id 的保密性。`JobKind` 派生自可合并扩展的 map;注册表将各个 kind 视为不透明的 id 命名空间。 ```ts type-equiv /** @@ -20,10 +20,64 @@ interface JobKindMap { `JobStatus` 为 `'running' | 'stopping' | 'completed' | 'killed' | 'failed'`;生产方特有的事实在运行期间归入 `JobView.progress`,结算后归入 `JobView.detail`。 + + +## Session 生命周期记录 + +有所有者的 job 在原始所有者 Session 中发布 `job/registered` 与 `job/settled`。全局唯一的 `jobId` 同时配对这两条记录并控制运行中的 job。SDK 通过 `session.event` 转发这些仅日志记录,不依赖输出读取。时间戳描述注册表提交时刻,不是 CPU 时间或精确的 OS 进程边界;缺少结算时保持不完整。`producerReported` 表示生产方通过兑现 `done` 报告了终态;强制销毁或 promise 拒绝时为 false,不独立确认资源已释放。 + +`job/settled` 可能出现在 `turn/end` 之后。SDK run 结果只覆盖自身观测窗口;需要较晚结算的消费方应保留 Session 订阅或读取持久化历史。轮次完成不表示所有有主 job 都已停止。 + +应用销毁可能在有主 job 的最后一条结算写入存储前停止 Session 事件路由或关闭写句柄。正常的一次性运行结束、信号关停和进程硬退出都可能出现这种情况。即使运行期注册表报告了终止,缺少 `job/settled` 的区间仍不完整;消费方不得虚构结束时间戳。 + +```ts type-equiv +/** Durable identity and registration time of one owned job execution. */ +interface JobRegisteredData { + /** Unique execution id accepted by job controls and retained in Session history. */ + readonly jobId: JobId + /** Original owner; copied history does not transfer execution ownership. */ + readonly owner: SessionId + /** Producer kind. */ + readonly kind: string + /** Producer-supplied label. */ + readonly label: string + /** Unix epoch milliseconds when registration committed. */ + readonly startedAt: number + /** Creating tool invocation, when the producer was called through a tool. */ + readonly toolCall?: JobToolCall +} +``` + +```ts type-equiv +/** Registry settlement, including whether the producer reported a terminal outcome. */ +interface JobSettledData extends JobRegisteredData { + /** Unix epoch milliseconds when the registry committed the terminal record. */ + readonly finishedAt: number + /** Recorded terminal outcome. */ + readonly status: JobOutcome['status'] + /** Source of the termination request, or producer completion. */ + readonly cause: JobSettleCause + /** True when done fulfilled; false for rejection or forced failure. Does not certify resource release. */ + readonly producerReported: boolean + /** Terminal reason, including a recorded kill reason when applicable. */ + readonly detail?: string +} +``` + ## 生产方约定 `JobSpec` 声明身份、拥有者会话、可选的拉取式 `output` 源与启动器。运行时会在完成预检后携带该 job 的 `JobHandle` 调用 `run()`,随后提交注册,不再执行可能失败的步骤。生产方拥有执行资源;运行时拥有身份、访问、生命周期状态与输出环。 +```ts type-equiv +/** Tool dispatch that created a job; nested calls retain their root invocation. */ +interface JobToolCall { + /** Exact invocation, including a PTC sub-call when applicable. */ + readonly callId: SessionEventMap['tool/call']['callId'] + /** Root model-requested invocation owning this execution. */ + readonly rootCallId: SessionEventMap['tool/call']['callId'] +} +``` + ```ts type-equiv /** * Producer declaration passed to {@link JobRegistry.start}. The runtime @@ -43,6 +97,8 @@ interface JobSpec { * caller until service disposal. */ owner?: SessionId + /** Creating tool invocation, retained in the durable lifecycle records. */ + toolCall?: JobToolCall /** * Optional UTF-8 byte cap for each complete model-facing completion notice or * output read, including controller status metadata. Independent of ring @@ -76,7 +132,7 @@ interface JobSpec { * throwing, so a producer's trailing flush cannot break its own teardown path. */ interface JobHandle { - /** The registry-issued id (`-N`). */ + /** The registry-issued id (`-`). */ readonly id: JobId /** * Append one chunk to the output ring. Offsets advance by the chunk's UTF-8 @@ -219,7 +275,7 @@ interface JobOutputRead { * stream all consume this one shape. */ interface JobView { - /** The registry-issued id (`-N`). */ + /** The registry-issued id (`-`). */ readonly id: JobId /** * The producer kind the job was registered with: a Host-registered @@ -405,7 +461,7 @@ Implementations must honor these semantics: * rejection leaves no job id or execution resource. A throwing starter * leaves nothing registered; after it returns, registration cannot fail. * @param spec - job identity, owner, output sources, and synchronous starter. - * @returns the registry-issued `-N` id. + * @returns the registry-issued `-` id. */ abstract start(spec: JobSpec): JobId diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index 8491f61b6d..f6fb858bef 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -36,14 +36,14 @@ en: 58dec2259b0b1c6f zh: fc99fe965acaabf3 /llm-streaming/the-model-request: - en: 824d18f76f990711 - zh: 8a2895513652e528 + en: 60c661bdcfec52dd + zh: c27a46f6c99efea1 /llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header: en: f2e6932e211f179b zh: 75112586a6f3f4aa /llm-streaming/official-deepseek-request-extensions: - en: b19f291f094157ed - zh: 682f13a833e8bb52 + en: 42bc50394b070e96 + zh: 007caa743ec3c790 /llm-streaming/service-and-provider-contracts: en: 8dc79d4cc82824c2 zh: 3ebabd3a117ad717 diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index f87c1e9d45..cd780fd0ed 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -498,11 +498,31 @@ interface LlmConfigurableProvider { * from outside. */ declared?: boolean + /** + * Route endpoint the adapter uses when the profile sets no `baseURL`; the + * adapter may still send an individual model to that model's own endpoint. + * Absent when the route has no fixed endpoint. + */ + defaultBaseURL?: string + /** Authentication the adapter performs when the profile names no credential reference; absent when it reports none. */ + nativeAuth?: LlmNativeAuth /** Configuration diagnostic for repair; unaffected models may remain serviceable. */ error?: string } ``` +A settings editor shows `defaultBaseURL` and `nativeAuth` for a profile that leaves the endpoint or the credential reference unset. `nativeAuth` lists environment variable names, never their values. + +```ts type-equiv +/** Authentication a provider route performs without a credential reference in its profile. */ +interface LlmNativeAuth { + /** Environment variables the route's authentication reads, in lookup order; empty when it reads none. */ + env: readonly string[] + /** Whether a stored OAuth sign-in can authenticate the route. */ + oauth: boolean +} +``` + ```ts type-equiv /** One adapter-discovered model; catalog membership is advisory, not request validation. */ interface LlmModelInfo { @@ -796,7 +816,7 @@ interface LlmCallConfigAdapterDefaults { ## Official DeepSeek request extensions -`ctx.deepseekLlmApiExtensions` is the provider-specific registry for additive top-level fields on `deepseek-official` requests. Contributor plugins use `register(field, provider)` to claim one field; the adapter calls `prepare(request)` after serializing its base body and merges the returned fields before HTTP. The prepared `accept()` transaction runs after 2xx, so a contributor can commit delivery state without treating a transport or provider rejection as acceptance. Preparation, collision, and acceptance failures use `REQUEST_EXTENSION` and fail the model request. A merged body that fails to serialize is sent without extension fields; acceptance is skipped and the provider plugin logs the omitted field names. +`ctx.deepseekLlmApiExtensions` is the provider-specific registry for additive top-level fields on `deepseek-official` requests. Contributor plugins use `register(field, provider)` to claim one field; the adapter calls `prepare(request)` after serializing its base body and merges the returned fields before HTTP. The prepared `accept()` transaction runs after 2xx, so a contributor can commit delivery state without treating a transport or provider rejection as acceptance. A contributor whose preparation throws is logged and omitted from that request, and an acceptance failure is logged without failing the request; a base-field collision uses `REQUEST_EXTENSION` and fails the model request. A merged body that fails to serialize is sent without extension fields; acceptance is skipped and the provider plugin logs the omitted field names. The [wire reference](../deepseek-llm-api-wire-extensions.md) defines the exact request headers, extension transaction, field versions, and receiver obligations. The shipped composition registers [`dsh_session_log`](../../packages/session/session-log-deepseek/README.md) as a lossless incremental canonical-log suffix and [`dsh_plugin_packages`](../../packages/llm/plugin-package-inventory-deepseek/README.md) as the complete active Loader-backed package set. These fields remain outside model messages and are absent from the pi-ai adapter path. @@ -931,8 +951,9 @@ register( field: K, provider: DeepSe /** * Prepare every currently registered field from one immutable base request. - * Preparation failures reject before HTTP dispatch. Field values are cloned and frozen; - * providers retain no mutable alias to the outgoing request. + * A provider whose preparation throws, or whose value cannot be cloned, is omitted + * from this request; the first such failure per field is logged. Only cancellation rejects. Field values are cloned + * and frozen; providers retain no mutable alias to the outgoing request. * @param request - exact serialized request facts before extension fields. * @returns detached fields and their idempotent joint acceptance transaction. */ diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 2f3c90e096..61ecc659bd 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -504,11 +504,31 @@ interface LlmConfigurableProvider { * from outside. */ declared?: boolean + /** + * Route endpoint the adapter uses when the profile sets no `baseURL`; the + * adapter may still send an individual model to that model's own endpoint. + * Absent when the route has no fixed endpoint. + */ + defaultBaseURL?: string + /** Authentication the adapter performs when the profile names no credential reference; absent when it reports none. */ + nativeAuth?: LlmNativeAuth /** Configuration diagnostic for repair; unaffected models may remain serviceable. */ error?: string } ``` +设置编辑器在提供方配置未设置端点或凭据引用时显示 `defaultBaseURL` 和 `nativeAuth`。`nativeAuth` 只列出环境变量名,不包含变量值。 + +```ts type-equiv +/** Authentication a provider route performs without a credential reference in its profile. */ +interface LlmNativeAuth { + /** Environment variables the route's authentication reads, in lookup order; empty when it reads none. */ + env: readonly string[] + /** Whether a stored OAuth sign-in can authenticate the route. */ + oauth: boolean +} +``` + ```ts type-equiv /** One adapter-discovered model; catalog membership is advisory, not request validation. */ interface LlmModelInfo { @@ -802,7 +822,7 @@ interface LlmCallConfigAdapterDefaults { ## DeepSeek 官方请求扩展 -`ctx.deepseekLlmApiExtensions` 是用于向 `deepseek-official` 请求添加顶层字段的提供方特定注册表。贡献插件通过 `register(field, provider)` 认领一个字段;适配器在序列化基础正文后调用 `prepare(request)`,并在 HTTP 前合并返回字段。已准备的 `accept()` 事务会在 2xx 后运行,因此贡献方可以提交交付状态,而不会把传输失败或提供方拒绝当作接受。准备、冲突与接受失败会使用 `REQUEST_EXTENSION`,并使模型请求失败。合并后的正文无法序列化时,请求不带扩展字段发出,跳过接受,并由提供方插件记录被省略的字段名。 +`ctx.deepseekLlmApiExtensions` 是用于向 `deepseek-official` 请求添加顶层字段的提供方特定注册表。贡献插件通过 `register(field, provider)` 认领一个字段;适配器在序列化基础正文后调用 `prepare(request)`,并在 HTTP 前合并返回字段。已准备的 `accept()` 事务会在 2xx 后运行,因此贡献方可以提交交付状态,而不会把传输失败或提供方拒绝当作接受。贡献方准备时抛错会被记录并在该次请求中省略,接受失败只记录告警而不使请求失败;与基础字段冲突时使用 `REQUEST_EXTENSION` 并使模型请求失败。合并后的正文无法序列化时,请求不带扩展字段发出,跳过接受,并由提供方插件记录被省略的字段名。 [协议参考](../deepseek-llm-api-wire-extensions.zh.md)定义确切的请求标头、扩展事务、字段版本和接收方义务。随附组合会将 [`dsh_session_log`](../../packages/session/session-log-deepseek/README.zh.md) 注册为无损增量权威日志后缀,并将 [`dsh_plugin_packages`](../../packages/llm/plugin-package-inventory-deepseek/README.zh.md) 注册为完整存活 Loader 包集合。这些字段仍位于模型消息之外,也不会进入 pi-ai 适配器路径。 @@ -937,8 +957,9 @@ register( field: K, provider: DeepSe /** * Prepare every currently registered field from one immutable base request. - * Preparation failures reject before HTTP dispatch. Field values are cloned and frozen; - * providers retain no mutable alias to the outgoing request. + * A provider whose preparation throws, or whose value cannot be cloned, is omitted + * from this request; the first such failure per field is logged. Only cancellation rejects. Field values are cloned + * and frozen; providers retain no mutable alias to the outgoing request. * @param request - exact serialized request facts before extension fields. * @returns detached fields and their idempotent joint acceptance transaction. */ diff --git a/docs/subsystems/persistence.md b/docs/subsystems/persistence.md index 7c6b47deb1..3c0c2586a7 100644 --- a/docs/subsystems/persistence.md +++ b/docs/subsystems/persistence.md @@ -311,6 +311,8 @@ type SessionPersistenceRevision = Branded<'SessionPersistenceRevision'> interface SessionPersistenceSnapshot { /** Detached metadata for one stored session. */ readonly header: SessionHeader + /** Header-only format classification; absent without versioned artifact metadata. */ + readonly formatStatus?: 'current' | 'migration-required' /** Opaque change token; see {@link SessionPersistence.stat}. */ readonly revision: SessionPersistenceRevision /** Logical event count, when the backend can provide it cheaply from metadata; otherwise absent. */ diff --git a/docs/subsystems/persistence.zh.md b/docs/subsystems/persistence.zh.md index 2883db7e22..dba0685409 100644 --- a/docs/subsystems/persistence.zh.md +++ b/docs/subsystems/persistence.zh.md @@ -311,6 +311,8 @@ type SessionPersistenceRevision = Branded<'SessionPersistenceRevision'> interface SessionPersistenceSnapshot { /** Detached metadata for one stored session. */ readonly header: SessionHeader + /** Header-only format classification; absent without versioned artifact metadata. */ + readonly formatStatus?: 'current' | 'migration-required' /** Opaque change token; see {@link SessionPersistence.stat}. */ readonly revision: SessionPersistenceRevision /** Logical event count, when the backend can provide it cheaply from metadata; otherwise absent. */ diff --git a/docs/subsystems/plan.i18n.yaml b/docs/subsystems/plan.i18n.yaml index 6ec7b89a19..e5ce0f0902 100644 --- a/docs/subsystems/plan.i18n.yaml +++ b/docs/subsystems/plan.i18n.yaml @@ -15,8 +15,8 @@ en: ee04468005fae8e1 zh: 1347d554102951f2 /plan-mode/the-exit-tool-and-the-plan-command: - en: ecf7fe520658b10f - zh: 9d6d2c4729e9a47e + en: b5bbc440552d7ade + zh: 17fb1cfed1bc48ef /plan-mode/the-service: en: 07c3eec12e0dc75c zh: 183d73f6672e2c5a diff --git a/docs/subsystems/plan.md b/docs/subsystems/plan.md index 1c29a87851..beba872f61 100644 --- a/docs/subsystems/plan.md +++ b/docs/subsystems/plan.md @@ -30,7 +30,7 @@ A missing, blank, or non-string `section` and any unknown key fail at plugin loa ## The exit tool and the `/plan` command -[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) stays registered while plan mode is inactive, so entering or leaving plan mode changes only the prompt section, never the request tool catalog; execution outside plan mode fails. In plan mode it requires a complete markdown plan starting with a `#` heading and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next accepted in-turn pre-step. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call carrying the user's feedback, so the model revises and presents again; a missing interaction channel and a service reload during review also fail the call rather than silently leaving plan mode. +[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) stays registered while plan mode is inactive, so entering or leaving plan mode changes only the prompt section, never the request tool catalog; execution outside plan mode fails. In plan mode it requires a complete markdown plan starting with a `#` heading and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next accepted in-turn pre-step. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel and a service reload during review also fail the call rather than silently leaving plan mode. When [`ctx.commands`](commands.md) is composed, the plugin registers `/plan [off|message]`: bare `/plan` selects plan mode, any other non-empty message selects it and then submits the text through `agent.steer()` so it becomes the next step's ordinary logged user message under plan guidance, and the exact argument `off` selects inactive, which also cancels a pending entry before it is appended and becomes visible to a request. diff --git a/docs/subsystems/plan.zh.md b/docs/subsystems/plan.zh.md index db2a7e1c2b..63463f0105 100644 --- a/docs/subsystems/plan.zh.md +++ b/docs/subsystems/plan.zh.md @@ -30,7 +30,7 @@ interface PlanModeConfig { ## 退出工具与 `/plan` 命令 -[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 在计划模式未激活时仍保持注册,因此进入或离开计划模式只改变提示词段落,绝不改变请求的工具目录;在计划模式之外执行会失败。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个被接受的轮内 pre-step 追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次携带用户反馈的失败调用,模型据此修订并再次呈交;评审期间交互通道缺失或服务重载同样使调用失败,而不是静默离开计划模式。 +[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 在计划模式未激活时仍保持注册,因此进入或离开计划模式只改变提示词段落,绝不改变请求的工具目录;在计划模式之外执行会失败。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个被接受的轮内 pre-step 追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次携带用户反馈的失败调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。评审期间交互通道缺失或服务重载同样使调用失败,而不是静默离开计划模式。 当 [`ctx.commands`](commands.zh.md) 被组合时,插件注册 `/plan [off|message]`:单独的 `/plan` 选择计划模式;任何其他非空消息先选择计划模式,再通过 `agent.steer()` 提交该文本,使其在计划指引下成为下一步骤的普通已记录用户消息;确切参数 `off` 选择未激活,这还会在待生效条目被追加并对请求可见之前将其取消。 diff --git a/docs/subsystems/ptc-runtime.i18n.yaml b/docs/subsystems/ptc-runtime.i18n.yaml index 4ad1978544..7c6f634157 100644 --- a/docs/subsystems/ptc-runtime.i18n.yaml +++ b/docs/subsystems/ptc-runtime.i18n.yaml @@ -6,14 +6,14 @@ 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 /ptc-runtime/captured-output-and-the-failure-taxonomy: - en: e5431173436c00c2 - zh: 4ba58e259bbadbc8 + en: 8eb1607888ab6efc + zh: 580c852d17b9413f /ptc-runtime/the-service: en: a82f828fa006c7e9 zh: 2279d36867335b57 diff --git a/docs/subsystems/ptc-runtime.md b/docs/subsystems/ptc-runtime.md index efab5bcefa..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: @@ -168,12 +177,12 @@ type PtcBindingFunction = (args: unknown) => Promise Logs are plain strings. Each source channel preserves emission order, while interleaving across independent channels is backend-dependent because channel metadata is not part of the seam. The runtime captures the program's console and stream output, and consumers render only the text. Implementations cap the serialized outer log-array plus completion-value or failure-message payload; fixed result-envelope syntax and consumer presentation whitespace are not part of that variable-payload ledger. Overflow is an explicit failure rather than in-band value substitution. -Failure kinds are **orthogonal outcomes reported independently** (per [defensive-patterns](../defensive-patterns.md)): a budget expiry is not an exception, an abort is not a timeout, and a substrate death (e.g. OOM) is neither: +Failure kinds are **orthogonal outcomes reported independently** (per [defensive-patterns](../defensive-patterns/general.md)): a budget expiry is not an exception, an abort is not a timeout, and a substrate death (e.g. OOM) is neither: ```ts type-equiv /** * Why a run failed. The kinds are orthogonal outcomes reported independently - * (per docs/defensive-patterns.md): a budget expiry is not an exception, an + * (per docs/defensive-patterns/general.md): a budget expiry is not an exception, an * abort is not a timeout, and a substrate death is neither. * * - `'exception'` — the program threw or failed to parse/transform. @@ -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 f35c5bd84d..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__` 不能遍历原型: @@ -168,12 +177,12 @@ type PtcBindingFunction = (args: unknown) => Promise 日志是纯字符串。每个来源通道保留自身的发出顺序;由于通道元数据不属于 seam,相互独立的通道如何交错由后端决定。运行时捕获程序的 console 与流输出,Consumer 只渲染文本。实现会对序列化后的外层日志数组,以及完成值或失败消息的组合载荷设置上限;固定的结果封装语法与 Consumer 展示空白不计入这份可变载荷计量。超限会显式失败,而不会在值中插入替代内容。 -失败类型是**正交的结果,独立报告**(见 [defensive-patterns](../defensive-patterns.zh.md)):预算耗尽不是异常,中止不是超时,基底崩溃(如 OOM)也不是二者中的任何一个: +失败类型是**正交的结果,独立报告**(见 [defensive-patterns](../defensive-patterns/general.zh.md)):预算耗尽不是异常,中止不是超时,基底崩溃(如 OOM)也不是二者中的任何一个: ```ts type-equiv /** * Why a run failed. The kinds are orthogonal outcomes reported independently - * (per docs/defensive-patterns.md): a budget expiry is not an exception, an + * (per docs/defensive-patterns/general.md): a budget expiry is not an exception, an * abort is not a timeout, and a substrate death is neither. * * - `'exception'` — the program threw or failed to parse/transform. @@ -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/scope.i18n.yaml b/docs/subsystems/scope.i18n.yaml index bce762d85d..f5dd6f8a73 100644 --- a/docs/subsystems/scope.i18n.yaml +++ b/docs/subsystems/scope.i18n.yaml @@ -4,7 +4,7 @@ # pnpm run verify-translation-pairing --write docs/subsystems/scope.md /scoped-registration: en: b786b68190a93d3f - zh: 8ea0fb2fac9a1529 + zh: d487dc4263d61a53 /scoped-registration/identity-and-dispatch-carrier: en: f4e1bdd96c43a845 zh: c74409f7f81bd0e0 diff --git a/docs/subsystems/scope.zh.md b/docs/subsystems/scope.zh.md index db791a407f..c48858d6ba 100644 --- a/docs/subsystems/scope.zh.md +++ b/docs/subsystems/scope.zh.md @@ -6,6 +6,8 @@ 源码:[`packages/core/scope/src/index.ts`](../../packages/core/scope/src/index.ts) 与 [`packages/core/scope/src/store.ts`](../../packages/core/scope/src/store.ts)。 + + ## 身份标识与分发载体 `ScopeKey` 是一个不透明的对象身份标识。已交付的 agent loop(智能体循环)使用活跃的 `Agent` 对象作为自身的 key,但该原语从不检视该对象。 diff --git a/docs/subsystems/session-query.md b/docs/subsystems/session-query.md index 1cf3dff325..1b07f1c698 100644 --- a/docs/subsystems/session-query.md +++ b/docs/subsystems/session-query.md @@ -24,6 +24,8 @@ interface SessionRecord { live: boolean /** Whether the active persistence backend currently lists the id, including a created-but-unmaterialized session it already observes. */ persisted: boolean + /** Current for live Sessions; otherwise the persistence format status when reported. */ + formatStatus?: 'current' | 'migration-required' } ``` diff --git a/docs/subsystems/session-query.zh.md b/docs/subsystems/session-query.zh.md index 2b8504dfb9..95b9b570af 100644 --- a/docs/subsystems/session-query.zh.md +++ b/docs/subsystems/session-query.zh.md @@ -24,6 +24,8 @@ interface SessionRecord { live: boolean /** Whether the active persistence backend currently lists the id, including a created-but-unmaterialized session it already observes. */ persisted: boolean + /** Current for live Sessions; otherwise the persistence format status when reported. */ + formatStatus?: 'current' | 'migration-required' } ``` diff --git a/docs/subsystems/session-title.i18n.yaml b/docs/subsystems/session-title.i18n.yaml index a701f0ad9d..72d5fb61aa 100644 --- a/docs/subsystems/session-title.i18n.yaml +++ b/docs/subsystems/session-title.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/session-title.md /session-titles: - en: a0ad8d5f000e5258 - zh: 9527bc25711342de + en: 40ede027d4f62b35 + zh: 0efd7cb0710a0ed9 /session-titles/durable-title-state: en: c6be2d86647daa6f zh: fb259d9fb4738f39 /session-titles/auxiliary-request-record: - en: c36916905dad76f9 - zh: c82ff6c3d62e53e5 + en: e5d5045ddfa7e771 + zh: 8c989ef59853cce4 /session-titles/provider-input-and-output: - en: 886e036e442ae06a - zh: 49f95782b8aa9bf3 + en: 28ee84e62db773f0 + zh: 93beca6fbcd02c4e diff --git a/docs/subsystems/session-title.md b/docs/subsystems/session-title.md index 699b0148a6..f953d3fcf2 100644 --- a/docs/subsystems/session-title.md +++ b/docs/subsystems/session-title.md @@ -2,7 +2,7 @@ English | [中文](session-title.zh.md) -Durable latest-wins title state and the optional asynchronous provider vocabulary owned by [`@deepseek-ai/dsh-session-title`](../../packages/session/session-title). The shared LLM helper owns the exact auxiliary request record. Package READMEs own timing, fallback, failure, and fork behavior; the generated [persistence catalog](../persistence-catalog.md) owns the complete event declarations. +Durable latest-wins title state and the optional asynchronous provider vocabulary owned by [`@deepseek-ai/dsh-session-title`](../../packages/session/session-title). The shared execution module owns the exact auxiliary request record. Package READMEs own timing, fallback, failure, and fork behavior; the generated [persistence catalog](../persistence-catalog.md) owns the complete event declarations. Sources: [`packages/session/session-title/src/index.ts`](../../packages/session/session-title/src/index.ts), [`packages/session/session-title-llm/src/index.ts`](../../packages/session/session-title-llm/src/index.ts) @@ -64,7 +64,7 @@ interface SessionTitleSnapshot extends SessionTitleEventData { ## Auxiliary request record -The shared LLM helper records each validated, dispatchable title request before calling the model. The payload reproduces the model-visible system and message input, routing, output limit, resolved reasoning effort, provider ownership, and source-message attribution even when generation later fails. +The shared execution module records each validated, dispatchable title request before calling the model. The payload reproduces the model-visible system and message input, routing, output limit, resolved reasoning effort, provider ownership, and source-message attribution even when generation later fails. ```ts type-equiv /** Exact model-visible request recorded before one auxiliary title dispatch. */ @@ -88,7 +88,7 @@ interface SessionTitleLlmRequestEventData { ## Provider input and output -The service snapshots eligible messages through one revision. A provider returns only seqs from that request; service-owned acceptance verifies ordering, normalizes the title, enforces the byte limit, and appends the title with its source-message seqs and source kind. +The service snapshots eligible messages through one revision and, immediately before each provider call, the latest accepted title including the fallback it just ensured. A provider returns only seqs from that request; service-owned acceptance verifies ordering, normalizes the title, enforces the byte limit, and appends the title with its source-message seqs and source kind. ```ts type-equiv /** One eligible human text message exposed to title providers. */ @@ -114,6 +114,12 @@ interface SessionTitleProviderRequest { readonly messages: readonly SessionTitleUserMessage[] /** Exact current logged main-request route, when one has been recorded. */ readonly route?: SessionTitleModelIdentity + /** + * Latest accepted title captured at invocation, including an accepted + * fallback whose event may follow the last eligible message. Absent before + * any title is accepted. The provider decides whether and how to use it. + */ + readonly currentTitle?: SessionTitleSnapshot /** Cancellation for supersession, disposal, timeout composition, or the explicit caller. */ readonly signal: AbortSignal } @@ -140,7 +146,7 @@ interface SessionTitleProvider { readonly automatic: SessionTitleAutomaticMode /** * Produce one title revision. - * @param request - message snapshot, current route, session, and cancellation. + * @param request - message snapshot, current title, current route, session, and cancellation. * @returns proposed title plus exact input seqs and the optional provider/model route used to generate it. */ generate(request: SessionTitleProviderRequest): Promise @@ -193,7 +199,8 @@ async refresh(session: Session, signal?: AbortSignal): Promise @@ -193,7 +199,8 @@ async refresh(session: Session, signal?: AbortSignal): Promise /** - * Search visible Session content without resuming an Agent. + * Search visible Session content without resuming an Agent. A non-owner + * receives only the hits whose Session `allows()` admits; `hasMore` + * describes the bounded result before that filtering. * @param request - literal message-content query. * @param signal - cancellation for list and search reads. * @returns authorized bounded Session search results. */ -@Remote('search') search(request: SessionSearchRequest, signal: AbortSignal): Promise +@Remote('search') async search(request: SessionSearchRequest, 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 @@ -922,10 +924,10 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * Fork one cold-readable exact event prefix into a new Session. An omitted * boundary selects the latest completed-turn prefix; an open cut receives * synthetic fork closers. - * @param request - source Session and optional exact inclusive event boundary. + * @param request - source Session, optional exact inclusive event boundary, and migration preflight choice. * @returns the new Session identity. */ -@Remote('fork') fork(request: SessionForkRequest): Promise +@Remote('fork') async fork(request: SessionForkRequest): Promise /** * Admit one prompt after explicitly resuming its Session. @@ -933,7 +935,7 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * @param signal - caller cancellation before prompt admission begins. * @returns acknowledgement that the Agent accepted the prompt. */ -@Remote('prompt') prompt(request: SessionPromptRequest, signal: AbortSignal): Promise +@Remote('prompt') async prompt(request: SessionPromptRequest, signal: AbortSignal): Promise /** * Read one image proven reachable from the addressed Session log. @@ -962,7 +964,7 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * @param signal - cancellation for persistence reads. * @returns one chronological page. */ -@Remote('page') page(request: SessionPageRequest, signal: AbortSignal): Promise +@Remote({ name: 'page', resources: { session: addressedSession } }) page(request: SessionPageRequest, signal: AbortSignal): Promise /** * Follow one Session log from its opening or resume cursor. @@ -971,13 +973,13 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * @returns a complete opening snapshot followed by gap-free durable event * frames and optional cursorless assistant-stream frames. */ -@Remote({ mode: 'stream' }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable +@Remote({ mode: 'stream', resources: { session: addressedSession } }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable /** - * Read all registered projections without activating an Agent. + * Read exact projections, returning cached hints only when migration is required. * @param request - Session whose current values are required. - * @param signal - cancellation for the Session observation. - * @returns complete baseline, or null when the Session does not exist. + * @param signal - cancellation for the Session read. + * @returns a sequenced baseline, cached hints when migration is deferred, or null when absent. */ @Remote('projections') async projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise @@ -986,7 +988,7 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * @param signal - cancellation owned by the Remote stream carrier. * @returns one complete baseline followed by live replacement frames. */ -@Remote({ mode: 'stream' }) control(signal: AbortSignal): AsyncIterable +@Remote({ mode: 'stream' }) async *control(signal: AbortSignal): AsyncIterable ``` Types: [SessionId](core.md) · [SessionInspection](persistence.md) · [SessionSearchRequest](session-query.md) diff --git a/docs/subsystems/session.zh.md b/docs/subsystems/session.zh.md index 8085cb8067..a3e5446b61 100644 --- a/docs/subsystems/session.zh.md +++ b/docs/subsystems/session.zh.md @@ -852,17 +852,19 @@ inspect( sessionId: SessionId, signal?: AbortSignal, ): Promise /** - * Search visible Session content without resuming an Agent. + * Search visible Session content without resuming an Agent. A non-owner + * receives only the hits whose Session `allows()` admits; `hasMore` + * describes the bounded result before that filtering. * @param request - literal message-content query. * @param signal - cancellation for list and search reads. * @returns authorized bounded Session search results. */ -@Remote('search') search(request: SessionSearchRequest, signal: AbortSignal): Promise +@Remote('search') async search(request: SessionSearchRequest, 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 @@ -926,10 +928,10 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * Fork one cold-readable exact event prefix into a new Session. An omitted * boundary selects the latest completed-turn prefix; an open cut receives * synthetic fork closers. - * @param request - source Session and optional exact inclusive event boundary. + * @param request - source Session, optional exact inclusive event boundary, and migration preflight choice. * @returns the new Session identity. */ -@Remote('fork') fork(request: SessionForkRequest): Promise +@Remote('fork') async fork(request: SessionForkRequest): Promise /** * Admit one prompt after explicitly resuming its Session. @@ -937,7 +939,7 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * @param signal - caller cancellation before prompt admission begins. * @returns acknowledgement that the Agent accepted the prompt. */ -@Remote('prompt') prompt(request: SessionPromptRequest, signal: AbortSignal): Promise +@Remote('prompt') async prompt(request: SessionPromptRequest, signal: AbortSignal): Promise /** * Read one image proven reachable from the addressed Session log. @@ -966,7 +968,7 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * @param signal - cancellation for persistence reads. * @returns one chronological page. */ -@Remote('page') page(request: SessionPageRequest, signal: AbortSignal): Promise +@Remote({ name: 'page', resources: { session: addressedSession } }) page(request: SessionPageRequest, signal: AbortSignal): Promise /** * Follow one Session log from its opening or resume cursor. @@ -975,13 +977,13 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * @returns a complete opening snapshot followed by gap-free durable event * frames and optional cursorless assistant-stream frames. */ -@Remote({ mode: 'stream' }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable +@Remote({ mode: 'stream', resources: { session: addressedSession } }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable /** - * Read all registered projections without activating an Agent. + * Read exact projections, returning cached hints only when migration is required. * @param request - Session whose current values are required. - * @param signal - cancellation for the Session observation. - * @returns complete baseline, or null when the Session does not exist. + * @param signal - cancellation for the Session read. + * @returns a sequenced baseline, cached hints when migration is deferred, or null when absent. */ @Remote('projections') async projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise @@ -990,7 +992,7 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | * @param signal - cancellation owned by the Remote stream carrier. * @returns one complete baseline followed by live replacement frames. */ -@Remote({ mode: 'stream' }) control(signal: AbortSignal): AsyncIterable +@Remote({ mode: 'stream' }) async *control(signal: AbortSignal): AsyncIterable ``` Types: [SessionId](core.zh.md) · [SessionInspection](persistence.zh.md) · [SessionSearchRequest](session-query.zh.md) 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 67850a5a7d..5da22cf2d1 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -10,19 +10,19 @@ zh: 441ed13ff3f81d2a /web-client-slots/cardinality-and-scope: en: 5b0ada069239576b - zh: 7e71ced7f17d78a6 + zh: 84e1e6b253d1461e /web-client-slots/component-inputs: en: 9cb70abb2e39b958 zh: cd4b6f1705d90e17 /web-client-slots/framework-provided-hooks: - en: 2fcfc55fbac80f72 - zh: ea3016f394c56b07 + en: c9f8d836214623ae + zh: 76dec55006396535 /web-client-slots/developer-provided-injection: - en: 7081335b356bf46b - zh: 631e60d29daf7196 -/web-client-slots/current-hierarchy: - en: 8a4cc4b8608ce0f6 - zh: 21281dcf047503b2 + 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 8a9448a4f8..12a8d89b8f 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -84,11 +84,12 @@ The shipped adapters add these standard props. They are available according to t | Availability | Props | Owner | |---|---|---| -| every scope | `useSessions`, `useSessionStatus`, `useSessionRetainInfo` | `ui-session` | -| every scope | `useWorkspaces` | `ui-workspace` | +| every scope | `useSessions`, `useSessionStatus`, `useSessionRetainInfo`, `useSessionAccess` | `ui-session` | +| every scope | `useWorkspaces`, `useWorkspaceAccess` | `ui-workspace` | +| every scope | `useRemoteAccess` (the `global` resource) | `api-remote-access` | | every scope | `usePanelInfo` | `ui-layout` | -| `session` | `sessionId`, `useSession`, `useProjection` | `ui-session` | -| `session-maybe` | optional `sessionId`, `useSession`, `useProjection` results | `ui-session` | +| `session` | `sessionId`, `useSession`, `useProjection`, `useAccess` (the bound Session's answer) | `ui-session` | +| `session-maybe` | optional `sessionId`, `useSession`, `useProjection`, `useAccess` results | `ui-session` | | `session` | `useConversation`, `useInput`, `inputActions` | `ui-conversation` | | `session-maybe` | optional `useConversation`, `useInput`, `inputActions` results | `ui-conversation` | | `session` | `useChat` | `ui-chat` | @@ -106,95 +107,86 @@ A reserved `hooks` object in that return value accepts bare `getSnapshot`/`subsc The owner of a slot may put an `inject` face in the child declaration when every occupant needs the same capability. Plain members reach all occupants unchanged. Function-valued members inside its `hooks` object are hook factories; they receive the slot's standard props and optional per-render `hookContext`, then return the constrained hook exposed to the occupant. `conversation.chat.node` uses this mechanism to provide `useTurnData(key)` for the node currently being rendered. -The session-scoped `conversation.chat.reasoning-body` chain receives unchanged `text` and `running` values for an expanded reasoning body. Its owner renders original compact Markdown when all entries decline; display contributions retain access to the original reasoning. - 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.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 bf8bc0cac7..77f3717f36 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -61,6 +61,8 @@ Slot 声明固定两个相互独立的维度。 对于 `single`、`list` 和 `keyed` cell,`priority` 是遮蔽优先级;对于 `chain`,它是选举顺序。数值越小越先运行或渲染。普通增量贡献应选用新的 list `id` 或 keyed `key`;复用已有 cell 表示有意替换其展示。 + + ## 组件输入 注册组件会在 binding 位置收到组装后的输入。组件应从这些类型推导 props,不要重新抄写成员。 @@ -84,11 +86,12 @@ Slot 声明固定两个相互独立的维度。 | 可用范围 | Props | Owner | |---|---|---| -| 所有 scope | `useSessions`、`useSessionStatus`、`useSessionRetainInfo` | `ui-session` | -| 所有 scope | `useWorkspaces` | `ui-workspace` | +| 所有 scope | `useSessions`、`useSessionStatus`、`useSessionRetainInfo`、`useSessionAccess` | `ui-session` | +| 所有 scope | `useWorkspaces`、`useWorkspaceAccess` | `ui-workspace` | +| 所有 scope | `useRemoteAccess`(`global` 资源) | `api-remote-access` | | 所有作用域 | `usePanelInfo` | `ui-layout` | -| `session` | `sessionId`、`useSession`、`useProjection` | `ui-session` | -| `session-maybe` | 结果可选的 `sessionId`、`useSession`、`useProjection` | `ui-session` | +| `session` | `sessionId`、`useSession`、`useProjection`、`useAccess`(所绑定 Session 的答案) | `ui-session` | +| `session-maybe` | 结果可选的 `sessionId`、`useSession`、`useProjection`、`useAccess` | `ui-session` | | `session` | `useConversation`、`useInput`、`inputActions` | `ui-conversation` | | `session-maybe` | 结果可选的 `useConversation`、`useInput`、`inputActions` | `ui-conversation` | | `session` | `useChat` | `ui-chat` | @@ -106,95 +109,88 @@ Renderer 还会根据声明的 store 创建 `useStore`,并根据声明的 loca 当每个 occupant 都需要同一种能力时,slot owner 可以在 child 声明里放置 `inject` face。普通成员会原样交给所有 occupant;其 `hooks` 对象中的函数成员是 hook factory,它会收到 slot 的标准 props 与可选的逐次渲染 `hookContext`,再返回提供给 occupant 的受限 hook。`conversation.chat.node` 正是通过这种机制,为当前渲染的 node 提供 `useTurnData(key)`。 -Session 作用域的 `conversation.chat.reasoning-body` 链为展开的思考正文提供未修改的 `text` 和 `running`。所有条目都拒绝认领时,owner 渲染原始紧凑 Markdown;显示贡献保留查看原始思考内容的能力。 - 一次渲染时 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.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/ssh.i18n.yaml b/docs/subsystems/ssh.i18n.yaml index 1451fd22a2..d432de67ba 100644 --- a/docs/subsystems/ssh.i18n.yaml +++ b/docs/subsystems/ssh.i18n.yaml @@ -6,8 +6,8 @@ en: 847a37e7a77c8a3f zh: 33f4de7837ec2faa /ssh/execution-coordinates: - en: 77968e8be38ab9be - zh: f5bf0f62b32e45c7 + en: 6dca62a58ecbc1ff + zh: 1ebb7dbe79927701 /ssh/transport-and-trust: en: e807ecd0222acb80 zh: b2077393b549a7fe diff --git a/docs/subsystems/ssh.md b/docs/subsystems/ssh.md index 04480e6ec3..440e42c26d 100644 --- a/docs/subsystems/ssh.md +++ b/docs/subsystems/ssh.md @@ -8,7 +8,7 @@ The [SSH provider family](../../packages/ssh/README.md) supplies one remote file Filesystem identities, executable lookup, process cwd, sandbox workspace roots and language-server file URLs refer to the SSH host. Providers canonicalize paths where the files exist, preserving filesystem interpretation of `symlink/..`. The policy resolver carries absolute execution-world spelling without trying to resolve remote paths on the Harness host. -`processPath()` supplies a path usable by the paired subprocess provider. `processPathFromHostPath()` remains unavailable for SSH; installing a remote artifact does not make an arbitrary host path portable. [`NodePtcRuntime`](../../packages/ptc-runtime/ptc-runtime-node/README.md) therefore takes an explicitly installed, digest-verified remote bootstrap. +`processPath()` supplies a path usable by the paired subprocess provider. `processPathFromHostPath()` remains unavailable for SSH; installing a remote artifact does not make an arbitrary host path portable. [`NodePtcRuntime`](../../packages/ptc-runtime/ptc-runtime-node/README.md) therefore takes the verified remote launch configuration: an installed script bootstrap or the [helper executable’s embedded worker](../../packages/ssh/ssh-helper-runtime/README.md). ## Transport and trust @@ -30,23 +30,36 @@ See the [decision record](../../.agents/notes/implemented/architecture/2026-09-1 ## Connection API +```ts type-equiv +/** Installed helper invocation; script deployments may also install a PTC bootstrap. */ +type HelperLaunch = { + /** Run the installed script with a separately installed Node executable. */ + kind: 'node-script' + /** Absolute remote Node executable. */ + node: string + /** Absolute remote PTC bootstrap; requires bootstrapHash. */ + bootstrapPath?: string + /** Lowercase SHA-256 of bootstrapPath; requires that path. */ + bootstrapHash?: string +} | { + /** Run the helper executable with its embedded Node and PTC worker. */ + kind: 'executable' +} +``` + ```ts type-equiv /** Deployment-owned SSH identity and installed helper; no model argument selects these values. */ interface Config { /** OpenSSH host alias, including its existing user, key and known-host configuration. */ host: string - /** Absolute remote Node executable. */ - node: string + /** Explicit script or self-contained executable invocation. */ + launch: HelperLaunch /** Absolute path to the installed, bundled helper entry. */ helper: string /** SHA-256 of that bundled helper; mismatches refuse the connection. */ helperHash: string /** Absolute remote default workspace. */ workspace: string - /** Optional preinstalled built PTC entry, paired with its expected digest. */ - bootstrapPath?: string - /** SHA-256 of bootstrapPath; both fields must be supplied together. */ - bootstrapHash?: string /** Connection and administrative-request deadline, at most 2,147,483,647 milliseconds. */ requestTimeoutMs?: number /** Maximum JSON payload bytes per helper request or response. */ @@ -67,10 +80,8 @@ declare class SshConnection extends Service { constructor(ctx: Context, config: Config); /** Hold plugin readiness until the remote identity and helper digest are verified. */ async [Service.init](): Promise; - /** Verified remote Node executable for the paired PTC runtime. */ - get nodeExecutable(): string; - /** Verified preinstalled PTC entry; unconfigured runtimes fail before program execution. */ - get bootstrapPath(): string; + /** Verified remote PTC launch configuration; script deployments require a verified bootstrap. */ + get ptcLaunch(): { kind: 'embedded'; executable: string } | { kind: 'node-script'; executable: string; bootstrapPath: string }; /** * Send a helper operation; cancellation never replays an ambiguous mutation. * @param method - the private helper operation. diff --git a/docs/subsystems/ssh.zh.md b/docs/subsystems/ssh.zh.md index 32d7c8b6c2..862d8402a1 100644 --- a/docs/subsystems/ssh.zh.md +++ b/docs/subsystems/ssh.zh.md @@ -8,7 +8,7 @@ 文件系统身份、可执行文件查找、进程 cwd、沙箱工作区根目录及语言服务器文件 URL 都指向 SSH 主机。提供方在文件实际存在的位置规范化路径,保留文件系统对 `symlink/..` 的解释。策略解析器保留执行环境中的绝对路径写法,不尝试在 Harness 主机上解析远端路径。 -`processPath()` 提供配套子进程提供方可用的路径。SSH 的 `processPathFromHostPath()` 仍不可用;安装远端产物不意味着任意主机路径可移植。因此 [`NodePtcRuntime`](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md) 使用显式安装并经过摘要验证的远端引导程序。 +`processPath()` 提供配套子进程提供方可用的路径。SSH 的 `processPathFromHostPath()` 仍不可用;安装远端产物不意味着任意主机路径可移植。因此 [`NodePtcRuntime`](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md) 使用验证后的远端启动配置:已安装的脚本引导程序,或 [helper 可执行文件内嵌的 worker](../../packages/ssh/ssh-helper-runtime/README.zh.md)。 ## 传输与信任 @@ -30,23 +30,36 @@ headless 通过已挂载的文件系统提供方记录和检查 Session cwd。 ## 连接 API +```ts type-equiv +/** Installed helper invocation; script deployments may also install a PTC bootstrap. */ +type HelperLaunch = { + /** Run the installed script with a separately installed Node executable. */ + kind: 'node-script' + /** Absolute remote Node executable. */ + node: string + /** Absolute remote PTC bootstrap; requires bootstrapHash. */ + bootstrapPath?: string + /** Lowercase SHA-256 of bootstrapPath; requires that path. */ + bootstrapHash?: string +} | { + /** Run the helper executable with its embedded Node and PTC worker. */ + kind: 'executable' +} +``` + ```ts type-equiv /** Deployment-owned SSH identity and installed helper; no model argument selects these values. */ interface Config { /** OpenSSH host alias, including its existing user, key and known-host configuration. */ host: string - /** Absolute remote Node executable. */ - node: string + /** Explicit script or self-contained executable invocation. */ + launch: HelperLaunch /** Absolute path to the installed, bundled helper entry. */ helper: string /** SHA-256 of that bundled helper; mismatches refuse the connection. */ helperHash: string /** Absolute remote default workspace. */ workspace: string - /** Optional preinstalled built PTC entry, paired with its expected digest. */ - bootstrapPath?: string - /** SHA-256 of bootstrapPath; both fields must be supplied together. */ - bootstrapHash?: string /** Connection and administrative-request deadline, at most 2,147,483,647 milliseconds. */ requestTimeoutMs?: number /** Maximum JSON payload bytes per helper request or response. */ @@ -67,10 +80,8 @@ declare class SshConnection extends Service { constructor(ctx: Context, config: Config); /** Hold plugin readiness until the remote identity and helper digest are verified. */ async [Service.init](): Promise; - /** Verified remote Node executable for the paired PTC runtime. */ - get nodeExecutable(): string; - /** Verified preinstalled PTC entry; unconfigured runtimes fail before program execution. */ - get bootstrapPath(): string; + /** Verified remote PTC launch configuration; script deployments require a verified bootstrap. */ + get ptcLaunch(): { kind: 'embedded'; executable: string } | { kind: 'node-script'; executable: string; bootstrapPath: string }; /** * Send a helper operation; cancellation never replays an ambiguous mutation. * @param method - the private helper operation. diff --git a/docs/subsystems/subagent.i18n.yaml b/docs/subsystems/subagent.i18n.yaml index 104548c425..21fa5dbbde 100644 --- a/docs/subsystems/subagent.i18n.yaml +++ b/docs/subsystems/subagent.i18n.yaml @@ -9,8 +9,8 @@ en: 8c92b131f67997f6 zh: c2dc606a0859420c /subagents/local-children-and-activations: - en: d926d4777ec0f11e - zh: 0ae6076e24b66401 + en: 6f87231d18d82916 + zh: 9f064b23058f8766 /subagents/messages-and-interruption: en: 623b06b3c12540bc zh: f56c6341e1c62768 diff --git a/docs/subsystems/subagent.md b/docs/subsystems/subagent.md index 8ad39194a1..30e064f25c 100644 --- a/docs/subsystems/subagent.md +++ b/docs/subsystems/subagent.md @@ -19,10 +19,10 @@ Optional `request.cwd` selects the child's initial directory; relative paths res */ interface SubagentCapabilities { readonly agentOptions: boolean + /** Supports selecting a preset independently of the parent's composition. */ + readonly agentPreset: boolean readonly outputSchema: boolean readonly depthLimit: boolean - readonly toolFilter: boolean - readonly persona: boolean } ``` @@ -70,6 +70,12 @@ interface SubagentActivation { interface SubagentStartRequest { /** Initial child directory; relative paths resolve against the parent's current directory. Omitted inherits that directory at start. */ readonly cwd?: string + /** + * Independent preset id; omission joins the parent's current generation. + * Requires a provider with `capabilities.agentPreset` that does not inherit + * parent context. + */ + readonly agentPreset?: string /** Optional short display label persisted with a session-backed child. */ readonly label?: string /** Content delivered as the child's user message. */ @@ -108,22 +114,6 @@ interface SubagentStartRequest { * start otherwise. */ readonly maxDepth?: number - /** - * Optional child tool scoping. Requires {@link SubagentCapabilities.toolFilter}; - * rejected at start otherwise. In-process backends apply it as a scoped - * `tools.restrict()` in the child's creation window: the named tools vanish - * from the child's prompt AND refuse to execute (one visibility), with loud - * unknown-name validation. - */ - readonly toolFilter?: ToolRestriction - /** - * Optional per-child persona. Requires {@link SubagentCapabilities.persona}; - * rejected at start otherwise. In-process backends register it as a scoped - * `deployment:persona-prefix` section on the child, SHADOWING the deployment's - * persona for this child alone — same template semantics as the deployment - * persona (strict `{{…}}` interpolation against the registered variables). - */ - readonly persona?: string } ``` @@ -137,6 +127,8 @@ interface ResolvedSubagentStartRequest extends SubagentStartRequest { ## Local children and activations +Spawn alone supports an independent `agentPreset`; omission and fork inherit the parent's active composition. The [child preset rules](../../packages/subagent/subagent/README.md#restoring-child-composition) define explicit selection, event ordering, and historical restoration. + A local child has a durable Session and at most one live activation. The manager reserves identity and capacity, prepares the child through its backend, and owns input admission, cold resume, and child-first disposal. The activation result settles after resource release and completion notification. Disposal reports cleanup failure separately without replacing a captured result. Structured capture closes input for that activation; a later cold resume does not inherit the output schema. ```ts type-equiv @@ -184,7 +176,7 @@ interface ContinuableCreateSpec { sendMessage authorizes the exact live sender and permits only adjacent local agents. Running children receive steering input; absent continuable children resume from persistence. External executions reject follow-ups. Both local and external executions automatically report their final text, structured result, diagnostic, and status in the parent settlement notice. Local children can also send messages through send_message. caller delivery suppresses settlement notices. drainDescendants and drainChildren await owned work teardown for local and external activations. ```ts type-equiv -/** Durable attribution for one model-authored message between adjacent Agents. */ +/** Durable attribution for one model-authored message between Agents. */ interface AgentMessageSource { readonly kind: 'agent-message' /** A message another agent addressed to this one (`relay` context form). */ diff --git a/docs/subsystems/subagent.zh.md b/docs/subsystems/subagent.zh.md index 220ffe5d42..c6d7119a25 100644 --- a/docs/subsystems/subagent.zh.md +++ b/docs/subsystems/subagent.zh.md @@ -19,10 +19,10 @@ */ interface SubagentCapabilities { readonly agentOptions: boolean + /** Supports selecting a preset independently of the parent's composition. */ + readonly agentPreset: boolean readonly outputSchema: boolean readonly depthLimit: boolean - readonly toolFilter: boolean - readonly persona: boolean } ``` @@ -70,6 +70,12 @@ interface SubagentActivation { interface SubagentStartRequest { /** Initial child directory; relative paths resolve against the parent's current directory. Omitted inherits that directory at start. */ readonly cwd?: string + /** + * Independent preset id; omission joins the parent's current generation. + * Requires a provider with `capabilities.agentPreset` that does not inherit + * parent context. + */ + readonly agentPreset?: string /** Optional short display label persisted with a session-backed child. */ readonly label?: string /** Content delivered as the child's user message. */ @@ -108,22 +114,6 @@ interface SubagentStartRequest { * start otherwise. */ readonly maxDepth?: number - /** - * Optional child tool scoping. Requires {@link SubagentCapabilities.toolFilter}; - * rejected at start otherwise. In-process backends apply it as a scoped - * `tools.restrict()` in the child's creation window: the named tools vanish - * from the child's prompt AND refuse to execute (one visibility), with loud - * unknown-name validation. - */ - readonly toolFilter?: ToolRestriction - /** - * Optional per-child persona. Requires {@link SubagentCapabilities.persona}; - * rejected at start otherwise. In-process backends register it as a scoped - * `deployment:persona-prefix` section on the child, SHADOWING the deployment's - * persona for this child alone — same template semantics as the deployment - * persona (strict `{{…}}` interpolation against the registered variables). - */ - readonly persona?: string } ``` @@ -137,6 +127,8 @@ interface ResolvedSubagentStartRequest extends SubagentStartRequest { ## 本地子代理与 activation +只有 spawn 支持独立的 `agentPreset`;省略选择与 fork 都继承父方的活跃组装。[子级 preset 规则](../../packages/subagent/subagent/README.zh.md#restoring-child-composition)定义显式选择、事件顺序和历史恢复行为。 + 本地子代理拥有持久 Session,最多有一个在线 activation。Manager 预留身份和容量,通过后端准备子代理,并管理输入准入、冷恢复以及先子后父的释放顺序。activation 结果在资源释放和完成通知之后结算。释放操作单独报告清理失败,不会覆盖已捕获的结果。结构化结果提交会关闭该 activation 的输入;之后的冷恢复不会继承输出 schema。 ```ts type-equiv @@ -184,7 +176,7 @@ interface ContinuableCreateSpec { sendMessage 根据确切的在线发送者实例授权,仅允许相邻本地代理通信。运行中的子代理接收引导输入;不在线的可继续子代理从持久化恢复。外部执行拒绝后续消息。本地与外部执行都会通过父级结束通知自动回传最终文本、结构化结果、诊断和状态。本地子代理也可以通过 send_message 发送消息。caller 回传会抑制结束通知。drainDescendants 与 drainChildren 对本地和外部 activation 都等待所属任务清理完成。 ```ts type-equiv -/** Durable attribution for one model-authored message between adjacent Agents. */ +/** Durable attribution for one model-authored message between Agents. */ interface AgentMessageSource { readonly kind: 'agent-message' /** A message another agent addressed to this one (`relay` context form). */ diff --git a/docs/subsystems/translation.i18n.yaml b/docs/subsystems/translation.i18n.yaml index a6f25d640c..58d834341f 100644 --- a/docs/subsystems/translation.i18n.yaml +++ b/docs/subsystems/translation.i18n.yaml @@ -9,11 +9,11 @@ en: 485abf6107c73e68 zh: 78a274d488274035 /text-translation/failures-and-data-handling: - en: cf92a1920650888c - zh: 3e8d3aa244cc8d46 + en: 436e55e924e3ad1e + zh: c8548fda1e86b078 /text-translation/persistent-translations: en: 40d175fbe66fd4cd zh: bff18511a8d386e9 /text-translation/reasoning-display: - en: 209dbbbf3000e087 - zh: f8e661359d0f3cb5 + en: aaf7d361b682fe4a + zh: 485e89bdb063665e diff --git a/docs/subsystems/translation.md b/docs/subsystems/translation.md index c5de82676f..306b5baf84 100644 --- a/docs/subsystems/translation.md +++ b/docs/subsystems/translation.md @@ -14,7 +14,7 @@ The service exposes its configured `maxTextChars`, measured in UTF-16 code units `TranslationError` carries a `TranslationErrorCode` distinguishing text limits, HTTP failures, invalid responses, response limits, owned deadlines, and request failures. `TRANSLATION_SESSION_REQUIRED` rejects a missing persistence backend or Session; `TRANSLATION_SESSION_INACTIVE` rejects an uncached inactive Session before provider dispatch; `TRANSLATION_STORAGE_ERROR` rejects invalid saved records or failed durability. Provider diagnostics omit submitted text and response bodies. Failed calls do not select another provider. Responses are validated as external JSON and redirects are rejected. -`TRANSLATION_UNAVAILABLE` rejects a missing active built-in owner or registered route, unconfigured credentials, absent exact `deepseek-flash` catalog membership, an owner/model-list/official credential-reference change before dispatch, provider withdrawal, or a prepared call whose reasoning effort is not `off`. A native `finish` with reason `error` maps to `TRANSLATION_REQUEST_FAILED`; a missing or other non-`stop` finish maps to `TRANSLATION_INVALID_RESPONSE`. +`TRANSLATION_UNAVAILABLE` rejects a missing active built-in owner or registered route, unconfigured credentials, absent exact `deepseek-flash` catalog membership, an owner, model-configuration (Official `models` or Account `modelOverrides`), or Official credential-reference change before dispatch, provider withdrawal, or a prepared call whose reasoning effort is not `off`. A native `finish` with reason `error` maps to `TRANSLATION_REQUEST_FAILED`; a missing or other non-`stop` finish maps to `TRANSLATION_INVALID_RESPONSE`. Google receives source text in a form POST body; Bing receives it in a JSON POST body. Both are remote services. Their anonymous endpoints provide no supported developer availability or quota guarantee. Regional connectivity must be verified on the user's network. @@ -30,7 +30,7 @@ The [optional bundle](../../packages/experimental/cot-translation-bundle/README. `CotTranslationPreferences` contains the accepted provider and target language. `CotTranslationSnapshot` pairs these preferences with the translator's current `maxTextChars` and eligible provider IDs. The browser reads this Host snapshot before registering translation controls, including when local settings storage is unavailable. Accepted settings updates and reconnects refresh both values; a changed request limit cancels and splits the expanded text again. -The session-scoped `conversation.chat.reasoning-body` chain receives the original `text` and `running` flag. Chat renders original Markdown when no contribution claims it. While enabled, the GUI translates completed paragraphs and request-sized prefixes of long streaming paragraphs only after expansion, and restores completed results from the current Session. Its local cache only optimizes that disclosure. The unfinished tail remains original. Original remains accessible. Closing the disclosure, switching provider or language, and unloading cancel outstanding calls and exclude late results. Provider failure preserves the original and requires an explicit retry; translated text never replaces original Session events or model input. +The GUI registers in the session-scoped `conversation.chat.reasoning.body` single Slot, replacing Chat's default entry. Both entries reuse the official `conversation.chat.reasoning.content` Factory; the translation wrapper selects display text, owns its toolbar and view state, and supplies its localized labels without duplicating Markdown rendering. While enabled, the GUI translates completed paragraphs and request-sized prefixes of long streaming paragraphs only after expansion, and restores completed results from the current Session. Its local cache only optimizes that disclosure. The unfinished tail remains original. Original remains accessible. Closing the disclosure, switching provider or language, and unloading cancel outstanding calls and exclude late results. Provider failure preserves the original and requires an explicit retry; translated text never replaces original Session events or model input. diff --git a/docs/subsystems/translation.zh.md b/docs/subsystems/translation.zh.md index e3700edcbd..a9ef52df83 100644 --- a/docs/subsystems/translation.zh.md +++ b/docs/subsystems/translation.zh.md @@ -14,7 +14,7 @@ `TranslationError` 的 `TranslationErrorCode` 区分文本超限、HTTP 失败、无效响应、响应超限、服务自身超时与请求失败。`TRANSLATION_SESSION_REQUIRED` 拒绝缺失的持久化后端或 Session,`TRANSLATION_SESSION_INACTIVE` 在调用 Provider 前拒绝未激活且缓存未命中的 Session,`TRANSLATION_STORAGE_ERROR` 拒绝无效保存记录或持久化失败。Provider 错误信息省略提交的文本与响应体。失败时不选择其他 Provider。响应作为外部 JSON 校验,重定向被拒绝。 -`TRANSLATION_UNAVAILABLE` 拒绝缺失的活跃内置所有者或已注册路由、未配置的凭据、目录中不存在精确的 `deepseek-flash`、派发前所有者/模型列表/官方凭据引用变化、提供方卸载,以及准备后的调用推理强度不是 `off` 的情况。原生 `finish` 的原因为 `error` 时映射为 `TRANSLATION_REQUEST_FAILED`;缺失 finish 或其他非 `stop` 原因映射为 `TRANSLATION_INVALID_RESPONSE`。 +`TRANSLATION_UNAVAILABLE` 拒绝缺失的活跃内置所有者或已注册路由、未配置的凭据、目录中不存在精确的 `deepseek-flash`、派发前所有者、模型配置(官方路由的 `models` 或账号路由的 `modelOverrides`)或官方凭据引用变化、提供方卸载,以及准备后的调用推理强度不是 `off` 的情况。原生 `finish` 的原因为 `error` 时映射为 `TRANSLATION_REQUEST_FAILED`;缺失 finish 或其他非 `stop` 原因映射为 `TRANSLATION_INVALID_RESPONSE`。 Google 在 form POST 请求体中接收原文,Bing 在 JSON POST 请求体中接收原文。两者都是远端服务。免登录端点不保证开发者 API 的可用性或免费额度。区域连通性须在用户网络上验证。 @@ -30,7 +30,7 @@ Google 在 form POST 请求体中接收原文,Bing 在 JSON POST 请求体中 `CotTranslationPreferences` 包含已接受的翻译服务和目标语言。`CotTranslationSnapshot` 将这些偏好与 translator 当前的 `maxTextChars` 及可用服务 ID 一起返回。浏览器在注册翻译控件前读取此 Host 快照,本地设置存储不可用时也如此。接受的设置更新及重新连接会刷新这两项值;请求长度限制变化时,展开内容的请求被取消并重新分片。 -Session 作用域的 `conversation.chat.reasoning-body` chain 接收原始 `text` 和 `running` 标志。没有 contribution 接管时,Chat 渲染原始 Markdown。启用后,GUI 只在展开后翻译完整段落和流式长段落中达到请求长度的前缀,并从当前 Session 恢复已完成结果;本地缓存只优化当前展开区域。未完成的末尾片段保留原文。原文始终可访问。关闭展开内容、切换 Provider 或语言、卸载插件都会取消未完成调用并忽略迟到的结果。Provider 失败时保留原文,必须显式重试;译文从不替换原始 Session 事件或模型输入。 +GUI 向 Session 作用域的 `conversation.chat.reasoning.body` single Slot 注册,替换 Chat 的默认条目。两个条目均复用官方 `conversation.chat.reasoning.content` Factory;翻译包装选择显示文本,自行维护工具栏和视图状态,传入自己的本地化 labels,不重复实现 Markdown 渲染。启用后,GUI 只在展开后翻译完整段落和流式长段落中达到请求长度的前缀,并从当前 Session 恢复已完成结果;本地缓存只优化当前展开区域。未完成的末尾片段保留原文。原文始终可访问。关闭展开内容、切换 Provider 或语言、卸载插件都会取消未完成调用并忽略迟到的结果。Provider 失败时保留原文,必须显式重试;译文从不替换原始 Session 事件或模型输入。 diff --git a/docs/subsystems/typert.i18n.yaml b/docs/subsystems/typert.i18n.yaml index a74d05084d..d6917635cf 100644 --- a/docs/subsystems/typert.i18n.yaml +++ b/docs/subsystems/typert.i18n.yaml @@ -9,14 +9,17 @@ en: 8725fa62f36364d7 zh: 0f2ff4bdf13ff55b /typert-remote-calls/invocation-descriptors: - en: 6417ffb792fd5385 - zh: c012707075a0b21f + en: 21e88d68154c2c92 + zh: 8c9e05c65ef0f34d +/typert-remote-calls/remote-access-resources: + en: fa95f70437c07395 + zh: d4870b678b569a89 /typert-remote-calls/typert-registry: - en: 29f578ba733cfd5a - zh: c486ff4ac2d1e3b4 + en: 5827ef50011811c9 + zh: 21a9e7b368ba211a /typert-remote-calls/host-gateway: - en: 90fab88fe51d17bb - zh: 2d4c3849cf2dc7d3 + en: 58b923de12e48f18 + zh: d3c2372d8becf65e /typert-remote-calls/consumer-remote: - en: 4836f8f44fef8fd3 - zh: 51f3ab2462a08ff4 + en: 324386c600a5fdf5 + zh: 7963501eb663e228 diff --git a/docs/subsystems/typert.md b/docs/subsystems/typert.md index f0ef75f223..fb5bca48fd 100644 --- a/docs/subsystems/typert.md +++ b/docs/subsystems/typert.md @@ -40,27 +40,31 @@ interface TypertLookupDefinition { An `InvocationDescriptor` is local reflection, not a wire message. Host and consumer builds generate corresponding descriptors; the request sends only the endpoint and named `args`. Strict codecs carry generated schema factories, while SRC codecs enforce JSON-safe inputs without structural type recovery. Unary result codecs can supply `encode()` for byte-containing subtrees and `decode()` for recursive native-byte validation; Client declarations narrow every `Uint8Array` to `ArrayBuffer` backing. Pure JSON results need neither byte detection nor Client decoding. Cancellation is an out-of-band carrier signal injected after business parameters and never enters `args`. +`createTypertRemoteInfo` returns a lazy class instance implementing `TypertRemoteInfo`, which extends the mountable `TypertRemoteContribution`. Its `methods` index aliases the direct objects in `descriptors`: each `TypertRemoteMethod` adds named `input(options?)` and `invoke`, retains documentation on the method and its parameters, and uses `result` as its only output codec. Unary `mode` is absent; stream `mode` is `'stream'`. Context-only receivers remain in descriptors and scoped declarations. Registry queries return base descriptors; `isTypertRemoteMethod` narrows generated direct capabilities without recovering endpoint-specific generics. + +`TypertSchema` guarantees parsing, not arbitrary Zod operations, although the raw factory spec requires Zod factories. Missing documentation or an unsupported optional JSON Schema projection does not invalidate an ordinary method. The info index and each input-policy view, parser, and derived projection are independently lazy and cached; no metadata or schema access invokes the network. The [protocol reference](<../../packages/typert/protocol/README.md>) defines these APIs, and the [generator reference](<../../packages/typert/generator/README.md#ordinary-remote-metadata>) defines their separate Host `./typert`, consumer `./remote`, and Client `./client/typert` artifacts. + +`TypertRemoteSpec` holds a package and endpoint-keyed `TypertRemoteMethodSpec` values. Each ordered `TypertRemoteParameterSpec` contains normal `codec` and `strictCodec` factories from the same checker-resolved type model; the runtime derives identities, wire-name defaults, and named-call views. `TypertRemoteInputOptions` has only `strict?: boolean`; `method.input(options?)` selects a cached `TypertRemoteValue` with matching parsing and optional documentation/projection, without changing Host dispatch or `result`. `RemoteDecoded` describes carrier-reconstructed unary results without narrowing arbitrary parser outputs. + ```ts type-equiv /** Codec attached to one invocation parameter or result. */ -type TypertCodec = - | { +type TypertCodec = + | TypertRemoteValue & { readonly mode: 'strict' readonly typeSymbol: string - /** Materialize and return the process-realm schema on first boundary use. */ - readonly create: () => TypertSchema /** * Decode a unary result whose fields require type-specific handling. * @param value - result reconstructed by the RPC carrier. * @returns the validated result, retaining native byte views. */ - readonly decode?: (value: unknown) => unknown + readonly decode?: ((value: unknown) => unknown) | undefined /** * Project typed binary fields into RPC result attachments. * @param value - native unary result. * @param writeBytes - records a byte view at its result-relative path and returns its JSON placeholder. * @returns JSON metadata with untouched JSON subtrees retained. */ - readonly encode?: (value: unknown, writeBytes: (bytes: Uint8Array, path: readonly (string | number)[]) => null) => unknown + readonly encode?: ((value: unknown, writeBytes: (bytes: Uint8Array, path: readonly (string | number)[]) => null) => unknown) | undefined } | { readonly mode: 'src-json' @@ -72,6 +76,8 @@ type TypertCodec = interface InvocationParameterDescriptor { /** Source-level parameter name. */ readonly name: string + /** Source parameter documentation, independent of JSON Schema support. */ + readonly description?: string /** Required key in the wire `args` object. */ readonly wire: string /** Whether the value is JSON or requires a registered Host lookup. */ @@ -135,6 +141,8 @@ interface InvocationDescriptor { } /** Codec for the unary result or each yielded stream item. */ readonly result: TypertCodec + /** Source-owned method documentation; ordinary methods need not have JSDoc. */ + readonly description?: string /** Source declaration used only for diagnostics. */ readonly sourceLocation?: InvocationSourceLocation } @@ -192,13 +200,35 @@ interface RemoteStreamHandle extends AsyncIterable { ```ts type-equiv /** - * One Peer's session on this Host. Connection owns it: `ctx` is the Cordis + * Merge-extensible caller identities. Each driver declares its own entry. + * Every entry is a JSON value with a unique literal `kind`, carries no + * credential, and is safe to persist in a Session log. + */ +interface PrincipalMap { + /** The local user who owns this Host. */ + owner: { readonly kind: 'owner' } +} +``` + +```ts type-equiv +/** One caller identity; the authorization layer reads only this. */ +type Principal = PrincipalMap[keyof PrincipalMap] +``` + +```ts type-equiv +/** + * One Peer's session on this Host. Its creator owns it: `ctx` is the Cordis * scope that owns connection-lifetime registrations and is disposed with the - * Peer. Who the Peer is and what it may do are not recorded here. + * Peer, and `principal` is the caller identity fixed when the Peer was created. */ interface PeerScope { readonly id: PeerId + /** Connection-lifetime registrations; disposed with the Peer. */ readonly ctx: Context + /** Caller identity fixed at creation by in-process Host code; no wire field can set it. */ + readonly principal: Principal + /** Aborted once the Peer is disposed; Remote streams that speak for the Peer end with it. */ + readonly signal: AbortSignal /** * Tear down every registration made through `ctx`. * @returns settles once the scope has quiesced; racing calls share one completion. @@ -207,6 +237,16 @@ interface PeerScope { } ``` +```ts type-equiv +/** Carrier capacity for buffered uplink frames of one logical stream. */ +interface RemoteUplinkWindow { + /** Maximum complete encoded frame bytes waiting for the Host consumer. */ + readonly maxBytes: number + /** UTF-8 envelope bytes added to a compact JSON item with a present value field. */ + readonly frameOverheadBytes: number +} +``` + ```ts type-equiv /** * The context of one Remote call, reachable inside the receiving method as @@ -221,10 +261,12 @@ interface RemoteInvocation { } /** Cordis service key of the receiving Service. */ readonly service: string - /** Peer the call speaks for; an in-process carrier speaks for the operator. */ + /** Peer the call speaks for; every carrier names it explicitly. */ readonly peer: PeerScope /** Carrier cancellation: Client cancel, socket close, or an uplink failure. */ readonly signal: AbortSignal + /** Carrier frame capacity; absent when the carrier imposes no encoded-frame inbox limit. */ + readonly uplinkWindow?: RemoteUplinkWindow | undefined /** * The Client's uplink items for this call. Available once; a second call * throws. With an uplink codec on the descriptor every item is decoded to @@ -240,9 +282,81 @@ interface RemoteInvocation { } ``` +## Remote access resources + +Every Remote method is under the access control of [`dsh-api-remote-access`](../../packages/api/remote-access/README.md): a non-owner call is allowed only when the policy for its principal kind binds, on every resource the call touches, a role that lists the endpoint action. The package that owns an identity type merge-declares its resource kind in `TypertResourceMap`; `global`, the built-in identity-less resource, is never a kind there. The Gateway reads a kind's identities from the `resources` readers of `@Remote({ resources })` or `@RemoteScope(key, { resources })`, else from a lookup parameter or scoped Context that declares the kind as its `resource`, else from the default field registered in `typert.resources`; a call that names no resource touches `global`. The [Peer principals Agent Note](../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md) owns the decision. + +```ts type-equiv +/** + * Merge-extensible resource kinds whose identities a Remote call or forwarded + * event may carry. The package that owns an identity type declares its kind; + * the value is that kind's identity type, a string type such as a branded id. + * `global` names the built-in identity-less resource and is never a kind here. + */ +interface TypertResourceMap {} +``` + +```ts type-equiv +/** One resource kind: the built-in `global` kind or a declared kind. */ +type RemoteAccessResourceKind = 'global' | TypertResourceKind +``` + +```ts type-equiv +/** + * One resource a call or forwarded event touches: `global`, or one identity + * of a declared kind. Identities are wire values, read before any lookup + * resolves or validates them. + */ +type RemoteAccessResource = + | { readonly kind: 'global' } + | { + [Kind in TypertResourceKind]: { readonly kind: Kind; readonly id: TypertResourceId } + }[TypertResourceKind] +``` + +```ts type-equiv +/** + * Explicit endpoint and resource choices for one Remote Scope method. + * @template WireArgs - the decorated method's positional parameters as the + * wire carries them; the default `never` admits readers of any tuple. + */ +interface RemoteScopeOptions { + /** Exported endpoint method; omission retains the implementation member name. */ + readonly name?: string + /** + * Per-kind readers of the resources one call touches. Each receives the + * method's arguments as its own parameters, JSON arguments as their Typert + * codecs validated them, a lookup parameter as its wire identity and a + * cancellation parameter as the call's signal, so it performs plain reads + * only, and returns one identity, several, or `undefined` for none. A + * throw, an empty list, or an identity other than a non-empty string + * refuses the call. For a kind without a reader, the Gateway reads the + * identity of a scoped Context whose Host adapter declares that `resource` + * and of lookup parameters declaring it, else the field registered in + * `typert.resources`: a top-level argument or, failing that, the first + * object argument. A call that carries no identity touches `global`. The + * readers and these defaults together must name every resource the method + * accesses: access control never checks a resource they omit. + */ + readonly resources?: TypertResourceReaders +} +``` + +```ts type-equiv +/** + * Explicit endpoint, stream, and resource choices for one direct Remote method. + * @template WireArgs - the decorated method's positional parameters as the + * wire carries them; the default `never` admits readers of any tuple. + */ +interface RemoteMethodOptions extends RemoteScopeOptions { + /** `stream`: deliver each Iterable item over the shared logical-stream carrier. */ + readonly mode?: 'stream' +} +``` + ## Typert registry -`ctx.typert` separates current-environment descriptors, explicitly selected Remote contributions, lookup providers, and scoped Context providers. A lookup provider owns the stable wire declaration and default resolver; Host composition can configure an effect-scoped synchronous or asynchronous resolver for the same key, and unloading that configuration restores the default policy. Registrations are Cordis-owned effects and return awaitable disposers. +`ctx.typert` separates current-environment descriptors, explicitly selected Remote contributions, lookup providers, scoped Context providers, and the default fields of resource kinds. A lookup provider owns the stable wire declaration and default resolver; Host composition can configure an effect-scoped synchronous or asynchronous resolver for the same key, and unloading that configuration restores the default policy. Registrations are Cordis-owned effects and return awaitable disposers. ```ts type-equiv /** Minimal Typert runtime consumed through dependency inversion. */ @@ -251,6 +365,7 @@ interface TypertRegistryContract { readonly remotes: TypertRemoteRegistry readonly lookups: TypertLookupRegistry readonly contexts: TypertContextRegistry + readonly resources: TypertResourceRegistry } ``` @@ -263,7 +378,7 @@ interface TypertRemoteNamespaceMap {} ## Host Gateway -Connection decodes its carrier envelope before calling `ctx.typertGateway`. The request carries exact named wire fields and the carrier's cancellation signal separately; infrastructure and boundary failures ride `TypertGatewayError`, whose `gateway/*` codes are ordinary `RemoteError` codes, so the RPC adapter passes every structurally identified `RemoteError` through with its code and details intact and folds only unrecognized exceptions into `gateway/internal`. +Connection decodes its carrier envelope before calling `ctx.typertGateway`. The request carries exact named wire fields, the carrier's cancellation signal, and the Peer the call speaks for separately; every carrier and in-process caller names that Peer, and the Gateway refuses a disposed one with `gateway/peer-disposed`. For a non-owner call the Gateway resolves its resources and asks `ctx.remoteAccess.decide()` after argument validation and before any lookup or Context resolution; infrastructure and boundary failures ride `TypertGatewayError`, whose `gateway/*` codes are ordinary `RemoteError` codes, so the RPC adapter passes every structurally identified `RemoteError` through with its code and details intact and folds only unrecognized exceptions into `gateway/internal`. ```ts type-equiv /** One Remote method request after a carrier has decoded its envelope. */ @@ -279,8 +394,10 @@ interface InvokeRemoteRequest { * `invocation.uplink()`; absent means an immediately ended iterable. */ readonly uplink?: AsyncIterable - /** Peer the call speaks for; absent means an in-process carrier, answered as the operator. */ - readonly peer?: PeerScope + /** Carrier-provided frame capacity; absent for carriers without an encoded-frame inbox limit. */ + readonly uplinkWindow?: RemoteUplinkWindow | undefined + /** Peer the call speaks for; every carrier and in-process caller names it explicitly. */ + readonly peer: PeerScope /** Carrier or direct-caller cancellation injected only into cancellation-aware methods. */ readonly signal?: AbortSignal } @@ -302,6 +419,7 @@ type TypertGatewayErrorCode = | 'gateway/lookup-not-found' | 'gateway/lookup-unavailable' | 'gateway/method-unavailable' + | 'gateway/peer-disposed' | 'gateway/protocol' | 'gateway/provider-mismatch' | 'gateway/result-invalid' @@ -316,8 +434,8 @@ interface TypertGateway { /** Carrier adapter shared by WebSocket and in-process transports. */ readonly wireStream: TypertGatewayWireStream /** - * Check for an active Client event stream. - * @returns whether a stream is open and has not been cancelled. + * Check for an active owner Client event stream, the only kind that can answer forwarded waterfalls. + * @returns whether an owner stream is open and has not been cancelled. */ hasLiveClient(): boolean /** @@ -350,6 +468,8 @@ interface TypertGateway { `ctx.remote` exposes only namespaces contributed by imported `/remote` artifacts. `$mount()` installs generated descriptors and concrete methods as one fiber-owned operation. Each namespace is a traced `remote.` Cordis child Service whose lifetime spans its mounted methods; no JavaScript Proxy or Host business Service type enters the consumer. +Metadata ownership is separate from connection ownership; the [registry reference](<../../packages/typert/registry/README.md>) covers offline registration and mount lifetimes. + ```ts type-equiv /** Client Remote capability implemented by the Gateway and consumed by Remote assemblies. */ interface TypertClientRemote extends TypertRemoteNamespaceMap { @@ -380,6 +500,88 @@ interface TypertClientRemote extends TypertRemoteNamespaceMap { Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + +### `ctx.remoteAccess` — `RemoteAccessService` + +Registry of access policies, the Gateway's access decisions, list filtering, and the per-Peer access snapshot. Every composition that mounts the Gateway mounts this service too. + +```ts cordis-catalog +/** + * Register the policy of one non-owner principal kind in the caller's + * fiber; open snapshots are recomputed on registration and removal. + * @param kind - the principal kind the policy serves; never `owner`. + * @param policy - business-owned bindings and refusal reasons for principals of `kind`. + * @returns disposer removing this policy. + * @throws Error when `kind` already has a policy. + */ +registerPolicy>(kind: K, policy: RemoteAccessPolicy): () => void + +/** + * Report that the bindings or condition answers for `principal` may have + * changed. Business packages call this on every grant, revocation, mode + * change, and expiry; open snapshots re-push, and the next failure of each + * policy is logged again. + * @param principal - affected principal; omitted for every principal. + */ +invalidate(principal?: Principal): void + +/** + * Gateway-only: decide one request whose resources the Gateway resolved. + * The owner is allowed, and so is `remoteAccess/follow`: every Peer reads + * its own snapshot. Otherwise the action is allowed only when, on every + * listed resource, some binding of the principal's policy names that + * resource, has a role listing the action, and has no condition or a + * condition that allows. `bindings()` is called once per decision. + * @param request - the caller or recipient, the action, the resources it + * touches, and a call's arguments. + * @returns `allow`; or `deny` with `no-allow` when the principal kind has + * no policy, the first refusing condition's reason on the first resource + * no binding allows, else `explain()`'s reason, else `no-allow`; + * `policy-failed` when `bindings()`, a condition, or `explain()` throws, + * logged once per policy until the next `invalidate()`. The Gateway + * throws `remote-access/denied` for a denied call and drops a denied event. + */ +decide(request: RemoteAccessRequest): RemoteAccessDecision + +/** + * Filter items inside a Remote method. The invocation is read from the + * Context that accessed this service, so call it as + * `this.ctx.remoteAccess.allows(resource)` from the Remote method. Each + * check reads the policy's bindings again, so a long-running stream sees + * binding changes from the next check on. + * @param resource - resource of one result item. + * @returns true for the owner and outside a Remote call; otherwise whether + * the invocation's endpoint action is allowed on `resource` without call + * arguments, false when the policy is absent or fails. + */ +allows(resource: RemoteAccessResource): boolean + +/** + * The baseline a page opens with before its snapshot stream connects. A + * business package rendering a non-owner page assigns this value to + * {@link REMOTE_ACCESS_SNAPSHOT_KEY} after every index injection row, + * replacing the owner baseline the webServer index carries. + * @param principal - the page's caller identity. + * @returns the owner baseline for the owner; otherwise the principal's current grants. + */ +snapshotFor(principal: Principal): RemoteAccessBaseline + +/** + * Stream the calling Peer's access snapshot: one baseline, then `upsert` + * and `remove` frames after each `invalidate()` and each policy + * registration or removal that changes a grant. The owner receives only + * `{ owner: true }`. The generation ends when `signal` aborts or this + * service unloads, so a reloaded service starts every reader from a fresh + * baseline. + * @param signal - generation cancellation. + * @returns the access frames of one generation. + */ +@Remote({ mode: 'stream' }) async *follow(signal: AbortSignal): AsyncIterable +``` + +Source: [`packages/api/remote-access/src/index.ts`](../../packages/api/remote-access/src/index.ts) + ### `ctx.typert` — `TypertRegistry` @@ -452,8 +654,8 @@ Resolve strict generated definitions or conservative SRC markers against current ```ts cordis-catalog /** - * Check for an active Client event stream. - * @returns whether a stream is open and has not been cancelled. + * Check for an active owner Client event stream, the only kind that can answer forwarded waterfalls. + * @returns whether an owner stream is open and has not been cancelled. */ hasLiveClient(): boolean diff --git a/docs/subsystems/typert.zh.md b/docs/subsystems/typert.zh.md index e2414dfc5e..11b3fd8dbb 100644 --- a/docs/subsystems/typert.zh.md +++ b/docs/subsystems/typert.zh.md @@ -40,27 +40,31 @@ interface TypertLookupDefinition { `InvocationDescriptor` 是本地反射信息,不是 wire message。Host 与消费方构建会生成彼此对应的 descriptor;请求只发送 endpoint 与具名 `args`。strict codec 携带生成的 schema factory,SRC codec 则在不恢复结构类型的前提下强制要求输入为 JSON 安全值。一元结果 codec 可提供 `encode()` 处理含字节的子树,并通过 `decode()` 递归校验原生字节;Client 声明将每个 `Uint8Array` 限定为以 `ArrayBuffer` 为底层缓冲区。纯 JSON 结果无需字节识别或 Client 解码。取消通过带外 carrier signal 表达:它在业务参数之后注入,绝不进入 `args`。 +`createTypertRemoteInfo` 返回实现 `TypertRemoteInfo` 的惰性类实例,后者扩展可挂载的 `TypertRemoteContribution`。其 `methods` 索引引用 `descriptors` 中的直接方法对象:每个 `TypertRemoteMethod` 增加具名 `input(options?)` 和 `invoke`,在方法及参数上保留文档,并以 `result` 作为唯一输出 codec。一元 `mode` 缺省;流式 `mode` 为 `'stream'`。仅使用 Context 接收器的方法保留在描述符和作用域声明中。Registry 查询返回基础描述符;`isTypertRemoteMethod` 收窄生成的直接调用能力,但不会恢复各端点的精确泛型。 + +`TypertSchema` 保证解析能力,不保证任意 Zod 操作,尽管原始 factory spec 要求 Zod factory。缺少文档或不支持可选的 JSON Schema 投影,不会使普通方法失效。info 索引与每种输入策略的视图、解析器和派生投影都独立惰性求值并缓存;读取元数据或 schema 绝不发起网络调用。[协议参考](<../../packages/typert/protocol/README.zh.md>)定义这些 API,[生成器参考](<../../packages/typert/generator/README.zh.md#ordinary-remote-metadata>)定义它们彼此分离的 Host `./typert`、消费方 `./remote` 和 Client `./client/typert` 产物。 + +`TypertRemoteSpec` 保存包名与按端点键控的 `TypertRemoteMethodSpec`。每个有序 `TypertRemoteParameterSpec` 条目都包含从同一 checker 解析后类型模型生成的普通 `codec` 和 `strictCodec` factory;运行时派生标识、默认 wire 名称和具名调用视图。`TypertRemoteInputOptions` 仅包含 `strict?: boolean`;`method.input(options?)` 选择缓存的 `TypertRemoteValue`,提供匹配的解析及可选文档/投影,而不改变 Host 分发或 `result`。`RemoteDecoded` 则描述 carrier 重建的一元结果,不会收窄任意解析器输出。 + ```ts type-equiv /** Codec attached to one invocation parameter or result. */ -type TypertCodec = - | { +type TypertCodec = + | TypertRemoteValue & { readonly mode: 'strict' readonly typeSymbol: string - /** Materialize and return the process-realm schema on first boundary use. */ - readonly create: () => TypertSchema /** * Decode a unary result whose fields require type-specific handling. * @param value - result reconstructed by the RPC carrier. * @returns the validated result, retaining native byte views. */ - readonly decode?: (value: unknown) => unknown + readonly decode?: ((value: unknown) => unknown) | undefined /** * Project typed binary fields into RPC result attachments. * @param value - native unary result. * @param writeBytes - records a byte view at its result-relative path and returns its JSON placeholder. * @returns JSON metadata with untouched JSON subtrees retained. */ - readonly encode?: (value: unknown, writeBytes: (bytes: Uint8Array, path: readonly (string | number)[]) => null) => unknown + readonly encode?: ((value: unknown, writeBytes: (bytes: Uint8Array, path: readonly (string | number)[]) => null) => unknown) | undefined } | { readonly mode: 'src-json' @@ -72,6 +76,8 @@ type TypertCodec = interface InvocationParameterDescriptor { /** Source-level parameter name. */ readonly name: string + /** Source parameter documentation, independent of JSON Schema support. */ + readonly description?: string /** Required key in the wire `args` object. */ readonly wire: string /** Whether the value is JSON or requires a registered Host lookup. */ @@ -135,6 +141,8 @@ interface InvocationDescriptor { } /** Codec for the unary result or each yielded stream item. */ readonly result: TypertCodec + /** Source-owned method documentation; ordinary methods need not have JSDoc. */ + readonly description?: string /** Source declaration used only for diagnostics. */ readonly sourceLocation?: InvocationSourceLocation } @@ -192,13 +200,35 @@ interface RemoteStreamHandle extends AsyncIterable { ```ts type-equiv /** - * One Peer's session on this Host. Connection owns it: `ctx` is the Cordis + * Merge-extensible caller identities. Each driver declares its own entry. + * Every entry is a JSON value with a unique literal `kind`, carries no + * credential, and is safe to persist in a Session log. + */ +interface PrincipalMap { + /** The local user who owns this Host. */ + owner: { readonly kind: 'owner' } +} +``` + +```ts type-equiv +/** One caller identity; the authorization layer reads only this. */ +type Principal = PrincipalMap[keyof PrincipalMap] +``` + +```ts type-equiv +/** + * One Peer's session on this Host. Its creator owns it: `ctx` is the Cordis * scope that owns connection-lifetime registrations and is disposed with the - * Peer. Who the Peer is and what it may do are not recorded here. + * Peer, and `principal` is the caller identity fixed when the Peer was created. */ interface PeerScope { readonly id: PeerId + /** Connection-lifetime registrations; disposed with the Peer. */ readonly ctx: Context + /** Caller identity fixed at creation by in-process Host code; no wire field can set it. */ + readonly principal: Principal + /** Aborted once the Peer is disposed; Remote streams that speak for the Peer end with it. */ + readonly signal: AbortSignal /** * Tear down every registration made through `ctx`. * @returns settles once the scope has quiesced; racing calls share one completion. @@ -207,6 +237,16 @@ interface PeerScope { } ``` +```ts type-equiv +/** Carrier capacity for buffered uplink frames of one logical stream. */ +interface RemoteUplinkWindow { + /** Maximum complete encoded frame bytes waiting for the Host consumer. */ + readonly maxBytes: number + /** UTF-8 envelope bytes added to a compact JSON item with a present value field. */ + readonly frameOverheadBytes: number +} +``` + ```ts type-equiv /** * The context of one Remote call, reachable inside the receiving method as @@ -221,10 +261,12 @@ interface RemoteInvocation { } /** Cordis service key of the receiving Service. */ readonly service: string - /** Peer the call speaks for; an in-process carrier speaks for the operator. */ + /** Peer the call speaks for; every carrier names it explicitly. */ readonly peer: PeerScope /** Carrier cancellation: Client cancel, socket close, or an uplink failure. */ readonly signal: AbortSignal + /** Carrier frame capacity; absent when the carrier imposes no encoded-frame inbox limit. */ + readonly uplinkWindow?: RemoteUplinkWindow | undefined /** * The Client's uplink items for this call. Available once; a second call * throws. With an uplink codec on the descriptor every item is decoded to @@ -240,9 +282,81 @@ interface RemoteInvocation { } ``` +## Remote 访问资源 + +每个 Remote 方法都受 [`dsh-api-remote-access`](../../packages/api/remote-access/README.zh.md) 的访问控制:只有当该 principal 种类的 policy 在调用访问的每个资源上都绑定了列出该端点 action 的 role 时,非 owner 调用才被放行。拥有某个身份类型的包把其资源种类声明合并进 `TypertResourceMap`;内置的无身份资源 `global` 从不是其中的种类。Gateway 从 `@Remote({ resources })` 或 `@RemoteScope(key, { resources })` 的 `resources` 读取函数读取某个种类的身份,其次是把该种类声明为 `resource` 的 lookup 参数或作用域 Context,再次是在 `typert.resources` 中登记的默认字段;不指向任何资源的调用访问 `global`。决策由 [Peer 身份属性 Agent Note](../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md) 负责。 + +```ts type-equiv +/** + * Merge-extensible resource kinds whose identities a Remote call or forwarded + * event may carry. The package that owns an identity type declares its kind; + * the value is that kind's identity type, a string type such as a branded id. + * `global` names the built-in identity-less resource and is never a kind here. + */ +interface TypertResourceMap {} +``` + +```ts type-equiv +/** One resource kind: the built-in `global` kind or a declared kind. */ +type RemoteAccessResourceKind = 'global' | TypertResourceKind +``` + +```ts type-equiv +/** + * One resource a call or forwarded event touches: `global`, or one identity + * of a declared kind. Identities are wire values, read before any lookup + * resolves or validates them. + */ +type RemoteAccessResource = + | { readonly kind: 'global' } + | { + [Kind in TypertResourceKind]: { readonly kind: Kind; readonly id: TypertResourceId } + }[TypertResourceKind] +``` + +```ts type-equiv +/** + * Explicit endpoint and resource choices for one Remote Scope method. + * @template WireArgs - the decorated method's positional parameters as the + * wire carries them; the default `never` admits readers of any tuple. + */ +interface RemoteScopeOptions { + /** Exported endpoint method; omission retains the implementation member name. */ + readonly name?: string + /** + * Per-kind readers of the resources one call touches. Each receives the + * method's arguments as its own parameters, JSON arguments as their Typert + * codecs validated them, a lookup parameter as its wire identity and a + * cancellation parameter as the call's signal, so it performs plain reads + * only, and returns one identity, several, or `undefined` for none. A + * throw, an empty list, or an identity other than a non-empty string + * refuses the call. For a kind without a reader, the Gateway reads the + * identity of a scoped Context whose Host adapter declares that `resource` + * and of lookup parameters declaring it, else the field registered in + * `typert.resources`: a top-level argument or, failing that, the first + * object argument. A call that carries no identity touches `global`. The + * readers and these defaults together must name every resource the method + * accesses: access control never checks a resource they omit. + */ + readonly resources?: TypertResourceReaders +} +``` + +```ts type-equiv +/** + * Explicit endpoint, stream, and resource choices for one direct Remote method. + * @template WireArgs - the decorated method's positional parameters as the + * wire carries them; the default `never` admits readers of any tuple. + */ +interface RemoteMethodOptions extends RemoteScopeOptions { + /** `stream`: deliver each Iterable item over the shared logical-stream carrier. */ + readonly mode?: 'stream' +} +``` + ## Typert 注册表 -`ctx.typert` 分开保存当前环境的 descriptor、显式选择的 Remote contribution、lookup 提供方与作用域上下文提供方。lookup 提供方拥有稳定 wire 声明和默认 resolver;Host 组合可以为同一个 key 配置 effect-scoped 同步或异步 resolver,配置卸载后恢复默认策略。各项注册都是由 Cordis 持有的 effect,并返回可等待的 disposer。 +`ctx.typert` 分开保存当前环境的 descriptor、显式选择的 Remote contribution、lookup 提供方、作用域上下文提供方与资源种类的默认字段。lookup 提供方拥有稳定 wire 声明和默认 resolver;Host 组合可以为同一个 key 配置 effect-scoped 同步或异步 resolver,配置卸载后恢复默认策略。各项注册都是由 Cordis 持有的 effect,并返回可等待的 disposer。 ```ts type-equiv /** Minimal Typert runtime consumed through dependency inversion. */ @@ -251,6 +365,7 @@ interface TypertRegistryContract { readonly remotes: TypertRemoteRegistry readonly lookups: TypertLookupRegistry readonly contexts: TypertContextRegistry + readonly resources: TypertResourceRegistry } ``` @@ -263,7 +378,7 @@ interface TypertRemoteNamespaceMap {} ## Host Gateway -Connection 会先解码 carrier envelope,再调用 `ctx.typertGateway`。请求将精确的具名 wire 字段与 carrier 的取消 signal 分开携带;基础设施与边界失败由 `TypertGatewayError` 承载,其 `gateway/*` 码就是普通的 `RemoteError` 码,因此 RPC 适配器会把每个经结构识别的 `RemoteError` 连同其 code 与 details 原样放行,只把无法识别的异常归并为 `gateway/internal`。 +Connection 会先解码 carrier envelope,再调用 `ctx.typertGateway`。请求将精确的具名 wire 字段、carrier 的取消 signal 与本次调用代表的 Peer 分开携带;每个载体与进程内调用方都显式给出该 Peer,Gateway 以 `gateway/peer-disposed` 拒绝已 dispose 的 Peer。对非 owner 调用,Gateway 在参数校验之后、任何 lookup 或 Context 解析之前解析其资源并询问 `ctx.remoteAccess.decide()`;基础设施与边界失败由 `TypertGatewayError` 承载,其 `gateway/*` 码就是普通的 `RemoteError` 码,因此 RPC 适配器会把每个经结构识别的 `RemoteError` 连同其 code 与 details 原样放行,只把无法识别的异常归并为 `gateway/internal`。 ```ts type-equiv /** One Remote method request after a carrier has decoded its envelope. */ @@ -279,8 +394,10 @@ interface InvokeRemoteRequest { * `invocation.uplink()`; absent means an immediately ended iterable. */ readonly uplink?: AsyncIterable - /** Peer the call speaks for; absent means an in-process carrier, answered as the operator. */ - readonly peer?: PeerScope + /** Carrier-provided frame capacity; absent for carriers without an encoded-frame inbox limit. */ + readonly uplinkWindow?: RemoteUplinkWindow | undefined + /** Peer the call speaks for; every carrier and in-process caller names it explicitly. */ + readonly peer: PeerScope /** Carrier or direct-caller cancellation injected only into cancellation-aware methods. */ readonly signal?: AbortSignal } @@ -302,6 +419,7 @@ type TypertGatewayErrorCode = | 'gateway/lookup-not-found' | 'gateway/lookup-unavailable' | 'gateway/method-unavailable' + | 'gateway/peer-disposed' | 'gateway/protocol' | 'gateway/provider-mismatch' | 'gateway/result-invalid' @@ -316,8 +434,8 @@ interface TypertGateway { /** Carrier adapter shared by WebSocket and in-process transports. */ readonly wireStream: TypertGatewayWireStream /** - * Check for an active Client event stream. - * @returns whether a stream is open and has not been cancelled. + * Check for an active owner Client event stream, the only kind that can answer forwarded waterfalls. + * @returns whether an owner stream is open and has not been cancelled. */ hasLiveClient(): boolean /** @@ -350,6 +468,8 @@ interface TypertGateway { `ctx.remote` 只暴露由已导入 `/remote` 产物贡献的 namespace。`$mount()` 会把生成的 descriptor 与具体方法作为一项由 fiber 持有的操作统一注册。每个 namespace 都是可追踪的 `remote.` Cordis 子服务,其生命周期覆盖已挂载的方法;JavaScript Proxy 与 Host 业务服务类型都不会进入消费方。 +元数据所有权与连接所有权相互独立;[注册表参考](<../../packages/typert/registry/README.zh.md>)说明离线注册与挂载生命周期。 + ```ts type-equiv /** Client Remote capability implemented by the Gateway and consumed by Remote assemblies. */ interface TypertClientRemote extends TypertRemoteNamespaceMap { @@ -380,6 +500,88 @@ interface TypertClientRemote extends TypertRemoteNamespaceMap { Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.zh.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + +### `ctx.remoteAccess` — `RemoteAccessService` + +Registry of access policies, the Gateway's access decisions, list filtering, and the per-Peer access snapshot. Every composition that mounts the Gateway mounts this service too. + +```ts cordis-catalog +/** + * Register the policy of one non-owner principal kind in the caller's + * fiber; open snapshots are recomputed on registration and removal. + * @param kind - the principal kind the policy serves; never `owner`. + * @param policy - business-owned bindings and refusal reasons for principals of `kind`. + * @returns disposer removing this policy. + * @throws Error when `kind` already has a policy. + */ +registerPolicy>(kind: K, policy: RemoteAccessPolicy): () => void + +/** + * Report that the bindings or condition answers for `principal` may have + * changed. Business packages call this on every grant, revocation, mode + * change, and expiry; open snapshots re-push, and the next failure of each + * policy is logged again. + * @param principal - affected principal; omitted for every principal. + */ +invalidate(principal?: Principal): void + +/** + * Gateway-only: decide one request whose resources the Gateway resolved. + * The owner is allowed, and so is `remoteAccess/follow`: every Peer reads + * its own snapshot. Otherwise the action is allowed only when, on every + * listed resource, some binding of the principal's policy names that + * resource, has a role listing the action, and has no condition or a + * condition that allows. `bindings()` is called once per decision. + * @param request - the caller or recipient, the action, the resources it + * touches, and a call's arguments. + * @returns `allow`; or `deny` with `no-allow` when the principal kind has + * no policy, the first refusing condition's reason on the first resource + * no binding allows, else `explain()`'s reason, else `no-allow`; + * `policy-failed` when `bindings()`, a condition, or `explain()` throws, + * logged once per policy until the next `invalidate()`. The Gateway + * throws `remote-access/denied` for a denied call and drops a denied event. + */ +decide(request: RemoteAccessRequest): RemoteAccessDecision + +/** + * Filter items inside a Remote method. The invocation is read from the + * Context that accessed this service, so call it as + * `this.ctx.remoteAccess.allows(resource)` from the Remote method. Each + * check reads the policy's bindings again, so a long-running stream sees + * binding changes from the next check on. + * @param resource - resource of one result item. + * @returns true for the owner and outside a Remote call; otherwise whether + * the invocation's endpoint action is allowed on `resource` without call + * arguments, false when the policy is absent or fails. + */ +allows(resource: RemoteAccessResource): boolean + +/** + * The baseline a page opens with before its snapshot stream connects. A + * business package rendering a non-owner page assigns this value to + * {@link REMOTE_ACCESS_SNAPSHOT_KEY} after every index injection row, + * replacing the owner baseline the webServer index carries. + * @param principal - the page's caller identity. + * @returns the owner baseline for the owner; otherwise the principal's current grants. + */ +snapshotFor(principal: Principal): RemoteAccessBaseline + +/** + * Stream the calling Peer's access snapshot: one baseline, then `upsert` + * and `remove` frames after each `invalidate()` and each policy + * registration or removal that changes a grant. The owner receives only + * `{ owner: true }`. The generation ends when `signal` aborts or this + * service unloads, so a reloaded service starts every reader from a fresh + * baseline. + * @param signal - generation cancellation. + * @returns the access frames of one generation. + */ +@Remote({ mode: 'stream' }) async *follow(signal: AbortSignal): AsyncIterable +``` + +Source: [`packages/api/remote-access/src/index.ts`](../../packages/api/remote-access/src/index.ts) + ### `ctx.typert` — `TypertRegistry` @@ -452,8 +654,8 @@ Resolve strict generated definitions or conservative SRC markers against current ```ts cordis-catalog /** - * Check for an active Client event stream. - * @returns whether a stream is open and has not been cancelled. + * Check for an active owner Client event stream, the only kind that can answer forwarded waterfalls. + * @returns whether an owner stream is open and has not been cancelled. */ hasLiveClient(): boolean diff --git a/docs/subsystems/web-client.i18n.yaml b/docs/subsystems/web-client.i18n.yaml index 29bb05c709..593dcc3494 100644 --- a/docs/subsystems/web-client.i18n.yaml +++ b/docs/subsystems/web-client.i18n.yaml @@ -24,8 +24,8 @@ en: c063711f8247c240 zh: 5e54758bbaf1670c /web-client-architecture/conversation-and-presentation: - en: 71362f4ac9490bcb - zh: 025507ca615f5e2a + en: 9a22492f0d4359c6 + zh: 55d449e383e88f62 /web-client-architecture/data-paths: en: a254278432416473 zh: 567c2d3c6a20b304 diff --git a/docs/subsystems/web-client.md b/docs/subsystems/web-client.md index 3f0d7ecf99..bb68cd64a1 100644 --- a/docs/subsystems/web-client.md +++ b/docs/subsystems/web-client.md @@ -57,7 +57,7 @@ This pairing is not a second source of business truth. Host controllers decide d Web and desktop share the [Coding Tools preference](../../packages/client/ui-settings/README.md#use-this-package). It controls diagnostic Views, [available preset choices](../../packages/client/ui-agent-preset/README.md), changed-file cards, and the builtin HTML preview policy without changing Session records. -`ui-session` installs the Session scope adapter and publishes `useSessions`, `useSessionStatus`, `useSessionRetainInfo`, `useSession`, `sessionId`, and `useProjection`. `SessionProvider` inherits an outer binding or binds an explicit `SessionReference`, so concurrent subtrees can target different Sessions. Domain adapters add further standard sources without putting React hooks on the model objects. +`ui-session` installs the Session scope adapter and publishes `useSessions`, `useSessionStatus`, `useSessionRetainInfo`, `useSessionAccess`, `useSession`, `sessionId`, `useProjection`, and the Session-scope `useAccess` over the [remote-access](../../packages/api/remote-access/README.md) Client service. `SessionProvider` inherits an outer binding or binds an explicit `SessionReference`, so concurrent subtrees can target different Sessions. Domain adapters add further standard sources without putting React hooks on the model objects. `ui-conversation` binds once to each `SessionBinding.eventSource`. Its event registry correlates durable Session events and Client-only `assistant/live-chunk` updates into stable business Contexts, and its view registry materializes target snapshots. Chat Assistant, Trajectory Assistant, and Turn Tail interpret both live chunks and the compact streams embedded in durable settlements, so reconnect and paged history reproduce the same Assistant state without durable token rows. `ui-chat` and `ui-trajectory` register separate Definitions and builders: they may interpret the same event family, but they do not import or share each other's final display model. The shell selects a registered view and passes its snapshot through standard hooks and Slots. [Conversation](conversation.md) defines Context identity, replay, Location data, target builders, and keyed renderers. diff --git a/docs/subsystems/web-client.zh.md b/docs/subsystems/web-client.zh.md index 5230eef917..a3d62f738f 100644 --- a/docs/subsystems/web-client.zh.md +++ b/docs/subsystems/web-client.zh.md @@ -57,7 +57,7 @@ Connection 拥有请求 URL 解析、request correlation、`/api` carrier、trus Web 和桌面端共享[代码工作工具偏好](../../packages/client/ui-settings/README.zh.md#use-this-package)。它控制诊断 View、[可用的预设选项](../../packages/client/ui-agent-preset/README.zh.md)、改动文件卡片和内置 HTML 预览策略,不改变 Session 记录。 -`ui-session` 安装 Session scope adapter,并提供 `useSessions`、`useSessionStatus`、`useSessionRetainInfo`、`useSession`、`sessionId` 和 `useProjection`。`SessionProvider` 可以继承外围 binding,也可以绑定显式 `SessionReference`,因此并存子树可以指向不同 Session。领域 adapter 可以继续添加标准 source,但不会把 React hook 放进 model object。 +`ui-session` 安装 Session scope adapter,并在 [remote-access](../../packages/api/remote-access/README.zh.md) Client 服务之上提供 `useSessions`、`useSessionStatus`、`useSessionRetainInfo`、`useSessionAccess`、`useSession`、`sessionId`、`useProjection` 和会话作用域的 `useAccess`。`SessionProvider` 可以继承外围 binding,也可以绑定显式 `SessionReference`,因此并存子树可以指向不同 Session。领域 adapter 可以继续添加标准 source,但不会把 React hook 放进 model object。 `ui-conversation` 对每个 `SessionBinding.eventSource` 只绑定一次。它的 event registry 把持久 Session event 与 Client-only `assistant/live-chunk` update 关联成稳定的业务 Context,view registry 则 materialize target snapshot。Chat Assistant、Trajectory Assistant 与 Turn Tail 同时解释 live chunk 和持久 settlement 中嵌入的紧凑 stream,因此重连与分页历史无需持久 token 行即可复现相同 Assistant 状态。`ui-chat` 与 `ui-trajectory` 分别注册自己的 Definition 和 builder:它们可以解释同一 event family,但不会导入或共享彼此的最终 display model。Shell 选择一个已注册 view,再通过标准 hook 与 Slot 交付其 snapshot。[Conversation](conversation.zh.md)定义 Context identity、replay、Location data、target builder 与 keyed renderer。 diff --git a/docs/subsystems/web-server.i18n.yaml b/docs/subsystems/web-server.i18n.yaml index c2e4d0bec6..9a9d78794a 100644 --- a/docs/subsystems/web-server.i18n.yaml +++ b/docs/subsystems/web-server.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/web-server.md /http-server: - en: 778b8499fa5ec417 - zh: f2073db3d2ed8b70 + en: c9b2f67d3248c496 + zh: 5fa36d2837ff4f63 /http-server/routes: - en: 940bc78642c990b0 - zh: 901d2ba7e354a766 + en: e949c3738a35b58f + zh: 138e3aaeb319ddc4 /http-server/config: - en: 30118110a0ea3702 - zh: 940f2b69d2dd54af + en: 4b162bd9f280eb06 + zh: 3bea98dfee88c582 /http-server/the-service: - en: e304734ab2143438 - zh: 065f9c2acbbb07ca + en: cc36972b8458279f + zh: c129044935d44769 diff --git a/docs/subsystems/web-server.md b/docs/subsystems/web-server.md index 2826bbe9d2..df76650336 100644 --- a/docs/subsystems/web-server.md +++ b/docs/subsystems/web-server.md @@ -2,7 +2,7 @@ English | [中文](web-server.zh.md) -[dsh-host-webserver](../../packages/host/webserver) is the browser HTTP carrier for the GUI host: a single `node:http` plugin providing `ctx.webServer`, a named-route registry, optional gzip response compression, index.html transform callbacks, and one fallback handler that a plugin may claim. It is not part of the agent loop and not a capability seam; it knows no harness concepts, and another plugin registers every feature route, including the `/api` bridge, plugin bundles, and the HMR event stream ([layering reference](../../packages/boot/app-boot/README.md)). It serves browsers only: Electron loads the built files over `file://` and sends fetch requests through an IPC bridge instead of this server. +[dsh-host-webserver](../../packages/host/webserver) is the browser HTTP carrier for the GUI host: one `node:http` server — `node:https` when `tls` is configured — providing `ctx.webServer`, a named-route registry, optional gzip response compression, index.html transform callbacks, and one fallback handler that a plugin may claim. It is not part of the agent loop and not a capability seam; it knows no harness concepts, and another plugin registers every feature route, including the `/api` bridge, plugin bundles, and the HMR event stream ([layering reference](../../packages/boot/app-boot/README.md)). It serves browsers only: Electron loads the built files over `file://` and sends fetch requests through an IPC bridge instead of this server. Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) @@ -26,15 +26,34 @@ interface WebRoute { Match order is fixed: exact table first, then longest matching prefix, then the registered fallback. Registration order carries no request-facing semantics — named routes are composed to be disjoint, and the fallback seat answers anything no named route claims; one owner only, a second registration throws. The shipped Web composition claims the seat with [`dsh-host-frontend-static`](../../packages/host/frontend-static/src/index.ts), the SPA dist server with locked semantics: Connection authenticates the dist root and configured index before their HTML is read; non-index assets remain public; non-GET/HEAD is 405, traversal outside the dist root is 403, existing files are served directly, absent or non-file targets are empty 404 responses, and unknown extensions ship as octet-stream. + + ## Config ```ts type-equiv -/** Web server listen and response-compression config. */ +/** Web server listen, TLS, and response-compression config. */ interface Config { - /** Listen host; the two supported values are loopback and all-interfaces. */ - host: '127.0.0.1' | '0.0.0.0' + /** + * Listen address: a concrete IPv4 or IPv6 literal of one local interface, + * for example the container's own Pod address from `hostname -i`. A loopback + * literal (any address in 127/8, `::1`, or a mapped form of either) keeps the + * server on this machine; any other literal serves the network that address + * belongs to, over plain HTTP unless `tls` is set. The unspecified address — + * IPv4 any, IPv6 any, and the IPv4-mapped forms of IPv4 any — is rejected at + * load: it would expose the port on every interface at once. + */ + host: string /** Listen port; zero requests an OS-assigned port. */ port: number + /** + * Serve HTTPS with this certificate and key instead of plain HTTP. Both files + * are read once, before the listener binds: an unreadable or empty file, + * invalid PEM, or a key that does not match the certificate rejects + * initialization rather than falling back to HTTP. The material is never + * re-read, so replacing a certificate takes a reload. Omitted or null listens + * over plain HTTP. + */ + tls?: TlsConfig /** Response compression for socket-backed HTTP requests. @default 'none' */ compression?: 'none' | 'gzip' /** Gzip DEFLATE level from 0 through 9. @default 1 */ @@ -44,13 +63,27 @@ interface Config { } ``` -`host` accepts only `127.0.0.1` (default posture) and `0.0.0.0` (deliberate network exposure). The carrier itself owns no TLS, authentication, or Origin policy, so a non-loopback bind exposes the server unless the composition supplies those controls. `compression` defaults to `none`; the shipped Web bundle selects gzip level 1 with a 1024-byte threshold. The shipped `dsh web` command selects loopback and rejects `--host 0.0.0.0`; its Connection plugin supplies Host/Origin checks plus browser-session authentication for every Host API route and stream. Other compositions own their bind and route-authentication policy. The dist location is an assembly fact of the frontend plugin that claims the seat. +```ts type-equiv +/** + * TLS material for the HTTPS listener: one certificate chain file and the + * private key file it pairs with. Both hold PEM text and both resolve against + * the process working directory. + */ +interface TlsConfig { + /** Certificate chain file, leaf certificate first, PEM, no passphrase. */ + certFile: string + /** Private key file for the chain's leaf certificate; unencrypted PEM. */ + keyFile: string +} +``` + +No composition can bind every interface at once: the unspecified address is rejected at load. The exported `isWildcardHost` and `isLoopbackHost` classify a bind address from its parsed value, and an IPv6 `%zone` is kept for `listen` while classification reads the address alone. The carrier owns no authentication or Origin policy, and it serves plain HTTP unless `tls` supplies a certificate and key. `compression` defaults to `none`; the shipped Web bundle selects gzip level 1 with a 1024-byte threshold. The shipped `dsh web` command selects loopback by default and accepts one concrete `--host` address, warning at startup when a non-loopback bind serves plain HTTP; its Connection plugin supplies Host/Origin checks plus browser-session authentication for every Host API route and stream, and the bind address plus `--trusted-host` govern which browser Host is accepted; `--public-url` changes only the advertised URL. Other compositions own their bind and route-authentication policy. The dist location is an assembly fact of the frontend plugin that claims the seat. ## The service -`WebServer` (`ctx.webServer`) listens immediately on activation; a listen failure (EADDRINUSE…) rejects initialization, and the boot process reports the failed fiber. `register(route)` adds one named route and returns its disposer; a duplicate `(kind, path)` throws because route patterns are a composition-level contract and a collision is a misconfiguration. Gzip wraps eligible socket-backed responses inside the server, so route handlers retain direct `ServerResponse` ownership and no response-writing API is added to the service. Existing content encodings, `Cache-Control: no-transform`, ranges, SSE, ZIP, and the packaged `.gz` Worker image remain identity responses. `collectIndexInjections()` gathers structured `IndexInjection` rows over one `webserver/index-inject` emit, and `renderIndex(html)` renders them into successful root and configured index responses before applying the raw `tapIndex(transform)` escape-hatch transforms in registration order; [dsh-client-modules](../../packages/client/modules) answers the event with the boot manifest rows. `port` reads the listening port, including the port assigned by the OS when `config.port` is 0. +`WebServer` (`ctx.webServer`) listens immediately on activation; a listen failure (EADDRINUSE…) rejects initialization, and the boot process reports the failed fiber. The `tls` pair is read once before the listener binds, and an unreadable, empty, or mismatched pair rejects initialization the same way instead of falling back to HTTP. `register(route)` adds one named route and returns its disposer; a duplicate `(kind, path)` throws because route patterns are a composition-level contract and a collision is a misconfiguration. Gzip wraps eligible socket-backed responses inside the server, so route handlers retain direct `ServerResponse` ownership and no response-writing API is added to the service. Existing content encodings, `Cache-Control: no-transform`, ranges, SSE, ZIP, and the packaged `.gz` Worker image remain identity responses. `collectIndexInjections()` gathers structured `IndexInjection` rows over one `webserver/index-inject` emit, and `renderIndex(html)` renders them into successful root and configured index responses before applying the raw `tapIndex(transform)` escape-hatch transforms in registration order; [dsh-client-modules](../../packages/client/modules) answers the event with the boot manifest rows. `port` reads the listening port, including the port assigned by the OS when `config.port` is 0, and `protocol` reports the scheme the listener serves (`http:` or `https:`). -A request whose handling throws (a malformed %-escape hitting `decodeURIComponent`, a client dropping mid-body) is logged as a warning and answered 400 — or the socket destroyed when headers are already out — never a process exit. Disposal pairs `close()` with `closeAllConnections()` because a handler may hold its response open (SSE) and such connections never end on their own; without the force-close, teardown would hang. The package never prints: the URL line belongs to the shell. Per-package operational detail, including the dev-mode bundle watch pipeline, stays in the [README](../../packages/host/webserver/README.md). +A request whose handling throws (a malformed %-escape hitting `decodeURIComponent`, a client dropping mid-body) is logged as a warning and answered 400 — or the socket destroyed when headers are already out — never a process exit. Disposal pairs `close()` with `closeAllConnections()` because a handler may hold its response open (SSE) and such connections never end on their own; without the force-close, teardown would hang. A TLS socket counts as a connection only after its handshake, so the server tracks raw TLS sockets beside upgraded ones and destroys both at disposal. The package never prints: the URL line belongs to the shell. Per-package operational detail, including the dev-mode bundle watch pipeline, stays in the [README](../../packages/host/webserver/README.md). @@ -83,15 +116,27 @@ createSharedFetchHandler(channel: '/api'): ConnectionFetchHandler requestRejection(request: ConnectionTrustRequest): ConnectionRequestRejection /** - * Admit one request: it passes {@link requestRejection} and speaks for the - * operator, or it is refused with that status. + * Admit one network request: it passes {@link requestRejection} and speaks + * for {@link browserPeer}, or it is refused with that status. * @param request - request headers from the HTTP or upgrade request. - * @returns the operator Peer, or the rejection status. + * @returns the admitted Peer, or the rejection status. */ admit(request: ConnectionTrustRequest): PeerAdmission +/** + * Create an independent Peer. In-process only: no route, header, query, or + * cookie reaches it. Disposed with the Context that read `ctx.connection`, + * or earlier by its own `dispose()`. + * @param options - caller identity the Peer speaks for. + * @param options.principal - principal fixed for the Peer's lifetime. + * @returns a new Peer distinct from every other Peer. + */ +createPeer(options: { readonly principal: Principal }): PeerScope + /** * Authenticate one frontend index request, owning a token redirect or 401. + * The cookie this mints is `Secure` when the mounted Web carrier serves TLS, + * which only that listener's protocol decides. * @param request - root or configured-index HTTP request. * @param response - response owned when the result is false. * @returns true only when the frontend may serve index.html. @@ -106,15 +151,41 @@ authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexRespons authenticatedUrl(baseUrl: string): string ``` +Types: [Principal](typert.md) + 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` -The browser HTTP carrier service. Activation listens immediately. 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. A listen failure rejects initialization, and the boot process reports the failed fiber. +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 72ef366958..ed53d0ec22 100644 --- a/docs/subsystems/web-server.zh.md +++ b/docs/subsystems/web-server.zh.md @@ -2,7 +2,7 @@ [English](web-server.md) | 中文 -[dsh-host-webserver](../../packages/host/webserver) 是 GUI Host 的浏览器 HTTP 载体:它是一个提供 `ctx.webServer` 的 `node:http` 插件,包含具名路由注册表、可选的 gzip 响应压缩、index.html 转换回调,以及一个可由插件认领的回退处理器。它不属于 agent loop(智能体循环),也不是能力 seam;它不了解任何 harness 概念。其他插件负责注册所有功能路由,包括 `/api` 桥接、插件 bundle 和 HMR(热模块替换)事件流([分层说明](../../packages/boot/app-boot/README.zh.md))。该服务器只服务浏览器:Electron 通过 `file://` 加载已构建文件,并经 IPC 桥接发送 fetch 请求,不使用本服务器。 +[dsh-host-webserver](../../packages/host/webserver) 是 GUI Host 的浏览器 HTTP 载体:一个 `node:http` 服务器——配置 `tls` 时改用 `node:https`——提供 `ctx.webServer`、具名路由注册表、可选的 gzip 响应压缩、index.html 转换回调,以及一个可由插件认领的回退处理器。它不属于 agent loop(智能体循环),也不是能力 seam;它不了解任何 harness 概念。其他插件负责注册所有功能路由,包括 `/api` 桥接、插件 bundle 和 HMR(热模块替换)事件流([分层说明](../../packages/boot/app-boot/README.zh.md))。该服务器只服务浏览器:Electron 通过 `file://` 加载已构建文件,并经 IPC 桥接发送 fetch 请求,不使用本服务器。 源码:[`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) @@ -26,15 +26,34 @@ interface WebRoute { 匹配顺序固定:先查 exact 表,再取最长匹配前缀,最后落到已注册的回退。注册顺序不携带任何面向请求的语义:具名路由在组合上互不相交,任何未被具名路由认领的请求都由回退席位应答;席位只有一个所有者,第二次注册会抛出异常。发布的 Web 组合用 [`dsh-host-frontend-static`](../../packages/host/frontend-static/src/index.ts) 认领席位,即遵循固定语义的 SPA dist 服务器:Connection 在读取 dist 根目录和配置 index 的 HTML 前完成认证;非 index 资产保持公开;非 GET/HEAD 返回 405,越出 dist 根目录的遍历返回 403,现有文件直接提供,缺失或不是文件的目标返回空的 404,未知扩展名按 octet-stream 发送。 + + ## 配置 ```ts type-equiv -/** Web server listen and response-compression config. */ +/** Web server listen, TLS, and response-compression config. */ interface Config { - /** Listen host; the two supported values are loopback and all-interfaces. */ - host: '127.0.0.1' | '0.0.0.0' + /** + * Listen address: a concrete IPv4 or IPv6 literal of one local interface, + * for example the container's own Pod address from `hostname -i`. A loopback + * literal (any address in 127/8, `::1`, or a mapped form of either) keeps the + * server on this machine; any other literal serves the network that address + * belongs to, over plain HTTP unless `tls` is set. The unspecified address — + * IPv4 any, IPv6 any, and the IPv4-mapped forms of IPv4 any — is rejected at + * load: it would expose the port on every interface at once. + */ + host: string /** Listen port; zero requests an OS-assigned port. */ port: number + /** + * Serve HTTPS with this certificate and key instead of plain HTTP. Both files + * are read once, before the listener binds: an unreadable or empty file, + * invalid PEM, or a key that does not match the certificate rejects + * initialization rather than falling back to HTTP. The material is never + * re-read, so replacing a certificate takes a reload. Omitted or null listens + * over plain HTTP. + */ + tls?: TlsConfig /** Response compression for socket-backed HTTP requests. @default 'none' */ compression?: 'none' | 'gzip' /** Gzip DEFLATE level from 0 through 9. @default 1 */ @@ -44,13 +63,27 @@ interface Config { } ``` -`host` 只接受 `127.0.0.1`(默认姿态)和 `0.0.0.0`(刻意的网络暴露)。载体本身不拥有 TLS、认证或 Origin 策略,因此绑定到非回环地址会暴露服务器,除非组合层提供这些控制。`compression` 默认为 `none`;随附的 Web 组合选择 gzip level 1 和 1024 字节阈值。随附的 `dsh web` 命令选择 loopback 并拒绝 `--host 0.0.0.0`;其 Connection 插件为每个 Host API route 与 stream 提供 Host/Origin 校验和浏览器会话认证。其他组合自行拥有绑定与路由认证策略。dist 位置是认领席位的前端插件的组装事实。 +```ts type-equiv +/** + * TLS material for the HTTPS listener: one certificate chain file and the + * private key file it pairs with. Both hold PEM text and both resolve against + * the process working directory. + */ +interface TlsConfig { + /** Certificate chain file, leaf certificate first, PEM, no passphrase. */ + certFile: string + /** Private key file for the chain's leaf certificate; unencrypted PEM. */ + keyFile: string +} +``` + +没有组合能一次性绑定所有网络接口:未指定地址在加载时即被拒绝。导出的 `isWildcardHost` 与 `isLoopbackHost` 按解析后的地址值分类,IPv6 的 `%zone` 会保留给 `listen`,而分类只读取地址本身。载体不拥有认证或 Origin 策略,并且除非 `tls` 提供证书与密钥,否则以明文 HTTP 提供服务。`compression` 默认为 `none`;随附的 Web 组合选择 gzip level 1 和 1024 字节阈值。随附的 `dsh web` 命令默认选择 loopback 并接受一个具体的 `--host` 地址,非 loopback 绑定以明文 HTTP 提供服务时会在启动时警告;其 Connection 插件为每个 Host API route 与 stream 提供 Host/Origin 校验和浏览器会话认证,绑定地址加 `--trusted-host` 决定接受哪个浏览器 Host;`--public-url` 只改变公告的 URL。其他组合自行拥有绑定与路由认证策略。dist 位置是认领席位的前端插件的组装事实。 ## 服务 -`WebServer`(`ctx.webServer`)在激活时立即监听;监听失败(EADDRINUSE 等)会使初始化被拒绝,启动进程会报告失败的 fiber。`register(route)` 添加一条具名路由并返回其 disposer;重复的 `(kind, path)` 抛出异常,因为路由模式是组合层约定,冲突即配置错误。Gzip 在服务器内部包装符合条件且基于 socket 的响应,因此 route handler 继续直接持有 `ServerResponse`,服务也不新增响应写出 API。已有内容编码、`Cache-Control: no-transform`、范围响应、SSE、ZIP 与打包后的 `.gz` Worker 镜像均保持 identity 响应。`collectIndexInjections()` 经一次 `webserver/index-inject` emit 收集结构化 `IndexInjection` 行,`renderIndex(html)` 把它们渲染进成功的根路径和配置 index 响应,随后再按注册顺序应用原始的 `tapIndex(transform)` 逃生口转换;[dsh-client-modules](../../packages/client/modules) 以启动 manifest(元数据清单)行回应该事件。`port` 读取监听端口,包括 `config.port` 为 0 时操作系统分配的端口。 +`WebServer`(`ctx.webServer`)在激活时立即监听;监听失败(EADDRINUSE 等)会使初始化被拒绝,启动进程会报告失败的 fiber。`tls` 证书对在监听器绑定前读取一次;文件不可读、为空或二者不匹配时同样会使初始化被拒绝,而不是回退到 HTTP。`register(route)` 添加一条具名路由并返回其 disposer;重复的 `(kind, path)` 抛出异常,因为路由模式是组合层约定,冲突即配置错误。Gzip 在服务器内部包装符合条件且基于 socket 的响应,因此 route handler 继续直接持有 `ServerResponse`,服务也不新增响应写出 API。已有内容编码、`Cache-Control: no-transform`、范围响应、SSE、ZIP 与打包后的 `.gz` Worker 镜像均保持 identity 响应。`collectIndexInjections()` 经一次 `webserver/index-inject` emit 收集结构化 `IndexInjection` 行,`renderIndex(html)` 把它们渲染进成功的根路径和配置 index 响应,随后再按注册顺序应用原始的 `tapIndex(transform)` 逃生口转换;[dsh-client-modules](../../packages/client/modules) 以启动 manifest(元数据清单)行回应该事件。`port` 读取监听端口,包括 `config.port` 为 0 时操作系统分配的端口,`protocol` 则报告监听器提供的协议(`http:` 或 `https:`)。 -处理过程中抛出异常的请求(畸形的 % 转义撞上 `decodeURIComponent`、客户端在请求体中途断开)会记录为警告并应答 400(响应头已发出时则销毁 socket),绝不导致进程退出。dispose(资源释放)把 `close()` 与 `closeAllConnections()` 配对使用,因为处理器可能像 SSE(Server-Sent Events)那样保持响应打开,而这类连接永远不会自行结束;没有强制关闭,拆卸就会挂起。该包从不打印输出:URL 行归 shell 所有。逐包运维细节(含开发模式的 bundle 监视流水线)留在 [README](../../packages/host/webserver/README.zh.md) 中。 +处理过程中抛出异常的请求(畸形的 % 转义撞上 `decodeURIComponent`、客户端在请求体中途断开)会记录为警告并应答 400(响应头已发出时则销毁 socket),绝不导致进程退出。dispose(资源释放)把 `close()` 与 `closeAllConnections()` 配对使用,因为处理器可能像 SSE(Server-Sent Events)那样保持响应打开,而这类连接永远不会自行结束;没有强制关闭,拆卸就会挂起。TLS socket 只有完成握手后才计入连接,因此服务器会把原始 TLS socket 与升级后的 socket 一并跟踪,并在 dispose 时销毁两者。该包从不打印输出:URL 行归 shell 所有。逐包运维细节(含开发模式的 bundle 监视流水线)留在 [README](../../packages/host/webserver/README.zh.md) 中。 @@ -83,15 +116,27 @@ createSharedFetchHandler(channel: '/api'): ConnectionFetchHandler requestRejection(request: ConnectionTrustRequest): ConnectionRequestRejection /** - * Admit one request: it passes {@link requestRejection} and speaks for the - * operator, or it is refused with that status. + * Admit one network request: it passes {@link requestRejection} and speaks + * for {@link browserPeer}, or it is refused with that status. * @param request - request headers from the HTTP or upgrade request. - * @returns the operator Peer, or the rejection status. + * @returns the admitted Peer, or the rejection status. */ admit(request: ConnectionTrustRequest): PeerAdmission +/** + * Create an independent Peer. In-process only: no route, header, query, or + * cookie reaches it. Disposed with the Context that read `ctx.connection`, + * or earlier by its own `dispose()`. + * @param options - caller identity the Peer speaks for. + * @param options.principal - principal fixed for the Peer's lifetime. + * @returns a new Peer distinct from every other Peer. + */ +createPeer(options: { readonly principal: Principal }): PeerScope + /** * Authenticate one frontend index request, owning a token redirect or 401. + * The cookie this mints is `Secure` when the mounted Web carrier serves TLS, + * which only that listener's protocol decides. * @param request - root or configured-index HTTP request. * @param response - response owned when the result is false. * @returns true only when the frontend may serve index.html. @@ -106,15 +151,41 @@ authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexRespons authenticatedUrl(baseUrl: string): string ``` +Types: [Principal](typert.zh.md) + 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` -The browser HTTP carrier service. Activation listens immediately. 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. A listen failure rejects initialization, and the boot process reports the failed fiber. +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..b363ba184d 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` @@ -273,35 +277,13 @@ Typed Remote control of transient Session-owned terminal processes. @Remote({ mode: 'stream' }) retain(sessionId: SessionId, id: WebTerminalId, signal: AbortSignal): AsyncIterable /** - * Attach to a terminal without binding its process lifetime to the transport. + * Attach terminal input and output to one physical Remote stream. * @param agent - Session owner supplied by the Gateway. * @param id - terminal identity. - * @param attachmentId - new exclusive input attachment. - * @param signal - physical stream cancellation. - * @returns screen recovery followed by output and metadata changes. + * @param signal - attachment cancellation; the process remains alive and input is never replayed. + * @returns screen recovery, output, writable state and provider-acceptance acknowledgements. */ -@Remote({ mode: 'stream' }) follow(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, signal: AbortSignal): AsyncIterable - -/** - * Deliver raw input, including Tab completion and control characters. - * @param agent - Session owner supplied by the Gateway. - * @param id - terminal identity. - * @param attachmentId - current writable attachment. - * @param data - input bytes represented as UTF-8 text. - * @returns after provider input acceptance. - */ -@Remote async write(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, data: string): Promise - -/** - * Update the dimensions of the PTY and recovery screen. - * @param agent - Session owner supplied by the Gateway. - * @param id - terminal identity. - * @param attachmentId - current writable attachment. - * @param cols - column count. - * @param rows - row count. - * @returns after the resize completes. - */ -@Remote async resize(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, cols: number, rows: number): Promise +@Remote({ mode: 'stream' }) attach(agent: Agent, id: WebTerminalId, signal: AbortSignal): RemoteStream /** * Rename a terminal without changing its shell. @@ -320,7 +302,7 @@ Typed Remote control of transient Session-owned terminal processes. @Remote async close(agent: Agent, id: WebTerminalId): Promise ``` -Types: [Agent](core.md) · [SessionId](core.md) +Types: [Agent](core.md) · [RemoteStream](typert.md) · [SessionId](core.md) Source: [`packages/api/terminal-controller/src/index.ts`](../../packages/api/terminal-controller/src/index.ts) @@ -405,11 +387,17 @@ Host service backing the generated `ctx.remote.workspace` namespace. @Remote('unpinSession') unpinSession(request: WorkspaceUnpinSessionRequest): Promise /** - * Stream a complete Workspace baseline followed by ordered increments. + * Stream a complete Workspace baseline followed by ordered increments. A + * non-owner receives only the Workspaces and Sessions `allows()` admits. + * When a delivered Workspace is no longer admitted at its next change or + * the next order change, the stream sends a `replace` frame with the + * complete filtered state instead of a `remove`, because a Client never + * resurrects a removed Workspace; a `remove` frame reports a deletion and + * reaches only a Client that received that Workspace. * @param signal - generation cancellation. * @returns baseline followed by ordered Workspace increments. */ -@Remote({ mode: 'stream' }) follow(signal: AbortSignal): AsyncIterable +@Remote({ mode: 'stream' }) async *follow(signal: AbortSignal): AsyncIterable ``` Source: [`packages/api/workspace-controller/src/index.ts`](../../packages/api/workspace-controller/src/index.ts) diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 868712b4c9..c04a05c97d 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` @@ -273,35 +277,13 @@ Typed Remote control of transient Session-owned terminal processes. @Remote({ mode: 'stream' }) retain(sessionId: SessionId, id: WebTerminalId, signal: AbortSignal): AsyncIterable /** - * Attach to a terminal without binding its process lifetime to the transport. + * Attach terminal input and output to one physical Remote stream. * @param agent - Session owner supplied by the Gateway. * @param id - terminal identity. - * @param attachmentId - new exclusive input attachment. - * @param signal - physical stream cancellation. - * @returns screen recovery followed by output and metadata changes. + * @param signal - attachment cancellation; the process remains alive and input is never replayed. + * @returns screen recovery, output, writable state and provider-acceptance acknowledgements. */ -@Remote({ mode: 'stream' }) follow(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, signal: AbortSignal): AsyncIterable - -/** - * Deliver raw input, including Tab completion and control characters. - * @param agent - Session owner supplied by the Gateway. - * @param id - terminal identity. - * @param attachmentId - current writable attachment. - * @param data - input bytes represented as UTF-8 text. - * @returns after provider input acceptance. - */ -@Remote async write(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, data: string): Promise - -/** - * Update the dimensions of the PTY and recovery screen. - * @param agent - Session owner supplied by the Gateway. - * @param id - terminal identity. - * @param attachmentId - current writable attachment. - * @param cols - column count. - * @param rows - row count. - * @returns after the resize completes. - */ -@Remote async resize(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, cols: number, rows: number): Promise +@Remote({ mode: 'stream' }) attach(agent: Agent, id: WebTerminalId, signal: AbortSignal): RemoteStream /** * Rename a terminal without changing its shell. @@ -320,7 +302,7 @@ Typed Remote control of transient Session-owned terminal processes. @Remote async close(agent: Agent, id: WebTerminalId): Promise ``` -Types: [Agent](core.zh.md) · [SessionId](core.zh.md) +Types: [Agent](core.zh.md) · [RemoteStream](typert.zh.md) · [SessionId](core.zh.md) Source: [`packages/api/terminal-controller/src/index.ts`](../../packages/api/terminal-controller/src/index.ts) @@ -405,11 +387,17 @@ Host service backing the generated `ctx.remote.workspace` namespace. @Remote('unpinSession') unpinSession(request: WorkspaceUnpinSessionRequest): Promise /** - * Stream a complete Workspace baseline followed by ordered increments. + * Stream a complete Workspace baseline followed by ordered increments. A + * non-owner receives only the Workspaces and Sessions `allows()` admits. + * When a delivered Workspace is no longer admitted at its next change or + * the next order change, the stream sends a `replace` frame with the + * complete filtered state instead of a `remove`, because a Client never + * resurrects a removed Workspace; a `remove` frame reports a deletion and + * reaches only a Client that received that Workspace. * @param signal - generation cancellation. * @returns baseline followed by ordered Workspace increments. */ -@Remote({ mode: 'stream' }) follow(signal: AbortSignal): AsyncIterable +@Remote({ mode: 'stream' }) async *follow(signal: AbortSignal): AsyncIterable ``` Source: [`packages/api/workspace-controller/src/index.ts`](../../packages/api/workspace-controller/src/index.ts) diff --git a/docs/testing.i18n.yaml b/docs/testing.i18n.yaml index d7936c0fef..4a45861506 100644 --- a/docs/testing.i18n.yaml +++ b/docs/testing.i18n.yaml @@ -9,8 +9,8 @@ en: c024da7e8d9cb056 zh: c4cc1a66d2903656 /testing-policy/how-specs-execute: - en: 5d8eb65958da096d - zh: 4a40f1c5fe5b2d14 + en: 022c534e72e23142 + zh: c07a20994224f37c /testing-policy/the-with-key-policy-inference-is-cheap-here: en: d555af53068bf523 zh: ddc4265e5de5b3be diff --git a/docs/testing.md b/docs/testing.md index 9ea6db1501..1ba63f9c35 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -18,7 +18,7 @@ Session fixtures retain headers and payloads but omit body sequence/time envelop ## How specs execute -Forked workers run several spec files at once, the coverage gate splits into concurrent partitions beside the other gates in its job, and the self-hosted runners share one host and one volume. Only the process is isolated: ports, predictable paths, external namespaces, and inherited children are not. Own each acquired resource through teardown. A spec passing only alone has a test defect, not an unstable runner. [dsh-ci-test-reliability](../.agents/skills/dsh-ci-test-reliability/SKILL.md) owns the allocation, restoration, synchronization, timeout-budget, platform, and teardown rules; its [flake diagnosis workflow](../.agents/skills/dsh-ci-test-reliability/references/ci-flake-diagnosis.md) classifies an existing probabilistic failure. [Unexpected fork exits](../scripts/coverage-fork-diagnostics.ts) report PID, file, code, and signal. +Forked workers run several spec files at once, the coverage gate splits into [concurrent partitions](../scripts/coverage-partitions.ts) beside the other gates in its job, and the self-hosted runners share one host and one volume. Only the process is isolated: ports, predictable paths, external namespaces, and inherited children are not. Own each acquired resource through teardown. A spec passing only alone has a test defect, not an unstable runner. [dsh-ci-test-reliability](../.agents/skills/dsh-ci-test-reliability/SKILL.md) owns the allocation, restoration, synchronization, timeout-budget, platform, and teardown rules; its [flake diagnosis workflow](../.agents/skills/dsh-ci-test-reliability/references/ci-flake-diagnosis.md) classifies an existing probabilistic failure. [Unexpected fork exits](../scripts/coverage-fork-diagnostics.ts) report PID, file, code, and signal. ## The with-key policy: inference is cheap here diff --git a/docs/testing.zh.md b/docs/testing.zh.md index 81c16c60ab..c7545a9686 100644 --- a/docs/testing.zh.md +++ b/docs/testing.zh.md @@ -18,7 +18,7 @@ Session fixture 保留 header 与 payload,但省略正文 seq/time envelope; ## spec 如何被执行 -fork 出的 worker 会同时运行多个 spec 文件,coverage gate 会拆成并发的 partition,与同一个 job 中的其它 gate 并排运行,而自托管 runner 共用同一台宿主机和同一个卷。被隔离的只有进程:端口、可预测路径、外部命名空间和继承而来的子进程都不隔离。为每个占用的资源负责到 teardown。只在单独运行时通过的 spec 存在测试缺陷,而非 runner 不稳定。[dsh-ci-test-reliability](../.agents/skills/dsh-ci-test-reliability/SKILL.md) 负责资源分配、状态恢复、同步、超时预算、平台差异与 teardown 规则;它的 [flake 诊断流程](../.agents/skills/dsh-ci-test-reliability/references/ci-flake-diagnosis.md)用于归类已经存在的概率性失败。 [fork 意外退出](../scripts/coverage-fork-diagnostics.ts)时会报告 PID、文件、退出码和信号。 +fork 出的 worker 会同时运行多个 spec 文件,coverage gate 会拆成[并发的 partition](../scripts/coverage-partitions.ts),与同一个 job 中的其它 gate 并排运行,而自托管 runner 共用同一台宿主机和同一个卷。被隔离的只有进程:端口、可预测路径、外部命名空间和继承而来的子进程都不隔离。为每个占用的资源负责到 teardown。只在单独运行时通过的 spec 存在测试缺陷,而非 runner 不稳定。[dsh-ci-test-reliability](../.agents/skills/dsh-ci-test-reliability/SKILL.md) 负责资源分配、状态恢复、同步、超时预算、平台差异与 teardown 规则;它的 [flake 诊断流程](../.agents/skills/dsh-ci-test-reliability/references/ci-flake-diagnosis.md)用于归类已经存在的概率性失败。 [fork 意外退出](../scripts/coverage-fork-diagnostics.ts)时会报告 PID、文件、退出码和信号。 ## 带密钥策略:推理(inference)在这里很便宜 diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index e14eeb549f..af0cd38b46 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -9,14 +9,14 @@ en: 6cc2cd9ced70bb09 zh: 1c0e6cb4ba2ed637 /tool-schema-catalog/tool-package-map: - en: 7caa258c67464109 - zh: 53bfb5581c48dc45 + en: e18a3e3c916afb23 + zh: 4284b50a5e9bd12f /tool-schema-catalog/deepseek-ai-dsh-plugin-manager: en: e0143916bb634762 zh: e0143916bb634762 /tool-schema-catalog/deepseek-ai-dsh-plugin-manager/plugin-manager: - en: ab4d1e7f7aa435b5 - zh: 70af9245b9b98039 + en: 55b6f02a3ef555cf + zh: 5263303aa6efd86e /tool-schema-catalog/deepseek-ai-dsh-mcp-resources: en: dd78bd55ec83a539 zh: dd78bd55ec83a539 @@ -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 @@ -264,8 +264,8 @@ en: f9457f033f75f00a zh: a2d60ec44118c34c /tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team/send-message: - en: e99455aec4656ff2 - zh: a8f88ec35cfe38b8 + en: ec50e6a0b86aecc6 + zh: 29c8728536a5adf1 /tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team/spawn-teammate: en: 02d6cc746e234b99 zh: 49bc60ac098bca48 @@ -282,8 +282,8 @@ en: 2eac7360ba68b1bd zh: b5d676bf288c245e /tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team/wait-agent: - en: fbc4d75a9bcf6816 - zh: 672131ac2705f411 + en: e70c77a45832bb28 + zh: 7d03bec294b65452 /tool-schema-catalog/deepseek-ai-dsh-tool-todo: en: dea62d26fb18ff68 zh: dea62d26fb18ff68 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 143d1b29df..f96fe0802d 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -40,7 +40,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`, `subagent` | `ctx.tools`, `ctx.subagents`, `ctx.systemPrompt`, `ctx.llm for model discovery and selected-route validation` | `tool/call`, `tool/result`, `child session events through the chosen provider` | `subagent`, `subagent_fork` | The registered delegation name is the load-time `toolName` config (default `subagent`); the default schema above has model selection off, while the discovery schema is shown as the fixed companion available in an enabled Session. Web presets sample the Plugins preference for each new top-level Session and preserve that decision for its child Sessions; `subagent_fork` remains fixed-route. Each instance selects its backend through `provider` and reads model-selection settings through `modelSelectionSettings`. Every delegation returns a child id promptly; local children accept follow-ups, while external backends report their single execution automatically. | | `@deepseek-ai/dsh-tool-subagent-control` | `interrupt_agent`, `list_agents`, `send_message` | `ctx.tools`, `ctx.subagents`, `ctx.agents and ctx.sessionProjections (list_agents only)` | `tool/call`, `tool/result`, `child session events through ctx.subagents` | - | The globally named discovery, interruption, and local-message tools over managed subagents: provider-bound `tool-subagent` instances register distinct delegation tools, while this package registers `send_message` and `interrupt_agent` once, plus `list_agents` from its separately loaded `/list-agents` plugin (whose catalog rows use the sessionProjections and live Agent registries). | | `@deepseek-ai/dsh-tool-jobs` | `job_kill`, `job_list`, `job_output` | `ctx.tools`, `ctx.jobs`, `ctx.systemPrompt` | `tool/call`, `tool/result`, `user/message via agent.inject() for background completion notices` | - | The kind-agnostic background-job controller: background bash commands and PTY sends are read, listed, and killed through the same three tools. Loading the plugin attaches the controller that arms producers' `ctx.jobs.start()`. | -| `@deepseek-ai/dsh-experimental-tool-agent-team` | `interrupt_agent`, `list_agents`, `send_message`, `spawn_teammate`, `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update`, `wait_agent` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `an exact live Team member Agent` | `tool/call`, `team/member`, `team/message/queued`, `team/message/delivered`, `team/task`, `tool/result` | - | All nine tools are scoped to implicit Team Leads and durable teammates. The shipped dsh-base bundle keeps the package disabled; the documented Agent Teams profile patch enables it while disabling the legacy continuable-child control names. | +| `@deepseek-ai/dsh-experimental-tool-agent-team` | `interrupt_agent`, `list_agents`, `send_message`, `spawn_teammate`, `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update`, `wait_agent` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `an exact live Team member Agent` | `tool/call`, `team/member`, `team/task`, `agent/inbox/spliced`, `user/message on inbox claim`, `tool/result` | - | All nine tools are scoped to implicit Team Leads and durable teammates. The shipped dsh-base bundle keeps the package disabled; the documented Agent Teams profile patch enables it while disabling the legacy continuable-child control names. | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`, `owning Agent session` | `tool/call`, `todo/write`, `tool/result` | - | todo_write is session-owned state; UIs render the latest todo/write event as a checklist. `allowParallelInProgress` is required with no default, so the catalog states its choice: `true`, whose description invites several `in_progress` items. A deployment choosing `false` receives the same tool with a description asking for exactly one active task. | | `@deepseek-ai/dsh-tool-working-directory` | `working_directory` | `ctx.tools`, `ctx.workingDirectory` | `tool/call`, `working-directory/change`, `user context for directory changes`, `tool/result` | - | Reads or changes the calling Session directory. Existing shells and processes retain their own directories; origin metadata and permission roots stay fixed. | | `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `working-directory/change`, `tool/result` | - | Explicit experimental composition only. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. Leaving retains the branch and checkout. | @@ -54,7 +54,7 @@ This table connects model-visible tool names to the plugin package and service s ### `plugin_manager` -List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately; startup profiles require restart. Incompatible DSH peer dependencies block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one. +List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately, including upgrades of installed packages; a change result that is not applied carries nextStep, which says what to do or tell the user. Incompatible DSH peer dependencies block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one. ```json { @@ -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", @@ -1397,7 +1397,7 @@ Create a reminder in the current session that delivers prompt when it becomes du }, "title": { "type": "string", - "description": "Task name of at most 120 characters, shown on the task card and in task lists." + "description": "Concise task name in the user's language, at most 120 characters. Name only the core action and subject; keep essential target identifiers such as PR numbers and branch names. Do not include execution frequency (e.g. daily, hourly), scheduled dates/times, time zones, task status, or configuration and execution details (e.g. read-only mode, profile-tag filters), even when embedded in the requested or existing title. Do not append parenthetical notes. Put scheduling information in the timing parameters and execution instructions in prompt." }, "after_seconds": { "type": "number", @@ -1558,7 +1558,7 @@ Change a reminder in place, keeping its id. Supply a new title, prompt, or at mo }, "title": { "type": "string", - "description": "New task name of at most 120 characters." + "description": "New task name; follow the schedule_create title rules." }, "prompt": { "type": "string", @@ -2257,7 +2257,7 @@ Source: [`packages/experimental/tool-agent-team/src/index.ts`](../packages/exper ### `send_message` -Send one durable message to another Team member. A running target receives it at the nearest step boundary; an inactive target starts or resumes a turn. +Send one message to another Team member. A running target receives it at the nearest step boundary; an inactive target starts or resumes a turn. ```json { @@ -2489,7 +2489,7 @@ Source: [`packages/experimental/tool-agent-team/src/index.ts`](../packages/exper ### `wait_agent` -Wait for the next teammate status, mailbox, or shared-task change after this call starts. This never wakes inactive members and returns noProgress immediately when no other member is running or provisioning. Re-list after wakeup or timeout instead of polling. +Wait for the next teammate status, message, or shared-task change after this call starts. This never wakes inactive members and returns noProgress immediately when no other member is running or provisioning. Re-list after wakeup or timeout instead of polling. ```json { diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index 23ef011dc5..f7ed4a8c08 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -44,7 +44,7 @@ | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`、`subagent` | `ctx.tools`、`ctx.subagents`、`ctx.systemPrompt`、`用于模型发现和所选路由校验的 ctx.llm` | `tool/call`、`tool/result`、`child session events through the chosen provider` | `subagent`、`subagent_fork` | 注册的委派工具名称取决于加载时 `toolName` 配置(默认为 `subagent`);上述默认 schema 关闭模型选择,而发现 schema 则展示为已启用 Session 中可用的固定配套工具。Web preset 会在每个新顶层 Session 创建时读取插件页偏好,并为其子 Session 保留该决定;`subagent_fork` 始终使用固定路由。每个实例通过 `provider` 选择后端,通过 `modelSelectionSettings` 读取模型选择设置。每次委派都会立即返回子代理 id;本地子代理接受后续消息,外部后端自动汇报单次执行结果。 | | `@deepseek-ai/dsh-tool-subagent-control` | `interrupt_agent`、`list_agents`、`send_message` | `ctx.tools`、`ctx.subagents`、`ctx.agents and ctx.sessionProjections (list_agents only)` | `tool/call`、`tool/result`、`child session events through ctx.subagents` | - | 这些是用于发现、中断托管 subagent 和向本地子代理发送消息的全局命名工具:绑定提供方的 `tool-subagent` 实例注册不同的委派工具;本包注册一次 `send_message` 和 `interrupt_agent`,另由 `list_agents` 通过单独加载的 `/list-agents` 插件提供,其目录行使用 sessionProjections 和实时 Agent 注册表。 | | `@deepseek-ai/dsh-tool-jobs` | `job_kill`、`job_list`、`job_output` | `ctx.tools`、`ctx.jobs`、`ctx.systemPrompt` | `tool/call`、`tool/result`、`user/message via agent.inject() for background completion notices` | - | 与任务种类无关的后台任务控制器:后台 bash 命令与 PTY 发送 都通过相同的 3 个工具读取、列出和终止。加载该插件会挂接控制器,从而启用生产方的 `ctx.jobs.start()`。 | -| `@deepseek-ai/dsh-experimental-tool-agent-team` | `interrupt_agent`、`list_agents`、`send_message`、`spawn_teammate`、`team_task_create`、`team_task_get`、`team_task_list`、`team_task_update`、`wait_agent` | `ctx.tools`、`ctx.systemPrompt`、`ctx.agentTeams`、`an exact live Team member Agent` | `tool/call`、`team/member`、`team/message/queued`、`team/message/delivered`、`team/task`、`tool/result` | - | 这 9 个工具限定于隐式 Team Lead 与持久 teammate 作用域。随产品发布的 dsh-base bundle 默认禁用该包;文档中的 Agent Teams profile patch 会启用它,并禁用旧 continuable child 的同名控制工具。 | +| `@deepseek-ai/dsh-experimental-tool-agent-team` | `interrupt_agent`、`list_agents`、`send_message`、`spawn_teammate`、`team_task_create`、`team_task_get`、`team_task_list`、`team_task_update`、`wait_agent` | `ctx.tools`、`ctx.systemPrompt`、`ctx.agentTeams`、`an exact live Team member Agent` | `tool/call`、`team/member`、`team/task`、`agent/inbox/spliced`、`user/message on inbox claim`、`tool/result` | - | 这 9 个工具限定于隐式 Team Lead 与持久 teammate 作用域。随产品发布的 dsh-base bundle 默认禁用该包;文档中的 Agent Teams profile patch 会启用它,并禁用旧 continuable child 的同名控制工具。 | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`、`owning Agent session` | `tool/call`、`todo/write`、`tool/result` | - | todo_write 是会话所有的状态;UI 将最新的 todo/write 事件渲染为检查清单。`allowParallelInProgress` 是没有默认值的必填项,因此本目录明确选择 `true`,对应描述允许同时存在多个 `in_progress` 项。选择 `false` 的部署会获得同一工具,但描述会要求只能有 1 个活动任务。 | | `@deepseek-ai/dsh-tool-working-directory` | `working_directory` | `ctx.tools`, `ctx.workingDirectory` | `tool/call`, `working-directory/change`, `user context for directory changes`, `tool/result` | - | 读取或改变调用方 Session 的目录。已有 shell 和进程保留自己的目录;原始元数据和权限根目录保持不变。 | | `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `working-directory/change`, `tool/result` | - | 仅通过显式实验组合加载。在现有写权限下从固定的本地提交创建新分支与检出目录,再改变 Session 工作目录。离开时保留分支与检出目录。 | @@ -58,7 +58,7 @@ ### `plugin_manager` -列出当前 profile 中的插件或组合包,启用或禁用它们,安装组合包或移除已安装的组合包。每项操作都要求 danger-full-access 权限或本次调用的批准。批准不改变会话权限模式。变更影响该 profile 的所有会话。先列出条目以获取准确标识。包安装可能运行已获批准的构建脚本。支持热更新的 profile 立即应用变更;仅启动时加载的 profile 需要重启。不兼容的 DSH peer 依赖会阻止安装和激活。版本豁免可能导致崩溃和数据丢失:授权前必须警告用户,并获得用户对精确插件版本与运行时版本组合的明确许可。 +列出当前 profile 中的插件或组合包,启用或禁用它们,安装组合包或移除已安装的组合包。每项操作都要求 danger-full-access 权限或本次调用的批准。批准不改变会话权限模式。变更影响该 profile 的所有会话。先列出条目以获取准确标识。包安装可能运行已获批准的构建脚本。支持热更新的 profile 立即应用变更,包括已安装包的升级;未直接应用的变更结果带有 nextStep,说明下一步要做什么或告诉用户什么。不兼容的 DSH peer 依赖会阻止安装和激活。版本豁免可能导致崩溃和数据丢失:授权前必须警告用户,并获得用户对精确插件版本与运行时版本组合的明确许可。 ```json { @@ -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", @@ -1403,7 +1403,7 @@ create、edit、pause 和 resume 要求直接来自人类的根权限;complete }, "title": { "type": "string", - "description": "Task name of at most 120 characters, shown on the task card and in task lists." + "description": "Concise task name in the user's language, at most 120 characters. Name only the core action and subject; keep essential target identifiers such as PR numbers and branch names. Do not include execution frequency (e.g. daily, hourly), scheduled dates/times, time zones, task status, or configuration and execution details (e.g. read-only mode, profile-tag filters), even when embedded in the requested or existing title. Do not append parenthetical notes. Put scheduling information in the timing parameters and execution instructions in prompt." }, "after_seconds": { "type": "number", @@ -1564,7 +1564,7 @@ create、edit、pause 和 resume 要求直接来自人类的根权限;complete }, "title": { "type": "string", - "description": "New task name of at most 120 characters." + "description": "New task name; follow the schedule_create title rules." }, "prompt": { "type": "string", @@ -2263,7 +2263,7 @@ lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后, ### `send_message` -向另一名 Team member 发送一条持久消息。running target 会在最近的步骤边界收到消息;inactive target 会启动或恢复一个 turn。 +向另一名 Team member 发送一条消息。running target 会在最近的步骤边界收到消息;inactive target 会启动或恢复一个 turn。 ```json { @@ -2495,7 +2495,7 @@ lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后, ### `wait_agent` -等待本次调用开始后下一次 teammate 状态、mailbox 或共享任务变更。它绝不会唤醒 inactive member;若没有其他 member 正在 running 或 provisioning,则立即返回 noProgress。唤醒或超时后应重新列出状态,而不是轮询。 +等待本次调用开始后下一次 teammate 状态、消息或共享任务变更。它绝不会唤醒 inactive member;若没有其他 member 正在 running 或 provisioning,则立即返回 noProgress。唤醒或超时后应重新列出状态,而不是轮询。 ```json { 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/bundled-python-tests/guide.i18n.yaml b/docs/upgrade-guide/v0.2.0-rc.2/bundled-python-tests/guide.i18n.yaml new file mode 100644 index 0000000000..5d121913f3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.0-rc.2/bundled-python-tests/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/bundled-python-tests/guide.md +/: + en: 985656162a55b14a + zh: c32bda15938879e5 +/numpy-and-pandas-upstream-tests-require-a-separate-environment: + en: ec0ae29022f8ce8c + zh: f5e49682b842544d +/numpy-and-pandas-upstream-tests-require-a-separate-environment/change: + en: 41410ee875be7975 + zh: b052e7b3c8fb096b +/numpy-and-pandas-upstream-tests-require-a-separate-environment/migration: + en: 00c4b10f8df805e7 + zh: 06ef0fbda56c9acf diff --git a/docs/upgrade-guide/v0.2.0-rc.2/bundled-python-tests/guide.md b/docs/upgrade-guide/v0.2.0-rc.2/bundled-python-tests/guide.md new file mode 100644 index 0000000000..0c3978d20b --- /dev/null +++ b/docs/upgrade-guide/v0.2.0-rc.2/bundled-python-tests/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "Bundled NumPy and pandas omit their upstream test suites." +--- + +# NumPy and pandas upstream tests require a separate environment + +English | [中文](guide.zh.md) + +## Change + +Desktop and Python SDK runtime distributions previously included NumPy and pandas test directories. Bundled distributions now omit those directories, so scripts importing their test modules or running their complete upstream suites need a separate installation. Data processing, Office authoring, `numpy.testing`, `pandas.testing`, and `pandas._testing` remain available. + +## Migration + +1. If your scripts import `numpy.*.tests` or `pandas.tests`, install the original NumPy and pandas distributions and their upstream testing dependencies in a separate Python environment. Keep that environment outside the managed Harness runtime directory, which upgrades replace. +2. Run the affected scripts or upstream suites with that environment's interpreter. Scripts that use only library functionality or retained testing helpers require no changes. +3. Confirm that the previously failing test-module imports and affected scripts succeed with the separate interpreter. The bundled versions are recorded in the [runtime lock](../../../../scripts/primary-runtime/lock.json). diff --git a/docs/upgrade-guide/v0.2.0-rc.2/bundled-python-tests/guide.zh.md b/docs/upgrade-guide/v0.2.0-rc.2/bundled-python-tests/guide.zh.md new file mode 100644 index 0000000000..9e36c71dc6 --- /dev/null +++ b/docs/upgrade-guide/v0.2.0-rc.2/bundled-python-tests/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "内置 NumPy 和 pandas 不包含其上游测试套件。" +--- + +# NumPy 和 pandas 上游测试需要独立环境 + +[English](guide.md) | 中文 + +## 变更 + +Desktop 和 Python SDK 运行时分发包此前包含 NumPy 和 pandas 测试目录。内置分发包现在裁剪这些目录,因此导入其测试模块或运行其完整上游测试套件的脚本需要独立安装环境。数据处理、Office 创作、`numpy.testing`、`pandas.testing` 和 `pandas._testing` 仍然可用。 + +## 迁移 + +1. 如果脚本导入 `numpy.*.tests` 或 `pandas.tests`,请在独立 Python 环境中安装原始 NumPy 和 pandas 分发包及其上游测试依赖。请将该环境放在 Harness 托管运行时目录之外,升级会替换托管目录。 +2. 使用该环境的解释器运行受影响的脚本或上游测试套件。仅使用库功能或保留的 testing 辅助 API 的脚本无需修改。 +3. 确认先前失败的测试模块导入及相关脚本均可在独立解释器中成功运行。随包版本记录在[运行时锁文件](../../../../scripts/primary-runtime/lock.json)中。 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/upgrade-guide/v0.2.1-alpha.1/deepseek-model-discovery/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/deepseek-model-discovery/guide.i18n.yaml new file mode 100644 index 0000000000..8e8646abe0 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/deepseek-model-discovery/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.1-alpha.1/deepseek-model-discovery/guide.md +/: + en: 059ab5482d52d8b8 + zh: 006b65489bc4ec70 +/deepseek-api-key-model-visibility: + en: 7b14dc7133967bfd + zh: 4f338ae1e8151feb +/deepseek-api-key-model-visibility/change: + en: ab0b141fbb3167ab + zh: 918f4202223abe44 +/deepseek-api-key-model-visibility/migration: + en: 2fda36f7e543f1d0 + zh: e8522f256de5adaa diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/deepseek-model-discovery/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/deepseek-model-discovery/guide.md new file mode 100644 index 0000000000..a5fa635ccd --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/deepseek-model-discovery/guide.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "DeepSeek API-key model discovery requires a configured credential." +--- + +# DeepSeek API-key model visibility + +English | [中文](guide.zh.md) + +## Change + +The `deepseek-official` route previously listed its configured models without an API key. It now returns an empty catalog when its credential is missing, so Desktop and Web hide the DeepSeek group. Model discovery reports malformed credentials and credential lookup failures. A saved or default selection absent from the catalog displays “Select model” without changing the stored selection. The independent DeepSeek account route still uses account login. + +## Migration + +1. To use the API-key route, configure its key in Settings → Models or supply the reference named by `apiKeyEnv` (default `DEEPSEEK_API_KEY`) through the launch environment. +2. Reopen the model selector and confirm the DeepSeek group appears. Custom discovery consumers must handle an empty catalog before credentials are configured; listing models does not verify that the remote API accepts the key. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/deepseek-model-discovery/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/deepseek-model-discovery/guide.zh.md new file mode 100644 index 0000000000..46ff3452ff --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/deepseek-model-discovery/guide.zh.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "DeepSeek API Key 模型发现要求已配置凭据。" +--- + +# DeepSeek API Key 模型可见性 + +[English](guide.md) | 中文 + +## 变更 + +`deepseek-official` 路由此前在没有 API Key 时也会列出配置的模型。现在凭据缺失时返回空目录,因此桌面端和 Web 隐藏 DeepSeek 分组。模型发现会报告凭据格式错误和凭据读取失败。已保存或默认的选择不在目录中时,界面显示“请选择模型”,保存的选择保持不变。独立的 DeepSeek 账号路由仍使用账号登录。 + +## 迁移 + +1. 要使用 API Key 路由,请在设置 → 模型中配置密钥,或通过启动环境提供 `apiKeyEnv` 指定的凭据引用(默认为 `DEEPSEEK_API_KEY`)。 +2. 重新打开模型选择器,确认 DeepSeek 分组出现。自定义模型发现消费者必须处理配置凭据前的空目录;模型列出不代表远端 API 已接受密钥。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/desktop-test-auth-popup/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/desktop-test-auth-popup/guide.i18n.yaml new file mode 100644 index 0000000000..e7568e9555 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/desktop-test-auth-popup/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.1-alpha.1/desktop-test-auth-popup/guide.md +/: + en: 97a3763818ba118c + zh: ba856458827cb637 +/enable-test-update-policy-authentication-dialogs-locally: + en: 33515a78d8b30d7a + zh: 6f821057b75e319e +/enable-test-update-policy-authentication-dialogs-locally/change: + en: 21d23ef8d1d3599c + zh: 389633b096767f73 +/enable-test-update-policy-authentication-dialogs-locally/migration: + en: e6b3bc48daaa13b1 + zh: df50a981844d3de6 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/desktop-test-auth-popup/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/desktop-test-auth-popup/guide.md new file mode 100644 index 0000000000..4a70b5f34f --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/desktop-test-auth-popup/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "Desktop test builds require local opt-in before showing any Feishu update-policy authentication dialogs." +--- + +# Enable test update-policy authentication dialogs locally + +English | [中文](guide.zh.md) + +## Change + +Test builds previously offered Feishu login after an unauthenticated startup or manual update-policy check. All test authentication dialogs now default to disabled, including manual checks and mandatory-update refreshes. Test gateway cookies do not survive restart. With login disabled, a gateway requiring authentication cannot provide new mandatory-update decisions; enable the setting, restart and sign in to obtain them. Authentication failures retain any mandatory block already known in the same process; production policy requests and product account login are unchanged. + +## Migration + +1. Launch the updated application once to create `app.getPath('userData')/desktop/settings.json` if missing. Existing files are retained, and a missing field defaults to `false`. See [local desktop settings](../../../../apps/desktop/README.md#local-desktop-settings) for platform paths and error recovery. +2. To permit Feishu login, set `updates.allowTestAuthPopupWindow` to `true` in that file, then fully quit and restart Desktop. An unauthenticated test-policy response can now offer login. Leave the default unchanged if no login dialogs are wanted. +3. To disable dialogs again, set the field to `false` and restart. Startup and manual checks must not show Feishu authentication dialogs. Updates still query policy, and authentication failures do not clear a known mandatory block. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/desktop-test-auth-popup/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/desktop-test-auth-popup/guide.zh.md new file mode 100644 index 0000000000..2e803cee31 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/desktop-test-auth-popup/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "桌面测试包需要在本地显式开启后,才能显示飞书更新策略鉴权弹窗。" +--- + +# 在本地开启测试更新策略鉴权弹窗 + +[English](guide.md) | 中文 + +## 变更 + +测试包此前会在启动或手动检查更新策略未通过鉴权后提供飞书登录入口。现在所有测试鉴权弹窗默认关闭,包括手动检查和强更刷新。测试网关 Cookie 不跨重启保存。禁止登录时,需要鉴权的网关无法提供新的强更决策;需开启设置、重启并登录后才能获取。鉴权失败仍保留同一进程中已知的强更阻塞;正式环境策略请求和产品账号登录保持不变。 + +## 迁移 + +1. 启动更新后的应用一次,在 `app.getPath('userData')/desktop/settings.json` 缺失时生成该文件。已有文件会保留,字段缺失时默认为 `false`。平台路径和错误恢复方法见[本地桌面设置](../../../../apps/desktop/README.zh.md#local-desktop-settings)。 +2. 如需允许飞书登录,在文件中将 `updates.allowTestAuthPopupWindow` 设为 `true`,然后完全退出并重启 Desktop。此时测试策略的未鉴权响应可以提供登录入口。不需要登录弹窗时保持默认值即可。 +3. 如需再次关闭弹窗,将字段设为 `false` 并重启。启动和手动检查均不得显示飞书鉴权弹窗。更新仍会查询策略,鉴权失败不会解除已知强更阻塞。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/job-id-identity/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/job-id-identity/guide.i18n.yaml new file mode 100644 index 0000000000..6e120f29bd --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/job-id-identity/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.1-alpha.1/job-id-identity/guide.md +/: + en: d6fdce6b58c67691 + zh: a103e5028f5442d0 +/background-job-ids-identify-one-execution: + en: 9b06780be69e93f6 + zh: c33945fd584c6a23 +/background-job-ids-identify-one-execution/change: + en: 047ec9d0337bfc0b + zh: 1218472855e81189 +/background-job-ids-identify-one-execution/migration: + en: 08921c9c25218c83 + zh: 7ff1d3ac63ae40ef diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/job-id-identity/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/job-id-identity/guide.md new file mode 100644 index 0000000000..16ded54d20 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/job-id-identity/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "JobId now identifies one background execution across registry lifetimes." +--- + +# Background job ids identify one execution + +English | [中文](guide.zh.md) + +## Change + +The job registry returns `-` instead of `-N`; the suffix is 16 lowercase UUID hex characters. The same `JobId` appears in live controls, `job/registered`, and `job/settled`; lifecycle records no longer carry `executionId`. The identifier remains owner-authorized. Existing Session histories remain unchanged and do not resume their jobs. + +## Migration + +1. Pass the exact id returned by a start result or `jobs.list()` to `job_output` and `job_kill`; use `job_output` with `wait: true` to wait. Remove code that constructs an id from the kind and an ordinal. +2. Pair SDK lifecycle events by `data.jobId`. Remove imports of `JobExecutionId` and code that maps it to a process-local `jobId`. +3. Verify a new job's registration and settlement contain the same `jobId`, and a later registry instance issues a different one. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/job-id-identity/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/job-id-identity/guide.zh.md new file mode 100644 index 0000000000..372a3b6c9f --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/job-id-identity/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "JobId 现在跨注册表生命周期标识一次后台执行。" +--- + +# 后台 job id 标识一次执行 + +[English](guide.md) | 中文 + +## 变更 + +job 注册表返回 `-`,不再返回 `-N`;后缀是 UUID 的 16 位小写十六进制字符。运行期控制、`job/registered` 和 `job/settled` 使用同一个 `JobId`;生命周期记录不再携带 `executionId`。访问仍按所有者授权。已有 Session 历史保持原样,不会恢复其中的 job。 + +## 迁移 + +1. 把启动结果或 `jobs.list()` 返回的原始 id 传给 `job_output` 和 `job_kill`;等待时为 `job_output` 设置 `wait: true`。移除按 kind 和序号构造 id 的代码。 +2. 使用 `data.jobId` 配对 SDK 生命周期事件。移除 `JobExecutionId` 导入,以及将它映射为进程内 `jobId` 的代码。 +3. 核对新 job 的注册与结算含有相同 `jobId`,后续注册表实例发放不同 id。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/jsonl-persistence-plugin/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/jsonl-persistence-plugin/guide.i18n.yaml new file mode 100644 index 0000000000..57d0ff470e --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/jsonl-persistence-plugin/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.1-alpha.1/jsonl-persistence-plugin/guide.md +/: + en: eff30513d0de970b + zh: c16a32f374bd07e1 +/mount-jsonl-persistence-through-its-plugin: + en: ae3ff407a497cf5c + zh: 1b71e651967b8255 +/mount-jsonl-persistence-through-its-plugin/change: + en: ea5defddc1a9b989 + zh: 97902f22a4196b12 +/mount-jsonl-persistence-through-its-plugin/migration: + en: 93d9f202c59303e9 + zh: c5ced26ed819d7c5 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/jsonl-persistence-plugin/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/jsonl-persistence-plugin/guide.md new file mode 100644 index 0000000000..a05bdef3eb --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/jsonl-persistence-plugin/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "JSONL persistence uses a namespace plugin import; direct service-class construction and class type annotations must use the persistence service instead." +--- + +# Mount JSONL persistence through its plugin + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/dsh-session-persistence-jsonl` exports a function plugin through named `name`, `Config`, and `apply` exports, with no default export. Default imports, direct construction, subclassing, `instanceof`, and class type annotations are affected. The plugin retains listeners and handles through the consumer unloads triggered by removing this provider; concurrent root disposal remains unordered. The `sessionPersistence` service API, YAML configuration, and stored files remain unchanged. + +## Migration + +1. Replace the default import with `import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'`. Existing `ctx.plugin(JsonlSessionPersistence, config)` calls remain valid; replace direct construction with this mounting call. For dynamic imports, use the module namespace returned by `await import(...)` instead of its `.default`. Consumers declare `inject: ['sessionPersistence']` and access `ctx.sessionPersistence`. +2. Use the `SessionPersistence` type from `@deepseek-ai/dsh-session-persistence` for service annotations. Replace concrete-class `instanceof` checks and subclasses with consumers of that service; the concrete JSONL class is private. +3. Await plugin startup and confirm a session can be created, flushed, and reopened. Register asynchronous consumer cleanup in the scope that injects `sessionPersistence` so backend unloading waits for it. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/jsonl-persistence-plugin/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/jsonl-persistence-plugin/guide.zh.md new file mode 100644 index 0000000000..0cf8323713 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/jsonl-persistence-plugin/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "JSONL 持久化使用插件命名空间导入;直接构造服务类和类类型标注需要改用持久化服务。" +--- + +# 通过插件挂载 JSONL 持久化 + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-session-persistence-jsonl` 通过命名导出的 `name`、`Config` 和 `apply` 提供函数插件,没有默认导出。默认导入、直接构造、继承、`instanceof` 和类类型标注会受到影响。插件会保留监听器和句柄,直到移除该提供者所触发的消费者卸载完成;根作用域的并发卸载仍不保证顺序。`sessionPersistence` 服务 API、YAML 配置和存储文件保持不变。 + +## 迁移 + +1. 将默认导入替换为 `import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'`。现有的 `ctx.plugin(JsonlSessionPersistence, config)` 调用仍然有效;将直接构造改为该挂载调用。动态导入直接使用 `await import(...)` 返回的模块命名空间,不再取其 `.default`。消费者声明 `inject: ['sessionPersistence']` 并访问 `ctx.sessionPersistence`。 +2. 服务类型标注使用 `@deepseek-ai/dsh-session-persistence` 的 `SessionPersistence` 类型。将针对具体类的 `instanceof` 检查和子类改为消费该服务;具体 JSONL 类是私有的。 +3. 等待插件启动完成,确认能够创建、flush 并重新打开会话。将消费者的异步清理注册到注入 `sessionPersistence` 的作用域中,以便后端卸载时等待它完成。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.i18n.yaml index 870c91d93d..6a374bc79d 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.md /: - en: a77928d6130fe601 - zh: da46d612268c3ced -/native-subagent-bundles-include-preset-tools: - en: b5c79b41fc34574a - zh: d784adcf343b0817 -/native-subagent-bundles-include-preset-tools/change: - en: 7d4af3e4ab91ef72 - zh: 837377c96d5eee12 -/native-subagent-bundles-include-preset-tools/migration: - en: 3257a5d18d07cada - zh: b663a7ae020bbfee + en: 4e1c7b1bfb2ba5ca + zh: c3f5ac60d10a215f +/native-subagent-bundles-include-global-tools: + en: 8f785a4b502f1f78 + zh: 527952686410adba +/native-subagent-bundles-include-global-tools/change: + en: 3432d6ba2ccf6492 + zh: 41cdf90f9d5b330d +/native-subagent-bundles-include-global-tools/migration: + en: 304dc5243b2f8159 + zh: 38cd9aa136dc8009 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.md index 5a08637440..830ee3b60b 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.md +++ b/docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.md @@ -1,32 +1,31 @@ --- kind: upgrade-guide -description: "Claude Code and Codex bundles add delegation tools to full Web presets while retaining their package and row identities." +description: "Claude Code and Codex bundles add global delegation tools while retaining their package and row identities." --- -# Native subagent bundles include preset tools +# Native subagent bundles include global tools English | [中文](guide.zh.md) ## Change -`@deepseek-ai/dsh-subagent-claude-code` and `@deepseek-ai/dsh-subagent-codex` keep their package names, bundle selections, provider row IDs, configuration, and native authentication. In Web and Desktop, a selected bundle now adds enabled delegation tools to `preset-standard`, `preset-cordis`, and `preset-ptc`; previously the bundle registered only its provider. Existing Agents retain their composition; new Agents and subsequently reopened Sessions receive the selected tools. +`@deepseek-ai/dsh-subagent-claude-code` and `@deepseek-ai/dsh-subagent-codex` keep their package names, bundle selections, provider row IDs, configuration, and native authentication. A selected bundle now also registers its delegation tool as a Host global tool, visible to every preset including minimal; previously the bundle registered only its provider. Live Agents see the tool from their next request after the bundle is enabled, and lose it after the bundle is switched off. -The contributed rows retain `tool-subagent-claude-code` and `tool-subagent-codex`. Later user layers can override their configuration or disabled state, and a complete preset configuration replacement keeps its own child list. An override does not select an unselected bundle. Duplicate declarations of the same model-facing tool still fail. +The contributed Host rows are `tool-subagent-claude-code` and `tool-subagent-codex`. Later user layers can override their configuration or disabled state by row id. An override does not select an unselected bundle. A preset that registers its own tool with the same name shadows the global tool for its Agents. Delegation follows the shared managed-activation API: the tool returns a child ID, and completion arrives as a logged notice to the parent Agent. Remove obsolete `backgroundMode` settings; `maxDepth: provider-managed` remains supported for these native providers. ## Migration 1. Preserve selected bundle names, provider configuration, and authentication. Existing provider-only packages need **Update** in Plugins → Official to receive the tool-contributing bundle; restart when requested. To adopt a new provider, enable its card. [Installation targets](../../../../packages/boot/plugin-manager/README.md#use-this-package) follow the published DSH version or source checkout; equal version strings do not make an older registry package equivalent to a development link. Off only deselects; Remove remains separate. -2. Configure the familiar tool row ID with a scoped patch. Configuration overrides still replace the complete configuration. For example, this keeps Codex disabled in standard while other full presets use their selected composition: +2. Configure the tool with an ordinary row patch. Configuration overrides still replace the complete configuration. For example, this keeps the Codex tool disabled while the provider stays registered: ```yaml - - preset: preset-standard - id: tool-subagent-codex + - id: tool-subagent-codex disabled: true ``` -3. If an additional manual row registers the same tool in a preset, remove that redundant row or disable the bundle's contribution explicitly. A copied complete preset can retain its existing tool declarations and disabled state. Verify the effective tool catalog in a new Session; minimal keeps its current shell and working-directory tools. +3. If a manual Host row registers the same tool name, remove that redundant row or disable the bundle's row. Verify the effective tool catalog in a Session. 4. Plugin clients receive required `BundleInfo.official` and `BundleInfo.availability` fields; detail-slot `PluginPackageRef` receives them too. `official` identifies project maintenance, `availability` reports `installation`, `profile`, or `missing`, and `installed` still means a profile dependency declaration. Detail-slot readers that only display existing fields need no changes; constructors and exact validators must include the new fields. Optional `installTarget` identifies the offered version and registry or local-link spec. -**Other profiles.** Headless, SDK, ACP, and custom profiles without the three full preset targets are outside this compatibility scope. Selecting these bundle layers fails for missing preset targets and can retain the saved selection; there is no automatic rollback. Such profiles can keep the installed provider package without selecting its bundle and explicitly compose provider/tool rows using the [Codex](../../../../packages/subagent/subagent-codex/README.md#exposing-the-tool) or [Claude Code](../../../../packages/subagent/subagent-claude-code/README.md#exposing-the-tool) example. +**Other profiles.** The bundle layers insert Host rows only, so headless, SDK, ACP, and custom profiles can select them as well. Profiles that keep the provider package without selecting its bundle can compose the same rows using the [Codex](../../../../packages/subagent/subagent-codex/README.md#exposing-the-tool) or [Claude Code](../../../../packages/subagent/subagent-claude-code/README.md#exposing-the-tool) example. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.zh.md index e98a34f503..76c130bab3 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-alpha.1/native-subagent-bundle-tools/guide.zh.md @@ -1,32 +1,31 @@ --- kind: upgrade-guide -description: "Claude Code 与 Codex bundle 为完整 Web 预设添加委派工具,同时保留包名和行标识。" +description: "Claude Code 与 Codex bundle 添加全局委派工具,同时保留包名和行标识。" --- -# 原生子代理 bundle 包含预设工具 +# 原生子代理 bundle 包含全局工具 [English](guide.md) | 中文 ## 变更 -`@deepseek-ai/dsh-subagent-claude-code` 和 `@deepseek-ai/dsh-subagent-codex` 保留包名、bundle 选择、提供方行 ID、配置及原生认证。在 Web 和 Desktop 中,已选中的 bundle 现在会为 `preset-standard`、`preset-cordis` 和 `preset-ptc` 添加启用的委派工具;此前 bundle 只注册提供方。已有 Agent 保留其组合;新 Agent 和之后重新打开的 Session 使用选中的工具。 +`@deepseek-ai/dsh-subagent-claude-code` 和 `@deepseek-ai/dsh-subagent-codex` 保留包名、bundle 选择、提供方行 ID、配置及原生认证。已选中的 bundle 现在还会把委派工具注册为 Host 全局工具,包括 minimal 在内的所有预设都可见;此前 bundle 只注册提供方。启用 bundle 后,运行中的 Agent 从下一次请求起即可看到该工具;关闭后则不再可见。 -贡献行保留 `tool-subagent-claude-code` 和 `tool-subagent-codex`。后续用户层可以覆盖其配置或禁用状态,完整的预设配置替换保留自己的子列表。覆盖不会选中未选中的 bundle。重复声明同一个面向模型的工具仍会失败。 +贡献的 Host 行为 `tool-subagent-claude-code` 和 `tool-subagent-codex`。后续用户层可以按行 ID 覆盖其配置或禁用状态。覆盖不会选中未选中的 bundle。预设自行注册的同名工具会为其 Agent 遮蔽该全局工具。 委派遵循共享的托管 activation API:工具返回子级 ID,完成结果通过已记录的通知发送给父 Agent。移除已废弃的 `backgroundMode` 设置;这些原生提供方仍支持 `maxDepth: provider-managed`。 ## 迁移 1. 保留已选中的 bundle 名称、提供方配置和认证。已有仅提供方的包需要在插件 → 官方中**更新**才能获得贡献工具的 bundle;按提示重启。要使用新的提供方,启用其卡片。[安装目标](../../../../packages/boot/plugin-manager/README.zh.md#use-this-package)对应已发布的 DSH 版本或源码 checkout;版本字符串相同不代表旧注册表包等同于开发链接。关闭只取消选择;删除仍为独立操作。 -2. 使用作用域补丁配置熟悉的工具行 ID。配置覆盖仍会替换整份配置。例如,以下补丁在 standard 中保持 Codex 禁用,其他完整预设则使用其选中的组合: +2. 使用普通行补丁配置该工具。配置覆盖仍会替换整份配置。例如,以下补丁在保留提供方注册的同时禁用 Codex 工具: ```yaml - - preset: preset-standard - id: tool-subagent-codex + - id: tool-subagent-codex disabled: true ``` -3. 如果额外的手动行在预设中注册了同一个工具,移除该重复行,或显式禁用 bundle 的贡献行。复制的完整预设可以保留其现有工具声明和禁用状态。在新 Session 中验证有效工具目录;minimal 保留当前的 shell 和工作目录工具。 +3. 如果手动的 Host 行注册了同名工具,移除该重复行,或禁用 bundle 的贡献行。在 Session 中验证有效工具目录。 4. 插件客户端收到必填的 `BundleInfo.official` 和 `BundleInfo.availability` 字段;详情 slot 的 `PluginPackageRef` 也会收到它们。`official` 标识项目维护,`availability` 表示 `installation`、`profile` 或 `missing`,`installed` 仍表示 profile 的依赖声明。只展示已有字段的详情 slot 读取方无需修改;构造方和精确校验器必须包含新增字段。可选的 `installTarget` 标识所提供的版本及注册表或本地链接 spec。 -**其他 profile。** Headless、SDK、ACP 和缺少三个完整预设目标的自定义 profile 不在此次兼容范围内。选择这些 bundle 层会因缺少预设目标而失败,并可能保留已保存的选择;没有自动回滚。这些 profile 可以保留已安装的提供方包而不选择其 bundle,并参考 [Codex](../../../../packages/subagent/subagent-codex/README.zh.md#exposing-the-tool) 或 [Claude Code](../../../../packages/subagent/subagent-claude-code/README.zh.md#exposing-the-tool) 示例显式组合提供方和工具行。 +**其他 profile。** 这些 bundle 层只插入 Host 行,因此 headless、SDK、ACP 和自定义 profile 也可以选择它们。保留提供方包而不选择其 bundle 的 profile,可以参考 [Codex](../../../../packages/subagent/subagent-codex/README.zh.md#exposing-the-tool) 或 [Claude Code](../../../../packages/subagent/subagent-claude-code/README.zh.md#exposing-the-tool) 示例组合相同的行。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/new-session-generations/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/new-session-generations/guide.i18n.yaml index 01ecc3a8b0..a7b23a204d 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.1/new-session-generations/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-alpha.1/new-session-generations/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 5e4b26181326018f zh: 99bc75dcd12bf647 /start-a-fresh-agent-with-new-session/change: - en: ab12aadb31d0d3e8 - zh: 637b446aef86456e + en: 45a6960304768d90 + zh: 4b105688ffdd36e1 /start-a-fresh-agent-with-new-session/migration: - en: 9565e66b6bcdf269 - zh: 226e470de85aa8b6 + en: 4642b2a1aee12fb3 + zh: 53ae60e9d612ab6b diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/new-session-generations/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/new-session-generations/guide.md index bc735fe299..2c699ccfa2 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.1/new-session-generations/guide.md +++ b/docs/upgrade-guide/v0.2.1-alpha.1/new-session-generations/guide.md @@ -9,12 +9,12 @@ English | [中文](guide.zh.md) ## Change -In Web and Desktop, New Session creates a fresh Session and Agent using the current preset definition. It previously reused an existing empty Session in the workspace, which could retain tools from before an optional bundle changed. +In Web and Desktop, New Session creates a fresh Session and Agent using the current preset definition. It previously reused an existing empty Session in the workspace, which could retain an earlier preset definition. -Client calls to `uiWorkspace.startSession(workspaceId)` follow the same behavior. Workspace reconnection through `openWorkspace` or `connectWorkspace` still reuses an eligible blank. Calls with draft-preparation options preserve their existing reuse and content rules. Existing Agents retain their composition. +Client calls to `uiWorkspace.startSession(workspaceId)` follow the same behavior. Workspace reconnection through `openWorkspace` or `connectWorkspace` still reuses an eligible blank. Calls with draft-preparation options preserve their existing reuse and content rules. Existing Agents retain their preset composition; global optional tools update on their next request when a bundle is switched. ## Migration -1. After changing optional bundles, use New Session to obtain the current tool composition. Continue in an existing Session when its retained composition is intentional. +1. After changing a preset definition, use New Session to create an Agent with the current definition. Continue in an existing Session when its retained preset composition is intentional. 2. Client integrations that reconnect a workspace should use `openWorkspace` or `connectWorkspace`. Keep explicit draft-preparation options when preparing an existing draft. -3. Confirm that the new Agent has the selected tools; no persisted Session files or profile patches need rewriting. +3. Confirm that the new Agent uses the updated preset definition; no persisted Session files or profile patches need rewriting. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/new-session-generations/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/new-session-generations/guide.zh.md index b3371908a1..baf065ad9c 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.1/new-session-generations/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-alpha.1/new-session-generations/guide.zh.md @@ -9,12 +9,12 @@ description: "新会话会创建新的 Agent,不再复用已有空 Session。" ## 变更 -在 Web 和 Desktop 中,新会话按当前预设定义创建新的 Session 和 Agent。此前该操作会复用工作区内已有的空 Session,因而可能保留可选组合包变更前的工具。 +在 Web 和 Desktop 中,新会话按当前预设定义创建新的 Session 和 Agent。此前该操作会复用工作区内已有的空 Session,因而可能保留较早的预设定义。 -客户端调用 `uiWorkspace.startSession(workspaceId)` 采用相同行为。通过 `openWorkspace` 或 `connectWorkspace` 重连工作区时仍复用符合条件的空 Session。带草稿准备选项的调用保留已有复用与内容规则。已有 Agent 保留其组合。 +客户端调用 `uiWorkspace.startSession(workspaceId)` 采用相同行为。通过 `openWorkspace` 或 `connectWorkspace` 重连工作区时仍复用符合条件的空 Session。带草稿准备选项的调用保留已有复用与内容规则。已有 Agent 保留其预设组合;切换组合包后,全局可选工具会在其下一次请求时更新。 ## 迁移 -1. 更改可选组合包后,通过新会话取得当前工具组合。需要保留原组合时,继续使用已有 Session。 +1. 更改预设定义后,通过新会话创建使用当前定义的 Agent。需要保留原预设组合时,继续使用已有 Session。 2. 重连工作区的客户端集成应使用 `openWorkspace` 或 `connectWorkspace`。准备已有草稿时保留显式草稿准备选项。 -3. 确认新 Agent 拥有已选择的工具;无需重写持久化 Session 文件或 profile patch。 +3. 确认新 Agent 使用更新后的预设定义;无需重写持久化 Session 文件或 profile patch。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/preset-bundle-rows/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/preset-bundle-rows/guide.i18n.yaml deleted file mode 100644 index bf382c449c..0000000000 --- a/docs/upgrade-guide/v0.2.1-alpha.1/preset-bundle-rows/guide.i18n.yaml +++ /dev/null @@ -1,16 +0,0 @@ -# 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.1-alpha.1/preset-bundle-rows/guide.md -/: - en: 25de822f0f884eb9 - zh: c910706695f91c76 -/identify-bundle-rows-by-their-preset: - en: 95cdaba0de8fe664 - zh: f7382ff6b9f65a49 -/identify-bundle-rows-by-their-preset/change: - en: e43402c18f6b6de8 - zh: 32f3e46546e9d1f8 -/identify-bundle-rows-by-their-preset/migration: - en: 89cead6b9cd199bd - zh: 8a13a234d9feacbb diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/preset-bundle-rows/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/preset-bundle-rows/guide.md deleted file mode 100644 index 225cf96268..0000000000 --- a/docs/upgrade-guide/v0.2.1-alpha.1/preset-bundle-rows/guide.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -kind: upgrade-guide -description: "Plugin-manager bundle inventories include preset-scoped rows whose row IDs are unique only within their preset." ---- - -# Identify bundle rows by their preset - -English | [中文](guide.zh.md) - -## Change - -The next release adds preset-scoped declarations to `PluginManager.listBundles().rows`. A bundle can declare the same `rowId` in several presets. `PluginRowRef` values passed to detail slots carry the same optional `preset` identity. These rows carry `preset`, optional `composition` state, and `readOnlyReason: 'preset-managed'`; they do not carry an editable root `entryId`. - -Clients that key rows only by bundle name and `rowId`, or treat every row as a root plugin switch, must distinguish preset declarations. Existing root rows retain their current identity and controls. - -## Migration - -1. Include `preset` in row identity, alongside the bundle name and `rowId`. Keep the absent-preset case distinct from every named preset. -2. Render `preset-managed` rows read-only in direct row controls. Use the bundle switch or an explicit scoped profile patch to configure them. Only pass a returned root `entryId` to `setPluginEnabled`. -3. Read preset row state from `composition`, instead of looking up a root Loader entry with the same `rowId`. -4. For YAML edits, use `preset` to address the outer declaration and `id` to address its child: - - ```yaml - - preset: preset-standard - id: optional-tool-str-replace-editor - disabled: true - ``` - -5. Verify that a bundle contributing to standard, cordis, and ptc shows three distinct rows and that root-row switches continue to work. The [profile patch reference](../../../../packages/boot/app-boot/README.md) describes ordering and validation. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/preset-bundle-rows/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/preset-bundle-rows/guide.zh.md deleted file mode 100644 index d2800b9591..0000000000 --- a/docs/upgrade-guide/v0.2.1-alpha.1/preset-bundle-rows/guide.zh.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -kind: upgrade-guide -description: "插件管理器的组合包清单包含预设作用域行,其行 ID 仅在所属预设内唯一。" ---- - -# 按所属预设区分组合包行 - -[English](guide.md) | 中文 - -## 变更 - -下一个版本在 `PluginManager.listBundles().rows` 中加入预设作用域声明。一个组合包可以在多个预设中声明相同的 `rowId`。详情插槽中的 `PluginRowRef` 也携带可选的 `preset` 标识。这些行包含 `preset`、可选的 `composition` 状态和 `readOnlyReason: 'preset-managed'`,不包含可编辑的根级 `entryId`。 - -仅用组合包名和 `rowId` 作为行标识,或将所有行都视为根插件开关的客户端,必须区分预设声明。已有根行保留当前标识和控制方式。 - -## 迁移 - -1. 将 `preset` 与组合包名、`rowId` 一起纳入行标识。区分没有预设的情况与每个具名预设。 -2. 在直接行控制中只读展示 `preset-managed` 行。通过组合包开关或显式的预设作用域 profile patch 配置这些行。只将实际返回的根级 `entryId` 传给 `setPluginEnabled`。 -3. 从 `composition` 读取预设行状态,不要按同一个 `rowId` 查找根 Loader 条目。 -4. 编辑 YAML 时,用 `preset` 定位外层声明,用 `id` 定位其子行: - - ```yaml - - preset: preset-standard - id: optional-tool-str-replace-editor - disabled: true - ``` - -5. 确认同时向 standard、cordis 和 ptc 贡献行的组合包显示三个不同的行,且根行开关仍可使用。[Profile patch 参考](../../../../packages/boot/app-boot/README.zh.md)说明顺序与校验规则。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/python-optional-resources/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/python-optional-resources/guide.i18n.yaml new file mode 100644 index 0000000000..d7f903cbe4 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/python-optional-resources/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.1-alpha.1/python-optional-resources/guide.md +/: + en: d6baeff3354ba733 + zh: 54e736a9718228f8 +/download-optional-python-runtime-resources-explicitly: + en: b9a46f870d69cf79 + zh: 1ed1da9167fad3b1 +/download-optional-python-runtime-resources-explicitly/change: + en: 92d45d6f2a499e9b + zh: d4560da85fc5cfbf +/download-optional-python-runtime-resources-explicitly/migration: + en: 0f0b15be52301aed + zh: 646d7b47069714d4 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/python-optional-resources/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/python-optional-resources/guide.md new file mode 100644 index 0000000000..21c5a025e5 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/python-optional-resources/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "Python runtime wheels require explicit downloads for Office conversion and bundled authoring environments." +--- + +# Download optional Python runtime resources explicitly + +English | [中文](guide.zh.md) + +## Change + +Python runtime wheels omit the Office sidecar and authoring interpreters and libraries. SDK startup does not download them. Office operations require an explicit download; the authoring environment and conversion engine can be selected independently. The SDK still packages the normal `dsh` CLI and requires no system Node.js. + +## Migration + +1. Before processing Office files, call `deepseek_harness_runtime.download_office()`. Before using the bundled authoring environment, call `deepseek_harness_runtime.download_primary_runtime()`. Both reuse completed caches and return absolute paths. +2. For offline deployment, prepare the cache with the matching runtime release on the target platform and copy it to that platform's deployment. Set `DSH_RESOURCE_CACHE` to its absolute root before downloads and SDK startup. See the [runtime reference](../../../../python/sdk-runtime/README.md). +3. Start the SDK and confirm the required resources are available. `deepseek_harness_runtime.resolve_office_launch_args()` checks the Office CLI paths without downloading. Existing `DSH_PRIMARY_RUNTIME` paths remain supported; an empty value disables the authoring query. Profile patches can independently disable `skill-office`. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/python-optional-resources/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/python-optional-resources/guide.zh.md new file mode 100644 index 0000000000..9c804c6d34 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/python-optional-resources/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "Python 运行时 wheel 的 Office 转换与内置创作环境需要显式下载。" +--- + +# 显式下载可选 Python 运行时资源 + +[English](guide.md) | 中文 + +## 变更 + +Python 运行时 wheel 不包含 Office sidecar、创作解释器和库。SDK 启动不会下载这些资源。Office 操作需要显式下载;创作环境和转换引擎可以独立选择。SDK 仍打包常规 `dsh` CLI,无需系统 Node.js。 + +## 迁移 + +1. 处理 Office 文件前调用 `deepseek_harness_runtime.download_office()`。使用内置创作环境前调用 `deepseek_harness_runtime.download_primary_runtime()`。两者复用完整缓存并返回绝对路径。 +2. 离线部署时,在目标平台使用匹配的运行时发布版本准备缓存,并将其复制到该平台的部署环境。下载和启动 SDK 前,将 `DSH_RESOURCE_CACHE` 设为缓存的绝对根目录。详见[运行时参考](../../../../python/sdk-runtime/README.zh.md)。 +3. 启动 SDK 并确认所需资源可用。`deepseek_harness_runtime.resolve_office_launch_args()` 检查 Office CLI 路径,不执行下载。既有 `DSH_PRIMARY_RUNTIME` 路径仍受支持;空值禁用创作环境查询。Profile patch 可独立禁用 `skill-office`。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/session-title-provider-strategy/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/session-title-provider-strategy/guide.i18n.yaml new file mode 100644 index 0000000000..f972f05aa0 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/session-title-provider-strategy/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.1-alpha.1/session-title-provider-strategy/guide.md +/: + en: 08f294cc358eaffb + zh: 46ef86d9f933ea58 +/migrate-session-title-providers: + en: c9e33d3bdc0595c6 + zh: 55a049680ff8ae9b +/migrate-session-title-providers/change: + en: 3a8d72fb2c793d51 + zh: 9acc89004dd31096 +/migrate-session-title-providers/migration: + en: ea9efdc5234c0541 + zh: 845d80a7c6c05672 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/session-title-provider-strategy/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/session-title-provider-strategy/guide.md new file mode 100644 index 0000000000..bf0eb87a91 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/session-title-provider-strategy/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "Session-title providers register directly, own their strategy settings, and share only prepared execution." +--- + +# Migrate session-title providers + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/dsh-session-title-llm` no longer exports `registerSessionTitleLlmProvider`, `generateSessionTitleWithLlm`, or `SessionTitleLlmMessageSelector`. `SessionTitleLlmConfig` now holds only execution controls (`maxInputBytes`, `maxOutputTokens`, `timeoutMs`, and the optional `provider`/`model` pair); `targetWords` and `targetCjkCharacters` moved into each provider's own `Config`. Each provider owns its system instruction, message framing, title parsing, reasoning selection, and output interpretation, registers directly with `ctx.sessionTitle.register()`, and calls `executeSessionTitleLlm(ctx, config, request, providerId, { system, input, messageSeqs, selectReasoningEffort })`. That function returns the assembled content blocks, the terminal finish, and the used model route. `SessionTitleProviderRequest` gains an optional `currentTitle` snapshot. + +## Migration + +1. Replace a `registerSessionTitleLlmProvider(...)` call with a direct `ctx.sessionTitle.register({ id, automatic, generate })`; keep the same `id` and cadence. +2. In `generate(request)`, build your own system prompt and user input, pass a `selectReasoningEffort` function, then call `executeSessionTitleLlm` with `{ system, input, messageSeqs, selectReasoningEffort }`. +3. Reject a `tool-calls` or `max-tokens` terminal finish and tool-call blocks; derive the title from the text blocks. +4. Read `request.currentTitle` when the strategy should preserve an accepted provider title; it is absent before any title. +5. Generate a title and confirm the saved result plus the exact `session/title-llm-request` record. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/session-title-provider-strategy/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/session-title-provider-strategy/guide.zh.md new file mode 100644 index 0000000000..9bf62d63fe --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/session-title-provider-strategy/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "会话标题提供方直接注册、拥有自己的策略设置,并只共享准备好的执行。" +--- + +# 迁移会话标题提供方 + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-session-title-llm` 不再导出 `registerSessionTitleLlmProvider`、`generateSessionTitleWithLlm` 或 `SessionTitleLlmMessageSelector`。`SessionTitleLlmConfig` 现在只包含执行控制(`maxInputBytes`、`maxOutputTokens`、`timeoutMs` 以及可选的 `provider`/`model` 对);`targetWords` 与 `targetCjkCharacters` 已移入各提供方自己的 `Config`。各提供方拥有自己的系统指令、消息封装、标题解析、推理选择与输出解释,直接通过 `ctx.sessionTitle.register()` 注册,并调用 `executeSessionTitleLlm(ctx, config, request, providerId, { system, input, messageSeqs, selectReasoningEffort })`。该函数返回组装后的内容块、终止结束原因与所用模型路由。`SessionTitleProviderRequest` 新增可选的 `currentTitle` 快照。 + +## 迁移 + +1. 把 `registerSessionTitleLlmProvider(...)` 调用替换为直接 `ctx.sessionTitle.register({ id, automatic, generate })`;保持相同的 `id` 与节奏。 +2. 在 `generate(request)` 中构建自己的系统提示词与用户输入,传入 `selectReasoningEffort` 函数,然后用 `{ system, input, messageSeqs, selectReasoningEffort }` 调用 `executeSessionTitleLlm`。 +3. 拒绝 `tool-calls` 或 `max-tokens` 终止结束原因与工具调用块;从文本块派生标题。 +4. 当策略需要保留已接纳的提供方标题时读取 `request.currentTitle`;任何标题被接纳前该值为缺省。 +5. 生成一次标题,确认保存的结果以及确切的 `session/title-llm-request` 记录。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/ssh-helper-launch/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/ssh-helper-launch/guide.i18n.yaml new file mode 100644 index 0000000000..4f0fc7d434 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/ssh-helper-launch/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.1-alpha.1/ssh-helper-launch/guide.md +/: + en: ece09d74b8b3da0e + zh: 4762937e93aa8bf0 +/ssh-helper-and-ptc-launch-configuration: + en: e757aad6a0030eb3 + zh: 2f87638444248a40 +/ssh-helper-and-ptc-launch-configuration/change: + en: 7e78555e386835b1 + zh: 5a0d9de8e1312682 +/ssh-helper-and-ptc-launch-configuration/migration: + en: 33f5268892e099c9 + zh: c97f51289a61d323 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/ssh-helper-launch/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/ssh-helper-launch/guide.md new file mode 100644 index 0000000000..5f32a8363d --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/ssh-helper-launch/guide.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "SSH and Node PTC configurations use explicit launch modes, and SSH clients require a matching protocol-2 helper." +--- + +# SSH helper and PTC launch configuration + +English | [中文](guide.zh.md) + +## Change + +Custom SSH compositions must update their `cordis.yml` and installed helper together. `dsh-ssh` replaces top-level `node`, `bootstrapPath` and `bootstrapHash` with `launch`, and requires SSH protocol 2. `dsh-ptc-runtime-node` replaces `nodeExecutable` and `bootstrapPath` with `launch`. The connection's `nodeExecutable` and `bootstrapPath` getters are replaced by `ptcLaunch`. + +## Migration + +1. For a script helper, move `node`, `bootstrapPath` and `bootstrapHash` under `launch: { kind: node-script }`. Keep `helper`, `helperHash`, `host` and `workspace` at their existing locations. Install the matching helper script and update `helperHash`; update the bootstrap and its hash together when configured. +2. For a packaged helper, extract the complete archive and set `launch: { kind: executable }`, `helper` to the executable's absolute remote path, and `helperHash` to its digest from `manifest.json`. +3. Configure the remote PTC provider with `launch: ctx.ssh.ptcLaunch` in the composition's existing JavaScript configuration. For an explicitly configured local Node worker, use `launch: { kind: 'node-script', executable: previousNodeExecutable, bootstrapPath: previousBootstrapPath }`. Omitted local launch configuration still selects the current process's runtime. +4. Start the configured profile and exercise a remote file read, a process command and a PTC call. A protocol or digest mismatch requires updating the installed helper and its configuration together. See the [SSH deployment requirements](../../../../packages/ssh/ssh/README.md#use-this-package). diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/ssh-helper-launch/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/ssh-helper-launch/guide.zh.md new file mode 100644 index 0000000000..eb6dca6dfa --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/ssh-helper-launch/guide.zh.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "SSH 和 Node PTC 配置改用显式启动模式,SSH 客户端要求使用匹配的协议 2 helper。" +--- + +# SSH helper 与 PTC 启动配置 + +[English](guide.md) | 中文 + +## 变更 + +自定义 SSH 组合必须一起更新 `cordis.yml` 和已安装的 helper。`dsh-ssh` 将顶层 `node`、`bootstrapPath` 和 `bootstrapHash` 替换为 `launch`,并要求 SSH 协议 2。`dsh-ptc-runtime-node` 将 `nodeExecutable` 和 `bootstrapPath` 替换为 `launch`。连接的 `nodeExecutable` 和 `bootstrapPath` getter 替换为 `ptcLaunch`。 + +## 迁移 + +1. 使用脚本 helper 时,将 `node`、`bootstrapPath` 和 `bootstrapHash` 移入 `launch: { kind: node-script }`。`helper`、`helperHash`、`host` 和 `workspace` 保持原位置。安装匹配的 helper 脚本并更新 `helperHash`;配置了 bootstrap 时,一起更新该文件及其摘要。 +2. 使用打包后的 helper 时,解压完整发行包,设置 `launch: { kind: executable }`,将 `helper` 设为可执行文件的远端绝对路径,将 `helperHash` 设为 `manifest.json` 中该文件的摘要。 +3. 在组合现有的 JavaScript 配置中,通过 `launch: ctx.ssh.ptcLaunch` 配置远端 PTC 提供方。显式配置本地 Node worker 时,使用 `launch: { kind: 'node-script', executable: previousNodeExecutable, bootstrapPath: previousBootstrapPath }`。省略本地启动配置时,仍选择当前进程的运行时。 +4. 启动配置好的 profile,执行一次远端文件读取、进程命令和 PTC 调用。出现协议或摘要不匹配时,需要一起更新已安装的 helper 及其配置。参见 [SSH 部署要求](../../../../packages/ssh/ssh/README.zh.md#use-this-package)。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.i18n.yaml new file mode 100644 index 0000000000..3a047980af --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/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.1-alpha.1/subagent-preset-composition/guide.md +/: + en: 0351f79f0f7acc90 + zh: c6815e557ffa1a2f +/configure-subagent-composition-through-presets: + en: aab975172f278acf + zh: 4e6dad4ef487cc52 +/configure-subagent-composition-through-presets/change: + en: e758e1d0c34846db + zh: 93675aa1b3f7be4e +/configure-subagent-composition-through-presets/migration: + en: 0ae5b3e77d8c4b83 + zh: 746b44875e23dea6 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.md new file mode 100644 index 0000000000..c41f6f4c26 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: "Subagent persona and toolFilter configuration is replaced by Agent Preset composition." +--- + +# Configure subagent composition through presets + +English | [中文](guide.zh.md) + +## Change + +`dsh-tool-subagent` rejects `persona` and `toolFilter` configuration. New `SubagentStartRequest` values and provider capabilities no longer expose either field. In-process spawn selects a preset through `agentPreset`; its persona and tools come from that preset's plugins. Fork inherits the parent's preset and cannot independently change persona or restrict tools. Model and reasoning-effort options are unchanged. + +The shipped `standard`, `ptc`, and `cordis` delegation tools no longer hide `schedule_*` tools. Delegated callers still receive the existing execution refusal. Historical child Session descriptors retain their persona and tool restrictions when resumed. + +## Migration + +1. Remove `persona` and `toolFilter` from `dsh-tool-subagent` rows in your profile patches and custom presets. Update programmatic callers and provider capability declarations to remove the same fields. +2. For spawn, define an Agent Preset containing `dsh-persona` and the required tool plugins, then set the delegation tool's `agentPreset` to its id. Use `allowedAgentPresets` to offer several declared presets to the parent model. Presets select plugin compositions; there is no replacement per-child tool-name filter. +3. For fork, remove the overrides and accept the inherited composition. If the task needs a different composition, use spawn with a preset; it does not inherit the parent's conversation. +4. Start a new Session and delegate a task. Confirm that the child uses the selected preset's persona and tools. Existing persisted child Sessions need no manual edits. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.zh.md new file mode 100644 index 0000000000..dd84e38eda --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.zh.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: "Subagent 的 persona 与 toolFilter 配置由 Agent Preset 组装替代。" +--- + +# 通过 preset 配置子 Agent 组装 + +[English](guide.md) | 中文 + +## 变更 + +`dsh-tool-subagent` 拒绝 `persona` 与 `toolFilter` 配置。新的 `SubagentStartRequest` 和提供方能力声明也不再暴露这两个字段。进程内 spawn 通过 `agentPreset` 选择 preset,其 persona 与工具来自该 preset 的插件。fork 继承父方 preset,不能独立改变 persona 或限制工具。模型与推理强度选项保持不变。 + +出货的 `standard`、`ptc` 和 `cordis` 委派工具不再隐藏 `schedule_*` 工具。委派调用方仍会收到已有的执行拒绝。历史子 Session 的 descriptor 在恢复时仍应用其 persona 与工具限制。 + +## 迁移 + +1. 从 profile patch 和自定义 preset 的 `dsh-tool-subagent` 行中移除 `persona` 与 `toolFilter`。同步从程序化调用方和提供方能力声明中移除这两个字段。 +2. 对于 spawn,定义包含 `dsh-persona` 和所需工具插件的 Agent Preset,再将委派工具的 `agentPreset` 设为其 id。使用 `allowedAgentPresets` 向父模型开放多个已声明 preset。preset 选择插件组合,不提供替代的逐子级工具名过滤器。 +3. 对于 fork,移除覆盖并接受继承的组合。如果任务需要不同组合,使用带 preset 的 spawn;它不继承父方对话。 +4. 启动新 Session 并委派任务,确认子级使用所选 preset 的 persona 与工具。已有持久化子 Session 无须手动修改。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.i18n.yaml new file mode 100644 index 0000000000..0f10d46677 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/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.1-alpha.1/team-direct-inbox/guide.md +/: + en: d154c0e25274bb2f + zh: 7e59bdf067d2b141 +/agent-teams-messages-use-target-inboxes: + en: 04d7dcbdc1679eae + zh: 8b083641a9262d80 +/agent-teams-messages-use-target-inboxes/change: + en: 9968decf3dd340af + zh: 736a32caac4b5103 +/agent-teams-messages-use-target-inboxes/migration: + en: 7ffd442bfd55769e + zh: ffb11a143f11ce7f diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.md new file mode 100644 index 0000000000..974c1aa13c --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: "Agent Teams removes its pending-message limit and stops delivering historical queued mail." +--- + +# Agent Teams messages use target inboxes + +English | [中文](guide.zh.md) + +## Change + +The experimental Agent Teams plugin sends new messages directly to the target Agent inbox instead of retaining a separate Team mailbox. `send_message` returns only `{ "sent": true }`; it exposes neither a message ID nor an `accepted` or `queued` status. Acceptance does not confirm model processing or a synchronous storage flush. Failed sends are not retained for retry, and explicit resends are not deduplicated. + +The `maxPendingMessagesPerMember` configuration key is removed. Historical `team/message/queued` and `team/message/delivered` records remain readable, but queued messages that were not delivered before upgrading are never dispatched. Roster and task state remain durable. + +## Migration + +1. Before upgrading, let pending Team messages finish and confirm that their targets received them. After upgrading, explicitly resend any required undelivered message; check the target's history first to avoid duplicates. Do not edit historical Session records. +2. Remove `maxPendingMessagesPerMember` from the `@deepseek-ai/dsh-experimental-agent-team` plugin configuration in your `cordis.yml` or overlays. There is no replacement Team queue limit; `maxMessageBytes` still bounds each complete sender-framed message. +3. Update any consumer of `send_message` results to read `sent` instead of message IDs or delivery statuses, and handle send errors explicitly. Do not treat success as completed target work. The `ctx.agentTeams.sendMessage()` service still returns `messageId`. +4. Start your Team-enabled profile, send a message to another member, and confirm that the tool returns `{ "sent": true }` and that the target receives it. Consult the [package reference](../../../../packages/experimental/agent-team/README.md#use-this-package) for delivery semantics. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.zh.md new file mode 100644 index 0000000000..c10791fbf7 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.zh.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: "Agent Teams 移除待投递消息数量限制,并停止投递历史排队消息。" +--- + +# Agent Teams 消息使用目标收件箱 + +[English](guide.md) | 中文 + +## 变更 + +实验性 Agent Teams 插件将新消息直接发送到目标 Agent 收件箱,不再保留独立的 Team 邮箱。`send_message` 仅返回 `{ "sent": true }`,不暴露消息 ID,也不返回 `accepted` 或 `queued` 状态。接收成功不表示模型已处理消息,也不保证同步刷新到存储。失败的发送不会保留以供重试,显式重发也不会去重。 + +配置键 `maxPendingMessagesPerMember` 已移除。历史 `team/message/queued` 和 `team/message/delivered` 记录仍可读取,但升级前尚未投递的排队消息永远不会被派发。成员名单与任务状态仍然持久保存。 + +## 迁移 + +1. 升级前,让待投递的 Team 消息完成投递,并确认目标已收到。升级后,显式重发仍需处理的未投递消息;先检查目标历史,避免重复。不要编辑历史 Session 记录。 +2. 从 `cordis.yml` 或覆盖配置中 `@deepseek-ai/dsh-experimental-agent-team` 插件的配置移除 `maxPendingMessagesPerMember`。没有替代的 Team 队列限制;`maxMessageBytes` 仍限制包含发送者标识的完整消息大小。 +3. 更新所有读取 `send_message` 结果的调用方,改为读取 `sent` 而非消息 ID 或投递状态,并显式处理发送错误。不要把发送成功视为目标工作已完成。`ctx.agentTeams.sendMessage()` 服务仍返回 `messageId`。 +4. 启动启用 Team 的 profile,向其他成员发送消息,确认工具返回 `{ "sent": true }` 且目标收到消息。投递语义参见[包参考](../../../../packages/experimental/agent-team/README.zh.md#use-this-package)。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/web-listener-trust-config/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/web-listener-trust-config/guide.i18n.yaml new file mode 100644 index 0000000000..6e50b44007 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/web-listener-trust-config/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.1-alpha.1/web-listener-trust-config/guide.md +/: + en: af5832d4e9eece99 + zh: 8f97dad6921ed8a0 +/web-listener-and-trust-configuration-moves-to-webstartup: + en: de3788e700062659 + zh: 9def0e8f38896304 +/web-listener-and-trust-configuration-moves-to-webstartup/change: + en: 19f901fb2974aab5 + zh: b4ef886f85b61637 +/web-listener-and-trust-configuration-moves-to-webstartup/migration: + en: 30917eb37ead3e10 + zh: fd1b26eada570dd3 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/web-listener-trust-config/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/web-listener-trust-config/guide.md new file mode 100644 index 0000000000..6f18f4d7a1 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/web-listener-trust-config/guide.md @@ -0,0 +1,36 @@ +--- +kind: upgrade-guide +description: "The Web profile replaces the `webRuntime` service and the `web-runtime` row's `trustedHosts` config with `webStartup`, and rejects a wildcard listener host." +--- + +# Web listener and trust configuration moves to `webStartup` + +English | [中文](guide.zh.md) + +## Change + +The Web profile no longer provides the `webRuntime` service, and the `web-runtime` row no longer declares a `trustedHosts` config value. A profile, overlay, or `--patch` file that injects `webRuntime` now waits for a service that never mounts, and an expression reading `ctx.webRuntime.trustedHosts` fails to evaluate, so the required Connection cannot start. + +The `web-startup` row provides one `webStartup` service carrying the invocation's `--trusted-host` authorities, and the `connection` row reads them from `ctx.webStartup.trustedHosts`. The listener host must also be one concrete IPv4 or IPv6 address of a local interface: `host: 0.0.0.0`, `--host ::`, and every other unspecified address are rejected at load, because binding every interface exposes the port to the network. + +## Migration + +1. Replace `inject: [webRuntime]` with `inject: [webStartup]` on every row that needs invocation trust. +2. Replace `ctx.webRuntime.trustedHosts` expressions with `ctx.webStartup.trustedHosts`, and drop `ctx.webRuntime.lanAddresses`, which no longer exists. +3. Rewrite the `connection` overlay for `webStartup`, and move any `trustedHosts` value that the `web-runtime` row carried into its expression. A patch replaces the matched row's whole `config`, so restate that config completely, and write an array-valued `!!js` expression as a quoted scalar: + + ```yaml + # before + - id: connection + inject: [webRuntime] + config: + trustedHosts: !!js "['app.internal', ...ctx.webRuntime.trustedHosts]" + # after + - id: connection + inject: [webStartup] + config: + trustedHosts: !!js "['app.internal', ...ctx.webStartup.trustedHosts]" + ``` + +4. Replace a wildcard `host` with one concrete address of a local interface. The bind IP itself is accepted by the Host fence with no `--trusted-host` entry; a proxy or DNS authority still needs one. +5. Boot with the migrated overlay: `dsh --profile web --patch ./extra.yml --no-open` must print the `dsh web:` URL line and serve. A row still waiting on `webRuntime` leaves the required Connection pending and reports an activation failure, and a rejected `host` fails at load. `dsh --profile web --patch ./extra.yml --dump-config` prints the composed patch before boot. [The Web bundle README](../../../../packages/bundle/web-app/README.md) owns the composed rows. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/web-listener-trust-config/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/web-listener-trust-config/guide.zh.md new file mode 100644 index 0000000000..5e9f3d211f --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/web-listener-trust-config/guide.zh.md @@ -0,0 +1,36 @@ +--- +kind: upgrade-guide +description: "Web profile 用 `webStartup` 取代 `webRuntime` 服务与 `web-runtime` 行的 `trustedHosts` 配置,并拒绝通配监听地址。" +--- + +# Web 监听与信任配置迁移到 `webStartup` + +[English](guide.md) | 中文 + +## 变更 + +Web profile 不再提供 `webRuntime` 服务,`web-runtime` 行也不再声明 `trustedHosts` 配置值。仍注入 `webRuntime` 的 profile、overlay 或 `--patch` 文件会等待一个永不挂载的服务,读取 `ctx.webRuntime.trustedHosts` 的表达式则会求值失败,导致必需的 Connection 无法启动。 + +`web-startup` 行提供唯一的 `webStartup` 服务,携带本次调用的 `--trusted-host` authority;`connection` 行通过 `ctx.webStartup.trustedHosts` 读取它们。监听 host 现在也必须是本机网卡的一个具体 IPv4 或 IPv6 地址:`host: 0.0.0.0`、`--host ::` 及其他未指定地址都会在加载时被拒绝,因为绑定所有接口会把端口暴露到网络。 + +## 迁移 + +1. 将所有需要调用信任的行的 `inject: [webRuntime]` 换成 `inject: [webStartup]`。 +2. 将 `ctx.webRuntime.trustedHosts` 表达式换成 `ctx.webStartup.trustedHosts`,并删除已不存在的 `ctx.webRuntime.lanAddresses`。 +3. 按 `webStartup` 改写 `connection` overlay,并把原先由 `web-runtime` 行携带的 `trustedHosts` 值并入其表达式。patch 会整体替换所匹配行的 `config`,因此必须完整重述该配置;数组值的 `!!js` 表达式要写成带引号的标量: + + ```yaml + # before + - id: connection + inject: [webRuntime] + config: + trustedHosts: !!js "['app.internal', ...ctx.webRuntime.trustedHosts]" + # after + - id: connection + inject: [webStartup] + config: + trustedHosts: !!js "['app.internal', ...ctx.webStartup.trustedHosts]" + ``` + +4. 将通配 `host` 换成本机网卡的一个具体地址。所绑定的 IP 会被 Host 栅栏直接接受,无需 `--trusted-host`;代理或 DNS authority 仍需显式配置。 +5. 使用迁移后的 overlay 启动:`dsh --profile web --patch ./extra.yml --no-open` 必须打印 `dsh web:` URL 行并正常服务。仍在等待 `webRuntime` 的行会让必需的 Connection 保持 pending 并报告激活失败;被拒绝的 `host` 会在加载时失败。`dsh --profile web --patch ./extra.yml --dump-config` 可在启动前打印组合后的 patch。[Web 组合包 README](../../../../packages/bundle/web-app/README.zh.md)说明这些行。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/deepseek-account-model-catalog/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.2/deepseek-account-model-catalog/guide.i18n.yaml new file mode 100644 index 0000000000..5d77befdf5 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/deepseek-account-model-catalog/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.1-alpha.2/deepseek-account-model-catalog/guide.md +/: + en: 60a8441ae7ea6841 + zh: 3715b44e11c5131b +/deepseek-account-models-come-from-the-account-listing: + en: 2208c82c24d75a53 + zh: fa6c53c925aae6f2 +/deepseek-account-models-come-from-the-account-listing/change: + en: bf4c84372b8b1316 + zh: af1623701d19b62e +/deepseek-account-models-come-from-the-account-listing/migration: + en: 7ce26a5a1926b292 + zh: 35dfc17997834e4d diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/deepseek-account-model-catalog/guide.md b/docs/upgrade-guide/v0.2.1-alpha.2/deepseek-account-model-catalog/guide.md new file mode 100644 index 0000000000..9bedcf6c07 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/deepseek-account-model-catalog/guide.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "The DeepSeek account route no longer accepts a models catalog; the account listing supplies its models and modelOverrides adjusts them." +--- + +# DeepSeek account models come from the account listing + +English | [中文](guide.zh.md) + +## Change + +The `deepseek-account` route previously read its model catalog from the `models` field of the `llm-deepseek-account` entry, which the Models page could edit for the account. The route now lists models from the account's `GET /models` endpoint, serves the built-in catalog until a listing loads, and accepts per-model adjustments only through `modelOverrides`; the Models page no longer offers an editor for this route. A listed model can require a newer DeepSeek Harness; such a model is hidden, and a request for it fails with `CLIENT_UPGRADE_REQUIRED`. A `models` field left in the entry, including one saved by the earlier Models page editor, stops the plugin at load with `llm-deepseek-account: models is no longer configurable`, and Desktop and Web show no account models until the field is removed. Signed-in accounts without a saved catalog need no action. + +## Migration + +1. Open `$DSH_HOME/profiles//cordis.patch.yml` and find the entry with `id: llm-deepseek-account`. +2. Delete its `models` field. For each model whose fields you changed, move only the changed fields under `modelOverrides.`: + + ```yaml + - id: llm-deepseek-account + config: + modelOverrides: + deepseek-flash: + maxTokens: 131072 + ``` + +3. Restart DeepSeek Harness, sign in to the DeepSeek account, and confirm that the model selector lists the account models and the Models page shows the account as signed in. An override the listed model rejects, or one that names an unknown model, appears as the account's diagnostic on the Models page. diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/deepseek-account-model-catalog/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.2/deepseek-account-model-catalog/guide.zh.md new file mode 100644 index 0000000000..a95a72d633 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/deepseek-account-model-catalog/guide.zh.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "DeepSeek 账号路由不再接受 models 目录;模型由账号的模型列表提供,单个模型通过 modelOverrides 调整。" +--- + +# DeepSeek 账号模型改由账号的模型列表提供 + +[English](guide.md) | 中文 + +## 变更 + +`deepseek-account` 路由此前从 `llm-deepseek-account` 条目的 `models` 字段读取模型目录,模型页可以为账号编辑这份目录。现在该路由从账号的 `GET /models` 端点列出模型,在列表加载之前使用内置目录,单个模型只能通过 `modelOverrides` 调整;模型页不再为该路由提供编辑器。列表中的模型可以要求更新版本的 DeepSeek Harness,这样的模型会被隐藏,请求它时以 `CLIENT_UPGRADE_REQUIRED` 失败。条目中遗留的 `models` 字段,包括早先模型页编辑器保存的,会让插件在加载时报 `llm-deepseek-account: models is no longer configurable` 并停止,删除该字段之前桌面端和 Web 都不显示账号模型。没有保存过账号目录的已登录账号无需操作。 + +## 迁移 + +1. 打开 `$DSH_HOME/profiles//cordis.patch.yml`,找到 `id: llm-deepseek-account` 的条目。 +2. 删除其中的 `models` 字段。对改过字段的模型,只把改过的字段移到 `modelOverrides.<模型 id>` 下: + + ```yaml + - id: llm-deepseek-account + config: + modelOverrides: + deepseek-flash: + maxTokens: 131072 + ``` + +3. 重启 DeepSeek Harness 并登录 DeepSeek 账号,确认模型选择器列出账号模型、模型页显示账号已登录。被列出的模型拒绝的覆盖,或指向未知模型的覆盖,会作为该账号的诊断信息显示在模型页上。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/desktop-font-size-shortcuts/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.2/desktop-font-size-shortcuts/guide.i18n.yaml new file mode 100644 index 0000000000..a4a47e22a2 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/desktop-font-size-shortcuts/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.1-alpha.2/desktop-font-size-shortcuts/guide.md +/: + en: 0863e2ef201c6e98 + zh: e7042cab4852e9c8 +/desktop-font-size-shortcuts-reserve-custom-key-combinations: + en: 7c82d9faadaec1e0 + zh: 91d60eb7a660e1b3 +/desktop-font-size-shortcuts-reserve-custom-key-combinations/change: + en: cb025eb9ae5e18ae + zh: 094ec608c1ce4dad +/desktop-font-size-shortcuts-reserve-custom-key-combinations/migration: + en: bc66077939ee3df3 + zh: f8460bf5ec20ac58 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/desktop-font-size-shortcuts/guide.md b/docs/upgrade-guide/v0.2.1-alpha.2/desktop-font-size-shortcuts/guide.md new file mode 100644 index 0000000000..f674031611 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/desktop-font-size-shortcuts/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "Desktop font-size shortcuts reserve key combinations previously available to custom shortcuts." +--- + +# Desktop font-size shortcuts reserve custom key combinations + +English | [中文](guide.zh.md) + +## Change + +Desktop reserves `Cmd`/`Ctrl` + `=` (including `Shift` + `=` for `+`) and `Cmd`/`Ctrl` + `-` to adjust text, code, and terminal font sizes together. Use `Cmd` on macOS and `Ctrl` on Windows and Linux. Custom bindings using these combinations, including overlapping two-key chords, remain saved but no longer execute. Web shortcut behavior is unchanged. + +## Migration + +1. Open Settings → General → Keyboard shortcuts in Desktop and find any custom binding marked as conflicting with a font-size shortcut. +2. Record a nonconflicting combination for that action, or choose **Remove** to disable its keyboard shortcut. **Restore default** is available when the action's default does not conflict. +3. Try the reassigned action, then press `Cmd`/`Ctrl` + `=` and `Cmd`/`Ctrl` + `-`. Confirm that all three font sizes change in Settings and remain saved after reopening Desktop. diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/desktop-font-size-shortcuts/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.2/desktop-font-size-shortcuts/guide.zh.md new file mode 100644 index 0000000000..a9d052744f --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/desktop-font-size-shortcuts/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "桌面端字号快捷键占用了原先可用于自定义快捷键的组合键。" +--- + +# 桌面端字号快捷键占用部分自定义组合键 + +[English](guide.md) | 中文 + +## 变更 + +桌面端保留 `Cmd`/`Ctrl` + `=`(包括输入 `+` 的 `Shift` + `=`)和 `Cmd`/`Ctrl` + `-`,用于一起调整正文、代码和终端字号。macOS 使用 `Cmd`,Windows 和 Linux 使用 `Ctrl`。使用这些组合键的自定义绑定,包括与其重叠的双键序列,仍会保存,但不再执行。Web 端快捷键行为不变。 + +## 迁移 + +1. 在桌面端打开「设置 → 通用 → 键盘快捷键」,找到标记为与字号快捷键冲突的自定义绑定。 +2. 为该操作录制不冲突的组合键,或选择「移除」禁用其快捷键。操作的默认快捷键不冲突时,也可以选择「恢复默认」。 +3. 尝试重新绑定的操作,再按 `Cmd`/`Ctrl` + `=` 和 `Cmd`/`Ctrl` + `-`。确认设置中的三组字号一起变化,并在重新打开桌面端后仍保留。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-azure-provider/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-azure-provider/guide.i18n.yaml new file mode 100644 index 0000000000..46b8b3fcd7 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-azure-provider/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.1-alpha.2/pi-ai-azure-provider/guide.md +/: + en: 51d5b5b4d2fb1b8a + zh: 4dc9af2458a8fcac +/azure-provider-route-rename: + en: 105c73820d057e28 + zh: 91a7bfc5c282e164 +/azure-provider-route-rename/change: + en: d5ce9089d8aa7119 + zh: f337926f85b01bc1 +/azure-provider-route-rename/migration: + en: 8fb23fbb8184fa00 + zh: 8c44fb293a8dd70a diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-azure-provider/guide.md b/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-azure-provider/guide.md new file mode 100644 index 0000000000..1b4119f4d7 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-azure-provider/guide.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "The pi-ai Azure provider route is renamed from azure-openai-responses to azure." +--- + +# Azure provider route rename + +English | [中文](guide.zh.md) + +## Change + +The installed pi-ai catalog identifies the Azure provider as `azure` instead of `azure-openai-responses`. The `azure` route includes both Responses and Chat Completions models. The Responses API identifier remains `azure-openai-responses`, and the `AZURE_OPENAI_*` environment variables keep their names. Configurations and model selections that use the old provider key no longer resolve the Azure catalog. + +## Migration + +1. In the `llm-pi-ai` configuration in `$DSH_HOME/profiles//cordis.patch.yml` or another supplying layer, rename `config.providers.azure-openai-responses` to `config.providers.azure`. Preserve its existing fields and any `apiKeyEnv` reference. +2. Use catalog model IDs under `models`; map a custom Azure deployment name with `AZURE_OPENAI_DEPLOYMENT_NAME_MAP`. The mixed catalog cannot infer a protocol for a model ID absent from the catalog. An explicit route-level `api` overrides every model on that route; it does not select the Azure provider. +3. Update explicit request/default provider selections to `azure`, and reselect an Azure model when continuing an existing Session. Configure the new Azure entry in Settings → Models if its key was stored for the old entry. Do not edit historical Session events. +4. Confirm that Settings → Models offers `azure` and lists the expected models, then send a short request using the configured deployment. diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-azure-provider/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-azure-provider/guide.zh.md new file mode 100644 index 0000000000..ad62892268 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-azure-provider/guide.zh.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "pi-ai 的 Azure 提供方路由从 azure-openai-responses 更名为 azure。" +--- + +# Azure 提供方路由更名 + +[English](guide.md) | 中文 + +## 变更 + +已安装的 pi-ai 目录使用 `azure` 标识 Azure 提供方,替代 `azure-openai-responses`。`azure` 路由同时包含 Responses 和 Chat Completions 模型。Responses API 标识仍为 `azure-openai-responses`,`AZURE_OPENAI_*` 环境变量名称也保持不变。使用旧提供方键的配置和模型选择无法再解析 Azure 目录。 + +## 迁移 + +1. 在 `$DSH_HOME/profiles//cordis.patch.yml` 或其他提供配置的层中,找到 `llm-pi-ai` 配置,将 `config.providers.azure-openai-responses` 改为 `config.providers.azure`。保留原有字段及任何 `apiKeyEnv` 引用。 +2. 在 `models` 中使用目录模型 ID;自定义 Azure 部署名称通过 `AZURE_OPENAI_DEPLOYMENT_NAME_MAP` 映射。混合协议目录无法为目录外的模型 ID 推断协议。显式设置路由级 `api` 会覆盖该路由所有模型的协议,并不表示选择 Azure 提供方。 +3. 将显式请求及默认模型配置中的提供方改为 `azure`,继续现有 Session 时重新选择 Azure 模型。若密钥存储在旧条目下,请在“设置 → 模型”中配置新的 Azure 条目。不要修改历史 Session 事件。 +4. 确认“设置 → 模型”提供 `azure` 且列出预期模型,再向所配置的部署发送一条简短请求。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-model-discovery/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-model-discovery/guide.i18n.yaml new file mode 100644 index 0000000000..4412c0cf22 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-model-discovery/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.1-alpha.2/pi-ai-model-discovery/guide.md +/: + en: 40afcce4dbdcb337 + zh: 33c5647441bd1dcb +/pi-ai-model-visibility-without-a-credential: + en: 1bc74c0ce4085c3c + zh: 0a2be91b04c069c8 +/pi-ai-model-visibility-without-a-credential/change: + en: f92005c2a3d4645c + zh: 5bfb1685cdf3437c +/pi-ai-model-visibility-without-a-credential/migration: + en: 26d72c82e5c60031 + zh: 4b582d3e4d022dd8 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-model-discovery/guide.md b/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-model-discovery/guide.md new file mode 100644 index 0000000000..0427fda13a --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-model-discovery/guide.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "pi-ai routes that name a credential hide their models until the credential is configured." +--- + +# pi-ai model visibility without a credential + +English | [中文](guide.zh.md) + +## Change + +A pi-ai route that names a credential through `apiKeyEnv` previously listed its configured models while that credential was missing, and requests then failed with `MISSING_CREDENTIAL`. Model discovery now returns an empty catalog for such a route until the credential resolves, so Desktop and Web hide its group. Other credential errors, such as a malformed key, still fail model discovery. Routes that use the provider's native authentication or name no credential keep their configured catalog. A saved or default selection absent from the catalog displays “Select model” without changing the stored selection. + +## Migration + +1. To use such a route, configure its key in Settings → Models, or supply the reference its `apiKeyEnv` names through the launch environment. +2. Reopen the model selector and confirm that the route's group appears. Custom model discovery consumers must handle an empty catalog before the credential is configured; a listed catalog does not mean that the remote API accepts the key. diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-model-discovery/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-model-discovery/guide.zh.md new file mode 100644 index 0000000000..b4855afad2 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/pi-ai-model-discovery/guide.zh.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "指定了凭据的 pi-ai 路由在凭据配置之前隐藏其模型。" +--- + +# pi-ai 路由缺少凭据时的模型可见性 + +[English](guide.md) | 中文 + +## 变更 + +通过 `apiKeyEnv` 指定凭据的 pi-ai 路由,此前在凭据缺失时也会列出配置的模型,请求随后以 `MISSING_CREDENTIAL` 失败。现在凭据解析到之前,模型发现对这样的路由返回空目录,因此桌面端和 Web 隐藏它的分组。其他凭据错误(例如密钥格式错误)仍会让模型发现失败。使用提供方原生认证或未指定凭据的路由保留配置的目录。已保存或默认的选择不在目录中时,界面显示“请选择模型”,保存的选择保持不变。 + +## 迁移 + +1. 要使用这样的路由,请在设置 → 模型中配置密钥,或通过启动环境提供 `apiKeyEnv` 指定的凭据引用。 +2. 重新打开模型选择器,确认该路由的分组出现。自定义模型发现消费者必须处理配置凭据前的空目录;列出目录不代表远端 API 已接受密钥。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/plugin-install-over-installed/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.2/plugin-install-over-installed/guide.i18n.yaml new file mode 100644 index 0000000000..d3693c2a4f --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/plugin-install-over-installed/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.1-alpha.2/plugin-install-over-installed/guide.md +/: + en: 036db2d1004f0aa0 + zh: fb026ec0af7949f6 +/installing-over-an-installed-plugin-package-is-refused-with-hmr: + en: a941bcec1d8f3b70 + zh: ac5ca3517057a52c +/installing-over-an-installed-plugin-package-is-refused-with-hmr/change: + en: e521f46141e8be0a + zh: 1d34929d5d90e466 +/installing-over-an-installed-plugin-package-is-refused-with-hmr/migration: + en: f72eeb19e689bbee + zh: 9ae1f049688edf38 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/plugin-install-over-installed/guide.md b/docs/upgrade-guide/v0.2.1-alpha.2/plugin-install-over-installed/guide.md new file mode 100644 index 0000000000..53b51a1113 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/plugin-install-over-installed/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "With HMR, installing a package that is already installed fails with already-installed; an upgrade removes the package first." +--- + +# Installing over an installed plugin package is refused with HMR + +English | [中文](guide.zh.md) + +## Change + +In a profile that runs HMR, which the shipped profiles do, `pluginManager.installBundle(spec)` used to run pnpm over a package the profile already depends on and report `restart-required` while the previous version kept running. It now fails before pnpm runs, with `application: 'failed'` and `error.code: 'already-installed'`, and changes no profile file, when the spec names an installed package: a registry name with or without a version, a local directory, or the git or tarball spec the dependency was saved with. Repeating an installation of the same spec fails the same way instead of reporting `changed: false`. + +This affects callers of `installBundle()` through the Host API and the remote client in `@deepseek-ai/dsh-api-remotes/client`, and the agent's `plugin_manager` tool (`install_bundle`). An installed package that cannot be removed, such as a bundle carrying plugin management, can no longer be installed over while HMR runs. The Web page's Update for an Official plugin removes the package and installs the new version itself. Without HMR, installing over an installed package still runs pnpm and reports `restart-required`. + +## Migration + +1. To install another version or location of an installed package, call `removeBundle(name)` first, then `installBundle(spec)`. For the agent tool, call `remove_bundle`, then `install_bundle`. The removal stops the bundle's plugins and drops its packages' mappings, so the new version is mapped afresh and starts without a restart. +2. If code switches exhaustively over `ManagementError['code']`, handle the `already-installed` code. +3. Confirm the migration: installing the package again returns `already-installed`, and after `removeBundle` the same `installBundle` call returns `applied` with the new `version`. diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/plugin-install-over-installed/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.2/plugin-install-over-installed/guide.zh.md new file mode 100644 index 0000000000..4a3d7adf53 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/plugin-install-over-installed/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "启用 HMR 时,安装已安装的包会以 already-installed 失败;升级需要先移除该包。" +--- + +# 启用 HMR 时拒绝在已安装的插件包上再次安装 + +[English](guide.md) | 中文 + +## 变更 + +在运行 HMR(热模块替换)的 profile 中(随附的 profile 都运行 HMR),`pluginManager.installBundle(spec)` 此前会对 profile 已依赖的包运行 pnpm,并在旧版本继续运行时报告 `restart-required`。现在当 spec 指向已安装的包时,它会在运行 pnpm 之前失败,返回 `application: 'failed'` 和 `error.code: 'already-installed'`,且不修改任何 profile 文件。这里的 spec 包括带或不带版本的注册表包名、本地目录,以及保存依赖时使用的 git 或 tarball spec。重复安装同一个 spec 也会以同样方式失败,不再报告 `changed: false`。 + +受影响的调用方包括:通过 Host API 调用 `installBundle()` 的代码、`@deepseek-ai/dsh-api-remotes/client` 中的远端客户端,以及 agent 的 `plugin_manager` 工具(`install_bundle`)。启用 HMR 时,不能再在无法移除的已安装包(例如带有插件管理的组合包)上安装。Web 页面上官方插件的“更新”操作会自行移除该包并安装新版本。未启用 HMR 时,在已安装的包上安装仍会运行 pnpm 并报告 `restart-required`。 + +## 迁移 + +1. 要安装已安装包的其他版本或其他位置,先调用 `removeBundle(name)`,再调用 `installBundle(spec)`。使用 agent 工具时,先调用 `remove_bundle`,再调用 `install_bundle`。移除操作会停止该 bundle 的插件,并删除其各个包的映射,因此新版本会重新建立映射,无需重启即可启动。 +2. 如果代码对 `ManagementError['code']` 做穷尽 switch,需要处理 `already-installed`。 +3. 确认迁移结果:再次安装该包返回 `already-installed`;执行 `removeBundle` 后,同样的 `installBundle` 调用返回 `applied` 和新的 `version`。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/sdk-minimal-image-compaction/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.2/sdk-minimal-image-compaction/guide.i18n.yaml new file mode 100644 index 0000000000..7855124a09 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/sdk-minimal-image-compaction/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.1-alpha.2/sdk-minimal-image-compaction/guide.md +/: + en: 5fc67054b45f1734 + zh: 0cb92b2e036dfb67 +/sdk-minimal-image-reading-and-automatic-compaction: + en: 1b0161d44c885284 + zh: 5babee2ad7dc2571 +/sdk-minimal-image-reading-and-automatic-compaction/change: + en: 42d90c20c9549611 + zh: f904303bea2a60a8 +/sdk-minimal-image-reading-and-automatic-compaction/migration: + en: e944f28ce8c2ef8d + zh: 3bd5fd84a02e5866 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/sdk-minimal-image-compaction/guide.md b/docs/upgrade-guide/v0.2.1-alpha.2/sdk-minimal-image-compaction/guide.md new file mode 100644 index 0000000000..a1cd0795fa --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/sdk-minimal-image-compaction/guide.md @@ -0,0 +1,32 @@ +--- +kind: upgrade-guide +description: "The sdk-minimal default tool roster adds read_image and automatically summarizes older context." +--- + +# SDK-minimal image reading and automatic compaction + +English | [中文](guide.zh.md) + +## Change + +`sdk-minimal` advertises `read_image` alongside its persistent shell and `working_directory`. Automatic compaction sends an additional model request to summarize older history when context pressure reaches the configured threshold. The complete Session log remains stored as uncompressed JSONL. Images that exceed the route budget are permanently replaced by attachment/path placeholders so the request can retry. SDK prompt text does not execute `/compact`. + +Clients that pin tool names, benchmark prompt size, or count model requests must account for these defaults. Image reading requires an adapter route that declares image input. See the [bundle reference](../../../../packages/bundle/sdk-minimal/README.md) for configuration and model effects. + +## Migration + +1. Accept the new defaults, or place this patch in `$DSH_HOME/profiles/sdk-minimal/cordis.patch.yml` to retain the previous default tools and disable automatic compaction: + +```yaml +- id: tool-fs + config: + read: false + readImage: false + write: false + edit: false +- id: compaction-basic + config: + auto: false +``` + +2. Launch a fresh SDK runtime. Without additional user plugins, its model requests contain the persistent `bash` or `pwsh` tool and `working_directory`; it sends no automatic summarization requests. diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/sdk-minimal-image-compaction/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.2/sdk-minimal-image-compaction/guide.zh.md new file mode 100644 index 0000000000..6d4d43a100 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/sdk-minimal-image-compaction/guide.zh.md @@ -0,0 +1,32 @@ +--- +kind: upgrade-guide +description: "sdk-minimal 默认工具清单新增 read_image,并自动生成较早上下文的摘要。" +--- + +# SDK-minimal 图片读取与自动压缩 + +[English](guide.md) | 中文 + +## 变更 + +`sdk-minimal` 在持久 shell 和 `working_directory` 之外公布 `read_image`。上下文压力达到配置阈值时,自动压缩会额外发起模型请求,生成较早历史的摘要。完整 Session 日志仍存储为未压缩 JSONL。图片超出路由预算时会被永久替换为包含附件与路径的占位文本,以便重试请求。SDK 提示词文本不会执行 `/compact`。 + +固定工具名称、基准提示词大小或统计模型请求数的客户端必须考虑这些默认行为。图片读取需要适配器路由声明支持图片输入。配置与模型影响见[组合包参考](../../../../packages/bundle/sdk-minimal/README.zh.md)。 + +## 迁移 + +1. 接受新增默认能力,或将以下 patch 写入 `$DSH_HOME/profiles/sdk-minimal/cordis.patch.yml`,保留原有默认工具并关闭自动压缩: + +```yaml +- id: tool-fs + config: + read: false + readImage: false + write: false + edit: false +- id: compaction-basic + config: + auto: false +``` + +2. 启动新的 SDK 运行时。未额外配置用户插件时,模型请求包含持久 `bash` 或 `pwsh` 工具及 `working_directory`;不会发起自动摘要请求。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.i18n.yaml new file mode 100644 index 0000000000..60dff113e1 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/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.1-alpha.2/stored-credentials-precedence/guide.md +/: + en: 9fc8377bd2d6e38c + zh: b77fd76aeee0f592 +/a-stored-key-takes-precedence-over-an-exported-variable: + en: 0d002196a3f19850 + zh: 7dcbbb6a44216f01 +/a-stored-key-takes-precedence-over-an-exported-variable/change: + en: 4ac6ffc5e782f765 + zh: 51a69db953708bd3 +/a-stored-key-takes-precedence-over-an-exported-variable/migration: + en: d4f534f82476b5e9 + zh: 5371eaaae96a3759 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.md b/docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.md new file mode 100644 index 0000000000..5726a62e23 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.md @@ -0,0 +1,25 @@ +--- +kind: upgrade-guide +description: "Stored credentials now precede environment fallbacks when the store is mounted; the shipped headless profile omits stored authentication." +--- + +# A stored key takes precedence over an exported variable + +English | [中文](guide.zh.md) + +## Change + +Earlier releases used an exported environment variable before the `refs` entry with the same name in `$DSH_HOME/.credentials.yaml` (`~/.dsh/.credentials.yaml` by default). This applied to `DEEPSEEK_API_KEY=… dsh`, a shell profile export, a CI secret, and a container `-e` value. While the name was exported, the Models page could not save a key for it. + +Now the stored entry wins. The exported variable applies only while the file stores no value for that name, and `$cwd/.env` and `$DSH_HOME/.env` still apply only after both. The Models page can save and replace a key while the name is exported. + +The shipped `headless` profile instead disables the credential store, authorization and DeepSeek account provider. It uses the launch environment, project `.env`, then Harness-home `.env`, and leaves `.credentials.yaml` untouched. Saved API keys and sign-ins no longer authenticate headless jobs by default. Web, SDK and ACP retain the store. + +You are affected when a harness home stores a value under `refs` and the process that launches `dsh` exports the same name. This includes a container that mounts such a home. Requests now use the stored key instead of the exported one. A CI job or container that starts with a fresh harness home, without `.credentials.yaml`, is not affected. The [stored credential precedence](../../../../.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.md) Agent Note records the reason. + +## Migration + +1. Compare the names under `refs` in `$DSH_HOME/.credentials.yaml` with the variables that your shell, CI job, or container exports. A name that appears in only one place needs no action. +2. For each name that appears in both places, keep the stored key if it is the account you want. Otherwise, delete the name's line under `refs`. A running harness reloads the file, so the next request reads the exported variable without a restart. +3. For a headless job, export the required key and run `dsh headless ""`. To keep using a saved key or sign-in, apply the three-row [headless restoration patch](../../../../packages/bundle/headless/README.md#credentials); restored storage also restores saved-first precedence. Existing profile, home or command overlays can override the shipped rows, so inspect `dsh headless --dump-config` when checking the effective composition. +4. Confirm the intended request account and that the launching process exports a non-empty value where needed. Check names and presence without printing credential values. A headless run relying only on a saved credential now fails; restoring storage or supplying supported environment authentication resolves it. diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.zh.md new file mode 100644 index 0000000000..239d0367ac --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.zh.md @@ -0,0 +1,25 @@ +--- +kind: upgrade-guide +description: "挂载存储时,已保存凭据现在优先于环境后备;随附 headless profile 不挂载存储认证。" +--- + +# 存储的密钥优先于导出的变量 + +[English](guide.md) | 中文 + +## 变更 + +早期版本会先使用导出的环境变量,再使用 `$DSH_HOME/.credentials.yaml`(默认为 `~/.dsh/.credentials.yaml`)中同名的 `refs` 条目。这适用于 `DEEPSEEK_API_KEY=… dsh`、shell 配置文件中的导出、CI 机密和容器 `-e` 值。该名字被导出期间,Models 页面无法为其保存密钥。 + +现在存储的条目优先。只有当文件没有为该名字存储值时,导出的变量才会生效;`$cwd/.env` 和 `$DSH_HOME/.env` 仍排在两者之后。即使该名字已被导出,Models 页面也可以保存和替换密钥。 + +随附的 `headless` profile 则禁用凭据存储、authorization 和 DeepSeek account 提供方。它依次使用启动环境、项目 `.env` 和 Harness home `.env`,并保持 `.credentials.yaml` 原样。已保存 API 密钥和登录凭据默认不再为 headless 任务提供认证。Web、SDK 和 ACP 保留存储。 + +如果某个 harness home 在 `refs` 下存储了值,而启动 `dsh` 的进程导出了同名变量,你就会受到影响。挂载了这类 home 的容器也包括在内。请求现在使用存储的密钥,而不是导出的密钥。以全新 harness home 启动、没有 `.credentials.yaml` 的 CI 作业或容器不受影响。[存储凭据优先级](../../../../.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.zh.md) Agent Note 记录了原因。 + +## 迁移 + +1. 将 `$DSH_HOME/.credentials.yaml` 中 `refs` 下的名字,与 shell、CI 作业或容器导出的变量进行比较。只出现在其中一处的名字无需处理。 +2. 对同时出现在两处的名字,如果存储的密钥正是你要使用的账户,就保留它。否则,删除 `refs` 下该名字所在的行。运行中的 harness 会重新加载该文件,因此下一次请求无需重启即可读取导出的变量。 +3. 对 headless 任务,导出所需密钥并运行 `dsh headless ""`。要继续使用已保存密钥或登录凭据,请应用三行配置的 [headless 恢复 patch](../../../../packages/bundle/headless/README.zh.md#credentials);恢复存储也恢复已保存凭据优先。现有 profile、home 或命令覆盖可以覆盖随附行,因此核对有效组合时请查看 `dsh headless --dump-config`。 +4. 确认请求使用预期账户,并在需要时确认启动进程导出了非空值。只检查名字和是否存在,不要打印凭据值。仅依赖已保存凭据的 headless 运行现在会失败;恢复存储或提供受支持的环境认证即可解决。 diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index 6f9b6e315e..85cf647be1 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -9,8 +9,8 @@ en: 2c6b665adc256b4e zh: 2240e4c1573ebe9c /configure-models/add-a-third-party-provider: - en: 0fe5f88e692f618c - zh: 4f2e493818d8934f + en: 4b99a9b34d117eea + zh: dddeb5a08c0d3cc6 /configure-models/add-a-custom-model-api: en: 17867305a3e1b52a zh: 876fedf1f6f563e4 @@ -26,6 +26,9 @@ /configure-models/advanced-configuration/image-input: en: 75350cb615da03a4 zh: 6f8b3510085e4ac4 +/configure-models/advanced-configuration/deepseek-account-models: + en: fc09d02a89b211a7 + zh: e0f23a8912a24178 /configure-models/advanced-configuration/reasoning-effort: en: f7581a0760fdfd2c zh: dc6eaa16f74a0e9f diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index 773ff6722a..1fd84e9f1a 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -16,7 +16,9 @@ Keys are write-only. The page receives a redacted descriptor after saving, never Choose **Add model provider**. The card opens on **Third-party model provider**: pick a provider dsh ships with — the list shows provider ids such as `anthropic`, `openai`, `moonshotai` for Kimi, or `zai` for GLM — enter its API key, and save. The installed catalog supplies the endpoint, protocol, and model list. -Providers that sign in with OAuth, such as Codex, are not supported here yet. +The authentication **?** explains saved-credential priority and the environment fallbacks displayed for a key field. Leaving the key blank preserves existing authentication. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference. + +For an existing profile that names a credential reference, **API key source** shows the layer currently supplying that reference: saved credentials, launch environment, `$cwd/.env`, or `$DSH_HOME/.env`. Native authentication without a named reference has no source label. ## Add a custom model API @@ -108,6 +110,21 @@ In pi-ai configuration, every list must name at least one modality except a mode Both fields state a claim about your endpoint rather than checking it. A model that declares images its endpoint does not serve is not caught here; the provider rejects the request instead. +### DeepSeek account models + +A signed-in DeepSeek account lists its models from the account service, so the Models page offers no model editor for it. Adjust a single model with `modelOverrides` in `$DSH_HOME/profiles//cordis.patch.yml`; the fields match a DeepSeek `models` entry, and unset fields keep the listed values: + +```yaml +- id: llm-deepseek-account + config: + modelOverrides: + deepseek-flash: + contextWindow: 524288 + maxTokens: 131072 +``` + +A model that needs a newer DeepSeek Harness fails with `CLIENT_UPGRADE_REQUIRED`, which names the version to install. The [account provider reference](../../../packages/llm/llm-deepseek-account/README.md) owns the listing, fallback, and gating rules. + ### Reasoning effort The model picker offers an **Effort** menu for a model that declares reasoning levels. A built-in provider's models inherit their levels from the installed catalog. A model you enter by hand declares none, so the Effort entry does not appear in the menu and the endpoint's own default decides whether the model thinks. Declare the levels with `reasoningEfforts` in `$DSH_HOME/profiles//cordis.patch.yml`: diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index 6d618ed1e9..340f6b8b97 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -16,7 +16,9 @@ 选择**添加模型提供商**。卡片默认打开在**第三方模型提供商**:选取 dsh 自带的提供商——列表显示的是提供商 id,例如 `anthropic`、`openai`、Kimi 对应的 `moonshotai`、GLM 对应的 `zai`——输入其 API 密钥并保存。已安装目录会提供端点、协议和模型列表。 -通过 OAuth 登录的提供商(例如 Codex)暂不支持。 +认证 **?** 说明已保存凭据的优先级,以及密钥字段所显示的环境后备。密钥留空会保留现有认证。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。 + +已有 profile 指定凭据引用时,**API 密钥来源**显示当前为该引用供值的层:已保存凭据、启动环境、`$cwd/.env` 或 `$DSH_HOME/.env`。未指定引用的原生认证不显示来源标签。 ## 添加自定义模型 API @@ -108,6 +110,21 @@ DeepSeek 将省略的 `inputModalities` 视为纯文本,并拒绝空列表。 这两个字段都是对你端点的断言,而不是对它的检查。声明了端点并不提供的图片能力的模型不会在这里被拦下,改由提供商拒绝该请求。 +### DeepSeek 账号的模型 + +已登录 DeepSeek 账号的模型列表来自账号服务,因此模型页不为它提供模型编辑器。要调整单个模型,在 `$DSH_HOME/profiles//cordis.patch.yml` 中使用 `modelOverrides`;字段与 DeepSeek 的 `models` 条目相同,未设置的字段沿用列表中的值: + +```yaml +- id: llm-deepseek-account + config: + modelOverrides: + deepseek-flash: + contextWindow: 524288 + maxTokens: 131072 +``` + +需要更新版 DeepSeek Harness 的模型会以 `CLIENT_UPGRADE_REQUIRED` 失败,并写明需要安装的版本。列表、兜底和门控规则见[账号提供方参考](../../../packages/llm/llm-deepseek-account/README.zh.md)。 + ### 推理等级 对于声明了推理等级的模型,模型选择器会提供**推理等级**菜单。内置提供商的模型从已安装目录继承其等级。手动录入的模型不声明任何等级,因此模型菜单里不会出现推理等级项,由端点自身的默认值决定模型是否思考。请在 `$DSH_HOME/profiles//cordis.patch.yml` 中用 `reasoningEfforts` 声明等级: diff --git a/docs/user/guide/public-deployments.i18n.yaml b/docs/user/guide/public-deployments.i18n.yaml index 7bd0d94673..757429dcc0 100644 --- a/docs/user/guide/public-deployments.i18n.yaml +++ b/docs/user/guide/public-deployments.i18n.yaml @@ -3,17 +3,17 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/user/guide/public-deployments.md /publish-the-web-ui-behind-a-reverse-proxy: - en: 15b92e92d2526f37 - zh: b58079cf6eee78cc + 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: 8dd9d910a93fe54d - zh: 1e9e21d9949c8ab2 + en: 2f93051763125365 + zh: 1dd699cb84ecf034 /publish-the-web-ui-behind-a-reverse-proxy/trust-the-authority-browsers-use: - en: 907b5f90c9860733 - zh: dcbffd3f00d6c64f + en: 08e5a6cc45918876 + zh: d59178e10e915748 /publish-the-web-ui-behind-a-reverse-proxy/secure-the-external-leg: - en: a833880da5c8bbf4 - zh: 6f9bd565b7266241 + en: 2afac1f10e2d2e88 + zh: f9b4b03a5aad27e1 diff --git a/docs/user/guide/public-deployments.md b/docs/user/guide/public-deployments.md index 22bf5f8b0c..70e107fe6d 100644 --- a/docs/user/guide/public-deployments.md +++ b/docs/user/guide/public-deployments.md @@ -2,7 +2,7 @@ English | [中文](public-deployments.zh.md) -`dsh --profile web` serves the GUI over plain HTTP on a loopback port, so a browser on another machine cannot reach it, and the process knows nothing about the address you do use. A reverse proxy in front of it owns that external leg — the public host name, TLS, and the path prefix it strips before forwarding to the listener — and `--public-url` tells DSH which address browsers use: +`dsh --profile web` serves the GUI on a loopback port, so a browser on another machine cannot reach it, and the process knows nothing about the address you do use. A reverse proxy in front of it owns that external leg — the public host name, TLS, and the path prefix it strips before forwarding to the listener — and `--public-url` tells DSH which address browsers use: ```sh dsh --profile web --public-url https://app.example/ui/ --trusted-host app.example @@ -10,24 +10,28 @@ 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 - **Preserve the browser-facing `Host`.** The fence compares the received `Host` against the accepted authorities, so the proxy forwards it unchanged instead of rewriting it to the listener's address. - **Strip the mount prefix.** The listener answers origin-root routes, so a request for `/ui/api/...` must arrive as `/api/...`. - **Forward upgrades.** Every request and WebSocket upgrade the page opens must reach the listener with its `Upgrade` and `Connection` headers intact; TLS terminates on the proxy's external leg when it serves HTTPS. -- **Rewrite cookie scope.** The backend always issues host-only `Path=/` cookies without `Secure`; the proxy rewrites `Path` to the mount (`/ui/`) and adds `Secure` on its HTTPS leg. +- **Rewrite cookie scope.** A backend serving plain HTTP issues host-only `Path=/` cookies without `Secure`; the proxy then rewrites `Path` to the mount (`/ui/`) and adds `Secure` on its HTTPS leg. A backend listener serving its own TLS already marks the cookie `Secure`, so the proxy only rewrites `Path`. - **Redirect the bare mount.** `/ui/` is the only entry: it alone exchanges the launch token for the session cookie, and it or `/ui/index.html` serves the document to a browser that already holds that cookie, because the served document resolves URLs against its own directory. A request to `/ui` must arrive as `/ui/`, and the stripped backend cannot reconstruct that external path. ## Trust the authority browsers use -The fence accepts loopback plus every authority `--trusted-host` names. A browser that reaches the deployment under any other authority gets 403 for every API call, however correct the proxy is, so name the browser-visible authority with `--trusted-host`; advertising it with `--public-url` is display only and does not admit it. An entry without a port matches any port, which suits a tunnel that binds a different one each time. The fence only admits the request; the launch token in the printed URL and the signed session cookie authenticate it. +The fence accepts loopback, the listener's own bind address, and every authority `--trusted-host` names. A browser that reaches the deployment under any other authority gets 403 for every API call, however correct the proxy is, so name the browser-visible authority with `--trusted-host`; advertising it with `--public-url` is display only and does not admit it. An entry without a port matches any port, which suits a tunnel that binds a different one each time. The fence only admits the request; the launch token in the printed URL and the signed session cookie authenticate it. TLS, wherever it terminates, changes none of this: the certificate identifies the server to the browser, not the browser to the server. Neither the advertised URL nor the fence protects the listening port itself, so restrict the port to the trusted proxy or network. ## Secure the external leg -Terminate TLS at the proxy. An `http://` advertised root sends the launch token and the session cookie unencrypted, and an `https://` root encrypts only the browser-to-proxy leg. The printed URL carries a process credential, so share it only with intended users. +Terminate TLS at the proxy, on the listener itself, or on both; `--public-url` remains an advertisement. An `http://` browser-facing root exposes the launch token in plaintext. An `https://` proxy root protects the browser-to-proxy leg; encryption between proxy and listener depends on the listener's TLS configuration. -The [Web app reference](../../../packages/bundle/web-app/README.md#public-deployments) owns the `--public-url` and `--trusted-host` command-line contract and the `publicUrl` and `trustedHosts` fields. +To terminate on the listener, pass `--tls-cert` and `--tls-key`, each a path resolved against the process working directory: the certificate file holds the full chain and the key file an unencrypted PEM private key. DSH never obtains, renews, or watches certificates, and the carrier reads the files once, so replace them and reload the listener or restart the process to change them; startup fails on a missing or invalid pair and never falls back to HTTP. The browser applies its own trust store and name checks, so the certificate must cover the hostname or IP you open. The default port stays 3080. Native TLS needs no proxy, but proxy deployments and `--public-url` remain supported independently. A TLS listener marks session cookies `Secure`; keep the public browser-facing leg HTTPS so browsers can return those cookies. + +The printed URL carries a process credential, so share it only with intended users. + +The [Web app reference](../../../packages/bundle/web-app/README.md#public-deployments) documents the `--public-url`, `--trusted-host`, and `--tls-cert`/`--tls-key` command-line options. In the Web profile, `publicUrl` configures the `web-runtime` row, `trustedHosts` configures the [Connection row](../../../packages/client/connection/README.md), and `tls` configures the [webserver row](../../../docs/subsystems/web-server.md#config). diff --git a/docs/user/guide/public-deployments.zh.md b/docs/user/guide/public-deployments.zh.md index 54abc1e30a..93572f0db1 100644 --- a/docs/user/guide/public-deployments.zh.md +++ b/docs/user/guide/public-deployments.zh.md @@ -2,7 +2,7 @@ [English](public-deployments.md) | 中文 -`dsh --profile web` 在 loopback 端口上以明文 HTTP 提供 GUI,因此其他机器上的浏览器无法访问它,进程也无从得知你实际使用的地址。它前面的反向代理拥有这条外部链路——公开主机名、TLS,以及转发到监听器之前剥离的路径前缀——`--public-url` 则告诉 DSH 浏览器使用的是哪个地址: +`dsh --profile web` 在 loopback 端口上提供 GUI,因此其他机器上的浏览器无法访问它,进程也无从得知你实际使用的地址。它前面的反向代理拥有这条外部链路——公开主机名、TLS,以及转发到监听器之前剥离的路径前缀——`--public-url` 则告诉 DSH 浏览器使用的是哪个地址: ```sh dsh --profile web --public-url https://app.example/ui/ --trusted-host app.example @@ -10,24 +10,28 @@ 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` 配置字段发布同样的公告。 ## 代理必须做什么 - **保留浏览器可见的 `Host`。** 栅栏把收到的 `Host` 与被接受的 authority 比对,因此代理应原样转发,而不要改写成监听器的地址。 - **剥离挂载前缀。** 监听器应答的是 origin-root 路由,因此对 `/ui/api/...` 的请求必须以 `/api/...` 抵达。 - **转发升级请求。** 页面发出的每个请求与 WebSocket 升级都必须连同其 `Upgrade` 与 `Connection` 头抵达监听器;代理对外提供 HTTPS 时,TLS 在其外部链路上终止。 -- **改写 cookie 作用域。** 后端始终签发不带 `Secure` 的 host-only `Path=/` cookie;代理把 `Path` 改写为挂载(`/ui/`),并仅在其 HTTPS 链路上添加 `Secure`。 +- **改写 cookie 作用域。** 以明文 HTTP 提供服务的后端签发不带 `Secure` 的 host-only `Path=/` cookie;代理再把 `Path` 改写为挂载(`/ui/`),并仅在其 HTTPS 链路上添加 `Secure`。监听器自身提供 TLS 时 cookie 已带 `Secure`,代理只需改写 `Path`。 - **重定向裸挂载。** `/ui/` 是唯一入口:只有它把启动 token 换成会话 cookie;已持有该 cookie 的浏览器可由它或 `/ui/index.html` 取得文档,因为所提供的文档以自身目录解析 URL。对 `/ui` 的请求必须以 `/ui/` 抵达,而被剥离路径的后端无法重建该外部路径。 ## 信任浏览器使用的 authority -栅栏接受 loopback,以及每个由 `--trusted-host` 点名的 authority。浏览器若以其他任何 authority 访问部署,无论代理多么正确,每个 API 调用都会得到 403,因此请用 `--trusted-host` 点名浏览器可见的 authority;用 `--public-url` 公告它只是展示,并不等于接纳。不带端口的条目匹配任意端口,适合每次绑定不同端口的隧道。栅栏只放行请求;打印 URL 中的启动 token 与签名会话 cookie 才完成认证。 +栅栏接受 loopback、监听器自身的绑定地址,以及每个由 `--trusted-host` 点名的 authority。浏览器若以其他任何 authority 访问部署,无论代理多么正确,每个 API 调用都会得到 403,因此请用 `--trusted-host` 点名浏览器可见的 authority;用 `--public-url` 公告它只是展示,并不等于接纳。不带端口的条目匹配任意端口,适合每次绑定不同端口的隧道。栅栏只放行请求;打印 URL 中的启动 token 与签名会话 cookie 才完成认证。无论 TLS 在哪里终止都不改变这一切:证书只是向浏览器标识服务器,而不是向服务器标识浏览器。 无论是公告 URL 还是栅栏都不保护监听端口本身,因此请把端口限制在可信代理或网络内。 ## 保护外部链路 -在代理处终止 TLS。`http://` 公告根会以明文发送启动 token 与会话 cookie,而 `https://` 根只加密浏览器到代理这一段。打印的 URL 携带进程凭据,只应与预期用户分享。 +可以在代理处、监听器本身或两者上终止 TLS;`--public-url` 仍只是公告。面向浏览器的 `http://` 根会明文暴露启动 token。`https://` 代理根保护浏览器到代理这一段;代理与监听器之间是否加密取决于监听器的 TLS 配置。 -[Web 应用参考](../../../packages/bundle/web-app/README.zh.md#public-deployments)负责 `--public-url` 与 `--trusted-host` 的命令行约定,以及 `publicUrl` 与 `trustedHosts` 字段。 +要在监听器上终止 TLS,请传入 `--tls-cert` 与 `--tls-key`,两者各是相对进程工作目录解析的路径:证书文件包含完整证书链,密钥文件为不带口令的 PEM 私钥。DSH 从不获取、续期或监视证书,且载体只读取一次文件,因此更换文件后需重新加载监听器或重启进程;文件缺失或无效时启动失败,绝不回退到 HTTP。浏览器使用自己的信任库与名称校验,因此证书必须覆盖你所访问的 hostname 或 IP。默认端口仍为 3080。原生 TLS 不需要代理,但代理部署与 `--public-url` 仍分别受支持。TLS 监听器会给会话 cookie 加上 `Secure`;公开部署的浏览器侧链路应保持 HTTPS,才能让浏览器回传这些 cookie。 + +打印的 URL 携带进程凭据,只应与预期用户分享。 + +[Web 应用参考](../../../packages/bundle/web-app/README.zh.md#public-deployments)说明 `--public-url`、`--trusted-host` 与 `--tls-cert`/`--tls-key` 命令行选项。在 Web profile 中,`publicUrl` 配置在 `web-runtime` 行,`trustedHosts` 配置在 [Connection 行](../../../packages/client/connection/README.zh.md),`tls` 配置在 [webserver 行](../../../docs/subsystems/web-server.zh.md#config)。 diff --git a/docs/user/guide/python-sdk.i18n.yaml b/docs/user/guide/python-sdk.i18n.yaml index 1eac40d8fb..f911334f40 100644 --- a/docs/user/guide/python-sdk.i18n.yaml +++ b/docs/user/guide/python-sdk.i18n.yaml @@ -21,8 +21,8 @@ en: 592dd306b920cd83 zh: 8c22110621c12ba5 /get-started-with-the-python-sdk/install-or-define-plugins/opt-in-to-str-replace-editor: - en: c63ca1e3a99e6fe1 - zh: 2ceddea3f30d92d3 + en: 450d54b6e9e38469 + zh: f0dc06a08c073571 /get-started-with-the-python-sdk/understand-the-minimal-profile: - en: 5eaacc1bc52853c4 - zh: 5b94bfc79aac04d8 + en: 8ed0bfd3cc9cc967 + zh: a52dab4cb3dd09ea diff --git a/docs/user/guide/python-sdk.md b/docs/user/guide/python-sdk.md index 837e97aa27..438598c378 100644 --- a/docs/user/guide/python-sdk.md +++ b/docs/user/guide/python-sdk.md @@ -152,19 +152,15 @@ Another `profile` is valid when it includes `@deepseek-ai/dsh-sdk-app` or anothe ### Opt in to `str_replace_editor` -The bundled runtime includes `str_replace_editor`, but `sdk-minimal` omits it from the default Cordis tree. To use it, save this configuration as `editor.patch.yml`; `insert` adds both the editor and the filesystem provider that the minimal profile lacks: +The bundled runtime includes `str_replace_editor`, but `sdk-minimal` omits it from the default Cordis tree. To use it, save this configuration as `editor.patch.yml`; `insert` adds the editor using the existing filesystem provider: ```yaml - insert: - - id: fs-local - name: '@deepseek-ai/dsh-fs-local' - config: - cwd: !!js process.cwd() - id: tool-str-replace-editor name: '@deepseek-ai/dsh-tool-str-replace-editor' ``` -Pass `patches=("/absolute/path/to/editor.patch.yml",)` when constructing `DeepSeekHarness(profile="sdk-minimal", ...)`, or put the patch in `$DSH_HOME/profiles/sdk-minimal/cordis.patch.yml` for persistent configuration. On the next runtime launch, model requests include `str_replace_editor` beside the persistent shell. The local filesystem provider uses the runtime working directory for relative paths; like the minimal shell, it does not confine access to that directory. For the standard `sdk` profile, insert only the editor row so it uses the existing filesystem provider and policies. +Pass `patches=("/absolute/path/to/editor.patch.yml",)` when constructing `DeepSeekHarness(profile="sdk-minimal", ...)`, or put the patch in `$DSH_HOME/profiles/sdk-minimal/cordis.patch.yml` for persistent configuration. On the next runtime launch, model requests include `str_replace_editor` beside the default tools. The local filesystem provider uses the runtime working directory for relative paths; like the minimal shell, it does not confine access to that directory. The same patch works with the standard `sdk` profile. ## Understand the minimal profile @@ -172,12 +168,15 @@ Pass `patches=("/absolute/path/to/editor.patch.yml",)` when constructing `DeepSe |---|---| | System prompt | `DSH_SYSTEM_PROMPT`, falling back to `You are a helpful software engineer assistant.` | | Model in `minimal.py` | `--model`, then `DSH_MODEL`, then `deepseek-v4-flash` | -| Model-facing tool | Persistent `bash` on Linux/macOS or `pwsh` on Windows | +| Model-facing tools | Persistent `bash` on Linux/macOS or `pwsh` on Windows, `read_image`, and `working_directory` | | Shell timeout | 300 seconds | -| Runtime context and compaction | Absent | +| Optional runtime context | Absent | +| Context compaction | Automatic; summarizes older history through an additional model request | | Session persistence | Uncompressed JSONL under `/sessions` | -The profile's sole bundle inserts the complete tree over an empty root and does not include `dsh-base`; later base-profile tools therefore cannot appear implicitly. It contains the SDK protocol, one environment-configured DeepSeek adapter, local execution, and persistence, while filesystem tools, settings, managed credentials, OTel telemetry, Web tools, subagents, local instruction discovery, and compaction are absent. The [DeepSeek session-log contributor](../../../packages/session/session-log-deepseek/README.md) uploads unaccepted log events with DeepSeek requests by default, at most `maxBytes` (8 MiB) per request; set `session-log-deepseek.enabled: false` in a profile patch to disable it. It pins `danger-full-access`, so the platform-selected persistent shell can modify any path visible to the runtime; use a disposable checkout or container. +The profile's sole bundle inserts the complete tree over an empty root and does not include `dsh-base`; later base-profile tools therefore cannot appear implicitly. It contains the SDK protocol, one environment-configured DeepSeek adapter, local execution, and persistence, while text file tools, settings, managed credentials, OTel telemetry, Web tools, subagents, and local instruction discovery are absent. The [DeepSeek session-log contributor](../../../packages/session/session-log-deepseek/README.md) uploads unaccepted log events with DeepSeek requests by default, at most `maxBytes` (8 MiB) per request; set `session-log-deepseek.enabled: false` in a profile patch to disable it. It pins `danger-full-access`, so the platform-selected persistent shell can modify any path visible to the runtime; use a disposable checkout or container. + +Image reading requires an image-capable route. Automatic compaction preserves the complete Session log; see the [bundle reference](../../../packages/bundle/sdk-minimal/README.md) for model and storage effects. SDK prompt text does not execute `/compact` or other slash commands. The installed wheel still packages the full `web` profile and frontend assets. Run `dsh web` against an explicit `DSH_HOME` when a Python SDK deployment also needs the browser application; `web` is a separate CLI application and cannot serve a Python SDK client. diff --git a/docs/user/guide/python-sdk.zh.md b/docs/user/guide/python-sdk.zh.md index d7742bec58..b7a86e9860 100644 --- a/docs/user/guide/python-sdk.zh.md +++ b/docs/user/guide/python-sdk.zh.md @@ -152,19 +152,15 @@ dsh plugin --profile sdk-minimal add file:C:/work/my-plugin-bundle ### 显式启用 `str_replace_editor` -随附运行时包含 `str_replace_editor`,但 `sdk-minimal` 的默认 Cordis tree 不挂载它。要使用该工具,请将以下配置保存为 `editor.patch.yml`;`insert` 会添加 editor,以及极简 profile 缺少的文件系统后端: +随附运行时包含 `str_replace_editor`,但 `sdk-minimal` 的默认 Cordis tree 不挂载它。要使用该工具,请将以下配置保存为 `editor.patch.yml`;`insert` 会添加 editor,并使用已有的文件系统后端: ```yaml - insert: - - id: fs-local - name: '@deepseek-ai/dsh-fs-local' - config: - cwd: !!js process.cwd() - id: tool-str-replace-editor name: '@deepseek-ai/dsh-tool-str-replace-editor' ``` -构造 `DeepSeekHarness(profile="sdk-minimal", ...)` 时传入 `patches=("/absolute/path/to/editor.patch.yml",)`,或将 patch 写入 `$DSH_HOME/profiles/sdk-minimal/cordis.patch.yml` 以持久保存配置。下次运行时启动后,模型请求会在持久 shell 之外包含 `str_replace_editor`。本地文件系统后端以运行时工作目录解析相对路径;与极简 shell 一样,它不会将访问限制在该目录内。对于标准 `sdk` profile,只插入 editor 配置项,让它使用已有的文件系统后端与策略。 +构造 `DeepSeekHarness(profile="sdk-minimal", ...)` 时传入 `patches=("/absolute/path/to/editor.patch.yml",)`,或将 patch 写入 `$DSH_HOME/profiles/sdk-minimal/cordis.patch.yml` 以持久保存配置。下次运行时启动后,模型请求会在默认工具之外包含 `str_replace_editor`。本地文件系统后端以运行时工作目录解析相对路径;与极简 shell 一样,它不会将访问限制在该目录内。该 patch 也适用于标准 `sdk` profile。 ## 理解极简 profile @@ -172,12 +168,15 @@ dsh plugin --profile sdk-minimal add file:C:/work/my-plugin-bundle |---|---| | 系统提示词 | `DSH_SYSTEM_PROMPT`,未设置时为 `You are a helpful software engineer assistant.` | | `minimal.py` 的模型 | `--model`,然后是 `DSH_MODEL`,最后是 `deepseek-v4-flash` | -| 面向模型的工具 | Linux/macOS 上的持久 `bash` 或 Windows 上的 `pwsh` | +| 面向模型的工具 | Linux/macOS 上的持久 `bash` 或 Windows 上的 `pwsh`、`read_image` 和 `working_directory` | | Shell 超时 | 300 秒 | -| 运行时上下文与 compaction | 不存在 | +| 可选运行时上下文 | 不存在 | +| 上下文压缩 | 自动执行;通过额外模型请求生成较早历史的摘要 | | 会话持久化 | `/sessions` 下的未压缩 JSONL | -该 profile 的唯一组合包会在空根之上插入完整配置树,且不包含 `dsh-base`,因此基础 profile 以后新增的工具不会隐式出现。它包含 SDK 协议、一个由环境配置的 DeepSeek 适配器、本地执行与持久化;文件系统工具、settings、托管凭据、OTel 遥测、Web 工具、subagent、本地指令发现和 compaction 均不存在。[DeepSeek 会话日志贡献器](../../../packages/session/session-log-deepseek/README.zh.md)默认随 DeepSeek 请求上传未接受的日志事件,每次请求最多 `maxBytes`(8 MiB);在 profile patch 中设置 `session-log-deepseek.enabled: false` 可将其关闭。它固定使用 `danger-full-access`,因此按平台选择的持久 shell 可以修改运行时可见的任何路径;应使用一次性 checkout 或容器。 +该 profile 的唯一组合包会在空根之上插入完整配置树,且不包含 `dsh-base`,因此基础 profile 以后新增的工具不会隐式出现。它包含 SDK 协议、一个由环境配置的 DeepSeek 适配器、本地执行与持久化;文本文件工具、settings、托管凭据、OTel 遥测、Web 工具、subagent、本地指令发现均不存在。[DeepSeek 会话日志贡献器](../../../packages/session/session-log-deepseek/README.zh.md)默认随 DeepSeek 请求上传未接受的日志事件,每次请求最多 `maxBytes`(8 MiB);在 profile patch 中设置 `session-log-deepseek.enabled: false` 可将其关闭。它固定使用 `danger-full-access`,因此按平台选择的持久 shell 可以修改运行时可见的任何路径;应使用一次性 checkout 或容器。 + +图片读取需要支持图片输入的路由。自动压缩保留完整 Session 日志;模型与存储影响见[组合包参考](../../../packages/bundle/sdk-minimal/README.zh.md)。SDK 提示词文本不会执行 `/compact` 或其他斜杠命令。 已安装 wheel 仍会打包完整 `web` profile 与前端产物。如果 Python SDK 部署还需要浏览器应用,请针对显式 `DSH_HOME` 运行 `dsh web`;`web` 是独立 CLI 应用,不能为 Python SDK client 提供服务。 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 837bf1d905..3b9e5f2b36 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-root", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "license": "MIT", "private": true, "type": "module", @@ -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", @@ -238,7 +240,10 @@ "@types/js-yaml": "^4.0.9", "@types/jsdom": "^28.0.3", "@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", @@ -246,6 +251,7 @@ "@yarnpkg/cli-dist": "4.18.0", "eslint-plugin-sonarjs": "^4.2.0", "execa": "^10.0.1", + "zod": "^4.4.3", "extract-zip": "^2.0.1", "fast-check": "^4.9.0", "fflate": "^0.8.2", @@ -261,6 +267,7 @@ "micromark-extension-gfm": "^3.0.0", "oxlint": "1.81.0", "oxlint-tsgolint": "7.0.2001", + "papaparse": "5.5.3", "pnpm": "11.28.5", "publint": "^0.3.24", "semver": "^7.8.5", diff --git a/packages/AGENTS.md b/packages/AGENTS.md index 8c071dac2e..50f203586c 100644 --- a/packages/AGENTS.md +++ b/packages/AGENTS.md @@ -10,6 +10,8 @@ These package-specific rules supplement the repo-wide [conventions](../AGENTS.md - **Design Service Definitions for all current Consumers.** Keep tool-schema, Loader, UI, transport, and provider-specific behavior in the Consumer or provider; do not let one Consumer dictate the service contract ([capability-seam rationale](../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)). Inverse smell: a public service method with one internal caller — pass a private capability closure instead (`RunCodeBridgeOptions`). - **Require a current owner and need.** Tie each abstraction, state machine, option, defensive copy, and compatibility path to a current contract or production consumer, and keep behavior in its owning plugin or service. - **Require evidence for public choices.** Configurability does not justify an unsupported default, public operation set, format, or imported external concept. Use current-consumer evidence or relevant prior art; otherwise require an explicit value or defer the choice. +- **Give shared state an owner.** Hang shared state on a service or instance. A module-level cache, a singleton, a global `WeakMap`, or a `Symbol.for` / `globalThis` / `window.__X__` bypass hides that owner; add no new global `current`, `active`, or `selection` singleton, and derive context from the current scope instead. +- **Keep business rules in their own package.** A runtime, controller, manager, gateway, or API dispatch layer carries generic orchestration; a business branch belongs to an independent package and attaches through a registration surface or projected data ([where new behavior goes](../docs/architecture.md#where-new-behavior-goes)). - **Write model-facing contracts from the model's perspective.** Prompts, tool schemas, results, and diagnostics contain only task-relevant concepts, not UI, transport, or implementation vocabulary. Pin stable model-visible text verbatim and dynamic behavior through snapshots or end-to-end coverage. - **Enforce a decision in the operation that makes it.** Schema omission, prompt filtering, facades, wrappers, and listener order are not enforcement when direct or alternate callers can bypass them; test denial through the executor. - **Publish state only at its commit point.** Emit each notification and update derived state only after the operation succeeds; derive caches, prompts, UI echoes, replay, and query views from one authoritative source. diff --git a/packages/acp/acp/package.json b/packages/acp/acp/package.json index a491ae3e56..47ffa189bc 100644 --- a/packages/acp/acp/package.json +++ b/packages/acp/acp/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-acp", "description": "Automation-only Agent Client Protocol server for driving DeepSeek Harness agents over JSON-RPC stdio", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/acp/acp/tests/harness.ts b/packages/acp/acp/tests/harness.ts index 51d89dab25..12ee80b95b 100644 --- a/packages/acp/acp/tests/harness.ts +++ b/packages/acp/acp/tests/harness.ts @@ -23,7 +23,7 @@ import type { ImageAttachmentLimits, ImageAttachmentRef, SaveImageAttachment, St import { type GenerateOptions, LlmAdapter, ReasoningEffortId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' -import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import TokenMeter from '@deepseek-ai/dsh-token-meter' import * as AcpPlugin from '../src/index.ts' import type { AcpConfig } from '../src/index.ts' diff --git a/packages/api/README.i18n.yaml b/packages/api/README.i18n.yaml index 7c3e86cc1c..bbe9d4ab52 100644 --- a/packages/api/README.i18n.yaml +++ b/packages/api/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /api-remote-api-layers/packages: - en: 9bf51a5550fd4853 - zh: 4d13dd77d86f7f97 + en: 37388d921f2f47cf + zh: 24eb674c14dc2c6d /api-remote-api-layers/related-documentation: en: 507116ae09161df1 zh: f5e538ac5fdaf454 diff --git a/packages/api/README.md b/packages/api/README.md index 691a56856d..9f490b8134 100644 --- a/packages/api/README.md +++ b/packages/api/README.md @@ -28,6 +28,7 @@ The packages below provide the Remote layer; the package READMEs own the exhaust |---|---|---| | [`remotes/`](remotes/README.md) | Chooses which Host capabilities and events the Client can consume. | — | | [`gateway/`](gateway/README.md) | Carries typed unary calls, multiplexed streams with their Client uplinks, and forwarded Host events. | `ctx.typertGateway` / `ctx.remote` | +| [`remote-access/`](remote-access/README.md) | Decides which Remote methods non-owner Peers may call, filters list results, and streams each Peer's access snapshot. | `ctx.remoteAccess` / `ctx.remote.remoteAccess` | | [`job-controller/`](job-controller/README.md) | Streams one background job's observation record to the Client. | `ctx.jobController` / `ctx.remote.job` | | [`session-controller/`](session-controller/README.md) | Owns Session commands, history streams, live control state, and Agent/Session identity policy. | `ctx.sessionController` / `ctx.remote.session` | | [`settings-controller/`](settings-controller/README.md) | Owns the configuration-surface reads and writes over the settings-domain seams. | `ctx.settingsController`, `ctx.credentialsController` / `ctx.remote.settings`, `ctx.remote.credentials` | diff --git a/packages/api/README.zh.md b/packages/api/README.zh.md index 9303fbaae7..3d7ae60113 100644 --- a/packages/api/README.zh.md +++ b/packages/api/README.zh.md @@ -28,6 +28,7 @@ kind: "package-group" |---|---|---| | [`remotes/`](remotes/README.zh.md) | 决定 Client 可以消费哪些 Host 能力与事件。 | — | | [`gateway/`](gateway/README.zh.md) | 承载类型化一元调用、带 Client 上行的多路复用流,以及转发的 Host 事件。 | `ctx.typertGateway` / `ctx.remote` | +| [`remote-access/`](remote-access/README.zh.md) | 决定非 owner Peer 可以调用哪些 Remote 方法,过滤列表结果,并为每个 Peer 推送其访问快照。 | `ctx.remoteAccess` / `ctx.remote.remoteAccess` | | [`job-controller/`](job-controller/README.zh.md) | 把一个后台任务的观测 record 流式送到 Client。 | `ctx.jobController` / `ctx.remote.job` | | [`session-controller/`](session-controller/README.zh.md) | 拥有会话命令、历史记录流、实时控制状态与 Agent/Session 身份策略。 | `ctx.sessionController` / `ctx.remote.session` | | [`settings-controller/`](settings-controller/README.zh.md) | 拥有 settings 域各 seam 之上的配置界面读写。 | `ctx.settingsController`、`ctx.credentialsController` / `ctx.remote.settings`、`ctx.remote.credentials` | 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 5fc1052837..6c067afd96 100644 --- a/packages/api/account-controller/package.json +++ b/packages/api/account-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-account-controller", "description": "Expose safe account operations over authenticated Remote", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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", @@ -48,7 +50,7 @@ ], "license": "MIT", "dependencies": { - "zod": "^4.4.3" + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/api/gateway/README.i18n.yaml b/packages/api/gateway/README.i18n.yaml index e8cf3b7f4b..4b8cb2e1f4 100644 --- a/packages/api/gateway/README.i18n.yaml +++ b/packages/api/gateway/README.i18n.yaml @@ -15,11 +15,11 @@ en: d9859219cdb0f367 zh: 2a3cfa8cb786e327 /deepseek-ai-dsh-api-gateway/host-service-typertgatewayservice-ctx-key-typertgateway: - en: 5179435c09004549 - zh: c904462396531947 + en: 6019f9b47d9ab474 + zh: b72d9c378bdafffb /deepseek-ai-dsh-api-gateway/client-service-clientremote-ctx-key-remote: en: c106f0ca3e547f84 - zh: 833e30d7151c41c7 + zh: 8eadd3bffde9e49d /deepseek-ai-dsh-api-gateway/model-experience: en: 6cb309d3378f035d zh: 998042a02ee32850 @@ -27,8 +27,8 @@ en: af5abeee32f2d93b zh: b320bb727a223a13 /deepseek-ai-dsh-api-gateway/known-limitations-and-deferred-work: - en: 3ade2903f40a0a98 - zh: 9af1d557fefdbd89 + en: f817580f28d30dc2 + zh: 5262b8fbcf9d65e8 /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..e31fa33e80 100644 --- a/packages/api/gateway/README.md +++ b/packages/api/gateway/README.md @@ -30,19 +30,23 @@ Strict mode reads generated invocation descriptors from `ctx.typert.local`. Look The Host entry registers a trusted-host interceptor on Connection's shared `/api` FetchHandler. Connection passes this composite handler through its HTTP bridge; the handler dispatches claimed endpoints to Gateway and returns 404 for unclaimed requests unless an exact Fetch route owns them. Direct `invoke()` calls preserve business errors; `TypertGatewayError` is a `RemoteError` subclass whose `gateway/*` codes name the failures owned by dispatch, binding, providers, lookup, Context, arguments, codecs, and the uplink: `gateway/uplink-overflow` for an uplink whose buffered frames exceed `streamInboxBytes`, `gateway/protocol` for an uplink item after `end`, and the codec code `gateway/input-invalid` for a rejected uplink item. A resolver that refuses on policy grounds — a cold-resume failure or an ownership fence — throws its own `RemoteError`, and the code it chose reaches the caller unchanged. +Every call names the Peer it speaks for: `InvokeRemoteRequest.peer` and the `peer` argument of `wireStream.open()` are required, and the Gateway never supplies a default Peer. Dispatch from a disposed Peer fails with `gateway/peer-disposed`, for unary calls, streams, `$events`, and `$events/result` alike, and wire paths check it before they read the payload. The Host service injects `remoteAccess` and does not start without [`dsh-api-remote-access`](../remote-access/README.md). After the endpoint and argument-field checks, every call validates its JSON arguments once against their Typert-compiled types, failing with `gateway/input-invalid`, and dispatch reuses the validated values. For a call whose Peer principal is not the owner, after that validation and before lookup and Context resolution, the Gateway resolves the resources the call touches and asks `ctx.remoteAccess.decide({ principal, action, resources, args })` with the endpoint as the action and the validated arguments as `args`, or refuses with reason `resource-invalid` without asking when the resources are invalid; a refused call throws `remote-access/denied` with details `{ action, reason }`, so a refused call fails before it activates any Session. An owner call is dispatched without resource resolution or a decision. + +Resources are read from the arguments validated against their Typert-compiled types, which drop object fields those types do not declare, while lookup and Context identities keep their wire values. For each resource kind, a reader in the method's `@Remote({ resources })` or `@RemoteScope(key, { resources })` options wins; it is called with the method's positional arguments, where lookup positions hold wire identities and the cancellation position holds the call's signal, and is read from the class metadata of the root Service instance. Otherwise every lookup parameter whose provider declares that kind through `resource` contributes its wire identity, an omitted optional one contributing none, and a Context method whose Host Context adapter declares that kind contributes its Context identity, read from the arguments before the Context is resolved. Otherwise the kind's default field registered in `typert.resources` is read from a top-level argument of that name or, failing that, from the first object argument. A reader that throws or returns an empty list, a default field holding an array, or an identity, including a Context identity, that is not a non-empty string makes the resolution `invalid`; a call that names no resource touches the `global` resource alone, and a call that names resources touches only those. A forwarded event carries every resource its entry declares, so there a reader returning `undefined` also makes the resolution `invalid`, while an entry without readers touches `global`. + 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. -Every stream also carries a Client-to-Host uplink on the same logical stream. A method declares the uplink item type as the second type argument of its return type, `RemoteStream` from [`dsh-typert-protocol`](../../typert/protocol/README.md); `In` defaults to `never`, and a method that returns `Iterable`, `AsyncIterable`, or `RemoteStream` declares that it reads none. The running method reads its call as `this.ctx.invocation`: the Gateway derives the receiver from a Context carrying that `RemoteInvocation` — `request`, `service`, `peer`, `signal`, and `uplink()` — so nothing enters the parameter list, and `ctx.invocation` is `undefined` on a Context no Remote call derived. `uplink()` is available once per call. With a descriptor codec it decodes every item before delivery; without one — an SRC method, or a method whose `In` is `never` — it delivers JSON-safe `unknown` values. The Client sends each item as an `item` frame on the open logical stream, a top-level `undefined` item as an `item` frame without `value`, and its half-close as an `end` frame; the method observes the half-close as the end of the `uplink()` iteration and cancellation through `signal`. A rejected item fails the whole stream with `gateway/input-invalid` (field `uplink`). Uplink items are validated one by one at the Host because they arrive from the browser; downlink items are values the Host method produced and pass through unchecked. When the method finishes its downlink the Gateway returns the uplink iterator and drops unread items; items sent to a method that never takes its uplink wait in the inbox until then. Each logical stream buffers at most `streamInboxBytes` (262144 by default) of uplink frame bytes; overflow fails the stream with `gateway/uplink-overflow`, and an item after `end` fails it with `gateway/protocol`, in both cases without closing the socket. `item`, `end`, and `cancel` frames for a stream id the Host has already finished are dropped; only a duplicate `open` closes the socket. Gateway-owned streams such as `$events` return their uplink as soon as they open, so their `item` frames are dropped instead of buffered. A unary method may also call `uplink()`; its items are readable only while the method runs. Every stream speaks for the operator Peer: a WebSocket's streams for the Peer Connection admitted at upgrade, whose scope disposal closes the socket, and an in-process carrier's for the operator directly. +Every stream also carries a Client-to-Host uplink on the same logical stream. A method declares the uplink item type as the second type argument of its return type, `RemoteStream` from [`dsh-typert-protocol`](../../typert/protocol/README.md); `In` defaults to `never`, and a method that returns `Iterable`, `AsyncIterable`, or `RemoteStream` declares that it reads none. The running method reads its call as `this.ctx.invocation`: the Gateway derives the receiver from a Context carrying that `RemoteInvocation` — `request`, `service`, `peer`, `signal`, and `uplink()` — so nothing enters the parameter list, and `ctx.invocation` is `undefined` on a Context no Remote call derived. `uplink()` is available once per call. With a descriptor codec it decodes every item before delivery; without one — an SRC method, or a method whose `In` is `never` — it delivers JSON-safe `unknown` values. The Client sends each item as an `item` frame on the open logical stream, a top-level `undefined` item as an `item` frame without `value`, and its half-close as an `end` frame; the method observes the half-close as the end of the `uplink()` iteration and cancellation through `signal`. A rejected item fails the whole stream with `gateway/input-invalid` (field `uplink`). Uplink items are validated one by one at the Host because they arrive from the browser; downlink items are values the Host method produced and pass through unchecked. When the method finishes its downlink the Gateway returns the uplink iterator and drops unread items; items sent to a method that never takes its uplink wait in the inbox until then. Each logical stream buffers at most `streamInboxBytes` (262144 by default) of uplink frame bytes; overflow fails the stream with `gateway/uplink-overflow`, and an item after `end` fails it with `gateway/protocol`, in both cases without closing the socket. `item`, `end`, and `cancel` frames for a stream id the Host has already finished are dropped; only a duplicate `open` closes the socket. Gateway-owned streams such as `$events` return their uplink as soon as they open, so their `item` frames are dropped instead of buffered. A unary method may also call `uplink()`; its items are readable only while the method runs. Every stream speaks for an explicitly named Peer: a WebSocket's streams for the Peer Connection admitted at upgrade, whose scope disposal closes the socket, and an in-process carrier's for the Peer its caller passes. A stream method's `signal` also aborts when that Peer is disposed, so the stream ends with `gateway/cancelled`, and a `$events` stream ends with its Peer; a unary call already running is not cancelled. Stream cancellation and stopping keep read-local state, not a history of delivered items, on the Host downlink, Host uplink, and Client uplink pump. Completing the downlink also wakes pending uplink reads. -Host composition can register one application event source through `registerRemoteEvents()`. Gateway reserves the internal `$events` logical endpoint for that source, accepts only empty `args`, and aborts streams opened by the registration when the source is withdrawn. API Remotes owns the event selection, argument validation, per-Client queues, and the Host home sent in the opening `{ type: 'ready', clientId, host: { home } }` frame. Its source factory attaches incremental listeners synchronously, so the Client publishes the generation and starts baseline reads only after incremental delivery is ready. +Host composition can register one application event source through `registerRemoteEvents()`. Gateway reserves the internal `$events` logical endpoint for that source, accepts only empty `args`, and aborts streams opened by the registration when the source is withdrawn. API Remotes owns the event selection, argument validation, per-Client queues, and the Host home sent in the opening `{ type: 'ready', clientId, host: { home } }` frame. Its source factory attaches incremental listeners synchronously, so the Client publishes the generation and starts baseline reads only after incremental delivery is ready. A `$events` stream whose Peer principal is not the owner never receives a scoped waterfall it could answer; it receives a broadcast emit frame, whole and untrimmed, only when `ctx.remoteAccess.decide({ principal, action: 'event:', resources })` allows it on the resources the frame's readers name, or on `global` for a frame without readers; the resources are resolved once per frame, a frame whose resources are invalid reaches no non-owner stream without a decision, and a denied frame is dropped for that stream alone. An `$events/result` reply from such a Peer fails with `gateway/invocation-unavailable`. -`hasLiveClient()` checks the existing `$events` records for an uncancelled stream. A cancelled stream does not count even while its iterator is still awaiting cleanup; a bare WebSocket does not count. This synchronous observation does not guarantee delivery or Client provider readiness. +`hasLiveClient()` checks the existing `$events` records for an uncancelled stream whose Peer principal is the owner, the only kind that can answer a forwarded waterfall. A cancelled stream does not count even while its iterator is still awaiting cleanup; a bare WebSocket does not count. This synchronous observation does not guarantee delivery or Client provider readiness. ## Client service: `ClientRemote` (ctx key: `remote`) @@ -86,8 +90,9 @@ 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. -- 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. +- `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. +- The Gateway exposes each WebSocket stream's inbox capacity and JSON envelope cost through `invocation.uplinkWindow`; carriers without an encoded-frame inbox limit leave it absent. Domain protocols can advertise this window and use acknowledgements to bound in-flight bytes. The Gateway itself does not issue credits: 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..4160546db6 100644 --- a/packages/api/gateway/README.zh.md +++ b/packages/api/gateway/README.zh.md @@ -30,19 +30,23 @@ kind: "package-reference" Connection 可用时,Host 入口会在 Connection 共享的 `/api` FetchHandler 上注册 trusted-host interceptor。Connection 把这个复合 handler 交给 HTTP bridge;handler 将已认领 endpoint 分发给 Gateway,未认领且没有精确 Fetch 路由负责的请求返回 404。直接调用 `invoke()` 会保留业务错误;`TypertGatewayError` 是 `RemoteError` 的子类,其 `gateway/*` 码命名了分发、绑定、提供方、查找、Context、参数、编解码器以及上行各自负责的故障:缓冲帧超过 `streamInboxBytes` 的上行报 `gateway/uplink-overflow`,`end` 之后的上行项报 `gateway/protocol`,被 codec 拒绝的上行项报编解码码 `gateway/input-invalid`。因策略而拒绝的解析器——冷恢复失败或 ownership fence——抛出自己的 `RemoteError`,它选定的码原样到达调用方。 +每次调用都指明它所代表的 Peer:`InvokeRemoteRequest.peer` 与 `wireStream.open()` 的 `peer` 参数都是必填项,Gateway 从不提供默认 Peer。来自已释放 Peer 的分发以 `gateway/peer-disposed` 失败,一元调用、流、`$events` 与 `$events/result` 一律如此,wire 路径在读取 payload 之前检查。Host 服务注入 `remoteAccess`,没有 [`dsh-api-remote-access`](../remote-access/README.zh.md) 就不启动。每次调用在 endpoint 与参数字段检查之后按 Typert 编译类型校验一次 JSON 参数,失败为 `gateway/input-invalid`,分派复用校验后的值。对 Peer 的 principal 不是 owner 的调用,Gateway 在该校验之后、lookup 与 Context 解析之前解析调用访问的资源,并以端点为 action、校验后的参数为 `args` 询问 `ctx.remoteAccess.decide({ principal, action, resources, args })`,资源非法时不询问而以原因 `resource-invalid` 拒绝;被拒的调用抛出 details 为 `{ action, reason }` 的 `remote-access/denied`,因此被拒绝的调用在激活任何 Session 之前就失败。owner 的调用不解析资源、不询问判定即分派。 + +资源从经 Typert 编译类型校验后的参数中读取,校验会移除类型未声明的对象字段,lookup 与 Context 身份保持 wire 值。对每个资源种类,方法 `@Remote({ resources })` 或 `@RemoteScope(key, { resources })` options 中的读取函数优先;它以方法的位置参数调用(lookup 位为 wire 身份,取消参数位为调用的 signal),从根 Service 实例的类元数据读取。否则 provider 经 `resource` 声明了该种类的每个 lookup 参数贡献其 wire 身份,省略的可选 lookup 参数不贡献;Host Context adapter 声明了该种类的 Context 方法贡献其 Context 身份,在解析 Context 之前直接从参数读取。再否则从同名顶层参数读取该种类在 `typert.resources` 中登记的默认字段,没有同名参数时读第一个对象参数的同名字段。读取函数抛错或返回空列表、默认字段读到数组、或某个身份(含 Context 身份)不是非空字符串时,解析结果为 `invalid`;不指明任何资源的调用只访问 `global` 资源,指明了资源的调用只访问这些资源。转发事件携带其条目声明的每个资源,因此在事件路径上读取函数返回 `undefined` 同样使解析结果为 `invalid`,而没有读取函数的条目访问 `global`。 + 支持取消的 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 会立即注册,并自行负责启动顺序;进程内调用不变。 -每条流还在同一条逻辑流上携带从 Client 到 Host 的上行。方法把上行项类型声明为返回类型的第二个类型参数——来自 [`dsh-typert-protocol`](../../typert/protocol/README.zh.md) 的 `RemoteStream`;`In` 缺省为 `never`,返回 `Iterable`、`AsyncIterable` 或 `RemoteStream` 的方法即声明自己不读上行。运行中的方法通过 `this.ctx.invocation` 读取本次调用:Gateway 从携带该 `RemoteInvocation`(`request`、`service`、`peer`、`signal` 与 `uplink()`)的 Context 派生接收者,因此没有任何东西进入参数列表,而非 Remote 调用派生的 Context 上 `ctx.invocation` 为 `undefined`。`uplink()` 每次调用只能取一次。描述符带 codec 时它在交付前逐项解码;不带时——SRC 方法,或 `In` 为 `never` 的方法——它交付经 JSON 安全校验的 `unknown` 值。Client 在已打开的逻辑流上把每一项作为 `item` 帧发送(顶层 `undefined` 项是不带 `value` 的 `item` 帧),以 `end` 帧表示半关闭;方法通过 `uplink()` 迭代结束感知半关闭,通过 `signal` 感知取消。被拒绝的项使整条流以 `gateway/input-invalid`(字段 `uplink`)失败。上行项在 Host 逐项校验,因为它们来自浏览器;下行项是 Host 方法产出的值,不经校验原样透传。方法结束下行时 Gateway 调用 uplink 迭代器的 return 并丢弃未读的项;发给从未取用 uplink 的方法的项在 inbox 里等到那时为止。每条逻辑流最多缓冲 `streamInboxBytes`(默认 262144)字节的上行帧;超限使流以 `gateway/uplink-overflow` 失败,`end` 之后的项使流以 `gateway/protocol` 失败,两种情况都不关闭 socket。发给 Host 已结束的流 id 的 `item`、`end` 与 `cancel` 帧被丢弃;只有重复的 `open` 会关闭 socket。`$events` 这类 Gateway 自有的流在打开时立即 return 其 uplink,因此它们的 `item` 帧被丢弃而不缓冲。一元方法也可以调用 `uplink()`;其项只在方法运行期间可读。每条流都代表操作者 Peer:WebSocket 上的流代表 Connection 在升级时接纳的 Peer,该 scope 释放时 socket 关闭;进程内载体的流直接代表操作者。 +每条流还在同一条逻辑流上携带从 Client 到 Host 的上行。方法把上行项类型声明为返回类型的第二个类型参数——来自 [`dsh-typert-protocol`](../../typert/protocol/README.zh.md) 的 `RemoteStream`;`In` 缺省为 `never`,返回 `Iterable`、`AsyncIterable` 或 `RemoteStream` 的方法即声明自己不读上行。运行中的方法通过 `this.ctx.invocation` 读取本次调用:Gateway 从携带该 `RemoteInvocation`(`request`、`service`、`peer`、`signal` 与 `uplink()`)的 Context 派生接收者,因此没有任何东西进入参数列表,而非 Remote 调用派生的 Context 上 `ctx.invocation` 为 `undefined`。`uplink()` 每次调用只能取一次。描述符带 codec 时它在交付前逐项解码;不带时——SRC 方法,或 `In` 为 `never` 的方法——它交付经 JSON 安全校验的 `unknown` 值。Client 在已打开的逻辑流上把每一项作为 `item` 帧发送(顶层 `undefined` 项是不带 `value` 的 `item` 帧),以 `end` 帧表示半关闭;方法通过 `uplink()` 迭代结束感知半关闭,通过 `signal` 感知取消。被拒绝的项使整条流以 `gateway/input-invalid`(字段 `uplink`)失败。上行项在 Host 逐项校验,因为它们来自浏览器;下行项是 Host 方法产出的值,不经校验原样透传。方法结束下行时 Gateway 调用 uplink 迭代器的 return 并丢弃未读的项;发给从未取用 uplink 的方法的项在 inbox 里等到那时为止。每条逻辑流最多缓冲 `streamInboxBytes`(默认 262144)字节的上行帧;超限使流以 `gateway/uplink-overflow` 失败,`end` 之后的项使流以 `gateway/protocol` 失败,两种情况都不关闭 socket。发给 Host 已结束的流 id 的 `item`、`end` 与 `cancel` 帧被丢弃;只有重复的 `open` 会关闭 socket。`$events` 这类 Gateway 自有的流在打开时立即 return 其 uplink,因此它们的 `item` 帧被丢弃而不缓冲。一元方法也可以调用 `uplink()`;其项只在方法运行期间可读。每条流都代表一个显式指明的 Peer:WebSocket 上的流代表 Connection 在升级时接纳的 Peer,该 scope 释放时 socket 关闭;进程内载体的流代表其调用方传入的 Peer。该 Peer 释放时,流方法的 `signal` 也随之中止,流以 `gateway/cancelled` 结束,`$events` 流也随其 Peer 结束;已在运行的一元调用不会被取消。 Host 下行、Host 上行和 Client 上行泵的取消与停止状态归属单次读取,不保留已交付项的历史。下行结束也会唤醒尚未完成的上行读取。 -Host 组合可通过 `registerRemoteEvents()` 注册唯一的应用事件 source。Gateway 为它保留内部 `$events` logical endpoint,只接受空 `args`,并在 source 撤回时中止该注册打开的流。事件名单、参数校验、每个 Client 的队列及 opening `{ type: 'ready', clientId, host: { home } }` frame 中的 Host home 由 API Remotes 拥有。source factory 在返回 iterable 前同步挂好增量 listener,因此 Client 只在增量投递就绪后发布 generation 并开始 baseline 读取。 +Host 组合可通过 `registerRemoteEvents()` 注册唯一的应用事件 source。Gateway 为它保留内部 `$events` logical endpoint,只接受空 `args`,并在 source 撤回时中止该注册打开的流。事件名单、参数校验、每个 Client 的队列及 opening `{ type: 'ready', clientId, host: { home } }` frame 中的 Host home 由 API Remotes 拥有。source factory 在返回 iterable 前同步挂好增量 listener,因此 Client 只在增量投递就绪后发布 generation 并开始 baseline 读取。Peer 的 principal 不是 owner 的 `$events` 流从不收到它可以作答的 scoped waterfall(瀑布式事件);只有当 `ctx.remoteAccess.decide({ principal, action: 'event:', resources })` 在该帧读取函数指明的资源上(帧没有读取函数时为 `global`)允许时,才整条、不裁剪地收到广播 emit 帧;每帧只解析一次资源,资源非法的帧不经判定即不送达任何非 owner 流,被拒的帧只对该流丢弃。这类 Peer 的 `$events/result` 回复以 `gateway/invocation-unavailable` 失败。 -`hasLiveClient()` 检查已有 `$events` 记录中是否有未取消的流。已取消的流即使尚未完成 iterator 清理也不计入,单独的 WebSocket 也不计入。这一同步观察不保证后续投递成功或 Client Provider 已就绪。 +`hasLiveClient()` 检查已有 `$events` 记录中是否有 Peer principal 为 owner 的未取消流,只有这类流能回答转发的 waterfall。已取消的流即使尚未完成 iterator 清理也不计入,单独的 WebSocket 也不计入。这一同步观察不保证后续投递成功或 Client Provider 已就绪。 ## Client 服务:`ClientRemote`(ctx key:`remote`) @@ -59,7 +63,7 @@ Host 组合可通过 `registerRemoteEvents()` 注册唯一的应用事件 source `ctx.remote.$stream()` 返回跨越多个物理载体代次的单消费方 `RemoteStream`。Host 仍在线时,它允许一次立即重试;Host 离线时,它等待下一代连接,并为每个流项标注物理代次。领域消费方校验并接受各代次的 opening value;业务与协议错误仍然终止流。一切终态失败离开本面时都是 `RemoteError`,包括重试耗尽和在 opening value 之前就结束的代次,因此流消费方与一元调用方用同一种方式判别。`RemoteStreamCarrierError` 命名的是可重试的物理丢失,它只作为 `carrierFailed` 回调参数到达领域,绝不作为终态结果。`RemoteSnapshotStream` 在此之上规定每代由一个初始快照和后续 delta 组成。`RemoteJournalStream` 基于领域提供的 entry 闭区间提供 follow-before-page、分页、重连追赶与缺口修复;它丢弃完整重复项,并拒绝缺口、倒置区间和部分重叠。领域还可以携带无 cursor 的通知:通知绝不推进或修复持久 cursor,在缺口修复期间收到的通知只会在 replacement page 提交后发布。若更新代次取代该修复,旧代次 held notification 会与其 page 一同丢弃。对任一种流执行 dispose(资源释放)时,系统会取消该流的请求,并在活动 iterator 完全停止后完成资源释放。 -`ctx.remote.$on()` 订阅一条被转发的 Host 事件。它的合法键恰好等于 Host 装配声明的转发选择,listener 类型就是事件所属包自己的 Cordis `Events` 声明,因此不存在会与之漂移的第二份签名。每个订阅归属调用方 fiber,并随该 fiber 一起消失。Client Remote 服务激活时就把 `$events` pump 注册为 Connection generation source,无论当前是否存在 `$on` listener。浏览器使用 Remote mux,进程内组合使用 `connection.rpc.open`;opening `ready` 项建立 Connection generation 并提供 Host 信息。物理 carrier 失败、Remote 流故障、意外正常结束、非 ready 首项或畸形事件项都会终止该 generation,由 Connection 按持续且间隔封顶的带抖动指数退避重开。普通通知按注册顺序运行并隔离 listener 失败;Agent-scoped waterfall(瀑布式事件)允许 listener 返回结果、调用 `next()` 或拒绝,Gateway 再通过现有 HTTP 一元载体回送该结果。 +`ctx.remote.$on()` 订阅一条被转发的 Host 事件。它的合法键恰好等于 Host 装配声明的转发选择,listener 类型就是事件所属包自己的 Cordis `Events` 声明,因此不存在会与之漂移的第二份签名。每个订阅归属调用方 fiber,并随该 fiber 一起消失。Client Remote 服务激活时就把 `$events` pump 注册为 Connection generation source,无论当前是否存在 `$on` listener。浏览器使用 Remote mux,进程内组合使用 `connection.rpc.open`;opening `ready` 项建立 Connection generation 并提供 Host 信息。物理 carrier 失败、Remote 流故障、意外正常结束、非 ready 首项或畸形事件项都会终止该 generation,由 Connection 按持续且间隔封顶的带抖动指数退避重开。普通通知按注册顺序运行并隔离 listener 失败;Agent-scoped waterfall 允许 listener 返回结果、调用 `next()` 或拒绝,Gateway 再通过现有 HTTP 一元载体回送该结果。 Client waterfall 的 Context 解析保持同步。解析器可以返回借用的 Context 或 `TypertOwnedValue`;Gateway 仅在处理器使用和回复结算均结束后释放 owned value。Context 解析失败保留既有的记录错误并委托语义,处理器失败产生拒绝回复。取消会抑制迟到回复,但不会释放处理器仍在使用的 Context。每个 handler 都必须响应 `request.signal` 并在取消后结束;插件销毁与 Connection generation 替换会等待未结束的 handler 结算。Session Context 的获取本身不执行历史 I/O。 @@ -86,8 +90,9 @@ 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 会终止连接;如果部署的事件循环或网络可能停顿超过该间隔,必须调大此配置。 -- 上行除了有界的 Host inbox 之外没有流控:Client 发送快于方法读取,或发给从未取用 uplink 的方法时,其流以 `gateway/uplink-overflow` 失败;上行项不会跨载体代际重放,需要恢复上行的领域在重开的请求里自带确认游标。 +- `websocketHeartbeatIntervalMs` 同时是 Ping 周期和活动截止时间。对端连续两个周期没有活动时,Host 会终止连接;如果部署的事件循环或网络可能停顿超过该间隔,必须调大此配置。 +- 排队写入完成只说明 TCP 对端确认了数据。经过带缓冲的反向代理时,该对端是代理,因此持续下行期间 Client 消失,要等代理不再接收数据后才会被检测到。 +- Gateway 通过 `invocation.uplinkWindow` 提供每条 WebSocket 流的 inbox 容量与 JSON 封装开销;没有编码帧 inbox 限额的载体省略该字段。领域协议可以公布该窗口并通过确认约束在途字节数。Gateway 本身不发放额度: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 98040a54b2..8e4684fe05 100644 --- a/packages/api/gateway/package.json +++ b/packages/api/gateway/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-gateway", "description": "Typert Remote Host dispatcher and Client API endpoint", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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", @@ -65,10 +67,10 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:*" }, "peerDependencies": { - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-client-connection": "workspace:*" + "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { + "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-cmdline": "workspace:*", "@deepseek-ai/dsh-client-connection": "workspace:*", @@ -78,6 +80,6 @@ "@deepseek-ai/dsh-util-crypto": "workspace:*", "@types/ws": "^8.18.1", "@deepseek-ai/cordis": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" } } diff --git a/packages/api/gateway/src/access.ts b/packages/api/gateway/src/access.ts new file mode 100644 index 0000000000..d85ebb3e65 --- /dev/null +++ b/packages/api/gateway/src/access.ts @@ -0,0 +1,172 @@ +/** + * Resource resolution for non-owner access decisions: the resources one call + * or one forwarded event touches, read from Typert-validated arguments before + * any lookup or Context resolves them. + * @module @deepseek-ai/dsh-api-gateway/src/access + */ + +import type { + InvocationDescriptor, + RemoteAccessResource, + TypertRegistryContract, + TypertResourceReader, +} from '@deepseek-ai/dsh-typert-protocol' + +const GLOBAL: readonly RemoteAccessResource[] = Object.freeze([Object.freeze({ kind: 'global' })]) + +/** Resource ids one source produced for a kind, or `invalid` for a malformed value. */ +type ResourceIds = readonly unknown[] | 'invalid' + +/** + * Resolve the resources one call touches. For each resource kind, a + * `resources` reader of the method wins; otherwise every lookup parameter + * whose provider declares the kind contributes its wire resource id, and so + * does the Context identity of a Context method whose Host adapter declares + * the kind; otherwise the kind's default field registered in + * `typert.resources` is read from a top-level argument or, failing that, + * from the first object argument. + * @param typert - registry holding default fields, lookup providers, and Host Context adapters. + * @param readers - the method's `resources` readers, or `undefined` when it declares none. + * @param descriptor - receiver, parameter order, lookups, and cancellation slot of the method. + * @param args - named arguments matched to the descriptor's field set: JSON + * arguments as their Typert codecs validated them, lookup and Context + * identities as wire values. + * @param signal - value placed in the cancellation slot of the positional arguments. + * @returns the touched resources, the global resource alone when none; + * `undefined` when the resources are invalid: a reader throws or returns + * an empty list, a default field holds an array, or a resource id is not a + * non-empty string. + */ +export function callResources( + typert: Pick, + readers: Readonly> | undefined, + descriptor: Pick, + args: Readonly>, + signal: AbortSignal, +): readonly RemoteAccessResource[] | undefined { + // Each later source replaces an earlier one for its kind and keeps the kind's position. + const sources = new Map ResourceIds>() + for (const { kind, field } of typert.resources.entries()) { + sources.set(kind, () => { + // A default field names exactly one resource id; only a reader may return several. + const id = defaultFieldId(descriptor, args, field) + return Array.isArray(id) ? 'invalid' : id === undefined ? [] : [id] + }) + } + for (const [kind, ids] of lookupResources(typert, descriptor, args)) { + sources.set(kind, () => ids) + } + let positional: readonly unknown[] | undefined + for (const [kind, reader] of Object.entries(readers ?? {})) { + sources.set(kind, () => { + positional ??= [ + ...descriptor.parameters.map(parameter => args[parameter.wire]), + ...descriptor.cancellation === undefined ? [] : [signal], + ] + return read(reader, positional, []) + }) + } + const resources: RemoteAccessResource[] = [] + for (const [kind, ids] of sources) { + if (!collect(resources, kind, ids())) return undefined + } + return resources.length === 0 ? GLOBAL : resources +} + +/** + * Resolve the resources one forwarded event notification touches. An event + * carries every resource it declares, so a reader returning `undefined` + * makes the notification invalid instead of a global one. + * @param readers - the event entry's declared readers, or `undefined` when it declares none. + * @param args - the event's validated JSON arguments, passed to each reader as its positional arguments. + * @returns the global resource alone without readers, including an empty + * reader set; otherwise the touched resources; `undefined` when the + * resources are invalid: a resource id is missing or malformed. + */ +export function eventResources( + readers: Readonly> | undefined, + args: readonly unknown[], +): readonly RemoteAccessResource[] | undefined { + const declared = Object.entries(readers ?? {}) + if (declared.length === 0) return GLOBAL + const resources: RemoteAccessResource[] = [] + for (const [kind, reader] of declared) { + if (!collect(resources, kind, read(reader, args, 'invalid'))) return undefined + } + return resources +} + +/** + * The resource ids lookup parameters and the Context identity name, per + * resource kind: the Context identity first, then lookup parameters in order. + * An optional lookup parameter the call omits names no resource id; the + * Context identity is required. + */ +function lookupResources( + typert: Pick, + descriptor: Pick, + args: Readonly>, +): ReadonlyMap { + const ids = new Map() + const add = (kind: string, id: unknown): void => { + const list = ids.get(kind) + if (list === undefined) ids.set(kind, [id]) + else list.push(id) + } + const receiver = descriptor.invocation + if (receiver.kind === 'context') { + const kind = typert.contexts.getHost(receiver.context)?.resource + // oxlint-disable-next-line typescript/no-unnecessary-condition -- domain packages merge resource kinds into TypertResourceMap. + if (kind !== undefined) add(kind, args[receiver.wire]) + } + for (const parameter of descriptor.parameters) { + if (parameter.lookup === undefined) continue + const kind = typert.lookups.get(parameter.lookup)?.resource + const id = args[parameter.wire] + // oxlint-disable-next-line typescript/no-unnecessary-condition -- domain packages merge resource kinds into TypertResourceMap. + if (kind !== undefined && id !== undefined) add(kind, id) + } + return ids +} + +/** Run one reader with spread positional arguments: `undefined` yields `absent`, a list names several and must not be empty. */ +function read(reader: TypertResourceReader, args: readonly unknown[], absent: ResourceIds): ResourceIds { + let value: unknown + try { + value = reader(...args) + } catch { + // Any reader error means it cannot name its resources, so they are invalid. + return 'invalid' + } + if (value === undefined) return absent + if (!Array.isArray(value)) return [value] + return value.length === 0 ? 'invalid' : value +} + +/** Append one kind's resource ids; false when any is malformed. */ +function collect(resources: RemoteAccessResource[], kind: string, ids: ResourceIds): boolean { + if (ids === 'invalid') return false + for (const id of ids) { + if (typeof id !== 'string' || id.length === 0) return false + // Kinds come from registrations, lookups, Context adapters, and reader keys, all typed by the merged resource map. + resources.push({ kind, id } as RemoteAccessResource) + } + return true +} + +/** The default field: a top-level argument, else that field of the first object argument. */ +function defaultFieldId( + descriptor: Pick, + args: Readonly>, + field: string, +): unknown { + if (descriptor.parameters.some(parameter => parameter.wire === field)) return args[field] + for (const parameter of descriptor.parameters) { + const value = args[parameter.wire] + if (typeof value !== 'object' || value === null || Array.isArray(value)) continue + if (!Object.hasOwn(value, field)) return undefined + const id: unknown = Reflect.get(value, field) + return id + } + return undefined +} diff --git a/packages/api/gateway/src/index.ts b/packages/api/gateway/src/index.ts index e97a065076..294fe78698 100644 --- a/packages/api/gateway/src/index.ts +++ b/packages/api/gateway/src/index.ts @@ -7,11 +7,12 @@ import { randomUUID } from 'node:crypto' import { Context, Service, symbols } from '@deepseek-ai/cordis' -import { - OperatorPeer, - type ConnectionRpcAttachment, - type ConnectionRpcHandler, +import type { + ConnectionRpcAttachment, + ConnectionRpcHandler, } from '@deepseek-ai/dsh-client-connection' +import type { RemoteAccessDecision } from '@deepseek-ai/dsh-api-remote-access' +import { callResources, eventResources } from './access.ts' import { Deque } from '@deepseek-ai/dsh-deque' import type { WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' @@ -26,7 +27,10 @@ import { type InvocationDescriptor, type InvocationParameterDescriptor, type PeerScope, + type Principal, + type RemoteAccessResource, type RemoteInvocation, + type RemoteMethodMarker, type TypertCodec, type TypertGatewayBinding, } from '@deepseek-ai/dsh-typert-protocol' @@ -100,6 +104,7 @@ interface PreparedInvocation { /** Carrier inputs `GatewayInvocation.uplink()` decodes on first use. */ interface UplinkSource { + readonly window: RemoteInvocation['uplinkWindow'] /** Carrier items; an immediately ended iterable when the carrier has none. */ readonly source: AsyncIterable /** Descriptor codec, or the JSON-safety codec when the descriptor declares no uplink. */ @@ -120,6 +125,10 @@ interface RemoteEventClient { readonly queue: RemoteEventQueue readonly signal: AbortSignal readonly deliveries: Map + /** The stream's Peer principal: only the owner answers scoped waterfalls and receives every broadcast. */ + readonly principal: Principal + /** Only owner streams receive scoped waterfalls they could answer; other Peers receive admitted broadcasts only. */ + readonly answers: boolean } interface PendingRemoteEvent { @@ -197,7 +206,7 @@ export class TypertGatewayError extends RemoteError { * @typert service typertGateway */ export class TypertGatewayService extends Service implements TypertGateway { - static inject = ['typert'] + static inject = ['typert', 'remoteAccess'] static Config: z = z.object({ websocketHeartbeatIntervalMs: z.number().step(1).min(1).max(MAX_TIMER_DELAY_MS) .default(DEFAULT_WEBSOCKET_HEARTBEAT_INTERVAL_MS), @@ -212,7 +221,6 @@ export class TypertGatewayService extends Service implements TypertGateway { } private srcClaims: ReadonlySet | undefined - private inProcessOperator: PeerScope | undefined private remoteEvents: RegisteredRemoteEventSource | undefined private readonly remoteEventClients = new Map() private readonly pendingRemoteEvents = new Map() @@ -240,8 +248,8 @@ export class TypertGatewayService extends Service implements TypertGateway { ctx.inject(['connection', 'webServer'], (webCtx) => { const listen = (): void => { const mux = new RemoteStreamMuxServer( - (endpoint, payload, uplink, peer, control) => - this.openWireStream(endpoint, payload, uplink, peer, control.signal, control), + (endpoint, payload, uplink, peer, control, window) => + this.openWireStream(endpoint, payload, uplink, peer, control.signal, control, window), this.wireStream.failure, resolved.websocketHeartbeatIntervalMs, resolved.streamInboxBytes, @@ -278,12 +286,12 @@ export class TypertGatewayService extends Service implements TypertGateway { } /** - * Check for an active Client event stream. - * @returns whether a stream is open and has not been cancelled. + * Check for an active owner Client event stream, the only kind that can answer forwarded waterfalls. + * @returns whether an owner stream is open and has not been cancelled. */ hasLiveClient(): boolean { for (const client of this.remoteEventClients.values()) { - if (!client.signal.aborted) return true + if (client.answers && !client.signal.aborted) return true } return false } @@ -331,6 +339,18 @@ export class TypertGatewayService extends Service implements TypertGateway { return this.srcClaims.has(endpoint) } + /** + * The `resources` readers of a method, read from the root Service's class + * metadata so a Context method's receiver is not resolved before access is + * decided; `undefined` when the Service is absent or the method declares none. + */ + private resourceReaders(descriptor: InvocationDescriptor): RemoteMethodMarker['resources'] { + const receiver: unknown = this.ctx.get(descriptor.service) + if (!isObject(receiver)) return undefined + const member = descriptor.implementation ?? descriptor.method + return remoteMethods(originalOf(receiver)).find(marker => marker.method === member)?.resources + } + private collectSrcClaims(): ReadonlySet { const claims = new Set() for (const [serviceKey, definition] of Object.entries(this.ctx.reflect.props)) { @@ -429,6 +449,11 @@ export class TypertGatewayService extends Service implements TypertGateway { ): Promise { if (endpoint === REMOTE_EVENT_RESULT_ENDPOINT) { try { + assertPeerLive(peer, endpoint) + // oxlint-disable-next-line typescript/no-unnecessary-condition -- other packages merge non-owner kinds into PrincipalMap. + if (peer.principal.kind !== 'owner') { + throw new TypertGatewayError('gateway/invocation-unavailable', endpoint, 'only owner Peers answer forwarded Remote events') + } const result = parseRemoteEventResultPayload(payload) const client = this.remoteEventClients.get(result.clientId) if (client === undefined) { @@ -447,34 +472,24 @@ export class TypertGatewayService extends Service implements TypertGateway { endpoint: string, payload: unknown, uplink: AsyncIterable, - peer: PeerScope | undefined, + peer: PeerScope, signal: AbortSignal, control: AbortController, + uplinkWindow?: RemoteInvocation['uplinkWindow'], ): Promise> { if (endpoint === REMOTE_EVENT_STREAM_ENDPOINT) { // A Gateway-owned stream reads no uplink: releasing it now keeps its items out of the bounded inbox. releaseUplink(uplink) - return this.openRemoteEvents(payload, signal) + assertPeerLive(peer, endpoint) + return this.openRemoteEvents(payload, signal, peer) } - return this.openStream({ ...remoteRequest(endpoint, payload, signal, peer), uplink }, control) - } - - /** - * The Peer an in-process carrier speaks for when it names none: the - * operator's Peer when Connection is mounted, otherwise an operator scope the - * Gateway owns for its own lifetime. - * @returns the operator Peer. - */ - private operatorPeer(): PeerScope { - const connection = this.ctx.get('connection') - if (connection !== undefined) return connection.operator - this.inProcessOperator ??= new OperatorPeer(this.ctx) - return this.inProcessOperator + return this.openStream({ ...remoteRequest(endpoint, payload, signal, peer), uplink, uplinkWindow }, control) } private async *openRemoteEvents( payload: unknown, signal: AbortSignal, + peer: PeerScope, ): AsyncGenerator< RemoteEventEmitFrame | RemoteEventInvocationFrame | RemoteEventCancellationFrame | RemoteEventReadyFrame @@ -500,7 +515,7 @@ export class TypertGatewayService extends Service implements TypertGateway { 'forwarded Remote event source is unavailable', ) } - const lifetime = AbortSignal.any([signal, registration.lifetime.signal]) + const lifetime = AbortSignal.any([signal, registration.lifetime.signal, peer.signal]) let clientId = randomUUID() as RemoteEventClientId while (this.remoteEventClients.has(clientId)) clientId = randomUUID() as RemoteEventClientId const client: RemoteEventClient = { @@ -508,9 +523,14 @@ export class TypertGatewayService extends Service implements TypertGateway { queue: new RemoteEventQueue(), signal: lifetime, deliveries: new Map(), + principal: peer.principal, + // oxlint-disable-next-line typescript/no-unnecessary-condition -- other packages merge non-owner kinds into PrincipalMap. + answers: peer.principal.kind === 'owner', } this.remoteEventClients.set(clientId, client) - for (const pending of this.pendingRemoteEvents.values()) this.deliverRemoteEvent(pending, client) + if (client.answers) { + for (const pending of this.pendingRemoteEvents.values()) this.deliverRemoteEvent(pending, client) + } try { yield { ...REMOTE_EVENT_STREAM_READY, clientId, host: registration.host } yield* client.queue.iterate(lifetime) @@ -543,7 +563,21 @@ export class TypertGatewayService extends Service implements TypertGateway { event: frame.event, args: frame.args, } - for (const client of this.remoteEventClients.values()) client.queue.push(wire) + let resolved = false + let resources: readonly RemoteAccessResource[] | undefined + for (const client of this.remoteEventClients.values()) { + if (!client.answers) { + // A non-owner receives the whole notification or nothing: its resources decide, payloads are never trimmed, + // and a notification with invalid resources reaches no non-owner. + if (!resolved) { + resources = eventResources(frame.resources, frame.args) + resolved = true + } + if (resources === undefined) continue + if (this.ctx.remoteAccess.decide({ principal: client.principal, action: `event:${frame.event}`, resources }).kind === 'deny') continue + } + client.queue.push(wire) + } } private startRemoteEvent(source: TypertRemoteEventInvocation): void { @@ -599,7 +633,11 @@ export class TypertGatewayService extends Service implements TypertGateway { this.pendingRemoteEvents.set(id, pending) for (const signal of signals) signal.addEventListener('abort', abort, { once: true }) if ([...signals].some(signal => signal.aborted)) abort() - else for (const client of this.remoteEventClients.values()) this.deliverRemoteEvent(pending, client) + else { + for (const client of this.remoteEventClients.values()) { + if (client.answers) this.deliverRemoteEvent(pending, client) + } + } } catch (error) { source.reject(error) } @@ -701,9 +739,36 @@ export class TypertGatewayService extends Service implements TypertGateway { control: AbortController, ): Promise { const endpoint = endpointOf(request.namespace, request.method) + assertPeerLive(request.peer, endpoint) const descriptor = this.resolveDescriptor(request.namespace, request.method, endpoint) assertExactArguments(request.args, descriptor, endpoint) - const receiverContext = await this.resolveReceiverContext(descriptor, request.args, endpoint) + const validated = validateArguments(descriptor, request.args, endpoint) + // Access precedes lookup resolution, so a refused call activates nothing. + // oxlint-disable-next-line typescript/no-unnecessary-condition -- other packages merge non-owner kinds into PrincipalMap. + if (request.peer.principal.kind !== 'owner') { + const resources = callResources( + this.ctx.typert, + this.resourceReaders(descriptor), + descriptor, + validated, + request.signal ?? NEVER_ABORTED_SIGNAL, + ) + const decision: RemoteAccessDecision = resources === undefined + ? { kind: 'deny', reason: 'resource-invalid' } + : this.ctx.remoteAccess.decide({ + principal: request.peer.principal, + action: `${descriptor.namespace}/${descriptor.method}`, + resources, + args: validated, + }) + if (decision.kind === 'deny') { + throw new RemoteError('remote-access/denied', `remote access: ${endpoint}: access denied (${decision.reason})`, { + action: endpoint, + reason: decision.reason, + }) + } + } + const receiverContext = await this.resolveReceiverContext(descriptor, validated, endpoint) const receiver: unknown = receiverContext.get(descriptor.service) if (!isObject(receiver)) { throw new TypertGatewayError( @@ -714,15 +779,16 @@ export class TypertGatewayService extends Service implements TypertGateway { } validateBinding(receiver, descriptor.service, descriptor.namespace, endpoint) const args = await Promise.all(descriptor.parameters.map(parameter => - this.resolveParameter(parameter, request.args, endpoint))) - const signal = methodSignal(request, control) + this.resolveParameter(parameter, validated, endpoint))) + const signal = methodSignal(request, control, descriptor.mode === 'stream') const invocation = new GatewayInvocation( { namespace: request.namespace, method: request.method, args: request.args }, descriptor.service, - request.peer ?? this.operatorPeer(), + request.peer, signal, { source: request.uplink ?? EMPTY_ASYNC_ITERABLE, + window: request.uplinkWindow, codec: descriptor.uplink?.codec ?? SRC_JSON_CODEC, endpoint, abort: (reason) => { control.abort(reason) }, @@ -942,13 +1008,10 @@ export class TypertGatewayService extends Service implements TypertGateway { args: Readonly>, endpoint: string, ): Promise { - // An absent field reached assertExactArguments' allowance, so this parameter - // takes undefined; a present-but-undefined field is not JSON-safe input and - // still fails decode. Lookup ids are never omissible, so absence here only - // ever belongs to a json parameter. + // Lookup ids are never omissible, so an absent field belongs to a json parameter that takes undefined. if (!Object.hasOwn(args, parameter.wire)) return undefined + if (parameter.source === 'json') return args[parameter.wire] const value = decode(parameter.codec, args[parameter.wire], endpoint, parameter.wire) - if (parameter.source === 'json') return value const key = parameter.lookup /* v8 ignore next -- registry validation rejects strict descriptors without a key, and SRC derivation always supplies one. */ if (key === undefined) { @@ -1085,12 +1148,18 @@ class RemoteEventQueue { this.waiter?.() } + /** + * Yield buffered and later frames until the queue ends or `signal` aborts. + * An abort discards the frames still buffered, so a revoked Peer receives none of them. + * @param signal - Client generation lifetime. + * @returns the queued wire frames in push order. + */ async *iterate(signal: AbortSignal): AsyncGenerator { const abort = (): void => { this.end() } signal.addEventListener('abort', abort, { once: true }) try { while (true) { - while (this.frames.size > 0) yield this.frames.popFront() as RemoteEventWireFrame + while (this.frames.size > 0 && !signal.aborted) yield this.frames.popFront() as RemoteEventWireFrame if (this.closed || signal.aborted) return await new Promise((resolve) => { this.waiter = resolve }) this.waiter = undefined @@ -1128,8 +1197,10 @@ function remoteRequest( endpoint: string, payload: unknown, signal: AbortSignal, - peer?: PeerScope, + peer: PeerScope, ): InvokeRemoteRequest { + // A disposed Peer is refused whatever it sent. + assertPeerLive(peer, endpoint) const segments = endpoint.split('/') if (segments.length !== 2 || segments[0] === '' || segments[1] === '') { throw new Error(`invalid Remote endpoint ${JSON.stringify(endpoint)}`) @@ -1143,20 +1214,34 @@ function remoteRequest( || !isPlainObject(payload.args)) { throw new Error('Remote payload must contain exactly one plain-object args field') } - return { namespace, method, args: payload.args, signal, ...(peer === undefined ? {} : { peer }) } + return { namespace, method, args: payload.args, signal, peer } } /** * The signal a method observes. A carrier that supplies an uplink fails the * stream through `control` when an item is rejected, so that invocation joins - * `control` with the carrier signal; every other invocation keeps the carrier - * signal's identity. + * `control` with the carrier signal; a stream also ends with its Peer. Every + * other invocation keeps the carrier signal's identity. */ -function methodSignal(request: InvokeRemoteRequest, control: AbortController): AbortSignal { +function methodSignal(request: InvokeRemoteRequest, control: AbortController, stream: boolean): AbortSignal { const carrier = request.signal - if (request.uplink === undefined) return carrier ?? NEVER_ABORTED_SIGNAL - if (carrier === undefined || carrier === control.signal) return control.signal - return AbortSignal.any([carrier, control.signal]) + if (request.uplink === undefined && !stream) return carrier ?? NEVER_ABORTED_SIGNAL + const joined = carrier === undefined || carrier === control.signal ? [control.signal] : [carrier, control.signal] + // `AbortSignal.any` leaves each source only a weak reference to the joined signal, + // so per-stream joins on a Host-lifetime Peer signal accumulate nothing. + return AbortSignal.any(stream ? [...joined, request.peer.signal] : joined) +} + +/** + * Refuse a call whose Peer has been disposed. + * @param peer - Peer the call speaks for. + * @param endpoint - endpoint named in the failure. + * @throws {@link TypertGatewayError} `gateway/peer-disposed` once the Peer is disposed. + */ +function assertPeerLive(peer: PeerScope, endpoint: string): void { + if (peer.signal.aborted) { + throw new TypertGatewayError('gateway/peer-disposed', endpoint, 'the calling Peer has been disposed') + } } function isIterable(value: unknown): value is Iterable | AsyncIterable { @@ -1309,6 +1394,8 @@ class GatewayInvocation implements RemoteInvocation { private decoder: UplinkDecoder | undefined private taken = false + get uplinkWindow(): RemoteInvocation['uplinkWindow'] { return this.uplink_.window } + /** * @param request - decoded endpoint and wire arguments. * @param service - Cordis service key of the receiver. @@ -1503,6 +1590,28 @@ function assertExactArguments( throw new TypertGatewayError('gateway/arguments-invalid', endpoint, `args fields do not match the descriptor: ${clauses.join('; ')}`) } +/** + * Decode every present JSON argument once through its parameter codec; a + * Typert codec drops object fields its compiled type does not declare. Lookup + * and Context identities keep their wire values; dispatch decodes and resolves + * them only after the access check. An absent field stays absent; a present + * `undefined` is not JSON-safe and fails decoding. + */ +function validateArguments( + descriptor: InvocationDescriptor, + args: Readonly>, + endpoint: string, +): Readonly> { + const entries: [string, unknown][] = [] + if (descriptor.invocation.kind === 'context') entries.push([descriptor.invocation.wire, args[descriptor.invocation.wire]]) + for (const parameter of descriptor.parameters) { + if (!Object.hasOwn(args, parameter.wire)) continue + const value = args[parameter.wire] + entries.push([parameter.wire, parameter.source === 'json' ? decode(parameter.codec, value, endpoint, parameter.wire) : value]) + } + return Object.fromEntries(entries) +} + function decode( codec: TypertCodec, value: unknown, diff --git a/packages/api/gateway/src/remote-error-codes.ts b/packages/api/gateway/src/remote-error-codes.ts index 5e560557cc..e61432b8c5 100644 --- a/packages/api/gateway/src/remote-error-codes.ts +++ b/packages/api/gateway/src/remote-error-codes.ts @@ -27,6 +27,7 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'gateway/lookup-not-found': TypertGatewayFaultDetails 'gateway/lookup-unavailable': TypertGatewayFaultDetails 'gateway/method-unavailable': TypertGatewayFaultDetails + 'gateway/peer-disposed': TypertGatewayFaultDetails 'gateway/protocol': TypertGatewayFaultDetails 'gateway/provider-mismatch': TypertGatewayFaultDetails 'gateway/result-invalid': TypertGatewayFaultDetails diff --git a/packages/api/gateway/src/stream-server.ts b/packages/api/gateway/src/stream-server.ts index 9454f03f2d..2473f1a8e6 100644 --- a/packages/api/gateway/src/stream-server.ts +++ b/packages/api/gateway/src/stream-server.ts @@ -3,7 +3,7 @@ import type { IncomingMessage } from 'node:http' import type { Duplex } from 'node:stream' import { Deque } from '@deepseek-ai/dsh-deque' -import { RemoteError, remoteErrorOf, type PeerScope } from '@deepseek-ai/dsh-typert-protocol' +import { RemoteError, remoteErrorOf, type PeerScope, type RemoteUplinkWindow } from '@deepseek-ai/dsh-typert-protocol' import WebSocket, { WebSocketServer, type RawData } from 'ws' import { parseRemoteStreamClientMessage, @@ -16,7 +16,7 @@ import { * Open one validated Remote stream for a decoded wire request on behalf of one * Peer. `uplink` carries the Client's items; `control` cancels the logical * stream, and aborting it with a Remote failure as the reason delivers that - * failure to the Client. + * failure to the Client. `window` describes this stream's complete-frame inbox budget. */ export type RemoteStreamOpener = ( endpoint: string, @@ -24,6 +24,7 @@ export type RemoteStreamOpener = ( uplink: AsyncIterable, peer: PeerScope, control: AbortController, + window: RemoteUplinkWindow, ) => Promise> /** The opener one socket uses: its Peer is fixed at upgrade time. */ @@ -32,6 +33,7 @@ type BoundStreamOpener = ( payload: unknown, uplink: AsyncIterable, control: AbortController, + window: RemoteUplinkWindow, ) => Promise> /** Convert an invocation or carrier failure to a stable wire value. */ @@ -72,12 +74,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 bound: BoundStreamOpener = (endpoint, payload, uplink, control, window) => + this.open(endpoint, payload, uplink, peer, control, window) + const connection = new RemoteStreamMuxConnection(websocket, bound, this.failure, this.streamInboxBytes, alive) const done = connection.run() this.connections.add(done) void done.then(() => { @@ -141,13 +143,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 @@ -230,7 +242,10 @@ class RemoteStreamMuxConnection { ): Promise { let outcome: { readonly failed: false } | { readonly failed: true; readonly error: unknown } try { - const source = await this.open(endpoint, payload, active.inbox, active.abort) + const source = await this.open(endpoint, payload, active.inbox, active.abort, { + maxBytes: this.streamInboxBytes, + frameOverheadBytes: Buffer.byteLength(JSON.stringify({ type: 'item', streamId, value: null }), 'utf8') - 'null'.length, + }) for await (const value of source) { await this.send({ type: 'item', streamId, value }) } @@ -283,10 +298,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/src/types.ts b/packages/api/gateway/src/types.ts index 9fa3a012b5..d83f120ab3 100644 --- a/packages/api/gateway/src/types.ts +++ b/packages/api/gateway/src/types.ts @@ -4,7 +4,7 @@ */ import type { Context } from '@deepseek-ai/cordis' -import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol' +import type { PeerScope, RemoteUplinkWindow, TypertResourceReader } from '@deepseek-ai/dsh-typert-protocol' import type { RemoteEventHostInfo } from './stream-protocol.ts' /** One Remote method request after a carrier has decoded its envelope. */ @@ -20,8 +20,10 @@ export interface InvokeRemoteRequest { * `invocation.uplink()`; absent means an immediately ended iterable. */ readonly uplink?: AsyncIterable - /** Peer the call speaks for; absent means an in-process carrier, answered as the operator. */ - readonly peer?: PeerScope + /** Carrier-provided frame capacity; absent for carriers without an encoded-frame inbox limit. */ + readonly uplinkWindow?: RemoteUplinkWindow | undefined + /** Peer the call speaks for; every carrier and in-process caller names it explicitly. */ + readonly peer: PeerScope /** Carrier or direct-caller cancellation injected only into cancellation-aware methods. */ readonly signal?: AbortSignal } @@ -32,6 +34,12 @@ export interface TypertRemoteEventFrame { readonly event: string /** Original event argument list after the owner validates it for JSON transport. */ readonly args: readonly unknown[] + /** + * Readers of the resources the arguments carry, keyed by resource kind and + * called with the arguments as positional parameters. Absent or empty for + * a notification that touches the global resource. + */ + readonly resources?: Readonly> } /** Live Host values used to project one scoped Remote Event. */ @@ -88,7 +96,7 @@ export interface TypertGatewayWireStream { * @param payload - decoded carrier payload. * @param uplink - Client-to-Host items of the logical stream; a Gateway-owned endpoint returns its iterator * as soon as it opens, so the carrier drops those items instead of buffering them. - * @param peer - Peer the stream speaks for; `undefined` means the operator's in-process carrier. + * @param peer - Peer the stream speaks for; required, never defaulted. * @param signal - logical-stream cancellation. * @returns validated stream values. */ @@ -96,7 +104,7 @@ export interface TypertGatewayWireStream { endpoint: string, payload: unknown, uplink: AsyncIterable, - peer: PeerScope | undefined, + peer: PeerScope, signal: AbortSignal, ) => Promise> @@ -127,6 +135,7 @@ export type TypertGatewayErrorCode = | 'gateway/lookup-not-found' | 'gateway/lookup-unavailable' | 'gateway/method-unavailable' + | 'gateway/peer-disposed' | 'gateway/protocol' | 'gateway/provider-mismatch' | 'gateway/result-invalid' @@ -140,8 +149,8 @@ export interface TypertGateway { readonly wireStream: TypertGatewayWireStream /** - * Check for an active Client event stream. - * @returns whether a stream is open and has not been cancelled. + * Check for an active owner Client event stream, the only kind that can answer forwarded waterfalls. + * @returns whether an owner stream is open and has not been cancelled. */ hasLiveClient(): boolean diff --git a/packages/api/gateway/tests/echo-stream.host.spec.ts b/packages/api/gateway/tests/echo-stream.host.spec.ts index d56b529002..24a24f6918 100644 --- a/packages/api/gateway/tests/echo-stream.host.spec.ts +++ b/packages/api/gateway/tests/echo-stream.host.spec.ts @@ -7,7 +7,9 @@ import WebServer from '@deepseek-ai/dsh-host-webserver' import { Remote, TypertRemoteService, type RemoteStream } from '@deepseek-ai/dsh-typert-protocol' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' import TypertGatewayService from '@deepseek-ai/dsh-api-gateway' +import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access' import { browserCookie, provideBrowserCredentials } from './browser-credentials.ts' +import { ownerPeer } from './peer.ts' /** The smallest Remote stream that reads its uplink: every carrier has to serve it alike. */ class EchoService extends TypertRemoteService { @@ -36,6 +38,7 @@ describe('the echo stream on each carrier', () => { it('echoes uplink items through the in-process carrier', async () => { const ctx = await setup(false) const replies = await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'echo', method: 'echo', args: { prefix: '> ' }, uplink: items(['a', 'b']), }) await expect(collect(replies)).resolves.toEqual(['> a', '> b']) @@ -73,6 +76,7 @@ async function setup(transport: boolean): Promise { provideBrowserCredentials(ctx) } await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) await ctx.plugin(TypertGatewayService, {}) if (transport) await ctx.plugin({ inject: [...connectionInject], apply: applyConnection }) await ctx.plugin(EchoService) diff --git a/packages/api/gateway/tests/gateway-access.host.spec.ts b/packages/api/gateway/tests/gateway-access.host.spec.ts new file mode 100644 index 0000000000..42cbb1bbff --- /dev/null +++ b/packages/api/gateway/tests/gateway-access.host.spec.ts @@ -0,0 +1,915 @@ +import { describe, expect, it, vi, afterEach } from 'vitest' +import { Context, symbols } from '@deepseek-ai/cordis' +import { apply as applyConnection, inject as connectionInject } from '@deepseek-ai/dsh-client-connection' +import RemoteAccessService, { + type RemoteAccessAction, + type RemoteAccessBinding, + type RemoteAccessCondition, + type RemoteAccessResource, + type RemoteAccessResourceKind, + type RemoteAccessRole, +} from '@deepseek-ai/dsh-api-remote-access' +import { + Remote, + RemoteScope, + TypertRemoteService, + type InvocationDescriptor, + type InvocationParameterDescriptor, + type PeerScope, + type Principal, + type PrincipalMap, + type TypertContext, + type TypertLookup, + type TypertResource, +} from '@deepseek-ai/dsh-typert-protocol' +import TypertRegistry from '@deepseek-ai/dsh-typert-registry' +import { z } from 'zod' +import TypertGatewayService, { type TypertRemoteEventDispatch } from '@deepseek-ai/dsh-api-gateway' +import { callResources, eventResources } from '../src/access.ts' +import { provideBrowserCredentials } from './browser-credentials.ts' +import { ownerPeer, peerFor } from './peer.ts' + +interface AccessAgent { + readonly id: string +} + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + /** Test-only non-owner caller shared by the access specs. */ + 'test-guest': { readonly kind: 'test-guest'; readonly guest: string } + } + interface TypertLookupMap { + gatewayAccessAgent: TypertLookup + } + interface TypertContextMap { + gatewayAccessScope: TypertContext + } + interface TypertResourceMap { + /** Test-only resource kinds; the Gateway itself names no kind. */ + 'test-shelf': TypertResource + 'test-desk': TypertResource + } +} + +type Guest = PrincipalMap['test-guest'] + +const OWNER: Principal = { kind: 'owner' } +const GUEST: Guest = { kind: 'test-guest', guest: 'gateway' } +const GLOBAL = { kind: 'global' } as const +const shelf = (id: string) => ({ kind: 'test-shelf', id }) as const +const desk = (id: string) => ({ kind: 'test-desk', id }) as const + +const FIXTURE_ACTIONS: readonly RemoteAccessAction[] = [ + 'accessFixture/open', 'accessFixture/read', 'accessFixture/byAgent', 'accessFixture/byLookup', + 'accessFixture/byLookupAndOption', 'accessFixture/byList', 'accessFixture/scoped', 'accessFixture/scopedOnDesk', + 'accessFixture/scopedByReader', 'accessFixture/annotate', 'absentAccess/read', 'event:fixture/notice', 'event:fixture/shelf', +] + +function role(resource: K): RemoteAccessRole { + return { name: `test:${resource}`, resource, actions: FIXTURE_ACTIONS } +} + +/** One binding granting every fixture action on `resource`. */ +function on(resource: RemoteAccessResource): RemoteAccessBinding { + switch (resource.kind) { + case 'global': + return { role: role('global'), resource } + case 'test-shelf': + return { role: role('test-shelf'), resource } + case 'test-desk': + return { role: role('test-desk'), resource } + default: + throw new Error('no fixture role for this resource kind') + } +} + +class AccessFixture extends TypertRemoteService { + readonly principals: Principal[] = [] + readonly requests: unknown[] = [] + release: PromiseWithResolvers = Promise.withResolvers() + + constructor(ctx: Context) { + super(ctx, 'accessFixture') + } + + @Remote + open(): string { + return this.seen() + } + + @Remote + read(request: { readonly shelfId?: unknown; readonly principal?: unknown }): string { + void request + return this.seen() + } + + @Remote({ resources: { 'test-shelf': agentId => agentId } }) + byAgent(agentId: string): string { + void agentId + return this.seen() + } + + @Remote + byLookup(agent: AccessAgent): string { + return `${agent.id}:${this.seen()}` + } + + @Remote({ resources: { 'test-desk': (agentId, request) => [agentId, request.deskId] } }) + byLookupAndOption(agent: AccessAgent, request: { readonly deskId: string; readonly shelfId: string }): string { + void request + return `${agent.id}:${this.seen()}` + } + + @Remote({ resources: { 'test-shelf': shelfIds => shelfIds } }) + byList(shelfIds: readonly string[]): string { + void shelfIds + return this.seen() + } + + @Remote + annotate(request: { readonly title: string }): string { + this.requests.push(request) + return this.seen() + } + + @RemoteScope('gatewayAccessScope') + scoped(): string { + return this.seen() + } + + @RemoteScope('gatewayAccessScope', { resources: { 'test-desk': request => request.deskId } }) + scopedOnDesk(request: { readonly deskId: string }): string { + void request + return this.seen() + } + + @RemoteScope('gatewayAccessScope', { resources: { 'test-shelf': request => request.shelfId } }) + scopedByReader(request: { readonly shelfId: string }): string { + void request + return this.seen() + } + + @Remote + async slow(): Promise { + await this.release.promise + return this.seen() + } + + @Remote({ mode: 'stream' }) + async *watch(signal: AbortSignal): AsyncIterable { + yield this.seen() + await new Promise((resolve) => { + if (signal.aborted) resolve() + else signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) + } + + private seen(): string { + const principal = this.ctx.invocation?.peer.principal + if (principal !== undefined) this.principals.push(principal) + return principal?.kind ?? 'none' + } +} + +const roots: Context[] = [] + +afterEach(async () => { + vi.restoreAllMocks() + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) +}) + +async function setup(options: { readonly connection?: boolean } = {}): Promise<{ + readonly ctx: Context + readonly fixture: AccessFixture + /** Replace the guest's bindings: every fixture action on each listed resource. */ + readonly hold: (...resources: RemoteAccessResource[]) => void + readonly bindings: ReturnType readonly RemoteAccessBinding[]>> +}> { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) + await ctx.plugin(TypertGatewayService) + if (options.connection === true) { + provideBrowserCredentials(ctx) + await ctx.plugin({ inject: [...connectionInject], apply: applyConnection }) + } + ctx.typert.resources.register('test-shelf', { field: 'shelfId' }) + await ctx.plugin(AccessFixture) + let held: readonly RemoteAccessBinding[] = [] + const bindings = vi.fn((guest: Guest): readonly RemoteAccessBinding[] => { void guest; return held }) + ctx.remoteAccess.registerPolicy('test-guest', { bindings }) + const receiver = ctx.get('accessFixture') as AccessFixture & { [symbols.original]?: AccessFixture } + return { + ctx, + fixture: receiver[symbols.original] ?? receiver, + hold: (...resources) => { held = resources.map(on) }, + bindings, + } +} + +/** Record every request the service decides from now on; the returned function lists their actions and resources in order. */ +function recordDecisions(): () => { readonly action: string; readonly resources: unknown }[] { + const decide = vi.spyOn(RemoteAccessService.prototype, 'decide') + return () => decide.mock.calls.map(([request]) => ({ action: request.action, resources: request.resources })) +} + +function call(ctx: Context, peer: PeerScope, method: string, args: Record = {}): Promise { + return ctx.typertGateway.invoke({ peer, namespace: 'accessFixture', method, args }) +} + +function registerScope(ctx: Context, resource: 'test-shelf' | undefined, resolve = vi.fn((id: string) => { void id; return ctx })): typeof resolve { + ctx.typert.contexts.registerHost('gatewayAccessScope', { + wire: 'scopeId', + wireTypeSymbol: '@fixture/access#ScopeId', + ...resource === undefined ? {} : { resource }, + resolve, + }) + return resolve +} + +function strictCodec(name: string, create: () => z.ZodType): InvocationParameterDescriptor['codec'] { + return { mode: 'strict', typeSymbol: `@fixture/access#${name}`, create } +} + +/** Give each listed fixture method a strict descriptor with these parameters. */ +function registerStrict(ctx: Context, methods: Readonly>): void { + ctx.typert.register({ + package: '@fixture/gateway-access-strict', + face: 'host', + schemas: [], + model: { services: [], events: [], objects: [] }, + invocations: Object.entries(methods).map(([method, parameters]) => ({ + id: `@fixture/gateway-access-strict#accessFixture/${method}`, + service: 'accessFixture', + namespace: 'accessFixture', + method, + invocation: { kind: 'direct' }, + parameters, + result: { mode: 'strict', typeSymbol: '@fixture/access#Result', create: () => z.string() }, + })), + }) +} + +describe('Gateway access checks', () => { + it('dispatches the owner without resolving resources or reading the policy', async () => { + const { ctx, bindings } = await setup() + const decide = vi.spyOn(RemoteAccessService.prototype, 'decide') + await expect(call(ctx, ownerPeer(ctx), 'open')).resolves.toBe('owner') + await expect(call(ctx, ownerPeer(ctx), 'read', { request: { shelfId: 7 } })).resolves.toBe('owner') + expect(decide).not.toHaveBeenCalled() + expect(bindings).not.toHaveBeenCalled() + }) + + it('starts only in a composition that mounts remoteAccess', async () => { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(TypertRegistry) + void ctx.plugin(TypertGatewayService) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(ctx.get('typertGateway')).toBeUndefined() + await ctx.plugin(RemoteAccessService) + await vi.waitFor(() => { expect(ctx.get('typertGateway')).toBeDefined() }) + }) + + it('refuses a non-owner call no binding allows before the method runs', async () => { + const { ctx, fixture, hold } = await setup() + const guest = peerFor(ctx, GUEST) + await expect(call(ctx, guest, 'open')).rejects.toMatchObject({ + code: 'remote-access/denied', + message: 'remote access: accessFixture/open: access denied (no-allow)', + details: { action: 'accessFixture/open', reason: 'no-allow' }, + }) + expect(fixture.principals).toEqual([]) + hold(GLOBAL) + await expect(call(ctx, guest, 'open')).resolves.toBe('test-guest') + expect(fixture.principals).toEqual([GUEST]) + }) + + it('hands remoteAccess the endpoint action, the resolved resources, and the call arguments', async () => { + const { ctx, hold } = await setup() + hold(GLOBAL, shelf('s1'), shelf('s2')) + const decide = vi.spyOn(RemoteAccessService.prototype, 'decide') + const guest = peerFor(ctx, GUEST) + await call(ctx, guest, 'read', { request: { shelfId: 's1' } }) + await call(ctx, guest, 'byAgent', { agentId: 's2' }) + await call(ctx, guest, 'read', { request: {} }) + expect(decide.mock.calls.map(([request]) => request)).toEqual([ + { principal: GUEST, action: 'accessFixture/read', resources: [shelf('s1')], args: { request: { shelfId: 's1' } } }, + { principal: GUEST, action: 'accessFixture/byAgent', resources: [shelf('s2')], args: { agentId: 's2' } }, + { principal: GUEST, action: 'accessFixture/read', resources: [GLOBAL], args: { request: {} } }, + ]) + }) + + it('reads a lookup parameter\'s resource and lets a reader replace it for its kind', async () => { + const { ctx, hold } = await setup() + hold(shelf('s9'), desk('a1'), desk('a2'), desk('d9')) + const decisions = recordDecisions() + ctx.typert.lookups.register('gatewayAccessAgent', { + parameter: 'agent', + wire: 'agentId', + resource: 'test-desk', + hostTypeSymbol: '@fixture/access#Agent', + wireTypeSymbol: '@fixture/access#AgentId', + resolve: (id: string) => ({ id }), + }) + const guest = peerFor(ctx, GUEST) + await expect(call(ctx, guest, 'byLookup', { agentId: 'a1' })).resolves.toBe('a1:test-guest') + await expect(call(ctx, guest, 'byLookupAndOption', { agentId: 'a2', request: { deskId: 'd9', shelfId: 's9' } })) + .resolves.toBe('a2:test-guest') + expect(decisions().map(({ resources }) => resources)).toEqual([ + [desk('a1')], + // The reader owns `test-desk`; the registered `shelfId` field still names `test-shelf`. + [shelf('s9'), desk('a2'), desk('d9')], + ]) + }) + + it('refuses an empty reader list and a malformed default field with resource-invalid without asking remoteAccess', async () => { + const { ctx, hold, bindings } = await setup() + hold(shelf('s1'), shelf('s2')) + const decide = vi.spyOn(RemoteAccessService.prototype, 'decide') + const guest = peerFor(ctx, GUEST) + await expect(call(ctx, guest, 'byList', { shelfIds: [] })).rejects.toMatchObject({ + code: 'remote-access/denied', details: { action: 'accessFixture/byList', reason: 'resource-invalid' }, + }) + await expect(call(ctx, guest, 'read', { request: { shelfId: 7 } })).rejects.toMatchObject({ + code: 'remote-access/denied', details: { reason: 'resource-invalid' }, + }) + expect(decide).not.toHaveBeenCalled() + expect(bindings).not.toHaveBeenCalled() + // Every listed resource must be allowed. + await expect(call(ctx, guest, 'byList', { shelfIds: ['s1', 's2'] })).resolves.toBe('test-guest') + await expect(call(ctx, guest, 'byList', { shelfIds: ['s1', 's3'] })).rejects.toMatchObject({ details: { reason: 'no-allow' } }) + }) + + it('resolves a strict method whose Service is absent from its arguments alone', async () => { + const { ctx } = await setup() + const decisions = recordDecisions() + ctx.typert.register({ + package: '@fixture/gateway-access', + face: 'host', + schemas: [], + model: { services: [], events: [], objects: [] }, + invocations: [{ + id: '@fixture/gateway-access#absentAccess/read', + service: 'absentAccess', + namespace: 'absentAccess', + method: 'read', + invocation: { kind: 'direct' }, + parameters: [], + result: { mode: 'strict', typeSymbol: '@fixture/gateway-access#Result', create: () => z.string() }, + }], + }) + await expect(ctx.typertGateway.invoke({ peer: peerFor(ctx, GUEST), namespace: 'absentAccess', method: 'read', args: {} })) + .rejects.toMatchObject({ code: 'remote-access/denied', details: { action: 'absentAccess/read', reason: 'no-allow' } }) + expect(decisions()).toEqual([{ action: 'absentAccess/read', resources: [GLOBAL] }]) + }) + + it('checks access before resolving lookups, so a refused call activates nothing', async () => { + const { ctx, hold } = await setup() + const resolve = vi.fn((id: string) => ({ id })) + ctx.typert.lookups.register('gatewayAccessAgent', { + parameter: 'agent', + wire: 'agentId', + hostTypeSymbol: '@fixture/access#Agent', + wireTypeSymbol: '@fixture/access#AgentId', + resolve, + }) + const guest = peerFor(ctx, GUEST) + await expect(call(ctx, guest, 'byLookup', { agentId: 'a1' })).rejects.toMatchObject({ code: 'remote-access/denied' }) + expect(resolve).not.toHaveBeenCalled() + // A lookup without a resource kind contributes nothing, so the call touches the global resource. + hold(GLOBAL) + await expect(call(ctx, guest, 'byLookup', { agentId: 'a1' })).resolves.toBe('a1:test-guest') + expect(resolve).toHaveBeenCalledOnce() + }) + + it('keeps the principal out of reach of wire fields', async () => { + const { ctx, fixture, hold } = await setup({ connection: true }) + hold(GLOBAL) + const guest = ctx.connection.createPeer({ principal: GUEST }) + await expect(call(ctx, guest, 'read', { request: {}, principal: OWNER })).rejects.toMatchObject({ + code: 'gateway/arguments-invalid', + }) + const shared = ctx.connection.createSharedFetchHandler('/api') + const response = await shared.fetch(new Request('http://host/api/accessFixture/read', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + type: 'client-request', + rpcId: 'rpc-1', + method: 'accessFixture/read', + principal: OWNER, + payload: { args: { request: { principal: OWNER } } }, + }), + }), guest) + expect(await response.json()).toMatchObject({ result: { ok: true, value: 'test-guest' } }) + const payloadSibling = await shared.fetch(new Request('http://host/api/accessFixture/read', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + type: 'client-request', + rpcId: 'rpc-2', + method: 'accessFixture/read', + payload: { args: { request: {} }, principal: OWNER }, + }), + }), guest) + expect(await payloadSibling.json()).toMatchObject({ result: { ok: false } }) + expect(fixture.principals).toEqual([GUEST]) + }) +}) + +describe('Gateway access checks on Typert-validated arguments', () => { + const titleRequest = (create: () => z.ZodType = () => z.object({ title: z.string() })): InvocationParameterDescriptor => + ({ name: 'request', wire: 'request', source: 'json', codec: strictCodec('TitleRequest', create) }) + + it('resolves resources from the decoded arguments, so an undeclared nested field names no resource', async () => { + const { ctx, fixture, hold } = await setup() + const create = vi.fn(() => z.object({ title: z.string() })) + registerStrict(ctx, { + annotate: [titleRequest(create)], + read: [{ name: 'request', wire: 'request', source: 'json', codec: strictCodec('ShelfRequest', () => z.object({ shelfId: z.string() })) }], + }) + const decide = vi.spyOn(RemoteAccessService.prototype, 'decide') + const guest = peerFor(ctx, GUEST) + hold(shelf('s1')) + await expect(call(ctx, guest, 'annotate', { request: { title: 't', shelfId: 's1' } })).rejects.toMatchObject({ + code: 'remote-access/denied', details: { action: 'accessFixture/annotate', reason: 'no-allow' }, + }) + await expect(call(ctx, guest, 'read', { request: { shelfId: 's1', principal: OWNER } })).resolves.toBe('test-guest') + hold(GLOBAL) + await expect(call(ctx, guest, 'annotate', { request: { title: 't', shelfId: 's1' } })).resolves.toBe('test-guest') + expect(decide.mock.calls.map(([request]) => request)).toEqual([ + { principal: GUEST, action: 'accessFixture/annotate', resources: [GLOBAL], args: { request: { title: 't' } } }, + { principal: GUEST, action: 'accessFixture/read', resources: [shelf('s1')], args: { request: { shelfId: 's1' } } }, + { principal: GUEST, action: 'accessFixture/annotate', resources: [GLOBAL], args: { request: { title: 't' } } }, + ]) + // Dispatch receives the value the access check read, decoded once per call. + expect(fixture.requests).toEqual([{ title: 't' }]) + expect(create).toHaveBeenCalledTimes(2) + }) + + it('hands a condition the decoded arguments, so it cannot read an undeclared field', async () => { + const { ctx, bindings } = await setup() + registerStrict(ctx, { annotate: [titleRequest()] }) + const seen: unknown[] = [] + const condition: RemoteAccessCondition<'global'> = ({ args }) => { + seen.push(args) + return { kind: 'allow' } + } + bindings.mockImplementation(() => [{ role: role('global'), resource: GLOBAL, condition }]) + await expect(call(ctx, peerFor(ctx, GUEST), 'annotate', { request: { title: 't', readOnly: false } })).resolves.toBe('test-guest') + expect(seen).toEqual([{ request: { title: 't' } }]) + }) + + it('passes readers the decoded arguments and lookup wire identities, resolving no lookup for a refused call', async () => { + const { ctx, hold } = await setup() + const resolve = vi.fn((id: string) => ({ id })) + ctx.typert.lookups.register('gatewayAccessAgent', { + parameter: 'agent', + wire: 'agentId', + resource: 'test-desk', + hostTypeSymbol: '@fixture/access#Agent', + wireTypeSymbol: '@fixture/access#AgentId', + resolve, + }) + registerStrict(ctx, { + byLookupAndOption: [ + { name: 'agent', wire: 'agentId', source: 'lookup', lookup: 'gatewayAccessAgent', codec: strictCodec('AgentId', () => z.string()) }, + { name: 'request', wire: 'request', source: 'json', codec: strictCodec('DeskRequest', () => z.object({ deskId: z.string() })) }, + ], + }) + const decisions = recordDecisions() + const guest = peerFor(ctx, GUEST) + const args = { agentId: 'a2', request: { deskId: 'd9', shelfId: 's9' } } + hold(shelf('s9'), desk('a2')) + await expect(call(ctx, guest, 'byLookupAndOption', args)).rejects.toMatchObject({ details: { reason: 'no-allow' } }) + expect(resolve).not.toHaveBeenCalled() + hold(desk('a2'), desk('d9')) + await expect(call(ctx, guest, 'byLookupAndOption', args)).resolves.toBe('a2:test-guest') + expect(resolve).toHaveBeenCalledExactlyOnceWith('a2') + // The undeclared `shelfId` names no `test-shelf` resource. + expect(decisions().map(({ resources }) => resources)).toEqual([[desk('a2'), desk('d9')], [desk('a2'), desk('d9')]]) + }) + + it('refuses arguments their codec rejects with gateway/input-invalid before the access check', async () => { + const { ctx, fixture, bindings } = await setup() + registerStrict(ctx, { annotate: [titleRequest()] }) + const decide = vi.spyOn(RemoteAccessService.prototype, 'decide') + for (const peer of [peerFor(ctx, GUEST), ownerPeer(ctx)]) { + await expect(call(ctx, peer, 'annotate', { request: { title: 7, shelfId: 's1' } })).rejects.toMatchObject({ + code: 'gateway/input-invalid', details: { endpoint: 'accessFixture/annotate', field: 'request' }, + }) + } + expect(decide).not.toHaveBeenCalled() + expect(bindings).not.toHaveBeenCalled() + expect(fixture.requests).toEqual([]) + }) +}) + +describe('Gateway access checks for Context methods', () => { + it('reads the Context identity as the resource its adapter declares, before resolving the Context', async () => { + const { ctx, fixture, hold } = await setup() + const resolve = registerScope(ctx, 'test-shelf') + const guest = peerFor(ctx, GUEST) + await expect(call(ctx, guest, 'scoped', { scopeId: 's1' })).rejects.toMatchObject({ + code: 'remote-access/denied', details: { action: 'accessFixture/scoped', reason: 'no-allow' }, + }) + expect(resolve).not.toHaveBeenCalled() + hold(shelf('s1')) + await expect(call(ctx, guest, 'scoped', { scopeId: 's1' })).resolves.toBe('test-guest') + expect(resolve).toHaveBeenCalledWith('s1') + expect(fixture.principals).toEqual([GUEST]) + }) + + it('adds the resources a reader declares to the Context resource, and lets a reader replace it for its kind', async () => { + const { ctx, hold } = await setup() + registerScope(ctx, 'test-shelf') + const decisions = recordDecisions() + const guest = peerFor(ctx, GUEST) + hold(shelf('s1')) + await expect(call(ctx, guest, 'scopedOnDesk', { scopeId: 's1', request: { deskId: 'd1' } })).rejects.toMatchObject({ + details: { reason: 'no-allow' }, + }) + hold(shelf('s1'), desk('d1')) + await expect(call(ctx, guest, 'scopedOnDesk', { scopeId: 's1', request: { deskId: 'd1' } })).resolves.toBe('test-guest') + await expect(call(ctx, guest, 'scopedByReader', { scopeId: 's9', request: { shelfId: 's1' } })).resolves.toBe('test-guest') + expect(decisions().map(({ resources }) => resources)).toEqual([ + [shelf('s1'), desk('d1')], + [shelf('s1'), desk('d1')], + [shelf('s1')], + ]) + }) + + it('refuses a malformed Context identity with resource-invalid without asking remoteAccess or resolving the Context', async () => { + const { ctx, hold, bindings } = await setup() + const resolve = registerScope(ctx, 'test-shelf') + hold(GLOBAL, shelf('s1')) + const decide = vi.spyOn(RemoteAccessService.prototype, 'decide') + const guest = peerFor(ctx, GUEST) + for (const scopeId of [7, '']) { + await expect(call(ctx, guest, 'scoped', { scopeId })).rejects.toMatchObject({ + code: 'remote-access/denied', details: { action: 'accessFixture/scoped', reason: 'resource-invalid' }, + }) + } + expect(resolve).not.toHaveBeenCalled() + expect(decide).not.toHaveBeenCalled() + expect(bindings).not.toHaveBeenCalled() + }) + + it('resolves a Context method whose adapter declares no resource by the ordinary sources', async () => { + const { ctx, hold } = await setup() + registerScope(ctx, undefined) + const decisions = recordDecisions() + const guest = peerFor(ctx, GUEST) + await expect(call(ctx, guest, 'scoped', { scopeId: 's1' })).rejects.toMatchObject({ details: { reason: 'no-allow' } }) + hold(GLOBAL, desk('d1')) + await expect(call(ctx, guest, 'scoped', { scopeId: 's1' })).resolves.toBe('test-guest') + await expect(call(ctx, guest, 'scopedOnDesk', { scopeId: 's1', request: { deskId: 'd1' } })).resolves.toBe('test-guest') + expect(decisions().map(({ resources }) => resources)).toEqual([ + [GLOBAL], + [GLOBAL], + [desk('d1')], + ]) + }) +}) + +describe('Gateway Peer lifetime', () => { + it('refuses calls and streams from a disposed Peer without affecting other Peers', async () => { + const { ctx } = await setup({ connection: true }) + const peer = peerFor(ctx, OWNER) + await peer.dispose() + await expect(call(ctx, peer, 'open')).rejects.toMatchObject({ code: 'gateway/peer-disposed' }) + await expect(ctx.typertGateway.stream({ peer, namespace: 'accessFixture', method: 'watch', args: {} })) + .rejects.toMatchObject({ code: 'gateway/peer-disposed' }) + await expect(ctx.typertGateway.wireStream.open('$events', { args: {} }, (async function* () {})(), peer, new AbortController().signal)) + .rejects.toMatchObject({ code: 'gateway/peer-disposed' }) + const result = await ctx.connection.createSharedFetchHandler('/api').fetch(new Request('http://host/api/$events/result', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + type: 'client-request', + rpcId: 'rpc-disposed', + method: '$events/result', + payload: { args: { clientId: 'any', eventId: 'any', outcome: { kind: 'next' } } }, + }), + }), peer) + expect(await result.json()).toMatchObject({ result: { ok: false, error: { code: 'gateway/peer-disposed' } } }) + await expect(call(ctx, ownerPeer(ctx), 'open')).resolves.toBe('owner') + }) + + it('refuses a disposed Peer before reading its wire payload', async () => { + const { ctx } = await setup({ connection: true }) + const peer = peerFor(ctx, OWNER) + await peer.dispose() + for (const payload of [{}, { args: 1 }, { args: {}, extra: true }]) { + await expect(ctx.typertGateway.wireStream.open('accessFixture/watch', payload, (async function* () {})(), peer, new AbortController().signal)) + .rejects.toMatchObject({ code: 'gateway/peer-disposed' }) + } + const response = await ctx.connection.createSharedFetchHandler('/api').fetch(new Request('http://host/api/accessFixture/open', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ type: 'client-request', rpcId: 'rpc-malformed', method: 'accessFixture/open', payload: { args: 1 } }), + }), peer) + expect(await response.json()).toMatchObject({ result: { ok: false, error: { code: 'gateway/peer-disposed' } } }) + }) + + it('ends a disposed Peer\'s streams and lets its running unary calls finish', async () => { + const { ctx, fixture } = await setup() + const peer = peerFor(ctx, OWNER) + const other = peerFor(ctx, OWNER) + const stream = (await ctx.typertGateway.stream({ peer, namespace: 'accessFixture', method: 'watch', args: {} }))[Symbol.asyncIterator]() + const survivorAbort = new AbortController() + const survivor = (await ctx.typertGateway.stream({ + peer: other, namespace: 'accessFixture', method: 'watch', args: {}, signal: survivorAbort.signal, + }))[Symbol.asyncIterator]() + await expect(stream.next()).resolves.toEqual({ done: false, value: 'owner' }) + await expect(survivor.next()).resolves.toEqual({ done: false, value: 'owner' }) + const running = call(ctx, peer, 'slow') + const pending = stream.next() + await peer.dispose() + // The stream's method signal joins the Peer's, so disposal cancels it like a carrier cancel. + await expect(pending).rejects.toMatchObject({ code: 'gateway/cancelled' }) + fixture.release.resolve() + await expect(running).resolves.toBe('owner') + const next = survivor.next() + let settled = false + void next.then(() => { settled = true }, () => { settled = true }) + await new Promise(resolve => setTimeout(resolve, 10)) + expect(settled).toBe(false) + survivorAbort.abort() + await expect(next).rejects.toMatchObject({ code: 'gateway/cancelled' }) + }) +}) + +/** Install a pushable event source; `push` yields one dispatch to every open `$events` stream. */ +function eventSource(ctx: Context): (dispatch: TypertRemoteEventDispatch) => void { + const queue: TypertRemoteEventDispatch[] = [] + let wake: (() => void) | undefined + ctx.effect(() => ctx.typertGateway.registerRemoteEvents(async function* (signal) { + while (!signal.aborted) { + while (queue.length > 0) yield queue.shift() as TypertRemoteEventDispatch + await new Promise((resolve) => { + wake = resolve + signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) + } + }, { home: '/fixture' })) + return (dispatch) => { + queue.push(dispatch) + wake?.() + } +} + +describe('Gateway forwarded events for non-owner Peers', () => { + it('delivers only allowed broadcasts and no answerable waterfall to a non-owner, and refuses its results', async () => { + const { ctx, hold } = await setup({ connection: true }) + hold(shelf('s1')) + const decide = vi.spyOn(RemoteAccessService.prototype, 'decide') + const push = eventSource(ctx) + const guest = ctx.connection.createPeer({ principal: GUEST }) + const abort = new AbortController() + const guestEvents = (await ctx.typertGateway.wireStream.open('$events', { args: {} }, (async function* () {})(), guest, abort.signal))[Symbol.asyncIterator]() + const guestReady = await guestEvents.next() + // A non-owner stream receives the same Host facts but cannot answer, so it does not count as a live Client. + expect(guestReady.value).toMatchObject({ type: 'ready', host: { home: '/fixture' } }) + expect(ctx.typertGateway.hasLiveClient()).toBe(false) + const ownerEvents = (await ctx.typertGateway.wireStream.open('$events', { args: {} }, (async function* () {})(), ctx.connection.browserPeer, abort.signal))[Symbol.asyncIterator]() + await expect(ownerEvents.next()).resolves.toMatchObject({ value: { type: 'ready', host: { home: '/fixture' } } }) + expect(ctx.typertGateway.hasLiveClient()).toBe(true) + + const agentCtx = ctx.extend({}) + const subject = {} + const settled = vi.fn() + push({ + event: 'fixture/ask', + request: { question: 'q', agent: subject }, + context: { value: agentCtx, subject, agentId: 'agent-1' }, + resolve: settled, + reject: settled, + }) + const resources = { 'test-shelf': (shelfId: unknown) => shelfId } + push({ event: 'fixture/notice', args: ['hello'] }) + push({ event: 'fixture/shelf', args: ['s2'], resources }) + push({ event: 'fixture/shelf', args: ['s1'], resources }) + await expect(ownerEvents.next()).resolves.toMatchObject({ value: { type: 'waterfall', event: 'fixture/ask' } }) + await expect(ownerEvents.next()).resolves.toMatchObject({ value: { type: 'emit', event: 'fixture/notice' } }) + await expect(ownerEvents.next()).resolves.toMatchObject({ value: { type: 'emit', event: 'fixture/shelf', args: ['s2'] } }) + await expect(ownerEvents.next()).resolves.toMatchObject({ value: { type: 'emit', event: 'fixture/shelf', args: ['s1'] } }) + // The global notice and the denied shelf never reach the non-owner; the allowed one arrives whole. + await expect(guestEvents.next()).resolves.toEqual({ done: false, value: { type: 'emit', event: 'fixture/shelf', args: ['s1'] } }) + expect(decide.mock.calls.map(([request]) => request)).toEqual([ + { principal: GUEST, action: 'event:fixture/notice', resources: [GLOBAL] }, + { principal: GUEST, action: 'event:fixture/shelf', resources: [shelf('s2')] }, + { principal: GUEST, action: 'event:fixture/shelf', resources: [shelf('s1')] }, + ]) + + const clientId: unknown = Reflect.get(guestReady.value as object, 'clientId') + const shared = ctx.connection.createSharedFetchHandler('/api') + const refused = await shared.fetch(new Request('http://host/api/$events/result', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + type: 'client-request', + rpcId: 'rpc-result', + method: '$events/result', + payload: { args: { clientId, eventId: 'any', outcome: { kind: 'next' } } }, + }), + }), guest) + expect(await refused.json()).toMatchObject({ + result: { ok: false, error: { code: 'gateway/invocation-unavailable', details: { endpoint: '$events/result' } } }, + }) + abort.abort() + await guestEvents.return?.() + await ownerEvents.return?.() + }) + + it('delivers a global event that a global role lists, and drops one whose resource is missing without asking remoteAccess', async () => { + const { ctx, hold } = await setup({ connection: true }) + hold(GLOBAL, shelf('s1')) + const decisions = recordDecisions() + const push = eventSource(ctx) + const abort = new AbortController() + const open = async (): Promise> => (await ctx.typertGateway.wireStream.open( + '$events', { args: {} }, (async function* () {})(), ctx.connection.createPeer({ principal: GUEST }), abort.signal, + ))[Symbol.asyncIterator]() + const streams = [await open(), await open()] + for (const events of streams) await events.next() + const missing = vi.fn(() => undefined) + push({ event: 'fixture/shelf', args: [null], resources: { 'test-shelf': missing } }) + push({ event: 'fixture/notice', args: ['hello'], resources: {} }) + for (const events of streams) { + await expect(events.next()).resolves.toEqual({ done: false, value: { type: 'emit', event: 'fixture/notice', args: ['hello'] } }) + } + // A frame's resources are resolved once for all non-owner streams. + expect(missing).toHaveBeenCalledOnce() + const notice = { action: 'event:fixture/notice', resources: [GLOBAL] } + expect(decisions()).toEqual([notice, notice]) + abort.abort() + for (const events of streams) await events.return?.() + }) + + it('discards the events buffered for a revoked non-owner Peer and keeps other streams', async () => { + const { ctx, hold } = await setup({ connection: true }) + hold(shelf('s1')) + const push = eventSource(ctx) + const abort = new AbortController() + const open = async (peer: PeerScope): Promise> => + (await ctx.typertGateway.wireStream.open('$events', { args: {} }, (async function* () {})(), peer, abort.signal))[Symbol.asyncIterator]() + const revoked = ctx.connection.createPeer({ principal: GUEST }) + const lagging = await open(revoked) + const other = await open(ctx.connection.createPeer({ principal: GUEST })) + const owner = await open(ctx.connection.browserPeer) + for (const events of [lagging, other, owner]) await events.next() + const resources = { 'test-shelf': (shelfId: unknown) => shelfId } + push({ event: 'fixture/shelf', args: ['s1'], resources }) + push({ event: 'fixture/shelf', args: ['s1'], resources }) + const frame = { done: false, value: { type: 'emit', event: 'fixture/shelf', args: ['s1'] } } + for (const events of [other, owner]) { + await expect(events.next()).resolves.toMatchObject(frame) + await expect(events.next()).resolves.toMatchObject(frame) + } + // Both frames were queued for the lagging stream before its Peer was revoked. + await revoked.dispose() + await expect(lagging.next()).resolves.toEqual({ done: true, value: undefined }) + push({ event: 'fixture/shelf', args: ['s1'], resources }) + for (const events of [other, owner]) await expect(events.next()).resolves.toMatchObject(frame) + abort.abort() + for (const events of [other, owner]) await events.return?.() + }) + + it('contains a throwing policy to the non-owner deliveries it decides', async () => { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) + await ctx.plugin(TypertGatewayService) + provideBrowserCredentials(ctx) + await ctx.plugin({ inject: [...connectionInject], apply: applyConnection }) + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + ctx.remoteAccess.registerPolicy('test-guest', { bindings: () => { throw new Error('binding store unavailable') } }) + const push = eventSource(ctx) + const abort = new AbortController() + const open = async (peer: PeerScope): Promise> => + (await ctx.typertGateway.wireStream.open('$events', { args: {} }, (async function* () {})(), peer, abort.signal))[Symbol.asyncIterator]() + const guestEvents = await open(ctx.connection.createPeer({ principal: GUEST })) + const ownerEvents = await open(ctx.connection.browserPeer) + await guestEvents.next() + await ownerEvents.next() + push({ event: 'fixture/shelf', args: ['s1'], resources: { 'test-shelf': (shelfId: unknown) => shelfId } }) + push({ event: 'fixture/notice', args: ['after'] }) + await expect(ownerEvents.next()).resolves.toMatchObject({ value: { type: 'emit', event: 'fixture/shelf' } }) + // The shared source survives the failure: later events still reach the owner. + await expect(ownerEvents.next()).resolves.toMatchObject({ value: { type: 'emit', event: 'fixture/notice' } }) + expect(warn).toHaveBeenCalledWith( + 'remote access: the "test-guest" policy failed to list bindings for event:fixture/shelf; its further failures are not logged until access state changes') + const guestNext = guestEvents.next() + abort.abort() + await expect(guestNext).resolves.toEqual({ done: true, value: undefined }) + await ownerEvents.return?.() + }) +}) + +describe('resource resolution', () => { + const NEVER = new AbortController().signal + const ROOM = { kind: 'test-shelf', id: 'r1' } as const + const DESK = { kind: 'test-desk', id: 'd1' } as const + const DIRECT: InvocationDescriptor['invocation'] = { kind: 'direct' } + + /** A direct method's descriptor fields carrying only what resource resolution reads. */ + function method(...wires: string[]): Pick { + return { invocation: DIRECT, parameters: wires.map(wire => ({ name: wire, wire, source: 'json' }) as InvocationParameterDescriptor) } + } + + async function registry(): Promise { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(TypertRegistry) + ctx.typert.resources.register('test-shelf', { field: 'roomId' }) + ctx.typert.resources.register('test-desk', { field: 'deskId' }) + return ctx.typert + } + + it('reads a default field from a top-level argument, else from the first object argument, else touches global', async () => { + const typert = await registry() + expect(callResources(typert, undefined, method('roomId'), { roomId: 'r1' }, NEVER)) + .toEqual([ROOM]) + expect(callResources(typert, undefined, method('count', 'tags', 'none', 'request'), { + count: 1, tags: ['r9'], none: null, request: { roomId: 'r1', deskId: 'd1' }, + }, NEVER)).toEqual([ROOM, DESK]) + // Only the first object argument is read; a later one naming the field does not count. + expect(callResources(typert, undefined, method('first', 'second'), { first: {}, second: { roomId: 'r1' } }, NEVER)) + .toEqual([GLOBAL]) + expect(callResources(typert, undefined, method(), {}, NEVER)).toEqual([GLOBAL]) + }) + + it('lets a reader replace the defaults for its kind, called with the positional wire arguments', async () => { + const typert = await registry() + const readers = { 'test-shelf': (ids: unknown) => ids } + expect(callResources(typert, readers, method('ids'), { ids: ['r1', 'r2'] }, NEVER)) + .toEqual([ROOM, { kind: 'test-shelf', id: 'r2' }]) + expect(callResources(typert, readers, method('ids', 'roomId'), { ids: undefined, roomId: 'r9' }, NEVER)) + .toEqual([GLOBAL]) + const signal = new AbortController().signal + const positional = vi.fn((...args: readonly unknown[]) => (args.at(-1) === signal ? args[1] : 'wrong')) + expect(callResources(typert, { 'test-desk': positional }, { + ...method('first', 'desk'), cancellation: { parameter: 'signal' }, + }, { first: 'f', desk: 'd1' }, signal)).toEqual([DESK]) + expect(positional).toHaveBeenCalledWith('f', 'd1', signal) + }) + + it('reads lookup parameters and a Context identity of a declared kind, an omitted optional lookup as none', async () => { + const typert = await registry() + typert.lookups.register('gatewayAccessAgent', { + parameter: 'agent', + wire: 'agentId', + resource: 'test-desk', + hostTypeSymbol: '@fixture/access#Agent', + wireTypeSymbol: '@fixture/access#AgentId', + resolve: (id: string) => ({ id }), + }) + typert.contexts.registerHost('gatewayAccessScope', { + wire: 'scopeId', wireTypeSymbol: '@fixture/access#ScopeId', resource: 'test-desk', resolve: () => undefined, + }) + const agent = { name: 'agent', wire: 'agentId', source: 'lookup', lookup: 'gatewayAccessAgent' } as InvocationParameterDescriptor + const unknownLookup = { name: 'other', wire: 'otherId', source: 'lookup', lookup: 'absentLookup' } as InvocationParameterDescriptor + expect(callResources(typert, undefined, { invocation: DIRECT, parameters: [agent, unknownLookup] }, { agentId: undefined, otherId: 'o1' }, NEVER)) + .toEqual([GLOBAL]) + expect(callResources(typert, undefined, { invocation: DIRECT, parameters: [agent] }, { agentId: 'd1' }, NEVER)) + .toEqual([DESK]) + const scoped = (context: string): InvocationDescriptor['invocation'] => ({ kind: 'context', context, wire: 'scopeId', codec: { mode: 'src-json' } }) + expect(callResources(typert, undefined, { invocation: scoped('gatewayAccessScope'), parameters: [agent] }, { scopeId: 'd0', agentId: 'd1' }, NEVER)) + .toEqual([{ kind: 'test-desk', id: 'd0' }, DESK]) + // A required Context identity is never omitted, so a missing one is malformed. + expect(callResources(typert, undefined, { invocation: scoped('gatewayAccessScope'), parameters: [] }, {}, NEVER)) + .toBeUndefined() + expect(callResources(typert, undefined, { invocation: scoped('absentScope'), parameters: [] }, { scopeId: 'd0' }, NEVER)) + .toEqual([GLOBAL]) + }) + + it('reports invalid resources when a reader throws or returns an empty list, or a resource id is not a non-empty string', async () => { + const typert = await registry() + const one = method('value') + const throwing = { 'test-shelf': () => { throw new TypeError('malformed call') } } + expect(callResources(typert, throwing, one, { value: 1 }, NEVER)).toBeUndefined() + for (const value of ['', 7, ['r1', ''], [null], []]) { + expect(callResources(typert, { 'test-shelf': (read: unknown) => read }, one, { value }, NEVER)).toBeUndefined() + } + // A default field names exactly one identity, so an array is malformed. + for (const roomId of [7, ['r1'], '']) { + expect(callResources(typert, undefined, method('roomId'), { roomId }, NEVER)).toBeUndefined() + } + }) + + it('reads a forwarded event through the readers its entry declares, and the global resource without them', () => { + expect(eventResources(undefined, ['r1'])).toEqual([GLOBAL]) + expect(eventResources({}, ['r1'])).toEqual([GLOBAL]) + expect(eventResources({ 'test-shelf': (id: unknown) => id }, ['r1'])).toEqual([ROOM]) + expect(eventResources({ 'test-desk': (_first: unknown, second: unknown) => second }, ['r1', 'd1'])) + .toEqual([DESK]) + // An event carries every resource it declares, so a missing one is invalid rather than a global event. + expect(eventResources({ 'test-shelf': () => undefined }, ['r1'])).toBeUndefined() + expect(eventResources({ 'test-shelf': () => [] }, ['r1'])).toBeUndefined() + expect(eventResources({ 'test-shelf': () => 7 }, ['r1'])).toBeUndefined() + }) +}) diff --git a/packages/api/gateway/tests/gateway-stream.host.spec.ts b/packages/api/gateway/tests/gateway-stream.host.spec.ts index 012f1b73fa..72a46e21f6 100644 --- a/packages/api/gateway/tests/gateway-stream.host.spec.ts +++ b/packages/api/gateway/tests/gateway-stream.host.spec.ts @@ -21,6 +21,7 @@ import { RemoteError, } from '@deepseek-ai/dsh-typert-protocol' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' +import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access' declare module '@deepseek-ai/dsh-typert-protocol' { interface RemoteErrorDetailsMap { @@ -41,6 +42,7 @@ import type { RemoteEventClientId, RemoteEventInvocationFrame, } from '../src/stream-protocol.ts' +import { ownerPeer, peerFor } from './peer.ts' vi.mock('node:crypto', async (importOriginal) => { const actual = await importOriginal() @@ -56,6 +58,7 @@ class FeedService extends TypertRemoteService { readonly signals: AbortSignal[] = [] readonly peeked: unknown[] = [] readonly peers: PeerScope[] = [] + readonly windows: RemoteInvocation['uplinkWindow'][] = [] leftover: AsyncIterator | undefined source: Iterable = [] returns = 0 @@ -130,6 +133,7 @@ class FeedService extends TypertRemoteService { this.signals.push(signal) const invocation = this.invocation() this.peers.push(invocation.peer) + this.windows.push(invocation.uplinkWindow) try { for await (const item of invocation.uplink()) yield `${prefix}${item}` } finally { @@ -366,13 +370,13 @@ describe('Typert Remote streams', () => { const unregister = ctx.effect(() => ctx.typertGateway.registerRemoteEvents(source.source, REMOTE_HOST)) const abort = new AbortController() const empty = (async function* () {})() - const events = await ctx.typertGateway.wireStream.open('$events', { args: {} }, empty, undefined, abort.signal) + const events = await ctx.typertGateway.wireStream.open('$events', { args: {} }, empty, ownerPeer(ctx), abort.signal) const first = events[Symbol.asyncIterator]() await first.next() expect(ctx.typertGateway.hasLiveClient()).toBe(true) abort.abort() expect(ctx.typertGateway.hasLiveClient()).toBe(false) - const replacement = await ctx.typertGateway.wireStream.open('$events', { args: {} }, empty, undefined, new AbortController().signal) + const replacement = await ctx.typertGateway.wireStream.open('$events', { args: {} }, empty, ownerPeer(ctx), new AbortController().signal) const second = replacement[Symbol.asyncIterator]() try { await second.next() @@ -430,7 +434,7 @@ describe('Typert Remote streams', () => { 'feed/sync', { args: { label: 'wire' } }, toAsync([]), - undefined, + ownerPeer(ctx), new AbortController().signal, ) await expect(collect(source)).resolves.toEqual(['wire:one', 'wire:two']) @@ -439,7 +443,7 @@ describe('Typert Remote streams', () => { 'feed/echo', { args: { prefix: 'wire:' } }, toAsync(['a', 'b']), - undefined, + ownerPeer(ctx), new AbortController().signal, ) await expect(collect(echoed)).resolves.toEqual(['wire:a', 'wire:b']) @@ -448,13 +452,16 @@ describe('Typert Remote streams', () => { it('delivers uplink items through the in-process carrier and ends on half-close', async () => { const { ctx, service } = await setup(false) await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'echo', args: { prefix: '> ' }, uplink: toAsync(['a', 'b']), }))).resolves.toEqual(['> a', '> b']) expect(service.returns).toBe(1) await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'echo', args: { prefix: 'x' }, }))).resolves.toEqual([]) await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'echo', args: { prefix: 'x' }, })).rejects.toMatchObject({ code: 'gateway/signature-invalid', @@ -472,6 +479,7 @@ describe('Typert Remote streams', () => { }), } await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'ignore', args: { prefix: 'i' }, uplink: unread, }))).resolves.toEqual(['i:one', 'i:two']) await vi.waitFor(() => { expect(returned).toHaveBeenCalledOnce() }) @@ -480,6 +488,7 @@ describe('Typert Remote streams', () => { it('fails a stream whose uplink item fails its codec, even when the method swallows the failure', async () => { const { ctx, service } = await setup(false) const rejected = await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'echo', args: { prefix: '' }, uplink: toAsync(['ok', 1]), }) const iterator = rejected[Symbol.asyncIterator]() @@ -494,6 +503,7 @@ describe('Typert Remote streams', () => { expect(service.returns).toBe(1) await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'swallow', args: {}, uplink: toAsync([1]), }))).rejects.toMatchObject({ code: 'gateway/input-invalid' }) }) @@ -502,6 +512,7 @@ describe('Typert Remote streams', () => { const { ctx, service } = await setup(false) const abort = new AbortController() const source = await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'peek', args: {}, uplink: neverYielding(), signal: abort.signal, }) const iterator = source[Symbol.asyncIterator]() @@ -518,6 +529,7 @@ describe('Typert Remote streams', () => { const { ctx, service } = await setup(false) const abort = new AbortController() const source = await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'hold', args: {}, uplink: toAsync(['unread']), signal: abort.signal, }) const iterator = source[Symbol.asyncIterator]() @@ -534,7 +546,9 @@ describe('Typert Remote streams', () => { it('exposes the call as ctx.invocation, delivers codec-less uplink items as unknown, and hands the uplink out once', async () => { const { ctx, service } = await setup(false) + const caller = peerFor(ctx, { kind: 'owner' }) await expect(collect(await ctx.typertGateway.stream({ + peer: caller, namespace: 'feed', method: 'context', args: { label: 'ctx' }, uplink: toAsync([1, { nested: true }]), }))).resolves.toEqual([ 'feed/context:feed:{"label":"ctx"}:ctx', @@ -545,18 +559,22 @@ describe('Typert Remote streams', () => { expect(service.peers.at(-1)?.id).toMatch(/^[0-9a-f-]{36}$/) expect(service.invocationOutsideCall()).toBeUndefined() await expect(collect(await ctx.typertGateway.stream({ + peer: caller, namespace: 'feed', method: 'context', args: { label: 'again' }, }))).resolves.toHaveLength(2) + expect(service.peers.at(-1)).toBe(caller) expect(service.peers.at(-1)).toBe(service.peers.at(-2)) await expect(service.peers.at(-1)?.dispose()).resolves.toBeUndefined() // Items sent to a method that never takes its uplink wait in the carrier and are dropped when the downlink ends. await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'sync', args: { label: 'closed' }, uplink: toAsync(['unread']), }))).resolves.toEqual(['closed:one', 'closed:two']) // Without a codec an item still has to be a JSON-safe value. await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'context', args: { label: 'bad' }, uplink: toAsync([1n]), }))).rejects.toMatchObject({ code: 'gateway/input-invalid', @@ -577,6 +595,7 @@ describe('Typert Remote streams', () => { }), } const source = await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'hold', args: {}, uplink: stuck, signal: abort.signal, }) const iterator = source[Symbol.asyncIterator]() @@ -590,6 +609,7 @@ describe('Typert Remote streams', () => { it('closes the uplink before returning a method blocked on it', async () => { const { ctx } = await setup(false) const source = await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'drain', args: {}, uplink: neverYielding(), }) const iterator = source[Symbol.asyncIterator]() @@ -606,6 +626,7 @@ describe('Typert Remote streams', () => { let index = 0 const returned = vi.fn(async (): Promise> => ({ done: true, value: undefined })) const source = await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'hold', args: {}, uplink: { [Symbol.asyncIterator]: () => ({ next: () => reads[index++]!.promise, return: returned }) }, }) @@ -637,9 +658,9 @@ describe('Typert Remote streams', () => { const { ctx, service } = await setup(false) service.source = { [Symbol.iterator]: () => ({ next: () => new ReadResult() }) } const source = await ctx.typertGateway.stream(direction === 'downlink' - ? { namespace: 'feed', method: 'items', args: {} } + ? { peer: ownerPeer(ctx), namespace: 'feed', method: 'items', args: {} } : { - namespace: 'feed', method: 'echo', args: { prefix: '' }, + peer: ownerPeer(ctx), namespace: 'feed', method: 'echo', args: { prefix: '' }, uplink: { [Symbol.asyncIterator]: () => ({ next: async () => new ReadResult() }) }, }) const iterator = source[Symbol.asyncIterator]() @@ -662,6 +683,7 @@ describe('Typert Remote streams', () => { const next = vi.fn((): IteratorResult => ({ done: false, value: 'item' })) service.source = { [Symbol.iterator]: () => ({ next }) } const source = await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'items', args: {}, signal: abort.signal, }) const iterator = source[Symbol.asyncIterator]() @@ -685,9 +707,9 @@ describe('Typert Remote streams', () => { } service.source = { [Symbol.iterator]: () => ({ next }) } const source = await ctx.typertGateway.stream(direction === 'downlink' - ? { namespace: 'feed', method: 'items', args: {}, signal: abort.signal } + ? { peer: ownerPeer(ctx), namespace: 'feed', method: 'items', args: {}, signal: abort.signal } : { - namespace: 'feed', method: 'hold', args: {}, signal: abort.signal, + peer: ownerPeer(ctx), namespace: 'feed', method: 'hold', args: {}, signal: abort.signal, uplink: { [Symbol.asyncIterator]: () => ({ next }) }, }) const iterator = source[Symbol.asyncIterator]() @@ -704,6 +726,7 @@ describe('Typert Remote streams', () => { it('reports done on every read after the uplink ended', async () => { const { ctx } = await setup(false) await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'rereads', args: {}, uplink: toAsync(['a', 'b']), }))).resolves.toEqual(['a', 'b', 'done']) }) @@ -711,6 +734,7 @@ describe('Typert Remote streams', () => { it('accepts a top-level undefined uplink item where no codec applies and rejects it where one does', async () => { const { ctx } = await setup(false) await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'context', args: { label: 'absent' }, uplink: toAsync([undefined, 'x']), }))).resolves.toEqual([ 'feed/context:feed:{"label":"absent"}:absent', @@ -719,6 +743,7 @@ describe('Typert Remote streams', () => { 'typert gateway: feed/context: invocation.uplink() is available once per call', ]) await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'echo', args: { prefix: '' }, uplink: toAsync([undefined]), }))).rejects.toMatchObject({ code: 'gateway/input-invalid', details: { endpoint: 'feed/echo', field: 'uplink' } }) }) @@ -730,6 +755,7 @@ describe('Typert Remote streams', () => { [Symbol.asyncIterator]: () => ({ next: () => new Promise>(() => {}), return: returned }), } await expect(ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'unary', args: { label: 'a' }, uplink: unread, })).rejects.toMatchObject({ code: 'gateway/signature-invalid' }) await vi.waitFor(() => { expect(returned).toHaveBeenCalledOnce() }) @@ -738,6 +764,7 @@ describe('Typert Remote streams', () => { it('lets a unary method read uplink items while it runs', async () => { const { ctx } = await setup(false) await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'unaryUplink', args: {}, uplink: toAsync(['a', 'b']), })).resolves.toEqual(['a', 'b']) }) @@ -745,10 +772,43 @@ describe('Typert Remote streams', () => { it('derives SRC descriptors whose uplink arrives without a codec', async () => { const { ctx } = await setup(false) await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'srcEcho', args: { prefix: 's:' }, uplink: toAsync(['a', 2]), }))).resolves.toEqual(['s:a', 's:2']) }) + it('passes carrier capacity to the invocation and leaves unlimited carriers without a window', async () => { + const { ctx, service } = await setup(false) + const window = { maxBytes: 512, frameOverheadBytes: 40 } + for (const uplinkWindow of [undefined, window]) { + await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), + namespace: 'feed', method: 'echo', args: { prefix: '' }, uplink: toAsync(['a']), uplinkWindow, + }))).resolves.toEqual(['a']) + } + expect(service.windows).toEqual([undefined, window]) + }) + + it('reports configured frame capacity and the encoded envelope size for the current stream id', async () => { + const { ctx, service } = await setup(true, { streamInboxBytes: 512 }) + const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { headers: { cookie: browserCookie(ctx) } }) + await once(socket, 'open') + try { + const streamId = '界"window' + sendOpen(socket, streamId, 'feed/echo', { prefix: '' }) + socket.send(JSON.stringify({ type: 'end', streamId })) + await vi.waitFor(() => { expect(service.windows).toHaveLength(1) }) + const value = 'line\n界' + const complete = JSON.stringify({ type: 'item', streamId, value }) + expect(service.windows[0]).toEqual({ + maxBytes: 512, frameOverheadBytes: Buffer.byteLength(complete, 'utf8') - Buffer.byteLength(JSON.stringify(value), 'utf8'), + }) + } finally { + socket.close() + await once(socket, 'close') + } + }) + it('echoes uplink frames over the WebSocket carrier and fails misused uplinks per stream', async () => { const { ctx, service } = await setup(true) const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { @@ -770,7 +830,7 @@ describe('Typert Remote streams', () => { ]) }) expect(service.returns).toBe(1) - expect(service.peers.at(-1)).toBe(ctx.connection.operator) + expect(service.peers.at(-1)).toBe(ctx.connection.browserPeer) sendOpen(socket, 'rejected', 'feed/echo', { prefix: '' }) socket.send(JSON.stringify({ type: 'item', streamId: 'rejected', value: 1 })) @@ -827,6 +887,7 @@ describe('Typert Remote streams', () => { const { ctx, service } = await setup(false) const abort = new AbortController() const source = await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'follow', args: { label: 'a' }, @@ -837,35 +898,44 @@ describe('Typert Remote streams', () => { const pending = iterator.next() abort.abort(new Error('fixture cancellation')) await expect(pending).rejects.toThrow('Remote invocation "feed/follow" was aborted') - expect(service.signals).toEqual([abort.signal]) + // A stream's method signal also ends with its Peer, so it follows the caller's signal rather than being it. + expect(service.signals).toHaveLength(1) + expect(service.signals[0]?.reason).toBe(abort.signal.reason) expect(service.returns).toBe(1) await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'sync', args: { label: 'b' }, }))).resolves.toEqual(['b:one', 'b:two']) await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'invalid', args: {}, }))).resolves.toEqual([42]) await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'nonJson', args: {}, }))).resolves.toEqual([1n]) await expect(ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'missing', args: {}, })).rejects.toMatchObject({ code: 'gateway/result-invalid' }) await expect(collect(await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'src', args: { label: 'c' }, }))).resolves.toEqual(['c:src']) const abortedBeforeOpen = new AbortController() abortedBeforeOpen.abort(new Error('cancelled before open')) await expect(ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'abortBeforeOpen', args: {}, signal: abortedBeforeOpen.signal, })).rejects.toThrow('Remote invocation "feed/abortBeforeOpen" was aborted') const abortedBeforeIteration = new AbortController() abortedBeforeIteration.abort(new Error('cancelled before iteration')) const preCancelled = await ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'sync', args: { label: 'ignored' }, signal: abortedBeforeIteration.signal, }) await expect(collect(preCancelled)).rejects.toThrow('Remote invocation "feed/sync" was aborted') @@ -874,9 +944,11 @@ describe('Typert Remote streams', () => { it('keeps unary and stream invocation modes distinct', async () => { const { ctx } = await setup(false) await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'sync', args: { label: 'a' }, })).rejects.toMatchObject({ code: 'gateway/signature-invalid' } satisfies Partial) await expect(ctx.typertGateway.stream({ + peer: ownerPeer(ctx), namespace: 'feed', method: 'unary', args: { label: 'a' }, })).rejects.toMatchObject({ code: 'gateway/signature-invalid' } satisfies Partial) }) @@ -971,7 +1043,7 @@ describe('Typert Remote streams', () => { const idle: AsyncIterable = { [Symbol.asyncIterator]: () => ({ next: () => new Promise>(() => {}), return: returned }), } - const events = await ctx.typertGateway.wireStream.open('$events', { args: {} }, idle, undefined, new AbortController().signal) + const events = await ctx.typertGateway.wireStream.open('$events', { args: {} }, idle, ownerPeer(ctx), new AbortController().signal) await vi.waitFor(() => { expect(returned).toHaveBeenCalledOnce() }) await events[Symbol.asyncIterator]().return?.() @@ -1226,7 +1298,7 @@ describe('Typert Remote streams', () => { it('retries a colliding Remote event Client id before opening the second generation', async () => { const { ctx } = await setup(true) - // Connection minted the operator Peer id above; only the event Client ids are counted below. + // Connection minted the browser Peer id above; only the event Client ids are counted below. randomUuid.mockClear() const source = new RemoteEventSourceProbe() const unregister = ctx.typertGateway.registerRemoteEvents(source.source, REMOTE_HOST) @@ -1560,6 +1632,7 @@ async function setup( provideBrowserCredentials(ctx) } await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) await ctx.plugin(TypertGatewayService, gatewayConfig) if (transport) { await ctx.plugin({ inject: [...connectionInject], apply: applyConnection }) diff --git a/packages/api/gateway/tests/gateway.host.spec.ts b/packages/api/gateway/tests/gateway.host.spec.ts index e0fcbec649..8f3f6fddc4 100644 --- a/packages/api/gateway/tests/gateway.host.spec.ts +++ b/packages/api/gateway/tests/gateway.host.spec.ts @@ -7,7 +7,6 @@ import { apply as applyConnection, inject as connectionInject } from '@deepseek- import type { ConnectionRpcHandler, HostConnectionHandle, - PeerId, PeerScope, } from '@deepseek-ai/dsh-client-connection' import type { WebServer, WebRoute } from '@deepseek-ai/dsh-host-webserver' @@ -23,7 +22,9 @@ import { } from '@deepseek-ai/dsh-typert-protocol' import TypertRegistry, { type TypertContribution } from '@deepseek-ai/dsh-typert-registry' import TypertGatewayService, { TypertGatewayError } from '@deepseek-ai/dsh-api-gateway' +import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access' import { provideBrowserCredentials } from './browser-credentials.ts' +import { ownerPeer } from './peer.ts' interface FixtureAgent { readonly id: string @@ -116,12 +117,12 @@ class FakeConnectionService extends Service { channel: string | undefined matches: ((endpoint: string) => boolean) | undefined handler: FakeRpcHandler | undefined - /** The operator Peer every call this fake dispatches speaks for. */ - readonly operator: PeerScope + /** The browser Peer every call this fake dispatches speaks for. */ + readonly browserPeer: PeerScope constructor(ctx: Context) { super(ctx, 'connection') - this.operator = { id: 'fake-operator' as PeerId, ctx, dispose: () => Promise.resolve() } + this.browserPeer = ownerPeer(ctx) } get rpc() { @@ -135,7 +136,7 @@ class FakeConnectionService extends Service { owner.effect(() => { this.channel = channel this.matches = matches - this.handler = (endpoint, payload, signal) => handler(endpoint, payload, signal, this.operator) + this.handler = (endpoint, payload, signal) => handler(endpoint, payload, signal, this.browserPeer) return () => { this.channel = undefined this.matches = undefined @@ -407,6 +408,7 @@ describe('TypertGatewayService', () => { const abort = new AbortController() await expect(caller.typertGateway.invoke({ + peer: ownerPeer(caller), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: ' ship ' } }, @@ -416,6 +418,7 @@ describe('TypertGatewayService', () => { expect(service.lastSignal).toBe(abort.signal) await expect(caller.typertGateway.invoke({ + peer: ownerPeer(caller), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'again' } }, @@ -431,6 +434,7 @@ describe('TypertGatewayService', () => { registerStrict(ctx, [renameDescriptor()]) await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'rename', args: { agentId: 'agent-1', request: { title: 'land' } }, @@ -446,6 +450,7 @@ describe('TypertGatewayService', () => { const abort = new AbortController() await expect(caller.typertGateway.invoke({ + peer: ownerPeer(caller), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'ship' } }, @@ -464,6 +469,7 @@ describe('TypertGatewayService', () => { registerAgentLookup(ctx, { id: 'agent-1' }) await expect(ctx.extend({ fixtureScope: 'unbound' }).typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'ship' } }, @@ -477,6 +483,7 @@ describe('TypertGatewayService', () => { await dispose() await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'ship' } }, @@ -490,6 +497,7 @@ describe('TypertGatewayService', () => { ctx.typert.contexts.registerHost('gatewayFixture', contextProvider(scoped)) await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'rename', args: { agentId: 'agent-1', request: { title: 'land' } }, @@ -503,15 +511,19 @@ describe('TypertGatewayService', () => { await ctx.plugin(InheritedMethodService) await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'exported', method: 'execute', args: { value: 'ship' }, })).resolves.toBe('ship') await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'empty', method: 'ping', args: {}, })).resolves.toBe('pong') await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'inherited', method: 'run', args: { value: 'land' }, })).resolves.toBe('land') await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'other', method: 'absent', args: {}, }), 'gateway/invocation-unavailable') }) @@ -521,6 +533,7 @@ describe('TypertGatewayService', () => { await colliding.plugin(CollidingWireService) registerAgentLookup(colliding, { id: 'agent-1' }) await expectCode(colliding.typertGateway.invoke({ + peer: ownerPeer(colliding), namespace: 'colliding-wire', method: 'run', args: { agentId: 'agent-1' }, @@ -528,6 +541,7 @@ describe('TypertGatewayService', () => { const missing = await setup() await expectCode(missing.ctx.typertGateway.invoke({ + peer: ownerPeer(missing.ctx), namespace: 'goals', method: 'rename', args: { agentId: 'agent-1', request: { title: 'land' } }, @@ -537,6 +551,7 @@ describe('TypertGatewayService', () => { await contextCollision.plugin(ContextWireService) contextCollision.typert.contexts.registerHost('gatewayFixture', contextProvider(contextCollision.extend())) await expectCode(contextCollision.typertGateway.invoke({ + peer: ownerPeer(contextCollision), namespace: 'context-wire', method: 'run', args: { agentId: 'agent-1' }, @@ -551,6 +566,7 @@ describe('TypertGatewayService', () => { await disposeLookup() await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'ship' } }, @@ -559,6 +575,7 @@ describe('TypertGatewayService', () => { registerAgentLookup(ctx, agent) await serviceFiber.dispose() await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'ship' } }, @@ -573,6 +590,7 @@ describe('TypertGatewayService', () => { await dispose() await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'rename', args: { agentId: 'agent-1', request: { title: 'land' } }, @@ -583,6 +601,7 @@ describe('TypertGatewayService', () => { resolve: () => { throw new Error('provider failed') }, }) const error = await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'rename', args: { agentId: 'agent-1', request: { title: 'land' } }, @@ -600,6 +619,7 @@ describe('TypertGatewayService', () => { registerStrict(ctx, [renameDescriptor()]) await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'rename', args: { agentId: 'agent-1', request: { title: 'land' } }, @@ -615,6 +635,7 @@ describe('TypertGatewayService', () => { wire: 'differentAgentId', }) await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'rename', args: { agentId: 'agent-1', request: { title: 'land' } }, @@ -626,6 +647,7 @@ describe('TypertGatewayService', () => { resolve: () => undefined, }) await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'rename', args: { agentId: 'agent-1', request: { title: 'land' } }, @@ -640,6 +662,7 @@ describe('TypertGatewayService', () => { resolve: async () => { throw new Error('lookup failed') }, }) const failure = await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'ship' } }, @@ -652,6 +675,7 @@ describe('TypertGatewayService', () => { resolve: () => Promise.resolve(undefined), }) await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'ship' } }, @@ -663,6 +687,7 @@ describe('TypertGatewayService', () => { resolve: async id => ({ id }), }) await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'ship' } }, @@ -675,6 +700,7 @@ describe('TypertGatewayService', () => { await dispose() await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'passthrough', args: { value: 'would pass through SRC' }, @@ -684,12 +710,14 @@ describe('TypertGatewayService', () => { it('seeds the no-downgrade guard from definitions present before Gateway startup', async () => { const ctx = new Context() await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) const dispose = registerStrict(ctx, [passthroughDescriptor()]) await ctx.plugin(TypertGatewayService) await ctx.plugin(GoalService) await dispose() await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'passthrough', args: { value: 'would pass through SRC' }, @@ -699,6 +727,7 @@ describe('TypertGatewayService', () => { it('retains the no-downgrade guard across Gateway Service reloads', async () => { const ctx = new Context() await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) const gatewayFiber = ctx.plugin(TypertGatewayService) await gatewayFiber await ctx.plugin(GoalService) @@ -709,6 +738,7 @@ describe('TypertGatewayService', () => { await ctx.plugin(TypertGatewayService) await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'passthrough', args: { value: 'would pass through SRC' }, @@ -721,6 +751,7 @@ describe('TypertGatewayService', () => { await ctx.plugin(SecondSharedService) const error = await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'shared', method: 'run', args: { value: 'ship' }, @@ -739,6 +770,7 @@ describe('TypertGatewayService', () => { const ctx = await setupGateway() await ctx.plugin(testCase.plugin) await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: testCase.namespace, method: 'run', args: testCase.args, @@ -753,6 +785,7 @@ describe('TypertGatewayService', () => { ctx.typert.lookups.register('gatewayFixtureAlias', provider) await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'ship' } }, @@ -764,16 +797,19 @@ describe('TypertGatewayService', () => { registerAgentLookup(ctx, { id: 'agent-1' }) await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: { request: { title: 'ship' } }, }), 'gateway/arguments-invalid') await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'ship' }, optional: true }, }), 'gateway/arguments-invalid') await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: [] as unknown as Record, @@ -786,6 +822,7 @@ describe('TypertGatewayService', () => { registerStrict(ctx, [strictOnlyDescriptor()]) await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'strictOnly', args: { request: { title: 1 } }, @@ -793,6 +830,7 @@ describe('TypertGatewayService', () => { service.nextResult = { title: 1 } await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'strictOnly', args: { request: { title: 'ship' } }, @@ -805,6 +843,7 @@ describe('TypertGatewayService', () => { service.nextResult = 1n await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'strictOnly', args: { request: { title: 'ship' } }, @@ -824,6 +863,7 @@ describe('TypertGatewayService', () => { ])('rejects non-JSON SRC input %#', async (value) => { const { ctx } = await setup() await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'passthrough', args: { value }, @@ -836,6 +876,7 @@ describe('TypertGatewayService', () => { // cannot see which are optional, so an absent field is admitted; the case // above keeps an explicitly undefined field rejected. await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'passthrough', args: {}, @@ -848,6 +889,7 @@ describe('TypertGatewayService', () => { const cyclic: { self?: unknown } = {} cyclic.self = cyclic await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'passthrough', args: { value: cyclic }, @@ -856,6 +898,7 @@ describe('TypertGatewayService', () => { const result = new Date(0) service.nextResult = result await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'passthrough', args: { value: null }, @@ -865,6 +908,7 @@ describe('TypertGatewayService', () => { it('accepts dense JSON and rejects decorated arrays and object properties', async () => { const { ctx } = await setup() await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'passthrough', args: { value: [1, { nested: true }] }, @@ -882,6 +926,7 @@ describe('TypertGatewayService', () => { Object.defineProperty(accessor, 'value', { get: () => true, enumerable: true }) for (const value of [sparseWithExtra, symbolArray, symbolObject, hidden, accessor]) { await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'passthrough', args: { value }, }), 'gateway/input-invalid') } @@ -896,6 +941,7 @@ describe('TypertGatewayService', () => { registerStrict(ctx, [createDescriptor()]) await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'ship' } }, @@ -906,6 +952,7 @@ describe('TypertGatewayService', () => { const ctx = await setupGateway() await ctx.plugin(WrongBindingService) await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'wrong-binding', method: 'run', args: { value: 'ship' }, @@ -914,6 +961,7 @@ describe('TypertGatewayService', () => { await ctx.plugin(GoalService) registerStrict(ctx, [{ ...passthroughDescriptor(), method: 'missing' }]) await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'missing', args: { value: 'ship' }, @@ -931,6 +979,7 @@ describe('TypertGatewayService', () => { method: 'run', }]) await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'no-binding', method: 'run', args: { value: 'ship' }, }), 'gateway/binding-invalid') @@ -954,6 +1003,7 @@ describe('TypertGatewayService', () => { }], }) await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'plain', method: 'run', args: { value: 'land' }, })).resolves.toBe('land') }) @@ -968,6 +1018,7 @@ describe('TypertGatewayService', () => { }) try { await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'missing-method', method: 'run', args: { value: 'ship' }, }), 'gateway/method-unavailable') } finally { @@ -981,6 +1032,7 @@ describe('TypertGatewayService', () => { service.businessError = failure await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'fail', args: { request: { reason: 'fixture' } }, @@ -990,6 +1042,7 @@ describe('TypertGatewayService', () => { it('reports an absent endpoint without retaining receiver state', async () => { const { ctx } = await setup() await expectCode(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'absent', args: {}, @@ -999,6 +1052,7 @@ describe('TypertGatewayService', () => { it('mounts a shared /api interceptor through an optional Connection and returns existing RPC results', async () => { const ctx = new Context().extend({ fixtureScope: 'rpc-caller' }) await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) await ctx.plugin(FakeConnectionService) const gatewayFiber = ctx.plugin(TypertGatewayService) await gatewayFiber @@ -1031,11 +1085,12 @@ describe('TypertGatewayService', () => { abort.abort(new Error('client disconnected')) expect(service.lastSignal?.aborted).toBe(true) await expect(ctx.typertGateway.invoke({ + peer: ownerPeer(ctx), namespace: 'goals', method: 'create', args: { agentId: 'agent-1', request: { title: 'direct' } }, })).resolves.toMatchObject({ title: 'direct' }) - expect(service.lastPeer).toBe(connection.operator) + expect(service.lastPeer).toBe(connection.browserPeer) const invalid = await handler('goals/create', { invalid: true }, signal) expect(invalid).toMatchObject({ ok: false, @@ -1207,6 +1262,7 @@ describe('TypertGatewayService', () => { it('claims and validates in-process Remote event results for the active Client generation', async () => { const ctx = new Context() await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) await ctx.plugin(FakeConnectionService) await ctx.plugin(TypertGatewayService) const connection = rawConnection(ctx) @@ -1229,7 +1285,9 @@ describe('TypertGatewayService', () => { }) })(), { home: '/home/fixture' }) const carrier = new AbortController() - const events = rawGatewayEventHarness(ctx).openRemoteEvents({ args: {} }, carrier.signal) + const events = (await ctx.typertGateway.wireStream.open( + '$events', { args: {} }, (async function* () {})(), ownerPeer(ctx), carrier.signal, + ))[Symbol.asyncIterator]() const opening = await events.next() expect(opening).toMatchObject({ done: false, @@ -1252,7 +1310,7 @@ describe('TypertGatewayService', () => { value: undefined, }) - await events.return(undefined) + await events.return?.(undefined) await unregister() await ctx.fiber.dispose() }) @@ -1260,6 +1318,7 @@ describe('TypertGatewayService', () => { it('preserves a lookup policy rejection through the Connection RPC result', async () => { const ctx = new Context() await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) await ctx.plugin(FakeConnectionService) await ctx.plugin(TypertGatewayService) await ctx.plugin(GoalService) @@ -1284,6 +1343,7 @@ describe('TypertGatewayService', () => { it('caches SRC ownership until the Cordis Service set changes', async () => { const ctx = new Context() await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) await ctx.plugin(FakeConnectionService) await ctx.plugin(TypertGatewayService) const observedFiber = ctx.plugin(ObservedClaimService) @@ -1319,6 +1379,7 @@ describe('TypertGatewayService', () => { const connectionFiber = ctx.plugin({ inject: [...connectionInject], apply: applyConnection }) await connectionFiber await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) const gatewayFiber = ctx.plugin(TypertGatewayService) await gatewayFiber const goalFiber = ctx.plugin(GoalService) @@ -1428,6 +1489,7 @@ async function setup(): Promise<{ async function setupGateway(): Promise { const ctx = new Context() await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) await ctx.plugin(TypertGatewayService) return ctx } @@ -1444,17 +1506,6 @@ function rawConnection(ctx: Context): FakeConnectionService { return receiver[symbols.original] ?? receiver } -interface GatewayEventHarness { - openRemoteEvents(payload: unknown, signal: AbortSignal): AsyncGenerator -} - -function rawGatewayEventHarness(ctx: Context): GatewayEventHarness { - const receiver = ctx.get('typertGateway') as unknown as GatewayEventHarness & { - [symbols.original]?: GatewayEventHarness - } - return receiver[symbols.original] ?? receiver -} - function registerStrict(ctx: Context, descriptors: readonly InvocationDescriptor[]): () => Promise { return ctx.typert.register({ package: '@fixture/gateway', diff --git a/packages/api/gateway/tests/peer.ts b/packages/api/gateway/tests/peer.ts new file mode 100644 index 0000000000..2571e791d5 --- /dev/null +++ b/packages/api/gateway/tests/peer.ts @@ -0,0 +1,30 @@ +/** Owner Peers for Gateway specs: every in-process call names its Peer explicitly. */ +import type { Context } from '@deepseek-ai/cordis' +import { Peer } from '@deepseek-ai/dsh-client-connection' +import type { PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol' + +const owners = new WeakMap() + +/** + * The owner Peer of one test Context tree, created on first use. + * @param ctx - any Context of the tree; the Peer hangs under its root. + * @returns the tree's shared owner Peer. + */ +export function ownerPeer(ctx: Context): PeerScope { + let peer = owners.get(ctx.root) + if (peer === undefined) { + peer = new Peer(ctx.root, { principal: { kind: 'owner' } }) + owners.set(ctx.root, peer) + } + return peer +} + +/** + * A fresh Peer of one principal under the test Context tree. + * @param ctx - any Context of the tree; the Peer hangs under its root. + * @param principal - identity the Peer speaks for. + * @returns an independent Peer. + */ +export function peerFor(ctx: Context, principal: Principal): PeerScope { + return new Peer(ctx.root, { principal }) +} diff --git a/packages/api/gateway/tests/stream-server.host.spec.ts b/packages/api/gateway/tests/stream-server.host.spec.ts index 469aa25b0c..87c0784d5d 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) @@ -527,6 +575,8 @@ async function fixturePeer(): Promise { return { id: 'fixture-peer' as PeerId, ctx: fiber.ctx, + principal: { kind: 'owner' }, + signal: new AbortController().signal, dispose: async () => { await fiber.dispose() }, } } @@ -585,6 +635,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/tests/strict-source.host.spec.ts b/packages/api/gateway/tests/strict-source.host.spec.ts new file mode 100644 index 0000000000..fcf4988c12 --- /dev/null +++ b/packages/api/gateway/tests/strict-source.host.spec.ts @@ -0,0 +1,80 @@ +import { Context, Service } from '@deepseek-ai/cordis' +import { afterEach, expect, it } from 'vitest' +import { z } from 'zod' +import { bindTypertRemote, Remote } from '@deepseek-ai/dsh-typert-protocol' +import TypertRegistry, { type TypertContribution } from '@deepseek-ai/dsh-typert-registry' +import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access' +import TypertGateway from '../src/index.ts' +import { ownerPeer } from './peer.ts' + +const contexts: Context[] = [] +afterEach(async () => { await Promise.all(contexts.splice(0).map(ctx => ctx.fiber.dispose())) }) + +const contribution: TypertContribution = { + package: '@fixture/strict', face: 'host', schemas: [], + model: { services: [], events: [], objects: [] }, + invocations: [{ + id: '@fixture/strict#items/read', service: 'items', namespace: 'items', method: 'read', + invocation: { kind: 'direct' }, + parameters: [{ name: 'request', wire: 'request', source: 'json', codec: { + mode: 'strict', typeSymbol: 'Request', create: () => z.strictObject({ title: z.string() }), + } }], + result: { mode: 'strict', typeSymbol: 'string', create: () => z.string() }, + }], +} + +class ItemsService extends Service { + readonly typertRemote + calls = 0 + constructor(ctx: Context) { + super(ctx, 'items') + this.typertRemote = bindTypertRemote(this, 'items') + } + @Remote + read(request: { title: string }): string { + this.calls++ + return request.title + } +} + +async function setup() { + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) + await ctx.plugin(TypertGateway) + const service = new ItemsService(ctx) + return { ctx, service } +} + +it('validates source dispatch with the ordinary local Registry before invoking the Service', async () => { + const { ctx, service } = await setup() + ctx.typert.register(contribution) + await expect(ctx.typertGateway.invoke({ namespace: 'items', method: 'read', args: { request: { title: 'ready' } }, peer: ownerPeer(ctx) })) + .resolves.toBe('ready') + for (const args of [{}, { request: { title: 'ready', extra: true } }, { request: { title: 1 } }]) { + const code: unknown = expect.stringMatching(/^gateway\/(arguments|input)-invalid$/) + await expect(ctx.typertGateway.invoke({ namespace: 'items', method: 'read', args, peer: ownerPeer(ctx) })) + .rejects.toMatchObject({ code }) + } + expect(service.calls).toBe(1) +}) + +it('allows limited source fallback without recovering erased object constraints', async () => { + const { ctx, service } = await setup() + await expect(ctx.typertGateway.invoke({ namespace: 'items', method: 'read', args: { request: { title: 'ready', extra: true } }, peer: ownerPeer(ctx) })) + .resolves.toBe('ready') + expect(service.calls).toBe(1) +}) + +it('refuses source fallback after the strict definition owner unloads', async () => { + const { ctx, service } = await setup() + const owner = ctx.plugin({ inject: ['typert'], apply(ctx) { ctx.typert.register(contribution) } }) + await owner + expect(ctx.typert.local.get('items/read')).toBe(contribution.invocations[0]) + await owner.dispose() + expect(ctx.typert.local.get('items/read')).toBeUndefined() + await expect(ctx.typertGateway.invoke({ namespace: 'items', method: 'read', args: { request: { title: 'ready' } }, peer: ownerPeer(ctx) })) + .rejects.toMatchObject({ code: 'gateway/definition-unavailable' }) + expect(service.calls).toBe(0) +}) diff --git a/packages/api/gateway/tsconfig.host.json b/packages/api/gateway/tsconfig.host.json index 5cb68a7183..7694cea7cb 100644 --- a/packages/api/gateway/tsconfig.host.json +++ b/packages/api/gateway/tsconfig.host.json @@ -6,6 +6,7 @@ "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" }, "files": [ + "src/access.ts", "src/index.ts", "src/remote-error-codes.ts", "src/stream-protocol.ts", @@ -28,6 +29,9 @@ { "path": "../../client/connection/tsconfig.host.json" }, + { + "path": "../remote-access/tsconfig.host.json" + }, { "path": "../../host/webserver" }, 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 666fa150e5..6170f0a4fc 100644 --- a/packages/api/job-controller/package.json +++ b/packages/api/job-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-job-controller", "description": "Job Remote observation stream and the reference-counted client job-output service", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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", @@ -71,7 +73,7 @@ "dependencies": { "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" 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/remote-access/README.i18n.yaml b/packages/api/remote-access/README.i18n.yaml new file mode 100644 index 0000000000..df8ad59235 --- /dev/null +++ b/packages/api/remote-access/README.i18n.yaml @@ -0,0 +1,34 @@ +# 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/api/remote-access/README.md +/: + en: bbd88553f12d4f3d + zh: c5fa4ac3f9746170 +/deepseek-ai-dsh-api-remote-access: + en: 15713a51f827c9c1 + zh: a1349a5f83efc82c +/deepseek-ai-dsh-api-remote-access/summary: + en: ee81bdee09f42c9b + zh: 41c6864e59c24519 +/deepseek-ai-dsh-api-remote-access/table-of-contents: + en: a18ecc232e3c3933 + zh: b8e43580403f6d77 +/deepseek-ai-dsh-api-remote-access/host-service-remoteaccessservice-ctx-key-remoteaccess: + en: 9175835ea5c5bff1 + zh: 0e33b266fdac3d13 +/deepseek-ai-dsh-api-remote-access/client-face: + en: 1db01235b6af84fa + zh: c0ced511cc1841a0 +/deepseek-ai-dsh-api-remote-access/model-experience: + en: 8b07250cecacd3aa + zh: d28ab93980bdcdad +/deepseek-ai-dsh-api-remote-access/model-experience/kv-cache-effect: + en: 60835eca1cee4e0e + zh: 3b5579ceccd5b5e7 +/deepseek-ai-dsh-api-remote-access/known-limitations-and-deferred-work: + en: 66b483bf5144ac46 + zh: 84bde5e0b1af270b +/deepseek-ai-dsh-api-remote-access/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: e88aeb617ffb74ea diff --git a/packages/api/remote-access/README.md b/packages/api/remote-access/README.md new file mode 100644 index 0000000000..8d9df9e542 --- /dev/null +++ b/packages/api/remote-access/README.md @@ -0,0 +1,97 @@ +--- +description: "Method-level Remote access control for non-owner Peers: role-based policy decisions, list filtering, and the per-Peer access snapshot." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-api-remote-access + +English | [中文](README.zh.md) + +## Summary + +Decides which Remote methods a non-owner Peer may call and which forwarded events it may receive. Business packages define roles, each an action set over one resource kind, and register one policy per non-owner principal kind that binds roles to resources. The [API Gateway](../gateway/README.md) resolves the resources a call or event touches and asks this package before it resolves lookups or decodes arguments. List methods filter items through `allows()`, and each Peer follows its own access snapshot, so the Client can hide entries the Host would refuse. The [Peer principals Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md) owns the design. + +## Table of Contents + +- [Host service: `RemoteAccessService` (ctx key: `remoteAccess`)](#host-service) +- [Client face](#client-face) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Host service: `RemoteAccessService` (ctx key: `remoteAccess`) + +Every composition that mounts [API Gateway](../gateway/README.md) mounts this service: the Gateway injects `remoteAccess` and does not start without it. [`bundle/base`](../../bundle/base/cordis.patch.yml) loads it beside `typert-gateway`. The owner (`{ kind: 'owner' }`) is never checked; every method below concerns non-owner principals. + +| Member | Contract | +|---|---| +| `registerPolicy(kind, policy)` | Registers the `RemoteAccessPolicy` of one non-owner principal kind; its `bindings()` and `explain()` receive principals typed by that kind. A second policy for the same kind throws. The registration is a Cordis effect of the caller's fiber; registration and removal recompute open snapshots. | +| `invalidate(principal?)` | Reports that bindings or condition answers for one principal, or for every principal, may have changed. A business package calls it on every grant, revocation, mode change, and expiry. | +| `decide(request)` | Gateway-only. `request` is `{ principal, action, resources, args? }`: the caller or recipient, the endpoint `ns/method` or `event:`, the valid resources the Gateway resolved, and a call's arguments validated against their Typert-compiled types, with lookup parameters as wire identities. Returns `{ kind: 'allow' }` or `{ kind: 'deny', reason }`; the Gateway throws `remote-access/denied` with details `{ action, reason }` for a denied call and drops a denied event without building an error. The owner and `remoteAccess/follow` are always allowed. | +| `allows(resource)` | Reads the invocation of the Context that accessed the service, so a list method calls `this.ctx.remoteAccess.allows(resource)` for each item. Decides the call's endpoint action on that resource without arguments, reading the bindings again on every check. True for the owner and outside a Remote call. | +| `snapshotFor(principal)` | The baseline a page opens with: `{ type: 'baseline', owner: true }` for the owner, otherwise the principal's current grants. | +| `follow(signal)` | Remote stream `remoteAccess/follow`: one `baseline`, then `upsert` and `remove` frames. The owner receives only `{ type: 'baseline', owner: true }`. The stream ends when `signal` aborts or the service unloads, so a reloaded service starts every reader from a fresh baseline. | + +A role `{ name, resource, actions }` is a plain value naming an action set over one resource kind, `global` or a kind declared in `TypertResourceMap`. A binding `{ role, resource, condition? }` grants the role on one resource of the role's kind. A policy answers `bindings(principal)` and an optional `explain(request)` synchronously from state it holds in memory. A request is allowed only when, on every resolved resource, some binding names that resource, its role lists the action, and it has no condition or its condition allows. Resources are independent: a grant on `global` implies nothing on any other resource, and no resource implies another. A condition receives `{ action, resource, args? }` and runs only for a binding whose resource and role match; `args` is absent for events, snapshots, and list filtering. `bindings()` runs once per `decide()`, once per `allows()` check, and once per snapshot computation; it is never cached across decisions, so time-dependent state applies to the next call. + +The Gateway resolves resources from `@Remote` and `@RemoteScope` `resources` readers, lookup and Host Context adapter `resource` declarations, and the default fields in `typert.resources`, and the [API Gateway](../gateway/README.md) owns that order; this package reads no argument field. A call that names no resource touches the `global` resource alone, so only a `global` role can allow it; putting an action in a `global` role lets the principal call it on any resource the call does not name. The Gateway refuses a call whose resources are invalid with `resource-invalid` without asking `decide()`. + +When `bindings()`, a condition, or `explain()` throws, the decision is refused with `policy-failed`; in a snapshot, a throwing `bindings()` leaves the principal no grant and a throwing condition excludes its action. A faulty rule therefore never breaks the shared `$events` source, the snapshot stream, or page rendering. The service logger reports the first failure of each policy after each `invalidate()` and each policy registration or removal; later failures of that policy stay silent until then. + +A forwarded event is decided as the action `event:` on the resources its forwarding entry's readers name, or on `global` when the entry declares none, and reaches a non-owner whole or not at all; its payload is never trimmed. An event carries every resource it declares, so a reader that returns `undefined` makes the event's resources invalid, and the Gateway delivers it to no non-owner without asking `decide()`. An event names at most one resource, so collection changes travel on follow streams (`session/follow`, `session/control`, `workspace/follow`), whose methods decide each item inline through `allows()`. + +The service adds a `global` row named `REMOTE_ACCESS_SNAPSHOT_KEY` (`__DSH_REMOTE_ACCESS__`) holding the owner baseline `{ type: 'baseline', owner: true }` to every index the webServer renders through `webserver/index-inject`. A business package that renders a non-owner page, such as a liveshare viewer page rendered on the owner Host, places an assignment of that global to `ctx.remoteAccess.snapshotFor(principal)` after every index injection row, for example a `global` row appended to the end of `ctx.webServer.collectIndexInjections()`. The later assignment replaces the owner baseline, and the Client entry reads the global when it mounts, so the page opens with the viewer's grants instead of the owner's. + +| `details.reason` of `remote-access/denied` | Cause | +|---|---| +| `resource-invalid` | Given by the Gateway before `decide()`: a resource reader threw or returned an empty list, or a resource id, including a Context identity, is not a non-empty string. | +| `no-allow` | The principal kind has no policy, or no binding allows the action on some resource and neither a condition nor `explain()` names a reason. | +| `policy-failed` | `bindings()`, a condition, or `explain()` threw; the failure is logged as described above. | +| condition or `explain()` reason | On the first resource no binding allows, the first refusing condition of a matching binding names the reason; without one, `explain(request)` does. | + +Snapshot grants list, per resource the principal's bindings name, the sorted endpoint actions of those bindings' roles that `decide()` allows there without call arguments, so the snapshot agrees with `decide()` for the same principal, action, and resource; a resource with no such action gets no grant, and the stream pushes `remove` once its allowed set becomes empty. `event:` actions never enter the snapshot. Snapshots are recomputed only after `invalidate()` and policy registration or removal. + + +## Client face + +The Client entry reads the baseline the index injected under `REMOTE_ACCESS_SNAPSHOT_KEY` synchronously, mounts the generated `remoteAccess` contribution itself through `mountAccess(ctx, contribution, initial)`, follows the snapshot stream, and provides: + +- the Client service `ctx.remoteAccess.source(kind, id, action)`, an identity-stable boolean source per `(kind, id, action)` for one resource of a declared kind; +- the standard Hook `useRemoteAccess(action)`, which answers on the `global` resource. + +Domain UI packages publish their resource Hooks over `source()`: [ui-session](../../client/ui-session/README.md) provides `useSessionAccess(sessionId, action)` and the Session-scope `useAccess(action)` on Session resources, a different name from the `global` `useRemoteAccess`, and [ui-workspace](../../client/ui-workspace/README.md) provides `useWorkspaceAccess(workspaceId, action)` on Workspace resources. A Hook's `action` is a `RemoteEndpoint`, an endpoint some Client Remote namespace declares. A non-owner answer is whether that resource's grant lists the action and never falls back to the `global` answer, so a resource without a grant, or whose grant lists no action, answers false. Every answer is true for the owner; a non-owner page without an injected baseline, and a non-owner page whose stream fails terminally, answers false; the terminal failure is reported with its error, for a non-owner with the advice to reload the page and for the owner with the note that its answers are unaffected; a reconnect keeps the last snapshot. A malformed injected baseline fails the mount. Hooks never issue requests, and the Host still checks every call. [`dsh-client-test-runtime`](../../test-support/client-runtime/README.md) replaces this row with allow-all access in Client specs. + + +## Model Experience + +None, as this package decides Remote access for Client callers and registers nothing model-facing. + +#### KV Cache effect + +No direct effect. + +## Known Limitations and Deferred Work + + + +- Snapshot and list-filtering decisions carry no call arguments, so a condition that refines its answer from `args` can refuse a call that the snapshot shows as allowed. +- Resource readers and automatic resolution must cover every resource a method touches; a resource the call does not name is not checked, so a principal granted on the named resources reaches it. +- Default resource resolution matches wire field names; adding a field with a registered kind's name to a method adds that kind's resource to the call. +- Exact Connection Fetch routes do not pass through the Gateway; the shared Fetch handler refuses them to every non-owner Peer with 403 until each route declares its own access rule. +- Interaction participation (answering forwarded waterfalls) is owner-only: non-owner `$events` streams receive only the broadcast frames whose `event:` action the policy allows on the event's resources. +- `api-session/added` carries the whole `SessionSummary`, so a non-owner allowed to receive it also learns its `parentSessionId`. +- A granted Session's cwd and tool paths already contain the owner's absolute paths, so the `$events` ready frame gives a non-owner the full `host`, including `home`; the Gateway does not hide `home` separately. +- `workspace/follow` notices a Workspace whose visibility a policy revoked only when that Workspace or the Workspace order next changes, and then replaces the non-owner's baseline; an access change alone sends no frame. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/api/remote-access/README.zh.md b/packages/api/remote-access/README.zh.md new file mode 100644 index 0000000000..8d593f7132 --- /dev/null +++ b/packages/api/remote-access/README.zh.md @@ -0,0 +1,97 @@ +--- +description: "非 owner Peer 的 Remote 方法级访问控制:基于角色的 policy 判定、列表过滤与每个 Peer 的访问快照。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-api-remote-access + +[English](README.md) | 中文 + +## 概述 + +决定非 owner Peer 可以调用哪些 Remote 方法、可以收到哪些转发事件。业务包定义 role(限定一种资源种类的 action 集合),并为每种非 owner principal kind 注册一个 policy,把 role 绑定到资源上。[API Gateway](../gateway/README.zh.md) 解析一次调用或一个事件访问的资源,并在解析 lookup、解码参数之前询问本包。列表方法经 `allows()` 逐项过滤;每个 Peer 订阅自己的访问快照,Client 据此隐藏 Host 会拒绝的入口。设计由 [Peer 身份属性 Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md) 负责。 + +## 目录 + +- [Host 服务:`RemoteAccessService`(ctx key:`remoteAccess`)](#host-service) +- [Client 面](#client-face) +- [模型体验](#model-experience) +- [已知限制与暂缓事项](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## Host 服务:`RemoteAccessService`(ctx key:`remoteAccess`) + +挂载 [API Gateway](../gateway/README.zh.md) 的组合都要挂载本服务:Gateway 注入 `remoteAccess`,没有它就不启动。[`bundle/base`](../../bundle/base/cordis.patch.yml) 紧随 `typert-gateway` 装配它。owner(`{ kind: 'owner' }`)从不受检查;下列成员都只针对非 owner principal。 + +| 成员 | 契约 | +|---|---| +| `registerPolicy(kind, policy)` | 为一种非 owner principal kind 注册 `RemoteAccessPolicy`;其 `bindings()` 与 `explain()` 收到的 principal 按该 kind 定型。同一 kind 再注册一个 policy 即抛错。登记是调用方 fiber 的 Cordis effect;注册与撤回都会重新计算已打开的快照。 | +| `invalidate(principal?)` | 报告某个 principal(省略时为所有 principal)的 binding 或 condition 结论可能已变化。业务包在每次授权、撤权、模式切换与过期时调用。 | +| `decide(request)` | 仅供 Gateway 使用。`request` 为 `{ principal, action, resources, args? }`:调用方或接收方、端点 `ns/method` 或 `event:`、Gateway 解析出的合法资源,以及调用中按 Typert 编译类型校验后的参数(lookup 参数为 wire 身份)。返回 `{ kind: 'allow' }` 或 `{ kind: 'deny', reason }`;调用被拒时由 Gateway 抛出 details 为 `{ action, reason }` 的 `remote-access/denied`,事件被拒时由 Gateway 直接丢弃、不构造错误。owner 与 `remoteAccess/follow` 恒放行。 | +| `allows(resource)` | 读访问本服务的 Context 上的 invocation,因此列表方法对每一项调用 `this.ctx.remoteAccess.allows(resource)`。不带参数判定该调用的端点 action 在该资源上是否被允许,每次判定都重新读取 binding。owner 与 Remote 调用之外恒为 true。 | +| `snapshotFor(principal)` | 页面打开时的 baseline:owner 为 `{ type: 'baseline', owner: true }`,否则为该 principal 当前的 grant。 | +| `follow(signal)` | Remote stream `remoteAccess/follow`:一个 `baseline`,之后是 `upsert` 与 `remove` 帧。owner 只收到 `{ type: 'baseline', owner: true }`。`signal` abort 或服务卸载时流结束,因此重载后的服务从新的 baseline 回答每个读者。 | + +role `{ name, resource, actions }` 是普通值,表示限定一种资源种类(`global` 或在 `TypertResourceMap` 中声明的种类)的 action 集合。binding `{ role, resource, condition? }` 在该 role 种类的一个资源上授予该 role。policy 根据预先载入内存的状态同步回答 `bindings(principal)` 与可选的 `explain(request)`。只有在每个已解析资源上都有某个 binding 指向该资源、其 role 列出该 action、且没有 condition 或 condition 放行时,请求才被放行。资源之间相互独立:`global` 上的授权不蕴含任何其他资源上的授权,任何资源也不蕴含另一个资源。condition 收到 `{ action, resource, args? }`,只对资源与 role 都匹配的 binding 调用;事件、快照与列表过滤时没有 `args`。`bindings()` 在每次 `decide()`、每次 `allows()` 判定与每次快照计算中各调用一次,不跨判定缓存,因此依赖时间的状态对下一次调用即时生效。 + +Gateway 依次从 `@Remote` 与 `@RemoteScope` 的 `resources` 读取函数、lookup 与 Host Context adapter 的 `resource` 声明、`typert.resources` 中的默认字段解析资源,解析顺序由 [API Gateway](../gateway/README.zh.md) 负责;本包不读取任何参数字段。不指明任何资源的调用只访问 `global` 资源,因此只有 `global` 级 role 能放行;把某个 action 放进 `global` 级 role,等于允许该 principal 在调用未指明的任何资源上调用它。资源非法的调用由 Gateway 以 `resource-invalid` 拒绝,不询问 `decide()`。 + +`bindings()`、condition 或 `explain()` 抛错时,本次判定以 `policy-failed` 拒绝;计算快照时,`bindings()` 抛错即该 principal 没有 grant,condition 抛错即该 action 不放行。有问题的规则因此不会破坏共享的 `$events` 事件源、快照流或页面渲染。每次 `invalidate()` 以及每次 policy 注册或撤回之后,服务日志对每个 policy 只报告第一次失败;此后该 policy 的失败不再记录,直到下一次上述变化。 + +转发事件按其转发条目的读取函数指明的资源(条目未声明时为 `global`)判定 action `event:`,对非 owner 整条送达或整条不送,从不裁剪 payload。事件携带其声明的每个资源,因此读取函数返回 `undefined` 时该事件的资源非法,Gateway 不询问 `decide()`,不送达任何非 owner。一个事件至多指明一个资源,因此集合类变化走 follow 类流(`session/follow`、`session/control`、`workspace/follow`),由这些方法内联经 `allows()` 逐项判定。 + +本服务经 `webserver/index-inject` 为 webServer 渲染的每个 index 加入名为 `REMOTE_ACCESS_SNAPSHOT_KEY`(`__DSH_REMOTE_ACCESS__`)的 `global` 行,值为 owner baseline `{ type: 'baseline', owner: true }`。渲染非 owner 页面的业务包(例如在 owner Host 上渲染 liveshare 读者页)在所有 index 注入行之后放置一条把该全局赋值为 `ctx.remoteAccess.snapshotFor(principal)` 的语句,例如追加到 `ctx.webServer.collectIndexInjections()` 末尾的一条 `global` 行。后写的赋值覆盖 owner baseline,Client 入口在挂载时读取该全局,因此页面以读者的 grant 而非 owner 的快照打开。 + +| `remote-access/denied` 的 `details.reason` | 原因 | +|---|---| +| `resource-invalid` | 由 Gateway 在 `decide()` 之前给出:资源读取函数抛错或返回空列表,或某个资源 id(含 Context 身份)不是非空字符串。 | +| `no-allow` | 该 principal kind 没有 policy,或在某个资源上没有 binding 放行该 action,且 condition 与 `explain()` 都没有给出原因。 | +| `policy-failed` | `bindings()`、condition 或 `explain()` 抛错;该失败按上文规则记录日志。 | +| condition 或 `explain()` 的原因 | 在第一个没有 binding 放行的资源上,取匹配 binding 中第一个拒绝的 condition 的原因;没有时取 `explain(request)` 的返回值。 | + +快照 grant 按该 principal 的 binding 所指的每个资源,列出这些 binding 的 role 中、经 `decide()` 在该资源上不带调用参数放行的端点 action(已排序),因此在同一 principal、action 与资源上快照与 `decide()` 一致;没有此类 action 的资源不出 grant,放行集合变空时推送 `remove`。`event:` action 不进入快照。快照只在 `invalidate()` 与 policy 注册或撤回之后重算。 + + +## Client 面 + +Client 入口同步读取 index 注入在 `REMOTE_ACCESS_SNAPSHOT_KEY` 下的 baseline,经 `mountAccess(ctx, contribution, initial)` 自行挂载生成的 `remoteAccess` contribution,订阅快照流,并提供: + +- Client 服务 `ctx.remoteAccess.source(kind, id, action)`,为已声明种类的某个资源上的每个 `(kind, id, action)` 提供一个身份稳定的布尔 source; +- 标准 Hook `useRemoteAccess(action)`,回答 `global` 资源上的访问。 + +领域 UI 包在 `source()` 之上发布各自资源的 Hook:[ui-session](../../client/ui-session/README.zh.md) 提供 Session 资源上的 `useSessionAccess(sessionId, action)` 与会话作用域的 `useAccess(action)`(与 `global` 资源上的 `useRemoteAccess` 不同名),[ui-workspace](../../client/ui-workspace/README.zh.md) 提供 Workspace 资源上的 `useWorkspaceAccess(workspaceId, action)`。Hook 的 `action` 类型为 `RemoteEndpoint`,即某个 Client Remote namespace 声明的端点。非 owner 的答案是该资源的 grant 是否列出该 action,不回退 `global` 答案,因此没有 grant 或 grant 未列出任何 action 的资源回答 false。owner 的所有答案为 true;没有注入 baseline 的非 owner 页面、快照流终止失败的非 owner 页面,所有答案为 false;终止失败会连同错误一并报告,非 owner 附“刷新页面重连”的提示,owner 附“答案不受影响”的说明;重连期间保留上次快照。注入的 baseline 格式错误时挂载失败。Hook 从不发请求,Host 仍检查每次调用。[`dsh-client-test-runtime`](../../test-support/client-runtime/README.zh.md) 在 Client spec 中以全允许的访问替换本行。 + + +## 模型体验 + +无:本包为 Client 调用方判别 Remote 访问,不注册任何面向模型的内容。 + +#### KV Cache 影响 + +无直接影响。 + +## 已知限制与暂缓事项 + + + +- 快照与列表过滤的判定不带调用参数,因此按 `args` 细化结论的 condition 可能拒绝快照显示为允许的调用。 +- 资源读取函数与自动解析必须覆盖方法访问的全部资源;调用未指明的资源不受检查,持有已指明资源授权的 principal 可以访问它。 +- 默认资源解析按 wire 字段名匹配;给方法新增与已登记种类同名的字段,会让调用多访问该种类的资源。 +- exact Connection Fetch route 不经过 Gateway;在各路由声明自己的访问规则之前,共享 Fetch handler 对所有非 owner Peer 返回 403。 +- 交互参与(回答转发的 waterfall)仅限 owner:非 owner 的 `$events` 流只收到 policy 在事件资源上放行其 `event:` action 的广播帧。 +- `api-session/added` 携带完整的 `SessionSummary`,因此被允许接收它的非 owner 也会得知其 `parentSessionId`。 +- 被授权 Session 的 cwd 与工具路径本就包含 owner 的绝对路径,因此 `$events` ready 帧向非 owner 提供完整的 `host`(含 `home`);Gateway 不单独隐藏 `home`。 +- policy 撤销某个 Workspace 的可见性后,`workspace/follow` 只在该 Workspace 或 Workspace 顺序下一次变化时察觉并重推非 owner 的 baseline;仅访问变化不会发送帧。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +无。 + +
diff --git a/packages/api/remote-access/package.json b/packages/api/remote-access/package.json new file mode 100644 index 0000000000..a6eaaf4e8c --- /dev/null +++ b/packages/api/remote-access/package.json @@ -0,0 +1,87 @@ +{ + "name": "@deepseek-ai/dsh-api-remote-access", + "description": "Method-level Remote access control for non-owner Peers and the per-Peer access snapshot", + "version": "0.2.1-alpha.2", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/api/remote-access" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./typert": { + "types": "./lib/typert.host.d.ts", + "default": "./lib/typert.host.js" + }, + "./remote": { + "types": "./lib/typert.remote-client.d.ts", + "default": "./lib/typert.remote-client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "dsh": { + "client": { + "external": [ + "@deepseek-ai/dsh-api-gateway/client" + ], + "inject": [ + "@deepseek-ai/dsh-api-gateway", + "@deepseek-ai/dsh-client-ui-renderer" + ], + "platform": "web" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "files": [ + "lib/index.js", + "lib/client.js", + "lib/types/**/*.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "lib/typert.host.js", + "lib/typert.host.d.ts", + "lib/typert.remote-client.js", + "lib/typert.remote-client.d.ts", + "lib/typert.remote-client.d.ts.map", + "src" + ], + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "zod": "4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-client-connection": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-host-webserver": "workspace:*", + "@deepseek-ai/dsh-typert-registry": "workspace:*" + } +} diff --git a/packages/api/remote-access/src/client/index.ts b/packages/api/remote-access/src/client/index.ts new file mode 100644 index 0000000000..396f56a16a --- /dev/null +++ b/packages/api/remote-access/src/client/index.ts @@ -0,0 +1,33 @@ +/** + * Client face: starts from the access snapshot the index injected, follows + * the calling Peer's snapshot stream, provides the `remoteAccess` Client + * service whose `source(kind, id, action)` answers for any declared-kind + * resource, and publishes `useRemoteAccess(action)` on the global resource. + * Domain UI adapters publish their own resource Hooks over `source()`. Every + * answer is a boolean: true for the owner, false without a snapshot or after + * a non-owner stream fails; the Host enforces every call regardless. + * @module @deepseek-ai/dsh-api-remote-access/client + */ + +import type { Context } from '@deepseek-ai/cordis' +import remoteAccessRemote from '@deepseek-ai/dsh-api-remote-access/remote' +import { REMOTE_ACCESS_SNAPSHOT_KEY } from '../snapshot.ts' +import { mountAccess } from './mount.ts' +import { parseInjectedBaseline } from './state.ts' + +export type { + RemoteAccessAction, RemoteAccessEndpoint, RemoteAccessFrame, RemoteAccessGrant, RemoteAccessResource, TypertResourceKind, +} from '../types.ts' +export type { ClientRemoteAccess, RemoteEndpoint } from './mount.ts' + +/** Required Client services: the Remote mount face and the Slot registry. */ +export const inject = ['remote', 'slots'] + +/** + * Mount the generated `remoteAccess` namespace and publish the access Hooks. + * @param ctx - Client root Context. + * @returns disposer that withdraws the namespace after the stream stops. + */ +export function apply(ctx: Context): Promise<() => Promise> { + return mountAccess(ctx, remoteAccessRemote, parseInjectedBaseline(Reflect.get(globalThis, REMOTE_ACCESS_SNAPSHOT_KEY))) +} diff --git a/packages/api/remote-access/src/client/mount.ts b/packages/api/remote-access/src/client/mount.ts new file mode 100644 index 0000000000..257aa396c2 --- /dev/null +++ b/packages/api/remote-access/src/client/mount.ts @@ -0,0 +1,132 @@ +/** + * Client access mount: follows the calling Peer's access snapshot, provides + * the `remoteAccess` Client service, and publishes the global-resource `useRemoteAccess` Hook. + * The entry module supplies the generated `remoteAccess` contribution, so + * specs mount a fake one. + * @module @deepseek-ai/dsh-api-remote-access/src/client/mount + */ + +import { Service, type Context } from '@deepseek-ai/cordis' +import { + RemoteSnapshotStream, + RemoteStreamCarrierError, + type ClientRemote, +} from '@deepseek-ai/dsh-api-gateway/client' +import type {} from '@deepseek-ai/dsh-api-remote-access/remote' +import type { HostObservable, RootStandardSourceContribution } from '@deepseek-ai/dsh-client-ui-slots' +// Type-only: the SlotRegistry (`ctx.slots`) merge. +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { TypertRemoteContribution, TypertRemoteMap, TypertResourceKind } from '@deepseek-ai/dsh-typert-protocol' +import type { RemoteAccessFrame } from '../types.ts' +import { ClientAccessState, type Baseline } from './state.ts' + +/** Every endpoint the Client Remote namespaces declare. */ +export type RemoteEndpoint = Extract + +/** Client access answers over the calling Peer's snapshot; it never issues a request. */ +export interface ClientRemoteAccess { + /** + * Whether the current Peer may call `action` on one resource. + * True for the owner; false without a baseline and after a non-owner + * stream fails; otherwise whether the resource's grant lists the action. + * @param kind - resource kind declared in `TypertResourceMap`. + * @param id - resource identity. + * @param action - endpoint action the caller would invoke. + * @returns identity-stable boolean source for this `(kind, id, action)`. + */ + source(kind: TypertResourceKind, id: string, action: string): HostObservable +} + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Client access answers for the calling Peer. */ + remoteAccess: ClientRemoteAccess + } +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface GlobalStandardProps { + /** Whether the current Peer may call `action` on the global resource. */ + useRemoteAccess: (action: RemoteEndpoint) => boolean + } +} + +type IncrementFrame = Exclude + +/** The `remoteAccess` Client service over one snapshot owner. */ +class ClientRemoteAccessService extends Service implements ClientRemoteAccess { + /** + * @param ctx - Client Context the service is provided on. + * @param state - snapshot owner answering every source. + */ + constructor(ctx: Context, private readonly state: ClientAccessState) { + super(ctx, 'remoteAccess') + } + + source(kind: TypertResourceKind, id: string, action: string): HostObservable { + return this.state.resource(kind, id, action) + } +} + +/** + * Mount the `remoteAccess` namespace, follow the access snapshot, provide the + * `remoteAccess` Client service, and publish the global-resource `useRemoteAccess` Hook. + * Answers start from the page's injected baseline, or false without one, + * and follow the stream's frames from then on. + * @param ctx - Client root Context injecting `remote` and `slots`. + * @param contribution - generated `remoteAccess` Remote contribution. + * @param initial - the page's injected opening baseline, read before the stream connects. + * @returns disposer that withdraws the namespace after the stream stops. + */ +export async function mountAccess( + ctx: Context, + contribution: TypertRemoteContribution, + initial?: Baseline, +): Promise<() => Promise> { + const state = new ClientAccessState(initial) + new ClientRemoteAccessService(ctx, state) + ctx.slots.provideRoot({ + keyedHooks: { remoteAccess: action => state.global(action) }, + } satisfies RootStandardSourceContribution) + const unmount = await ctx.remote.$mount(contribution) + const follow = ctx.inject(['remote.remoteAccess'], (remoteCtx) => { + const control = createAccessStream(remoteCtx.remote, state, remoteCtx.logger) + control.start() + remoteCtx.effect(() => async () => { await control.dispose() }, 'remote-access.client.follow') + }) + return async () => { + await follow.dispose() + await unmount() + } +} + +/** + * Create the reconnecting access snapshot stream. A carrier loss keeps the + * last snapshot while the stream reconnects; a terminal failure keeps the + * owner's answers and turns a non-owner's answers false. + */ +function createAccessStream( + remote: ClientRemote, + state: ClientAccessState, + logger: Context['logger'], +): RemoteSnapshotStream { + const stream = remote.$stream({ + name: 'Remote access stream', + open: signal => remote.remoteAccess.follow(signal), + ended: accepted => accepted + ? new RemoteStreamCarrierError('Remote access stream ended without a terminal result') + : new Error('Remote access stream ended before its opening snapshot'), + }) + return new RemoteSnapshotStream(stream, { + name: 'Remote access stream', + isSnapshot: (frame): frame is Baseline => frame.type === 'baseline', + replace: (frame) => { state.replace(frame) }, + update: (frame) => { state.update(frame) }, + failed: (error) => { + // Only a non-owner's answers turn false after a terminal failure, so only its report names the recovery. + if (state.owner) logger.error('access snapshot stream failed; owner access answers are unaffected', error) + else logger.error('access snapshot stream failed; reload the page to reconnect', error) + state.unavailable() + }, + }) +} diff --git a/packages/api/remote-access/src/client/state.ts b/packages/api/remote-access/src/client/state.ts new file mode 100644 index 0000000000..b0ee02b400 --- /dev/null +++ b/packages/api/remote-access/src/client/state.ts @@ -0,0 +1,208 @@ +/** + * React-free Client access state: the latest `remoteAccess/follow` snapshot + * and identity-stable boolean sources per resource and action. + * @module @deepseek-ai/dsh-api-remote-access/src/client/state + */ + +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { RemoteAccessFrame, RemoteAccessGrant, RemoteAccessResource } from '../types.ts' + +/** Actions allowed per resource identity, for one declared resource kind. */ +type KindGrants = ReadonlyMap> + +type AccessSnapshot = + /** No baseline, or a non-owner snapshot stream failed: every answer is false. */ + | { readonly kind: 'closed' } + | { readonly kind: 'owner' } + | { + readonly kind: 'granted' + readonly global: ReadonlySet + readonly resources: ReadonlyMap + } + +type GrantedSnapshot = Extract + +const CLOSED: AccessSnapshot = Object.freeze({ kind: 'closed' }) +const OWNER_SNAPSHOT: AccessSnapshot = Object.freeze({ kind: 'owner' }) +const GLOBAL_KEY = '\u0000global' + +/** The opening frame of a snapshot generation. */ +export type Baseline = Extract + +/** + * Validate the opening baseline an index injection row assigned to the page. + * @param value - the injected global; `undefined` when the page carries none. + * @returns the baseline, or `undefined` when none was injected. + * @throws TypeError when the injected value is not a baseline frame. + */ +export function parseInjectedBaseline(value: unknown): Baseline | undefined { + if (value === undefined) return undefined + if (!isRecord(value) || value['type'] !== 'baseline') throw new TypeError('remote access: the injected access snapshot is not a baseline frame') + if (value['owner'] === true) return { type: 'baseline', owner: true } + const grants = value['grants'] + if (value['owner'] !== false || !Array.isArray(grants) || !grants.every(isGrant)) { + throw new TypeError('remote access: the injected access snapshot carries malformed grants') + } + return { type: 'baseline', owner: false, grants } +} + +function isGrant(value: unknown): value is RemoteAccessGrant { + if (!isRecord(value) || !isResource(value['resource'])) return false + const actions = value['actions'] + return Array.isArray(actions) && actions.every(action => typeof action === 'string') +} + +function isResource(value: unknown): value is RemoteAccessResource { + if (!isRecord(value) || typeof value['kind'] !== 'string') return false + return value['kind'] === 'global' || typeof value['id'] === 'string' +} + +function isRecord(value: unknown): value is Readonly> { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** + * Snapshot owner for one Client generation. Sources are cached per + * `(kind, id, action)` so Hook bindings keep their identity; each source + * computes its boolean from the current snapshot. + */ +export class ClientAccessState { + private snapshot: AccessSnapshot = CLOSED + + /** @param initial - the page's injected opening baseline; without one every answer is false until a baseline arrives. */ + constructor(initial?: Baseline) { + if (initial !== undefined) this.replace(initial) + } + private readonly listeners = new Set<() => void>() + private readonly sources = new Map>() + + /** + * Answer for one action on the global resource. + * @param action - endpoint action the caller may invoke. + * @returns identity-stable boolean source. + */ + global(action: string): HostObservable { + return this.cached(GLOBAL_KEY, '', action) + } + + /** + * Answer for one action on one resource of a declared kind. + * @param kind - declared resource kind. + * @param id - resource identity. + * @param action - endpoint action the caller may invoke. + * @returns identity-stable boolean source. + */ + resource(kind: string, id: string, action: string): HostObservable { + return this.cached(kind, id, action) + } + + /** + * Replace the snapshot from one generation's opening frame. + * @param frame - owner or non-owner baseline. + */ + replace(frame: Baseline): void { + if (frame.owner) { + this.publish(OWNER_SNAPSHOT) + return + } + let global: ReadonlySet = new Set() + const resources = new Map>>() + // The baseline is unpublished, so its maps are filled in place. + for (const { resource, actions } of frame.grants) { + if (resource.kind === 'global') { + global = new Set(actions) + continue + } + let grants = resources.get(resource.kind) + if (grants === undefined) { + grants = new Map() + resources.set(resource.kind, grants) + } + grants.set(resource.id, new Set(actions)) + } + this.publish({ kind: 'granted', global, resources }) + } + + /** + * Apply one increment of the current generation. + * @param frame - `upsert` or `remove`. + */ + update(frame: Exclude): void { + const current = this.snapshot + if (current.kind !== 'granted') return + switch (frame.type) { + case 'upsert': + this.publish(withGrant(current, frame.grant)) + return + case 'remove': + this.publish(withGrant(current, { resource: frame.resource, actions: [] }, true)) + return + /* v8 ignore next -- the generated Remote codec validates this closed union. */ + default: + return assertNever(frame) + } + } + + /** Whether the current snapshot is the owner's, whose answers never depend on the stream. */ + get owner(): boolean { + return this.snapshot.kind === 'owner' + } + + /** The stream failed terminally: the owner keeps every answer; a non-owner's answers become false. */ + unavailable(): void { + if (this.snapshot.kind !== 'owner') this.publish(CLOSED) + } + + private cached(kind: string, id: string, action: string): HostObservable { + const key = `${kind}\u0000${id}\u0000${action}` + let source = this.sources.get(key) + if (source === undefined) { + source = { + getSnapshot: () => answer(this.snapshot, kind, id, action), + subscribe: (listener) => { + this.listeners.add(listener) + return () => { this.listeners.delete(listener) } + }, + } + this.sources.set(key, source) + } + return source + } + + private publish(next: AccessSnapshot): void { + this.snapshot = next + for (const listener of [...this.listeners]) listener() + } +} + +function answer(snapshot: AccessSnapshot, kind: string, id: string, action: string): boolean { + switch (snapshot.kind) { + case 'closed': + return false + case 'owner': + return true + case 'granted': { + const allowed = kind === GLOBAL_KEY ? snapshot.global : snapshot.resources.get(kind)?.get(id) + return allowed?.has(action) ?? false + } + /* v8 ignore next -- closed union. */ + default: + return assertNever(snapshot) + } +} + +function withGrant(snapshot: GrantedSnapshot, grant: RemoteAccessGrant, remove = false): GrantedSnapshot { + const resource = grant.resource + if (resource.kind === 'global') return { ...snapshot, global: new Set(grant.actions) } + const resources = new Map(snapshot.resources) + const grants = new Map(resources.get(resource.kind)) + if (remove) grants.delete(resource.id) + else grants.set(resource.id, new Set(grant.actions)) + resources.set(resource.kind, grants) + return { ...snapshot, resources } +} + +/* v8 ignore next 3 -- closed-union backstop. */ +function assertNever(value: never): never { + throw new Error(`unreachable access frame: ${JSON.stringify(value)}`) +} diff --git a/packages/api/remote-access/src/index.ts b/packages/api/remote-access/src/index.ts new file mode 100644 index 0000000000..5b3cf41e0f --- /dev/null +++ b/packages/api/remote-access/src/index.ts @@ -0,0 +1,424 @@ +/** + * Host method-level access control. The Gateway asks `decide()` before it + * dispatches a non-owner call or forwards an event to a non-owner Peer; list + * methods filter items through `allows()`; every Peer reads its own access + * snapshot, first from the index and then from `follow()`. Business packages + * register one policy per non-owner principal kind. + * @module @deepseek-ai/dsh-api-remote-access + */ + +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-host-webserver' +import { + Remote, + TypertRemoteService, + principalOf, + type Principal, + type PrincipalMap, + type RemoteAccessResource, +} from '@deepseek-ai/dsh-typert-protocol' +import { REMOTE_ACCESS_SNAPSHOT_KEY } from './snapshot.ts' +import type { + RemoteAccessAction, + RemoteAccessDecision, + RemoteAccessFrame, + RemoteAccessGrant, + RemoteAccessPolicy, + RemoteAccessRequest, +} from './types.ts' + +export type * from './types.ts' +export { REMOTE_ACCESS_SNAPSHOT_KEY } from './snapshot.ts' + +/** The opening frame of a snapshot generation. */ +export type RemoteAccessBaseline = Extract + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Host method-level access control for non-owner Peers. */ + remoteAccess: RemoteAccessService + } +} + +/** The snapshot endpoint every Peer may read for itself. */ +const FOLLOW_ACTION: RemoteAccessAction = 'remoteAccess/follow' +const ALLOW: RemoteAccessDecision = Object.freeze({ kind: 'allow' }) +const NO_ALLOW: RemoteAccessDecision = Object.freeze({ kind: 'deny', reason: 'no-allow' }) +const POLICY_FAILED: RemoteAccessDecision = Object.freeze({ kind: 'deny', reason: 'policy-failed' }) +const OWNER: Principal = Object.freeze({ kind: 'owner' }) +const OWNER_BASELINE: RemoteAccessBaseline = Object.freeze({ type: 'baseline', owner: true }) + +/** + * A binding seen without its resource kind. Method syntax keeps the condition + * of every kind assignable; each condition is called only with a resource + * equal to its own binding's resource. + */ +interface ErasedBinding { + readonly role: { readonly actions: readonly RemoteAccessAction[] } + readonly resource: RemoteAccessResource + condition?(request: { + readonly action: RemoteAccessAction + readonly resource: RemoteAccessResource + readonly args?: Readonly> + }): RemoteAccessDecision +} + +/** One registered policy with the principal kind it serves. */ +interface PolicyEntry { + readonly kind: string + readonly policy: RemoteAccessPolicy +} + +/** A condition's refusal. */ +type Refusal = Extract + +/** The answer for one action on one resource, before any `explain()`. */ +type Evaluation = + | { readonly kind: 'allow' } + /** No binding allows; `refusal` is the first refusing condition's decision, if any condition ran. */ + | { readonly kind: 'refuse'; readonly refusal: Refusal | undefined } + | { readonly kind: 'failed' } + +const ALLOWED: Evaluation = Object.freeze({ kind: 'allow' }) +const FAILED: Evaluation = Object.freeze({ kind: 'failed' }) + +/** One open non-owner snapshot generation; changes coalesce until its reader wakes. */ +class AccessFollower { + private dirty = false + private wake: (() => void) | undefined + + /** @param principal - the generation's caller identity; never the owner. */ + constructor(readonly principal: Principal) {} + + /** Mark the generation stale and wake its reader. */ + touch(): void { + this.dirty = true + this.wake?.() + } + + /** + * Wait until the generation is stale or cancelled. + * @param signal - generation cancellation. + * @returns true when stale; false once cancelled. + */ + async changed(signal: AbortSignal): Promise { + const abort = (): void => { this.wake?.() } + signal.addEventListener('abort', abort, { once: true }) + try { + while (!this.dirty && !signal.aborted) { + await new Promise((resolve) => { this.wake = resolve }) + this.wake = undefined + } + } finally { + signal.removeEventListener('abort', abort) + } + this.dirty = false + return !signal.aborted + } +} + +/** + * Registry of access policies, the Gateway's access decisions, list + * filtering, and the per-Peer access snapshot. Every composition that mounts + * the Gateway mounts this service too. + */ +export class RemoteAccessService extends TypertRemoteService { + private readonly policies = new Map() + /** Policies whose failure was logged since the last `invalidate()`; their later failures stay silent. */ + private readonly reported = new Set() + private readonly followers = new Set() + /** Aborted when this instance unloads; every open snapshot generation ends with it. */ + private readonly lifetime = new AbortController() + + /** @param ctx - owning Host plugin Context. */ + constructor(ctx: Context) { + super(ctx, 'remoteAccess') + ctx.effect(() => () => { this.lifetime.abort() }, 'remoteAccess: snapshot generations') + // Every index the webServer renders belongs to the owner; snapshotFor documents non-owner pages. + ctx.inject(['webServer'], (webCtx) => { + webCtx.on('webserver/index-inject', (table) => { + table.push({ kind: 'global', name: REMOTE_ACCESS_SNAPSHOT_KEY, value: OWNER_BASELINE }) + }) + }) + } + + /** + * Register the policy of one non-owner principal kind in the caller's + * fiber; open snapshots are recomputed on registration and removal. + * @param kind - the principal kind the policy serves; never `owner`. + * @param policy - business-owned bindings and refusal reasons for principals of `kind`. + * @returns disposer removing this policy. + * @throws Error when `kind` already has a policy. + */ + registerPolicy>(kind: K, policy: RemoteAccessPolicy): () => void { + const policies = this.policies + if (policies.has(kind)) throw new Error(`remote access: principal kind ${JSON.stringify(kind)} already has a policy`) + const entry: PolicyEntry = { kind, policy } + const dispose = this.ctx.effect(() => { + policies.set(kind, entry) + this.invalidate() + return () => { + policies.delete(kind) + this.invalidate() + } + }, `remoteAccess.registerPolicy(${JSON.stringify(kind)})`) + return () => { void dispose() } + } + + /** + * Report that the bindings or condition answers for `principal` may have + * changed. Business packages call this on every grant, revocation, mode + * change, and expiry; open snapshots re-push, and the next failure of each + * policy is logged again. + * @param principal - affected principal; omitted for every principal. + */ + invalidate(principal?: Principal): void { + this.reported.clear() + const key = principal === undefined ? undefined : canonicalJson(principal) + for (const follower of this.followers) { + if (key === undefined || canonicalJson(follower.principal) === key) follower.touch() + } + } + + /** + * Gateway-only: decide one request whose resources the Gateway resolved. + * The owner is allowed, and so is `remoteAccess/follow`: every Peer reads + * its own snapshot. Otherwise the action is allowed only when, on every + * listed resource, some binding of the principal's policy names that + * resource, has a role listing the action, and has no condition or a + * condition that allows. `bindings()` is called once per decision. + * @param request - the caller or recipient, the action, the resources it + * touches, and a call's arguments. + * @returns `allow`; or `deny` with `no-allow` when the principal kind has + * no policy, the first refusing condition's reason on the first resource + * no binding allows, else `explain()`'s reason, else `no-allow`; + * `policy-failed` when `bindings()`, a condition, or `explain()` throws, + * logged once per policy until the next `invalidate()`. The Gateway + * throws `remote-access/denied` for a denied call and drops a denied event. + */ + decide(request: RemoteAccessRequest): RemoteAccessDecision { + const { principal, action } = request + // oxlint-disable-next-line typescript/no-unnecessary-condition -- other packages merge non-owner kinds into PrincipalMap. + if (principal.kind === 'owner' || action === FOLLOW_ACTION) return ALLOW + const entry = this.policies.get(principal.kind) + if (entry === undefined) return NO_ALLOW + const bindings = this.bindingsOf(entry, principal, action) + if (bindings === undefined) return POLICY_FAILED + for (const resource of request.resources) { + const evaluation = this.evaluate(entry, bindings, action, resource, request.args) + switch (evaluation.kind) { + case 'allow': + continue + case 'failed': + return POLICY_FAILED + case 'refuse': + return evaluation.refusal ?? this.explain(entry, request) + /* v8 ignore next -- closed union. */ + default: + return assertNever(evaluation) + } + } + return ALLOW + } + + /** + * Filter items inside a Remote method. The invocation is read from the + * Context that accessed this service, so call it as + * `this.ctx.remoteAccess.allows(resource)` from the Remote method. Each + * check reads the policy's bindings again, so a long-running stream sees + * binding changes from the next check on. + * @param resource - resource of one result item. + * @returns true for the owner and outside a Remote call; otherwise whether + * the invocation's endpoint action is allowed on `resource` without call + * arguments, false when the policy is absent or fails. + */ + allows(resource: RemoteAccessResource): boolean { + const invocation = this.ctx.invocation + const principal = principalOf(invocation) + if (invocation === undefined || principal === undefined) return true + const action: RemoteAccessAction = `${invocation.request.namespace}/${invocation.request.method}` + const entry = this.policies.get(principal.kind) + if (entry === undefined) return false + const bindings = this.bindingsOf(entry, principal, action) + return bindings !== undefined && this.evaluate(entry, bindings, action, resource, undefined).kind === 'allow' + } + + /** + * The baseline a page opens with before its snapshot stream connects. A + * business package rendering a non-owner page assigns this value to + * {@link REMOTE_ACCESS_SNAPSHOT_KEY} after every index injection row, + * replacing the owner baseline the webServer index carries. + * @param principal - the page's caller identity. + * @returns the owner baseline for the owner; otherwise the principal's current grants. + */ + snapshotFor(principal: Principal): RemoteAccessBaseline { + // oxlint-disable-next-line typescript/no-unnecessary-condition -- other packages merge non-owner kinds into PrincipalMap. + if (principal.kind === 'owner') return OWNER_BASELINE + return { type: 'baseline', owner: false, grants: this.grantsFor(principal) } + } + + /** + * Stream the calling Peer's access snapshot: one baseline, then `upsert` + * and `remove` frames after each `invalidate()` and each policy + * registration or removal that changes a grant. The owner receives only + * `{ owner: true }`. The generation ends when `signal` aborts or this + * service unloads, so a reloaded service starts every reader from a fresh + * baseline. + * @param signal - generation cancellation. + * @returns the access frames of one generation. + */ + @Remote({ mode: 'stream' }) + async *follow(signal: AbortSignal): AsyncIterable { + signal.throwIfAborted() + const generation = AbortSignal.any([signal, this.lifetime.signal]) + const principal = principalOf(this.ctx.invocation) + if (principal === undefined) { + yield this.snapshotFor(OWNER) + await abortion(generation) + return + } + const follower = new AccessFollower(principal) + this.followers.add(follower) + try { + let sent = this.grantsFor(principal) + yield { type: 'baseline', owner: false, grants: sent } + while (await follower.changed(generation)) { + const next = this.grantsFor(principal) + const previous = sent + sent = next + for (const grant of next) { + const before = previous.find(other => sameResource(other.resource, grant.resource)) + if (before === undefined || !sameActions(before.actions, grant.actions)) yield { type: 'upsert', grant } + } + for (const grant of previous) { + if (!next.some(other => sameResource(other.resource, grant.resource))) yield { type: 'remove', resource: grant.resource } + } + } + } finally { + this.followers.delete(follower) + } + } + + /** One `bindings()` call; `undefined` after a logged failure. */ + private bindingsOf(entry: PolicyEntry, principal: Principal, purpose: string): readonly ErasedBinding[] | undefined { + try { + return entry.policy.bindings(principal) + } catch (error) { + // A policy failure is contained to this question, so one faulty rule cannot break a shared event stream. + this.report(entry, `list bindings for ${purpose}`, error) + return undefined + } + } + + /** Find a binding on `resource` whose role lists `action` and whose condition, if any, allows. */ + private evaluate( + entry: PolicyEntry, + bindings: readonly ErasedBinding[], + action: RemoteAccessAction, + resource: RemoteAccessResource, + args: Readonly> | undefined, + ): Evaluation { + let refusal: Refusal | undefined + for (const binding of bindings) { + if (!sameResource(binding.resource, resource) || !binding.role.actions.includes(action)) continue + if (binding.condition === undefined) return ALLOWED + let decision: RemoteAccessDecision + try { + decision = binding.condition(args === undefined ? { action, resource } : { action, resource, args }) + } catch (error) { + this.report(entry, `evaluate a condition for ${action}`, error) + return FAILED + } + if (decision.kind === 'allow') return ALLOWED + refusal ??= decision + } + return { kind: 'refuse', refusal } + } + + /** The refusal reason `explain()` names, else `no-allow`; `policy-failed` when it throws. */ + private explain(entry: PolicyEntry, request: RemoteAccessRequest): RemoteAccessDecision { + let reason: string | undefined + try { + reason = entry.policy.explain?.(request) + } catch (error) { + this.report(entry, `explain a refusal of ${request.action}`, error) + return POLICY_FAILED + } + return reason === undefined ? NO_ALLOW : { kind: 'deny', reason } + } + + /** + * One grant per bound resource, in first-binding order: the endpoint + * actions of the resource's bindings that `decide()` would allow there + * without call arguments. A resource with no such action gets no grant; + * event actions stay out of the snapshot. + */ + private grantsFor(principal: Principal): readonly RemoteAccessGrant[] { + const entry = this.policies.get(principal.kind) + if (entry === undefined) return [] + const bindings = this.bindingsOf(entry, principal, 'a snapshot') + if (bindings === undefined) return [] + const grants: RemoteAccessGrant[] = [] + const seen: RemoteAccessResource[] = [] + for (const { resource } of bindings) { + if (seen.some(other => sameResource(other, resource))) continue + seen.push(resource) + const candidates = new Set() + for (const binding of bindings) { + if (!sameResource(binding.resource, resource)) continue + for (const action of binding.role.actions) { + if (!action.startsWith('event:')) candidates.add(action) + } + } + const actions = [...candidates].filter(action => this.evaluate(entry, bindings, action, resource, undefined).kind === 'allow').sort() + if (actions.length > 0) grants.push(Object.freeze({ resource, actions: Object.freeze(actions) })) + } + return grants + } + + /** Log a policy failure once per policy until the next `invalidate()`; snapshots and lists ask many times per change. */ + private report(entry: PolicyEntry, action: string, error: unknown): void { + if (this.reported.has(entry)) return + this.reported.add(entry) + this.ctx.logger.warn( + `remote access: the ${JSON.stringify(entry.kind)} policy failed to ${action}; its further failures are not logged until access state changes`) + this.ctx.logger.warn(error) + } +} + +/* v8 ignore next 3 -- closed-union backstop. */ +function assertNever(value: never): never { + throw new Error(`remote access: unreachable value ${JSON.stringify(value)}`) +} + +/** Key-order-independent JSON text identifying one principal. */ +function canonicalJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]` + if (typeof value === 'object' && value !== null) { + // Own keys are unique, so no two entries compare equal. + const entries = Object.entries(value).sort(([left], [right]) => (left < right ? -1 : 1)) + return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(',')}}` + } + return JSON.stringify(value) +} + +/** Resources are equal when their kinds and ids are; `global` carries no id. */ +function sameResource( + left: { readonly kind: string; readonly id?: unknown }, + right: { readonly kind: string; readonly id?: unknown }, +): boolean { + return left.kind === right.kind && left.id === right.id +} + +function sameActions(left: readonly string[], right: readonly string[]): boolean { + return left.length === right.length && left.every((action, index) => action === right[index]) +} + +function abortion(signal: AbortSignal): Promise { + return new Promise((resolve) => { + if (signal.aborted) resolve() + else signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) +} + +export default RemoteAccessService diff --git a/packages/api/remote-access/src/snapshot.ts b/packages/api/remote-access/src/snapshot.ts new file mode 100644 index 0000000000..ad3a490205 --- /dev/null +++ b/packages/api/remote-access/src/snapshot.ts @@ -0,0 +1,8 @@ +/** + * The index global carrying a page's first access snapshot, shared by the + * Host row that writes it and the Client mount that reads it. + * @module @deepseek-ai/dsh-api-remote-access/src/snapshot + */ + +/** `globalThis` property an index injection row assigns to the page's opening baseline. */ +export const REMOTE_ACCESS_SNAPSHOT_KEY = '__DSH_REMOTE_ACCESS__' diff --git a/packages/api/remote-access/src/types.ts b/packages/api/remote-access/src/types.ts new file mode 100644 index 0000000000..c598ee60a2 --- /dev/null +++ b/packages/api/remote-access/src/types.ts @@ -0,0 +1,142 @@ +/** + * Method-level access control contracts: actions, roles, bindings, policies, + * decision requests, and the access snapshot stream. + * @module @deepseek-ai/dsh-api-remote-access/types + */ + +import type { + Principal, + RemoteAccessResource, + RemoteAccessResourceKind, + RemoteAccessResourceOf, +} from '@deepseek-ai/dsh-typert-protocol' + +export type { + RemoteAccessResource, + RemoteAccessResourceKind, + RemoteAccessResourceOf, + TypertResourceKind, + TypertResourceMap, +} from '@deepseek-ai/dsh-typert-protocol' + +/** Canonical `/` Remote endpoint; its segments never contain `:`. */ +export type RemoteAccessEndpoint = `${string}/${string}` + +/** A Remote endpoint, or `event:` for one forwarded event. */ +export type RemoteAccessAction = RemoteAccessEndpoint | `event:${string}` + +/** A named action set over one resource kind; a plain value the business package owns. */ +export interface RemoteAccessRole { + /** Name for diagnostics; decisions read only `resource` and `actions`. */ + readonly name: string + /** The resource kind every binding of this role names. */ + readonly resource: K + /** Actions the role allows on its binding's resource. */ + readonly actions: readonly RemoteAccessAction[] +} + +/** Answer of `decide()` and of a condition. */ +export type RemoteAccessDecision = + | { readonly kind: 'allow' } + | { readonly kind: 'deny'; readonly reason: string } + +/** + * Refines one binding for one action on its resource. Called synchronously, + * only for a binding whose resource matches and whose role lists the action. + * @param request - the action, the binding's resource, and the named + * arguments of a concrete call, validated against their Typert-compiled + * types with lookup parameters as wire identities; `args` is absent for + * events, snapshots, and list filtering, where the condition answers for + * the action alone. + * @returns allow, or deny with the reason a refused call reports. + */ +export type RemoteAccessCondition = (request: { + readonly action: RemoteAccessAction + readonly resource: RemoteAccessResourceOf + readonly args?: Readonly> +}) => RemoteAccessDecision + +/** One role on one resource of the role's kind; the resource type follows from the role. */ +export type RemoteAccessBinding = { + [K in RemoteAccessResourceKind]: { + readonly role: RemoteAccessRole + readonly resource: RemoteAccessResourceOf + /** Without a condition, the binding allows every action its role lists. */ + readonly condition?: RemoteAccessCondition + } +}[RemoteAccessResourceKind] + +/** One access question: may `principal` take `action` on `resources`. */ +export interface RemoteAccessRequest

{ + readonly principal: P + readonly action: RemoteAccessAction + /** + * Every resource the action touches, the global resource alone when it + * names none; allowed only when the action is allowed on every listed resource. + */ + readonly resources: readonly RemoteAccessResource[] + /** + * Named arguments of a concrete call, validated against their Typert-compiled types + * with lookup parameters as wire identities; absent for events, snapshots, and list filtering. + */ + readonly args?: Readonly> +} + +/** + * Business rules for one non-owner principal kind. Every member answers + * synchronously from state the business package holds in memory. + */ +export interface RemoteAccessPolicy

{ + /** + * List the principal's bindings. Called once per `decide()`, once per + * `allows()`, and once per snapshot computation; never cached. + * @param principal - non-owner caller of this policy's kind. + * @returns every binding the principal holds now. + */ + bindings(principal: P): readonly RemoteAccessBinding[] + /** + * Name the reason for a request no binding allows; called only after the + * decision is already a deny, so it never changes the decision. + * @param request - the refused request. + * @returns the reason a refused call reports, or `undefined` for `no-allow`. + */ + explain?(request: RemoteAccessRequest

): string | undefined +} + +/** Details of a refused non-owner call. */ +export interface RemoteAccessDeniedDetails { + /** Canonical `/` endpoint of the refused call. */ + readonly action: string + /** + * A condition's or `explain()`'s reason, `no-allow`, or `policy-failed`; + * the Gateway refuses a call whose resources are invalid with + * `resource-invalid` before `decide()` is asked. + */ + readonly reason: string +} + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface RemoteErrorDetailsMap { + 'remote-access/denied': RemoteAccessDeniedDetails + } +} + +/** The endpoint actions one principal may call on one resource. */ +export interface RemoteAccessGrant { + readonly resource: RemoteAccessResource + /** + * Endpoint actions allowed on this resource without call arguments, sorted; + * plain strings because Typert generates no codec for template literal types. + */ + readonly actions: readonly string[] +} + +/** + * One frame of `remoteAccess/follow`. A generation opens with one baseline; + * an owner baseline is the only frame of its generation. + */ +export type RemoteAccessFrame = + | { readonly type: 'baseline'; readonly owner: true } + | { readonly type: 'baseline'; readonly owner: false; readonly grants: readonly RemoteAccessGrant[] } + | { readonly type: 'upsert'; readonly grant: RemoteAccessGrant } + | { readonly type: 'remove'; readonly resource: RemoteAccessResource } diff --git a/packages/api/remote-access/tests/client-access.client.spec.ts b/packages/api/remote-access/tests/client-access.client.spec.ts new file mode 100644 index 0000000000..b73944ec58 --- /dev/null +++ b/packages/api/remote-access/tests/client-access.client.spec.ts @@ -0,0 +1,291 @@ +import { describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import type { HostObservable, RootStandardSourceContribution } from '@deepseek-ai/dsh-client-ui-slots' +import type { TypertRemoteContribution, TypertResource } from '@deepseek-ai/dsh-typert-protocol' +import type { RemoteAccessFrame, RemoteAccessGrant } from '../src/types.ts' +import { ClientAccessState, parseInjectedBaseline, type Baseline } from '../src/client/state.ts' +import { mountAccess } from '../src/client/mount.ts' + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface TypertResourceMap { + /** Test-only resource kinds; the Client face itself names no kind. */ + 'test-shelf': TypertResource + 'test-desk': TypertResource + } +} + +const GRANTED: Extract = { + type: 'baseline', + owner: false, + grants: [ + { resource: { kind: 'global' }, actions: ['session/list'] }, + { resource: { kind: 'test-shelf', id: 's1' }, actions: ['session/fork', 'session/prompt'] }, + { resource: { kind: 'test-desk', id: 'd1' }, actions: ['workspace/follow'] }, + ], +} + +describe('ClientAccessState', () => { + it('answers false without a baseline and after a non-owner stream fails, and true for the owner', () => { + const state = new ClientAccessState() + expect(state.global('session/create').getSnapshot()).toBe(false) + expect(state.resource('test-shelf', 's9', 'session/fork').getSnapshot()).toBe(false) + state.replace({ type: 'baseline', owner: true }) + expect(state.resource('test-desk', 'd9', 'workspace/follow').getSnapshot()).toBe(true) + state.unavailable() + expect(state.resource('test-desk', 'd9', 'workspace/follow').getSnapshot()).toBe(true) + state.replace(GRANTED) + expect(state.global('session/list').getSnapshot()).toBe(true) + state.unavailable() + expect(state.global('session/list').getSnapshot()).toBe(false) + }) + + it('starts from the injected baseline before any stream frame', () => { + expect(new ClientAccessState({ type: 'baseline', owner: true }).global('session/create').getSnapshot()).toBe(true) + const granted = new ClientAccessState(GRANTED) + expect(granted.global('session/list').getSnapshot()).toBe(true) + expect(granted.resource('test-shelf', 's1', 'session/fork').getSnapshot()).toBe(true) + expect(granted.global('session/create').getSnapshot()).toBe(false) + }) + + it('validates the injected baseline and refuses a malformed one', () => { + expect(parseInjectedBaseline(undefined)).toBeUndefined() + expect(parseInjectedBaseline({ type: 'baseline', owner: true, extra: 1 })).toEqual({ type: 'baseline', owner: true }) + expect(parseInjectedBaseline(JSON.parse(JSON.stringify(GRANTED)))).toEqual(GRANTED) + for (const malformed of [ + null, 'baseline', [], { type: 'upsert' }, + { type: 'baseline' }, { type: 'baseline', owner: false }, { type: 'baseline', owner: false, grants: [7] }, + { type: 'baseline', owner: false, grants: [{ resource: { kind: 'test-shelf' }, actions: [] }] }, + { type: 'baseline', owner: false, grants: [{ resource: { kind: 7 }, actions: [] }] }, + { type: 'baseline', owner: false, grants: [{ resource: { kind: 'global' }, actions: 'session/list' }] }, + { type: 'baseline', owner: false, grants: [{ resource: { kind: 'global' }, actions: [7] }] }, + { type: 'baseline', owner: false, grants: [{ resource: { kind: 'global' } }] }, + { type: 'baseline', owner: false, grants: [{ scope: { kind: 'page' }, endpoints: ['session/list'] }] }, + ]) { + expect(() => parseInjectedBaseline(malformed)).toThrow(TypeError) + } + }) + + it('answers each resource from its own grant without falling back to the global resource', () => { + const state = new ClientAccessState() + state.replace(GRANTED) + expect(state.global('session/list').getSnapshot()).toBe(true) + expect(state.global('session/fork').getSnapshot()).toBe(false) + expect(state.resource('test-shelf', 's1', 'session/fork').getSnapshot()).toBe(true) + expect(state.resource('test-shelf', 's1', 'session/list').getSnapshot()).toBe(false) + expect(state.resource('test-shelf', 's2', 'session/fork').getSnapshot()).toBe(false) + expect(state.resource('test-desk', 'd1', 'workspace/follow').getSnapshot()).toBe(true) + expect(state.resource('test-desk', 'd2', 'workspace/follow').getSnapshot()).toBe(false) + }) + + it('applies upserts and removals and notifies subscribers until they unsubscribe', () => { + const state = new ClientAccessState() + state.replace(GRANTED) + const fork = state.resource('test-shelf', 's1', 'session/fork') + const listener = vi.fn() + const unsubscribe = fork.subscribe(listener) + state.update({ type: 'upsert', grant: { resource: { kind: 'test-shelf', id: 's1' }, actions: ['session/prompt'] } }) + expect(fork.getSnapshot()).toBe(false) + expect(listener).toHaveBeenCalledOnce() + state.update({ type: 'upsert', grant: { resource: { kind: 'global' }, actions: ['session/create'] } }) + expect(state.global('session/create').getSnapshot()).toBe(true) + state.update({ type: 'upsert', grant: { resource: { kind: 'test-desk', id: 'd2' }, actions: ['workspace/follow'] } }) + expect(state.resource('test-desk', 'd2', 'workspace/follow').getSnapshot()).toBe(true) + state.update({ type: 'remove', resource: { kind: 'test-desk', id: 'd2' } }) + expect(state.resource('test-desk', 'd2', 'workspace/follow').getSnapshot()).toBe(false) + state.update({ type: 'remove', resource: { kind: 'test-shelf', id: 's1' } }) + expect(state.resource('test-shelf', 's1', 'session/prompt').getSnapshot()).toBe(false) + // Removing a kind that never had a grant leaves the other kinds intact. + state.update({ type: 'remove', resource: { kind: 'test-shelf', id: 'absent' } }) + unsubscribe() + state.update({ type: 'remove', resource: { kind: 'global' } }) + expect(listener).toHaveBeenCalledTimes(6) + expect(state.global('session/create').getSnapshot()).toBe(false) + }) + + it('applies a baseline of many grants of one kind in one pass and notifies once', () => { + const state = new ClientAccessState() + const first = state.resource('test-shelf', 's0', 'session/fork') + const listener = vi.fn() + first.subscribe(listener) + const grants: RemoteAccessGrant[] = Array.from({ length: 20_000 }, (_, index) => ({ + resource: { kind: 'test-shelf', id: `s${index}` }, + actions: ['session/fork'], + })) + // Copying the kind's grants once per grant takes seconds at this size and exceeds the spec timeout. + state.replace({ type: 'baseline', owner: false, grants }) + expect(listener).toHaveBeenCalledOnce() + expect(first.getSnapshot()).toBe(true) + expect(state.resource('test-shelf', 's19999', 'session/fork').getSnapshot()).toBe(true) + expect(state.resource('test-shelf', 's20000', 'session/fork').getSnapshot()).toBe(false) + }) + + it('ignores increments outside a non-owner generation and keeps source identity stable', () => { + const state = new ClientAccessState() + state.update({ type: 'upsert', grant: { resource: { kind: 'global' }, actions: ['session/list'] } }) + expect(state.global('session/list').getSnapshot()).toBe(false) + state.replace({ type: 'baseline', owner: true }) + state.update({ type: 'remove', resource: { kind: 'global' } }) + expect(state.global('session/list').getSnapshot()).toBe(true) + expect(state.global('session/list')).toBe(state.global('session/list')) + expect(state.resource('test-shelf', 's1', 'session/fork')).toBe(state.resource('test-shelf', 's1', 'session/fork')) + expect(state.resource('test-shelf', 's1', 'session/fork')).not.toBe(state.resource('test-desk', 's1', 'session/fork')) + }) +}) + +interface FakeStreamOptions { + readonly name: string + readonly open: (signal: AbortSignal) => unknown + readonly ended: (accepted: boolean) => Error +} + +/** One controllable generation of `remoteAccess/follow`, standing in for the Gateway-owned carrier. */ +class FakeAccessStream { + private readonly frames: RemoteAccessFrame[] = [] + private wake: (() => void) | undefined + private done = false + private failure: Error | undefined + + constructor(readonly options: FakeStreamOptions) {} + + push(frame: RemoteAccessFrame): void { + this.frames.push(frame) + this.wake?.() + } + + fail(error: Error): void { + this.failure = error + this.wake?.() + } + + restart(): void {} + + async dispose(): Promise { + this.done = true + this.wake?.() + } + + async *[Symbol.asyncIterator](): AsyncIterator<{ + readonly generation: number + readonly value: RemoteAccessFrame + readonly accept: () => void + }> { + while (!this.done) { + if (this.failure !== undefined) throw this.failure + const frame = this.frames.shift() + if (frame !== undefined) { + yield { generation: 1, value: frame, accept: () => {} } + continue + } + await new Promise((resolve) => { this.wake = resolve }) + } + } +} + +function value(source: HostObservable | undefined): unknown { + if (source === undefined) throw new Error('missing source') + return source.getSnapshot() +} + +async function mounted(initial?: Baseline): Promise<{ + readonly ctx: Context + readonly stream: () => FakeAccessStream + readonly global: (action: string) => HostObservable | undefined + readonly follow: ReturnType + readonly mount: ReturnType + readonly unmount: ReturnType + readonly contribution: TypertRemoteContribution + readonly dispose: () => Promise +}> { + const ctx = new Context() + let stream: FakeAccessStream | undefined + const follow = vi.fn() + const unmount = vi.fn(async () => {}) + const remote = { + $mount: vi.fn(async () => unmount), + $stream: (options: FakeStreamOptions) => { + stream = new FakeAccessStream(options) + return stream + }, + remoteAccess: { follow }, + } + let root: RootStandardSourceContribution | undefined + ctx.provide('remote', remote as never) + ctx.provide('slots', { + provideRoot: (contribution: RootStandardSourceContribution) => { + root = contribution + return () => {} + }, + } as never) + const contribution: TypertRemoteContribution = { package: '@deepseek-ai/dsh-api-remote-access', descriptors: [] } + let dispose: (() => Promise) | undefined + await ctx.plugin({ + inject: ['remote', 'slots'], + apply: async (pluginCtx: Context) => { dispose = await mountAccess(pluginCtx, contribution, initial) }, + }) + // The generated namespace arrives after the mount, as `$mount` provides it. + ctx.provide('remote.remoteAccess', remote.remoteAccess as never) + await vi.waitFor(() => { expect(stream).toBeDefined() }) + return { + ctx, + stream: () => stream as FakeAccessStream, + global: action => root?.keyedHooks?.['remoteAccess']?.(action), + follow, + mount: remote.$mount, + unmount, + contribution, + dispose: async () => { await dispose?.() }, + } +} + +describe('remote-access Client mount', () => { + it('provides the global-resource Hook and the remoteAccess service over the followed snapshot', async () => { + const access = await mounted() + expect(access.mount).toHaveBeenCalledWith(access.contribution) + const globalFork = access.global('session/fork') + const shelfFork = access.ctx.remoteAccess.source('test-shelf', 's1', 'session/fork') + const deskFollow = access.ctx.remoteAccess.source('test-desk', 'd1', 'workspace/follow') + expect(access.ctx.remoteAccess.source('test-shelf', 's1', 'session/fork')).toBe(shelfFork) + expect([value(globalFork), value(shelfFork), value(deskFollow)]).toEqual([false, false, false]) + + access.stream().push(GRANTED) + await vi.waitFor(() => { expect(value(shelfFork)).toBe(true) }) + expect(value(globalFork)).toBe(false) + expect(value(deskFollow)).toBe(true) + access.stream().push({ type: 'remove', resource: { kind: 'test-shelf', id: 's1' } }) + await vi.waitFor(() => { expect(value(shelfFork)).toBe(false) }) + // Reading an answer never issues a request; only the stream factory reaches the namespace. + expect(access.follow).not.toHaveBeenCalled() + access.stream().options.open(new AbortController().signal) + expect(access.follow).toHaveBeenCalledOnce() + expect(access.stream().options.ended(true).message).toMatch(/without a terminal result/) + expect(access.stream().options.ended(false).message).toMatch(/before its opening snapshot/) + + await access.dispose() + expect(access.unmount).toHaveBeenCalledOnce() + }) + + it('answers from the injected baseline at once and false once a non-owner stream fails terminally', async () => { + const access = await mounted(GRANTED) + const report = vi.spyOn(access.ctx.logger, 'error').mockImplementation(() => undefined) + const globalList = access.global('session/list') + expect(value(globalList)).toBe(true) + const failure = new Error('carrier closed for good') + access.stream().fail(failure) + await vi.waitFor(() => { expect(value(globalList)).toBe(false) }) + expect(report).toHaveBeenCalledWith('access snapshot stream failed; reload the page to reconnect', failure) + await access.dispose() + }) + + it('keeps the owner\'s answers when its stream fails terminally', async () => { + const access = await mounted({ type: 'baseline', owner: true }) + const report = vi.spyOn(access.ctx.logger, 'error').mockImplementation(() => undefined) + const globalFork = access.global('session/fork') + expect(value(globalFork)).toBe(true) + const failure = new Error('carrier closed for good') + access.stream().fail(failure) + await vi.waitFor(() => { expect(report).toHaveBeenCalledOnce() }) + expect(report).toHaveBeenCalledWith('access snapshot stream failed; owner access answers are unaffected', failure) + expect(value(globalFork)).toBe(true) + await access.dispose() + }) +}) diff --git a/packages/api/remote-access/tests/remote-access.host.spec.ts b/packages/api/remote-access/tests/remote-access.host.spec.ts new file mode 100644 index 0000000000..f29d4d1744 --- /dev/null +++ b/packages/api/remote-access/tests/remote-access.host.spec.ts @@ -0,0 +1,610 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import TypertGatewayService from '@deepseek-ai/dsh-api-gateway' +import { Peer } from '@deepseek-ai/dsh-client-connection' +import type { IndexInjection } from '@deepseek-ai/dsh-host-webserver' +import { + Remote, + TypertRemoteService, + type PeerScope, + type Principal, + type PrincipalMap, + type RemoteInvocation, + type TypertResource, +} from '@deepseek-ai/dsh-typert-protocol' +import TypertRegistry from '@deepseek-ai/dsh-typert-registry' +import RemoteAccessService, { + REMOTE_ACCESS_SNAPSHOT_KEY, + type RemoteAccessBinding, + type RemoteAccessCondition, + type RemoteAccessFrame, + type RemoteAccessGrant, + type RemoteAccessPolicy, + type RemoteAccessRequest, + type RemoteAccessResource, + type RemoteAccessResourceOf, + type RemoteAccessRole, +} from '../src/index.ts' + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + /** Test-only non-owner caller shared by the access specs. */ + 'test-guest': { readonly kind: 'test-guest'; readonly guest: string } + /** Test-only non-owner caller whose identity carries a list. */ + 'test-crew': { readonly kind: 'test-crew'; readonly members: readonly string[] } + } + interface TypertResourceMap { + /** Test-only resource kinds; the service itself names no kind. */ + 'test-shelf': TypertResource + 'test-desk': TypertResource + } +} + +type Guest = PrincipalMap['test-guest'] + +const OWNER: Principal = { kind: 'owner' } +const GUEST: Guest = { kind: 'test-guest', guest: 'a' } +const OTHER: Guest = { kind: 'test-guest', guest: 'b' } +const CREW: Principal = { kind: 'test-crew', members: ['a', 'b'] } +const GLOBAL: RemoteAccessResourceOf<'global'> = { kind: 'global' } +const ROOM: RemoteAccessResourceOf<'test-shelf'> = { kind: 'test-shelf', id: 'r1' } +const ROOM2: RemoteAccessResourceOf<'test-shelf'> = { kind: 'test-shelf', id: 'r2' } +const DESK: RemoteAccessResourceOf<'test-desk'> = { kind: 'test-desk', id: 'd1' } + +const READER: RemoteAccessRole<'global'> = { + name: 'test:reader', + resource: 'global', + actions: ['notes/read', 'notes/rooms', 'notes/write', 'event:notes/changed'], +} +const SHELF_READER: RemoteAccessRole<'test-shelf'> = { + name: 'test:shelf-reader', + resource: 'test-shelf', + actions: ['notes/rooms', 'notes/read', 'event:notes/changed'], +} +const SHELF_WRITER: RemoteAccessRole<'test-shelf'> = { name: 'test:shelf-writer', resource: 'test-shelf', actions: ['notes/write'] } +const DESK_WRITER: RemoteAccessRole<'test-desk'> = { name: 'test:desk-writer', resource: 'test-desk', actions: ['notes/write'] } + +class Notes extends TypertRemoteService { + static inject = ['remoteAccess'] + + constructor(ctx: Context) { super(ctx, 'notes') } + + @Remote + read(): string { return 'read' } + + /** Resolves to the shelf its request names through the registered default field. */ + @Remote + write(request: { readonly shelfId: string; readonly text: string }): string { return request.text } + + @Remote + hidden(): string { return 'hidden' } + + /** A list method: a global call, then one `allows()` check per item. */ + @Remote + rooms(): string[] { + return ['r1', 'r2'].filter(id => this.ctx.remoteAccess.allows({ kind: 'test-shelf', id })) + } +} + +/** A policy whose bindings live in memory per guest, the way a business package preloads them. */ +class GuestPolicy implements RemoteAccessPolicy { + readonly held = new Map() + readonly bindings = vi.fn((guest: Guest): readonly RemoteAccessBinding[] => this.held.get(guest.guest) ?? []) + + hold(guest: Guest, ...bindings: RemoteAccessBinding[]): void { + this.held.set(guest.guest, bindings) + } +} + +const roots: Context[] = [] + +afterEach(async () => { + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) +}) + +async function setup(): Promise<{ readonly ctx: Context; readonly access: RemoteAccessService }> { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) + await ctx.plugin(TypertGatewayService) + ctx.typert.resources.register('test-shelf', { field: 'shelfId' }) + await ctx.plugin(Notes) + return { ctx, access: ctx.remoteAccess } +} + +function call(ctx: Context, principal: Principal, method: string, args: Record = {}): Promise { + return ctx.typertGateway.invoke({ peer: new Peer(ctx, { principal }), namespace: 'notes', method, args }) +} + +/** A request by `principal` for `action` on `resources`. */ +function ask(principal: Principal, action: RemoteAccessRequest['action'], ...resources: RemoteAccessResource[]): RemoteAccessRequest { + return { principal, action, resources } +} + +const NEVER = new AbortController().signal + +/** The invocation a Gateway binds while dispatching `remoteAccess/follow` for one principal. */ +function invocationOf(ctx: Context, principal: Principal, method = 'follow', namespace = 'remoteAccess'): RemoteInvocation { + return { + request: { namespace, method, args: {} }, + service: namespace, + peer: new Peer(ctx, { principal }), + signal: NEVER, + uplink: (): AsyncIterable => ({ [Symbol.asyncIterator]: () => ({ next: async () => ({ done: true, value: undefined }) }) }), + } +} + +async function follow(ctx: Context, principal: Principal): Promise<{ + readonly frames: RemoteAccessFrame[] + readonly next: () => Promise + readonly stop: () => Promise +}> { + const abort = new AbortController() + const peer: PeerScope = new Peer(ctx, { principal }) + const stream = await ctx.typertGateway.stream({ peer, namespace: 'remoteAccess', method: 'follow', args: {}, signal: abort.signal }) + const iterator = stream[Symbol.asyncIterator]() + const frames: RemoteAccessFrame[] = [] + return { + frames, + next: async () => { + const result = await iterator.next() + if (result.done === true) throw new Error('access stream ended') + const frame = result.value as RemoteAccessFrame + frames.push(frame) + return frame + }, + stop: async () => { + abort.abort() + await iterator.return?.() + }, + } +} + +interface SpiedListenerMethod { + readonly mock: { readonly calls: readonly unknown[][]; readonly contexts: readonly unknown[] } +} + +/** `abort` registrations a spied `EventTarget` method received on AbortSignals. */ +function abortListenerCalls(spy: SpiedListenerMethod): number { + return spy.mock.calls.filter((args, index) => args[0] === 'abort' && spy.mock.contexts[index] instanceof AbortSignal).length +} + +describe('RemoteAccessService registrations', () => { + it('removes a policy with its disposer and with the plugin fiber that registered it', async () => { + const { ctx, access } = await setup() + const policy = new GuestPolicy() + policy.hold(GUEST, { role: READER, resource: GLOBAL }) + const dispose = access.registerPolicy('test-guest', policy) + await expect(call(ctx, GUEST, 'read')).resolves.toBe('read') + dispose() + await expect(call(ctx, GUEST, 'read')).rejects.toMatchObject({ code: 'remote-access/denied', details: { reason: 'no-allow' } }) + const fiber = ctx.plugin({ + inject: ['remoteAccess'], + apply: (pluginCtx: Context) => { pluginCtx.remoteAccess.registerPolicy('test-guest', policy) }, + }) + await fiber + await expect(call(ctx, GUEST, 'read')).resolves.toBe('read') + await fiber.dispose() + await expect(call(ctx, GUEST, 'read')).rejects.toMatchObject({ code: 'remote-access/denied', details: { reason: 'no-allow' } }) + }) + + it('accepts one policy per principal kind', async () => { + const { access } = await setup() + access.registerPolicy('test-guest', new GuestPolicy()) + expect(() => access.registerPolicy('test-guest', new GuestPolicy())) + .toThrow('remote access: principal kind "test-guest" already has a policy') + access.registerPolicy('test-crew', { bindings: () => [{ role: READER, resource: GLOBAL }] }) + expect(access.decide(ask(CREW, 'notes/read', GLOBAL))).toEqual({ kind: 'allow' }) + }) +}) + +describe('RemoteAccessService.decide', () => { + it('allows the owner without any policy and refuses a kind without a policy', async () => { + const { ctx, access } = await setup() + expect(access.decide(ask(OWNER, 'notes/hidden', ROOM))).toEqual({ kind: 'allow' }) + await expect(call(ctx, OWNER, 'hidden')).resolves.toBe('hidden') + await expect(call(ctx, GUEST, 'read')).rejects.toMatchObject({ + code: 'remote-access/denied', details: { action: 'notes/read', reason: 'no-allow' }, + }) + }) + + it('allows only actions a bound role lists on the resource the binding names', async () => { + const { ctx, access } = await setup() + const policy = new GuestPolicy() + access.registerPolicy('test-guest', policy) + policy.hold(GUEST, { role: READER, resource: GLOBAL }, { role: SHELF_WRITER, resource: ROOM }) + await expect(call(ctx, GUEST, 'read')).resolves.toBe('read') + await expect(call(ctx, GUEST, 'hidden')).rejects.toMatchObject({ details: { action: 'notes/hidden', reason: 'no-allow' } }) + await expect(call(ctx, GUEST, 'write', { request: { shelfId: 'r1', text: 'hi' } })).resolves.toBe('hi') + await expect(call(ctx, GUEST, 'write', { request: { shelfId: 'r2', text: 'hi' } })).rejects.toMatchObject({ details: { reason: 'no-allow' } }) + await expect(call(ctx, OTHER, 'read')).rejects.toMatchObject({ details: { reason: 'no-allow' } }) + // Resources are independent: a global grant implies nothing on a shelf, and a shelf grant nothing on global. + expect(access.decide(ask(GUEST, 'notes/read', ROOM))).toEqual({ kind: 'deny', reason: 'no-allow' }) + expect(access.decide(ask(GUEST, 'notes/write', GLOBAL))).toEqual({ kind: 'allow' }) + policy.hold(GUEST, { role: SHELF_WRITER, resource: ROOM }) + expect(access.decide(ask(GUEST, 'notes/write', GLOBAL))).toEqual({ kind: 'deny', reason: 'no-allow' }) + }) + + it('requires the action on every resource of the target', async () => { + const { access } = await setup() + const policy = new GuestPolicy() + access.registerPolicy('test-guest', policy) + const both = ask(GUEST, 'notes/write', ROOM, DESK) + policy.hold(GUEST, { role: SHELF_WRITER, resource: ROOM }) + expect(access.decide(both)).toEqual({ kind: 'deny', reason: 'no-allow' }) + policy.hold(GUEST, { role: SHELF_WRITER, resource: ROOM }, { role: DESK_WRITER, resource: DESK }) + expect(access.decide(both)).toEqual({ kind: 'allow' }) + expect(policy.bindings).toHaveBeenCalledTimes(2) + }) + + it('asks a matching binding\'s condition, which can refuse with its own reason', async () => { + const { ctx, access } = await setup() + const policy = new GuestPolicy() + access.registerPolicy('test-guest', policy) + const paused = vi.fn>(() => ({ kind: 'deny', reason: 'shelf-paused' })) + const locked = vi.fn>(() => ({ kind: 'deny', reason: 'shelf-locked' })) + const short = vi.fn>(({ args }) => { + const request: unknown = args?.['request'] + return typeof request === 'object' && request !== null && Reflect.get(request, 'text') === 'ok' + ? { kind: 'allow' } + : { kind: 'deny', reason: 'text-refused' } + }) + const unrelated = vi.fn>(() => ({ kind: 'allow' })) + policy.hold(GUEST, + { role: SHELF_READER, resource: ROOM, condition: unrelated }, + { role: SHELF_WRITER, resource: ROOM2, condition: unrelated }, + { role: SHELF_WRITER, resource: ROOM, condition: paused }, + { role: SHELF_WRITER, resource: ROOM, condition: locked }) + await expect(call(ctx, GUEST, 'write', { request: { shelfId: 'r1', text: 'x' } })).rejects.toMatchObject({ + code: 'remote-access/denied', details: { action: 'notes/write', reason: 'shelf-paused' }, + }) + expect(paused).toHaveBeenCalledWith({ action: 'notes/write', resource: ROOM, args: { request: { shelfId: 'r1', text: 'x' } } }) + expect(locked).toHaveBeenCalledOnce() + // A condition runs only for a binding whose resource matches and whose role lists the action. + expect(unrelated).not.toHaveBeenCalled() + + policy.hold(GUEST, { role: SHELF_WRITER, resource: ROOM, condition: short }) + await expect(call(ctx, GUEST, 'write', { request: { shelfId: 'r1', text: 'x' } })).rejects.toMatchObject({ details: { reason: 'text-refused' } }) + await expect(call(ctx, GUEST, 'write', { request: { shelfId: 'r1', text: 'ok' } })).resolves.toBe('ok') + + // Any binding without a condition, or with an allowing one, allows. + policy.hold(GUEST, { role: SHELF_WRITER, resource: ROOM, condition: paused }, { role: SHELF_WRITER, resource: ROOM }) + expect(access.decide(ask(GUEST, 'notes/write', ROOM))).toEqual({ kind: 'allow' }) + expect(paused).toHaveBeenLastCalledWith({ action: 'notes/write', resource: ROOM }) + }) + + it('names the reason explain() gives once no binding allows, without changing the decision', async () => { + const { access } = await setup() + const policy = new GuestPolicy() + const explain = vi.fn((request: { readonly action: string }) => (request.action === 'notes/write' ? 'share-not-writable' : undefined)) + access.registerPolicy('test-guest', { bindings: policy.bindings, explain }) + policy.hold(GUEST, { role: READER, resource: GLOBAL }) + expect(access.decide(ask(GUEST, 'notes/read', GLOBAL))).toEqual({ kind: 'allow' }) + expect(explain).not.toHaveBeenCalled() + const write = { ...ask(GUEST, 'notes/write', ROOM, DESK), args: { request: {} } } + expect(access.decide(write)).toEqual({ kind: 'deny', reason: 'share-not-writable' }) + expect(explain).toHaveBeenCalledWith({ principal: GUEST, action: 'notes/write', resources: [ROOM, DESK], args: { request: {} } }) + expect(access.decide(ask(GUEST, 'notes/hidden', GLOBAL))).toEqual({ kind: 'deny', reason: 'no-allow' }) + expect(explain).toHaveBeenLastCalledWith({ principal: GUEST, action: 'notes/hidden', resources: [GLOBAL] }) + // A refusing condition's reason comes first. + const paused: RemoteAccessCondition<'test-shelf'> = () => ({ kind: 'deny', reason: 'shelf-paused' }) + policy.hold(GUEST, { role: SHELF_WRITER, resource: ROOM, condition: paused }) + expect(access.decide(ask(GUEST, 'notes/write', ROOM))).toEqual({ kind: 'deny', reason: 'shelf-paused' }) + expect(explain).toHaveBeenCalledTimes(2) + }) + + it('refuses with policy-failed when bindings(), a condition, or explain() throws, logging each policy once per change', async () => { + const { ctx, access } = await setup() + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + const failures = (): unknown[] => warn.mock.calls.flatMap(([value]) => (value instanceof Error ? [value.message] : [])) + let mode: 'bindings' | 'condition' | 'explain' = 'bindings' + access.registerPolicy('test-guest', { + bindings: () => { + if (mode === 'bindings') throw new Error('binding store unavailable') + return [{ role: SHELF_WRITER, resource: ROOM, condition: () => { throw new Error('condition failed') } }] + }, + explain: () => { throw new Error('explain failed') }, + }) + access.registerPolicy('test-crew', { bindings: () => { throw new Error('crew store unavailable') } }) + for (let round = 0; round < 3; round++) { + expect(access.decide(ask(GUEST, 'notes/write', ROOM))).toEqual({ kind: 'deny', reason: 'policy-failed' }) + expect(access.decide(ask(CREW, 'notes/write', ROOM))).toEqual({ kind: 'deny', reason: 'policy-failed' }) + } + await expect(call(ctx, GUEST, 'write', { request: { shelfId: 'r1', text: 'x' } })).rejects.toMatchObject({ + code: 'remote-access/denied', details: { action: 'notes/write', reason: 'policy-failed' }, + }) + expect(failures()).toEqual(['binding store unavailable', 'crew store unavailable']) + expect(warn).toHaveBeenCalledWith( + 'remote access: the "test-guest" policy failed to list bindings for notes/write; its further failures are not logged until access state changes') + + mode = 'condition' + access.invalidate(OTHER) + expect(access.decide(ask(GUEST, 'notes/write', ROOM))).toEqual({ kind: 'deny', reason: 'policy-failed' }) + expect(warn).toHaveBeenCalledWith( + 'remote access: the "test-guest" policy failed to evaluate a condition for notes/write; its further failures are not logged until access state changes') + + mode = 'explain' + access.invalidate() + expect(access.decide(ask(GUEST, 'notes/read', ROOM))).toEqual({ kind: 'deny', reason: 'policy-failed' }) + expect(warn).toHaveBeenCalledWith( + 'remote access: the "test-guest" policy failed to explain a refusal of notes/read; its further failures are not logged until access state changes') + expect(failures()).toEqual(['binding store unavailable', 'crew store unavailable', 'condition failed', 'explain failed']) + }) + + it('always lets a Peer open its own access snapshot', async () => { + const { ctx, access } = await setup() + access.registerPolicy('test-guest', { bindings: () => [] }) + const guest = await follow(ctx, GUEST) + await expect(guest.next()).resolves.toEqual({ type: 'baseline', owner: false, grants: [] }) + await guest.stop() + }) +}) + +describe('RemoteAccessService.allows', () => { + it('filters list items for non-owners on one resource without arguments', async () => { + const { ctx, access } = await setup() + const policy = new GuestPolicy() + access.registerPolicy('test-guest', policy) + const reader = vi.fn>(() => ({ kind: 'allow' })) + policy.hold(GUEST, { role: READER, resource: GLOBAL }, { role: SHELF_READER, resource: ROOM, condition: reader }) + await expect(call(ctx, GUEST, 'rooms')).resolves.toEqual(['r1']) + expect(reader).toHaveBeenCalledWith({ action: 'notes/rooms', resource: ROOM }) + // One call for the Gateway's decision and one per item check. + expect(policy.bindings).toHaveBeenCalledTimes(3) + policy.bindings.mockClear() + await expect(call(ctx, OWNER, 'rooms')).resolves.toEqual(['r1', 'r2']) + expect(access.allows(ROOM)).toBe(true) + expect(policy.bindings).not.toHaveBeenCalled() + }) + + it('reads the bindings on every check, so a running call sees binding changes from its next check on', async () => { + const { ctx, access } = await setup() + const policy = new GuestPolicy() + access.registerPolicy('test-guest', policy) + policy.hold(GUEST, { role: SHELF_READER, resource: ROOM }) + // One long-running call, such as a follow stream that filters every frame. + const stream = ctx.extend({ invocation: invocationOf(ctx, GUEST, 'rooms', 'notes') }).remoteAccess + expect(stream.allows(ROOM)).toBe(true) + expect(stream.allows(ROOM2)).toBe(false) + policy.hold(GUEST, { role: SHELF_READER, resource: ROOM2 }) + expect(stream.allows(ROOM)).toBe(false) + expect(stream.allows(ROOM2)).toBe(true) + }) + + it('allows nothing when the principal kind has no policy or the policy fails', async () => { + const { ctx, access } = await setup() + vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + const crewCall = ctx.extend({ invocation: invocationOf(ctx, CREW, 'rooms', 'notes') }) + expect(crewCall.remoteAccess.allows(ROOM)).toBe(false) + const bindings = vi.fn((): readonly RemoteAccessBinding[] => { throw new Error('binding store unavailable') }) + access.registerPolicy('test-guest', { bindings }) + const guestCall = ctx.extend({ invocation: invocationOf(ctx, GUEST, 'rooms', 'notes') }) + expect(guestCall.remoteAccess.allows(ROOM)).toBe(false) + expect(guestCall.remoteAccess.allows(ROOM2)).toBe(false) + expect(bindings).toHaveBeenCalledTimes(2) + }) +}) + +describe('first snapshots', () => { + it('gives the owner the owner baseline and a non-owner its current grants', async () => { + const { access } = await setup() + const policy = new GuestPolicy() + policy.hold(GUEST, { role: READER, resource: GLOBAL }) + access.registerPolicy('test-guest', policy) + expect(access.snapshotFor(OWNER)).toEqual({ type: 'baseline', owner: true }) + expect(access.snapshotFor(GUEST)).toEqual({ + type: 'baseline', owner: false, grants: [{ resource: GLOBAL, actions: ['notes/read', 'notes/rooms', 'notes/write'] }], + }) + expect(access.snapshotFor(CREW)).toEqual({ type: 'baseline', owner: false, grants: [] }) + expect(REMOTE_ACCESS_SNAPSHOT_KEY).toBe('__DSH_REMOTE_ACCESS__') + }) + + it('injects the owner baseline into every index the webServer renders', async () => { + const { ctx } = await setup() + const render = (): IndexInjection[] => { + const table: IndexInjection[] = [] + ctx.emit('webserver/index-inject', table) + return table + } + expect(render()).toEqual([]) + ctx.provide('webServer', {} as Context['webServer']) + await vi.waitFor(() => { + expect(render()).toEqual([{ kind: 'global', name: '__DSH_REMOTE_ACCESS__', value: { type: 'baseline', owner: true } }]) + }) + }) + + it('lists per bound resource the endpoint actions decide() allows there without arguments, and no grant where none is allowed', async () => { + const { ctx, access } = await setup() + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + const policy = new GuestPolicy() + access.registerPolicy('test-guest', policy) + const writeOnly: RemoteAccessCondition<'test-shelf'> = ({ action }) => + action === 'notes/write' ? { kind: 'allow' } : { kind: 'deny', reason: 'read-paused' } + policy.hold(GUEST, + { role: SHELF_READER, resource: ROOM, condition: writeOnly }, + { role: SHELF_WRITER, resource: ROOM }, + { role: DESK_WRITER, resource: DESK, condition: () => { throw new Error('condition failed') } }, + { role: READER, resource: GLOBAL }) + const grants: RemoteAccessGrant[] = [ + { resource: ROOM, actions: ['notes/write'] }, + { resource: GLOBAL, actions: ['notes/read', 'notes/rooms', 'notes/write'] }, + ] + expect(access.snapshotFor(GUEST)).toEqual({ type: 'baseline', owner: false, grants }) + for (const resource of [ROOM, GLOBAL]) { + for (const action of ['notes/read', 'notes/rooms', 'notes/write'] as const) { + const listed = grants.find(grant => grant.resource === resource)?.actions.includes(action) === true + expect(access.decide(ask(GUEST, action, resource)).kind).toBe(listed ? 'allow' : 'deny') + } + } + // Event actions are decided per notification and never enter the snapshot. + expect(access.decide(ask(GUEST, 'event:notes/changed', GLOBAL))).toEqual({ kind: 'allow' }) + expect(warn).toHaveBeenCalledWith(expect.objectContaining({ message: 'condition failed' })) + }) + + it('gives a principal whose bindings() throws no grant', async () => { + const { ctx, access } = await setup() + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + access.registerPolicy('test-guest', { bindings: () => { throw new Error('binding store unavailable') } }) + expect(access.snapshotFor(GUEST)).toEqual({ type: 'baseline', owner: false, grants: [] }) + const guest = await follow(ctx, GUEST) + await expect(guest.next()).resolves.toEqual({ type: 'baseline', owner: false, grants: [] }) + expect(warn).toHaveBeenCalledWith( + 'remote access: the "test-guest" policy failed to list bindings for a snapshot; its further failures are not logged until access state changes') + await guest.stop() + }) +}) + +describe('remoteAccess/follow', () => { + it('sends the owner one owner baseline and nothing else', async () => { + const { ctx } = await setup() + const owner = await follow(ctx, OWNER) + await expect(owner.next()).resolves.toEqual({ type: 'baseline', owner: true }) + await owner.stop() + expect(owner.frames).toHaveLength(1) + + // Outside a Remote call the caller is trusted in-process code, answered as the owner. + for (const abortWhileWaiting of [false, true]) { + const abort = new AbortController() + const direct = ctx.remoteAccess.follow(abort.signal)[Symbol.asyncIterator]() + await expect(direct.next()).resolves.toEqual({ done: false, value: { type: 'baseline', owner: true } }) + if (!abortWhileWaiting) abort.abort() + const end = direct.next() + if (abortWhileWaiting) abort.abort() + await expect(end).resolves.toEqual({ done: true, value: undefined }) + } + }) + + it('pushes upserts and removals after invalidation and policy changes', async () => { + const { ctx, access } = await setup() + const policy = new GuestPolicy() + access.registerPolicy('test-guest', policy) + const guest = await follow(ctx, GUEST) + const other = await follow(ctx, OTHER) + const crew = await follow(ctx, CREW) + await expect(guest.next()).resolves.toEqual({ type: 'baseline', owner: false, grants: [] }) + await other.next() + await expect(crew.next()).resolves.toEqual({ type: 'baseline', owner: false, grants: [] }) + + policy.hold(GUEST, { role: SHELF_WRITER, resource: ROOM }) + access.invalidate(GUEST) + await expect(guest.next()).resolves.toEqual({ type: 'upsert', grant: { resource: ROOM, actions: ['notes/write'] } }) + + policy.hold(GUEST, { role: SHELF_WRITER, resource: ROOM }, { role: SHELF_READER, resource: ROOM }) + access.invalidate() + await expect(guest.next()).resolves.toEqual({ + type: 'upsert', grant: { resource: ROOM, actions: ['notes/read', 'notes/rooms', 'notes/write'] }, + }) + + policy.hold(GUEST, { role: READER, resource: GLOBAL }) + access.invalidate(GUEST) + await expect(guest.next()).resolves.toEqual({ + type: 'upsert', grant: { resource: GLOBAL, actions: ['notes/read', 'notes/rooms', 'notes/write'] }, + }) + await expect(guest.next()).resolves.toEqual({ type: 'remove', resource: ROOM }) + + // An unchanged grant is not pushed again. + policy.hold(GUEST, { role: READER, resource: GLOBAL }, { role: SHELF_WRITER, resource: ROOM2 }) + access.invalidate(GUEST) + await expect(guest.next()).resolves.toEqual({ type: 'upsert', grant: { resource: ROOM2, actions: ['notes/write'] } }) + policy.hold(GUEST, + { role: { ...READER, actions: ['notes/hidden', 'notes/read', 'notes/rooms'] }, resource: GLOBAL }, + { role: SHELF_WRITER, resource: ROOM2 }) + access.invalidate(GUEST) + await expect(guest.next()).resolves.toEqual({ + type: 'upsert', grant: { resource: GLOBAL, actions: ['notes/hidden', 'notes/read', 'notes/rooms'] }, + }) + // A resource on which no action stays allowed loses its grant. + const paused: RemoteAccessCondition<'test-shelf'> = () => ({ kind: 'deny', reason: 'shelf-paused' }) + policy.hold(GUEST, + { role: { ...READER, actions: ['notes/hidden', 'notes/read', 'notes/rooms'] }, resource: GLOBAL }, + { role: SHELF_WRITER, resource: ROOM2, condition: paused }) + access.invalidate(GUEST) + await expect(guest.next()).resolves.toEqual({ type: 'remove', resource: ROOM2 }) + + const disposeCrew = access.registerPolicy('test-crew', { bindings: () => [{ role: SHELF_WRITER, resource: ROOM2 }] }) + await expect(crew.next()).resolves.toEqual({ type: 'upsert', grant: { resource: ROOM2, actions: ['notes/write'] } }) + access.invalidate({ kind: 'test-crew', members: ['a', 'b'] }) + disposeCrew() + await expect(crew.next()).resolves.toEqual({ type: 'remove', resource: ROOM2 }) + + await guest.stop() + await crew.stop() + // Every recomputation for the other principal produced the same grants, so it received no increment. + expect(other.frames).toHaveLength(1) + await other.stop() + }) + + it('keeps no abort listener from a wait that a change ended', async () => { + const { ctx, access } = await setup() + const policy = new GuestPolicy() + access.registerPolicy('test-guest', policy) + const abort = new AbortController() + const stream = ctx.extend({ invocation: invocationOf(ctx, GUEST) }).remoteAccess.follow(abort.signal)[Symbol.asyncIterator]() + await stream.next() + const add = vi.spyOn(EventTarget.prototype, 'addEventListener') + const remove = vi.spyOn(EventTarget.prototype, 'removeEventListener') + try { + for (let round = 0; round < 30; round++) { + // The reader is already waiting when the change arrives. + const pending = stream.next() + policy.hold(GUEST, { role: round % 2 === 0 ? READER : { ...READER, actions: ['notes/read'] }, resource: GLOBAL }) + access.invalidate(GUEST) + await expect(pending).resolves.toMatchObject({ done: false, value: { type: 'upsert' } }) + } + expect(abortListenerCalls(add)).toBeGreaterThan(0) + expect(abortListenerCalls(add) - abortListenerCalls(remove)).toBe(0) + } finally { + add.mockRestore() + remove.mockRestore() + } + abort.abort() + await stream.return?.() + }) + + it('ends every open generation when the service unloads, so a reloaded service starts from a fresh baseline', async () => { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(TypertRegistry) + const service = ctx.plugin(RemoteAccessService) + await service + await ctx.plugin(TypertGatewayService) + await ctx.plugin(Notes) + const policy = new GuestPolicy() + policy.hold(GUEST, { role: READER, resource: GLOBAL }) + ctx.remoteAccess.registerPolicy('test-guest', policy) + const open = async (principal: Principal): Promise> => + (await ctx.typertGateway.stream({ + peer: new Peer(ctx, { principal }), namespace: 'remoteAccess', method: 'follow', args: {}, + }))[Symbol.asyncIterator]() + const guest = await open(GUEST) + const owner = await open(OWNER) + await expect(guest.next()).resolves.toMatchObject({ + value: { type: 'baseline', grants: [{ resource: GLOBAL, actions: ['notes/read', 'notes/rooms', 'notes/write'] }] }, + }) + await expect(owner.next()).resolves.toMatchObject({ value: { type: 'baseline', owner: true } }) + const guestEnd = guest.next() + await service.dispose() + await expect(guestEnd).resolves.toEqual({ done: true, value: undefined }) + await expect(owner.next()).resolves.toEqual({ done: true, value: undefined }) + + await ctx.plugin(RemoteAccessService) + await vi.waitFor(() => { expect(ctx.get('typertGateway')).toBeDefined() }) + const reopened = await follow(ctx, GUEST) + await expect(reopened.next()).resolves.toEqual({ type: 'baseline', owner: false, grants: [] }) + await reopened.stop() + }) + + it('stops a non-owner generation that is cancelled while waiting', async () => { + const { ctx, access } = await setup() + access.registerPolicy('test-guest', new GuestPolicy()) + const abort = new AbortController() + const stream = ctx.extend({ invocation: invocationOf(ctx, GUEST) }).remoteAccess.follow(abort.signal)[Symbol.asyncIterator]() + await expect(stream.next()).resolves.toMatchObject({ value: { type: 'baseline', owner: false } }) + const pending = stream.next() + abort.abort() + await expect(pending).resolves.toEqual({ done: true, value: undefined }) + // A cancelled generation no longer receives invalidations. + access.invalidate() + }) +}) diff --git a/packages/api/remote-access/tsconfig.client.json b/packages/api/remote-access/tsconfig.client.json new file mode 100644 index 0000000000..0ddeaeac30 --- /dev/null +++ b/packages/api/remote-access/tsconfig.client.json @@ -0,0 +1,22 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "files": [ + "src/client/index.ts", + "src/client/mount.ts", + "src/client/state.ts", + "src/snapshot.ts", + "src/types.ts" + ], + "references": [ + { "path": "../../../vendor/cordis" }, + { "path": "../gateway/tsconfig.client.json" }, + { "path": "../../client/ui-renderer" }, + { "path": "../../client/ui-slots" }, + { "path": "../../typert/protocol" } + ] +} diff --git a/packages/api/remote-access/tsconfig.host.json b/packages/api/remote-access/tsconfig.host.json new file mode 100644 index 0000000000..0d9e8a79c8 --- /dev/null +++ b/packages/api/remote-access/tsconfig.host.json @@ -0,0 +1,18 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "files": [ + "src/index.ts", + "src/snapshot.ts", + "src/types.ts" + ], + "references": [ + { "path": "../../../vendor/cordis" }, + { "path": "../../host/webserver" }, + { "path": "../../typert/protocol" } + ] +} diff --git a/packages/api/remote-access/tsconfig.json b/packages/api/remote-access/tsconfig.json new file mode 100644 index 0000000000..2a0b0e33f7 --- /dev/null +++ b/packages/api/remote-access/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.host.json" }, + { "path": "./tsconfig.client.json" } + ] +} diff --git a/packages/api/remote-access/tsdown.config.ts b/packages/api/remote-access/tsdown.config.ts new file mode 100644 index 0000000000..0e42a1163e --- /dev/null +++ b/packages/api/remote-access/tsdown.config.ts @@ -0,0 +1,7 @@ +import { clientBundle } from '../../client/tsdown.client.ts' + +export default clientBundle( + import.meta.dirname, + ['lib/types/index.js'], + { hostPhase: true }, +) diff --git a/packages/api/remotes/README.i18n.yaml b/packages/api/remotes/README.i18n.yaml index c8686dd4e2..3339260812 100644 --- a/packages/api/remotes/README.i18n.yaml +++ b/packages/api/remotes/README.i18n.yaml @@ -18,8 +18,8 @@ en: a80d44e0683768a5 zh: 379833ac180e5418 /deepseek-ai-dsh-api-remotes/forwarded-host-events: - en: d6d82bf0e55ae5e9 - zh: c3a0c80f8b115039 + en: 31bb9a2f50094b84 + zh: 226c055739d5def7 /deepseek-ai-dsh-api-remotes/build-boundary: en: 7a9934a3ba5b185f zh: 40457fd5707f57f0 diff --git a/packages/api/remotes/README.md b/packages/api/remotes/README.md index f479777030..bde4e4c93a 100644 --- a/packages/api/remotes/README.md +++ b/packages/api/remotes/README.md @@ -44,6 +44,8 @@ This package owns no physical transport or Host service discovery. It projects t The listener signature is not restated here. Each allowlisted event's Cordis `Events` declaration lives in its owner package's client-safe `./types` export, and both faces of this package pull those declarations in. The Host face additionally asserts every entry against `TypertForwardableEventEntry`: an `emit` entry must be a declared one-way event, while a `waterfall` entry must be a declared Agent-scoped waterfall whose final parameter is its same-result `next()` callback. +An `emit` entry may declare `resources`, readers keyed by `TypertResourceMap` kind and typed by the event's own parameters, such as `resources: { session: summary => summary.sessionId }` on `api-session/added`. The Host entry attaches them to each forwarded frame unchanged, and the Gateway forwards a notification to a non-owner Peer only when access control allows the event on the resources they name; a notification without `resources` touches the built-in `global` resource. `api-session/activity`, `api-session/added`, `api-session/error`, `api-session/removed`, and `api-session/status` declare their Session. A notification names one resource identity or none; collection changes travel on follow streams instead. + The Host entry registers an independent allowlist listener set and queue for each Client stream. It rejects non-JSON ordinary-event arguments before enqueueing. For a waterfall, it projects only the top-level Agent identity and JSON request fields; a Client result must also be lossless JSON, while `next()` delegates to the following Host listener. Each scoped waterfall request must carry its routed Agent directly as `request.agent`; the Host rejects a missing or mismatched identity before forwarding. The source attaches all listeners synchronously before `ctx.typertGateway.registerRemoteEvents()` exposes Gateway's internal `$events` logical stream, so its first `ready` item proves that incremental delivery is active and carries the Host home for Client path display. Withdrawing the registration aborts active streams. The payload-free `schedule/changed` event invalidates Schedule task queries; Clients re-read after a notification and reconnect. The payload-free `permission-presets/catalog-changed` event invalidates the process catalog. A Client subscribes before its first `permissionPresets.catalog()` read and re-reads the complete snapshot after a notification; the event carries no catalog state and changes no Session sequence. diff --git a/packages/api/remotes/README.zh.md b/packages/api/remotes/README.zh.md index b130e28b76..680e41e045 100644 --- a/packages/api/remotes/README.zh.md +++ b/packages/api/remotes/README.zh.md @@ -44,6 +44,8 @@ Client 组合挂载 Office 转换、Commands、凭据、settings、Goal、Schedu 监听器签名不在此处重写。名单内每条事件的 Cordis `Events` 声明都住在其 owner 包 client-safe 的 `./types` 导出,本包两个 face 都把那些声明纳入编译面。Host face 还会把每个条目断言给 `TypertForwardableEventEntry`:`emit` 条目必须是已声明的单向事件,`waterfall` 条目则必须是已声明的 agent-scoped waterfall,且其最后一个参数是返回相同结果类型的 `next()` 回调。 +`emit` 条目可以声明 `resources`:以 `TypertResourceMap` 种类为键、类型由该事件自身参数决定的读取函数,例如 `api-session/added` 上的 `resources: { session: summary => summary.sessionId }`。Host entry 把它们原样附在每个转发帧上;只有访问控制在它们给出的资源上允许该事件时,Gateway 才把通知转发给非 owner Peer,未声明 `resources` 的通知触及内置的 `global` 资源。`api-session/activity`、`api-session/added`、`api-session/error`、`api-session/removed` 与 `api-session/status` 声明其 Session。一个通知只携带一个资源身份或不携带;集合类变化改走 follow 类流。 + Host entry 为每条 Client 流独立注册一组 allowlist listener 和一个队列,并在普通事件入队前拒绝非 JSON 参数。对于 waterfall,它只投影顶层 agent 身份与 JSON 请求字段;Client 结果也必须能无损表示为 JSON,而 `next()` 会委托给后续 Host listener。每个作用域 waterfall 请求都必须以 `request.agent` 直接携带路由所用的 agent;Host 会在转发前拒绝缺失或不匹配的身份。该 source 在 `ctx.typertGateway.registerRemoteEvents()` 暴露 Gateway 内部的 `$events` 逻辑流前同步挂好所有 listener,因此首个 `ready` 项既能证明增量投递已就绪,也会携带供 Client 显示路径的 Host home。撤回注册会中止活动流。 无 payload 的 `schedule/changed` 事件使 Schedule 任务查询失效;Client 在收到通知及重连后重新读取。无 payload 的 `permission-presets/catalog-changed` 事件使进程目录失效。Client 在首次读取 `permissionPresets.catalog()` 前先订阅,并在通知后重新读取完整快照;该事件不携带目录状态,也不改变 Session 序号。 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 153dba81db..62b7dffc57 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-remotes", "description": "Remote BFF assembly for application-selected Host capabilities", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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", @@ -82,6 +84,7 @@ "@deepseek-ai/dsh-permission-presets": "workspace:*", "@deepseek-ai/dsh-schedule": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-reference": "workspace:*", "@deepseek-ai/dsh-settings": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", @@ -89,7 +92,7 @@ "@deepseek-ai/dsh-user-approval": "workspace:*", "@deepseek-ai/dsh-user-questions": "workspace:*", "@deepseek-ai/cordis": "workspace:~", - "zod": "^4.4.3", + "zod": "4.4.3", "@deepseek-ai/dsh-command-feedback": "workspace:*", "@deepseek-ai/dsh-api-terminal-controller": "workspace:*", "@deepseek-ai/dsh-plugin-manager": "workspace:*", diff --git a/packages/api/remotes/src/client/index.ts b/packages/api/remotes/src/client/index.ts index 49ed1e5392..68997853d6 100644 --- a/packages/api/remotes/src/client/index.ts +++ b/packages/api/remotes/src/client/index.ts @@ -34,7 +34,8 @@ export type { BundleInfo, BundleRowInfo, ChangeResult, IncompatiblePlugin, InspectOptions, InstallBundleOptions, InstallSpecKind, ManagementError, PackageResult, PluginChange, PluginEntryId, PluginInfo, PluginInspectProblem, PluginInstallCancellation, PluginInstallFailureKind, - PluginInstallLogChunk, PluginInstallProgress, PluginInstallRequestId, PluginRegistries, PluginSpecInspection, ReadOnlyReason, Registry, + PluginInstallLogChunk, PluginInstallProgress, PluginInstallRequestId, PluginRegistries, PluginSpecInspection, + ReadOnlyReason, Registry, RestartReason, } from '@deepseek-ai/dsh-plugin-manager/types' export type {} from '@deepseek-ai/dsh-plugin-manager/remote' export type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/remote' @@ -144,7 +145,7 @@ export type { // Provider registry and discovery vocabulary for the llm namespace. export type { LlmConfigurableProvider, LlmDiscoveredModel, - LlmModelDiscoveryRequest, LlmProviderInfo, + LlmModelDiscoveryRequest, LlmNativeAuth, LlmProviderInfo, } from '@deepseek-ai/dsh-llm/types' // Reference-discovery result vocabulary for the fileReferences and // sessionReferenceResolver namespaces. diff --git a/packages/api/remotes/src/index.ts b/packages/api/remotes/src/index.ts index 781ffbb95a..d2fa2989f1 100644 --- a/packages/api/remotes/src/index.ts +++ b/packages/api/remotes/src/index.ts @@ -48,10 +48,12 @@ export function apply(ctx: Context): void { function remoteEventSource(ctx: Context): TypertRemoteEventSource { return (signal) => { const queue = new RemoteEventQueue() - const disposers = API_REMOTE_FORWARDED_EVENTS.map(({ event, mode }) => { + const disposers = API_REMOTE_FORWARDED_EVENTS.map((entry) => { + const { event, mode } = entry if (mode === 'emit') { + const resources = 'resources' in entry ? entry.resources : undefined return ctx.on(event as never, ((...args: unknown[]) => { - queue.push({ event, args: assertJsonArgs(event, args) }) + queue.push({ event, args: assertJsonArgs(event, args), ...resources === undefined ? {} : { resources } }) }) as never) } return ctx.on(event as never, (function ( diff --git a/packages/api/remotes/src/remote-events.ts b/packages/api/remotes/src/remote-events.ts index f57a5c6481..c59f72030c 100644 --- a/packages/api/remotes/src/remote-events.ts +++ b/packages/api/remotes/src/remote-events.ts @@ -7,6 +7,7 @@ */ import type {} from '@deepseek-ai/dsh-api-session-controller/remote-events' +import type { SessionId } from '@deepseek-ai/dsh-session/types' import type {} from '@deepseek-ai/dsh-deepseek-account/types' import type {} from '@deepseek-ai/dsh-permission-presets/types' import type {} from '@deepseek-ai/dsh-plugin-manager/types' @@ -16,15 +17,19 @@ import type { TypertForwardableEventEntry } from '@deepseek-ai/dsh-typert-protoc /** * Host events this application forwards without renaming. The explicit mode is * both the Host dispatch strategy and the legal key set of `ctx.remote.$on`. + * An `emit` entry declares readers of the resources its payload carries, or + * none to touch the built-in `global` resource; it reaches a non-owner Peer + * only when access control allows it. Each notification names one resource + * identity or none, and collection changes travel on follow streams instead. */ export const API_REMOTE_FORWARDED_EVENTS = [ { event: 'agent-preset/selected', mode: 'emit' }, { event: 'approval/request', mode: 'waterfall' }, - { event: 'api-session/activity', mode: 'emit' }, - { event: 'api-session/added', mode: 'emit' }, - { event: 'api-session/error', mode: 'emit' }, - { event: 'api-session/removed', mode: 'emit' }, - { event: 'api-session/status', mode: 'emit' }, + { event: 'api-session/activity', mode: 'emit', resources: { session: (sessionId): SessionId => sessionId } }, + { event: 'api-session/added', mode: 'emit', resources: { session: (summary): SessionId => summary.sessionId } }, + { event: 'api-session/error', mode: 'emit', resources: { session: (sessionId): SessionId => sessionId } }, + { event: 'api-session/removed', mode: 'emit', resources: { session: (sessionId): SessionId => sessionId } }, + { event: 'api-session/status', mode: 'emit', resources: { session: (sessionId): SessionId => sessionId } }, { event: 'commands/change', mode: 'emit' }, { event: 'deepseek-account/session-expired', mode: 'emit' }, { event: 'deepseek-account/model-sign-in-required', mode: 'emit' }, diff --git a/packages/api/remotes/tests/built-lib.e2e.ts b/packages/api/remotes/tests/built-lib.e2e.ts index 991c1ac46e..5b8200c657 100644 --- a/packages/api/remotes/tests/built-lib.e2e.ts +++ b/packages/api/remotes/tests/built-lib.e2e.ts @@ -24,6 +24,7 @@ const requiredArtifacts = [ 'packages/goal/goal/lib/typert.host.js', 'packages/api/gateway/lib/client.js', 'packages/api/gateway/lib/index.js', + 'packages/api/remote-access/lib/index.js', 'packages/typert/registry/lib/client.js', 'packages/typert/registry/lib/index.js', 'packages/session/session-projection/lib/index.js', @@ -39,6 +40,7 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { connectionHost: 'packages/client/connection/lib/index.js', goal: 'packages/goal/goal/lib/index.js', goalTypert: 'packages/goal/goal/lib/typert.host.js', + remoteAccess: 'packages/api/remote-access/lib/index.js', registryClient: 'packages/typert/registry/lib/client.js', registryHost: 'packages/typert/registry/lib/index.js', remotesClient: 'packages/api/remotes/lib/client.js', @@ -55,6 +57,7 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { const { default: AgentRegistry } = await import(urls.agent) const connectionHost = await import(urls.connectionHost) const { default: TypertRemoteService } = await import(urls.apiGatewayHost) + const { default: RemoteAccessService } = await import(urls.remoteAccess) const { default: GoalService } = await import(urls.goal) const { default: SessionProjectionRegistry } = await import(urls.sessionProjections) const { TYPERT } = await import(urls.goalTypert) @@ -84,6 +87,7 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { await host.plugin({ inject: connectionHost.inject, apply: connectionHost.apply }) await host.plugin(TypertRegistry) await host.plugin(AgentRegistry) + await host.plugin(RemoteAccessService) await host.plugin(TypertRemoteService) await host.plugin(SessionProjectionRegistry) await host.plugin(GoalService) diff --git a/packages/api/remotes/tests/remote-events.host.spec.ts b/packages/api/remotes/tests/remote-events.host.spec.ts index 80841acf6d..977257ee44 100644 --- a/packages/api/remotes/tests/remote-events.host.spec.ts +++ b/packages/api/remotes/tests/remote-events.host.spec.ts @@ -152,6 +152,33 @@ describe('Remote event Host source', () => { await ctx.fiber.dispose() }) + it('attaches each declared resource reader to its forwarded notification', async () => { + const { ctx, gateway, fiber } = await setup() + const abort = new AbortController() + const stream = sourceOf(gateway)(abort.signal)[Symbol.asyncIterator]() + const cases: readonly (readonly [string, readonly unknown[], string])[] = [ + ['api-session/activity', ['s-activity', 1], 's-activity'], + ['api-session/added', [{ sessionId: 's-added' }], 's-added'], + ['api-session/error', ['s-error', 'boom'], 's-error'], + ['api-session/removed', ['s-removed'], 's-removed'], + ['api-session/status', ['s-status', true], 's-status'], + ] + for (const [event, args, sessionId] of cases) { + emitRaw(ctx, event, args) + const next = await stream.next() + if (next.done === true || 'context' in next.value) throw new Error(`${event} was not forwarded as a notification`) + const frame = next.value + expect(frame).toMatchObject({ event, args }) + expect(frame.resources?.['session']?.(...frame.args)).toBe(sessionId) + } + // An event that declares no resources carries no readers, so access control sees the global resource. + emitRaw(ctx, 'commands/change', []) + await expect(stream.next()).resolves.toEqual({ done: false, value: { event: 'commands/change', args: [] } }) + abort.abort(new Error('Client disconnected')) + await fiber.dispose() + await ctx.fiber.dispose() + }) + it('rejects a non-JSON argument without poisoning the stream', async () => { const { ctx, gateway } = await setup() const abort = new AbortController() diff --git a/packages/api/remotes/tsconfig.client.json b/packages/api/remotes/tsconfig.client.json index 279c07025f..729bbd9e6b 100644 --- a/packages/api/remotes/tsconfig.client.json +++ b/packages/api/remotes/tsconfig.client.json @@ -33,6 +33,9 @@ { "path": "../../context/session-reference" }, + { + "path": "../../core/session" + }, { "path": "../../extensions/cordis-host-runner" }, 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 18627b3c99..46f670802e 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: ae2715276ec70675 - zh: 0937d1335c21eff2 + en: f9e4042fae88f801 + zh: f379f78966d57c2e /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 d5a7f2a7a7..02dff176ba 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -31,13 +31,17 @@ History pages and follow opening snapshots carry one `{ type: 'event', event: Se The Client journal validates current Session event envelopes before publishing follow snapshots, live entries, or history pages. It reuses the browser-safe Session validators for required surface markers, exact replacement endpoints, earlier unique source seqs, embedded Assistant provider metadata, request-header omissions, and tool-error consistency. Invalid records fail without field stripping or normalization; range membership and source existence remain durable-log checks on the Host. -Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, attachment, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and subagent ownership fence to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` reads one complete baseline through a live-preferred Session observation without activating an Agent. It returns null for a missing Session and serves any registered projection keys. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Initial reads and live projection frames use the same sequence ordering. +Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, attachment, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and subagent ownership fence to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` normally reads an exact baseline, including current-format cold logs, and returns `kind: sequenced`. Only a read requiring migration returns `kind: migration-required` hints without `asOfSeq`; missing keys remain absent. It returns null for a missing Session. Fork callers may set `allowMigration: false` to receive `session/migration-required` instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values. + +Every Remote endpoint is access-controlled: a Peer whose principal is not the owner reaches an endpoint only when, on every resource the call touches, a binding of that principal kind's policy in [`dsh-api-remote-access`](../remote-access/README.md) grants a role listing the action ([Peer principals Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md)). The controller injects `remoteAccess` and registers the `session` resource kind with the default field `sessionId` through `typert.resources`. `session/page` and `session/follow` declare a `session` reader in `@Remote({ resources })` that reads `request.address.sessionId` for an ordinary Session address and `request.address.childSessionId` for a subagent address; whether access to the parent Session covers its children is the policy's rule. `session/projections` reads the Session resource from `request.sessionId`, so a reconnecting reader reloads only the projections of Sessions it may read. `session/list`, `session/search`, and `session/control` read no resource, so their calls touch the `global` resource and need a `global` role; for a non-owner caller, `session/list` returns only the rows, `session/search` only the hits, and `session/control` only the baseline projections and projection frames, whose Session `ctx.remoteAccess.allows()` admits for the same action, so that action also belongs to a `session` role; owner results are unfiltered. `session/prompt` builds the durable `user-rpc` message source in its Remote method and records `principal` only for a non-owner caller, read through `principalOf(this.ctx.invocation)`; a source without `principal` belongs to the owner. + +List rows carry `formatStatus` when available, so Clients can identify migration-required Sessions without requesting their projections. Host list generation yields between complete rows only when its configured work slice is exhausted; cheap remaining work returns without a forced yield. Request cancellation is checked per row and after each yield and rejects without partial results. Each row is synchronous; the list does not promise one cross-Session snapshot. A Session already queued as cold remains a cached row if it attaches during a yield: Client in-flight mutation replay corrects its availability, and sequenced projections supersede cached hints. 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 c6c7f51633..b01a99cc1f 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -31,13 +31,17 @@ kind: "package-reference" Client journal 在发布 follow 快照、live entry 或历史页之前验证当前 Session 事件 envelope。它复用浏览器安全的 Session validator,检查必需的 surface marker、精确的 replacement endpoint、更早且唯一的 source seq、内嵌 Assistant 提供方元数据、request header 可选字段的省略规则以及工具错误一致性。无效 record 直接失败,不删除字段或归一化;范围成员与来源存在性仍由 Host 的持久日志检查。 -每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 通过一次 live-preferred Session observation 读取完整基线,不激活 Agent。Session 不存在时返回 null,并可提供任意已注册的 projection key。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。初始读取与实时 projection 帧使用相同的序号排序规则。 +每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 正常读取准确基线,包括当前格式的冷日志,返回 `kind: sequenced`。只有需要迁移时才返回不带 `asOfSeq` 的 `kind: migration-required` 提示,缺少的键保持缺席。Session 不存在时返回 null。Fork 调用者可设置 `allowMigration: false`,在源历史需要迁移时收到 `session/migration-required`;省略则保持自动迁移。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。有序读取与实时 projection 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。 + +每个 Remote 端点都受访问控制:principal 不是 owner 的 Peer 只有在本次调用访问的每个资源上,该 principal kind 在 [`dsh-api-remote-access`](../remote-access/README.zh.md) 中的 policy 都有某个 binding 授予列出该 action 的 role 时,才能调用该端点([Peer 身份属性 Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md))。控制器注入 `remoteAccess`,并经 `typert.resources` 以默认字段 `sessionId` 登记 `session` 资源种类。`session/page` 与 `session/follow` 在 `@Remote({ resources })` 中声明 `session` 读取函数:对普通 Session 地址读 `request.address.sessionId`,对 subagent 地址读 `request.address.childSessionId`;父会话的访问权是否覆盖其子会话由 policy 决定。`session/projections` 从 `request.sessionId` 读取会话资源,因此重连的读者只会重新读取它可读的会话的 projections。`session/list`、`session/search` 与 `session/control` 不读取资源,其调用访问 `global` 资源,需要 `global` role;对非 owner 调用方,`session/list` 只返回其 Session 被 `ctx.remoteAccess.allows()` 按同一 action 允许的行,`session/search` 只返回这类 Session 的命中,`session/control` 也只返回这类 Session 的 baseline projection 与 projection 帧,因此该 action 也要列在 `session` role 中;owner 的结果不过滤。`session/prompt` 在其 Remote 方法内构造持久的 `user-rpc` 消息 source,且只为非 owner 调用方记录经 `principalOf(this.ctx.invocation)` 读取的 `principal`;不带 `principal` 的 source 属于 owner。 + +列表行在状态可用时携带 `formatStatus`,Client 无需请求其投影即可识别需要迁移的 Session。 Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件循环;剩余工作较少时直接返回,不强制让出。每行及每次让出之后检查请求取消,取消时拒绝返回部分结果。每行同步计算;列表不承诺跨 Session 的统一快照。已经进入冷态队列的 Session 若在让出期间接入,仍返回缓存行:Client 对进行中请求的变更重放会纠正其可用性,带序号的投影会覆盖缓存提示。 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 6060164c0d..1b6173d4b3 100644 --- a/packages/api/session-controller/package.json +++ b/packages/api/session-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-session-controller", "description": "Session Remote commands, cold reads, and live control transport", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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", @@ -77,7 +79,7 @@ "@deepseek-ai/dsh-deque": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", "mime-types": "^3.0.2", - "zod": "^4.4.3" + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -124,6 +126,7 @@ } }, "devDependencies": { + "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-agent-default-model": "workspace:*", @@ -148,6 +151,7 @@ "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-persistence": "workspace:*", + "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-session-projection-cache": "workspace:*", "@deepseek-ai/dsh-session-query": "workspace:*", 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 076188c1e0..a52d2c155a 100644 --- a/packages/api/session-controller/src/client/contract/sessions.ts +++ b/packages/api/session-controller/src/client/contract/sessions.ts @@ -79,24 +79,27 @@ 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. * @param id - possible addressed child id. - * @returns a retained or loaded-catalog address, without retaining a new selection or scope. + * @returns a retained, catalog-derived, or unknown-mode listed address, without retaining a new selection or scope. */ subagentAddress(id: SessionId): SubagentAddress | undefined /** - * Load all Session projections once per connection; retry an unsuccessful initial read. + * Read projections without starting migration; retry failed or migration-deferred reads. * @param sessionId - Session to inspect without opening its conversation. * @returns completion of the current or newly started refresh. */ @@ -134,6 +137,8 @@ export interface ISessions { atSeq?: number increaseTitle?: boolean onCreated?: (childId: SessionId) => void + /** False refuses source migration; omission preserves the Host default. */ + allowMigration?: boolean }): Promise /** * Borrow an already-retained Agent-scoped Context without extending its lifetime. diff --git a/packages/api/session-controller/src/client/sessions/lineage.ts b/packages/api/session-controller/src/client/sessions/lineage.ts index b0b49311f3..e74cd9dce5 100644 --- a/packages/api/session-controller/src/client/sessions/lineage.ts +++ b/packages/api/session-controller/src/client/sessions/lineage.ts @@ -27,6 +27,8 @@ export interface SessionListEntry { parentSessionId?: SessionId /** Coarse durable origin for navigation filtering; not a continuation capability. */ origin?: 'subagent' + /** Format classification supplied by the Host list. */ + formatStatus?: SessionSummary['formatStatus'] cwd?: string /** Current host-computed projection values for list consumers. */ projectionValues?: Readonly> diff --git a/packages/api/session-controller/src/client/sessions/manager.ts b/packages/api/session-controller/src/client/sessions/manager.ts index db7236c1b2..b8bec9be8a 100644 --- a/packages/api/session-controller/src/client/sessions/manager.ts +++ b/packages/api/session-controller/src/client/sessions/manager.ts @@ -61,7 +61,7 @@ export interface SessionListSnapshot { /** Shared projection values and the lifecycle of their explicit baseline read. */ export interface SessionProjectionSnapshot { readonly values: Readonly> - readonly state: 'idle' | 'loading' | 'ready' | 'error' + readonly state: 'idle' | 'loading' | 'ready' | 'migration-required' | 'error' readonly error: RemoteFailure | null } @@ -153,8 +153,9 @@ export class SessionManager { /** * Resolve an address for breadcrumb navigation without retaining transport authority. - * @param sessionId - possible child id in an already-loaded catalog. - * @returns A retained or catalog-derived direct-parent address. + * @param sessionId - possible child id in received Session metadata. + * @returns A retained address, then a catalog address, then an unknown-mode address + * from a listed subagent header; undefined without that evidence. */ subagentAddress(sessionId: SessionId): SubagentAddress | undefined { const retained = this.addresses.get(sessionId) @@ -170,7 +171,13 @@ export class SessionManager { } } } - return undefined + const summary = this.summaries.find(summary => summary.sessionId === sessionId) + if (summary?.origin !== 'subagent' || summary.parentSessionId === undefined) return undefined + return { + parentSessionId: summary.parentSessionId, + childSessionId: sessionId, + mode: 'unknown', + } } // ---- Instance management ---- @@ -332,7 +339,7 @@ export class SessionManager { } /** - * Load a complete projection baseline once per connection; retry unsuccessful reads. + * Read projections without starting migration; retry failed or migration-deferred reads. * @param sessionId - Session to inspect without opening its conversation. * @returns completion of the current or newly started read. */ @@ -350,13 +357,26 @@ export class SessionManager { const result = await this.remote.session.projections({ sessionId }, controller.signal) if (controller.signal.aborted) return if (result.ok) { - if (result.value !== null) { - store.seed({ ...result.value, asOfSeq: sessionSeqCursor(result.value.asOfSeq) }) + const value = result.value + if (value !== null) { + switch (value.kind) { + case 'sequenced': + store.seed({ values: value.values, asOfSeq: sessionSeqCursor(value.asOfSeq) }) + break + case 'migration-required': + store.applyCached(value.values) + break + default: + assertNever(value, 'session projections result') + } } else if (store.values() === initialValues) { // A later frame proves existence independently of an earlier missing read. store.clear() } - this.projectionLoads.set(sessionId, { state: 'ready', error: null }) + this.projectionLoads.set(sessionId, { + state: value?.kind === 'migration-required' ? 'migration-required' : 'ready', + error: null, + }) } else { this.projectionLoads.set(sessionId, { state: 'error', error: result.error }) } @@ -482,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 } @@ -526,16 +550,17 @@ export class SessionManager { * preserve it or lower it after an exact cut before the first `turn/start`; * lineage rides parentSessionId. A child published before Workspace * attachment fails is also reconciled into the list. - * @param opts - source session and the optional exact inclusive boundary seq. + * @param opts - source session, optional exact inclusive boundary seq, and permission to start migration. * @returns the fork result (the child session id). */ async fork( - opts: { sessionId: SessionId; atSeq?: SessionSeq }, + opts: { sessionId: SessionId; atSeq?: SessionSeq; allowMigration?: boolean }, ): Promise> { const source = this.summaries.find(s => s.sessionId === opts.sessionId) const result = await this.remote.session.fork({ sessionId: opts.sessionId, ...opts.atSeq === undefined ? {} : { atSeq: opts.atSeq }, + ...opts.allowMigration === undefined ? {} : { allowMigration: opts.allowMigration }, }) const childId = result.ok ? result.value.sessionId @@ -774,6 +799,7 @@ export class SessionManager { && prev.blank === entry.blank && prev.parentSessionId === entry.parentSessionId && prev.cwd === entry.cwd && prev.origin === entry.origin && prev.title === entry.title && prev.depth === entry.depth + && prev.formatStatus === entry.formatStatus && prev.projectionValues === entry.projectionValues ) return prev this.entryCache.set(entry.sessionId, entry) @@ -813,6 +839,7 @@ function applyMutation(summaries: readonly SessionSummary[], mutation: SessionLi ...(mutation.kind === 'upsert' ? { agentAvailable: mutation.summary.agentAvailable, running: mutation.summary.running, + ...(mutation.summary.formatStatus === undefined ? {} : { formatStatus: mutation.summary.formatStatus }), } : {}), ...(existing.cwd === undefined && mutation.summary.cwd !== undefined ? { cwd: mutation.summary.cwd } : {}), ...(existing.parentSessionId === undefined && mutation.summary.parentSessionId !== undefined @@ -823,6 +850,7 @@ function applyMutation(summaries: readonly SessionSummary[], mutation: SessionLi if (filled.cwd === existing.cwd && filled.parentSessionId === existing.parentSessionId && filled.origin === existing.origin && filled.blank === existing.blank && filled.agentAvailable === existing.agentAvailable && filled.running === existing.running + && filled.formatStatus === existing.formatStatus ) return [...summaries] return summaries.map(summary => summary.sessionId === mutation.summary.sessionId ? filled : summary) } diff --git a/packages/api/session-controller/src/client/sessions/projection-store.ts b/packages/api/session-controller/src/client/sessions/projection-store.ts index ae36cea19c..c10c81c475 100644 --- a/packages/api/session-controller/src/client/sessions/projection-store.ts +++ b/packages/api/session-controller/src/client/sessions/projection-store.ts @@ -6,8 +6,8 @@ * (`{ value, seq }`) comes from the connected Host — a follow opening * baseline, a Session Controller `projection` frame, a list block the Host * computed for an attached Session — and merges under **higher seq wins** - * against other sequenced rows. A `cached` row (`{ value }`) comes from the - * session list's view of the persisted checkpoint, carries no comparable + * against other sequenced rows. A `cached` row (`{ value }`) comes from + * a Host view of the persisted checkpoint, carries no comparable * seq, and yields to every sequenced write. No client-side domain folding * exists: a domain ships projection support with zero client code. Per-key * bare observable faces feed `useProjection` (ui-renderer binds them). @@ -166,7 +166,7 @@ export class ProjectionValueStore { } /** - * Fill keys from a session-list block the Host labeled `cached`: a zero-I/O + * Fill keys from a Host block labeled `cached`: a zero-I/O * view of the persisted checkpoint. A cached value lands only where no * sequenced row exists: a connected Session has already answered for such * a key, and the list's view of the persisted checkpoint cannot be newer diff --git a/packages/api/session-controller/src/client/sessions/service.ts b/packages/api/session-controller/src/client/sessions/service.ts index 964105a486..b992a34920 100644 --- a/packages/api/session-controller/src/client/sessions/service.ts +++ b/packages/api/session-controller/src/client/sessions/service.ts @@ -21,6 +21,7 @@ import { SessionManager } from './manager.ts' import type { SessionRemotes } from './remotes.ts' import type { SessionListPhase, SessionSearchResultItem, SessionProjectionSnapshot } from './manager.ts' import type { Session } from './session.ts' +import type { SessionListEntry } from './lineage.ts' /** Session list row projected from the host list RPC plus live stream increments. */ export interface SessionSummary { @@ -33,6 +34,8 @@ export interface SessionSummary { parentId?: SessionId /** Coarse durable origin for navigation filtering; not a continuation capability. */ origin?: 'subagent' + /** Format classification supplied by the Host list, when available. */ + formatStatus?: SessionListEntry['formatStatus'] /** Host running state for `ids` members; a display fallback for other rows. */ running: boolean /** Local ownership counts; Host metadata refreshes cannot overwrite them. */ @@ -332,14 +335,14 @@ export class ClientSessions implements ISessions { * Resolve an already discovered direct-parent address without opening it. * Feature plugins use this to avoid Agent-bound RPCs in persisted child views. * @param id - possible addressed child id. - * @returns A retained or loaded-catalog address, without retaining a new selection or scope. + * @returns A retained, catalog-derived, or unknown-mode listed address, without retaining a new selection or scope. */ subagentAddress(id: SessionId): SubagentAddress | undefined { return this.manager.subagentAddress(id) } /** - * Load all Session projections once per connection; retry an unsuccessful initial read. + * Read projections without starting migration; retry failed or migration-deferred reads. * @param sessionId - Session to inspect without opening its conversation. */ refreshProjections(sessionId: SessionId): Promise { @@ -424,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() @@ -443,7 +451,7 @@ export class ClientSessions implements ISessions { * seq (a real event seq the caller already knows; a cut inside an open * turn is balanced Host-side with synthetic closers, and omission selects * the latest completed-turn prefix), and whether to increment an - * inherited durable title before resolving. + * inherited durable title before resolving, plus permission to start source migration. * @returns the child session id. * @throws {SessionForkError} with the source id. * @throws {Error} when a requested child-title rename fails after creation. @@ -453,6 +461,7 @@ export class ClientSessions implements ISessions { atSeq?: number increaseTitle?: boolean onCreated?: (childId: SessionId) => void + allowMigration?: boolean }): Promise { const sourceTitle = opts.increaseTitle ? this.list.getSnapshot().byId[opts.sessionId]?.title @@ -460,6 +469,7 @@ export class ClientSessions implements ISessions { const result = await this.manager.fork({ sessionId: opts.sessionId, ...(opts.atSeq === undefined ? {} : { atSeq: SessionSeq(opts.atSeq) }), + ...(opts.allowMigration === undefined ? {} : { allowMigration: opts.allowMigration }), }) if (!result.ok) throw new SessionForkError(result.error, opts.sessionId) this.projectList() @@ -622,6 +632,7 @@ export class ClientSessions implements ISessions { retainedBy: this.retentionSnapshot(entry.sessionId).retainedBy, blank: entry.blank, updatedAt: entry.updatedAt, + formatStatus: entry.formatStatus, ...(entry.projectionValues === undefined ? {} : { projectionValues: entry.projectionValues }), diff --git a/packages/api/session-controller/src/client/sessions/session.ts b/packages/api/session-controller/src/client/sessions/session.ts index 284abc5656..09494e01ab 100644 --- a/packages/api/session-controller/src/client/sessions/session.ts +++ b/packages/api/session-controller/src/client/sessions/session.ts @@ -289,7 +289,7 @@ export class Session implements SessionFace { // wire type is used; this array is not filtered or reordered. const routedContent = content as Exclude[] const routed = await this.remote.subagents.prompt({ - requestId: randomUUID() as SessionRequestId, + requestId: requestId ?? randomUUID() as SessionRequestId, parentSessionId: this.address.parentSessionId, childSessionId: this.address.childSessionId, mode: 'continuable', diff --git a/packages/api/session-controller/src/commands.ts b/packages/api/session-controller/src/commands.ts index 7e900b92ae..8dd38573c8 100644 --- a/packages/api/session-controller/src/commands.ts +++ b/packages/api/session-controller/src/commands.ts @@ -20,7 +20,6 @@ import { SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session' import type { SessionEvent, SessionHeader, SessionId, UserMessage } from '@deepseek-ai/dsh-session' import { SessionQueryError, type SessionObservation } from '@deepseek-ai/dsh-session-query' import { SessionTitleInvalidError } from '@deepseek-ai/dsh-session-title' -import { canonicalClientTimeZone } from '@deepseek-ai/dsh-util-time' import { assertNever } from '@deepseek-ai/dsh-util-values' import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import type { Workspace } from '@deepseek-ai/dsh-workspace' @@ -33,6 +32,7 @@ import { apiSessionSubagentOwnershipError, hasApiSessionSubagentOwner, inspectApiSession, + type ApiSessionCreated, } from './agent.ts' import type { SessionAttachmentRequest, @@ -64,7 +64,12 @@ type PromptContentCandidate = | SessionPromptRequest['content'][number] | Extract['content'][number] -function hasPromptContent(content: readonly PromptContentCandidate[]): boolean { +/** + * Whether prompt content carries non-whitespace text or an attachment. + * @param content - submitted or edited prompt parts. + * @returns false for content the Agent must not receive. + */ +export function hasPromptContent(content: readonly PromptContentCandidate[]): boolean { return content.some(part => part.type !== 'text' || part.text.trim().length > 0) } @@ -98,15 +103,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 +122,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 +146,7 @@ export class SessionCommandController { ) } } - const agentPreset = this.agents.presetForSession(adopted.session) - return { sessionId, ...(agentPreset === undefined ? {} : { agentPreset }) } + return { sessionId, ...(created.agentPreset === undefined ? {} : { agentPreset: created.agentPreset }) } } /** @@ -304,35 +310,15 @@ export class SessionCommandController { } /** - * Reject empty content, then admit one prompt after Agent and attachment validation. - * @param request - Session identity, prompt content, source metadata, and delivery mode. + * Admit one prompt after Agent and attachment validation; the Remote method + * has already validated the content and built the durable message source. + * @param request - Session identity, prompt content, and delivery mode. + * @param source - the `user-rpc` source recorded on the accepted message. * @returns acknowledgement that the Agent accepted the prompt. */ - async prompt(request: SessionPromptRequest): Promise { - if (!hasPromptContent(request.content)) { - throw new RemoteError( - 'gateway/bad-request', - 'prompt content must include non-whitespace text or an attachment', - {}, - ) - } - const clientTimeZone = request.clientTimeZone === undefined - ? undefined - : canonicalClientTimeZone(request.clientTimeZone) - if (request.clientTimeZone !== undefined && clientTimeZone === undefined) { - throw new RemoteError( - 'session/invalid-time-zone', - 'clientTimeZone must be UTC or a valid IANA Area/Location name', - { value: request.clientTimeZone }, - ) - } + async prompt(request: SessionPromptRequest, source: MessageSource): Promise { const agent = await this.resolveAgent(request.sessionId) if (hasPromptRequest(agent, request.requestId)) return { accepted: true } - const source: MessageSource = { - kind: 'user', - rpcId: request.requestId, - ...(clientTimeZone === undefined ? {} : { clientTimeZone }), - } const hasImage = request.content.some(part => part.type === 'image') const admit = async (): Promise => { try { @@ -530,16 +516,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 +534,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 8e38822fbc..2362bce21c 100644 --- a/packages/api/session-controller/src/index.ts +++ b/packages/api/session-controller/src/index.ts @@ -6,19 +6,23 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-fs' import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { errorChain, ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { errorChain, ReasoningEffortId, type MessageSource } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-client-file-upload' import { canOpenNativePath, nativeFileManager, nativeFileApplications, openNativeFileApplication, openNativeAssociatedPath, revealNativePath } from '@deepseek-ai/dsh-native-command' import type { SessionId } from '@deepseek-ai/dsh-session' import type { SessionInspection } from '@deepseek-ai/dsh-session-persistence' +import type {} from '@deepseek-ai/dsh-session-projection-cache' import { SessionQueryError, type SessionObservation } from '@deepseek-ai/dsh-session-query' -import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import { Remote, RemoteError, TypertRemoteService, principalOf } from '@deepseek-ai/dsh-typert-protocol' +import { canonicalClientTimeZone } from '@deepseek-ai/dsh-util-time' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type {} from '@deepseek-ai/dsh-api-remote-access' import { ApiSessionAgentController, inspectApiSession, type ApiSessionAgentResult, } from './agent.ts' -import { SessionCommandController } from './commands.ts' +import { SessionCommandController, hasPromptContent } from './commands.ts' import { SessionControlController } from './control.ts' import { SessionHistoryController } from './history.ts' import { SessionFileReferences } from './file-references.ts' @@ -31,6 +35,7 @@ import { ArchivedSessionGate } from './archived-session-gate.ts' import type { ModelCatalog, SessionWorkspacePathApplication, + SessionAddress, SessionAttachmentRequest, SessionAttachmentValue, SessionCancelRequest, @@ -75,6 +80,16 @@ declare module '@deepseek-ai/cordis' { } } +/** + * Read the Session resource a history address names: the Session itself, or + * the child Session whose transcript a subagent address reads. + * @param request - history request carrying the durable address. + * @returns the Session whose access the read requires. + */ +function addressedSession(request: { readonly address: SessionAddress }): SessionId { + return request.address.kind === 'session' ? request.address.sessionId : request.address.childSessionId +} + /** Session Controller deployment policy. */ export interface Config { /** Override platform desktop-opener detection. */ @@ -109,6 +124,7 @@ export class SessionController extends TypertRemoteService { 'fileUploads', 'fs', 'llm', + 'remoteAccess', 'sessions', 'sessionProjections', 'sessionQuery', @@ -140,6 +156,7 @@ export class SessionController extends TypertRemoteService { */ constructor(ctx: Context, config: Config, internals: SessionControllerInternals = {}) { super(ctx, 'sessionController', { namespace: 'session' }) + ctx.typert.resources.register('session', { field: 'sessionId' }) const resolved = SessionController.Config(config) installModelSelectionProjection(ctx) this.agents = new ApiSessionAgentController(ctx) @@ -257,24 +274,28 @@ export class SessionController extends TypertRemoteService { */ @Remote('list') async list(_request: SessionListRequest, signal: AbortSignal): Promise { - return { items: await this.listState.list(signal) } + const items = await this.listState.list(signal) + return { items: items.filter(item => this.ctx.remoteAccess.allows({ kind: 'session', id: item.sessionId })) } } /** - * Search visible Session content without resuming an Agent. + * Search visible Session content without resuming an Agent. A non-owner + * receives only the hits whose Session `allows()` admits; `hasMore` + * describes the bounded result before that filtering. * @param request - literal message-content query. * @param signal - cancellation for list and search reads. * @returns authorized bounded Session search results. */ @Remote('search') - search(request: SessionSearchRequest, signal: AbortSignal): Promise { - return this.listState.search(request.query, signal) + async search(request: SessionSearchRequest, signal: AbortSignal): Promise { + const result = await this.listState.search(request.query, signal) + return { ...result, items: result.items.filter(item => this.ctx.remoteAccess.allows({ kind: 'session', id: item.sessionId })) } } /** - * 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 { @@ -415,11 +436,19 @@ export class SessionController extends TypertRemoteService { * Fork one cold-readable exact event prefix into a new Session. An omitted * boundary selects the latest completed-turn prefix; an open cut receives * synthetic fork closers. - * @param request - source Session and optional exact inclusive event boundary. + * @param request - source Session, optional exact inclusive event boundary, and migration preflight choice. * @returns the new Session identity. */ @Remote('fork') - fork(request: SessionForkRequest): Promise { + async fork(request: SessionForkRequest): Promise { + if (request.allowMigration === false && this.ctx.sessions.get(request.sessionId) === undefined) { + const stored = await this.ctx.get('sessionPersistence')?.stat(request.sessionId) + if (stored?.formatStatus === 'migration-required' && this.ctx.sessions.get(request.sessionId) === undefined) { + throw new RemoteError('session/migration-required', 'Open the source Session to complete migration before forking', { + sessionId: request.sessionId, + }) + } + } return this.commands.fork(request) } @@ -430,9 +459,30 @@ export class SessionController extends TypertRemoteService { * @returns acknowledgement that the Agent accepted the prompt. */ @Remote('prompt') - prompt(request: SessionPromptRequest, signal: AbortSignal): Promise { + async prompt(request: SessionPromptRequest, signal: AbortSignal): Promise { signal.throwIfAborted() - return this.commands.prompt(request) + if (!hasPromptContent(request.content)) { + throw new RemoteError('gateway/bad-request', 'prompt content must include non-whitespace text or an attachment', {}) + } + const clientTimeZone = request.clientTimeZone === undefined + ? undefined + : canonicalClientTimeZone(request.clientTimeZone) + if (request.clientTimeZone !== undefined && clientTimeZone === undefined) { + throw new RemoteError( + 'session/invalid-time-zone', + 'clientTimeZone must be UTC or a valid IANA Area/Location name', + { value: request.clientTimeZone }, + ) + } + // The caller is recorded only when it is not the owner, so owner messages keep their exact source. + const principal = principalOf(this.ctx.invocation) + const source: MessageSource = { + kind: 'user', + rpcId: request.requestId, + ...(clientTimeZone === undefined ? {} : { clientTimeZone }), + ...(principal === undefined ? {} : { principal }), + } + return this.commands.prompt(request, source) } /** @@ -471,7 +521,7 @@ export class SessionController extends TypertRemoteService { * @param signal - cancellation for persistence reads. * @returns one chronological page. */ - @Remote('page') + @Remote({ name: 'page', resources: { session: addressedSession } }) page(request: SessionPageRequest, signal: AbortSignal): Promise { return this.history.page(request, signal) } @@ -483,16 +533,16 @@ export class SessionController extends TypertRemoteService { * @returns a complete opening snapshot followed by gap-free durable event * frames and optional cursorless assistant-stream frames. */ - @Remote({ mode: 'stream' }) + @Remote({ mode: 'stream', resources: { session: addressedSession } }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable { return this.history.follow(request, signal) } /** - * Read all registered projections without activating an Agent. + * Read exact projections, returning cached hints only when migration is required. * @param request - Session whose current values are required. - * @param signal - cancellation for the Session observation. - * @returns complete baseline, or null when the Session does not exist. + * @param signal - cancellation for the Session read. + * @returns a sequenced baseline, cached hints when migration is deferred, or null when absent. */ @Remote('projections') async projections(request: SessionProjectionsRequest, signal: AbortSignal): Promise { @@ -501,16 +551,29 @@ export class SessionController extends TypertRemoteService { throw new RemoteError('gateway/bad-request', 'sessionId must not be empty', {}) } try { + signal.throwIfAborted() + const live = this.liveProjections(sessionId) + if (live !== undefined) return live + const stored = await this.ctx.get('sessionPersistence')?.stat(sessionId, { signal }) + signal.throwIfAborted() + const attached = this.liveProjections(sessionId) + if (attached !== undefined) return attached + if (stored === undefined) return null + if (stored.formatStatus === 'migration-required') { + const cached = this.ctx.get('sessionProjectionCache')?.cachedSnapshot(stored.header) + return { kind: 'migration-required', values: { ...cached?.values } as SessionProjectionValues } + } using observation = await this.ctx.sessionQuery.observeSession(sessionId, { signal }) const projections = observation.projections if (projections === undefined) { throw new RemoteError('session/projections-unavailable', 'Session projections are unavailable', {}) } - return { asOfSeq: projections.asOfSeq, values: projections.values as SessionProjectionValues } + return { kind: 'sequenced', asOfSeq: projections.asOfSeq, values: projections.values as SessionProjectionValues } } catch (error: unknown) { - if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') return null - if (signal.aborted - || (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_ABORTED')) { + if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') { + return this.liveProjections(sessionId) ?? null + } + if (signal.aborted || (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_ABORTED')) { throw new RemoteError('gateway/cancelled', 'Session projection read was cancelled', {}, { cause: error }) } if (error instanceof RemoteError) throw error @@ -518,14 +581,38 @@ export class SessionController extends TypertRemoteService { } } + private liveProjections( + sessionId: SessionId, + ): Extract | undefined { + const session = this.ctx.sessions.get(sessionId) + if (session === undefined) return undefined + const snapshot = this.ctx.sessionProjections.snapshot(session) + return { kind: 'sequenced', asOfSeq: snapshot.asOfSeq, values: snapshot.values as SessionProjectionValues } + } + /** * Stream a complete live-control baseline followed by replacement frames. * @param signal - cancellation owned by the Remote stream carrier. * @returns one complete baseline followed by live replacement frames. */ @Remote({ mode: 'stream' }) - control(signal: AbortSignal): AsyncIterable { - return this.controlState.control(signal) + async *control(signal: AbortSignal): AsyncIterable { + for await (const frame of this.controlState.control(signal)) { + switch (frame.type) { + case 'baseline': { + const projections = Object.fromEntries(Object.entries(frame.value.projections) + .filter(([sessionId]) => this.ctx.remoteAccess.allows({ kind: 'session', id: sessionId as SessionId }))) + yield { type: 'baseline', value: { ...frame.value, projections } } + break + } + case 'projection': + if (this.ctx.remoteAccess.allows({ kind: 'session', id: frame.sessionId })) yield frame + break + /* v8 ignore next -- closed control-frame union. */ + default: + assertNever(frame) + } + } } diff --git a/packages/api/session-controller/src/list.ts b/packages/api/session-controller/src/list.ts index c51d119805..d7ef1ad43c 100644 --- a/packages/api/session-controller/src/list.ts +++ b/packages/api/session-controller/src/list.ts @@ -8,7 +8,7 @@ import type { ImageAttachmentLimits } from '@deepseek-ai/dsh-attachment' import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { ProjectionSnapshot } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-session-projection-cache' -import { SessionQueryError, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' +import { SessionQueryError, type SessionRecord, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import { z } from 'zod' import { @@ -116,6 +116,7 @@ export class ApiSessionList { sessionId: session.id, updatedAt: updatedAt(session.header, metadata), agentAvailable: this.ctx.agents.get(session.id)?.session === session, + formatStatus: 'current', running: this.ctx.agents.get(session.id)?.status === 'running', blank: metadata?.blank ?? session.seq === 0, ...listFields(session.header), @@ -133,7 +134,7 @@ export class ApiSessionList { const records = await this.ctx.sessionQuery.listSessions(signal) signal?.throwIfAborted() const items: SessionSummary[] = [] - const cold: SessionHeader[] = [] + const cold: SessionRecord[] = [] let yieldDeadline = performance.now() + this.workSliceMs for (const record of records) { signal?.throwIfAborted() @@ -141,7 +142,7 @@ export class ApiSessionList { if (live !== undefined) { items.push(this.summaryFor(live)) } else if (record.header.cwd !== undefined) { - cold.push(record.header) + cold.push(record) } if (performance.now() >= yieldDeadline) { await scheduler.yield() @@ -149,9 +150,9 @@ export class ApiSessionList { yieldDeadline = performance.now() + this.workSliceMs } } - for (const header of cold) { + for (const record of cold) { signal?.throwIfAborted() - items.push(this.summarizeCold(header)) + items.push(this.summarizeCold(record)) if (performance.now() >= yieldDeadline) { await scheduler.yield() signal?.throwIfAborted() @@ -163,13 +164,14 @@ export class ApiSessionList { return items } - private summarizeCold(header: SessionHeader): SessionSummary { + private summarizeCold({ header, formatStatus }: SessionRecord): SessionSummary { const projections = this.projectionsFor(header, undefined) const metadata = projections?.values.sessionListMetadata return { sessionId: header.id, updatedAt: updatedAt(header, metadata), agentAvailable: false, + ...(formatStatus === undefined ? {} : { formatStatus }), running: false, // A large, metadata-less, or inaccessible cache miss remains unknown and visible. blank: metadata?.blank ?? false, diff --git a/packages/api/session-controller/src/types.ts b/packages/api/session-controller/src/types.ts index a8f0d7e450..c0b2b9a573 100644 --- a/packages/api/session-controller/src/types.ts +++ b/packages/api/session-controller/src/types.ts @@ -9,6 +9,7 @@ import type { LlmAttemptId, MessageId } from '@deepseek-ai/dsh-llm/brand' import type { TextBlock } from '@deepseek-ai/dsh-llm' import type { SessionId, SessionSeqCursor } from '@deepseek-ai/dsh-session/types' import type { SessionProjectionMap } from '@deepseek-ai/dsh-session-projection/types' +import type { Principal } from '@deepseek-ai/dsh-typert-protocol' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' @@ -177,6 +178,8 @@ export type QueueAction = export interface SessionSummary { /** Whether this Session currently owns a live Agent. */ readonly agentAvailable: boolean + /** Current for attached Sessions; otherwise the persistence format status when reported. */ + readonly formatStatus?: 'current' | 'migration-required' readonly sessionId: SessionId readonly updatedAt: number readonly running: boolean @@ -217,13 +220,13 @@ 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 } 'session/steer-unavailable': { readonly itemId: MessageId } 'session/title-invalid': { readonly sessionId: SessionId } 'session/fork-unavailable': { readonly sessionId: SessionId } + 'session/migration-required': { readonly sessionId: SessionId } 'subagent/not-found': { readonly parentSessionId: SessionId readonly childSessionId: SessionId @@ -281,17 +284,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 } @@ -322,6 +331,8 @@ export interface SessionForkRequest { readonly sessionId: SessionId /** Exact inclusive source event seq; omission selects the latest completed-turn prefix. */ readonly atSeq?: number + /** False asks the Host to check for required migration before forking. Defaults to true. */ + readonly allowMigration?: boolean } /** Identity of a newly forked Session. */ @@ -399,8 +410,12 @@ export type SessionRequestId = Branded<'session-request-id'> declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { - /** Browser prompt correlation and optional Host-validated time zone. */ - 'user-rpc': { kind: 'user'; rpcId: SessionRequestId; clientTimeZone?: string } + /** + * Browser prompt correlation, optional Host-validated time zone, and the + * caller that submitted the prompt. `principal` is written only for a + * caller other than the owner, so an absent `principal` means the owner. + */ + 'user-rpc': { kind: 'user'; rpcId: SessionRequestId; clientTimeZone?: string; principal?: Principal } } } @@ -419,8 +434,11 @@ export interface SessionProjectionsRequest { readonly sessionId: SessionId } -/** Complete Session projection baseline; null when the Session does not exist. */ -export type SessionProjectionsValue = SessionProjectionBaseline | null +/** Exact projections carry their event cut; required migration returns sequence-free cache hints. Null means absent. */ +export type SessionProjectionsValue = + | (SessionProjectionBaseline & { readonly kind: 'sequenced' }) + | { readonly kind: 'migration-required'; readonly values: SessionProjectionValues } + | null /** One raw Session event in the Remote journal. */ export interface SessionEventEntry { 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/commands-upload-file.host.spec.ts b/packages/api/session-controller/tests/commands-upload-file.host.spec.ts index 53d1137628..4c7bc2ed5a 100644 --- a/packages/api/session-controller/tests/commands-upload-file.host.spec.ts +++ b/packages/api/session-controller/tests/commands-upload-file.host.spec.ts @@ -7,7 +7,7 @@ import type { FileAttachmentRef, ImageAttachmentRef, SaveFileAttachment, SaveFileStreamAttachment, } from '@deepseek-ai/dsh-attachment' import { createUserMessage } from '@deepseek-ai/dsh-llm' -import type { UserMessage } from '@deepseek-ai/dsh-llm' +import type { MessageSource, UserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import CommandRuntime from '@deepseek-ai/dsh-commands' import { createScope } from '@deepseek-ai/dsh-scope' @@ -113,6 +113,9 @@ async function uploadHarness(origin?: 'subagent'): Promise<{ } } +/** The owner source `SessionController.prompt()` builds for {@link promptRequest}. */ +const USER_SOURCE: MessageSource = { kind: 'user', rpcId: 'req-1' as SessionRequestId } + function promptRequest(content: Parameters[0]['content']) { return { requestId: 'req-1' as SessionRequestId, @@ -163,7 +166,7 @@ describe('Session file uploads', () => { { type: 'file', receiptId: receipt.receiptId }, { type: 'image', mediaType: 'image/png', data: 'AAAA' }, { type: 'text', text: 'read it' }, - ])) + ]), USER_SOURCE) expect(followup).toHaveBeenCalledTimes(1) const message = followup.mock.calls[0]?.[0] as UserMessage expect(message.content).toEqual([ @@ -190,7 +193,7 @@ describe('Session file uploads', () => { name: 'huge.bin', })) expect(receipt.file).toMatchObject({ name: 'huge.bin', bytes: 5 }) - await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }])) + await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE) expect((followup.mock.calls[0]?.[0] as UserMessage).content).toEqual([ { type: 'file', attachment: receipt.file }, ]) @@ -217,7 +220,7 @@ describe('Session file uploads', () => { await expect(controller.prompt(promptRequest([ { type: 'image', mediaType: 'image/png', data: 'AAAA' }, { type: 'file', receiptId: 'missing-receipt' as FileUploadReceiptId }, - ]))).rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'FILE_NOT_STAGED' } }) + ]), USER_SOURCE)).rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'FILE_NOT_STAGED' } }) expect(followup).not.toHaveBeenCalled() expect(saveImages).not.toHaveBeenCalled() }) @@ -302,7 +305,7 @@ describe('Session file uploads', () => { const { controller, uploads, agent } = await uploadHarness() uploads.retirePrompt(agent, 'not-staged') const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal) - await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }])) + await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE) expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file) uploads.retirePrompt(agent, 'other-request') expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file) @@ -317,7 +320,7 @@ describe('Session file uploads', () => { { data: 'AAAA' }, new AbortController().signal, ) - await first.controller.prompt(promptRequest([{ type: 'file', receiptId: observed.receiptId }])) + await first.controller.prompt(promptRequest([{ type: 'file', receiptId: observed.receiptId }]), USER_SOURCE) first.ctx.emit('session/event', first.agent.session, { type: 'user/message', data: createUserMessage({ @@ -345,9 +348,9 @@ describe('Session file uploads', () => { it('deduplicates a retried rpcId already present in the Agent inbox', async () => { const { controller, agent, followup } = await uploadHarness() const request = promptRequest([{ type: 'text', text: 'once' }]) - await controller.prompt(request) + await controller.prompt(request, USER_SOURCE) agent.inbox.append('next-turn', followup.mock.calls[0]?.[0] as UserMessage) - await expect(controller.prompt(request)).resolves.toEqual({ accepted: true }) + await expect(controller.prompt(request, USER_SOURCE)).resolves.toEqual({ accepted: true }) expect(followup).toHaveBeenCalledOnce() }) @@ -364,7 +367,7 @@ describe('Session file uploads', () => { source: { kind: 'user', rpcId: request.requestId }, }), { surfaceOp: 'append' }) - await expect(controller.prompt(request)).resolves.toEqual({ accepted: true }) + await expect(controller.prompt(request, USER_SOURCE)).resolves.toEqual({ accepted: true }) expect(followup).not.toHaveBeenCalled() }) @@ -374,7 +377,7 @@ describe('Session file uploads', () => { saveImages.mockReturnValueOnce(admitted.promise) const prompting = controller.prompt(promptRequest([ { type: 'image', mediaType: 'image/png', data: 'AAAA' }, - ])) + ]), USER_SOURCE) await vi.waitFor(() => { expect(saveImages).toHaveBeenCalledOnce() }) await disposeAgent() admitted.resolve([{ @@ -386,7 +389,7 @@ describe('Session file uploads', () => { it('rejects when a previously bound receipt retires during image admission', async () => { const { controller, uploads, agent, saveImages } = await uploadHarness() const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal) - await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }])) + await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE) const admitted = Promise.withResolvers() saveImages.mockReturnValueOnce(admitted.promise) const prompting = controller.prompt({ @@ -395,7 +398,7 @@ describe('Session file uploads', () => { { type: 'image', mediaType: 'image/png', data: 'AAAA' }, ]), requestId: 'req-2' as SessionRequestId, - }) + }, USER_SOURCE) await vi.waitFor(() => { expect(saveImages).toHaveBeenCalledOnce() }) uploads.retirePrompt(agent, 'req-1') admitted.resolve([{ @@ -409,12 +412,12 @@ describe('Session file uploads', () => { it('keeps the prior receipt binding when a later prompt attempt fails', async () => { const { controller, uploads, agent, followup } = await uploadHarness() const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal) - await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }])) + await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE) followup.mockImplementationOnce(() => { throw new Error('busy') }) await expect(controller.prompt({ ...promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), requestId: 'req-2' as SessionRequestId, - })).rejects.toMatchObject({ code: 'session/agent-busy' }) + }, USER_SOURCE)).rejects.toMatchObject({ code: 'session/agent-busy' }) uploads.retirePrompt(agent, 'req-1') expect(uploads.resolve(agent, receipt.receiptId)).toBeUndefined() }) @@ -425,7 +428,7 @@ describe('Session file uploads', () => { followup.mockImplementationOnce(() => { throw new Error('busy') }) await expect(controller.prompt(promptRequest([ { type: 'file', receiptId: receipt.receiptId }, - ]))).rejects.toMatchObject({ code: 'session/agent-busy' }) + ]), USER_SOURCE)).rejects.toMatchObject({ code: 'session/agent-busy' }) uploads.retirePrompt(agent, 'req-1') expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file) }) @@ -433,7 +436,7 @@ describe('Session file uploads', () => { it('retires a prompt-bound receipt when its queued occurrence is removed', async () => { const { controller, uploads, agent, followup } = await uploadHarness() const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal) - await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }])) + await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE) const queued = followup.mock.calls[0]?.[0] as UserMessage agent.inbox.append('next-turn', queued) expect(await controller.updateQueue({ @@ -454,7 +457,7 @@ describe('Session file uploads', () => { await controller.prompt(promptRequest([ { type: 'file', receiptId: first.receiptId }, { type: 'file', receiptId: second.receiptId }, - ])) + ]), USER_SOURCE) const message = followup.mock.calls[0]?.[0] as UserMessage expect(message.content).toEqual([ diff --git a/packages/api/session-controller/tests/list-scheduling.host.spec.ts b/packages/api/session-controller/tests/list-scheduling.host.spec.ts index eefea76713..b3e412ec9f 100644 --- a/packages/api/session-controller/tests/list-scheduling.host.spec.ts +++ b/packages/api/session-controller/tests/list-scheduling.host.spec.ts @@ -8,6 +8,7 @@ import type { SessionRecord } from '@deepseek-ai/dsh-session-query' import { resolve } from 'node:path' import { performance } from 'node:perf_hooks' import { scheduler } from 'node:timers/promises' +import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access' import SessionController from '../src/index.ts' import { afterEach, describe, expect, it, vi } from 'vitest' import { ApiSessionList } from '../src/list.ts' @@ -181,10 +182,15 @@ describe('Session-list work slices', () => { it('routes an overridden budget through the public Session Controller', async () => { const h = await harness([{ id: 'first', phase: 'cold' }, { id: 'middle', phase: 'cold' }, { id: 'last', phase: 'cold' }], 4) const dispose = (): void => {} - h.ctx.provide('typert', { lookups: { configure: () => dispose }, contexts: { configureHost: () => dispose } } as never) + h.ctx.provide('typert', { + lookups: { configure: () => dispose }, + contexts: { configureHost: () => dispose }, + resources: { register: () => dispose }, + } as never) h.ctx.provide('fileUploads', { registerAgentResolver: () => dispose } as never) h.ctx.provide('agentDefaultModel', { currentSelection: () => ({ provider: 'test', model: 'test' }) } as never) h.ctx.provide('workspaceRegistry', { list: () => [], archivedSessionIds: [] } as never) + new RemoteAccessService(h.ctx) const controller = new SessionController(h.ctx, { nativeOpen: false, listWorkSliceMs: 4 }, { canOpenPath: () => false }) const yieldWork = vi.spyOn(scheduler, 'yield') const result = await controller.list({}, new AbortController().signal) diff --git a/packages/api/session-controller/tests/manager.client.spec.ts b/packages/api/session-controller/tests/manager.client.spec.ts index 4da138a716..bcf4a033be 100644 --- a/packages/api/session-controller/tests/manager.client.spec.ts +++ b/packages/api/session-controller/tests/manager.client.spec.ts @@ -4,6 +4,7 @@ */ import { describe, expect, onTestFinished, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' import type { SessionId } from '@deepseek-ai/dsh-api-remotes/client' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import { SessionSeq } from '@deepseek-ai/dsh-session/types' @@ -14,6 +15,7 @@ import { } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts' import type {} from '@deepseek-ai/dsh-session-title/client' import { SessionManager } from '../src/client/sessions/manager.ts' +import { ClientSessions } from '../src/client/sessions/service.ts' import type { SessionRemotes } from '../src/client/sessions/remotes.ts' import { entries, plainTurn } from './event-script.client.ts' import { FOLLOW, err, followScript, sessionWorld } from './remote/session.client.ts' @@ -647,6 +649,7 @@ describe('list lifecycle', () => { const items = manager.getListSnapshot().items // Cold row: title surfaces straight from the list block — no open, no history. expect(items.find(item => item.sessionId === S1)?.title).toBe('Cold cached') + expect(manager.getListSnapshot().projectionsBySession[S1]?.state).toBe('idle') // A cached list block never displaces a sequenced value, whatever watermark its record holds. expect(items.find(item => item.sessionId === S2)?.title).toBe('Pushed') }) @@ -741,12 +744,83 @@ describe('subagent catalogs', () => { expect(manager.getListSnapshot().items).toEqual([]) }) + it('prefers retained and catalog addresses to header-derived unknown modes', ({ mock, remote }) => { + const manager = makeManager(mock, remote) + onTestFinished(() => manager.dispose()) + manager.handleSessionAdded(summary(S2, { parentSessionId: S1, origin: 'subagent' })) + manager.handleControlFrame({ + type: 'projection', sessionId: S1, key: 'subagentCatalog', seq: 0, + value: [{ id: S2, createdAt: 1, mode: 'continuable', label: 'worker' }], + }) + + expect(manager.subagentAddress(S2)).toEqual({ + parentSessionId: S1, childSessionId: S2, mode: 'continuable', + }) + const retained: SubagentAddress = { parentSessionId: S1, childSessionId: S2, mode: 'one-shot' } + manager.resolveTarget(retained) + expect(manager.subagentAddress(S2)).toBe(retained) + expect(remote.session.list).not.toHaveBeenCalled() + expect(remote.session.projections).not.toHaveBeenCalled() + }) + + it.for([ + ['ordinary session', {}], + ['ordinary fork', { parentSessionId: S1 }], + ['parentless subagent', { origin: 'subagent' }], + ] as const)('does not derive a subagent address for an %s', ([, fields], { mock, remote }) => { + const manager = makeManager(mock, remote) + onTestFinished(() => manager.dispose()) + manager.handleSessionAdded(summary(S2, fields)) + + expect(manager.subagentAddress(S2)).toBeUndefined() + expect(manager.subagentAddress(S1)).toBeUndefined() + expect(manager.resolveTarget(S2)).toBe(S2) + expect(manager.get(S2).getSnapshot().subagent).toBeNull() + expect(remote.session.list).not.toHaveBeenCalled() + expect(remote.session.projections).not.toHaveBeenCalled() + }) + + it('retains a header-discovered ancestor through subagent follow without discovery reads', async ({ mock, remote, start }) => { + const grandchild = 'header-grandchild' as SessionId + const descendantAddress: SubagentAddress = { + parentSessionId: S2, childSessionId: grandchild, mode: 'continuable', + } + const ancestorAddress: SubagentAddress = { parentSessionId: S1, childSessionId: S2, mode: 'unknown' } + mock.load(sessionWorld) + remote.session.list.mockResolvedValueOnce(ok({ items: [ + summary(S1), + summary(S2, { parentSessionId: S1, origin: 'subagent' }), + summary(grandchild, { parentSessionId: S2, origin: 'subagent' }), + ] })) + const client = await start() + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const sessions = new ClientSessions(ctx, client.ctx.remote) + await sessions.refresh() + using descendant = sessions.retain(descendantAddress, { source: 'mainView' }) + await descendant.ready + + using ancestor = sessions.retain(S2, { source: 'mainView' }) + await ancestor.ready + + expect(mock.log.requests(FOLLOW)).toMatchObject([ + { address: { kind: 'subagent', ...descendantAddress } }, + { address: { kind: 'subagent', ...ancestorAddress } }, + ]) + expect(ancestor.binding.session.getSnapshot()).toMatchObject({ + openState: 'open', subagent: { address: ancestorAddress }, + }) + expect(remote.session.list).toHaveBeenCalledOnce() + expect(remote.session.projections).not.toHaveBeenCalled() + expect(mock.log.requests('session/page')).toEqual([]) + }) + it('keeps a catalog-discovered child address across identity resolution and status frames', async ({ mock, remote, start }) => { remote.session.list.mockImplementation(() => Promise.resolve(ok({ items: [ summary(S1), summary(S2, { parentSessionId: S1, origin: 'subagent' }), ] as never[] }))) - remote.session.projections.mockImplementation(() => Promise.resolve(ok({ asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, + remote.session.projections.mockImplementation(() => Promise.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, id: S2, mode: 'continuable', label: 'worker', }] } }))) mock.load(sessionWorld) @@ -859,6 +933,74 @@ describe('subagent catalogs', () => { expect(remote.session.projections.mock.calls.map(([request]) => request)).toEqual([]) }) + it.for(['control', 'follow'] as const)('replaces cached projection hints with the %s baseline', async (source, { mock, remote, start }) => { + mock.load(sessionWorld) + remote.session.projections.mockResolvedValueOnce(ok({ kind: 'migration-required', values: { + title: 'Cached title', + subagentCatalog: [{ id: S2, createdAt: 1, mode: 'unknown' }], + } })) + const client = await start() + const manager = new SessionManager(client.ctx.remote) + onTestFinished(() => manager.dispose()) + + await manager.refreshProjections(S1) + expect(manager.getListSnapshot().projectionsBySession[S1]).toMatchObject({ + state: 'migration-required', error: null, + values: { title: 'Cached title', subagentCatalog: [{ id: S2, mode: 'unknown' }] }, + }) + expect(remote.session.follow).not.toHaveBeenCalled() + const session = manager.get(S1) + expect(session.projections.seqOf('subagentCatalog')).toBeUndefined() + const baseline = { asOfSeq: 0, values: { + subagentCatalog: [{ id: S2, createdAt: 1, mode: 'one-shot' as const, label: 'Loaded child' }], + } } + if (source === 'control') { + manager.handleControlFrame({ type: 'baseline', value: { projections: { [S1]: baseline } } }) + } else { + mock.stream(FOLLOW, followScript(ok({ records: [], hasMore: false, projections: baseline }))) + await session.open() + } + + expect(manager.getListSnapshot().projectionsBySession[S1]?.values).toEqual(baseline.values) + expect(session.projections.seqOf('subagentCatalog')).toBe(0) + expect(session.projections.get('title')).toBeUndefined() + }) + + it.for(['control', 'follow'] as const)('keeps %s projections when a cached read arrives late', async (source, { mock, remote, start }) => { + mock.load(sessionWorld) + const response = Promise.withResolvers>>() + remote.session.projections.mockReturnValueOnce(response.promise) + const client = await start() + const manager = new SessionManager(client.ctx.remote) + const read = manager.refreshProjections(S1) + const baseline = { asOfSeq: 4, values: { + title: 'Loaded title', + subagentCatalog: [{ id: S2, createdAt: 1, mode: 'continuable' as const, label: 'Loaded child' }], + } } + try { + expect(remote.session.projections).toHaveBeenCalledOnce() + if (source === 'control') { + manager.handleControlFrame({ type: 'baseline', value: { projections: { [S1]: baseline } } }) + } else { + mock.stream(FOLLOW, followScript(ok({ records: [], hasMore: false, projections: baseline }))) + await manager.get(S1).open() + } + response.resolve(ok({ kind: 'migration-required', values: { + title: 'Cached title', subagentCatalog: [{ id: S2, createdAt: 1, mode: 'unknown' }], + } })) + await read + + expect(manager.getListSnapshot().projectionsBySession[S1]).toMatchObject({ + state: 'migration-required', error: null, values: baseline.values, + }) + expect(manager.get(S1).projections.seqOf('subagentCatalog')).toBe(4) + } finally { + response.resolve(ok(null)) + await read + await manager.dispose() + } + }) + it('keeps newer pushed membership when the initial read returns an older baseline', async ({ mock, remote }) => { const response = Promise.withResolvers>>() remote.session.projections.mockImplementation(() => response.promise) @@ -868,12 +1010,27 @@ describe('subagent catalogs', () => { type: 'projection', sessionId: S1, key: 'subagentCatalog', seq: 5, value: [{ id: S2, createdAt: 1, mode: 'continuable', label: 'pushed' }], }) - response.resolve(ok({ asOfSeq: 3, values: { subagentCatalog: [] } })) + response.resolve(ok({ kind: 'sequenced', asOfSeq: 3, values: { subagentCatalog: [] } })) await read expect(manager.getListSnapshot().projectionsBySession[S1]?.values.subagentCatalog?.[0]?.label).toBe('pushed') expect(remote.session.projections.mock.calls.map(([request]) => request)).toHaveLength(1) }) + it('retries a migration-deferred projection read and accepts the completed catalog', async ({ mock, remote }) => { + const manager = makeManager(mock, remote) + remote.session.projections.mockResolvedValueOnce(ok({ kind: 'migration-required', values: {} })) + await manager.refreshProjections(S1) + expect(manager.getListSnapshot().projectionsBySession[S1]).toMatchObject({ + state: 'migration-required', values: {}, + }) + remote.session.projections.mockResolvedValueOnce(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [] } })) + await manager.refreshProjections(S1) + expect(manager.getListSnapshot().projectionsBySession[S1]).toMatchObject({ + state: 'ready', values: { subagentCatalog: [] }, + }) + expect(remote.session.projections).toHaveBeenCalledTimes(2) + }) + it.for([false, true])('keeps live parent availability when an earlier initial read settles (failure: %s)', async (failure, { mock, remote }) => { const response = Promise.withResolvers>>() remote.session.projections.mockImplementation(() => response.promise) @@ -885,7 +1042,7 @@ describe('subagent catalogs', () => { manager.handleSessionStatus(S1, false) response.resolve(failure ? err(new RemoteError('gateway/internal', 'offline', {})) - : ok({ asOfSeq: 0, values: { subagentCatalog: [] } })) + : ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [] } })) await read expect(child.getSnapshot().subagent?.parentAvailable).toBe(true) expect(remote.session.projections.mock.calls.map(([request]) => request)).toHaveLength(1) @@ -925,7 +1082,7 @@ describe('subagent catalogs', () => { const read = manager.refreshProjections(S1) expect(manager.refreshProjections(S1)).toBe(read) expect(manager.getListSnapshot().projectionsBySession[S1]?.state).toBe('loading') - response.resolve(ok({ asOfSeq: 0, values: { + response.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ id: S2, createdAt: 1, mode: 'one-shot' }], title: 'cold parent', } })) @@ -946,7 +1103,7 @@ describe('subagent catalogs', () => { const read = manager.refreshProjections(S1) manager.handleSessionAdded(summary(S2, { origin: 'subagent', parentSessionId: S1 })) manager.handleSessionStatus(S2, true) - response.resolve(ok({ asOfSeq: 0, values: { + response.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ id: S2, createdAt: 1, mode: 'continuable', label: 'worker' }], } })) await read @@ -980,7 +1137,7 @@ describe('subagent catalogs', () => { value: [{ id: S2, createdAt: 1, mode: 'one-shot' }] }) await manager.refreshProjections(S1) expect(manager.getListSnapshot().projectionsBySession[S1]).toMatchObject({ state: 'error', values: { subagentCatalog: [{ id: S2 }] } }) - remote.session.projections.mockImplementation(() => Promise.resolve(ok({ asOfSeq: 2, values: { subagentCatalog: [] } }))) + remote.session.projections.mockImplementation(() => Promise.resolve(ok({ kind: 'sequenced', asOfSeq: 2, values: { subagentCatalog: [] } }))) await manager.refreshProjections(S1) expect(manager.getListSnapshot().projectionsBySession[S1]).toMatchObject({ state: 'ready', values: { subagentCatalog: [{ id: S2 }] } }) }) @@ -991,7 +1148,7 @@ describe('subagent catalogs', () => { const manager = makeManager(mock, remote) const read = manager.refreshProjections(S1) manager.handleSessionRemoved(S1) - response.resolve(ok({ asOfSeq: 0, values: { subagentCatalog: [] } })) + response.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [] } })) await read expect(manager.getListSnapshot().items.some(item => item.sessionId === S1)).toBe(false) expect(remote.session.projections.mock.calls.map(([request]) => request)).toHaveLength(1) @@ -1037,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) @@ -1081,6 +1249,20 @@ describe('remaining branches', () => { expect(manager.getListSnapshot().items[0]).not.toHaveProperty('cwd') }) + it.for([undefined, false, true])('forwards fork migration permission %s to the Remote request', async (allowMigration, { mock, remote }) => { + const manager = makeManager(mock, remote) + onTestFinished(() => manager.dispose()) + remote.session.fork.mockResolvedValueOnce(ok({ sessionId: S2 })) + const permission = allowMigration === undefined ? {} : { allowMigration } + + await expect(manager.fork({ sessionId: S1, atSeq: SessionSeq(7), ...permission })) + .resolves.toEqual(ok({ sessionId: S2 })) + + expect(remote.session.fork).toHaveBeenCalledExactlyOnceWith({ sessionId: S1, atSeq: 7, ...permission }) + expect(remote.session.follow).not.toHaveBeenCalled() + expect(manager.getListSnapshot().items[0]).toMatchObject({ sessionId: S2, parentSessionId: S1 }) + }) + it('reconciles a fork child published before workspace attachment fails', async ({ mock, remote }) => { remote.session.fork.mockResolvedValue(err(new RemoteError('session/workspace-attach-failed', 'forked but unattached', { sessionId: S2, workspaceId: 'w1', @@ -1317,7 +1499,7 @@ describe('connected generation', () => { summary(S1), summary(S2, { parentSessionId: S1, origin: 'subagent', running: hostRunning }), ] as never[] }))) - remote.session.projections.mockImplementation(() => Promise.resolve(ok({ asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, id: S2, mode: 'continuable', label: 'worker' }] } }))) + remote.session.projections.mockImplementation(() => Promise.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, id: S2, mode: 'continuable', label: 'worker' }] } }))) const manager = makeManager(mock, remote) try { await manager.refreshList() @@ -1341,13 +1523,13 @@ describe('connected generation', () => { const previous = Promise.withResolvers>>() remote.session.projections .mockReturnValueOnce(previous.promise) - .mockResolvedValue(ok({ asOfSeq: 0, values: { subagentCatalog: [] } })) + .mockResolvedValue(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [] } })) const manager = makeManager(mock, remote) try { const read = manager.refreshProjections(S1) manager.handleConnected() expect(remote.session.projections.mock.calls.map(([request]) => request)).toHaveLength(2) - previous.resolve(ok({ asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, id: S2, mode: 'continuable', label: 'worker' }] } })) + previous.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, id: S2, mode: 'continuable', label: 'worker' }] } })) await read await vi.waitFor(() => { expect(manager.getListSnapshot().projectionsBySession[S1]).toMatchObject({ @@ -1395,7 +1577,7 @@ describe('connected generation', () => { manager.handleConnected() expect(manager.get(S2).getSnapshot().subagent).toEqual({ address }) - parent.resolve(ok({ asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, + parent.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, id: S2, mode: 'continuable', label: 'worker', }] } })) diff --git a/packages/api/session-controller/tests/projection-discovery.host.spec.ts b/packages/api/session-controller/tests/projection-discovery.host.spec.ts new file mode 100644 index 0000000000..fcfe1a4820 --- /dev/null +++ b/packages/api/session-controller/tests/projection-discovery.host.spec.ts @@ -0,0 +1,424 @@ +/** Projection reads distinguish ordinary cold history from history that still needs migration. */ + +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session' +import type { SessionHeader } from '@deepseek-ai/dsh-session' +import type { SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import SessionProjectionCache, { + checkpointRecord, + projectionCacheDomainSpec, + type CheckpointRecord, +} from '@deepseek-ai/dsh-session-projection-cache' +import { titleProjectionDefinition } from '@deepseek-ai/dsh-session-title' +import Storage from '@deepseek-ai/dsh-storage' +import * as StorageDomain from '@deepseek-ai/dsh-storage-domain' +import * as StorageJson from '@deepseek-ai/dsh-storage-json' +import { subagentCatalogProjectionDefinition } from '@deepseek-ai/dsh-subagent/src/catalog.ts' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { createSessionTestController } from './test-remote.ts' + +const contexts: Context[] = [] +const roots: string[] = [] +const readAudits: Array<() => void> = [] + +afterEach(async () => { + try { + for (const audit of readAudits.splice(0)) audit() + } finally { + vi.restoreAllMocks() + try { + await Promise.all(contexts.splice(0).map(ctx => ctx.fiber.dispose())) + } finally { + await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) + } + } +}) + +async function harness(withPersistence = true) { + const root = await mkdtemp(join(tmpdir(), 'dsh-projection-discovery-')) + roots.push(root) + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(SessionStore) + await ctx.plugin(AgentRegistry) + await ctx.plugin(SessionProjectionRegistry) + ctx.sessionProjections.register(subagentCatalogProjectionDefinition) + ctx.sessionProjections.register(titleProjectionDefinition) + if (withPersistence) { + await ctx.plugin(JsonlSessionPersistence, { root: join(root, 'logs'), compression: 'none' }) + const list = vi.spyOn(ctx.sessionPersistence, 'list').mockRejectedValue(new Error('unexpected corpus listing')) + readAudits.push(() => { + expect(list).not.toHaveBeenCalled() + }) + } + const controller = createSessionTestController(ctx, { + defaultModelSelection: () => ({ provider: 'test', model: 'test' }), + cwd: root, + }) + const list = vi.spyOn(ctx.sessionQuery, 'listSessions').mockRejectedValue(new Error('unexpected Session listing')) + readAudits.push(() => { + expect(list).not.toHaveBeenCalled() + }) + return { ctx, root, controller } +} + +type Harness = Awaited> + +async function stored( + fixture: Harness, + id: SessionId, + fields: Partial> = {}, + version = SESSION_FORMAT_VERSION, +) { + const header: SessionHeader = { + version: SESSION_FORMAT_VERSION, + id, + createdAt: 10, + delegationDepth: 0, + isSeeded: false, + ...fields, + } + const path = join(fixture.root, 'logs', '_no-cwd', id, `session.v${version}.jsonl`) + const bytes = `${JSON.stringify({ type: 'session', ...header, version })}\n` + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, bytes) + return { header, path, bytes } +} + +async function seedCache( + fixture: Harness, + header: SessionHeader, + catalog: 'child' | 'empty' | 'absent', + matchingIdentity = true, +) { + const rows: CheckpointRecord['rows'] = { + title: { ver: titleProjectionDefinition.stateVersion, seq: SessionSeq(50), val: 'cached title' }, + } + if (catalog !== 'absent') { + const empty = subagentCatalogProjectionDefinition.init(header, SessionLogOffset(0)) + const state = catalog === 'empty' ? empty : subagentCatalogProjectionDefinition.apply(empty, { + type: 'subagent/catalog', + seq: SessionSeq(0), + time: 1, + data: { + version: 1, + childId: SessionId('cached-child'), + childCreatedAt: 2, + mode: 'one-shot', + label: 'cached child', + }, + }) + const record = checkpointRecord.parse({ + identity: { createdAt: header.createdAt }, + rows: { subagentCatalog: { ver: subagentCatalogProjectionDefinition.stateVersion, seq: 50, val: state } }, + }) + Object.assign(rows, record.rows) + } + const record: CheckpointRecord = { + identity: { + formatVersion: SESSION_FORMAT_VERSION, + createdAt: matchingIdentity ? header.createdAt : header.createdAt + 1, + cwd: header.cwd, + isSeeded: header.isSeeded, + inheritedEventCount: SessionLogOffset(0), + }, + rows, + } + const cacheRoot = join(fixture.root, 'cache') + const path = join(cacheRoot, projectionCacheDomainSpec.name, 'sessions', `${header.id}.json`) + const bytes = JSON.stringify({ version: projectionCacheDomainSpec.version, record }) + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, bytes) + await fixture.ctx.plugin(Storage) + await fixture.ctx.plugin(StorageJson, { root: cacheRoot }) + await fixture.ctx.plugin(StorageDomain, { backend: 'json' }) + await fixture.ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 }) + const write = vi.spyOn(fixture.ctx.sessionProjectionCache, 'write').mockRejectedValue(new Error('unexpected cache write')) + const hydrate = vi.spyOn(fixture.ctx.sessionProjectionCache, 'hydratePrepared').mockImplementation(() => { + throw new Error('unexpected cached hydration') + }) + readAudits.push(() => { + expect(write).not.toHaveBeenCalled() + expect(hydrate).not.toHaveBeenCalled() + }) + return { path, bytes } +} + +describe('Session projection discovery', () => { + it('defers V3 migration without reading child bodies or publishing a successor', async () => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('parent'), {}, 3) + const child = await stored(fixture, SessionId('child'), { origin: 'subagent', parentSession: parent.header.id, createdAt: 20 }, 3) + const grandchild = await stored(fixture, SessionId('grandchild'), { origin: 'subagent', parentSession: child.header.id, createdAt: 30 }, 3) + const fork = await stored(fixture, SessionId('ordinary-fork'), { parentSession: parent.header.id, isSeeded: true }, 3) + const unrelated = await stored(fixture, SessionId('unrelated'), { origin: 'subagent', parentSession: SessionId('another-parent') }, 3) + const open = vi.spyOn(fixture.ctx.sessionPersistence, 'open') + const observe = vi.spyOn(fixture.ctx.sessionQuery, 'observeSession') + + await expect(fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal)).resolves.toEqual({ + kind: 'migration-required', + values: {}, + }) + expect(open).not.toHaveBeenCalled() + expect(observe).not.toHaveBeenCalled() + expect(await fixture.ctx.sessionPersistence.stat(parent.header.id)).toMatchObject({ + formatStatus: 'migration-required', + }) + expect(fixture.ctx.sessions.list()).toEqual([]) + for (const source of [parent, child, grandchild, fork, unrelated]) { + expect(await readFile(source.path, 'utf8')).toBe(source.bytes) + expect(await readdir(dirname(source.path))).toEqual(['session.v3.jsonl']) + } + }) + + it.each(['child', 'empty'] as const)('serves a valid %s catalog cache when migration is required', async (catalog) => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('cached-parent'), {}, 3) + const cache = await seedCache(fixture, parent.header, catalog) + const list = vi.spyOn(fixture.ctx.sessionQuery, 'listSessions').mockRejectedValue(new Error('unexpected fallback')) + await expect(fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal)).resolves.toEqual({ + kind: 'migration-required', + values: { + title: 'cached title', + subagentCatalog: catalog === 'empty' ? [] : [{ id: 'cached-child', createdAt: 2, mode: 'one-shot', label: 'cached child' }], + }, + }) + expect(list).not.toHaveBeenCalled() + expect(await readFile(cache.path, 'utf8')).toBe(cache.bytes) + }) + + it('serves other cached hints without inventing a missing catalog', async () => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('title-parent'), {}, 3) + await stored(fixture, SessionId('title-child'), { origin: 'subagent', parentSession: parent.header.id }) + const cache = await seedCache(fixture, parent.header, 'absent') + await expect(fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal)).resolves.toEqual({ + kind: 'migration-required', + values: { title: 'cached title' }, + }) + expect(fixture.ctx.sessionProjectionCache.cachedSnapshot(parent.header)?.values).toEqual({ title: 'cached title' }) + expect(await readFile(cache.path, 'utf8')).toBe(cache.bytes) + }) + + it('returns no hints from an unrelated cache identity', async () => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('recreated-parent'), {}, 3) + await seedCache(fixture, parent.header, 'child', false) + await expect(fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal)).resolves.toEqual({ + kind: 'migration-required', values: {}, + }) + }) + + it.each([true, false])('returns null for an absent Session (persistence mounted: %s)', async (withPersistence) => { + const fixture = await harness(withPersistence) + const list = vi.spyOn(fixture.ctx.sessionQuery, 'listSessions') + await expect(fixture.controller.projections({ sessionId: SessionId('missing') }, new AbortController().signal)).resolves.toBeNull() + expect(list).not.toHaveBeenCalled() + }) + + it('reads a current-format cold catalog from disk when its cache is absent', async () => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('current-cold')) + const event = { + type: 'subagent/catalog', seq: 0, time: 1, + data: { version: 1, childId: 'current-child', childCreatedAt: 2, mode: 'continuable', label: 'worker' }, + } + await writeFile(parent.path, `${parent.bytes}${JSON.stringify(event)}\n`) + const open = vi.spyOn(fixture.ctx.sessionPersistence, 'open') + const observe = vi.spyOn(fixture.ctx.sessionQuery, 'observeSession') + const signal = new AbortController().signal + + await expect(fixture.controller.projections({ sessionId: parent.header.id }, signal)).resolves.toMatchObject({ + kind: 'sequenced', asOfSeq: 0, + values: { subagentCatalog: [{ id: 'current-child', mode: 'continuable', label: 'worker' }] }, + }) + expect(observe).toHaveBeenCalledWith(parent.header.id, { signal }) + expect(open).toHaveBeenCalledWith(parent.header.id, 'read', { signal }) + expect(fixture.ctx.sessions.get(parent.header.id)).toBeUndefined() + expect(fixture.ctx.agents.get(parent.header.id)).toBeUndefined() + }) + + it('reports read-prepared historical files as migration-required until a successor is published', async () => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('prepared-cold'), {}, 3) + const observation = await fixture.ctx.sessionQuery.observeSession(parent.header.id) + observation[Symbol.dispose]() + const open = vi.spyOn(fixture.ctx.sessionPersistence, 'open').mockRejectedValue(new Error('unexpected body reread')) + + expect(await fixture.ctx.sessionPersistence.stat(parent.header.id)).toMatchObject({ + formatStatus: 'migration-required', + }) + await expect(fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal)) + .resolves.toEqual({ kind: 'migration-required', values: {} }) + expect(open).not.toHaveBeenCalled() + expect(fixture.ctx.sessions.get(parent.header.id)).toBeUndefined() + expect(await readFile(parent.path, 'utf8')).toBe(parent.bytes) + expect(await readdir(dirname(parent.path))).toEqual(['session.v3.jsonl']) + }) + + it('reads sequenced projections after write publication replaces the disk format status', async () => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('published-cold'), {}, 3) + using observation = await fixture.ctx.sessionQuery.observeSession(parent.header.id) + const expected = observation.projections + const signal = new AbortController().signal + await expect(fixture.controller.projections({ sessionId: parent.header.id }, signal)) + .resolves.toEqual({ kind: 'migration-required', values: {} }) + + const writer = await fixture.ctx.sessionPersistence.open(parent.header.id, 'write') + try { + await writer.flush() + } finally { + await writer.close() + } + + expect(await fixture.ctx.sessionPersistence.stat(parent.header.id)).toMatchObject({ + formatStatus: 'current', + }) + await expect(fixture.controller.projections({ sessionId: parent.header.id }, signal)) + .resolves.toEqual({ kind: 'sequenced', ...expected }) + expect(fixture.ctx.sessions.get(parent.header.id)).toBeUndefined() + expect(await readFile(parent.path, 'utf8')).toBe(parent.bytes) + // POSIX retains the write-lock inode after close; Windows uses a semaphore. + expect((await readdir(dirname(parent.path))).filter(name => name !== 'session.lock').sort()) + .toEqual(['session.v3.jsonl', `session.v${SESSION_FORMAT_VERSION}.jsonl`].sort()) + }) + + it('reports unsupported current-format events instead of deferring migration', async () => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('corrupt-current')) + await writeFile(parent.path, `${parent.bytes}${JSON.stringify({ type: 'missing/plugin-event', seq: 0, time: 1, data: {} })}\n`) + await expect(fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal)) + .rejects.toMatchObject({ code: 'gateway/internal' }) + }) + + it('reports unavailable projections from an otherwise readable observation', async () => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('without-projections')) + using source = await fixture.ctx.sessionQuery.observeSession(parent.header.id) + const { projections: _projections, ...observation } = source + vi.spyOn(fixture.ctx.sessionQuery, 'observeSession').mockResolvedValueOnce(observation) + + await expect(fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal)) + .rejects.toMatchObject({ code: 'session/projections-unavailable' }) + }) + + it.each([false, true])('rechecks live history when the stored source disappears after preflight (attached: %s)', async (attached) => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('missing-after-preflight')) + const snapshot = await fixture.ctx.sessionPersistence.stat(parent.header.id) + vi.spyOn(fixture.ctx.sessionPersistence, 'stat') + .mockResolvedValueOnce(snapshot) + .mockImplementationOnce(() => { + if (attached) fixture.ctx.sessions.create(parent.header.id, { meta: parent.header }) + return Promise.resolve(undefined) + }) + + const result = await fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal) + expect(result).toEqual(attached + ? { kind: 'sequenced', ...fixture.ctx.sessionProjections.snapshot(fixture.ctx.sessions.get(parent.header.id)!) } + : null) + }) + + it('serves the live registry cut instead of a conflicting cached hint', async () => { + const fixture = await harness() + const live = fixture.ctx.sessions.create(SessionId('live'), { meta: { cwd: fixture.root } }) + live.append('turn/start', { turn: 1 }) + const expected = fixture.ctx.sessionProjections.snapshot(live) + await seedCache(fixture, live.header, 'child') + const cached = vi.spyOn(fixture.ctx.sessionProjectionCache, 'cachedSnapshot') + const stat = vi.spyOn(fixture.ctx.sessionPersistence, 'stat').mockRejectedValue(new Error('metadata unavailable')) + await expect(fixture.controller.projections({ sessionId: live.id }, new AbortController().signal)).resolves.toEqual({ + kind: 'sequenced', ...expected, + }) + expect(stat).not.toHaveBeenCalled() + expect(cached).not.toHaveBeenCalled() + }) + + it.each([true, false])('prefers a Session attached during stat (stored header present: %s)', async (present) => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('stat-race'), {}, 3) + const snapshot = await fixture.ctx.sessionPersistence.stat(parent.header.id) + const entered = Promise.withResolvers() + const finish = Promise.withResolvers() + vi.spyOn(fixture.ctx.sessionPersistence, 'stat').mockImplementation(() => { + entered.resolve(undefined) + return finish.promise + }) + const operation = fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal) + try { + await entered.promise + const live = fixture.ctx.sessions.create(parent.header.id, { meta: parent.header }) + live.append('turn/start', { turn: 1 }) + finish.resolve(present ? snapshot : undefined) + await expect(operation).resolves.toEqual({ kind: 'sequenced', ...fixture.ctx.sessionProjections.snapshot(live) }) + } finally { + finish.resolve(undefined) + await Promise.allSettled([operation]) + } + }) + + it('reports target metadata I/O failures instead of an empty result', async () => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('failed-metadata')) + const failure = new Error('target metadata unavailable') + vi.spyOn(fixture.ctx.sessionPersistence, 'stat').mockRejectedValue(failure) + await expect(fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal)) + .rejects.toMatchObject({ code: 'gateway/internal', cause: failure }) + }) + + it('honors cancellation while waiting for target metadata', async () => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('cancelled-metadata')) + const snapshot = await fixture.ctx.sessionPersistence.stat(parent.header.id) + const entered = Promise.withResolvers() + const finish = Promise.withResolvers() + vi.spyOn(fixture.ctx.sessionPersistence, 'stat').mockImplementation(async () => { + entered.resolve(undefined) + await finish.promise + return snapshot + }) + const abort = new AbortController() + const operation = fixture.controller.projections({ sessionId: parent.header.id }, abort.signal) + try { + await entered.promise + abort.abort(new Error('cancelled by caller')) + finish.resolve(undefined) + await expect(operation).rejects.toMatchObject({ code: 'gateway/cancelled' }) + } finally { + finish.resolve(undefined) + await Promise.allSettled([operation]) + } + }) + + it('rejects an already-cancelled read before metadata access', async () => { + const fixture = await harness() + const stat = vi.spyOn(fixture.ctx.sessionPersistence, 'stat') + await expect(fixture.controller.projections({ sessionId: SessionId('cancelled') }, AbortSignal.abort())) + .rejects.toMatchObject({ code: 'gateway/cancelled' }) + expect(stat).not.toHaveBeenCalled() + }) + + it('preserves Remote failures while reading the migration cache metadata', async () => { + const fixture = await harness() + const parent = await stored(fixture, SessionId('typed-failures'), {}, 3) + const failure = new RemoteError('gateway/internal', 'metadata failure', {}) + vi.spyOn(fixture.ctx.sessionPersistence, 'stat').mockRejectedValueOnce(failure) + await expect(fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal)).rejects.toBe(failure) + }) + + it('rejects an empty identity without querying metadata', async () => { + const fixture = await harness() + const stat = vi.spyOn(fixture.ctx.sessionPersistence, 'stat') + await expect(fixture.controller.projections({ sessionId: SessionId('') }, new AbortController().signal)) + .rejects.toMatchObject({ code: 'gateway/bad-request' }) + expect(stat).not.toHaveBeenCalled() + }) +}) diff --git a/packages/api/session-controller/tests/remote-access.host.spec.ts b/packages/api/session-controller/tests/remote-access.host.spec.ts new file mode 100644 index 0000000000..bd39bc13f1 --- /dev/null +++ b/packages/api/session-controller/tests/remote-access.host.spec.ts @@ -0,0 +1,222 @@ +/** + * Session Controller under non-owner callers: the Session resource kind it + * registers, the Session readers of `session/page` and `session/follow`, + * `session/list`, `session/search`, and `session/control` called through a + * `global` role and filtered per Session through `remoteAccess.allows()`, the caller recorded + * on prompt sources, and `session/projections` admitted per Session through + * the Gateway. + */ + +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 TypertGatewayService from '@deepseek-ai/dsh-api-gateway' +import type { RemoteAccessBinding, RemoteAccessRole } from '@deepseek-ai/dsh-api-remote-access' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import { remoteMethods, type PeerId, type PeerScope, type Principal, type RemoteInvocation } from '@deepseek-ai/dsh-typert-protocol' +import TypertRegistry from '@deepseek-ai/dsh-typert-registry' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type SessionController from '../src/index.ts' +import { ApiSessionList } from '../src/list.ts' +import type { SessionControlFrame, SessionRequestId, SessionSearchValue } from '../src/types.ts' +import { createSessionTestController } from './test-remote.ts' + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + /** Test-only non-owner caller shared by the access specs. */ + 'test-guest': { readonly kind: 'test-guest'; readonly guest: string } + } +} + +const OWNER: Principal = { kind: 'owner' } +const GUEST: Principal = { kind: 'test-guest', guest: 'session-controller' } +const SHARED = SessionId('shared-session') +const PRIVATE = SessionId('private-session') + +/** Calls the Session list and control methods; each item still needs a Session role. */ +const LISTER: RemoteAccessRole<'global'> = { name: 'test:session-lister', resource: 'global', actions: ['session/list', 'session/control'] } +/** Reads one Session: its list row, its control projections, and its stored projections. */ +const READER: RemoteAccessRole<'session'> = { + name: 'test:session-reader', resource: 'session', actions: ['session/list', 'session/control', 'session/projections'], +} +const LIST_CALLS: RemoteAccessBinding = { role: LISTER, resource: { kind: 'global' } } +const READS_SHARED: RemoteAccessBinding = { role: READER, resource: { kind: 'session', id: SHARED } } +const SEARCH_CALLS: RemoteAccessBinding = { + role: { name: 'test:session-searcher', resource: 'global', actions: ['session/search'] }, + resource: { kind: 'global' }, +} +const SEARCHES_SHARED: RemoteAccessBinding = { + role: { name: 'test:session-search-reader', resource: 'session', actions: ['session/search'] }, + resource: { kind: 'session', id: SHARED }, +} + +const owned = new Set() +afterEach(async () => { + await Promise.all([...owned].map(ctx => ctx.fiber.dispose())) + owned.clear() +}) + +/** + * Register the guest policy. + * @returns the bindings the policy answers with; edits apply from the next Remote call. + */ +function guestPolicy(ctx: Context, ...bindings: RemoteAccessBinding[]): RemoteAccessBinding[] { + const held = [...bindings] + ctx.remoteAccess.registerPolicy('test-guest', { bindings: () => held }) + return held +} + +/** Invoke `session/` as the guest through the Gateway. */ +function guestCall(ctx: Context, method: string, args: Readonly>): Promise { + const peer: PeerScope = { id: 'session-access-peer' as PeerId, ctx, principal: GUEST, signal: new AbortController().signal, dispose: async () => {} } + return ctx.typertGateway.invoke({ peer, namespace: 'session', method, args }) +} + +async function harness(): Promise<{ + readonly ctx: Context + readonly controller: SessionController + readonly shared: Agent + readonly hidden: Agent + /** The Context a Gateway dispatch of `session/` binds for `principal`. */ + readonly as: (principal: Principal, method: string) => Context +}> { + const ctx = new Context() + owned.add(ctx) + await ctx.plugin(TypertRegistry) + await mountAgentLoopTestDependencies(ctx) + const loop = await mountAgentLoopTestHarness(ctx) + const shared = await loop.create(SHARED) + const hidden = await loop.create(PRIVATE) + const controller = createSessionTestController(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' }) + const as = (principal: Principal, method: string): Context => { + const invocation: RemoteInvocation = { + request: { namespace: 'session', method, args: {} }, + service: 'sessionController', + peer: { id: 'session-access-peer' as PeerId, ctx, principal, signal: new AbortController().signal, dispose: async () => {} }, + signal: new AbortController().signal, + uplink: (): AsyncIterable => ({ [Symbol.asyncIterator]: () => ({ next: async () => ({ done: true, value: undefined }) }) }), + } + return ctx.extend({ invocation }) + } + return { ctx, controller, shared, hidden, as } +} + +function message(text: string) { + return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }) +} + +describe('Session Controller access', () => { + it('owns the Session resource kind and its default sessionId field', async () => { + const { ctx } = await harness() + expect(() => ctx.typert.resources.register('session', { field: 'sessionId' })).toThrow(/already registered/) + }) + + it('reads the Session resource of page and follow requests from the addressed Session', async () => { + const { controller } = await harness() + for (const method of ['page', 'follow']) { + const reader = remoteMethods(controller).find(marker => marker.method === method)?.resources?.['session'] + expect(reader?.({ address: { kind: 'session', sessionId: SHARED } })).toBe(SHARED) + // A subagent address reads the child transcript; whether the parent's access covers it is the policy's rule. + expect(reader?.({ address: { kind: 'subagent', parentSessionId: SHARED, childSessionId: PRIVATE } })).toBe(PRIVATE) + } + }) + + it('lets a global role call session/list and lists only the Sessions a Session role admits', async () => { + const { ctx, as } = await harness() + await ctx.plugin(TypertGatewayService) + const held = guestPolicy(ctx, LIST_CALLS, READS_SHARED) + const rows = async (): Promise => { + const value = await guestCall(ctx, 'list', { _request: {} }) as { readonly items: readonly { readonly sessionId: SessionId }[] } + return value.items.map(item => item.sessionId) + } + await expect(rows()).resolves.toEqual([SHARED]) + // The global role admits the call, not any row. + held.splice(0, held.length, LIST_CALLS) + await expect(rows()).resolves.toEqual([]) + // A Session role alone does not admit the call: the global resource does not inherit from it. + held.splice(0, held.length, READS_SHARED) + await expect(rows()).rejects.toMatchObject({ + code: 'remote-access/denied', details: { action: 'session/list', reason: 'no-allow' }, + }) + const owner = await as(OWNER, 'list').sessionController.list({}, new AbortController().signal) + expect(owner.items.map(item => item.sessionId).sort()).toEqual([PRIVATE, SHARED].sort()) + }) + + it('returns a non-owner only the session/search hits whose Session a Session role admits', async () => { + const { ctx, as } = await harness() + await ctx.plugin(TypertGatewayService) + guestPolicy(ctx, SEARCH_CALLS, SEARCHES_SHARED) + const hits: SessionSearchValue = { + items: [{ sessionId: PRIVATE, snippet: 'private hit' }, { sessionId: SHARED, snippet: 'shared hit' }], + hasMore: true, + } + vi.spyOn(ApiSessionList.prototype, 'search').mockResolvedValue(hits) + await expect(guestCall(ctx, 'search', { request: { query: 'hit' } })).resolves.toEqual({ + items: [{ sessionId: SHARED, snippet: 'shared hit' }], + hasMore: true, + }) + await expect(as(OWNER, 'search').sessionController.search({ query: 'hit' }, new AbortController().signal)).resolves.toEqual(hits) + }) + + it('filters session/control baselines and projection frames for a non-owner', async () => { + const { ctx, shared, hidden, as } = await harness() + guestPolicy(ctx, LIST_CALLS, READS_SHARED) + const abort = new AbortController() + const guest = as(GUEST, 'control').sessionController.control(abort.signal)[Symbol.asyncIterator]() + const owner = as(OWNER, 'control').sessionController.control(abort.signal)[Symbol.asyncIterator]() + const baselineSessions = async (iterator: AsyncIterator): Promise => { + const next = await iterator.next() + if (next.done === true || next.value.type !== 'baseline') throw new Error('control stream opened without a baseline') + return Object.keys(next.value.value.projections).sort() + } + expect(await baselineSessions(guest)).toEqual([SHARED]) + expect(await baselineSessions(owner)).toEqual([PRIVATE, SHARED].sort()) + + hidden.inbox.append('next-turn', message('private work')) + shared.inbox.append('next-turn', message('shared work')) + const projected = async (iterator: AsyncIterator): Promise => { + for (;;) { + const next = await iterator.next() + if (next.done === true) throw new Error('control stream ended') + if (next.value.type === 'projection' && next.value.key === 'inbox') return next.value.sessionId + } + } + // The owner sees the private Session's frame first; the guest's first Inbox frame is the shared one. + expect(await projected(owner)).toBe(PRIVATE) + expect(await projected(guest)).toBe(SHARED) + abort.abort() + await Promise.all([guest.return?.(), owner.return?.()]) + }) + + it('records a non-owner caller on the prompt source and leaves owner sources unchanged', async () => { + const { shared, as } = await harness() + const signal = new AbortController().signal + const prompt = (principal: Principal, requestId: string) => as(principal, 'prompt').sessionController.prompt({ + sessionId: SHARED, + requestId: requestId as SessionRequestId, + mode: 'queue', + content: [{ type: 'text', text: `from ${principal.kind}` }], + }, signal) + await expect(prompt(GUEST, 'guest-1')).resolves.toEqual({ accepted: true }) + await expect(prompt(OWNER, 'owner-1')).resolves.toEqual({ accepted: true }) + // The durable Inbox splice records each accepted message with its source. + const logged = shared.session.snapshotEvents() + .flatMap(event => event.type === 'agent/inbox/spliced' ? event.data.inserted.map(item => item.source) : []) + expect(logged).toEqual([ + { kind: 'user', rpcId: 'guest-1', principal: GUEST }, + { kind: 'user', rpcId: 'owner-1' }, + ]) + }) + + it('lets a non-owner read projections only in a Session its Session role names', async () => { + const { ctx } = await harness() + await ctx.plugin(TypertGatewayService) + guestPolicy(ctx, READS_SHARED) + const projections = (sessionId: SessionId): Promise => guestCall(ctx, 'projections', { request: { sessionId } }) + await expect(projections(SHARED)).resolves.toMatchObject({ kind: 'sequenced' }) + await expect(projections(PRIVATE)).rejects.toMatchObject({ + code: 'remote-access/denied', details: { action: 'session/projections', reason: 'no-allow' }, + }) + }) +}) diff --git a/packages/api/session-controller/tests/remote/session.client.ts b/packages/api/session-controller/tests/remote/session.client.ts index 4d86abcf9e..591dd60985 100644 --- a/packages/api/session-controller/tests/remote/session.client.ts +++ b/packages/api/session-controller/tests/remote/session.client.ts @@ -145,7 +145,7 @@ export const sessionWorld: RemoteTable = { data: 'AA==', }), 'session/page': pageRule(ok({ records: [], hasMore: false })), - 'session/projections': ok({ asOfSeq: -1, values: { subagentCatalog: [] } }), + 'session/projections': ok({ kind: 'sequenced', asOfSeq: -1, values: { subagentCatalog: [] } }), 'subagents/prompt': ok({ messageId: 'fake-message' }), 'subagents/interruptByParent': ok({ accepted: true }), }, diff --git a/packages/api/session-controller/tests/session-cold.host.spec.ts b/packages/api/session-controller/tests/session-cold.host.spec.ts index aefd8b9288..a6b7a033dd 100644 --- a/packages/api/session-controller/tests/session-cold.host.spec.ts +++ b/packages/api/session-controller/tests/session-cold.host.spec.ts @@ -77,6 +77,53 @@ function conversationEvents(): SessionEvent[] { } describe('sessions.list cold merge', () => { + it('preserves listed format status and prefers live readiness without extra persistence reads', async () => { + const ctx = new Context() + try { + await ctx.plugin(SessionStore) + await ctx.plugin(AgentRegistry) + const historical = header('format-historical', 100) + const current = header('format-current', 200) + const unknown = header('format-unknown', 300) + const shared = ctx.sessions.create(sid('format-shared'), { meta: { createdAt: 400, cwd: '/proj' } }).header + const liveOnly = ctx.sessions.create(sid('format-live'), { meta: { cwd: '/proj' } }) + const snapshots: SessionPersistenceSnapshot[] = [ + { ...statSnapshot(historical), formatStatus: 'migration-required' }, + { ...statSnapshot(current), formatStatus: 'current' }, + statSnapshot(unknown), + { ...statSnapshot(shared), formatStatus: 'migration-required' }, + ] + const list = vi.fn(async () => snapshots) + const stat = vi.fn() + const open = vi.fn() + ctx.provide('sessionPersistence', { list, stat, open } as never) + const remote = createSessionTestRemote(ctx, { + defaultModelSelection: () => ({ provider: 'p', model: 'm' }), + cwd: '/tmp', + }) + const observe = vi.spyOn(ctx.sessionQuery, 'observeSession') + try { + const response = await remote.list(request({})) + if (!response.ok) throw new Error('list failed') + const byId = new Map(response.value.items.map(item => [item.sessionId, item])) + expect(byId.get(historical.id)).toMatchObject({ formatStatus: 'migration-required' }) + expect(byId.get(current.id)).toMatchObject({ formatStatus: 'current' }) + expect(byId.get(unknown.id)).toMatchObject({ sessionId: unknown.id }) + expect(byId.get(unknown.id)).not.toHaveProperty('formatStatus') + expect(byId.get(shared.id)).toMatchObject({ formatStatus: 'current' }) + expect(byId.get(liveOnly.id)).toMatchObject({ formatStatus: 'current' }) + expect(list).toHaveBeenCalledTimes(1) + expect(stat).not.toHaveBeenCalled() + expect(open).not.toHaveBeenCalled() + expect(observe).not.toHaveBeenCalled() + } finally { + observe.mockRestore() + } + } finally { + await ctx.fiber.dispose() + } + }) + it('uses a predecessor title hint with zero cold stat or body reads', async () => { const ctx = new Context() await ctx.plugin(SessionStore) diff --git a/packages/api/session-controller/tests/session-fork.host.spec.ts b/packages/api/session-controller/tests/session-fork.host.spec.ts index 137eeeb190..e6ba8321ce 100644 --- a/packages/api/session-controller/tests/session-fork.host.spec.ts +++ b/packages/api/session-controller/tests/session-fork.host.spec.ts @@ -11,6 +11,7 @@ import { ToolCallId, createMessage, createUserMessage, ReasoningEffortId } from import type { LlmCallConfig } from '@deepseek-ai/dsh-llm' import SessionStore, { TOOL_OUTCOME_UNKNOWN, SESSION_FORMAT_VERSION, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import { SessionPersistenceRevision, type SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import TokenMeter from '@deepseek-ai/dsh-token-meter' import type { Workspace } from '@deepseek-ai/dsh-workspace' @@ -95,6 +96,151 @@ const remote = (ctx: Context) => createSessionTestRemote(ctx, { }) describe('sessions.fork', () => { + it.each([ + { allowMigration: undefined, status: 'current' }, + { allowMigration: false, status: 'current' }, + { allowMigration: false, status: undefined }, + { allowMigration: undefined, status: 'migration-required' }, + { allowMigration: true, status: 'migration-required' }, + ] as const)('forks cold history with allowMigration=$allowMigration and format=$status', async ({ allowMigration, status }) => { + const ctx = await composed() + try { + const source = ctx.sessions.prepare(sid('current-cold'), { meta: { cwd: '/proj' } }) + source.append('turn/start', { turn: 1 }) + source.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + const snapshot: SessionPersistenceSnapshot = { + header: source.header, + revision: SessionPersistenceRevision('test:cold-source'), + ...status === undefined ? {} : { formatStatus: status }, + } + ctx.provide('sessionPersistence', testSessionPersistence(ctx, { + list: () => Promise.resolve([source.header]), + stat: () => Promise.resolve(snapshot), + inspect: () => Promise.resolve({ meta: source.header, events: source.snapshotEvents() }), + }) as never) + const open = vi.spyOn(ctx.sessionPersistence, 'open') + + const response = await remote(ctx).fork({ + sessionId: source.id, + ...allowMigration === undefined ? {} : { allowMigration }, + }) + + if (!response.ok) throw response.error + expect(open).toHaveBeenCalledWith(source.id, 'read', undefined) + expect(ctx.sessions.get(source.id)).toBeUndefined() + expect(ctx.sessions.get(response.value.sessionId)?.inheritedEventCount).toBe(2) + } finally { + await ctx.fiber.dispose() + } + }) + + it('reports required migration before creating a fork when the caller disallows it', async () => { + const ctx = await composed() + try { + const sourceId = sid('requires-migration') + const source = ctx.sessions.prepare(sourceId, { meta: { cwd: '/proj' } }) + const snapshot: SessionPersistenceSnapshot = { + header: source.header, + revision: SessionPersistenceRevision('test:requires-migration'), + formatStatus: 'migration-required', + } + const stat = vi.fn(async () => snapshot) + ctx.provide('sessionPersistence', testSessionPersistence(ctx, { stat }) as never) + const open = vi.spyOn(ctx.sessionPersistence, 'open') + const observe = vi.spyOn(ctx.sessionQuery, 'observeSession') + const create = vi.spyOn(ctx.agents, 'create') + + await expect(remote(ctx).fork({ sessionId: sourceId, allowMigration: false })).resolves.toMatchObject({ + ok: false, error: { code: 'session/migration-required', details: { sessionId: sourceId } }, + }) + expect(stat).toHaveBeenCalledExactlyOnceWith(sourceId) + expect(open).not.toHaveBeenCalled() + expect(observe).not.toHaveBeenCalled() + expect(create).not.toHaveBeenCalled() + } finally { + await ctx.fiber.dispose() + } + }) + + it('forks a resident Session without consulting disk metadata or requiring a live Agent', async () => { + const ctx = await composed() + try { + const source = ctx.sessions.create(sid('resident-source'), { meta: { cwd: '/proj' } }) + source.append('turn/start', { turn: 1 }) + source.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + const stat = vi.fn(() => Promise.reject(new Error('unexpected metadata read'))) + ctx.provide('sessionPersistence', testSessionPersistence(ctx, { stat }) as never) + + const result = await remote(ctx).fork({ sessionId: source.id, allowMigration: false }) + + if (!result.ok) throw result.error + expect(stat).not.toHaveBeenCalled() + expect(ctx.agents.get(source.id)).toBeUndefined() + expect(ctx.sessions.get(result.value.sessionId)?.inheritedEventCount).toBe(2) + } finally { + await ctx.fiber.dispose() + } + }) + + it('forks a source attached while its historical format stat is pending', async () => { + const ctx = await composed() + try { + const sourceId = sid('attached-during-stat') + const source = ctx.sessions.prepare(sourceId, { meta: { cwd: '/proj' } }) + const snapshot: SessionPersistenceSnapshot = { + header: source.header, + revision: SessionPersistenceRevision('test:attaching-source'), + formatStatus: 'migration-required', + } + const entered = Promise.withResolvers() + const finish = Promise.withResolvers() + const stat = vi.fn(() => { + entered.resolve(undefined) + return finish.promise + }) + ctx.provide('sessionPersistence', testSessionPersistence(ctx, { stat }) as never) + const operation = remote(ctx).fork({ sessionId: sourceId, allowMigration: false }) + try { + await entered.promise + const live = ctx.sessions.create(sourceId, { meta: source.header }) + live.append('turn/start', { turn: 1 }) + live.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + finish.resolve(snapshot) + + const result = await operation + if (!result.ok) throw result.error + expect(stat).toHaveBeenCalledExactlyOnceWith(sourceId) + expect(ctx.sessions.get(result.value.sessionId)?.inheritedEventCount).toBe(2) + } finally { + finish.resolve(undefined) + await Promise.allSettled([operation]) + } + } finally { + await ctx.fiber.dispose() + } + }) + + it('reports a stat failure without treating it as required migration or opening the source', async () => { + const ctx = await composed() + try { + const sourceId = sid('failed-source-stat') + const stat = vi.fn(() => Promise.reject(new Error('source metadata unavailable'))) + ctx.provide('sessionPersistence', testSessionPersistence(ctx, { stat }) as never) + const observe = vi.spyOn(ctx.sessionQuery, 'observeSession') + const create = vi.spyOn(ctx.agents, 'create') + + await expect(remote(ctx).fork({ sessionId: sourceId, allowMigration: false })).resolves.toMatchObject({ + ok: false, error: { code: 'gateway/internal', message: 'source metadata unavailable' }, + }) + + expect(stat).toHaveBeenCalledExactlyOnceWith(sourceId) + expect(observe).not.toHaveBeenCalled() + expect(create).not.toHaveBeenCalled() + } finally { + await ctx.fiber.dispose() + } + }) + it('keeps the completed manual compaction checkpoint when atSeq is omitted', async () => { const ctx = new Context() try { 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/tests/session.client.spec.ts b/packages/api/session-controller/tests/session.client.spec.ts index ccba6d3a6a..8d1838e40f 100644 --- a/packages/api/session-controller/tests/session.client.spec.ts +++ b/packages/api/session-controller/tests/session.client.spec.ts @@ -513,6 +513,19 @@ describe('prompt and cancel errors', () => { expect(session.getSnapshot().subagent).toEqual({ address: CHILD, parentAvailable: true }) }) + it('sends an addressed child continuation under its echo request id and retires a refused echo', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID, { address: CHILD, parentAvailable: true }) + await session.open() + const accepted = session.beginSubmission({ mode: 'queue', text: '继续', attachments: [] }) + await session.prompt([{ type: 'text', text: '继续' }], 'queue', undefined, accepted.requestId) + expect(mock.log.requests('subagents/prompt')).toMatchObject([{ requestId: accepted.requestId, ...CHILD }]) + expect(session.getSnapshot().pendingSubmissions.map(echo => echo.requestId)).toEqual([accepted.requestId]) + + const refused = session.beginSubmission({ mode: 'queue', text: '附件', attachments: [] }) + await session.prompt([{ type: 'file', receiptId: 'receipt' as never }], 'queue', undefined, refused.requestId) + expect(session.getSnapshot().pendingSubmissions.map(echo => echo.requestId)).toEqual([accepted.requestId]) + }) + it('forwards continuation image parts to the subagent prompt Remote unstripped', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID, { address: CHILD, parentAvailable: true }) await session.open() diff --git a/packages/api/session-controller/tests/sessions-service.client.spec.ts b/packages/api/session-controller/tests/sessions-service.client.spec.ts index e25339bc93..d92a83198e 100644 --- a/packages/api/session-controller/tests/sessions-service.client.spec.ts +++ b/packages/api/session-controller/tests/sessions-service.client.spec.ts @@ -79,6 +79,31 @@ async function feedList(b: Bench, rows: FeedRow[]): Promise { } describe('list store projection', () => { + it('publishes format-status changes and preserves a newer update over an in-flight list', async ({ bench }) => { + const b = bench() + const historical = { + sessionId: sid('s1'), updatedAt: 1, running: false, blank: false, agentAvailable: false, + formatStatus: 'migration-required' as const, + } + b.mock.remote.session.list.mockResolvedValue(ok({ items: [historical] })) + await b.svc.refresh() + await Promise.resolve() + expect(b.svc.list.getSnapshot().byId[sid('s1')]?.formatStatus).toBe('migration-required') + + const pending = Promise.withResolvers>>() + b.unblock.push(() => { pending.resolve(ok({ items: [historical] })) }) + b.mock.remote.session.list.mockReturnValueOnce(pending.promise) + const refreshing = b.svc.refresh() + b.svc.handleSessionAdded({ ...historical, formatStatus: 'current' }) + await Promise.resolve() + expect(b.svc.list.getSnapshot().byId[sid('s1')]?.formatStatus).toBe('current') + pending.resolve(ok({ items: [historical] })) + await refreshing + await Promise.resolve() + expect(b.svc.list.getSnapshot().byId[sid('s1')]?.formatStatus).toBe('current') + expect(b.mock.remote.session.projections).not.toHaveBeenCalled() + }) + it('projects durable titles separately from cwd/id display fallbacks and parent links', async ({ bench }) => { const b = bench() b.svc.handleControlFrame({ @@ -730,7 +755,7 @@ describe('catalog-addressed navigation', () => { const b = bench() await feedList(b, [{ id: 'root' }]) b.mock.remote.session.projections.mockResolvedValue(ok({ - asOfSeq: 0, values: { subagentCatalog: [{ id: sid('child'), createdAt: 1, mode: 'continuable', label: 'Child' }] }, + kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ id: sid('child'), createdAt: 1, mode: 'continuable', label: 'Child' }] }, })) await b.svc.refreshProjections(sid('root')) const address = b.svc.subagentAddress(sid('child'))! @@ -761,7 +786,7 @@ describe('catalog-addressed navigation', () => { type: 'projection', sessionId: sid('one-shot'), key: 'title', value: title, seq: 2, }) b.mock.remote.session.projections.mockResolvedValue(ok({ - asOfSeq: 0, values: { subagentCatalog: [{ id: sid('one-shot'), createdAt: 1, mode: 'one-shot' }] }, + kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ id: sid('one-shot'), createdAt: 1, mode: 'one-shot' }] }, })) await b.svc.refreshProjections(sid('root')) expect(b.svc.list.getSnapshot().byId[sid('one-shot')]?.displayTitle).toBe(title ?? 'one-shot') @@ -780,16 +805,16 @@ describe('catalog-addressed navigation', () => { b.mock.remote.session.projections.mockImplementation((payload) => { const { sessionId } = payload as { sessionId: SessionId } if (sessionId === sid('root')) { - return Promise.resolve(ok({ asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, + return Promise.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, id: sid('child'), mode: 'continuable', label: 'Child', }] } })) } if (sessionId === sid('child')) { - return Promise.resolve(ok({ asOfSeq: 0, values: { title: 'Child session title', subagentCatalog: [{ createdAt: 1, + return Promise.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { title: 'Child session title', subagentCatalog: [{ createdAt: 1, id: sid('grandchild'), mode: 'continuable', label: 'Grandchild', }] } })) } - return Promise.resolve(ok({ asOfSeq: 0, values: { subagentCatalog: [] } })) + return Promise.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [] } })) }) await feedList(b, [ { id: 'root' }, @@ -819,16 +844,16 @@ describe('catalog-addressed navigation', () => { b.mock.remote.session.projections.mockImplementation((payload) => { const { sessionId } = payload as { sessionId: SessionId } if (sessionId === sid('root')) { - return Promise.resolve(ok({ asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, + return Promise.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, id: sid('child'), mode: 'continuable', label: 'Child', }] } })) } if (sessionId === sid('child')) { - return Promise.resolve(ok({ asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, + return Promise.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ createdAt: 1, id: sid('grandchild'), mode: 'continuable', label: 'Grandchild', }] } })) } - return Promise.resolve(ok({ asOfSeq: 0, values: { subagentCatalog: [] } })) + return Promise.resolve(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [] } })) }) await feedList(b, [{ id: 'root' }]) await b.svc.refreshProjections(sid('root')) @@ -907,6 +932,38 @@ describe('create', () => { }) describe('fork', () => { + it.for([undefined, false, true])('forwards migration permission %s without opening the source', async (allowMigration, { bench }) => { + const b = bench() + b.mock.remote.session.fork.mockResolvedValueOnce(ok({ sessionId: sid('child') })) + const source = sid('source') + const permission = allowMigration === undefined ? {} : { allowMigration } + + await expect(b.svc.fork({ sessionId: source, atSeq: 7, ...permission })).resolves.toBe(sid('child')) + + expect(b.mock.remote.session.fork).toHaveBeenCalledExactlyOnceWith({ sessionId: source, atSeq: 7, ...permission }) + expect(b.svc.binding(source)).toBeUndefined() + expect(b.mock.log.requests(FOLLOW)).toHaveLength(0) + }) + + it('preserves the Host migration refusal without creating or opening a Session', async ({ bench }) => { + const b = bench() + const source = sid('source') + const error = new RemoteError('session/migration-required', 'migration required', { sessionId: source }) + const onCreated = vi.fn<(childId: SessionId) => void>() + b.mock.remote.session.fork.mockResolvedValueOnce(err(error)) + + const failure = await b.svc.fork({ sessionId: source, allowMigration: false, onCreated }) + .catch((cause: unknown) => cause) + + expect(failure).toBeInstanceOf(SessionForkError) + expect(failure).toMatchObject({ sourceSessionId: source, rpcError: error }) + expect(b.mock.remote.session.fork).toHaveBeenCalledExactlyOnceWith({ sessionId: source, allowMigration: false }) + expect(onCreated).not.toHaveBeenCalled() + expect(b.mock.remote.session.rename).not.toHaveBeenCalled() + expect(b.svc.list.getSnapshot().ids).toEqual([]) + expect(b.mock.log.requests(FOLLOW)).toHaveLength(0) + }) + it('propagates a failed fork without creating or retaining a child', async ({ bench }) => { const b = bench() const error = new RemoteError('session/not-found', 'source missing', { sessionId: sid('source') }) diff --git a/packages/api/session-controller/tests/subagent-catalog.host.spec.ts b/packages/api/session-controller/tests/subagent-catalog.host.spec.ts index 4d9c4360fc..de1852991a 100644 --- a/packages/api/session-controller/tests/subagent-catalog.host.spec.ts +++ b/packages/api/session-controller/tests/subagent-catalog.host.spec.ts @@ -2,12 +2,10 @@ import { Context } from '@deepseek-ai/cordis' import { provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' -import SessionStore, { SESSION_FORMAT_VERSION, SessionLogOffset, SessionSeq, SessionId } from '@deepseek-ai/dsh-session' +import SessionStore, { SESSION_FORMAT_VERSION, SessionSeq, SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' -import { SessionQueryError } from '@deepseek-ai/dsh-session-query' -import type { SessionObservation } from '@deepseek-ai/dsh-session-query' import SubagentRuntime from '@deepseek-ai/dsh-subagent' -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { createSessionTestController, installSessionReadTestServices, @@ -41,8 +39,15 @@ const events: SessionEvent[] = [{ }, }] +const contexts: Context[] = [] +afterEach(async () => { + vi.restoreAllMocks() + await Promise.all(contexts.splice(0).map(ctx => ctx.fiber.dispose())) +}) + async function bench() { const ctx = new Context() + contexts.push(ctx) await ctx.plugin(SessionStore) await ctx.plugin(AgentRegistry) ctx.provide('sessionPersistence', testSessionPersistence(ctx, { @@ -82,20 +87,48 @@ describe('SessionController subagent catalog', () => { } }) - it('requests a stored parent catalog by id without loading an Agent', async () => { + it.each([false, true])('reads an uncached parent catalog without loading an Agent (explicit current format: %s)', async (withFormat) => { const { ctx, controller } = await bench() + const stored = await ctx.sessionPersistence.stat(PARENT) + if (stored === undefined) throw new Error('parent fixture is missing') + const stat = vi.spyOn(ctx.sessionPersistence, 'stat').mockResolvedValueOnce(withFormat + ? { ...stored, formatStatus: 'current' } + : stored) const observe = vi.spyOn(ctx.sessionQuery, 'observeSession') + const open = vi.spyOn(ctx.sessionPersistence, 'open') + const resume = vi.spyOn(ctx.agents, 'resume').mockRejectedValue(new Error('unexpected Agent resume')) const signal = new AbortController().signal - await expect(controller.projections({ sessionId: PARENT }, signal)).resolves.toMatchObject({ values: { subagentCatalog: [{ - id: CHILD, - mode: 'continuable', - label: 'worker', - }] } }) - expect(observe).toHaveBeenCalledOnce() - expect(observe).toHaveBeenCalledWith(PARENT, { - signal, + await expect(controller.projections({ sessionId: PARENT }, signal)).resolves.toMatchObject({ + kind: 'sequenced', values: { subagentCatalog: [{ id: CHILD, mode: 'continuable', label: 'worker' }] }, }) + expect(stat).toHaveBeenCalledWith(PARENT, { signal }) + expect(observe).toHaveBeenCalledWith(PARENT, { signal }) + expect(open).toHaveBeenCalledWith(PARENT, 'read', { signal }) + expect(resume).not.toHaveBeenCalled() + expect(ctx.sessions.get(PARENT)).toBeUndefined() + expect(ctx.agents.get(PARENT)).toBeUndefined() + }) + + it('uses disk migration status instead of the normalized header version to defer a cold catalog read', async () => { + const { ctx, controller } = await bench() + const stored = await ctx.sessionPersistence.stat(PARENT) + if (stored === undefined) throw new Error('parent fixture is missing') + vi.spyOn(ctx.sessionPersistence, 'stat').mockResolvedValueOnce({ + ...stored, + formatStatus: 'migration-required', + }) + const observe = vi.spyOn(ctx.sessionQuery, 'observeSession') + const open = vi.spyOn(ctx.sessionPersistence, 'open') + + expect(stored.header.version).toBe(SESSION_FORMAT_VERSION) + await expect(controller.projections({ sessionId: PARENT }, new AbortController().signal)) + .resolves.toEqual({ kind: 'migration-required', values: {} }) + + expect(observe).not.toHaveBeenCalled() + expect(open).not.toHaveBeenCalled() + expect(ctx.sessions.get(PARENT)).toBeUndefined() + expect(ctx.agents.get(PARENT)).toBeUndefined() }) it('serves a live parent from its maintained registry state without folding its log', async () => { @@ -113,7 +146,7 @@ describe('SessionController subagent catalog', () => { const hydrate = vi.spyOn(ctx.sessionProjections, 'hydrate') const result = await controller.projections({ sessionId: PARENT }, new AbortController().signal) - expect(result).toMatchObject({ values: { subagentCatalog: [{ + expect(result).toMatchObject({ kind: 'sequenced', values: { subagentCatalog: [{ id: CHILD, mode: 'one-shot', label: 'live worker', @@ -140,7 +173,7 @@ describe('SessionController subagent catalog', () => { const unavailable = await controller.list({}, new AbortController().signal) expect(unavailable.items.find(item => item.sessionId === PARENT)?.agentAvailable).toBe(false) const result = await controller.projections({ sessionId: PARENT }, new AbortController().signal) - expect(result).toMatchObject({ asOfSeq: 0, values: { subagentCatalog: [{ id: CHILD, createdAt: 8, mode: 'one-shot' }] } }) + expect(result).toMatchObject({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ id: CHILD, createdAt: 8, mode: 'one-shot' }] } }) }) it('does not republish a Session when its Agent outlives the Session registration', async () => { @@ -158,6 +191,7 @@ describe('SessionController subagent catalog', () => { it('reads registered projections without a subagent provider or catalog key', async () => { const ctx = new Context() + contexts.push(ctx) await ctx.plugin(SessionStore) await ctx.plugin(AgentRegistry) installSessionReadTestServices(ctx) @@ -165,7 +199,8 @@ describe('SessionController subagent catalog', () => { const session = ctx.sessions.create(PARENT, { meta: { cwd: '/workspace' } }) const expected = ctx.sessionProjections.snapshot(session) expect(expected.values.subagentCatalog).toBeUndefined() - await expect(controller.projections({ sessionId: PARENT }, new AbortController().signal)).resolves.toEqual(expected) + await expect(controller.projections({ sessionId: PARENT }, new AbortController().signal)) + .resolves.toEqual({ kind: 'sequenced', ...expected }) expect(ctx.agents.get(PARENT)).toBeUndefined() }) @@ -183,36 +218,19 @@ describe('SessionController subagent catalog', () => { }) }) - it('maps query cancellation, missing projections, and unexpected failures', async () => { + it('reports a live snapshot failure without falling back to stored metadata', async () => { const { ctx, controller } = await bench() - const observe = vi.spyOn(ctx.sessionQuery, 'observeSession') - observe.mockRejectedValueOnce(new SessionQueryError( - 'query cancelled', - 'SESSION_QUERY_ABORTED', - )) - await expect(controller.projections({ sessionId: PARENT }, new AbortController().signal)).rejects.toMatchObject({ - code: 'gateway/cancelled', + const parent = ctx.sessions.create(PARENT, { meta: { cwd: '/workspace' } }) + const failure = new Error('projection snapshot failed') + const snapshot = vi.spyOn(ctx.sessionProjections, 'snapshot').mockImplementationOnce(() => { + throw failure }) - - observe.mockRestore() - // An observation without the catalog state means no registry served it. - const stateless: SessionObservation = { - source: 'prepared', - header, - inheritedEventCount: SessionLogOffset(0), - events, - cursor: SessionSeq(0), - retain: () => stateless, - [Symbol.dispose]: () => {}, - } - vi.spyOn(ctx.sessionQuery, 'observeSession').mockResolvedValueOnce(stateless) - await expect(controller.projections({ sessionId: PARENT }, new AbortController().signal)).rejects.toMatchObject({ - code: 'session/projections-unavailable', - }) - - vi.spyOn(ctx.sessionQuery, 'observeSession').mockRejectedValueOnce(new Error('storage offline')) + const stat = vi.spyOn(ctx.sessionPersistence, 'stat') await expect(controller.projections({ sessionId: PARENT }, new AbortController().signal)).rejects.toMatchObject({ code: 'gateway/internal', + cause: failure, }) + expect(snapshot).toHaveBeenCalledWith(parent) + expect(stat).not.toHaveBeenCalled() }) }) diff --git a/packages/api/session-controller/tests/test-remote.ts b/packages/api/session-controller/tests/test-remote.ts index 71db06b22b..586afcde7b 100644 --- a/packages/api/session-controller/tests/test-remote.ts +++ b/packages/api/session-controller/tests/test-remote.ts @@ -31,6 +31,7 @@ import { remoteErrorOf, type RemoteResult, } from '@deepseek-ai/dsh-typert-protocol' +import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access' import SessionController from '../src/index.ts' import type { ModelCatalog, @@ -243,6 +244,7 @@ function installControllers( ctx.provide('typert', { lookups: { configure: () => dispose }, contexts: { configureHost: () => dispose }, + resources: { register: () => dispose }, } as never) } if (ctx.get('agentDefaultModel') === undefined) { @@ -289,6 +291,7 @@ function installControllers( } as never) } installSessionReadTestServices(ctx) + if (ctx.get('remoteAccess') === undefined) new RemoteAccessService(ctx) const cwd = vi.spyOn(process, 'cwd').mockReturnValue(defaults.cwd) let controller: SessionController try { diff --git a/packages/api/session-controller/tsconfig.host.json b/packages/api/session-controller/tsconfig.host.json index 6376b437ca..8f90ca7a6a 100644 --- a/packages/api/session-controller/tsconfig.host.json +++ b/packages/api/session-controller/tsconfig.host.json @@ -104,6 +104,9 @@ { "path": "../../typert/protocol" }, + { + "path": "../remote-access/tsconfig.host.json" + }, { "path": "../../typert/registry" }, 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 568e0cca9d..8de6b6bd54 100644 --- a/packages/api/settings-controller/package.json +++ b/packages/api/settings-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-settings-controller", "description": "Remote owner for the configuration surfaces over the settings-domain seams", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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", @@ -49,7 +51,7 @@ "license": "MIT", "dependencies": { "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/api/settings-controller/src/credentials.ts b/packages/api/settings-controller/src/credentials.ts index 99c42a4cf0..3889669048 100644 --- a/packages/api/settings-controller/src/credentials.ts +++ b/packages/api/settings-controller/src/credentials.ts @@ -132,11 +132,12 @@ export class CredentialsController extends TypertRemoteService { /** * Run one remote write and report every refusal as `credential/rejected` - * carrying the seam's own message: a read-only source shadowing the reference - * is what a configuration surface must show verbatim. Callers brand the - * reference before entering, so a name outside the grammar never reaches this - * path and fails the same way it does on the read side. The details name only - * the reference, so no failure path can carry the value back out. + * carrying the seam's own message: a provider refusal, such as a stored + * document that no longer parses, is what a settings page must show + * verbatim. Callers brand the reference before entering, so a name outside + * the grammar never reaches this path and fails the same way it does on the + * read side. The details name only the reference, so no failure path can + * carry the value back out. */ private async write(ref: string, write: () => Promise): Promise { try { diff --git a/packages/api/settings-controller/src/types.ts b/packages/api/settings-controller/src/types.ts index 2110184363..3d11c6ab0c 100644 --- a/packages/api/settings-controller/src/types.ts +++ b/packages/api/settings-controller/src/types.ts @@ -20,9 +20,9 @@ declare module '@deepseek-ai/dsh-typert-protocol' { */ 'settings/conflict': { readonly ns: string; readonly expected: number; readonly actual: number } /** - * The provider refused a valid credential write, for example because a - * read-only source shadows the reference. The details name only the - * reference, never the value. + * The provider refused a valid credential write, for example because the + * stored document no longer parses. The details name only the reference, + * never the value. */ 'credential/rejected': { readonly ref: string } } diff --git a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts index 9ac14d9eb8..5eeb190385 100644 --- a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts +++ b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts @@ -24,7 +24,7 @@ class LiteralRejectingCredentials extends MemoryCredentials { /** A store whose provider-owned policy rejects an otherwise valid write. */ class RejectingCredentials extends MemoryCredentials { override set(): Promise { - return Promise.reject(new Error('a read-only source shadows this reference')) + return Promise.reject(new Error('the stored document no longer parses')) } } @@ -120,7 +120,7 @@ describe('the credentials Remote namespace a configuration surface calls', () => const failure = await controller.set('DEEPSEEK_API_KEY', 'sk-live').catch((error: unknown) => error) const { code, message, details } = remoteErrorOf(failure) ?? {} expect(code).toBe('credential/rejected') - expect(message).toContain('read-only source') + expect(message).toContain('no longer parses') expect(details).toEqual({ ref: 'DEEPSEEK_API_KEY' }) }) diff --git a/packages/api/terminal-controller/README.i18n.yaml b/packages/api/terminal-controller/README.i18n.yaml index 167264cbde..e25664e9e3 100644 --- a/packages/api/terminal-controller/README.i18n.yaml +++ b/packages/api/terminal-controller/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 1fa9a72d1ee045cc /deepseek-ai-dsh-api-terminal-controller/use-this-package: - en: abda92ff99530baa - zh: 67aa726392ae8e05 + en: 056c8b23819be51f + zh: d4525149ad4c32ce /deepseek-ai-dsh-api-terminal-controller/understand-the-implementation: - en: 94dcd1835c55acc2 - zh: cbfeb2da8cb60395 + en: b34684c82aa5fe5f + zh: 07638715c8708546 /deepseek-ai-dsh-api-terminal-controller/further-exploration: en: b1b5d2a2bfb8cc6a zh: aa0ea568aa63fda5 diff --git a/packages/api/terminal-controller/README.md b/packages/api/terminal-controller/README.md index 2709674163..856ebc96de 100644 --- a/packages/api/terminal-controller/README.md +++ b/packages/api/terminal-controller/README.md @@ -25,7 +25,7 @@ Open the execution environment's default shell in the Session's current working ## Use this package -The Web bundle mounts this package with the subprocess provider, working-directory service, sandbox policy and Typert Gateway. `remote.terminal` exposes `environment`, `shells`, `list`, `create`, `retain`, `follow`, `write`, `resize`, `rename` and `close`; each operation is scoped by Session identity. Listing reads retained Host terminals directly, so viewing an offline Session neither activates an Agent nor produces a recovery error. +The Web bundle mounts this package with the subprocess provider, working-directory service, sandbox policy and Typert Gateway. `remote.terminal` exposes `environment`, `shells`, `list`, `create`, `retain`, `attach`, `rename` and `close`; each operation is scoped by Session identity. Listing reads retained Host terminals directly, so viewing an offline Session neither activates an Agent nor produces a recovery error. Shell discovery lists the execution environment's declared default shell first. Only when the provider omits that default does resolution use `/bin/sh` on POSIX or `cmd.exe` on Windows. An optional `shell` profile overrides that choice with executable `path`, display `name` and `args` (default `[]`). The selector also probes `shellCandidates` through the execution provider and omits confirmed lookup misses. It lists each executable name once, ignoring letter case and `.exe`, and keeps the earliest entry, because PATH lookup can reach the default through another directory, such as `/usr/bin/bash` for `/bin/bash` on merged-`/usr` systems. Creation accepts a discovered `shellPath` and verifies it again; resolution or transport failure is reported without launching a different shell. Environment lookup reads the current directory and limits without filesystem validation or shell resolution, so unavailable directories or default shells do not prevent reattaching to an existing process. Automatic POSIX profiles start interactively, and PowerShell uses `-NoLogo`, so completion and startup configuration remain shell-owned. New terminals validate the current directory through the [working-directory service](../../session/working-directory/README.md) before spawning, including its recovery behavior. Existing terminals keep their process directories. User terminals run with the execution environment’s system-user permissions, independently of the Agent’s sandbox mode and approval policy. Operating-system and container restrictions still apply; DSH does not elevate the user. The subprocess provider retains its credential-environment scrubbing. @@ -36,8 +36,8 @@ Shell discovery lists the execution environment's declared default shell first. | `maxTerminals` | `8` | Retained terminals and pending allocations per Session | | `maxCols`, `maxRows` | `500`, `200` | Maximum PTY dimensions | | `scrollback` | `1000` | Retained screen history rows | -| `maxBufferedBytes` | `2097152` | Output queued for one follower | -| `maxInputBytes` | `65536` | Maximum input request bytes | +| `maxBufferedBytes` | `2097152` | Encoded output per follower and buffered Client input | +| `maxInputBytes` | `65536` | Maximum raw UTF-8 bytes per input command and across unacknowledged Client input | | `disposeGraceMs` | `1000` | Provider termination grace in milliseconds | | `unattendedTimeoutMs` | `7200000` | Continuous confirmed idle time without window holds before cleanup; `0` disables automatic reclamation | | `activityPollIntervalMs` | `30000` | Interval between unattended activity observations | @@ -51,11 +51,13 @@ An open tab in any connected window retains its terminal, including hidden tabs

Implementation internals — click to expand -The Host uses `ctx.subprocess.spawnTerminal` with `TERM=xterm-256color`; it never launches a desktop terminal application. Streaming UTF-8 decoding preserves split characters and leading BOMs, and replaces incomplete trailing bytes at EOF. Unary control uses the Gateway, and `follow` uses its multiplexed Remote stream transport. Headless xterm and its serializer produce each opening screen after all preceding output writes, then monotone output sequences identify subsequent frames. Slow followers fail explicitly; a new attachment restores the current screen. +The Host uses `ctx.subprocess.spawnTerminal` with `TERM=xterm-256color`; it never launches a desktop terminal application. Streaming UTF-8 decoding preserves split characters and leading BOMs, and replaces incomplete trailing bytes at EOF. The duplex `attach` Remote stream carries output and ordered `write`/`resize` commands on the Gateway mux. Each command has a consecutive attachment-local sequence; an `ack` confirms provider acceptance or reports control refusal. Snapshots and state frames carry the receiving attachment's `writable` flag. Headless xterm and its serializer produce each opening screen after all preceding output writes, then monotone output sequences identify subsequent frames. Slow followers fail explicitly; a new attachment restores the current screen. -The latest attachment owns input and resize. Detachment releases input control without killing the process. Explicit close awaits process cleanup and final output; cleanup failure retains the resource for retry. The Session remembers closed identities and rejects their delayed or repeated creation, including creation already in progress when close arrives. A new terminal uses a new identity. Pending allocations remain owned even if cancellation and cleanup both fail. Session owner disposal and controller disposal also terminate owned processes. Changing the Session’s sandbox mode leaves user terminals running with the same permissions. Input or resize refused after control transfer or process exit leaves the output attachment intact and disables input; rejected input is not replayed. +The latest attachment owns input and resize. Detachment releases input control without killing the process. Explicit close awaits process cleanup and final output; cleanup failure retains the resource for retry. The Session remembers closed identities and rejects their delayed or repeated creation, including creation already in progress when close arrives. A new terminal uses a new identity. Pending allocations remain owned even if cancellation and cleanup both fail. Session owner disposal and controller disposal also terminate owned processes. Changing the Session’s sandbox mode leaves user terminals running with the same permissions. Input or resize refused after control transfer or process exit leaves the output attachment intact and disables input; rejected input is not replayed. Provider completion disables input before output drainage finishes, and late input failures cannot discard a gracefully finished follower's final frames. -The Client saves each Session/content-to-terminal association before allocation under its own `dsh.terminal.binding.v1.*` localStorage key. The content identity is globally unique; layout-local tab ids only identify live view occurrences. Independent record writes and deletes preserve other windows' bindings. Restored views reuse that identity; the sidebar terminal provider restores its views before querying unrepresented Host terminals. A new view may create a process, while a recovered view reports a missing target without creating a replacement. Explicit close removes the association after saving its cleanup request. The Host supplies current process metadata and screen contents; neither is saved in the browser. The Client model acknowledges screen writes after the browser emulator processes them, serializes input and ignores stale attachment responses. Client-owned errors carry locale keys. Plugin disposal awaits active and previously detached output streams without closing Host processes. +The opening snapshot advertises the carrier's complete-frame `inputWindow`; in-process carriers without an inbox limit omit it. The Client counts JSON escaping, command fields, and the carrier envelope for both writes and resizes. Commands wait locally while unacknowledged frames fill that window; provider acknowledgements release capacity. `maxInputBytes` bounds raw UTF-8 input, while `maxBufferedBytes` bounds all queued and unacknowledged encoded input frames. A single frame that cannot fit the carrier window, or an exhausted Client buffer, reports `inputFull` and cancels the attachment without replaying queued commands. + +The Client saves each Session/content-to-terminal association before allocation under its own `dsh.terminal.binding.v1.*` localStorage key. The content identity is globally unique; layout-local tab ids only identify live view occurrences. Independent record writes and deletes preserve other windows' bindings. Restored views reuse that identity; the sidebar terminal provider restores its views before querying unrepresented Host terminals. A new view may create a process, while a recovered view reports a missing target without creating a replacement. Explicit close removes the association after saving its cleanup request. The Host supplies current process metadata and screen contents; neither is saved in the browser. The Client model acknowledges screen writes after the browser emulator processes them, pipelines input within its unacknowledged UTF-8 byte budget and ignores stale attachment responses. Reconnection creates a fresh command sequence and never replays unacknowledged input. Provider input failures end the attachment; its process and recovery screen remain available for explicit reconnection. Client-owned errors carry locale keys. Plugin disposal awaits active and previously detached output streams without closing Host processes. The separate `retain(sessionId, id, signal)` Remote stream acknowledges a window hold without Agent activation, screen output, input transfer or process creation. The terminal provider supplies the sidebar's complete open-tab inventory, and the Client intersects it with its own saved identities. Duplicate occurrences share one hold per window; stale associations alone retain nothing. Restored output attachments wait for an acknowledged current hold. Transport cancellation releases exactly that physical generation; plugin disposal joins all hold streams. Failed cleanup retains ownership and retries without reopening admission or restarting the idle grace. diff --git a/packages/api/terminal-controller/README.zh.md b/packages/api/terminal-controller/README.zh.md index 49fc7ab343..220d88190d 100644 --- a/packages/api/terminal-controller/README.zh.md +++ b/packages/api/terminal-controller/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用此包 -Web bundle 将此包与 subprocess provider、working-directory 服务、sandbox policy 和 Typert Gateway 一起挂载。`remote.terminal` 提供 `environment`、`shells`、`list`、`create`、`retain`、`follow`、`write`、`resize`、`rename` 和 `close`;每个操作均按 Session 标识限定范围。列表直接读取 Host 保留的终端,因此查看离线 Session 不会激活 Agent,也不会产生恢复错误。 +Web bundle 将此包与 subprocess provider、working-directory 服务、sandbox policy 和 Typert Gateway 一起挂载。`remote.terminal` 提供 `environment`、`shells`、`list`、`create`、`retain`、`attach`、`rename` 和 `close`;每个操作均按 Session 标识限定范围。列表直接读取 Host 保留的终端,因此查看离线 Session 不会激活 Agent,也不会产生恢复错误。 Shell 探测结果首先列出执行环境声明的默认 shell。仅当 provider 未声明默认值时,才在 POSIX 使用 `/bin/sh`,在 Windows 使用 `cmd.exe`。可选的 `shell` profile 通过可执行路径 `path`、显示名称 `name` 和参数 `args`(默认 `[]`)覆盖这一选择。选择器还会通过执行 provider 探测 `shellCandidates`,并省略确定未找到的候选。同一可执行文件名(不区分大小写,忽略 `.exe`)只列出最早的一项,因为 PATH 查找可能经由其他目录找到默认 shell,例如 merged-`/usr` 系统上 `/bin/bash` 对应的 `/usr/bin/bash`。创建请求接受探测返回的 `shellPath` 并再次验证;解析或传输失败会直接报告,不启动其他 shell。环境查询读取当前目录和限制,不校验文件系统或解析 shell,因此目录或默认 shell 不可用时仍可重新连接已有进程。POSIX 自动 profile 以交互模式启动,PowerShell 使用 `-NoLogo`,补全和启动配置仍由 shell 提供。新终端启动前通过[工作目录服务](../../session/working-directory/README.zh.md)校验当前目录,并采用该服务的恢复行为。已有终端保留其进程目录。用户终端使用执行环境中系统用户的权限,独立于 Agent 的沙箱模式和审批策略。操作系统和容器的限制仍然生效;DSH 不提升用户权限。Subprocess provider 继续清除环境中的凭据变量。 @@ -36,8 +36,8 @@ Shell 探测结果首先列出执行环境声明的默认 shell。仅当 provide | `maxTerminals` | `8` | 每个 Session 保留的终端和创建请求上限 | | `maxCols`、`maxRows` | `500`、`200` | PTY 最大尺寸 | | `scrollback` | `1000` | 屏幕历史行数 | -| `maxBufferedBytes` | `2097152` | 单个订阅者的输出排队上限 | -| `maxInputBytes` | `65536` | 单次输入请求的字节上限 | +| `maxBufferedBytes` | `2097152` | 单个订阅者输出及 Client 输入帧的缓存上限 | +| `maxInputBytes` | `65536` | 每条输入命令及 Client 未确认输入总量的原始 UTF-8 字节上限 | | `disposeGraceMs` | `1000` | provider 终止宽限期,单位毫秒 | | `unattendedTimeoutMs` | `7200000` | 无窗口持有且持续确认空闲后开始清理的时长;`0` 禁用自动回收 | | `activityPollIntervalMs` | `30000` | 无窗口持有时的活动观察间隔 | @@ -51,11 +51,13 @@ Shell 探测结果首先列出执行环境声明的默认 shell。仅当 provide
实现细节 -Host 通过 `ctx.subprocess.spawnTerminal` 创建 `TERM=xterm-256color` 的终端,不启动桌面终端应用。流式 UTF-8 解码保留跨块字符和开头的 BOM,并在 EOF 将不完整的尾部字节替换为替代字符。控制请求走 Gateway,`follow` 使用其复用的 Remote stream。Headless xterm 和序列化 addon 在此前输出写入后生成初始屏幕,后续增量携带单调序号。过慢的订阅者明确失败;重新连接恢复当前屏幕。 +Host 通过 `ctx.subprocess.spawnTerminal` 创建 `TERM=xterm-256color` 的终端,不启动桌面终端应用。流式 UTF-8 解码保留跨块字符和开头的 BOM,并在 EOF 将不完整的尾部字节替换为替代字符。双工 `attach` Remote 流通过 Gateway mux 传输输出和有序的 `write`/`resize` 命令。每条命令使用附件内连续递增的序号;`ack` 确认提供者已接受操作,或报告控制权拒绝。快照和状态帧携带接收附件的 `writable` 标记。Headless xterm 和序列化 addon 在此前输出写入后生成初始屏幕,后续增量携带单调序号。过慢的订阅者明确失败;重新连接恢复当前屏幕。 -最新连接持有输入和尺寸控制权。断开连接只释放输入权,不结束进程。显式关闭等待进程清理和最后输出;清理失败时保留资源以便重试。Session 记住已关闭的标识并拒绝迟到或重复的创建请求,包括关闭到达时仍在进行的创建。新终端使用新标识。取消创建且清理失败时,已分配的进程仍有所有者。Session owner 和 controller 卸载也会终止所拥有的进程。改变 Session 的沙箱模式时,用户终端继续以原有权限运行。控制权转移或进程退出后被拒绝的输入和尺寸请求保留输出连接并禁用输入,不重发被拒绝的输入。 +最新连接持有输入和尺寸控制权。断开连接只释放输入权,不结束进程。显式关闭等待进程清理和最后输出;清理失败时保留资源以便重试。Session 记住已关闭的标识并拒绝迟到或重复的创建请求,包括关闭到达时仍在进行的创建。新终端使用新标识。取消创建且清理失败时,已分配的进程仍有所有者。Session owner 和 controller 卸载也会终止所拥有的进程。改变 Session 的沙箱模式时,用户终端继续以原有权限运行。控制权转移或进程退出后被拒绝的输入和尺寸请求保留输出连接并禁用输入,不重发被拒绝的输入。提供者完成时即禁用输入,无须等待输出排空;迟到的输入失败不能丢弃已正常结束的订阅者所保留的尾部帧。 -Client 在分配前将每条 Session/内容与终端身份的关联保存到独立的 localStorage key `dsh.terminal.binding.v1.*`。内容身份全局唯一;布局内的 tab id 只标识活动视图 occurrence。逐条记录的写入和删除会保留其他窗口的关联。恢复视图复用该身份;侧栏 terminal provider 先恢复自己的视图,再查询尚无视图的 Host 终端。新视图可以创建进程,恢复视图在目标缺失时显示错误,不创建替代进程。显式关闭先保存清理请求,再删除关联。当前进程元数据和屏幕内容由 Host 提供,不保存在浏览器中。Client 模型在浏览器完成屏幕解析后确认帧,按序发送输入,并忽略旧连接迟到的响应。Client 自产错误携带本地化键。插件卸载等待活跃及先前断开的输出流结束,不关闭 Host 进程。 +初始快照公布载体的完整帧 `inputWindow`;没有 inbox 限额的进程内载体省略该字段。Client 对输入和尺寸调整都计入 JSON 转义、命令字段及载体封装的开销。未确认帧占满窗口时,命令在本地等待;提供者确认后释放额度。`maxInputBytes` 限制原始 UTF-8 输入,`maxBufferedBytes` 限制全部排队及未确认的编码输入帧。单帧无法容纳于载体窗口或 Client 缓存耗尽时,报告 `inputFull` 并取消附件,不重放排队命令。 + +Client 在分配前将每条 Session/内容与终端身份的关联保存到独立的 localStorage key `dsh.terminal.binding.v1.*`。内容身份全局唯一;布局内的 tab id 只标识活动视图 occurrence。逐条记录的写入和删除会保留其他窗口的关联。恢复视图复用该身份;侧栏 terminal provider 先恢复自己的视图,再查询尚无视图的 Host 终端。新视图可以创建进程,恢复视图在目标缺失时显示错误,不创建替代进程。显式关闭先保存清理请求,再删除关联。当前进程元数据和屏幕内容由 Host 提供,不保存在浏览器中。Client 模型在浏览器完成屏幕解析后确认帧,在未确认 UTF-8 字节预算内连续发送输入,并忽略旧连接迟到的响应。重连建立新的命令序列,绝不重放未确认输入。提供者输入失败会结束附件;进程和恢复屏幕仍可供显式重连使用。Client 自产错误携带本地化键。插件卸载等待活跃及先前断开的输出流结束,不关闭 Host 进程。 独立的 `retain(sessionId, id, signal)` Remote 流确认窗口持有关系,不激活 Agent、发送屏幕输出、转移输入权或创建进程。终端 provider 提供侧栏的完整打开标签清单,Client 将其与自己保存的身份取交集。同一窗口中的重复 occurrence 共用一个持有流;孤立的旧关联不会保活任何终端。恢复输出连接前必须等待当前持有关系确认。传输取消只释放对应的物理流代次;插件卸载等待全部持有流结束。清理失败时保留所有权并重试,不重新接受连接,也不重新计算空闲宽限期。 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 a03a3035c7..e6e99a8805 100644 --- a/packages/api/terminal-controller/package.json +++ b/packages/api/terminal-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-terminal-controller", "description": "Session-owned interactive terminals with shell discovery, screen recovery and typed Remote control", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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": { @@ -57,10 +58,11 @@ "@deepseek-ai/dsh-deque": "workspace:*", "@deepseek-ai/dsh-lazy-require": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "@xterm/headless": "^6.0.0", "@xterm/addon-serialize": "^0.14.0", - "zod": "^4.4.3" + "@xterm/headless": "^6.0.0", + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/dsh-subprocess": "workspace:*", @@ -84,6 +86,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/src/client/model.ts b/packages/api/terminal-controller/src/client/model.ts index 64bea4906e..d143e9c57a 100644 --- a/packages/api/terminal-controller/src/client/model.ts +++ b/packages/api/terminal-controller/src/client/model.ts @@ -1,13 +1,13 @@ /** React-free browser terminal state and reconnecting Remote-stream ownership. */ import { preferredShell, rememberShell } from './shell-preference.ts' -import { randomUUID } from '@deepseek-ai/dsh-util-crypto' import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import { Deque } from '@deepseek-ai/dsh-deque' import { RemoteStreamCarrierError, type ClientRemote, type RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' -import { RemoteError, remoteErrorOf, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { RemoteError, remoteErrorOf, type RemoteResult, type RemoteStreamHandle, type RemoteUplinkWindow } from '@deepseek-ai/dsh-typert-protocol' import type {} from '@deepseek-ai/dsh-api-terminal-controller/remote' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { - TerminalAttachmentId, TerminalEnvironment, TerminalFrame, + TerminalInput, TerminalEnvironment, TerminalFrame, WebTerminalId, WebTerminalInfo, } from '../types.ts' @@ -46,6 +46,24 @@ export interface TerminalViewState { readonly issue?: TerminalViewIssue | undefined } +interface InputCost { + readonly inputBytes: number + readonly frameBytes: number +} + +interface TerminalInputAttachment { + readonly handle: RemoteStreamHandle + readonly signal: AbortSignal + sequence: number + acknowledged: number + readonly pending: Map + readonly queued: Deque + window: RemoteUplinkWindow | undefined + bytes: number + bufferedBytes: number + inFlightBytes: number +} + /** A view survives DOM unmount; its process only ends on explicit close. */ export class TerminalView { /** Observable controls, process metadata and the next screen update awaiting acknowledgement. */ @@ -53,14 +71,12 @@ export class TerminalView { private readonly lifetime = new AbortController() private stream: RemoteStream | undefined private mounted = false - private attachmentId: TerminalAttachmentId | undefined + private attachment: TerminalInputAttachment | undefined private pendingRender: { revision: number; resolve: () => void } | undefined private revision = 0 private creation: Promise | undefined private loading: Promise | undefined private closing: Promise | undefined - private writes: Promise = Promise.resolve() - private queuedInput = 0 private readonly detaching = new Set>() /** @@ -164,9 +180,20 @@ export class TerminalView { open: async function* (this: TerminalView, signal: AbortSignal) { await this.retain?.(signal) signal.throwIfAborted() - const attachmentId = randomUUID() as TerminalAttachmentId - this.attachmentId = attachmentId - yield* this.remote.follow(this.sessionId, info.id, attachmentId, signal) + const handle = this.remote.attach(this.sessionId, info.id, signal) + const attachment: TerminalInputAttachment = { + handle, signal, sequence: 0, acknowledged: 0, + pending: new Map(), queued: new Deque(), window: undefined, + bytes: 0, bufferedBytes: 0, inFlightBytes: 0, + } + this.attachment = attachment + try { + for await (const frame of handle) { + if (frame.type === 'snapshot') attachment.window = frame.inputWindow + yield frame + } + } + finally { if (this.attachment === attachment) this.attachment = undefined } }.bind(this), ended: () => new TerminalViewError('attachmentEnded'), carrierFailed: () => { if (this.stream === stream) this.patch({ phase: 'disconnected', writable: false }) }, @@ -187,40 +214,66 @@ export class TerminalView { } /** - * Serialize raw input so concurrent RPC requests cannot reorder keystrokes. - * @param data - input from the terminal emulator. + * Queue input within the raw UTF-8 and encoded-frame budgets, waiting for carrier capacity. + * @param data - input from the terminal emulator; never replayed after disconnection. */ write(data: string): void { const state = this.state.getSnapshot() - const attachmentId = this.attachmentId - if (!state.writable || state.info === undefined || attachmentId === undefined) return + const attachment = this.attachment + if (!state.writable || state.info === undefined || attachment === undefined || attachment.signal.aborted) return + if (data.length === 0) return const bytes = new TextEncoder().encode(data).byteLength - if (this.queuedInput + bytes > (state.environment?.maxInputBytes ?? 0)) { this.fail(new TerminalViewError('inputFull')); return } - this.queuedInput += bytes - const id = state.info.id - this.writes = this.writes.then(async () => { - if (this.attachmentId !== attachmentId || !this.state.getSnapshot().writable) return - valueOf(await this.remote.write(this.sessionId, id, attachmentId, data)) - }).catch((error: unknown) => { if (this.attachmentId === attachmentId) this.fail(error) }).finally(() => { this.queuedInput -= bytes }) + if (attachment.bytes + bytes > (state.environment?.maxInputBytes ?? 0)) { this.failInput(new TerminalViewError('inputFull')); return } + this.send(attachment, { type: 'write', sequence: attachment.sequence + 1, data }, bytes) } /** - * Resize only from the currently writable view. + * Resize only from the currently writable view, ordered with keyboard input. * @param cols - measured column count. * @param rows - measured row count. */ resize(cols: number, rows: number): void { const state = this.state.getSnapshot() - const attachmentId = this.attachmentId - if (!state.writable || state.info === undefined || attachmentId === undefined) return + const attachment = this.attachment + if (!state.writable || state.info === undefined || attachment === undefined || attachment.signal.aborted) return if (state.info.cols === cols && state.info.rows === rows) return - const id = state.info.id cols = Math.min(cols, state.environment?.maxCols ?? cols) rows = Math.min(rows, state.environment?.maxRows ?? rows) - this.writes = this.writes.then(async () => { - if (this.attachmentId !== attachmentId || !this.state.getSnapshot().writable) return - valueOf(await this.remote.resize(this.sessionId, id, attachmentId, cols, rows)) - }).catch((error: unknown) => { if (this.attachmentId === attachmentId) this.fail(error) }) + this.send(attachment, { type: 'resize', sequence: attachment.sequence + 1, cols, rows }, 0) + } + + private send(attachment: TerminalInputAttachment, command: TerminalInput, bytes: number): void { + const frameBytes = new TextEncoder().encode(JSON.stringify(command)).byteLength + (attachment.window?.frameOverheadBytes ?? 0) + if (attachment.bufferedBytes + frameBytes > (this.state.getSnapshot().environment?.maxBufferedBytes ?? 0) + || (attachment.window !== undefined && frameBytes > attachment.window.maxBytes)) { + this.failInput(new TerminalViewError('inputFull')) + return + } + attachment.queued.pushBack({ command, inputBytes: bytes, frameBytes }) + attachment.sequence = command.sequence + attachment.bytes += bytes + attachment.bufferedBytes += frameBytes + this.flushInput(attachment) + } + + private flushInput(attachment: TerminalInputAttachment): void { + while (this.attachment === attachment && !attachment.signal.aborted && this.state.getSnapshot().writable) { + const next = attachment.queued.popFront() + if (next === undefined) return + if (attachment.window !== undefined && attachment.inFlightBytes + next.frameBytes > attachment.window.maxBytes) { + attachment.queued.pushFront(next) + return + } + try { attachment.handle.send(next.command) } + catch (error) { this.failInput(error); return } + attachment.pending.set(next.command.sequence, { inputBytes: next.inputBytes, frameBytes: next.frameBytes }) + attachment.inFlightBytes += next.frameBytes + } + } + + private failInput(error: unknown): void { + this.fail(error) + this.detach() } /** @@ -269,7 +322,7 @@ export class TerminalView { private detach(): void { const previous = this.stream this.stream = undefined - this.attachmentId = undefined + this.attachment = undefined this.pendingRender?.resolve() this.pendingRender = undefined if (previous !== undefined) { @@ -294,8 +347,23 @@ export class TerminalView { if (frame.sequence !== sequence + 1) throw new TerminalViewError('invalidOutput', 'Terminal output sequence has a gap') sequence = frame.sequence } else if (frame.type === 'snapshot') throw new TerminalViewError('invalidOutput', 'Unexpected terminal screen snapshot') + if (frame.type === 'ack') { + const attachment = this.attachment + /* v8 ignore next -- the physical opener retains its handle until this consumer advances. */ + if (attachment === undefined) throw new TerminalViewError('invalidOutput', 'Terminal acknowledgement has no attachment') + const pending = attachment.pending.get(frame.sequence) + if (frame.sequence !== attachment.acknowledged + 1 || pending === undefined) throw new TerminalViewError('invalidOutput', 'Terminal input acknowledgement is out of order') + attachment.acknowledged = frame.sequence + attachment.bytes -= pending.inputBytes + attachment.bufferedBytes -= pending.frameBytes + attachment.inFlightBytes -= pending.frameBytes + attachment.pending.delete(frame.sequence) + if (frame.refusal !== undefined) this.patch({ writable: false }) + this.flushInput(attachment) + continue + } if (frame.type !== 'output') { - this.patch({ info: frame.info, title: frame.info.title, phase: 'connected', writable: frame.info.state === 'running' && frame.info.controllerId === this.attachmentId }) + this.patch({ info: frame.info, title: frame.info.title, phase: 'connected', writable: frame.info.state === 'running' && frame.writable }) } if (frame.type !== 'state') { const revision = ++this.revision @@ -324,10 +392,6 @@ export class TerminalView { private fail(error: unknown): void { const failure = remoteErrorOf(error) - if (failure?.code === 'terminal/control-unavailable') { - this.patch({ writable: false, error: undefined, issue: undefined }) - return - } const issue = failure?.code === 'terminal/view' ? failure.details.issue : failure?.code === 'terminal/limit-reached' ? 'terminalLimit' : failure?.code === 'terminal/unavailable' ? 'missingTerminal' : undefined this.patch({ phase: error instanceof RemoteStreamCarrierError ? 'disconnected' : 'failed', writable: false, issue, error: error instanceof Error ? error.message : String(error) }) } diff --git a/packages/api/terminal-controller/src/index.ts b/packages/api/terminal-controller/src/index.ts index 953c34a9fc..75f454d77d 100644 --- a/packages/api/terminal-controller/src/index.ts +++ b/packages/api/terminal-controller/src/index.ts @@ -5,12 +5,12 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type { SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-sandbox-policy' import type {} from '@deepseek-ai/dsh-working-directory' -import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import { Remote, RemoteError, TypertRemoteService, type RemoteStream } from '@deepseek-ai/dsh-typert-protocol' import { discoverShells, resolveShell } from './shells.ts' import { BrowserTerminal } from './terminal.ts' import { TerminalRetention } from './retention.ts' import type { - TerminalShell, TerminalAttachmentId, TerminalCreateRequest, TerminalEnvironment, TerminalFrame, TerminalRetentionFrame, + TerminalShell, TerminalInput, TerminalCreateRequest, TerminalEnvironment, TerminalFrame, TerminalRetentionFrame, WebTerminalId, WebTerminalInfo, } from './types.ts' @@ -44,9 +44,9 @@ export interface Config { readonly maxRows: number /** Screen history rows retained for reconnecting clients. */ readonly scrollback: number - /** Maximum queued UTF-8 frame bytes per output follower before disconnection. */ + /** Maximum queued UTF-8 frame bytes per output follower and in the Client input buffer. */ readonly maxBufferedBytes: number - /** Maximum UTF-8 bytes in one input request. */ + /** Maximum raw UTF-8 bytes per input command and across unacknowledged Client input. */ readonly maxInputBytes: number /** Provider process-termination grace period in milliseconds. */ readonly disposeGraceMs: number @@ -120,7 +120,7 @@ export class TerminalController extends TypertRemoteService { signal.throwIfAborted() const { workingDirectory } = this.execution(agent) return { cwd: workingDirectory.get(agent.session), - maxInputBytes: this.config.maxInputBytes, maxCols: this.config.maxCols, + maxInputBytes: this.config.maxInputBytes, maxBufferedBytes: this.config.maxBufferedBytes, maxCols: this.config.maxCols, maxRows: this.config.maxRows, scrollback: this.config.scrollback } } @@ -206,46 +206,17 @@ export class TerminalController extends TypertRemoteService { } /** - * Attach to a terminal without binding its process lifetime to the transport. + * Attach terminal input and output to one physical Remote stream. * @param agent - Session owner supplied by the Gateway. * @param id - terminal identity. - * @param attachmentId - new exclusive input attachment. - * @param signal - physical stream cancellation. - * @returns screen recovery followed by output and metadata changes. + * @param signal - attachment cancellation; the process remains alive and input is never replayed. + * @returns screen recovery, output, writable state and provider-acceptance acknowledgements. */ @Remote({ mode: 'stream' }) - follow(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, signal: AbortSignal): AsyncIterable { - if (!/^[\w-]{1,128}$/u.test(attachmentId)) throw new Error('Invalid terminal attachment identity') - return this.terminal(agent, id).follow(attachmentId, signal) - } - - /** - * Deliver raw input, including Tab completion and control characters. - * @param agent - Session owner supplied by the Gateway. - * @param id - terminal identity. - * @param attachmentId - current writable attachment. - * @param data - input bytes represented as UTF-8 text. - * @returns after provider input acceptance. - */ - @Remote - async write(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, data: string): Promise { - if (Buffer.byteLength(data, 'utf8') > this.config.maxInputBytes) throw new Error('Terminal input exceeds the configured limit') - await this.terminal(agent, id).write(attachmentId, data) - } - - /** - * Update the dimensions of the PTY and recovery screen. - * @param agent - Session owner supplied by the Gateway. - * @param id - terminal identity. - * @param attachmentId - current writable attachment. - * @param cols - column count. - * @param rows - row count. - * @returns after the resize completes. - */ - @Remote - async resize(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, cols: number, rows: number): Promise { - this.dimensions(cols, rows) - await this.terminal(agent, id).resize(attachmentId, cols, rows) + attach(agent: Agent, id: WebTerminalId, signal: AbortSignal): RemoteStream { + const invocation = this.ctx.invocation + if (invocation === undefined) throw new Error('Terminal attachment requires a Remote invocation') + return this.terminal(agent, id).attach(invocation.uplink(), this.config, signal, invocation.uplinkWindow) } /** diff --git a/packages/api/terminal-controller/src/stream.ts b/packages/api/terminal-controller/src/stream.ts index 4ee89f254f..d3b33dc922 100644 --- a/packages/api/terminal-controller/src/stream.ts +++ b/packages/api/terminal-controller/src/stream.ts @@ -11,6 +11,9 @@ export class TerminalFollower { private finished = false private failure: Error | undefined + /** Whether this attachment still accepts input and output. */ + get active(): boolean { return !this.closed && !this.finished } + /** @param maxBytes - maximum queued UTF-8 bytes for this follower. */ constructor(private readonly maxBytes: number) {} @@ -22,8 +25,7 @@ export class TerminalFollower { if (this.closed || this.finished) return const bytes = Buffer.byteLength(JSON.stringify(frame), 'utf8') if (this.bytes + bytes > this.maxBytes) { - this.failure = new Error('Terminal output consumer exceeded its buffer; reconnect to recover the current screen') - this.close() + this.fail(new Error('Terminal output consumer exceeded its buffer; reconnect to recover the current screen')) return } this.queue.pushBack({ frame, bytes }) @@ -31,6 +33,16 @@ export class TerminalFollower { this.wake?.() } + /** + * Fail this attachment without stopping its terminal; failures after finish or close are ignored. + * @param error - input or output failure reported to the attached consumer. + */ + fail(error: Error): void { + if (!this.active) return + this.failure = error + this.close() + } + /** Finish after delivering every queued frame, including the final exit state. */ finish(): void { this.finished = true diff --git a/packages/api/terminal-controller/src/terminal.ts b/packages/api/terminal-controller/src/terminal.ts index b4f6623037..7268092b97 100644 --- a/packages/api/terminal-controller/src/terminal.ts +++ b/packages/api/terminal-controller/src/terminal.ts @@ -1,12 +1,13 @@ /** One PTY, a bounded terminal emulator and its detachable browser followers. */ -import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import { RemoteError, remoteErrorOf, type RemoteUplinkWindow } from '@deepseek-ai/dsh-typert-protocol' import type { Terminal as HeadlessTerminal } from '@xterm/headless' import type { SerializeAddon as Serializer } from '@xterm/addon-serialize' import type { SubprocessTerminalHandle } from '@deepseek-ai/dsh-subprocess' import { createLazyRequire } from '@deepseek-ai/dsh-lazy-require' import { TerminalFollower } from './stream.ts' import { TerminalRetention, type TerminalRetentionPolicy } from './retention.ts' -import type { TerminalAttachmentId, TerminalFrame, TerminalRetentionFrame, WebTerminalInfo } from './types.ts' +import type { TerminalEnvironment, TerminalInput, TerminalFrame, TerminalRetentionFrame, WebTerminalInfo } from './types.ts' const requireHeadless = createLazyRequire('@xterm/headless', import.meta.url) const requireSerialize = createLazyRequire('@xterm/addon-serialize', import.meta.url) @@ -19,9 +20,11 @@ export class BrowserTerminal { private sequence = 0 private operations: Promise = Promise.resolve() private readonly drained: Promise + /** Provider completion precedes output drainage and the published exit state. */ + private exited = false private closing: Promise | undefined private retention: TerminalRetention | undefined - private controller: { id: TerminalAttachmentId; follower: TerminalFollower } | undefined + private controller: TerminalFollower | undefined /** * @param handle - allocated terminal process range. @@ -69,64 +72,91 @@ export class BrowserTerminal { } /** - * Attach with exclusive input control; an older attachment becomes read-only. - * @param id - browser attachment identity. + * Attach with exclusive input control; older attachments keep receiving output. + * @param input - Gateway-decoded commands; returning its iterator must interrupt pending reads. + * @param limits - input byte and PTY dimension limits validated at the Remote boundary. * @param signal - attachment cancellation; never terminates the process. - * @returns a consistent screen followed by ordered output and state changes. + * @param inputWindow - carrier frame capacity; absent for a carrier without an encoded-frame inbox limit. + * @returns a screen baseline, output, per-attachment state and ordered command acknowledgements. */ - async *follow(id: TerminalAttachmentId, signal: AbortSignal): AsyncIterable { + async *attach(input: AsyncIterable, limits: Pick, signal: AbortSignal, inputWindow?: RemoteUplinkWindow): AsyncIterable { signal.throwIfAborted() const follower = new TerminalFollower(this.maxBufferedBytes) const baseline = await this.enqueue(() => { signal.throwIfAborted() - this.controller = { id, follower } - this.info = { ...this.info, controllerId: id } - this.broadcast({ type: 'state', info: this.info }) - const snapshot: TerminalFrame = { type: 'snapshot', sequence: this.sequence, screen: this.serializer.serialize(), info: this.info } + this.controller = follower + this.broadcastState() + const snapshot: TerminalFrame = { type: 'snapshot', sequence: this.sequence, screen: this.serializer.serialize(), info: this.info, writable: this.writable(follower), ...inputWindow === undefined ? {} : { inputWindow } } this.followers.add(follower) return snapshot }) + const uplink = input[Symbol.asyncIterator]() + const commands = this.consumeInput(uplink, follower, limits, signal).catch((error: unknown) => { + follower.fail(error instanceof Error ? error : new Error(String(error))) + }) try { yield baseline yield* follower.read(signal) } finally { this.followers.delete(follower) follower.close() - if (this.controller?.follower === follower) { + if (this.controller === follower) { this.controller = undefined - const { controllerId: _controllerId, ...info } = this.info - this.info = info - this.broadcast({ type: 'state', info }) + this.broadcastState() + } + // Gateway's uplink return wakes pending reads before attachment cleanup joins the input pump. + await uplink.return?.() + await commands + } + } + + private async consumeInput(input: AsyncIterator, follower: TerminalFollower, limits: Pick, signal: AbortSignal): Promise { + let sequence = 0 + while (true) { + const next = await input.next() + if (next.done === true || signal.aborted || !follower.active) return + const command = next.value + if (!Number.isSafeInteger(command.sequence) || command.sequence !== ++sequence) throw new Error('Terminal input sequence has a gap') + try { + await this.enqueue(async () => { + signal.throwIfAborted() + this.requireController(follower) + switch (command.type) { + case 'write': + if (Buffer.byteLength(command.data, 'utf8') > limits.maxInputBytes) throw new Error('Terminal input exceeds the configured limit') + this.retention?.invalidate() + await this.handle.write(command.data) + break + case 'resize': + if (!Number.isSafeInteger(command.cols) || command.cols < 2 || command.cols > limits.maxCols + || !Number.isSafeInteger(command.rows) || command.rows < 1 || command.rows > limits.maxRows) throw new Error('Terminal dimensions exceed the configured limits') + await this.handle.resize(command.cols, command.rows) + this.screen.resize(command.cols, command.rows) + this.info = { ...this.info, cols: command.cols, rows: command.rows } + this.broadcastState() + break + /* v8 ignore next -- the Gateway codec validates this closed union. */ + default: assertNever(command) + } + }) + follower.push({ type: 'ack', sequence }) + } catch (error) { + const failure = remoteErrorOf(error) + if (failure?.code === 'terminal/control-unavailable') { + follower.push({ type: 'ack', sequence, refusal: failure.details.reason }) + } else if (this.exited) { + follower.push({ type: 'ack', sequence, refusal: 'not-running' }) + } else throw error } } } - /** - * Send raw terminal input without command interpretation. - * @param id - current writable attachment. - * @param data - UTF-8 input, including shell completion/control keys. - * @returns when the provider accepts the input. - */ - write(id: TerminalAttachmentId, data: string): Promise { - this.retention?.invalidate() - return this.enqueue(async () => { this.requireController(id); await this.handle.write(data) }) + private writable(follower: TerminalFollower): boolean { + return !this.exited && this.closing === undefined && this.info.state === 'running' && this.controller === follower } - /** - * Resize the PTY and recovery screen in the same operation order as output. - * @param id - current writable attachment. - * @param cols - validated column count. - * @param rows - validated row count. - * @returns when the provider and emulator use the new dimensions. - */ - resize(id: TerminalAttachmentId, cols: number, rows: number): Promise { - return this.enqueue(async () => { - this.requireController(id) - await this.handle.resize(cols, rows) - this.screen.resize(cols, rows) - this.info = { ...this.info, cols, rows } - this.broadcast({ type: 'state', info: this.info }) - }) + private broadcastState(): void { + for (const follower of this.followers) follower.push({ type: 'state', info: this.info, writable: this.writable(follower) }) } /** @@ -135,7 +165,7 @@ export class BrowserTerminal { */ rename(title: string): void { this.info = { ...this.info, title } - this.broadcast({ type: 'state', info: this.info }) + this.broadcastState() } /** @@ -164,9 +194,9 @@ export class BrowserTerminal { return this.closing } - private requireController(id: TerminalAttachmentId): void { - if (this.closing !== undefined || this.info.state !== 'running') throw new RemoteError('terminal/control-unavailable', 'Terminal is not running', { reason: 'not-running' }) - if (this.controller?.id !== id) throw new RemoteError('terminal/control-unavailable', 'Terminal input is controlled by another attachment', { reason: 'read-only' }) + private requireController(follower: TerminalFollower): void { + if (this.exited || this.closing !== undefined || this.info.state !== 'running') throw new RemoteError('terminal/control-unavailable', 'Terminal is not running', { reason: 'not-running' }) + if (this.controller !== follower || !follower.active) throw new RemoteError('terminal/control-unavailable', 'Terminal input is controlled by another attachment', { reason: 'read-only' }) } private broadcast(frame: TerminalFrame): void { @@ -181,7 +211,7 @@ export class BrowserTerminal { private async consume(): Promise { const decoder = new TextDecoder('utf-8', { ignoreBOM: true }) - const outcome = this.handle.done.then(value => ({ value }), (error: unknown) => ({ error })) + const outcome = this.handle.done.then((value) => { this.exited = true; return { value } }, (error: unknown) => ({ error })) try { for await (const chunk of this.handle.output) { // Node Readable's iterator is untyped; this provider explicitly emits Buffer chunks. @@ -195,7 +225,7 @@ export class BrowserTerminal { } catch (error) { this.info = { ...this.info, state: 'failed', error: error instanceof Error ? error.message : String(error) } } - this.broadcast({ type: 'state', info: this.info }) + this.broadcastState() } private async output(data: string): Promise { diff --git a/packages/api/terminal-controller/src/types.ts b/packages/api/terminal-controller/src/types.ts index 8490ea1a7f..7c0eba8ff2 100644 --- a/packages/api/terminal-controller/src/types.ts +++ b/packages/api/terminal-controller/src/types.ts @@ -1,6 +1,6 @@ /** Browser terminal identities, metadata and screen-stream frames. */ import type { Branded } from '@deepseek-ai/dsh-brand' -import type {} from '@deepseek-ai/dsh-typert-protocol' +import type { RemoteUplinkWindow } from '@deepseek-ai/dsh-typert-protocol' declare module '@deepseek-ai/dsh-typert-protocol' { interface RemoteErrorDetailsMap { @@ -15,8 +15,6 @@ declare module '@deepseek-ai/dsh-typert-protocol' { /** A terminal identity scoped to one Session and one Host lifetime. */ export type WebTerminalId = Branded<'WebTerminalId'> -/** An attachment allowed to write and resize one terminal. */ -export type TerminalAttachmentId = Branded<'TerminalAttachmentId'> /** Acknowledges one physical window hold without taking screen or input control. */ export interface TerminalRetentionFrame { @@ -35,6 +33,8 @@ export interface TerminalEnvironment { /** Logged current directory, read without filesystem validation. */ readonly cwd: string readonly maxInputBytes: number + /** Maximum complete encoded Client input bytes retained until acknowledgement. */ + readonly maxBufferedBytes: number readonly maxCols: number readonly maxRows: number readonly scrollback: number @@ -52,7 +52,6 @@ export interface WebTerminalInfo { readonly state: 'running' | 'exited' | 'failed' readonly exitCode: number | null readonly error?: string - readonly controllerId?: TerminalAttachmentId } /** Create is idempotent for an open identity; closed identities cannot be recreated. */ @@ -64,8 +63,17 @@ export interface TerminalCreateRequest { readonly rows: number } -/** Every attachment begins with a complete bounded screen, then ordered output. */ +/** Commands are numbered consecutively from one within each attachment; acknowledgements never authorize replay. */ +export type TerminalInput = + | { readonly type: 'write'; readonly sequence: number; readonly data: string } + | { readonly type: 'resize'; readonly sequence: number; readonly cols: number; readonly rows: number } + +/** + * Every attachment begins with a complete bounded screen, then ordered output. + * inputWindow is absent when the carrier has no encoded-frame inbox limit. + */ export type TerminalFrame = - | { readonly type: 'snapshot'; readonly sequence: number; readonly screen: string; readonly info: WebTerminalInfo } + | { readonly type: 'snapshot'; readonly sequence: number; readonly screen: string; readonly info: WebTerminalInfo; readonly writable: boolean; readonly inputWindow?: RemoteUplinkWindow } | { readonly type: 'output'; readonly sequence: number; readonly data: string } - | { readonly type: 'state'; readonly info: WebTerminalInfo } + | { readonly type: 'state'; readonly info: WebTerminalInfo; readonly writable: boolean } + | { readonly type: 'ack'; readonly sequence: number; readonly refusal?: 'read-only' | 'not-running' } diff --git a/packages/api/terminal-controller/tests/controller.spec.ts b/packages/api/terminal-controller/tests/controller.spec.ts index d9f7ee273f..dd86c0be82 100644 --- a/packages/api/terminal-controller/tests/controller.spec.ts +++ b/packages/api/terminal-controller/tests/controller.spec.ts @@ -11,8 +11,10 @@ import { SubprocessExecutableNotFoundError, type SubprocessRuntime, type Subproc import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import { afterEach, describe, expect, it, vi } from 'vitest' import { TerminalController, type Config } from '../src/index.ts' +import { inputChannel } from './input.ts' +import type { RemoteInvocation, PeerId } from '@deepseek-ai/dsh-typert-protocol' import { resolveShell } from '../src/shells.ts' -import type { TerminalAttachmentId, WebTerminalId } from '../src/types.ts' +import type { TerminalInput, WebTerminalId } from '../src/types.ts' const roots: Context[] = [] afterEach(async () => { await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) }) @@ -70,7 +72,7 @@ describe('TerminalController', () => { it('creates the environment default shell and keeps an existing identity when that default changes', async () => { const { controller, agent, subprocess } = fixture({ shell: undefined }) subprocess.terminalEnvironment.mockResolvedValue({ platform: 'posix', defaultShell: '/usr/local/bin/zsh' }) - expect(controller.environment(agent, signal())).toEqual({ cwd: '/workspace', maxCols: 200, maxRows: 100, maxInputBytes: 1000, scrollback: 100 }) + expect(controller.environment(agent, signal())).toEqual({ cwd: '/workspace', maxCols: 200, maxRows: 100, maxInputBytes: 1000, maxBufferedBytes: 100_000, scrollback: 100 }) expect(subprocess.terminalEnvironment).not.toHaveBeenCalled() const created = await controller.create(agent, request, signal()) expect(created.shell.path).toBe('/usr/local/bin/zsh') @@ -87,7 +89,7 @@ describe('TerminalController', () => { subprocess.resolveExecutable.mockRejectedValue(new SubprocessExecutableNotFoundError('default shell was removed')) expect(controller.environment(agent, signal())).toMatchObject({ cwd: '/workspace', maxInputBytes: 1000 }) expect(controller.list(agent.id)).toMatchObject([{ id, state: 'running' }]) - const stream = controller.follow(agent, id, 'restored' as TerminalAttachmentId, signal())[Symbol.asyncIterator]() + const stream = attachController(agent, id, signal())[Symbol.asyncIterator]() try { expect(await stream.next()).toMatchObject({ done: false, value: { type: 'snapshot', info: { id, state: 'running' } } }) expect(subprocess.resolveExecutable).toHaveBeenCalledOnce() @@ -181,9 +183,9 @@ describe('TerminalController', () => { expect(subprocess.spawnTerminal).toHaveBeenCalledOnce() expect(subprocess.spawnTerminal).toHaveBeenCalledWith(expect.objectContaining({ terminalType: 'xterm-256color', cwd: '/workspace' })) expect(controller.list('other' as SessionId)).toEqual([]) - expect(() => controller.follow(owner(ctx, 'other'), id, 'writer' as TerminalAttachmentId, signal())).toThrow('no longer exists') + expect(() => attachController(owner(ctx, 'other'), id, signal())).toThrow('no longer exists') const abort = new AbortController() - const stream = controller.follow(agent, id, 'writer' as TerminalAttachmentId, abort.signal)[Symbol.asyncIterator]() + const stream = attachController(agent, id, abort.signal)[Symbol.asyncIterator]() const firstFrame = await stream.next() if (firstFrame.done === true) throw new Error('Terminal stream ended before its snapshot') expect(firstFrame.value.type).toBe('snapshot') @@ -266,13 +268,13 @@ describe('TerminalController', () => { expect(controller.list(agent.id)).toHaveLength(0) }) - it('rejects invalid dimensions, unavailable shells and oversized input before executing them', async () => { + it('rejects invalid dimensions and unavailable shells before allocating a process', async () => { const { controller, agent, subprocess } = fixture() await expect(controller.create(agent, { ...request, cols: 1 }, signal())).rejects.toThrow('dimensions') subprocess.resolveExecutable.mockRejectedValueOnce(new SubprocessExecutableNotFoundError('shell unavailable')) await expect(controller.create(agent, request, signal())).rejects.toThrow('unavailable') expect(subprocess.spawnTerminal).not.toHaveBeenCalled() - await expect(controller.write(agent, id, 'writer' as TerminalAttachmentId, 'x'.repeat(1001))).rejects.toThrow('input') + }) it('keeps the committed identity on repeated creation and counts pending reservations toward the Session limit', async () => { @@ -319,27 +321,32 @@ describe('TerminalController', () => { expect(controller.list(agent.id)).toEqual([]) }) - it('routes input, resize and trimmed names through the active attachment', async () => { + it('routes ordered input and resize through the current Remote attachment', async () => { const { controller, agent, handle } = fixture({ maxInputBytes: 6 }) await controller.create(agent, request, signal()) - const attachmentId = 'writer' as TerminalAttachmentId - const stream = controller.follow(agent, id, attachmentId, signal())[Symbol.asyncIterator]() + const input = inputChannel() + const stream = attachController(agent, id, signal(), input.source)[Symbol.asyncIterator]() await stream.next() try { - await controller.write(agent, id, attachmentId, '终端') + input.push({ type: 'write', sequence: 1, data: '终端' }) + expect((await stream.next()).value).toMatchObject({ type: 'ack', sequence: 1 }) expect(handle.write).toHaveBeenCalledWith('终端') - await expect(controller.write(agent, id, attachmentId, '终端!')).rejects.toThrow('input exceeds') - await controller.resize(agent, id, attachmentId, 200, 100) + input.push({ type: 'resize', sequence: 2, cols: 200, rows: 100 }) + expect((await stream.next()).value).toMatchObject({ type: 'state', info: { cols: 200, rows: 100 } }) + expect((await stream.next()).value).toMatchObject({ type: 'ack', sequence: 2 }) expect(handle.resize).toHaveBeenCalledWith(200, 100) controller.rename(agent, id, ' server logs ') expect(controller.list(agent.id)).toMatchObject([{ title: 'server logs', cols: 200, rows: 100 }]) + input.push({ type: 'write', sequence: 3, data: '终端!' }) + await stream.next() + await expect(stream.next()).rejects.toThrow('input exceeds') } finally { await stream.return?.() } }) - it.each([{ cols: 1.5, rows: 24 }, { cols: 201, rows: 24 }, { cols: 80, rows: 1.5 }, { cols: 80, rows: 0 }, { cols: 80, rows: 101 }])('rejects dimensions $cols × $rows before allocation or resize', async (dimensions) => { + it.each([{ cols: 1.5, rows: 24 }, { cols: 201, rows: 24 }, { cols: 80, rows: 1.5 }, { cols: 80, rows: 0 }, { cols: 80, rows: 101 }])('rejects dimensions $cols × $rows before allocation', async (dimensions) => { const { controller, agent, subprocess, handle } = fixture() await expect(controller.create(agent, { ...request, ...dimensions }, signal())).rejects.toThrow('dimensions') - await expect(controller.resize(agent, id, 'writer' as TerminalAttachmentId, dimensions.cols, dimensions.rows)).rejects.toThrow('dimensions') + expect(subprocess.spawnTerminal).not.toHaveBeenCalled() expect(handle.resize).not.toHaveBeenCalled() }) @@ -347,7 +354,7 @@ describe('TerminalController', () => { it('rejects invalid wire identities and names without changing retained terminals', async () => { const { controller, agent } = fixture() await expect(controller.create(agent, { ...request, id: '../terminal' as WebTerminalId }, signal())).rejects.toThrow('Invalid terminal identity') - expect(() => controller.follow(agent, id, '' as TerminalAttachmentId, signal())).toThrow('attachment identity') + expect(() => controller.attach(agent, id, signal())).toThrow('Remote invocation') expect(() => { controller.rename(agent, id, ' ') }).toThrow('1–120') expect(() => { controller.rename(agent, id, 'x'.repeat(121)) }).toThrow('1–120') await controller.close(agent, id) @@ -699,12 +706,40 @@ it.each(['allocation', 'committed'] as const)('retains failed %s cleanup, report it('classifies missing and closing terminal identities for localized recovery actions', async () => { const h = fixture() - expect(() => h.controller.follow(h.agent, id, 'view' as TerminalAttachmentId, signal())) + expect(() => attachController(h.agent, id, signal())) .toThrow(expect.objectContaining({ code: 'terminal/unavailable' })) await h.controller.create(h.agent, request, signal()) h.handle.terminate.mockRejectedValueOnce(new Error('cleanup pending')) await expect(h.controller.close(h.agent, id)).rejects.toThrow('cleanup pending') - expect(() => h.controller.follow(h.agent, id, 'view' as TerminalAttachmentId, signal())) + expect(() => attachController(h.agent, id, signal())) .toThrow(expect.objectContaining({ code: 'terminal/unavailable' })) await expect(h.controller.create(h.agent, request, signal())).rejects.toMatchObject({ code: 'terminal/unavailable' }) }) + +it('publishes the carrier input window in the attachment snapshot', async () => { + const { controller, agent } = fixture() + await controller.create(agent, request, signal()) + const abort = new AbortController() + const window = { maxBytes: 512, frameOverheadBytes: 76 } + const frames = attachController(agent, id, abort.signal, inputChannel().source, window)[Symbol.asyncIterator]() + try { + expect(await frames.next()).toMatchObject({ value: { type: 'snapshot', inputWindow: window } }) + } finally { + abort.abort() + await frames.return?.() + } +}) + +function attachController( + agent: Agent, terminalId: WebTerminalId, signal: AbortSignal, + input: AsyncIterable = inputChannel().source, + uplinkWindow?: RemoteInvocation['uplinkWindow'], +) { + const invocation: RemoteInvocation = { + request: { namespace: 'terminal', method: 'attach', args: {} }, service: 'terminalController', signal, + peer: { id: 'test-peer' as PeerId, ctx: agent.ctx, principal: { kind: 'owner' }, signal, dispose: async () => {} }, + uplink: () => input as AsyncIterable, + uplinkWindow, + } + return agent.ctx.extend({ invocation }).terminalController.attach(agent, terminalId, signal) +} diff --git a/packages/api/terminal-controller/tests/input.ts b/packages/api/terminal-controller/tests/input.ts new file mode 100644 index 0000000000..ae7a75c559 --- /dev/null +++ b/packages/api/terminal-controller/tests/input.ts @@ -0,0 +1,16 @@ +/** A typed uplink whose return interrupts a pending read, matching Gateway invocation cleanup. */ +export function inputChannel() { + let controller!: ReadableStreamDefaultController + const stream = new ReadableStream({ start(value) { controller = value } }) + const reader = stream.getReader() + const source: AsyncIterable = { + [Symbol.asyncIterator]: () => ({ + async next() { + const result = await reader.read() + return result.done ? { done: true, value: undefined } : { done: false, value: result.value } + }, + async return() { await reader.cancel(); return { done: true, value: undefined } }, + }), + } + return { source, push: (value: T) => { controller.enqueue(value) }, end: () => { controller.close() } } +} diff --git a/packages/api/terminal-controller/tests/model.client.spec.ts b/packages/api/terminal-controller/tests/model.client.spec.ts index 2c34b9c54b..fbae792001 100644 --- a/packages/api/terminal-controller/tests/model.client.spec.ts +++ b/packages/api/terminal-controller/tests/model.client.spec.ts @@ -1,19 +1,18 @@ /** Browser view ownership across slow RPCs, remounts and transport generations. */ -import { setImmediate } from 'node:timers/promises' import { afterEach, expect, it, vi } from 'vitest' import { RemoteStream, RemoteStreamCarrierError, type ClientRemote, type RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' -import { streamMethod } from '@deepseek-ai/dsh-remote-mock' +import { RemoteError, type RemoteResult, type RemoteUplinkWindow } from '@deepseek-ai/dsh-typert-protocol' +import { RemoteMock, streamMethod, type StreamHandle } from '@deepseek-ai/dsh-remote-mock' import type {} from '@deepseek-ai/dsh-api-terminal-controller/remote' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { TerminalView, type TerminalRemote } from '../src/client/model.ts' -import type { TerminalEnvironment, TerminalFrame, WebTerminalId, WebTerminalInfo } from '../src/types.ts' +import type { TerminalInput, TerminalEnvironment, TerminalFrame, WebTerminalId, WebTerminalInfo } from '../src/types.ts' const sessionId = 'session' as SessionId const info: WebTerminalInfo = { id: 'terminal' as WebTerminalId, shell: { name: 'bash', path: '/bin/bash', args: ['-i'] }, title: 'bash', cwd: '/workspace', rows: 24, cols: 80, state: 'running', exitCode: null } const environment: TerminalEnvironment = { - cwd: info.cwd, maxInputBytes: 1000, maxCols: 200, maxRows: 100, scrollback: 100, + cwd: info.cwd, maxInputBytes: 1000, maxBufferedBytes: 100_000, maxCols: 200, maxRows: 100, scrollback: 100, } const success = (value: T): RemoteResult => ({ ok: true, value }) const cleanups: (() => void | Promise)[] = [] @@ -30,7 +29,16 @@ function failure(message: string): RemoteResult { return { ok: false, error: new RemoteError('gateway/bad-request', message, {}) } } -function fixture(prepareStream?: (stream: RemoteStream) => void) { +function fixture(prepareStream?: (stream: RemoteStream) => void, inputWindow?: RemoteUplinkWindow) { + const attachments: StreamHandle[] = [] + const sent: TerminalInput[][] = [] + const mock = RemoteMock.create().stream('terminal/attach', async (args, stream) => { + attachments.push(stream) + const commands: TerminalInput[] = [] + sent.push(commands) + stream.push({ type: 'snapshot', sequence: 0, screen: 'ready', info: { ...info, id: args[1] }, writable: true, ...inputWindow === undefined ? {} : { inputWindow } }) + for await (const command of stream.uplink) commands.push(command as TerminalInput) + }) const remote: TerminalRemote = { retain: vi.fn(streamMethod(async function* (_session, _id, signal) { yield { type: 'retained' } @@ -43,11 +51,7 @@ function fixture(prepareStream?: (stream: RemoteStream) => void) { environment: vi.fn(async () => success(environment)), list: vi.fn(async () => success([])), create: vi.fn(async (_sessionId, request) => success({ ...info, id: request.id })), close: vi.fn(async () => success(undefined)), rename: vi.fn(async () => success(undefined)), - write: vi.fn(async () => success(undefined)), resize: vi.fn(async () => success(undefined)), - follow: vi.fn(streamMethod(async function* (_sessionId, id, attachmentId, signal) { - yield { type: 'snapshot', sequence: 0, screen: 'ready', info: { ...info, id, controllerId: attachmentId } } - await untilAborted(signal) - })), + attach: mock.remote.terminal.attach, } const options: RemoteStreamOptions[] = [] const streams: { dispose(): Promise; restart(): void }[] = [] @@ -64,7 +68,7 @@ function fixture(prepareStream?: (stream: RemoteStream) => void) { cleanups.push(async () => { await Promise.all(streams.map(stream => stream.dispose())) }) const model = new TerminalView(sessionId, remote, gateway, info.id) cleanups.push(() => model.dispose()) - return { model, remote, gateway, options, streams, generation } + return { model, remote, gateway, options, streams, generation, attachments, sent } } async function mount(model: TerminalView) { @@ -84,29 +88,11 @@ async function connected(model: TerminalView): Promise { acknowledge(model) } -it('does not let a late input failure downgrade a newer connection', async () => { - const { model, remote } = fixture() - await mount(model) - await expect.poll(() => model.state.getSnapshot().writable).toBe(true) - acknowledge(model) - const input = Promise.withResolvers>() - vi.mocked(remote.write).mockReturnValueOnce(input.promise) - model.write('x') - await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1) - model.connect() - await expect.poll(() => vi.mocked(remote.follow).mock.calls.length).toBe(2) - await expect.poll(() => model.state.getSnapshot().writable).toBe(true) - model.write('current input') - input.reject(new Error('old attachment was replaced')) - await expect.poll(() => vi.mocked(remote.write).mock.calls.some(call => call[3] === 'current input')).toBe(true) - expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', writable: true, error: undefined }) -}) - it('waits for render acknowledgement before publishing subsequent output', async () => { const { model, remote } = fixture() - vi.mocked(remote.follow).mockImplementation(streamMethod(async function* (_sessionId, id, controllerId, signal) { + vi.mocked(remote.attach).mockImplementation(streamMethod(async function* (_sessionId, id, signal) { const frames: TerminalFrame[] = [ - { type: 'snapshot', sequence: 0, screen: '', info: { ...info, id, controllerId } }, + { type: 'snapshot', writable: true, sequence: 0, screen: '', info: { ...info, id } }, { type: 'output', sequence: 1, data: 'first' }, { type: 'output', sequence: 2, data: 'second' }, ] @@ -121,77 +107,6 @@ it('waits for render acknowledgement before publishing subsequent output', async await expect.poll(() => model.state.getSnapshot().render?.frame).toMatchObject({ type: 'output', sequence: 2 }) }) -it('serializes input and resizes, clamps geometry, and suppresses unchanged sizes', async () => { - const { model, remote } = fixture() - await connected(model) - const input = Promise.withResolvers>() - vi.mocked(remote.write).mockReturnValueOnce(input.promise) - model.resize(80, 24) - model.write('first') - model.write('second') - model.resize(500, 300) - await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1) - expect(remote.resize).not.toHaveBeenCalled() - input.resolve(success(undefined)) - await expect.poll(() => vi.mocked(remote.resize).mock.calls.length).toBe(1) - const attachmentId = vi.mocked(remote.follow).mock.calls[0]![2] - const id = model.state.getSnapshot().info!.id - expect(vi.mocked(remote.write).mock.calls.map(call => call[3])).toEqual(['first', 'second']) - expect(remote.resize).toHaveBeenCalledWith(sessionId, id, attachmentId, 200, 100) - model.resize(90, 24) - await expect.poll(() => vi.mocked(remote.resize).mock.calls.length).toBe(2) -}) - -it('bounds queued input by UTF-8 bytes and releases the byte budget after settlement', async () => { - const { model, remote } = fixture() - vi.mocked(remote.environment).mockResolvedValue(success({ ...environment, maxInputBytes: 6 })) - await connected(model) - const input = Promise.withResolvers>() - vi.mocked(remote.write).mockReturnValueOnce(input.promise) - model.write('界界') - await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1) - model.write('a') - expect(model.state.getSnapshot()).toMatchObject({ phase: 'failed', issue: 'inputFull' }) - input.resolve(success(undefined)) - model.connect() - await expect.poll(() => model.state.getSnapshot().writable).toBe(true) - model.write('界界') - await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(2) - expect(vi.mocked(remote.write).mock.calls.map(call => call[3])).toEqual(['界界', '界界']) -}) - -it('drops queued commands from a detached attachment and ignores its late resize failure', async () => { - const { model, remote } = fixture() - await connected(model) - const input = Promise.withResolvers>() - vi.mocked(remote.resize).mockReturnValueOnce(input.promise) - model.resize(100, 30) - await expect.poll(() => vi.mocked(remote.resize).mock.calls.length).toBe(1) - model.write('stale') - model.resize(110, 35) - model.connect() - await expect.poll(() => model.state.getSnapshot().writable).toBe(true) - model.write('current') - input.resolve(failure('old attachment')) - await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1) - expect(vi.mocked(remote.write).mock.calls[0]?.[3]).toBe('current') - expect(remote.resize).toHaveBeenCalledOnce() - expect(model.state.getSnapshot().phase).toBe('connected') -}) - -it('publishes current input and resize failures and can reconnect for another attempt', async () => { - const { model, remote } = fixture() - await connected(model) - vi.mocked(remote.write).mockResolvedValueOnce(failure('input refused')) - model.write('x') - await expect.poll(() => model.state.getSnapshot().error).toBe('input refused') - model.connect() - await expect.poll(() => model.state.getSnapshot().writable).toBe(true) - vi.mocked(remote.resize).mockResolvedValueOnce(failure('resize refused')) - model.resize(100, 30) - await expect.poll(() => model.state.getSnapshot().error).toBe('resize refused') -}) - it('treats carrier loss as disconnected only for the active attachment', async () => { const { model, options } = fixture() await connected(model) @@ -206,11 +121,11 @@ it('treats carrier loss as disconnected only for the active attachment', async ( it.each([ ['output before snapshot', [{ type: 'output', sequence: 1, data: 'orphan' }], 'missing its screen snapshot'], - ['sequence gap', [{ type: 'snapshot', sequence: 4, screen: '', info }, { type: 'output', sequence: 6, data: 'gap' }], 'sequence has a gap'], - ['repeated snapshot', [{ type: 'snapshot', sequence: 4, screen: '', info }, { type: 'snapshot', sequence: 4, screen: '', info }], 'Unexpected terminal screen snapshot'], + ['sequence gap', [{ type: 'snapshot', writable: true, sequence: 4, screen: '', info }, { type: 'output', sequence: 6, data: 'gap' }], 'sequence has a gap'], + ['repeated snapshot', [{ type: 'snapshot', writable: true, sequence: 4, screen: '', info }, { type: 'snapshot', writable: true, sequence: 4, screen: '', info }], 'Unexpected terminal screen snapshot'], ] satisfies readonly (readonly [string, readonly TerminalFrame[], string])[])('refuses a malformed output stream: %s', async (_name, frames, message) => { const { model, remote } = fixture() - vi.mocked(remote.follow).mockImplementation(streamMethod(async function* () { yield* frames })) + vi.mocked(remote.attach).mockImplementation(streamMethod(async function* () { yield* frames })) await mount(model) if (frames[0]?.type === 'snapshot') { await expect.poll(() => model.state.getSnapshot().render).toBeDefined() @@ -222,9 +137,9 @@ it.each([ it('retains an exited screen and closes controls when its stream ends', async () => { const { model, remote } = fixture() - vi.mocked(remote.follow).mockImplementation(streamMethod(async function* (_sessionId, id, controllerId) { - yield { type: 'snapshot', sequence: 0, screen: 'last screen', info: { ...info, id, controllerId } } - yield { type: 'state', info: { ...info, id, controllerId, state: 'exited', exitCode: 3 } } + vi.mocked(remote.attach).mockImplementation(streamMethod(async function* (_sessionId, id) { + yield { type: 'snapshot', writable: true, sequence: 0, screen: 'last screen', info: { ...info, id } } + yield { type: 'state', writable: true, info: { ...info, id, state: 'exited', exitCode: 3 } } })) await connected(model) await expect.poll(() => model.state.getSnapshot().phase).toBe('closed') @@ -233,8 +148,8 @@ it('retains an exited screen and closes controls when its stream ends', async () it('reports an attachment ending while the shell is still running and permits manual reconnect', async () => { const { model, remote } = fixture() - vi.mocked(remote.follow).mockImplementationOnce(streamMethod(async function* (_sessionId, id, controllerId) { - yield { type: 'snapshot', sequence: 0, screen: '', info: { ...info, id, controllerId } } + vi.mocked(remote.attach).mockImplementationOnce(streamMethod(async function* (_sessionId, id) { + yield { type: 'snapshot', writable: true, sequence: 0, screen: '', info: { ...info, id } } })) await connected(model) await expect.poll(() => model.state.getSnapshot().issue).toBe('attachmentEnded') @@ -244,14 +159,14 @@ it('reports an attachment ending while the shell is still running and permits ma it('publishes remote control transfer without replacing the retained screen', async () => { const { model, remote } = fixture() - vi.mocked(remote.follow).mockImplementation(streamMethod(async function* (_sessionId, id, controllerId, signal) { - yield { type: 'snapshot', sequence: 0, screen: 'retained', info: { ...info, id, controllerId } } - yield { type: 'state', info: { ...info, id } } + vi.mocked(remote.attach).mockImplementation(streamMethod(async function* (_sessionId, id, signal) { + yield { type: 'snapshot', writable: true, sequence: 0, screen: 'retained', info: { ...info, id } } + yield { type: 'state', writable: false, info: { ...info, id } } await untilAborted(signal) })) await connected(model) await expect.poll(() => model.state.getSnapshot().writable).toBe(false) - expect(model.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', screen: 'retained' }) + expect(model.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', writable: true, screen: 'retained' }) }) /** Pause delivery after the real Gateway iterator settles, before the model observes it. */ @@ -293,13 +208,13 @@ it('ignores an already delivered screen when its attachment is replaced before t barrier.release() await model.rename('settled') expect(model.state.getSnapshot().render).toBe(current.render) - expect(remote.follow).toHaveBeenCalledTimes(2) + expect(remote.attach).toHaveBeenCalledTimes(2) }) it('ignores an already settled stream error after a newer attachment has become writable', async () => { const barrier = deliveryBarrier() const { model, remote } = fixture(barrier.prepare) - vi.mocked(remote.follow).mockImplementationOnce(streamMethod(async function* () { + vi.mocked(remote.attach).mockImplementationOnce(streamMethod(async function* () { yield* [] throw new Error('retired attachment failed') })) @@ -319,7 +234,7 @@ it('releases a pending screen render on carrier generation cancellation and acce const revision = model.state.getSnapshot().render!.revision streams[0]!.restart() await expect.poll(() => model.state.getSnapshot().render?.revision).toBe(revision + 1) - expect(remote.follow).toHaveBeenCalledTimes(2) + expect(remote.attach).toHaveBeenCalledTimes(2) expect(model.state.getSnapshot().writable).toBe(true) }) @@ -331,96 +246,10 @@ it('does not wait for the DOM callback of a screen whose generation was already streams[0]!.restart() barrier.release() await expect.poll(() => model.state.getSnapshot().render?.revision).toBe(2) - expect(remote.follow).toHaveBeenCalledTimes(2) + expect(remote.attach).toHaveBeenCalledTimes(2) expect(model.state.getSnapshot().writable).toBe(true) }) -it.each(['write', 'resize'] as const)('keeps a fresh attachment writable when a pending %s fails after automatic transport recovery', async (operation) => { - const { model, remote, generation } = fixture() - generation.set({ id: 1, host: { home: '/home/fixture' } }) - const disconnected = Promise.withResolvers() - vi.mocked(remote.follow).mockImplementationOnce(streamMethod(async function* (_sessionId, id, controllerId, signal) { - yield { type: 'snapshot', sequence: 0, screen: 'before disconnect', info: { ...info, id, controllerId } } - await Promise.race([disconnected.promise, untilAborted(signal)]) - if (signal?.aborted) return - throw new RemoteStreamCarrierError('connection lost') - })) - await connected(model) - const pending = Promise.withResolvers>() - if (operation === 'write') { - vi.mocked(remote.write).mockReturnValueOnce(pending.promise) - model.write('old input') - } else { - vi.mocked(remote.resize).mockReturnValueOnce(pending.promise) - model.resize(100, 30) - } - await expect.poll(() => vi.mocked(remote[operation]).mock.calls.length).toBe(1) - const oldAttachmentId = vi.mocked(remote.follow).mock.calls[0]![2] - generation.set(undefined) - disconnected.resolve(undefined) - await expect.poll(() => model.state.getSnapshot().phase).toBe('disconnected') - expect(model.state.getSnapshot().writable).toBe(false) - expect(remote.follow).toHaveBeenCalledOnce() - - generation.set({ id: 2, host: { home: '/home/fixture' } }) - await expect.poll(() => model.state.getSnapshot().writable).toBe(true) - expect(remote.follow).toHaveBeenCalledTimes(2) - const attachmentId = vi.mocked(remote.follow).mock.calls[1]![2] - expect(attachmentId).not.toBe(oldAttachmentId) - expect(model.state.getSnapshot().info?.controllerId).toBe(attachmentId) - expect(model.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', screen: 'ready' }) - - model.write('fresh input') - pending.reject(new Error('old attachment was replaced')) - await expect.poll(() => vi.mocked(remote.write).mock.calls.some(call => call[3] === 'fresh input')).toBe(true) - expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', writable: true, error: undefined }) - expect(vi.mocked(remote.write).mock.calls.at(-1)?.[2]).toBe(attachmentId) - expect(remote.create).toHaveBeenCalledOnce() - expect(remote.close).not.toHaveBeenCalled() -}) - -it('ignores controls before discovery and reconnects an existing process after remount', async () => { - const { model, remote } = fixture() - model.connect() - model.write('early') - model.resize(100, 30) - model.acknowledge(100) - expect(remote.follow).not.toHaveBeenCalled() - expect(remote.write).not.toHaveBeenCalled() - expect(remote.resize).not.toHaveBeenCalled() - const unmount = await mount(model) - await expect.poll(() => model.state.getSnapshot().writable).toBe(true) - unmount() - model.connect() - model.write('detached') - model.resize(100, 30) - expect(remote.follow).toHaveBeenCalledOnce() - expect(remote.write).not.toHaveBeenCalled() - expect(remote.resize).not.toHaveBeenCalled() - model.mount() - await expect.poll(() => remote.follow).toHaveBeenCalledTimes(2) - await expect.poll(() => model.state.getSnapshot().writable).toBe(true) - expect(remote.create).toHaveBeenCalledOnce() -}) - -it('keeps controls inert when process metadata or the attachment is unavailable', async () => { - const { model, remote } = fixture() - await connected(model) - const state = model.state.getSnapshot() - model.state.set({ ...state, info: undefined }) - model.write('missing metadata') - model.resize(100, 30) - expect(remote.write).not.toHaveBeenCalled() - expect(remote.resize).not.toHaveBeenCalled() - model.state.set({ ...state, environment: undefined }) - model.resize(100, 30) - await expect.poll(() => remote.resize).toHaveBeenCalledOnce() - expect(vi.mocked(remote.resize).mock.calls[0]?.slice(-2)).toEqual([100, 30]) - model.write('unknown budget') - expect(model.state.getSnapshot().issue).toBe('inputFull') - expect(remote.write).not.toHaveBeenCalled() -}) - it('renames an existing terminal, skips unchanged names, and exposes rename failures', async () => { const { model, remote } = fixture() await connected(model) @@ -462,7 +291,7 @@ it('retains state when disposal overtakes successful allocation or a failed disc else discovery.reject(new Error('late discovery failure')) await loading expect(model.state.getSnapshot()).toBe(before) - expect(remote.follow).not.toHaveBeenCalled() + expect(remote.attach).not.toHaveBeenCalled() } }) @@ -487,7 +316,7 @@ it('allows retry after failed process cleanup and never reconnects while close i const first = model.close() expect(model.close()).toBe(first) model.connect() - expect(remote.follow).toHaveBeenCalledOnce() + expect(remote.attach).toHaveBeenCalledOnce() closing.resolve(failure('close refused')) await expect(first).rejects.toThrow('close refused') expect(model.state.getSnapshot()).toMatchObject({ phase: 'failed', error: 'close refused' }) @@ -509,55 +338,7 @@ it('does not publish a close result or reconnect after disposal', async () => { model.mount() model.connect() expect(model.state.getSnapshot()).toBe(before) - expect(remote.follow).toHaveBeenCalledOnce() -}) - -it.each(['write', 'resize'] as const)('keeps the output connection when %s loses control before its state frame arrives', async (operation) => { - const { model, remote } = fixture() - const transfer = Promise.withResolvers() - const response = Promise.withResolvers>() - cleanups.push(() => { transfer.resolve(undefined); response.resolve(success(undefined)) }) - vi.mocked(remote.follow).mockImplementation(streamMethod(async function* (_session, id, controllerId, signal) { - yield { type: 'snapshot', sequence: 0, screen: 'retained screen', info: { ...info, id, controllerId } } - await transfer.promise - yield { type: 'state', info: { ...info, id } } - await untilAborted(signal) - })) - await connected(model) - vi.mocked(remote[operation]).mockReturnValueOnce(response.promise) - if (operation === 'write') model.write('before transfer') - else model.resize(100, 30) - model.write('queued before transfer') - await expect.poll(() => vi.mocked(remote[operation]).mock.calls.length).toBe(1) - response.resolve({ ok: false, error: new RemoteError('terminal/control-unavailable', 'Another window owns input', { reason: 'read-only' }) }) - await expect.poll(() => model.state.getSnapshot().writable).toBe(false) - expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', error: undefined, issue: undefined, render: { frame: { screen: 'retained screen' } } }) - transfer.resolve(undefined) - await expect.poll(() => model.state.getSnapshot().info?.controllerId).toBeUndefined() - expect(remote.follow).toHaveBeenCalledOnce() - expect(vi.mocked(remote.write).mock.calls.some(call => call[3] === 'queued before transfer')).toBe(false) -}) - -it('keeps an exited screen when a pending input is refused after the exit state arrives', async () => { - const { model, remote } = fixture() - const exit = Promise.withResolvers() - const response = Promise.withResolvers>() - cleanups.push(() => { exit.resolve(undefined); response.resolve(success(undefined)) }) - vi.mocked(remote.follow).mockImplementation(streamMethod(async function* (_session, id, controllerId, signal) { - yield { type: 'snapshot', sequence: 0, screen: 'final screen', info: { ...info, id, controllerId } } - await exit.promise - yield { type: 'state', info: { ...info, id, state: 'exited', exitCode: 0 } } - await untilAborted(signal) - })) - await connected(model) - vi.mocked(remote.write).mockReturnValueOnce(response.promise) - model.write('exit race') - await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1) - exit.resolve(undefined) - await expect.poll(() => model.state.getSnapshot().info?.state).toBe('exited') - response.resolve({ ok: false, error: new RemoteError('terminal/control-unavailable', 'Terminal is not running', { reason: 'not-running' }) }) - await setImmediate() - expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', writable: false, error: undefined, issue: undefined, render: { frame: { screen: 'final screen' } } }) + expect(remote.attach).toHaveBeenCalledOnce() }) it('exposes a localized quota error and clears it after a successful retry', async () => { @@ -568,3 +349,208 @@ it('exposes a localized quota error and clears it after a successful retry', asy await connected(model) expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', issue: undefined, error: undefined }) }) + +it('sends input and clamped resize in order without waiting for acknowledgements', async () => { + const h = fixture() + await connected(h.model) + h.model.resize(80, 24) + h.model.write('first') + h.model.write('second') + h.model.resize(500, 300) + await expect.poll(() => h.sent[0]?.length).toBe(3) + expect(h.sent[0]).toEqual([ + { type: 'write', sequence: 1, data: 'first' }, + { type: 'write', sequence: 2, data: 'second' }, + { type: 'resize', sequence: 3, cols: 200, rows: 100 }, + ]) +}) + +it('releases the UTF-8 input budget only on acknowledgement', async () => { + const h = fixture() + vi.mocked(h.remote.environment).mockResolvedValue(success({ ...environment, maxInputBytes: 6 })) + await connected(h.model) + h.model.write('界界') + await expect.poll(() => h.sent[0]?.length).toBe(1) + h.attachments[0]!.push({ type: 'ack', sequence: 1 }) + h.attachments[0]!.push({ type: 'state', info: { ...info, cols: 90 }, writable: true }) + await expect.poll(() => h.model.state.getSnapshot().info?.cols).toBe(90) + h.model.write('界界') + await expect.poll(() => h.sent[0]?.length).toBe(2) + h.model.write('a') + expect(h.model.state.getSnapshot()).toMatchObject({ phase: 'failed', issue: 'inputFull' }) +}) + +it('keeps output attached after an input refusal and stops further input', async () => { + const h = fixture() + await connected(h.model) + h.model.write('before transfer') + h.attachments[0]!.push({ type: 'ack', sequence: 1, refusal: 'read-only' }) + await expect.poll(() => h.model.state.getSnapshot().writable).toBe(false) + h.model.write('refused') + h.model.resize(100, 30) + h.attachments[0]!.push({ type: 'output', sequence: 1, data: 'still following' }) + await expect.poll(() => h.model.state.getSnapshot().render?.frame).toMatchObject({ data: 'still following' }) + expect(h.model.state.getSnapshot()).toMatchObject({ phase: 'connected', error: undefined }) + expect(h.remote.attach).toHaveBeenCalledOnce() + expect(h.sent[0]).toHaveLength(1) +}) + +it('discards the old generation budget and never replays unacknowledged input after reconnect', async () => { + const h = fixture() + h.generation.set({ id: 1, host: { home: '/home/fixture' } }) + await connected(h.model) + h.model.write('unconfirmed') + await expect.poll(() => h.sent[0]?.length).toBe(1) + h.generation.set(undefined) + h.attachments[0]!.fail(new RemoteStreamCarrierError('connection lost')) + await expect.poll(() => h.model.state.getSnapshot().phase).toBe('disconnected') + h.model.write('offline') + h.generation.set({ id: 2, host: { home: '/home/fixture' } }) + await expect.poll(() => h.attachments.length).toBe(2) + await expect.poll(() => h.model.state.getSnapshot().writable).toBe(true) + acknowledge(h.model) + h.model.write('fresh') + await expect.poll(() => h.sent[1]?.length).toBe(1) + expect(h.sent[1]).toEqual([{ type: 'write', sequence: 1, data: 'fresh' }]) + h.attachments[0]!.push({ type: 'ack', sequence: 1, refusal: 'read-only' }) + expect(h.model.state.getSnapshot().writable).toBe(true) + expect(h.remote.create).toHaveBeenCalledOnce() +}) + +it('ignores controls before mount and after detach, then reuses the process on remount', async () => { + const h = fixture() + h.model.write('early') + h.model.resize(100, 30) + const unmount = await mount(h.model) + await expect.poll(() => h.model.state.getSnapshot().writable).toBe(true) + unmount() + h.model.write('detached') + h.model.resize(100, 30) + expect(h.sent[0]).toEqual([]) + h.model.mount() + await expect.poll(() => h.remote.attach).toHaveBeenCalledTimes(2) + expect(h.remote.create).toHaveBeenCalledOnce() +}) + +it('rejects an out-of-order acknowledgement and reports synchronous send failures', async () => { + const h = fixture() + await connected(h.model) + h.model.write('input') + h.attachments[0]!.push({ type: 'ack', sequence: 2 }) + await expect.poll(() => h.model.state.getSnapshot().issue).toBe('invalidOutput') + h.model.connect() + await expect.poll(() => h.model.state.getSnapshot().writable).toBe(true) + const handle = vi.mocked(h.remote.attach).mock.results.at(-1)!.value as ReturnType + vi.spyOn(handle, 'send').mockImplementation(() => { throw new Error('send failed') }) + h.model.write('next') + expect(h.model.state.getSnapshot()).toMatchObject({ phase: 'failed', error: 'send failed' }) +}) + +it.each(['write', 'resize'] as const)('ignores empty input and stale render acknowledgements and refuses %s without limits', async (operation) => { + const h = fixture() + await connected(h.model) + h.model.acknowledge(-1) + h.model.write('') + const state = h.model.state.getSnapshot() + h.model.state.set({ ...state, info: undefined }) + h.model.write('missing') + h.model.resize(100, 30) + expect(h.sent[0]).toEqual([]) + h.model.state.set({ ...state, environment: undefined }) + if (operation === 'write') h.model.write('no budget') + else h.model.resize(100, 30) + expect(h.sent[0]).toEqual([]) + expect(h.model.state.getSnapshot().issue).toBe('inputFull') +}) + +function encodedFrame(command: TerminalInput): number { + return new TextEncoder().encode(JSON.stringify({ type: 'item', streamId: '00000000-0000-0000-0000-000000000000', value: command })).byteLength +} + +function inputWindow(maxBytes: number): RemoteUplinkWindow { + const command: TerminalInput = { type: 'write', sequence: 1, data: 'a' } + return { maxBytes, frameOverheadBytes: encodedFrame(command) - new TextEncoder().encode(JSON.stringify(command)).byteLength } +} + +it('waits for complete-frame capacity and sends queued write and resize commands in order', async () => { + const commands: TerminalInput[] = [ + { type: 'write', sequence: 1, data: '\u0001界' }, + { type: 'resize', sequence: 2, cols: 90, rows: 25 }, + { type: 'write', sequence: 3, data: 'last' }, + ] + const h = fixture(undefined, inputWindow(Math.max(...commands.map(encodedFrame)))) + await connected(h.model) + h.model.write('\u0001界') + h.model.resize(90, 25) + h.model.write('last') + await expect.poll(() => h.sent[0]).toEqual(commands.slice(0, 1)) + h.attachments[0]!.push({ type: 'ack', sequence: 1 }) + await expect.poll(() => h.sent[0]).toEqual(commands.slice(0, 2)) + h.attachments[0]!.push({ type: 'ack', sequence: 2 }) + await expect.poll(() => h.sent[0]).toEqual(commands) + expect(h.model.state.getSnapshot()).toMatchObject({ phase: 'connected', issue: undefined }) +}) + +it('keeps a burst of short commands within the advertised inbox and resumes on acknowledgements', async () => { + const window = inputWindow(262_144) + const h = fixture(undefined, window) + vi.mocked(h.remote.environment).mockResolvedValue(success({ ...environment, maxInputBytes: 65_536, maxBufferedBytes: 2_097_152 })) + await connected(h.model) + for (let index = 0; index < 3000; index++) h.model.write('a') + await expect.poll(() => h.sent[0]?.length).toBe(2250) + const first = h.sent[0]! + expect(first.reduce((bytes, command) => bytes + encodedFrame(command), 0)).toBeLessThanOrEqual(window.maxBytes) + for (let sequence = 1; sequence <= 1000; sequence++) h.attachments[0]!.push({ type: 'ack', sequence }) + await expect.poll(() => h.sent[0]?.length).toBe(3000) + expect(h.sent[0]!.slice(1000).reduce((bytes, command) => bytes + encodedFrame(command), 0)).toBeLessThanOrEqual(window.maxBytes) + expect(h.model.state.getSnapshot()).toMatchObject({ phase: 'connected', issue: undefined }) +}) + +it('counts queued resize frames against the Client buffer and cancels unsent commands on overflow', async () => { + const command: TerminalInput = { type: 'resize', sequence: 1, cols: 90, rows: 25 } + const bytes = encodedFrame(command) + const h = fixture(undefined, inputWindow(bytes)) + vi.mocked(h.remote.environment).mockResolvedValue(success({ ...environment, maxBufferedBytes: 2 * bytes })) + await connected(h.model) + h.model.resize(90, 25) + h.model.resize(91, 25) + await expect.poll(() => h.sent[0]?.length).toBe(1) + h.model.resize(92, 25) + expect(h.model.state.getSnapshot()).toMatchObject({ phase: 'failed', issue: 'inputFull' }) + expect(h.sent[0]).toEqual([command]) +}) + +it('refuses a single escaped input frame larger than the carrier window before sending it', async () => { + const h = fixture(undefined, inputWindow(150)) + await connected(h.model) + h.model.write('\u0001'.repeat(20)) + expect(h.model.state.getSnapshot()).toMatchObject({ phase: 'failed', issue: 'inputFull' }) + expect(h.sent[0]).toEqual([]) +}) + +it('rejects acknowledgements for commands still waiting in the Client queue', async () => { + const h = fixture(undefined, inputWindow(120)) + await connected(h.model) + h.model.write('a') + h.model.write('b') + await expect.poll(() => h.sent[0]?.length).toBe(1) + h.attachments[0]!.push({ type: 'ack', sequence: 2 }) + await expect.poll(() => h.model.state.getSnapshot().issue).toBe('invalidOutput') +}) + +it('drops waiting commands when input is refused and never replays them on a new attachment', async () => { + const h = fixture(undefined, inputWindow(120)) + await connected(h.model) + h.model.write('a') + h.model.write('b') + await expect.poll(() => h.sent[0]?.length).toBe(1) + h.attachments[0]!.push({ type: 'ack', sequence: 1, refusal: 'read-only' }) + await expect.poll(() => h.model.state.getSnapshot().writable).toBe(false) + expect(h.sent[0]).toHaveLength(1) + h.model.connect() + await expect.poll(() => h.attachments.length).toBe(2) + await expect.poll(() => h.model.state.getSnapshot().writable).toBe(true) + acknowledge(h.model) + h.model.write('c') + await expect.poll(() => h.sent[1]).toEqual([{ type: 'write', sequence: 1, data: 'c' }]) +}) diff --git a/packages/api/terminal-controller/tests/recovery.client.spec.ts b/packages/api/terminal-controller/tests/recovery.client.spec.ts index 690dd9bf0d..a3104bd55b 100644 --- a/packages/api/terminal-controller/tests/recovery.client.spec.ts +++ b/packages/api/terminal-controller/tests/recovery.client.spec.ts @@ -16,7 +16,9 @@ import * as TerminalClient from '../src/client/index.ts' const sessionId = 'session' as SessionId const info: WebTerminalInfo = { id: 'terminal' as WebTerminalId, shell: { name: 'zsh', path: '/bin/zsh', args: ['-i'] }, title: 'zsh', cwd: '/workspace', rows: 24, cols: 80, state: 'running', exitCode: null } -const environment: TerminalEnvironment = { cwd: info.cwd, maxInputBytes: 1000, maxCols: 200, maxRows: 100, scrollback: 100 } +const environment: TerminalEnvironment = { + cwd: info.cwd, maxInputBytes: 1000, maxBufferedBytes: 100_000, maxCols: 200, maxRows: 100, scrollback: 100, +} const success = (value: T): RemoteResult => ({ ok: true, value }) const failure = (message: string): RemoteResult => ({ ok: false, error: new RemoteError('gateway/bad-request', message, {}) }) const cleanups: (() => void | Promise)[] = [] @@ -41,9 +43,8 @@ function fixture() { environment: vi.fn(async () => success(environment)), list: vi.fn(async () => success([])), create: vi.fn(async (_session, request) => success({ ...info, id: request.id })), close: vi.fn(async () => success(undefined)), rename: vi.fn(async () => success(undefined)), - write: vi.fn(async () => success(undefined)), resize: vi.fn(async () => success(undefined)), - follow: vi.fn(streamMethod(async function* (_session, id, controllerId, signal) { - yield { type: 'snapshot', sequence: 0, screen: 'retained', info: { ...info, id, controllerId } } + attach: vi.fn(streamMethod(async function* (_session, id, signal) { + yield { type: 'snapshot', writable: true, sequence: 0, screen: 'retained', info: { ...info, id } } await new Promise((resolve) => { if (signal?.aborted) resolve() else signal?.addEventListener('abort', () => { resolve() }, { once: true }) @@ -93,8 +94,8 @@ it('recovers a listed process without creating another, including its title and model.mount() await model.refresh() expect(h.remote.create).not.toHaveBeenCalled() - await expect.poll(() => model.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', screen: 'retained' }) - expect(h.remote.follow).toHaveBeenCalledWith(sessionId, info.id, expect.any(String), expect.any(AbortSignal)) + await expect.poll(() => model.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', writable: true, screen: 'retained' }) + expect(h.remote.attach).toHaveBeenCalledWith(sessionId, info.id, expect.any(AbortSignal)) }) it('does not recreate a recovered terminal that disappeared after the recovery list was shown', async () => { @@ -140,7 +141,7 @@ it('waits for an in-flight creation while close detaches immediately and prevent await starting await closing expect(h.remote.close).toHaveBeenCalledWith(sessionId, info.id) - expect(h.remote.follow).not.toHaveBeenCalled() + expect(h.remote.attach).not.toHaveBeenCalled() }) it('does not allocate after close or disposal overtakes discovery', async () => { @@ -361,7 +362,7 @@ it('restores the same terminal in the same occurrence after reload without openi await restored.refresh() expect(restored.id).toBe(original.id) expect(h.remote.create).toHaveBeenCalledOnce() - await expect.poll(() => restored.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', screen: 'retained' }) + await expect.poll(() => restored.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', writable: true, screen: 'retained' }) }) it('offers retained processes when their saved occurrence is absent from the restored layout', async () => { @@ -490,10 +491,10 @@ it('waits for both active and detached stream finalizers during plugin disposal const finished = [Promise.withResolvers(), Promise.withResolvers()] cleanups.push(() => { for (const barrier of release) barrier.resolve(undefined) }) let index = 0 - vi.mocked(h.remote.follow).mockImplementation(streamMethod(async function* (_session, id, controllerId, signal) { + vi.mocked(h.remote.attach).mockImplementation(streamMethod(async function* (_session, id, signal) { const current = index++ try { - yield { type: 'snapshot', sequence: 0, screen: 'screen', info: { ...info, id, controllerId } } + yield { type: 'snapshot', writable: true, sequence: 0, screen: 'screen', info: { ...info, id } } await new Promise((resolve) => { if (signal?.aborted) resolve() else signal?.addEventListener('abort', () => { resolve() }, { once: true }) @@ -611,7 +612,7 @@ it('retains only open saved occurrences across inactive Sessions and deduplicate expect(h.remote.environment).not.toHaveBeenCalled() expect(h.remote.create).not.toHaveBeenCalled() expect(h.remote.list).not.toHaveBeenCalled() - expect(h.remote.follow).not.toHaveBeenCalled() + expect(h.remote.attach).not.toHaveBeenCalled() const calls = vi.mocked(h.remote.retain).mock.calls service.retainTabs([{ sessionId: otherSession, tabId: 'b', contentId: 'b' }]) await expect.poll(() => calls.find(call => call[0] === sessionId)?.[2]?.aborted).toBe(true) @@ -639,7 +640,7 @@ it('waits for the window hold acknowledgement before restoring an output attachm const model = service.view(sessionId, 'restored', 'restored') model.mount() await model.refresh() - expect(h.remote.follow).not.toHaveBeenCalled() + expect(h.remote.attach).not.toHaveBeenCalled() acknowledge.resolve(undefined) await expect.poll(() => model.state.getSnapshot().writable).toBe(true) expect(h.remote.retain).toHaveBeenCalledOnce() @@ -657,7 +658,7 @@ it('shows a missing terminal when retention loses the race to Host cleanup, with const model = service.view(sessionId, 'restored', 'restored') model.mount() await expect.poll(() => model.state.getSnapshot().issue).toBe('missingTerminal') - expect(h.remote.follow).not.toHaveBeenCalled() + expect(h.remote.attach).not.toHaveBeenCalled() expect(h.remote.create).not.toHaveBeenCalled() }) diff --git a/packages/api/terminal-controller/tests/stream.spec.ts b/packages/api/terminal-controller/tests/stream.spec.ts index a5fd9357ff..8a928378b7 100644 --- a/packages/api/terminal-controller/tests/stream.spec.ts +++ b/packages/api/terminal-controller/tests/stream.spec.ts @@ -78,3 +78,20 @@ describe('TerminalFollower', () => { expect(await follower.read(signal())[Symbol.asyncIterator]().next()).toEqual({ done: true, value: undefined }) }) }) + +it('does not replace an ended attachment with a late input failure', async () => { + const follower = new TerminalFollower(1000) + follower.close() + follower.fail(new Error('late write failed')) + expect(await follower.read(signal())[Symbol.asyncIterator]().next()).toEqual({ done: true, value: undefined }) +}) + +it('drains final frames when an input failure arrives after graceful finish', async () => { + const follower = new TerminalFollower(1000) + follower.push(frame) + follower.finish() + follower.fail(new Error('late write failed')) + const received: TerminalFrame[] = [] + for await (const item of follower.read(signal())) received.push(item) + expect(received).toEqual([frame]) +}) diff --git a/packages/api/terminal-controller/tests/terminal.spec.ts b/packages/api/terminal-controller/tests/terminal.spec.ts index 9735701b81..8881f18774 100644 --- a/packages/api/terminal-controller/tests/terminal.spec.ts +++ b/packages/api/terminal-controller/tests/terminal.spec.ts @@ -3,11 +3,11 @@ import { PassThrough } from 'node:stream' import { afterEach, describe, expect, it, vi } from 'vitest' import type { SubprocessOutcome, SubprocessTerminalHandle } from '@deepseek-ai/dsh-subprocess' import { BrowserTerminal } from '../src/terminal.ts' +import { inputChannel } from './input.ts' import { TerminalFollower } from '../src/stream.ts' -import type { TerminalAttachmentId, TerminalFrame, WebTerminalId, WebTerminalInfo } from '../src/types.ts' +import type { TerminalInput, TerminalFrame, WebTerminalId, WebTerminalInfo } from '../src/types.ts' const info: WebTerminalInfo = { id: 'terminal-test' as WebTerminalId, title: 'bash', shell: { path: '/bin/bash', name: 'bash', args: ['-i'] }, cwd: '/workspace', cols: 80, rows: 24, state: 'running', exitCode: null } -const attachment = (id: string): TerminalAttachmentId => id as TerminalAttachmentId const cleanups: (() => Promise)[] = [] afterEach(async () => { await Promise.all(cleanups.splice(0).map(close => close())) }) @@ -26,12 +26,14 @@ function fixture() { return { terminal, output, outcome, handle } } -async function attach(terminal: BrowserTerminal, id = 'first') { +async function attach(terminal: BrowserTerminal) { const controller = new AbortController() - const iterator = terminal.follow(attachment(id), controller.signal)[Symbol.asyncIterator]() + const input = inputChannel() + const frames = terminal.attach(input.source, { maxInputBytes: 1000, maxCols: 200, maxRows: 100 }, controller.signal) + const iterator = frames[Symbol.asyncIterator]() const baseline = await readFrame(iterator) cleanups.push(async () => { controller.abort(); await iterator.return?.() }) - return { controller, iterator, baseline } + return { controller, iterator, baseline, input } } describe('BrowserTerminal', () => { @@ -46,7 +48,7 @@ describe('BrowserTerminal', () => { expect(handle.terminate).not.toHaveBeenCalled() output.write(Buffer.from('world')) await expect.poll(() => terminal.info.state).toBe('running') - const second = await attach(terminal, 'second') + const second = await attach(terminal) // The baseline and its output queue share the same ordered screen write queue. const frames = [second.baseline] if (second.baseline.type === 'snapshot' && !second.baseline.screen.includes('world')) frames.push(await readFrame(second.iterator)) @@ -55,26 +57,6 @@ describe('BrowserTerminal', () => { expect(handle.terminate).not.toHaveBeenCalled() }) - it('preserves split UTF-8, gives the newest attachment input, and resizes both PTY and recovery screen', async () => { - const { terminal, output, handle } = fixture() - const first = await attach(terminal) - const encoded = Buffer.from('终端') - output.write(encoded.subarray(0, 2)) - await expect.poll(() => output.readableLength).toBe(0) - output.write(encoded.subarray(2)) - expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: '终端' }) - const second = await attach(terminal, 'second') - await expect(terminal.write(attachment('first'), 'ignored')).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'read-only' } }) - await terminal.write(attachment('second'), '\t') - expect(handle.write).toHaveBeenCalledWith('\t') - await terminal.resize(attachment('second'), 100, 30) - expect(handle.resize).toHaveBeenCalledWith(100, 30) - expect(terminal.info).toMatchObject({ cols: 100, rows: 30 }) - second.controller.abort() - await second.iterator.return?.() - expect(terminal.info.controllerId).toBeUndefined() - }) - it('keeps exit facts and screen until explicit cleanup and never starts a replacement process', async () => { const { terminal, output, outcome, handle } = fixture() const first = await attach(terminal) @@ -83,7 +65,7 @@ describe('BrowserTerminal', () => { expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: 'done' }) expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', info: { state: 'exited', exitCode: 7 } }) expect(handle.terminate).not.toHaveBeenCalled() - const second = await attach(terminal, 'second') + const second = await attach(terminal) expect(second.baseline).toMatchObject({ type: 'snapshot', info: { state: 'exited', exitCode: 7 } }) await terminal.close() expect(handle.terminate).toHaveBeenCalledOnce() @@ -102,72 +84,6 @@ describe('BrowserTerminal', () => { expect((await first.iterator.next()).done).toBe(true) }) - it('rejects input before attachment, during close and after process exit', async () => { - const { terminal, handle, output, outcome } = fixture() - await expect(terminal.write(attachment('first'), 'ignored')).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'read-only' } }) - const first = await attach(terminal) - output.end() - outcome.resolve({ exitCode: 0, signal: null }) - expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', info: { state: 'exited' } }) - await expect(terminal.write(attachment('first'), 'ignored')).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'not-running' } }) - await expect(terminal.resize(attachment('first'), 100, 30)).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'not-running' } }) - const closing = terminal.close() - await expect(terminal.write(attachment('first'), 'ignored')).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'not-running' } }) - await closing - expect(handle.write).not.toHaveBeenCalled() - expect(handle.resize).not.toHaveBeenCalled() - }) - - it('preserves the input controller when an older follower detaches', async () => { - const { terminal, handle } = fixture() - const first = await attach(terminal) - const second = await attach(terminal, 'second') - first.controller.abort() - await first.iterator.return?.() - expect(terminal.info.controllerId).toBe(attachment('second')) - terminal.rename('build output') - expect(await readFrame(second.iterator)).toMatchObject({ type: 'state', info: { title: 'build output', controllerId: 'second' } }) - await terminal.write(attachment('second'), 'pwd\r') - expect(handle.write).toHaveBeenCalledWith('pwd\r') - }) - - it('does not grant input to attachments cancelled before their snapshot is ready', async () => { - const { terminal, handle } = fixture() - const aborted = new AbortController() - aborted.abort(new Error('already detached')) - await expect(terminal.follow(attachment('cancelled'), aborted.signal)[Symbol.asyncIterator]().next()).rejects.toThrow('already detached') - await attach(terminal) - const writing = Promise.withResolvers() - const written = Promise.withResolvers() - handle.write.mockImplementationOnce(async () => { writing.resolve(undefined); await written.promise }) - const pendingWrite = terminal.write(attachment('first'), 'pwd\r') - try { - await writing.promise - const abort = new AbortController() - const pendingAttachment = terminal.follow(attachment('late'), abort.signal)[Symbol.asyncIterator]().next() - const rejected = expect(pendingAttachment).rejects.toThrow('detached while waiting') - abort.abort(new Error('detached while waiting')) - written.resolve(undefined) - await pendingWrite - await rejected - expect(terminal.info.controllerId).toBe(attachment('first')) - } finally { written.resolve(undefined) } - }) - - it('continues accepting operations after a provider write or resize fails', async () => { - const { terminal, handle } = fixture() - await attach(terminal) - handle.write.mockRejectedValueOnce(new Error('input transport failed')) - handle.resize.mockRejectedValueOnce(new Error('resize transport failed')) - await expect(terminal.write(attachment('first'), 'failed')).rejects.toThrow('input transport failed') - await expect(terminal.resize(attachment('first'), 100, 30)).rejects.toThrow('resize transport failed') - expect(terminal.info).toMatchObject({ cols: 80, rows: 24 }) - await terminal.write(attachment('first'), 'accepted') - await terminal.resize(attachment('first'), 90, 25) - expect(handle.write).toHaveBeenLastCalledWith('accepted') - expect(terminal.info).toMatchObject({ cols: 90, rows: 25 }) - }) - it.each([new Error('process wait failed'), 'remote process wait failed'])('publishes a failed process outcome and retains its recovery screen: %s', async (failure) => { const { terminal, output, outcome } = fixture() const first = await attach(terminal) @@ -175,7 +91,7 @@ describe('BrowserTerminal', () => { outcome.reject(failure) expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: 'last output' }) expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', info: { state: 'failed', error: failure instanceof Error ? failure.message : failure } }) - const second = await attach(terminal, 'second') + const second = await attach(terminal) expect(second.baseline).toMatchObject({ type: 'snapshot', screen: 'last output', info: { state: 'failed' } }) }) @@ -205,12 +121,13 @@ describe('BrowserTerminal', () => { it('shares concurrent close attempts and permits retry after termination fails', async () => { const { terminal, handle } = fixture() - await attach(terminal) + const view = await attach(terminal) handle.terminate.mockRejectedValueOnce(new Error('process range remains alive')) const first = terminal.close() expect(terminal.close()).toBe(first) await expect(first).rejects.toThrow('remains alive') - await terminal.write(attachment('first'), 'retry cleanup next') + view.input.push({ type: 'write', sequence: 1, data: 'retry cleanup next' }) + expect(await readFrame(view.iterator)).toMatchObject({ type: 'ack', sequence: 1 }) await terminal.close() expect(handle.terminate).toHaveBeenCalledTimes(2) }) @@ -234,3 +151,181 @@ it('refuses retention before allocation commit and disposes an uncommitted scree await terminal.dispose() expect(handle.terminate).toHaveBeenCalledOnce() }) + +it('preserves split UTF-8 and gives input control only to the newest attachment', async () => { + const { terminal, output, handle } = fixture() + const first = await attach(terminal) + const encoded = Buffer.from('终端') + output.write(encoded.subarray(0, 2)) + await expect.poll(() => output.readableLength).toBe(0) + output.write(encoded.subarray(2)) + expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: '终端' }) + const second = await attach(terminal) + expect(second.baseline).toMatchObject({ writable: true }) + expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', writable: false }) + first.input.push({ type: 'write', sequence: 1, data: 'refused' }) + expect(await readFrame(first.iterator)).toEqual({ type: 'ack', sequence: 1, refusal: 'read-only' }) + second.input.push({ type: 'write', sequence: 1, data: '\t' }) + expect(await readFrame(second.iterator)).toEqual({ type: 'ack', sequence: 1 }) + expect(handle.write).toHaveBeenCalledExactlyOnceWith('\t') + first.controller.abort() + await first.iterator.return?.() + second.input.push({ type: 'resize', sequence: 2, cols: 100, rows: 30 }) + expect(await readFrame(second.iterator)).toMatchObject({ type: 'state', writable: true, info: { cols: 100, rows: 30 } }) + expect(await readFrame(second.iterator)).toEqual({ type: 'ack', sequence: 2 }) + expect(handle.resize).toHaveBeenCalledWith(100, 30) +}) + +it('acknowledges provider acceptance in order and joins in-flight input on detach', async () => { + const { terminal, handle } = fixture() + const view = await attach(terminal) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + handle.write.mockImplementationOnce(async () => { entered.resolve(undefined); await release.promise }) + cleanups.push(async () => { release.resolve(undefined) }) + view.input.push({ type: 'write', sequence: 1, data: 'accepted' }) + view.input.push({ type: 'write', sequence: 2, data: 'cancelled' }) + view.input.push({ type: 'resize', sequence: 3, cols: 100, rows: 30 }) + await entered.promise + expect(handle.write).toHaveBeenCalledOnce() + expect(handle.resize).not.toHaveBeenCalled() + view.controller.abort() + let detached = false + const closing = view.iterator.return?.().then(() => { detached = true }) + await Promise.resolve() + expect(detached).toBe(false) + release.resolve(undefined) + await closing + expect(handle.write).toHaveBeenCalledExactlyOnceWith('accepted') + expect(handle.resize).not.toHaveBeenCalled() + expect(handle.terminate).not.toHaveBeenCalled() +}) + +it('half-closes input while continuing to publish output and exit state', async () => { + const { terminal, output, outcome } = fixture() + const view = await attach(terminal) + view.input.push({ type: 'write', sequence: 1, data: 'exit\r' }) + view.input.end() + expect(await readFrame(view.iterator)).toEqual({ type: 'ack', sequence: 1 }) + output.end('last output') + outcome.resolve({ exitCode: 3, signal: null }) + expect(await readFrame(view.iterator)).toMatchObject({ type: 'output', data: 'last output' }) + expect(await readFrame(view.iterator)).toMatchObject({ type: 'state', writable: false, info: { exitCode: 3 } }) +}) + +it.each([ + { type: 'write', sequence: 2, data: 'gap' }, + { type: 'write', sequence: 1, data: '界'.repeat(334) }, + { type: 'resize', sequence: 1, cols: 201, rows: 24 }, + { type: 'resize', sequence: 1, cols: 80, rows: 0 }, + { type: 'resize', sequence: 1, cols: 1.5, rows: 24 }, +] satisfies TerminalInput[])('rejects invalid input before executing it: %j', async (command) => { + const { terminal, handle } = fixture() + const view = await attach(terminal) + view.input.push(command) + await expect(view.iterator.next()).rejects.toThrow() + expect(handle.write).not.toHaveBeenCalled() + expect(handle.resize).not.toHaveBeenCalled() + expect(handle.terminate).not.toHaveBeenCalled() +}) + +it.each(['write', 'resize'] as const)('fails the attachment on a provider %s error and permits fresh attachment recovery', async (operation) => { + const { terminal, handle } = fixture() + const first = await attach(terminal) + handle[operation].mockRejectedValueOnce(new Error('provider failed')) + first.input.push(operation === 'write' ? { type: 'write', sequence: 1, data: 'failed' } : { type: 'resize', sequence: 1, cols: 90, rows: 25 }) + await expect(first.iterator.next()).rejects.toThrow('provider failed') + expect(terminal.info).toMatchObject({ cols: 80, rows: 24 }) + const second = await attach(terminal) + second.input.push({ type: 'write', sequence: 1, data: 'fresh' }) + expect(await readFrame(second.iterator)).toEqual({ type: 'ack', sequence: 1 }) + expect(handle.write).toHaveBeenLastCalledWith('fresh') +}) + +it.each(['write', 'resize'] as const)('preserves final output when an in-flight %s is refused during process exit', async (operation) => { + const { terminal, handle, output, outcome } = fixture() + const view = await attach(terminal) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + cleanups.push(async () => { release.resolve(undefined) }) + handle[operation].mockImplementationOnce(async () => { entered.resolve(undefined); await release.promise }) + view.input.push(operation === 'write' ? { type: 'write', sequence: 1, data: 'late' } : { type: 'resize', sequence: 1, cols: 90, rows: 25 }) + await entered.promise + outcome.resolve({ exitCode: 7, signal: null }) + output.end('FINAL OUTPUT') + release.reject(new Error('terminal process has exited')) + const frames = [await readFrame(view.iterator), await readFrame(view.iterator), await readFrame(view.iterator)] + expect(frames).toEqual(expect.arrayContaining([ + { type: 'ack', sequence: 1, refusal: 'not-running' }, + expect.objectContaining({ type: 'output', data: 'FINAL OUTPUT' }), + ])) + expect(frames.find(frame => frame.type === 'state')).toMatchObject({ writable: false, info: { state: 'exited', exitCode: 7 } }) +}) + +it('refuses queued input once the process completes while output is still draining', async () => { + const { terminal, handle, output, outcome } = fixture() + const view = await attach(terminal) + outcome.resolve({ exitCode: 0, signal: null }) + await outcome.promise + expect(terminal.info.state).toBe('running') + view.input.push({ type: 'write', sequence: 1, data: 'late' }) + expect(await readFrame(view.iterator)).toEqual({ type: 'ack', sequence: 1, refusal: 'not-running' }) + expect(handle.write).not.toHaveBeenCalled() + output.end('FINAL OUTPUT') + expect(await readFrame(view.iterator)).toMatchObject({ type: 'output', data: 'FINAL OUTPUT' }) + expect(await readFrame(view.iterator)).toMatchObject({ type: 'state', writable: false, info: { state: 'exited' } }) +}) + +it('refuses input after exit without ending the screen attachment', async () => { + const { terminal, output, outcome, handle } = fixture() + const view = await attach(terminal) + output.end() + outcome.resolve({ exitCode: 0, signal: null }) + expect(await readFrame(view.iterator)).toMatchObject({ type: 'state', writable: false }) + view.input.push({ type: 'write', sequence: 1, data: 'late' }) + expect(await readFrame(view.iterator)).toEqual({ type: 'ack', sequence: 1, refusal: 'not-running' }) + terminal.rename('finished') + expect(await readFrame(view.iterator)).toMatchObject({ type: 'state', info: { title: 'finished' } }) + expect(handle.write).not.toHaveBeenCalled() +}) + +it('does not grant input to an attachment cancelled before its screen baseline', async () => { + const { terminal } = fixture() + const input = inputChannel() + const abort = new AbortController() + abort.abort(new Error('already detached')) + await expect(terminal.attach(input.source, { maxInputBytes: 1000, maxCols: 200, maxRows: 100 }, abort.signal)[Symbol.asyncIterator]().next()).rejects.toThrow('already detached') +}) + +it('reports a non-Error provider input rejection through the attachment', async () => { + const { terminal, handle } = fixture() + const view = await attach(terminal) + handle.write.mockRejectedValueOnce('remote input failed') + view.input.push({ type: 'write', sequence: 1, data: 'input' }) + await expect(view.iterator.next()).rejects.toThrow('remote input failed') +}) + +it('preserves the current controller when a queued attachment is cancelled during an input write', async () => { + const { terminal, handle } = fixture() + const first = await attach(terminal) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + cleanups.push(async () => { release.resolve(undefined) }) + handle.write.mockImplementationOnce(async () => { entered.resolve(undefined); await release.promise }) + first.input.push({ type: 'write', sequence: 1, data: 'first' }) + await entered.promise + const abort = new AbortController() + const input = inputChannel() + const iterator = terminal.attach(input.source, { maxInputBytes: 1000, maxCols: 200, maxRows: 100 }, abort.signal)[Symbol.asyncIterator]() + cleanups.push(async () => { abort.abort(); await iterator.return?.() }) + const failed = expect(iterator.next()).rejects.toThrow('cancelled while queued') + abort.abort(new Error('cancelled while queued')) + release.resolve(undefined) + await failed + expect(await readFrame(first.iterator)).toEqual({ type: 'ack', sequence: 1 }) + terminal.rename('retained control') + expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', writable: true }) + first.input.push({ type: 'write', sequence: 2, data: 'still writable' }) + expect(await readFrame(first.iterator)).toEqual({ type: 'ack', sequence: 2 }) + expect(handle.write).toHaveBeenLastCalledWith('still writable') +}) diff --git a/packages/api/terminal-controller/tsconfig.client.json b/packages/api/terminal-controller/tsconfig.client.json index cdb554988a..055e471ad7 100644 --- a/packages/api/terminal-controller/tsconfig.client.json +++ b/packages/api/terminal-controller/tsconfig.client.json @@ -35,6 +35,9 @@ }, { "path": "../../util/crypto" + }, + { + "path": "../../util/deque" } ] } diff --git a/packages/api/terminal-controller/tsconfig.host.json b/packages/api/terminal-controller/tsconfig.host.json index 68bc1a559e..952e7df4b2 100644 --- a/packages/api/terminal-controller/tsconfig.host.json +++ b/packages/api/terminal-controller/tsconfig.host.json @@ -55,6 +55,9 @@ }, { "path": "../../util/lazy-require" + }, + { + "path": "../../util/values" } ] } 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/README.i18n.yaml b/packages/api/workspace-controller/README.i18n.yaml index d804399b83..e3cb08a719 100644 --- a/packages/api/workspace-controller/README.i18n.yaml +++ b/packages/api/workspace-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 4e53164159b5ce41 zh: 89582dc0294d0776 /workspace-controller/use-this-package: - en: aa0d93826ab685fe - zh: 144e48d49020f5a4 + en: 8276c5edb7d0db7d + zh: cda0c91f8c3776e6 /workspace-controller/use-this-package/first-use-workspace: en: 61032e060e7213f0 zh: 437eb982a8738539 diff --git a/packages/api/workspace-controller/README.md b/packages/api/workspace-controller/README.md index b24053384f..27c26c7d9b 100644 --- a/packages/api/workspace-controller/README.md +++ b/packages/api/workspace-controller/README.md @@ -24,6 +24,8 @@ English | [中文](README.zh.md) The Host controller serializes mutations whose correctness depends on current registry state and throws `RemoteError` with a stable error code for expected failures. Its `follow()` stream synchronously attaches to durable Workspace changes, emits one complete baseline first, then emits ordered `upsert`, `remove`, `order`, `archived`, and `pinned` increments. Archive and pin sets are Session id arrays, with the most recently pinned id first in the pin array. A reconnect starts another generation with a replacement baseline, so consumers do not depend on receiving every increment while disconnected. `archiveSession` without `stopActivity` refuses a Session with running work as `workspace/session-active`, whose details list that work by family (`turn`, `subagent`, `job`, `schedule`) with item ids and labels; with `stopActivity: true` the registry's providers stop the work first and the response arrives once the archive set is durable, while the stops settle in the background. +The controller injects `remoteAccess` and registers the `workspace` resource kind with the default field `workspaceId` through `typert.resources`. `workspace/follow` reads no resource, so its call touches the `global` resource: a Peer whose principal is not the owner may follow it only when its principal kind's policy in [`dsh-api-remote-access`](../remote-access/README.md) binds a `global` role listing the action. For that caller, the baseline, `upsert` frames, and `order` ids keep only the Workspaces `ctx.remoteAccess.allows()` admits as `workspace` resources, and only the Session ids it admits as `session` resources, within each Workspace and in the archived and pinned sets, so `workspace` and `session` roles list the same action. The stream tracks the Workspaces it delivered. When one is no longer admitted at its next change or in a new order, the stream sends a `replace` increment carrying the complete filtered state instead of a `remove`, because a removed id is never resurrected on the Client; `replace` is an ordinary increment that the Client applies like an opening baseline, not the start of a new generation, so it neither reports an error nor reconnects; once access returns, the Workspace reappears through an ordinary `upsert`. A `remove` frame reports a deletion and reaches only a caller that received that Workspace. Owner frames are unfiltered. + The Client entry provides `ClientWorkspaceModel` and `createWorkspaceStateStream()`. The model owns Workspace rows, registry order, archived and pinned Session identities, unary mutation echoes, and stream/unary race resolution. A newer Host row wins by `updatedAt`; a committed stream order outranks an older unary response; a removed Workspace id cannot be resurrected by delayed data. Pin snapshots change only when their identities or order change. The package exposes framework-neutral snapshots and subscriptions, leaving navigation policy and React hooks to the UI owner. `WorkspaceController.archiveSession(sessionId, { stopActivity })` throws `WorkspaceArchiveError` with the Host's `rpcError`, so a surface can tell the running-work refusal from a missing Session or a carrier fault and offer to stop the work. diff --git a/packages/api/workspace-controller/README.zh.md b/packages/api/workspace-controller/README.zh.md index dc240950cc..4772d0c9b1 100644 --- a/packages/api/workspace-controller/README.zh.md +++ b/packages/api/workspace-controller/README.zh.md @@ -24,6 +24,8 @@ kind: "package-reference" Host 控制器会串行执行正确性取决于当前注册表状态的变更,并为预期失败抛出带有稳定错误码的 `RemoteError`。它的 `follow()` 流会同步订阅持久 Workspace 变更,先发出一份完整 baseline,再按顺序发出 `upsert`、`remove`、`order`、`archived` 和 `pinned` 增量。归档与置顶集合都是会话 id 数组,置顶数组把最近置顶的 id 放在前面。重连会以替换 baseline 开始新一代,因此消费方不依赖收到断线期间的每个增量。不带 `stopActivity` 的 `archiveSession` 会以 `workspace/session-active` 拒绝仍有工作在跑的会话,其 details 按族(`turn`、`subagent`、`job`、`schedule`)列出这些工作及各项的 id 与名称;带 `stopActivity: true` 时注册表的提供方先停止这些工作,归档集合持久化后即返回响应,停止在后台收敛。 +控制器注入 `remoteAccess`,并经 `typert.resources` 以默认字段 `workspaceId` 登记 `workspace` 资源种类。`workspace/follow` 不读取资源,其调用访问 `global` 资源:principal 不是 owner 的 Peer 只有在其 principal kind 于 [`dsh-api-remote-access`](../remote-access/README.zh.md) 中的 policy 绑定了列出该 action 的 `global` role 时才能订阅它。对这类调用方,baseline、`upsert` 帧与 `order` 中的 id 只保留 `ctx.remoteAccess.allows()` 作为 `workspace` 资源允许的 Workspace,以及它作为 `session` 资源允许的会话 id(各 Workspace 内的会话以及归档与置顶集合),因此 `workspace` role 与 `session` role 也列出同一 action。流记录已下发的 Workspace。某个 Workspace 在下一次变化或新顺序中已不被允许时,流发送一个携带完整过滤后状态的 `replace` 增量帧而不是 `remove`,因为 Client 不会复活已移除的 id;`replace` 是普通增量帧,Client 像开场 baseline 一样整体替换状态,但它不开启新的一代,因此既不报告错误也不重连;访问恢复后,该 Workspace 经普通 `upsert` 重新出现。`remove` 帧表示删除,只发给收到过该 Workspace 的调用方。owner 的帧不过滤。 + Client 入口提供 `ClientWorkspaceModel` 和 `createWorkspaceStateStream()`。该模型拥有 Workspace 行、registry 顺序、归档与置顶会话身份、一元变更回显,以及流与一元调用的竞态处理。较新的 Host 行按 `updatedAt` 获胜;已提交的流顺序优先于较旧的一元响应;已经移除的 Workspace id 不会被延迟数据复活。置顶快照仅在会话身份或顺序变化时更新。该包公开与框架无关的快照和订阅,把导航策略与 React 钩子留给 UI owner。`WorkspaceController.archiveSession(sessionId, { stopActivity })` 抛出携带 Host `rpcError` 的 `WorkspaceArchiveError`,界面因此能区分"仍有工作在跑"的拒绝与会话缺失或载体故障,并提议停止这些工作。 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 67844bcfe3..c86b438d85 100644 --- a/packages/api/workspace-controller/package.json +++ b/packages/api/workspace-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-workspace-controller", "description": "Workspace Remote commands and reconnect-safe state transport", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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", @@ -76,7 +78,7 @@ "@deepseek-ai/dsh-deque": "workspace:*", "@deepseek-ai/dsh-native-command": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -91,6 +93,7 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", diff --git a/packages/api/workspace-controller/src/client/index.ts b/packages/api/workspace-controller/src/client/index.ts index c3182102a7..3bbf4670a0 100644 --- a/packages/api/workspace-controller/src/client/index.ts +++ b/packages/api/workspace-controller/src/client/index.ts @@ -98,6 +98,9 @@ export function createWorkspaceStateStream( function acceptIncrement(accept: WorkspaceFollowSink, frame: WorkspaceFollowIncrement): void { switch (frame.type) { + case 'replace': + accept.replaceBaseline(frame.value) + return case 'upsert': accept.upsertView(frame.workspace) return diff --git a/packages/api/workspace-controller/src/feed.ts b/packages/api/workspace-controller/src/feed.ts index 709f17fa5d..be1cbdb21c 100644 --- a/packages/api/workspace-controller/src/feed.ts +++ b/packages/api/workspace-controller/src/feed.ts @@ -15,6 +15,9 @@ import type { WorkspaceView, } from './types.ts' +/** The frames the feed produces: every follow frame except `replace`, which only access filtering sends. */ +type WorkspaceFeedFrame = Exclude + /** * Project one authoritative Workspace entity into its Remote value. * @param workspace - authoritative registry entity. @@ -82,7 +85,7 @@ export class WorkspaceFeed { * @param signal - generation cancellation. * @returns baseline followed by ordered Workspace increments. */ - async *follow(signal: AbortSignal): AsyncIterable { + async *follow(signal: AbortSignal): AsyncIterable { signal.throwIfAborted() const follower = new WorkspaceFollower() this.followers.add(follower) @@ -138,7 +141,7 @@ export class WorkspaceFeed { }) } - private publish(frame: Exclude): void { + private publish(frame: Exclude): void { for (const follower of this.followers) follower.push(frame) } } @@ -148,11 +151,11 @@ function sameStrings(left: readonly string[], right: readonly string[]): boolean } class WorkspaceFollower { - private readonly frames = new Deque() + private readonly frames = new Deque() private waiting: (() => void) | undefined private closed = false - push(frame: WorkspaceFollowFrame): void { + push(frame: WorkspaceFeedFrame): void { /* v8 ignore next -- closed followers are removed before later publication can reach them. */ if (this.closed) return this.frames.pushBack(frame) @@ -165,7 +168,7 @@ class WorkspaceFollower { this.waiting?.() } - async *read(signal: AbortSignal): AsyncIterable { + async *read(signal: AbortSignal): AsyncIterable { while (!this.closed && !signal.aborted) { const frame = this.frames.popFront() if (frame !== undefined) { diff --git a/packages/api/workspace-controller/src/index.ts b/packages/api/workspace-controller/src/index.ts index 0b23517921..f275eb3d12 100644 --- a/packages/api/workspace-controller/src/index.ts +++ b/packages/api/workspace-controller/src/index.ts @@ -3,6 +3,8 @@ import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import type {} from '@deepseek-ai/dsh-api-remote-access' +import type { SessionId } from '@deepseek-ai/dsh-session/types' import { WorkspaceCommands } from './commands.ts' import { DirectoryPickerController } from './directory-picker.ts' import { WorkspaceFeed, workspaceView } from './feed.ts' @@ -10,11 +12,13 @@ import { defaultWorkspaceDirectory, validateDocumentsDirectory } from './default import type { WorkspaceArchiveSessionRequest, WorkspaceArchiveValue, + WorkspaceBaseline, WorkspaceCreateRequest, WorkspaceCreateValue, WorkspaceDeleteRequest, WorkspaceDeleteValue, WorkspaceFollowFrame, + WorkspaceId, WorkspaceInsertBeforeRequest, WorkspaceInsertSessionBeforeRequest, WorkspaceOrderValue, @@ -49,7 +53,7 @@ declare module '@deepseek-ai/cordis' { /** Host service backing the generated `ctx.remote.workspace` namespace. */ export class WorkspaceController extends TypertRemoteService { - static inject = ['typert', 'workspaceRegistry'] + static inject = ['remoteAccess', 'typert', 'workspaceRegistry'] static Config: z = z.object({ documentsDirectory: z.string(), @@ -66,6 +70,7 @@ export class WorkspaceController extends TypertRemoteService { */ constructor(ctx: Context, config: Config = {}) { super(ctx, 'workspaceController', { namespace: 'workspace' }) + ctx.typert.resources.register('workspace', { field: 'workspaceId' }) this.config = WorkspaceController.Config(config) if (this.config.documentsDirectory !== undefined) validateDocumentsDirectory(this.config.documentsDirectory) this.commands = new WorkspaceCommands(ctx) @@ -187,14 +192,77 @@ export class WorkspaceController extends TypertRemoteService { } /** - * Stream a complete Workspace baseline followed by ordered increments. + * Stream a complete Workspace baseline followed by ordered increments. A + * non-owner receives only the Workspaces and Sessions `allows()` admits. + * When a delivered Workspace is no longer admitted at its next change or + * the next order change, the stream sends a `replace` frame with the + * complete filtered state instead of a `remove`, because a Client never + * resurrects a removed Workspace; a `remove` frame reports a deletion and + * reaches only a Client that received that Workspace. * @param signal - generation cancellation. * @returns baseline followed by ordered Workspace increments. */ @Remote({ mode: 'stream' }) - follow(signal: AbortSignal): AsyncIterable { - return this.feed.follow(signal) + async *follow(signal: AbortSignal): AsyncIterable { + const access = this.ctx.remoteAccess + const visible = (workspaceId: WorkspaceId): boolean => access.allows({ kind: 'workspace', id: workspaceId }) + const sessions = (sessionIds: readonly SessionId[]): SessionId[] => + sessionIds.filter(sessionId => access.allows({ kind: 'session', id: sessionId })) + /** Workspaces this generation has delivered and not yet removed. */ + const delivered = new Set() + /** The admitted part of `value`; it becomes the delivered set. */ + const filtered = (value: WorkspaceBaseline): WorkspaceBaseline => { + const items = value.items.filter(item => visible(item.workspaceId)) + delivered.clear() + for (const item of items) delivered.add(item.workspaceId) + return { + items: items.map(item => ({ ...item, sessionIds: sessions(item.sessionIds) })), + archivedSessionIds: sessions(value.archivedSessionIds), + pinnedSessionIds: sessions(value.pinnedSessionIds), + } + } + for await (const frame of this.feed.follow(signal)) { + switch (frame.type) { + case 'baseline': + yield { type: 'baseline', value: filtered(frame.value) } + break + case 'upsert': { + const workspaceId = frame.workspace.workspaceId + if (visible(workspaceId)) { + delivered.add(workspaceId) + yield { type: 'upsert', workspace: { ...frame.workspace, sessionIds: sessions(frame.workspace.sessionIds) } } + } else if (delivered.has(workspaceId)) { + yield { type: 'replace', value: filtered(this.feed.baseline()) } + } + break + } + case 'remove': + if (delivered.delete(frame.workspaceId)) yield frame + break + case 'order': + if (frame.workspaceIds.some(workspaceId => delivered.has(workspaceId) && !visible(workspaceId))) { + yield { type: 'replace', value: filtered(this.feed.baseline()) } + } else { + yield { type: 'order', workspaceIds: frame.workspaceIds.filter(visible) } + } + break + case 'archived': + yield { type: 'archived', archivedSessionIds: sessions(frame.archivedSessionIds) } + break + case 'pinned': + yield { type: 'pinned', pinnedSessionIds: sessions(frame.pinnedSessionIds) } + break + /* v8 ignore next -- closed follow-frame union. */ + default: + assertNever(frame) + } + } } } +/* v8 ignore next 3 -- closed-union backstop. */ +function assertNever(value: never): never { + throw new Error(`unreachable Workspace follow frame: ${JSON.stringify(value)}`) +} + export default WorkspaceController diff --git a/packages/api/workspace-controller/src/types.ts b/packages/api/workspace-controller/src/types.ts index d5b98746be..cdf9adf073 100644 --- a/packages/api/workspace-controller/src/types.ts +++ b/packages/api/workspace-controller/src/types.ts @@ -157,8 +157,13 @@ export interface WorkspaceBaseline { readonly pinnedSessionIds: readonly SessionId[] } -/** One ordered Workspace change after a generation's baseline. */ +/** + * One ordered Workspace change after a generation's baseline. `replace` + * carries the complete state that supersedes everything delivered before it + * in the generation; it is a change, not a new generation's opening frame. + */ export type WorkspaceFollowIncrement = + | { readonly type: 'replace'; readonly value: WorkspaceBaseline } | { readonly type: 'upsert'; readonly workspace: WorkspaceView } | { readonly type: 'remove'; readonly workspaceId: WorkspaceId } | { readonly type: 'order'; readonly workspaceIds: readonly WorkspaceId[] } diff --git a/packages/api/workspace-controller/tests/transport.client.spec.ts b/packages/api/workspace-controller/tests/transport.client.spec.ts index b74ddfb394..b1d6ca2a9b 100644 --- a/packages/api/workspace-controller/tests/transport.client.spec.ts +++ b/packages/api/workspace-controller/tests/transport.client.spec.ts @@ -183,6 +183,38 @@ describe('Workspace state stream', () => { expect(streamStates(mock)).toEqual(['cancelled']) }) + it('applies a replace increment in place, so a Workspace hidden and shown again never errors or reconnects', async ({ mock, start }) => { + const { remote } = await gatewayClient(mock, start) + mock.stream(FOLLOW, openStream([baseline('one', 'two')])) + const model = new ClientWorkspaceModel(remote.workspace) + const carrierFailed = vi.fn(() => { model.handleCarrierFailure() }) + const failed = vi.fn((error: unknown) => { model.handleStreamFailure(error) }) + const stream = createWorkspaceStateStream(remote, { accept: model, carrierFailed, failed }) + const states = new Set() + model.subscribe(() => { states.add(model.getSnapshot().state) }) + const ids = (): string[] => model.getSnapshot().items.map(item => item.workspaceId).sort() + const replace = (...workspaceIds: string[]): WorkspaceFollowFrame => ({ type: 'replace', value: baseline(...workspaceIds).value }) + + stream.start() + await vi.waitFor(() => { expect(ids()).toEqual(['one', 'two']) }) + // Access to `two` is revoked, restored through a replace, revoked again, and restored through an upsert. + mock.streams.push(FOLLOW, replace('one')) + await vi.waitFor(() => { expect(ids()).toEqual(['one']) }) + mock.streams.push(FOLLOW, replace('one', 'two')) + await vi.waitFor(() => { expect(ids()).toEqual(['one', 'two']) }) + mock.streams.push(FOLLOW, replace('one')) + await vi.waitFor(() => { expect(ids()).toEqual(['one']) }) + mock.streams.push(FOLLOW, { type: 'upsert', workspace: workspace('two') }) + await vi.waitFor(() => { expect(ids()).toEqual(['one', 'two']) }) + + expect(states).not.toContain('error') + expect(model.getSnapshot()).toMatchObject({ phase: 'ready', state: 'idle', error: null }) + expect(carrierFailed).not.toHaveBeenCalled() + expect(failed).not.toHaveBeenCalled() + expect(streamStates(mock)).toEqual(['open']) + await stream.dispose() + }) + it('retains the old state across carrier loss and applies the replacement baseline', async ({ mock, start }) => { const { remote } = await gatewayClient(mock, start) const carrier = new RemoteStreamCarrierError('socket lost') diff --git a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts index 35158490f2..f284f35155 100644 --- a/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts +++ b/packages/api/workspace-controller/tests/workspace-controller.host.spec.ts @@ -6,9 +6,10 @@ import { Context } from '@deepseek-ai/cordis' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import Storage from '@deepseek-ai/dsh-storage' import { DomainFacility } from '@deepseek-ai/dsh-storage-domain' -import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { RemoteError, type PeerId, type Principal, type RemoteInvocation } from '@deepseek-ai/dsh-typert-protocol' import WorkspaceRegistry from '@deepseek-ai/dsh-workspace' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' +import RemoteAccessService, { type RemoteAccessCondition, type RemoteAccessRole } from '@deepseek-ai/dsh-api-remote-access' import WorkspaceController from '../src/index.ts' import { DEFAULT_WORKSPACE_DIRECTORY } from '../src/default-workspace.ts' import { WorkspaceFeed } from '../src/feed.ts' @@ -67,11 +68,39 @@ async function harness(options: { systemDocuments?: boolean } = {}) { ctx.provide('typert', { lookups: { configure: () => dispose }, contexts: { configureHost: () => dispose }, + resources: { register: vi.fn(() => dispose) }, } as never) + new RemoteAccessService(ctx) const controller = new WorkspaceController(ctx, options.systemDocuments === true ? {} : { documentsDirectory: root }) return { controller, ctx, root, storageDomain } } +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + /** Test-only non-owner caller shared by the access specs. */ + 'test-guest': { readonly kind: 'test-guest'; readonly guest: string } + } +} + +/** Opens the Workspace follow stream; each Workspace and Session in it still needs its own role. */ +const FOLLOWER: RemoteAccessRole<'global'> = { name: 'test:workspace-follower', resource: 'global', actions: ['workspace/follow'] } +/** Shows one Workspace in the follow stream. */ +const WORKSPACE_VIEWER: RemoteAccessRole<'workspace'> = { name: 'test:workspace-viewer', resource: 'workspace', actions: ['workspace/follow'] } +/** Shows one Session id in the follow stream. */ +const SESSION_VIEWER: RemoteAccessRole<'session'> = { name: 'test:session-viewer', resource: 'session', actions: ['workspace/follow'] } + +/** The Context a Gateway dispatch of `workspace/follow` binds for `principal`. */ +function followerContext(ctx: Context, principal: Principal): Context { + const invocation: RemoteInvocation = { + request: { namespace: 'workspace', method: 'follow', args: {} }, + service: 'workspaceController', + peer: { id: 'workspace-access-peer' as PeerId, ctx, principal, signal: new AbortController().signal, dispose: async () => {} }, + signal: new AbortController().signal, + uplink: (): AsyncIterable => ({ [Symbol.asyncIterator]: () => ({ next: async () => ({ done: true, value: undefined }) }) }), + } + return ctx.extend({ invocation }) +} + function stageDir(root: string, name: string): string { const path = join(root, name) mkdirSync(path, { recursive: true }) @@ -416,6 +445,110 @@ describe('WorkspaceController follow', () => { await expect(iterator.next()).resolves.toEqual({ done: true, value: undefined }) }) + it('follows only the Workspaces and Sessions a non-owner may follow', async () => { + const { controller, ctx, root } = await harness() + // oxlint-disable-next-line typescript/unbound-method -- the assertion inspects the spy and never calls it. + expect(ctx.typert.resources.register).toHaveBeenCalledWith('workspace', { field: 'workspaceId' }) + const shown = await controller.create({ path: stageDir(root, 'shown') }) + const hiddenWorkspace = await controller.create({ path: stageDir(root, 'hidden') }) + const shownId = shown.workspace.workspaceId + const hiddenId = hiddenWorkspace.workspace.workspaceId + const shared = ctx.sessions.create(SessionId('shared'), { meta: { cwd: shown.workspace.path } }) + const secret = ctx.sessions.create(SessionId('secret'), { meta: { cwd: shown.workspace.path } }) + const workspace = ctx.workspaceRegistry.get(shownId) + if (workspace === undefined) throw new Error('fixture Workspace disappeared') + await workspace.attachSession(shared.id) + await workspace.attachSession(secret.id) + await controller.pinSession({ sessionId: shared.id }) + await controller.pinSession({ sessionId: secret.id }) + ctx.remoteAccess.registerPolicy('test-guest', { + bindings: () => [ + { role: FOLLOWER, resource: { kind: 'global' } }, + { role: WORKSPACE_VIEWER, resource: { kind: 'workspace', id: shownId } }, + { role: SESSION_VIEWER, resource: { kind: 'session', id: shared.id } }, + ], + }) + const guest: Principal = { kind: 'test-guest', guest: 'workspace-controller' } + const abort = new AbortController() + const iterator = followerContext(ctx, guest).workspaceController.follow(abort.signal)[Symbol.asyncIterator]() + await expect(nextFrame(iterator)).resolves.toEqual({ + type: 'baseline', + value: { + items: [expect.objectContaining({ workspaceId: shownId, sessionIds: [shared.id] })], + archivedSessionIds: [], + pinnedSessionIds: [shared.id], + }, + }) + + await controller.rename({ workspaceId: hiddenId, title: 'still hidden' }) + await controller.rename({ workspaceId: shownId, title: 'renamed' }) + await expect(nextFrame(iterator)).resolves.toMatchObject({ + type: 'upsert', workspace: { workspaceId: shownId, title: 'renamed', sessionIds: [shared.id] }, + }) + await controller.unpinSession({ sessionId: secret.id }) + await expect(nextFrame(iterator)).resolves.toEqual({ type: 'pinned', pinnedSessionIds: [shared.id] }) + await controller.unpinSession({ sessionId: shared.id }) + await controller.archiveSession({ sessionId: secret.id }) + await controller.archiveSession({ sessionId: shared.id }) + await expect(nextFrame(iterator)).resolves.toEqual({ type: 'pinned', pinnedSessionIds: [] }) + await expect(nextFrame(iterator)).resolves.toEqual({ type: 'archived', archivedSessionIds: [] }) + await expect(nextFrame(iterator)).resolves.toEqual({ type: 'archived', archivedSessionIds: [shared.id] }) + await controller.delete({ workspaceId: hiddenId }) + await expect(nextFrame(iterator)).resolves.toEqual({ type: 'order', workspaceIds: [shownId] }) + await controller.delete({ workspaceId: shownId }) + await expect(nextFrame(iterator)).resolves.toEqual({ type: 'order', workspaceIds: [] }) + await expect(nextFrame(iterator)).resolves.toEqual({ type: 'remove', workspaceId: shownId }) + + abort.abort() + await expect(iterator.next()).resolves.toEqual({ done: true, value: undefined }) + }) + + it('sends a non-owner a replace increment when a delivered Workspace loses visibility, so it can reappear', async () => { + const { controller, ctx, root } = await harness() + const first = (await controller.create({ path: stageDir(root, 'first') })).workspace.workspaceId + const second = (await controller.create({ path: stageDir(root, 'second') })).workspace.workspaceId + // One Remote call reads its bindings once, so visibility changes during the stream come from the condition. + const allowedWorkspaces = new Set([first, second]) + const stillShared: RemoteAccessCondition<'workspace'> = ({ resource }) => + allowedWorkspaces.has(resource.id) ? { kind: 'allow' } : { kind: 'deny', reason: 'test:unshared' } + ctx.remoteAccess.registerPolicy('test-guest', { + bindings: () => [ + { role: FOLLOWER, resource: { kind: 'global' } }, + ...[first, second].map(id => ({ role: WORKSPACE_VIEWER, resource: { kind: 'workspace', id } as const, condition: stillShared })), + ], + }) + const abort = new AbortController() + const iterator = followerContext(ctx, { kind: 'test-guest', guest: 'withdrawn' }).workspaceController.follow(abort.signal)[Symbol.asyncIterator]() + const ids = (frame: WorkspaceFollowFrame): string[] => + frame.type === 'baseline' || frame.type === 'replace' ? frame.value.items.map(item => item.workspaceId).sort() : [] + const opening = await nextFrame(iterator) + expect(opening.type).toBe('baseline') + expect(ids(opening)).toEqual([first, second].sort()) + + // Revoked: the next change replaces the state instead of sending a `remove` the Client would never undo. + allowedWorkspaces.delete(first) + await controller.rename({ workspaceId: first, title: 'revoked' }) + const withoutFirst = await nextFrame(iterator) + expect(withoutFirst.type).toBe('replace') + expect(ids(withoutFirst)).toEqual([second]) + allowedWorkspaces.delete(second) + const third = (await controller.create({ path: stageDir(root, 'third') })).workspace.workspaceId + const empty = await nextFrame(iterator) + expect(empty.type).toBe('replace') + expect(ids(empty)).toEqual([]) + // A deletion reaches only a Client that received the Workspace. + await controller.delete({ workspaceId: third }) + await expect(nextFrame(iterator)).resolves.toEqual({ type: 'order', workspaceIds: [] }) + + // Restored: the Workspace reappears through an ordinary upsert. + allowedWorkspaces.add(first) + await controller.rename({ workspaceId: first, title: 'restored' }) + await expect(nextFrame(iterator)).resolves.toMatchObject({ type: 'upsert', workspace: { workspaceId: first, title: 'restored' } }) + + abort.abort() + await expect(iterator.next()).resolves.toEqual({ done: true, value: undefined }) + }) + it('ignores unrelated domain writes and closes active followers on disposal', async () => { const { controller, ctx, root } = await harness() const abort = new AbortController() diff --git a/packages/api/workspace-controller/tsconfig.host.json b/packages/api/workspace-controller/tsconfig.host.json index ff1ca31080..e9d5104e98 100644 --- a/packages/api/workspace-controller/tsconfig.host.json +++ b/packages/api/workspace-controller/tsconfig.host.json @@ -21,6 +21,7 @@ { "path": "../../host/directory-picker" }, { "path": "../../storage/storage-domain" }, { "path": "../../typert/protocol" }, + { "path": "../remote-access/tsconfig.host.json" }, { "path": "../../util/deque" }, { "path": "../../util/native-command" }, { "path": "../../workspace/workspace" } 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 87144d75f8..a880a47fcc 100644 --- a/packages/api/workspace-files/package.json +++ b/packages/api/workspace-files/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-workspace-files", "description": "Workspace file service and Client resource provider: bounded reads, directory listing, and live metadata over the workspaceFiles Remote namespace", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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": { @@ -55,7 +56,7 @@ "@deepseek-ai/dsh-deque": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" @@ -63,6 +64,7 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-resources": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", @@ -74,6 +76,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/src/index.ts b/packages/api/workspace-files/src/index.ts index 1c1c652f1e..d6ecbc68c1 100644 --- a/packages/api/workspace-files/src/index.ts +++ b/packages/api/workspace-files/src/index.ts @@ -203,6 +203,7 @@ export class WorkspaceFiles extends TypertRemoteService { scope.typert.lookups.register('workspaceFileScope', { parameter: 'workspaceFileScope', wire: 'workspaceFileScopeId', + resource: 'session', hostTypeSymbol: '@deepseek-ai/dsh-api-workspace-files#WorkspaceFileScope', wireTypeSymbol: '@deepseek-ai/dsh-session/types#SessionId', resolve: async (sessionId) => { diff --git a/packages/api/workspace-files/tests/binary-rpc.spec.ts b/packages/api/workspace-files/tests/binary-rpc.spec.ts index 35058d58a1..dc42bfbe02 100644 --- a/packages/api/workspace-files/tests/binary-rpc.spec.ts +++ b/packages/api/workspace-files/tests/binary-rpc.spec.ts @@ -5,6 +5,7 @@ import { beforeEach, afterEach, expect, it, vi } from 'vitest' import SessionStore from '@deepseek-ai/dsh-session' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' import TypertGateway from '@deepseek-ai/dsh-api-gateway' +import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access' import { HostConnectionService } from '@deepseek-ai/dsh-client-connection/src/rpc-host.ts' import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' import { createWebConnectionRpc } from '@deepseek-ai/dsh-client-connection/src/client/rpc.ts' @@ -19,12 +20,14 @@ beforeEach(async () => { const ctx = harness.ctx await ctx.plugin(SessionStore) await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) await ctx.plugin(TypertGateway) await ctx.plugin((scope) => { new HostConnectionService(scope, [], {} as BrowserAuth) }) await ctx.plugin(WorkspaceFiles, { maxBytes: 8, maxFileBytes: 4, maxLines: 100, maxEntries: 100 }) ctx.sessions.create(harness.scope.sessionId, { meta: { cwd: harness.workspace, origin: 'subagent' } }) - const handler = (ctx.get('connection') as HostConnectionService).createSharedFetchHandler('/api') - rpc = createWebConnectionRpc(async (path, init) => handler.fetch(new Request(new URL(path, 'http://host'), init))) + const connection = ctx.get('connection') as HostConnectionService + const handler = connection.createSharedFetchHandler('/api') + rpc = createWebConnectionRpc(async (path, init) => handler.fetch(new Request(new URL(path, 'http://host'), init), connection.browserPeer)) }) afterEach(async () => { diff --git a/packages/api/workspace-files/tests/scope.spec.ts b/packages/api/workspace-files/tests/scope.spec.ts index 2d9cd097b2..d954063bfd 100644 --- a/packages/api/workspace-files/tests/scope.spec.ts +++ b/packages/api/workspace-files/tests/scope.spec.ts @@ -52,6 +52,8 @@ describe('Workspace Files Session scope lookup', () => { expect(lookup).toMatchObject({ parameter: 'workspaceFileScope', wire: 'workspaceFileScopeId', + // A method taking a scope reads the scope's Session as its access-control resource. + resource: 'session', hostTypeSymbol: '@deepseek-ai/dsh-api-workspace-files#WorkspaceFileScope', wireTypeSymbol: '@deepseek-ai/dsh-session/types#SessionId', }) 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 9af4fa08dd..d70bb93708 100644 --- a/packages/attachment/attachment-local/package.json +++ b/packages/attachment/attachment-local/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-attachment-local", "description": "Private content-addressed DSH_HOME attachment storage", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -14,11 +14,22 @@ "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", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", "src"], + "files": [ + "locale/*.json", + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], "license": "MIT", "peerDependencies": { "@deepseek-ai/dsh-attachment": "workspace:*", @@ -28,7 +39,7 @@ "dependencies": { "@deepseek-ai/dsh-lazy-require": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "sharp": "^0.35.5" + "sharp": "0.35.5" }, "devDependencies": { "@deepseek-ai/dsh-attachment": "workspace:*", diff --git a/packages/attachment/attachment/package.json b/packages/attachment/attachment/package.json index 1a8c50129b..b77a9b64b8 100644 --- a/packages/attachment/attachment/package.json +++ b/packages/attachment/attachment/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-attachment", "description": "Durable immutable attachment storage seam for the DeepSeek Harness", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index df0e4f782e..12b9f227e6 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/README.i18n.yaml @@ -21,11 +21,11 @@ en: 2fdfe02f2ed4a258 zh: d748228ece579c4a /deepseek-ai-dsh-app-boot/use-this-package/starting-the-app: - en: 1099528bde0e2aee - zh: b68772bdb9bb7856 + en: 4a424cd401556f20 + zh: 0b34dd18e0db6cea /deepseek-ai-dsh-app-boot/use-this-package/profiles: - en: 1db121100677e45f - zh: c6a8c6316020eb1b + en: d50b0fdaf62353dd + zh: 0fccb6968602e5de /deepseek-ai-dsh-app-boot/use-this-package/previewing-the-effective-configuration: en: 646a0ccdd7881ad1 zh: e3696acb1573dd7b @@ -33,38 +33,35 @@ en: c4a301652b851ce9 zh: 784871e19cd9db0a /deepseek-ai-dsh-app-boot/use-this-package/reading-plugin-display-metadata: - en: ebf6cb3960a5b378 - zh: 41ba129a0f86c168 + en: a9afb263b03d112c + zh: 31f5e797cd953c15 /deepseek-ai-dsh-app-boot/use-this-package/startup-and-reload-failures: - en: b2e5cfdf8847d214 - zh: 8d65771a3bd8a7c9 -/deepseek-ai-dsh-app-boot/use-this-package/telling-the-agent-where-the-harness-lives: - en: 07c459f26f4f8517 - zh: 210f1e4894731b1a + en: dc13dfa1f79292e4 + zh: d51682ced7a18ac2 /deepseek-ai-dsh-app-boot/understand-the-implementation: en: f4a2695cb4c8a570 zh: 89837235d2f376cf /deepseek-ai-dsh-app-boot/understand-the-implementation/design-notes: - en: 25a0d1b46fd66d68 - zh: 5cd8b4ac382dccdc + en: 9ecb744556705fd1 + zh: d83aaf2ebb91d0fc /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 + en: 1400c4f22a79b59a + zh: 269f6c91584aec3e /deepseek-ai-dsh-app-boot/known-limitations-and-deferred-work/dev-note: en: d2f0d68fe29fb750 zh: 323d21ee73a9e3f6 diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index 4821673423..5e4d3b460a 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -40,7 +40,7 @@ installFailLoud('dsh') const ctx = await boot('dsh', resolveConfigPath(argv[2], process.env.DSH_SNAPSHOT)) ``` -`installFailLoud` writes one labelled `util.inspect` diagnostic to stderr for an unhandled rejection or an uncaught exception, awaits the surface's release hook under a fixed timeout, and exits 1; control never returns to the failed operation, because only the throw site knows which state is intact, and the event loop runs only until the release settles or times out. With that entry point, startup keeps every plugin that can activate. An enabled failed plugin produces a labelled warning. A failed required entry makes startup dispose the whole app and exit nonzero; required ids absent from a profile and disabled required entries do not affect startup. The global required list covers shared Agent execution, application endpoints, and Web bootstrap/transport: `agent-loop`, `webserver`, `modules`, `connection`, `headless-runner`, `acp`, and `sdk-jsonrpc-server`. +`installFailLoud` writes one labelled `util.inspect` diagnostic to stderr for an unhandled rejection or an uncaught exception, awaits the surface's release hook under a fixed timeout, and exits 1; control never returns to the failed operation, because only the throw site knows which state is intact, and the event loop runs only until the release settles or times out. With that entry point, startup keeps every plugin that can activate. An enabled failed plugin produces a labelled warning. A failed required entry makes startup dispose the whole app and exit nonzero; required ids absent from a profile and disabled required entries do not affect startup. The global required list covers shared Agent execution, application endpoints, and Web bootstrap/transport: `agent-loop`, `webserver`, `web-runtime`, `modules`, `connection`, `headless-runner`, `acp`, and `sdk-jsonrpc-server`. ### Profiles @@ -62,21 +62,7 @@ Your machine-local preferences also live in the Harness home: The enabled `dsh-hmr` plugin watches the profile manifest and both user patch files, re-reads the ordered bundle layers, and applies the [reload failure policy](#startup-and-reload-failures). [DSH HMR](../hmr/README.md) serializes these reloads with [Plugin Manager](../plugin-manager/README.md) configuration writes; package operations run outside its queue. The launcher does not install HMR or watchers; disabled or absent HMR means changes require restart. -Inserted plugin names may be absolute filesystem paths, file URLs, or package specifiers. Patch loading converts absolute paths and patch-relative `./` or `../` paths to file URLs within `insert` rows, their nested groups, and inserted preset definitions; existing-entry name assertions and replacement `config` values remain literal. - -A profile patch may set `preset` to an outer row id and apply the remaining ordinary patch fields inside that row's literal `config.plugins` list. Any bundle or user layer can contribute these operations. Each operation sees the current child list; later user operations take precedence, and a later whole-preset `config` replacement replaces every earlier child contribution. Ordinary outer patches retain Include's single-index lookup: children introduced by replacing a group's `config` are not addressable outer targets. Missing or malformed outer preset targets and duplicate child ids introduced by an insertion fail composition. An unmatched inner `id` warns and skips, so disabling a bundle does not invalidate an old user override of its child. - -```yaml -- preset: preset-standard - insert: - - id: optional-string-editor - name: '@deepseek-ai/dsh-tool-str-replace-editor' -- preset: preset-standard - id: optional-string-editor - disabled: true -``` - -`ProfilePatch` extends the native patch fields with `preset`. `applyProfilePatches` composes these operations; `compileProfilePatches` returns ordinary Include patches. Startup, profile reload, effective-config dumps, schema inspection, and compatibility preflight share this compiler. Scoped `insert` module paths resolve beside their declaring patch, including nested groups; `!!js` remains unevaluated until each child activates. Native included-file patch lists keep their ordinary Include syntax. Loaded scoped insertions without IDs receive stable internal IDs derived from the canonical declaring file and entry position, including nested groups; ordinary anonymous root rows keep Loader’s existing behavior. Generated IDs identify contributions across reloads and retained revisions, and are implementation details rather than names to use in authored patches. Compiler failures name the declaring patch file and operation, including after profile layers are combined. +Inserted plugin names may be absolute filesystem paths, file URLs, or package specifiers. Patch loading converts absolute paths and patch-relative `./` or `../` paths to file URLs within `insert` rows and their nested groups; existing-entry name assertions and replacement `config` values remain literal. Before mounting profile rows, the `dsh` launcher computes one immutable runtime resolution from the installation and ordered bundle dependency graphs. Every profile launcher uses runtime resolution, including plain Node, packaged executables, and the Electron Host. It installs the runtime resolution through Node's ESM and CommonJS resolvers without creating fallback links. @@ -98,8 +84,6 @@ The projector preserves native omission behavior by checking literal defaults ag `resolvePluginResource(specifier, parentURL)` resolves a plugin module or exported resource to its local filesystem path through the active Node ESM resolver without evaluating it. It throws when the resolver is unavailable or the resource cannot resolve to a local file. -`realModuleFile(path)` canonicalizes an existing module resource in Node and packaged executables. It follows physical file symlinks and preserves archive-backed resources through their canonical containing directory. Missing or inaccessible resources throw. - Use `readPluginMeta(specifier, parentURL)` or `ctx.pluginPackages.metaOf(specifier, parentURL)` to read installed package display text without importing or activating the plugin. Lookup uses the complete package specifier and the caller's resolution base, respecting Node exports. File paths and file URLs return no metadata without resolving resources. For a package-root specifier, missing locale fields fall back to the accessible `package.json`; a subpath specifier never reads a `package.json`. Malformed metadata returns an `error` diagnostic. Results retain translations for Client-side language selection. The reader also loads an image data URL, even when locale text is complete: a package root uses its manifest `icon`, or `/icon` when that field is omitted; a subpath uses `/icon`. An icon error preserves valid text alongside the diagnostic. See [Plugin display metadata](../../../docs/cookbook/adding-a-package.md#plugin-display-metadata) for the author format. `ON_DEMAND_BUNDLES` names the public Official packages installed only on request. `OFFICIAL_ON_DEMAND_CATALOG` embeds their package-owned localized metadata and icons for offline discovery; `pnpm gen-official-bundle-catalog` explicitly updates generated content, and `verify-official-bundle-catalog` checks resource completeness and freshness; builds consume the committed catalog without importing provider code. The catalog contains no install target: [Plugin Manager](../plugin-manager/README.md#use-this-package) derives it from the running version and installation and uses the ordinary bundle installer. The [product-use check](../../../scripts/verify-product-use.ts) composes shipped and on-demand selections against Web without executing providers. @@ -107,7 +91,7 @@ Use `readPluginMeta(specifier, parentURL)` or `ctx.pluginPackages.metaOf(specifi ### Startup and reload failures -Profile reconciliation returns diagnostics for unchanged inactive entries without failing an unrelated mutation. A new inactive entry, a changed configuration or fiber, or a changed diagnostic fails reconciliation; removed fibers must still finish disposal. Active root rows that disappear or become literally disabled release their resources before replacement rows activate, so a singleton provider can drain in-flight work before its successor registers. Compilation and disposal checks use the same parsed root entries for each reconciliation. Explicit enablement targets must activate even when their failure predates the operation. Successful reconciliation emits `app-boot/config-reload` after lifecycle settlement and diagnostic checks, including programmatic updates without HMR. The event carries no diff or parsed config. Successful reconciliation returns after lifecycle settlement and diagnostic checks; volatile-only entry changes are committed by Loader during the update. +Profile reconciliation returns diagnostics for unchanged inactive entries without failing an unrelated mutation. A new inactive entry, a changed configuration or fiber, or a changed diagnostic fails reconciliation; removed fibers must still finish disposal. Explicit enablement targets must activate even when their failure predates the operation. `recomposeProfile(ctx, patches, binName, { requiredIds, running })` runs one recomposition together with the runtime resolution: it removes the rows the generation no longer lists and waits for their disposal while their packages are still mapped, publishes the latest generation of a recomputable resolution, runs the compatibility preflight against the published packages, applies the generation, starts the `running` entries and entries whose import failed that the update left without a running fiber, and judges activation. `running` lists the entries that ran before the caller stopped some of them; each that failed afterwards counts as a new failure. A failure before the generation applies puts the removed rows back at their places, which starts them again, and starts the `running` entries again. An entry waiting for a service is reported as a warning unless it is required, so it starts once a provider appears; `reconcileProfilePatches()` judges it the same way. A publication the resolution rejects is such a failure and reports `package-moved`. `reconcileProfilePatches()`, which the Config Editor uses, applies and judges the patches without publishing the resolution or retrying failed imports. An entry whose import failed is reported with the error Loader's import returns again, so judging it evaluates the module when the import now succeeds; the state recorded before the change imports nothing, so an entry whose import failed before counts as the same failure whatever its error now is. Successful reconciliation emits `app-boot/config-reload` after lifecycle settlement and diagnostic checks, including programmatic updates without HMR. The event carries no diff or parsed config. Successful reconciliation returns after lifecycle settlement and diagnostic checks; volatile-only entry changes are committed by Loader during the update. After the Loader settles, app-boot warns when only optional entries are inactive. If an enabled required entry cannot activate, `boot()` rejects with `StartupError` after disposal. An independently owned logger exporter retains warning and error records through asynchronous disposal and is released before `boot()` settles. Its message groups all failed plugins and pending services, marks required entries, and retains original stacks, nested causes, and aggregate members. The CLI prints that message once and saves [full startup diagnostics](../../../apps/cli/reference/README.md#startup-diagnostics) before exiting with code 1; unrelated exceptions retain their normal stack output. In the table, stopping startup means disposing any mounted plugins and exiting nonzero without reporting readiness; continuing keeps successful plugins running. Later configuration HMR does not repeat the required-startup audit and does not roll back the whole update. @@ -132,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. - ----- @@ -155,8 +135,8 @@ This section explains how the outcomes above are realized and points at the code - **Package metadata.** `ctx.pluginPackages.packageOf` locates the owning package without loading code or requiring an exported `package.json`; a subpath selects its package without validating that file. The installed runtime resolution owns selection even for a miss. Low-level embedders that install the service without one retain native lookup. Display metadata uses the separate entry-aware reader described above. - **Two Loader builtins.** `mountRootInclude` registers `cordis:include` and `cordis:group` as Loader builtins: a group row gives one `isolate` realm to a provider and its consumers together, and an agent preset outside this workspace cannot resolve `@deepseek-ai/cordis-plugin-group` by name. Both load through the ambient module pipeline rather than the included tree's own specifier resolution. - **Consumer-owned strictness.** Ordinary Loader groups keep successful siblings. App-boot applies the global required-entry policy after initial settlement; agent presets and dynamic multi-entry compositions own and dispose their separate Loader subtree when they require all-or-nothing setup. App-boot reads failed fibers to report their recorded errors and coalesces duplicate Loader rejection notifications through one process checkpoint. -- **One runtime resolution.** The installation-first and ordered-bundle breadth-first traversal produces the runtime table. Runtime resolution creates no links; runtime resolution entries occupy their package names at `$DSH_HOME/profiles/node_modules`, and every other name sees that directory as an ordinary ancestor. Profile load removes the `.dsh-module-fallback` projections that link-backend releases wrote into a profile; pnpm-installed packages stay. External bare targets selected by package `imports` use the same package order, while Node retains mapping, conditions, and exact target resolution. A complete successor may add package names, remove profile-scoped mappings and profile-local names, and update linked-root membership atomically; retained mappings keep their normalized directory, version, and scope. Installation anchors remain fixed; a profile mapping may change its declarer. [Plugin Manager](../plugin-manager/README.md) publishes successors after package operations ([decision](../../../.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.md)). -- **Removing linked interception.** A successor may remove a linked root without restart. Directories outside all remaining roots use native lookup for subsequent requests, which may find a development copy or report a missing package. Existing module references and Node caches stay unchanged. Re-adding the same link name and target is allowed; pointing a previously published name at a different target is rejected even after removal ([generation rules](../../../.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.md#immutable-generations)). +- **One runtime resolution.** The installation-first and ordered-bundle breadth-first traversal produces the runtime table. Runtime resolution creates no links; runtime resolution entries occupy their package names at `$DSH_HOME/profiles/node_modules`, and every other name sees that directory as an ordinary ancestor. Profile load removes the `.dsh-module-fallback` projections that link-backend releases wrote into a profile; pnpm-installed packages stay. External bare targets selected by package `imports` use the same package order, while Node retains mapping, conditions, and exact target resolution. A complete successor may add package names, remove profile-scoped mappings and profile-local names, and update linked-root membership atomically; retained mappings keep their normalized directory and scope. Installation mappings keep their version and anchor; a profile mapping may change its declarer and, for a package upgraded in place, its version. [Plugin Manager](../plugin-manager/README.md) publishes successors after package operations ([decision](../../../.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.md)). +- **Removing linked interception.** A successor may remove a linked root without restart. Directories outside all remaining roots use native lookup for subsequent requests, which may find a development copy or report a missing package. Existing module references and Node caches stay unchanged. A link name that is no profile mapping may point to another target, also after removal, and so may one whose mapping was removed first; Node's cached real paths of the previous target are relocated ([generation rules](../../../.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.md#immutable-generations)). - **Application-owned profiles.** Application-owned profiles use the same runtime resolution. Links within the active profile directory, including pnpm store links, are not external roots even when the profile is outside the shared profiles tree. Resolution does not modify their `node_modules`; pnpm owns installed packages. - **Owned Workers.** Worker build banners import `@deepseek-ai/dsh-app-boot/worker/profile-resolution-bootstrap` before bundled business code. Each Worker installs the structured-cloned runtime resolution in its own isolate. The bootstrap bundle has no static package imports. Source Worker entries retain their self-contained dependency closure, and third-party Workers receive no injection. - **Update completion.** App boot observes restart failures through the `internal/update` waterfall. Live patch reloads wait for the tree's fibers before auditing activation; `Fiber.update()` and `Entry.update()` alone do not establish restart success. @@ -167,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 | @@ -203,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 @@ -216,7 +196,7 @@ Boot itself changes no request prefix. `addHarnessSourceSection` places its sour These limits describe when this boot library is a poor fit or needs special care. They are current package constraints, not a task backlog. - **Runtime resolution depends on Node internals** — supported Node versions require the native builtin-access addon and executable compatibility coverage. Only built Harness-owned Workers receive the runtime resolution bootstrap; third-party Workers and custom `vm` linkers keep native resolution. -- **Relinking a profile package needs a restart** — Node caches real paths, so changing the target of a profile link or a dependency link requires a process restart. +- **Moving a profile package needs its removal first** — `replace()` rejects a retained profile mapping that moved to another directory or link target with `ResolutionRestartRequired`; removing the package and installing it again maps the new directory. A linked root may point to another directory once its profile mapping was removed. Node keeps the real path of every link it resolved through; once a link points elsewhere, or its name is installed again as a directory, a native lookup that selects a file below its previous target, for an importer outside it, selects the same file below the current one when that exists, including an explicit absolute path into the previous target. Installation mappings and local overrides still require a restart. - **Linked scope follows recorded real directories** — a hoisted dependency outside every linked root uses native Node. A peer read never invalidates Node caches or changes which files are watched. - **Source launches use an ESM-only hook** — CommonJS requests still need the JavaScript files selected by package exports; resolution does not supply missing build outputs. - **Snapshot replay swapping is basename-specific** — only a config ending in `cordis.yml` or `cordis.yaml` maps to the sibling `cordis.snapshot.yml`; custom config names require caller-managed selection. diff --git a/packages/boot/app-boot/README.zh.md b/packages/boot/app-boot/README.zh.md index 236c59d522..31fdebcb15 100644 --- a/packages/boot/app-boot/README.zh.md +++ b/packages/boot/app-boot/README.zh.md @@ -40,7 +40,7 @@ installFailLoud('dsh') const ctx = await boot('dsh', resolveConfigPath(argv[2], process.env.DSH_SNAPSHOT)) ``` -`installFailLoud` 会为未处理 rejection 或未捕获异常向 stderr 写一条带标签的 `util.inspect` 诊断,在固定超时内等待界面的 release 钩子,然后以 1 退出;控制流不会回到失败的操作,因为只有抛出点知道哪些状态仍然完整,事件循环只运行到 release 结束或超时。有了这个入口,启动会保留所有能够激活的插件。启用但失败的插件会产生带标签的警告。required entry 失败时,启动会拆卸整个应用并以非零码退出;profile 中不存在的 required id 和已禁用的 required entry 不影响启动。全局 required list 覆盖共享 Agent 执行、应用 endpoint,以及 Web 启动与传输:`agent-loop`、`webserver`、`modules`、`connection`、`headless-runner`、`acp` 和 `sdk-jsonrpc-server`。 +`installFailLoud` 会为未处理 rejection 或未捕获异常向 stderr 写一条带标签的 `util.inspect` 诊断,在固定超时内等待界面的 release 钩子,然后以 1 退出;控制流不会回到失败的操作,因为只有抛出点知道哪些状态仍然完整,事件循环只运行到 release 结束或超时。有了这个入口,启动会保留所有能够激活的插件。启用但失败的插件会产生带标签的警告。required entry 失败时,启动会拆卸整个应用并以非零码退出;profile 中不存在的 required id 和已禁用的 required entry 不影响启动。全局 required list 覆盖共享 Agent 执行、应用 endpoint,以及 Web 启动与传输:`agent-loop`、`webserver`、`web-runtime`、`modules`、`connection`、`headless-runner`、`acp` 和 `sdk-jsonrpc-server`。 ### Profile @@ -62,21 +62,7 @@ profile 导入插件前,DSH 会检查其 `peerDependencies` 中对 `@deepseek- 启用的 `dsh-hmr` 插件会监视 profile manifest 与两份用户 patch 文件,重新读取按顺序排列的组合包层,并应用[重载失败策略](#startup-and-reload-failures)。[DSH HMR](../hmr/README.zh.md) 将这些重载与[插件管理器](../plugin-manager/README.zh.md)的配置写入串行化;包操作在其队列之外执行。启动器不安装 HMR 或监视器;HMR 被禁用或不存在时,更改需要重启。 -插入条目的插件名可以是绝对文件系统路径、文件 URL 或包标识符。patch 加载会把 `insert` 条目、其嵌套分组和插入的 preset 定义中的绝对路径,以及相对于 patch 文件的 `./` 或 `../` 路径转换为文件 URL;对已有条目名称的断言及替换用的 `config` 值保持原样。 - -profile patch 可以将 `preset` 设为外层条目 id,把其余普通 patch 字段应用到该条目的字面量 `config.plugins` 列表中。任何 bundle 或用户层都可以提供这些操作。每个操作作用于当前子条目列表;较晚的用户操作优先,而较晚的整个 preset `config` 替换会覆盖此前所有子条目贡献。普通外层 patch 保留 Include 的单次索引查找语义:替换 group 的 `config` 所引入的子条目无法作为外层目标。外层 preset 目标缺失或格式错误、插入造成子条目 id 重复都会使组合失败。内层 `id` 不匹配时只警告并跳过,因此禁用 bundle 不会使用户保留的子条目覆盖失效。 - -```yaml -- preset: preset-standard - insert: - - id: optional-string-editor - name: '@deepseek-ai/dsh-tool-str-replace-editor' -- preset: preset-standard - id: optional-string-editor - disabled: true -``` - -`ProfilePatch` 在原生 patch 字段上增加 `preset`。`applyProfilePatches` 组合这些操作;`compileProfilePatches` 返回普通 Include patch。启动、profile 重载、有效配置 dump、schema 检查及兼容性预检共用此编译器。限定到 preset 的 `insert` 模块路径以声明它的 patch 所在目录为基准,包括嵌套分组;`!!js` 保持不求值,直至对应子条目激活。原生被 Include 引入文件的 patch 列表仍使用普通 Include 语法。 读取的作用域插入行若未声明 ID,会依据声明文件的规范路径及条目位置获得稳定的内部 ID,嵌套组内的行也如此;普通匿名根行保留 Loader 的既有行为。生成的 ID 用于在重载和保留代际之间识别贡献项,是实现细节,不是作者应在 patch 中引用的名称。编译失败会标明声明 patch 文件和操作序号,profile 层合并后也保留这些信息。 +插入条目的插件名可以是绝对文件系统路径、文件 URL 或包标识符。patch 加载会把 `insert` 条目及其嵌套分组中的绝对路径以及相对于 patch 文件的 `./` 或 `../` 路径转换为文件 URL;对已有条目名称的断言及替换用的 `config` 值保持原样。 挂载 profile 条目前,`dsh` launcher 会从安装依赖图与有序 bundle 依赖图计算一份不可变的 runtime resolution。普通 Node、打包可执行文件与 Electron Host 等所有 profile 启动器都使用 runtime 解析,将 runtime resolution 安装到 Node 的 ESM 与 CommonJS 解析器中,不创建 fallback 链接。 @@ -98,8 +84,6 @@ profile patch 可以将 `preset` 设为外层条目 id,把其余普通 patch `resolvePluginResource(specifier, parentURL)` 通过活动的 Node ESM 解析器将插件模块或导出资源解析为本地文件路径,不执行其代码。解析器不可用或资源无法解析为本地文件时会抛出错误。 -`realModuleFile(path)` 在 Node 和打包可执行程序中规范化已有模块资源的路径。它跟随物理文件符号链接,并通过规范化后的所在目录保留归档资源。资源不存在或无法访问时抛出错误。 - 使用 `readPluginMeta(specifier, parentURL)` 或 `ctx.pluginPackages.metaOf(specifier, parentURL)` 读取已安装包的展示文本,无需导入或激活插件。查询使用完整包标识与调用方的解析基准,并遵循 Node exports。文件路径与文件 URL 不解析资源,直接返回无元信息。包根标识缺失的 locale 字段回退到可访问的 `package.json`;子路径标识从不读取 `package.json`。格式错误的元信息返回 `error` 诊断。结果保留翻译,由 Client 选择语言。即使 locale 文本完整,读取器也会加载图片 data URL:包根使用清单 `icon`,省略该字段时使用 `<包名>/icon`;子路径使用 `<标识>/icon`。图标出错时,保留有效文本并附上诊断。作者格式见[插件展示元信息](../../../docs/cookbook/adding-a-package.zh.md#plugin-display-metadata)。 `ON_DEMAND_BUNDLES` 列出仅按需安装的官方公开包。`OFFICIAL_ON_DEMAND_CATALOG` 内嵌这些包拥有的本地化元信息和图标,支持离线发现;`pnpm gen-official-bundle-catalog` 显式更新生成内容,`verify-official-bundle-catalog` 检查资源完整性与新鲜度;构建只读取已提交的目录,不导入提供者代码。目录不保存安装目标;[插件管理器](../plugin-manager/README.zh.md#use-this-package)根据当前版本和安装位置确定目标,并使用普通组合包安装器。[产品用途检查](../../../scripts/verify-product-use.ts)将随附和按需选择与 Web 组合,但不执行提供者。 @@ -107,7 +91,7 @@ profile patch 可以将 `preset` 设为外层条目 id,把其余普通 patch ### 启动与重载失败 -profile 重载返回未变化的已有故障诊断,不让无关修改因此失败。新增未激活条目、配置或 fiber 变化、诊断变化都会使重载失败;被移除的 fiber 仍须完成释放。消失或被字面量禁用的活跃根条目先释放资源,再激活替代条目,因此单实例提供方可以先排空进行中的工作,再让后继者注册。每次重组时,编译与释放检查使用同一份已解析的根条目。显式启用的目标必须成功激活,即使它的故障早于本次操作。成功重载在生命周期结束及诊断检查通过后发出 `app-boot/config-reload`,包括未启用 HMR 时的程序化更新。事件不携带 diff 或解析后的配置。 成功重载在生命周期结束及诊断检查通过后返回;仅 volatile 的条目变化由 Loader 在更新过程中提交。 +profile 重载返回未变化的已有故障诊断,不让无关修改因此失败。新增未激活条目、配置或 fiber 变化、诊断变化都会使重载失败;被移除的 fiber 仍须完成释放。显式启用的目标必须成功激活,即使它的故障早于本次操作。`recomposeProfile(ctx, patches, binName, { requiredIds, running })` 与 runtime resolution 一起执行一次重新组合:它移除新一代组合不再列出的行,并在其包仍有映射时等待这些行释放完成,发布可重新计算的 resolution 的最新一代,使兼容性预检读取已发布的包,应用新一代组合,启动更新后没有运行中 fiber 的 `running` 条目和导入失败的条目,然后判定激活结果。`running` 列出调用方停止其中部分条目之前正在运行的条目;之后每个失败的条目都计为新的故障。新一代组合应用之前的失败会把移除的行放回原位置,从而重新启动它们,并重新启动 `running` 条目。等待服务的条目报告为警告(required 条目除外),因此出现提供方后它即启动;`reconcileProfilePatches()` 以同样方式判定它。resolution 拒绝的发布属于这种失败,并报告 `package-moved`。Config Editor 使用的 `reconcileProfilePatches()` 应用并判定 patch,不发布 resolution,也不重试失败的导入。导入失败的条目以 Loader 再次导入时返回的错误报告,因此若导入现在成功,判定该条目时会对模块求值;变更前记录的激活状态不执行任何导入,因此之前导入失败的条目无论现在的错误是什么,都计为同一个故障。成功重载在生命周期结束及诊断检查通过后发出 `app-boot/config-reload`,包括未启用 HMR 时的程序化更新。事件不携带 diff 或解析后的配置。成功重载在生命周期结束及诊断检查通过后返回;仅 volatile 的条目变化由 Loader 在更新过程中提交。 Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如果已启用的 required 条目无法激活,`boot()` 会在释放资源后以 `StartupError` 拒绝。独立管理生命周期的 logger exporter 会保留异步资源释放期间的警告和错误记录,并在 `boot()` 结算前释放。其消息分组列出所有失败插件和等待的服务,标记 required 条目,并保留原始堆栈、嵌套原因和聚合错误成员。CLI 仅输出该消息一次,并在保存[完整启动诊断](../../../apps/cli/reference/README.zh.md#startup-diagnostics)后以退出码 1 结束;其他异常保留正常堆栈输出。表中的“终止启动”指释放已挂载插件并以非零码退出,不报告就绪;“继续”指保留成功运行的插件。后续配置 HMR 不会再次执行 required 启动审计,也不会回滚整个更新。 @@ -132,10 +116,6 @@ Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如 如果你的应用持有终端,它可以在进程退出前把终端交还,你的 shell 绝不会残留在 raw 模式。交还过程有界:卡住的清理只会延迟致命退出,而不会取消它。 -### 告诉 agent(智能体)harness 所在位置 - -当你的应用启动模型驱动的 agent 时,你可以告诉 agent DSH 实现代码 checkout 的位置:它得知该路径,也知道不得据此推断工作目录——它应使用 `pwd`。这条指示在系统提示词靠前位置出现一次。没有系统提示词服务的应用会跳过;开发环境中,重新加载系统提示词后它会消失,直至下次启动。 - ----- @@ -155,8 +135,8 @@ Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如 - **包元数据。** `ctx.pluginPackages.packageOf` 定位所属包,不加载代码,也不要求导出 `package.json`;子路径选择其所属包,不校验该文件。安装 runtime resolution 后,即使查询未命中也以其选包规则为准。仅安装服务而不提供 runtime resolution 的底层嵌入方保留原生查询。展示元数据使用上文另述的入口感知读取器。 - **两个 Loader builtin。** `mountRootInclude` 把 `cordis:include` 与 `cordis:group` 注册为 Loader builtin:group 行能把一个提供方与它的消费方放进同一个 `isolate` realm,而位于本工作区之外的 agent preset 无法按名称解析 `@deepseek-ai/cordis-plugin-group`。两者都通过宿主的模块管线加载,而非被包含树自身的说明符解析。 - **由 consumer 持有严格语义。** 普通 Loader group 保留成功 sibling。App-boot 在首次结算后应用全局 required-entry policy;agent preset 与动态多 entry 组合在需要 all-or-nothing setup 时,持有并拆卸各自的独立 Loader 子树。App-boot 读取 failed fiber 来报告已记录的错误,并在一个进程检查点内合并 Loader 重复的 rejection 通知。 -- **唯一 runtime resolution。** 安装优先、有序 bundle 逐根 breadth-first 遍历生成运行时表。runtime 解析不创建链接;runtime resolution 条目占据 `$DSH_HOME/profiles/node_modules` 上各自的包名位置,其余包名把该目录当作普通祖先。profile 加载时删除 Link 后端发布版写进 profile 的 `.dsh-module-fallback` 投影;pnpm 安装的包保留。package `imports` 选中的外部 bare target 使用相同的选包顺序,映射、conditions 和精确 target 解析仍由 Node 负责。完整后继 runtime resolution 可以原子地增加 package name、移除 profile 范围的映射和 profile 本地包名、更新 linked root 集合;保留映射的规范化目录、版本和作用域不变。安装范围的锚点不变;profile 映射可以更换声明来源。[插件管理器](../plugin-manager/README.zh.md)在包操作之后发布后继代([决策](../../../.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.zh.md))。 -- **移除链接拦截。** 后继 generation 可以移除 linked root,无需重启。目录不再被任何剩余 root 覆盖时,后续请求使用原生查询,可能找到开发副本,也可能报告缺包。已有模块引用和 Node 缓存保持不变。同名、同目标可以重新加入;曾发布的名称改指向不同目标时,即使中间移除过也会被拒绝([generation 规则](../../../.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.zh.md#immutable-generations))。 +- **唯一 runtime resolution。** 安装优先、有序 bundle 逐根 breadth-first 遍历生成运行时表。runtime 解析不创建链接;runtime resolution 条目占据 `$DSH_HOME/profiles/node_modules` 上各自的包名位置,其余包名把该目录当作普通祖先。profile 加载时删除 Link 后端发布版写进 profile 的 `.dsh-module-fallback` 投影;pnpm 安装的包保留。package `imports` 选中的外部 bare target 使用相同的选包顺序,映射、conditions 和精确 target 解析仍由 Node 负责。完整后继 runtime resolution 可以原子地增加 package name、移除 profile 范围的映射和 profile 本地包名、更新 linked root 集合;保留映射的规范化目录和作用域不变。安装范围的映射保持版本和锚点不变;profile 映射可以更换声明来源,对原地升级的包还可以更改版本。[插件管理器](../plugin-manager/README.zh.md)在包操作之后发布后继代([决策](../../../.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.zh.md))。 +- **移除链接拦截。** 后继 generation 可以移除 linked root,无需重启。目录不再被任何剩余 root 覆盖时,后续请求使用原生查询,可能找到开发副本,也可能报告缺包。已有模块引用和 Node 缓存保持不变。不属于 profile 映射的链接名称可以指向其他目标,移除之后也可以;其 profile 映射先被移除的链接名称同样可以;Node 缓存的原目标真实路径会被重新定位([generation 规则](../../../.agents/notes/implemented/architecture/2026-09-09-profile-resolution-generations.zh.md#immutable-generations))。 - **应用自有 profile。** 应用自有 profile 使用相同的 runtime resolution。目标位于当前 profile 目录内的链接(包括 pnpm store 链接)不算外部 root,即使 profile 位于共享 profiles 树外。解析过程不修改其 `node_modules`;已安装包由 pnpm 管理。 - **自有 Worker。** Worker 构建 banner 会在业务 bundle 前导入 `@deepseek-ai/dsh-app-boot/worker/profile-resolution-bootstrap`。每个 Worker 在自己的 isolate 中安装结构化克隆的 runtime resolution。bootstrap bundle 不静态导入任何包。源码 Worker 入口保留自包含依赖,第三方 Worker 不接受注入。 - **更新完成。** App boot 通过 `internal/update` waterfall 观察重启失败。实时 patch 重载在检查激活状态前等待配置树中的 fiber;单独调用 `Fiber.update()` 或 `Entry.update()` 不能确定重启成功。 @@ -167,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 启用状态 | @@ -203,11 +183,11 @@ Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如 ## 模型体验 -模型通过此包加载的插件树间接受影响——只有该树贡献模型上下文;唯一贡献模型可见文本的导出 `addHarnessSourceSection`,也只有在消费方启动后调用它时才会产生影响。 +模型通过此包加载的插件树间接受影响——只有该树贡献模型上下文;没有导出会添加模型可见文本。 #### KV Cache 影响 -启动本身不改变请求前缀。`addHarnessSourceSection` 将源码路径放在第一方可复用指令之后,因此工具与配置一致时,不同 checkout 不会改变前置字节。不保证提供方复用缓存。 +启动本身不改变请求前缀。 ## 已知限制与延期工作 @@ -216,7 +196,7 @@ Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如 这些限制说明此启动库在何时不合适,或何时需要特别注意。它们是当前包约束,不是任务积压。 - **运行时解析依赖 Node 内部机制**——受支持的 Node 版本需要 native builtin access addon 和可执行兼容验证。只有构建后的 Harness 自有 Worker 接收 runtime resolution bootstrap;第三方 Worker 与自定义 `vm` linker 保持原生解析。 -- **重新链接 profile 包需要重启**——Node 缓存真实路径,因此改变 profile 链接或依赖链接的目标需要重启进程。 +- **移动 profile 包需要先卸载**——`replace()` 以 `ResolutionRestartRequired` 拒绝移动到其他目录或链接目标的保留 profile 映射;卸载该包后重新安装,即映射到新目录。linked root 的 profile 映射被移除后,它可以指向其他目录。Node 保留其解析过的每个链接的真实路径;链接指向别处后,或其名称作为目录重新安装后,原生查询为原目标之外的导入方选中原目标之下的文件时,若当前目标之下存在同一文件,会改为选中该文件,包括指向原目标的显式绝对路径。安装映射和本地覆盖仍需要重启。 - **链接作用域以记录的真实目录为准**——提升后的依赖若在所有 linked root 之外,就使用原生 Node。每次读取 peer 都不会使 Node 缓存失效,也不会改变被监视的文件。 - **源码启动只安装 ESM 钩子**——CommonJS 请求仍需要 package exports 选中的 JavaScript 文件,解析器不会补出缺失的构建产物。 - **快照回放替换仅识别特定 basename**——只有以 `cordis.yml` 或 `cordis.yaml` 结尾的配置会映射到同级 `cordis.snapshot.yml`;自定义配置名称需要调用方自行选择。 diff --git a/packages/boot/app-boot/package.json b/packages/boot/app-boot/package.json index 5ac33eaef3..02fcc44c2c 100644 --- a/packages/boot/app-boot/package.json +++ b/packages/boot/app-boot/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-app-boot", "description": "Shared boot glue for the app bins: .env loading, fail-loud Loader guards, snapshot-aware config resolution, and the Loader boot sequence", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -40,7 +40,7 @@ "@eslint-community/regexpp": "^4.12.2", "ajv": "^8.20.0", "js-yaml": "^4.3.2", - "node-addon-require-builtin": "^0.1.6", + "node-addon-require-builtin": "^0.1.9", "resolve.exports": "^2.0.3", "semver": "^7.8.5" }, @@ -50,7 +50,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/compatibility-preflight.ts b/packages/boot/app-boot/src/compatibility-preflight.ts index 1e33abe184..5b4589b117 100644 --- a/packages/boot/app-boot/src/compatibility-preflight.ts +++ b/packages/boot/app-boot/src/compatibility-preflight.ts @@ -7,7 +7,6 @@ import type { Context } from '@deepseek-ai/cordis' import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' import { applyEntryPatches, entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import { load } from 'js-yaml' -import { applyProfilePatches, type ProfilePatch } from './profile-patches.ts' import { resolvePluginResource } from './package-meta.ts' import { barePackageName } from './profile-resolution/resolver.ts' import type {} from './profile-resolution/service.ts' @@ -179,10 +178,10 @@ function preflight( * @returns One prepared insertion patch for profiles, or the original patches for non-profile callers. */ export function prepareProfilePatches( - ctx: Context, patches: ProfilePatch[], parentURL: string, binName = 'dsh', + ctx: Context, patches: PatchOptions[], parentURL: string, binName = 'dsh', ): PatchOptions[] { if (ctx.get('profileContext') === undefined) return patches - const entries = applyProfilePatches([], patches, patchWarning(ctx)) + const entries = applyEntryPatches([], patches, patchWarning(ctx)) const rows = prepareProfileEntries(ctx, entries, parentURL, binName) return rows.length === 0 ? [] : [{ insert: rows }] } diff --git a/packages/boot/app-boot/src/config-schema/document.ts b/packages/boot/app-boot/src/config-schema/document.ts index 768fb3c152..70428c6671 100644 --- a/packages/boot/app-boot/src/config-schema/document.ts +++ b/packages/boot/app-boot/src/config-schema/document.ts @@ -143,23 +143,13 @@ export async function buildConfigSchemaDocument( required: ['id'], properties: { id: { const: id } }, allOf: [ { not: { required: ['insert'] } }, - { not: { required: ['preset'] } }, { anyOf: [{ not: { required: ['name'] } }, { properties: { name: { enum: ['', target.name] } } }] }, ], }, then: { properties: { config: { $ref: configRef } } }, }) } - definitions.patch = { - ...patchStructure(), allOf: [ref('entryMetadata'), ...patchRules], - properties: { - insert: ref('entryList'), - preset: { - type: 'string', pattern: '\\S', - description: 'Outer preset row id. The remaining patch fields apply to its current config.plugins list; a missing or unaddressable preset fails composition.', - }, - }, - } + definitions.patch = { ...patchStructure(), allOf: [ref('entryMetadata'), ...patchRules] } const positions = new Map(entries.map((entry, index) => [entry.path, index])) diagnostics.sort((left, right) => (positions.get(left.path ?? '') ?? -1) - (positions.get(right.path ?? '') ?? -1)) return { diff --git a/packages/boot/app-boot/src/config-schema/index.ts b/packages/boot/app-boot/src/config-schema/index.ts index e515c961f0..44bb553249 100644 --- a/packages/boot/app-boot/src/config-schema/index.ts +++ b/packages/boot/app-boot/src/config-schema/index.ts @@ -1,6 +1,6 @@ /** Profile schema generation: composition diagnostics, runtime resolution, and boot-free discovery. */ -import type { ProfilePatch } from '../profile-patches.ts' +import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include' import { composeEntries, createRuntimeResolution, type Profile } from '../profile.ts' import { collectConfigSchemas } from './collect.ts' import type { ConfigSchemaDiagnostic, ConfigSchemaDump } from './types.ts' @@ -20,7 +20,7 @@ export type { ConfigSchemaDump, NativeConfigSchema } from './types.ts' */ export async function generateConfigSchema( profile: Profile, - layers: readonly ProfilePatch[][], + layers: readonly PatchOptions[][], installAnchor: string, ): Promise { const diagnostics: ConfigSchemaDiagnostic[] = [] diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index 38abd1f256..fded02c9c8 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -11,13 +11,13 @@ import { readFileSync } from 'node:fs' import { inspect, parseEnv } from 'node:util' import { basename, dirname, isAbsolute, resolve } from 'node:path' import * as yaml from 'js-yaml' -import { Context, type FiberState } from '@deepseek-ai/cordis' -import Loader, { type Entry, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader' -import Include, { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { Context, type Fiber, type FiberState } from '@deepseek-ai/cordis' +import Loader, { type Entry, type EntryGroup, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader' +import Include, { applyEntryPatches, entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import Group from '@deepseek-ai/cordis-plugin-group' import { dshHomePath, resolveDshHome } from '@deepseek-ai/dsh-home-paths' import { createLaunchEnvironmentSnapshot, type LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' -export { readProfilePatches, resolveTelemetryPatch, type ProfileContext, type ProfilePnpmInvocation } from './profile-context.ts' +export { readBundlePatches, readProfilePatches, resolveTelemetryPatch, type ProfileContext, type ProfilePnpmInvocation } from './profile-context.ts' export { sanitizeProfile } from './profile-sanitize.ts' export { getDshRuntimeVersion, evaluatePluginCompatibility, pluginCompatibilityWarning, type PluginCompatibility } from './plugin-compatibility.ts' export { @@ -25,16 +25,14 @@ export { setProfileVersionExemption, type ProfileCompatibility, } from './profile-compatibility.ts' import { prepareProfilePatches } from './compatibility-preflight.ts' -import { applyProfilePatches, compileProfilePatches, profilePatchPreset, prepareLoadedProfilePatches, type ProfilePatch } from './profile-patches.ts' -export { applyProfilePatches, compileProfilePatches, profilePatchPreset, type ProfilePatch, type ProfilePatchWarning } from './profile-patches.ts' +import { ProfileRuntimeResolution, type RuntimeResolution } from './profile.ts' +import { ResolutionRestartRequired } from './profile-resolution/resolver.ts' export { prepareProfileEntries, prepareProfilePatches } from './compatibility-preflight.ts' export { readPluginMeta, resolvePluginResource } from './package-meta.ts' export { ON_DEMAND_BUNDLES, OFFICIAL_ON_DEMAND_CATALOG, type OfficialBundleCatalogEntry } from './official-bundles.ts' -export { realModuleFile } from './profile-resolution/legacy-links.ts' 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, @@ -92,6 +90,7 @@ export { type PluginPackage, type PluginPackagesConfig, } from './profile-resolution/service.ts' +export { ResolutionRestartRequired } from './profile-resolution/resolver.ts' /** * Resolve the config to boot. Replay swaps a `cordis.yml` basename for @@ -268,7 +267,52 @@ const bootstrapIncludes = new WeakMap() // reference `process.env`. const userPatchesSchema = entryListSchema -/** Apply one complete patch generation and wait for Loader activation diagnostics. +/** What a caller of {@link recomposeProfile} already did and requires. */ +export interface ProfileRecompositionOptions { + /** Explicit enablement targets whose existing failures also reject the recomposition. */ + readonly requiredIds?: readonly string[] + /** + * Loader entries that ran before the caller stopped some of them. Each that no longer runs starts again, and each that + * failed afterwards counts as a new failure. + */ + readonly running?: readonly Entry[] +} + +/** The outcome of a {@link recomposeProfile} that applied or kept the composition. */ +export interface ProfileRecomposition { + /** Diagnostics for unchanged pre-existing inactive entries. */ + warnings: string[] + /** Present when the runtime resolution could not publish a moved package or a changed installation mapping. */ + restartReason?: 'package-moved' +} + +/** + * Recompose the profile from its complete patch list, together with its runtime resolution. The rows the generation no + * longer lists are removed first and their disposal finishes while their packages are still mapped; the latest + * generation of an installed, recomputable resolution is published; the compatibility preflight reads the published + * packages; the generation is applied to the root Include; entries that ran, and enabled entries whose import failed, + * start afterwards when the update left them without a running fiber; and activation is judged. A failure before the generation applies, + * including a publication the resolution rejects, which reports `package-moved`, puts the removed rows back at their + * places, starting them again, and starts the entries that ran again. An entry waiting for a service is reported as a + * warning unless it is required. Patches are copied with `structuredClone`, so they hold no functions. + * @param ctx Booted root context. + * @param patches Complete ordered patch list. + * @param binName Diagnostic prefix. + * @param options What the caller already did and requires. + * @returns Diagnostics for unchanged pre-existing inactive entries, and the restart reason of a rejected publication. + * @throws When the root Include is missing; the latest resolution cannot be read or published; preparation or the + * Loader update rejects; or for a new or changed failure, an inactive required entry, a failed entry that ran, or a + * healthy fiber whose disposal rejected. + */ +export function recomposeProfile( + ctx: Context, patches: PatchOptions[], binName: string, options: ProfileRecompositionOptions = {}, +): Promise { + return recompose(ctx, patches, binName, options, true) +} + +/** + * Apply a complete patch list to the root Include and judge activation, leaving the runtime resolution and entries + * whose import failed as they are. * @param ctx Booted root context. * @param patches Complete ordered patch list. * @param binName Diagnostic prefix. @@ -276,67 +320,196 @@ const userPatchesSchema = entryListSchema * @returns Diagnostics for unchanged pre-existing inactive entries; new or changed failures reject. */ export async function reconcileProfilePatches( - ctx: Context, patches: ProfilePatch[], binName: string, requiredIds: readonly string[] = [], + ctx: Context, patches: PatchOptions[], binName: string, requiredIds: readonly string[] = [], ): Promise { - const entry = bootstrapIncludes.get(ctx) - if (entry === undefined) throw new Error(`${binName}: profile reload requires the root Include entry`) - const previousFailures = (await inactiveEntries(ctx)).map(failure => ({ - ...failure, diagnostic: inactiveDiagnostic(failure), fiber: failure.entry.fiber, options: JSON.stringify(failure.entry.options), - })) - // Removed entries leave the Loader store before their async disposers finish. - const previousFibers = [...ctx.loader.entries()].flatMap(row => row.fiber === undefined ? [] : [{ - fiber: row.fiber, failed: row.fiber.state === FIBER_FAILED || row.fiber.state === FIBER_DISPOSED, - }]) - const { patches: _previous, ...includeConfig } = entry.options.config as Include.Config - // The recomposition judges the rows the launch judged, resolved from the file this Include read. - const parentURL = new URL('.', new URL(includeConfig.path, entry.parent.tree.ctx.baseUrl)).href - const initial = readRootEntries(includeConfig.path, parentURL, binName) - const prepared = prepareRootPatches(ctx, patches, includeConfig.path, parentURL, binName, initial) - await drainRetiringEntries(ctx, entry, initial, prepared) - await entry.update({ config: { ...includeConfig, patches: prepared } }) - const results = await Promise.allSettled(previousFibers.map(({ fiber }) => fiber.await())) - await ctx.loader.await() - const failures = await inactiveEntries(ctx) - const introduced = failures.filter(failure => requiredIds.includes(failure.entry.options.id) || !previousFailures.some(previous => - previous.entry === failure.entry && previous.fiber === failure.entry.fiber - && previous.options === JSON.stringify(failure.entry.options) && previous.diagnostic === inactiveDiagnostic(failure))) - if (introduced.length > 0) throw new Error(activationDiagnostic(binName, introduced).trimEnd()) - for (const [index, result] of results.entries()) { - if (result.status === 'rejected' && !previousFibers[index]?.failed) throw result.reason - } - ctx.emit('app-boot/config-reload') - return failures.map(inactiveDiagnostic) + return (await recompose(ctx, patches, binName, { requiredIds }, false)).warnings } -/** Disappearing and literal-disabled rows release singleton services before their replacements activate. */ -async function drainRetiringEntries( - ctx: Context, root: Entry, initial: EntryOptions[], patches: readonly ProfilePatch[], -): Promise { - const rows = applyProfilePatches(initial, patches) - const next = new Map() - const visit = (rows: EntryOptions[], outerDisabled = false): void => { - for (const row of rows) { - const disabled = outerDisabled || row.disabled === true - next.set(row.id, !row.group && disabled) - if (row.group && Array.isArray(row.config)) visit(row.config as EntryOptions[], disabled) +async function recompose( + ctx: Context, patches: PatchOptions[], binName: string, options: ProfileRecompositionOptions, withResolution: boolean, +): Promise { + const { requiredIds = [], running = [] } = options + let applying = false + // The rows stopped first, which a failure before the generation applies puts back. + let stopped: StoppedRow[] = [] + try { + const entry = bootstrapIncludes.get(ctx) + if (entry === undefined) throw new Error(`${binName}: profile reload requires the root Include entry`) + // Reading the prior state imports nothing, so plugin code does not run before the next resolution publishes. + const previousFailures = (await inactiveEntries(ctx, false)).map((failure): RecordedFailure => ({ + entry: failure.entry, fiber: failure.entry.fiber, options: JSON.stringify(failure.entry.options), + // An entry without a running fiber has no import error yet; the judgment after the update reads it. + diagnostic: failure.entry.fiber?.uid ? reloadDiagnostic(failure) : undefined, + })) + // Removed entries leave the Loader store before their async disposers finish. + const previousFibers = [...ctx.loader.entries()].flatMap(row => row.fiber === undefined ? [] : [{ + fiber: row.fiber, failed: row.fiber.state === FIBER_FAILED || row.fiber.state === FIBER_DISPOSED, + }]) + const { patches: previous = [], ...includeConfig } = entry.options.config as Include.Config + const current = withResolution ? ctx.get('pluginPackages')?.resolution : undefined + // A plain-data resolution has no inputs to recompute from. + const successor = current instanceof ProfileRuntimeResolution ? await current.computeLatestResolution() : undefined + if (successor !== undefined) { + // Rows the generation no longer lists stop, and their disposal finishes, while their packages are still mapped. + const listed = rowIds(structuredClone(patches)) + const composed = rowIds(structuredClone(previous)) + // Only rows of the root Include's tree; a nested Include file has its own ids. + const tree = entry.subgroup?.tree + const dropped = [...ctx.loader.entries()] + .filter(row => row.parent.tree === tree && composed.has(row.options.id) && !listed.has(row.options.id)) + // A dropped group takes its rows with it. + const ids = new Set(dropped.map(row => row.options.id)) + const topmost = dropped.filter(row => !ids.has(row.parent.ctx.fiber.entry?.options.id as string)) + // The Loader marks the options of a row it stops, so the copy taken before is the one restored. + stopped = topmost.map(row => ({ + group: row.parent, options: structuredClone(row.options), + index: row.parent.data.indexOf(row.options), + })) + if (topmost.length > 0) { + const fibers = dropped.flatMap(row => row.fiber === undefined ? [] : [row.fiber]) + for (const row of topmost) { + // A disabled row's disposal is the Loader's own, so it does not rewrite the profile's configuration file. + row.options.disabled = true + row.parent.remove(row.options.id) + } + await Promise.allSettled(fibers.map(fiber => fiber.await())) + await ctx.loader.await() + } + try { + publish(ctx, successor) + } catch (error) { + if (!(error instanceof ResolutionRestartRequired)) throw error + // The generation waits for the mappings the rejected publication would change. + return { warnings: [], restartReason: 'package-moved' } + } + } + // The recomposition judges the rows the launch judged, resolved from the file this Include read. + const parentURL = new URL('.', new URL(includeConfig.path, entry.parent.tree.ctx.baseUrl)).href + const prepared = prepareProfilePatches(ctx, patches, parentURL, binName) + applying = true + const retried = [...new Set([...running, ...withResolution ? [...ctx.loader.entries()].filter(importFailed) : []])] + try { + await entry.update({ config: { ...includeConfig, patches: prepared } }) + } finally { + await resume(ctx, retried) + } + const results = await Promise.allSettled(previousFibers.map(({ fiber }) => fiber.await())) + await ctx.loader.await() + const failures = await inactiveEntries(ctx) + const introduced = failures.filter((failure) => { + if (requiredIds.includes(failure.entry.options.id)) return true + // An entry waiting for a service starts once a provider appears. + if (failure.outcome.kind === 'pending') return false + // An entry that ran before the caller stopped it is a new failure even when it failed the same way before. + if (running.includes(failure.entry)) return true + return !previousFailures.some(previous => sameFailure(previous, failure)) + }) + if (introduced.length > 0) throw new Error(activationDiagnostic(binName, introduced, false).trimEnd()) + for (const [index, result] of results.entries()) { + if (result.status === 'rejected' && !previousFibers[index]?.failed) throw result.reason + } + ctx.emit('app-boot/config-reload') + return { warnings: failures.map(reloadDiagnostic) } + } finally { + // Before the generation applies, the rows removed first and the entries the caller stopped run again. + if (!applying && (stopped.length > 0 || running.length > 0)) { + try { + // Ascending original positions put each row back where it was. + for (const { group, options, index } of stopped.toSorted((left, right) => left.index - right.index)) { + // `create` starts the entry but leaves the group's option list as it is; that list is what the next update + // compares against to remove the row and what the Include writes back. + group.data.splice(index, 0, options) + await group.create(options) + } + await resume(ctx, running) + // A restored row is a new Loader entry with the id of the one that ran. + const ran = new Set(running.map(row => row.options.id)) + for (const failure of await inactiveEntries(ctx)) { + if (ran.has(failure.entry.options.id)) ctx.logger.warn(`${binName}: ${reloadDiagnostic(failure)}`) + } + } catch (error) { + // The recomposition's own failure is the outcome. + ctx.logger.warn(error) + } } } - visit(rows) - const retiring = [...ctx.loader.entries()].flatMap((entry) => { - const fiber = entry.fiber - return entry.parent.tree === root.subtree && fiber?.state === FIBER_ACTIVE - && (!next.has(entry.options.id) || next.get(entry.options.id)) ? [fiber] : [] - }) - await Promise.all(retiring.map(async (fiber) => { - await fiber.dispose() - await fiber.await() - })) +} + +/** An inactive entry as a recomposition found it before changing anything. */ +interface RecordedFailure { + entry: Entry + fiber: Fiber | undefined + /** The entry's options as JSON. */ + options: string + /** The reload diagnostic; `undefined` for an import failure, which matches any diagnostic. */ + diagnostic: string | undefined +} + +/** Whether an inactive entry is the failure recorded before: the same entry, fiber and options, and a matching diagnostic. */ +function sameFailure(previous: RecordedFailure, failure: InactiveEntry): boolean { + return previous.entry === failure.entry && previous.fiber === failure.entry.fiber + && previous.options === JSON.stringify(failure.entry.options) + && (previous.diagnostic === undefined || previous.diagnostic === reloadDiagnostic(failure)) +} + +/** A row a recomposition removed before publishing, with its place in its group. */ +interface StoppedRow { + group: EntryGroup + options: EntryOptions + index: number +} + +/** The ids of the rows a patch list inserts, including the rows of groups. */ +function rowIds(patches: readonly PatchOptions[]): Set { + const ids = new Set() + const visit = (rows: readonly EntryOptions[]): void => { + for (const row of rows) { + ids.add(row.id) + // A group keeps its rows in its configuration. + if ((row.group === true || row.name === 'cordis:group') && Array.isArray(row.config)) visit(row.config as EntryOptions[]) + } + } + // Patch warnings are logged when the generation itself is prepared. + visit(applyEntryPatches([], patches as PatchOptions[], () => {})) + return ids +} + +/** Publish a generation unless it maps exactly what is published, which would only drop the package caches. */ +function publish(ctx: Context, next: RuntimeResolution): void { + const table = ({ localPackageNames, entries, linkedRoots }: RuntimeResolution): string => + JSON.stringify([localPackageNames, entries, linkedRoots]) + const packages = ctx.pluginPackages + if (table(packages.resolution as RuntimeResolution) !== table(next)) packages.replace(next) +} + +/** Whether an enabled entry below a running parent has no fiber or keeps the disposed fiber of a failed import. */ +function importFailed(entry: Entry): boolean { + return enabledEntry(entry) && entry.parent.ctx.fiber.uid !== null + && (entry.fiber === undefined || entry.fiber.state === FIBER_DISPOSED) +} + +/** Whether an entry is enabled now; a throwing `disabled` expression counts as disabled. */ +function enabledEntry(entry: Entry): boolean { + try { + return !entry.disabled + } catch (_error) { + // Judgment reports the expression failure. + return false + } +} + +/** Start invalidated entries the Loader still holds without a running fiber, then wait until it settles. */ +async function resume(ctx: Context, invalidated: readonly Entry[]): Promise { + const entries = new Set(ctx.loader.entries()) + // A stopped entry starts again on update even with unchanged options; an unchanged Include does not update its rows. + for (const row of invalidated) if (entries.has(row) && !row.fiber?.uid) await row.update({}, false, true) + await ctx.loader.await() } /** - * Load an optional patch-list file: a top-level YAML array of profile patch - * entries: id-targeted overrides, `insert` lists, and preset-scoped operations, - * with `!!js` expressions allowed. A missing + * Load an optional patch-list file: a top-level YAML array of loader patch + * entries (`@deepseek-ai/cordis-plugin-include`'s `PatchOptions`): id-targeted config + * overrides and `insert` lists, with `!!js` expressions allowed. A missing * file means "no layer"; an unreadable, unparsable, or non-array file throws — * a present patch file that cannot apply is a misconfiguration and must fail * loud at boot, never be silently skipped. @@ -344,7 +517,7 @@ async function drainRetiringEntries( * @param file - absolute path of the patch file. * @returns the parsed patches, or `undefined` when the file does not exist. */ -export function loadOptionalPatches(binName: string, file: string): ProfilePatch[] | undefined { +export function loadOptionalPatches(binName: string, file: string): PatchOptions[] | undefined { let content: string try { content = readFileSync(file, 'utf8') @@ -364,7 +537,7 @@ export function loadOptionalPatches(binName: string, file: string): ProfilePatch * @param file - absolute path of the overlay file. * @returns the parsed patch list. */ -export function loadOverlayPatches(binName: string, file: string): ProfilePatch[] { +export function loadOverlayPatches(binName: string, file: string): PatchOptions[] { let content: string try { content = readFileSync(file, 'utf8') @@ -375,30 +548,24 @@ export function loadOverlayPatches(binName: string, file: string): ProfilePatch[ } /** Convert inserted filesystem paths to file URLs, anchoring relative paths beside the patch; keep assertion names literal. */ -function anchorInsertedPluginNames(patches: ProfilePatch[], file: string): ProfilePatch[] { +function anchorInsertedPluginNames(patches: PatchOptions[], file: string): PatchOptions[] { const base = dirname(resolve(file)) const visit = (entry: EntryOptions): void => { if (typeof entry.name === 'string' && (isAbsolute(entry.name) || entry.name.startsWith('./') || entry.name.startsWith('../'))) { entry.name = pathToFileURL(resolve(base, entry.name)).href } if (entry.group && Array.isArray(entry.config)) entry.config.forEach(visit) - const config = entry.config as { plugins?: unknown } | undefined - if (entry.name === '@deepseek-ai/dsh-agent-preset' && Array.isArray(config?.plugins)) { - (config.plugins as EntryOptions[]).forEach(visit) - } - } - for (const patch of patches) { - patch.insert?.forEach(visit) } + for (const patch of patches) patch.insert?.forEach(visit) return patches } /** * Parse one loader patch list: a top-level YAML array of - * profile patches (id-targeted overrides, `insert` lists, and preset-scoped - * operations, with `!!js` expressions allowed). Invalid lists and malformed - * preset targets throw because they cannot be applied. An ordinary or scoped - * child patch whose target is absent stays a per-entry Loader warning; a - * missing outer preset target fails composition. + * `@deepseek-ai/cordis-plugin-include` `PatchOptions` (id-targeted config overrides and + * `insert` lists, `!!js` expressions allowed). Every invalid field or value throws, + * because a patch file that cannot be applied at all is a misconfiguration; a + * single patch whose target row is absent stays a per-entry Loader warning, so + * one overlay shared across surfaces does not have to match every tree. * @param binName - the diagnostic prefix on the thrown error. * @param file - the source path, quoted in errors. * @param content - the file's text. @@ -407,7 +574,7 @@ function anchorInsertedPluginNames(patches: ProfilePatch[], file: string): Profi */ function parsePatchList( binName: string, file: string, content: string, label: string, -): ProfilePatch[] { +): PatchOptions[] { let parsed: unknown try { parsed = yaml.load(content, { schema: userPatchesSchema }) @@ -422,7 +589,7 @@ function parsePatchList( throw new Error(`${binName}: ${label} entry ${index + 1} in ${file} must be a mapping (a loader patch entry)`) } }) - return anchorInsertedPluginNames(prepareLoadedProfilePatches(parsed as ProfilePatch[], file, binName), file) + return anchorInsertedPluginNames(parsed as PatchOptions[], file) } /** One overlay patch list with the source label printed in dump comments. */ @@ -430,13 +597,13 @@ export interface ConfigDumpLayer { /** Source name shown in dump comments (a file basename or path). */ label: string /** The layer's patches, from {@link loadOverlayPatches} / {@link loadOptionalPatches}. */ - patches: ProfilePatch[] + patches: PatchOptions[] } /** * Compose the configured entry list: parse the base config file with the - * include's entry-list dialect, compile preset operations, then apply the - * flattened native patch list through Include's `applyEntryPatches` — the + * include's entry-list dialect, apply every layer's patches as ONE flattened + * list through the include's own patch algorithm (`applyEntryPatches`) — the * same call `boot()` makes, so even patch-visibility corner cases (a later * layer targeting a group child a plain config replacement introduced, which * the single-pass id index never sees) compose identically — then render the @@ -456,8 +623,8 @@ export interface ConfigDumpLayer { * A patch that matches no row is reported through `warn` with its layer * label, mirroring the Loader's boot-time warning. Earlier layers' patches * see an identical preceding state in every snapshot that includes them, so - * additional warnings belong to the added layer. Warning multiplicity is - * preserved when scoped and ordinary diagnostics have different ordering. + * each snapshot's warning list extends the previous one and the new tail + * belongs to the added layer. * @param binName - the diagnostic prefix on read/parse errors. * @param absoluteConfigPath - the base config file `boot()` would include. * @param layers - overlay layers in application order (later wins). @@ -490,14 +657,16 @@ export function renderConfigDump( // YAML parsing yields untyped rows; the include validates each entry // at mount, and the dump prints whatever the file holds, so `EntryOptions` // here is structural trust in the same file `boot()` would include. - const base = parsed as EntryOptions[] + const base = parsed as Parameters[0] // snapshot_k = ONE application of layers 1..k flattened, using the exact // arguments boot passes for that prefix. snapshot_N is the mounted composition. - // The compiler clones patch objects for each snapshot: native insertions retain - // references, so sharing them would let later snapshots mutate earlier results. - const snapshot = (count: number, warnings: string[]): EntryOptions[] => { - const flattened = layers.slice(0, count).flatMap(layer => layer.patches) - return applyProfilePatches(base, flattened, (message: string, ...args: unknown[]) => { + // The patches are cloned per call: applyEntryPatches detaches the entry + // list but pushes `insert` rows by reference from the patch list, so + // sharing patch objects across snapshot calls would leak a later + // snapshot's mutations into an earlier one's result. + const snapshot = (count: number, warnings: string[]): ReturnType => { + const flattened = structuredClone(layers.slice(0, count).flatMap(layer => layer.patches)) + return applyEntryPatches(base, flattened, (message: string, ...args: unknown[]) => { // The include logs through cordis's printf-style logger (`%C` = code); a // dump has no logger, so substitute inline for a plain line. let index = 0 @@ -514,11 +683,8 @@ export function renderConfigDump( if (layer === undefined) continue const warnings: string[] = [] composed = snapshot(count, warnings) - const remaining = [...previousWarnings] - for (const line of warnings) { - const previousIndex = remaining.indexOf(line) - if (previousIndex >= 0) remaining.splice(previousIndex, 1) - else warn(`${binName}: [${layer.label}] ${line}`) + for (const line of warnings.slice(previousWarnings.length)) { + warn(`${binName}: [${layer.label}] ${line}`) } const before = previous.map(entry => JSON.stringify(entry)) for (let index = 0; index < composed.length; index += 1) { @@ -562,22 +728,6 @@ function groupedDump( return lines.join('\n') + '\n' } -/** Compile profile operations before passing an ordinary patch list to the root Include. */ -function readRootEntries(configPath: string, parentURL: string, binName: string): EntryOptions[] { - const parsed: unknown = yaml.load(readFileSync(new URL(configPath, parentURL), 'utf8'), { schema: entryListSchema }) - if (!Array.isArray(parsed)) throw new Error(`${binName}: config ${configPath} must be a top-level array of entries`) - return parsed as EntryOptions[] -} - -function prepareRootPatches( - ctx: Context, patches: ProfilePatch[], configPath: string, parentURL: string, binName: string, initial?: EntryOptions[], -): ProfilePatch[] { - if (ctx.get('profileContext') !== undefined) return prepareProfilePatches(ctx, patches, parentURL, binName) - if (!patches.some(patch => profilePatchPreset(patch) !== undefined)) return patches - return compileProfilePatches(initial ?? readRootEntries(configPath, parentURL, binName), patches, - (message, ...args) => { ctx.logger.warn(message, ...args) }) -} - /** * Mount and remember the exact root Include entry used by app boot and user patch-layer HMR. * @param ctx - context carrying an initialized Loader service. @@ -593,7 +743,7 @@ function prepareRootPatches( export async function mountRootInclude( ctx: Context, absoluteConfigPath: string, - patches: readonly ProfilePatch[] = [], + patches: readonly PatchOptions[] = [], bareModuleBaseUrl?: string, binName = 'dsh', ): Promise { @@ -621,7 +771,7 @@ export async function mountRootInclude( // diagnostics unstable across runs (and snapshot fixtures). // The launcher's own copy is prepared here: compatibility decisions must be made before the root // Include imports anything, and they change no profile patch layer, manifest, or bundle list. - const prepared = prepareRootPatches(ctx, [...patches], pathToFileURL(absoluteConfigPath).href, pathToFileURL(dirname(absoluteConfigPath)).href + '/', binName) + const prepared = prepareProfilePatches(ctx, [...patches], pathToFileURL(dirname(absoluteConfigPath)).href + '/', binName) const includeConfig: Include.Config = { path: pathToFileURL(absoluteConfigPath).href, ...prepared.length > 0 ? { patches: prepared } : {}, @@ -801,6 +951,7 @@ const FIBER_DISPOSED = 4 as FiberState.DISPOSED const requiredStartupEntryIds = new Set([ 'agent-loop', 'webserver', + 'web-runtime', 'modules', 'connection', 'headless-runner', @@ -809,7 +960,7 @@ const requiredStartupEntryIds = new Set([ ]) /** Render plugin stacks, nested causes, and aggregate member failures once per error. */ -function formatActivationError(error: unknown): string { +function formatActivationError(error: unknown, stacks = true): string { const details: string[] = [] const seen = new Set() function visit(value: unknown): void { @@ -819,7 +970,7 @@ function formatActivationError(error: unknown): string { } if (seen.has(value)) return seen.add(value) - details.push(value.stack ?? value.message) + details.push(stacks ? value.stack ?? value.message : String(value)) if (value.cause !== undefined) visit(value.cause) if (value instanceof AggregateError) value.errors.forEach(visit) } @@ -871,12 +1022,24 @@ export class StartupError extends Error { } } +/** The error importing an entry's module raises now, which Node returns from its cache for a module that failed before. */ +async function importFailure(entry: Entry): Promise { + try { + await entry.parent.tree.import(entry.options.name) + return undefined + } catch (error) { + return error + } +} + /** * Collect Loader activation failures and disabled-expression errors. Failed * fibers are awaited to recover their recorded rejection reason and coalesce * duplicate Loader notifications through the next process rejection checkpoint. + * An entry whose import failed reports the error importing it raises now; without + * `importNow` nothing is imported and the entry reports a failed import without the import error. */ -async function inactiveEntries(ctx: Context): Promise { +async function inactiveEntries(ctx: Context, importNow = true): Promise { const failures: InactiveEntry[] = [] const rejectionReasons: unknown[] = [] for (const entry of ctx.loader.entries()) { @@ -887,8 +1050,12 @@ async function inactiveEntries(ctx: Context): Promise { continue } const fiber = entry.fiber - if (fiber === undefined) { - failures.push({ entry, outcome: { kind: 'failed', error: 'failed to import' } }) + // An entry whose import failed has no fiber, or keeps the disposed fiber of its previous activation. + if (fiber === undefined || fiber.state === FIBER_DISPOSED) { + const error = importNow ? await importFailure(entry) : undefined + failures.push({ entry, outcome: error === undefined + ? { kind: 'failed', error: fiber === undefined ? 'failed to import' : `fiber state ${String(fiber.state)}` } + : { kind: 'failed', error, phase: 'failed to import' } }) continue } const state = fiber.state @@ -917,22 +1084,28 @@ async function inactiveEntries(ctx: Context): Promise { } /** Render one failed plugin's original error and activation phase. */ -function failureDetail(outcome: Extract): string { - return `${outcome.phase === undefined ? '' : `${outcome.phase}: `}${formatActivationError(outcome.error)}` +function failureDetail(outcome: Extract, stacks = true): string { + return `${outcome.phase === undefined ? '' : `${outcome.phase}: `}${formatActivationError(outcome.error, stacks)}` } /** Render optional-only warnings without changing startup policy. */ function activationDiagnostic( binName: string, failures: readonly InactiveEntry[], + stacks = true, ): string { const noun = failures.length === 1 ? 'entry' : 'entries' - return `${binName}: warning: ${String(failures.length)} ${noun} did not activate\n${failures.map(inactiveDiagnostic).join('\n')}\n` + return `${binName}: warning: ${String(failures.length)} ${noun} did not activate\n${failures.map(failure => inactiveDiagnostic(failure, stacks)).join('\n')}\n` +} + +/** Per-entry reload text, which people read through the Web UI and agents, so it carries error messages without stack frames. */ +function reloadDiagnostic(failure: InactiveEntry): string { + return inactiveDiagnostic(failure, false) } /** Stable per-entry text for reload comparisons and optional warnings. */ -function inactiveDiagnostic({ entry, outcome }: InactiveEntry): string { - const detail = outcome.kind === 'failed' ? failureDetail(outcome) +function inactiveDiagnostic({ entry, outcome }: InactiveEntry, stacks = true): string { + const detail = outcome.kind === 'failed' ? failureDetail(outcome, stacks) : `pending (waiting for ${outcome.missing.length === 1 ? 'service' : 'services'}: ${outcome.missing.join(', ') || 'unknown'})` return `${entry.options.id} (${entry.options.name}): ${detail}` } @@ -1027,7 +1200,7 @@ export async function auditStartupEntries( export async function boot( binName: string, absoluteConfigPath: string, - patches?: ProfilePatch[], + patches?: PatchOptions[], prepare?: (ctx: Context) => Promise | void, bareModuleBaseUrl?: string, ): Promise { @@ -1084,38 +1257,10 @@ export async function boot( deepest = deepest.cause } const stack = deepest instanceof AggregateError - ? `\n${deepest.stack ?? deepest.message}\n${deepest.errors.map(formatActivationError).join('\n')}` + ? `\n${deepest.stack ?? deepest.message}\n${deepest.errors.map(error => formatActivationError(error)).join('\n')}` : deepest instanceof Error && deepest !== cause ? `\n${deepest.stack ?? deepest.message}` : '' throw new Error(`${binName}: ${stage}: ${detail}${stack}`, { cause }) } finally { 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/src/profile-context.ts b/packages/boot/app-boot/src/profile-context.ts index 4f299ae699..e2ebfad5ce 100644 --- a/packages/boot/app-boot/src/profile-context.ts +++ b/packages/boot/app-boot/src/profile-context.ts @@ -2,7 +2,7 @@ import { join } from 'node:path' import { composeEntries, loadProfileDirectory, PROFILE_PATCH_FILENAME, type Profile } from './profile.ts' import { loadOptionalPatches } from './index.ts' -import { cloneProfilePatches, type ProfilePatch } from './profile-patches.ts' +import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include' /** Application-owned package manager executable; environment applies only to package operations. */ export interface ProfilePnpmInvocation { @@ -24,7 +24,7 @@ export interface ProfileContext { /** Bundle packages used to start this process, before any persisted edits. */ readonly startedBundles: readonly string[] /** Parsed command-line overlays, applied above profile and home patches. */ - readonly overlays: readonly ProfilePatch[] + readonly overlays: readonly PatchOptions[] /** Launch-time DSH_TELEMETRY_DISABLED value; any non-empty value opts out. */ readonly telemetryDisabledEnv: string | undefined } @@ -49,21 +49,31 @@ const TELEMETRY_ROW_ID = 'session-telemetry-otel' * @param hasRow - whether the composition carries the telemetry row. * @returns the disable patch, or `undefined` when no hard-disable patch is required. */ -export function resolveTelemetryPatch(disabledEnv: string | undefined, hasRow: boolean): ProfilePatch | undefined { +export function resolveTelemetryPatch(disabledEnv: string | undefined, hasRow: boolean): PatchOptions | undefined { if ((disabledEnv ?? '') === '' || !hasRow) return undefined return { id: TELEMETRY_ROW_ID, disabled: true } } +/** Read the selected bundles' patches, which apply before the profile patch file. + * @param binName Diagnostic prefix for malformed or missing configuration. + * @param context Data supplied by the profile launcher. + * @param initialProfile Already loaded startup profile; omitted reads the current files. + * @returns Bundle patches in application order. + */ +export function readBundlePatches(binName: string, context: ProfileContext, initialProfile?: Profile): PatchOptions[] { + const profile = initialProfile ?? loadProfileDirectory(binName, context.dir, context.installAnchor, { userLayer: false }) + return profile.layers.flatMap(layer => layer.patches) +} + /** Read current bundle and user layers with the launch-time overlays. * @param binName Diagnostic prefix for malformed or missing configuration. * @param context Data supplied by the profile launcher. * @param initialProfile Already loaded startup profile; omitted reads the current files. * @returns Detached ordered patches; this function does not update the Loader. */ -export function readProfilePatches(binName: string, context: ProfileContext, initialProfile?: Profile): ProfilePatch[] { - const profile = initialProfile ?? loadProfileDirectory(binName, context.dir, context.installAnchor, { userLayer: false }) - const patches = cloneProfilePatches([ - ...profile.layers.flatMap(layer => layer.patches), +export function readProfilePatches(binName: string, context: ProfileContext, initialProfile?: Profile): PatchOptions[] { + const patches = structuredClone([ + ...readBundlePatches(binName, context, initialProfile), ...(initialProfile?.patches ?? loadOptionalPatches(binName, context.patchPath) ?? []), ...(loadOptionalPatches(binName, join(context.home, PROFILE_PATCH_FILENAME)) ?? []), ...context.overlays, diff --git a/packages/boot/app-boot/src/profile-patches.ts b/packages/boot/app-boot/src/profile-patches.ts deleted file mode 100644 index d7f34ab539..0000000000 --- a/packages/boot/app-boot/src/profile-patches.ts +++ /dev/null @@ -1,162 +0,0 @@ -/** Compile preset-scoped profile operations to the native Include patch language. */ - -import { createHash } from 'node:crypto' -import { applyEntryPatches, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' -import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' -import { realModuleFile } from './profile-resolution/legacy-links.ts' - -/** A native entry patch, optionally applied inside one preset row's `config.plugins`. */ -export interface ProfilePatch extends PatchOptions { - /** Literal id of an addressable outer preset row; `id` then addresses one of its child rows. */ - preset?: string -} - -interface PatchSource { readonly binName: string; readonly file: string; readonly operation: number } -const patchSources = new WeakMap() - -function sourcedError(patch: ProfilePatch, error: unknown): unknown { - const source = patchSources.get(patch) - return source === undefined ? error : new Error( - `${source.binName}: ${error instanceof Error ? error.message : String(error)} in ${source.file} (patch ${source.operation + 1})`, - { cause: error }, - ) -} - -/** Clone patch data while preserving the file attribution held outside its serialized fields. - * @param patches Complete ordered patches, possibly loaded from files. - * @returns Detached patches with the same diagnostic sources and shared-reference relationships. - */ -export function cloneProfilePatches(patches: readonly ProfilePatch[]): ProfilePatch[] { - const copied = structuredClone([...patches]) - const sources = patches.map(patch => patchSources.get(patch)) - copied.forEach((patch, index) => { - const source = sources[index] - if (source !== undefined) patchSources.set(patch, source) - }) - return copied -} - -/** Attach source diagnostics and stable internal identities to parsed scoped insertions. - * @param patches Parsed file patches, modified before they reach any composition consumer. - * @param file Declaring patch file; its canonical path distinguishes anonymous contributions. - * @param binName Diagnostic prefix. - * @returns The same patches, with anonymous scoped rows identified by file and position. - * @throws When a preset target is malformed, naming its declaring file and operation. - */ -export function prepareLoadedProfilePatches(patches: ProfilePatch[], file: string, binName: string): ProfilePatch[] { - const canonical = realModuleFile(file) - patches.forEach((patch, operation) => { - patchSources.set(patch, { binName, file, operation }) - try { - if (profilePatchPreset(patch) === undefined || patch.insert === undefined) return - const identify = (rows: EntryOptions[], parent: readonly number[]): void => { - rows.forEach((row, index) => { - const position = [...parent, index] - if (!row.id) row.id = `__dsh_profile_${createHash('sha256').update(JSON.stringify([canonical, operation, position])).digest('hex').slice(0, 32)}` - if (row.group && Array.isArray(row.config)) identify(row.config as EntryOptions[], position) - }) - } - identify(patch.insert, []) - } catch (error) { - throw sourcedError(patch, error) - } - }) - return patches -} - -/** Native Include diagnostic arguments. - * @param message Diagnostic format; `%C` marks a value rendered as code. - * @param args Values substituted into the diagnostic format. - */ -export type ProfilePatchWarning = (message: string, ...args: unknown[]) => void - -function visitRows(rows: readonly EntryOptions[], visit: (row: EntryOptions) => void): void { - for (const row of rows) { - visit(row) - if (row.group && Array.isArray(row.config)) visitRows(row.config as EntryOptions[], visit) - } -} - -/** Validate the profile-only target while keeping native patch fields under Include's existing rules. - * @param patch Parsed or programmatically supplied profile patch. - * @returns The literal outer row id, or undefined for an ordinary patch. - * @throws When a declared preset target is not a nonempty literal string. - */ -export function profilePatchPreset(patch: ProfilePatch): string | undefined { - if (!Object.hasOwn(patch, 'preset')) return undefined - if (typeof patch.preset !== 'string' || patch.preset.trim() === '') { - throw new Error('profile patch preset must be a nonempty literal row id') - } - return patch.preset -} - -function targetOf(initial: EntryOptions[], patches: PatchOptions[], preset: string): EntryOptions { - // The native index retains replaced-away children and never indexes replacement-created children. - // A marker override locates its actual reachable target without rebuilding that index from the result. - const marker = {} - const rows = applyEntryPatches(initial, [...structuredClone(patches), { id: preset, inject: marker }], () => {}) - let target: EntryOptions | undefined - visitRows(rows, (row) => { if (row.inject === marker) target = row }) - if (target === undefined) throw new Error(`profile patch preset ${JSON.stringify(preset)} is missing or not addressable`) - const config: unknown = target.config - if (config === null || typeof config !== 'object' || Array.isArray(config) || !Array.isArray(Reflect.get(config, 'plugins'))) { - throw new Error(`profile patch preset ${JSON.stringify(preset)} must have a literal config.plugins entry list`) - } - return target -} - -function assertInsertedIds(preset: string, rows: readonly EntryOptions[]): void { - const ids = new Set() - visitRows(rows, (row) => { - if (!row.id) return - if (ids.has(row.id)) throw new Error(`profile patch preset ${JSON.stringify(preset)} has duplicate entry id ${JSON.stringify(row.id)}`) - ids.add(row.id) - }) -} - -/** Lower preset operations to native whole-config replacements without changing native root patch indexing. - * Each scoped operation sees the then-current preset children. Inputs remain unchanged. - * @param initial Root entries before profile patches. - * @param patches Complete ordered profile patch list. - * @param warn Diagnostic sink for scoped child patches; ordinary patches report when Include applies the result. - * @returns Detached native patches, suitable for the root Include. - * @throws For malformed or unaddressable preset targets and duplicate inserted child ids. - */ -export function compileProfilePatches( - initial: EntryOptions[], patches: readonly ProfilePatch[], warn: ProfilePatchWarning = () => {}, -): PatchOptions[] { - const lowered: PatchOptions[] = [] - for (const patch of cloneProfilePatches(patches)) { - try { - const preset = profilePatchPreset(patch) - if (preset === undefined) { - lowered.push(patch) - continue - } - const target = targetOf(initial, lowered, preset) - const config = target.config as Record & { plugins: EntryOptions[] } - const { preset: _preset, ...operation } = patch - const plugins = applyEntryPatches(config.plugins, [operation], (message: string, ...args: unknown[]) => { - warn(`preset ${JSON.stringify(preset)}: ${message}`, ...args) - }) - if (operation.insert !== undefined) assertInsertedIds(preset, plugins) - lowered.push({ id: preset, config: { ...config, plugins } }) - } catch (error) { - throw sourcedError(patch, error) - } - } - return lowered -} - -/** Compose root entries and profile patches with the same compiler used for startup and reload. - * @param initial Root entries before profile patches. - * @param patches Complete ordered profile patch list. - * @param warn Diagnostic sink for unmatched ordinary and scoped child patches. - * @returns The effective entry list, with expressions unevaluated. - * @throws For malformed or unaddressable preset targets and duplicate inserted child ids. - */ -export function applyProfilePatches( - initial: EntryOptions[], patches: readonly ProfilePatch[], warn: ProfilePatchWarning = () => {}, -): EntryOptions[] { - return applyEntryPatches(initial, compileProfilePatches(initial, patches, warn), warn) -} diff --git a/packages/boot/app-boot/src/profile-resolution/resolver.ts b/packages/boot/app-boot/src/profile-resolution/resolver.ts index 85c530665d..60fce4f032 100644 --- a/packages/boot/app-boot/src/profile-resolution/resolver.ts +++ b/packages/boot/app-boot/src/profile-resolution/resolver.ts @@ -2,7 +2,7 @@ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs' import { createRequire, isBuiltin } from 'node:module' -import { basename, dirname, join, resolve, sep } from 'node:path' +import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { getEnvironmentData, setEnvironmentData } from 'node:worker_threads' import type { ModuleLoaderV1, ModuleLoaderV2, ResolveResult } from '@deepseek-ai/cordis-plugin-loader' @@ -100,8 +100,13 @@ interface ParentRoutes { type ResolutionRoutes = Map +/** A published entry with the real directory its modules load from. */ +interface CompiledEntry extends RuntimeResolutionEntry { + readonly realDir: string +} + interface CompiledResolution { - readonly entries: ReadonlyMap + readonly entries: ReadonlyMap readonly profilesDir: string readonly profileDir: string | undefined readonly profilePaths: readonly string[] @@ -113,6 +118,15 @@ interface CompiledResolution { readonly cjsRoutes: ResolutionRoutes } +/** A successor resolution the running process cannot adopt, such as a retained mapping in another directory; it waits for a restart. */ +export class ResolutionRestartRequired extends Error { + /** @param message Diagnostic naming the rejected changes. */ + constructor(message: string) { + super(message) + this.name = 'ResolutionRestartRequired' + } +} + /** Active interception in one Node isolate. */ export interface RuntimeInterception { /** @@ -125,13 +139,16 @@ export interface RuntimeInterception { packageDir(specifier: string, parentURL: string): string | undefined /** * Atomically publish a complete successor and fresh caches. Profile-scoped mappings, local names, and linked - * roots may be removed; removed roots stop intercepting uncovered directories. Existing modules and Node caches - * remain intact, so callers remove a package only after its plugins stop. - * A retained profile mapping may change its declarer if its normalized directory, version, and scope stay unchanged. + * roots may be removed; removed roots stop intercepting uncovered directories. A retained profile mapping may + * change its version and declarer when its normalized directory and scope stay unchanged, as when a package is + * upgraded in place. Existing modules and Node caches remain intact: callers remove a package only after its + * plugins stop, and replace the loaded modules of a package upgraded in place separately. + * A previously published link name may point to another real directory; callers stop the plugins of its previous + * target first, as removing and installing the package again does. * @param successor - fully constructed generation retaining the installation mappings. - * @throws when the profile scope, a retained directory, version, scope, or installation declarer changes; - * an installation mapping is removed; a new local name overrides an existing mapping; or a previously published - * link name selects a different real directory. + * @throws when the profile scope changes; and `ResolutionRestartRequired` when a retained profile mapping's real + * directory or scope, or an installation version or declarer changes; an installation mapping is removed; or a new + * local name overrides an existing mapping. */ replace(successor: RuntimeResolution): void /** Restore the native resolver methods. Interceptions dispose in reverse order. */ @@ -153,6 +170,18 @@ export function barePackageName(request: string): string | undefined { return second < 0 ? request : request.slice(0, second) } +/** The JavaScript and native real paths of an existing directory; none for a directory that no longer exists. */ +function realSpellings(path: string): string[] { + try { + // A packed worker's file system has no native realpath. + const native: unknown = Reflect.get(realpathSync, 'native') + return [realpathSync(path), ...typeof native === 'function' ? [String(Reflect.apply(native, realpathSync, [path]))] : []] + } catch (_error) { + // A removed previous directory keeps only its recorded spelling. + return [] + } +} + function canonicalPath(path: string): string { try { return realpathSync(path) @@ -170,7 +199,7 @@ function prefixes(path: string): readonly string[] { function compileResolution(resolution: RuntimeResolution): CompiledResolution { return { - entries: new Map(resolution.entries.map(entry => [entry.name, entry])), + entries: new Map(resolution.entries.map(entry => [entry.name, { ...entry, realDir: canonicalPath(entry.packageDir) }])), profilesDir: resolution.profilesDir, profileDir: resolution.profileDir, profilePaths: prefixes(resolution.profilesDir), @@ -363,10 +392,75 @@ function sameResolution(left: string, right: string): boolean { return canonicalPath(left) === canonicalPath(right) } +/** A directory as given and in its JavaScript and native real paths, each with a trailing separator. */ +function spellings(dir: string): string[] { + const result = new Set([dir + sep]) + for (const real of realSpellings(dir)) result.add(real + sep) + return [...result] +} + +/** + * The previous real directories of packages that moved, each mapped to the current one. Node keeps the real path of + * every link it resolved through and never refreshes it, so a lookup through a link that now points elsewhere still + * selects a file below the target Node saw first; {@link MovedDirectories.relocate} selects the same file below the + * current target instead. + */ +class MovedDirectories { + /** Previous directory to current directory, both with a trailing separator. */ + private readonly targets = new Map() + + /** + * Record that a package moved from one directory to another. Every spelling of the previous directory leads to the + * current one. A directory that an earlier move led to the previous one now leads to the current one as well, since + * Node still selects files below the earliest target. + * @param from Previous real directory. + * @param to Current real directory. + */ + record(from: string, to: string): void { + const previous = spellings(from) + const current = to + sep + for (const [key, value] of this.targets) { + if (previous.includes(value)) this.targets.set(key, current) + } + for (const key of previous) this.targets.set(key, current) + } + + /** + * Forget the previous directories that are current again, in any spelling, and records that lead to themselves. + * @param current The real directories the published resolution maps. + */ + forget(current: readonly string[]): void { + const active = new Set() + for (const dir of current) for (const spelling of spellings(dir)) active.add(spelling) + for (const [key, value] of [...this.targets]) { + if (active.has(key) || key === value) this.targets.delete(key) + } + } + + /** + * The same file below the current directory when it exists, for a file below a previous directory that an importer + * outside that directory selected. An importer inside the previous directory keeps its own package's files. The + * innermost previous directory decides. + * @param filename Selected file. + * @param parent Importer path. + * @returns The file to load. + */ + relocate(filename: string, parent: string | undefined): string { + let from = '' + for (const dir of this.targets.keys()) { + if (filename.startsWith(dir) && dir.length > from.length) from = dir + } + if (from === '' || parent?.startsWith(from) === true) return filename + const relocated = (this.targets.get(from) as string) + filename.slice(from.length) + return existsSync(relocated) ? relocated : filename + } +} + /** One mutable pointer to the immutable runtime resolution. */ class ResolutionRouter { private current: CompiledResolution - private readonly linkedTargets: Map + private linkedTargets: Map + private readonly moved = new MovedDirectories() constructor(resolution: RuntimeResolution, private readonly nodeModulePaths: (directory: string) => string[]) { this.current = compileResolution(resolution) @@ -379,37 +473,64 @@ class ResolutionRouter { || successor.profileDir !== this.current.profileDir) { throw new Error('profile resolution: a successor cannot change its profile scope') } + const rejected: string[] = [] + const moves: [string, string][] = [] for (const [name, current] of this.current.entries) { const next = entries.get(name) if (next === undefined && current.scope === 'profile') continue + if (next !== undefined && current.scope === 'profile' && next.scope === 'profile') { + // Real directories are compared: a link keeps its path when its target changes. + if (current.realDir === canonicalPath(next.packageDir)) continue + rejected.push(`profile resolution: replacing ${JSON.stringify(name)} requires a process restart`) + continue + } if (next === undefined || !sameResolution(current.packageDir, next.packageDir) || (current.scope === 'installation' && !sameResolution(current.declarer, next.declarer)) - || current.version !== next.version + || (current.scope === 'installation' && current.version !== next.version) || current.scope !== next.scope) { - throw new Error(`profile resolution: replacing ${JSON.stringify(name)} requires a process restart`) + rejected.push(`profile resolution: replacing ${JSON.stringify(name)} requires a process restart`) } } const localPackageNames = new Set(successor.localPackageNames) for (const name of localPackageNames) { if (!this.current.localPackageNames.has(name) && this.current.entries.has(name)) { - throw new Error(`profile resolution: overriding ${JSON.stringify(name)} locally requires a process restart`) + rejected.push(`profile resolution: overriding ${JSON.stringify(name)} locally requires a process restart`) } } - // Node retains realpath caches after a root leaves the interception scope. - for (const root of successor.linkedRoots) { - const previous = this.linkedTargets.get(root.name) - if (previous !== undefined && !sameResolution(previous, root.realPath)) { - throw new Error(`profile resolution: relinking ${JSON.stringify(root.name)} requires a process restart`) - } + // A link name pointing elsewhere, or installed again as a directory, moves its package. Names whose link and mapping + // are gone stay recorded, so the package that returns under the name is compared with its last target. + const targets = new Map(this.linkedTargets) + for (const [name, previous] of this.linkedTargets) { + const root = successor.linkedRoots.find(candidate => candidate.name === name) + const entry = entries.get(name) + const target = root?.realPath ?? (entry?.scope === 'profile' ? canonicalPath(entry.packageDir) : undefined) + if (target === undefined || sameResolution(previous, target)) continue + moves.push([previous, target]) + targets.set(name, target) } + if (rejected.length > 0) throw new ResolutionRestartRequired(rejected.join('; ')) const next = compileResolution(successor) - for (const { name, realPath } of successor.linkedRoots) { - if (!this.linkedTargets.has(name)) this.linkedTargets.set(name, realPath) - } + for (const { name, realPath } of successor.linkedRoots) targets.set(name, realPath) + this.linkedTargets = targets + for (const [from, to] of moves) this.moved.record(from, to) + const current: string[] = [] + for (const entry of next.entries.values()) current.push(entry.realDir) + for (const root of successor.linkedRoots) current.push(root.realPath) + this.moved.forget(current) this.current = next } + /** + * The file to load instead of one Node selected through a link that has moved since; see {@link MovedDirectories}. + * @param filename Selected file. + * @param parent Importer path. + * @returns The file to load. + */ + relocate(filename: string, parent: string | undefined): string { + return this.moved.relocate(filename, parent) + } + /** Whether a module path has an interception layer: it lies in the profiles tree, the active profile, or a linked root. */ hasInterceptionLayerForPath(path: string): boolean { return findInterceptionLayer(path, this.current) !== undefined @@ -764,7 +885,21 @@ export function installRuntimeInterception( delegatedEsm = previous } } - return adapted + // Node's last real-path step, for routed and native requests alike, may follow a link it resolved earlier. + const relocate = (result: ResolveResult, parent: string | undefined): ResolveResult => { + if (!result.url.startsWith('file:')) return result + const url = new URL(result.url) + const filename = fileURLToPath(url) + const relocated = router.relocate(filename, parent?.startsWith('file:') === true ? fileURLToPath(parent) : undefined) + if (relocated === filename) return result + url.pathname = pathToFileURL(relocated).pathname + return { ...result, url: url.href } + } + return (request, parent, attributes) => { + const result = adapted(request, parent, attributes) + /* v8 ignore next -- Node 24+ resolves synchronously; the Node 22 matrix covers its Promise result */ + return result instanceof Promise ? result.then(resolved => relocate(resolved, parent)) : relocate(result, parent) + } } let restoreEsm: () => void @@ -904,7 +1039,11 @@ export function installRuntimeInterception( delegatedCjs-- } } - cjs._resolveFilename = wrappedFilename + const relocatedFilename: CommonJsModule['_resolveFilename'] = (request, parent, main, options) => { + const filename = wrappedFilename(request, parent, main, options) + return isAbsolute(filename) ? router.relocate(filename, parent?.filename ?? undefined) : filename + } + cjs._resolveFilename = relocatedFilename return { packageDir(specifier, parentURL) { @@ -913,7 +1052,7 @@ export function installRuntimeInterception( replace(next) { router.replace(next) }, dispose() { /* v8 ignore else -- interceptions are disposed in reverse installation order */ - if (cjs._resolveFilename === wrappedFilename) cjs._resolveFilename = originalFilename + if (cjs._resolveFilename === relocatedFilename) cjs._resolveFilename = originalFilename restoreEsm() }, } diff --git a/packages/boot/app-boot/src/profile-resolution/service.ts b/packages/boot/app-boot/src/profile-resolution/service.ts index 7d493698a7..6e73c16c1a 100644 --- a/packages/boot/app-boot/src/profile-resolution/service.ts +++ b/packages/boot/app-boot/src/profile-resolution/service.ts @@ -76,10 +76,15 @@ export class PluginPackages extends Service { }, 'profile package resolution') } + /** The published runtime resolution, or `undefined` when Node resolves packages alone. */ + get resolution(): RuntimeResolution | undefined { + return this.current + } + /** * Publish a complete successor generation for this process and subsequently created Workers. * Profile mappings and local package names may be removed after their plugins stop; linked roots may also be removed. - * Retained profile mappings may change their declarer, but not their normalized directory, version, or scope; + * Retained profile mappings may change their declarer and version, but not their normalized directory or scope; * installation mappings must remain unchanged. Publication does not unload modules or clear Node caches. * @param successor - fully constructed generation accepted by {@link RuntimeInterception.replace}. */ diff --git a/packages/boot/app-boot/src/profile.ts b/packages/boot/app-boot/src/profile.ts index e8aee3ce21..cbece01be2 100644 --- a/packages/boot/app-boot/src/profile.ts +++ b/packages/boot/app-boot/src/profile.ts @@ -25,12 +25,12 @@ import { createRequire } from 'node:module' import { existsSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs' import { basename, dirname, join, relative, resolve, sep } from 'node:path' import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' +import { applyEntryPatches, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import { resolveDshHome } from '@deepseek-ai/dsh-home-paths' import type { DshBundleManifest, DshPackageManifest } from '@deepseek-ai/dsh-package-manifest' import { evaluatePluginCompatibility, pluginCompatibilityWarning } from './plugin-compatibility.ts' import { readProfileVersionExemptions } from './profile-compatibility.ts' import { loadOverlayPatches } from './index.ts' -import { applyProfilePatches, type ProfilePatch } from './profile-patches.ts' import { realModuleDirectory } from './profile-resolution/legacy-links.ts' /** Directory under the Harness home holding every profile. */ @@ -83,7 +83,7 @@ export interface ProfileLayer { /** Absolute paths of the bundle's patch files, in application order. */ patchPaths: readonly string[] /** The parsed patch lists of every file, concatenated in application order. */ - patches: ProfilePatch[] + patches: PatchOptions[] } /** A loaded profile: resolved bundle layers plus the user's own patch layer. */ @@ -97,7 +97,7 @@ export interface Profile { /** Absolute path of the profile's own patch file. */ patchPath: string /** The profile's own patches; empty when the file is absent. */ - patches: ProfilePatch[] + patches: PatchOptions[] /** Selected bundles that contributed no layer, in `dsh.profile.bundles` order, with why. */ skippedBundles: SkippedBundle[] } @@ -806,16 +806,16 @@ export function loadProfile( /** * Compose patch layers into the effective entry list over an empty root — - * compile preset operations and apply the same native patch list as boot, - * so flag derivation and config dumps see exactly what mounts. + * the same single `applyEntryPatches` call the boot include makes, so flag + * derivation and config dumps see exactly what mounts. * @param layers - patch lists in application order. * @param warn - sink for skipped-patch diagnostics; defaults to silent (boot repeats them). * @returns the composed entry list. */ export function composeEntries( - layers: readonly ProfilePatch[][], warn: (message: string) => void = () => {}, + layers: readonly PatchOptions[][], warn: (message: string) => void = () => {}, ): EntryOptions[] { - return applyProfilePatches([], layers.flat(), (message: string, ...args: unknown[]) => { + return applyEntryPatches([], structuredClone(layers.flat()), (message: string, ...args: unknown[]) => { let index = 0 warn(message.replace(/%C/g, () => JSON.stringify(args[index++]))) }) diff --git a/packages/boot/app-boot/tests/app-boot.spec.ts b/packages/boot/app-boot/tests/app-boot.spec.ts index f291e45cc6..5e83da0b17 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' @@ -558,6 +558,7 @@ describe('auditStartupEntries', () => { const requiredIds = [ 'agent-loop', 'webserver', + 'web-runtime', 'modules', 'connection', 'headless-runner', @@ -574,6 +575,7 @@ describe('auditStartupEntries', () => { } disabled?: boolean options: { id: string; name: string } + parent?: { tree: { import(name: string): Promise } } } const ctxWith = (entries: FakeEntry[]): Context => ({ @@ -609,7 +611,7 @@ describe('auditStartupEntries', () => { const warn = vi.fn() const original = new Error('todo apply failure') await auditStartupEntries(ctxWith([ - { options: { id: 'missing-tool', name: './missing.mjs' } }, + { options: { id: 'missing-tool', name: './missing.mjs' }, parent: { tree: { import: () => Promise.resolve() } } }, { fiber: fiber(3, original), options: { id: 'tool-todo', name: '@deepseek-ai/dsh-tool-todo' } }, { fiber: fiber(0, undefined, { ready: {}, missing: {} }, ['ready']), @@ -739,7 +741,7 @@ describe('auditStartupEntries', () => { it('omits an error cause when required plugins are only waiting for services', async () => { const error = await auditStartupEntries(ctxWith([ - { fiber: fiber(0, undefined, { webRuntime: {} }), options: { id: 'connection', name: './connection.mjs' } }, + { fiber: fiber(0, undefined, { webStartup: {} }), options: { id: 'connection', name: './connection.mjs' } }, ]), NAME, vi.fn()).catch((error: unknown) => error) expect(error).toBeInstanceOf(StartupError) expect(Object.hasOwn(error as StartupError, 'cause')).toBe(false) @@ -750,9 +752,9 @@ describe('auditStartupEntries', () => { it('keeps diagnostic metadata available without expanding it in ordinary error inspection', () => { const entries = [{ id: 'connection', module: './connection.mjs', required: true, fiberState: 0, - outcome: { kind: 'pending' as const, missing: ['webRuntime'] }, + outcome: { kind: 'pending' as const, missing: ['webStartup'] }, }] - const error = new StartupError('waiting for webRuntime', entries) + const error = new StartupError('waiting for webStartup', entries) const startup = { configurationPath: '/private/cordis.yml', messages: [ { ts: 1, name: 'loader', type: 'warn', args: ['raw diagnostic argument'] }, ] } @@ -760,7 +762,7 @@ describe('auditStartupEntries', () => { expect(error.entries).toBe(entries) expect(error.startup).toBe(startup) const output = inspect(error) - expect(output).toContain('waiting for webRuntime') + expect(output).toContain('waiting for webStartup') expect(output).not.toContain('connection.mjs') expect(output).not.toContain('/private/cordis.yml') expect(output).not.toContain('raw diagnostic argument') @@ -792,12 +794,12 @@ describe('auditStartupEntries', () => { const error = await auditStartupEntries(ctxWith([ { fiber: fiber(0, undefined, { webServer: {} }), options: { id: 'web-runtime', name: './web.mjs' } }, { fiber: fiber(3, original), options: { id: 'webserver', name: '@deepseek-ai/dsh-host-webserver' } }, - { fiber: fiber(0, undefined, { webRuntime: {} }), options: { id: 'connection', name: './connection.mjs' } }, + { fiber: fiber(0, undefined, { webStartup: {} }), options: { id: 'connection', name: './connection.mjs' } }, { fiber: fiber(0), options: { id: 'unknown', name: './unknown.mjs' } }, ]), NAME, warn).catch((error: unknown) => error) expect(error).toBeInstanceOf(StartupError) expect((error as Error).message).toMatchInlineSnapshot(` - "dsh-test-bin: startup failed: 2 required plugins did not activate + "dsh-test-bin: startup failed: 3 required plugins did not activate Failed plugins (1): webserver (required) @@ -806,10 +808,10 @@ describe('auditStartupEntries', () => { at Server.listen (node:net:1:2) Plugins waiting for services (3): - Plugin Missing services - connection (required) webRuntime - web-runtime webServer - unknown unknown" + Plugin Missing services + web-runtime (required) webServer + connection (required) webStartup + unknown unknown" `) expect(warn).not.toHaveBeenCalled() }) @@ -853,7 +855,7 @@ describe('boot', () => { const error = failure as StartupError expect(error.entries).toEqual([{ id: 'webserver', module: './missing.mjs', required: true, fiberState: undefined, - outcome: { kind: 'failed', error: 'failed to import' }, + outcome: { kind: 'failed', error: expect.objectContaining({ message: expect.stringContaining('missing.mjs') as string }) as Error, phase: 'failed to import' }, }]) expect(error.startup?.configurationPath).toBe(config) expect(error.startup?.messages.some(message => message.args.some(arg => arg instanceof Error && arg.message.includes('missing.mjs')))).toBe(true) @@ -1265,61 +1267,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/tests/config-schema.spec.ts b/packages/boot/app-boot/tests/config-schema.spec.ts index aaacfcd68e..debb11641a 100644 --- a/packages/boot/app-boot/tests/config-schema.spec.ts +++ b/packages/boot/app-boot/tests/config-schema.spec.ts @@ -500,10 +500,6 @@ describe('collectConfigSchemas', () => { expect(validates(result, [{ name: 'server', config: { port: 'wrong' } }])).toBe(false) expect(validates(result, [{ name: 'new-plugin', config: { arbitrary: true } }])).toBe(true) expect(validates(result, [{ id: 'server', disabled: true }], 'patchList')).toBe(true) - expect(validates(result, [{ preset: 'preset-standard', id: 'server', config: 'child-owned' }], 'patchList')).toBe(true) - expect(validates(result, [{ preset: '', insert: [] }], 'patchList')).toBe(false) - expect(validates(result, [{ preset: ' ', insert: [] }], 'patchList')).toBe(false) - expect(validates(result, [{ preset: { __jsExpr: 'ctx.preset' }, insert: [] }], 'patchList')).toBe(false) expect(validates(result, [{ id: 'server', config: { port: 'wrong' } }], 'patchList')).toBe(false) expect(validates(result, [{ id: 'server', config: {} }], 'patchList')).toBe(false) expect(validates(result, [{ id: 'server', name: 'not-server', config: 'ignored' }], 'patchList')).toBe(true) diff --git a/packages/boot/app-boot/tests/profile-patches-carrier.spec.ts b/packages/boot/app-boot/tests/profile-patches-carrier.spec.ts deleted file mode 100644 index d9d913d11e..0000000000 --- a/packages/boot/app-boot/tests/profile-patches-carrier.spec.ts +++ /dev/null @@ -1,78 +0,0 @@ -/** Patch identities work with archive-backed files and preserve physical filesystem aliases. */ -import { lstatSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it, onTestFinished, vi } from 'vitest' -import { loadOverlayPatches, realModuleFile } from '../src/index.ts' - -vi.mock('node:fs', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, realpathSync: Object.assign(vi.fn(actual.realpathSync), { native: actual.realpathSync.native }) } -}) - -afterEach(() => { vi.mocked(realpathSync).mockReset() }) - -function packagedRuntime(): void { - const previous = Object.getOwnPropertyDescriptor(process, 'pkg') - Object.defineProperty(process, 'pkg', { configurable: true, value: {} }) - onTestFinished(() => { - if (previous === undefined) Reflect.deleteProperty(process, 'pkg') - else Object.defineProperty(process, 'pkg', previous) - }) -} - -function fixture(): string { - const root = mkdtempSync(join(tmpdir(), 'profile-patch-carrier-')) - onTestFinished(() => { rmSync(root, { recursive: true, force: true }) }) - return root -} - -it('loads ordinary and anonymous scoped patches when packaged files support reads and directory realpath', () => { - packagedRuntime() - const root = fixture() - const file = join(root, 'cordis.patch.yml') - writeFileSync(file, JSON.stringify([ - { insert: [{ id: 'base', name: 'base' }] }, - { preset: 'preset-standard', insert: [{ name: 'anonymous' }] }, - ])) - vi.mocked(realpathSync).mockImplementation((path, options) => { - if (lstatSync(path).isFile()) throw Object.assign(new Error('archive file has no physical realpath'), { code: 'ENOENT' }) - return realpathSync.native(path, options) - }) - expect(() => realpathSync(file)).toThrow('archive file has no physical realpath') - const first = loadOverlayPatches('test', file) - expect(first[0]).toEqual({ insert: [{ id: 'base', name: 'base' }] }) - expect(first[1]?.insert?.[0]).toEqual({ id: expect.any(String) as string, name: 'anonymous' }) - expect(loadOverlayPatches('test', file)).toEqual(first) - expect(realModuleFile(file)).toBe(join(realpathSync(root), 'cordis.patch.yml')) -}) - -it.each([false, true])('keeps directory and file symlinks on the same patch identity (packaged: %s)', (packaged) => { - if (packaged) packagedRuntime() - const root = fixture() - const directory = join(root, 'bundle') - mkdirSync(directory) - const file = join(directory, 'Patch.yml') - writeFileSync(file, JSON.stringify([{ preset: 'preset-standard', insert: [{ name: 'anonymous' }] }])) - const directoryAlias = join(root, 'bundle-alias') - const fileAlias = join(root, 'patch-alias.yml') - symlinkSync(directory, directoryAlias, process.platform === 'win32' ? 'junction' : 'dir') - symlinkSync(file, fileAlias, 'file') - const first = loadOverlayPatches('test', file) - expect(loadOverlayPatches('test', join(directoryAlias, 'Patch.yml'))).toEqual(first) - expect(loadOverlayPatches('test', fileAlias)).toEqual(first) - expect(realModuleFile(fileAlias)).toBe(realpathSync(file)) -}) - -it('keeps ordinary physical resource normalization identical to Node realpath', () => { - const root = fixture() - const file = join(root, 'MixedCase.yml') - writeFileSync(file, '[]\n') - const requested = process.platform === 'win32' ? file.toLowerCase() : file - expect(realModuleFile(requested)).toBe(realpathSync(requested)) -}) - -it('reports missing packaged resources instead of assigning them an identity', () => { - packagedRuntime() - expect(() => realModuleFile(join(fixture(), 'absent.yml'))).toThrow('ENOENT') -}) diff --git a/packages/boot/app-boot/tests/profile-patches.spec.ts b/packages/boot/app-boot/tests/profile-patches.spec.ts deleted file mode 100644 index 7afd826d32..0000000000 --- a/packages/boot/app-boot/tests/profile-patches.spec.ts +++ /dev/null @@ -1,305 +0,0 @@ -/** Preset operations preserve native root patch lookup and share startup/dump/reload compilation. */ -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' -import { describe, expect, it, onTestFinished } from 'vitest' -import { load } from 'js-yaml' -import { Context } from '@deepseek-ai/cordis' -import { EntryGroup, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader' -import Group from '@deepseek-ai/cordis-plugin-group' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' -import { - applyProfilePatches, boot, compileProfilePatches, composeEntries, loadOverlayPatches, - prepareProfilePatches, profilePatchPreset, reconcileProfilePatches, renderConfigDump, type ProfilePatch, -} from '../src/index.ts' - -import { cloneProfilePatches } from '../src/profile-patches.ts' - -const preset = (plugins: EntryOptions[] = []): Omit & { - config: { id: string; description: string; plugins: EntryOptions[] } -} => ({ - id: 'preset-standard', name: 'cordis:test-preset', config: { id: 'standard', description: 'Original', plugins }, -}) -const row = (id: string): EntryOptions => ({ id, name: 'test-plugin', config: { value: 'initial' } }) -const children = (rows: EntryOptions[]): EntryOptions[] => (rows[0]!.config as { plugins: EntryOptions[] }).plugins -const temp = (): string => { - const dir = mkdtempSync(join(tmpdir(), 'dsh-preset-patches-')) - onTestFinished(() => { rmSync(dir, { recursive: true, force: true }) }) - return dir -} - -describe('preset patch composition', () => { - it('composes bundle insertions and later scoped user overrides without mutating inputs', () => { - const initial = [preset([row('base')])] - const patches: ProfilePatch[] = [ - { preset: 'preset-standard', insert: [row('optional')] }, - { preset: 'preset-standard', id: 'optional', config: { value: { __jsExpr: 'ctx.value' } } }, - { preset: 'preset-standard', id: 'base', disabled: true }, - ] - const original = structuredClone({ initial, patches }) - const result = applyProfilePatches(initial, patches) - expect(children(result)).toEqual([ - { ...row('base'), disabled: true }, - { ...row('optional'), config: { value: { __jsExpr: 'ctx.value' } } }, - ]) - expect(result[0]?.config).toMatchObject({ description: 'Original' }) - expect({ initial, patches }).toEqual(original) - expect(composeEntries([[{ insert: initial }], patches])).toEqual(result) - expect(compileProfilePatches(initial, patches).every(patch => !Object.hasOwn(patch, 'preset'))).toBe(true) - }) - - it('allows a later whole-preset replacement to replace all scoped edits', () => { - const replacement = { id: 'standard', plugins: [row('user')] } - expect(applyProfilePatches([preset()], [ - { preset: 'preset-standard', insert: [row('optional')] }, - { id: 'preset-standard', config: replacement }, - ])[0]?.config).toEqual(replacement) - }) - - it('applies each scoped operation to the current child list, including replacement children', () => { - const group = { id: 'group', name: 'cordis:group', group: true, config: [] } - const result = applyProfilePatches([preset([group])], [ - { preset: 'preset-standard', id: 'group', config: [row('replaced-child')] }, - { preset: 'preset-standard', id: 'replaced-child', disabled: true }, - { preset: 'preset-standard', id: 'group', insert: [row('inserted-child')] }, - ]) - expect(children(result)[0]?.config).toEqual([ - { ...row('replaced-child'), disabled: true }, row('inserted-child'), - ]) - }) - - it('retains ordinary root single-index behavior before and after a scoped operation', () => { - const warn: string[] = [] - const result = applyProfilePatches([ - { id: 'group', name: 'cordis:group', group: true, config: [] }, preset(), - ], [ - { id: 'group', config: [row('replacement')] }, - { preset: 'preset-standard', insert: [row('optional')] }, - { id: 'replacement', disabled: true }, - ], message => warn.push(message)) - expect(result[0]?.config).toEqual([row('replacement')]) - expect(warn).toEqual(['patch: entry %C not found']) - }) - - it.each([ - [{ id: 'group', name: 'cordis:group', group: true, config: [] }, [preset()]], - [{ id: 'group', name: 'cordis:group', group: true, config: [preset()] }, []], - ])('rejects an outer target added or removed by a whole-group replacement', (group, replacement) => { - expect(() => applyProfilePatches([group as EntryOptions], [ - { id: 'group', config: replacement }, { preset: 'preset-standard', insert: [row('optional')] }, - ])).toThrow('is missing or not addressable') - }) - - it('accepts an outer target inserted in a patchable group', () => { - const result = applyProfilePatches([{ id: 'group', name: 'cordis:group', group: true, config: [] }], [ - { id: 'group', insert: [preset()] }, - { preset: 'preset-standard', insert: [row('optional')] }, - ]) - expect(children(result[0]?.config as EntryOptions[])).toEqual([row('optional')]) - }) - - it('warns and skips a stale user override after its optional bundle is deselected', () => { - const messages: unknown[][] = [] - expect(applyProfilePatches([preset()], [{ preset: 'preset-standard', id: 'optional', disabled: true }], - (...args) => messages.push(args))).toEqual([preset()]) - expect(messages).toEqual([['preset "preset-standard": patch: entry %C not found', 'optional']]) - }) - - it.each([null, '', ' ', 1, { __jsExpr: 'ctx.preset' }])('rejects a nonliteral or empty outer target %j', (target) => { - const dir = temp() - const path = join(dir, 'patch.yml') - writeFileSync(path, JSON.stringify([{ preset: target, insert: [] }])) - expect(() => loadOverlayPatches('test', path)).toThrow('nonempty literal row id') - expect(() => loadOverlayPatches('test', path)).toThrow(path) - }) - - it('allows callers to omit a warning sink for skipped ordinary and scoped rows', () => { - expect(applyProfilePatches([], [{ id: 'missing', disabled: true }])).toEqual([]) - expect(compileProfilePatches([preset()], [{ preset: 'preset-standard', id: 'missing', disabled: true }])) - .toEqual([{ id: 'preset-standard', config: preset().config }]) - }) - - it('rejects a missing outer row', () => { - expect(() => applyProfilePatches([], [{ preset: 'missing', insert: [] }])).toThrow('preset "missing" is missing') - expect(profilePatchPreset({ id: 'ordinary' })).toBeUndefined() - }) - - it.each([undefined, null, [], { plugins: { __jsExpr: '[]' } }])('rejects a malformed preset config %j', (config) => { - expect(() => applyProfilePatches([{ ...preset(), config }], [{ preset: 'preset-standard', insert: [] }])) - .toThrow('literal config.plugins entry list') - }) - - it.each([ - { inserted: [row('same')] }, - { inserted: [{ id: 'nested', name: 'cordis:group', group: true, config: [row('same')] }] }, - ])('rejects inserted ids colliding with existing nested ids', ({ inserted }) => { - expect(() => applyProfilePatches([preset([ - { id: 'old-group', name: 'cordis:group', group: true, config: [row('same')] }, - ])], [{ preset: 'preset-standard', insert: inserted }])).toThrow('duplicate entry id "same"') - }) - - it('rejects duplicate ids inside an insertion and allows anonymous rows', () => { - expect(() => applyProfilePatches([preset()], [{ preset: 'preset-standard', insert: [row('same'), row('same')] }])) - .toThrow('duplicate entry id "same"') - const path = join(temp(), 'anonymous.patch.yml') - writeFileSync(path, JSON.stringify([{ preset: 'preset-standard', insert: [{ name: 'anonymous' }] }])) - expect(children(applyProfilePatches([preset()], loadOverlayPatches('test', path)))) - .toEqual([{ id: expect.any(String) as string, name: 'anonymous' }]) - }) - - it('keeps anonymous scoped identities stable by file and position without naming ordinary anonymous rows', () => { - const dir = temp() - const file = join(dir, 'contribution.patch.yml') - const content = JSON.stringify([ - { insert: [{ name: 'ordinary-anonymous' }] }, - { preset: 'preset-standard', insert: [ - { name: 'anonymous' }, - { id: 'explicit', name: 'cordis:group', group: true, config: [{ name: 'nested-anonymous' }] }, - ] }, - { preset: 'preset-standard', insert: [{ name: 'anonymous' }] }, - ]) - writeFileSync(file, content) - const first = loadOverlayPatches('test', file) - const second = loadOverlayPatches('test', file) - expect(second).toEqual(first) - expect(first[0]?.insert?.[0]?.id).toBeUndefined() - expect(first[1]?.insert?.[1]?.id).toBe('explicit') - const nested = first[1]?.insert?.[1]?.config as EntryOptions[] - const ids = [first[1]?.insert?.[0]?.id, nested[0]?.id, first[2]?.insert?.[0]?.id] - expect(ids.every(id => typeof id === 'string' && id.length > 0)).toBe(true) - expect(new Set(ids).size).toBe(3) - const other = join(dir, 'other.patch.yml') - writeFileSync(other, content) - expect(loadOverlayPatches('test', other)[1]?.insert?.[0]?.id).not.toBe(ids[0]) - expect(children(applyProfilePatches([preset()], first))).toEqual(children(applyProfilePatches([preset()], second))) - expect(Object.keys(first[1]!)).toEqual(['preset', 'insert']) - }) - - it.each([ - { initial: [], insert: [] }, - { initial: [preset()], insert: [{ id: 'group', name: 'cordis:group', group: true, config: [row('duplicate'), row('duplicate')] }] }, - { initial: [{ ...preset(), config: null }], insert: [] }, - ])('attributes scoped errors after cloning and flattening through composition, dumps, and boot', async ({ initial, insert }) => { - const dir = temp() - const path = join(dir, 'cordis.yml') - writeFileSync(path, JSON.stringify(initial)) - const patchFile = join(dir, 'third-party.patch.yml') - writeFileSync(patchFile, JSON.stringify([{ preset: 'preset-standard', insert }])) - const patches = cloneProfilePatches(loadOverlayPatches('test', patchFile)) - expect(() => composeEntries([[{ insert: initial }], patches])).toThrow(patchFile) - expect(() => renderConfigDump('test', path, [{ label: 'third-party', patches }])).toThrow(patchFile) - await expect(boot('test', path, patches)).rejects.toThrow(patchFile) - }) - - it('keeps anonymous rows from the initial preset beside newly inserted rows', () => { - const initial = load(JSON.stringify([{ ...preset(), config: { id: 'standard', plugins: [{ name: 'anonymous-base' }] } }])) as EntryOptions[] - expect(children(applyProfilePatches(initial, [{ preset: 'preset-standard', insert: [row('contributed')] }]))) - .toEqual([{ name: 'anonymous-base' }, row('contributed')]) - }) - - it('attributes errors from a caller warning sink to the loaded scoped operation', () => { - const path = join(temp(), 'warning.patch.yml') - writeFileSync(path, JSON.stringify([{ preset: 'preset-standard', id: 'absent', disabled: true }])) - expect(() => applyProfilePatches([preset()], loadOverlayPatches('test', path), () => { throw 'warning sink unavailable' })) - .toThrow(`warning sink unavailable in ${path}`) - }) - - it('attributes ordinary and scoped warnings to their own dump layers', () => { - const dir = temp() - const path = join(dir, 'cordis.yml') - writeFileSync(path, JSON.stringify([preset()])) - const warnings: string[] = [] - renderConfigDump('test', path, [ - { label: 'ordinary', patches: [{ id: 'missing', disabled: true }] }, - { label: 'scoped', patches: [{ preset: 'preset-standard', id: 'missing', disabled: true }] }, - ], message => warnings.push(message)) - expect(warnings).toEqual([ - 'test: [ordinary] patch: entry "missing" not found', - 'test: [scoped] preset "preset-standard": patch: entry "missing" not found', - ]) - }) -}) - -const capturePreset = { - [EntryGroup.key]: true, - async apply(ctx: Context, config: { plugins: EntryOptions[] }) { await ctx.plugin(Group, config.plugins) }, -} - -it('boots, dumps, and reloads a third-party relative module inside a contributed group', async () => { - const dir = temp() - const bundleDir = join(dir, 'third-party') - mkdirSync(bundleDir) - writeFileSync(join(bundleDir, 'relative.mjs'), [ - 'export function apply(ctx, config) {', - ' ctx.effect(() => ctx.reflect.provide("presetPatchResult", config.value))', - '}', - '', - ].join('\n')) - const path = join(dir, 'cordis.yml') - writeFileSync(path, JSON.stringify([preset()])) - const patchPath = join(bundleDir, 'cordis.patch.yml') - writeFileSync(patchPath, [ - '- preset: preset-standard', - ' insert:', - ' - id: nested', - ' name: cordis:group', - ' group: true', - ' config:', - ' - id: contributed', - ' name: ./relative.mjs', - ' config:', - ' value: !!js ctx.get("fixtureValue")', - '', - ].join('\n')) - const patches = loadOverlayPatches('test', patchPath) - const ctx = await boot('test', path, patches, (context) => { - context.loader.builtins['test-preset'] = capturePreset - context.provide('fixtureValue', 'from-child-context') - }) - onTestFinished(() => ctx.fiber.dispose()) - expect(ctx.get('presetPatchResult')).toBe('from-child-context') - const declared = [...ctx.loader.entries()].find(entry => entry.options.id === 'preset-standard')! - const dump = renderConfigDump('test', path, [{ label: 'third-party', patches }]) - expect(load(dump, { schema: entryListSchema })).toEqual([declared.options]) - expect(dump).toContain(pathToFileURL(join(bundleDir, 'relative.mjs')).href) - expect(dump).toContain('!!js ctx.get("fixtureValue")') - await reconcileProfilePatches(ctx, [...patches, { - preset: 'preset-standard', id: 'contributed', config: { value: 'user' }, - }], 'test') - expect(ctx.get('presetPatchResult')).toBe('user') - await reconcileProfilePatches(ctx, [], 'test') - expect(ctx.get('presetPatchResult')).toBeUndefined() - await reconcileProfilePatches(ctx, [{ preset: 'preset-standard', id: 'contributed', disabled: true }], 'test') - expect(ctx.get('presetPatchResult')).toBeUndefined() - await reconcileProfilePatches(ctx, patches, 'test') - expect(ctx.get('presetPatchResult')).toBe('from-child-context') -}) - -it('rejects a malformed root configuration before compiling its scoped patch', async () => { - const dir = temp() - const path = join(dir, 'cordis.yml') - writeFileSync(path, '{}\n') - await expect(boot('test', path, [{ preset: 'preset-standard', insert: [] }])) - .rejects.toThrow('must be a top-level array of entries') -}) - -it('leaves lower-level nonprofile compatibility callers in control of their native patches', async () => { - const ctx = new Context() - onTestFinished(() => ctx.fiber.dispose()) - const patches = [{ id: 'custom', disabled: true }] - expect(prepareProfilePatches(ctx, patches, pathToFileURL(temp()).href)).toBe(patches) -}) - -it('anchors relative modules in an inserted preset definition and its nested groups', () => { - const dir = temp() - const path = join(dir, 'cordis.patch.yml') - writeFileSync(path, JSON.stringify([{ insert: [{ - ...preset([{ id: 'group', name: 'cordis:group', group: true, config: [{ id: 'child', name: './child.mjs' }] }]), - name: '@deepseek-ai/dsh-agent-preset', - }] }])) - const patches = loadOverlayPatches('test', path) - expect(patches[0]?.insert?.[0]?.config).toMatchObject({ plugins: [{ config: [{ - name: pathToFileURL(join(dir, 'child.mjs')).href, - }] }] }) -}) diff --git a/packages/boot/app-boot/tests/profile-resolution-service.spec.ts b/packages/boot/app-boot/tests/profile-resolution-service.spec.ts index be57535fd4..9ca8a7e0d6 100644 --- a/packages/boot/app-boot/tests/profile-resolution-service.spec.ts +++ b/packages/boot/app-boot/tests/profile-resolution-service.spec.ts @@ -102,7 +102,7 @@ describe('profile package metadata service', () => { expect(createRequire(parentURL).resolve('metadata-lib')).toBe(join(packageDir, 'index.cjs')) }) - it('rejects refreshing a plain-data or absent resolution', async () => { + it('rejects refreshing a plain-data or absent resolution, and exposes the installed one', async () => { const root = mkdtempSync(join(tmpdir(), 'dsh-package-service-plain-')) roots.push(root) const packageDir = join(root, 'lib') @@ -112,10 +112,13 @@ describe('profile package metadata service', () => { resolution: resolution(join(root, 'profiles'), join(root, 'profiles', 'test'), packageDir, pkg(packageDir, '1.0.0'), '1.0.0'), }) await expect(ctx.pluginPackages.refresh()).rejects.toThrow('plugin-packages: the installed runtime resolution cannot be recomputed') + expect(ctx.pluginPackages.resolution?.profileDir).toBe(join(root, 'profiles', 'test')) + // Without an installed resolution Node resolves alone. const bare = new Context() contexts.push(bare) await bare.plugin(PluginPackages) await expect(bare.pluginPackages.refresh()).rejects.toThrow('plugin-packages: the installed runtime resolution cannot be recomputed') + expect(bare.pluginPackages.resolution).toBeUndefined() }) it('reads translated metadata from the selected local package without importing its entry', async () => { @@ -280,11 +283,11 @@ describe('profile package metadata service', () => { expectSelectedPackage(local, '2.0.0') const removedWorkerData = getEnvironmentData(key) expect(removedWorkerData).toEqual({ resolution: removed }) - expect(() => { ctx.pluginPackages.replace(relinked) }).toThrow( - 'profile resolution: relinking "linked-plugin" requires a process restart', - ) + expect(removedWorkerData).toEqual({ resolution: removed }) + // A link name may point to another directory once the plugins of its previous target stopped. + ctx.pluginPackages.replace(relinked) expectSelectedPackage(local, '2.0.0') - expect(getEnvironmentData(key)).toBe(removedWorkerData) + expect(getEnvironmentData(key)).toEqual({ resolution: relinked }) await ctx.fiber.dispose() contexts.pop() diff --git a/packages/boot/app-boot/tests/profile-resolution.spec.ts b/packages/boot/app-boot/tests/profile-resolution.spec.ts index 82cf24b0ea..b56d1a1774 100644 --- a/packages/boot/app-boot/tests/profile-resolution.spec.ts +++ b/packages/boot/app-boot/tests/profile-resolution.spec.ts @@ -18,6 +18,7 @@ import { getEnvironmentData } from 'node:worker_threads' import { afterEach, describe, expect, it } from 'vitest' import { installRuntimeInterception, + ResolutionRestartRequired, registerWorkerResolution, type RuntimeInterception, } from '../src/profile-resolution/resolver.ts' @@ -1642,14 +1643,128 @@ describe('runtime resolution', { concurrent: false }, () => { registration.replace({ ...withLocal, linkedRoots: [linked] }) registration.replace({ ...withLocal, linkedRoots: [] }) registration.replace({ ...withLocal, linkedRoots: [linked] }) - expect(() => { - registration.replace({ ...withLocal, linkedRoots: [{ ...linked, realPath: join(f.root, 'work', 'b') }] }) - }).toThrow(/relinking "linked-plugin" requires a process restart/u) + // A link name may point to another directory once its previous target's plugins stopped. + registration.replace({ ...withLocal, linkedRoots: [{ ...linked, realPath: join(f.root, 'work', 'b') }] }) expect(registration.packageDir( '@deepseek-ai/dsh-core', pathToFileURL(join(f.profile.dir, 'entry.mjs')).href, )).toBe(f.installed) }) + it('selects the current target for a native lookup through a link Node resolved before it moved', async () => { + const f = fixture() + const first = join(f.root, 'work', 'first') + const second = join(f.root, 'work', 'second') + pkg(first, 'linked-lib', 1) + pkg(second, 'linked-lib', 2) + // An importer outside every interception layer resolves natively through the link. + const outside = join(f.root, 'outside') + const link = join(outside, 'node_modules', 'linked-lib') + mkdirSync(dirname(link), { recursive: true }) + symlinkSync(first, link, process.platform === 'win32' ? 'junction' : 'dir') + const parentPath = join(outside, 'entry.mjs') + file(parentPath, '') + const parent = pathToFileURL(parentPath).href + const base = await resolutionOf(f) + const linked = { name: 'linked-lib', realPath: realpathSync.native(first) } + const registration = installRuntimeInterception({ ...base, linkedRoots: [linked] }) + registrations.push(registration) + expect(fileURLToPath(resolveFrom('linked-lib', parent))).toBe(join(realpathSync(first), 'index.js')) + expect(createRequire(parentPath).resolve('linked-lib')).toBe(join(realpathSync(first), 'index.cjs')) + unlinkSync(link) + symlinkSync(second, link, process.platform === 'win32' ? 'junction' : 'dir') + registration.replace({ ...base, linkedRoots: [{ ...linked, realPath: realpathSync.native(second) }] }) + expect(fileURLToPath(resolveFrom('linked-lib', parent))).toBe(join(realpathSync.native(second), 'index.js')) + expect(createRequire(parentPath).resolve('linked-lib')).toBe(join(realpathSync.native(second), 'index.cjs')) + // A file only the previous target has, or a builtin, stays as Node selected it. + file(join(first, 'only-first.cjs'), '') + expect(createRequire(parentPath).resolve(join(first, 'only-first.cjs'))).toBe(join(realpathSync(first), 'only-first.cjs')) + expect(resolveFrom('node:fs', parent)).toBe('node:fs') + // An entry point's lookup has no importer. + expect(fileURLToPath(resolveFrom(pathToFileURL(join(link, 'index.js')).href, undefined))).toBe(join(realpathSync.native(second), 'index.js')) + // A file system without a native realpath, as a packed worker has, records the JavaScript spelling alone. + const native: unknown = Reflect.get(realpathSync, 'native') + Reflect.deleteProperty(realpathSync, 'native') + try { + registration.replace({ ...base, linkedRoots: [{ ...linked, realPath: realpathSync(second) }] }) + } finally { Reflect.set(realpathSync, 'native', native) } + registration.replace({ ...base, linkedRoots: [{ ...linked, realPath: realpathSync.native(second) }] }) + // A second move takes files of the first target straight to the latest one. + const third = join(f.root, 'work', 'third') + pkg(third, 'linked-lib', 3) + unlinkSync(link) + symlinkSync(third, link, process.platform === 'win32' ? 'junction' : 'dir') + registration.replace({ ...base, linkedRoots: [{ ...linked, realPath: realpathSync.native(third) }] }) + expect(createRequire(parentPath).resolve('linked-lib')).toBe(join(realpathSync.native(third), 'index.cjs')) + // Another link's move leaves this link's relocation as it is, and the innermost previous directory decides. + const outer = { name: 'outer-lib', realPath: realpathSync.native(join(f.root, 'work')) } + const atThird = { ...linked, realPath: realpathSync.native(third) } + registration.replace({ ...base, linkedRoots: [atThird, outer] }) + registration.replace({ ...base, linkedRoots: [atThird, { ...outer, realPath: realpathSync.native(f.root) }] }) + expect(createRequire(parentPath).resolve(join(first, 'index.cjs'))).toBe(join(realpathSync.native(third), 'index.cjs')) + unlinkSync(link) + symlinkSync(second, link, process.platform === 'win32' ? 'junction' : 'dir') + registration.replace({ ...base, linkedRoots: [{ ...linked, realPath: realpathSync.native(second) }] }) + // An importer below the previous target keeps resolving there, and pointing the link back ends the relocation. + expect(createRequire(join(first, 'index.cjs')).resolve('./index.js')).toBe(join(realpathSync(first), 'index.js')) + unlinkSync(link) + symlinkSync(first, link, process.platform === 'win32' ? 'junction' : 'dir') + registration.replace({ ...base, linkedRoots: [linked] }) + expect(createRequire(parentPath).resolve('linked-lib')).toBe(join(realpathSync(first), 'index.cjs')) + // A link installed again as a directory at the same path keeps Node's cached link real path, which is relocated too. + expect(createRequire(parentPath).resolve('linked-lib')).toBe(join(realpathSync(first), 'index.cjs')) + unlinkSync(link) + pkg(link, 'linked-lib', 4) + registration.replace({ ...base, linkedRoots: [], entries: [...base.entries, { + name: 'linked-lib', packageDir: link, version: '4.0.0', declarer: join(link, 'package.json'), scope: 'profile', + }] }) + expect(createRequire(parentPath).resolve('linked-lib')).toBe(join(realpathSync.native(link), 'index.cjs')) + }) + + it('rejects a retained profile package moved to another directory, and maps it there once it was removed', async () => { + const f = fixture() + const firstDir = join(f.root, 'bundle-a', 'node_modules', 'private-lib') + const secondDir = join(f.root, 'bundle-b', 'node_modules', 'private-lib') + pkg(firstDir, 'private-lib', 1) + pkg(secondDir, 'private-lib', 2) + const base = await resolutionOf(f) + const entry = { + name: 'private-lib', packageDir: firstDir, version: '1.0.0', + declarer: join(firstDir, 'package.json'), scope: 'profile' as const, + } + const first = { ...base, entries: [...base.entries, entry] } + const registration = installRuntimeInterception(first) + registrations.push(registration) + const parent = pathToFileURL(join(f.profile.dir, 'entry.mjs')).href + const moved = { ...first, entries: [...base.entries, { + ...entry, packageDir: secondDir, version: '2.0.0', declarer: join(secondDir, 'package.json'), + }] } + expect(() => { registration.replace(moved) }).toThrow(ResolutionRestartRequired) + registration.replace(base) + registration.replace(moved) + expect(registration.packageDir('private-lib', parent)).toBe(secondDir) + }) + + it('reports a package whose link keeps its path but points to another directory', async () => { + const f = fixture() + const firstDir = join(f.root, 'source-a') + const secondDir = join(f.root, 'source-b') + pkg(firstDir, 'linked-lib', 1) + pkg(secondDir, 'linked-lib', 2) + const link = join(f.root, 'links', 'linked-lib') + mkdirSync(dirname(link), { recursive: true }) + symlinkSync(firstDir, link, process.platform === 'win32' ? 'junction' : 'dir') + const base = await resolutionOf(f) + const entry = { name: 'linked-lib', packageDir: link, version: '1.0.0', declarer: join(link, 'package.json'), scope: 'profile' as const } + const resolution = { ...base, entries: [...base.entries, entry], linkedRoots: [{ name: 'linked-lib', realPath: realpathSync(firstDir) }] } + const registration = installRuntimeInterception(resolution) + registrations.push(registration) + unlinkSync(link) + symlinkSync(secondDir, link, process.platform === 'win32' ? 'junction' : 'dir') + // The mapping and the linked root report the same package once. + const relinked = { ...resolution, linkedRoots: [{ name: 'linked-lib', realPath: realpathSync(secondDir) }] } + expect(() => { registration.replace(relinked) }).toThrow(/^profile resolution: replacing "linked-lib" requires a process restart$/u) + }) + it('removes profile mappings and local names while retaining changed profile mappings as restarts', async () => { const f = fixture() const firstDir = join(f.root, 'bundle-a', 'node_modules', 'private-lib') @@ -1708,7 +1823,19 @@ describe('runtime resolution', { concurrent: false }, () => { } }) - it.each(['directory', 'version', 'scope'] as const)('rejects a retained profile mapping with a different %s', async (change) => { + it('accepts a retained profile mapping upgraded in place', async () => { + const f = fixture() + const packageDir = join(f.root, 'bundle', 'node_modules', 'private-lib') + pkg(packageDir, 'private-lib', 1) + const base = await resolutionOf(f) + const entry = { name: 'private-lib', packageDir, declarer: join(packageDir, 'package.json'), version: '1.0.0', scope: 'profile' as const } + const registration = installRuntimeInterception({ ...base, entries: [...base.entries, entry] }) + registrations.push(registration) + registration.replace({ ...base, entries: [...base.entries, { ...entry, version: '2.0.0' }] }) + expect(registration.packageDir('private-lib', pathToFileURL(join(f.profile.dir, 'entry.mjs')).href)).toBe(packageDir) + }) + + it.each(['directory', 'scope'] as const)('rejects a retained profile mapping with a different %s', async (change) => { const f = fixture() const packageDir = join(f.root, 'bundle', 'node_modules', 'private-lib') pkg(packageDir, 'private-lib', 1) @@ -1719,7 +1846,6 @@ describe('runtime resolution', { concurrent: false }, () => { const successor = { ...entry, packageDir: change === 'directory' ? join(f.root, 'different') : entry.packageDir, - version: change === 'version' ? '2.0.0' : entry.version, scope: change === 'scope' ? 'installation' as const : entry.scope, } @@ -2205,7 +2331,7 @@ describe('runtime resolution', { concurrent: false }, () => { }) it.each(['initial', 'added'] as const)( - 'rejects a removed %s root retarget without reactivating either directory', async (generation) => { + 'accepts a removed %s root retargeted to another directory', async (generation) => { const { f, linkedRoot } = unsavedFixture() const link = join(f.profile.dir, 'node_modules', 'my-plugin') const linkType = process.platform === 'win32' ? 'junction' : 'dir' @@ -2237,11 +2363,10 @@ describe('runtime resolution', { concurrent: false }, () => { const successor = await resolutionOf(f) expect(successor.localPackageNames).toEqual([]) expect(successor.linkedRoots).toEqual([{ name: 'my-plugin', realPath: target }]) - expect(() => { registration.replace(successor) }) - .toThrow(/^profile resolution: relinking "my-plugin" requires a process restart$/u) + registration.replace(successor) expectPeerLookup(registration, require, parent, join(linkedRoot, 'node_modules', peer)) expectPeerLookup(registration, createRequire(join(target, 'entry.cjs')), - pathToFileURL(join(target, 'entry.mjs')).href, join(target, 'node_modules', peer)) + pathToFileURL(join(target, 'entry.mjs')).href, f.installed) } finally { registration.dispose() registrations.pop() @@ -2249,64 +2374,6 @@ describe('runtime resolution', { concurrent: false }, () => { }, ) - it('does not retain targets from a rejected successor', async () => { - const { f, linkedRoot } = unsavedFixture() - const modules = join(f.profile.dir, 'node_modules') - const originalLink = join(modules, 'my-plugin') - const newLink = join(modules, 'a-new-plugin') - const replacement = join(f.root, 'work', 'replacement') - const rejectedTarget = join(f.root, 'work', 'rejected-target') - const acceptedTarget = join(f.root, 'work', 'accepted-target') - for (const [dir, name, marker] of [ - [replacement, 'my-plugin', 22], - [rejectedTarget, 'a-new-plugin', 31], - [acceptedTarget, 'a-new-plugin', 32], - ] as const) { - pkg(dir, name, 0, {}, { [peer]: '*' }) - pkg(join(dir, 'node_modules', peer), peer, marker) - } - const require = createRequire(join(linkedRoot, 'entry.cjs')) - const parent = pathToFileURL(join(linkedRoot, 'entry.mjs')).href - const first = await resolutionOf(f) - expect(first.localPackageNames).toEqual([]) - const registration = installRuntimeInterception(first) - registrations.push(registration) - try { - expectPeerLookup(registration, require, parent, f.installed) - unlinkSync(originalLink) - const removed = await resolutionOf(f) - expect(removed.linkedRoots).toEqual([]) - registration.replace(removed) - expectPeerLookup(registration, require, parent, join(linkedRoot, 'node_modules', peer)) - - const linkType = process.platform === 'win32' ? 'junction' : 'dir' - symlinkSync(replacement, originalLink, linkType) - symlinkSync(rejectedTarget, newLink, linkType) - const rejected = await resolutionOf(f) - expect(rejected.linkedRoots).toEqual([ - { name: 'a-new-plugin', realPath: rejectedTarget }, - { name: 'my-plugin', realPath: replacement }, - ]) - expect(() => { registration.replace(rejected) }) - .toThrow(/^profile resolution: relinking "my-plugin" requires a process restart$/u) - expectPeerLookup(registration, require, parent, join(linkedRoot, 'node_modules', peer)) - expectPeerLookup(registration, createRequire(join(rejectedTarget, 'entry.cjs')), - pathToFileURL(join(rejectedTarget, 'entry.mjs')).href, join(rejectedTarget, 'node_modules', peer)) - - unlinkSync(originalLink) - unlinkSync(newLink) - symlinkSync(acceptedTarget, newLink, linkType) - const accepted = await resolutionOf(f) - expect(accepted.linkedRoots).toEqual([{ name: 'a-new-plugin', realPath: acceptedTarget }]) - registration.replace(accepted) - expectPeerLookup(registration, createRequire(join(acceptedTarget, 'entry.cjs')), - pathToFileURL(join(acceptedTarget, 'entry.mjs')).href, f.installed) - expectPeerLookup(registration, require, parent, join(linkedRoot, 'node_modules', peer)) - } finally { - registration.dispose() - registrations.pop() - } - }) }) it.each(['src', 'dist'] as const)( diff --git a/packages/boot/app-boot/tests/user-patches.spec.ts b/packages/boot/app-boot/tests/user-patches.spec.ts index 6db0154321..09e5653c56 100644 --- a/packages/boot/app-boot/tests/user-patches.spec.ts +++ b/packages/boot/app-boot/tests/user-patches.spec.ts @@ -337,7 +337,10 @@ describe('profile reconciliation settlement', () => { const patches = [{ insert: [{ id: 'missing-plugin', name: './missing.mjs' }] }] const ctx = await boot(NAME, join(dir, 'cordis.yml'), patches) onTestFinished(() => ctx.fiber.dispose()) - expect(await reconcileProfilePatches(ctx, patches, NAME)).toEqual(['missing-plugin (./missing.mjs): failed to import']) + // Reload diagnostics carry the import error's message without stack frames. + const prefix = 'missing-plugin \\(\\./missing\\.mjs\\): failed to import: Error \\[ERR_MODULE_NOT_FOUND\\]' + const diagnostic = new RegExp(`^${prefix}: Cannot find module '[^']*missing\\.mjs' imported from [^\\n]*$`, 'u') + expect(await reconcileProfilePatches(ctx, patches, NAME)).toEqual([expect.stringMatching(diagnostic)]) }) it('rejects a context without the launcher root Include', async () => { @@ -414,13 +417,11 @@ describe('profile reconciliation settlement', () => { onTestFinished(async () => { release.resolve(undefined); await ctx.fiber.dispose() }) let settled = false const operation = reconcileProfilePatches(ctx, [], NAME).then(() => { settled = true }) - onTestFinished(async () => { release.resolve(undefined); await operation }) await started.promise - expect([...ctx.loader.entries()].find(entry => entry.options.id === 'held')?.fiber?.uid).toBeNull() + expect([...ctx.loader.entries()].some(entry => entry.options.id === 'held')).toBe(false) expect(settled).toBe(false) release.resolve(undefined) await operation - expect([...ctx.loader.entries()].some(entry => entry.options.id === 'held')).toBe(false) expect(settled).toBe(true) }) }) 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/cmdline/package.json b/packages/boot/cmdline/package.json index fbb190a2e7..96e1174bc0 100644 --- a/packages/boot/cmdline/package.json +++ b/packages/boot/cmdline/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-cmdline", "description": "Immutable command-line handoff from a dsh launcher to any app plugin that injects cmdlineArgs", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/boot/config-editor/README.i18n.yaml b/packages/boot/config-editor/README.i18n.yaml index 265864b3ec..5727bdff08 100644 --- a/packages/boot/config-editor/README.i18n.yaml +++ b/packages/boot/config-editor/README.i18n.yaml @@ -18,8 +18,8 @@ en: 1eedaa5d72b48177 zh: 39abc1d927a692d2 /deepseek-ai-dsh-config-editor/understand-the-implementation: - en: 6c0265c949db473c - zh: fe1849f32f2d111c + en: baa887b5ecfa7001 + zh: d3e03c2b1d10c67e /deepseek-ai-dsh-config-editor/further-exploration: en: 0c9e1d1401a865cc zh: 6130d52636e84676 diff --git a/packages/boot/config-editor/README.md b/packages/boot/config-editor/README.md index e67bdad23a..17da6551f9 100644 --- a/packages/boot/config-editor/README.md +++ b/packages/boot/config-editor/README.md @@ -42,8 +42,6 @@ The [editor](src/index.ts) reconciles external changes before deriving a candida Configuration reads share one composition for entries without profile config overrides. Overridden entries are composed separately with only their own override removed; profile inserts and other entries' overrides remain effective. Returned configs are detached, and compositions are not cached between reads. -Host configuration reads, edits, and resets ignore preset-scoped operations, including those whose child IDs match Host entry IDs. -
diff --git a/packages/boot/config-editor/README.zh.md b/packages/boot/config-editor/README.zh.md index 62abcab4bc..d1ff18344f 100644 --- a/packages/boot/config-editor/README.zh.md +++ b/packages/boot/config-editor/README.zh.md @@ -42,8 +42,6 @@ kind: "package-reference" 读取配置时,没有 profile config 覆盖项的条目共用一次组合结果。有覆盖项的条目分别组合,仅移除自身的覆盖项;profile 插入的条目和其他条目的覆盖项仍然生效。返回的配置为独立副本,组合结果不跨读取缓存。 -Host 配置读取、编辑和重置均忽略预设作用域操作,包括子项 ID 与 Host 条目 ID 相同的操作。 -
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 1fe2798f67..8c9e2ecef3 100644 --- a/packages/boot/config-editor/package.json +++ b/packages/boot/config-editor/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-config-editor", "description": "Persist plugin configuration through profile patches and Loader reconciliation", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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", "lib/types/**/*.d.ts.map", diff --git a/packages/boot/config-editor/src/index.ts b/packages/boot/config-editor/src/index.ts index 4a3e5be473..ffec879f40 100644 --- a/packages/boot/config-editor/src/index.ts +++ b/packages/boot/config-editor/src/index.ts @@ -3,11 +3,11 @@ import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { isDeepStrictEqual } from 'node:util' import { Context, FiberState, Service, resolveConfig } from '@deepseek-ai/cordis' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import { entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import yaml from 'js-yaml' import type { Entry, EntryOptions } from '@deepseek-ai/cordis-plugin-loader' import type {} from '@deepseek-ai/dsh-hmr' -import { composeEntries, loadProfileDirectory, profilePatchPreset, readProfilePatches, reconcileProfilePatches, type ProfilePatch } from '@deepseek-ai/dsh-app-boot' +import { composeEntries, loadProfileDirectory, readProfilePatches, reconcileProfilePatches } from '@deepseek-ai/dsh-app-boot' import { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write' import { isMap, isSeq, parseDocument, Scalar, visit } from 'yaml' @@ -22,7 +22,7 @@ function flatten(rows: EntryOptions[]): EntryOptions[] { return rows.flatMap(row => [row, ...row.group && Array.isArray(row.config) ? flatten(row.config as EntryOptions[]) : []]) } -/** Persist Host entry configs without changing preset-scoped operations, then reconcile through Loader. */ +/** Persist complete raw configs and apply them through the normal Loader path. */ export class ConfigEditor extends Service { static inject = ['loader', 'profileContext'] @@ -50,9 +50,8 @@ export class ConfigEditor extends Service { const profile = this.ownerContext.profileContext const loaded = loadProfileDirectory('dsh', profile.dir, profile.installAnchor) const entries = this.entries() - const hostPatches = loaded.patches.filter(patch => profilePatchPreset(patch) === undefined) // An own config key can replace inherited config even when its value is undefined. - const overridden = new Set(hostPatches.filter(patch => patch.insert === undefined && Object.hasOwn(patch, 'config')).map(patch => patch.id)) + const overridden = new Set(loaded.patches.filter(patch => patch.insert === undefined && Object.hasOwn(patch, 'config')).map(patch => patch.id)) const composed = new Map() if (entries.some(entry => !overridden.has(entry.options.id))) { for (const row of flatten(composeEntries([...loaded.layers.map(layer => layer.patches), loaded.patches]))) { @@ -64,7 +63,7 @@ export class ConfigEditor extends Service { inherited: overridden.has(entry.options.id) ? this.inherited(entry, loaded) : structuredClone((composed.get(entry.options.id)?.config ?? {}) as Record), - override: structuredClone((hostPatches.findLast( + override: structuredClone((loaded.patches.findLast( row => row.id === entry.options.id && row.config !== undefined, )?.config ?? {}) as Record), })) @@ -72,7 +71,7 @@ export class ConfigEditor extends Service { private inherited(entry: Entry, loaded: ReturnType): Record { const patches = loaded.patches.map((patch) => { - if (patch.id !== entry.options.id || patch.insert !== undefined || profilePatchPreset(patch) !== undefined) return patch + if (patch.id !== entry.options.id || patch.insert !== undefined) return patch const rest = { ...patch }; Reflect.deleteProperty(rest, 'config') return rest }) @@ -116,12 +115,12 @@ export class ConfigEditor extends Service { if (!isSeq(document.contents)) throw new Error('Profile patch must be a YAML sequence') document.contents.flow = false const index = document.contents.items.findLastIndex((item, index) => isMap(item) - && document.getIn([index, 'id']) === entry.options.id && !item.has('insert') && !item.has('preset') + && document.getIn([index, 'id']) === entry.options.id && !item.has('insert') && (!item.has('name') || document.getIn([index, 'name']) === entry.options.name)) if (isDeepStrictEqual(next, inherited)) { for (let index = document.contents.items.length - 1; index >= 0; index--) { const row = document.contents.items[index] - if (!isMap(row) || document.getIn([index, 'id']) !== entry.options.id || row.has('insert') || row.has('preset')) continue + if (!isMap(row) || document.getIn([index, 'id']) !== entry.options.id || row.has('insert')) continue row.delete('config') if (row.items.length === Number(row.has('id')) + Number(row.has('name'))) document.delete(index) } @@ -135,7 +134,7 @@ export class ConfigEditor extends Service { } }) const profile = this.ownerContext.profileContext const loaded = loadProfileDirectory('dsh', profile.dir, profile.installAnchor) - const patches = readProfilePatches('dsh', profile, { ...loaded, patches: yaml.load(String(document), { schema: entryListSchema }) as ProfilePatch[] }) + const patches = readProfilePatches('dsh', profile, { ...loaded, patches: yaml.load(String(document), { schema: entryListSchema }) as PatchOptions[] }) const effective = flatten(composeEntries([patches])).find(row => row.id === entry.options.id) if (!isDeepStrictEqual(effective?.config ?? {}, next)) { throw new Error(`Configuration for "${entry.options.id}" is overridden by a home patch or command-line overlay`) diff --git a/packages/boot/hmr/README.i18n.yaml b/packages/boot/hmr/README.i18n.yaml index 4f1eef45bf..776c0d0fe7 100644 --- a/packages/boot/hmr/README.i18n.yaml +++ b/packages/boot/hmr/README.i18n.yaml @@ -18,11 +18,11 @@ en: 9fd376ac44e7f515 zh: 83bd165982e99d2a /deepseek-ai-dsh-hmr/use-this-package/configuration: - en: 45ee194ad781d603 - zh: b3d7fcd8ed73717c + en: 11ef18c6d08f39f3 + zh: 2911cdd03ff3747d /deepseek-ai-dsh-hmr/understand-the-implementation: - en: 227c3c99c3c4b597 - zh: 853b656340cb8bce + en: bd608f418630317f + zh: 053fa77a3fa571a9 /deepseek-ai-dsh-hmr/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 @@ -39,8 +39,8 @@ en: 89e0624fafd701fb zh: 19d36a33c1d9af9d /deepseek-ai-dsh-hmr/known-limitations-and-deferred-work: - en: 0f46d4df1dab7f3b - zh: d172835159a20cce + en: 709368e0d6a644c2 + zh: 2d0f76c2cece79dc /deepseek-ai-dsh-hmr/known-limitations-and-deferred-work/dev-note: en: 7972e4b2005ec9a4 zh: 754c49ec538c164c diff --git a/packages/boot/hmr/README.md b/packages/boot/hmr/README.md index 513abc07b2..8d2270b4a1 100644 --- a/packages/boot/hmr/README.md +++ b/packages/boot/hmr/README.md @@ -46,6 +46,8 @@ Existing configurations replace the module name `@deepseek-ai/cordis-plugin-hmr` Chokidar options, including polling, retain their existing meaning. Exact configuration watches also observe additions, removals and initially missing parent directories. They default to `awaitWriteFinish: true`: edits wait for Chokidar's 2-second write-stability window, avoiding its lossy change-event throttle. Configure `awaitWriteFinish` to adjust that window; disabling it can miss rapid consecutive edits. Direct Plugin Manager operations apply without waiting for file events. +Profile recompositions run by HMR's profile watches and by Plugin Manager also replace plugins whose loaded files below the profile directory changed on disk. This covers installed packages below `node_modules` and the targets of linked packages. A package whose files changed in place, such as a linked package whose build output changed or a dependency another installation upgraded, therefore takes effect without a restart at the next such recomposition; source watching through `root` is not required. A replacement that fails to load stops the previous plugin and is reported as `failed` with its load error instead of as a restart, which would load the same files; every later recomposition imports it again, so it starts once its files or dependencies are corrected. + ----- @@ -54,10 +56,20 @@ Chokidar options, including polling, retain their existing meaning. Exact config
Implementation internals — click to expand -`watchConfig()` registers an awaited configuration handler. `runExclusive()` serializes configuration changes and Loader updates with automatic reloads and rejects nested transactions. Package installation and removal run outside this queue. HMR does not acquire the package writer lock; manifest notifications reload only when the ordered `dsh.profile.bundles` list changes. Profile and home patch changes also trigger recomposition. File events received during a configuration transaction are processed afterward. Include refreshes and profile reconciliation reach plugins through ordinary Loader entry updates; Loader commits volatile-only changes in place. +`watchConfig()` registers an awaited configuration handler and watches only its target path and required parent directories; sibling files, including temporary writer locks, are excluded before native watcher creation. `runExclusive()` serializes configuration changes and Loader updates with automatic reloads and rejects nested transactions. Package installation and removal run outside this queue. HMR does not acquire the package writer lock; manifest notifications reload only when the ordered `dsh.profile.bundles` list changes. Profile and home patch changes also trigger recomposition. File events received during a configuration transaction are processed afterward. Include refreshes and profile reconciliation reach plugins through ordinary Loader entry updates; Loader commits volatile-only changes in place. App-boot owns profile parsing and patch precedence. HMR reads the launcher’s data-only `profileContext`, registers the profile manifest and both user patch watches during initialization, and waits for application readiness before processing changes. Its disposal closes the watchers and cancels reloads waiting for startup. Configuration watchers start outside the active transaction context so later notifications can enter the queue. +`reconcileProfile()` is shared by HMR’s profile watches and Plugin Manager; callers hold `runExclusive()`. Config Editor recomposes through app-boot without replacing modules. App-boot prepares and preflights the generation before caches or running entries change. + +File comparison covers the profile directory and linked package targets, recorded when the application becomes ready. [ModuleFiles](src/module-files.ts) records inode, size and modification time; adding a hard link alone does not invalidate a module. Existing modules retain the identities read before replacement, preserving later writes. Newly loaded modules are recorded at settlement so a subsequent installation does not restart them merely because they are recent. + +Replacement follows ES module links and every CommonJS parent’s `children`. A module's plugins are read from its ES module namespace and from the CommonJS exports Node already cached, without evaluating anything, so a CommonJS plugin registered outside a Loader entry keeps its cache. Host dependencies and plugins outside the traversable Loader tree stay pending. The remaining changed modules and their importers are evicted without a backup, and the Loader entries running affected plugins stop. HMR imports no replacement code itself: the Loader imports the current files when the generation starts an entry, so disabled, removed and incompatible rows never execute it, and dynamic `disabled` expressions and nested Includes are evaluated as at startup. + +Affected runtimes stop without making their entries disabled, and `reconcileProfile()` passes them to app-boot's single `recomposeProfile()` call, which starts them, including those below an unchanged Include and those outside the profile composition, without importing an entry twice. A failure before any stop leaves every plugin running; stopped plugins start again with the current resolution when no generation applied. After eviction, a replacement that fails to import or start is an activation failure and rejects the operation; its previous code no longer runs. Every recomposition imports entries whose import failed again, after expiring the package configuration below the profile roots and evicting modules whose links failed, so a corrected file or a dependency installed later takes effect without a restart. [ProfileReconciliation](../../../docs/subsystems/boot.md#profile-reconciliation) lists changes requiring a restart. A module first loaded during a recomposition whose file was written after the comparison stays stale, so a write during activation is loaded next time; comparison or cache-inspection failure requires a restart even when no changed URL is known. HMR’s watches log the result. + +After each recomposition, HMR evicts the loaded modules below the directories of the mappings the recomposition dropped and expires their package configuration, so the packages a removed or deselected bundle depends on, including those it imports dynamically, are imported afresh when it returns. A bundle package is not a mapping: its own files are replaced when they changed on disk, and a bundle switched off while its files stay unchanged keeps its modules loaded. A publication the runtime resolution rejects, such as a retained profile mapping that moved to another directory, stops and starts again the rows the generation would drop and leaves the composition as it was; the result has `restartReason: 'package-moved'`. + A changed `package.json` outside `node_modules` expires that package's cached configuration. A configuration-only manifest triggers no module reload; a manifest imported as a JSON module retains dependency-driven reloads, and one in the host dependency graph retains host reloads. Dedicated configuration watches keep their existing ownership. A new package entry takes effect when its Loader entry restarts. Loader entries retain their raw import results. HMR retains every distinct imported namespace for each entry name and configuration-tree base URL; an uninitialized entry does not overwrite another entry's namespace. HMR matches those objects to cached ModuleJob namespaces instead of resolving entry names again. Names without an imported namespace and `cordis:` builtins keep name-based resolution. Source reloads therefore use the loaded modules after `exports` or `main` changes. @@ -94,7 +106,16 @@ Reloading a contributing plugin can change later request prefixes; HMR does not - Module replacement requires Node loader internals. Framework dependency changes call the host-provided `loader.exit()` hook; HMR itself does not restart the process. -- Replacing installed package versions still requires a restart through Plugin Manager; manifests below `node_modules` keep Node's cached configuration. The browser Client module graph retains its separate browser-side loading mechanism. +- A change confined to `package.json` is not detected. Watcher notifications for manifests below `node_modules` are still ignored. The browser Client module graph retains its separate browser-side loading mechanism. +- Replacement follows static imports. A dynamic `import()` of a stale module evaluates the new file on its next call while its importer keeps running; existing Workers and the TSX loader thread keep their module caches. +- Every symbolic link below the profile's `node_modules` widens the comparison scope. Linking a package that the process entry point, located through the real path of a bin link, imports statically, such as `dsh-app-boot`, Cordis or the Loader from a dsh checkout, brings host modules into scope; their changes stay pending, and Plugin Manager reports `restart-required` for later operations until the process restarts. Linked dsh packages that Loader entries import are replaced like other plugins. +- The comparison records belong to one HMR instance. A recomposition that restarts the `hmr` entry itself records the current files again, so changes pending at that point are no longer reported or retried. +- A replacement that fails to import or start stays inactive until its files or dependencies are corrected; the previous version is not restored. +- Compatibility checks run only where DSH composes rows: startup, profile recomposition and preset mounting; the Loader checks nothing when it imports a module. A replaced profile row passes the recomposition's preflight, but a row outside the profile composition, such as a preset row or an entry added through `ctx.loader.create()`, restarts with replaced code without a check. Plugin Manager refuses incompatible versions, so this affects packages changed outside it, such as a manual `pnpm add` in the profile directory or a rebuilt `link:` package. +- The [packed worker loader](../../experimental/webworker-runtime/src/module-system/module-loader.ts) exposes neither Node’s `loadCache` nor `require.cache`; configuration recomposition remains available, but code replacement requires a restart. Native Node retains these caches even with asynchronous module hooks. The [packed worker browser test](../../../apps/web/tests/preview-boot.e2e.ts) exercises this deployment. +- A newly loaded file is first recorded after recomposition settles and counts as changed when its modification time follows the comparison. The comparison time is the modification time of a marker file HMR writes in the temporary directory, so on one machine both come from the clock local file writes are stamped with; an edit within the timestamp granularity of the profile's filesystem after the comparison counts as earlier and can be missed, and network filesystems stamp writes with the server's clock. +- A file replaced by a hard link to an older store file keeps an older modification time; when its module was first loaded after the last recording, the change is not detected. +- Profile recomposition caused by HMR's own watches does not run for dependency-only manifest changes, so an install performed outside Plugin Manager takes effect at the next recomposition or restart. - TSX loaders and ordinary application-created Workers are outside the supported package-cache refresh scope. - CommonJS requests must be resolvable by Node's default resolver. Synchronous hooks may postprocess the resulting filenames, as Desktop's Office resolver does; hooks requiring the original request name or introducing virtual requests are unsupported. Builtins retain Node's original loading behavior. - Future work: retain package invalidation across HMR disposal and replacement. Restoring the native readers can expose their older cached configuration again. diff --git a/packages/boot/hmr/README.zh.md b/packages/boot/hmr/README.zh.md index ba99733ccf..21044fe7d1 100644 --- a/packages/boot/hmr/README.zh.md +++ b/packages/boot/hmr/README.zh.md @@ -46,6 +46,8 @@ kind: "package-reference" Chokidar 选项(包括轮询)保持原有含义。精确配置监听同时观察新增、删除及初始不存在的父目录。它们默认使用 `awaitWriteFinish: true`:编辑后等待 Chokidar 的 2 秒写入稳定窗口,避免其变化事件节流丢失通知。可通过 `awaitWriteFinish` 调整窗口;禁用它可能漏掉快速连续编辑。直接通过 Plugin Manager 发起的操作无需等待文件事件即可应用。 +HMR 的 profile 监听和 Plugin Manager 执行的 profile 重新组合,还会替换 profile 目录下已加载文件在磁盘上发生变化的插件。这包括 `node_modules` 之下的已安装包,以及已链接包的目标。因此,文件被原地更改的包,例如构建输出发生变化的已链接包,或被另一次安装升级的依赖,会在下一次此类重新组合时生效,无需重启;不要求通过 `root` 监听源码。替换版本加载失败时,原插件被停止,并以 `failed` 及其加载错误报告,而不是报告为需要重启,因为重启会加载相同的文件;此后每次重新组合都会再次导入它,因此其文件或依赖被修正后它即启动。 + ----- @@ -54,10 +56,20 @@ Chokidar 选项(包括轮询)保持原有含义。精确配置监听同时
实现细节——点击展开 -`watchConfig()` 注册会被等待的配置处理器。`runExclusive()` 将配置变更、Loader 更新与自动重载串行化,并拒绝嵌套事务。包安装和删除在该队列之外执行。HMR 不获取包操作写锁;manifest 通知仅在有序的 `dsh.profile.bundles` 列表变化时触发重载。profile 与 home patch 变化也会触发重新组合。配置事务期间收到的文件事件在事务结束后处理。 Include 刷新和 profile 重载都通过普通的 Loader 条目更新到达插件;仅 volatile 变化由 Loader 就地提交。 +`watchConfig()` 注册会被等待的配置处理器,仅监听目标路径及必要的父目录;同级文件(包括临时写锁)在创建原生 watcher 前即被排除。`runExclusive()` 将配置变更、Loader 更新与自动重载串行化,并拒绝嵌套事务。包安装和删除在该队列之外执行。HMR 不获取包操作写锁;manifest 通知仅在有序的 `dsh.profile.bundles` 列表变化时触发重载。profile 与 home patch 变化也会触发重新组合。配置事务期间收到的文件事件在事务结束后处理。 Include 刷新和 profile 重载都通过普通的 Loader 条目更新到达插件;仅 volatile 变化由 Loader 就地提交。 App-boot 负责 profile 解析和 patch 优先级规则。HMR 读取启动器提供的纯数据 `profileContext`,在初始化时注册 profile manifest 和两份用户 patch 的监听,并等待应用就绪后处理更改。销毁 HMR 时会关闭监听器并取消等待启动的重载。配置监听器在当前事务上下文之外启动,使后续通知可以进入队列。 +`reconcileProfile()` 由 HMR 的 profile 监听和 Plugin Manager 共用;调用方持有 `runExclusive()`。Config Editor 通过 app-boot 重新组合,不替换模块。app-boot 在缓存或运行中条目发生变化前准备新一代组合并执行预检。 + +文件比较覆盖 profile 目录及已链接包的目标,在应用就绪时记录。[ModuleFiles](src/module-files.ts) 记录 inode、大小和修改时间;仅添加硬链接不会使模块失效。已有模块保留替换前读取的身份,以检测之后的写入。新加载的模块在结算时记录,因此后续安装不会仅因其文件较新而将其重启。 + +替换沿 ES 模块链接以及每个 CommonJS 父模块的 `children` 传播。模块的插件从其 ES 模块命名空间以及 Node 已缓存的 CommonJS exports 中读取,不求值任何代码,因此在 Loader entry 之外注册的 CommonJS 插件保留其缓存。宿主依赖及可遍历 Loader 树之外的插件保持待处理。其余已变化模块及其导入方被逐出且不保留备份,运行受影响插件的 Loader entry 被停止。HMR 本身不导入替换代码:新一代组合启动条目时,Loader 导入当前文件,因此停用、删除和不兼容的行永远不会执行替换代码,动态 `disabled` 表达式和嵌套 Include 按启动时的方式求值。 + +受影响的运行时停止,但其条目不会被标记为停用;`reconcileProfile()` 把它们传给 app-boot 的单次 `recomposeProfile()` 调用,由该调用启动它们,包括未变化 Include 之下的条目和 profile 组合之外的条目,且不会重复导入同一条目。任何插件停止之前发生的失败会让所有插件继续运行;没有新一代组合被应用时,已停止的插件以当前 resolution 重新启动。逐出之后,导入或启动失败的替换版本属于激活失败,使操作失败;其旧代码不再运行。每次重新组合都会先让 profile 根目录下的包配置失效并逐出链接失败的模块,再次导入此前导入失败的条目,因此修正后的文件或之后安装的依赖无需重启即生效。[ProfileReconciliation](../../../docs/subsystems/boot.zh.md#profile-reconciliation) 列出需要重启的变化。在重新组合期间首次加载、且其文件在比较之后被写入的模块保持陈旧,因此激活期间的写入会在下一次加载;比较或缓存检查失败时,即使无法确定已变化的 URL,也要求重启。HMR 的监听记录这些结果。 + +每次重新组合之后,HMR 逐出重新组合删除的映射所在目录之下的已加载模块,并使这些包的配置过期,因此已删除或取消选入的组合包连同其动态导入的依赖,在它再次出现时重新导入。组合包的包本身不是映射:其文件在磁盘上变化时被替换;关闭组合包而其文件未变化时,它的模块保持加载。runtime resolution 拒绝的发布(例如移动到其他目录的保留 profile 映射)会停止并重新启动新一代组合将删除的行,组合保持不变;结果带有 `restartReason: 'package-moved'`。 + `node_modules` 之外的 `package.json` 变化使该包的配置缓存失效。仅作为配置的 manifest 不触发模块重载;作为 JSON 模块导入的 manifest 保留依赖驱动重载,位于宿主依赖图中的 manifest 保留宿主重载。专属配置监听保留原有归属。新包入口在 Loader entry 重启时生效。 Loader entry 保留原始导入结果。HMR 为每个 entry 名称与配置树 base URL 保留所有不同的已导入命名空间;尚未初始化的 entry 不会覆盖其他 entry 的命名空间。HMR 将这些对象与缓存中 ModuleJob 的模块命名空间按对象身份匹配,不再重新解析 entry 名称。没有已导入命名空间的名称和 `cordis:` 内置入口仍按名称解析。因此 `exports` 或 `main` 改变后,源码重载仍使用已加载模块。 @@ -94,7 +106,16 @@ Loader entry 保留原始导入结果。HMR 为每个 entry 名称与配置树 b - 模块替换需要 Node loader 内部接口。框架依赖变化调用宿主提供的 `loader.exit()` 钩子;HMR 本身不重启进程。 -- 通过插件管理器替换已安装包版本仍需要重启;`node_modules` 之下的 manifest 保留 Node 缓存的配置。浏览器 Client 模块图保留独立的浏览器侧加载机制。 +- 仅限于 `package.json` 的变化不会被检测到。`node_modules` 之下 manifest 的监听通知仍被忽略。浏览器 Client 模块图保留独立的浏览器侧加载机制。 +- 替换沿静态导入传播。对陈旧模块的动态 `import()` 在下次调用时求值新文件,而其导入方继续运行;已存在的 Worker 和 TSX loader 线程保留各自的模块缓存。 +- profile 的 `node_modules` 之下的每个符号链接都会扩大比较范围。链接进程入口(通过 bin 链接的真实路径定位)静态导入的包(例如来自 dsh checkout 的 `dsh-app-boot`、Cordis 或 Loader)会把宿主模块纳入范围;这些模块的变化保持待处理,Plugin Manager 对后续操作报告 `restart-required`,直到进程重启。Loader entry 导入的已链接 dsh 包与其他插件一样被替换。 +- 比较记录属于单个 HMR 实例。重启 `hmr` 条目本身的重新组合会重新记录当前文件,因此此时待处理的变化不再被报告或重试。 +- 导入或启动失败的替换版本保持未激活,直到其文件或依赖被修正;旧版本不会被恢复。 +- 兼容性检查只在 DSH 组合行时运行:启动、profile 重新组合和 preset 挂载;Loader 导入模块时不做任何检查。被替换的 profile 行会通过重新组合的预检,但 profile 组合之外的行(例如 preset 行,或通过 `ctx.loader.create()` 添加的条目)以替换后的代码重启,不经检查。Plugin Manager 拒绝不兼容的版本,因此这只影响在它之外变化的包,例如在 profile 目录中手动执行 `pnpm add`,或重新构建的 `link:` 包。 +- [打包 worker loader](../../experimental/webworker-runtime/src/module-system/module-loader.ts) 不暴露 Node 的 `loadCache` 或 `require.cache`;配置重新组合仍可执行,但代码替换需要重启。原生 Node 即使使用异步模块 hook 也保留这些缓存。[打包 worker 浏览器测试](../../../apps/web/tests/preview-boot.e2e.ts) 覆盖此部署。 +- 新加载文件首次在重新组合结算后记录,其修改时间晚于比较时间时计为已变化。比较时间是 HMR 在临时目录中写入的标记文件的修改时间,因此在同一台机器上,两者都来自为本地文件写入记时的时钟;在比较之后、处于 profile 所在文件系统时间戳精度之内的修改被视为更早,可能被漏检;网络文件系统使用服务器的时钟为写入记时。 +- 若文件被替换为指向较旧 store 文件的硬链接,它保留较旧的修改时间;当其模块在上次记录之后才首次加载时,该变化不会被检测到。 +- HMR 自身监听触发的 profile 重新组合不会因仅涉及依赖的 manifest 变化而执行,因此在 Plugin Manager 之外执行的安装在下一次重新组合或重启时生效。 - TSX loader 和普通应用自行创建的 Worker 不在包缓存刷新支持范围内。 - CommonJS 请求必须能由 Node 默认 resolver 解析。同步 hook 可以像 Desktop 的 Office resolver 一样处理解析后的文件名;依赖原始请求名或引入虚拟请求的 hook 不受支持。内置模块保留 Node 原有的加载行为。 - 后续工作:跨 HMR 销毁和替换保留包配置失效状态。恢复原生 reader 后,其旧配置缓存可能重新可见。 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 56996edf69..7bf58668f6 100644 --- a/packages/boot/hmr/package.json +++ b/packages/boot/hmr/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-hmr", "description": "Coordinated module and profile configuration hot reload", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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", "lib/types/**/*.d.ts.map", @@ -40,8 +42,8 @@ }, "dependencies": { "@babel/code-frame": "^7.29.0", - "chokidar": "^4.0.3", - "node-addon-require-builtin": "^0.1.6", + "chokidar": "5.0.0", + "node-addon-require-builtin": "^0.1.9", "picomatch": "^4.0.7", "@deepseek-ai/schemastery": "workspace:~" }, diff --git a/packages/boot/hmr/src/index.ts b/packages/boot/hmr/src/index.ts index cad957dbda..47d71d9109 100644 --- a/packages/boot/hmr/src/index.ts +++ b/packages/boot/hmr/src/index.ts @@ -2,16 +2,19 @@ import assert from 'node:assert/strict' import { AsyncLocalStorage } from 'node:async_hooks' import { watchConfig as watchExactConfig } from './watch-config.ts' -import { Context, Inject, Service, type Fiber, type Plugin } from '@deepseek-ai/cordis' -import type { ModuleLoader, ModuleJob, ResolveResult } from '@deepseek-ai/cordis-plugin-loader' +import { Context, FiberState, Inject, Service, type Fiber, type Plugin } from '@deepseek-ai/cordis' +import type { Entry, ModuleLoader, ModuleJob, ResolveResult } from '@deepseek-ai/cordis-plugin-loader' import type { Include } from '@deepseek-ai/cordis-plugin-include' import { FSWatcher, watch, type ChokidarOptions } from 'chokidar' import { basename, dirname, join, relative, resolve, sep } from 'node:path' -import { readFileSync, realpathSync } from 'node:fs' -import { readProfileManifest, readProfilePatches, reconcileProfilePatches, PROFILE_PATCH_FILENAME } from '@deepseek-ai/dsh-app-boot' +import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs' +import { + readProfileManifest, readProfilePatches, recomposeProfile, PROFILE_PATCH_FILENAME, type RuntimeResolution, +} from '@deepseek-ai/dsh-app-boot' import type {} from '@deepseek-ai/dsh-cmdline' import { handleError } from './error.ts' import { PackageManifests } from './package-manifest.ts' +import { ModuleFiles } from './module-files.ts' import type {} from '@deepseek-ai/cordis-plugin-timer' import { fileURLToPath, pathToFileURL } from 'node:url' import { createRequire } from 'node:module' @@ -63,16 +66,16 @@ export interface HmrConfig extends ChokidarOptions { /** * Recursively collect all module dependencies from a ModuleJob. - * Skips node: builtins and node_modules to focus on user code. + * Skips node: builtins, and node_modules unless `includeNodeModules` is set, to focus on user code. */ -async function loadDependencies(job: ModuleJob, ignored = new Set()) { +async function loadDependencies(job: ModuleJob, ignored = new Set(), includeNodeModules = false) { const dependencies = new Set() async function traverse(job: ModuleJob) { if (ignored.has(job.url) || dependencies.has(job.url)) return - if (job.url.startsWith('node:') || job.url.includes('/node_modules/')) return + if (job.url.startsWith('node:') || (!includeNodeModules && job.url.includes('/node_modules/'))) return dependencies.add(job.url) - const children = await job.linked - await Promise.all(Array.prototype.map.call(children, traverse)) + const children = await linkedJobs(job) + await Promise.all(children.map(traverse)) } await traverse(job) return dependencies @@ -254,6 +257,9 @@ class Hmr extends Service { private closing = false private readonly configPaths = new Set() private readonly manifests = new PackageManifests() + private readonly files = new ModuleFiles() + /** Every module statically reachable from the process entry point, including those under node_modules; collected on first use. */ + private hostModules!: () => Promise> /** Serialize a caller-owned mutation with all automatic reload paths. * @param operation Work that must not overlap module or configuration replacement. @@ -308,7 +314,48 @@ class Hmr extends Service { this.baseDir = fileURLToPath(new URL(config.base || '.', ctx.baseUrl)) } + /** + * The cached ES module job for a URL. The packed worker loader exposes no Node module cache; native Node + * retains this cache even when asynchronous module hooks run in a separate thread. + */ + private esmJob(url: string): ModuleJob | undefined { + return this.hasEsmCache() ? this.internal.loadCache.get(url) : undefined + } + + /** Whether this thread keeps a Node ES module cache; the packed worker loader keeps none. */ + private hasEsmCache(): boolean { + const cache: unknown = Reflect.get(this.internal, 'loadCache') + return cache !== undefined + } + + /** Whether the ES module cache holds a job for a URL; `false` when this thread keeps no ES module cache. */ + private esmHas(url: string, type?: string): boolean { + return this.hasEsmCache() && (type === undefined ? this.internal.loadCache.has(url) : this.internal.loadCache.has(url, type)) + } + + /** ES module cache keys, empty when this thread keeps no ES module cache. */ + private esmUrls(): string[] { + return this.hasEsmCache() ? [...Map.prototype.keys.call(this.internal.loadCache) as Iterable] : [] + } + + /** ES module cache keys and CommonJS cache filenames as URLs. */ + private* loadedUrls(): Generator { + yield* this.esmUrls() + for (const filename of Object.keys(commonJsCache())) yield pathToFileURL(filename).href + } + + /** The module job of the process entry point, when the loader cached it under the entry's real path. */ + private mainJob(): ModuleJob | undefined { + const entry = process.argv[1] + if (entry === undefined) return undefined + // A package bin starts through a link, and Node caches the module under its target. + return this.esmJob(pathToFileURL(canonicalPath(resolve(entry))).href) + } + async* [Service.init](): AsyncGenerator<() => Promise, void, unknown> { + const mainJob = this.mainJob() + let host: Promise> | undefined + this.hostModules = () => host ??= mainJob === undefined ? Promise.resolve(new Set()) : loadDependencies(mainJob, new Set(), true) yield async () => { this.closing = true await this.watcher?.close() @@ -323,7 +370,16 @@ class Hmr extends Service { if (ready === undefined) throw new Error('Profile HMR requires application readiness') const started = Promise.withResolvers() this.applicationReady = started.promise - const unsubscribe = ready.onReady(() => { started.resolve(true) }) + const unsubscribe = ready.onReady(() => { + // Plugins started with the application are recorded; modules loaded later are compared by modification time. + try { + this.files.observe(this.profileModules(profileRoots(profile.dir))) + } catch (error) { + // Without a first record, modules are compared by modification time against this HMR instance’s creation time. + this.ctx.logger.warn(error) + } + started.resolve(true) + }) yield () => { unsubscribe(); started.resolve(false); return Promise.resolve() } const manifestPath = join(profile.dir, 'package.json') const patchFiles = [profile.patchPath, join(profile.home, PROFILE_PATCH_FILENAME)] @@ -340,8 +396,9 @@ class Hmr extends Service { } })]) if (inputs === lastInputs) return - const patches = readProfilePatches('dsh', profile) - const warnings = await reconcileProfilePatches(this.ownerContext.root, patches, 'dsh') + const { warnings, pending, restartReason } = await this.reconcileProfile() + if (restartReason !== undefined) this.ctx.logger.warn('restart required: %s', restartReason) + if (pending.length > 0) this.ctx.logger.warn('changed modules keep running their previous code until a restart: %o', pending) lastInputs = inputs lastBundles = bundles for (const diagnostic of warnings) this.ctx.logger.warn(diagnostic) @@ -363,8 +420,6 @@ class Hmr extends Service { // Collect externals before opening the watcher so every post-ready change // is observed by listeners that already have their classification state. - const mainJob = process.argv[1] === undefined ? undefined - : this.internal.loadCache.get(pathToFileURL(resolve(process.argv[1])).href) if (mainJob) { this.externals = await loadDependencies(mainJob) } else { @@ -399,7 +454,7 @@ class Hmr extends Service { fullReload = true continue } - if (this.internal.loadCache.has(url) || this.internal.loadCache.has(url, 'json')) { + if (this.esmHas(url) || this.esmHas(url, 'json')) { this.stashed.add(url) continue } @@ -454,7 +509,7 @@ class Hmr extends Service { * @returns Linked module URLs, or an empty list for an uncached module. */ async getLinked(url: string): Promise { - const job = this.internal.loadCache.get(url) + const job = this.esmJob(url) if (!job) return [] const linked = await job.linked return Array.prototype.map.call(linked, (job: ModuleJob) => job.url) as string[] @@ -546,7 +601,7 @@ class Hmr extends Service { try { const { url } = await names.resolve(name, baseUrl, moduleNamespace) if (this.declined.has(url)) continue - const job = this.internal.loadCache.get(url) + const job = this.esmJob(url) const plugin = this.ctx.loader.unwrapExports(job?.module?.getNamespace()) as Plugin | undefined if (!job || !plugin) continue pending.set(job, plugin) @@ -584,49 +639,7 @@ class Hmr extends Service { if (ReloadModules.include(reloads, plugin, job, this.ctx.registry.get(plugin))) this.accepted.add(job.url) } - /** - * Clear module caches for all accepted files before re-importing. - * - * We need to clear both: - * 1. ESM loadCache — managed by Node's internal ModuleLoader - * 2. CJS Module._cache — for CJS modules that were imported via import() - * - * In Node 24, CJS modules loaded via import() appear in both caches. - * If we only clear loadCache, the CJS cache may serve stale modules. - * - * We use Map.prototype methods directly on loadCache because: - * - In Node 22/23, loadCache is a plain Map - * - In Node 24, loadCache is a LoadCache extends Map - * where .delete() only sets the type slot to undefined (doesn't remove the entry) - * Using Map.prototype.delete ensures complete removal in both versions. - */ - const esmBackup = new Map() - const cjsBackup = new Map() - const require = createRequire(import.meta.url) - for (const filename of this.accepted) { - // Backup and clear ESM loadCache - const job: unknown = Map.prototype.get.call(this.internal.loadCache, filename) - esmBackup.set(filename, job) - Map.prototype.delete.call(this.internal.loadCache, filename) - - // Backup and clear CJS Module._cache - try { - const filepath = fileURLToPath(filename) - if (require.cache[filepath]) { - cjsBackup.set(filepath, require.cache[filepath]) - Reflect.deleteProperty(require.cache, filepath) - } - } catch { - // filename might not be a file: URL (e.g. node: protocol), ignore - } - } - - const rollback = () => { - for (const [filename, job] of esmBackup) { - Map.prototype.set.call(this.internal.loadCache, filename, job) - } - for (const [filepath, module] of cjsBackup) require.cache[filepath] = module - } + const rollback = this.evict(this.accepted) // Attempt to re-import all plugin entry files const generations = [...reloads].map(([previous, info]) => ({ @@ -726,8 +739,386 @@ class Hmr extends Service { replacements.updateEntries(this.ctx.loader) } this.ctx.emit('hmr/reload', reloads) + this.files.refresh(this.accepted) this.stashed = new Set() } + + /** + * Remove modules from the ES module and CommonJS caches so the next import evaluates their files again. + * + * CommonJS modules loaded through `import()` appear in both caches. Node's `LoadCache` maps each URL to per-type + * jobs, and its own `delete()` only clears one type slot, so whole entries are removed through `Map.prototype`. + * @returns Restores the removed cache entries. + */ + private evict(urls: Iterable): () => void { + const esmBackup = new Map() + const cjsBackup = new Map() + const cache = commonJsCache() + const list = [...urls] + // CommonJS-only files have no loadCache entry to restore. + const cached = new Set(this.esmUrls()) + for (const url of list) { + if (cached.has(url)) { + esmBackup.set(url, Map.prototype.get.call(this.internal.loadCache, url)) + Map.prototype.delete.call(this.internal.loadCache, url) + } + } + for (const filepath of list.filter(url => url.startsWith('file:')).map(url => fileURLToPath(url))) { + const module = cache[filepath] + if (module !== undefined) { + cjsBackup.set(filepath, module) + Reflect.deleteProperty(cache, filepath) + } + } + return () => { + for (const [url, job] of esmBackup) Map.prototype.set.call(this.internal.loadCache, url, job) + for (const [filepath, module] of cjsBackup) cache[filepath] = module + } + } + + /** Loaded `file:` modules below the given profile roots. */ + private profileModules(roots: readonly string[]): string[] { + return [...this.loadedUrls()].filter((url) => { + if (!url.startsWith('file:')) return false + const filename = fileURLToPath(url) + return roots.some(root => filename.startsWith(root)) + }) + } + + /** Static import edges between loaded modules, across ES module links and CommonJS `require` children. */ + private async moduleGraph(): Promise>> { + const importers = new Map>() + const add = (parent: string, child: string) => { + importers.set(child, (importers.get(child) ?? new Set()).add(parent)) + } + await Promise.all([...moduleJobs(this.internal)].map(async (job) => { + for (const child of await linkedJobs(job)) add(job.url, child.url) + })) + for (const [filename, module] of Object.entries(commonJsCache())) { + // Code that writes `require.cache` directly can store objects that are not Node modules. + /* v8 ignore next -- Node stores no undefined values in require.cache; the index type admits them */ + const children: unknown = module === undefined ? undefined : Reflect.get(module, 'children') + if (!Array.isArray(children)) continue + for (const child of children as NodeJS.Module[]) add(pathToFileURL(filename).href, pathToFileURL(child.filename).href) + } + return importers + } + + /** + * Plan the replacement of changed modules without changing anything. A changed module whose importers reach the + * process entry point's static graph, or a plugin that no affected Loader entry starts, stays loaded with its + * importers and is pending. The other changed modules and every module importing them are evicted by + * {@link stopPlanned}, which also expires the manifests from each changed file up to its root and stops the Loader + * entries running affected plugins. + * @param stale Changed module URLs. + * @param roots Directories, with a trailing separator, that bound the expired manifests. + * @returns The pending modules and the replacement of the others. + */ + private async planReplacement(stale: ReadonlySet, roots: readonly string[]): Promise { + const importers = await this.moduleGraph() + const host = await this.hostModules() + const managed = new Set(this.ctx.loader.entries()) + const plan: ReplacementPlan = { + pending: [], evicted: new Set(), manifests: new Set(), plugins: new Set(), fibers: new Set(), + } + for (const url of stale) { + const affected = new Set([url]) + for (const module of affected) for (const importer of importers.get(module) ?? []) affected.add(importer) + const running = [...new Set([...affected].flatMap(module => this.pluginsOf(module)))] + .flatMap(plugin => [...this.ctx.registry.get(plugin)?.fibers ?? []].map(fiber => ({ plugin, fiber }))) + const affectedFibers = new Set(running.map(({ fiber }) => fiber)) + /** The Loader entry whose own fiber runs an affected plugin and starts this fiber directly or through its ancestors. */ + const owner = (fiber: Fiber): Entry | undefined => { + for (let current = fiber; current.uid !== 0; current = current.parent.fiber) { + const entry = current.entry + if (entry?.fiber === current && managed.has(entry) && affectedFibers.has(current)) return entry + } + return undefined + } + const entries = running.flatMap(({ fiber }) => owner(fiber) ?? []) + // A plugin registered outside a Loader entry has no owner that can start its replacement. + const reason = [...affected].some(module => host.has(module)) ? 'host-module' + : entries.length < running.length ? 'unmanaged-plugin' : undefined + if (reason !== undefined) { + plan.pending.push({ url, reason }) + continue + } + for (const manifest of packageManifests(url, roots)) plan.manifests.add(manifest) + for (const module of affected) plan.evicted.add(module) + for (const { plugin, fiber } of running) { + plan.plugins.add(plugin) + plan.fibers.add(fiber) + } + } + return plan + } + + /** + * The plugins a loaded module exports, read from the ES module namespace and the CommonJS exports Node cached for it + * without evaluating anything. + * @param url Loaded module URL. + * @returns The exported plugins. + */ + private pluginsOf(url: string): Plugin[] { + const namespace = namespaceOf(this.esmJob(url)) + const required = url.startsWith('file:') ? commonJsCache()[fileURLToPath(url)] : undefined + const exports: unknown = required?.loaded === true ? required.exports : undefined + return [namespace, exports].filter(value => value !== undefined).map(value => this.ctx.loader.unwrapExports(value) as Plugin) + } + + /** + * Carry out a planned replacement: expire its manifests, evict its modules without a backup, and stop its Loader + * entries, so applying the generation imports the current files when it starts them. + * @param plan The planned replacement. + */ + private async stopPlanned(plan: ReplacementPlan): Promise { + for (const manifest of plan.manifests) this.manifests.invalidate(manifest) + this.evict(plan.evicted) + // Deleting the runtime stops its fibers without the Loader recording the entries as disabled. + for (const plugin of plan.plugins) this.ctx.registry.delete(plugin) + // Cordis contains disposal failures in the fiber, which logs them. + await Promise.allSettled([...plan.fibers].map(fiber => fiber.await())) + } + + /** + * Evict the loaded modules below the directories of mappings a recomposition dropped and expire their package + * configuration, so a disabled or removed package that is installed or enabled again is imported afresh. Modules of + * DSH's own static graph, and those below a directory that is still mapped, stay loaded. + * @param dropped Real directories, with a trailing separator, of the dropped mappings. + * @param kept Real directories, with a trailing separator, of the mappings that stay. + */ + private async evictDropped(dropped: readonly string[], kept: ReadonlySet): Promise { + if (dropped.length === 0) return + const host = new Set(await this.hostModules()) + const urls = this.profileModules(dropped).filter((url) => { + const filename = fileURLToPath(url) + return !host.has(url) && ![...kept].some(dir => filename.startsWith(dir)) + }) + for (const url of urls) for (const manifest of packageManifests(url, dropped)) this.manifests.invalidate(manifest) + this.evict(urls) + } + + /** Report a failed replacement step and retain the caller’s fallback outcome. */ + private async contained(step: string, operation: () => T | Promise, fallback: T): Promise { + try { + return await operation() + } catch (error) { + this.ctx.logger.warn('%s failed; module replacement was not completed', step) + this.ctx.logger.warn(error) + return fallback + } + } + + /** + * Recompose the profile from its manifest and patch files, replacing running plugins whose loaded files below the + * profile directory or its linked package targets changed on disk, and publishing its runtime resolution. Changed + * modules are evicted and the Loader entries running them stop; app-boot's {@link recomposeProfile} then publishes the + * resolution, applies the generation, starts the stopped entries with the current files and configuration, + * imports entries whose import failed again, and judges activation. Afterwards the modules below the mappings the + * recomposition dropped are evicted, so a removed or deselected package is imported afresh when it returns. Callers run + * inside {@link runExclusive}. + * @param requiredIds Entry ids whose inactive state is reported as a failure even when it predates this call. + * @returns Inactive-entry diagnostics, the changed modules that load after a restart, and a profile-wide restart reason. + * @throws The patch read, publication, preparation, apply, or activation failure of the recomposition, including a + * replacement plugin that fails to load or start, whose previous code no longer runs. + */ + async reconcileProfile(requiredIds: readonly string[] = []): Promise { + if (this.executing.getStore() !== true) throw new Error('HMR profile reconciliation must run inside runExclusive') + const profile = this.ownerContext.get('profileContext') + if (profile === undefined) throw new Error('HMR profile reconciliation requires profileContext') + // Entries this recomposition stops start again, and fail it when they cannot. + const running = [...this.ctx.loader.entries()].filter(entry => entry.fiber?.state === FiberState.ACTIVE) + // Read while the packages are still on disk, so a removed link's target is known in its real spellings. + const mapped = mappedDirectories(this.ownerContext.get('pluginPackages')?.resolution) + let comparison: ProfileComparison | undefined + let comparedAt = 0 + let pending: PendingModule[] = [] + try { + const patches = readProfilePatches('dsh', profile) + comparedAt = this.files.now() + // A failed comparison keeps every record, so the next recomposition compares the same modules again. + comparison = await this.contained('comparing loaded modules with disk', () => { + const roots = profileRoots(profile.dir) + return Promise.resolve({ roots, ...this.files.compare(this.profileModules(roots)) }) + }, undefined) + // Changed modules stay stale until replaced, including when the generation cannot be applied. + pending = [...comparison?.stale ?? []].map(url => ({ url, reason: 'module-comparison' })) + const compared = comparison + const unavailable = !this.hasEsmCache() + if (!unavailable && compared !== undefined && pending.length > 0) { + pending = await this.contained('planning module replacement', async () => { + const plan = await this.planReplacement(compared.stale, compared.roots) + await this.stopPlanned(plan) + return plan.pending + }, pending) + } + // Modules whose links or evaluation failed are evicted, so the recomposition retries failed imports against a + // corrected file or a dependency installed since. + await this.contained('expiring failed imports', () => { + // Without an ES module cache no failed module is known. + if (unavailable) return + const roots = compared?.roots ?? [realpathSync(profile.dir) + sep] + // A dependency installed since the failed import can sit in a directory Node recorded as having no manifest. + for (const root of roots) this.manifests.invalidate(join(root, 'package.json')) + // Node keeps a module whose links or evaluation failed. + this.evict(this.profileModules(roots).filter((url) => { + const job = this.esmJob(url) + return job !== undefined && namespaceOf(job) === undefined + })) + }, undefined) + const result = await recomposeProfile(this.ownerContext.root, patches, 'dsh', { requiredIds, running }) + const restartReason = compared === undefined || unavailable ? 'module-comparison' : result.restartReason + return { warnings: result.warnings, pending, ...restartReason === undefined ? {} : { restartReason } } + } finally { + const recorded = comparison + await this.contained('evicting dropped packages', () => { + const kept = mappedDirectories(this.ownerContext.get('pluginPackages')?.resolution) + return this.evictDropped([...mapped].filter(dir => !kept.has(dir)), kept) + }, undefined) + await this.contained('recording loaded module files', () => { + if (recorded === undefined) return + // Identities read before replacement keep writes made since then detectable. + const urls = this.profileModules(recorded.roots) + this.files.observe(urls, { seen: recorded.seen, retained: new Set(pending.map(({ url }) => url)), at: comparedAt }) + }, undefined) + } + } +} + +/** Loaded profile modules compared with disk, with the roots that bound them. */ +interface ProfileComparison { + roots: string[] + stale: Set + seen: Map +} + +/** The modules a replacement evicts, the manifests it expires, and the plugins it stops; pending modules stay loaded. */ +interface ReplacementPlan { + pending: PendingModule[] + evicted: Set + manifests: Set + plugins: Set + fibers: Set +} + +/** Outcome of {@link Hmr.reconcileProfile}. */ +export interface ProfileReconciliation { + /** Diagnostics for Loader entries left inactive. */ + warnings: string[] + /** Loaded modules whose files changed on disk and whose previous code keeps running until a restart. */ + pending: PendingModule[] + /** + * Why every change waits for a restart: `module-comparison` when module caches cannot be inspected or their files + * compared, even when no URLs are known; `package-moved` when the runtime resolution cannot publish a moved package. + */ + restartReason?: 'module-comparison' | 'package-moved' +} + +/** A changed module that loads only after a restart. */ +export interface PendingModule { + url: string + /** + * `host-module`: the process entry point's static graph imports it. `unmanaged-plugin`: it is imported by a plugin + * that runs outside a traversable Loader entry. `module-comparison`: loaded modules could not be compared with disk. + */ + reason: 'host-module' | 'unmanaged-plugin' | 'module-comparison' +} + +/** Node's `kErrored` module status, the same in every supported Node version. */ +const MODULE_ERRORED = 5 + +/** The namespace of a cached module job, or `undefined` when it has none or its evaluation threw. */ +function namespaceOf(job: ModuleJob | undefined): unknown { + if (job?.module === undefined) return undefined + // A module whose evaluation threw keeps a namespace whose bindings were never initialized. `getStatus()` exists on + // ModuleWrap in every supported Node version, like the other loader internals HMR reads. + const status: unknown = Reflect.apply(Reflect.get(job.module, 'getStatus') as () => number, job.module, []) + if (status === MODULE_ERRORED) return undefined + try { + return job.module.getNamespace() + /* v8 ignore start -- a cached module still linking in a concurrent import has no namespace yet; tests cannot hold an import there */ + } catch (_error) { + // A module that has not been instantiated exports no running plugin. + return undefined + } + /* v8 ignore stop */ +} + +/** + * The jobs a module job links to. Node 24+ may expose them as an array; Node 22 keeps the job of a failed import + * whose links reject, and such a job contributes no links. + */ +async function linkedJobs(job: ModuleJob): Promise { + /* v8 ignore next -- CI coverage runs Node 24+, which drops failed jobs from the cache */ + const linked = await Promise.resolve(job.linked).catch((_error: unknown) => []) + // Node 22 may return a null-prototype array without methods or an iterator. + return Array.from(linked) +} + +/** The Node-compatible CommonJS cache; the packed worker implements require without exposing this cache. */ +function commonJsCache(): NodeJS.Dict { + // Node's type declares the cache present for every `require`. + const cache: unknown = Reflect.get(createRequire(import.meta.url), 'cache') + return (cache ?? {}) as NodeJS.Dict +} + +/** Every module job in the loader cache; Node's `LoadCache` maps each URL to per-type jobs. */ +function* moduleJobs(internal: ModuleLoader): Generator { + for (const value of Map.prototype.values.call(internal.loadCache) as Iterable>>) { + yield* Object.values(value).filter(job => job !== undefined) + } +} + +/** + * The directories of a runtime resolution's profile mappings and linked roots, in every real spelling of those that + * exist, each with a trailing separator. + * @param resolution The published resolution, if any. + * @returns The directories; none without a resolution. + */ +function mappedDirectories(resolution: RuntimeResolution | undefined): Set { + const directories = new Set() + if (resolution === undefined) return directories + const dirs = [...resolution.entries.filter(entry => entry.scope === 'profile').map(entry => entry.packageDir), + ...resolution.linkedRoots.map(root => root.realPath)] + for (const dir of dirs) for (const spelling of existsSync(dir) ? realSpellings(dir) : [dir]) directories.add(spelling + sep) + return directories +} + +/** + * The JavaScript and native real paths of an existing path. A packed worker's file system has no native realpath. + * @param path Existing path. + * @returns The distinct spellings. + */ +function realSpellings(path: string): string[] { + const native: unknown = Reflect.get(realpathSync, 'native') + return [realpathSync(path), ...typeof native === 'function' ? [String(Reflect.apply(native, realpathSync, [path]))] : []] +} + +/** + * Real directories, with a trailing separator, of the profile and of the targets its linked packages point to. Each + * appears in both real-path spellings: Node's module caches use the JavaScript one, the runtime resolution the native + * one, and on Windows they differ for 8.3 short names. + */ +function profileRoots(dir: string): string[] { + const real = realpathSync(dir) + const modules = join(real, 'node_modules') + const names = existsSync(modules) ? readdirSync(modules) : [] + const packages = names.flatMap(name => name.startsWith('@') + ? readdirSync(join(modules, name)).map(child => join(modules, name, child)) + : [join(modules, name)]) + const linked = packages.filter(path => lstatSync(path).isSymbolicLink() && existsSync(path)) + return [...new Set([dir, ...linked].flatMap(path => realSpellings(path)).map(root => root + sep))] +} + +/** Every `package.json` from a module file's directory up to the profile root or linked package target containing it. */ +function packageManifests(url: string, roots: readonly string[]): string[] { + const manifests: string[] = [] + const contains = (directory: string) => roots.some(root => (directory + sep).startsWith(root)) + for (let directory = dirname(fileURLToPath(url)); contains(directory); directory = dirname(directory)) { + const candidate = join(directory, 'package.json') + if (existsSync(candidate)) manifests.push(candidate) + } + return manifests } namespace Hmr { diff --git a/packages/boot/hmr/src/module-files.ts b/packages/boot/hmr/src/module-files.ts new file mode 100644 index 0000000000..b734401ea4 --- /dev/null +++ b/packages/boot/hmr/src/module-files.ts @@ -0,0 +1,124 @@ +/** Disk identities of loaded module files, used to find modules whose files changed after loading. */ +import { mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' + +/** + * Coarsest file timestamp resolution among supported filesystems (FAT stores modification times in 2-second units). + * An unrecorded file modified within this interval before the last observation is treated as possibly changed. + */ +const TIMESTAMP_RESOLUTION_MS = 2000 + +interface FileIdentity { + /** Inode, size and modification time. */ + key: string + /** Modification time in epoch milliseconds. */ + modifiedAt: number +} + +function identityOf(url: string): FileIdentity | undefined { + let stats + try { + stats = statSync(fileURLToPath(url)) + } catch (_error) { + // A removed or unreadable file no longer provides the loaded module. + return undefined + } + return { key: `${String(stats.ino)}:${String(stats.size)}:${String(stats.mtimeMs)}`, modifiedAt: stats.mtimeMs } +} + +/** + * Records the inode, size and modification time of loaded `file:` modules. A module is stale when its file + * disappeared or its identity differs from the recorded one. Change time is not recorded: creating a hard link to a + * file, as pnpm does when it imports from its store, changes it without changing content. A module first loaded after + * the last observation has no record; it is stale when its file was modified at or after that observation, less the + * timestamp resolution, so a reinstall between loading and the next comparison is detected at the cost of reloading a + * module that was first loaded after such a write. + */ +export class ModuleFiles { + /** Identity per recorded module; `undefined` marks a stale module, such as a pending one first loaded after the last observation. */ + private records = new Map() + private observedAt = Date.now() + + /** + * The current time of the clock the operating system stamps local file writes with, read from a new marker file that is + * removed again. The system clock and file timestamps can differ by a clock tick in either direction, so module files + * are compared with this time; when no marker can be created, the system clock is used. + * @returns Epoch milliseconds. + */ + now(): number { + let directory: string + try { + directory = mkdtempSync(join(tmpdir(), 'dsh-hmr-clock-')) + } catch (_error) { + // An unwritable temporary directory leaves the less precise system clock. + return Date.now() + } + try { + const marker = join(directory, 'now') + writeFileSync(marker, '') + return statSync(marker).mtimeMs + } finally { + rmSync(directory, { recursive: true, force: true }) + } + } + + /** + * Compare loaded file modules with disk. + * @param urls `file:` URLs of the loaded modules to compare. + * @returns URLs of stale modules, and the identity read for each compared URL (`undefined` for a missing file). + */ + compare(urls: Iterable): { stale: Set; seen: Map } { + const stale = new Set() + const seen = new Map() + for (const url of urls) { + const identity = identityOf(url) + seen.set(url, identity?.key) + if (identity === undefined) { + stale.add(url) + continue + } + if (this.records.has(url) ? this.records.get(url) !== identity.key + : identity.modifiedAt >= this.observedAt - TIMESTAMP_RESOLUTION_MS) stale.add(url) + } + return { stale, seen } + } + + /** + * Replace every record with the identities of the given loaded modules. + * @param urls `file:` URLs of the loaded modules to record. + * @param options `seen` supplies identities read earlier for modules whose cache entry has not changed since, so a + * later write stays detectable; other modules are read now, and stay stale when their file was modified after `at`. + * `retained` modules keep their record, or are marked stale when they have none. `at` is the observation time from + * {@link now} used for unrecorded modules. + */ + observe(urls: Iterable, options: { + seen?: ReadonlyMap + retained?: ReadonlySet + at?: number + } = {}): void { + const { seen = new Map(), retained = new Set(), at = this.now() } = options + const records = new Map() + for (const url of urls) { + if (retained.has(url)) records.set(url, this.records.get(url)) + else if (seen.has(url)) records.set(url, seen.get(url)) + else { + // A module first loaded since `at` may have been evaluated before a write that followed it. A write in the same + // file clock tick as `at` counts as earlier, so files installed just before the comparison are not reloaded. + const identity = identityOf(url) + records.set(url, identity === undefined || identity.modifiedAt > at ? undefined : identity.key) + } + } + this.records = records + this.observedAt = at + } + + /** + * Record the current identity of modules just evaluated again, leaving every other record unchanged. + * @param urls `file:` URLs of the re-evaluated modules. + */ + refresh(urls: Iterable): void { + for (const url of urls) this.records.set(url, identityOf(url)?.key) + } +} diff --git a/packages/boot/hmr/src/watch-config.ts b/packages/boot/hmr/src/watch-config.ts index 6c62610dec..41815b5d8d 100644 --- a/packages/boot/hmr/src/watch-config.ts +++ b/packages/boot/hmr/src/watch-config.ts @@ -1,5 +1,5 @@ /** Exact-path watching for live profile patch files outside Cordis module roots. */ -import { dirname, relative, resolve } from 'node:path' +import { dirname, relative, resolve, sep } from 'node:path' import { realpath, stat } from 'node:fs/promises' import { watch, type ChokidarOptions } from 'chokidar' import type { Context } from '@deepseek-ai/cordis' @@ -25,7 +25,8 @@ async function findWatchRoot(filename: string): Promise<{ filename: string; root } /** - * Watch one patch path, including missing parents, and serialize refresh callbacks. + * Watch one patch path and its parent chain without subscribing to sibling files or directories. + * Missing parents are observed as they appear; refresh callbacks run serially. * @param ctx Context that owns watcher disposal and receives refresh failures. * @param filename Absolute patch-file path. * @param options Deployment watcher options; configuration watches enable write stabilization by default. @@ -46,6 +47,10 @@ export async function watchConfig( const watcher = watch(target.root, { // Stabilized events bypass Chokidar's lossy 50 ms change-event throttle. awaitWriteFinish: true, ...watchOptions, depth: target.depth, ignoreInitial: false, + ignored: (path) => { + const remainder = relative(resolve(path), target.filename) + return remainder === '..' || remainder.startsWith(`..${sep}`) + }, }) paths.add(target.filename) const state = { dirty: false } diff --git a/packages/boot/hmr/tests/module-files.spec.ts b/packages/boot/hmr/tests/module-files.spec.ts new file mode 100644 index 0000000000..1a0c32de83 --- /dev/null +++ b/packages/boot/hmr/tests/module-files.spec.ts @@ -0,0 +1,24 @@ +/** The file clock ModuleFiles compares module files with. */ +import * as fs from 'node:fs' +import { expect, it, vi } from 'vitest' +import { ModuleFiles } from '../src/module-files.ts' + +vi.mock('node:fs', async original => ({ ...await original() })) + +it('reads the time from a new marker file and removes it', () => { + const created = vi.spyOn(fs, 'mkdtempSync') + try { + const time = new ModuleFiles().now() + expect(time).toBeGreaterThan(0) + const directory = created.mock.results[0]?.value as string + expect(fs.existsSync(directory)).toBe(false) + } finally { created.mockRestore() } +}) + +it('falls back to the system clock when no marker can be created', () => { + const created = vi.spyOn(fs, 'mkdtempSync').mockImplementationOnce(() => { throw new Error('read-only') }) + try { + const before = Date.now() + expect(new ModuleFiles().now()).toBeGreaterThanOrEqual(before) + } finally { created.mockRestore() } +}) diff --git a/packages/boot/hmr/tests/package-reload.spec.ts b/packages/boot/hmr/tests/package-reload.spec.ts new file mode 100644 index 0000000000..5b3dc27571 --- /dev/null +++ b/packages/boot/hmr/tests/package-reload.spec.ts @@ -0,0 +1,1280 @@ +/** Profile reconciliation replaces plugins whose installed package files changed, through a real Loader and Node cache. */ +import { existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, symlinkSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs' +import NodeModule, { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, isAbsolute, join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { Context, FiberState, type Plugin } from '@deepseek-ai/cordis' +import Loader, { ModuleLoader, type Entry } from '@deepseek-ai/cordis-plugin-loader' +import { + boot, initProfile, ProfileRuntimeResolution, readProfileManifest, readProfilePatches, reconcileProfilePatches, ResolutionRestartRequired, + type PluginPackages, type ProfileContext, type RuntimeResolution, +} from '@deepseek-ai/dsh-app-boot' +import Timer from '@deepseek-ai/cordis-plugin-timer' +import { expect, it, onTestFinished, vi } from 'vitest' +import Hmr from '../src/index.ts' + +const watchers = vi.hoisted(() => [] as import('chokidar').FSWatcher[]) +vi.mock('chokidar', async (original) => { + const native = await original() + return { ...native, watch: () => { + const watcher = new native.FSWatcher() + watchers.push(watcher) + queueMicrotask(() => watcher.emit('ready')) + return watcher + } } +}) + +/** Silence the Loader's report of an entry whose import fails. */ +function quiet(ctx: Context): void { + const error = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) +} + +function file(path: string, source: string): void { + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, source) +} + +function plugin(version: string, imports = 'shared-lib'): string { + return `import { value } from '${imports}' +export const name = 'addon-${version}' +export function apply(ctx, config = {}) { + ctx.get('reloadTrace').push('start:${version}:' + value + ':' + (config.mode ?? '-')) + ctx.effect(() => () => { ctx.get('reloadTrace').push('stop:${version}') }) +} +` +} + +function addon(dir: string, version: string, source = plugin(version), mode?: string): void { + const root = join(dir, 'node_modules', 'addon') + file(join(root, 'package.json'), JSON.stringify({ + name: 'addon', version, type: 'module', exports: './index.mjs', dsh: { bundle: { patch: './cordis.patch.yml' } }, + })) + file(join(root, 'index.mjs'), source) + file(join(root, 'cordis.patch.yml'), `- insert:\n - id: addon\n name: addon\n${mode === undefined ? '' : ` config: { mode: ${mode} }\n`}`) +} + +function shared(dir: string, value: number): void { + const root = join(dir, 'node_modules', 'shared-lib') + file(join(root, 'package.json'), JSON.stringify({ name: 'shared-lib', version: `${String(value)}.0.0`, type: 'module', exports: './index.mjs' })) + file(join(root, 'index.mjs'), `export const value = ${String(value)}\n`) +} + +function other(dir: string): void { + const root = join(dir, 'node_modules', 'other') + file(join(root, 'package.json'), JSON.stringify({ + name: 'other', version: '1.0.0', type: 'module', exports: './index.mjs', dsh: { bundle: { patch: './cordis.patch.yml' } }, + })) + file(join(root, 'index.mjs'), `export function apply(ctx) { + ctx.get('reloadTrace').push('start:other') + ctx.effect(() => () => { ctx.get('reloadTrace').push('stop:other') }) +} +`) + file(join(root, 'cordis.patch.yml'), '- insert:\n - id: other\n name: other\n') +} + +function commonjs(dir: string, value: number): void { + const root = join(dir, 'node_modules', 'cjs-addon') + file(join(root, 'package.json'), JSON.stringify({ + name: 'cjs-addon', version: '1.0.0', main: './index.cjs', dsh: { bundle: { patch: './cordis.patch.yml' } }, + })) + file(join(root, 'index.cjs'), `const { value } = require('./helper.cjs') +exports.apply = (ctx) => { + ctx.get('reloadTrace').push('start:cjs:' + value) + ctx.effect(() => () => { ctx.get('reloadTrace').push('stop:cjs') }) +} +`) + file(join(root, 'helper.cjs'), `exports.value = ${String(value)}\n`) + file(join(root, 'cordis.patch.yml'), '- insert:\n - id: cjs-addon\n name: cjs-addon\n') +} + +/** Date every file below `dir` an hour back, as for packages installed before the application started. */ +function age(dir: string): void { + const past = new Date(Date.now() - 3_600_000) + for (const entry of readdirSync(dir, { recursive: true, withFileTypes: true })) { + if (entry.isFile()) utimesSync(join(entry.parentPath, entry.name), past, past) + } +} + +function linked(home: string, dir: string, value: number): string { + const target = join(home, 'work', 'linked') + file(join(target, 'package.json'), JSON.stringify({ + name: '@local/linked', version: '1.0.0', type: 'module', exports: './index.mjs', dsh: { bundle: { patch: './cordis.patch.yml' } }, + })) + file(join(target, 'index.mjs'), `export function apply(ctx) { + ctx.get('reloadTrace').push('start:linked:${String(value)}') + ctx.effect(() => () => { ctx.get('reloadTrace').push('stop:linked') }) +} +`) + file(join(target, 'cordis.patch.yml'), '- insert:\n - id: linked\n name: "@local/linked"\n') + const link = join(dir, 'node_modules', '@local', 'linked') + mkdirSync(dirname(link), { recursive: true }) + if (lstatSync(link, { throwIfNoEntry: false }) !== undefined) unlinkSync(link) + symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir') + return target +} + +async function fixture(bundles = ['addon', 'other'], before?: (home: string, dir: string) => Promise, ready = true) { + const home = realpathSync(mkdtempSync(join(tmpdir(), 'hmr-package-reload-'))) + const dir = join(home, 'profiles', 'test') + initProfile(dir, bundles) + writeFileSync(join(dir, 'cordis.yml'), '[]\n') + addon(dir, '1') + shared(dir, 1) + other(dir) + commonjs(dir, 1) + linked(home, dir, 1) + age(home) + await before?.(home, dir) + const profile: ProfileContext = { + name: 'test', dir, patchPath: join(dir, 'cordis.patch.yml'), home, cwd: home, + installAnchor: join(home, 'package.json'), startedBundles: bundles, overlays: [], telemetryDisabledEnv: undefined, + } + writeFileSync(profile.patchPath, JSON.stringify([{ insert: [ + { id: 'timer', name: 'cordis:timer' }, + { id: 'hmr', name: 'cordis:hmr', config: { root: [] } }, + ] }])) + const trace: string[] = [] + let commit: (() => void) | undefined + const firstWatcher = watchers.length + const ctx = await boot('test', join(dir, 'cordis.yml'), readProfilePatches('test', profile), (host) => { + host.provide('profileContext', profile) + host.provide('reloadTrace', trace) + host.provide('appReady', { onReady(listener) { commit = listener; return () => { commit = undefined } } }) + host.loader.builtins.timer = Timer + host.loader.builtins.hmr = Hmr + }) + onTestFinished(async () => { await ctx.fiber.dispose(); rmSync(home, { recursive: true, force: true }) }) + await ctx.loader.await() + if (ready) commit?.() + const reconcile = () => ctx.hmr.runExclusive(() => ctx.hmr.reconcileProfile()) + const select = (bundles: string[]) => { + const manifest = readProfileManifest('test', dir) + manifest.dsh = { profile: { bundles } } + writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest)) + } + /** Deliver a change of the profile patch file to HMR's own watch and wait for its recomposition. */ + const editPatch = async () => { + // Each configuration watch ignores paths other than its own file. + for (const watcher of watchers.slice(firstWatcher)) watcher.emit('change', profile.patchPath) + await vi.waitFor(async () => { await ctx.hmr.runExclusive(async () => {}) }) + await ctx.hmr.runExclusive(async () => {}) + } + return { ready: () => commit?.(), ctx, home, dir, trace, reconcile, select, editPatch, profile } +} + +it('leaves plugins running when no loaded file changed', async () => { + const f = await fixture() + expect(f.trace.toSorted()).toEqual(['start:1:1:-', 'start:other']) + f.trace.length = 0 + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual([]) +}) + +it('keeps a module whose file gains a hard link', async () => { + const f = await fixture() + f.trace.length = 0 + linkSync(join(f.dir, 'node_modules', 'addon', 'index.mjs'), join(f.home, 'store-copy.mjs')) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual([]) +}) + +it('replaces a plugin upgraded in place with the configuration of its new bundle patch', async () => { + const f = await fixture() + f.trace.length = 0 + addon(f.dir, '2', plugin('2'), 'fast') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['stop:1', 'start:2:1:fast']) +}) + +it('starts an upgraded plugin with a configuration its previous version rejects', async () => { + const f = await fixture() + addon(f.dir, '1', plugin('1').replace('export function apply(ctx, config = {}) {', "export function apply(ctx, config = {}) {\n if (config.mode) throw new Error('mode is unsupported')")) + age(f.dir) + await f.reconcile() + f.trace.length = 0 + addon(f.dir, '2', plugin('2'), 'fast') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['stop:1', 'start:2:1:fast']) +}) + +it('links an entry inserted by the upgraded bundle to the current files of a changed dependency', async () => { + const f = await fixture() + const extra = join(f.dir, 'node_modules', 'addon', 'extra.mjs') + f.trace.length = 0 + shared(f.dir, 2) + addon(f.dir, '1') + file(extra, `import { value } from 'shared-lib' +export function apply(ctx) { ctx.get('reloadTrace').push('start:extra:' + value) } +`) + file(join(f.dir, 'node_modules', 'addon', 'cordis.patch.yml'), '- insert:\n - id: addon\n name: addon\n - id: extra\n name: ./extra.mjs\n') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace.toSorted()).toEqual(['start:1:2:-', 'start:extra:2', 'stop:1']) +}) + +it('leaves a changed plugin that no Loader entry owns for a restart', async () => { + const f = await fixture([]) + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + const url = pathToFileURL(join(f.dir, 'node_modules', 'addon', 'index.mjs')).href + await f.ctx.plugin(f.ctx.loader.unwrapExports(await f.ctx.loader.import(url)) as Plugin) + expect(f.trace).toEqual(['start:1:1:-']) + addon(f.dir, '2') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [{ url, reason: 'unmanaged-plugin' }] }) + expect(f.trace).toEqual(['start:1:1:-']) +}) + +/** A runtime resolution table mapping `addon` to a directory, with further dropped profile packages. */ +function table(addonDir: string, ...dropped: string[]): RuntimeResolution { + const entry = (name: string, packageDir: string) => ({ + name, packageDir, version: '1.0.0', declarer: join(packageDir, 'package.json'), scope: 'profile' as const, + }) + return { + profilesDir: '/profiles', profileDir: '/profiles/test', localPackageNames: ['addon', ...dropped], + entries: [entry('addon', addonDir), ...dropped.map(name => entry(name, isAbsolute(name) ? name : `/packages/${name}`))], + linkedRoots: [], + } +} + +/** + * Install a recomputable runtime resolution whose latest generation is `latest`; `replace` decides each publication. + * @returns Each publication's mapped packages. + */ +function resolution( + ctx: Context, latest: RuntimeResolution, replace: () => void = () => {}, + published = table('/packages/addon', 'gone'), +) { + const source = { installAnchor: '', home: '', profileDir: undefined } + let current: RuntimeResolution = new ProfileRuntimeResolution(source, published) + const compute = vi.spyOn(ProfileRuntimeResolution.prototype, 'computeLatestResolution') + .mockResolvedValue(new ProfileRuntimeResolution(source, latest)) + onTestFinished(() => { compute.mockRestore() }) + const calls: string[] = [] + ctx.provide('pluginPackages', { + // The compatibility preflight finds no package metadata and admits every row. + packageOf: () => undefined, + get resolution() { return current }, + replace(next: RuntimeResolution) { + calls.push(`publish:${next.entries.map(entry => entry.name).join(',')}`) + replace() + current = next + }, + } as Pick as PluginPackages) + return calls +} + +it('stops the rows a generation drops before publishing its resolution, then applies it', async () => { + const f = await fixture() + f.trace.length = 0 + const calls = resolution(f.ctx, table('/packages/addon-2'), () => { f.trace.push('published') }) + f.select(['addon']) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(calls).toEqual(['publish:addon']) + expect(f.trace).toEqual(['stop:other', 'published']) +}) + +it.each(['unchanged', 'changed'] as const)('rejects a publication failure, starting %s plugins it stopped again', async (kind) => { + const f = await fixture() + f.trace.length = 0 + resolution(f.ctx, table('/packages/addon-2'), () => { throw new Error('resolution unreadable') }) + if (kind === 'changed') addon(f.dir, '2') + await expect(f.reconcile()).rejects.toThrow('resolution unreadable') + expect(f.trace).toEqual(kind === 'changed' ? ['stop:1', 'start:2:1:-'] : []) +}) + +it('reports an entry left waiting for a service the replacement no longer provides as a warning', async () => { + const f = await fixture(['addon', 'other'], async (_home, dir) => { + addon(dir, '1', `export function apply(ctx) { + ctx.get('reloadTrace').push('start:1') + ctx.provide('addonService', {}) +} +`) + file(join(dir, 'node_modules', 'other', 'index.mjs'), `export const inject = ['addonService'] +export function apply(ctx) { ctx.get('reloadTrace').push('start:other') } +`) + age(join(dir, 'node_modules')) + }) + quiet(f.ctx) + f.trace.length = 0 + addon(f.dir, '2', "export function apply(ctx) { ctx.get('reloadTrace').push('start:2') }\n") + // The entry starts once a provider appears. + await expect(f.reconcile()).resolves.toMatchObject({ warnings: [expect.stringContaining('addonService')] }) + expect(f.trace).toEqual(['start:2']) +}) + +it('imports a row the update inserts once when its import fails', async () => { + const f = await fixture(['addon']) + const error = vi.spyOn(f.ctx.logger, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + file(join(f.dir, 'node_modules', 'other', 'index.mjs'), "import 'missing-lib'\n") + f.select(['addon', 'other']) + await expect(f.reconcile()).rejects.toThrow(/missing-lib/u) + expect(error.mock.calls.filter(([value]) => String(value).includes('missing-lib'))).toHaveLength(1) +}) + +it('keeps the publication failure when starting the stopped plugins again throws', async () => { + const f = await fixture() + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + resolution(f.ctx, table('/packages/addon-2'), () => { throw new Error('resolution unreadable') }) + addon(f.dir, '2') + const settle = vi.spyOn(f.ctx.loader, 'await').mockRejectedValueOnce(new Error('loader unavailable')) + onTestFinished(() => { settle.mockRestore() }) + await expect(f.reconcile()).rejects.toThrow('resolution unreadable') + expect(warn).toHaveBeenCalledWith(expect.objectContaining({ message: 'loader unavailable' })) +}) + +it('logs a stopped plugin that does not start again after the publication fails', async () => { + const f = await fixture() + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + resolution(f.ctx, table('/packages/addon-2'), () => { throw new Error('resolution unreadable') }) + addon(f.dir, '2', "export function apply() { throw new Error('addon cannot start') }\n") + quiet(f.ctx) + // An unrelated failed entry is left to the next judgment. + await f.ctx.loader.create({ name: 'late-plugin' }) + await f.ctx.loader.await() + await expect(f.reconcile()).rejects.toThrow('resolution unreadable') + expect(warn).toHaveBeenCalledWith(expect.stringMatching(/^dsh: addon \(addon\): .*addon cannot start/su)) + expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('late-plugin')) +}) + +it('reports a stopped entry that no recomposition started again by its fiber state', async () => { + const f = await fixture() + const url = pathToFileURL(join(f.dir, 'node_modules', 'addon', 'index.mjs')).href + const plugin = f.ctx.loader.unwrapExports(await f.ctx.loader.import(url)) as Plugin + const fibers = [...f.ctx.registry.get(plugin)?.fibers ?? []] + f.ctx.registry.delete(plugin) + await Promise.all(fibers.map(fiber => fiber.await())) + // Applying the same patches leaves the unchanged Include's rows alone. + const warnings = await f.ctx.hmr.runExclusive(() => reconcileProfilePatches(f.ctx.root, readProfilePatches('test', f.profile), 'test')) + expect(warnings).toEqual([expect.stringMatching(/^addon \(addon\): fiber state 4/u)]) +}) + +it('logs a failure to restore the stopped rows and still reports the rejected publication', async () => { + const f = await fixture() + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + resolution(f.ctx, table('/packages/addon-2'), () => { throw new ResolutionRestartRequired('installation mapping changed') }) + const include = [...f.ctx.loader.entries()].find(entry => entry.options.id === 'include') as Entry + const restoring = vi.spyOn(include.subgroup!, 'create').mockRejectedValueOnce(new Error('restore failed')) + onTestFinished(() => { restoring.mockRestore() }) + f.select(['addon']) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [], restartReason: 'package-moved' }) + expect(warn).toHaveBeenCalledWith(expect.objectContaining({ message: 'restore failed' })) +}) + +it('restores the composition while the resolution waits for a restart', async () => { + const f = await fixture() + f.trace.length = 0 + resolution(f.ctx, table('/packages/addon-2'), () => { throw new ResolutionRestartRequired('installation mapping changed') }) + f.select(['addon']) + const config = readFileSync(join(f.dir, 'cordis.yml'), 'utf8') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [], restartReason: 'package-moved' }) + // The row the generation drops stops before the publication and starts again once it is rejected. + expect(f.trace).toEqual(['stop:other', 'start:other']) + // Stopping and restoring rows leaves the profile's configuration file as it was. + await new Promise(resolve => setTimeout(resolve, 50)) + expect(readFileSync(join(f.dir, 'cordis.yml'), 'utf8')).toBe(config) +}) + +it('waits for a dropped row to finish disposing, and keeps a stopped kept row stopped, until the resolution publishes', async () => { + const f = await fixture(['addon', 'other'], async (_home, dir) => { + file(join(dir, 'node_modules', 'other', 'index.mjs'), `export function apply(ctx) { + ctx.get('reloadTrace').push('start:other') + ctx.effect(() => async () => { await new Promise(resolve => setTimeout(resolve, 20)); ctx.get('reloadTrace').push('stop:other') }) +} +`) + }) + f.trace.length = 0 + // The addon's own file changed, so HMR stops its entry before the recomposition. + addon(f.dir, '2') + resolution(f.ctx, table('/packages/addon-2'), () => { f.trace.push('published') }) + f.select(['addon']) + await f.reconcile() + expect(f.trace).toEqual(['stop:1', 'stop:other', 'published', 'start:2:1:-']) +}) + +it('puts several dropped rows back at their places when the resolution waits for a restart', async () => { + const f = await fixture() + const rows = [{ id: 'timer', name: 'cordis:timer' }, { id: 'hmr', name: 'cordis:hmr', config: { root: [] } }] + const order = ['first', 'middle', 'second'] + writeFileSync(f.profile.patchPath, JSON.stringify([{ insert: [...rows, { id: 'first', name: 'other' }, { id: 'middle', name: 'other' }, { id: 'second', name: 'other' }] }])) + await f.reconcile() + resolution(f.ctx, table('/packages/addon-2'), () => { throw new ResolutionRestartRequired('installation mapping changed') }) + writeFileSync(f.profile.patchPath, JSON.stringify([{ insert: [...rows, { id: 'middle', name: 'other' }] }])) + await expect(f.reconcile()).resolves.toMatchObject({ restartReason: 'package-moved' }) + const include = [...f.ctx.loader.entries()].find(entry => entry.options.id === 'include') as Entry + expect(include.subgroup!.data.map(row => row.id).filter(id => order.includes(id))).toEqual(order) +}) + +it('puts a dropped row back into its group when the resolution waits for a restart', async () => { + const f = await fixture() + const rows = [{ id: 'timer', name: 'cordis:timer' }, { id: 'hmr', name: 'cordis:hmr', config: { root: [] } }] + writeFileSync(f.profile.patchPath, JSON.stringify([{ insert: [...rows, { id: 'group', name: 'cordis:group', config: [{ id: 'child', name: 'other' }] }] }])) + await f.reconcile() + f.trace.length = 0 + resolution(f.ctx, table('/packages/addon-2'), () => { throw new ResolutionRestartRequired('installation mapping changed') }) + writeFileSync(f.profile.patchPath, JSON.stringify([{ insert: [...rows, { id: 'group', name: 'cordis:group', config: [] }] }])) + await expect(f.reconcile()).resolves.toMatchObject({ restartReason: 'package-moved' }) + expect(f.trace).toEqual(['stop:other', 'start:other']) + const group = [...f.ctx.loader.entries()].find(entry => entry.options.id === 'group') as Entry + expect(group.subgroup!.data.map(row => row.id)).toEqual(['child']) +}) + +it('removes a disabled row a generation drops without waiting for a fiber', async () => { + const f = await fixture() + const rows = [{ id: 'timer', name: 'cordis:timer' }, { id: 'hmr', name: 'cordis:hmr', config: { root: [] } }] + writeFileSync(f.profile.patchPath, JSON.stringify([{ insert: [...rows, { id: 'idle', name: 'other', disabled: true }] }])) + await f.reconcile() + f.trace.length = 0 + resolution(f.ctx, table('/packages/addon-2'), () => { f.trace.push('published') }) + writeFileSync(f.profile.patchPath, JSON.stringify([{ insert: rows }])) + await f.reconcile() + expect(f.trace).toEqual(['published']) + expect([...f.ctx.loader.entries()].some(entry => entry.options.id === 'idle')).toBe(false) +}) + +it('stops a row a generation drops from a group before publishing its resolution', async () => { + const f = await fixture() + const rows = [{ id: 'timer', name: 'cordis:timer' }, { id: 'hmr', name: 'cordis:hmr', config: { root: [] } }] + writeFileSync(f.profile.patchPath, JSON.stringify([{ insert: [...rows, { id: 'group', name: 'cordis:group', config: [{ id: 'child', name: 'other' }] }] }])) + await f.reconcile() + f.trace.length = 0 + resolution(f.ctx, table('/packages/addon-2'), () => { f.trace.push('published') }) + writeFileSync(f.profile.patchPath, JSON.stringify([{ insert: [...rows, { id: 'group', name: 'cordis:group', config: [] }] }])) + await f.reconcile() + expect(f.trace).toEqual(['stop:other', 'published']) +}) +it.each(['added', 'nested', 'renamed'] as const)('leaves a generation with an %s row unapplied while the resolution waits for a restart', async (kind) => { + const f = await fixture(['addon']) + f.trace.length = 0 + resolution(f.ctx, table('/packages/addon-2'), () => { throw new ResolutionRestartRequired('installation mapping changed') }) + const rows = [{ id: 'timer', name: 'cordis:timer' }, { id: 'hmr', name: 'cordis:hmr', config: { root: [] } }] + if (kind === 'added') f.select(['addon', 'other']) + else { + writeFileSync(f.profile.patchPath, JSON.stringify(kind === 'nested' + ? [{ insert: [...rows, { id: 'group', name: 'cordis:group', config: [{ id: 'child', name: 'other' }] }] }] + : [{ insert: rows }, { id: 'addon', name: 'other' }])) + } + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [], restartReason: 'package-moved' }) + expect(f.trace).toEqual([]) +}) + +it('judges the activation without importing an entry whose import failed before the resolution publishes', async () => { + const f = await fixture([]) + quiet(f.ctx) + const id = await f.ctx.loader.create({ name: 'late-plugin' }) + await f.ctx.loader.await() + await f.reconcile() + const order: string[] = [] + resolution(f.ctx, table('/packages/addon-2'), () => { order.push('publish') }) + const tree = f.ctx.loader.resolve(id).parent.tree + const original = tree.import.bind(tree) + const load = vi.spyOn(tree, 'import').mockImplementation((...args): Promise => { order.push('import'); return original(...args) as Promise }) + onTestFinished(() => { load.mockRestore() }) + await f.reconcile() + // Importing before the resolution publishes could evaluate plugin code against the previous mappings. + expect(order[0]).toBe('publish') + expect(order).toContain('import') +}) + +it('keeps an entry that failed to import before as a warning when it fails with another error', async () => { + const f = await fixture([]) + quiet(f.ctx) + const id = await f.ctx.loader.create({ name: 'late-plugin' }) + await f.ctx.loader.await() + await f.reconcile() + const tree = f.ctx.loader.resolve(id).parent.tree + const load = vi.spyOn(tree, 'import').mockRejectedValue(new Error('another missing dependency')) + onTestFinished(() => { load.mockRestore() }) + const result = await f.reconcile() + expect(result.warnings).toEqual([expect.stringContaining('another missing dependency')]) +}) + +it('records plugins started before application readiness without restarting a recently installed one', async () => { + const f = await fixture(['addon'], undefined, false) + // A plugin installed just now starts after HMR but before the application is ready; writing its files stamps them + // with the file clock, as an installation does. + other(f.dir) + await f.ctx.loader.create({ name: 'other' }) + await f.ctx.loader.await() + f.ready() + f.trace.length = 0 + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual([]) +}) + +// The recomposition that disables the failed entry still retries it, which expires the profile's package +// configuration and evicts its failed modules, so enabling it later reads the installed dependency. +it('loads a failed entry enabled again after its dependency was installed', async () => { + const f = await fixture(undefined, async (_home, dir) => { + addon(dir, '1', plugin('1', 'late-lib')) + }) + quiet(f.ctx) + const rows = [{ id: 'timer', name: 'cordis:timer' }, { id: 'hmr', name: 'cordis:hmr', config: { root: [] } }] + writeFileSync(f.profile.patchPath, JSON.stringify([{ insert: rows }, { id: 'addon', disabled: true }])) + await f.reconcile() + file(join(f.dir, 'node_modules', 'late-lib', 'package.json'), JSON.stringify({ name: 'late-lib', type: 'module', exports: './index.mjs' })) + file(join(f.dir, 'node_modules', 'late-lib', 'index.mjs'), 'export const value = 7\n') + writeFileSync(f.profile.patchPath, JSON.stringify([{ insert: rows }])) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toContain('start:1:7:-') +}) + +it('starts a service plugin again once the dependency whose evaluation failed is corrected', async () => { + const f = await fixture(['addon'], async (_home, dir) => { + file(join(dir, 'node_modules', 'addon', 'dep.mjs'), "throw new Error('dep fails')\n") + file(join(dir, 'node_modules', 'addon', 'index.mjs'), `import './dep.mjs' +export default class Addon { + constructor(ctx) { ctx.get('reloadTrace').push('start:service') } +} +`) + }) + quiet(f.ctx) + file(join(f.dir, 'node_modules', 'addon', 'dep.mjs'), 'export {}\n') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['start:service']) +}) + +it.each(['link', 'missing'] as const)('finds the host module graph through a process entry given as a %s path', async (kind) => { + const argv = process.argv + onTestFinished(() => { process.argv = argv }) + const f = await fixture(undefined, async (home, dir) => { + const main = join(dir, 'main.mjs') + file(main, "import './node_modules/shared-lib/index.mjs'\n") + await ModuleLoader.fromInternal()!.import(pathToFileURL(main).href, import.meta.url, {}) + const entry = join(home, 'bin-dsh') + if (kind === 'link') symlinkSync(main, entry) + process.argv = [argv[0]!, entry] + }) + shared(f.dir, 2) + const url = pathToFileURL(join(f.dir, 'node_modules', 'shared-lib', 'index.mjs')).href + await expect(f.reconcile()).resolves.toEqual({ warnings: [], + pending: kind === 'link' ? [{ url, reason: 'host-module' }] : [] }) +}) + +it('leaves a CommonJS plugin registered outside a Loader entry, and its cache, for a restart', async () => { + const f = await fixture([]) + const require = createRequire(import.meta.url) + const root = join(f.dir, 'node_modules', 'cjs-addon') + await f.ctx.plugin(f.ctx.loader.unwrapExports(require(join(root, 'index.cjs'))) as Plugin) + expect(f.trace).toEqual(['start:cjs:1']) + const cached = require.cache[join(root, 'helper.cjs')] + commonjs(f.dir, 2) + const result = await f.reconcile() + expect(result.pending).toContainEqual({ url: pathToFileURL(join(root, 'helper.cjs')).href, reason: 'unmanaged-plugin' }) + expect(require.cache[join(root, 'helper.cjs')]).toBe(cached) + expect(f.trace).toEqual(['start:cjs:1']) +}) + +it('replaces a changed module that a data URL module imports', async () => { + const f = await fixture() + const url = pathToFileURL(join(f.dir, 'node_modules', 'shared-lib', 'index.mjs')).href + await import(`data:text/javascript,import ${JSON.stringify(url)}`) + f.trace.length = 0 + shared(f.dir, 2) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['stop:1', 'start:1:2:-']) +}) + +it('reads no plugin from a CommonJS module that is still loading', async () => { + const f = await fixture() + const require = createRequire(import.meta.url) + const partial = join(f.dir, 'node_modules', 'addon', 'partial.cjs') + file(partial, 'module.exports = {}\n') + // A module whose evaluation has not finished is cached with `loaded: false`. + require.cache[partial] = { exports: { apply() {} }, loaded: false } as NodeJS.Module + onTestFinished(() => { Reflect.deleteProperty(require.cache, partial) }) + f.trace.length = 0 + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual([]) +}) + +it('replaces a module first loaded during a recomposition whose file changed before it settled', async () => { + const f = await fixture(['addon'], async (_home, dir) => { + const root = join(dir, 'node_modules', 'other') + file(join(root, 'dep.mjs'), 'export const value = 1\n') + // The write lands well after the comparison; file clocks can date a write within one tick of it earlier. + file(join(root, 'index.mjs'), `import { writeFileSync } from 'node:fs' +import { setTimeout } from 'node:timers/promises' +import { value } from './dep.mjs' +export async function apply(ctx) { + ctx.get('reloadTrace').push('start:other:' + value) + await setTimeout(50) + writeFileSync(${JSON.stringify(join(root, 'dep.mjs'))}, 'export const value = 2\\n') +} +`) + }) + f.trace.length = 0 + f.select(['addon', 'other']) + await f.reconcile() + expect(f.trace).toEqual(['start:other:1']) + f.trace.length = 0 + await f.reconcile() + expect(f.trace).toEqual(['start:other:2']) +}) + +it('replaces other changed plugins when one changed plugin cannot be replaced', async () => { + const f = await fixture(['other']) + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + const url = pathToFileURL(join(f.dir, 'node_modules', 'addon', 'index.mjs')).href + await f.ctx.plugin(f.ctx.loader.unwrapExports(await f.ctx.loader.import(url)) as Plugin) + f.trace.length = 0 + addon(f.dir, '2') + other(f.dir) + file(join(f.dir, 'node_modules', 'other', 'index.mjs'), `export function apply(ctx) { + ctx.get('reloadTrace').push('start:other:2') +} +`) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [{ url, reason: 'unmanaged-plugin' }] }) + expect(f.trace).toEqual(['stop:other', 'start:other:2']) +}) + +it('starts a replaced entry outside the profile composition once and judges its activation', async () => { + const f = await fixture([]) + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + const id = await f.ctx.loader.create({ name: 'addon' }) + await f.ctx.loader.await() + f.trace.length = 0 + addon(f.dir, '2') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['stop:1', 'start:2:1:-']) + addon(f.dir, '3', "export function apply() { throw new Error('version 3 cannot start') }\n") + await expect(f.reconcile()).rejects.toThrow('version 3 cannot start') + expect(f.ctx.loader.resolve(id).fiber?.state).not.toBe(FiberState.ACTIVE) +}) + +it('reports a replaced entry whose package entry point now fails to import', async () => { + const f = await fixture([]) + const error = vi.spyOn(f.ctx.logger, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + await f.ctx.loader.create({ name: 'addon' }) + await f.ctx.loader.await() + const root = join(f.dir, 'node_modules', 'addon') + addon(f.dir, '2') + file(join(root, 'moved.mjs'), "import 'missing-lib'\n") + file(join(root, 'package.json'), JSON.stringify({ name: 'addon', version: '2', type: 'module', exports: './moved.mjs' })) + await expect(f.reconcile()).rejects.toThrow('did not activate') +}) + +it('does not start the new code of a plugin its new bundle patch disables', async () => { + const f = await fixture() + f.trace.length = 0 + addon(f.dir, '2', plugin('2')) + file(join(f.dir, 'node_modules', 'addon', 'cordis.patch.yml'), '- insert:\n - id: addon\n name: addon\n disabled: true\n') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['stop:1']) +}) + +it('replaces the importers of a changed shared dependency only', async () => { + const f = await fixture() + f.trace.length = 0 + shared(f.dir, 2) + await f.reconcile() + expect(f.trace).toEqual(['stop:1', 'start:1:2:-']) +}) + +it('replaces a plugin of a linked package whose target changed', async () => { + const f = await fixture(['@local/linked']) + expect(f.trace).toEqual(['start:linked:1']) + linked(f.home, f.dir, 2) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['start:linked:1', 'stop:linked', 'start:linked:2']) +}) + +it('stops a plugin whose replacement fails to load and starts its corrected files', async () => { + const f = await fixture() + quiet(f.ctx) + f.trace.length = 0 + addon(f.dir, '2', plugin('2', 'missing-lib')) + await expect(f.reconcile()).rejects.toThrow(/failed to import: .*'missing-lib'/u) + expect(f.trace).toEqual(['stop:1']) + // An unchanged failure is reported without rejecting later recompositions. + await expect(f.reconcile()).resolves.toEqual({ warnings: [expect.stringContaining("'missing-lib'")], pending: [] }) + addon(f.dir, '3') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['stop:1', 'start:3:1:-']) +}) + +it('loads a changed dependency together with the corrected plugin that failed to load', async () => { + const f = await fixture() + quiet(f.ctx) + f.trace.length = 0 + shared(f.dir, 2) + addon(f.dir, '2', plugin('2', 'missing-lib')) + await expect(f.reconcile()).rejects.toThrow('missing-lib') + addon(f.dir, '3') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['stop:1', 'start:3:2:-']) +}) + +it('loads a plugin whose missing dependency was installed after its replacement failed', async () => { + const f = await fixture() + quiet(f.ctx) + f.trace.length = 0 + addon(f.dir, '2', plugin('2', 'late-lib')) + await expect(f.reconcile()).rejects.toThrow('late-lib') + file(join(f.dir, 'node_modules', 'late-lib', 'package.json'), JSON.stringify({ name: 'late-lib', type: 'module', exports: './index.mjs' })) + file(join(f.dir, 'node_modules', 'late-lib', 'index.mjs'), 'export const value = 7\n') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['stop:1', 'start:2:7:-']) +}) + +it('loads a package reinstalled at the same path after removal', async () => { + const f = await fixture() + f.select(['other']) + await f.reconcile() + rmSync(join(f.dir, 'node_modules', 'addon'), { recursive: true }) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + addon(f.dir, '2') + f.select(['addon', 'other']) + f.trace.length = 0 + await f.reconcile() + expect(f.trace).toEqual(['start:2:1:-']) +}) + +it('replaces a CommonJS plugin whose required file changed', async () => { + const f = await fixture(['cjs-addon']) + expect(f.trace).toEqual(['start:cjs:1']) + commonjs(f.dir, 2) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['start:cjs:1', 'stop:cjs', 'start:cjs:2']) +}) + +it('stops a CommonJS plugin whose required file fails and applies its correction', async () => { + const f = await fixture(['cjs-addon']) + quiet(f.ctx) + const helper = join(f.dir, 'node_modules', 'cjs-addon', 'helper.cjs') + file(helper, "throw new Error('broken helper')\n") + await expect(f.reconcile()).rejects.toThrow('broken helper') + expect(f.trace).toEqual(['start:cjs:1', 'stop:cjs']) + commonjs(f.dir, 3) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['start:cjs:1', 'stop:cjs', 'start:cjs:3']) +}) + +it('keeps a module first loaded after the last observation when its file predates it', async () => { + const f = await fixture() + const late = join(f.dir, 'node_modules', 'late', 'index.mjs') + file(late, 'export const loaded = Symbol("late")\nexport function apply() {}\n') + age(join(f.dir, 'node_modules', 'late')) + const url = pathToFileURL(late).href + const first = await f.ctx.loader.import(url) as { loaded: symbol } + // A running plugin keeps its package loaded. + await f.ctx.plugin(f.ctx.loader.unwrapExports(first) as Plugin) + await f.reconcile() + expect((await f.ctx.loader.import(url) as { loaded: symbol }).loaded).toBe(first.loaded) +}) + +it('compares module files on a file system without a native realpath, as a packed worker has', async () => { + const f = await fixture() + const native: unknown = Reflect.get(realpathSync, 'native') + Reflect.deleteProperty(realpathSync, 'native') + onTestFinished(() => { Reflect.set(realpathSync, 'native', native) }) + f.trace.length = 0 + addon(f.dir, '2') + try { + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + } finally { Reflect.set(realpathSync, 'native', native) } + expect(f.trace).toEqual(['stop:1', 'start:2:1:-']) +}) + +it('evicts a package a stopped plugin imported dynamically once the resolution drops its mapping', async () => { + const f = await fixture() + const lazy = join(f.dir, 'node_modules', 'lazy-dep') + file(join(lazy, 'package.json'), JSON.stringify({ name: 'lazy-dep', type: 'module' })) + file(join(lazy, 'index.mjs'), 'export const loaded = Symbol("lazy")\n') + age(lazy) + const url = pathToFileURL(join(realpathSync(lazy), 'index.mjs')).href + const first = await f.ctx.loader.import(url) as { loaded: symbol } + resolution(f.ctx, table('/packages/addon'), () => {}, table('/packages/addon', realpathSync(lazy))) + await f.reconcile() + expect((await f.ctx.loader.import(url) as { loaded: symbol }).loaded).not.toBe(first.loaded) +}) + +it('keeps the modules below a directory that stays mapped inside a dropped one', async () => { + const f = await fixture() + const outer = join(f.dir, 'node_modules', 'outer-lib') + const inner = join(outer, 'node_modules', 'inner-lib') + file(join(outer, 'package.json'), JSON.stringify({ name: 'outer-lib', type: 'module' })) + file(join(outer, 'index.mjs'), 'export const loaded = Symbol("outer")\n') + file(join(inner, 'package.json'), JSON.stringify({ name: 'inner-lib', type: 'module' })) + file(join(inner, 'index.mjs'), 'export const loaded = Symbol("inner")\n') + age(outer) + const outerUrl = pathToFileURL(join(realpathSync(outer), 'index.mjs')).href + const innerUrl = pathToFileURL(join(realpathSync(inner), 'index.mjs')).href + const outerFirst = await f.ctx.loader.import(outerUrl) as { loaded: symbol } + const innerFirst = await f.ctx.loader.import(innerUrl) as { loaded: symbol } + resolution(f.ctx, table('/packages/addon', realpathSync(inner)), () => {}, table('/packages/addon', realpathSync(outer), realpathSync(inner))) + await f.reconcile() + expect((await f.ctx.loader.import(outerUrl) as { loaded: symbol }).loaded).not.toBe(outerFirst.loaded) + expect((await f.ctx.loader.import(innerUrl) as { loaded: symbol }).loaded).toBe(innerFirst.loaded) +}) + +it('keeps the modules of a stopped plugin whose package stays mapped', async () => { + const f = await fixture() + const url = pathToFileURL(join(f.dir, 'node_modules', 'addon', 'index.mjs')).href + const first: unknown = await f.ctx.loader.import(url) + f.select(['other']) + await f.reconcile() + // Only the packages of dropped mappings are evicted; the deselected bundle's unchanged files stay loaded. + expect(await f.ctx.loader.import(url)).toBe(first) +}) + +it('evaluates again a module first loaded after the last observation when its file was written since', async () => { + const f = await fixture() + const late = join(f.dir, 'node_modules', 'late', 'index.mjs') + file(late, 'export const loaded = Symbol("late")\n') + const url = pathToFileURL(late).href + const first = await f.ctx.loader.import(url) as { loaded: symbol } + await f.reconcile() + expect((await f.ctx.loader.import(url) as { loaded: symbol }).loaded).not.toBe(first.loaded) +}) + +it('ignores modules whose loading failed while collecting importers', async () => { + const f = await fixture() + const broken = join(f.dir, 'node_modules', 'broken', 'index.mjs') + file(broken, "import 'missing-lib'\n") + await expect(f.ctx.loader.import(pathToFileURL(broken).href)).rejects.toThrow() + f.trace.length = 0 + shared(f.dir, 2) + await f.reconcile() + expect(f.trace).toEqual(['stop:1', 'start:1:2:-']) +}) + +it('leaves changed modules of the host module graph for a restart', async () => { + const argv = process.argv + onTestFinished(() => { process.argv = argv }) + const f = await fixture(undefined, async (_home, dir) => { + const main = join(dir, 'main.mjs') + file(main, "import './node_modules/shared-lib/index.mjs'\n") + process.argv = [argv[0]!, main] + await ModuleLoader.fromInternal()!.import(pathToFileURL(main).href, import.meta.url, {}) + }) + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + const url = pathToFileURL(join(f.dir, 'node_modules', 'shared-lib', 'index.mjs')).href + f.trace.length = 0 + shared(f.dir, 2) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [{ url, reason: 'host-module' }] }) + expect(f.trace).toEqual([]) +}) + +it('still recomposes when planning the replacement fails', async () => { + const f = await fixture() + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + Reflect.set(f.ctx.hmr, 'hostModules', () => Promise.reject(new Error('graph unavailable'))) + f.trace.length = 0 + shared(f.dir, 2) + f.select(['addon']) + const url = pathToFileURL(join(f.dir, 'node_modules', 'shared-lib', 'index.mjs')).href + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [{ url, reason: 'module-comparison' }] }) + expect(f.trace).toEqual(['stop:other']) + expect(warn).toHaveBeenCalledWith(expect.objectContaining({ message: 'graph unavailable' })) +}) + +it('replaces running plugins before reporting a recomposition failure', async () => { + const f = await fixture() + f.trace.length = 0 + shared(f.dir, 2) + writeFileSync(join(f.dir, 'cordis.patch.yml'), JSON.stringify([{ insert: [ + { id: 'timer', name: 'cordis:timer' }, + { id: 'hmr', name: 'cordis:hmr', config: { root: [] } }, + { id: 'broken', name: './missing.mjs' }, + ] }])) + const error = vi.spyOn(f.ctx.logger, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + await expect(f.ctx.hmr.runExclusive(() => f.ctx.hmr.reconcileProfile(['broken']))).rejects.toThrow('broken') + expect(f.trace).toEqual(['stop:1', 'start:1:2:-']) +}) + +it('reconciles only inside an HMR transaction of a profile application', async () => { + const f = await fixture() + await expect(f.ctx.hmr.reconcileProfile()).rejects.toThrow('must run inside runExclusive') + const ctx = new Context() + ctx.baseUrl = pathToFileURL(f.dir + '/').href + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(Loader) + await ctx.plugin(Timer) + await ctx.plugin(Hmr, { root: [], ignored: [], debounce: 0 }) + await expect(ctx.hmr.runExclusive(() => ctx.hmr.reconcileProfile())).rejects.toThrow('requires profileContext') +}) + +it('replaces changed modules when the process has no entry module', async () => { + const argv = process.argv + process.argv = [] + onTestFinished(() => { process.argv = argv }) + const f = await fixture() + f.trace.length = 0 + shared(f.dir, 2) + await f.reconcile() + expect(f.trace).toEqual(['stop:1', 'start:1:2:-']) +}) + +it('retries a failed replacement of a plugin loaded after the last observation', async () => { + const f = await fixture([]) + quiet(f.ctx) + await f.ctx.loader.create({ name: 'addon' }) + await f.ctx.loader.await() + addon(f.dir, '2', plugin('2', 'missing-lib')) + await expect(f.reconcile()).rejects.toThrow('missing-lib') + addon(f.dir, '3') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['start:1:1:-', 'stop:1', 'start:3:1:-']) +}) + +it('logs the changed modules its own profile watch leaves', async () => { + const argv = process.argv + onTestFinished(() => { process.argv = argv }) + const f = await fixture(undefined, async (_home, dir) => { + const main = join(dir, 'main.mjs') + file(main, "import './node_modules/shared-lib/index.mjs'\n") + process.argv = [argv[0]!, main] + await ModuleLoader.fromInternal()!.import(pathToFileURL(main).href, import.meta.url, {}) + }) + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + shared(f.dir, 2) + await f.editPatch() + const url = pathToFileURL(join(f.dir, 'node_modules', 'shared-lib', 'index.mjs')).href + expect(warn).toHaveBeenCalledWith(expect.stringContaining('keep running their previous code'), [{ url, reason: 'host-module' }]) +}) + +it('reports a required restart when the profile packages cannot be listed', async () => { + const f = await fixture(undefined, async (_home, dir) => { + // A scope entry that is a file makes listing its packages fail. + file(join(dir, 'node_modules', '@broken'), '') + }) + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + f.trace.length = 0 + f.select(['addon']) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [], restartReason: 'module-comparison' }) + expect(f.trace).toEqual(['stop:other']) + expect(warn).toHaveBeenCalledWith(expect.objectContaining({ code: 'ENOTDIR' })) +}) + +it('compares only CommonJS modules when module hooks keep the ES module cache on another thread', async () => { + const f = await fixture(['cjs-addon']) + const internal = ModuleLoader.fromInternal()! + const cache: unknown = Reflect.get(internal, 'loadCache') + Reflect.set(internal, 'loadCache', undefined) + onTestFinished(() => { Reflect.set(internal, 'loadCache', cache) }) + const warn = vi.spyOn(f.ctx.logger, 'warn') + onTestFinished(() => { warn.mockRestore() }) + commonjs(f.dir, 2) + await expect(f.reconcile()).resolves.toMatchObject({ warnings: [] }) + expect(warn).not.toHaveBeenCalled() +}) + +it('reads no module links and ignores source changes with a worker-style loader', async () => { + const f = await fixture() + const internal = ModuleLoader.fromInternal()! + const cache: unknown = Reflect.get(internal, 'loadCache') + Reflect.set(internal, 'loadCache', undefined) + onTestFinished(() => { Reflect.set(internal, 'loadCache', cache) }) + const warn = vi.spyOn(f.ctx.logger, 'warn') + onTestFinished(() => { warn.mockRestore() }) + const changes: string[] = [] + f.ctx.on('hmr/change', (url) => { changes.push(url) }) + const source = join(f.dir, 'node_modules', 'addon', 'index.mjs') + await expect(f.ctx.hmr.getLinked(pathToFileURL(source).href)).resolves.toEqual([]) + for (const watcher of watchers.slice(-1)) watcher.emit('change', source) + await vi.waitFor(() => { expect(changes).toEqual([pathToFileURL(source).href]) }) + expect(warn).not.toHaveBeenCalled() +}) + +it('requests a restart for module replacement without Node-compatible caches', async () => { + const f = await fixture() + const internal = ModuleLoader.fromInternal()! + const esm: unknown = Reflect.get(internal, 'loadCache') + const commonjs: unknown = Reflect.get(NodeModule, '_cache') + Reflect.set(internal, 'loadCache', undefined) + Reflect.set(NodeModule, '_cache', undefined) + onTestFinished(() => { Reflect.set(internal, 'loadCache', esm); Reflect.set(NodeModule, '_cache', commonjs) }) + const warn = vi.spyOn(f.ctx.logger, 'warn') + onTestFinished(() => { warn.mockRestore() }) + f.trace.length = 0 + // Patches remain identical: native imports cannot run while these cache fields are hidden. + shared(f.dir, 2) + const result = await f.reconcile() + Reflect.set(internal, 'loadCache', esm) + Reflect.set(NodeModule, '_cache', commonjs) + expect(result).toEqual({ warnings: [], pending: [], restartReason: 'module-comparison' }) + expect(f.trace).toEqual([]) + expect(warn).not.toHaveBeenCalled() +}) + +it('removes a plugin whose replacement fails to load without reporting the failure', async () => { + const f = await fixture() + addon(f.dir, '2', plugin('2', 'missing-lib')) + f.select(['other']) + f.trace.length = 0 + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['stop:1']) +}) + +it('replaces changed plugins beside CommonJS cache entries that are not Node modules', async () => { + const f = await fixture() + const require = createRequire(import.meta.url) + const planted = join(f.dir, 'planted.cjs') + // Some libraries store plain objects in require.cache to provide a module without loading it. + require.cache[planted] = { exports: {} } as NodeJS.Module + onTestFinished(() => { Reflect.deleteProperty(require.cache, planted) }) + f.trace.length = 0 + addon(f.dir, '2') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['stop:1', 'start:2:1:-']) +}) + +it('imports the corrected files of an entry whose import failed', async () => { + const f = await fixture() + addon(f.dir, '2', plugin('2', 'missing-lib')) + f.select(['other']) + await f.reconcile() + // Selected again, the entry imports the broken files and has no fiber. + // The Loader logs the entry's import failure. + const error = vi.spyOn(f.ctx.logger, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + f.select(['addon', 'other']) + await expect(f.reconcile()).rejects.toThrow(/failed to import: .*missing-lib/u) + f.trace.length = 0 + addon(f.dir, '3') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['start:3:1:-']) +}) + +it('leaves a disabled entry whose import failed until it is enabled', async () => { + const f = await fixture() + addon(f.dir, '2', plugin('2', 'missing-lib')) + f.select(['other']) + await f.reconcile() + // The Loader logs the entry's import failure. + const error = vi.spyOn(f.ctx.logger, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + f.select(['addon', 'other']) + await expect(f.reconcile()).rejects.toThrow('failed to import') + const rows = [{ id: 'timer', name: 'cordis:timer' }, { id: 'hmr', name: 'cordis:hmr', config: { root: [] } }] + writeFileSync(f.profile.patchPath, JSON.stringify([{ insert: rows }, { id: 'addon', disabled: true }])) + await f.reconcile() + f.trace.length = 0 + addon(f.dir, '3') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual([]) + writeFileSync(f.profile.patchPath, JSON.stringify([{ insert: rows }])) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['start:3:1:-']) +}) + + +/** Install a plugin package that records its start. */ +function late(dir: string): void { + const root = join(dir, 'node_modules', 'late-plugin') + file(join(root, 'package.json'), JSON.stringify({ name: 'late-plugin', type: 'module', exports: './index.mjs' })) + file(join(root, 'index.mjs'), "export function apply(ctx) { ctx.get('reloadTrace').push('start:late') }\n") +} + +it('retries a failed import while the profile packages cannot be listed', async () => { + const f = await fixture([]) + quiet(f.ctx) + await f.ctx.loader.create({ name: 'late-plugin' }) + await f.ctx.loader.await() + // A scope entry that is a file makes listing its packages fail. + file(join(f.dir, 'node_modules', '@broken'), '') + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + late(f.dir) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [], restartReason: 'module-comparison' }) + expect(f.trace).toEqual(['start:late']) +}) + +it('starts an entry whose missing dependency was installed after startup', async () => { + const f = await fixture([], async (_home, dir) => { + file(join(dir, 'node_modules', 'needs-late', 'package.json'), JSON.stringify({ name: 'needs-late', type: 'module', exports: './index.mjs' })) + file(join(dir, 'node_modules', 'needs-late', 'index.mjs'), "export { apply } from 'late-plugin'\n") + }) + quiet(f.ctx) + await f.ctx.loader.create({ name: 'needs-late' }) + await f.ctx.loader.await() + await f.reconcile() + late(f.dir) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['start:late']) +}) + +it('imports a failing replacement with a new configuration once', async () => { + const f = await fixture() + const error = vi.spyOn(f.ctx.logger, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + addon(f.dir, '2', plugin('2', 'missing-lib'), 'fast') + await expect(f.reconcile()).rejects.toThrow('missing-lib') + expect(error.mock.calls.filter(([value]) => String(value).includes('missing-lib'))).toHaveLength(1) +}) + +it('reports an entry whose import failed and whose disabling expression throws', async () => { + const f = await fixture([]) + quiet(f.ctx) + const id = await f.ctx.loader.create({ name: 'late-plugin' }) + await f.ctx.loader.await() + Reflect.set(f.ctx.loader.resolve(id).options, 'disabled', { __jsExpr: 'undefined.x' }) + // Recomposition still applies and judges; the unchanged expression failure is reported. + await expect(f.reconcile()).resolves.toEqual({ warnings: [expect.stringContaining('disabled expression failed')], pending: [] }) +}) + +it('leaves a changed plugin that an unchanged plugin registered dynamically for a restart', async () => { + const f = await fixture(['other'], async (_home, dir) => { + const root = join(dir, 'node_modules', 'other') + file(join(root, 'child.mjs'), "export function apply(ctx) { ctx.get('reloadTrace').push('start:child:1') }\n") + file(join(root, 'index.mjs'), "const child = await import('./child.mjs')\nexport function apply(ctx) { ctx.plugin(child) }\n") + }) + f.trace.length = 0 + const child = join(f.dir, 'node_modules', 'other', 'child.mjs') + file(child, "export function apply(ctx) { ctx.get('reloadTrace').push('start:child:2') }\n") + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [{ url: pathToFileURL(child).href, reason: 'unmanaged-plugin' }] }) + expect(f.trace).toEqual([]) +}) + +it('recovers from an initial listing failure without replacing unchanged old files', async () => { + const f = await fixture(undefined, async (_home, dir) => { file(join(dir, 'node_modules', '@broken'), '') }) + unlinkSync(join(f.dir, 'node_modules', '@broken')) + f.trace.length = 0 + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual([]) +}) + +it('records freshly mounted plugin files so installing the next bundle does not restart them', async () => { + const f = await fixture([]) + addon(f.dir, '2') + f.select(['addon']) + await f.reconcile() + f.trace.length = 0 + other(f.dir) + f.select(['addon', 'other']) + await f.reconcile() + expect(f.trace).toEqual(['start:other']) +}) + +it('walks Node 22 null-prototype linked arrays', async () => { + const f = await fixture() + const internal = ModuleLoader.fromInternal()! + const url = pathToFileURL(join(f.dir, 'node_modules', 'addon', 'index.mjs')).href + const job = internal.loadCache.get(url)! + const linked = job.linked + const children = Array.from(await linked) + Object.setPrototypeOf(children, null) + Reflect.set(job, 'linked', Promise.resolve(children)) + onTestFinished(() => { Reflect.set(job, 'linked', linked) }) + shared(f.dir, 2) + f.trace.length = 0 + await f.reconcile() + expect(f.trace).toEqual(['stop:1', 'start:1:2:-']) +}) + +it('keeps CommonJS plugins and their caches pending when no ES module jobs are available', async () => { + const f = await fixture(['cjs-addon']) + const internal = ModuleLoader.fromInternal()! + const esm: unknown = Reflect.get(internal, 'loadCache') + const require = createRequire(import.meta.url) + const helper = join(f.dir, 'node_modules', 'cjs-addon', 'helper.cjs') + const cached = require.cache[helper] + file(helper, 'exports.value = 2\n') + Reflect.set(internal, 'loadCache', undefined) + onTestFinished(() => { Reflect.set(internal, 'loadCache', esm) }) + try { + const expected = { warnings: [], restartReason: 'module-comparison', + pending: [{ url: pathToFileURL(helper).href, reason: 'module-comparison' }] } + await expect(f.reconcile()).resolves.toEqual(expected) + await expect(f.reconcile()).resolves.toEqual(expected) + expect(require.cache[helper]).toBe(cached) + expect(f.trace).toEqual(['start:cjs:1']) + } finally { Reflect.set(internal, 'loadCache', esm) } +}) + +it.each(['disabled', 'removed', 'incompatible', 'dynamic'] as const)('never evaluates the replacement of a %s row', async (kind) => { + const f = await fixture() + const marker = join(f.home, 'evaluated') + addon(f.dir, '2', `import { writeFileSync } from 'node:fs'; writeFileSync(${JSON.stringify(marker)}, 'yes');\n` + plugin('2')) + if (kind === 'incompatible') { + const path = join(f.dir, 'node_modules', 'addon', 'package.json') + file(path, JSON.stringify({ name: 'addon', version: '2.0.0', type: 'module', exports: './index.mjs', + peerDependencies: { '@deepseek-ai/dsh': '<0.0.0' }, dsh: { bundle: { patch: './cordis.patch.yml' } } })) + } else if (kind === 'removed') { + f.select(['other']) + } else { + file(join(f.dir, 'node_modules', 'addon', 'cordis.patch.yml'), + `- insert:\n - id: addon\n name: addon\n disabled: ${kind === 'dynamic' ? '!!js "true"' : 'true'}\n`) + } + f.trace.length = 0 + await f.reconcile() + expect(existsSync(marker)).toBe(false) + expect(f.trace).toEqual(['stop:1']) + addon(f.dir, '3') + f.select(['addon', 'other']) + await f.reconcile() + expect(f.trace).toContain('start:3:1:-') +}) + +it('restarts both CommonJS requirers of a changed shared child', async () => { + const f = await fixture(['cjs-addon'], async (_home, dir) => { + const root = join(dir, 'node_modules', 'other') + file(join(root, 'package.json'), JSON.stringify({ name: 'other', version: '1.0.0', main: './index.cjs', + dsh: { bundle: { patch: './cordis.patch.yml' } } })) + file(join(root, 'index.cjs'), `const helper = require('../cjs-addon/helper.cjs') +exports.apply = ctx => { + ctx.get('reloadTrace').push('start:second:' + helper.value) + ctx.effect(() => () => ctx.get('reloadTrace').push('stop:second')) +} +`) + }) + f.select(['cjs-addon', 'other']) + await f.reconcile() + f.trace.length = 0 + file(join(f.dir, 'node_modules', 'cjs-addon', 'helper.cjs'), 'exports.value = 2\n') + await f.reconcile() + expect(f.trace.toSorted()).toEqual(['start:cjs:2', 'start:second:2', 'stop:cjs', 'stop:second']) +}) + + +it('replaces a row whose disabling is an expression', async () => { + const f = await fixture(undefined, async (_home, dir) => { + file(join(dir, 'node_modules', 'addon', 'cordis.patch.yml'), + '- insert:\n - id: addon\n name: addon\n disabled: !!js "false"\n') + }) + f.trace.length = 0 + shared(f.dir, 2) + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['stop:1', 'start:1:2:-']) +}) + +it('logs a profile-wide restart requirement from its watch when caches are unavailable', async () => { + const f = await fixture() + const internal = ModuleLoader.fromInternal()! + const esm: unknown = Reflect.get(internal, 'loadCache') + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore(); Reflect.set(internal, 'loadCache', esm) }) + Reflect.set(internal, 'loadCache', undefined) + try { + await f.editPatch() + expect(warn).toHaveBeenCalledWith('restart required: %s', 'module-comparison') + } finally { Reflect.set(internal, 'loadCache', esm) } +}) + + +it.each(['group', 'include'] as const)('replaces the children of a nested %s', async (kind) => { + const f = await fixture(['addon'], async (_home, dir) => { + const config = join(dir, 'nested.yml') + file(config, '- id: child\n name: addon\n') + file(join(dir, 'node_modules', 'addon', 'cordis.patch.yml'), JSON.stringify([{ insert: [kind === 'group' + ? { id: 'nested', name: 'cordis:group', config: [{ id: 'child', name: 'addon' }] } + : { id: 'nested', name: 'cordis:include', config: { path: pathToFileURL(config).href } }] }])) + }) + f.trace.length = 0 + addon(f.dir, '2') + await expect(f.reconcile()).resolves.toEqual({ warnings: [], pending: [] }) + expect(f.trace).toEqual(['stop:1', 'start:2:1:-']) +}) diff --git a/packages/boot/hmr/tests/watch-config.spec.ts b/packages/boot/hmr/tests/watch-config.spec.ts index 7d0caf035b..e187d20a07 100644 --- a/packages/boot/hmr/tests/watch-config.spec.ts +++ b/packages/boot/hmr/tests/watch-config.spec.ts @@ -10,10 +10,13 @@ import { watchConfig } from '../src/watch-config.ts' import Hmr from '../src/index.ts' import Loader from '@deepseek-ai/cordis-plugin-loader' import Timer from '@deepseek-ai/cordis-plugin-timer' +import { writeFileAtomic } from '@deepseek-ai/dsh-atomic-write' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { FSWatcher, type ChokidarOptions } from 'chokidar' -const configWatch = vi.hoisted(() => ({ create: undefined as ((options?: ChokidarOptions) => FSWatcher) | undefined })) +const configWatch = vi.hoisted(() => ({ + create: undefined as ((paths: string | string[], options?: ChokidarOptions) => FSWatcher) | undefined, +})) vi.mock('node:fs', async (importOriginal) => { const native = await importOriginal() return { ...native, realpathSync: vi.fn(native.realpathSync) } @@ -25,7 +28,7 @@ vi.mock('node:fs/promises', async (importOriginal) => { vi.mock('chokidar', async (importOriginal) => { const native = await importOriginal() return { ...native, watch: (paths: string | string[], options?: ChokidarOptions) => - configWatch.create === undefined ? native.watch(paths, options) : configWatch.create(options) } + configWatch.create === undefined ? native.watch(paths, options) : configWatch.create(paths, options) } }) /** Every per-test tree root, removed once the booted watcher has been disposed. */ @@ -80,6 +83,42 @@ describe('HMR exact config paths', () => { for (const root of hmrRoots.splice(0)) rmSync(root, { recursive: true, force: true }) }) + it.for([false, true])('excludes siblings while observing config replacement through an alias (missing parents: %s)', async (missingParents, test) => { + const root = mkdtempSync(join(tmpdir(), 'dsh-hmr-config-scope-')) + onTestFinished(() => { rmSync(root, { recursive: true, force: true }) }) + const target = join(root, 'target') + const dir = join(root, 'alias') + mkdirSync(target) + symlinkSync(target, dir, process.platform === 'win32' ? 'junction' : 'dir') + const filename = join(dir, ...(missingParents ? ['later', 'nested'] : []), 'package.json') + writeFileSync(join(dir, 'package.json.lock'), 'held') + mkdirSync(join(dir, 'unrelated')) + writeFileSync(join(dir, 'unrelated', 'config.yml'), 'ignored') + if (!missingParents) writeFileSync(filename, 'initial') + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + let watcher!: FSWatcher + const previousFactory = configWatch.create + onTestFinished(() => { configWatch.create = previousFactory }) + configWatch.create = (paths, options) => { + watcher = new FSWatcher(options) + return watcher.add(paths) + } + const observed: string[] = [] + await watchConfig(ctx, filename, {}, () => { observed.push(readFileSync(filename, 'utf8')) }) + const watchedEntries = () => Object.values(watcher.getWatched()).flat() + expect(watchedEntries()).not.toContain('package.json.lock') + expect(watchedEntries()).not.toContain('unrelated') + ensureNativeWatchLive(dir) + await writeFileAtomic(filename, 'created', { mode: 0o600 }) + await eventually(() => observed.includes('created'), 'created config was not observed', test.task.timeout) + await writeFileAtomic(filename, 'replaced', { mode: 0o600 }) + await eventually(() => observed.includes('replaced'), 'replaced config was not observed', test.task.timeout) + expect(watchedEntries()).toContain('package.json') + expect(watchedEntries()).not.toContain('package.json.lock') + expect(watchedEntries()).not.toContain('unrelated') + }) + it.each(['relative', 'absolute'])('observes %s module roots through a filesystem alias', { timeout: 30_000 }, async (rootKind) => { const target = mkdtempSync(join(tmpdir(), 'dsh-hmr-module-canonical-')) const alias = `${target}-alias` @@ -252,7 +291,7 @@ describe('HMR exact config paths', () => { let watcher!: FSWatcher const previousFactory = configWatch.create onTestFinished(() => { configWatch.create = previousFactory }) - configWatch.create = (options) => { + configWatch.create = (_paths, options) => { watcher = new FSWatcher(options) // Use Chokidar's real normalization with deterministic event delivery. Reflect.set(watcher, '_readyEmitted', true) diff --git a/packages/boot/plugin-manager/README.i18n.yaml b/packages/boot/plugin-manager/README.i18n.yaml index 7a2bca2062..9cb4ec1a9f 100644 --- a/packages/boot/plugin-manager/README.i18n.yaml +++ b/packages/boot/plugin-manager/README.i18n.yaml @@ -15,8 +15,8 @@ en: 87679c51aa3693f5 zh: 11684a48a5806afb /deepseek-ai-dsh-plugin-manager/use-this-package: - en: af5bf0a205b5a2a1 - zh: 0114039816454a1a + en: 95c1b18f8432090a + zh: 213e54a1547a1da1 /deepseek-ai-dsh-plugin-manager/use-this-package/version-compatibility-and-exemptions: en: 920c0acb3b9feaf3 zh: ba6e832a256880a7 @@ -24,8 +24,8 @@ en: d5643a06f300c30a zh: 9348b6a7676a2849 /deepseek-ai-dsh-plugin-manager/understand-the-implementation: - en: 7b54d30e231bb325 - zh: 08df9441fed9927f + en: 495dadf79c48c43c + zh: 9884dd04a5bb49dc /deepseek-ai-dsh-plugin-manager/further-exploration: en: c6538243d8702a0d zh: 04a82d923353c75f @@ -36,8 +36,8 @@ en: 1815ec6ce56c80d4 zh: 2d7ac75d3b25eb6b /deepseek-ai-dsh-plugin-manager/model-experience/management-tool/what-the-model-sees: - en: 72d6c70869b12f22 - zh: 45218d6f1e765fb1 + en: b1dae91f98350290 + zh: 802ae86d923ac6ce /deepseek-ai-dsh-plugin-manager/model-experience/management-tool/token-effect: en: bc70208bd361dbcd zh: bb651d6066066c6c @@ -45,11 +45,11 @@ en: c29f60be7f3edc1a zh: d9b9388b96ef95cc /deepseek-ai-dsh-plugin-manager/known-limitations-and-deferred-work: - en: 7d7ea29063e358ca - zh: e3399db77a97f62a + en: 6b93fd9851b79a0e + zh: d2cf1982e8cfc718 /deepseek-ai-dsh-plugin-manager/known-limitations-and-deferred-work/failure-behavior: - en: 4447e4df8d62b274 - zh: c76443e2edb97b1d + en: c670eb2330b441e8 + zh: 2c8223e03e1e3ef0 /deepseek-ai-dsh-plugin-manager/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/boot/plugin-manager/README.md b/packages/boot/plugin-manager/README.md index 6763a7a9f8..0c36040de2 100644 --- a/packages/boot/plugin-manager/README.md +++ b/packages/boot/plugin-manager/README.md @@ -37,12 +37,10 @@ For a deployment without agent presets, enable the tool in the profile patch. Pr disabled: false ``` -A plugin toggle updates only `disabled` in the last matching override in the profile's `cordis.patch.yml`, or appends an override when none matches. Matching uses the entry id and any module-name assertion. A bundle toggle changes `package.json`'s ordered `dsh.profile.bundles` list. Disabling retains the dependency; enabling appends the bundle at the end, which can change configuration precedence. Installation enables a new bundle by default. Home and invocation patches retain their higher priority. +A plugin toggle updates only `disabled` in the last matching override in the profile's `cordis.patch.yml`, or appends an override when none matches. Matching uses the entry id and any module-name assertion. An override holding only `id` and `disabled` is removed, and none is appended, when the bundle layers and the remaining profile patches already give the entry the requested state, so the profile patch records only departures from the bundles. Home and invocation patches are left out of that comparison; they apply after the profile patch and do not decide what it records. A bundle toggle changes `package.json`'s ordered `dsh.profile.bundles` list. Disabling retains the dependency; enabling appends the bundle at the end, which can change configuration precedence. Installation enables a new bundle by default. Home and invocation patches retain their higher priority. A selected bundle that cannot load remains in `listBundles` with an `error`; `enabled` records the saved selection, not successful loading. The plugin page shows the error and allows deselection. A broken bundle cannot be enabled. Management bundles remain protected if their files become unreadable. -Scoped bundle rows carry both their declared `rowId` and outer `preset` target. The manager reads declarations without composing the bundle alone, so rows remain visible while Off. Their optional `composition` state comes from the current preset inventory; they have no editable root `entryId`, and their `preset-managed` read-only reason directs configuration to the preset or bundle. Enabling audits every affected preset using its registered declaring row, including failures the registry retained instead of throwing; unrelated unchanged preset failures become warnings. Bundle toggles validate the saved composition even without HMR; composition failures keep the saved selection and return a diagnostic immediately. Remove refuses while a current or retained preset generation uses a contributed row, matched by defining preset row, child row ID, and resolved module, or any module belonging to the bundle package itself. This protection lasts after Off until those generations release the modules; unrelated rows using a shared dependency do not prevent removal. Anonymous scoped insertions receive the same protection. Missing module files do not make a different contribution match; identical retained declarations remain protected when their files are unavailable. - `listBundles` includes optional display `meta` for each bundle and its declared plugin rows, including disabled bundles. The Client selects a language from these values. The separate `description` field is the bundle's raw `package.json.description`; a metadata diagnostic does not block management. `source` gives a profile dependency as a spec `pnpm add` accepts: a git address or URL as recorded without the user information of an http(s) URL (a query string stays as recorded), a `file:` or `link:` path made absolute against the profile or the home directory for `~`, and a registry range, tag, or alias after the package name, as is any spec of a package installed under another name; a bundle the installation supplies has none, even when the profile also depends on it, because the installation's copy is the one that loads. The `plugin_manager` tool omits UI display metadata from list results. `listBundles` marks shipped optional bundles and on-demand catalog entries as `official`, independently of package installation. `availability` identifies a readable installation-provided or profile package, or `missing`; on-demand catalog entries exclude undeclared transitive copies. `installed` only records whether the profile declares the dependency. An absent on-demand entry carries embedded localized metadata and a host-derived `installTarget` containing the running DSH version and install spec, without registry access. Profile-declared packages with unreadable files retain their declaration and expose the normal error. @@ -51,7 +49,7 @@ Scoped bundle rows carry both their declared `rowId` and outer `preset` target. Published installations offer `package@`. Source Web and development Desktop offer `link:` from the running CLI installation, including its development symlink. Package names resolve through workspace manifests; current working directory and prerelease suffixes do not select a checkout. Missing packages, bundle patches, or built entry points produce a diagnostic without registry fallback. Prepare the checkout with `pnpm install` and `pnpm run build`. Linked packages use that checkout’s dependencies and peers; rebuilding and restarting remain necessary after code changes. A registry copy or another checkout’s link can need replacement even when its version matches. -Official on-demand installs and explicit updates call the same `installBundle` operation as other bundles. Registry targets use `saveExact: true`; development targets retain the ordinary `link:` dependency. Updates pass the current `enabled` selection; replacing an existing dependency reports `restart-required`. Turning Off only deselects the layer, and Remove uses the existing removal checks. Installation failure restores the profile manifest and lockfile; activation failure after installation can retain the saved dependency and selection. The existing peer-compatibility check still applies, without an additional Official-only version admission rule. +Official on-demand installs call the same `installBundle` operation as other bundles. Registry targets use `saveExact: true`; development targets retain the ordinary `link:` dependency. An explicit update removes the installed package and installs the target with the current `enabled` selection; without HMR, a bundle that runs since startup cannot be removed, so the installation goes over it and reports `restart-required`. A failed or cancelled installation after the removal leaves the package uninstalled, and the reinstalled bundle joins the end of the selection. Turning Off only deselects the layer, and Remove uses the existing removal checks. Installation failure restores the profile manifest and lockfile; activation failure after installation can retain the saved dependency and selection. The existing peer-compatibility check still applies, without an additional Official-only version admission rule. `installBundle` checks GitHub repositories with `git ls-remote` before starting pnpm, using the profile directory and the installer's Git and proxy configuration. `githubConnectionTimeoutMs` defaults to 5000 ms and limits only this check, not package download or builds. The check disables credential helpers and prompts; only network failures and timeouts stop installation, reporting `failedAt: 'spec-host'` with the existing failure kind and diagnostic log. Authentication, repository lookup and other failures are left to pnpm, including its HTTPS-to-SSH fallback. Cancellation and manager disposal stop the check and its descendants. Registry packages, paths, tarballs and other Git hosts skip this check. A reachable repository can still fail during download or bundle validation. @@ -99,9 +97,9 @@ The CLI exposes `dsh plugin --profile version-exemptions`, `allow-vers The service and `dsh plugin` share the package operations in [operations.ts](src/operations.ts). The launcher supplies the current profile; [DSH HMR](../hmr/README.md) serializes module reloads, file watching and management writes. Each configuration refresh re-reads bundle selection and patch layers, updates the original root Include, and awaits removed plugin resources as well as the remaining Loader tree. CLI and service operations share the profile manifest writer lock to prevent concurrent package and manifest writes. HMR does not acquire that lock. Pnpm runs outside the HMR queue; installation selects the bundle after pnpm succeeds, while removal deselects and unloads the bundle before pnpm runs. -Installing a new package, enabling a bundle, disabling it with HMR after its plugins stop, and a successful removal publish the profile's runtime resolution. Shared dependencies may pass to another bundle's declaration when their normalized directory, version, and scope stay unchanged. Without HMR, a deselected startup bundle still runs: while any such bundle is absent from the saved selection, subsequent package operations retain the entire current table and report `restart-required`. Other new installations and removals of non-running bundles can still publish without HMR; activation waits for restart. Overwriting an installed package publishes nothing and reports `restart-required` ([decision](../../../.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.md)). +Without HMR, installing a new package, enabling a bundle and a successful removal publish the profile's runtime resolution; with HMR, every operation leaves publication to [HMR](../hmr/README.md)'s recomposition, which removes dropped mappings after their plugins stop. Shared dependencies may pass to another bundle's declaration when their normalized directory and scope stay unchanged. Without HMR, a deselected startup bundle still runs: while any such bundle is absent from the saved selection, subsequent package operations retain the entire current table and report `restart-required`. Other new installations and removals of non-running bundles can still publish without HMR; activation waits for restart. With HMR, `installBundle()` refuses a package that is already installed with `already-installed`, before pnpm runs, when the spec names it: a registry name, a local directory, or the git or tarball spec its dependency was saved with. A package that cannot be removed, such as a bundle carrying plugin management, therefore cannot be installed over with HMR. Installing another version is a removal and an installation, so the previous version's plugins stop, its modules are evicted and its mappings removed before the new one is installed; the Web page's Update for an Official plugin does both. A git or tarball spec whose package is known only after pnpm ran can still install over an installed package: without HMR it reports `restart-required`, and with HMR the recomposition replaces the running plugins whose loaded files changed. A replacement that fails to import or start reports `failed` with the activation diagnostic, which names the import error; the previous version no longer runs, and every later operation imports it again, so it starts once its files or dependencies are corrected. An unchanged import failure is a warning of later operations; a changed one fails them. A publication the runtime resolution rejects, because an installed package now resolves to another directory or a mapping of the DSH installation changed, leaves the composition as it was, after stopping and starting again the rows it would drop, and reports `restart-required` with `package-moved`. Disabling or removing a bundle evicts the modules of the packages whose mappings it drops. Every `restart-required` result carries `restartReason`: `no-hmr`, `package-moved`, or the [HMR pending reason](../hmr/README.md) of a changed module that loads only after a restart, unless the operation reports `overridden` ([decision](../../../.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.md)). -A service run whose captured output stays silent for `idleTimeoutMs` is terminated, reports `timedOut` alongside its exit status, is classified `timeout` whatever status the signal left behind, and is not retried on the next registry, which bounds how long one operation can hold the profile lock; the CLI inherits the terminal, captures no output, and stays unbounded for its operator to interrupt. A run completes when its process exits, and the pipes then drain under a bounded grace period, so a descendant that inherited them cannot hold the operation open. A terminated run stops its whole process tree and waits for it, because a lifecycle script outlives the pnpm process that started it (issue #4981). Each operation records the pnpm run it starts in `.plugin-manager/run.json` and removes the record when the run ends. A lock whose holder process exited is taken over by the next writer, but that process's pnpm tree can still be running, so an operation that finds a record waits up to five seconds for the recorded run to stop and otherwise fails with a diagnostic that names the process and the record, without running pnpm. Dependency-only changes do not trigger configuration reloads. +A service run whose captured output stays silent for `idleTimeoutMs` is terminated, reports `timedOut` alongside its exit status, is classified `timeout` whatever status the signal left behind, and is not retried on the next registry, which bounds how long one operation can hold the profile lock; the CLI inherits the terminal, captures no output, and stays unbounded for its operator to interrupt. A run completes when its process exits, and the pipes then drain under a bounded grace period, so a descendant that inherited them cannot hold the operation open. The diagnostic file is closed before the call settles, including preparation or spawn failures. A terminated run stops its whole process tree and waits for it, because a lifecycle script outlives the pnpm process that started it (issue #4981). Each operation records the pnpm run it starts in `.plugin-manager/run.json` and removes the record when the run ends. A lock whose holder process exited is taken over by the next writer, but that process's pnpm tree can still be running, so an operation that finds a record waits up to five seconds for the recorded run to stop and otherwise fails with a diagnostic that names the process and the record, without running pnpm. Dependency-only changes do not trigger configuration reloads. Results contain the last attempted stage, target, saved-state change, application status and error codes. Web dictionaries render management text; pnpm and Loader diagnostics remain unmodified. Unrelated pre-existing inactive entries return warnings; new or changed failures and inactive explicit enablement targets fail the operation. A failed or cancelled package run, or failed bundle validation, restores the manifest and lockfile snapshotted before pnpm ran ([rationale](../../../.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.md)); later failures retain saved changes as described in [Failure behavior](#failure-behavior). Installations are tracked by request id until their call settles, so a cancellation names one run and joins its settlement without taking the profile lock. The CLI inherits authentication variables and terminal descriptors; service operations use a scrubbed environment and captured output. @@ -124,7 +122,7 @@ Results contain the last attempted stage, target, saved-state change, applicatio #### What the model sees -The [`plugin_manager` tool](../../../docs/tool-catalog.md#deepseek-aidsh-plugin-manager) lists plugin entries and bundles and performs profile-wide changes. Its results include saved-state changes, application status and package diagnostics. Management operations do not inject messages into Agents. +The [`plugin_manager` tool](../../../docs/tool-catalog.md#deepseek-aidsh-plugin-manager) lists plugin entries and bundles and performs profile-wide changes. Its results include saved-state changes, application status and package diagnostics. A change result that is not plainly applied adds `nextStep`, a sentence derived from its application status, refusal code, package-manager failure kind or restart reason that says what the model does next or tells the user. Management operations do not inject messages into Agents. #### Token effect @@ -139,9 +137,10 @@ Tool results append to the transcript. Enabling or disabling other tools can cha - Web approves the entire displayed pending group; it has no per-package selection. -- Package replacements require restarting the process to load a fresh JavaScript module generation. +- pnpm verifies every lockfile tarball URL against its default registry when a command changes the lockfile. After a package was installed from another registry, installing a different package with the default registry, or removing that package after a restart, can fail with `ERR_PNPM_TARBALL_URL_MISMATCH`. +- Package replacements require restarting the process without HMR. A package relinked outside Plugin Manager while it is still installed waits for a restart. - Startup-only profiles cannot remove packages used to start the current process; stop it and use `dsh plugin`. -- The manager cannot disable its own management components, change another profile, or directly edit individual rows inside an agent preset. +- The manager cannot disable its own management components, change another profile, or edit an agent preset's composition. - A failed removal may leave dependencies partially changed, and a failed or cancelled installation can leave downloaded files under `node_modules` or the pnpm store. Inactive dependencies with missing files remain removable. Diagnostic logs remain under the profile's `.plugin-manager/logs` directory. - Management results describe Host activation. Browser synchronization failures appear separately in the Settings plugin list. - Desktop package operations remain owned by the Desktop shell. @@ -158,7 +157,7 @@ Failures preserve completed steps and report the actual remaining state. Profile | Resolution publication after a successful package operation fails | Keep completed disk changes and the previous runtime table. Report `application: 'failed'` with the publication diagnostic; pnpm's zero exit code does not mean publication succeeded. | | Remove: any step fails | Stop at the failed step. Preserve completed changes, retain remaining dependencies for retry, and report removal failure. Do not re-enable the bundle. | -Installation finishes after pnpm and bundle validation succeed; subsequent publication or enablement failure does not undo installation. Removal proceeds in order: remove the bundle from `dsh.profile.bundles`, unload its runtime contributions, run `pnpm remove`, then publish runtime resolution unless a deselected startup bundle still runs without HMR. A failed step prevents subsequent steps; publication failure after removal does not restore deleted packages. A selected name that neither the profile's dependencies nor the installation holds, such as a retired bundle, is also removable; its removal stops after deselection and runs no pnpm. +Installation finishes after pnpm and bundle validation succeed; subsequent publication or enablement failure does not undo installation. Removal proceeds in order: remove the bundle from `dsh.profile.bundles`, unload its runtime contributions, run `pnpm remove`, then publish runtime resolution unless a deselected startup bundle still runs without HMR. `pnpm remove` runs with the registry this manager last installed the package from in the running process, because pnpm verifies lockfile tarball URLs against its default registry; a package installed before the process started is removed with the registry an installation asks first. A failed step prevents subsequent steps; publication failure after removal does not restore deleted packages. A selected name that neither the profile's dependencies nor the installation holds, such as a retired bundle, is also removable; its removal stops after deselection and runs no pnpm. Restoration rewrites only the two snapshotted files; user-authored patch configuration, application data, diagnostic logs and files pnpm downloaded remain untouched, and the next package operation prunes packages no manifest references. diff --git a/packages/boot/plugin-manager/README.zh.md b/packages/boot/plugin-manager/README.zh.md index ba365135f2..d5211beaa5 100644 --- a/packages/boot/plugin-manager/README.zh.md +++ b/packages/boot/plugin-manager/README.zh.md @@ -28,7 +28,7 @@ kind: "package-reference" ## 使用本包 -基于 base 的 profile 提供管理服务。在 Web 中,侧边栏的**插件**页([ui-plugin-manager](../../client/ui-plugin-manager/README.zh.md))管理 profile 的组合包及其能唯一定位的行;设置页的插件列表保持只读。Agent 预设条目保持只读。`plugin_manager` 工具提供相同操作,在 Creator 模式中启用。其他预设仍默认禁用。 每个工具操作都要求 `danger-full-access` 或本次调用的批准。在较低沙箱模式下,`ask` 会请求审批;`never`、拒绝、取消或审批渠道不可用时均不执行。批准不改变会话的权限模式。profile 变更跨会话持久化,已安装的 Host 代码在宿主进程内运行,不受工作区沙箱限制。依赖构建脚本仍需单独批准。 +基于 base 的 profile 提供管理服务。在 Web 中,侧边栏的**插件**页([ui-plugin-manager](../../client/ui-plugin-manager/README.zh.md))管理 profile 的组合包及其能唯一定位的行;设置页的插件列表保持只读。Agent 预设条目保持只读。`plugin_manager` 工具提供相同操作,在 Creator 模式中启用。其他预设仍默认禁用。每个工具操作都要求 `danger-full-access` 或本次调用的批准。在较低沙箱模式下,`ask` 会请求审批;`never`、拒绝、取消或审批渠道不可用时均不执行。批准不改变会话的权限模式。profile 变更跨会话持久化,已安装的 Host 代码在宿主进程内运行,不受工作区沙箱限制。依赖构建脚本仍需单独批准。 未使用 Agent 预设的部署在 profile patch 中启用工具;使用预设的会话由其预设中的 `tool-plugin-manager` 条目控制。 @@ -37,12 +37,10 @@ kind: "package-reference" disabled: false ``` -插件开关只更新 profile 的 `cordis.patch.yml` 中最后一条匹配覆盖项的 `disabled`;没有匹配项时追加。匹配依据是条目 id,以及覆盖项声明的模块名称。组合包开关修改 `package.json` 的有序 `dsh.profile.bundles` 列表。关闭保留依赖;开启追加到列表末尾,可能改变配置优先级。安装新组合包默认启用。home 和单次启动 patch 保留更高优先级。 +插件开关只更新 profile 的 `cordis.patch.yml` 中最后一条匹配覆盖项的 `disabled`;没有匹配项时追加。匹配依据是条目 id,以及覆盖项声明的模块名称。如果组合包层和其余 profile patch 已使条目处于所请求的状态,仅含 `id` 与 `disabled` 的覆盖项会被移除,也不会追加覆盖项,因此 profile patch 只记录与组合包不同的设置。该比较不计入 home 和单次启动 patch;它们在 profile patch 之后应用,不决定 profile patch 记录什么。组合包开关修改 `package.json` 的有序 `dsh.profile.bundles` 列表。关闭保留依赖;开启追加到列表末尾,可能改变配置优先级。安装新组合包默认启用。home 和单次启动 patch 保留更高优先级。 已选择但无法加载的组合包仍会出现在 `listBundles` 中,并携带 `error`;`enabled` 表示保存的选择,不代表加载成功。插件页面显示错误并允许取消选择。损坏的组合包无法启用。管理组合包的文件变得不可读后仍受保护。 -限定到 preset 的组合包行同时携带声明的 `rowId` 和外层 `preset` 目标。管理器读取声明,不单独组合该 bundle,因此 Off 状态下仍能列出这些行。可选的 `composition` 状态来自当前 preset 清单;这些行没有可编辑的根条目 `entryId`,其 `preset-managed` 只读原因指引用户通过预设或组合包进行配置。启用根据注册的声明行检查所有受影响的 preset,包括注册表保留而未抛出的故障;无关且未变化的 preset 故障作为警告返回。即使没有 HMR,组合包开关也会校验保存后的组合;组合失败会保留已保存的选择并立即返回诊断。当前或被保留的 preset 代仍使用贡献行(按定义 preset 的行、子行 ID 和解析后的模块匹配),或属于组合包自身的任意模块时,Remove 都会拒绝。这项保护在 Off 后仍持续,直到这些代释放模块;无关行使用共享依赖不会阻止移除。匿名作用域插入行受到相同保护。模块文件缺失不会导致另一贡献项被误认为匹配;文件不可用时,相同的保留声明仍受保护。 - `listBundles` 为各组合包及其声明的插件行提供可选的展示 `meta`,包括已禁用的组合包。Client 从这些值中选择语言。单独的 `description` 字段是该组合包原始的 `package.json.description`;元信息诊断不会阻止管理操作。`source` 以 `pnpm add` 接受的 spec 给出 profile 依赖:git 地址或 URL 按记录给出,但去掉 http(s) URL 的 user information(查询字符串保持原样);`file:` 或 `link:` 路径按 profile 目录解析为绝对路径,`~` 展开为主目录;注册表版本范围、标签或别名接在包名的 `@` 之后,以别名安装的包的 spec 也是如此。安装提供的组合包没有该字段,即使 profile 也依赖它,因为实际加载的是安装中的副本。`plugin_manager` 工具的列表结果不包含 UI 展示元信息。 `listBundles` 将随附可选组合包和按需目录项标为 `official`,与包的安装状态独立。`availability` 表示可读取的安装随附包、profile 包,或 `missing`;按需目录项不计入未声明的传递依赖副本。`installed` 仅表示 profile 是否声明该依赖。尚未安装的按需条目携带内嵌的本地化元信息,以及 Host 生成、包含当前 DSH 版本与安装 spec 的 `installTarget`,无需访问注册表。profile 已声明但文件不可读的包保留依赖声明,并展示原有错误。 @@ -51,7 +49,7 @@ kind: "package-reference" 已发布的安装提供 `package@<当前 DSH 版本>`。源码 Web 与开发 Desktop 提供 `link:<工作区包的绝对目录>`,目录来自当前 CLI 的安装位置,包括其开发符号链接。包名通过工作区清单解析;当前工作目录和预发布版本后缀不用于选择 checkout。包、bundle patch 或已构建入口缺失时报告诊断,不回退到注册表。使用 `pnpm install` 和 `pnpm run build` 准备 checkout。链接包使用该 checkout 的依赖与 peer;代码改变后仍需重新构建并重启。即使版本相同,注册表副本或其他 checkout 的链接也可能需要替换。 -官方按需安装与显式更新调用和其他组合包相同的 `installBundle` 操作。注册表目标使用 `saveExact: true`;开发目标保留普通 `link:` 依赖。更新传入当前 `enabled` 选择状态;替换已有依赖会报告 `restart-required`。关闭仅取消选择配置层,移除使用原有移除检查。安装失败恢复 profile 清单和锁文件;安装成功后激活失败可能保留已保存的依赖和选择。原有 peer 兼容性检查继续生效,不增加仅针对官方条目的版本准入规则。 +官方按需安装调用和其他组合包相同的 `installBundle` 操作。注册表目标使用 `saveExact: true`;开发目标保留普通 `link:` 依赖。显式更新先删除已安装的包,再以当前 `enabled` 选择状态安装目标;没有 HMR 时,自启动起运行的组合包无法删除,因此安装直接覆盖它并报告 `restart-required`。删除之后安装失败或被取消时,该包保持未安装,重新安装的组合包排在选择列表末尾。关闭仅取消选择配置层,移除使用原有移除检查。安装失败恢复 profile 清单和锁文件;安装成功后激活失败可能保留已保存的依赖和选择。原有 peer 兼容性检查继续生效,不增加仅针对官方条目的版本准入规则。 `installBundle` 在启动 pnpm 前通过 `git ls-remote` 检查 GitHub 仓库,使用 profile 目录及安装器的 Git 与代理配置。`githubConnectionTimeoutMs` 默认为 5000 毫秒,只限制这次检查,不限制包下载或构建。检查禁用凭据助手和认证提示;只有网络失败与超时会停止安装,通过现有失败类型与诊断日志返回,并标记 `failedAt: 'spec-host'`。认证、仓库查找及其他失败继续交给 pnpm,包括其 HTTPS 到 SSH 的回退。取消安装或销毁管理器会停止检查及其子进程。注册表包、本地路径、压缩包和其他 Git 主机跳过此检查。仓库可达后,下载或组合包验证仍可能失败。 @@ -99,9 +97,9 @@ CLI 提供 `dsh plugin --profile version-exemptions`、`allow-version 服务与 `dsh plugin` 共用 [operations.ts](src/operations.ts) 中的包管理操作。启动器提供当前 profile;[DSH HMR](../hmr/README.zh.md) 串行执行模块重载、文件监听和管理写入。每次配置刷新重新读取组合包选择与 patch 层,更新原有根 Include,并等待已移除插件释放资源及剩余 Loader 树稳定。CLI 与 service 操作共用 profile manifest 写锁,防止并发包操作和 manifest 写入。HMR 不获取该锁。pnpm 在 HMR 队列之外执行;安装在 pnpm 成功后选入组合包,删除则在执行 pnpm 前取消选入并完成卸载。 -安装新包、启用组合包、有 HMR 时停用组合包并等插件退出后、以及删除成功后,都会发布 profile 的 runtime resolution。共享依赖的规范化目录、版本和作用域不变时,可以改由另一个组合包声明。没有 HMR 时,已取消选入的启动组合包仍在运行:只要保存的选择列表中缺少任何这样的组合包,后续包操作就保留整张当前表,并报告 `restart-required`。其他新安装和未运行组合包的删除仍可在没有 HMR 时发布;激活等待重启。覆盖已安装的包不发布,并报告 `restart-required`([决策](../../../.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.zh.md))。 +没有 HMR 时,安装新包、启用组合包以及删除成功后,都会发布 profile 的 runtime resolution;有 HMR 时,每个操作都把发布交给 [HMR](../hmr/README.zh.md) 的重新组合,该重新组合在相关插件停止后移除被丢弃的映射。共享依赖的规范化目录和作用域不变时,可以改由另一个组合包声明。没有 HMR 时,已取消选入的启动组合包仍在运行:只要保存的选择列表中缺少任何这样的组合包,后续包操作就保留整张当前表,并报告 `restart-required`。其他新安装和未运行组合包的删除仍可在没有 HMR 时发布;激活等待重启。有 HMR 时,spec 指明已安装的包,`installBundle()` 在运行 pnpm 之前以 `already-installed` 拒绝安装;spec 可以是 registry 包名、本地目录,或保存依赖时使用的 git 或 tarball spec。因此,有 HMR 时无法在不能删除的包(例如带有插件管理的组合包)上安装。安装另一个版本需要先卸载再安装,因此在安装新版本之前,旧版本的插件停止,其模块被逐出,其映射被移除;Web 页面中官方插件的更新会依次执行这两步。运行 pnpm 之后才能确定包名的 git 或 tarball spec 仍可能安装到已安装的包上:没有 HMR 时报告 `restart-required`;有 HMR 时,重新组合替换已加载文件发生变化的运行中插件。替换版本导入或启动失败时报告 `failed` 及激活诊断,该诊断给出导入错误;旧版本不再运行,此后每次操作都会再次导入它,因此其文件或依赖被修正后它即启动。未变化的导入失败在后续操作中作为警告报告;已变化的导入失败使后续操作失败。已安装的包现在解析到其他目录,或 DSH 安装的映射发生变化,使 runtime resolution 拒绝发布时,它停止并重新启动该发布将丢弃的行,组合保持不变,并报告带 `package-moved` 的 `restart-required`。停用或删除组合包时,会逐出因此被删除映射的那些包的模块。每个 `restart-required` 结果都带有 `restartReason`:`no-hmr`、`package-moved`,或只有重启后才能加载的已变化模块的 [HMR 待处理原因](../hmr/README.zh.md),除非操作报告 `overridden`([决策](../../../.agents/notes/implemented/architecture/2026-09-30-profile-package-refresh-and-manifest-invalidation.zh.md))。 -service 运行若在 `idleTimeoutMs` 内没有任何捕获输出即被终止,与退出状态一并报告 `timedOut`,不论信号留下什么退出状态都归类为 `timeout`,且不再转问下一个注册表,因此单次操作占用 profile 锁的时长有上界;CLI 继承终端、不捕获输出,因此不受此上界约束,由操作者中断。运行以进程退出为完成点,随后只在一个有界的宽限窗口内排空管道,因此继承管道的孙进程无法让操作挂起。被终止的运行会停止整棵进程树并等待其消失,因为生命周期脚本的存活时间超过启动它的 pnpm 进程(issue #4981)。每个操作把它启动的 pnpm 运行记录在 `.plugin-manager/run.json` 中,并在运行结束时删除该记录。持有者进程已退出的锁会被下一个写入方接管,但该进程的 pnpm 进程树可能仍在运行,因此发现记录的操作最多等待五秒让记录中的运行停止,否则不运行 pnpm,并以指明该进程与记录文件的诊断失败。仅依赖字段变化不会触发配置重载。 +service 运行若在 `idleTimeoutMs` 内没有任何捕获输出即被终止,与退出状态一并报告 `timedOut`,不论信号留下什么退出状态都归类为 `timeout`,且不再转问下一个注册表,因此单次操作占用 profile 锁的时长有上界;CLI 继承终端、不捕获输出,因此不受此上界约束,由操作者中断。运行以进程退出为完成点,随后只在一个有界的宽限窗口内排空管道,因此继承管道的孙进程无法让操作挂起。诊断文件会在调用结束前关闭,包括准备或创建进程失败的情况。被终止的运行会停止整棵进程树并等待其消失,因为生命周期脚本的存活时间超过启动它的 pnpm 进程(issue #4981)。每个操作把它启动的 pnpm 运行记录在 `.plugin-manager/run.json` 中,并在运行结束时删除该记录。持有者进程已退出的锁会被下一个写入方接管,但该进程的 pnpm 进程树可能仍在运行,因此发现记录的操作最多等待五秒让记录中的运行停止,否则不运行 pnpm,并以指明该进程与记录文件的诊断失败。仅依赖字段变化不会触发配置重载。 结果包含最后尝试的阶段、目标、磁盘变化、应用状态和错误码。Web 词典呈现管理文案;pnpm 与 Loader 的诊断保持原样。无关的已有故障作为警告返回;新出现、配置变化后的故障,以及显式启用目标未激活,都会使操作失败。包管理运行失败或被取消,或组合包校验失败时,会恢复 pnpm 运行前快照的 manifest 与 lockfile([理由](../../../.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.zh.md));后续失败按[失败行为](#failure-behavior)所述保留已保存的改动。安装按 request id 跟踪到调用结束,因此取消只针对一次运行,并且不取 profile 锁就能等待它结束。CLI 继承认证环境和终端描述符;service 使用清理后的环境并捕获输出。管理器直接读取文件和 Loader 状态,不维护第二份目标状态注册表,因此不发布单独的运行时不变式伴生入口。 @@ -124,7 +122,7 @@ service 运行若在 `idleTimeoutMs` 内没有任何捕获输出即被终止, #### 模型看到什么 -[`plugin_manager` 工具](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plugin-manager) 列出插件条目和组合包,并执行影响整个 profile 的改动。结果包含保存状态变化、应用状态和包管理诊断。管理操作不会向 Agent 注入消息。 +[`plugin_manager` 工具](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plugin-manager) 列出插件条目和组合包,并执行影响整个 profile 的改动。结果包含保存状态变化、应用状态和包管理诊断。未直接应用的变更结果会增加 `nextStep`,这是一句根据应用状态、拒绝代码、包管理器失败类型或重启原因生成的说明,指出模型下一步做什么或告诉用户什么。管理操作不会向 Agent 注入消息。 #### Token 影响 @@ -139,9 +137,10 @@ service 运行若在 `idleTimeoutMs` 内没有任何捕获输出即被终止, - Web 一次批准显示出来的整组待决定包,没有逐包选择。 -- 替换已有包后需要重启进程,以加载新的 JavaScript 模块版本。 +- 命令改动锁文件时,pnpm 按默认注册表校验锁文件中的每个 tarball URL。某个包从其他注册表安装后,使用默认注册表安装另一个包,或在重启后删除该包,可能以 `ERR_PNPM_TARBALL_URL_MISMATCH` 失败。 +- 没有 HMR 时,替换包需要重启进程。在 Plugin Manager 之外重新链接仍处于安装状态的包,需要等待重启。 - 仅启动时加载的 profile 不能删除当前进程启动时使用的包;停止进程后使用 `dsh plugin`。 -- 管理器不能关闭自身所需的管理组件、修改其他 profile 或直接编辑 agent 预设内部的单个条目。 +- 管理器不能关闭自身所需的管理组件、修改其他 profile 或编辑 agent 预设组合。 - 失败的删除可能留下部分依赖改动,失败或被取消的安装可能在 `node_modules` 或 pnpm 缓存中留下已下载文件。文件缺失的未启用依赖仍可删除。诊断日志保留在 profile 的 `.plugin-manager/logs` 目录中。 - 管理结果描述 Host 激活状态。浏览器同步失败会在设置的插件列表中单独显示。 - Desktop 包管理操作仍由 Desktop shell 负责。 @@ -158,7 +157,7 @@ service 运行若在 `idleTimeoutMs` 内没有任何捕获输出即被终止, | 包操作成功后解析表发布失败 | 保留已完成的磁盘改动和上一张运行时表。报告 `application: 'failed'` 及发布诊断;pnpm 的零退出码不代表发布成功。 | | 卸载:任一步失败 | 停在失败步骤,保留已完成的改动和待重试删除的依赖,报告卸载失败。不重新启用组合包。 | -pnpm 执行和组合包校验成功即完成安装,后续发布或启用失败不撤销安装。卸载依次执行:从 `dsh.profile.bundles` 移除组合包、卸载运行时贡献、执行 `pnpm remove`,然后发布 runtime resolution,除非没有 HMR 且已取消选入的启动组合包仍在运行。任一步失败都不继续执行后续步骤;删除后的发布失败不会恢复已删除的包。 profile 依赖和安装都不持有的已选名称(例如已下线的组合包)同样可卸载;其卸载在取消选择后结束,不运行 pnpm。 +pnpm 执行和组合包校验成功即完成安装,后续发布或启用失败不撤销安装。卸载依次执行:从 `dsh.profile.bundles` 移除组合包、卸载运行时贡献、执行 `pnpm remove`,然后发布 runtime resolution,除非没有 HMR 且已取消选入的启动组合包仍在运行。`pnpm remove` 使用本管理器在当前进程中最近一次安装该包时所用的注册表,因为 pnpm 按默认注册表校验锁文件中的 tarball URL;进程启动前安装的包使用安装时首先询问的注册表删除。任一步失败都不继续执行后续步骤;删除后的发布失败不会恢复已删除的包。 profile 依赖和安装都不持有的已选名称(例如已下线的组合包)同样可卸载;其卸载在取消选择后结束,不运行 pnpm。 恢复只重写这两份快照文件;用户编写的 patch 配置、应用数据、诊断日志以及 pnpm 已下载的文件保持原样,没有 manifest 引用的包由下一次包操作清理。 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 7e13d96b65..72bd8d54ae 100644 --- a/packages/boot/plugin-manager/package.json +++ b/packages/boot/plugin-manager/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-plugin-manager", "description": "Current-profile plugin and bundle management shared by dsh CLI, Web and agent tools", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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", @@ -65,7 +69,7 @@ "@deepseek-ai/schemastery": "workspace:~", "execa": "^10.0.1", "yaml": "^2.9.0", - "zod": "^4.4.3", + "zod": "4.4.3", "@deepseek-ai/dsh-util-values": "workspace:*" }, "peerDependencies": { @@ -79,8 +83,7 @@ "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-sandbox-policy": "workspace:*", "@deepseek-ai/dsh-sandbox": "workspace:*", - "@deepseek-ai/dsh-user-approval": "workspace:*", - "@deepseek-ai/dsh-agent-preset-registry": "workspace:*" + "@deepseek-ai/dsh-user-approval": "workspace:*" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-hmr": { @@ -88,9 +91,6 @@ }, "@deepseek-ai/dsh-user-approval": { "optional": true - }, - "@deepseek-ai/dsh-agent-preset-registry": { - "optional": true } }, "devDependencies": { @@ -111,10 +111,6 @@ "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-sandbox": "workspace:*", - "@deepseek-ai/dsh-user-approval": "workspace:*", - "@deepseek-ai/dsh-agent-preset-registry": "workspace:*", - "@deepseek-ai/dsh-agent-preset": "workspace:*", - "@deepseek-ai/dsh-scope": "workspace:*", - "@deepseek-ai/dsh-session-title": "workspace:*" + "@deepseek-ai/dsh-user-approval": "workspace:*" } } diff --git a/packages/boot/plugin-manager/src/bundle-rows.ts b/packages/boot/plugin-manager/src/bundle-rows.ts deleted file mode 100644 index 9a150f3bd7..0000000000 --- a/packages/boot/plugin-manager/src/bundle-rows.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** Raw bundle declarations remain inspectable while their prerequisite layers are disabled. */ -import { existsSync } from 'node:fs' -import { dirname, isAbsolute, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' -import { realModuleFile, profilePatchPreset, type ProfilePatch, type PluginPackages } from '@deepseek-ai/dsh-app-boot' - -/** A declared child row and the outer preset operation that contributes it. */ -export interface BundleDeclaration { - readonly row: EntryOptions - readonly preset?: string -} - -/** Read inserted rows without applying a bundle against an incomplete profile. - * @param patches Parsed bundle patches, whose module paths are already anchored. - * @returns Declarations in patch order, including nested groups. - */ -export function bundleDeclarations(patches: readonly ProfilePatch[]): BundleDeclaration[] { - const result: BundleDeclaration[] = [] - const visit = (rows: EntryOptions[], preset?: string): void => { - for (const row of rows) { - result.push({ row, ...preset === undefined ? {} : { preset } }) - if (row.group && Array.isArray(row.config)) visit(row.config as EntryOptions[], preset) - } - } - for (const patch of patches) { - if (patch.insert !== undefined) visit(patch.insert, profilePatchPreset(patch)) - } - return result -} - -/** Locate the package owning a bare import or filesystem module without importing its code. - * @param specifier Configured module name or anchored file URL. - * @param base Declaring Loader tree's resolution URL. - * @param packages Optional profile package lookup for bare specifiers. - * @returns Canonical package manifest path, or undefined for builtins, missing modules, and unowned files. - */ -export function bundleModuleOwner( - specifier: string, base: string, packages?: Pick, -): string | undefined { - const known = packages?.packageOf(specifier, base) - if (known !== undefined) return realModuleFile(known.manifestPath) - if (!specifier.startsWith('file:') && !specifier.startsWith('.') && !isAbsolute(specifier)) return undefined - const file = isAbsolute(specifier) ? specifier : fileURLToPath(new URL(specifier, base)) - if (!existsSync(file)) return undefined - let dir = dirname(realModuleFile(file)) - while (true) { - const manifest = join(dir, 'package.json') - if (existsSync(manifest)) return realModuleFile(manifest) - const parent = dirname(dir) - if (parent === dir) return undefined - dir = parent - } -} diff --git a/packages/boot/plugin-manager/src/index.ts b/packages/boot/plugin-manager/src/index.ts index 5c77c0a97c..6734d2872b 100644 --- a/packages/boot/plugin-manager/src/index.ts +++ b/packages/boot/plugin-manager/src/index.ts @@ -7,17 +7,16 @@ import { pathToFileURL } from 'node:url' import { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write' import { Context } from '@deepseek-ai/cordis' import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' -import type { PluginInventorySnapshot } from '@deepseek-ai/dsh-host-plugin-inventory/types' -import type { AgentPreset } from '@deepseek-ai/dsh-agent-preset-registry' +import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include' import z from '@deepseek-ai/schemastery' import { TypertRemoteService, Remote } from '@deepseek-ai/dsh-typert-protocol' import { pluginEntryId, readPluginInventory } from '@deepseek-ai/dsh-host-plugin-inventory' import { - readPluginMeta, resolvePluginResource, realModuleFile, readProfileManifest, resolveBundleDir, loadOverlayPatches, composeEntries, - reconcileProfilePatches, readProfilePatches, OPTIONAL_BUNDLES, bundlePatchPaths, + readPluginMeta, readProfileManifest, resolveBundleDir, loadOverlayPatches, composeEntries, + readProfilePatches, OPTIONAL_BUNDLES, bundlePatchPaths, evaluatePluginCompatibility, readProfileCompatibility, readProfileVersionExemptions, - setProfileVersionExemption, PROFILE_COMPATIBILITY_FILENAME, profilePatchPreset, type ProfilePatch, - OFFICIAL_ON_DEMAND_CATALOG, getDshRuntimeVersion, + setProfileVersionExemption, PROFILE_COMPATIBILITY_FILENAME, + OFFICIAL_ON_DEMAND_CATALOG, getDshRuntimeVersion, ResolutionRestartRequired, } from '@deepseek-ai/dsh-app-boot' import type {} from '@deepseek-ai/dsh-hmr' import type { ProfileContext, ProfileManifest } from '@deepseek-ai/dsh-app-boot' @@ -26,10 +25,9 @@ import { classifyInstallFailure } from './install-failure.ts' import { officialBundleInstallTarget } from './official-install-target.ts' import { dependencySpec, InvalidInstallSpecError, parseInstallSpec, type ParsedInstallSpec } from './install-spec.ts' import { attributeFailure, normalizeRegistry, NPMMIRROR_REGISTRY, registryPlan } from './registry.ts' -import { writePluginEnabled } from './patch.ts' +import { flatten, writePluginEnabled } from './patch.ts' import { incompatiblePlugin, ManagementFailure } from './failure.ts' import { approveBuilds, recordPendingBuilds } from './build-approval.ts' -import { bundleDeclarations, bundleModuleOwner, type BundleDeclaration } from './bundle-rows.ts' import { checkGithubConnection } from './github-connection.ts' import type { BundleInfo, BundleRowInfo, ChangeResult, InspectOptions, InstallBundleOptions, ManagementError, PackageResult, PluginChange, @@ -73,7 +71,7 @@ const protectedModules = new Set([ '@deepseek-ai/dsh-host-webserver', '@deepseek-ai/dsh-client-modules', '@deepseek-ai/dsh-client-ui-settings-plugin-inventory', '@deepseek-ai/dsh-client-ui-plugin-manager', '@deepseek-ai/dsh-host-plugin-inventory', '@deepseek-ai/dsh-typert-registry', - '@deepseek-ai/dsh-api-remotes', + '@deepseek-ai/dsh-api-remotes', '@deepseek-ai/dsh-api-remote-access', '@deepseek-ai/cordis-plugin-timer', '@deepseek-ai/dsh-client-connection', '@deepseek-ai/dsh-host-frontend-static', '@deepseek-ai/dsh-tools', '@deepseek-ai/dsh-hmr', @@ -85,11 +83,6 @@ const RESTORED_FILES = ['package.json', 'pnpm-lock.yaml'] as const /** pnpm's colour escapes, which a JSON answer may be wrapped in. */ const ANSI_SEQUENCE = /\x1b\[[0-9;]*m/g -/** Flatten only the groups addressable by the profile's patch composer. */ -function flatten(rows: EntryOptions[]): EntryOptions[] { - return rows.flatMap(row => [row, ...(row.group && Array.isArray(row.config) ? flatten(row.config as EntryOptions[]) : [])]) -} - /** Preserve the exact observed diagnostic, including non-Error failures. */ function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error) } @@ -158,6 +151,40 @@ function printedError(printed: string): string { return [code, message].filter((part): part is string => typeof part === 'string').join(' ') } +/** What applying the saved profile reports into a change result. */ +type Reload = Pick + +/** The bundles a profile manifest selects. */ +function bundleSelection(manifest: ProfileManifest): readonly string[] { + return manifest.dsh?.profile?.bundles ?? [] +} + +/** + * The package an installation spec names before pnpm runs: a registry name, a local directory's manifest name, or the + * dependency saved with this git or tarball spec, compared as the plugin list shows saved specs. + * @param spec The installation spec. + * @param dependencies The profile's saved dependencies. + * @param profileDir The profile directory saved local paths are relative to. + * @returns The package name, or `undefined` when only the installation tells it. + */ +function specPackageName(spec: string, dependencies: Readonly>, profileDir: string): string | undefined { + const parsed = parsedForRegistry(spec) + if (parsed.kind === 'registry') return parsed.name + if (parsed.kind === 'path') return packageName(parsed.path) + const specs = parsed.kind === 'tarball' && parsed.path !== undefined ? [spec, `file:${parsed.path}`] : [spec] + return Object.entries(dependencies).find(([dependency, saved]) => specs.includes(dependencySpec(dependency, saved, profileDir)))?.[0] +} + +/** The package name a local directory declares, or `undefined` without a readable manifest. */ +function packageName(dir: string): string | undefined { + try { + return readProfileManifest('dsh', dir).name + } catch (_error) { + // pnpm reports the unreadable directory itself. + return undefined + } +} + /** The spec's form, for deciding whether a failed attempt was the registry's; a form the parser refuses has no host of its own. */ function parsedForRegistry(spec: string): ParsedInstallSpec { try { @@ -191,6 +218,11 @@ export class PluginManager extends TypertRemoteService { }) /** Management bundles remain protected if their files become unreadable. */ private readonly managementBundles = new Set() + /** + * The registry each package was last installed from by this manager in this process. pnpm verifies lockfile tarball + * URLs against its default registry unless they belong to a named registry, so a later removal names it again. + */ + private readonly installedFrom = new Map() private readonly ownerEntryId: string | undefined private readonly packageOperations = new Set>() private readonly profile: ProfileContext @@ -249,7 +281,7 @@ export class PluginManager extends TypertRemoteService { setVersionExemption(packageVersion: string, runtimeVersion: string, enabled: boolean, acceptRisk?: boolean): Promise { return this.change(result => this.configure(async () => { await setProfileVersionExemption(this.profile.dir, packageVersion, runtimeVersion, enabled, acceptRisk === true) - result.warnings = await this.reload() + Object.assign(result, await this.reload()) }), { stage: 'enable', target: packageVersion, enabled }, 'bundle') } @@ -281,12 +313,10 @@ export class PluginManager extends TypertRemoteService { * display metadata, activation selections, whether the installation offers the bundle, and removal availability. */ @Remote - async listBundles(): Promise { - const inventory = await readPluginInventory(this.ctx) - const definitions = await this.ctx.get('agentPresets')?.list() ?? [] + listBundles(): Promise { const manifest = readProfileManifest('dsh', this.profile.dir) const exemptions = readProfileVersionExemptions(this.profile.dir) - const selected = manifest.dsh?.profile?.bundles ?? [] + const selected = bundleSelection(manifest) const recorded = manifest.dependencies ?? {} const dependencies = Object.keys(recorded) const installation = JSON.parse(readFileSync(this.profile.installAnchor, 'utf8')) as InstallationManifest @@ -341,7 +371,7 @@ export class PluginManager extends TypertRemoteService { ...meta === undefined ? {} : { meta }, ...sourceOf(info.name), enabled, installed, optional, removable: removable && readOnlyReason === undefined, ...(readOnlyReason === undefined ? {} : { readOnlyReason }), - ...this.declaredRows(name, info, inventory, definitions), + ...this.declaredRows(name, info), ...targetError === undefined ? {} : { error: targetError } }) } catch (error) { if (enabled || installed || optional || offered !== undefined) { @@ -352,7 +382,7 @@ export class PluginManager extends TypertRemoteService { } } } - return bundles + return Promise.resolve(bundles) } /** Read the registries this manager asks: the configured first one, its fallbacks in order, and what pnpm's own configuration names. @@ -387,7 +417,7 @@ export class PluginManager extends TypertRemoteService { const manifest = readProfileManifest('dsh', this.profile.dir) const installation = JSON.parse(readFileSync(this.profile.installAnchor, 'utf8')) as InstallationManifest const known = new Set([ - ...manifest.dsh?.profile?.bundles ?? [], ...Object.keys(manifest.dependencies ?? {}), ...Object.keys(installation.dependencies ?? {}), + ...bundleSelection(manifest), ...Object.keys(manifest.dependencies ?? {}), ...Object.keys(installation.dependencies ?? {}), ]) const plan = registryPlan(options?.registry, await this.registries()) const registry = plan[0] as Registry @@ -464,8 +494,8 @@ export class PluginManager extends TypertRemoteService { const row = (await this.listPlugins()).find(item => item.entryId === id) if (row === undefined) throw new ManagementFailure('unknown-plugin') if (row.readOnlyReason !== undefined) throw new ManagementFailure(row.readOnlyReason) - await writePluginEnabled(this.profile.patchPath, row.patchId, row.moduleName, enabled) - result.warnings = await this.reload(enabled ? [row.patchId] : []) + await writePluginEnabled(this.profile, row.patchId, row.moduleName, enabled) + Object.assign(result, await this.reload(enabled ? [row.patchId] : [])) const current = (await this.listPlugins()).find(item => item.entryId === id) return current?.enabled !== enabled && this.ownerContext.get('hmr') !== undefined ? 'overridden' : undefined }), { stage: 'enable', target: id, enabled }, 'plugin') @@ -480,11 +510,7 @@ export class PluginManager extends TypertRemoteService { setBundleEnabled(name: string, enabled: boolean): Promise { return this.change(result => this.configure(async () => { await this.selectBundle(name, enabled) - if (enabled) await this.refreshPackages() - const rows = enabled ? this.bundleRows(name) : [] - result.warnings = await this.reload(rows.filter(row => row.preset === undefined).map(({ row }) => row.id), - enabled ? this.bundlePresets(name) : []) - if (!enabled && this.ownerContext.get('hmr') !== undefined) await this.refreshPackages() + Object.assign(result, enabled ? await this.publishAndReload(this.bundleRows(name).map(row => row.id)) : await this.reload()) }), { stage: 'enable', target: name, enabled }, 'bundle') } @@ -511,12 +537,17 @@ export class PluginManager extends TypertRemoteService { const result = this.change(async (result) => { if (spec.trim() === '' || spec.startsWith('-')) throw new ManagementFailure('invalid-spec') if (stopped()) throw new InstallCancelledError() + const before = readProfileManifest('dsh', this.profile.dir).dependencies ?? {} + // With HMR, an installed package is removed before another version is installed, so its plugins stop first. + const known = specPackageName(spec, before, this.profile.dir) + if (this.ownerContext.get('hmr') !== undefined && known !== undefined && Object.hasOwn(before, known)) { + throw new ManagementFailure('already-installed') + } if (options?.approvedBuilds !== undefined) { await approveBuilds(this.profile.dir, options.approvedBuilds) result.approvedBuilds = options.approvedBuilds } const files = await this.readRestoredFiles() - const before = readProfileManifest('dsh', this.profile.dir).dependencies ?? {} let name: string let version: string | undefined try { @@ -539,11 +570,13 @@ export class PluginManager extends TypertRemoteService { // The last run is the result's; the registries asked stay listed whatever the outcome. const plan = registryPlan(options?.registry, await this.registries()) let run: PackageResult | undefined + let used: Registry = null for (const [index, registry] of plan.entries()) { if (index > 0) await this.restoreFiles(files) // A stop that landed while the files went back, or before the first run, starts no run with a dead signal. if (stopped()) throw new InstallCancelledError() result.registries.push(registry) + used = registry announce('installing', { registry, index: index + 1, total: plan.length }) run = await this.runPnpm(['add', spec, ...options?.saveExact === true ? ['--save-exact'] : [], ...registryArguments(registry)], control.abort.signal, requestId) result.packageResult = run @@ -577,11 +610,10 @@ export class PluginManager extends TypertRemoteService { } const after = readProfileManifest('dsh', this.profile.dir).dependencies ?? {} const installed = Object.keys(after).filter(name => before[name] !== after[name]) - // Registry retries can retain the saved range after a partial installation. + // Without HMR a repeated installation can leave the saved dependency as it was. if (installed.length === 0) { - const parsed = parsedForRegistry(spec) - const localName = parsed.kind === 'path' ? readProfileManifest('dsh', parsed.path).name : undefined - installed.push(...Object.keys(after).filter(name => name === localName || spec === name || spec.startsWith(`${name}@`))) + const local = specPackageName(spec, after, this.profile.dir) + if (local !== undefined && Object.hasOwn(after, local)) installed.push(local) } const target = installed[0] if (installed.length !== 1 || target === undefined) throw new ManagementFailure('ambiguous-install') @@ -593,6 +625,7 @@ export class PluginManager extends TypertRemoteService { if (compatibility !== undefined && !compatibility.exempted) throw new ManagementFailure('incompatible-version', [incompatiblePlugin(compatibility)]) for (const file of bundlePatchPaths(dir, manifest.dsh.bundle)) loadOverlayPatches('dsh', file) version = manifest.version + this.installedFrom.set(name, used) } catch (error) { // pnpm has exited by now, so the files it rewrote go back as they were. await this.restoreFiles(files) @@ -606,9 +639,11 @@ export class PluginManager extends TypertRemoteService { result.stage = 'enable' return this.configure(async () => { if (options?.enabled !== false) await this.selectBundle(name, true) - if (Object.hasOwn(before, name)) return 'restart-required' - await this.refreshPackages() - if (options?.enabled !== false) result.warnings = await this.reload([], this.bundlePresets(name)) + // Without HMR the replaced package's plugins keep running until the restart the result already reports. + if (Object.hasOwn(before, name) && this.ownerContext.get('hmr') === undefined) return + // A selected bundle's own rows must start. + const selected = bundleSelection(readProfileManifest('dsh', this.profile.dir)).includes(name) + Object.assign(result, await this.publishAndReload(selected ? this.bundleRows(name).map(row => row.id) : [])) }) }, { stage: 'install', target: spec, enabled: options?.enabled !== false }, 'install') control.result = result @@ -653,93 +688,68 @@ export class PluginManager extends TypertRemoteService { const installed = await this.configure(async () => { const bundle = (await this.listBundles()).find(item => item.name === name) if (bundle === undefined || !bundle.removable) throw new ManagementFailure('not-removable') - const contributions = bundle.error === undefined ? this.bundleRows(name) : [] if (this.ownerContext.get('hmr') === undefined && (this.profile.startedBundles.includes(name) - || contributions.some(({ row, preset }) => preset === undefined && [...this.ctx.loader.entries()] - .some(entry => entry.options.id === row.id && entry.fiber !== undefined)) - || this.retainedBundleModules(name, contributions))) { + || (bundle.error === undefined && this.bundleRows(name).some(row => [...this.ctx.loader.entries()] + .some(entry => entry.options.id === row.id && entry.fiber !== undefined))))) { throw new ManagementFailure('stop-profile') } + const contributions = bundle.error === undefined ? this.bundleRows(name) : [] if (bundle.enabled) { await this.selectBundle(name, false) - result.warnings = await this.reload() + Object.assign(result, await this.reload()) } if ([...this.ctx.loader.entries()].some(entry => entry.fiber?.uid != null - && contributions.some(({ row, preset }) => preset === undefined - && row.id === entry.options.id && row.name === entry.options.name)) - || this.retainedBundleModules(name, contributions)) { + && contributions.some(row => row.id === entry.options.id && row.name === entry.options.name))) { throw new ManagementFailure('bundle-in-use') } return bundle.installed }) if (!installed) return - result.packageResult = await this.runPnpm(['remove', name]) + // `pnpm remove` takes no `--registry` option; the generic configuration flag sets the same setting. A package + // installed before this process started is removed with the registry an installation asks first. + const registry = this.installedFrom.has(name) ? this.installedFrom.get(name) : this.configuredRegistries.registry + result.packageResult = await this.runPnpm(['remove', name, ...typeof registry === 'string' ? [`--config.registry=${registry}`] : []]) if (result.packageResult.exitCode !== 0 || result.packageResult.timedOut === true) { throw new Error(result.packageResult.output) } - await this.configure(() => this.refreshPackages()) + this.installedFrom.delete(name) + Object.assign(result, await this.configure(() => this.publishAndReload())) }, { stage: 'remove', target: name }, 'remove') } - /** The rows a bundle declares, joined by outer preset and child id where applicable. */ - private declaredRows(name: string, info: ProfileManifest, inventory: PluginInventorySnapshot, definitions: readonly AgentPreset[]): Pick { - const patches = this.bundlePatches(name, info) + /** The rows a bundle's patch inserts and the existing rows it changes; an unreadable patch throws. */ + private declaredRows(name: string, info: ProfileManifest): Pick { + const bundle = info.dsh?.bundle + /* v8 ignore next -- bundleManifest answers only manifests that declare a patch */ + if (bundle === undefined) return { rows: [], overrides: [] } const dir = resolveBundleDir('dsh', name, this.profile.installAnchor, this.profile.dir) - const entries = [...this.ctx.loader.entries()] + const patches: PatchOptions[] = bundlePatchPaths(dir, bundle).flatMap(file => loadOverlayPatches('dsh', file)) + // One entry per row id: the Loader keeps a single entry for an id, whichever layer declared it last. + const live = new Map() + for (const entry of this.ctx.loader.entries()) { + /* v8 ignore next -- the Loader gives every entry an id before it is listed */ + if (typeof entry.options.id === 'string') live.set(entry.options.id, { + entryId: pluginEntryId(entry.id), baseUrl: entry.parent.tree.ctx.baseUrl, + }) + } const rows: BundleRowInfo[] = [] const packages = this.ctx.get('pluginPackages') - for (const { row, preset } of bundleDeclarations(patches)) { - if (typeof row.id !== 'string' || typeof row.name !== 'string') continue - const matches = preset === undefined ? entries.filter(entry => entry.options.id === row.id && entry.options.name === row.name) : [] - const active = matches.length === 1 ? matches[0] : undefined - const base = active?.parent.tree.ctx.baseUrl ?? pathToFileURL(join(dir, 'package.json')).href + for (const row of flatten(composeEntries([patches.filter(item => item.insert !== undefined)]))) { + // Group rows are containers without a plugin inventory entry; their children carry the switches. + if (typeof row.id !== 'string' || typeof row.name !== 'string' || row.group === true) continue + const active = live.get(row.id) + const entryId = active?.entryId + const base = active?.baseUrl ?? pathToFileURL(join(dir, 'package.json')).href const meta = packages?.metaOf(row.name, base) - const presetId = preset === undefined ? undefined : definitions.find(item => item.definitionEntryId === preset)?.id - const composition = inventory.agentPresets?.find(item => item.id === presetId)?.rows - .find(item => item.entryId === row.id && item.moduleName === row.name) rows.push({ rowId: row.id, moduleName: row.name, - ...preset === undefined ? {} : { preset, readOnlyReason: 'preset-managed' as const }, - ...composition === undefined ? {} : { composition: { enabled: composition.enabled, fiberPhase: composition.fiberPhase } }, - ...active === undefined ? {} : { entryId: pluginEntryId(active.id) }, ...meta === undefined ? {} : { meta } }) + ...entryId === undefined ? {} : { entryId }, ...meta === undefined ? {} : { meta } }) } - const key = (preset: string | undefined, id: string): string => JSON.stringify([preset, id]) - const declared = new Set(rows.map(row => key(row.preset, row.rowId))) - const overrides = [...new Set(patches.flatMap((item) => { - const preset = profilePatchPreset(item) - return item.insert === undefined && typeof item.id === 'string' && !declared.has(key(preset, item.id)) - ? [preset === undefined ? item.id : `${preset}/${item.id}`] : [] - }))] + const declared = new Set(rows.map(row => row.rowId)) + const overrides = [...new Set(patches.flatMap(item => + item.insert === undefined && typeof item.id === 'string' && !declared.has(item.id) ? [item.id] : []))] return { rows, overrides } } - /** Retained revisions still hold module code even after a bundle has been deselected. */ - private retainedBundleModules(name: string, declarations: readonly BundleDeclaration[]): boolean { - const presets = this.ctx.get('agentPresets') - if (presets === undefined || declarations.length === 0) return false - const manifest = join(resolveBundleDir('dsh', name, this.profile.installAnchor, this.profile.dir), 'package.json') - const base = pathToFileURL(manifest).href - const owner = realModuleFile(manifest) - const moduleKey = (specifier: string, parentURL: string): string | undefined => { - if (specifier.startsWith('cordis:')) return specifier - try { return realModuleFile(resolvePluginResource(specifier, parentURL)) } - catch (error) { - // An externally removed module cannot match another resolved file; identical declarations remain protected below. - if (['ENOENT', 'ENOTDIR', 'ERR_MODULE_NOT_FOUND', 'ERR_PACKAGE_PATH_NOT_EXPORTED'].includes(String((error as NodeJS.ErrnoException).code))) return undefined - throw error - } - } - return presets.inspectCompositions().some(composition => composition.modules.some((module) => { - const moduleBase = module.baseUrl ?? base - if (bundleModuleOwner(module.moduleName, moduleBase, this.ctx.get('pluginPackages')) === owner) return true - return module.useHostBase && declarations.some(({ row, preset }) => { - if (preset === undefined || preset !== composition.definitionEntryId || row.id !== module.entryId) return false - const declared = moduleKey(row.name, base) - const retained = moduleKey(module.moduleName, moduleBase) - return declared === undefined || retained === undefined ? row.name === module.moduleName : declared === retained - }) - })) - } - /** Run one pnpm command in the profile, streaming its output as install-log chunks. */ private async runPnpm( args: readonly string[], signal?: AbortSignal, requestId?: PluginInstallRequestId, @@ -797,7 +807,7 @@ export class PluginManager extends TypertRemoteService { private async selectBundle(name: string, enabled: boolean): Promise { const manifest = readProfileManifest('dsh', this.profile.dir) - const previous = manifest.dsh?.profile?.bundles ?? [] + const previous = bundleSelection(manifest) if (enabled || !previous.includes(name)) { const metadata = bundleManifest(name, this.profile.dir, this.profile.installAnchor) if (metadata === undefined) throw new ManagementFailure('not-bundle') @@ -817,31 +827,21 @@ export class PluginManager extends TypertRemoteService { if (enabled) this.protectsManager(name) } - private bundlePatches(name: string, known?: ProfileManifest): ProfilePatch[] { - const info = known ?? bundleManifest(name, this.profile.dir, this.profile.installAnchor) + private bundleRows(name: string): EntryOptions[] { + const info = bundleManifest(name, this.profile.dir, this.profile.installAnchor) if (info?.dsh?.bundle === undefined) return [] const dir = resolveBundleDir('dsh', name, this.profile.installAnchor, this.profile.dir) - return bundlePatchPaths(dir, info.dsh.bundle).flatMap(file => loadOverlayPatches('dsh', file)) - } - - private bundleRows(name: string): BundleDeclaration[] { return bundleDeclarations(this.bundlePatches(name)) } - - private bundlePresets(name: string): string[] { - return [...new Set(this.bundlePatches(name).flatMap((patch) => { - const preset = profilePatchPreset(patch) - return preset === undefined ? [] : [preset] - }))] + return flatten(composeEntries([bundlePatchPaths(dir, info.dsh.bundle).flatMap(file => loadOverlayPatches('dsh', file))])) } private protectsManager(name: string): boolean { if (this.managementBundles.has(name)) return true - let rows: BundleDeclaration[] + let rows: EntryOptions[] try { rows = this.bundleRows(name) } catch (_error) { // Unreadable bundles contribute no new rows; listBundles reports their diagnostics. return false } - const protectedBundle = rows.some(({ row, preset }) => preset === undefined - && (protectedModules.has(row.name) || `include:${row.id}` === this.ownerEntryId)) + const protectedBundle = rows.some(row => protectedModules.has(row.name) || `include:${row.id}` === this.ownerEntryId) if (protectedBundle) this.managementBundles.add(name) return protectedBundle } @@ -852,42 +852,47 @@ export class PluginManager extends TypertRemoteService { return hmr === undefined ? apply() : hmr.runExclusive(apply) } + /** + * Publish the profile's runtime resolution without HMR, unless a deselected startup bundle still runs and needs the + * current table. A publication that needs a restart waits for the restart the result already reports. + */ private async refreshPackages(): Promise { - if (this.ownerContext.get('hmr') === undefined) { - const selected = readProfileManifest('dsh', this.profile.dir).dsh?.profile?.bundles ?? [] - // Deselected startup bundles still run without HMR and need the existing package table. - if (this.profile.startedBundles.some(name => !selected.includes(name))) return + const selected = bundleSelection(readProfileManifest('dsh', this.profile.dir)) + if (this.profile.startedBundles.some(name => !selected.includes(name))) return + try { + const packages = this.ownerContext.get('pluginPackages') + // A dropped mapping's bundle is not running: the guard above keeps the table while a deselected startup bundle runs. + if (packages?.resolution !== undefined) await packages.refresh() + } catch (error) { + if (!(error instanceof ResolutionRestartRequired)) throw error } - await this.ownerContext.get('pluginPackages')?.refresh() } - /** Configuration identity distinguishes a changed failed preset from an unrelated pre-existing warning. */ - private presetConfiguration(preset: AgentPreset): string { - return JSON.stringify([...this.ctx.loader.entries()].flatMap((entry) => { - const config = entry.options.config as { id?: unknown; plugins?: unknown } | undefined - return entry.options.id === preset.definitionEntryId && config?.id === preset.id && Array.isArray(config.plugins) ? [config] : [] - })) + /** + * Apply a package change: without HMR, publish the runtime resolution when that is safe, then {@link reload}. + * @param requiredIds Entry ids that must start. + * @returns The reload's outcome. + */ + private async publishAndReload(requiredIds: readonly string[] = []): Promise { + if (this.ownerContext.get('hmr') === undefined) await this.refreshPackages() + return this.reload(requiredIds) } - private async reload(requiredIds: readonly string[] = [], requiredPresets: readonly string[] = []): Promise { - if (this.ownerContext.get('hmr') === undefined) { + /** + * Apply the saved profile; with HMR it recomposes live, including the runtime resolution. + * @param requiredIds Entry ids that must start. + * @returns Warnings about entries that were already inactive, and why the change waits for a restart, if it does. + */ + private async reload(requiredIds: readonly string[] = []): Promise { + const hmr = this.ownerContext.get('hmr') + if (hmr === undefined) { + // Startup-only profiles recompose at restart; the saved patches still have to compose. composeEntries([readProfilePatches('dsh', this.profile)]) - return [] + return { warnings: [] } } - const presets = this.ctx.get('agentPresets') - const before = new Map((await presets?.list() ?? []).map(row => - [row.id, { broken: row.broken, config: this.presetConfiguration(row) }])) - const warnings = await reconcileProfilePatches( - this.ownerContext.root, readProfilePatches('dsh', this.profile), 'dsh', [...requiredIds, ...requiredPresets], - ) - const after = await this.ctx.get('agentPresets')?.list() ?? [] - const required = new Set(after.filter(row => row.definitionEntryId !== undefined && requiredPresets.includes(row.definitionEntryId)) - .map(row => row.id)) - const broken = after.filter(row => row.broken !== undefined) - const failed = broken.filter(row => required.has(row.id) || before.get(row.id)?.broken !== row.broken - || before.get(row.id)?.config !== this.presetConfiguration(row)) - if (failed.length > 0) throw new Error(failed.map(row => `agent preset ${row.id}: ${row.broken}`).join('\n')) - return [...warnings, ...broken.map(row => `agent preset ${row.id}: ${row.broken}`)] + const { warnings, pending, restartReason } = await hmr.reconcileProfile(requiredIds) + const restart = restartReason ?? pending[0]?.reason + return restart === undefined ? { warnings } : { warnings, restartReason: restart } } private async change( @@ -899,9 +904,12 @@ export class PluginManager extends TypertRemoteService { this.abort.signal.throwIfAborted() const before = this.diskState() const result: ChangeResult = { ...request, changed: false, - application: this.ownerContext.get('hmr') !== undefined ? 'applied' : 'restart-required' } + ...this.ownerContext.get('hmr') !== undefined ? { application: 'applied' } : { application: 'restart-required', restartReason: 'no-hmr' } } try { - result.application = await operation(result) ?? result.application + const outcome = await operation(result) + if (outcome !== undefined) result.application = outcome + // A reload that waits for a restart leaves the change saved but not applied. + else if (result.application === 'applied' && result.restartReason !== undefined) result.application = 'restart-required' } catch (error) { if (error instanceof InstallCancelledError) { result.application = 'cancelled' @@ -910,6 +918,7 @@ export class PluginManager extends TypertRemoteService { result.error = managementError(error) } } + if (result.application !== 'restart-required') delete result.restartReason result.changed = before !== this.diskState() this.ownerContext.emit('plugin-manager/changed', { reason }) return result diff --git a/packages/boot/plugin-manager/src/operations.ts b/packages/boot/plugin-manager/src/operations.ts index 8d58402e76..a6fe676544 100644 --- a/packages/boot/plugin-manager/src/operations.ts +++ b/packages/boot/plugin-manager/src/operations.ts @@ -4,17 +4,17 @@ import { existsSync, readFileSync } from 'node:fs' import { mkdir, mkdtemp, open, rm } from 'node:fs/promises' import { join, resolve } from 'node:path' import { execa } from 'execa' +import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' import { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write' import { DEFAULT_PROFILE_BUNDLES, bundlePatchPaths, initProfile, PROFILE_TEMPLATES, readProfileManifest, - resolveBundleDir, resolveProfileDir, loadOverlayPatches, readProfileVersionExemptions, + resolveBundleDir, resolveProfileDir, loadOverlayPatches, composeEntries, readProfileVersionExemptions, evaluatePluginCompatibility, pluginCompatibilityWarning, type ProfileManifest, } from '@deepseek-ai/dsh-app-boot' import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess' import { parseInstallSpec } from './install-spec.ts' import { awaitTreeGone, leadsOwnGroup, treeAlive, type RunTree } from './run-tree.ts' import { incompatiblePlugin } from './failure.ts' -import { bundleDeclarations } from './bundle-rows.ts' import type { IncompatiblePlugin, PackageResult, Registry } from './types.ts' export { setProfileVersionExemption, readProfileVersionExemptions } from '@deepseek-ai/dsh-app-boot' @@ -251,11 +251,15 @@ function bundleComponentManifests(manifest: ProfileManifest, dir: string, anchor if (bundle === undefined) return [] const patches = bundlePatchPaths(dir, bundle).flatMap(file => loadOverlayPatches('dsh', file)) const names = new Set() - for (const { row } of bundleDeclarations(patches)) { - if (typeof row.name !== 'string' || row.name.startsWith('.') || row.name.startsWith('/') || row.name.includes(':')) continue - const parts = row.name.split('/') - names.add(parts.slice(0, row.name.startsWith('@') ? 2 : 1).join('/')) + const visit = (rows: EntryOptions[]) => { + for (const row of rows) { + if (row.group && Array.isArray(row.config)) visit(row.config as EntryOptions[]) + if (typeof row.name !== 'string' || row.name.startsWith('.') || row.name.startsWith('/') || row.name.includes(':')) continue + const parts = row.name.split('/') + names.add(parts.slice(0, row.name.startsWith('@') ? 2 : 1).join('/')) + } } + visit(composeEntries([patches.filter(patch => patch.insert !== undefined)])) return [...names].flatMap((name) => { let packageDir: string try { packageDir = resolveBundleDir('dsh', name, anchor, dir) } catch (error) { @@ -276,6 +280,7 @@ function bundleComponentManifests(manifest: ProfileManifest, dir: string, anchor * @param options Output, activation and cancellation policy. * @returns Exit status, whether the silence bound stopped the run, and the diagnostic path. * A compatibility denial returns exit code 1. Service output is bounded; CLI output uses inherited descriptors. + * The diagnostic file is closed on return or rejection, including preparation and spawn failures. */ export async function runProfilePnpm( context: PackageOperationContext, args: readonly string[], options: PackageOperationOptions, @@ -287,7 +292,7 @@ export async function runProfilePnpm( await mkdir(logRoot, { recursive: true, mode: 0o700 }) const logDir = await mkdtemp(join(logRoot, 'operation-')) const logPath = join(logDir, 'pnpm.log') - const log = await open(logPath, 'wx', 0o600) + await using log = await open(logPath, 'wx', 0o600) if (active !== undefined) { await log.write(active) await log.close() @@ -344,7 +349,7 @@ export async function runProfilePnpm( } } catch (error) { void error; continue } } - if (preflight.length > 0) return rejected(preflight, 'nothing was installed') + if (preflight.length > 0) return await rejected(preflight, 'nothing was installed') const cancellation = new AbortController() // A service run captures output, so execa terminates the tree it leads when the // run is killed: a lifecycle script outlives the pnpm process that started it. diff --git a/packages/boot/plugin-manager/src/patch.ts b/packages/boot/plugin-manager/src/patch.ts index 3a4aa69f09..0dfacb2de6 100644 --- a/packages/boot/plugin-manager/src/patch.ts +++ b/packages/boot/plugin-manager/src/patch.ts @@ -1,17 +1,29 @@ -/** Comment-preserving profile plugin enablement edits. */ +/** Comment-preserving profile plugin enablement edits and the entry flattening they compare against. */ import { readFile } from 'node:fs/promises' -import { isMap, isSeq, parseDocument } from 'yaml' -import { loadOptionalPatches } from '@deepseek-ai/dsh-app-boot' +import { isMap, isNode, isScalar, isSeq, parseDocument } from 'yaml' +import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' +import { composeEntries, loadOptionalPatches, readBundlePatches, type ProfileContext } from '@deepseek-ai/dsh-app-boot' import { writeFileAtomic } from '@deepseek-ai/dsh-atomic-write' -/** Replace the last matching Host override or append one, preserving preset-scoped operations. - * @param filename Current profile patch file. - * @param id Unique Host composition entry id. +/** Flatten only the groups addressable by the profile's patch composer. + * @param rows Composed top-level entries. + * @returns Entries in depth-first order. + */ +export function flatten(rows: EntryOptions[]): EntryOptions[] { + return rows.flatMap(row => [row, ...(row.group && Array.isArray(row.config) ? flatten(row.config as EntryOptions[]) : [])]) +} + +/** Replace the last matching override or append one after existing insertions. An override that holds only `id` and + * `disabled`, without anchors, is removed, or not appended, when the bundle layers and the remaining profile patches + * already give the entry the requested literal `disabled` value; home patches and launch overlays are not consulted. + * @param profile Profile whose patch file is edited and whose selected bundles supply the compared composition. + * @param id Unique composition entry id. * @param name Module name used to match name-qualified overrides. * @param enabled Desired entry enablement. * @returns Whether the file changed. */ -export async function writePluginEnabled(filename: string, id: string, name: string, enabled: boolean): Promise { +export async function writePluginEnabled(profile: ProfileContext, id: string, name: string, enabled: boolean): Promise { + const filename = profile.patchPath let text: string try { text = await readFile(filename, 'utf8') @@ -25,17 +37,40 @@ export async function writePluginEnabled(filename: string, id: string, name: str const error = document.errors[0] if (error !== undefined) throw error if (!isSeq(document.contents)) throw new Error('Profile patch must be a YAML sequence') - loadOptionalPatches('dsh', filename) + const patches = loadOptionalPatches('dsh', filename) ?? [] + const bundlePatches = readBundlePatches('dsh', profile) const items = document.contents.items const target = items.findLast((item, index) => { - if (!isMap(item) || document.getIn([index, 'id']) !== id || item.has('insert') || item.has('preset')) return false + if (!isMap(item) || document.getIn([index, 'id']) !== id || item.has('insert')) return false const expectedName = document.getIn([index, 'name']) return !expectedName || expectedName === name }) + // Compares the entry's own literal `disabled`; a `!!js` value never matches, so its override is kept. + const implied = (index: number): boolean => { + const row = flatten(composeEntries([[...bundlePatches, ...patches.toSpliced(index, 1)]])).findLast(entry => entry.id === id) + return row !== undefined && (row.disabled ?? false) === !enabled + } if (isMap(target)) { - if (document.getIn([items.indexOf(target), 'disabled']) === !enabled) return false - document.setIn([items.indexOf(target), 'disabled'], !enabled) + const index = items.indexOf(target) + // A removed anchor would leave later aliases unresolved. + const onlySwitch = target.anchor === undefined && target.items.every(pair => isScalar(pair.key) && isScalar(pair.value) + && pair.key.anchor === undefined && pair.value.anchor === undefined && (pair.key.value === 'id' || pair.key.value === 'disabled')) + if (onlySwitch && implied(index)) { + document.deleteIn([index]) + // The comment above the removed override can be the file header, so it moves to the following item, above an + // emptied sequence, or after the remaining items. + const comment = target.commentBefore + const next = items[index] + if (comment && isNode(next)) next.commentBefore = next.commentBefore ? `${comment}\n${next.commentBefore}` : comment + else if (comment && items.length === 0) document.contents.commentBefore = comment + else if (comment) document.comment = document.comment ? `${comment}\n${document.comment}` : comment + } else if (document.getIn([index, 'disabled']) === !enabled) { + return false + } else { + document.setIn([index, 'disabled'], !enabled) + } } else { + if (implied(items.length)) return false document.add({ id, disabled: !enabled }) } await writeFileAtomic(filename, String(document), { mode: 0o600 }) diff --git a/packages/boot/plugin-manager/src/tools.ts b/packages/boot/plugin-manager/src/tools.ts index 29c58e898d..553f73572c 100644 --- a/packages/boot/plugin-manager/src/tools.ts +++ b/packages/boot/plugin-manager/src/tools.ts @@ -5,10 +5,76 @@ import type {} from './index.ts' import type {} from '@deepseek-ai/dsh-sandbox-policy' import type {} from '@deepseek-ai/dsh-user-approval' import { approveEscalation } from '@deepseek-ai/dsh-sandbox' -import type { PluginEntryId } from './types.ts' +import type { ChangeResult, ManagementError, PluginEntryId, PluginInstallFailureKind, RestartReason } from './types.ts' import { defineTool } from '@deepseek-ai/dsh-tools' import { getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot' +/** What the model does next for each refusal the manager reports. */ +const ERROR_STEPS: Record = { + 'management-required': 'This entry belongs to plugin management itself and cannot be changed.', + 'unaddressable': 'This entry has no unique profile patch target; tell the user to edit the profile patch file directly.', + 'unknown-plugin': 'Call list_plugins and retry with an exact entryId.', + 'invalid-spec': 'Retry with an npm package name, a git URL, a tarball URL, or an absolute local directory.', + 'already-installed': 'The package is already installed; to install another version, call remove_bundle first, then install_bundle again.', + 'ambiguous-install': 'The dependency change named no single package; call list_bundles to see what was installed.', + 'not-bundle': 'The package declares no dsh.bundle and cannot be managed as a plugin; install a DSH plugin bundle instead.', + 'not-removable': 'Call list_bundles; only bundles marked removable can be removed.', + 'stop-profile': 'This profile runs without HMR; tell the user to stop DSH and run `dsh plugin --profile remove `.', + 'bundle-in-use': 'Call list_plugins, disable the entries from other layers that still use this bundle, then retry.', + 'stale-approval': 'Call install_bundle again without approvedBuilds to read the current pendingBuilds.', + 'incompatible-version': 'Install a version compatible with the running DSH. A version exemption needs the user\'s explicit acceptance of crash and data-loss risk.', + 'operation-error': 'Report the diagnostic to the user; retry only after its cause is addressed.', +} + +/** What the model does next for each package-manager failure. */ +const FAILURE_STEPS: Partial> = { + 'pnpm-missing': 'pnpm is not available to DSH; tell the user to install pnpm.', + 'timeout': 'Retry, or retry with another registry.', + 'not-found': 'Check the package name and version with the user, then retry.', + 'no-matching-version': 'Retry with a published version.', + 'network': 'Retry later or pass another registry.', + 'disk-full': 'Tell the user to free disk space, then retry.', + 'permission': 'Tell the user DSH cannot write the profile directory; retry after they fix its permissions.', + 'build-blocked': 'Ask the user whether to allow the install scripts of the packages in pendingBuilds; if they approve, retry with approvedBuilds.', +} + +/** Why a change waits for a restart, as the model tells the user. */ +const RESTART_STEPS: Record = { + 'no-hmr': 'this profile applies changes only at startup', + 'package-moved': 'an installed package now resolves to another directory, or the change replaces a package the DSH installation provides; remove a package before installing it from another location', + 'host-module': 'the change reaches modules DSH itself loaded', + 'unmanaged-plugin': 'the change reaches a plugin running outside the plugin list', + 'module-comparison': 'DSH could not compare loaded plugins with their files', +} + +/** + * The model-facing result of a change: the manager's result plus the next step its outcome calls for. + * @param result The manager's result. + * @returns The result with `nextStep` when it is not plainly applied. + */ +function withNextStep(result: ChangeResult): ChangeResult & { nextStep?: string } { + switch (result.application) { + case 'applied': + return result + case 'cancelled': + return { ...result, nextStep: 'The installation was cancelled and its files restored; nothing changed.' } + case 'overridden': + return { ...result, nextStep: 'Saved, but a higher-priority layer such as the agent preset overrides it; tell the user it is not in effect.' } + case 'restart-required': { + const reason = result.restartReason === undefined ? '' : `: ${RESTART_STEPS[result.restartReason]}` + return { ...result, nextStep: `Tell the user to restart DSH to apply this change${reason}.` } + } + case 'failed': { + const code = result.error?.code ?? 'operation-error' + // A refusal code is more specific than the package manager's failure kind. + const kind = code === 'operation-error' ? result.packageResult?.kind : undefined + return { ...result, nextStep: (kind === undefined ? undefined : FAILURE_STEPS[kind]) ?? ERROR_STEPS[code] } + } + /* v8 ignore next -- ChangeResult.application is a closed union */ + default: return assertNever(result.application) + } +} + /** Required services for the management tool. */ export const inject = ['tools', 'pluginManager', 'sandboxPolicy'] @@ -18,7 +84,7 @@ export const inject = ['tools', 'pluginManager', 'sandboxPolicy'] export function apply(ctx: Context): void { ctx.tools.register(defineTool({ name: 'plugin_manager', - description: 'List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately; startup profiles require restart. Incompatible DSH peer dependencies block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.', + description: 'List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately, including upgrades of installed packages; a change result that is not applied carries nextStep, which says what to do or tell the user. Incompatible DSH peer dependencies block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.', parameters: { action: { type: 'string', required: true, enum: ['list_plugins', 'list_bundles', 'set_plugin', 'set_bundle', 'install_bundle', 'remove_bundle', 'list_version_exemptions', 'set_version_exemption'], description: 'Management operation.' }, target: { type: 'string', description: 'Plugin entry id, bundle package name, or installation spec, according to action. For an Official catalog entry, pass list_bundles installTarget.spec to install_bundle.' }, @@ -50,7 +116,8 @@ export function apply(ctx: Context): void { if (args.target === undefined || args.runtimeVersion === undefined || args.enabled === undefined) { throw new Error('target package-name@version, runtimeVersion, and enabled are required') } - return JSON.stringify(await manager.setVersionExemption(args.target, args.runtimeVersion, args.enabled, args.acceptRisk)) + return JSON.stringify(withNextStep( + await manager.setVersionExemption(args.target, args.runtimeVersion, args.enabled, args.acceptRisk))) case 'list_plugins': case 'list_bundles': { const offset = args.offset ?? 0 @@ -69,20 +136,20 @@ export function apply(ctx: Context): void { case 'set_plugin': case 'set_bundle': { if (args.target === undefined || args.enabled === undefined) throw new Error('target and enabled are required') - return JSON.stringify(await (args.action === 'set_plugin' + return JSON.stringify(withNextStep(await (args.action === 'set_plugin' ? manager.setPluginEnabled(args.target as PluginEntryId, args.enabled) - : manager.setBundleEnabled(args.target, args.enabled))) + : manager.setBundleEnabled(args.target, args.enabled)))) } case 'install_bundle': if (args.target === undefined) throw new Error('target package spec is required') - return JSON.stringify(await manager.installBundle(args.target, { + return JSON.stringify(withNextStep(await manager.installBundle(args.target, { ...args.enabled === undefined ? {} : { enabled: args.enabled }, ...args.approvedBuilds === undefined ? {} : { approvedBuilds: args.approvedBuilds }, ...args.registry === undefined ? {} : { registry: args.registry }, - })) + }))) case 'remove_bundle': if (args.target === undefined) throw new Error('target bundle name is required') - return JSON.stringify(await manager.removeBundle(args.target)) + return JSON.stringify(withNextStep(await manager.removeBundle(args.target))) /* v8 ignore next -- tool JSON validation rejects actions outside the declared enum */ default: return assertNever(args.action) } diff --git a/packages/boot/plugin-manager/src/types.ts b/packages/boot/plugin-manager/src/types.ts index 725d146c3f..15e808e198 100644 --- a/packages/boot/plugin-manager/src/types.ts +++ b/packages/boot/plugin-manager/src/types.ts @@ -1,12 +1,12 @@ /** Public plugin management records shared with clients. */ import type { Branded } from '@deepseek-ai/dsh-brand' import type { PluginLocalizedMeta } from '@deepseek-ai/dsh-package-manifest' -import type { PluginInventoryEntry, AgentPresetPluginRow } from '@deepseek-ai/dsh-host-plugin-inventory/types' +import type { PluginInventoryEntry } from '@deepseek-ai/dsh-host-plugin-inventory/types' export type { PluginEntryId } from '@deepseek-ai/dsh-host-plugin-inventory/types' import type { PluginEntryId } from '@deepseek-ai/dsh-host-plugin-inventory/types' /** Reasons a profile control cannot modify its target. */ -export type ReadOnlyReason = 'management-required' | 'unaddressable' | 'preset-managed' +export type ReadOnlyReason = 'management-required' | 'unaddressable' /** A package whose declared DSH peers reject the running DSH version, without an exemption for the exact pair. */ export interface IncompatiblePlugin { @@ -19,12 +19,21 @@ export interface IncompatiblePlugin { /** Localizable management failure and optional external diagnostic. */ export interface ManagementError { - code: ReadOnlyReason | 'unknown-plugin' | 'invalid-spec' | 'ambiguous-install' | 'not-bundle' | 'not-removable' | 'stop-profile' | 'bundle-in-use' | 'stale-approval' | 'incompatible-version' | 'operation-error' + code: ReadOnlyReason | 'unknown-plugin' | 'invalid-spec' | 'already-installed' | 'ambiguous-install' | 'not-bundle' | 'not-removable' | 'stop-profile' | 'bundle-in-use' | 'stale-approval' | 'incompatible-version' | 'operation-error' diagnostic?: string /** Present with `incompatible-version`: the packages the running DSH version rejects. */ incompatible?: IncompatiblePlugin[] } +/** + * Why a change waits for the next start: `no-hmr` profiles apply changes only at startup; `package-moved` changes map an + * installed package to another directory without removing it first, or change or locally override a package the DSH + * installation provides; `host-module` changes reach + * modules the running process itself imports; `unmanaged-plugin` changes reach a plugin running outside a Loader entry; + * `module-comparison` means loaded modules could not be compared with disk. + */ +export type RestartReason = 'no-hmr' | 'package-moved' | 'host-module' | 'unmanaged-plugin' | 'module-comparison' + /** One running-profile entry and its persistent control availability. */ export type PluginInfo = PluginInventoryEntry & ( | { patchId: string; readOnlyReason?: never } @@ -33,14 +42,8 @@ export type PluginInfo = PluginInventoryEntry & ( /** One row a bundle's patch declares, with its live entry while the bundle contributes it. */ export interface BundleRowInfo { - /** Declared row id, or an internal identity for an anonymous scoped insertion. */ + /** The row id as the patch declares it. */ rowId: string - /** Outer preset row id; together with rowId identifies a scoped declaration. */ - preset?: string - /** Why direct row controls are unavailable; scoped rows are configured through their preset or bundle. */ - readOnlyReason?: ReadOnlyReason - /** Current preset composition state; scoped rows have no editable root Loader entry. */ - composition?: Pick /** The module the row names. */ moduleName: string /** Local package display metadata, including rows whose bundle is disabled. */ @@ -129,6 +132,8 @@ export interface ChangeResult { changed: boolean /** `cancelled` is an installation the caller stopped, its files restored. */ application: 'applied' | 'restart-required' | 'overridden' | 'failed' | 'cancelled' + /** Present with `restart-required`: why the change takes effect only at the next start. */ + restartReason?: RestartReason /** Last attempted step; successful installation can proceed to enablement. */ stage: 'install' | 'enable' | 'remove' target: string diff --git a/packages/boot/plugin-manager/tests/bundle-rows.spec.ts b/packages/boot/plugin-manager/tests/bundle-rows.spec.ts deleted file mode 100644 index e65959f8d5..0000000000 --- a/packages/boot/plugin-manager/tests/bundle-rows.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -/** Declaration identity and module ownership before activating a bundle. */ -import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' -import { expect, it, onTestFinished } from 'vitest' -import { Context } from '@deepseek-ai/cordis' -import { PluginPackages } from '@deepseek-ai/dsh-app-boot' -import { bundleDeclarations, bundleModuleOwner } from '../src/bundle-rows.ts' - -it('reads nested declarations without requiring their target profile or preset', () => { - const row = { id: 'child', name: './child.mjs' } - expect(bundleDeclarations([ - { id: 'absent-group', insert: [row] }, - { preset: 'absent-preset', insert: [{ id: 'group', name: 'cordis:group', group: true, config: [row] }] }, - { preset: 'absent-preset', id: 'other', disabled: true }, - ])).toEqual([ - { row }, - { row: { id: 'group', name: 'cordis:group', group: true, config: [row] }, preset: 'absent-preset' }, - { row, preset: 'absent-preset' }, - ]) -}) - -it('finds canonical owners for bare, relative, absolute, and file URL modules without evaluating them', async () => { - const dir = mkdtempSync(join(tmpdir(), 'bundle-owner-')) - const ctx = new Context() - onTestFinished(async () => { await ctx.fiber.dispose(); rmSync(dir, { recursive: true, force: true }) }) - const packageDir = join(dir, 'node_modules', 'fixture') - mkdirSync(join(packageDir, 'lib'), { recursive: true }) - const manifest = join(packageDir, 'package.json') - writeFileSync(manifest, '{"name":"fixture","version":"1.0.0","exports":"./lib/index.mjs"}\n') - const module = join(packageDir, 'lib', 'index.mjs') - writeFileSync(module, 'throw new Error("must not import ownership probes")\n') - const base = pathToFileURL(join(dir, 'profile.json')).href - await ctx.plugin(PluginPackages) - const expected = realpathSync(manifest) - expect(bundleModuleOwner('fixture', base, ctx.pluginPackages)).toBe(expected) - expect(bundleModuleOwner('fixture/lib/index.mjs', base, ctx.pluginPackages)).toBe(expected) - expect(bundleModuleOwner('./node_modules/fixture/lib/index.mjs', base)).toBe(expected) - expect(bundleModuleOwner(module, base)).toBe(expected) - expect(bundleModuleOwner(pathToFileURL(module).href, base)).toBe(expected) - expect(bundleModuleOwner('cordis:group', base)).toBeUndefined() - expect(bundleModuleOwner('uninstalled', base)).toBeUndefined() - expect(bundleModuleOwner('./absent.mjs', base)).toBeUndefined() - const loose = join(dir, 'loose.mjs') - writeFileSync(loose, '') - expect(bundleModuleOwner(loose, base)).toBeUndefined() - const linked = join(dir, 'linked') - symlinkSync(packageDir, linked, process.platform === 'win32' ? 'junction' : 'dir') - expect(bundleModuleOwner(pathToFileURL(join(linked, 'lib/index.mjs')).href, base)).toBe(expected) - const otherPackage = join(dir, 'other-package') - mkdirSync(otherPackage) - writeFileSync(join(otherPackage, 'package.json'), '{"name":"other-package"}\n') - const otherModule = join(otherPackage, 'foreign.mjs') - writeFileSync(otherModule, 'export function apply() {}\n') - const fileLink = join(packageDir, 'borrowed.mjs') - symlinkSync(otherModule, fileLink, 'file') - expect(bundleModuleOwner(fileLink, base)).toBe(realpathSync(join(otherPackage, 'package.json'))) - -}) diff --git a/packages/boot/plugin-manager/tests/manager.spec.ts b/packages/boot/plugin-manager/tests/manager.spec.ts index 52cd122dce..844d376b26 100644 --- a/packages/boot/plugin-manager/tests/manager.spec.ts +++ b/packages/boot/plugin-manager/tests/manager.spec.ts @@ -458,14 +458,16 @@ it.each([ }) }) -it('turns a plugin off and on without duplicating patch overrides', async () => { +it('turns a plugin off and on without leaving a patch override the bundle already implies', async () => { const { manager, dir } = await fixture() const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId expect(await manager.setPluginEnabled(id, false)).toMatchObject({ changed: true, application: 'applied' }) expect((await manager.listPlugins()).find(row => row.entryId === id)?.enabled).toBe(false) expect(await manager.setPluginEnabled(id, false)).toMatchObject({ changed: false, application: 'applied' }) - expect(await manager.setPluginEnabled(id, true)).toMatchObject({ changed: true, application: 'applied' }) expect(readFileSync(join(dir, 'cordis.patch.yml'), 'utf8').match(/id: managed/g)).toHaveLength(1) + expect(await manager.setPluginEnabled(id, true)).toMatchObject({ changed: true, application: 'applied' }) + expect((await manager.listPlugins()).find(row => row.entryId === id)?.enabled).toBe(true) + expect(readFileSync(join(dir, 'cordis.patch.yml'), 'utf8')).not.toContain('id: managed') }) it('retains installed dependencies when toggling a bundle and appends it when re-enabled', async () => { @@ -481,9 +483,11 @@ it('retains installed dependencies when toggling a bundle and appends it when re }) it('reports an overlay overriding a saved plugin toggle', async () => { - const { manager } = await fixture('live', true) + const { manager, dir } = await fixture('live', true) + writeFileSync(join(dir, 'cordis.patch.yml'), '- id: managed\n disabled: true\n') const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId expect(await manager.setPluginEnabled(id, true)).toMatchObject({ changed: true, application: 'overridden' }) + expect(await manager.setPluginEnabled(id, true)).toMatchObject({ changed: false, application: 'overridden' }) }) it('saves startup-only toggles and refuses removal of currently used packages', async () => { @@ -731,6 +735,7 @@ it.each([ '@deepseek-ai/dsh-host-plugin-inventory', '@deepseek-ai/dsh-typert-registry', '@deepseek-ai/dsh-api-remotes', + '@deepseek-ai/dsh-api-remote-access', ])('protects the management dependency %s and its containing bundle', async (name) => { const { ctx, manager, bundle, profile, dir } = await fixture('startup') bundle('extra', [{ id: 'dependency', name, disabled: true }]) @@ -761,6 +766,7 @@ it('addresses children inside profile groups and marks ambiguous ids read-only', config: [{ id: 'child', name: './plugin.mjs', config: { service: 'child' } }] }]) expect(await manager.setBundleEnabled('grouped', true)).toMatchObject({ application: 'applied' }) expect((await manager.listPlugins()).find(row => row.patchId === 'child')).toBeDefined() + expect((await manager.listBundles()).find(item => item.name === 'grouped')?.rows.map(row => row.rowId)).toEqual(['child']) const entries = composeEntries([readProfilePatches('test', profile)]) const duplicate = entries.find(row => row.id === 'managed')! writeFileSync(profile.patchPath, JSON.stringify([{ insert: [duplicate] }])) @@ -792,14 +798,23 @@ it('restores the manifest when the package pnpm added declares no bundle', async expect((await manager.listBundles()).some(row => row.name === 'plain')).toBe(false) }) -it('never removes an existing dependency after installation validation fails', async () => { +it('refuses to install over an installed package, by name, version or local directory, without running pnpm', async () => { const { manager, dir } = await fixture() - writeFileSync(join(dir, 'node_modules', 'extra', 'package.json'), '{"name":"extra"}') const install = vi.spyOn(operations, 'runProfilePnpm').mockResolvedValue({ exitCode: 0, output: '', truncated: false, logPath: '/operation.log' }) onTestFinished(() => { install.mockRestore() }) - const result = await manager.installBundle('extra') - expect(result).toMatchObject({ application: 'failed', stage: 'install', error: { code: 'not-bundle' } }) - expect(install).toHaveBeenCalledOnce() + for (const spec of ['extra', 'extra@2', join(dir, 'node_modules', 'extra'), `link:${join(dir, 'node_modules', 'extra')}`]) { + expect(await manager.installBundle(spec)).toMatchObject({ application: 'failed', stage: 'install', changed: false, error: { code: 'already-installed' } }) + } + // A tarball saved as a path relative to the profile, and a refused install's script approvals, write nothing. + const manifest = readProfileManifest('test', dir) + writeFileSync(join(dir, 'package.json'), JSON.stringify({ ...manifest, dependencies: { extra: 'file:../extra-1.0.0.tgz' } })) + const workspace = join(dir, 'pnpm-workspace.yaml') + const settings = existsSync(workspace) ? readFileSync(workspace, 'utf8') : undefined + expect(await manager.installBundle(join(dir, '..', 'extra-1.0.0.tgz'), { approvedBuilds: ['native-provider'] })) + .toMatchObject({ application: 'failed', changed: false, error: { code: 'already-installed' } }) + expect(existsSync(workspace) ? readFileSync(workspace, 'utf8') : undefined).toBe(settings) + writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest)) + expect(install).not.toHaveBeenCalled() expect(readProfileManifest('test', dir).dependencies).toEqual({ extra: '1.0.0' }) }) @@ -850,12 +865,18 @@ it('returns unchanged failures as warnings while toggling and removing another b expect(remove).toHaveBeenCalledOnce() }) -it('reports repeated installs as requiring restart and ambiguous package changes as failures', async () => { +it('recognizes a repeated installation without HMR that leaves the saved dependency as it was', async () => { + const { manager, dir } = await fixture('startup') + const install = vi.spyOn(operations, 'runProfilePnpm').mockResolvedValue({ exitCode: 0, output: '', truncated: false, logPath: join(dir, 'pnpm.log') }) + onTestFinished(() => { install.mockRestore() }) + expect(await manager.installBundle(`link:${join(dir, 'node_modules', 'extra')}`, { enabled: false })) + .toMatchObject({ changed: false, application: 'restart-required', bundle: 'extra', enabled: false }) +}) + +it('reports ambiguous package changes as failures', async () => { const { manager, dir } = await fixture() const install = vi.spyOn(operations, 'runProfilePnpm').mockResolvedValue({ exitCode: 0, output: '', truncated: false, logPath: join(dir, 'pnpm.log') }) onTestFinished(() => { install.mockRestore() }) - expect(await manager.installBundle('extra')).toMatchObject({ changed: false, application: 'restart-required' }) - expect(await manager.installBundle('extra@1')).toMatchObject({ changed: false, application: 'restart-required' }) expect(await manager.installBundle('extra-long@1')).toMatchObject({ changed: false, application: 'failed', error: { code: 'ambiguous-install' } }) install.mockImplementationOnce(async () => { writeFileSync(join(dir, 'package.json'), '{}') @@ -865,6 +886,41 @@ it('reports repeated installs as requiring restart and ambiguous package changes expect(readProfileManifest('test', dir).dependencies).toEqual({ extra: '1.0.0' }) }) +it('removes a package with the registry it was installed from, so pnpm verifies its lockfile entries there', async () => { + const { manager, dir, bundle } = await fixture() + const corp = 'https://npm.corp.example/' + const pnpm = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async (_context, args) => { + const name = String(args[1]) + const manifest = readProfileManifest('test', dir) + if (args[0] === 'add') { + bundle(name, [{ id: name, name: './plugin.mjs', config: { service: name } }]) + manifest.dependencies = { ...manifest.dependencies, [name]: '1.0.0' } + } else { + delete manifest.dependencies?.[name] + } + writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest)) + return { exitCode: 0, output: '', truncated: false, logPath: join(dir, 'pnpm.log') } + }) + onTestFinished(() => { pnpm.mockRestore() }) + expect(await manager.installBundle('mirrored', { enabled: false, registry: corp })).toMatchObject({ application: 'applied' }) + expect(await manager.removeBundle('mirrored')).toMatchObject({ application: 'applied' }) + expect(pnpm.mock.calls.at(-1)?.[1]).toEqual(['remove', 'mirrored', `--config.registry=${corp}`]) + // A failed installation records no registry, and a failed removal keeps the recorded one for the retry. + pnpm.mockResolvedValueOnce({ exitCode: 1, output: 'failed', truncated: false, logPath: join(dir, 'pnpm.log') }) + expect(await manager.installBundle('failing', { enabled: false, registry: corp })).toMatchObject({ application: 'failed' }) + expect(await manager.installBundle('mirrored', { enabled: false, registry: corp })).toMatchObject({ application: 'applied' }) + pnpm.mockResolvedValueOnce({ exitCode: 1, output: 'remove failed', truncated: false, logPath: join(dir, 'pnpm.log') }) + expect(await manager.removeBundle('mirrored')).toMatchObject({ application: 'failed' }) + expect(await manager.removeBundle('mirrored')).toMatchObject({ application: 'applied' }) + expect(pnpm.mock.calls.at(-1)?.[1]).toEqual(['remove', 'mirrored', `--config.registry=${corp}`]) + // A package this manager did not install is removed with the registry an installation asks first. + bundle('mirrored', []) + const manifest = readProfileManifest('test', dir) + writeFileSync(join(dir, 'package.json'), JSON.stringify({ ...manifest, dependencies: { ...manifest.dependencies, mirrored: '1.0.0' } })) + await manager.removeBundle('mirrored') + expect(pnpm.mock.calls.at(-1)?.[1]).toEqual(['remove', 'mirrored']) +}) + it('streams pnpm output, reports the installation phases, and names the installed bundle', async () => { const { ctx, manager, dir, bundle } = await fixture() const chunks: PluginInstallLogChunk[] = [] @@ -1522,30 +1578,6 @@ it('uses the generic exact installer and keeps an Official entry through on, off expect((await manager.listBundles()).find(item => item.name === name)).toMatchObject({ official: true, availability: 'missing', enabled: false, installed: false }) }) -it.each([true, false])('updates an Official dependency while preserving selection=%s and requiring restart', async (enabled) => { - const { manager, dir, bundle, profile } = await fixture() - const name = OFFICIAL_ON_DEMAND_CATALOG[0]!.packageName - bundle(name, [], profile.home) - const manifest = readProfileManifest('test', dir) - manifest.dependencies = { ...manifest.dependencies, [name]: '1.0.0' } - if (enabled) manifest.dsh!.profile!.bundles!.push(name) - writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest)) - const listed = (await manager.listBundles()).find(item => item.name === name) - expect(listed).toMatchObject({ version: '1.0.0', official: true, availability: 'profile', - installTarget: { spec: `${name}@${getDshRuntimeVersion()}`, version: getDshRuntimeVersion() } }) - expect(listed?.error).toBeUndefined() - const pnpm = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => { - const current = readProfileManifest('test', dir) - current.dependencies = { ...current.dependencies, [name]: getDshRuntimeVersion() } - writeFileSync(join(dir, 'package.json'), JSON.stringify(current)) - return { exitCode: 0, output: '', truncated: false, logPath: '/install.log' } - }) - onTestFinished(() => { pnpm.mockRestore() }) - expect(await manager.installBundle(`${name}@${getDshRuntimeVersion()}`, { enabled, saveExact: true })) - .toMatchObject({ application: 'restart-required', enabled }) - expect(readProfileManifest('test', dir).dsh?.profile?.bundles?.includes(name)).toBe(enabled) -}) - it('restores dependency and selection after an exact version is unavailable', async () => { const { manager, dir, bundle, profile } = await fixture() const name = OFFICIAL_ON_DEMAND_CATALOG[0]!.packageName @@ -1653,11 +1685,3 @@ it.each(['absent', 'bundle', 'not-bundle', 'unreadable'])('keeps a missing sourc expect((await manager.listBundles()).find(item => item.name === name)?.error?.diagnostic).toContain('restore the checkout') expect((await manager.listBundles()).find(item => item.name === name)?.installTarget).toBeUndefined() }) - -it('recognizes a repeated local link install without a dependency-spec change', async () => { - const { manager, dir } = await fixture() - const install = vi.spyOn(operations, 'runProfilePnpm').mockResolvedValue({ exitCode: 0, output: '', truncated: false, logPath: join(dir, 'pnpm.log') }) - onTestFinished(() => { install.mockRestore() }) - expect(await manager.installBundle(`link:${join(dir, 'node_modules', 'extra')}`, { enabled: false })) - .toMatchObject({ changed: false, application: 'restart-required', bundle: 'extra', enabled: false }) -}) diff --git a/packages/boot/plugin-manager/tests/operation-logs.spec.ts b/packages/boot/plugin-manager/tests/operation-logs.spec.ts new file mode 100644 index 0000000000..a7a19367ab --- /dev/null +++ b/packages/boot/plugin-manager/tests/operation-logs.spec.ts @@ -0,0 +1,48 @@ +/** Pnpm diagnostics release their real file descriptor when preparation rejects. */ +import { fstatSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import type { FileHandle } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import { initProfile } from '@deepseek-ai/dsh-app-boot' +import { runProfilePnpm } from '../src/operations.ts' + +const observed = vi.hoisted(() => { + const logs: Array<{ handle: FileHandle; fd: number }> = [] + return { logs } +}) + +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + open: async (...args: Parameters) => { + const handle = await actual.open(...args) + if (typeof args[0] === 'string' && args[0].endsWith('pnpm.log')) { + observed.logs.push({ handle, fd: handle.fd }) + } + return handle + }, + } +}) + +it('closes the pnpm log when the profile manifest cannot be parsed', async () => { + const home = mkdtempSync(join(tmpdir(), 'manager-log-lifetime-')) + onTestFinished(async () => { + for (const { handle } of observed.logs.splice(0)) await handle.close() + rmSync(home, { recursive: true, force: true }) + }) + const dir = join(home, 'profiles', 'test') + const installAnchor = join(home, 'package.json') + writeFileSync(installAnchor, '{}\n') + initProfile(dir, []) + writeFileSync(join(dir, 'package.json'), '{') + + await expect(runProfilePnpm({ home, profile: 'test', installAnchor, cwd: home }, ['install'], { + execution: 'service', outputBytes: 100, activateNewBundles: false, + })).rejects.toThrow(SyntaxError) + + expect(observed.logs).toHaveLength(1) + const { fd } = observed.logs[0]! + expect(() => fstatSync(fd)).toThrow(expect.objectContaining({ code: 'EBADF' })) +}) diff --git a/packages/boot/plugin-manager/tests/operations.spec.ts b/packages/boot/plugin-manager/tests/operations.spec.ts index f9aa34314c..9a062e8af9 100644 --- a/packages/boot/plugin-manager/tests/operations.spec.ts +++ b/packages/boot/plugin-manager/tests/operations.spec.ts @@ -471,7 +471,7 @@ it.each(['devDependencies', 'optionalDependencies'])('checks installed direct pl expect(await runProfilePnpm(context, ['install'], { execution: 'service', outputBytes: 8192 })).toMatchObject({ exitCode: 1 }) }) -it.each([undefined, 'preset-standard'])('rejects an incompatible component contributed to %s by a newly installed bundle', async (preset) => { +it('rejects an incompatible component declared by a newly installed bundle', async () => { const { dir, context, pnpm } = fixture() pnpm.mutate = (target) => { install(target, 'bundle') @@ -481,16 +481,7 @@ it.each([undefined, 'preset-standard'])('rejects an incompatible component contr writeFileSync(join(component, 'package.json'), JSON.stringify({ name: 'component', version: '1.0.0', peerDependencies: { '@deepseek-ai/dsh': '>=999.0.0' }, })) - const unrelated = join(target, 'node_modules', 'component') - mkdirSync(unrelated, { recursive: true }) - writeFileSync(join(unrelated, 'package.json'), JSON.stringify({ name: 'component', version: '2.0.0' })) - mkdirSync(join(packageDir, 'nested')) - writeFileSync(join(packageDir, 'nested', 'group.mjs'), 'export function apply() {}\n') - writeFileSync(join(packageDir, 'cordis.patch.yml'), JSON.stringify([{ - ...preset === undefined ? {} : { preset }, insert: [{ id: 'relative-group', name: './nested/group.mjs', group: true, - config: [{ id: 'component', name: 'component/subpath' }], - }], - }])) + writeFileSync(join(packageDir, 'cordis.patch.yml'), '- insert:\n - id: component\n name: component/subpath\n') } const outcome = await runProfilePnpm(context, ['add', 'bundle'], { execution: 'service', outputBytes: 8192, activateNewBundles: false }) expect(outcome.exitCode).toBe(1) @@ -512,7 +503,7 @@ it('restores the manifest on malformed installed peer metadata and bounds the wa expect(readFileSync(join(dir, 'package.json'), 'utf8')).toBe(before) }) -it('validates nested preset contributions without requiring their target preset to be selected', async () => { +it('checks scoped components in nested groups while leaving unresolved and local rows to startup', async () => { const { context, pnpm } = fixture() pnpm.mutate = (target) => { install(target, 'bundle') @@ -520,7 +511,7 @@ it('validates nested preset contributions without requiring their target preset const component = join(packageDir, 'node_modules', '@example', 'component') mkdirSync(component, { recursive: true }) writeFileSync(join(component, 'package.json'), JSON.stringify({ name: '@example/component', version: '1.0.0' })) - writeFileSync(join(packageDir, 'cordis.patch.yml'), JSON.stringify([{ preset: 'preset-standard', insert: [ + writeFileSync(join(packageDir, 'cordis.patch.yml'), JSON.stringify([{ insert: [ { id: 'group', group: true, config: [{ id: 'component', name: '@example/component/subpath' }] }, { id: 'empty-group', group: true, config: {} }, { id: 'relative', name: './plugin.mjs' }, diff --git a/packages/boot/plugin-manager/tests/package-reload.spec.ts b/packages/boot/plugin-manager/tests/package-reload.spec.ts index d83aab3be3..b5569a6229 100644 --- a/packages/boot/plugin-manager/tests/package-reload.spec.ts +++ b/packages/boot/plugin-manager/tests/package-reload.spec.ts @@ -1,14 +1,15 @@ /** GUI package operations publish profile package resolution around activation and disposal through the real Loader. */ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' import { join } from 'node:path' import { pathToFileURL } from 'node:url' -import { FiberState, type Context } from '@deepseek-ai/cordis' +import { FiberState, type Context, type Plugin } from '@deepseek-ai/cordis' import Timer from '@deepseek-ai/cordis-plugin-timer' import { - boot, createRuntimeResolution, initProfile, loadProfileDirectory, PluginPackages, + boot, createRuntimeResolution, initProfile, loadProfileDirectory, PluginPackages, ProfileRuntimeResolution, readProfileManifest, readProfilePatches, type ProfileContext, + ResolutionRestartRequired, } from '@deepseek-ai/dsh-app-boot' import Hmr from '@deepseek-ai/dsh-hmr' import type { ChokidarOptions } from 'chokidar' @@ -160,6 +161,12 @@ export function apply(ctx) { } /** Answer each pnpm run by recording it in the trace and applying `run` to the profile files. */ +/** Remove the installed addon bundle, as an upgrade does before it installs another version. */ +async function removeAddon(manager: PluginManager, dir: string, trace: string[]): Promise { + mockPnpm(dir, trace, () => { removeFiles(dir) }) + expect(await manager.removeBundle('addon')).toMatchObject({ application: 'applied' }) +} + function mockPnpm(dir: string, trace: string[], run: (args: readonly string[]) => void, exitCode = 0) { const pnpm = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async (_context, args) => { trace.push(`pnpm:${String(args[0])}`) @@ -187,6 +194,11 @@ it('publishes a newly installed enabled bundle before its private bare plugin st expect(ctx.get('addonVersion')).toBe(1) expect(ctx.pluginPackages.packageOf('addon-plugin', parentURL)?.version).toBe('1.0.0') expect(readFileSync(evaluationPath, 'utf8')).toBe('addon:1\n') + // A failure without HMR carries no restart reason. + mockPnpm(dir, trace, () => {}, 1) + const failed = await manager.installBundle('addon@3', { enabled: true }) + expect(failed).toMatchObject({ application: 'failed' }) + expect(failed).not.toHaveProperty('restartReason') }) it('publishes a newly installed disabled bundle without evaluating its plugin', async () => { @@ -296,8 +308,9 @@ it.each(['disable', 'remove'] as const)('retains a shared dependency after %s of const result = operation === 'disable' ? await manager.setBundleEnabled('addon', false) : await manager.removeBundle('addon') expect(result).toMatchObject({ application: 'applied', changed: true }) - expect(published).toHaveBeenCalledOnce() - expect(published.mock.calls[0]?.[0].entries.find(item => item.name === 'addon-plugin')).toMatchObject({ + // A removal publishes when its plugins stopped, and again once pnpm removed the package. + expect(published).toHaveBeenCalledTimes(operation === 'disable' ? 1 : 2) + expect(published.mock.calls.at(-1)?.[0].entries.find(item => item.name === 'addon-plugin')).toMatchObject({ packageDir: sharedDir, version: '1.0.0', scope: 'profile', declarer: join(dir, 'node_modules', 'other', 'package.json'), }) expect(entry()).toBeUndefined() @@ -321,8 +334,9 @@ it('removes a running bundle after its plugin stops and then publishes', async ( application: 'applied', changed: true, packageResult: { exitCode: 0 }, }) expect(pnpm).toHaveBeenCalledOnce() - expect(published).toHaveBeenCalledOnce() - expect(trace).toEqual(['start:sibling', 'start:addon:1', 'stop:addon:1', 'pnpm:remove', 'publish']) + // The bundle's private mappings go once its plugin stopped; the package's own name goes after pnpm removed it. + expect(published).toHaveBeenCalledTimes(2) + expect(trace).toEqual(['start:sibling', 'start:addon:1', 'stop:addon:1', 'publish', 'pnpm:remove', 'publish']) expect(previous?.uid).toBeNull() expect(existsSync(bundleDir)).toBe(false) expect(ctx.pluginPackages.packageOf('addon', parentURL)).toBeUndefined() @@ -356,23 +370,183 @@ it('removes and publishes a bundle that is not running without HMR', async () => expect(ctx.get('packageReloadSibling')).toBe(sibling) }) -it.each([{ live: true }, { live: false }])('keeps the running version and publishes nothing when an installed bundle is overwritten with HMR=$live', async ({ live }) => { - const { ctx, dir, trace, published, manager, evaluationPath, entry } = await fixture({ live, installed: true }) - const previous = entry()?.fiber - expect(previous?.state).toBe(FiberState.ACTIVE) - expect(ctx.get('addonVersion')).toBe(1) - mockPnpm(dir, trace, (args) => { - expect(args.slice(0, 2)).toEqual(['add', 'addon@2']) - installFiles(dir, 2) - }) +it('refuses to overwrite an installed bundle, and installs another version once it is removed', async () => { + const { ctx, dir, trace, manager, evaluationPath, entry } = await fixture({ installed: true }) + const pnpm = mockPnpm(dir, trace, () => { installFiles(dir, 2) }) + expect(await manager.installBundle('addon@2', { enabled: true })) + .toMatchObject({ application: 'failed', changed: false, error: { code: 'already-installed' } }) + expect(pnpm).not.toHaveBeenCalled() + await removeAddon(manager, dir, trace) + mockPnpm(dir, trace, () => { installFiles(dir, 2) }) + expect(await manager.installBundle('addon@2', { enabled: true })).toMatchObject({ application: 'applied', changed: true }) + expect(trace).toEqual(['start:sibling', 'start:addon:1', 'stop:addon:1', 'publish', 'pnpm:remove', 'publish', 'pnpm:add', 'publish', 'start:addon:2']) + expect(entry()?.fiber?.state).toBe(FiberState.ACTIVE) + expect(ctx.get('addonVersion')).toBe(2) + expect(readFileSync(evaluationPath, 'utf8')).toBe('addon:1\naddon:2\n') +}) - expect(await manager.installBundle('addon@2', { enabled: true })).toMatchObject({ application: 'restart-required', changed: true }) +it('reports the load error when a reinstalled version fails to load', async () => { + const { ctx, dir, trace, manager, entry } = await fixture({ installed: true }) + await removeAddon(manager, dir, trace) + mockPnpm(dir, trace, () => { + installFiles(dir, 2) + writeFileSync(join(dir, 'node_modules', 'addon', 'node_modules', 'addon-plugin', 'plugin.mjs'), "import 'missing-lib'\n") + }) + const result = await manager.installBundle('addon@2', { enabled: true }) + expect(result).toMatchObject({ application: 'failed', changed: true, error: { code: 'operation-error', + diagnostic: expect.stringMatching(/failed to import: .*'missing-lib'/u) as string } }) + expect(entry()?.fiber?.uid).toBeFalsy() + expect(ctx.get('addonVersion')).toBeUndefined() +}) + +/** Write a linkable bundle source and return the package directory an installation spec names. */ +function linkSource(source: string, version: number): string { + writeBundle(source, version) + return join(source, 'node_modules', 'addon') +} + +/** Link the profile's addon dependency to a source directory, as a local directory install does. */ +function linkTo(dir: string, source: string, version: number): void { + writeBundle(source, version) + rmSync(join(dir, 'node_modules', 'addon'), { recursive: true, force: true }) + symlinkSync(join(source, 'node_modules', 'addon'), join(dir, 'node_modules', 'addon'), process.platform === 'win32' ? 'junction' : 'dir') + const manifest = readProfileManifest('test', dir) + manifest.dependencies = { ...manifest.dependencies, addon: `link:${source}` } + writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest)) +} + +it('starts a plugin relinked to another directory without a restart', async () => { + const { ctx, dir, trace, manager } = await fixture({ installed: true }) + // Sources outside the profiles tree are linked roots, whose targets the resolution records. + const work = mkdtempSync(join(tmpdir(), 'plugin-manager-relink-')) + onTestFinished(() => { rmSync(work, { recursive: true, force: true }) }) + await removeAddon(manager, dir, trace) + mockPnpm(dir, trace, () => { linkTo(dir, join(work, 'source-2'), 2) }) + expect(await manager.installBundle(linkSource(join(work, 'source-2'), 2), { enabled: true })).toMatchObject({ application: 'applied' }) + expect(ctx.get('addonVersion')).toBe(2) + // Removing the bundle stops its plugins and evicts the previous directory, so the next link target is published. + trace.length = 0 + await removeAddon(manager, dir, trace) + mockPnpm(dir, trace, () => { linkTo(dir, join(work, 'source-3'), 3) }) + expect(await manager.installBundle(linkSource(join(work, 'source-3'), 3), { enabled: true })).toMatchObject({ application: 'applied', changed: true }) + expect(trace).toEqual(['stop:addon:2', 'publish', 'pnpm:remove', 'publish', 'pnpm:add', 'publish', 'start:addon:3']) + expect(ctx.get('addonVersion')).toBe(3) +}) + +it('starts a registry installation of a package that was linked before', async () => { + const { ctx, dir, trace, manager } = await fixture({ installed: true }) + await removeAddon(manager, dir, trace) + mockPnpm(dir, trace, () => { linkTo(dir, join(dir, '..', 'addon-source-2'), 2) }) + expect(await manager.installBundle(linkSource(join(dir, '..', 'addon-source-2'), 2), { enabled: true })).toMatchObject({ application: 'applied' }) + trace.length = 0 + await removeAddon(manager, dir, trace) + mockPnpm(dir, trace, () => { installFiles(dir, 3) }) + expect(await manager.installBundle('addon@3', { enabled: true })).toMatchObject({ application: 'applied', changed: true }) + expect(trace).toEqual(['stop:addon:2', 'publish', 'pnpm:remove', 'publish', 'pnpm:add', 'publish', 'start:addon:3']) + expect(ctx.get('addonVersion')).toBe(3) +}) + +it('stops nothing before installing a directory without a readable manifest', async () => { + const { dir, trace, manager } = await fixture({ installed: true }) + mockPnpm(dir, trace, () => {}, 1) + trace.length = 0 + expect(await manager.installBundle(join(dir, '..', 'missing-source'))).toMatchObject({ application: 'failed' }) + expect(trace).not.toContain('stop:addon:1') +}) + +it('starts a bundle reinstalled from another link target while a plugin outside a Loader entry keeps the previous one', async () => { + const { ctx, dir, trace, manager } = await fixture({ installed: true }) + const source = join(dir, '..', 'addon-source-2') + await removeAddon(manager, dir, trace) + mockPnpm(dir, trace, () => { linkTo(dir, source, 2) }) + expect(await manager.installBundle(linkSource(source, 2), { enabled: true })).toMatchObject({ application: 'applied' }) + const extra = join(realpathSync(source), 'node_modules', 'addon', 'extra.mjs') + writeFileSync(extra, "export function apply(ctx) { ctx.get('packageReloadTrace')?.push('start:extra') }\n") + // A file written before HMR's last observation is not suspected of changing after it loaded. + utimesSync(extra, new Date(Date.now() - 3_600_000), new Date(Date.now() - 3_600_000)) + await ctx.plugin(ctx.loader.unwrapExports(await ctx.loader.import(pathToFileURL(extra).href)) as Plugin) + await removeAddon(manager, dir, trace) + trace.length = 0 + mockPnpm(dir, trace, () => { linkTo(dir, join(dir, '..', 'addon-source-3'), 3) }) + // Plugins outside a Loader entry are the caller's; the reinstalled bundle starts from the new link target. + expect(await manager.installBundle(linkSource(join(dir, '..', 'addon-source-3'), 3), { enabled: true })) + .toMatchObject({ application: 'applied', changed: true }) + expect(trace).toEqual(['pnpm:add', 'publish', 'start:addon:3']) +}) + +it('restores a disable whose publication waits for a restart and reports other publication failures', async () => { + const { ctx, trace, manager } = await fixture({ installed: true }) + // Another package's link points elsewhere since the last publication, so the next one is rejected. + const current = ctx.pluginPackages.resolution as ProfileRuntimeResolution + const next = await current.computeLatestResolution() + const relinked = vi.spyOn(ProfileRuntimeResolution.prototype, 'computeLatestResolution').mockResolvedValueOnce(new ProfileRuntimeResolution( + { installAnchor: '', home: '', profileDir: undefined }, + { profilesDir: next.profilesDir, profileDir: next.profileDir, localPackageNames: next.localPackageNames, entries: next.entries, + linkedRoots: [...next.linkedRoots, { name: 'other', realPath: '/elsewhere' }] }, + )) + onTestFinished(() => { relinked.mockRestore() }) + const packages = ctx.pluginPackages + const replace = packages.replace.bind(packages) + const blocked = vi.spyOn(packages, 'replace').mockImplementation((successor) => { + if (successor.linkedRoots.some(root => root.name === 'other')) throw new ResolutionRestartRequired('installation mapping changed') + replace(successor) + }) + onTestFinished(() => { blocked.mockRestore() }) + // The bundle's plugins stop before the publication and start again once it is rejected. + trace.length = 0 + const disabled = await manager.setBundleEnabled('addon', false) + expect(disabled).toMatchObject({ application: 'restart-required', restartReason: 'package-moved' }) + expect(trace).toEqual(['stop:addon:1', 'start:addon:1']) + blocked.mockRestore() + const latest = vi.spyOn(ProfileRuntimeResolution.prototype, 'computeLatestResolution').mockRejectedValueOnce(new Error('resolution unreadable')) + onTestFinished(() => { latest.mockRestore() }) + expect(await manager.setBundleEnabled('addon', false)) + .toMatchObject({ application: 'failed', error: { code: 'operation-error', diagnostic: 'resolution unreadable' } }) +}) + +it('requires a restart when a reinstalled plugin also runs outside a Loader entry', async () => { + const { ctx, dir, trace, manager } = await fixture({ installed: true, enabled: false }) + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + const url = pathToFileURL(join(dir, 'node_modules', 'addon', 'node_modules', 'addon-plugin', 'plugin.mjs')).href + await ctx.plugin(ctx.loader.unwrapExports(await ctx.loader.import(url)) as Plugin) + // Removing the files of a plugin that keeps running outside a Loader entry waits for a restart too. + mockPnpm(dir, trace, () => { removeFiles(dir) }) + expect(await manager.removeBundle('addon')).toMatchObject({ application: 'restart-required', restartReason: 'unmanaged-plugin' }) + mockPnpm(dir, trace, () => { installFiles(dir, 2) }) + expect(await manager.installBundle('addon@2', { enabled: false })) + .toMatchObject({ application: 'restart-required', restartReason: 'unmanaged-plugin', changed: true }) + expect(ctx.get('addonVersion')).toBe(1) +}) + +it('keeps the no-HMR restart when publishing the resolution needs a restart, and fails on other publication errors', async () => { + const { ctx, dir, trace, manager } = await fixture({ live: false }) + const refresh = vi.spyOn(ctx.pluginPackages, 'refresh') + .mockRejectedValueOnce(new ResolutionRestartRequired('moved')) + .mockRejectedValueOnce(new Error('resolution unreadable')) + onTestFinished(() => { refresh.mockRestore() }) + mockPnpm(dir, trace, () => { installFiles(dir, 1) }) + expect(await manager.installBundle('addon')).toMatchObject({ application: 'restart-required', restartReason: 'no-hmr' }) + mockPnpm(dir, trace, () => { removeFiles(dir) }) + expect(await manager.removeBundle('addon')).toMatchObject({ application: 'failed', error: { diagnostic: 'resolution unreadable' } }) +}) + +it('requires a restart when a tarball whose package is known only after installation replaces an installed bundle without HMR', async () => { + const { dir, trace, manager } = await fixture({ live: false, installed: true }) + const tarball = join(dir, '..', 'addon-2.tgz') + writeFileSync(tarball, '') + mockPnpm(dir, trace, () => { installFiles(dir, 2) }) + expect(await manager.installBundle(tarball, { enabled: true })) + .toMatchObject({ application: 'restart-required', restartReason: 'no-hmr', bundle: 'addon', changed: true }) +}) + +it('installs over an installed bundle without HMR and keeps the running version until the restart', async () => { + const { ctx, dir, trace, published, manager } = await fixture({ live: false, installed: true }) + mockPnpm(dir, trace, () => { installFiles(dir, 2) }) + expect(await manager.installBundle('addon@2', { enabled: true })) + .toMatchObject({ application: 'restart-required', restartReason: 'no-hmr', changed: true }) expect(published).not.toHaveBeenCalled() - expect(trace).toEqual(['start:sibling', 'start:addon:1', 'pnpm:add']) - expect(entry()?.fiber).toBe(previous) - expect(previous?.state).toBe(FiberState.ACTIVE) expect(ctx.get('addonVersion')).toBe(1) - expect(readFileSync(evaluationPath, 'utf8')).toBe('addon:1\n') }) it('publishes nothing after installation fails', async () => { @@ -392,21 +566,26 @@ it('publishes nothing after installation fails', async () => { it.each(['install', 'remove'] as const)('keeps successful %s disk changes when resolution publication fails', async (operation) => { const { ctx, dir, trace, published, manager, parentURL, entry } = await fixture({ installed: operation === 'remove' }) - const previous = ctx.pluginPackages.packageOf('addon-plugin', parentURL) mockPnpm(dir, trace, () => { if (operation === 'install') installFiles(dir, 1); else removeFiles(dir) }) - published.mockImplementation(() => { throw new Error('publication rejected') }) + const publish = published.getMockImplementation() + // Removal publishes once its plugins stopped and again after pnpm removed the package; the second publication fails. + published.mockImplementation((successor) => { + if (operation === 'install' || trace.includes('pnpm:remove')) throw new Error('publication rejected') + publish?.(successor) + }) const result = operation === 'install' ? await manager.installBundle('addon') : await manager.removeBundle('addon') expect(result).toMatchObject({ application: 'failed', changed: true, error: { diagnostic: 'publication rejected' }, packageResult: { exitCode: 0 }, }) - expect(published).toHaveBeenCalledOnce() + expect(published).toHaveBeenCalledTimes(operation === 'install' ? 1 : 2) const manifest = readProfileManifest('test', dir) expect(manifest.dependencies).toEqual(operation === 'install' ? { addon: '1.0.0' } : {}) expect(manifest.dsh?.profile?.bundles).toEqual(operation === 'install' ? ['core', 'addon'] : ['core']) expect(existsSync(join(dir, 'node_modules', 'addon'))).toBe(operation === 'install') - expect(ctx.pluginPackages.packageOf('addon-plugin', parentURL)).toBe(previous) + // A removal publishes the bundle's private mappings away once its plugins stopped. + expect(ctx.pluginPackages.packageOf('addon-plugin', parentURL)).toBeUndefined() expect(entry()).toBeUndefined() }) @@ -455,3 +634,19 @@ it('publishes a newly installed bundle without HMR and leaves its activation to expect(ctx.get('addonVersion')).toBeUndefined() expect(existsSync(evaluationPath)).toBe(false) }) + + +it('reports restart-required when a reinstallation cannot compare the loaded module files', async () => { + const { ctx, dir, trace, manager } = await fixture({ installed: true }) + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + await removeAddon(manager, dir, trace) + mockPnpm(dir, trace, () => { + installFiles(dir, 2) + writeFileSync(join(dir, 'node_modules', '@broken'), '') + }) + const result = await manager.installBundle('addon@2', { enabled: true }) + expect(result).toMatchObject({ application: 'restart-required', restartReason: 'module-comparison' }) + expect(ctx.get('addonVersion')).toBe(2) + expect(warn).toHaveBeenCalledWith(expect.objectContaining({ code: 'ENOTDIR' })) +}) diff --git a/packages/boot/plugin-manager/tests/patch.spec.ts b/packages/boot/plugin-manager/tests/patch.spec.ts index a51c544d2f..9580da1e52 100644 --- a/packages/boot/plugin-manager/tests/patch.spec.ts +++ b/packages/boot/plugin-manager/tests/patch.spec.ts @@ -4,85 +4,83 @@ import { join } from 'node:path' import { tmpdir } from 'node:os' import { expect, it, onTestFinished } from 'vitest' import { applyEntryPatches } from '@deepseek-ai/cordis-plugin-include' -import { loadOptionalPatches } from '@deepseek-ai/dsh-app-boot' +import { initProfile, loadOptionalPatches, type ProfileContext } from '@deepseek-ai/dsh-app-boot' import { writePluginEnabled } from '../src/patch.ts' -async function fixture(text?: string): Promise { - const dir = await mkdtemp(join(tmpdir(), 'manager-patch-')) - onTestFinished(() => rm(dir, { recursive: true, force: true })) - const file = join(dir, 'cordis.patch.yml') - if (text !== undefined) await writeFile(file, text) - return file +const TOOL = { id: 'tool', name: 'package' } + +/** Create a profile whose patch file holds `text` (none when omitted) and whose one selected bundle inserts `rows`. */ +async function fixture(text?: string, rows: object[] = []): Promise { + const home = await mkdtemp(join(tmpdir(), 'manager-patch-')) + onTestFinished(() => rm(home, { recursive: true, force: true })) + const dir = join(home, 'profile') + const installAnchor = join(home, 'package.json') + await writeFile(installAnchor, '{"name":"installation","dependencies":{}}') + initProfile(dir, ['bundle']) + const bundle = join(dir, 'node_modules', 'bundle') + await mkdir(bundle, { recursive: true }) + await writeFile(join(bundle, 'package.json'), JSON.stringify({ name: 'bundle', version: '1.0.0', dsh: { bundle: { patch: './cordis.patch.yml' } } })) + await writeFile(join(bundle, 'cordis.patch.yml'), JSON.stringify([{ insert: rows }])) + const patchPath = join(dir, 'cordis.patch.yml') + await (text === undefined ? rm(patchPath) : writeFile(patchPath, text)) + return { name: 'test', dir, patchPath, installAnchor, cwd: home, home, startedBundles: ['bundle'], overlays: [], telemetryDisabledEnv: undefined } } it('preserves comments, expressions, unrelated configuration and the last override', async () => { - const file = await fixture('# personal configuration\n- id: tool\n config:\n value: !!js process.platform\n- id: tool\n disabled: false # availability\n') - expect(await writePluginEnabled(file, 'tool', 'package', false)).toBe(true) - const text = await readFile(file, 'utf8') + const profile = await fixture('# personal configuration\n- id: tool\n config:\n value: !!js process.platform\n- id: tool\n disabled: false # availability\n') + expect(await writePluginEnabled(profile, 'tool', 'package', false)).toBe(true) + const text = await readFile(profile.patchPath, 'utf8') expect(text).toContain('# personal configuration') expect(text).toContain('!!js process.platform') expect(text).toContain('# availability') - expect(loadOptionalPatches('test', file)).toEqual([ + expect(loadOptionalPatches('test', profile.patchPath)).toEqual([ { id: 'tool', config: { value: { __jsExpr: 'process.platform' } } }, { id: 'tool', disabled: true }, ]) - expect(await writePluginEnabled(file, 'tool', 'package', false)).toBe(false) - expect(await readFile(file, 'utf8')).toBe(text) - expect(await writePluginEnabled(file, 'tool', 'package', true)).toBe(true) + expect(await writePluginEnabled(profile, 'tool', 'package', false)).toBe(false) + expect(await readFile(profile.patchPath, 'utf8')).toBe(text) + expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(true) }) it('creates a missing patch file and appends after insertions', async () => { - const file = await fixture() - await writePluginEnabled(file, 'tool', 'package', false) - expect(loadOptionalPatches('test', file)).toEqual([{ id: 'tool', disabled: true }]) - await writeFile(file, '- insert:\n - id: tool\n name: package\n') - await writePluginEnabled(file, 'tool', 'package', true) - expect(loadOptionalPatches('test', file)).toEqual([ - { insert: [{ id: 'tool', name: 'package' }] }, { id: 'tool', disabled: false }, + const profile = await fixture() + await writePluginEnabled(profile, 'tool', 'package', false) + expect(loadOptionalPatches('test', profile.patchPath)).toEqual([{ id: 'tool', disabled: true }]) + await writeFile(profile.patchPath, '- insert:\n - id: tool\n name: package\n') + await writePluginEnabled(profile, 'tool', 'package', false) + expect(loadOptionalPatches('test', profile.patchPath)).toEqual([ + { insert: [{ id: 'tool', name: 'package' }] }, { id: 'tool', disabled: true }, ]) }) -it.each([false, true])('preserves same-ID preset overrides when a Host override exists: %s', async (hostOverride) => { - const preset = { preset: 'preset-standard', id: 'tool-bash', name: 'package', disabled: true } - const file = await fixture(JSON.stringify([ - ...hostOverride ? [{ id: 'tool-bash', disabled: false }] : [], preset, - ])) - expect(await writePluginEnabled(file, 'tool-bash', 'package', false)).toBe(true) - const disabled = { id: 'tool-bash', disabled: true } - expect(loadOptionalPatches('test', file)).toEqual(hostOverride ? [disabled, preset] : [preset, disabled]) - expect(await writePluginEnabled(file, 'tool-bash', 'package', true)).toBe(true) - const enabled = { id: 'tool-bash', disabled: false } - expect(loadOptionalPatches('test', file)).toEqual(hostOverride ? [enabled, preset] : [preset, enabled]) -}) - it.each(['- id: [broken', 'mapping: true\n'])('refuses malformed documents without overwriting %s', async (text) => { - const file = await fixture(text) - await expect(writePluginEnabled(file, 'tool', 'package', true)).rejects.toThrow() - expect(await readFile(file, 'utf8')).toBe(text) + const profile = await fixture(text) + await expect(writePluginEnabled(profile, 'tool', 'package', true)).rejects.toThrow() + expect(await readFile(profile.patchPath, 'utf8')).toBe(text) }) it('retains name-asserting overrides and appends an unambiguous switch', async () => { - const file = await fixture('- id: tool\n name: another-package\n disabled: false\n') - await writePluginEnabled(file, 'tool', 'package', false) - expect(loadOptionalPatches('test', file)).toEqual([ + const profile = await fixture('- id: tool\n name: another-package\n disabled: false\n') + await writePluginEnabled(profile, 'tool', 'package', false) + expect(loadOptionalPatches('test', profile.patchPath)).toEqual([ { id: 'tool', name: 'another-package', disabled: false }, { id: 'tool', disabled: true }, ]) - expect(await writePluginEnabled(file, 'tool', 'package', false)).toBe(false) + expect(await writePluginEnabled(profile, 'tool', 'package', false)).toBe(false) }) it('reports read failures without replacing a directory with configuration', async () => { - const file = await fixture() - await mkdir(file) - await expect(writePluginEnabled(file, 'tool', 'package', true)).rejects.toThrow() + const profile = await fixture() + await mkdir(profile.patchPath) + await expect(writePluginEnabled(profile, 'tool', 'package', true)).rejects.toThrow() }) it('updates the last matching named override and leaves mismatched names untouched', async () => { - const file = await fixture('- id: tool\n disabled: true\n- id: tool\n name: package\n config:\n value: !!js process.platform\n disabled: true # availability\n- id: tool\n name: another-package\n disabled: true\n') - expect(await writePluginEnabled(file, 'tool', 'package', true)).toBe(true) - const text = await readFile(file, 'utf8') + const profile = await fixture('- id: tool\n disabled: true\n- id: tool\n name: package\n config:\n value: !!js process.platform\n disabled: true # availability\n- id: tool\n name: another-package\n disabled: true\n') + expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(true) + const text = await readFile(profile.patchPath, 'utf8') expect(text).toContain('!!js process.platform') expect(text).toContain('# availability') - const patches = loadOptionalPatches('test', file) + const patches = loadOptionalPatches('test', profile.patchPath) expect(patches).toEqual([ { id: 'tool', disabled: true }, { id: 'tool', name: 'package', config: { value: { __jsExpr: 'process.platform' } }, disabled: false }, @@ -90,8 +88,75 @@ it('updates the last matching named override and leaves mismatched names untouch ]) expect(applyEntryPatches([{ id: 'tool', name: 'package' }], patches, () => {})) .toMatchObject([{ id: 'tool', name: 'package', disabled: false }]) - expect(await writePluginEnabled(file, 'tool', 'package', true)).toBe(false) - expect(await readFile(file, 'utf8')).toBe(text) - expect(await writePluginEnabled(file, 'tool', 'package', false)).toBe(true) - expect(loadOptionalPatches('test', file)).toHaveLength(3) + expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(false) + expect(await readFile(profile.patchPath, 'utf8')).toBe(text) + expect(await writePluginEnabled(profile, 'tool', 'package', false)).toBe(true) + expect(loadOptionalPatches('test', profile.patchPath)).toHaveLength(3) +}) + +it('removes or omits a plain switch that restates the bundle layers', async () => { + const profile = await fixture('# personal configuration\n- id: other\n disabled: true\n- id: tool\n disabled: true\n', [TOOL]) + expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(true) + expect(await readFile(profile.patchPath, 'utf8')).toBe('# personal configuration\n- id: other\n disabled: true\n') + expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(false) + expect(await readFile(profile.patchPath, 'utf8')).toBe('# personal configuration\n- id: other\n disabled: true\n') + expect(await writePluginEnabled(profile, 'tool', 'package', false)).toBe(true) + expect(loadOptionalPatches('test', profile.patchPath)).toEqual([{ id: 'other', disabled: true }, { id: 'tool', disabled: true }]) +}) + +it('keeps a switch that carries other settings or differs from the bundle layers', async () => { + const profile = await fixture('- id: tool\n config: { value: 1 }\n disabled: true\n', [TOOL]) + expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(true) + expect(loadOptionalPatches('test', profile.patchPath)).toEqual([{ id: 'tool', config: { value: 1 }, disabled: false }]) + const plain = await fixture('- id: tool\n disabled: true\n', [{ ...TOOL, disabled: true }]) + expect(await writePluginEnabled(plain, 'tool', 'package', true)).toBe(true) + expect(loadOptionalPatches('test', plain.patchPath)).toEqual([{ id: 'tool', disabled: false }]) +}) + +it('keeps the comment above a removed switch and prunes a switch the composition already implies', async () => { + const profile = await fixture('# header\n- id: tool\n disabled: false\n# other\n- id: other\n disabled: true\n', [TOOL]) + expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(true) + expect(await readFile(profile.patchPath, 'utf8')).toBe('# header\n# other\n- id: other\n disabled: true\n') + const first = await fixture('# header\n- id: tool\n disabled: true\n- id: other\n disabled: true\n', [TOOL]) + expect(await writePluginEnabled(first, 'tool', 'package', true)).toBe(true) + expect(await readFile(first.patchPath, 'utf8')).toBe('# header\n- id: other\n disabled: true\n') + const only = await fixture('# header\n- id: tool\n disabled: true\n', [TOOL]) + expect(await writePluginEnabled(only, 'tool', 'package', true)).toBe(true) + expect(loadOptionalPatches('test', only.patchPath)).toEqual([]) + expect(await readFile(only.patchPath, 'utf8')).toBe('# header\n[]\n') + const last = await fixture('- id: other\n disabled: true\n# about tool\n- id: tool\n disabled: true\n', [TOOL]) + expect(await writePluginEnabled(last, 'tool', 'package', true)).toBe(true) + expect(await readFile(last.patchPath, 'utf8')).toBe('- id: other\n disabled: true\n\n# about tool\n') + const lastWithTail = await fixture('- id: other\n disabled: true\n# about tool\n- id: tool\n disabled: true\n# tail\n', [TOOL]) + expect(await writePluginEnabled(lastWithTail, 'tool', 'package', true)).toBe(true) + expect(await readFile(lastWithTail.patchPath, 'utf8')).toBe('- id: other\n disabled: true\n\n# about tool\n# tail\n') + const trailing = await fixture('- id: tool\n disabled: true # removed\n# tail\n', [TOOL]) + expect(await writePluginEnabled(trailing, 'tool', 'package', true)).toBe(true) + expect(loadOptionalPatches('test', trailing.patchPath)).toEqual([]) + expect(await readFile(trailing.patchPath, 'utf8')).toContain('# tail') + const both = await fixture('# header\n- id: tool\n disabled: true\n# tail\n', [TOOL]) + expect(await writePluginEnabled(both, 'tool', 'package', true)).toBe(true) + expect(await readFile(both.patchPath, 'utf8')).toBe('# header\n[]\n\n# tail\n') +}) + +it('treats insertions in the profile patch as part of the inherited composition', async () => { + const profile = await fixture('- insert:\n - id: tool\n name: package\n') + expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(false) + expect(loadOptionalPatches('test', profile.patchPath)).toEqual([{ insert: [{ id: 'tool', name: 'package' }] }]) +}) + +it.each([ + ['a value', '- id: &plugin tool\n disabled: true\n- id: other\n config: { target: *plugin }\n', { target: 'tool' }], + ['the entry', '- &plugin { id: tool, disabled: true }\n- id: other\n config: { target: *plugin }\n', { target: { id: 'tool', disabled: false } }], + ['a key', '- id: tool\n &key disabled: true\n- id: other\n config: { *key : 1 }\n', { disabled: 1 }], +])('keeps a switch whose anchor on %s other entries reference', async (_, text, config) => { + const profile = await fixture(text, [TOOL]) + expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(true) + expect(loadOptionalPatches('test', profile.patchPath)).toEqual([{ id: 'tool', disabled: false }, { id: 'other', config }]) +}) + +it('keeps a switch whose value is an alias', async () => { + const profile = await fixture('- id: other\n config: { flag: &flag true }\n- id: tool\n disabled: *flag\n', [TOOL]) + expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(true) + expect(loadOptionalPatches('test', profile.patchPath)).toEqual([{ id: 'other', config: { flag: true } }, { id: 'tool', disabled: false }]) }) diff --git a/packages/boot/plugin-manager/tests/preset-bundles.spec.ts b/packages/boot/plugin-manager/tests/preset-bundles.spec.ts deleted file mode 100644 index 08c063b180..0000000000 --- a/packages/boot/plugin-manager/tests/preset-bundles.spec.ts +++ /dev/null @@ -1,424 +0,0 @@ -/** Scoped bundles use real preset generations, profile reloads, and package-removal admission. */ -import fs, { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { syncBuiltinESMExports } from 'node:module' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' -import { expect, it, onTestFinished, vi } from 'vitest' -import type { Context } from '@deepseek-ai/cordis' -import Timer from '@deepseek-ai/cordis-plugin-timer' -import { boot, initProfile, PluginPackages, readProfileManifest, readProfilePatches, createRuntimeResolution, loadProfileDirectory, type ProfileContext, type ProfilePatch } from '@deepseek-ai/dsh-app-boot' -import Hmr from '@deepseek-ai/dsh-hmr' -import AgentPreset from '@deepseek-ai/dsh-agent-preset' -import AgentPresets from '@deepseek-ai/dsh-agent-preset-registry' -import { createScope } from '@deepseek-ai/dsh-scope' -import SessionStore, { SessionId, type Session } from '@deepseek-ai/dsh-session' -import SessionProjections from '@deepseek-ai/dsh-session-projection' -import SessionTitle, { SessionTitleProviderId, type SessionTitleProviderRequest, type SessionTitleProviderResult } from '@deepseek-ai/dsh-session-title' -import { createUserMessage } from '@deepseek-ai/dsh-llm' -import PluginManager from '../src/index.ts' -import * as operations from '../src/operations.ts' -import * as appBoot from '@deepseek-ai/dsh-app-boot' - -async function fixture(options: { title?: boolean; hmr?: boolean; presets?: boolean } = {}) { - const home = mkdtempSync(join(tmpdir(), 'preset-bundle-')) - let owner: Context | undefined - onTestFinished(async () => { await owner?.fiber.dispose(); rmSync(home, { recursive: true, force: true }) }) - const dir = join(home, 'profiles', 'test') - const anchor = join(home, 'package.json') - writeFileSync(anchor, '{"name":"test-installation","dependencies":{}}\n') - initProfile(dir, ['core']) - writeFileSync(join(dir, 'cordis.yml'), '[]\n') - const bundle = (name: string, patches: ProfilePatch[]): string => { - const path = join(dir, 'node_modules', name) - mkdirSync(path, { recursive: true }) - writeFileSync(join(path, 'package.json'), JSON.stringify({ name, version: '1.0.0', dsh: { bundle: { patch: './cordis.patch.yml' } } })) - writeFileSync(join(path, 'cordis.patch.yml'), JSON.stringify(patches)) - writeFileSync(join(path, 'plugin.mjs'), 'export function apply(ctx, config) { if (config?.fail) throw new Error("scoped plugin failed"); ctx.get("scopedBundleTrace").push("start"); ctx.effect(() => () => { ctx.get("scopedBundleTrace").push("stop") }) }\n') - return path - } - bundle('core', [{ insert: [ - { id: 'manager', name: 'cordis:manager' }, - { id: 'sessions', name: 'cordis:sessions' }, - { id: 'session-projections', name: 'cordis:session-projections' }, - { id: 'presets', name: 'cordis:presets', config: { default: 'standard' } }, - ...(options.presets === false ? [] : ['standard', 'cordis']).map(id => ({ id: `preset-${id}`, name: 'cordis:preset', config: { id, plugins: [] } })), - ...options.title === true ? [ - { id: 'title', name: 'cordis:title', config: { fallbackMaxWords: 5, fallbackMaxBytes: 100, maxTitleBytes: 100 } }, - { id: 'default-title', name: 'cordis:title-provider', config: { id: 'default' } }, - ] : [], - ] }]) - const addon = bundle('addon', ['standard', 'cordis'].map(preset => ({ preset: `preset-${preset}`, insert: [{ - id: 'shared-id', name: './plugin.mjs', - }] }))) - const manifest = readProfileManifest('test', dir) - manifest.dependencies = { addon: '1.0.0' } - writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest)) - const profile: ProfileContext = { - name: 'test', dir, patchPath: join(dir, 'cordis.patch.yml'), installAnchor: anchor, - cwd: home, home, startedBundles: ['core'], overlays: [], telemetryDisabledEnv: undefined, - } - const resolution = await createRuntimeResolution({ installAnchor: anchor, profile: loadProfileDirectory('test', dir, anchor), home }) - const calls: { - id: string - request: SessionTitleProviderRequest - pending: ReturnType> - }[] = [] - const entered: { current: ReturnType> } = { current: Promise.withResolvers() } - const trace: string[] = [] - const ctx = await boot('test', join(dir, 'cordis.yml'), readProfilePatches('test', profile), async (host) => { - owner = host - host.provide('profileContext', profile) - host.provide('scopedBundleTrace', trace) - host.provide('appReady', { onReady(listener) { listener(); return () => {} } }) - Object.assign(host.loader.builtins, { - manager: PluginManager, sessions: SessionStore, 'session-projections': SessionProjections, - presets: AgentPresets, preset: AgentPreset, title: SessionTitle, - 'title-provider': { - inject: ['sessionTitle'], - apply(ctx: Context, config: { id: string }) { - ctx.sessionTitle.register({ - id: SessionTitleProviderId(config.id), automatic: 'all-prompts', - generate(request) { - const pending = Promise.withResolvers() - calls.push({ id: config.id, request, pending }) - entered.current.resolve(undefined) - return pending.promise - }, - }) - }, - }, - }) - await host.plugin(PluginPackages, { resolution }) - }) - await ctx.plugin(Timer) - if (options.hmr !== false) { - await ctx.plugin(Hmr, { root: [], ignored: [], debounce: 0 }) - await ctx.hmr.runExclusive(async () => {}) - } - onTestFinished(() => { - for (const call of calls) call.pending.resolve({ title: 'teardown', messageSeqs: call.request.messages.map(message => message.seq) }) - }) - return { ctx, manager: ctx.pluginManager, profile, dir, addon, bundle, trace, calls, entered } -} - -it('lists scoped declarations while Off and keeps equal inner ids distinct across presets', async () => { - const { manager, addon } = await fixture() - const patchFile = join(addon, 'cordis.patch.yml') - const patches = JSON.parse(readFileSync(patchFile, 'utf8')) as ProfilePatch[] - writeFileSync(patchFile, JSON.stringify([...patches, - { id: 'shared-id', disabled: true }, - { preset: 'preset-standard', id: 'absent', disabled: true }, - ])) - const moduleName = pathToFileURL(join(addon, 'plugin.mjs')).href - expect((await manager.listBundles()).find(row => row.name === 'addon')?.rows).toEqual([ - { rowId: 'shared-id', preset: 'preset-standard', readOnlyReason: 'preset-managed', moduleName }, - { rowId: 'shared-id', preset: 'preset-cordis', readOnlyReason: 'preset-managed', moduleName }, - ]) - expect(await manager.setBundleEnabled('addon', true)).toMatchObject({ application: 'applied', changed: true }) - const enabled = (await manager.listBundles()).find(row => row.name === 'addon')! - expect(enabled.rows).toEqual([ - { rowId: 'shared-id', preset: 'preset-standard', readOnlyReason: 'preset-managed', moduleName, composition: { enabled: true, fiberPhase: 'active' } }, - { rowId: 'shared-id', preset: 'preset-cordis', readOnlyReason: 'preset-managed', moduleName, composition: { enabled: true, fiberPhase: 'active' } }, - ]) - expect(enabled.rows.every(row => row.entryId === undefined)).toBe(true) - expect(enabled.overrides).toEqual(['shared-id', 'preset-standard/absent']) - expect(await manager.setBundleEnabled('addon', false)).toMatchObject({ application: 'applied' }) - expect((await manager.listBundles()).find(row => row.name === 'addon')?.rows.every(row => row.composition === undefined)).toBe(true) -}) - -it('loads a third-party relative child inside a real preset group and retains its package until release', async () => { - const { manager, ctx, dir, addon, bundle, trace } = await fixture() - bundle('addon', [{ preset: 'preset-standard', insert: [{ - id: 'relative-group', name: 'cordis:group', group: true, config: [{ - id: 'relative-child', name: './nested/relative.mjs', config: { value: 'nested-preset' }, - }], - }] }]) - mkdirSync(join(addon, 'nested')) - writeFileSync(join(addon, 'nested/relative.mjs'), [ - 'export function apply(ctx, config) {', - ' ctx.get("scopedBundleTrace").push(`relative:start:${config.value}`)', - ' ctx.effect(() => () => { ctx.get("scopedBundleTrace").push("relative:stop") })', - '}', - '', - ].join('\n')) - const moduleName = pathToFileURL(join(addon, 'nested/relative.mjs')).href - const declared = (await manager.listBundles()).find(row => row.name === 'addon')?.rows - .find(row => row.rowId === 'relative-child') - expect(declared).toEqual({ rowId: 'relative-child', preset: 'preset-standard', readOnlyReason: 'preset-managed', moduleName }) - expect(await manager.setBundleEnabled('addon', true)).toMatchObject({ application: 'applied' }) - expect(trace).toEqual(['relative:start:nested-preset']) - expect((await ctx.agentPresets.compositionInventory()).find(preset => preset.id === 'standard')?.rows) - .toMatchObject([{ entryId: 'relative-child', moduleName, enabled: true }]) - - const owner = createScope(ctx, {}) - onTestFinished(() => owner.dispose()) - await ctx.agentPresets.mount(owner.ctx, 'standard') - expect(await manager.setBundleEnabled('addon', false)).toMatchObject({ application: 'applied' }) - expect(ctx.agentPresets.inspectCompositions(owner.ctx)[0]?.modules).toMatchObject([{ moduleName }]) - expect(trace).toEqual(['relative:start:nested-preset']) - const remove = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => { - const manifest = readProfileManifest('test', dir) - delete manifest.dependencies?.addon - writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest)) - return { exitCode: 0, output: '', truncated: false, logPath: join(dir, 'remove.log') } - }) - onTestFinished(() => { remove.mockRestore() }) - expect(await manager.removeBundle('addon')).toMatchObject({ application: 'failed', error: { code: 'bundle-in-use' } }) - expect(remove).not.toHaveBeenCalled() - await owner.dispose() - expect(trace).toEqual(['relative:start:nested-preset', 'relative:stop']) - expect(await manager.removeBundle('addon')).toMatchObject({ application: 'applied', changed: true }) - expect(remove).toHaveBeenCalledOnce() -}) - -it('retains a failed selection, reports affected preset failures again, and keeps unrelated failures as warnings', async () => { - const { manager, dir, bundle, ctx } = await fixture() - bundle('broken', [{ preset: 'preset-standard', insert: [{ id: 'broken', name: './plugin.mjs', config: { fail: true } }] }]) - const result = await manager.setBundleEnabled('broken', true) - expect(result).toMatchObject({ application: 'failed', changed: true, error: { diagnostic: expect.stringContaining('agent preset standard') as string } }) - expect(readProfileManifest('test', dir).dsh?.profile?.bundles).toContain('broken') - expect(await manager.setBundleEnabled('broken', true)).toMatchObject({ application: 'failed', changed: false }) - expect((await ctx.agentPresets.list()).find(row => row.id === 'standard')?.broken).toContain('scoped plugin failed') - bundle('unrelated', [{ insert: [{ id: 'unrelated', name: './plugin.mjs' }] }]) - expect(await manager.setBundleEnabled('unrelated', true)).toMatchObject({ application: 'applied', warnings: [expect.stringContaining('agent preset standard')] }) - expect(await manager.setBundleEnabled('broken', false)).toMatchObject({ application: 'applied' }) - expect((await ctx.agentPresets.list()).every(row => row.broken === undefined)).toBe(true) -}) - -it('refuses a no-op scoped enable when its Host preset row already failed before registering', async () => { - const { manager, ctx, bundle, dir } = await fixture() - bundle('invalid-definition', [{ id: 'preset-standard', config: { id: '', plugins: [] } }]) - expect(await manager.setBundleEnabled('invalid-definition', true)).toMatchObject({ application: 'failed' }) - expect((await ctx.agentPresets.list()).map(row => row.id)).not.toContain('standard') - bundle('scoped-noop', [{ preset: 'preset-standard', insert: [] }]) - expect(await manager.setBundleEnabled('scoped-noop', true)).toMatchObject({ - application: 'failed', changed: true, error: { diagnostic: expect.stringContaining('Preset id must not be empty') as string }, - }) - expect(readProfileManifest('test', dir).dsh?.profile?.bundles).toContain('scoped-noop') -}) - -it.each([{ id: 'standard' }, { id: 'standard', plugins: [] }])( - 'keeps existing preset failures as warnings when an unrelated Host config is %j', async (config) => { - const { manager, bundle, ctx } = await fixture() - expect(await ctx.agentPresets.list()).toMatchObject([{ id: 'cordis', definitionEntryId: 'preset-cordis' }, { id: 'standard', definitionEntryId: 'preset-standard' }]) - expect((await ctx.agentPresets.remoteExportList()).presets.every(row => !Object.hasOwn(row, 'definitionEntryId'))).toBe(true) - bundle('broken', [{ preset: 'preset-standard', insert: [{ id: 'broken', name: './plugin.mjs', config: { fail: true } }] }]) - expect(await manager.setBundleEnabled('broken', true)).toMatchObject({ application: 'failed' }) - bundle('ordinary', [{ insert: [{ id: 'ordinary', name: './plugin.mjs', config }] }]) - expect(await manager.setBundleEnabled('ordinary', true)).toMatchObject({ - application: 'applied', warnings: [expect.stringContaining('agent preset standard')], - }) - }, -) - -it('reports invalid composition immediately without HMR while retaining the saved selection', async () => { - const { manager, dir } = await fixture({ hmr: false, presets: false }) - expect(await manager.setBundleEnabled('addon', true)).toMatchObject({ - application: 'failed', changed: true, error: { diagnostic: expect.stringContaining(join('addon', 'cordis.patch.yml')) as string }, - }) - expect(readProfileManifest('test', dir).dsh?.profile?.bundles).toContain('addon') - expect(await manager.setBundleEnabled('addon', false)).toMatchObject({ application: 'restart-required', changed: true }) - expect(readProfileManifest('test', dir).dsh?.profile?.bundles).not.toContain('addon') -}) - -it('refuses Remove after Off while an old Agent scope retains the bundle, then removes after release', async () => { - const { manager, ctx, dir, trace } = await fixture() - expect(await manager.setBundleEnabled('addon', true)).toMatchObject({ application: 'applied' }) - const agent = createScope(ctx, {}) - onTestFinished(() => agent.dispose()) - await ctx.agentPresets.mount(agent.ctx, 'standard') - expect(await manager.setBundleEnabled('addon', false)).toMatchObject({ application: 'applied' }) - expect(ctx.agentPresets.inspectCompositions(agent.ctx)[0]?.modules).toHaveLength(1) - const remove = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => { - const manifest = readProfileManifest('test', dir) - delete manifest.dependencies?.addon - writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest)) - return { exitCode: 0, output: '', truncated: false, logPath: join(dir, 'remove.log') } - }) - onTestFinished(() => { remove.mockRestore() }) - expect(await manager.removeBundle('addon')).toMatchObject({ application: 'failed', error: { code: 'bundle-in-use' }, changed: false }) - expect(remove).not.toHaveBeenCalled() - await agent.dispose() - expect(trace.filter(item => item === 'stop')).toHaveLength(2) - expect(await manager.removeBundle('addon')).toMatchObject({ application: 'applied', changed: true }) - expect(remove).toHaveBeenCalledOnce() -}) - -it.each([false, true].flatMap(anonymous => [false, true].map(archive => ({ anonymous, archive })))) -('removes a released contribution while base presets keep using the same shared module (anonymous=$anonymous, archive=$archive)', async ({ anonymous, archive }) => { - // Resolver identities must be created under the same carrier that later refreshes them. - if (archive) { - const previousPkg = Object.getOwnPropertyDescriptor(process, 'pkg') - onTestFinished(() => { - if (previousPkg === undefined) Reflect.deleteProperty(process, 'pkg') - else Object.defineProperty(process, 'pkg', previousPkg) - }) - Object.defineProperty(process, 'pkg', { configurable: true, value: {} }) - } - const { manager, ctx, dir, addon } = await fixture() - const shared = join(dir, 'node_modules', 'shared-fixture') - mkdirSync(shared) - writeFileSync(join(shared, 'package.json'), JSON.stringify({ name: 'shared-fixture', version: '1.0.0', type: 'module', exports: './index.mjs' })) - writeFileSync(join(shared, 'index.mjs'), 'export function apply() {}\n') - const core = join(dir, 'node_modules', 'core') - const corePatches = JSON.parse(readFileSync(join(core, 'cordis.patch.yml'), 'utf8')) as ProfilePatch[] - for (const row of corePatches[0]!.insert!) { - if (row.id === 'preset-standard') row.config = { id: 'standard', plugins: [{ id: 'base-shared', name: 'shared-fixture' }] } - if (row.id === 'preset-cordis') row.config = { id: 'cordis', plugins: [{ id: 'addon-shared', name: 'shared-fixture' }] } - } - writeFileSync(join(core, 'cordis.patch.yml'), JSON.stringify(corePatches)) - writeFileSync(join(addon, 'cordis.patch.yml'), JSON.stringify([{ - preset: 'preset-standard', insert: [{ ...anonymous ? {} : { id: 'addon-shared' }, name: 'shared-fixture' }], - }])) - for (const packageDir of [core, addon]) { - const manifest = readProfileManifest('test', packageDir) - manifest.dependencies = { 'shared-fixture': '1.0.0' } - writeFileSync(join(packageDir, 'package.json'), JSON.stringify(manifest)) - } - expect(await manager.setBundleEnabled('addon', true)).toMatchObject({ application: 'applied' }) - const owner = createScope(ctx, {}) - onTestFinished(() => owner.dispose()) - await ctx.agentPresets.mount(owner.ctx, 'standard') - expect(await manager.setBundleEnabled('addon', false)).toMatchObject({ application: 'applied' }) - expect(ctx.agentPresets.inspectCompositions(owner.ctx)).toMatchObject([{ - id: 'standard', definitionEntryId: 'preset-standard', modules: [ - { entryId: 'base-shared', moduleName: 'shared-fixture' }, - { entryId: anonymous ? expect.any(String) as string : 'addon-shared', moduleName: 'shared-fixture' }, - ], - }]) - if (archive) { - const original = fs.realpathSync - onTestFinished(() => { fs.realpathSync = original; syncBuiltinESMExports() }) - fs.realpathSync = new Proxy(original, { - apply(target, receiver: unknown, args: unknown[]): unknown { - if (['package.json', 'index.mjs'].some(file => String(args[0]).endsWith(join('shared-fixture', file)))) { - throw Object.assign(new Error('archive-backed files have no realpath entry'), { code: 'ENOENT' }) - } - return Reflect.apply(target, receiver, args) - }, - }) - syncBuiltinESMExports() - expect(() => fs.realpathSync(join(shared, 'package.json'))).toThrow('archive-backed') - expect(readFileSync(join(shared, 'index.mjs'), 'utf8')).toContain('export function apply') - } - const remove = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => { - const manifest = readProfileManifest('test', dir) - delete manifest.dependencies?.addon - writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest)) - return { exitCode: 0, output: '', truncated: false, logPath: join(dir, 'remove.log') } - }) - onTestFinished(() => { remove.mockRestore() }) - expect(await manager.removeBundle('addon')).toMatchObject({ application: 'failed', error: { code: 'bundle-in-use' } }) - expect(remove).not.toHaveBeenCalled() - await owner.dispose() - expect(ctx.agentPresets.inspectCompositions().flatMap(preset => preset.modules).map(module => module.moduleName)) - .toEqual(['shared-fixture', 'shared-fixture']) - const removed = await manager.removeBundle('addon') - expect(removed, JSON.stringify(removed.error)).toMatchObject({ application: 'applied', changed: true }) - expect(remove).toHaveBeenCalledOnce() -}) - -it('removes an unrelated bundle when another retained row with the same id has lost its module file', async () => { - const { manager, ctx, dir, addon, bundle } = await fixture() - expect(await manager.setBundleEnabled('addon', true)).toMatchObject({ application: 'applied' }) - const owner = createScope(ctx, {}) - onTestFinished(() => owner.dispose()) - await ctx.agentPresets.mount(owner.ctx, 'standard') - expect(await manager.setBundleEnabled('addon', false)).toMatchObject({ application: 'applied' }) - bundle('unrelated', [{ preset: 'preset-standard', insert: [{ id: 'shared-id', name: './plugin.mjs' }] }]) - const manifest = readProfileManifest('test', dir) - manifest.dependencies = { ...manifest.dependencies, unrelated: '1.0.0' } - writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest)) - rmSync(join(addon, 'plugin.mjs')) - const remove = vi.spyOn(operations, 'runProfilePnpm').mockResolvedValue({ - exitCode: 0, output: '', truncated: false, logPath: join(dir, 'remove.log'), - }) - onTestFinished(() => { remove.mockRestore() }) - expect(await manager.removeBundle('addon')).toMatchObject({ application: 'failed', error: { code: 'bundle-in-use' } }) - expect(remove).not.toHaveBeenCalled() - const resolution = vi.spyOn(appBoot, 'resolvePluginResource').mockImplementationOnce(() => { throw new Error('resolver unavailable') }) - onTestFinished(() => { resolution.mockRestore() }) - expect(await manager.removeBundle('unrelated')).toMatchObject({ application: 'failed', error: { diagnostic: 'resolver unavailable' } }) - expect(remove).not.toHaveBeenCalled() - resolution.mockRestore() - expect(await manager.removeBundle('unrelated')).toMatchObject({ application: 'applied' }) - expect(remove).toHaveBeenCalledOnce() - expect(ctx.agentPresets.inspectCompositions(owner.ctx)[0]?.modules).toHaveLength(1) -}) - -it('retains contributed builtin rows even when no package owns their module names', async () => { - const { manager, ctx, bundle } = await fixture() - ctx.loader.builtins['retained-fixture'] = { apply() {} } - bundle('addon', [{ preset: 'preset-standard', insert: [{ id: 'builtin', name: 'cordis:retained-fixture' }] }]) - expect(await manager.setBundleEnabled('addon', true)).toMatchObject({ application: 'applied' }) - const agent = createScope(ctx, {}) - onTestFinished(() => agent.dispose()) - await ctx.agentPresets.mount(agent.ctx, 'standard') - expect(await manager.setBundleEnabled('addon', false)).toMatchObject({ application: 'applied' }) - const inspect = ctx.agentPresets.inspectCompositions.bind(ctx.agentPresets) - const projection = vi.spyOn(ctx.agentPresets, 'inspectCompositions').mockImplementation(() => inspect().map(composition => ({ - ...composition, modules: composition.modules.map(({ baseUrl: _baseUrl, ...module }) => module), - }))) - onTestFinished(() => { projection.mockRestore() }) - expect(await manager.removeBundle('addon')).toMatchObject({ application: 'failed', error: { code: 'bundle-in-use' } }) -}) - -it('refuses removal when a different module from the same package remains in a preset', async () => { - const { manager, ctx, dir, addon } = await fixture() - const source = readFileSync(join(addon, 'plugin.mjs'), 'utf8') - writeFileSync(join(addon, 'other.mjs'), source) - expect(await manager.setBundleEnabled('addon', true)).toMatchObject({ application: 'applied' }) - writeFileSync(join(dir, 'cordis.patch.yml'), JSON.stringify([{ - preset: 'preset-standard', insert: [{ id: 'independent', name: pathToFileURL(join(addon, 'other.mjs')).href }], - }])) - expect(await manager.setBundleEnabled('addon', false)).toMatchObject({ application: 'applied' }) - expect(ctx.agentPresets.inspectCompositions().some(row => row.modules.some(module => module.moduleName.endsWith('/other.mjs')))).toBe(true) - const remove = vi.spyOn(operations, 'runProfilePnpm') - onTestFinished(() => { remove.mockRestore() }) - expect(await manager.removeBundle('addon')).toMatchObject({ application: 'failed', error: { code: 'bundle-in-use' } }) - expect(remove).not.toHaveBeenCalled() -}) - -async function requestTitle(session: Session): Promise { - session.append('turn/start', { turn: 1 }) - session.append('user/message', createUserMessage({ content: [{ type: 'text', text: 'Title for provider switch' }], source: { kind: 'user' } }), { surfaceOp: 'append' }) - await new Promise((resolve) => { queueMicrotask(resolve) }) - session.append('request/header', { header: { config: { provider: 'test', model: 'test' } }, reason: 'initial' }) -} - -it('drains and rejects stale title completions before activating each replacement in both directions', async () => { - const { manager, ctx, bundle, calls, entered } = await fixture({ title: true }) - bundle('titles', [ - { id: 'default-title', disabled: true }, - { insert: [{ id: 'optional-title', name: 'cordis:title-provider', config: { id: 'optional' } }] }, - ]) - for (const [enabled, expected] of [[true, 'default'], [false, 'optional']] as const) { - entered.current = Promise.withResolvers() - const session = ctx.sessions.create(SessionId(`title-switch-${String(enabled)}`)) - await requestTitle(session) - await entered.current.promise - const call = calls.at(-1)! - expect(call.id).toBe(expected) - const aborted = Promise.withResolvers() - call.request.signal.addEventListener('abort', () => { aborted.resolve(undefined) }, { once: true }) - let complete = false - const switching = manager.setBundleEnabled('titles', enabled).then((result) => { complete = true; return result }) - onTestFinished(async () => { - call.pending.resolve({ title: 'teardown', messageSeqs: call.request.messages.map(message => message.seq) }) - await switching - }) - await aborted.promise - expect(complete).toBe(false) - expect(calls).toHaveLength(enabled ? 1 : 2) - call.pending.resolve({ title: 'stale result', messageSeqs: call.request.messages.map(message => message.seq) }) - expect(await switching).toMatchObject({ application: 'applied' }) - expect(ctx.sessionTitle.get(session)?.source.kind).toBe('fallback') - } - entered.current = Promise.withResolvers() - const final = ctx.sessions.create(SessionId('title-switch-final')) - await requestTitle(final) - await entered.current.promise - expect(calls.at(-1)?.id).toBe('default') - calls.at(-1)?.pending.resolve({ title: 'final title', messageSeqs: calls.at(-1)!.request.messages.map(message => message.seq) }) -}) diff --git a/packages/boot/plugin-manager/tests/tools.spec.ts b/packages/boot/plugin-manager/tests/tools.spec.ts index bc7da82dfe..c7981e2296 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' @@ -281,3 +282,25 @@ it('presents reads and changes distinctly and disposes its registration', async await fiber.dispose() expect(ctx.tools.get('plugin_manager')).toBeUndefined() }) + +it('tells the agent the next step for each change outcome it can act on', async () => { + const { manager, call } = await fixture() + const outcome = async (result: object): Promise => { + manager.setBundleEnabled.mockResolvedValueOnce(result as never) + return (JSON.parse(resultText(await call({ action: 'set_bundle', target: 'bundle', enabled: true }))) as { nextStep?: string }).nextStep + } + expect(await outcome({ changed: true, application: 'applied' })).toBeUndefined() + expect(await outcome({ changed: false, application: 'cancelled' })).toContain('nothing changed') + expect(await outcome({ changed: true, application: 'overridden' })).toContain('higher-priority layer') + expect(await outcome({ changed: true, application: 'restart-required', restartReason: 'host-module' })) + .toBe('Tell the user to restart DSH to apply this change: the change reaches modules DSH itself loaded.') + expect(await outcome({ changed: true, application: 'restart-required' })).toBe('Tell the user to restart DSH to apply this change.') + expect(await outcome({ changed: false, application: 'failed', packageResult: { kind: 'build-blocked' } })).toContain('approvedBuilds') + // A refusal code is more specific than the package manager's failure kind. + expect(await outcome({ changed: false, application: 'failed', packageResult: { kind: 'network' }, error: { code: 'stale-approval' } })) + .toContain('without approvedBuilds') + // A failure kind without its own step falls back to the refusal code. + expect(await outcome({ changed: false, application: 'failed', packageResult: { kind: 'unknown' }, error: { code: 'operation-error' } })) + .toContain('Report the diagnostic') + expect(await outcome({ changed: false, application: 'failed' })).toContain('Report the diagnostic') +}) diff --git a/packages/boot/plugin-manager/tsconfig.json b/packages/boot/plugin-manager/tsconfig.json index 643f870407..ba181795a1 100644 --- a/packages/boot/plugin-manager/tsconfig.json +++ b/packages/boot/plugin-manager/tsconfig.json @@ -64,9 +64,6 @@ }, { "path": "../../interaction/user-approval" - }, - { - "path": "../../preset/agent-preset-registry" } ] } diff --git a/packages/browser-use/browser-use/package.json b/packages/browser-use/browser-use/package.json index 58fe381489..58970dec4f 100644 --- a/packages/browser-use/browser-use/package.json +++ b/packages/browser-use/browser-use/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-browser-use", "description": "Exclusive named browser-use provider registration", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/acp-app/package.json b/packages/bundle/acp-app/package.json index 2aa91ed8b1..6d6e737e4d 100644 --- a/packages/bundle/acp-app/package.json +++ b/packages/bundle/acp-app/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-acp-app", "description": "The dsh ACP profile bundle: automation-only JSON-RPC stdio and process lifecycle over dsh-base", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/base/cordis.patch.yml b/packages/bundle/base/cordis.patch.yml index 5219c2444f..ee2f8f280b 100644 --- a/packages/bundle/base/cordis.patch.yml +++ b/packages/bundle/base/cordis.patch.yml @@ -52,6 +52,11 @@ - id: typert-gateway name: '@deepseek-ai/dsh-api-gateway' + # Method-level access control for non-owner Peers; the Gateway requires it, + # and its Client half publishes the standard access Hooks. + - id: remote-access + name: '@deepseek-ai/dsh-api-remote-access' + - id: session-title name: '@deepseek-ai/dsh-session-title' config: @@ -105,8 +110,8 @@ name: '@deepseek-ai/dsh-settings' disabled: !!js "!ctx.get('profileContext')" - # Credential sources: inherited environment over the managed - # `$DSH_HOME/.credentials.yaml`, with project and user `.env` fallbacks. + # Credential sources: managed `$DSH_HOME/.credentials.yaml`, then inherited + # environment, project `.env`, and user `.env` fallbacks. # Adapters resolve references per request; the Models page writes only the # managed document, which is never materialized into the process environment. - id: authorization @@ -328,7 +333,7 @@ name: '@deepseek-ai/dsh-plan-mode' config: section: | - You are in plan mode. Stay in plan mode until exit_plan_mode succeeds or the user switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode. + You are in plan mode. Stay in plan mode until the user approves your plan through exit_plan_mode or switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode. Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery. diff --git a/packages/bundle/base/package.json b/packages/bundle/base/package.json index c8ccd95c8f..1eb581ddbc 100644 --- a/packages/bundle/base/package.json +++ b/packages/bundle/base/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-base", "description": "The shared dsh core as a profile bundle: the first patch layer of base-backed profiles, inserting core rows over the empty profile root", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -61,6 +61,7 @@ "@deepseek-ai/dsh-goal": "workspace:*", "@deepseek-ai/dsh-goal-round-driver": "workspace:*", "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", "@deepseek-ai/dsh-llm-deepseek-account": "workspace:*", diff --git a/packages/bundle/headless/README.i18n.yaml b/packages/bundle/headless/README.i18n.yaml index c3715b490f..6597e4b433 100644 --- a/packages/bundle/headless/README.i18n.yaml +++ b/packages/bundle/headless/README.i18n.yaml @@ -18,8 +18,11 @@ en: 4447012f4c84100d zh: faf579ae9f04c096 /deepseek-ai-dsh-headless/use-this-package/running-a-one-shot-task: - en: 76a22e98d2b3cc2f - zh: c9eb624609b8cc32 + en: 89a48af61a38afc3 + zh: fe202a1bb2c11781 +/deepseek-ai-dsh-headless/use-this-package/credentials: + en: ca8217837ee9c698 + zh: fa20daf27d4e09ef /deepseek-ai-dsh-headless/use-this-package/choosing-the-session-identity: en: dbaa2fac63910a4c zh: 4fd5c17815ca444b @@ -57,8 +60,8 @@ en: 0b0f74b412c7c6d8 zh: 6e8f918d0c4bf342 /deepseek-ai-dsh-headless/known-limitations-and-deferred-work: - en: b2df65836d53ba03 - zh: 82a56dc1255a0c3b + en: 3a6dc9666d852219 + zh: b764f203815e179e /deepseek-ai-dsh-headless/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/bundle/headless/README.md b/packages/bundle/headless/README.md index e7776f0591..bc2a7ff532 100644 --- a/packages/bundle/headless/README.md +++ b/packages/bundle/headless/README.md @@ -49,6 +49,26 @@ The task and run options are supplied through three settings: The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-headless) is the exhaustive source for every accepted field and its JSDoc. + +### Credentials + +The shipped headless profile disables the managed credential store and its authorization and DeepSeek account consumers. API-key routes use the launch environment, then `/.env`, then `$DSH_HOME/.env`. Keys and sign-ins saved by the GUI are ignored without changing their file. Providers that require a saved sign-in fail unless stored authentication is restored; external provider credential chains, such as AWS profiles, remain available. + +Unset an empty launch variable to allow its `.env` fallback; an exported empty value shadows that fallback. + +To restore stored authentication, add these rows to `$DSH_HOME/profiles/headless/cordis.patch.yml` or a `--patch` overlay: + +```yaml +- id: credentials + disabled: false +- id: authorization + disabled: false +- id: deepseek-account + disabled: false +``` + +The restored store uses [saved credentials before environment fallbacks](../../credentials/credentials-local/README.md). Web, SDK and ACP profiles keep that default ordering. Headless sessions, settings and tool behavior are unchanged; this profile choice is not a filesystem access boundary. + ### Choosing the session identity Every invocation defaults to a fresh `session-` identity, which `--json` reports in its opening `session` event. Pass `--session-id ` to continue that conversation: the runner adopts the persisted Session with that id, and an id with no stored Session fails before the task runs rather than quietly opening an empty history. Adoption requires the composed `sessionPersistence` and `sessionQuery` services, so a profile that omits either fails loudly instead of returning an id whose history dies with the process. An Agent already live under the requested id in this process is refused: another owner may still drive it, so the runner cannot claim an exclusive run interval over it. The identity is opaque, so the exact string is used, whitespace included. The working directory is resolved through the mounted filesystem provider (`fs.resolve('.')` and `fs.processPath()`), or the process cwd when no filesystem service is mounted; new Sessions record that directory. Adoption compares the recorded cwd with the same provider-resolved directory and refuses a Session that is a subagent or forked session, that recorded no working directory, that runs under an agent preset this profile does not compose, or whose preset record is malformed — the check reads the preset the Session log currently records, so a Session that switched preset while blank is rejected too. A supervisor therefore cannot silently drive someone else's conversation under a different composition; any mismatch fails before the task runs. @@ -133,6 +153,7 @@ The runner adds nothing to the request prefix; it only drives one user message t These limits tell you when headless does not fit and what it needs from the `dsh` launcher. They are current package constraints, not a general CLI comparison or a task backlog. - **One task per run** — after the task is answered the process exits; there is no interactive follow-up, so split multi-step work into separate runs. +- **Final background-job settlement may be absent from persisted history** — process teardown can end Session routing or close its writer before an owned job settles, including normal completion and signal shutdown; the [job lifecycle contract](../../../docs/subsystems/jobs.md#session-lifecycle-records) defines how consumers retain incomplete intervals. - **Runs through the `dsh` launcher** — starting the headless profile another way fails at startup, because only the launcher can request the process exit. - **No pre-token heartbeat** — in default mode stderr stays silent until the provider emits a non-empty reasoning delta; a delayed first token exposes no earlier progress signal. - **Reasoning enters stderr logs** — in default mode, redirection and supervisors may retain substantially more and potentially sensitive model output; route stderr to a controlled sink when needed. diff --git a/packages/bundle/headless/README.zh.md b/packages/bundle/headless/README.zh.md index a7d35fdbe9..fb79a898e2 100644 --- a/packages/bundle/headless/README.zh.md +++ b/packages/bundle/headless/README.zh.md @@ -49,6 +49,26 @@ agent 会完成该任务,把提供方的每个非空推理(reasoning)增 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-headless)是所有受支持字段及其 JSDoc 的完整真源。 + +### 凭据 + +随附的 headless profile 禁用托管凭据存储,以及依赖它的 authorization 和 DeepSeek account 消费方。API 密钥路由依次使用启动环境、`<运行命令的目录>/.env` 和 `$DSH_HOME/.env`。GUI 保存的密钥和登录凭据不会被使用,存储文件保持原样。需要已保存登录凭据的提供方会失败,除非恢复存储认证;AWS profile 等提供方外部凭据链仍然可用。 + +启动变量为空时,请取消导出该变量,让 `.env` 后备生效;已导出的空值会遮蔽后备值。 + +要恢复存储认证,请把以下行加入 `$DSH_HOME/profiles/headless/cordis.patch.yml` 或 `--patch` 覆盖文件: + +```yaml +- id: credentials + disabled: false +- id: authorization + disabled: false +- id: deepseek-account + disabled: false +``` + +恢复后,存储仍按[已保存凭据优先于环境后备](../../credentials/credentials-local/README.zh.md)解析。Web、SDK 和 ACP profile 保留这一默认顺序。headless 的会话、settings 和工具行为不变;这种 profile 配置选择不构成文件系统访问边界。 + ### 选择 Session 标识 每次调用默认使用全新的 `session-` 标识,`--json` 会在开头的 `session` 事件里报告它。传入 `--session-id ` 延续这段对话:runner 沿用该 id 对应的持久化 Session,而该 id 没有持久化 Session 时会在任务运行前失败,而不是悄悄开出一段空历史。沿用要求已组合 `sessionPersistence` 与 `sessionQuery` 服务,因此缺少任一服务的 profile 会显式失败,而不会返回一个历史随进程消失的 id。本进程中已存在持有该 id 的存活 Agent 时会被拒绝:它的原 owner 可能仍在驱动它,runner 无法取得独占的运行区间。标识是不透明的,因此会原样使用调用方给出的字符串,包括空白字符。工作目录通过已挂载的文件系统提供方解析(`fs.resolve('.')` 与 `fs.processPath()`);未挂载文件系统服务时使用进程 cwd,新 Session 会记录该目录。沿用会将已记录 cwd 与同一提供方解析出的目录比较,并拒绝子 agent 或 fork 会话、未记录工作目录的会话、运行在本 profile 不组合的 agent preset 下的会话,以及 preset 记录畸形的会话——该检查读取 Session 日志当前记录的 preset,因此在空白期切换过 preset 的会话同样会被拒绝。因此监督进程无法在另一套组合下悄悄驱动他人的会话;任一不匹配都会在任务运行前失败。 @@ -133,6 +153,7 @@ runner 不向请求前缀添加任何内容;它只是驱动组合出的配置 这些限制告诉你 headless 何时不适用、它需要 `dsh` 启动器提供什么。它们是当前包约束,不是通用的 CLI(命令行界面)对比或任务积压。 - **每次运行一个任务**——任务得到回答后进程即退出;没有交互式后续,因此多步工作请拆成多次运行。 +- **持久化历史可能缺少后台 job 的最后一条结算**——进程销毁可能在有主 job 结算前停止 Session 路由或关闭写句柄,正常结束和信号关停也可能如此;[job 生命周期约定](../../../docs/subsystems/jobs.zh.md#session-lifecycle-records)说明消费方如何保留不完整区间。 - **通过 `dsh` 启动器运行**——以其他方式启动 headless profile 会在启动时失败,因为只有启动器能请求进程退出。 - **首个 token 前没有心跳**——默认模式下,提供方发出第一个非空推理增量前,stderr 保持静默;延迟首个 token 的提供方不会更早给出进度信号。 - **推理进入 stderr 日志**——默认模式下,重定向与监督进程可能保留显著更多且可能敏感的模型输出;需要时应把 stderr 路由到受控位置。 diff --git a/packages/bundle/headless/cordis.patch.yml b/packages/bundle/headless/cordis.patch.yml index 20f13b54e6..cf224539eb 100644 --- a/packages/bundle/headless/cordis.patch.yml +++ b/packages/bundle/headless/cordis.patch.yml @@ -31,3 +31,13 @@ - id: hmr disabled: true + +# One-shot jobs use launch-time credentials instead of the interactive store. +- id: credentials + disabled: true + +- id: authorization + disabled: true + +- id: deepseek-account + disabled: true diff --git a/packages/bundle/headless/package.json b/packages/bundle/headless/package.json index 4655f48c37..529831a664 100644 --- a/packages/bundle/headless/package.json +++ b/packages/bundle/headless/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-headless", "description": "The dsh one-shot bundle: a direct core Agent/Session runner over dsh-base with no Host, HTTP, or browser layer", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/headless/tests/headless.spec.ts b/packages/bundle/headless/tests/headless.spec.ts index cc73507d5f..468c1e67a9 100644 --- a/packages/bundle/headless/tests/headless.spec.ts +++ b/packages/bundle/headless/tests/headless.spec.ts @@ -260,7 +260,7 @@ describe('headless runner', () => { await test.ctx.plugin(SubagentRuntime) test.ctx.subagents.registerProvider({ name: 'external', inheritsParentContext: false, - capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, agentPreset: false, outputSchema: false, depthLimit: false }, start: async () => ({ id: brandString('settlement-child'), result: Promise.resolve({ output: [{ type: 'text' as const, text: 'child answer' }], stopReason: 'completed' as const }), diff --git a/packages/bundle/sdk-app/README.i18n.yaml b/packages/bundle/sdk-app/README.i18n.yaml index b8b29a0453..fb39b99573 100644 --- a/packages/bundle/sdk-app/README.i18n.yaml +++ b/packages/bundle/sdk-app/README.i18n.yaml @@ -9,27 +9,27 @@ en: 1393fc0c2c6cf60c zh: 61e2f2c46463101b /deepseek-ai-dsh-sdk-app/summary: - en: f96841d96dc95a30 - zh: 88aa3e92ae1deb9c + en: 5583f814d74d685f + zh: 7d52ecc2cdcd78d4 /deepseek-ai-dsh-sdk-app/table-of-contents: en: 4e53164159b5ce41 zh: 89582dc0294d0776 /deepseek-ai-dsh-sdk-app/use-this-package: - en: 465be8e510a86913 - zh: 07e2e1efba1d108b + en: 63573087d1db9aff + zh: 638612ac3f0da2c0 /deepseek-ai-dsh-sdk-app/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 -/deepseek-ai-dsh-sdk-app/model-experience/sdk-coding-agent-persona: - en: af149b1e7ed0a5fc - zh: fe483822d03deddb -/deepseek-ai-dsh-sdk-app/model-experience/sdk-coding-agent-persona/what-the-model-sees: - en: afe0af085d77833e - zh: f41ef2a2219f1248 -/deepseek-ai-dsh-sdk-app/model-experience/sdk-coding-agent-persona/token-effect: - en: 371d28831239e0a8 - zh: 57595359ff30a259 -/deepseek-ai-dsh-sdk-app/model-experience/sdk-coding-agent-persona/kv-cache-effect: +/deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context: + en: 4f88e647c6df4f42 + zh: 2bd3e4b0bdfe9412 +/deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context/what-the-model-sees: + en: 40f68e7d3f181ed6 + zh: 64b0d7c8bf63dfa1 +/deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context/token-effect: + en: 92d8ecb761e3ca7b + zh: e14c71ee2c31e818 +/deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context/kv-cache-effect: en: 5b0e33295fb90e19 zh: 4d48ca75bb677202 /deepseek-ai-dsh-sdk-app/known-limitations-and-deferred-work: diff --git a/packages/bundle/sdk-app/README.md b/packages/bundle/sdk-app/README.md index df3d0aa353..a149ec1254 100644 --- a/packages/bundle/sdk-app/README.md +++ b/packages/bundle/sdk-app/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -The SDK stdio application as a `dsh` profile bundle over [`dsh-base`](../base/README.md). It inherits the base's disabled module-HMR policy; its patch sets the coding-agent persona, mounts an app-owned zero-option command provider, and starts [`dsh-sdk-jsonrpc-server`](../../sdk/server/README.md) only after that provider accepts the invocation. `dsh --profile sdk --help` therefore writes help and exits without claiming stdin or stdout. The standalone [`sdk-minimal`](../sdk-minimal/README.md) bundle reuses the same startup provider with its own profile name. +The SDK stdio application as a `dsh` profile bundle over [`dsh-base`](../base/README.md). It inherits the base's disabled module-HMR policy; its patch mounts an app-owned zero-option command provider, and starts [`dsh-sdk-jsonrpc-server`](../../sdk/server/README.md) only after that provider accepts the invocation. `dsh --profile sdk --help` therefore writes help and exits without claiming stdin or stdout. The standalone [`sdk-minimal`](../sdk-minimal/README.md) bundle reuses the same startup provider with its own profile name. ## Table of Contents @@ -33,22 +33,22 @@ The startup provider binds stdin EOF to the launcher's bounded successful shutdo The SDK uses the base `read`, `write`, and `edit` defaults. To add `str_replace_editor`, use the explicit insertion patch in the [base configuration guide](../base/README.md#use-this-package). The standalone `sdk-minimal` profile owns its separate tool selection. -The packaged Python runtime enables the [Office runtime query and skills](../../skill/tool-workspace-dependencies/README.md#use-this-package) by default. `DSH_PRIMARY_RUNTIME` overrides its bundled payload; an empty value disables both rows. Source launches without a carrier default remain opt-in. The tool reads the payload in place. Profile patches can disable `skill-office` or replace its `assetRoot` independently of `workspace-dependencies`; filesystem skills with the same name take precedence over bundled skills. See the [runtime package](../../../python/sdk-runtime/README.md) for packaging and configuration. +The Python runtime exposes explicitly downloaded authoring resources and Office sidecars to this profile. `DSH_PRIMARY_RUNTIME` overrides the authoring payload; an empty value disables its query. Office skills can use either resource independently. Profile patches can disable `skill-office` or replace its `assetRoot` independently of `workspace-dependencies`; filesystem skills with the same name take precedence. See the [runtime package](../../../python/sdk-runtime/README.md) for downloads and configuration. ----- ## Model Experience -### SDK coding-agent persona +### SDK model context #### What the model sees -The profile supplies `You are a coding agent powered by the {{model}} model.` before first-party guidance; the SDK initialization route resolves `{{model}}`. Each Session receives its current directory in required user-role context from [`dsh-working-directory`](../../session/working-directory/README.md). Default file tool schemas include `read`, `write`, and `edit`; they omit `str_replace_editor`. +The profile inherits the base system prompt, including the `You are an AI agent powered by DeepSeek Harness.` identity, without adding a task-specific persona. Each Session receives its current directory in required user-role context from [`dsh-working-directory`](../../session/working-directory/README.md). Default file tool schemas include `read`, `write`, and `edit`; they omit `str_replace_editor`. #### Token effect -One short stable persona plus the data-dependent base prompt sections and selected tool schemas. +The base prompt sections and selected tool schemas determine token usage; this profile adds no persona text. #### KV Cache effect diff --git a/packages/bundle/sdk-app/README.zh.md b/packages/bundle/sdk-app/README.zh.md index 026d442b1a..f244072935 100644 --- a/packages/bundle/sdk-app/README.zh.md +++ b/packages/bundle/sdk-app/README.zh.md @@ -9,7 +9,7 @@ kind: "package-bundle" ## 概述 -以 [`dsh-base`](../base/README.zh.md) 为基础的 SDK stdio 应用 `dsh` profile 组合包。它继承 base 默认禁用模块 HMR(热模块替换)的策略;其 patch 设置 coding agent(编程智能体)persona、挂载应用自有的零选项命令提供方,并且只在该提供方接受调用后启动 [`dsh-sdk-jsonrpc-server`](../../sdk/server/README.zh.md)。因此,`dsh --profile sdk --help` 会写出 help 并退出,不会占用 stdin 或 stdout。独立的 [`sdk-minimal`](../sdk-minimal/README.zh.md) bundle 复用同一个启动提供方,并提供自己的 profile 名称。 +以 [`dsh-base`](../base/README.zh.md) 为基础的 SDK stdio 应用 `dsh` profile 组合包。它继承 base 默认禁用模块 HMR(热模块替换)的策略;其 patch 挂载应用自有的零选项命令提供方,并且只在该提供方接受调用后启动 [`dsh-sdk-jsonrpc-server`](../../sdk/server/README.zh.md)。因此,`dsh --profile sdk --help` 会写出 help 并退出,不会占用 stdin 或 stdout。独立的 [`sdk-minimal`](../sdk-minimal/README.zh.md) bundle 复用同一个启动提供方,并提供自己的 profile 名称。 ## 目录 @@ -33,22 +33,22 @@ kind: "package-bundle" SDK 使用 base 默认提供的 `read`、`write` 和 `edit`。要添加 `str_replace_editor`,请使用 [base 配置指南](../base/README.zh.md#use-this-package)中的显式插入 patch。独立的 `sdk-minimal` profile 自行决定其工具选择。 -打包的 Python runtime 默认启用 [Office 运行时查询与 skills](../../skill/tool-workspace-dependencies/README.zh.md#use-this-package)。`DSH_PRIMARY_RUNTIME` 覆盖随包 payload;空值禁用两行。没有载体默认路径的源码启动仍需显式启用。工具原位读取 payload。profile patch 可独立于 `workspace-dependencies` 禁用 `skill-office` 或替换其 `assetRoot`;同名文件系统 skills 优先于随包 skills。打包与配置见 [runtime 包](../../../python/sdk-runtime/README.zh.md)。 +Python 运行时向本 profile 提供显式下载的创作资源和 Office sidecar。`DSH_PRIMARY_RUNTIME` 覆盖创作载荷;空值禁用其查询。Office skills 可独立使用任一种资源。Profile patch 可独立于 `workspace-dependencies` 禁用 `skill-office` 或替换其 `assetRoot`;同名文件系统 skills 优先。下载与配置见[运行时包](../../../python/sdk-runtime/README.zh.md)。 ----- ## 模型体验 -### SDK coding agent persona +### SDK 模型上下文 #### 模型看到什么 -profile 在第一方指导之前提供 `You are a coding agent powered by the {{model}} model.`;SDK 初始化路由解析 `{{model}}`。每个 Session 通过 [`dsh-working-directory`](../../session/working-directory/README.zh.md) 提供的必需 user-role 上下文接收当前目录。默认文件工具 schema 包含 `read`、`write` 和 `edit`,不包含 `str_replace_editor`。 +profile 继承 base 系统提示词,包括 `You are an AI agent powered by DeepSeek Harness.` 身份说明,不额外添加特定任务的 persona。每个 Session 通过 [`dsh-working-directory`](../../session/working-directory/README.zh.md) 提供的必需 user-role 上下文接收当前目录。默认文件工具 schema 包含 `read`、`write` 和 `edit`,不包含 `str_replace_editor`。 #### Token 影响 -一段简短稳定的 persona,加上随数据变化的 base 提示词段落与所选工具 schema。 +base 提示词段落与所选工具 schema 决定 token 用量;此 profile 不额外添加 persona 文本。 #### KV Cache 影响 diff --git a/packages/bundle/sdk-app/cordis.patch.yml b/packages/bundle/sdk-app/cordis.patch.yml index d852a0a41d..004a81ce9b 100644 --- a/packages/bundle/sdk-app/cordis.patch.yml +++ b/packages/bundle/sdk-app/cordis.patch.yml @@ -1,10 +1,5 @@ # The SDK application over dsh-base. Stdout belongs exclusively to JSON-RPC. -- id: system-prompt - config: - personaPrefix: >- - You are a coding agent powered by the {{model}} model. - - id: session-title-llm disabled: true @@ -34,7 +29,8 @@ - id: skill-office name: '@deepseek-ai/dsh-skill-office' - disabled: !!js "!(process.env.DSH_PRIMARY_RUNTIME ?? process.env.DSH_BUNDLED_PRIMARY_RUNTIME)" + disabled: !!js "!(process.env.DSH_PRIMARY_RUNTIME ?? process.env.DSH_BUNDLED_PRIMARY_RUNTIME) && !process.env.DSH_BUNDLED_OFFICE_CLI" config: - assetRoot: !!js "process.getBuiltinModule('node:path').resolve(process.env.DSH_PRIMARY_RUNTIME ?? process.env.DSH_BUNDLED_PRIMARY_RUNTIME ?? '', '..', 'office-skills')" - node: !!js "process.getBuiltinModule('node:path').resolve(process.env.DSH_PRIMARY_RUNTIME ?? process.env.DSH_BUNDLED_PRIMARY_RUNTIME ?? '', 'dependencies', 'node', 'bin', process.platform === 'win32' ? 'node.exe' : 'node')" + assetRoot: !!js "process.env.DSH_BUNDLED_OFFICE_SKILLS ?? process.getBuiltinModule('node:path').resolve(process.env.DSH_PRIMARY_RUNTIME ?? process.env.DSH_BUNDLED_PRIMARY_RUNTIME ?? '', '..', 'office-skills')" + cli: !!js "process.env.DSH_BUNDLED_OFFICE_CLI === '' ? false : process.env.DSH_BUNDLED_OFFICE_CLI" + node: !!js "process.env.DSH_BUNDLED_OFFICE_NODE ?? process.getBuiltinModule('node:path').resolve(process.env.DSH_PRIMARY_RUNTIME ?? process.env.DSH_BUNDLED_PRIMARY_RUNTIME ?? '', 'dependencies', 'node', 'bin', process.platform === 'win32' ? 'node.exe' : 'node')" diff --git a/packages/bundle/sdk-app/package.json b/packages/bundle/sdk-app/package.json index 23205a07e8..57a146abba 100644 --- a/packages/bundle/sdk-app/package.json +++ b/packages/bundle/sdk-app/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-sdk-app", "description": "The dsh SDK profile bundle: stdio JSON-RPC serving and process lifecycle over dsh-base", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/sdk-minimal/README.i18n.yaml b/packages/bundle/sdk-minimal/README.i18n.yaml index 1a22a57b32..b93af7197d 100644 --- a/packages/bundle/sdk-minimal/README.i18n.yaml +++ b/packages/bundle/sdk-minimal/README.i18n.yaml @@ -3,23 +3,23 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/bundle/sdk-minimal/README.md /: - en: 7cbc0e332890851f - zh: 07c71026d8e1bb15 + en: b2fce08b0fa865da + zh: 97e214d87ded4b54 /deepseek-ai-dsh-sdk-minimal: en: 807c43eedba7d53e zh: 9f1efe5d6ac393f7 /deepseek-ai-dsh-sdk-minimal/summary: - en: c0a98b4bcbb3e719 - zh: 92895dd5ce381cd1 + en: 31b83af058b212f9 + zh: 289678ac3738ee5e /deepseek-ai-dsh-sdk-minimal/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-sdk-minimal/use-this-package: - en: f920307c0cf12118 - zh: edf9051846fecd5c + en: 39483eef4a61f212 + zh: 62d82f46a04e07fe /deepseek-ai-dsh-sdk-minimal/understand-the-implementation: - en: 91f4a78ab7a688d3 - zh: 7bb8bf33c0d8b429 + en: 5db5d8f041867958 + zh: bff5ef3a2e140712 /deepseek-ai-dsh-sdk-minimal/understand-the-implementation/source-map: en: 3784c554e96ab004 zh: 0a05d4fe1e26b3b1 @@ -33,17 +33,17 @@ en: bd87e16b0c6e0506 zh: c8ee5e3b4578754e /deepseek-ai-dsh-sdk-minimal/model-experience/minimal-coding-agent-composition/what-the-model-sees: - en: 724e1f4075df9293 - zh: 35955569ded10b56 + en: df40d9529b566cfa + zh: 4678769b4f85120b /deepseek-ai-dsh-sdk-minimal/model-experience/minimal-coding-agent-composition/token-effect: - en: 5df298b2c9f95d27 - zh: def93cd59b5ca843 + en: 9b7a23c7a447eb22 + zh: e01bfd06d19b7d18 /deepseek-ai-dsh-sdk-minimal/model-experience/minimal-coding-agent-composition/kv-cache-effect: - en: 904ae09b5fdb87c1 - zh: de6fcaaa12bd9733 + en: dd887b6519f40ab3 + zh: a98e56411fdc79df /deepseek-ai-dsh-sdk-minimal/known-limitations-and-deferred-work: - en: 8f74b1b4f39eda83 - zh: af96ec4cb42810c5 + en: 00c4192d6af9f621 + zh: 460451ab6dc07c3a /deepseek-ai-dsh-sdk-minimal/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/bundle/sdk-minimal/README.md b/packages/bundle/sdk-minimal/README.md index 7a4a0ff127..9accd1fec2 100644 --- a/packages/bundle/sdk-minimal/README.md +++ b/packages/bundle/sdk-minimal/README.md @@ -1,5 +1,5 @@ --- -description: "Standalone SDK profile with a persistent shell and Session working-directory tool for a minimal cross-platform coding agent without the shared base bundle." +description: "Standalone SDK profile with a persistent shell, image reading, automatic context compaction, and a Session working-directory tool for a minimal cross-platform coding agent without the shared base bundle." kind: "package-bundle" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Use `dsh --profile sdk-minimal` when an SDK client needs a small, explicit coding-agent runtime. By default, the profile advertises a platform-selected persistent shell and `working_directory`, persists sessions as uncompressed JSONL, and selects the model from the SDK initialization request. It supplies a complete Cordis tree and excludes `dsh-base`, Web, settings, managed credentials, telemetry, compaction, filesystem tools, workspace instructions, skills, jobs, and subagents. Its danger-full-access policy lets the shell modify any path available to the process, so use it only with an isolated workspace. +Use `dsh --profile sdk-minimal` when an SDK client needs a small, explicit coding-agent runtime. By default, the profile advertises a platform-selected persistent shell, `read_image`, and `working_directory`, persists sessions as uncompressed JSONL, and selects the model from the SDK initialization request. It supplies a complete Cordis tree and excludes `dsh-base`, Web, settings, managed credentials, telemetry, text file tools, workspace instructions, skills, jobs, and subagents. Its danger-full-access policy lets the shell modify any path available to the process, so use it only with an isolated workspace. ## Table of Contents @@ -38,7 +38,7 @@ Use `dsh plugin --profile sdk-minimal` to manage persistent external dependencie The profile mounts exactly one persistent shell stack: Bash on Linux and macOS, or PowerShell on Windows. Both stacks use a 300-second timeout and one owner-scoped terminal; the other platform's rows remain disabled. -Like every shipped profile, it mounts [MCP resources](../../mcp/mcp-resources/README.md) once. Configure only [MCP client entries](../../mcp/mcp-client/README.md) to add servers. Clients mounted by another provider also count as configured. With no server configured in the caller's scope, MCP contributes no prompt text or tools and the default remains the shell and `working_directory` tools. +Like every shipped profile, it mounts [MCP resources](../../mcp/mcp-resources/README.md) once. Configure only [MCP client entries](../../mcp/mcp-client/README.md) to add servers. Clients mounted by another provider also count as configured. With no server configured in the caller's scope, MCP contributes no prompt text or tools and the default remains the shell, `read_image`, and `working_directory` tools. ----- @@ -48,7 +48,7 @@ Like every shipped profile, it mounts [MCP resources](../../mcp/mcp-resources/RE
Implementation internals — click to expand -The bundle's single insert is the complete application tree: SDK stdio startup and JSON-RPC serving, one environment-configured DeepSeek adapter, the explicit agent core, conditional MCP resource tools, local filesystem and subprocess services, Session working-directory state and its tool, a platform-selected persistent shell PTY, and uncompressed JSONL persistence under `$DSH_HOME/sessions`. It does not inherit another bundle, so every extra row is an explicit profile change. +The bundle's single insert is the complete application tree: SDK stdio startup and JSON-RPC serving, one environment-configured DeepSeek adapter, the explicit agent core, conditional MCP resource tools, local filesystem, image attachments, automatic context compaction, and subprocess services, Session working-directory state and its tool, a platform-selected persistent shell PTY, and uncompressed JSONL persistence under `$DSH_HOME/sessions`. It does not inherit another bundle, so every extra row is an explicit profile change. ### Source map @@ -78,21 +78,23 @@ The bundle's single insert is the complete application tree: SDK stdio startup a #### What the model sees -The system prompt is `DSH_SYSTEM_PROMPT` or `You are a helpful software engineer assistant.`. With no MCP server configured, the advertised tools are `working_directory` and owner-scoped persistent `bash` on Linux/macOS or `pwsh` on Windows. Required user context supplies the current directory. Optional runtime context, filesystem tools, workspace instructions, skills, jobs controls, compaction, and Harness identity are absent. +The system prompt is `DSH_SYSTEM_PROMPT` or `You are a helpful software engineer assistant.`. With no MCP server configured, the advertised tools are `read_image`, `working_directory`, and owner-scoped persistent `bash` on Linux/macOS or `pwsh` on Windows. Required user context supplies the current directory. Optional runtime context, text file tools, workspace instructions, skills, jobs controls, and Harness identity are absent. #### Token effect -By default, one stable persona, two tool schemas, and user context for the initial directory and subsequent changes. Configured MCP servers add their tools, shared resource tools, and available server instructions. Tool results and ordinary conversation history grow with the session. +By default, one stable persona, three tool schemas, and user context for the initial directory and subsequent changes. Configured MCP servers add their tools, shared resource tools, and available server instructions. Images consume model input tokens. When images exceed the route budget, [image offload](../../compaction/compaction-image-offload/README.md) permanently replaces older image occurrences with attachment/path placeholders and retries the request or compaction summary. Automatic compaction sends an additional summarization request when context pressure reaches the configured threshold and replaces older model-visible history with its summary; the durable JSONL log retains those events. #### KV Cache effect -Stable for a fixed persona, platform, provider, model, and bundle patch stack. Profile changes take effect on the next process. +Stable for a fixed persona, platform, provider, model, and bundle patch stack. Compaction replaces part of the request history and can reduce cache reuse. Image offload also ends cache reuse at the first changed image. Profile changes take effect on the next process. ## Known Limitations and Deferred Work - **The composition intentionally omits shared product services** — select `dsh --profile sdk` when settings, managed credentials, policy presets, telemetry, Web tools, or the full default tool roster are required. +- **Image reading requires an image-capable model** — select a route whose adapter declares image input; text-only routes return a tool error. Images are stored under `$DSH_HOME/attachments/v1`. +- **Compaction is automatic** — configure [compaction-basic](../../compaction/compaction-basic/README.md) through profile patches. SDK prompt text does not execute `/compact` or other slash commands. - **User patches can expand the tree and corrupt stdout** — profile customization is trusted application composition; a plugin that writes ordinary text to stdout can break JSON-RPC framing. diff --git a/packages/bundle/sdk-minimal/README.zh.md b/packages/bundle/sdk-minimal/README.zh.md index 96de535e19..d35655df20 100644 --- a/packages/bundle/sdk-minimal/README.zh.md +++ b/packages/bundle/sdk-minimal/README.zh.md @@ -1,5 +1,5 @@ --- -description: "独立 SDK profile,提供持久 shell 和 Session 工作目录工具,用于不含共享 base bundle 的极简跨平台 coding agent(编程智能体)。" +description: "独立 SDK profile,提供持久 shell、图片读取、自动上下文压缩和 Session 工作目录工具,用于不含共享 base bundle 的极简跨平台 coding agent(编程智能体)。" kind: "package-bundle" --- @@ -9,7 +9,7 @@ kind: "package-bundle" ## 概述 -当 SDK 客户端需要小型、显式的 coding agent 运行时时,请使用 `dsh --profile sdk-minimal`。该 profile 默认公布按平台选择的持久 shell 和 `working_directory`,把会话持久化为未压缩 JSONL,并从 SDK 初始化请求选择模型。它提供完整 Cordis 配置树,并排除 `dsh-base`、Web、settings、托管凭据、遥测、压缩(compaction)、文件系统工具、workspace 指令、skill(技能)、jobs 与 subagent。其 danger-full-access 策略允许 shell 修改进程可访问的任何路径,因此只能配合隔离 workspace 使用。 +当 SDK 客户端需要小型、显式的 coding agent 运行时时,请使用 `dsh --profile sdk-minimal`。该 profile 默认公布按平台选择的持久 shell、`read_image` 和 `working_directory`,把会话持久化为未压缩 JSONL,并从 SDK 初始化请求选择模型。它提供完整 Cordis 配置树,并排除 `dsh-base`、Web、settings、托管凭据、遥测、文本文件工具、workspace 指令、skill(技能)、jobs 与 subagent。其 danger-full-access 策略允许 shell 修改进程可访问的任何路径,因此只能配合隔离 workspace 使用。 ## 目录 @@ -38,7 +38,7 @@ dsh --profile sdk-minimal 该 profile 只挂载一套持久 shell:Linux 和 macOS 使用 Bash,Windows 使用 PowerShell。两套配置都使用 300 秒超时与一个 agent 自有终端;另一平台的配置项保持禁用。 -与其他随附 profile 一样,它统一挂载 [MCP 资源](../../mcp/mcp-resources/README.zh.md)一次。只需配置 [MCP 客户端条目](../../mcp/mcp-client/README.zh.md)即可添加服务器。其他提供方挂载的客户端也属于已配置状态。调用方作用域中未配置服务器时,MCP 不贡献提示词文本或工具,默认仍为 shell 与 `working_directory` 两个工具。 +与其他随附 profile 一样,它统一挂载 [MCP 资源](../../mcp/mcp-resources/README.zh.md)一次。只需配置 [MCP 客户端条目](../../mcp/mcp-client/README.zh.md)即可添加服务器。其他提供方挂载的客户端也属于已配置状态。调用方作用域中未配置服务器时,MCP 不贡献提示词文本或工具,默认仍为 shell、`read_image` 与 `working_directory` 三个工具。 ----- @@ -48,7 +48,7 @@ dsh --profile sdk-minimal
实现细节——点击展开 -该 bundle 的单个 insert 就是完整应用配置树:SDK stdio 启动与 JSON-RPC 服务、一个由环境配置的 DeepSeek 适配器、显式 agent 核心、按配置启用的 MCP 资源工具、本地文件系统与子进程服务、Session 工作目录状态及其工具、按平台选择的持久 shell PTY,以及位于 `$DSH_HOME/sessions` 的未压缩 JSONL 持久化。它不继承其他 bundle,因此每个额外配置项都是显式 profile 变更。 +该 bundle 的单个 insert 就是完整应用配置树:SDK stdio 启动与 JSON-RPC 服务、一个由环境配置的 DeepSeek 适配器、显式 agent 核心、按配置启用的 MCP 资源工具、本地文件系统、图片附件、自动上下文压缩与子进程服务、Session 工作目录状态及其工具、按平台选择的持久 shell PTY,以及位于 `$DSH_HOME/sessions` 的未压缩 JSONL 持久化。它不继承其他 bundle,因此每个额外配置项都是显式 profile 变更。 ### 源码地图 @@ -78,21 +78,23 @@ dsh --profile sdk-minimal #### 模型看到的内容 -系统提示词取 `DSH_SYSTEM_PROMPT`,未设置时使用 `You are a helpful software engineer assistant.`。未配置 MCP 服务器时,对外公布的工具为 `working_directory`,以及 Linux/macOS 上 agent 所有的持久 `bash` 或 Windows 上的 `pwsh`。必需的用户上下文提供当前目录。可选运行时上下文、文件系统工具、workspace 指令、skill、jobs 控制、压缩与 Harness 身份均不存在。 +系统提示词取 `DSH_SYSTEM_PROMPT`,未设置时使用 `You are a helpful software engineer assistant.`。未配置 MCP 服务器时,对外公布的工具为 `read_image`、`working_directory`,以及 Linux/macOS 上 agent 所有的持久 `bash` 或 Windows 上的 `pwsh`。必需的用户上下文提供当前目录。可选运行时上下文、文本文件工具、workspace 指令、skill、jobs 控制与 Harness 身份均不存在。 #### Token 影响 -默认是一个稳定 persona、两个工具 schema,以及初始目录与后续变更的用户上下文。已配置 MCP 服务器会添加自己的工具、共享资源工具及可用的服务器指令。工具结果与普通对话历史随会话增长。 +默认是一个稳定 persona、三个工具 schema,以及初始目录与后续变更的用户上下文。已配置 MCP 服务器会添加自己的工具、共享资源工具及可用的服务器指令。图片消耗模型输入 token。图片超过路由预算时,[图片省略](../../compaction/compaction-image-offload/README.zh.md)会永久将较早的图片位置替换为包含附件与路径的占位文本,并重试请求或压缩摘要。上下文压力达到配置阈值时,自动压缩会额外发起摘要请求,并用摘要替换较早的模型可见历史;持久 JSONL 日志保留这些事件。 #### KV Cache 影响 -当 persona、平台、提供方、模型与 bundle patch 栈固定时保持稳定。Profile 变更在下一个进程生效。 +当 persona、平台、提供方、模型与 bundle patch 栈固定时保持稳定。压缩会替换部分请求历史,可能降低缓存复用率。图片省略还会使缓存复用止于第一张被修改的图片。Profile 变更在下一个进程生效。 ## 已知限制与延期工作 - **该组合刻意省略共享产品服务** — 需要 settings、托管凭据、策略预设、遥测、Web 工具或完整默认工具清单时,请选择 `dsh --profile sdk`。 +- **图片读取需要支持图片输入的模型** — 选择适配器声明支持图片输入的路由;纯文本路由会返回工具错误。图片存储在 `$DSH_HOME/attachments/v1` 下。 +- **压缩由系统自动执行** — 通过 profile patch 配置 [compaction-basic](../../compaction/compaction-basic/README.zh.md)。SDK 提示词文本不会执行 `/compact` 或其他斜杠命令。 - **用户 patch 可以扩展配置树并破坏 stdout** — profile 自定义属于受信任的应用组合;向 stdout 写入普通文本的插件会破坏 JSON-RPC 分帧。 diff --git a/packages/bundle/sdk-minimal/cordis.patch.yml b/packages/bundle/sdk-minimal/cordis.patch.yml index 6c8dbce78a..79922e7113 100644 --- a/packages/bundle/sdk-minimal/cordis.patch.yml +++ b/packages/bundle/sdk-minimal/cordis.patch.yml @@ -38,6 +38,17 @@ - id: filesystem name: '@deepseek-ai/dsh-fs-local' + - id: attachment-local + name: '@deepseek-ai/dsh-attachment-local' + + - id: tool-fs + name: '@deepseek-ai/dsh-tool-fs' + config: + read: false + readImage: true + write: false + edit: false + - id: working-directory name: '@deepseek-ai/dsh-working-directory' @@ -47,6 +58,15 @@ - id: session-projection name: '@deepseek-ai/dsh-session-projection' + - id: token-meter + name: '@deepseek-ai/dsh-token-meter' + + - id: compaction-basic + name: '@deepseek-ai/dsh-compaction-basic' + + - id: image-offload + name: '@deepseek-ai/dsh-compaction-image-offload' + - id: sandbox-policy name: '@deepseek-ai/dsh-sandbox-policy' config: diff --git a/packages/bundle/sdk-minimal/package.json b/packages/bundle/sdk-minimal/package.json index 236e7e4240..0a1c6b3317 100644 --- a/packages/bundle/sdk-minimal/package.json +++ b/packages/bundle/sdk-minimal/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-sdk-minimal", "description": "The standalone minimal SDK profile bundle: JSON-RPC, one DeepSeek adapter, persistent shell, and JSONL sessions", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -40,6 +40,9 @@ "@deepseek-ai/cordis-plugin-timer": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-agent-loop": "workspace:*", + "@deepseek-ai/dsh-attachment-local": "workspace:*", + "@deepseek-ai/dsh-compaction-basic": "workspace:*", + "@deepseek-ai/dsh-compaction-image-offload": "workspace:*", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*", "@deepseek-ai/dsh-jobs-local": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", @@ -60,7 +63,9 @@ "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-terminal": "workspace:*", "@deepseek-ai/dsh-terminal-bash": "workspace:*", + "@deepseek-ai/dsh-token-meter": "workspace:*", "@deepseek-ai/dsh-tool-bash-persistent": "workspace:*", + "@deepseek-ai/dsh-tool-fs": "workspace:*", "@deepseek-ai/dsh-tool-pwsh-persistent": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", diff --git a/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts b/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts index 4194bdf4b0..f4e24e5bc5 100644 --- a/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts +++ b/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts @@ -34,9 +34,14 @@ describe('dsh-sdk-minimal bundle', () => { ['llm-deepseek', '@deepseek-ai/dsh-llm-deepseek-api-key'], ['sandbox', '@deepseek-ai/dsh-sandbox-local'], ['filesystem', '@deepseek-ai/dsh-fs-local'], + ['attachment-local', '@deepseek-ai/dsh-attachment-local'], + ['tool-fs', '@deepseek-ai/dsh-tool-fs'], ['working-directory', '@deepseek-ai/dsh-working-directory'], ['tool-working-directory', '@deepseek-ai/dsh-tool-working-directory'], ['session-projection', '@deepseek-ai/dsh-session-projection'], + ['token-meter', '@deepseek-ai/dsh-token-meter'], + ['compaction-basic', '@deepseek-ai/dsh-compaction-basic'], + ['image-offload', '@deepseek-ai/dsh-compaction-image-offload'], ['sandbox-policy', '@deepseek-ai/dsh-sandbox-policy'], ['subprocess', '@deepseek-ai/dsh-subprocess-local'], ['pty', '@deepseek-ai/dsh-terminal'], @@ -73,6 +78,8 @@ describe('dsh-sdk-minimal bundle', () => { personaPrefix: { __jsExpr: "process.env.DSH_SYSTEM_PROMPT ?? 'You are a helpful software engineer assistant.'" }, }) expect(rows.find(row => row.id === 'agent-loop')?.config).toEqual({ agents: [] }) + expect(rows.find(row => row.id === 'tool-fs')?.config).toEqual({ read: false, readImage: true, write: false, edit: false }) + expect(rows.find(row => row.id === 'compaction-basic')?.config).toBeUndefined() expect(rows.find(row => row.id === 'terminal-bash')).toMatchObject({ disabled: { __jsExpr: "process.platform === 'win32'" }, }) diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml index 0c5a6c4a2e..1d8e07a01e 100644 --- a/packages/bundle/web-app/README.i18n.yaml +++ b/packages/bundle/web-app/README.i18n.yaml @@ -9,8 +9,8 @@ en: a85684740ecd278a zh: 7c54099b9edccf01 /deepseek-ai-dsh-web-app/summary: - en: fd97ee0c14fb5378 - zh: 0e1ccba47bc408d9 + en: 0a2a9876194543e5 + zh: ff472776a44ae260 /deepseek-ai-dsh-web-app/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb @@ -18,59 +18,56 @@ en: 3bd37b85139d2fa7 zh: ba86c807eb83866e /deepseek-ai-dsh-web-app/use-this-package/starting-the-web-gui: - en: b7ab01cfe9fed40f - zh: 23703ab7727c3ab5 + en: e3cac911f080d8ef + zh: 60749e9f5c39c1bc /deepseek-ai-dsh-web-app/use-this-package/configuration: - en: a9ee366c5af68a6c - zh: 2711d7a3926e1101 + en: b1787804544f2587 + zh: ce09d2c248ffd999 /deepseek-ai-dsh-web-app/use-this-package/listening-trust-and-public-deployments: - en: a79add86cb73d966 - zh: 78b58259f98ed063 + en: e6ddea1d2fc40501 + zh: ff08b6fa3fc24136 /deepseek-ai-dsh-web-app/use-this-package/running-over-ssh: - en: 45db677dcc91c5c9 - zh: 75b765f7f1e15035 + en: df205a26b6d49168 + zh: e46ed7cf9e06248a /deepseek-ai-dsh-web-app/use-this-package/per-session-agent-setup: en: ccd6fc264b51e44b zh: 3265c68477a89ec9 /deepseek-ai-dsh-web-app/understand-the-implementation: - en: fb819d10930089a8 - zh: f2dee0ff170a4d41 + en: 323742a00cfe67b2 + zh: eff5245a82fc16e7 /deepseek-ai-dsh-web-app/understand-the-implementation/patch-semantics: - en: 23ddb4d33e79c0a1 - zh: dc9a458b9492b49b + 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/lan-trust-sampling: - en: b5ed8ff0056ca9da - zh: fdc1fa4f14cb00b3 /deepseek-ai-dsh-web-app/understand-the-implementation/source-map: - en: e41444bed021a121 - zh: 44088a90df50d5b4 + 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: d6de1d07249ef3b0 - zh: 49d01329256e2eb3 + en: 635c1336e2f4e821 + zh: caabdecb02e2df14 /deepseek-ai-dsh-web-app/known-limitations-and-deferred-work/dev-note: en: 3f81b4f3beb74a0d zh: 2e377ca40822d093 diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md index fc4584fbad..2305d402cd 100644 --- a/packages/bundle/web-app/README.md +++ b/packages/bundle/web-app/README.md @@ -13,7 +13,7 @@ Desktop analytics schedules partial batches every 30 seconds, with a 15-second e ## Summary -Run `dsh --profile web` for browser chat, model and settings management, and session history, using the same model access, tools, and safety defaults as other dsh surfaces. Startup prints a tokenized URL and normally opens the default browser; SSH sessions and `--no-open` require manual opening. You can change the port and allow extra hosts, but cannot bind all network interfaces. Remote access supports an advertised public HTTP(S) URL behind a prefix-stripping proxy. For one-shot command-line tasks, use `dsh-headless`. +Run `dsh --profile web` for browser chat, model and settings management, and session history, with the same model access, tools, and safety defaults as other dsh surfaces. Startup prints a tokenized URL and normally opens the default browser; SSH sessions and `--no-open` require manual opening. You can change the port, allow extra authorities, bind one concrete local IP, and serve HTTPS from a certificate you supply; wildcard addresses are rejected. Remote access uses an advertised HTTP(S) URL behind a prefix-stripping proxy, listener TLS, or plain HTTP on a non-loopback bind. Use the headless profile for one-shot command-line tasks. ## Table of Contents @@ -40,36 +40,51 @@ dsh --profile web --no-open --port 8080 After startup you see a `dsh web:` line whose root URL carries a fresh process token. Unless `--no-open` or an SSH session suppresses it, the default browser opens that URL, receives a signed cookie, and redirects to the same directory without the token. You know it worked when the page loads and you can chat with the agent. Two failures to expect: if the frontend is not built, startup stops with a build hint (`pnpm run build` in a checkout); if the browser cannot be opened, a credential-free diagnostic prints to stderr while the server keeps running — open the printed startup URL yourself. -**Settings → Models** displays **DeepSeek**, using `DEEPSEEK_API_KEY`. The default is `deepseek-official` / `deepseek-flash` (DeepSeek-V41-Flash). The [DeepSeek plugin](../../llm/llm-deepseek/README.md#endpoint-and-wire-format) uses the Messages API. +**Settings → Models** displays **DeepSeek**, using `DEEPSEEK_API_KEY`. The default is `deepseek-official` / `deepseek-flash` (DeepSeek-V4.1-Flash). The [DeepSeek plugin](../../llm/llm-deepseek/README.md#endpoint-and-wire-format) uses the Messages API. Saved model selections override the composition default. The settings card accepts a Messages-compatible API address and a credential reference. ### Configuration -`--host` and `--port` configure the listener; `--public-url` names the advertised public HTTP(S) root the GUI is reached at behind a prefix-stripping proxy, and `--trusted-host` adds further accepted authorities. All are described under [Listening, trust, and public deployments](#public-deployments): +The `minimal` agent preset uses a persistent shell, the `read_image` tool, and a fixed persona, with automatic history compaction and the idle-session `/compact` command. It shares the Host token meter and owns an isolated compaction backend. [Compaction configuration and retention](../../compaction/compaction-basic/README.md#use-this-package) follow the existing backend. Image reads reuse the Host filesystem and attachment store and require an image-capable model; text read, write, and edit tools remain excluded. + +`--host` and `--port` configure the listener; `--tls-cert` and `--tls-key` make it serve HTTPS; `--public-url` names the advertised public HTTP(S) root the GUI is reached at behind a prefix-stripping proxy, and `--trusted-host` adds further accepted authorities. All are described under [Listening, trust, and public deployments](#public-deployments), and the `tls` field those flags set is documented with the [carrier's config](../../../docs/subsystems/web-server.md#config): | Field | Default | Meaning | |---|---|---| | `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 | -| `publicUrl` | Unset | Advertised HTTP(S) application root; otherwise announce the listener's loopback URL | -| `trustedHosts` | `[]` | Extra hosts allowed to reach the GUI from the network | +| `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. ### Listening, trust, and public deployments -By default the GUI listens on loopback and accepts connections from this machine only; repeatable `--trusted-host` adds the authorities its Host/Origin fence accepts, so a remote browser reaches it behind a prefix-stripping proxy or through a port-forwarding client that presents a trusted hostname. +By default the GUI listens on loopback and accepts connections from this machine only. Only `--host` changes the listener: it accepts one concrete local IPv4 or IPv6 address, never a wildcard. A non-loopback listener without TLS serves plain HTTP and warns at startup, even when an HTTPS `--public-url` fronts it. The Host/Origin fence accepts the bind IP itself; other non-loopback authorities require `--trusted-host`, so a remote browser reaches the GUI behind a prefix-stripping proxy or through a port-forwarding client that presents a trusted hostname. The launch-token exchange and signed session cookie authenticate every API method and WebSocket stream. -`--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. +Pass `--tls-cert` and `--tls-key` together to serve HTTPS from the listener instead of plain HTTP. Each names a file resolved against the process working directory: the certificate file holds the full chain and the key file an unencrypted PEM private key. The flags are one setting — supplying only one is a usage error, and supplying neither keeps the plain-HTTP default. Startup fails when a file is missing, unreadable, empty, or not a valid certificate-and-key pair; it never falls back to HTTP. Nothing re-reads the material while the listener runs, so serving a different certificate needs a listener reload or a process restart. DSH issues, renews, and watches nothing: there is no ACME client, no self-signed fallback, and no redirect listener. The browser applies its own trust store and host-name matching, so a certificate the browser does not trust, or one whose subject alternative names miss the authority you open, fails before the page loads. The default port stays 3080, and `--tls-cert`/`--tls-key` do not follow `--public-url`: the listener's certificate covers the authority browsers dial. TLS changes nothing about authority: Connection still authenticates every request and still checks Host/Origin, and the session cookie it mints is `Secure` whenever the receiving listener serves HTTPS. -The printed URL contains a process credential; share it only with intended users, and `printUrl: false` suppresses the line with or without `--public-url`. +A container can bind its Pod address and advertise the ingress that fronts it: + +```sh +dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public-url https://app.example/ --trusted-host app.example +``` + +`hostname -i` may list several addresses; `--host` takes one, so the command selects the first. A zone ID such as `fe80::1%eth0` cannot appear in a URL, so the advertised root drops a redundant loopback zone while a non-loopback zone requires an explicit `--public-url`. + +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 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. + +The printed URL contains a process credential; share it only with intended users. `printUrl: false` suppresses the line with or without `--public-url`, and the credential never appears in the model context or in `DSH_WEB_URL`. ### Running over SSH -When you launch `dsh --profile web` over SSH, the URL line still prints but the browser is not opened for you: the SSH client or editor owns the local forwarding address. Without an advertised root the printed URL names the remote host's loopback endpoint, which you reach through your forwarding address. With `--public-url` the printed URL is the authenticated advertised root; the browser handoff stays suppressed, because opening a browser on the remote host cannot reach your screen. +When you launch `dsh --profile web` over SSH, the URL line still prints but the browser is not opened for you: the SSH client or editor owns the local forwarding address. Without an advertised root the printed URL names the remote host's bind-address endpoint — loopback for a loopback bind — which you reach through your forwarding address. With `--public-url` the printed URL is the authenticated advertised root; the browser handoff stays suppressed, because opening a browser on the remote host cannot reach your screen. ### Per-session agent setup @@ -83,37 +98,32 @@ 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, trust sampling, 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 -A patch replaces the targeted row's whole `config`, so each web row restates every key it owns: the persona prefix template, the `DSH_TOOLS_MODE` PTC mode opt-in, and the `session-query-sqlite` values on the base rows, then `insert` adds the web host rows, transport, and browser roster. The `webserver` and `web-runtime` rows inject the `webStartup` provider and read their invocation values directly; the `connection` row instead reads the bind-dependent `webRuntime` values the web-runtime row publishes, which are that provider's authorities plus the LAN literals of an all-interfaces bind. The per-agent tool rows the base mounts process-wide are disabled here and the preset roster takes over; the reasoning for each host-plane versus preset-plane decision is inline in the patch. +A patch replaces the targeted row's whole `config`, so each web row restates every key it owns: the persona prefix template, the `DSH_TOOLS_MODE` PTC mode opt-in, and the `session-query-sqlite` values on the base rows, then `insert` adds the web host rows, transport, and browser roster. The `webserver`, `web-runtime`, and `connection` rows inject the `webStartup` provider and read their invocation values directly; Connection composes its accepted authorities from `ctx.webStartup.trustedHosts`, and the Host/Origin fence accepts the listener's bind IP independently of that list. The per-agent tool rows the base mounts process-wide are disabled here and the preset roster takes over; the reasoning for each host-plane versus preset-plane decision is inline in the patch. ### 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 The URL line and browser handoff are readiness signals: supervisors RPC as soon as they observe the line, and a browser requests the page as soon as it opens, so both run only after the Loader tree settles, the required-startup audit passes, and Connection authentication is available — or immediately in a hand-built tree without a Loader. Client combo JavaScript and source maps remain unmaterialized at this point. Optional plugin failures do not suppress readiness; a required startup failure or a tree disposed mid-boot announces nothing. -### LAN trust sampling - -`resolveLanTrust` samples the network once at boot: a loopback bind (`127.0.0.1`) derives no LAN addresses, while an all-interfaces bind adds every non-internal IPv4 literal. The derived literals plus the explicit `--trusted-host` authorities form the `/api` browser-trust fence, and the printed LAN URL always matches that fence. - ### Source map | File | Role | |---|---| -| [`src/index.ts`](src/index.ts) | The `web-app` glue plugin: dist resolution, advertised application URL, LAN trust sampling, 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`, `--public-url`, `--trusted-host`, `--no-open`, `--help` | +| [`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 resolution, fallback seat, prompt sections, readiness, advertised URL 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/trusted-hosts.spec.ts`](tests/trusted-hosts.spec.ts) | LAN-trust sampling | | [`tests/browser-open.spec.ts`](tests/browser-open.spec.ts) | Default-browser handoff after the page is reachable |
@@ -136,19 +146,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 @@ -158,12 +168,12 @@ Source and Web sections follow first-party reusable instructions. Different chec These limits tell you what to expect in unusual setups — a source checkout, SSH sessions, or strict networks. They are current package constraints, not a general browser comparison or a task backlog. - **The frontend must be built** — a source checkout needs `pnpm run build` first; startup stops with a build hint when the dist is missing, and there is no source-serving fallback. -- **The listener has no TLS** — protect the external leg with a TLS-terminating proxy; an HTTP advertised root sends credentials without encryption. -- **LAN addresses are sampled once at startup** — interface changes after boot are not re-advertised; the printed LAN URL always matches what was sampled. +- **TLS is opt-in and unmanaged** — the listener serves HTTPS only when `--tls-cert` and `--tls-key` name a full chain and its unencrypted key; DSH never obtains, renews, or watches certificates, and a changed file needs a listener reload or a process restart. The browser must trust that certificate, its names must cover the authority you open, and the certificate is independent of `--public-url`. +- **Without TLS the external leg is plain HTTP** — protect it with a TLS-terminating proxy, and do not send the launch URL over a network you do not trust. - **Only the handoff start is observable** — the GUI reports that the browser was asked to open, not that it actually opened; a later browser exit is never reported, and the printed URL is your manual fallback. -- **SSH sessions keep the URL but skip the browser handoff** — without an advertised root the printed URL names the remote host's loopback endpoint; the SSH client or editor must expose and open the local forwarded address. +- **SSH sessions keep the URL but skip the browser handoff** — without an advertised root the printed URL names the remote host's bind-address endpoint (loopback for a loopback bind); the SSH client or editor must expose and open the local forwarded address. - **`BROWSER` overrides only come from the environment** — a discovered `.env` cannot set `BROWSER`; only an inherited value can choose the executable for the automatic handoff. -- **Binding all network interfaces is not supported** — `--host 0.0.0.0` is rejected at startup for safety; use the default loopback host. +- **Binding all network interfaces is not supported** — a wildcard `--host`, including the IPv4-mapped forms Linux reads as IPv4 any, is rejected at startup for safety; bind one concrete IPv4 or IPv6 address of a local interface instead. ### Dev Note diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md index 3b7774bfd2..8d08ede8af 100644 --- a/packages/bundle/web-app/README.zh.md +++ b/packages/bundle/web-app/README.zh.md @@ -13,7 +13,7 @@ kind: "package-bundle" ## 概述 -运行 `dsh --profile web`,获得浏览器内的聊天、模型与设置管理以及会话历史,并与其他 dsh 表层共用同一套模型访问、工具与安全默认值。启动时会打印带 token 的 URL,通常还会在默认浏览器中打开;SSH 会话和 `--no-open` 需要手动打开。你可以更改端口并允许额外主机,但不能绑定所有网络接口。跨机访问支持在剥离前缀的代理之后公告一个公开的 HTTP(S) URL。一次性的命令行任务应使用 `dsh-headless`。 +运行 `dsh --profile web`,获得浏览器内的聊天、模型与设置管理以及会话历史,并与其他 dsh 表层共用同一套模型访问、工具与安全默认值。启动时会打印带 token 的 URL,通常还会在默认浏览器中打开;SSH 会话和 `--no-open` 需要手动打开。你可以更改端口、允许额外 authority、绑定一个具体的本机 IP,并用自己提供的证书直接提供 HTTPS;通配地址会被拒绝。跨机访问使用剥离前缀代理后公告的 HTTP(S) URL、监听器 TLS,或非 loopback 绑定上的明文 HTTP。一次性的命令行任务应使用 headless 配置。 ## 目录 @@ -40,36 +40,51 @@ dsh --profile web --no-open --port 8080 启动后你会看到 `dsh web:` 行,其根 URL 携带新的进程 token。除非 `--no-open` 或 SSH 会话抑制,否则默认浏览器会打开该 URL、取得签名 cookie,再重定向到不含认证参数的同一目录。页面加载且你可以与 agent 对话,就说明成功了。两种可预期的失败:前端未构建时,启动会以构建提示停止(checkout 中运行 `pnpm run build`);浏览器无法打开时,stderr 会打印不含凭据的诊断,但服务器会继续运行——请自行打开已打印的启动 URL。 -**设置 → 模型**显示 **DeepSeek**,使用 `DEEPSEEK_API_KEY`。默认模型为 `deepseek-official` / `deepseek-flash`(DeepSeek-V41-Flash)。[DeepSeek 插件](../../llm/llm-deepseek/README.zh.md#endpoint-and-wire-format)使用 Messages API。 +**设置 → 模型**显示 **DeepSeek**,使用 `DEEPSEEK_API_KEY`。默认模型为 `deepseek-official` / `deepseek-flash`(DeepSeek-V4.1-Flash)。[DeepSeek 插件](../../llm/llm-deepseek/README.zh.md#endpoint-and-wire-format)使用 Messages API。 已保存的模型选择覆盖组合默认值。设置卡接受兼容 Messages 的 API 地址与凭据引用。 ### 配置 -`--host` 与 `--port` 配置监听器;`--public-url` 指定 GUI 在剥离前缀的代理之后对外公告的公开 HTTP(S) 根,`--trusted-host` 则添加更多被接受的 authority。两者都在[监听、信任与公开部署](#public-deployments)中说明: +`minimal` agent preset 使用持久 Shell、`read_image` 工具和固定 persona,支持自动历史压缩以及会话空闲时的 `/compact` 命令。它复用 Host token meter,并拥有隔离的压缩后端。[压缩配置与保留策略](../../compaction/compaction-basic/README.zh.md#use-this-package) 沿用现有后端。图片读取复用 Host 文件系统和附件存储,要求模型支持图片输入;不加载文本读取、写入和编辑工具。 + +`--host` 与 `--port` 配置监听器;`--tls-cert` 与 `--tls-key` 让它直接提供 HTTPS;`--public-url` 指定 GUI 在剥离前缀的代理之后对外公告的公开 HTTP(S) 根,`--trusted-host` 则添加更多被接受的 authority。这些都在[监听、信任与公开部署](#public-deployments)中说明,而这些 flag 设置的 `tls` 字段记录在[载体的配置](../../../docs/subsystems/web-server.zh.md#config)中: | 字段 | 默认值 | 含义 | |---|---|---| | `openBrowser` | `true` | 启动后用默认浏览器打开;SSH 启动会抑制它 | | `printUrl` | `true` | 启动时打印 `dsh web:` URL 行 | -| `surfaceContext` | `true` | 给 agent 提供 GUI 定位上下文,并把 `DSH_WEB_URL` 暴露给其 shell 命令 | -| `publicUrl` | 未设置 | 对外公告的 HTTP(S) 应用根;否则公告监听器的 loopback URL | -| `trustedHosts` | `[]` | 允许从网络访问 GUI 的额外主机 | +| `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 的作用域不会列出它们。 ### 监听、信任与公开部署 -默认情况下 GUI 只在 loopback 上监听,只接受本机的连接;可重复的 `--trusted-host` 会添加其 Host/Origin 栅栏接受的 authority,因此远端浏览器要么经由剥离前缀的代理访问,要么通过以可信主机名呈现的端口转发客户端访问。 +默认情况下 GUI 只监听 loopback,只接受本机的连接。只有 `--host` 会改变监听器:它接受一个具体的本机 IPv4 或 IPv6 地址,不接受通配地址。未启用 TLS 的非 loopback 监听器提供明文 HTTP,并在启动时警告,即使前置 HTTPS 的 `--public-url` 也不例外。Host/Origin 栅栏接受绑定 IP 本身;其他非 loopback authority 需要 `--trusted-host`,因此远端浏览器要么经由剥离前缀的代理访问 GUI,要么通过以可信主机名呈现的端口转发客户端访问。启动 token 交换与签名会话 cookie 认证每个 API 方法与 WebSocket 流。 -`--public-url` 公告浏览器使用的 HTTP(S) 根——打印与打开的启动 URL、`DSH_WEB_URL` 与 web 表层定位。公告不授予任何信任:浏览器可见的 authority 还必须用 `--trusted-host` 点名。该 flag 不配置监听器、路由或 cookie 作用域,因为外部链路归代理所有:[在反向代理之后发布 Web UI](../../../docs/user/guide/public-deployments.zh.md)列出了这样的部署必须提供什么。 +同时传入 `--tls-cert` 与 `--tls-key`,监听器便以 HTTPS 而非明文 HTTP 提供服务。两者各指定一个相对进程工作目录解析的文件:证书文件包含完整证书链,密钥文件为不带口令的 PEM 私钥。它们属于同一个设置——只提供一个会报用法错误,两个都不提供则保持明文 HTTP 默认值。文件缺失、不可读、为空,或不是有效的证书与密钥对时启动失败;绝不回退到 HTTP。监听器运行期间不会重新读取这些材料,因此更换证书需要重新加载监听器或重启进程。DSH 不签发、不续期也不监视任何证书:没有 ACME 客户端、没有自签名兜底,也没有重定向监听器。浏览器使用自己的信任库与主机名匹配,因此浏览器不信任的证书,或其 subject alternative name 未覆盖你所访问 authority 的证书,会在页面加载前失败。默认端口仍为 3080,且 `--tls-cert`/`--tls-key` 不跟随 `--public-url`:监听器的证书覆盖浏览器实际访问的 authority。TLS 不改变授权模型:Connection 仍认证每个请求并仍校验 Host/Origin,且只要接收请求的监听器提供 HTTPS,它所签发的会话 cookie 就带 `Secure`。 -打印的 URL 包含进程凭据,只应与预期用户分享;`printUrl: false` 无论是否配置 `--public-url` 都会抑制该行。 +容器可以绑定其 Pod 地址,并公告前置的 ingress: + +```sh +dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public-url https://app.example/ --trusted-host app.example +``` + +`hostname -i` 可能列出多个地址;`--host` 只接受一个,因此命令取第一个。`fe80::1%eth0` 这样的 zone ID 不能出现在 URL 中,因此公告根会剥离多余的 loopback zone,而非 loopback zone 则要求显式提供 `--public-url`。 + +未设置 `--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`,以及 agent 运行时上下文中的 Web GUI URL。公告不授予任何信任:浏览器可见的 authority 还必须用 `--trusted-host` 点名。该 flag 不配置监听器、路由或 cookie 作用域,因为外部链路归代理所有:[在反向代理之后发布 Web UI](../../../docs/user/guide/public-deployments.zh.md)列出了这样的部署必须提供什么。 + +无论是公告 URL 还是浏览器信任栅栏都不保护端口本身,因此请把端口限制在可信代理或网络内。 + +打印的 URL 包含进程凭据,只应与预期用户分享。`printUrl: false` 无论是否配置 `--public-url` 都会抑制该行,凭据也绝不会出现在模型上下文或 `DSH_WEB_URL` 中。 ### 通过 SSH 运行 -通过 SSH 启动 `dsh --profile web` 时,URL 行仍会打印,但不会为你打开浏览器:本地转发地址由 SSH 客户端或编辑器持有。没有公告根时,打印的 URL 指向远端宿主机 loopback 端点,你通过自己的转发地址访问它。配置了 `--public-url` 时,打印的 URL 是带认证的公告根;浏览器交接仍被抑制,因为在远端宿主机上打开浏览器无法到达你的屏幕。 +通过 SSH 启动 `dsh --profile web` 时,URL 行仍会打印,但不会为你打开浏览器:本地转发地址由 SSH 客户端或编辑器持有。没有公告根时,打印的 URL 指向远端宿主机的绑定地址端点——绑定 loopback 时即 loopback——你通过自己的转发地址访问它。配置了 `--public-url` 时,打印的 URL 是带认证的公告根;浏览器交接仍被抑制,因为在远端宿主机上打开浏览器无法到达你的屏幕。 ### 按会话的 agent 设置 @@ -83,37 +98,32 @@ dsh --profile web --no-open --port 8080
实现细节——点击展开 -此 bundle 由一层五个文件的补丁和一个运行时胶水插件组成:`cordis.patch.yml` 承载宿主行和 preset 注册表,每个 `presets/.patch.yml` 插入一条随发行版交付的 preset 声明,按 `dsh.bundle.patch` 列出的顺序应用。存储栈与投影缓存来自 `dsh-base`;Web 叠加层的工作区和消息反馈条目消费共享的 `storageDomain` 服务。补丁重述 base 有意省略的界面专用值,插入 Web 专用宿主条目和浏览器插件列表,再将 Agent 层移到预设后面。胶水插件负责 dist 服务、公告应用 URL、信任采样、提示词段落、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 语义 -patch 会替换目标行的整个 `config`,因此每个 Web 行都重述自己拥有的每个键:基础行上的 persona 前缀模板、`DSH_TOOLS_MODE` PTC mode 开关与 `session-query-sqlite` 值,随后 `insert` 添加 Web 宿主行、传输层与浏览器名录。`webserver` 与 `web-runtime` 行注入 `webStartup` 提供方并直接读取本次调用的取值;`connection` 行则改为读取 web-runtime 行发布的、与绑定相关的 `webRuntime` 值,即该提供方的 authority 加上全接口绑定的 LAN 字面量。base 以进程级挂载的按 agent 工具行在这里被禁用,由 preset 名录接管;每项宿主层与 preset 层归属决策的理由以行内注释写在 patch 里。 +patch 会替换目标行的整个 `config`,因此每个 Web 行都重述自己拥有的每个键:基础行上的 persona 前缀模板、`DSH_TOOLS_MODE` PTC mode 开关与 `session-query-sqlite` 值,随后 `insert` 添加 Web 宿主行、传输层与浏览器名录。`webserver`、`web-runtime` 与 `connection` 行都注入 `webStartup` 提供方并直接读取本次调用的取值;Connection 的被接受 authority 全部来自 `ctx.webStartup.trustedHosts`,Host/Origin 栅栏则独立于该列表接受监听器的绑定 IP。base 以进程级挂载的按 agent 工具行在这里被禁用,由 preset 名录接管;每项宿主层与 preset 层归属决策的理由以行内注释写在 patch 里。 ### 公告应用 URL -启动显示与浏览器交接接收附带启动 token 的公告根;web 表层提示词与 `DSH_WEB_URL` 接收不含凭据的形式。根本身由[监听、信任与公开部署](#public-deployments)定义。 +启动显示与浏览器交接接收附带启动 token 的公告根;agent 的运行时上下文与 `DSH_WEB_URL` 接收不含凭据的形式。根本身由[监听、信任与公开部署](#public-deployments)定义。 ### 就绪宣告 URL 行与浏览器交接都是就绪信号:监督方一观察到该行就发起 RPC,浏览器一打开就请求页面,因此两者只在 Loader 配置树结算、通过 required 启动检查且 Connection 认证可用后运行——在没有 Loader 的手工构建树中则立即运行。此时 client combo JavaScript 和 source map 仍未物化。可选插件失败不会阻止就绪宣告;required 启动失败或启动中途被释放的树不会宣告任何内容。 -### LAN 信任采样 - -`resolveLanTrust` 在启动时只采样一次网络:loopback 绑定(`127.0.0.1`)不派生任何 LAN 地址,绑定所有网卡则会加入每个非 internal IPv4 字面量。派生字面量加上显式的 `--trusted-host` 权威标识组成 `/api` 浏览器信任栅栏,打印的 LAN URL 始终与该栅栏一致。 - ### 源码地图 | 文件 | 职责 | |---|---| -| [`src/index.ts`](src/index.ts) | `web-app` 粘合插件:dist 解析、公告应用 URL、LAN 信任采样、提示词段落、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`、`--public-url`、`--trusted-host`、`--no-open`、`--help` | +| [`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 解析、回退席位、提示词段落、就绪宣告、公告 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/trusted-hosts.spec.ts`](tests/trusted-hosts.spec.ts) | LAN 信任采样 | | [`tests/browser-open.spec.ts`](tests/browser-open.spec.ts) | 页面可达后的默认浏览器交接 |
@@ -136,19 +146,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 不会改变前置前缀;不保证提供方复用缓存。 +无;该插件不贡献系统提示词文本。 ## 已知限制与延期工作 @@ -158,12 +168,12 @@ URL 行与浏览器交接都是就绪信号:监督方一观察到该行就发 这些限制告诉你在不常见的环境下会遇到什么——源码 checkout、SSH 会话或严格网络。它们是当前包约束,不是通用的浏览器对比或任务积压。 - **前端必须已构建**——源码 checkout 需要先运行 `pnpm run build`;dist 缺失时启动会以构建提示停止,且没有从源码直接服务的回退路径。 -- **监听器不提供 TLS**——请用终止 TLS 的代理保护外部链路;HTTP 公告根会以明文发送凭据。 -- **LAN 地址只在启动时采样一次**——启动后的网卡变化不会重新公告;打印的 LAN URL 始终与采样结果一致。 +- **TLS 需自行启用且不代管**——只有传入 `--tls-cert` 与 `--tls-key`(完整证书链与不带口令的密钥)时监听器才提供 HTTPS;DSH 从不获取、续期或监视证书,更换文件需要重新加载监听器或重启进程。浏览器必须信任该证书,其名称必须覆盖你所访问的 authority,且证书与 `--public-url` 相互独立。 +- **未启用 TLS 时外部链路是明文 HTTP**——请用终止 TLS 的代理保护它,不要在不受信任的网络上发送启动 URL。 - **只能观察到交接的启动**——GUI 只报告浏览器被请求打开,而不是它确实打开了;之后的浏览器退出永远不会上报,打印的 URL 是你的手动回退路径。 -- **SSH 会话保留 URL 但跳过浏览器交接**——没有公告根时,打印的 URL 指向远端宿主机 loopback 端点;SSH 客户端或编辑器必须暴露并打开本地转发地址。 +- **SSH 会话保留 URL 但跳过浏览器交接**——没有公告根时,打印的 URL 指向远端宿主机的绑定地址;SSH 客户端或编辑器必须暴露并打开本地转发地址。 - **`BROWSER` 覆盖只能来自环境**——被发现的 `.env` 不能设置 `BROWSER`;只有继承值能为自动交接选择可执行文件。 -- **不支持绑定所有网络接口**——出于安全考虑,`--host 0.0.0.0` 会在启动时被拒绝;请使用默认 loopback 主机。 +- **不支持绑定所有网络接口**——出于安全考虑,通配 `--host`(含 Linux 视为 IPv4 any 的 IPv4-mapped 形式)会在启动时被拒绝;请改为绑定本机某个接口的一个具体 IPv4 或 IPv6 地址。 ### 开发备注 diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index ee5201b9c7..a1ca0b5483 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -7,8 +7,9 @@ # # The web-startup plugin injects `cmdlineArgs` and provides `webStartup` as an # ordinary Cordis service. Rows configured from flags inject that service, so -# Loader resolves their expressions only after it exists. The web runtime then -# provides bind-dependent `webRuntime` values to the trust fence. +# Loader resolves their expressions only after it exists. The web-runtime row +# validates the advertised public URL; Connection reads invocation authorities +# directly from `webStartup`. # `dsh --profile web --help` provides no `webStartup`, so no server binds. # ── surface-specific values the base deliberately omits ───────────────────── @@ -173,28 +174,26 @@ # webStartup provider, with these deployment fallbacks. The dist is served # by the web-runtime row below through the fallback seat. Routing and # browser-facing asset paths do not depend on the advertised URL, which the - # web-runtime row owns. + # web-runtime row owns; Connection reads trust authorities from webStartup. + # This row rejects wildcard binds. - id: webserver name: '@deepseek-ai/dsh-host-webserver' inject: [webStartup] config: host: !!js ctx.webStartup.host ?? '127.0.0.1' port: !!js ctx.webStartup.port ?? 3080 + tls: !!js ctx.webStartup.tls compression: gzip compressionLevel: 1 compressionThresholdBytes: 1024 # 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` (the - # loopback URL when unset). After the server binds, this row samples LAN - # trust once and provides `webRuntime`. 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] @@ -203,7 +202,14 @@ printUrl: true publicUrl: !!js ctx.webStartup.publicUrl surfaceContext: true - trustedHosts: !!js ctx.webStartup.trustedHosts + + # 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 @@ -223,16 +229,16 @@ # Owns both ends of the web transport: node half binds the gateway to the # webserver under /api; browser half is the fetch/SSE client. Every API - # request and upgrade passes the loopback plus trustedHosts policy; an - # advertised public URL contributes nothing to it. + # request and upgrade passes the loopback, listener-bind, or trustedHosts + # policy; an advertised public URL contributes nothing to it. - id: connection name: '@deepseek-ai/dsh-client-connection' - inject: [webRuntime] + inject: [webStartup] config: - # LAN literals derived from the active bind plus --trusted-host extras. - # A deployment adding authorities keeps this expression and concatenates - # its literals, for example: ['app.internal', ...ctx.webRuntime.trustedHosts]. - trustedHosts: !!js ctx.webRuntime.trustedHosts + # Keep invocation authorities (each --trusted-host value) when adding + # deployment values, for example: ['app.internal', ...ctx.webStartup.trustedHosts]. + # The listener's bind IP is accepted separately from this list. + trustedHosts: !!js ctx.webStartup.trustedHosts # Raw Blob and ReadableStream uploads run independently of Connection's # RPC and generation service. @@ -377,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 1333adb356..e99dac38e0 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -1,7 +1,7 @@ { "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)", - "version": "0.2.1-alpha.1", + "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", @@ -95,6 +99,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:*", @@ -183,13 +188,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:~", @@ -201,7 +206,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/presets/cordis.patch.yml b/packages/bundle/web-app/presets/cordis.patch.yml index 277176f1a0..75b94016d2 100644 --- a/packages/bundle/web-app/presets/cordis.patch.yml +++ b/packages/bundle/web-app/presets/cordis.patch.yml @@ -51,7 +51,7 @@ name: '@deepseek-ai/dsh-plan-mode' config: section: | - You are in plan mode. Stay in plan mode until exit_plan_mode succeeds or the user switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode. + You are in plan mode. Stay in plan mode until the user approves your plan through exit_plan_mode or switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode. Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery. @@ -95,23 +95,11 @@ provider: spawn toolName: subagent modelSelectionSettings: true - toolFilter: - deny: - - schedule_create - - schedule_delete - - schedule_list - - schedule_update - id: tool-subagent-fork name: '@deepseek-ai/dsh-tool-subagent' config: provider: fork toolName: subagent_fork - toolFilter: - deny: - - schedule_create - - schedule_delete - - schedule_list - - schedule_update - id: workflow-ptc name: '@deepseek-ai/dsh-workflow-ptc' config: diff --git a/packages/bundle/web-app/presets/minimal.patch.yml b/packages/bundle/web-app/presets/minimal.patch.yml index ee36823e27..043e34cb01 100644 --- a/packages/bundle/web-app/presets/minimal.patch.yml +++ b/packages/bundle/web-app/presets/minimal.patch.yml @@ -14,6 +14,23 @@ prefix: You are a helpful software engineer assistant. complete: true includeRuntimeContext: false + - id: tool-fs + name: '@deepseek-ai/dsh-tool-fs' + config: + read: false + readImage: true + write: false + edit: false + - id: compaction + name: cordis:group + group: true + isolate: + compaction: true + config: + - id: compaction-basic + name: '@deepseek-ai/dsh-compaction-basic' + - id: command-compact + name: '@deepseek-ai/dsh-command-compact' - id: persistent-shell name: cordis:group group: true diff --git a/packages/bundle/web-app/presets/ptc.patch.yml b/packages/bundle/web-app/presets/ptc.patch.yml index 1aed4cb9e9..19771435ba 100644 --- a/packages/bundle/web-app/presets/ptc.patch.yml +++ b/packages/bundle/web-app/presets/ptc.patch.yml @@ -52,7 +52,7 @@ name: '@deepseek-ai/dsh-plan-mode' config: section: | - You are in plan mode. Stay in plan mode until exit_plan_mode succeeds or the user switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode. + You are in plan mode. Stay in plan mode until the user approves your plan through exit_plan_mode or switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode. Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery. @@ -96,23 +96,11 @@ provider: spawn toolName: subagent modelSelectionSettings: true - toolFilter: - deny: - - schedule_create - - schedule_delete - - schedule_list - - schedule_update - id: tool-subagent-fork name: '@deepseek-ai/dsh-tool-subagent' config: provider: fork toolName: subagent_fork - toolFilter: - deny: - - schedule_create - - schedule_delete - - schedule_list - - schedule_update - id: workflow-ptc name: '@deepseek-ai/dsh-workflow-ptc' disabled: true diff --git a/packages/bundle/web-app/presets/standard.patch.yml b/packages/bundle/web-app/presets/standard.patch.yml index f2a9e080fe..77c048feb8 100644 --- a/packages/bundle/web-app/presets/standard.patch.yml +++ b/packages/bundle/web-app/presets/standard.patch.yml @@ -52,7 +52,7 @@ name: '@deepseek-ai/dsh-plan-mode' config: section: | - You are in plan mode. Stay in plan mode until exit_plan_mode succeeds or the user switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode. + You are in plan mode. Stay in plan mode until the user approves your plan through exit_plan_mode or switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode. Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery. @@ -96,23 +96,11 @@ provider: spawn toolName: subagent modelSelectionSettings: true - toolFilter: - deny: - - schedule_create - - schedule_delete - - schedule_list - - schedule_update - id: tool-subagent-fork name: '@deepseek-ai/dsh-tool-subagent' config: provider: fork toolName: subagent_fork - toolFilter: - deny: - - schedule_create - - schedule_delete - - schedule_list - - schedule_update - id: workflow-ptc name: '@deepseek-ai/dsh-workflow-ptc' config: diff --git a/packages/bundle/web-app/src/index.ts b/packages/bundle/web-app/src/index.ts index bf1aec78c1..b93b559620 100644 --- a/packages/bundle/web-app/src/index.ts +++ b/packages/bundle/web-app/src/index.ts @@ -4,41 +4,50 @@ * 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 root — the loopback URL - * otherwise. App command-line values arrive through the `webStartup` service - * expressions in the bundle patch. + * 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 */ import { spawn, type ChildProcess } from 'node:child_process' import { createRequire } from 'node:module' import { dirname, join } from 'node:path' -import { networkInterfaces } from 'node:os' -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 { 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-host-webserver' 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() -/** Runtime service that releases Web rows after bind-dependent values resolve. */ -const WEB_RUNTIME_SERVICE = 'webRuntime' - /** Services required before the web runtime can mount. */ export const inject = ['webServer'] @@ -49,22 +58,18 @@ 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 `/`. Advertisement only; - * see [public deployments](../README.md#public-deployments). Absent or YAML - * `null` advertises the loopback URL. + * `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. */ publicUrl?: string - /** Explicit `--trusted-host` authorities from this invocation. */ - trustedHosts: string[] } export const Config: z = z.object({ @@ -72,26 +77,11 @@ export const Config: z = z.object({ printUrl: z.boolean().default(true), surfaceContext: z.boolean().default(true), publicUrl: z.transform(z.string(), value => parsePublicUrl(value).href), - trustedHosts: z.array(String).default([]), }) -/** Bind-dependent Web values shared by the trust fence and URL display. */ -export interface WebRuntimeValues { - /** LAN IPv4 literals sampled once when the server binds all interfaces. */ - lanAddresses: string[] - /** LAN literals followed by explicit invocation authorities. */ - trustedHosts: string[] -} - /** Environment variable naming the advertised URL of this Web GUI. */ const DSH_WEB_URL = 'DSH_WEB_URL' as const -// Display-only mirror of the webserver schema's loopback host: the address the -// local URL always prints. Not a source of truth — the schema is. -const LOOPBACK_HOST = '127.0.0.1' -/** The webserver schema's all-interfaces bind literal. */ -const ALL_INTERFACES_HOST = '0.0.0.0' - const BROWSER_OPENER_MODULE = import.meta.resolve('open') const BROWSER_OPENER_PROGRAM = ` @@ -123,51 +113,6 @@ try { } ` -/** - * Resolve one LAN-trust snapshot from the active server bind. - * - * Derived entries are port-less IP literals: DNS rebinding needs an - * attacker-controlled name, while an IP-literal Host is safe on any port and - * an OS-assigned port is unknowable before bind. - * @param bindHost - the active webserver bind host. - * @param extra - explicit `--trusted-host` values, in argument order. - * @returns the LAN display addresses and invocation-derived fence authorities. - */ -export function resolveLanTrust(bindHost: string, extra: readonly string[]): WebRuntimeValues { - const lanAddresses = bindHost === ALL_INTERFACES_HOST - ? Object.values(networkInterfaces()).flat() - .filter((iface): iface is NonNullable => iface !== undefined && iface.family === 'IPv4' && !iface.internal) - .map(iface => iface.address) - : [] - return { lanAddresses, trustedHosts: [...lanAddresses, ...extra] } -} - -/** 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.' -} - -/** Resolve the canonical loopback URL from the active Web server. */ -function localWebUrl(ctx: Context): string { - const port = ctx.get('webServer')?.port - if (port === undefined) throw new Error('web-app: webServer service missing while resolving Web runtime') - return `http://${LOOPBACK_HOST}:${String(port)}` -} - -function appRootUrl(ctx: Context, publicUrl: string | undefined): string { - if (publicUrl !== undefined) return publicUrl - return localWebUrl(ctx) -} - /** * Dist location is workspace knowledge of this bundle: anchored on the * frontend package manifest, not configured. Existence is a request-time @@ -233,38 +178,40 @@ 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}. */ export function apply(ctx: Context, config: Config): void { - const runtime = resolveLanTrust(ctx.webServer.host, config.trustedHosts) // The schema validates a present string; an explicit YAML `null` bypasses // the string transform and reaches here, meaning unset. const publicUrl = config.publicUrl ?? undefined - // The loopback URL belongs to this host. Under SSH, the operator reaches it + const boundHost = ctx.webServer.host + 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)) - // Release dependent rows only after bind-dependent trust has been sampled once. - ctx.provide(WEB_RUNTIME_SERVICE, runtime) + /** 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() }), }) }) } @@ -277,17 +224,11 @@ 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) - // Reuse the exact LAN snapshot provided to the /api trust fence. - const lanCandidate = runtime.lanAddresses[0] - const port = connectionCtx.webServer.port - const lanUrl = lanCandidate === undefined - ? undefined - : connectionCtx.connection.authenticatedUrl(`http://${lanCandidate}:${String(port)}`) ANNOUNCED_ROOTS.add(connectionCtx.root) if (config.printUrl) { - console.log(`dsh web: ${authenticatedUrl}${lanUrl === undefined ? '' : ` (LAN: ${lanUrl})`}`) + console.log(`dsh web: ${authenticatedUrl}`) } if (handoffBrowser) { console.log('dsh web: opening the default browser; pass --no-open to disable') diff --git a/packages/bundle/web-app/src/startup.ts b/packages/bundle/web-app/src/startup.ts index 749dd8ea5d..3152e085fb 100644 --- a/packages/bundle/web-app/src/startup.ts +++ b/packages/bundle/web-app/src/startup.ts @@ -1,6 +1,6 @@ /** * The web app's command-line provider: it parses the `dsh --profile web` flag - * family (`--host`, `--port`, `--public-url`, `--trusted-host`, `--no-open`) + * family (`--host`, `--port`, `--public-url`, `--trusted-host`, `--no-open`, TLS) * and its `--help` text, then provides the immutable values as * {@link WEB_STARTUP_SERVICE}. Ordinary rows inject that service before * reading it from lazy config. @@ -10,6 +10,7 @@ import { Command } from 'commander' import type { Context } from '@deepseek-ai/cordis' import { parseCmdline } from '@deepseek-ai/dsh-cmdline' +import { isWildcardHost, type TlsConfig } from '@deepseek-ai/dsh-host-webserver' import { parsePublicUrl } from './public-url.ts' /** Stable Cordis plugin name. */ @@ -36,6 +37,8 @@ export interface WebStartupValues { publicUrl?: string /** Explicit `--trusted-host` authorities, in argument order. */ trustedHosts: string[] + /** Server certificate chain and unencrypted private key supplied together. */ + tls?: TlsConfig } /** The web flag family, as commander parsed it. */ @@ -45,6 +48,8 @@ interface WebOptions { port?: string publicUrl?: string trustedHost?: string[] + tlsCert?: string + tlsKey?: string } /** @@ -56,38 +61,49 @@ function webCommand(): Command { .name('dsh --profile web') .description('Serve the DeepSeek Harness browser UI.') .helpOption('-h, --help', 'show this help') - .option('--host ', 'bind host') + .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') .addHelpText('after', ` Examples: dsh --profile web serve on the composed host and port dsh --profile web --no-open serve without opening a browser dsh --profile web --port 8080 serve on another port + dsh --profile web --host 10.0.0.7 bind one local interface address dsh --profile web --public-url https://app.example/ui/ --trusted-host app.example advertise a prefix-stripping HTTPS proxy entry and admit its authority + dsh --profile web --tls-cert ./server-chain.pem --tls-key ./server-key.pem + serve HTTPS with an existing certificate and key `) } /** * Parse and provide the Web invocation as an ordinary Cordis service. The - * command's action publishes the flags this invocation named; `--host 0.0.0.0`, - * a non-numeric `--port`, or a malformed `--public-url` is a usage error, so on - * rejection (and on `--help`) nothing is provided. + * command's action publishes the flags this invocation named. Invalid flags, + * including an unpaired TLS certificate or key, are usage errors; rejection + * and `--help` provide no service. * @param ctx - plugin context carrying the command line. */ export function apply(ctx: Context): void { const program = webCommand() program.action(() => { const options = program.opts() - if (options.host === '0.0.0.0') { - program.error('error: --host 0.0.0.0 is intentionally not supported yet for safety: it would expose remote code execution to the network; use 127.0.0.1 instead') + if (options.host !== undefined && isWildcardHost(options.host)) { + program.error(`error: --host ${options.host} is an unspecified (wildcard) address, which is not supported: binding every interface would expose remote code execution to the network; bind one concrete IPv4 or IPv6 address instead`) } if (options.port !== undefined && !/^\d+$/.test(options.port)) { program.error(`error: --port must be a number, got ${JSON.stringify(options.port)}`) } + let tls: TlsConfig | undefined + if (options.tlsCert !== undefined && options.tlsKey !== undefined) { + tls = { certFile: options.tlsCert, keyFile: options.tlsKey } + } else if (options.tlsCert !== undefined || options.tlsKey !== undefined) { + program.error('error: --tls-cert and --tls-key must be supplied together') + } if (options.publicUrl !== undefined) { try { parsePublicUrl(options.publicUrl, '--public-url') @@ -100,6 +116,7 @@ export function apply(ctx: Context): void { ...options.host !== undefined && { host: options.host }, ...options.port !== undefined && { port: Number(options.port) }, ...options.publicUrl !== undefined && { publicUrl: options.publicUrl }, + ...tls !== undefined && { tls }, trustedHosts: options.trustedHost ?? [], } satisfies WebStartupValues) }) diff --git a/packages/bundle/web-app/tests/browser-open.spec.ts b/packages/bundle/web-app/tests/browser-open.spec.ts index c9bc0c31cf..bc303e4d21 100644 --- a/packages/bundle/web-app/tests/browser-open.spec.ts +++ b/packages/bundle/web-app/tests/browser-open.spec.ts @@ -72,7 +72,6 @@ describe('web app browser startup', () => { ' openBrowser: true', ' printUrl: false', ' surfaceContext: false', - ' trustedHosts: []', '', ].join('\n')) diff --git a/packages/bundle/web-app/tests/startup.spec.ts b/packages/bundle/web-app/tests/startup.spec.ts index 322e98a818..9a7a01a5cb 100644 --- a/packages/bundle/web-app/tests/startup.spec.ts +++ b/packages/bundle/web-app/tests/startup.spec.ts @@ -65,6 +65,7 @@ export const apply = ctx => globalThis.__webStartupApply(ctx) ' port: !!js ctx.webStartup.port ?? 3080', ' publicUrl: !!js ctx.webStartup.publicUrl', ' trustedHosts: !!js ctx.webStartup.trustedHosts', + ' tls: !!js ctx.webStartup.tls', '- id: provider', ` name: ${pathToFileURL(join(dir, 'provider.mjs')).href}`, '', @@ -100,17 +101,30 @@ describe('web command-line provider', () => { '--port', '8080', '--trusted-host', 'lab.internal', 'lab-2.internal', '--trusted-host', '10.0.0.9', + '--tls-cert', 'fullchain.pem', + '--tls-key', 'private-key.pem', ]) expect(values).toEqual({ host: '127.0.0.1', openBrowser: false, port: 8080, trustedHosts: ['lab.internal', 'lab-2.internal', '10.0.0.9'], + tls: { certFile: 'fullchain.pem', keyFile: 'private-key.pem' }, }) expect(observed.readerConfig).toEqual(values) expect(observed.exits).toEqual([]) }) + // The webserver suite owns the wildcard spellings; the CLI only has to + // refuse them by address value before any consumer activates. + it.each(['0.0.0.0', '::ffff:0.0.0.0'])('rejects wildcard --host %s before activating consumers', async (host) => { + const { values, observed } = await bootProvider(['--host', host]) + expect(observed.out).toContain(`error: --host ${host} is an unspecified (wildcard) address`) + expect(values).toBeUndefined() + expect(observed.readerConfig).toBeUndefined() + expect(observed.exits).toEqual([1]) + }) + it('leaves deployment values to each consumer when flags omit them', async () => { const { values, observed } = await bootProvider([]) expect(values).toEqual({ openBrowser: true, trustedHosts: [] }) @@ -141,14 +155,6 @@ describe('web command-line provider', () => { expect(observed.exits).toEqual([1]) }) - it('rejects the intentionally unsupported all-interfaces host before the consumer activates', async () => { - const { values, observed } = await bootProvider(['--host', '0.0.0.0']) - expect(observed.out).toContain('--host 0.0.0.0 is intentionally not supported yet for safety: it would expose remote code execution to the network; use 127.0.0.1 instead') - expect(values).toBeUndefined() - expect(observed.readerConfig).toBeUndefined() - expect(observed.exits).toEqual([1]) - }) - it('publishes --public-url as advertisement only, leaving the fence to --trusted-host', async () => { const { values, observed } = await bootProvider([ '--public-url', 'https://web.example/ui', @@ -169,6 +175,14 @@ describe('web command-line provider', () => { expect(observed.exits).toEqual([]) }) + it.each(['--tls-cert', '--tls-key'])('rejects an unpaired %s before activating consumers', async (flag) => { + const { values, observed } = await bootProvider([flag, 'server.pem']) + expect(observed.out).toContain('--tls-cert and --tls-key must be supplied together') + expect(values).toBeUndefined() + expect(observed.readerConfig).toBeUndefined() + expect(observed.exits).toEqual([1]) + }) + it('rejects a malformed --public-url before the consumer activates', async () => { // The parser's own suite owns the exhaustive spellings; the provider only // has to fail the invocation before any consumer activates. diff --git a/packages/bundle/web-app/tests/trusted-hosts.spec.ts b/packages/bundle/web-app/tests/trusted-hosts.spec.ts deleted file mode 100644 index 5972569b0d..0000000000 --- a/packages/bundle/web-app/tests/trusted-hosts.spec.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** Single-sample LAN-trust resolution for the /api browser-trust fence (`resolveLanTrust`). */ - -import { describe, expect, it, vi } from 'vitest' -import { resolveLanTrust } from '../src/index.ts' - -vi.mock('node:os', () => ({ - networkInterfaces: () => ({ - lo0: [ - { family: 'IPv4', internal: true, address: '127.0.0.1' }, - ], - en0: [ - { family: 'IPv6', internal: false, address: 'fe80::1' }, - { family: 'IPv4', internal: false, address: '192.168.1.5' }, - ], - en1: [ - { family: 'IPv4', internal: false, address: '10.0.0.7' }, - ], - utun0: undefined, - }), -})) - -describe('resolveLanTrust', () => { - it('samples non-internal IPv4 addresses once for an all-interfaces bind: trust and display share them', () => { - const { lanAddresses, trustedHosts } = resolveLanTrust('0.0.0.0', ['harness.internal:3080']) - expect(lanAddresses).toEqual(['192.168.1.5', '10.0.0.7']) - expect(trustedHosts).toEqual(['192.168.1.5', '10.0.0.7', 'harness.internal:3080']) - }) - - it('derives nothing for a loopback bind — extras alone stand, no LAN URL to print', () => { - expect(resolveLanTrust('127.0.0.1', [])).toEqual({ lanAddresses: [], trustedHosts: [] }) - expect(resolveLanTrust('127.0.0.1', ['lab.internal'])) - .toEqual({ lanAddresses: [], trustedHosts: ['lab.internal'] }) - }) -}) diff --git a/packages/bundle/web-app/tests/web-app.spec.ts b/packages/bundle/web-app/tests/web-app.spec.ts index 6d2b4be201..67a350355d 100644 --- a/packages/bundle/web-app/tests/web-app.spec.ts +++ b/packages/bundle/web-app/tests/web-app.spec.ts @@ -1,11 +1,4 @@ -/** - * Web runtime glue behavior: dist resolution through the bundle's own hook, - * the frontend-static child claiming the fallback seat, the web-surface - * prompt section and bash runtime variables, and readiness publication through - * the URL line and default-browser handoff. The advertised URL comes from this - * plugin's `publicUrl` config (loopback when unset), never from the bound - * webserver. - */ +/** Web runtime URL publication, exposure warnings, and Loader/browser handoff readiness. */ import { EventEmitter } from 'node:events' import { spawn, type ChildProcess } from 'node:child_process' @@ -18,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 => ({ @@ -27,14 +19,6 @@ vi.mock('node:child_process', async importOriginal => ({ spawn: vi.fn(), })) -vi.mock('node:os', async importOriginal => ({ - ...await importOriginal(), - networkInterfaces: () => ({ - lo0: [{ family: 'IPv4', internal: true, address: '127.0.0.1' }], - en0: [{ family: 'IPv4', internal: false, address: '192.168.1.5' }], - }), -})) - let dist: string | undefined beforeEach(() => { @@ -72,19 +56,17 @@ function stageDist(): string { return index } -/** A fake webServer capturing the fallback seat and index taps. */ -function fakeHttpServer(host: '127.0.0.1' | '0.0.0.0' = '127.0.0.1'): { server: WebServer; seat: () => unknown } { - let fallback: unknown - const server = { +/** Web carrier without a network listener. */ +function fakeHttpServer(host = '127.0.0.1'): { server: WebServer } { + const server: Pick = { host, port: 4567, - registerFallback: (handler: unknown) => { - fallback = handler - return () => { fallback = undefined } - }, + protocol: 'http:', + getOrigin() { return `http://${bindUrlHost(host) ?? ''}:${String(this.port)}` }, + registerFallback: () => () => {}, renderIndex: (html: string) => html, - } as unknown as WebServer - return { server, seat: () => fallback } + } + return { server: server as WebServer } } /** Deterministic Host Connection face for URL publication and frontend injection. */ @@ -115,15 +97,20 @@ interface BashContribution { } describe('web-app runtime glue', () => { - it('mounts dist serving, prompt section, bash variables, and publishes the URL with the LAN snapshot', async () => { + it.each([ + '127.0.0.1', + '::ffff:127.0.0.1', + '::ffff:7f00:1', + ])('publishes the URL and surface context for %s before handing it to the browser', async (bind) => { stageDist() const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) // Editor markers and a project .env SSH value do not establish a remote launch. ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([ { source: 'process', values: { VSCODE_IPC_HOOK_CLI: '/tmp/local-vscode-ipc' } }, { source: 'project-env', path: '/work/.env', values: { SSH_CONNECTION: 'stale-project-value' } }, ])) - const { server, seat } = fakeHttpServer('0.0.0.0') + const { server } = fakeHttpServer(bind) ctx.provide('webServer', server) provideConnection(ctx) const contributions: BashContribution[] = [] @@ -138,34 +125,20 @@ describe('web-app runtime glue', () => { const log = vi.spyOn(console, 'log').mockImplementation((message) => { lifecycle.push(String(message)) }) const openBrowser = vi.fn(async (url: string) => { lifecycle.push(`open:${url}`) }) internals.openBrowser = openBrowser - apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: true, trustedHosts: ['lab.internal'] })) - await ctx.plugin(SystemPrompt, { personaPrefix: '' }) - // Settle the injected registrations. - await new Promise(resolve => setTimeout(resolve, 0)) + apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: true })) + await vi.waitFor(() => { expect(openBrowser).toHaveBeenCalled() }) - expect(seat()).toBeDefined() // frontend-static claimed the fallback - expect(ctx.get('webRuntime')).toEqual({ - lanAddresses: ['192.168.1.5'], - trustedHosts: ['192.168.1.5', 'lab.internal'], - }) - expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token (LAN: http://192.168.1.5:4567/?token=test-token)') + expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') expect(log).toHaveBeenCalledWith('dsh web: opening the default browser; pass --no-open to disable') expect(openBrowser).toHaveBeenCalledWith('http://127.0.0.1:4567/?token=test-token') expect(lifecycle).toEqual([ - 'dsh web: http://127.0.0.1:4567/?token=test-token (LAN: http://192.168.1.5:4567/?token=test-token)', + 'dsh web: http://127.0.0.1:4567/?token=test-token', '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' }) - await ctx.fiber.dispose() + 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 () => { @@ -192,9 +165,7 @@ describe('web-app runtime glue', () => { printUrl: true, surfaceContext: true, publicUrl: 'https://proxy.example:8443/web', - trustedHosts: ['proxy.example:8443'], })) - await ctx.plugin(SystemPrompt, { personaPrefix: '' }) await vi.waitFor(() => { expect(openBrowser).toHaveBeenCalled() }) expect(lifecycle).toEqual([ @@ -202,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 () => { @@ -218,18 +187,14 @@ describe('web-app runtime glue', () => { const log = vi.spyOn(console, 'log').mockImplementation(() => {}) const openBrowser = vi.fn(async () => {}) internals.openBrowser = openBrowser - apply(ctx, new Config({ openBrowser: false, printUrl: false, surfaceContext: true, trustedHosts: [] })) - await ctx.plugin(SystemPrompt, { personaPrefix: '' }) + apply(ctx, new Config({ openBrowser: false, printUrl: false, surfaceContext: true })) 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) @@ -241,28 +206,106 @@ describe('web-app runtime glue', () => { return () => {} }, } as never) - apply(ctx, new Config({ openBrowser: false, printUrl: false, surfaceContext: false, trustedHosts: [] })) - await ctx.plugin(SystemPrompt, { personaPrefix: '' }) + apply(ctx, new Config({ openBrowser: false, printUrl: false, surfaceContext: false })) 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() }) - it('prints the loopback-only URL line when no LAN snapshot exists', async () => { + it.each([ + { bind: '127.0.0.1', printed: '127.0.0.1' }, + { bind: '::1', printed: '[::1]' }, + { bind: '0:0:0:0:0:ffff:7f08:a', printed: '127.8.0.10' }, + { bind: '::ffff:127.0.0.1%lo', printed: '127.0.0.1' }, + { bind: '::0.0.0.1', printed: '[::1]' }, + { bind: '::0.0.0.1%lo', printed: '[::1]' }, + ])('prints the $bind loopback address without warning or opening a browser', async ({ bind, printed }) => { stageDist() const ctx = new Context() - ctx.provide('webServer', fakeHttpServer().server) + onTestFinished(() => ctx.fiber.dispose()) + ctx.provide('webServer', fakeHttpServer(bind).server) provideConnection(ctx) const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: true, trustedHosts: [] })) - await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') - await ctx.fiber.dispose() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const openBrowser = vi.fn(async () => {}) + internals.openBrowser = openBrowser + apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: true })) + await vi.waitFor(() => { expect(log).toHaveBeenCalledWith(`dsh web: http://${printed}:4567/?token=test-token`) }) + expect(warn).not.toHaveBeenCalled() + expect(openBrowser).not.toHaveBeenCalled() }) + it.each([ + { bind: '10.1.2.3', printed: '10.1.2.3' }, + // `::127.0.0.1` names the IPv6 address `::7f00:1`, so the tail spelling an + // IPv4 loopback address makes it no loopback bind. + { bind: '::127.0.0.1', printed: '[::7f00:1]' }, + ])('warns and advertises the $bind bind address when the listener is not loopback', async ({ bind, printed }) => { + stageDist() + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + ctx.provide('webServer', fakeHttpServer(bind).server) + provideConnection(ctx) + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const openBrowser = vi.fn(async () => {}) + internals.openBrowser = openBrowser + apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: false })) + await vi.waitFor(() => { expect(openBrowser).toHaveBeenCalled() }) + + // A non-loopback bind has no loopback listener, so the printed and opened + // root names the bind address; startup warns that the port is plain HTTP. + expect(warn).toHaveBeenCalledTimes(1) + expect(warn).toHaveBeenCalledWith( + `dsh web: listening on ${bind} over plain HTTP; restrict this port to a trusted proxy or network`, + ) + expect(log).toHaveBeenCalledWith(`dsh web: http://${printed}:4567/?token=test-token`) + expect(openBrowser).toHaveBeenCalledWith(`http://${printed}:4567/?token=test-token`) + }) + + + it('drops an IPv6 zone id from the advertised URL', async () => { + stageDist() + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + // `::1%lo` listens on IPv6 loopback, but a zone id cannot appear in a URL; + // the advertised form must stay a parseable address. + ctx.provide('webServer', fakeHttpServer('::1%lo').server) + provideConnection(ctx) + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: false })) + await vi.waitFor(() => { expect(log).toHaveBeenCalled() }) + + expect(log).toHaveBeenCalledWith('dsh web: http://[::1]:4567/?token=test-token') + }) + + it.each(['fe80::1%lo', '::127.0.0.1%lo'])('refuses its own activation when %s carries an interface zone id', async (bind) => { + stageDist() + // A zone id cannot appear in a URL, and a non-loopback bind that names one + // has no root this runtime can prove reachable: this row must fail rather + // than let a boot continue without an advertised entry point. + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + ctx.provide('webServer', fakeHttpServer(bind).server) + expect(() => { apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: false })) }) + .toThrow(/carries an interface zone id, which no URL can express; pass --public-url/u) + + // A declared root makes the same bind usable. + const declared = new Context() + onTestFinished(() => declared.fiber.dispose()) + declared.provide('webServer', fakeHttpServer(bind).server) + provideConnection(declared) + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + apply(declared, new Config({ + openBrowser: false, printUrl: true, surfaceContext: false, publicUrl: 'https://app.example/ui/', + })) + await vi.waitFor(() => { expect(log).toHaveBeenCalled() }) + expect(log).toHaveBeenCalledWith('dsh web: https://app.example/ui/?token=test-token') + }) + + it('does not publish readiness again when Connection reloads', async () => { stageDist() const ctx = new Context() @@ -270,7 +313,7 @@ describe('web-app runtime glue', () => { const first = ctx.plugin((connectionCtx: Context) => { provideConnection(connectionCtx) }) await first const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: true, trustedHosts: [] })) + apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: true })) await new Promise(resolve => setTimeout(resolve, 0)) expect(log).toHaveBeenCalledTimes(1) @@ -288,7 +331,7 @@ describe('web-app runtime glue', () => { ctx.provide('webServer', fakeHttpServer().server) provideConnection(ctx) const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: false, publicUrl: null as never, trustedHosts: [] })) + apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: false, publicUrl: null as never })) await vi.waitFor(() => { expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') }) }) @@ -304,7 +347,7 @@ describe('web-app runtime glue', () => { const log = vi.spyOn(console, 'log').mockImplementation(() => {}) const openBrowser = vi.fn(async () => {}) internals.openBrowser = openBrowser - apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: false, trustedHosts: [] })) + apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: false })) await new Promise(resolve => setTimeout(resolve, 0)) expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') expect(openBrowser).not.toHaveBeenCalled() @@ -324,7 +367,7 @@ describe('web-app runtime glue', () => { const settlement = new Promise((resolve) => { release = resolve }) provideLoader(settled, () => settlement) const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - apply(settled, new Config({ openBrowser: true, printUrl: true, surfaceContext: true, trustedHosts: [] })) + apply(settled, new Config({ openBrowser: true, printUrl: true, surfaceContext: true })) await new Promise(resolve => setTimeout(resolve, 0)) expect(log).not.toHaveBeenCalled() expect(openBrowser).not.toHaveBeenCalled() @@ -342,7 +385,7 @@ describe('web-app runtime glue', () => { failed.provide('webServer', fakeHttpServer().server) provideConnection(failed) provideLoader(failed, async () => { throw new Error('boot failed') }) - apply(failed, new Config({ openBrowser: true, printUrl: true, surfaceContext: true, trustedHosts: [] })) + apply(failed, new Config({ openBrowser: true, printUrl: true, surfaceContext: true })) await new Promise(resolve => setTimeout(resolve, 0)) expect(log).not.toHaveBeenCalled() expect(openBrowser).not.toHaveBeenCalled() @@ -361,7 +404,7 @@ describe('web-app runtime glue', () => { let releaseTorn: () => void const tornSettlement = new Promise((resolve) => { releaseTorn = resolve }) provideLoader(torn, () => tornSettlement) - apply(torn, new Config({ openBrowser: true, printUrl: true, surfaceContext: true, trustedHosts: [] })) + apply(torn, new Config({ openBrowser: true, printUrl: true, surfaceContext: true })) await new Promise(resolve => setTimeout(resolve, 0)) await child.dispose() // the webServer service goes away releaseTorn!() @@ -392,7 +435,7 @@ describe('web-app runtime glue', () => { const openBrowser = vi.fn(async () => {}) internals.openBrowser = openBrowser const audit = vi.spyOn(AppBoot, 'auditStartupEntries') - apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: false, trustedHosts: [] })) + apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: false })) await vi.waitFor(() => { expect(audit).toHaveBeenCalledOnce() }) await Promise.allSettled(audit.mock.results.map(result => result.value as Promise)) if (announces) { @@ -404,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, trustedHosts: [] })) - 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 @@ -439,7 +466,7 @@ describe('web-app runtime glue', () => { internals.openBrowser = vi.fn(async () => { throw failure }) const log = vi.spyOn(console, 'log').mockImplementation(() => {}) const diagnostic = vi.spyOn(console, 'error').mockImplementation(() => {}) - apply(ctx, new Config({ openBrowser: true, printUrl: false, surfaceContext: false, trustedHosts: [] })) + apply(ctx, new Config({ openBrowser: true, printUrl: false, surfaceContext: false })) await new Promise(resolve => setTimeout(resolve, 0)) expect(log).toHaveBeenCalledWith('dsh web: opening the default browser; pass --no-open to disable') expect(diagnostic).toHaveBeenCalledWith( 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 2d39d6b3ca..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.) @@ -16,6 +16,7 @@ The [Slots reference](../../docs/subsystems/slots.md) owns the current design; t 6. **Stores: read `props.useStore`, write `props.actions.*`** — the declared actions are the complete mutation API. Write the store as an exported `createXXXStore()` factory (module-level handles are forbidden — de-facto singletons); share by passing one handle to registrations inside `apply`. A Factory may instead receive the factory itself to create one handle per committed render position. Production code never calls the factory or `.create()` outside registration; tests do (that is the sanctioned zero-machinery path). 7. **inject returns plain data and callbacks** from the apply closure's own ctx — no hand-made hooks, no ReactNode producers, no whole-service objects. A registrant-private reactive fact uses the reserved `hooks` compartment (bare observables the renderer binds to `use`; components never see the sources). The plugin may use only the dependencies named by its `inject` declaration; there is no wider ctx to reach for. 8. **Factory local Components keep stable identities**: pass module-level function Components through `renderFactorySlot(..., { slots })`. Creating a Component function during render intentionally remounts that local subtree and resets its local state; the caller owns that behavior. +9. **A `key` states identity**: pass one when it names which entity or instance the element represents. A key that only silences a warning, or that encodes render order, misstates identity and makes a later remount or reuse decision wrong. ## Reactive read and contract-currency discipline @@ -27,6 +28,8 @@ How live data reaches render code, and what UI domains may share: 4. **UI domains share JSON-compatible data and callbacks.** Owner props, injected values, store state, and provide contributions use these values. Tool `args` may carry the [lazy argument reader](../../.agents/notes/implemented/architecture/2026-09-24-preparing-tool-arguments.md); its Definition republishes the block when an observed answer changes. Transient file-read and document-preview content may also carry `Uint8Array`: published buffers are borrowed read-only, copied before Worker transfer, and never persisted in layout or Session JSON. The injected `hooks` compartment is the only place for bare observables, and components never receive those sources directly. Route ReactNode content through a slot; do not add ReactNode-valued owner props or injected members (the composer's existing `accessory`/`overlay`/`leftItems`/`rightItems` fields remain until they move to slots). 5. **An observable source keeps two identities stable**: the source object itself (hook binding is cached per source), and its snapshot between changes (`getSnapshot` returns the same reference until the fact moves). 6. **Whoever rebuilds a published value republishes it through the same source in the same step**, and a registration path that can run after consumers exist notifies the live consumers as part of registering. +7. **Resource consumers go through `useResource`.** An element showing a resource reads it through the injected `useResource` hook, and a domain wrapper composes its own hook over it rather than reimplementing the fetch, cache, or polling below. Wrapping is free at the business layer as long as the bottom layer is not rebuilt ([client resources](../../docs/subsystems/client-resources.md)). +8. **Effects do not synchronize state.** `useLayoutEffect` is not a default and `useEffect` is not the fix: a layout measurement answers why it happens here, why CSS cannot express it, and why it must be pixel-based, then takes an injected measurement hook. An effect never pushes render-derivable data back to a parent through a props setter; decide it during render, give the host a render-time channel, or move it to the inject face. ## Export discipline (client plugin packages) @@ -66,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 @@ -73,11 +77,11 @@ Client business code may statically read `process.env.DSH_CLIENT_*`; every refer ## Shared modules and the module graph -A dynamic browser half either carries a module privately or requests the shared module-table identity. The client baseline is centralized in [`web/src/platform.ts`](web/src/platform.ts): `PLATFORM_MODULES` names shell-seeded React, Cordis, and static Client libraries; `PRELOADED_CLIENT_EXTERNALS` is reserved for dynamic rows whose factories must arrive before shell boot and is empty when no such row exists. +A dynamic browser half either carries a module privately or requests the shared module-table identity. The client baseline is centralized in [`web/src/platform.ts`](web/src/platform.ts): `PLATFORM_MODULES` names shell-seeded React, Cordis, selected third-party libraries, and static Client libraries; `PRELOADED_CLIENT_EXTERNALS` is reserved for dynamic rows whose factories must arrive before shell boot and is empty when no such row exists. -1. **Baseline externals are implicit for every dynamic bundle.** Do not repeat React, Cordis, `client/store`, `ui-primitives`, `ui-slots`, or `ui-dockkit` in package manifests. +1. **Baseline externals are implicit for every dynamic bundle.** Do not repeat entries from `PLATFORM_MODULES` in `dsh.client.external`; npm dependency declarations still follow the dependency rules above. 2. **`dsh.client.external` is not a feature-plugin dependency mechanism.** Only infrastructure, transport, or generated assembly may add a package-specific non-baseline value request whose dynamic row must be materialized through the module table. Declare the exact import specifier; only a trailing `/client` aliases the package row. -3. **Silence means a private copy.** Ordinary third-party implementation libraries may be bundled independently. A value reached only through `import type` is erased and creates no request. +3. **Silence means a private copy.** Third-party implementation libraries outside the baseline may be bundled independently. A value reached only through `import type` is erased and creates no request. 4. **A request has two possible suppliers.** A dynamic package supplies its own row; `PLATFORM_MODULES` supplies an exact static-table key. There is no `dsh.client.provide` alias protocol. 5. **Validate both sides.** The dynamic build preset externalizes the baseline and rejects undeclared workspace value imports; [`verify-client-packages`](../../scripts/verify-client-packages.ts) rejects malformed or redundant requests, missing suppliers, and synchronous request cycles. 6. **Package-local dynamic chunks are self-contained.** Source uses `import()` and the shared preset emits `require.async("./client..js")`; an entry or chunk must not retain a synchronous relative `require("./client*.js")`. Keep every static relative dependency inside its owning output chunk rather than relying on a sibling-chunk graph the runtime does not support. @@ -139,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. @@ -150,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/README.i18n.yaml b/packages/client/connection/README.i18n.yaml index 7498a796dd..851c94ecbc 100644 --- a/packages/client/connection/README.i18n.yaml +++ b/packages/client/connection/README.i18n.yaml @@ -18,8 +18,8 @@ en: 13b54969ff1d00a4 zh: 4d2ffff0445472ed /deepseek-ai-dsh-client-connection/browser-authentication-and-request-trust: - en: ab52ef146d0b5b42 - zh: 6314d50cfe5683e1 + en: dbd48251ac03d968 + zh: 6323c09d75e56ecc /deepseek-ai-dsh-client-connection/connection-generation: en: 116f94e44c0d87e7 zh: 59ef48984154d858 @@ -30,8 +30,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-client-connection/known-limitations-and-deferred-work: - en: 2c964a7546604347 - zh: c30b59fc92a01c36 + en: ad73c3b97f348ad1 + zh: fec950f970112182 /deepseek-ai-dsh-client-connection/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/connection/README.md b/packages/client/connection/README.md index f973fe1d4e..a5b4d4cc85 100644 --- a/packages/client/connection/README.md +++ b/packages/client/connection/README.md @@ -38,11 +38,13 @@ The browser uses HTTP POST for Remote unary calls. API Gateway owns the `/api/re Every Host RPC method and WebSocket stream requires one browser session; there is no method-specific loopback tier. Each process mints a random launch token. `dsh-web-app` prints and opens its application URL with `?token=...`, preserving the caller's authority and mount; `frontend-static` delegates root and index requests to `ctx.connection.authorizeIndex`, which accepts that token only on `GET /`, writes an authority-bound signed cookie, and redirects to clean `./`, which drops the token and keeps the request's directory. A missing, expired, malformed, or wrong-authority cookie returns 401 before RPC dispatch. Static assets remain public. The HTTP carrier accepts no query token outside the root exchange and no Authorization-header token. -The cookie signing secret is the owner-scoped `client-connection/browser-session` grant record in `ctx.credentials`. The local provider persists it in `$DSH_HOME/.credentials.yaml`; `BrowserAuth` loads or creates the record during Connection activation and retains the secret in memory, so request authentication is synchronous. Deleting or replacing the record takes effect on the next Connection activation. Cookies carry an absolute issue/expiry interval, defaulting to 30 days through `cookieMaxAgeDays`, and bind the normalized hostname plus port in both their deterministic name and signed payload. They are host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`; they deliberately omit `Secure` because the shipped server uses loopback HTTP. +The cookie signing secret is the owner-scoped `client-connection/browser-session` grant record in `ctx.credentials`. The local provider persists it in `$DSH_HOME/.credentials.yaml`; `BrowserAuth` loads or creates the record during Connection activation and retains the secret in memory, so request authentication is synchronous. Deleting or replacing the record takes effect on the next Connection activation. Cookies carry an absolute issue/expiry interval, defaulting to 30 days through `cookieMaxAgeDays`, and bind the normalized hostname plus port in both their deterministic name and signed payload. They are host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`, and carry `Secure` exactly when the listener that received the index request serves TLS; only that listener's own protocol decides, never a `publicUrl` announcement or a forwarded header. -Before authentication, every request still passes `src/api-request-trust.ts`. Its `Host` must be loopback or match a `trustedHosts` entry: exact on `host:port`, any port on port-less entries, both sides WHATWG-normalized. An attached `Origin` must equal that Host and `sec-fetch-site: cross-site` is refused. Malformed configured authorities fail plugin load. These checks defend DNS rebinding and cross-site browser requests; they never establish identity. A failed Host/Origin check returns 403, while a trusted but unauthenticated request returns 401. `dsh web --host 0.0.0.0` remains unsupported. Decision records: [browser request trust](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md) and [browser token authentication](../../../.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md). +HTTPS cookie names and signed audiences include the `https:` scheme, so HTTP cookies cannot authenticate to a TLS listener even on the same hostname and port. Default ports normalize under the listener's scheme. Existing HTTP cookie audiences remain unchanged. -Every admitted request speaks for one Peer, the operator. `ctx.connection.operator` is that `PeerScope`: its `ctx` is a Cordis scope that owns connection-lifetime registrations and is disposed with the Connection. `ctx.connection.admit(request)` runs the trust and authentication checks and answers with the rejection status or the operator; the `/api` route and the Gateway's WebSocket upgrade admit through it, and every RPC handler receives the Peer of its call. `OperatorPeer` is exported so a composition without Connection, such as the Gateway's in-process carrier, owns an operator scope with the same contract. +Before authentication, every request passes `src/api-request-trust.ts`. Its `Host` must be loopback, equal the listener's bind IP literal on any port, or match a `trustedHosts` entry: exact on `host:port`, any port on port-less entries. Host and configured entries use the listener's scheme for WHATWG default-port normalization, not a forwarded header or `Origin`. An attached HTTP(S) `Origin` must name the same authority, with Host parsed under that Origin's scheme to support HTTPS proxies over HTTP upstreams; `sec-fetch-site: cross-site` is refused. Malformed configured authorities fail plugin load. `allowsRemoteAuthorities` reports whether `trustedHosts` permits a non-loopback authority; accepting the bind IP does not change that list. These checks defend DNS rebinding and cross-site browser requests; they never establish identity. A failed Host/Origin check returns 403, while a trusted but unauthenticated request returns 401. `dsh web --host 0.0.0.0` is unsupported. Decision records: [browser request trust](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md) and [browser token authentication](../../../.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md). + +Every request speaks for one Peer, a `PeerScope` whose `principal` names the caller and whose `signal` aborts when its scope ends. `ctx.connection.browserPeer` is the Peer every authenticated browser connection shares; its principal is `{ kind: 'owner' }` and its scope is disposed with the Connection. `ctx.connection.admit(request)` runs the trust and authentication checks and answers with the rejection status or `browserPeer`; the `/api` route and the Gateway's WebSocket upgrade admit through it, and every RPC handler receives the Peer of its call. `ctx.connection.createPeer({ principal })` creates an independent in-process Peer, disposed with the Context that read `ctx.connection` or earlier by its own `dispose()`; no route, header, query, or cookie can create one or set its principal. The exported `Peer` class implements both, and a composition without Connection constructs it directly as `new Peer(owner, { principal })`. `fetch(request, peer)` and the HTTP bridge take the Peer explicitly; an exact route answers 403 to a Peer whose principal is not the owner. Method-level access for other principals belongs to [`dsh-api-remote-access`](../../api/remote-access/README.md). Authenticated shared HTTP requests pass through the `connection/request` waterfall before body transfer. A listener may refuse new requests or await `next()` through response completion; removing its owning fiber removes admission behavior. Desktop uses this hook to lock new API work during an approved installation without canceling already-admitted work. Client disconnection aborts the handler signal; the bridge stops socket writes and drains any remaining response chunks. WebSocket stream ownership remains with API Gateway. @@ -72,7 +74,7 @@ None; this package neither assembles nor sends a provider request. - **Buffered `/api` routes retain each request body in memory** — `maxRequestBodyBytes` (default 300 MiB, sized for the default 200 MiB aggregate image limit after base64 expansion plus envelope headroom) bounds ordinary image and RPC envelopes. Opt-in streaming routes receive backpressured chunks and bypass the aggregate cap; route implementations own persistence, cancellation, and any storage quota. -- **The browser cookie is not marked `Secure`** — loopback HTTP is the shipped transport, so exposing the same authority over plaintext networking can expose the bearer cookie in transit. +- **A plain-HTTP listener exposes the bearer cookie in transit** — such a deployment cannot mark the browser cookie `Secure`, so serving the same authority over a network can leak the session cookie; configure TLS on the Web carrier ([`dsh-host-webserver`](../../host/webserver/README.md)) to have the cookie marked `Secure` and confined to TLS. - **There is no logout operation** — clearing the browser cookie ends one browser session; deleting the owner credential record and restarting `dsh` revokes every session. diff --git a/packages/client/connection/README.zh.md b/packages/client/connection/README.zh.md index 246d875586..cb23e015bd 100644 --- a/packages/client/connection/README.zh.md +++ b/packages/client/connection/README.zh.md @@ -38,11 +38,13 @@ kind: "package-reference" 每个 Host RPC 方法和 WebSocket 流都要求一个浏览器会话,不存在按方法区分的 loopback 层。每个进程生成一个随机启动令牌。`dsh-web-app` 打印并打开带 `?token=...` 的应用 URL,保留调用方的 authority 与挂载;`frontend-static` 把根路径和 index 请求交给 `ctx.connection.authorizeIndex`,后者只在 `GET /` 接受该令牌,写入绑定 authority 的签名 cookie,再重定向到干净的 `./`,移除令牌并保留请求目录。缺失、过期、畸形或 authority 不匹配的 cookie 会在 RPC 分发前得到 401。静态资源保持公开。HTTP 载体不在根路径交换之外接受 query token,也不接受 Authorization header token。 -cookie 签名密钥是 `ctx.credentials` 中由 `client-connection/browser-session` 拥有的 grant 记录。本地提供方把它持久化到 `$DSH_HOME/.credentials.yaml`;`BrowserAuth` 在 Connection 激活期间加载或创建该记录,并把密钥留在内存中,因此请求认证同步执行。删除或替换该记录会在下一次 Connection 激活时生效。cookie 携带绝对签发与过期区间,`cookieMaxAgeDays` 默认设为 30 天,并在确定性名称与签名 payload 中同时绑定规范化 hostname 和 port。它是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`;随附服务器使用 loopback HTTP,因此刻意不设置 `Secure`。 +cookie 签名密钥是 `ctx.credentials` 中由 `client-connection/browser-session` 拥有的 grant 记录。本地提供方把它持久化到 `$DSH_HOME/.credentials.yaml`;`BrowserAuth` 在 Connection 激活期间加载或创建该记录,并把密钥留在内存中,因此请求认证同步执行。删除或替换该记录会在下一次 Connection 激活时生效。cookie 携带绝对签发与过期区间,`cookieMaxAgeDays` 默认设为 30 天,并在确定性名称与签名 payload 中同时绑定规范化 hostname 和 port。它是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`;收到该 index 请求的监听器提供 TLS 时才带上 `Secure`,且只由该监听器自身的协议决定,`publicUrl` 声明与转发头都不参与判断。 -认证之前,每个请求仍经过 `src/api-request-trust.ts`。其 `Host` 必须是 loopback,或与 `trustedHosts` 条目匹配:带端口的 `host:port` 精确匹配,不带端口的条目匹配任意端口,两侧均经 WHATWG 归一化。若附带 `Origin`,它必须等于该 Host;`sec-fetch-site: cross-site` 一律拒绝。畸形配置 authority 会让插件加载失败。这些检查防御 DNS rebinding 与跨站浏览器请求,绝不建立身份。Host/Origin 校验失败返回 403;Host 可信但未认证的请求返回 401。`dsh web --host 0.0.0.0` 仍不受支持。决策记录:[浏览器请求信任](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md)与[浏览器令牌认证](../../../.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md)。 +HTTPS cookie 名称与签名 audience 包含 `https:` scheme,因此即使 hostname 和 port 相同,HTTP cookie 也无法通过 TLS 监听器的认证。默认端口按监听器的 scheme 归一化。既有 HTTP cookie audience 保持不变。 -每个被接纳的请求都代表同一个 Peer——操作者。`ctx.connection.operator` 就是这个 `PeerScope`:其 `ctx` 是拥有连接期注册的 Cordis scope,随 Connection 一起释放。`ctx.connection.admit(request)` 执行信任与认证检查,以拒绝状态或操作者作答;`/api` 路由与 Gateway 的 WebSocket 升级都经它接纳,每个 RPC 处理器都收到本次调用的 Peer。`OperatorPeer` 对外导出,供没有 Connection 的组合(例如 Gateway 的进程内载体)以同一约定拥有一个操作者 scope。 +认证之前,每个请求都经过 `src/api-request-trust.ts`。其 `Host` 必须是 loopback、等于监听器的绑定 IP 字面量(端口不限),或与 `trustedHosts` 条目匹配:带端口的 `host:port` 精确匹配,不带端口的条目匹配任意端口。Host 与配置条目按监听器的 scheme 做 WHATWG 默认端口归一化,不采信转发 header 或 `Origin`。附带的 HTTP(S) `Origin` 必须指向同一 authority;此时按 Origin 的 scheme 解析 Host,以支持 HTTPS 代理转发到 HTTP 上游;`sec-fetch-site: cross-site` 一律拒绝。畸形配置 authority 会让插件加载失败。`allowsRemoteAuthorities` 报告 `trustedHosts` 是否允许非 loopback authority;接受绑定 IP 不会改变该列表。这些检查防御 DNS rebinding 与跨站浏览器请求,绝不建立身份。Host/Origin 校验失败返回 403;Host 可信但未认证的请求返回 401。`dsh web --host 0.0.0.0` 不受支持。决策记录:[浏览器请求信任](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md)与[浏览器令牌认证](../../../.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md)。 + +每个请求都代表一个 Peer:一个 `PeerScope`,其 `principal` 指明调用方,其 `signal` 在 scope 结束时中止。`ctx.connection.browserPeer` 是所有通过认证的浏览器连接共享的 Peer;其 principal 为 `{ kind: 'owner' }`,scope 随 Connection 一起释放。`ctx.connection.admit(request)` 执行信任与认证检查,以拒绝状态或 `browserPeer` 作答;`/api` 路由与 Gateway 的 WebSocket 升级都经它接纳,每个 RPC 处理器都收到本次调用的 Peer。`ctx.connection.createPeer({ principal })` 创建一个独立的进程内 Peer,随读取 `ctx.connection` 的 Context 释放,或更早经其自身的 `dispose()` 释放;任何路由、header、query 或 cookie 都无法创建它或设置其 principal。导出的 `Peer` 类实现这两者,没有 Connection 的组合直接以 `new Peer(owner, { principal })` 构造。`fetch(request, peer)` 与 HTTP bridge 显式接收 Peer;对 principal 不是 owner 的 Peer,exact route 返回 403。其他 principal 的方法级访问归 [`dsh-api-remote-access`](../../api/remote-access/README.zh.md)。 通过认证的共享 HTTP 请求在传输请求体之前经过 `connection/request` waterfall。监听器可以拒绝新请求,或等待 `next()` 直到响应完成;释放所属 fiber 会移除准入行为。Desktop 使用此扩展点,在已批准的安装期间锁住新的 API 工作,而不取消已接纳的工作。客户端断开会中止处理函数的信号;桥接器停止写入 socket,并排空剩余响应块。WebSocket 流仍由 API Gateway 负责。 @@ -72,7 +74,7 @@ API Gateway Client 把内部 `$events` 逻辑流注册为唯一 generation sourc - **缓冲型 `/api` 路由会把每个请求体保留在内存里**:`maxRequestBodyBytes`(默认 300 MiB,按默认 200 MiB 图片总量上限经 base64 膨胀加信封余量得出)限制普通图片与 RPC 信封。显式启用的流式路由接收带背压的分块并绕过总量上限;路由实现负责持久化、取消与存储配额。 -- **浏览器 cookie 不带 `Secure`**:当前随产品提供的传输方式是 loopback HTTP;若部署经明文网络暴露同一 authority,bearer cookie 可能在传输中泄露。 +- **明文 HTTP 监听器会在传输中暴露 bearer cookie**:此类部署无法给浏览器 cookie 加 `Secure`;若把同一 authority 暴露到网络上,会话 cookie 可能泄露;在 Web 载体([`dsh-host-webserver`](../../host/webserver/README.zh.md))上配置 TLS 即可让 cookie 带上 `Secure` 并只经 TLS 发送。 - **没有 logout 操作**:清除浏览器 cookie 会结束单个浏览器会话;删除 owner 凭据记录并重启 `dsh` 会撤销全部会话。 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 881601a7df..057a4dda71 100644 --- a/packages/client/connection/package.json +++ b/packages/client/connection/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-connection", "description": "Authenticated RPC transport and generation lifecycle", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -36,9 +37,10 @@ "dependencies": { "@deepseek-ai/dsh-credentials": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts", diff --git a/packages/client/connection/src/api-request-trust.ts b/packages/client/connection/src/api-request-trust.ts index 1065dfe876..a2fb78ec6c 100644 --- a/packages/client/connection/src/api-request-trust.ts +++ b/packages/client/connection/src/api-request-trust.ts @@ -4,13 +4,12 @@ * the attacker's domain while the socket reaches this server) and cross-site * requests fired from a malicious page. The Host fence binds every request, * browser-looking or not: over plain HTTP a browser attaches neither Origin - * nor Fetch-Metadata to reads (images and navigations — those - * headers go only to trustworthy destinations), so an unmarked request may - * still be a rebound browser read and Host is the one header rebinding cannot - * forge. Non-browser and remote clients pass the same fence via loopback, - * deployment-derived LAN IP literals, or a declared `trustedHosts` authority. - * Network reachability and authentication stay out of scope: binding policy - * belongs to the webserver config, and this fence is not an auth layer. + * nor Fetch-Metadata to reads (images and navigations — those headers go only + * to trustworthy destinations), so an unmarked request may still be a rebound + * browser read and Host is the one header rebinding cannot forge. Non-browser + * and remote clients pass the same fence via loopback, the listener's bind IP + * literal, or a declared `trustedHosts` authority. Binding policy belongs to + * the webserver config; this fence never establishes identity. */ import { isLoopbackHostname } from './loopback-hostname.ts' @@ -22,11 +21,16 @@ function header(headers: ConnectionTrustRequest['headers'], name: string): strin return typeof value === 'string' ? value : undefined } -/** Normalized URL of a Host-header authority (hostname lowercased, default port stripped, IPv6 bracketed), or undefined when unparsable. */ -function parseAuthority(authority: string): URL | undefined { +/** + * Normalized URL of a bare authority (hostname lowercased, default port + * stripped, IPv6 bracketed), or undefined when unparsable. + * @param authority - `host` or `host:port` text. + * @param scheme - special scheme to parse under; its default port is the one stripped. + */ +function parseAuthority(authority: string, scheme: 'http:' | 'https:' = 'http:'): URL | undefined { try { - // http: is a WHATWG "special scheme": parsing yields a non-empty hostname or throws. - return new URL(`http://${authority}`) + // http: and https: are WHATWG "special schemes": parsing yields a non-empty hostname or throws. + return new URL(`${scheme}//${authority}`) } catch { return undefined } @@ -60,21 +64,19 @@ export function assertTrustedAuthority(entry: string): void { * shapes like `host:port ` as port-less. */ function canonicalAuthority(entry: string, entryUrl: URL): string { - // An authority that parsed under http cannot fail under https. - const port = entryUrl.port !== '' ? entryUrl.port : new URL(`https://${entry}`).port + const port = entryUrl.port !== '' ? entryUrl.port : new URL(`${entryUrl.protocol === 'http:' ? 'https:' : 'http:'}//${entry}`).port return port === '' ? entryUrl.hostname : `${entryUrl.hostname}:${port}` } /** * Whether the request authority matches a `trustedHosts` entry. An entry with * an explicit port matches that exact authority; a port-less entry matches the - * hostname on any port (the shape the CLI derives for IP-literal LAN serving, - * where the bound port may be OS-assigned). Both sides compare through WHATWG - * normalization, so case and a redundant `:80` never decide trust. + * hostname on any port. Both sides compare through WHATWG normalization, + * so case and a redundant scheme-default port never decide trust. */ -function isTrustedAuthority(hostUrl: URL, trustedHosts: readonly string[]): boolean { +function isTrustedAuthority(hostUrl: URL, trustedHosts: readonly string[], protocol: 'http:' | 'https:'): boolean { return trustedHosts.some((entry) => { - const entryUrl = parseAuthority(entry) + const entryUrl = parseAuthority(entry, protocol) if (entryUrl === undefined) return false return canonicalAuthority(entry, entryUrl) === entryUrl.hostname ? entryUrl.hostname === hostUrl.hostname @@ -82,13 +84,46 @@ function isTrustedAuthority(hostUrl: URL, trustedHosts: readonly string[]): bool }) } +/** + * Classify an authority already accepted by {@link assertTrustedAuthority}. + * @param entry - the configured authority, verbatim. + * @returns true unless the entry parses as a loopback hostname. + */ +export function isRemoteAuthority(entry: string): boolean { + const url = parseAuthority(entry) + return url === undefined || !isLoopbackHostname(url.hostname) +} + +/** + * Whether a parsed authority names the deployment's own bind address. A browser + * dialing that literal sends it as Host, and accepting it grants nothing + * further: the literal is no rebinding target, the Origin and cross-site checks + * still apply, and it stays outside `trustedHosts`. Matching ignores the port, + * like a port-less entry, and any `%zone` id (an interface selector, not + * address text). + */ +function isBindAddressAuthority(hostUrl: URL, bindHost: string | undefined): boolean { + if (bindHost === undefined) return false + const zoneAt = bindHost.indexOf('%') + const address = zoneAt === -1 ? bindHost : bindHost.slice(0, zoneAt) + const bindUrl = parseAuthority(address.includes(':') ? `[${address}]` : address) + return bindUrl !== undefined && bindUrl.hostname === hostUrl.hostname +} + /** * Decide whether one /api request may reach the RPC bridge. * @param request - Node HTTP or Fetch request facts (headers). * @param trustedHosts - non-loopback authorities this deployment serves: exact `host:port`, or port-less `host` matching any port. - * @returns true when the Host is ours (loopback or trusted) and any attached browser markers are same-origin. + * @param bindHost - the listener's own bind IP literal, accepted on any port independently of `trustedHosts`. + * @param protocol - listener protocol for default Host ports; HTTP when no Web carrier is mounted. + * @returns true when the Host is ours (loopback, the bind address, or trusted) and any attached browser markers are same-origin. */ -export function isTrustedApiRequest(request: ConnectionTrustRequest, trustedHosts: readonly string[]): boolean { +export function isTrustedApiRequest( + request: ConnectionTrustRequest, + trustedHosts: readonly string[], + bindHost?: string, + protocol: 'http:' | 'https:' = 'http:', +): boolean { // Host fence (DNS-rebinding defense), applied to every request: the browser // fills Host from the URL it believes it is talking to, so a rebound page // carries the attacker's domain here even though the socket lands on this @@ -98,9 +133,11 @@ export function isTrustedApiRequest(request: ConnectionTrustRequest, trustedHost // by the rebound page. const host = header(request.headers, 'host') if (host === undefined) return false - const hostUrl = parseAuthority(host) + const hostUrl = parseAuthority(host, protocol) if (hostUrl === undefined) return false - if (!isLoopbackHostname(hostUrl.hostname) && !isTrustedAuthority(hostUrl, trustedHosts)) return false + if (!isLoopbackHostname(hostUrl.hostname) + && !isTrustedAuthority(hostUrl, trustedHosts, protocol) + && !isBindAddressAuthority(hostUrl, bindHost)) return false // Cross-site fence: modern browsers label the initiator relationship on // every fetch; an explicit cross-site marker is refused regardless of Origin. if (header(request.headers, 'sec-fetch-site') === 'cross-site') return false @@ -110,9 +147,30 @@ export function isTrustedApiRequest(request: ConnectionTrustRequest, trustedHost // literal "null" (sandboxed iframes, file: pages) is an opaque origin, refused. const origin = header(request.headers, 'origin') if (origin === undefined) return true + return isSameAuthorityOrigin(origin, host) +} + +/** + * Compare Host under the Origin's HTTP(S) scheme so default ports normalize + * consistently. The transport may remain HTTP behind an HTTPS proxy. + * @param origin - verbatim Origin header value. + * @param host - verbatim Host header value already accepted by the Host fence. + * @returns true only when the Origin is this listener's own `http(s)` authority. + */ +function isSameAuthorityOrigin(origin: string, host: string): boolean { + let originUrl: URL try { - return new URL(origin).host === hostUrl.host + originUrl = new URL(origin) } catch { return false } + // Only http(s) can name this listener: the opaque `null` already threw above, + // and every other scheme (file:, ftp:) fails here rather than matching by + // hostname alone. + const scheme = originUrl.protocol === 'https:' ? 'https:' + : originUrl.protocol === 'http:' ? 'http:' + : undefined + if (scheme === undefined) return false + const hostUrl = parseAuthority(host, scheme) + return hostUrl !== undefined && originUrl.host === hostUrl.host } diff --git a/packages/client/connection/src/browser-auth.ts b/packages/client/connection/src/browser-auth.ts index 5691180d96..6b01531da6 100644 --- a/packages/client/connection/src/browser-auth.ts +++ b/packages/client/connection/src/browser-auth.ts @@ -66,12 +66,13 @@ function header( return typeof value === 'string' ? value : undefined } -/** Canonical request authority used as the cookie name and signed audience. */ -function requestAuthority(headers: ConnectionTrustRequest['headers']): string | undefined { +/** Protocol-scoped cookie audience; HTTP retains its existing authority-only spelling. */ +function requestAudience(headers: ConnectionTrustRequest['headers'], secure: boolean): string | undefined { const host = header(headers, 'host') if (host === undefined) return undefined try { - return new URL(`http://${host}`).host + const url = new URL(`${secure ? 'https:' : 'http:'}//${host}`) + return secure ? url.origin : url.host } catch { return undefined } @@ -118,8 +119,15 @@ function cookieValue(headerValue: string, name: string): string | undefined { } /** Serialize the fixed browser-session attributes; generated names and values are cookie-safe base64url. */ -function sessionCookie(name: string, value: string, expiresAt: number, maxAgeSeconds: number): string { - return `${name}=${value}; Max-Age=${String(maxAgeSeconds)}; Path=/; Expires=${new Date(expiresAt).toUTCString()}; HttpOnly; SameSite=Strict` +function sessionCookie( + name: string, + value: string, + expiresAt: number, + maxAgeSeconds: number, + secure: boolean, +): string { + const attributes = `${name}=${value}; Max-Age=${String(maxAgeSeconds)}; Path=/; Expires=${new Date(expiresAt).toUTCString()}; HttpOnly; SameSite=Strict` + return secure ? `${attributes}; Secure` : attributes } function signature(secret: Buffer, body: string): Buffer { @@ -233,14 +241,18 @@ export class BrowserAuth { * 401 response. * @param req - incoming root or configured-index request. * @param res - response owned when this method returns false. + * @param secure - whether the listener receiving this request serves TLS; the + * minted cookie carries `Secure` when it does. Only that listener's own + * protocol decides, never a `publicUrl` announcement or a forwarded header: + * those describe a hop this process does not terminate. * @returns true only when the caller may serve index.html. */ - authorizeIndex(req: ConnectionIndexRequest, res: ConnectionIndexResponse): boolean { + authorizeIndex(req: ConnectionIndexRequest, res: ConnectionIndexResponse, secure = false): boolean { /* v8 ignore next -- node:http always supplies url on server requests. */ const url = new URL(req.url ?? '/', 'http://dsh.invalid') const tokens = url.searchParams.getAll(TOKEN_QUERY) if (tokens.length > 0) { - const authority = requestAuthority(req.headers) + const authority = requestAudience(req.headers, secure) if (req.method === 'GET' && url.pathname === '/' && tokens.length === 1 && authority !== undefined && tokenMatches(tokens.join(''), this.launchToken)) { const issuedAt = Date.now() @@ -256,13 +268,13 @@ export class BrowserAuth { 'location': './', 'referrer-policy': 'no-referrer', 'set-cookie': sessionCookie( - cookieName(authority), value, expiresAt, Math.floor(this.maxAgeMilliseconds / 1000), + cookieName(authority), value, expiresAt, Math.floor(this.maxAgeMilliseconds / 1000), secure, ), }) res.end() return false } - if (req.method === 'GET' && url.pathname === '/' && this.isAuthenticated(req)) { + if (req.method === 'GET' && url.pathname === '/' && this.isAuthenticated(req, secure)) { res.writeHead(303, { 'cache-control': 'no-store', 'location': './', @@ -274,7 +286,7 @@ export class BrowserAuth { this.writeUnauthorized(req, res) return false } - if (this.isAuthenticated(req)) return true + if (this.isAuthenticated(req, secure)) return true this.writeUnauthorized(req, res) return false } @@ -282,10 +294,11 @@ export class BrowserAuth { /** * Verify the authority-bound browser cookie on a Host request. * @param request - request headers carrying Host and Cookie. + * @param secure - whether the receiving listener uses TLS, including its default port. * @returns true only for an unexpired cookie signed by this activation's loaded secret. */ - isAuthenticated(request: ConnectionTrustRequest): boolean { - const authority = requestAuthority(request.headers) + isAuthenticated(request: ConnectionTrustRequest, secure = false): boolean { + const authority = requestAudience(request.headers, secure) const rawCookie = header(request.headers, 'cookie') if (authority === undefined || rawCookie === undefined) return false const value = cookieValue(rawCookie, cookieName(authority)) diff --git a/packages/client/connection/src/client/index.ts b/packages/client/connection/src/client/index.ts index e9d80a64f4..910cea58c5 100644 --- a/packages/client/connection/src/client/index.ts +++ b/packages/client/connection/src/client/index.ts @@ -96,7 +96,7 @@ export interface ClientTransportHooks { /** * The transport owner declares the page owns the Host outright: the Host * runs inside a worker this page spawned, so no other party can reach it and - * the loopback stand-in for "the operator's own machine" is vacuous. + * the loopback stand-in for "the owner's own machine" is vacuous. * `ctx.connection.isLoopback` then reports the privileged surface reachable * regardless of the page authority. Only a shell that assembles its own * transport can set this; served pages never carry the global at all. diff --git a/packages/client/connection/src/http-bridge.ts b/packages/client/connection/src/http-bridge.ts index 713f53dcea..2343b1c38b 100644 --- a/packages/client/connection/src/http-bridge.ts +++ b/packages/client/connection/src/http-bridge.ts @@ -5,6 +5,7 @@ import type { IncomingMessage } from 'node:http' import { Readable } from 'node:stream' +import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol' import type { ConnectionFetchHandler } from './rpc.ts' /** Default carrier cap for all HTTP RPC bodies: sized for the default @@ -30,12 +31,14 @@ interface BridgeServerResponse { * @param req - incoming node:http request. * @param res - node:http response the bridge writes and owns to completion. * @param apiHandler - fetch-shaped API carrier the request is dispatched to. + * @param peer - Peer the carrier admitted the request as. * @param maxRequestBodyBytes - maximum bytes buffered for a buffered route. */ export async function bridge( req: IncomingMessage, res: BridgeServerResponse, apiHandler: ConnectionFetchHandler, + peer: PeerScope, maxRequestBodyBytes = DEFAULT_MAX_REQUEST_BODY_BYTES, ): Promise { const abort = new AbortController() @@ -91,7 +94,7 @@ export async function bridge( duplex: 'half', } as RequestInit & { duplex: 'half' }) } - const response = await apiHandler.fetch(request) + const response = await apiHandler.fetch(request, peer) const requestUnread = bodyMode === 'streaming' && !req.readableEnded const responseHeaders = Object.fromEntries(response.headers.entries()) res.writeHead(response.status, requestUnread ? { ...responseHeaders, connection: 'close' } : responseHeaders) diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index 647174f743..ce58da1606 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -36,9 +36,10 @@ export type { RpcMessage, ServerResponse, } from './rpc.ts' -export type { PeerId, PeerScope, RemoteInvocation } from '@deepseek-ai/dsh-typert-protocol' +export type { PeerId, PeerScope, Principal, RemoteInvocation } from '@deepseek-ai/dsh-typert-protocol' export { RpcId, transportError } from './rpc.ts' -export { OperatorPeer } from './operator-peer.ts' +export { Peer } from './peer.ts' +export type { PeerOptions } from './peer.ts' export { clientRequestSchema, rpcErrorSchema, @@ -94,11 +95,9 @@ export interface ConnectionConfig { recovery?: ConnectionRecoveryConfig /** * Authorities this deployment serves beyond loopback: exact `host:port`, or - * port-less `host` matching any port. The /api trust fence refuses any - * request whose Host is neither loopback nor listed here, so a - * non-loopback (`0.0.0.0`) deployment must declare the names it is reached - * by; the Web runtime derives LAN IP literals from an active all-interface - * bind. An entry that is not a bare, canonical authority fails plugin load. + * port-less `host` matching any port. The fence accepts loopback and the + * listener's own bind IP independently; other remote authorities require + * an entry here. A non-canonical or non-bare authority fails plugin load. */ trustedHosts?: string[] /** Absolute browser-session lifetime in days. Default: 30. */ @@ -152,7 +151,7 @@ export async function apply(ctx: Context, config?: ConnectionConfig): Promise bridge(req, res, fetchHandler, maxRequestBodyBytes)) + await webCtx.waterfall('connection/request', req, res, () => bridge(req, res, fetchHandler, admission.peer, maxRequestBodyBytes)) }, } webCtx.effect(() => webCtx.webServer.register(route), 'client-connection: /api route') diff --git a/packages/client/connection/src/operator-peer.ts b/packages/client/connection/src/operator-peer.ts deleted file mode 100644 index 83325f78e7..0000000000 --- a/packages/client/connection/src/operator-peer.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** - * The operator Peer: the one party this Host answers to. Connection owns it - * for its own lifetime, admits every request as it, and hands it to each - * Remote call as `invocation.peer`. - * @module @deepseek-ai/dsh-client-connection/src/operator-peer - */ - -import { randomUUID } from 'node:crypto' -import type { Context } from '@deepseek-ai/cordis' -import { createScope, type Scope } from '@deepseek-ai/dsh-scope' -import type { PeerId, PeerScope } from '@deepseek-ai/dsh-typert-protocol' - -/** - * The operator's scope. The instance is its own scope key, so `scopeOf(peer.ctx)` - * returns it and events dispatched with `scopeTarget(subject, peer)` reach - * listeners registered through `peer.ctx` and nobody else. - */ -export class OperatorPeer implements PeerScope { - readonly id: PeerId = randomUUID() as PeerId - readonly ctx: Context - private readonly scope: Scope - - /** @param owner - Connection plugin context the scope fiber hangs under. */ - constructor(owner: Context) { - this.scope = createScope(owner, this) - this.ctx = this.scope.ctx - } - - /** Tear down every connection-lifetime registration; racing calls share one completion. */ - dispose(): Promise { - return this.scope.dispose() - } -} diff --git a/packages/client/connection/src/peer.ts b/packages/client/connection/src/peer.ts new file mode 100644 index 0000000000..991ac521ba --- /dev/null +++ b/packages/client/connection/src/peer.ts @@ -0,0 +1,49 @@ +/** + * The Peer: one party admitted to this Host. Its creator fixes the principal + * it speaks for and owns its lifetime; Gateway hands it to each Remote call as + * `invocation.peer`. + * @module @deepseek-ai/dsh-client-connection/src/peer + */ + +import { randomUUID } from 'node:crypto' +import type { Context } from '@deepseek-ai/cordis' +import { createScope, type Scope } from '@deepseek-ai/dsh-scope' +import type { PeerId, PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol' + +/** Construction options for one {@link Peer}. */ +export interface PeerOptions { + /** Caller identity every call through this Peer speaks for. */ + readonly principal: Principal +} + +/** + * One Peer's scope. The instance is its own scope key, so `scopeOf(peer.ctx)` + * returns it and events dispatched with `scopeTarget(subject, peer)` reach + * listeners registered through `peer.ctx` and nobody else. + */ +export class Peer implements PeerScope { + readonly id: PeerId = randomUUID() as PeerId + readonly ctx: Context + readonly principal: Principal + readonly signal: AbortSignal + private readonly scope: Scope + + /** + * @param owner - Context the scope fiber hangs under; disposing it disposes the Peer. + * @param options - the principal fixed for this Peer's lifetime. + */ + constructor(owner: Context, options: PeerOptions) { + this.principal = options.principal + this.scope = createScope(owner, this) + this.ctx = this.scope.ctx + const lifetime = new AbortController() + this.signal = lifetime.signal + // Runs however the scope ends: dispose() or the owner Context unloading. + this.ctx.effect(() => () => { lifetime.abort(new Error(`Peer ${this.id} was disposed`)) }, 'client-connection: Peer lifetime') + } + + /** Tear down every connection-lifetime registration; racing calls share one completion. */ + dispose(): Promise { + return this.scope.dispose() + } +} diff --git a/packages/client/connection/src/rpc-host.ts b/packages/client/connection/src/rpc-host.ts index 0f98bc1f19..33562d790f 100644 --- a/packages/client/connection/src/rpc-host.ts +++ b/packages/client/connection/src/rpc-host.ts @@ -2,7 +2,7 @@ import { Context, Service } from '@deepseek-ai/cordis' import type { WebRoute } from '@deepseek-ai/dsh-host-webserver' -import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol' +import type { PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol' import { RpcId, type ClientRequest, @@ -10,10 +10,10 @@ import { } from './rpc.ts' import { clientRequestSchema } from './rpc-schema.ts' import { bridge } from './http-bridge.ts' -import { isTrustedApiRequest } from './api-request-trust.ts' +import { isRemoteAuthority, isTrustedApiRequest } from './api-request-trust.ts' import { API_PATH } from './api-path.ts' import type { BrowserAuth } from './browser-auth.ts' -import { OperatorPeer } from './operator-peer.ts' +import { Peer } from './peer.ts' import type { PeerAdmission, ConnectionIndexRequest, @@ -61,11 +61,13 @@ declare module '@deepseek-ai/cordis' { /** Host Connection service whose channel registrations belong to the caller fiber. */ export class HostConnectionService extends Service implements HostConnectionHandle { - /** The operator Peer every admitted request speaks for. */ - readonly operator: PeerScope + /** The Peer every authenticated browser connection shares. */ + readonly browserPeer: PeerScope private readonly interceptors = new Map() private readonly fetchRoutes = new Map() + readonly allowsRemoteAuthorities: boolean + /** * Provide the Host half over the active HTTP server. * @param ctx - owning Connection plugin context. @@ -78,8 +80,9 @@ export class HostConnectionService extends Service implements HostConnectionHand private readonly browserAuth: BrowserAuth, ) { super(ctx, 'connection') - this.operator = new OperatorPeer(ctx) - ctx.effect(() => () => this.operator.dispose(), 'client-connection: operator Peer') + this.browserPeer = new Peer(ctx, { principal: { kind: 'owner' } }) + ctx.effect(() => () => this.browserPeer.dispose(), 'client-connection: browser Peer') + this.allowsRemoteAuthorities = trustedHosts.some(isRemoteAuthority) } /** Generic channel registry scoped to the Context reading this service. */ @@ -100,21 +103,29 @@ export class HostConnectionService extends Service implements HostConnectionHand } } - /** Apply the configured Host/Origin fence, then browser authentication. */ + /** Apply the Host/Origin fence, then browser authentication. */ requestRejection(request: ConnectionTrustRequest): ConnectionRequestRejection { - if (!isTrustedApiRequest(request, this.trustedHosts)) return 403 - return this.browserAuth.isAuthenticated(request) ? undefined : 401 + const carrier = this.ctx.get('webServer') + if (!isTrustedApiRequest(request, this.trustedHosts, carrier?.host, carrier?.protocol ?? 'http:')) return 403 + return this.browserAuth.isAuthenticated(request, carrier?.protocol === 'https:') ? undefined : 401 } - /** A request that passes the fence and authentication speaks for the operator. */ + /** A request that passes the fence and authentication speaks for the shared browser Peer. */ admit(request: ConnectionTrustRequest): PeerAdmission { const rejection = this.requestRejection(request) - return rejection === undefined ? { peer: this.operator } : { rejection } + return rejection === undefined ? { peer: this.browserPeer } : { rejection } } - /** Authenticate an index request through the process-token exchange or cookie. */ + /** Create one in-process Peer owned by the Context that read this service. */ + createPeer(options: { readonly principal: Principal }): PeerScope { + return new Peer(this.ctx, options) + } + + /** + * Authenticate an index request; native TLS listeners mint Secure cookies. + */ authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexResponse): boolean { - return this.browserAuth.authorizeIndex(request, response) + return this.browserAuth.authorizeIndex(request, response, this.ctx.get('webServer')?.protocol === 'https:') } /** Add this process's launch token to the clean application URL. */ @@ -135,16 +146,21 @@ export class HostConnectionService extends Service implements HostConnectionHand const route = this.fetchRoutes.get(url.pathname) return route?.methods.has(method) === true ? route.requestBody : 'buffered' }, - fetch: (request) => { + fetch: (request, peer) => { const pathname = new URL(request.url).pathname const route = this.fetchRoutes.get(pathname) - if (route?.methods.has(request.method) === true) return route.fetch(request) + if (route?.methods.has(request.method) === true) { + // Exact routes bypass Gateway access checks, so only the owner reaches them. + // oxlint-disable-next-line typescript/no-unnecessary-condition -- other packages merge non-owner kinds into PrincipalMap. + if (peer.principal.kind !== 'owner') return Promise.resolve(new Response('forbidden', { status: 403 })) + return route.fetch(request) + } const endpoint = endpointFromPath(channel, pathname) const interceptor = this.interceptors.get(channel) if (endpoint === undefined || interceptor === undefined || !interceptor.matches(endpoint)) { return Promise.resolve(new Response('not found', { status: 404 })) } - return interceptor.fetchHandler.fetch(request) + return interceptor.fetchHandler.fetch(request, peer) }, } } @@ -174,7 +190,7 @@ export class HostConnectionService extends Service implements HostConnectionHand handler: ConnectionRpcHandler, ): () => Promise { assertChannel(channel) - const fetchHandler = rpcFetchHandler(channel, handler, this.operator) + const fetchHandler = rpcFetchHandler(channel, handler) const route: WebRoute = { kind: 'prefix', path: channel, @@ -185,7 +201,7 @@ export class HostConnectionService extends Service implements HostConnectionHand res.end(admission.rejection === 401 ? 'unauthorized' : 'forbidden') return } - await bridge(req, res, fetchHandler) + await bridge(req, res, fetchHandler, admission.peer) }, } return owner.effect( @@ -205,7 +221,7 @@ export class HostConnectionService extends Service implements HostConnectionHand } const interceptor: ConnectionRpcInterceptor = { matches, - fetchHandler: rpcFetchHandler(channel, handler, this.operator), + fetchHandler: rpcFetchHandler(channel, handler), } return owner.effect(() => { if (this.interceptors.has(channel)) { @@ -222,11 +238,10 @@ export class HostConnectionService extends Service implements HostConnectionHand function rpcFetchHandler( channel: string, handler: ConnectionRpcHandler, - peer: PeerScope, ): ConnectionFetchHandler { return { requestBodyMode: () => 'buffered', - async fetch(request: Request): Promise { + async fetch(request: Request, peer: PeerScope): Promise { const endpoint = endpointFromPath(channel, new URL(request.url).pathname) if (request.method !== 'POST' || endpoint === undefined) { return new Response('not found', { status: 404 }) diff --git a/packages/client/connection/src/rpc.ts b/packages/client/connection/src/rpc.ts index 0b8755bf71..2d1cfda387 100644 --- a/packages/client/connection/src/rpc.ts +++ b/packages/client/connection/src/rpc.ts @@ -1,7 +1,7 @@ /** Generic unary RPC contracts shared by the Host and Client Connection halves. */ import type { Branded } from '@deepseek-ai/dsh-brand' -import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol' +import type { PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol' /** Correlation id minted by a caller and echoed by the Connection response. */ export type RpcId = Branded<'rpc-id'> @@ -115,14 +115,14 @@ export interface ConnectionIndexResponse { end(body?: string): unknown } -/** Outcome of admitting one request: the operator Peer it speaks for, or the status refusing it. */ +/** Outcome of admitting one request: the Peer it speaks for, or the status refusing it. */ export type PeerAdmission = | { readonly peer: PeerScope } | { readonly rejection: 401 | 403 } /** * Handler invoked after Connection has decoded the transport envelope. - * `peer` is the Peer the request was admitted as: the operator. + * `peer` is the Peer the carrier admitted or the in-process caller supplied. */ export type ConnectionRpcHandler = ( endpoint: string, @@ -148,7 +148,11 @@ export interface ConnectionFetchRoute { readonly methods: readonly ConnectionFetchMethod[] /** Buffered requests obey the configured JSON cap; streaming requests arrive with backpressure and no aggregate cap. */ readonly requestBody: ConnectionRequestBodyMode - /** Handle one request after the physical carrier has applied its trust and authentication policy. */ + /** + * Handle one request after the physical carrier has applied its trust and + * authentication policy. Only owner Peers reach an exact route; the shared + * handler answers 403 for every other principal. + */ readonly fetch: (request: Request) => Promise } @@ -195,8 +199,17 @@ export interface HostConnectionHandle { readonly rpc: HostConnectionRpc /** Exact Fetch routes for streaming or browser-native responses. */ readonly fetch: HostConnectionFetch - /** The operator Peer every admitted request speaks for; its scope lives as long as Connection. */ - readonly operator: PeerScope + /** + * The Peer every authenticated browser connection shares; its principal is + * the owner and its scope lives as long as Connection. + */ + readonly browserPeer: PeerScope + + /** + * Whether this deployment accepts authorities beyond loopback: true only + * when a validated `trustedHosts` entry names a non-loopback hostname. + */ + readonly allowsRemoteAuthorities: boolean /** * Compose exact Fetch routes and the shared-channel RPC interceptor. @@ -214,15 +227,27 @@ export interface HostConnectionHandle { requestRejection(request: ConnectionTrustRequest): ConnectionRequestRejection /** - * Admit one request: it passes {@link requestRejection} and speaks for the - * operator, or it is refused with that status. + * Admit one network request: it passes {@link requestRejection} and speaks + * for {@link browserPeer}, or it is refused with that status. * @param request - request headers from the HTTP or upgrade request. - * @returns the operator Peer, or the rejection status. + * @returns the admitted Peer, or the rejection status. */ admit(request: ConnectionTrustRequest): PeerAdmission + /** + * Create an independent Peer. In-process only: no route, header, query, or + * cookie reaches it. Disposed with the Context that read `ctx.connection`, + * or earlier by its own `dispose()`. + * @param options - caller identity the Peer speaks for. + * @param options.principal - principal fixed for the Peer's lifetime. + * @returns a new Peer distinct from every other Peer. + */ + createPeer(options: { readonly principal: Principal }): PeerScope + /** * Authenticate one frontend index request, owning a token redirect or 401. + * The cookie this mints is `Secure` when the mounted Web carrier serves TLS, + * which only that listener's protocol decides. * @param request - root or configured-index HTTP request. * @param response - response owned when the result is false. * @returns true only when the frontend may serve index.html. @@ -249,9 +274,10 @@ export interface ConnectionFetchHandler { /** * Dispatch one already-authenticated request. * @param request - Fetch request below the shared channel. - * @returns the registered response or a 404 response. + * @param peer - Peer to dispatch as; required, never defaulted. + * @returns the registered response, a 403 response for an exact route and a non-owner Peer, or a 404 response. */ - fetch(request: Request): Promise + fetch(request: Request, peer: PeerScope): Promise } /** Client caller for logical RPC channels carried by the current transport. */ diff --git a/packages/client/connection/tests/api-request-trust.host.spec.ts b/packages/client/connection/tests/api-request-trust.host.spec.ts index 359a461e94..9d07ce679f 100644 --- a/packages/client/connection/tests/api-request-trust.host.spec.ts +++ b/packages/client/connection/tests/api-request-trust.host.spec.ts @@ -25,6 +25,26 @@ describe('isTrustedApiRequest', () => { } }) + it('accepts the listener\'s own bind address port-lessly, and nothing that merely resembles it', () => { + // A browser dialing the bind address sends that IP literal as Host; the + // port is not part of the grant. + for (const host of ['10.1.2.3', '10.1.2.3:3080', '10.1.2.3:9999']) { + expect(isTrustedApiRequest(request({ host }), [], '10.1.2.3')).toBe(true) + } + expect(isTrustedApiRequest(request({ host: '10.1.2.4:3080' }), [], '10.1.2.3')).toBe(false) + expect(isTrustedApiRequest(request({ host: 'dsh-direct.lan:3080' }), [], '10.1.2.3')).toBe(false) + expect(isTrustedApiRequest(request({ host: '10.1.2.3:3080' }), [])).toBe(false) + // IPv6 spellings compare through the same normalization as Host, mapped + // forms included; a zone id selects the local interface, not the address. + for (const host of ['[fd00::1]', '[fd00::1]:3080', '[::ffff:a01:203]:3080', '[::ffff:10.1.2.3]:3080']) { + const bindHost = host.startsWith('[::ffff') ? '::ffff:10.1.2.3' : 'fd00::1' + expect(isTrustedApiRequest(request({ host }), [], bindHost)).toBe(true) + } + expect(isTrustedApiRequest(request({ host: '[fd00::2]:3080' }), [], 'fd00::1')).toBe(false) + expect(isTrustedApiRequest(request({ host: '[fd00::1]:3080' }), [], 'fe80::1%lo')).toBe(false) + expect(isTrustedApiRequest(request({ host: '[fe80::1]:3080' }), [], 'fe80::1%lo')).toBe(true) + }) + it('refuses a rebound Host: the attacker domain names the socket it did not expect', () => { expect(isTrustedApiRequest(request({ host: 'evil.example:3080', @@ -33,6 +53,32 @@ describe('isTrustedApiRequest', () => { }), [])).toBe(false) }) + it('compares Origin and Host under the Origin scheme, so HTTPS default ports normalize like HTTP ones', () => { + // A browser omits the default port it dialed, while a proxy or a direct + // client may still write it in Host: both spellings name one authority. + expect(isTrustedApiRequest(request({ host: 'harness.internal:443', origin: 'https://harness.internal' }), ['harness.internal'])).toBe(true) + expect(isTrustedApiRequest(request({ host: 'harness.internal:443', origin: 'https://harness.internal:443' }), ['harness.internal'])).toBe(true) + expect(isTrustedApiRequest(request({ host: 'harness.internal', origin: 'https://harness.internal:443' }), ['harness.internal'])).toBe(true) + expect(isTrustedApiRequest(request({ host: 'harness.internal:80', origin: 'http://harness.internal' }), ['harness.internal'])).toBe(true) + // A TLS-terminating proxy forwards the browser's https Origin to a plain-HTTP upstream. + expect(isTrustedApiRequest(request({ host: 'harness.internal', origin: 'https://harness.internal' }), ['harness.internal'])).toBe(true) + // A real hostname or port difference still decides, in both directions. + expect(isTrustedApiRequest(request({ host: 'harness.internal:443', origin: 'https://harness.internal:444' }), ['harness.internal'])).toBe(false) + expect(isTrustedApiRequest(request({ host: 'harness.internal:80', origin: 'https://harness.internal' }), ['harness.internal'])).toBe(false) + expect(isTrustedApiRequest(request({ host: 'harness.internal:443', origin: 'http://harness.internal' }), ['harness.internal'])).toBe(false) + expect(isTrustedApiRequest(request({ host: 'harness.internal:443', origin: 'https://evil.example' }), ['harness.internal'])).toBe(false) + // Cross-site labelling outranks a purely spelling-level match. + expect(isTrustedApiRequest(request({ + host: 'harness.internal:443', + origin: 'https://harness.internal', + 'sec-fetch-site': 'cross-site', + }), ['harness.internal'])).toBe(false) + // Only http(s) names this listener; opaque and other schemes never compare as an authority. + for (const origin of ['ftp://harness.internal', 'file://harness.internal', 'ws://harness.internal', 'null']) { + expect(isTrustedApiRequest(request({ host: 'harness.internal', origin }), ['harness.internal']), origin).toBe(false) + } + }) + it('accepts a declared public authority: exact on host:port entries, any port on port-less entries', () => { const headers = { host: 'harness.internal:3080', origin: 'http://harness.internal:3080' } expect(isTrustedApiRequest(request(headers), ['harness.internal:3080'])).toBe(true) diff --git a/packages/client/connection/tests/binary-rpc.host.spec.ts b/packages/client/connection/tests/binary-rpc.host.spec.ts index 05ec270545..4431199ec6 100644 --- a/packages/client/connection/tests/binary-rpc.host.spec.ts +++ b/packages/client/connection/tests/binary-rpc.host.spec.ts @@ -35,7 +35,7 @@ describe('Connection binary RPC', () => { attachments: [{ path: ['data'], bytes: data }], })) const handler = connection.createSharedFetchHandler('/api') - ctx.webServer.register({ kind: 'prefix', path: '/api', handler: (req, res) => bridge(req, res, handler) }) + ctx.webServer.register({ kind: 'prefix', path: '/api', handler: (req, res) => bridge(req, res, handler, connection.browserPeer) }) let transferred = 0 let encoding: string | undefined const rpc = createWebConnectionRpc((path, init) => new Promise((resolve, reject) => { @@ -111,7 +111,7 @@ describe('Connection binary RPC', () => { const shared = connection.createSharedFetchHandler('/api') const mediaTypes: (string | null)[] = [] const rpc = createWebConnectionRpc(async (url, init) => { - const response = await shared.fetch(new Request(new URL(url, 'http://host'), init)) + const response = await shared.fetch(new Request(new URL(url, 'http://host'), init), connection.browserPeer) mediaTypes.push(response.headers.get('content-type')) return response }) @@ -144,7 +144,7 @@ describe('Connection binary RPC', () => { attachments: [{ path: ['content'], bytes: content }], })) const handler = connection.createSharedFetchHandler('/api') - const rpc = createWebConnectionRpc((url, init) => handler.fetch(new Request(new URL(url, 'http://host'), init))) + const rpc = createWebConnectionRpc((url, init) => handler.fetch(new Request(new URL(url, 'http://host'), init), connection.browserPeer)) expect(await rpc.call('/api', 'fixture/read', {})).toEqual({ ok: true, value: { content: new Uint8Array([0, 128, 255]), metadata: { count: 1 } }, }) @@ -211,7 +211,7 @@ describe('Connection binary RPC', () => { const connection = ctx.get('connection') as HostConnectionService connection.rpc.intercept('/api', () => true, async () => next) const handler = connection.createSharedFetchHandler('/api') - const rpc = createWebConnectionRpc((url, init) => handler.fetch(new Request(new URL(url, 'http://host'), init))) + const rpc = createWebConnectionRpc((url, init) => handler.fetch(new Request(new URL(url, 'http://host'), init), connection.browserPeer)) const expected = { files: [{ name: 'a.png', content: data }, { name: 'b.png', content: new Uint8Array([2, 3]) }, { name: 'empty' }], 'dots./[]': [new Uint8Array(), null, [data]], diff --git a/packages/client/connection/tests/browser-auth.host.spec.ts b/packages/client/connection/tests/browser-auth.host.spec.ts index c271aa313b..f108023c69 100644 --- a/packages/client/connection/tests/browser-auth.host.spec.ts +++ b/packages/client/connection/tests/browser-auth.host.spec.ts @@ -76,11 +76,12 @@ function request(url: string, authority = '127.0.0.1:3080', init?: { function exchange( auth: BrowserAuth, authority = '127.0.0.1:3080', + secure = false, ): { cookie: string; launchUrl: string; state: ResponseState } { const launchUrl = auth.authenticatedUrl(`http://${authority}`) const target = new URL(launchUrl) const res = response() - expect(auth.authorizeIndex(request(`${target.pathname}${target.search}`, authority), res.value)).toBe(false) + expect(auth.authorizeIndex(request(`${target.pathname}${target.search}`, authority), res.value, secure)).toBe(false) const setCookie = res.state.headers?.['set-cookie'] if (setCookie === undefined) throw new Error('token exchange did not set a cookie') return { cookie: setCookie.split(';', 1)[0]!, launchUrl, state: res.state } @@ -140,6 +141,34 @@ describe('BrowserAuth', () => { }) }) + it('keeps HTTPS port 443 distinct from HTTP port 80 with one signing secret', async () => { + const auth = await createAuth(new RecordCredentials()) + const plain = exchange(auth, 'harness.example') + const tls = exchange(auth, 'harness.example', true) + expect(auth.isAuthenticated(request('/', 'harness.example', { cookie: plain.cookie }), true)).toBe(false) + expect(auth.isAuthenticated(request('/', 'harness.example', { cookie: tls.cookie }), true)).toBe(true) + expect(auth.isAuthenticated(request('/', 'harness.example:443', { cookie: tls.cookie }), true)).toBe(true) + expect(auth.isAuthenticated(request('/', 'harness.example', { cookie: tls.cookie }))).toBe(false) + }) + + it('rejects HTTP cookie replay after enabling TLS on the same authority', async () => { + const store = new RecordCredentials() + const authority = 'harness.example:3080' + const plain = exchange(await createAuth(store), authority) + const restarted = await createAuth(store) + const denied = response() + expect(restarted.authorizeIndex(request('/', authority, { cookie: plain.cookie }), denied.value, true)).toBe(false) + expect(denied.state.status).toBe(401) + + const tls = exchange(restarted, authority, true) + expect(tls.state.headers?.['set-cookie']).toContain('; Secure') + expect(restarted.isAuthenticated(request('/', authority, { cookie: tls.cookie }), true)).toBe(true) + expect(restarted.isAuthenticated(request('/', authority, { cookie: tls.cookie }))).toBe(false) + const tlsName = tls.cookie.slice(0, tls.cookie.indexOf('=')) + const plainValue = plain.cookie.slice(plain.cookie.indexOf('=') + 1) + expect(restarted.isAuthenticated(request('/', authority, { cookie: `${tlsName}=${plainValue}` }), true)).toBe(false) + }) + it('preserves the caller authority and mount while adding only this process token', async () => { const auth = await createAuth(new RecordCredentials()) const mounted = new URL(auth.authenticatedUrl('https://gateway.example/tools/dsh/')) diff --git a/packages/client/connection/tests/fetch-routes.host.spec.ts b/packages/client/connection/tests/fetch-routes.host.spec.ts index ddb9b3b264..a6b6d159c6 100644 --- a/packages/client/connection/tests/fetch-routes.host.spec.ts +++ b/packages/client/connection/tests/fetch-routes.host.spec.ts @@ -1,4 +1,5 @@ import { Context } from '@deepseek-ai/cordis' +import type { PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol' import { describe, expect, it, vi } from 'vitest' import type { BrowserAuth } from '../src/browser-auth.ts' import { HostConnectionService } from '../src/rpc-host.ts' @@ -18,6 +19,15 @@ async function mounted(): Promise<{ } } +const GUEST: Principal = { kind: 'test-guest', guest: 'connection' } + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + /** Test-only non-owner caller shared by the access specs. */ + 'test-guest': { readonly kind: 'test-guest'; readonly guest: string } + } +} + describe('Connection exact Fetch routes', () => { it('dispatches owned methods and returns 404 for unclaimed requests', async () => { const { connection, dispose: disposeFiber } = await mounted() @@ -33,7 +43,7 @@ describe('Connection exact Fetch routes', () => { const response = await shared.fetch(new Request( 'http://host/api/session.export?sessionId=session-1', - )) + ), connection.browserPeer) expect(shared.requestBodyMode({ method: 'POST', url: new URL('http://host/api/session.export'), })).toBe('streaming') @@ -43,12 +53,12 @@ describe('Connection exact Fetch routes', () => { expect(response.status).toBe(200) expect(await response.json()).toEqual({ query: 'session-1' }) expect(route).toHaveBeenCalledOnce() - const post = await shared.fetch(new Request('http://host/api/session.export', { method: 'POST' })) + const post = await shared.fetch(new Request('http://host/api/session.export', { method: 'POST' }), connection.browserPeer) expect(post.status).toBe(200) expect(route).toHaveBeenCalledTimes(2) await dispose() - const withdrawn = await shared.fetch(new Request('http://host/api/session.export')) + const withdrawn = await shared.fetch(new Request('http://host/api/session.export'), connection.browserPeer) expect(withdrawn.status).toBe(404) await disposeFiber() }) @@ -80,4 +90,76 @@ describe('Connection exact Fetch routes', () => { })).not.toThrow() await disposeFiber() }) + + it('refuses exact routes to non-owner Peers while the RPC interceptor still receives them', async () => { + const { connection, dispose: disposeFiber } = await mounted() + const route = vi.fn(async () => new Response('route')) + const disposeRoute = connection.fetch.register({ + path: '/api/session.export', methods: ['GET'], requestBody: 'buffered', fetch: route, + }) + const peers: PeerScope[] = [] + const disposeInterceptor = connection.rpc.intercept('/api', () => true, async (_endpoint, _payload, _signal, peer) => { + peers.push(peer) + return { ok: true, value: null } + }) + const guest = connection.createPeer({ principal: GUEST }) + const shared = connection.createSharedFetchHandler('/api') + + const refused = await shared.fetch(new Request('http://host/api/session.export'), guest) + expect(refused.status).toBe(403) + expect(route).not.toHaveBeenCalled() + expect((await shared.fetch(new Request('http://host/api/session.export'), connection.browserPeer)).status).toBe(200) + + const rpc = await shared.fetch(new Request('http://host/api/goals/get', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ type: 'client-request', rpcId: 'rpc-1', method: 'goals/get', payload: { args: {} } }), + }), guest) + expect(rpc.status).toBe(200) + expect(peers).toEqual([guest]) + await disposeInterceptor() + await disposeRoute() + await disposeFiber() + }) +}) + +describe('Connection in-process Peers', () => { + it('creates independent Peers that keep their principal and leave with the reading Context', async () => { + const { connection, dispose } = await mounted() + const first = connection.createPeer({ principal: GUEST }) + const second = connection.createPeer({ principal: GUEST }) + const owner = connection.createPeer({ principal: { kind: 'owner' } }) + expect(new Set([first.id, second.id, owner.id, connection.browserPeer.id]).size).toBe(4) + expect(first.principal).toBe(GUEST) + expect(owner.principal).toEqual({ kind: 'owner' }) + expect(first.ctx).not.toBe(second.ctx) + + const released = vi.fn() + first.ctx.effect(() => released, 'first Peer registration') + await first.dispose() + expect(released).toHaveBeenCalledOnce() + expect(() => first.ctx.effect(() => () => {})).toThrow() + // Disposing one Peer leaves the others usable. + expect(() => second.ctx.effect(() => () => {})()).not.toThrow() + + await dispose() + }) + + it('disposes a created Peer with the plugin that read the Connection', async () => { + const ctx = new Context() + const provider = ctx.plugin((pluginCtx) => { new HostConnectionService(pluginCtx, [], {} as BrowserAuth) }) + await provider.await() + let created: PeerScope | undefined + const consumer = ctx.plugin({ + inject: ['connection'], + apply: (consumerCtx: Context) => { created = consumerCtx.connection.createPeer({ principal: GUEST }) }, + }) + await consumer.await() + const lingering = vi.fn() + created!.ctx.effect(() => lingering, 'consumer Peer registration') + await consumer.dispose() + expect(lingering).toHaveBeenCalledOnce() + expect(() => created!.ctx.effect(() => () => {})).toThrow() + await provider.dispose() + }) }) diff --git a/packages/client/connection/tests/http-bridge.host.spec.ts b/packages/client/connection/tests/http-bridge.host.spec.ts index e9fa9df364..e612a0608d 100644 --- a/packages/client/connection/tests/http-bridge.host.spec.ts +++ b/packages/client/connection/tests/http-bridge.host.spec.ts @@ -1,8 +1,12 @@ import { EventEmitter } from 'node:events' import { Readable } from 'node:stream' import type { IncomingMessage, ServerResponse } from 'node:http' +import { Context } from '@deepseek-ai/cordis' import { describe, expect, it } from 'vitest' import { bridge } from '../src/http-bridge.ts' +import { Peer } from '../src/peer.ts' + +const PEER = new Peer(new Context(), { principal: { kind: 'owner' } }) describe('HTTP bridge abort', () => { it('destroys a declared-oversize request instead of draining it', async () => { @@ -26,7 +30,7 @@ describe('HTTP bridge abort', () => { await bridge(request, response, { requestBodyMode: () => 'buffered', fetch: () => { throw new Error('a rejected request must never reach the handler') }, - }, 1000) + }, PEER, 1000) // The socket must not stay parked draining a body the client can trickle // at will after the rejection — same discipline as the chunked overrun. expect(status).toBe(413) @@ -68,7 +72,7 @@ describe('HTTP bridge abort', () => { } return Response.json({ aborted: fetchRequest.signal.aborted }) }, - }, Number.MAX_SAFE_INTEGER) + }, PEER, Number.MAX_SAFE_INTEGER) await started response.emit('close') await pending @@ -102,7 +106,7 @@ describe('HTTP bridge abort', () => { const pending = bridge(request, response, { requestBodyMode: () => 'buffered', fetch: async () => new Response(body), - }).then(() => { settled = true }) + }, PEER).then(() => { settled = true }) try { await expect.poll(() => settled).toBe(true) expect(writes).toBe(1) @@ -134,7 +138,7 @@ describe('HTTP bridge abort', () => { const pending = bridge(request, response, { requestBodyMode: () => 'buffered', fetch: async () => new Response(body), - }) + }, PEER) await started.promise response.emit('close') controller.enqueue(Uint8Array.of(1)) @@ -172,7 +176,7 @@ describe('HTTP bridge abort', () => { for await (const chunk of input.body) received.push(chunk) return new Response('stored') }, - }, 1) + }, PEER, 1) await started expect(received).toEqual([]) @@ -206,7 +210,7 @@ describe('HTTP bridge abort', () => { await bridge(request, response, { requestBodyMode: () => 'streaming', fetch: () => Promise.resolve(new Response(null, { status: 415 })), - }, 1) + }, PEER, 1) expect(status).toBe(415) expect(headers).toMatchObject({ connection: 'close' }) expect(destroyed).toEqual([true]) diff --git a/packages/client/connection/tests/node-half.host.spec.ts b/packages/client/connection/tests/node-half.host.spec.ts index 5642bff493..ce37c41383 100644 --- a/packages/client/connection/tests/node-half.host.spec.ts +++ b/packages/client/connection/tests/node-half.host.spec.ts @@ -25,8 +25,12 @@ import { provideBrowserCredentials } from './browser-credentials.ts' function fakeHttpServer( routes: WebRoute[], upgrades: WebUpgradeRoute[], -): Pick { + host = '127.0.0.1', + protocol: WebServer['protocol'] = 'http:', +): Pick { return { + host, + protocol, register(route) { if (routes.some(candidate => candidate.kind === route.kind && candidate.path === route.path)) { throw new Error(`duplicate route ${route.path}`) @@ -90,7 +94,7 @@ function fakeResponse(): { return { response, state } } -async function mounted(config?: ConnectionConfig): Promise<{ +async function mounted(config?: ConnectionConfig, protocol: WebServer['protocol'] = 'http:'): Promise<{ ctx: Context routes: WebRoute[] upgrades: WebUpgradeRoute[] @@ -101,7 +105,7 @@ async function mounted(config?: ConnectionConfig): Promise<{ const routes: WebRoute[] = [] const upgrades: WebUpgradeRoute[] = [] provideBrowserCredentials(ctx) - ctx.provide('webServer', fakeHttpServer(routes, upgrades) as WebServer) + ctx.provide('webServer', fakeHttpServer(routes, upgrades, '127.0.0.1', protocol) as WebServer) const fiber = ctx.plugin({ inject: [...inject], apply }, config) await fiber.await() return { @@ -194,6 +198,65 @@ describe('connection node half', () => { await fiber.dispose() }) + it('accepts the bind address of a web carrier attached after Connection', async () => { + const ctx = new Context() + const routes: WebRoute[] = [] + const upgrades: WebUpgradeRoute[] = [] + provideBrowserCredentials(ctx) + const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.example'] }) + try { + await fiber.await() + const connection = ctx.get('connection') as HostConnectionHandle + const web = ctx.plugin((webCtx) => { + webCtx.provide('webServer', fakeHttpServer(routes, upgrades, '10.1.2.3') as WebServer) + }) + try { + await web.await() + await expect.poll(() => routes.find(route => route.path === API_PATH)).toBeDefined() + const bound = browserCookie(connection, '10.1.2.3:3080') + expect(connection.requestRejection(fakeRequest({ host: '10.1.2.3:3080', cookie: bound }))).toBeUndefined() + } finally { + await web.dispose() + } + } finally { + await fiber.dispose() + } + }) + + it('uses the TLS default port for markerless exact-authority grants', async () => { + const { connection, dispose } = await mounted({ trustedHosts: ['tls.example:443', 'plain.example:80'] }, 'https:') + try { + expect(connection.requestRejection(fakeRequest({ host: 'tls.example' }))).toBe(401) + expect(connection.requestRejection(fakeRequest({ host: 'plain.example' }))).toBe(403) + expect(connection.requestRejection(fakeRequest({ host: 'tls.example:444' }))).toBe(403) + } finally { + await dispose() + } + }) + + it('marks the minted browser cookie Secure from the mounted listener protocol', async () => { + for (const [protocol, secure] of [['http:', false], ['https:', true]] as const) { + const { connection, dispose } = await mounted(undefined, protocol) + try { + const url = new URL(connection.authenticatedUrl('http://127.0.0.1:3080')) + const exchanged = fakeResponse() + connection.authorizeIndex( + fakeRequest({ host: '127.0.0.1:3080', 'x-forwarded-proto': secure ? 'http' : 'https' }, `${url.pathname}${url.search}`), + exchanged.response, + ) + const setCookie = exchanged.state.headers?.['set-cookie'] + expect(setCookie?.endsWith('; Secure'), protocol).toBe(secure) + if (setCookie === undefined) throw new Error('browser token exchange did not set a cookie') + expect(connection.requestRejection(fakeRequest({ + host: '127.0.0.1:3080', + cookie: setCookie.split(';', 1)[0]!, + }))).toBeUndefined() + } finally { + await dispose() + } + } + }) + it('injects validated browser recovery timing and withdraws it on disposal', async () => { const { ctx, dispose } = await mounted({ recovery: { generationReadyTimeoutMs: 25_000 } }) try { @@ -223,6 +286,22 @@ describe('connection node half', () => { expect(ctx.get('connection')).toBeUndefined() }) + it('reports allowsRemoteAuthorities from validated trustedHosts only', async () => { + const cases: { trustedHosts: string[]; expected: boolean }[] = [ + { trustedHosts: ['127.0.0.1', 'localhost', '[::1]'], expected: false }, + { trustedHosts: ['harness.example'], expected: true }, + { trustedHosts: ['127.0.0.1', 'harness.example'], expected: true }, + ] + for (const { trustedHosts, expected } of cases) { + const deployment = await mounted({ trustedHosts }) + try { + expect(deployment.connection.allowsRemoteAuthorities, trustedHosts.join(',')).toBe(expected) + } finally { + await deployment.dispose() + } + } + }) + it('reserves enough default carrier capacity for the 200 MiB image batch', () => { expect(DEFAULT_MAX_REQUEST_BODY_BYTES).toBe(300 * 1024 * 1024) expect(DEFAULT_MAX_REQUEST_BODY_BYTES).toBeGreaterThan(Math.ceil(200 * 1024 * 1024 * 4 / 3) + 1024 * 1024) @@ -311,8 +390,6 @@ describe('connection node half', () => { cookie: browserCookie(connection, '127.0.0.1:3080'), }), loopback.response) expect(loopback.state.status).toBe(404) - // An all-interfaces composition derives port-less LAN IP literals, which - // pass markerless curl on any port. const lan = fakeResponse() await routes[0]!.handler(fakeRequest({ host: '192.168.1.5:3080', @@ -478,7 +555,7 @@ describe('connection node half', () => { await fiber.dispose() }) - it('admits every trusted, authenticated request as the operator Peer and hands each call that Peer', async () => { + it('admits every trusted, authenticated request as the owner browser Peer and hands each call that Peer', async () => { const { connection, routes, dispose } = await mounted({ trustedHosts: ['harness.example'] }) const peers: PeerScope[] = [] const remove = connection.rpc.intercept( @@ -492,7 +569,7 @@ describe('connection node half', () => { expect(connection.admit(fakeRequest({ host: 'other.example' }))).toEqual({ rejection: 403 }) expect(connection.admit(fakeRequest({ host: '127.0.0.1:3080' }))).toEqual({ rejection: 401 }) const cookie = browserCookie(connection, '127.0.0.1:3080') - expect(connection.admit(fakeRequest({ host: '127.0.0.1:3080', cookie }))).toEqual({ peer: connection.operator }) + expect(connection.admit(fakeRequest({ host: '127.0.0.1:3080', cookie }))).toEqual({ peer: connection.browserPeer }) const route = routes.find(candidate => candidate.path === API_PATH)! const request: ClientRequest = { @@ -504,17 +581,18 @@ describe('connection node half', () => { const answered = fakeResponse() await route.handler(fakePost({ host: '127.0.0.1:3080', cookie }, '/api/goals/create', request), answered.response) expect(JSON.parse(String(answered.state.body))).toMatchObject({ result: { ok: true, value: null } }) - // A shell-owned carrier dispatches the shared handler without the bridge and speaks for the operator too. + // A shell-owned carrier dispatches the shared handler without the bridge and speaks for the browser Peer too. const direct = await connection.createSharedFetchHandler('/api').fetch(new Request('http://127.0.0.1:3080/api/goals/create', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(request), - })) + }), connection.browserPeer) expect(direct.status).toBe(200) - expect(peers).toEqual([connection.operator, connection.operator]) + expect(peers).toEqual([connection.browserPeer, connection.browserPeer]) + expect(connection.browserPeer.principal).toEqual({ kind: 'owner' }) // Racing disposals share one completion, and the scope goes with the Connection. - await Promise.all([connection.operator.dispose(), connection.operator.dispose()]) + await Promise.all([connection.browserPeer.dispose(), connection.browserPeer.dispose()]) await remove() await dispose() }) diff --git a/packages/client/connection/tsconfig.host.json b/packages/client/connection/tsconfig.host.json index 66d9844f17..0a60bb86ea 100644 --- a/packages/client/connection/tsconfig.host.json +++ b/packages/client/connection/tsconfig.host.json @@ -14,7 +14,7 @@ "src/http-bridge.ts", "src/index.ts", "src/loopback-hostname.ts", - "src/operator-peer.ts", + "src/peer.ts", "src/recovery-config.ts", "src/rpc-host.ts", "src/rpc-schema.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 c7cd4b0902..1e8204cf51 100644 --- a/packages/client/file-upload/package.json +++ b/packages/client/file-upload/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-file-upload", "description": "Agent-scoped browser file upload, streaming intake, and staged receipt service", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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", @@ -66,7 +68,7 @@ "src" ], "dependencies": { - "zod": "^4.4.3", + "zod": "4.4.3", "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*" }, 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 e1b3b47cd6..2c16cb4667 100644 --- a/packages/client/hmr/package.json +++ b/packages/client/hmr/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-hmr", "description": "Web client graph synchronization and rebuilt-bundle reload transport", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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/README.i18n.yaml b/packages/client/locale/README.i18n.yaml index 4b363e6971..2e2736659e 100644 --- a/packages/client/locale/README.i18n.yaml +++ b/packages/client/locale/README.i18n.yaml @@ -9,8 +9,8 @@ en: 9365090d78467dea zh: 74b6fbb9769d795f /deepseek-ai-dsh-client-locale/summary: - en: a548ff3095e8d7d8 - zh: fec6ad47291018f8 + en: d8cc5ae25160ca20 + zh: e8fc2b9fb663cdee /deepseek-ai-dsh-client-locale/table-of-contents: en: d152484eb41ac6b4 zh: bda879a892f240f0 @@ -30,8 +30,8 @@ en: aa4e9c70523339cc zh: 3359eddc4e9ef15e /deepseek-ai-dsh-client-locale/use-this-package/what-the-host-half-does: - en: 8fa91333f7fc3387 - zh: 789a9cbb3eace3b0 + en: 784035ca4b4838b8 + zh: 4a258795f408528f /deepseek-ai-dsh-client-locale/understand-the-implementation: en: 288d8db39f9acfc5 zh: d65cf2ffae8ad35c @@ -39,8 +39,8 @@ en: c2e0ab8bb6bcb26a zh: 508dec4db2c0fde6 /deepseek-ai-dsh-client-locale/understand-the-implementation/preference-resolution: - en: 4bc9dffa4629f537 - zh: f51633c658b8d25b + en: d602d957654641c6 + zh: 2db822b746a6471d /deepseek-ai-dsh-client-locale/understand-the-implementation/dictionary-lookup: en: f8dcc4035830e738 zh: 8452ac63ee148c61 diff --git a/packages/client/locale/README.md b/packages/client/locale/README.md index 930c715a47..8c52703748 100644 --- a/packages/client/locale/README.md +++ b/packages/client/locale/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Use `dsh-client-locale` to switch the web GUI between the shipped English and Chinese locales or languages added by client plugins. User selections take effect immediately; loopback pages persist them in `$DSH_HOME/cordis.patch.yml`, while non-loopback pages keep them only for the current process. New browsers use the first supported language requested by the browser until an allowed stored preference arrives. Plugin authors add typed namespace dictionaries and translate through the public locale API; slot-rendered copy updates without a reload. +Use `dsh-client-locale` to switch the web GUI between the shipped English and Chinese locales or languages added by client plugins. User selections take effect immediately; every authenticated browser persists them as `locale.preference` in `$DSH_HOME/cordis.patch.yml` through the Host settings service. New browsers use the first supported language requested by the browser until the Host read delivers a stored preference. Plugin authors add typed namespace dictionaries and translate through the public locale API; slot-rendered copy updates without a reload. ## Table of Contents @@ -67,7 +67,7 @@ An external id is a non-empty ASCII BCP 47-style tag. Its fallback must already ### What the Host half does -The Host persists the preference through the settings service on loopback pages. The Client deliberately withholds that settings scope on non-loopback pages, so their locale selection remains process-local even though Connection authenticates every API method. +Every authenticated browser persists the preference through the Host settings service under the shared [settings scope policy](../ui-settings/README.md). ----- @@ -85,7 +85,7 @@ One `LocaleRuntime` owns the preference and the dictionary registry, and is itse ### Preference resolution -The provisional locale comes from the browser (`navigator.languages` matched by full tag and then primary subtag, English as the fallback), standing in until the allowed Host-backed settings scope delivers its stored preference. The Host read runs after plugin activation so an unavailable or withheld settings scope cannot block the page, and the result replaces the provisional value live. A stored external locale waits for its definition to register. `setLocale` is the only write entry; it persists even when the id already matches the active locale, because the active value may be provisional and must survive a different browser sharing the same home. +The provisional locale comes from the browser (`navigator.languages` matched by full tag and then primary subtag, English as the fallback), standing in until the Host settings scope delivers its stored preference. The Host read runs after plugin activation so an unavailable settings scope cannot block the page, and the result replaces the provisional value live. A stored external locale waits for its definition to register. `setLocale` is the only write entry; it persists even when the id already matches the active locale, because the active value may be provisional and must survive a different browser sharing the same home. ### Dictionary lookup diff --git a/packages/client/locale/README.zh.md b/packages/client/locale/README.zh.md index 6298fac88f..0527984591 100644 --- a/packages/client/locale/README.zh.md +++ b/packages/client/locale/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -使用 `dsh-client-locale` 可在 web GUI 中切换内置的英文和中文 locale,或 client 插件添加的语言。用户选择会立即生效;loopback 页面把选择持久化到 `$DSH_HOME/cordis.patch.yml`,非 loopback 页面则只为当前进程保留选择。全新浏览器会使用浏览器请求的第一个受支持语言,直到允许读取的已存储偏好到达。插件作者可添加类型化命名空间字典,并通过公开 locale API 翻译;经 slot 渲染的文案无需重新加载即可随语言切换更新。 +使用 `dsh-client-locale` 可在 web GUI 中切换内置的英文和中文 locale,或 client 插件添加的语言。用户选择会立即生效;每个已认证浏览器都通过 Host settings 服务把选择以 `locale.preference` 持久化到 `$DSH_HOME/cordis.patch.yml`。全新浏览器会使用浏览器请求的第一个受支持语言,直到 Host 读取送达已存储偏好。插件作者可添加类型化命名空间字典,并通过公开 locale API 翻译;经 slot 渲染的文案无需重新加载即可随语言切换更新。 ## 目录 @@ -67,7 +67,7 @@ export function apply(ctx) { ### Host 半侧做什么 -Host 通过 settings 服务为 loopback 页面持久化偏好。Client 会刻意拒绝非 loopback 页面使用该 settings scope,因此即使 Connection 认证所有 API 方法,它们的 locale 选择仍只存在于进程内。 +每个已认证浏览器都遵循共享的 [settings scope 策略](../ui-settings/README.zh.md),通过 Host settings 服务持久化偏好。 ----- @@ -85,7 +85,7 @@ Host 通过 settings 服务为 loopback 页面持久化偏好。Client 会刻意 ### 偏好解析 -临时 locale 来自浏览器(`navigator.languages` 先按完整标签、再按主语言子标签匹配,以英文作为回退),在允许使用的 Host-backed settings scope 送达其存储偏好之前生效。Host 读取在插件激活后运行,因此 settings scope 不可用或被拒绝都不会阻塞页面,结果会实时替换临时值。已存储的外部 locale 会等待其定义注册。`setLocale` 是唯一写入入口;即使 id 已与生效中的 locale 匹配也会持久化,因为生效中的值可能是临时的,必须能供共享同一 home 的其他浏览器继续使用。 +临时 locale 来自浏览器(`navigator.languages` 先按完整标签、再按主语言子标签匹配,以英文作为回退),在 Host settings scope 送达其存储偏好之前生效。Host 读取在插件激活后运行,因此 settings scope 不可用不会阻塞页面,结果会实时替换临时值。已存储的外部 locale 会等待其定义注册。`setLocale` 是唯一写入入口;即使 id 已与生效中的 locale 匹配也会持久化,因为生效中的值可能是临时的,必须能在共享同一 home 的其他浏览器上存活。 ### 字典查找 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 fbc182390b..c649898e09 100644 --- a/packages/client/locale/package.json +++ b/packages/client/locale/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-locale", "description": "Locale plugin: Host-backed preference, extensible language catalog, browser fallback, and typed built-in dictionaries", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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/tests/language-row.client.spec.tsx b/packages/client/locale/tests/language-row.client.spec.tsx index 776542c0f2..ecf23dd6e9 100644 --- a/packages/client/locale/tests/language-row.client.spec.tsx +++ b/packages/client/locale/tests/language-row.client.spec.tsx @@ -5,7 +5,7 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' import { LanguageRow } from '../src/client/LanguageRow.tsx' import type { LanguageRowComponentProps } from '../src/client/LanguageRow.tsx' import { createLanguageRowStore } from '../src/client/settings-store.ts' @@ -44,6 +44,7 @@ function mount(active = 'en') { useSessionStatus, usePanelInfo, useSessionRetainInfo: () => undefined, useResource, useWorkspaces: emptyWorkspaces(), + ...allowAllAccess, useStore: bindSnapshotSelector(store), actions: store.actions, t: (key: string) => key === 'language.title' ? 'Language' : key, 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/README.i18n.yaml b/packages/client/modules/README.i18n.yaml index 4ab13cc6e9..ebb8ecbb3a 100644 --- a/packages/client/modules/README.i18n.yaml +++ b/packages/client/modules/README.i18n.yaml @@ -27,8 +27,8 @@ en: 45740a56e931d094 zh: b3362af77c804459 /deepseek-ai-dsh-client-modules/use-this-package/sharing-modules: - en: 0aaf0693db8bb203 - zh: 9f4738cdc6b55c26 + en: 1778b5a63ecde5e8 + zh: 537b4f8c755af8ad /deepseek-ai-dsh-client-modules/use-this-package/build-requirements: en: b6a4d3b901c89efe zh: 615b5f3eec41f281 diff --git a/packages/client/modules/README.md b/packages/client/modules/README.md index 3388eb2ae4..8224ab0ac7 100644 --- a/packages/client/modules/README.md +++ b/packages/client/modules/README.md @@ -43,7 +43,7 @@ An open Web page follows the Host's complete module graph through the HMR transp ### Sharing modules -The shell seeds a frozen module table (`PLATFORM_MODULES`: React, Cordis, and static UI libraries); every dynamic bundle resolves its externals against exactly that baseline. `dsh.client.external` adds only exact non-baseline requests, each answered by the dynamic package row it names or an exact static-table key. Type-only imports are erased and create no request. Composition rejects malformed requests, missing suppliers, self-requests, and synchronous request cycles. +The shell seeds a frozen module table ([`PLATFORM_MODULES`](../web/README.md#the-shared-module-table)); every dynamic bundle resolves its externals against exactly that baseline. `dsh.client.external` adds only exact non-baseline requests, each answered by the dynamic package row it names or an exact static-table key. Type-only imports are erased and create no request. Composition rejects malformed requests, missing suppliers, self-requests, and synchronous request cycles. ### Build requirements diff --git a/packages/client/modules/README.zh.md b/packages/client/modules/README.zh.md index 3cbc600ee5..c972fe38d4 100644 --- a/packages/client/modules/README.zh.md +++ b/packages/client/modules/README.zh.md @@ -43,7 +43,7 @@ application combo 脚本只携带每个插件的 `client.js` 入口,并在启 ### 共享模块 -外壳初始化一张冻结的模块表(`PLATFORM_MODULES`:React、Cordis 与静态 UI 库);每个动态 bundle 都精确针对该基座解析其 external。`dsh.client.external` 只添加基座之外的精确请求;系统会将每个请求解析到其指定的动态包 row 或完全匹配的静态表键。纯类型 import 会被擦除,不产生请求。组合阶段会拒绝畸形请求、缺失提供方、自请求与同步请求环。 +外壳初始化一张冻结的模块表([`PLATFORM_MODULES`](../web/README.zh.md#the-shared-module-table));每个动态 bundle 都精确针对该基座解析其 external。`dsh.client.external` 只添加基座之外的精确请求;系统会将每个请求解析到其指定的动态包 row 或完全匹配的静态表键。纯类型 import 会被擦除,不产生请求。组合阶段会拒绝畸形请求、缺失提供方、自请求与同步请求环。 ### 构建要求 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 f441c356f6..1a5eaf5a1c 100644 --- a/packages/client/modules/package.json +++ b/packages/client/modules/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-modules", "description": "Client module system, dual-face: node half composes the __DSH_BOOT__ entry graph (incremental dsh.client scan, bundle route, index tap, webPlugins service); browser half is the lazy-CJS module table the vendored cordis Loader consumes as its internal seam", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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 b3a957e8a6..4eedc354a5 100644 --- a/packages/client/product-analytics/package.json +++ b/packages/client/product-analytics/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-product-analytics", "description": "Desktop product event collection and authenticated Host reporting", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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", @@ -81,6 +83,6 @@ "dependencies": { "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" } } 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 87554f8d7d..b95500ffed 100644 --- a/packages/client/resources/package.json +++ b/packages/client/resources/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-resources", "description": "Unified client resource model: protocol-registered providers turn URL addresses into live values, consumed through the useResource global standard hook", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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 fbb01628e2..581e8a3d62 100644 --- a/packages/client/shortcuts/package.json +++ b/packages/client/shortcuts/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-shortcuts", "description": "Application keyboard command registry and physical-key routing", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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/package.json b/packages/client/store/package.json index 7ae6fd4a45..2f1d7d1440 100644 --- a/packages/client/store/package.json +++ b/packages/client/store/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-store", "description": "React-free observable and snapshot-store contracts with the shared Zustand/Immer engine", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, 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 795ce96711..c0fc2b7e70 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`, @@ -496,7 +496,7 @@ function clientConfig(id: string, entry: string, clientBanner?: (fileName: strin deps: { neverBundle: isRequested, // Anything NOT requested from the loader module table must inline - // (wire/type layers, zod, clsx — every non-shared dep). A require() the + // (wire/type layers, clsx — every non-shared dep). A require() the // table cannot answer is a guaranteed runtime throw, so the rule is the // package's own request list: requested specifiers stay imports, // everything else is bundled. diff --git a/packages/client/ui-agent-preset/README.i18n.yaml b/packages/client/ui-agent-preset/README.i18n.yaml index 7181942309..6027efa51f 100644 --- a/packages/client/ui-agent-preset/README.i18n.yaml +++ b/packages/client/ui-agent-preset/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: b3ad7867f23dad1c /deepseek-ai-dsh-client-ui-agent-preset/use-this-package: - en: d616984e840f036e - zh: 3e7c97c7d10669eb + en: e015215c32d78b52 + zh: e8a8029903de7515 /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 09df3e46f3..fdade6a4af 100644 --- a/packages/client/ui-agent-preset/README.md +++ b/packages/client/ui-agent-preset/README.md @@ -29,9 +29,9 @@ Settings shows the built-in and custom card groups with default highlighting and With Coding Tools off in General Settings, the new-session picker and Settings roster offer Standard, Creator, and custom presets; turning them on also offers PTC and Minimal. Default selection and the Creator entry remain available in both states. Choosing a healthy default also synchronizes the blank session on the current new-task surface. Creator starts a new task using the `cordis` preset. -Turning Coding Tools off clears all unapplied choices through the existing Developer tools subscription. Once the off value is accepted, a host-backed connection resets a saved built-in PTC or Minimal default to Standard. Saved Standard, Creator, and custom defaults (including named PTC or Minimal overrides) stay unchanged. The user can select an available preset again after turning Coding Tools off. Existing sessions keep their selected mode; New Session uses the current default. An existing mode's label remains visible even when that mode is absent from the menu. Turning Coding Tools back on does not restore the old default or cleared choice. A remote connection using in-memory settings does not rewrite the Host's default. If Standard is missing or broken, the default remains unchanged and an error is shown. +Turning Coding Tools off clears all unapplied choices through the existing Developer tools subscription. Once the off value is accepted, every authenticated browser resets a saved built-in PTC or Minimal default to Standard. Saved Standard, Creator, and custom defaults (including named PTC or Minimal overrides) stay unchanged. The user can select an available preset again after turning Coding Tools off. Existing sessions keep their selected mode; New Session uses the current default. An existing mode's label remains visible even when that mode is absent from the menu. Turning Coding Tools back on does not restore the old default or cleared choice. If Standard is missing or broken, the default remains unchanged and an error is shown. -Known shipped presets offer mode details and usage examples in a read-only dialog. Its tabs preserve each page's scroll position; closing returns focus to the opening action. Help does not change the new-task default. The default badge replaces the card's group badge, and the preset id appears beside the title. Guide copy and examples belong to this package. +Known shipped presets offer mode details and usage examples in a read-only dialog. Minimal's guide explains image reading, automatic history compaction, and the idle-session `/compact` command. Its tabs preserve each page's scroll position; closing returns focus to the opening action. Help does not change the new-task default. The default badge replaces the card's group badge, and the preset id appears beside the title. Guide copy and examples belong to this package. **Let the agent create a plugin** in the Plugins page's **Add plugin** arrow menu enters the same Creator flow as Settings. It submits no message and preserves unsent drafts. While the roster loads or Creator is unavailable, the menu item is disabled with an explanation. Both entries show a Toast with the reason if the Host refuses the preset switch. @@ -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 7514fc9953..eacce41712 100644 --- a/packages/client/ui-agent-preset/README.zh.md +++ b/packages/client/ui-agent-preset/README.zh.md @@ -29,9 +29,9 @@ kind: "package-reference" 关闭通用设置中的代码工作工具后,新会话选择器和设置页列表提供标准、创造和自定义预设;开启后还提供 PTC 和极简模式。两种状态下均保留默认值选择和创造入口。选择健康定义作为默认值也会同步当前新任务页面的空白会话。Creator 入口开启一个使用 `cordis` preset 的新任务。 -关闭代码工作工具时,沿用现有 Developer tools 订阅清空所有尚未应用的选择。关闭状态被接受后,使用 Host 持久化设置的连接会将已保存的内置 PTC 或极简默认值回退为标准模式。已保存的标准、创造和自定义默认值(包括有名称的 PTC 或极简覆盖项)保持不变。关闭后用户仍可重新选择可用预设。已有会话保留所选模式;新会话使用当前默认值。即使已有会话的模式不在菜单中,其标签仍会显示。重新开启代码工作工具不会恢复原默认值或已清除的选择。使用内存设置的远程连接不会改写 Host 的默认值。标准模式缺失或损坏时,默认值保持不变,并显示错误。 +关闭代码工作工具时,沿用现有 Developer tools 订阅清空所有尚未应用的选择。关闭状态被接受后,每个已认证浏览器都会将已保存的内置 PTC 或极简默认值回退为标准模式。已保存的标准、创造和自定义默认值(包括有名称的 PTC 或极简覆盖项)保持不变。关闭后用户仍可重新选择可用预设。已有会话保留所选模式;新会话使用当前默认值。即使已有会话的模式不在菜单中,其标签仍会显示。重新开启代码工作工具不会恢复原默认值或已清除的选择。标准模式缺失或损坏时,默认值保持不变,并显示错误。 -已知的内置预设提供只读的模式说明与使用示例对话框。各页签保留各自的滚动位置;关闭后焦点回到打开它的操作。帮助不会改变新任务默认值。默认徽标取代卡片的分组徽标,预设 id 显示在标题旁。指南文案与示例归本包所有。 +已知的内置预设提供只读的模式说明与使用示例对话框。极简模式指南介绍图片读取、自动历史压缩以及会话空闲时的 `/compact` 命令。各页签保留各自的滚动位置;关闭后焦点回到打开它的操作。帮助不会改变新任务默认值。默认徽标取代卡片的分组徽标,预设 id 显示在标题旁。指南文案与示例归本包所有。 插件页**添加插件**箭头菜单中的**让 Agent 创建插件**进入与设置页相同的创造流程,不发送消息,并保留未发送的草稿。读取预设列表或创造模式不可用时,菜单项禁用并说明原因。Host 拒绝切换预设时,两处入口均通过 Toast 显示原因。 @@ -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 b37e353385..efae94da58 100644 --- a/packages/client/ui-agent-preset/package.json +++ b/packages/client/ui-agent-preset/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-agent-preset", "description": "Agent-preset surfaces: the default for later sessions, this session's seat, and the composition editor", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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/guide-locales.ts b/packages/client/ui-agent-preset/src/client/guide-locales.ts index c41b55aef7..2d8320f298 100644 --- a/packages/client/ui-agent-preset/src/client/guide-locales.ts +++ b/packages/client/ui-agent-preset/src/client/guide-locales.ts @@ -42,7 +42,7 @@ export const guideEn = { guideMinimalIntro: 'Choose Minimal mode for a new task. For a comparison, hold the model, permissions, input, and starting workspace state constant across runs.', guideMinimalExplanation: [ '### What is included', - 'One persistent shell tool and a fixed system prompt. The built-in preset does not load Skills, planning, context compaction, or the standard runtime context.', + 'One persistent shell tool, read_image, and a fixed system prompt. Image reading requires an image-capable model. Older history is compacted automatically under context pressure; use /compact while the agent is idle to compact it manually. The built-in preset does not load Skills, planning, or the standard runtime context.', '### When to choose it', 'Use it as a baseline for experiments and comparisons. It can still read files and execute scripts through shell commands, but offers fewer built-in ways to manage a long task. Fewer tools does not necessarily make it easier for a beginner.', ].join('\n\n'), @@ -120,7 +120,7 @@ export const guideZh: Record = { guideMinimalIntro: '新建任务时选择「极简模式」。做对照测试时,保持模型、权限、任务输入和工作区起始状态一致。', guideMinimalExplanation: [ '### 保留哪些能力', - '仅提供一个持久 Shell 工具,并使用固定系统提示词。内置预设不加载 Skills、计划、上下文压缩,也不注入标准运行时上下文。', + '提供持久 Shell 和 read_image 工具,并使用固定系统提示词。读取图片需要支持图片输入的模型。上下文压力达到阈值时自动压缩较早历史;Agent 空闲时可输入 /compact 手动压缩。内置预设不加载 Skills、计划,也不注入标准运行时上下文。', '### 什么时候选', '适合作为实验和对照测试的基线。Agent 仍能通过终端命令读写文件、运行脚本,但缺少管理长任务的内置辅助能力。工具少,不代表对新手更容易。', ].join('\n\n'), diff --git a/packages/client/ui-agent-preset/src/client/index.ts b/packages/client/ui-agent-preset/src/client/index.ts index 184b7fd791..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" @@ -74,8 +74,7 @@ export function apply(ctx: ClientContext): void { const presetSettings = ctx.configForms.get(AGENT_PRESET_SETTINGS_NS) let active = true // Host preferences start at false before their first accepted document. - const codingToolsDisabled = (): boolean => active && toolsSettings.getSnapshot().mode === 'host' - && toolsSettings.getSnapshot().value?.enabled === false + const codingToolsDisabled = (): boolean => active && toolsSettings.getSnapshot().value?.enabled === false const controller = new AgentPresetSettingsController(ctx) const staged: AgentPresetStage = { id: undefined, introduce: false } const seats = new WeakMapWithValues() @@ -199,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/locales.ts b/packages/client/ui-agent-preset/src/client/locales.ts index 1863c2e108..49178ca524 100644 --- a/packages/client/ui-agent-preset/src/client/locales.ts +++ b/packages/client/ui-agent-preset/src/client/locales.ts @@ -55,7 +55,7 @@ export const en: Record = { 'Includes all Standard mode capabilities. Better suited to tasks that call tools in batches and then filter, organize, deduplicate, count, or summarize the results.', presetMinimalName: 'Minimal mode', presetMinimalDescription: - 'The agent works using only a terminal tool. Useful for testing and comparing its basic performance.', + 'The agent uses a terminal and image reading, with context compaction. Useful for testing and comparing its basic performance.', presetCordisName: 'Creator mode', presetCordisDescription: 'Customize DSH through conversation. Let the agent write plugins that add features or UI, or combine tools and prompts to create your own mode.', @@ -97,7 +97,7 @@ export const zh: Record = { presetPtcName: 'PTC 模式', presetPtcDescription: '包含标准模式的所有能力,更适合批量调用工具,并对结果进行筛选、整理、去重、统计或汇总的任务。', presetMinimalName: '极简模式', - presetMinimalDescription: 'Agent 仅使用终端工具完成任务,适合测试和对比其基础表现。', + presetMinimalDescription: 'Agent 使用终端和图片读取工具,并支持上下文压缩,适合测试和对比其基础表现。', presetCordisName: '创造模式', presetCordisDescription: '用对话定制 DSH:让 Agent 编写插件,添加新功能或界面;也能组合工具和提示词,创建自己的模式。', 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/src/client/section-store.ts b/packages/client/ui-agent-preset/src/client/section-store.ts index 3ab2bdd2aa..317543daf8 100644 --- a/packages/client/ui-agent-preset/src/client/section-store.ts +++ b/packages/client/ui-agent-preset/src/client/section-store.ts @@ -86,7 +86,7 @@ export class AgentPresetSectionController { while (this.pendingSave !== undefined) await this.pendingSave if (!shouldReset()) return const settings = this.ctx.configForms.get(AGENT_PRESET_SETTINGS_NS).getSnapshot() - if (settings.mode !== 'host' || settings.status !== 'ready' || !settings.writable || settings.revision === undefined) return + if (settings.status !== 'ready' || !settings.writable || settings.revision === undefined) return await this.load() if (!shouldReset() || this.store.getSnapshot().status !== 'ready') return const rows = this.store.getSnapshot().rows 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 f23bde9a6e..c891d1d6d4 100644 --- a/packages/client/ui-agent-preset/tests/apply.client.spec.ts +++ b/packages/client/ui-agent-preset/tests/apply.client.spec.ts @@ -72,7 +72,6 @@ async function bench(options: { describeGate?: Promise presets?: AgentPresetRow[] developerToolsEnabled?: boolean - memory?: boolean } = {}) { const ctx = new Context() // The host's answer, mutable so a spec can move the default the way the @@ -138,7 +137,6 @@ async function bench(options: { } const remote = new TestRemote(ctx, { settings }) - if (options.memory === true) remote.$host = { home: undefined, isLoopback: false } // The roster and the switch are the AgentPresets Remote namespace; the // shared double carries no generated namespaces, so this spec stages its // own. Registered twice on purpose: the nested key satisfies the plugin's @@ -174,9 +172,9 @@ async function bench(options: { await ctx.plugin({ inject: [...settingsInject], apply: settingsApply }).await() if (options.describeGate === undefined) { await vi.waitFor(() => { - expect(ctx.configForms.developerTools.enabled.getSnapshot()).toBe(options.memory === true ? true : developerToolsEnabled) + expect(ctx.configForms.developerTools.enabled.getSnapshot()).toBe(developerToolsEnabled) }) - if (options.memory !== true) await vi.waitFor(() => { expect(ctx.configForms.get('ui-settings').getSnapshot().status).toBe('ready') }) + await vi.waitFor(() => { expect(ctx.configForms.get('ui-settings').getSnapshot().status).toBe('ready') }) } /** Publish a new Developer tools choice the way the settings mirror does. */ const setDeveloperTools = async (enabled: boolean): Promise => { @@ -214,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 }) }, @@ -933,7 +931,6 @@ describe('ui-agent-preset apply', () => { await b.ctx.plugin({ inject: [...inject], apply }).await() expect(b.calls.filter(call => call.startsWith('settings:'))).toEqual([]) await b.setDeveloperTools(false) - expect(b.ctx.configForms.get('agent-preset-registry').getSnapshot()).toMatchObject({ status: 'ready', mode: 'host', writable: true, revision: 0 }) await vi.waitFor(() => { expect(b.calls.filter(call => call.startsWith('settings:'))).toEqual(['settings:{"selectedDefault":"standard"}']) }) await b.ctx.fiber.dispose() }) @@ -1030,36 +1027,6 @@ describe('ui-agent-preset apply', () => { await b.ctx.fiber.dispose() }) - it.each(['ptc', 'minimal'])('clears a browser-local staged %s choice without rewriting the Host default', async (preset) => { - const b = await bench({ memory: true, presets: [ - ...ROSTER_MOVED.value.presets, { id: 'ptc', isDefault: false }, - ] }) - declareRoot(b.slots) - declareConversation(b.slots) - b.ctx.provide('conversation', {} as never) - const state: { current?: string; byId: Record } = { - byId: { s1: { id: 's1', blank: true } }, - } - const sessions = sessionsDouble(b.ctx, state) - b.ctx.provide('sessions', sessions as never) - b.ctx.provide('uiWorkspace', uiWorkspaceDouble() as never) - await b.ctx.plugin({ inject: [...inject], apply }).await() - const injectSeat = b.slots.entries('conversation.hero.agentPreset')[0]! - .inject as (sessionId?: SessionId) => AgentPresetSeatInjected & Record - const chip = injectSeat() - await chip.load() - await chip.select(preset) - await b.ctx.configForms.developerTools.setEnabled(false) - const section = (b.slots.entries('settings.section')[0]!.inject as () => AgentPresetSectionInjected & Record)() - await section.load() - expect(section.hooks.agentPresetSection.getSnapshot().rows.find(row => row.isDefault)?.id).toBe('minimal') - expect(b.calls.filter(call => call.startsWith('settings:'))).toEqual([]) - state.current = 's1' - await injectSeat(SessionId('s1')).load() - sessions.notify() - expect(b.calls.filter(call => call.startsWith('select:'))).toEqual([]) - await b.ctx.fiber.dispose() - }) it('loads the header label from the shared roster store', async () => { const { ctx, slots } = await bench() @@ -1099,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. @@ -1112,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) @@ -1133,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/tests/create-plugin-menu-item.client.spec.tsx b/packages/client/ui-agent-preset/tests/create-plugin-menu-item.client.spec.tsx index d1ecedaa66..578234c898 100644 --- a/packages/client/ui-agent-preset/tests/create-plugin-menu-item.client.spec.tsx +++ b/packages/client/ui-agent-preset/tests/create-plugin-menu-item.client.spec.tsx @@ -2,7 +2,7 @@ import { useState, type ComponentProps } from 'react' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' -import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { Menu, MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' import { CreatePluginMenuItem } from '../src/client/CreatePluginMenuItem.tsx' @@ -29,6 +29,7 @@ function view(roster: Partial = {}, inMenu = false) { useAgentPresets: bindSnapshotSelector(agentPresets), usePanelInfo: unusedHook, useSessions: unusedHook, useSessionStatus: unusedHook, useSessionRetainInfo: unusedHook, useWorkspaces: unusedHook, useResource: unusedHook, + ...allowAllAccess, load, startCreatorDraft, onDismiss, } function TestMenu() { diff --git a/packages/client/ui-agent-preset/tests/section-store.client.spec.ts b/packages/client/ui-agent-preset/tests/section-store.client.spec.ts index ba2d1841b9..f1a88d720a 100644 --- a/packages/client/ui-agent-preset/tests/section-store.client.spec.ts +++ b/packages/client/ui-agent-preset/tests/section-store.client.spec.ts @@ -7,7 +7,7 @@ import { en } from '../src/client/locales.ts' function fixture() { const form = createSnapshotStore>({ - status: 'ready', mode: 'host', writable: true, revision: 7, value: { selectedDefault: 'minimal' }, base: {}, user: {}, + status: 'ready', writable: true, revision: 7, value: { selectedDefault: 'minimal' }, base: {}, user: {}, }) const remote = { agentPresets: { list: vi.fn(async (): Promise<{ ok: true; value: { presets: AgentPresetRow[] } }> => ({ @@ -149,7 +149,7 @@ describe('Coding Tools default reconciliation', () => { it.each([ { status: 'loading' as const }, { status: 'unavailable' as const }, - { mode: 'memory' as const }, { writable: false }, { revision: undefined }, + { writable: false }, { revision: undefined }, ])('does not write without a writable accepted Host form: %j', async (patch) => { const f = setup() f.form.set({ ...f.form.getSnapshot(), ...patch }) diff --git a/packages/client/ui-agent-preset/tests/section.client.spec.tsx b/packages/client/ui-agent-preset/tests/section.client.spec.tsx index 6505bceb7f..78a4f599e3 100644 --- a/packages/client/ui-agent-preset/tests/section.client.spec.tsx +++ b/packages/client/ui-agent-preset/tests/section.client.spec.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' -import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { Modal } from '@deepseek-ai/dsh-client-ui-primitives' import { AgentPresetSection, type AgentPresetSectionProps } from '../src/client/AgentPresetSection.tsx' @@ -23,6 +23,7 @@ function view(partial: Partial = {}, startCreatorDraft? ...(startCreatorDraft === undefined ? {} : { startCreatorDraft }), usePanelInfo: unusedHook, useSessions: unusedHook, useSessionStatus: unusedHook, useSessionRetainInfo: unusedHook, useWorkspaces: unusedHook, useResource: unusedHook, + ...allowAllAccess, useAgentPresetSection: bindSnapshotSelector(store), useDeveloperTools: bindSnapshotSelector(developerTools), t: key => translations.get(key) ?? key } 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 81569ff26c..b77d601fad 100644 --- a/packages/client/ui-approval/package.json +++ b/packages/client/ui-approval/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-approval", "description": "Approval composer takeover over the scoped Remote Event waterfall", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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 55801fc185..7b212b6cf7 100644 --- a/packages/client/ui-attachment/package.json +++ b/packages/client/ui-attachment/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-attachment", "description": "Dynamic attachment presentation plugin for conversation input, message-image, and trajectory image slots", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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 8647939e25..d4f47f9057 100644 --- a/packages/client/ui-brand-official/package.json +++ b/packages/client/ui-brand-official/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-brand-official", "description": "Official DeepSeek Harness brand occupants for the Web client's sidebar slots", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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 91c230be23..3f4ae6e1ae 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: 0a1948349b1fbfd9 - zh: 56256e4d695e5192 + 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: 14343dd14e493f4b - zh: 7cc7a25d05ea798f + 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: 0ca3e8c4eab1ca78 - zh: 1a1c71bab151eb7d + en: 4cd7c81d70d2f365 + zh: 18eca6d16e44b6c2 /deepseek-ai-dsh-client-ui-chat/grouped-rendering: - en: c769b9eaddf02549 - zh: e36efc654be557e2 + en: 81d7ca7595c34d39 + zh: 29eb8248c75e9ea6 /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: 69b021c5a5d8b5a7 - zh: 091ae7986c7a8a20 + en: 284737900cb75668 + zh: 12e0844082ff79ce /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 02bcbe3ddb..0438804975 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -33,11 +33,19 @@ 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. -Settings → General → Open chat links in selects the destination for ordinary clicks on Chat HTTP(S) links: In-App Sidebar (default) opens a new right-Sidebar Browser tab, while Default Browser opens an external tab. The setting follows Keyboard shortcuts and is shown only while the Sidebar Browser is available. If the Sidebar Browser is not registered, both choices use the external browser; modified clicks retain native behavior. The `ui-chat.linkOpening` preference persists on loopback browsers and stays process-local when settings cannot persist writes. Sent file references and skills confirmed by the message’s logged invocation also open in the right Sidebar. File paths use the viewed Session; skill names resolve through its current input-trigger source. Both use the prose file-link dotted underline on hover or focus. Sessions, directories, and command labels remain non-navigating references. +Settings → General → Open chat links in selects the destination for ordinary clicks on Chat HTTP(S) links: In-App Sidebar (default) opens a new right-Sidebar Browser tab, while Default Browser opens an external tab. The setting follows Keyboard shortcuts and is shown only while the Sidebar Browser is available. If the Sidebar Browser is not registered, both choices use the external browser; modified clicks retain native behavior. The `ui-chat.linkOpening` preference persists on the Host for authenticated browsers and stays process-local when settings cannot persist writes. Sent file references and skills confirmed by the message’s logged invocation also open in the right Sidebar. File paths use the viewed Session; skill names resolve through its current input-trigger source. Both use the prose file-link dotted underline on hover or focus. Sessions, directories, and command labels remain non-navigating references. ## Hidden Chat rows @@ -60,9 +68,9 @@ 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. -On non-loopback browsers, the preference remains process-local because the settings scope cannot persist writes. Explicit selections update every consumer immediately; accepted Host settings reconcile the live value on loopback browsers. +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. Preference menus restore focus to their trigger without scrolling before publishing a new selection. @@ -84,6 +92,8 @@ 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), saved through the same Host profile configuration. + ----- @@ -93,9 +103,11 @@ 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 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. The positions, from outermost inward `exchange`, `input`, `turn`, and `process`, are defined in [group-tree.ts](src/client/contract/group-tree.ts); process grouping, whole-Turn folding, and Turn-input detection read them, so an external Definition places its Chat rows by declaring one. 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. -The process group uses a stable `div` layout box, a scroll body, and an uncapped content box that reports growth inside the body. Business styles must adapt spacing within and across groups, including hidden or empty members and the answer-spacing exception. CSS variables do not belong in the Group Definition. +The process group uses a stable `div` layout box, a scroll body, and an uncapped content box that reports growth inside the body. Business styles must adapt spacing within and across groups, including hidden or empty members and the answer-spacing exception. The `conversation.chat.flow` slot adds a `display: contents` DOM anchor; row selectors match that anchor directly, without repeating its column ancestry. The running status shares the rows' parent, so its divider uses the same visible-sibling rules. The anchor contributes no spacing of its own. CSS variables do not belong in the Group Definition. Running group titles, reasoning previews, tool and command rows, the active retry line, and the bottom running status use the shared [TextShimmer](../ui-primitives/README.md#component-catalog). Each row’s text shares one left-to-right highlight, including collapsed group titles; icons and hover chevrons retain their base appearance. Tool and process rows sit 6px apart. An expanded group title has 8px before its content, Assistant responses have 12px from adjacent process rows, and completed-Turn duration/status controls have 16px around them. Hidden and empty rows, including retained empty slot anchors, add no gap. The running “Deep diving” text retains its blue base while its theme-specific highlight sweeps across it. @@ -105,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 `conversation.chat.reasoning-body` chain offers the original reasoning text and streaming state only when its body is expanded. An unclaimed body keeps compact Markdown; a claiming display extension must preserve access to the original text. 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. @@ -116,13 +128,21 @@ Process rows share one text and icon color in every Work details mode: tertiary ## Scroll ownership -Chat restores semantic anchors across history prepend and renderer remounts, with browser scroll anchoring disabled on its scrollport only while following the tail. Pinned scroll deliveries without reader movement, and reader input that reaches the exact floor, update follow ownership immediately, before subsequent layout changes can invalidate their floor. Other reader movement remains pending until the sampling interval or `scrollend`, even inside the follow threshold, so layout growth cannot erase small scroll gestures. Submitting transcript input or steering immediately restores tail following and clears an older pending reader sample. While the reader is pinned to the floor, `ResizeObserver` follows the new floor and selects the latest loaded Turn without reading row geometry. Once the reader moves away, flow-height changes preserve the top position and the reading-line geometry selects the active Turn. Turn-rail previews paint above sticky Markdown code-block banners, while the rail frame remains inside the transcript band above the composer. +Chat waits for initial history before automatic content, scroll, or size updates initialize reading state. Running Sessions restore their initial visibility and position before fold animations become eligible. + +Chat restores semantic anchors across history prepend and renderer remounts, with browser scroll anchoring disabled on its scrollport only while following the tail. Pinned scroll deliveries without reader movement, and reader input that reaches the floor within subpixel rounding, update follow ownership immediately, before subsequent layout changes can invalidate their floor. Other reader movement remains pending until the sampling interval or `scrollend`, even inside the follow threshold, so layout growth cannot erase small scroll gestures. Under completion-time folding, submitting transcript input or steering immediately restores tail following and clears an older pending reader sample. While the reader is pinned to the floor, `ResizeObserver` follows the new floor and selects the latest loaded Turn without reading row geometry. Once the reader moves away, flow-height changes preserve the top position and the reading-line geometry selects the active Turn. Turn-rail previews paint above sticky Markdown code-block banners, while the rail frame remains inside the transcript band above the composer. The turn rail and back-to-bottom button sit outside the clipped transcript. They use the shared conversation scrollport for sticky positioning, or the Chat frame for absolute positioning when Chat owns its scrollport. The rail hides when the transcript's available width, excluding its horizontal padding, is at most 900px; the browser viewport width is not the criterion. The transcript root uses `overflow-x: visible; overflow-y: clip`: vertical overflow is clipped without creating a scroll container. Sticky Markdown code banners and expanded compaction headers therefore retain the actual conversation scrollport as their reference when no nearer scrolling ancestor exists. Capped process groups and terminal sections keep their own scrollports. -Outer transcript following and each open capped group's following are independent. Native animation progress retains follow intent; a reader gesture interrupts the animation, and actual movement determines whether following remains enabled. Scroll chaining can move the outer transcript, which then applies its own distance threshold. The back-to-bottom button restores only outer following. +Outer transcript following and each open capped group's following are independent. Native animation progress retains follow intent; only that scrollport's own `scrollend` settles its animation. Browsers without `scrollend` may retain the native follow target until a later bottom-aligned update or reader gesture. A reader gesture interrupts the animation, and actual movement determines whether following remains enabled. Scroll chaining can move the outer transcript, which then applies its own distance threshold. The back-to-bottom button restores only outer following. + +Next-message folding moves every batch of closing rows and the scrollport on one frame clock, with browser scroll anchoring disabled during the fold; there is no separate reserve-then-follow path. A row that starts closing or revealing while a batch runs keeps its size until that batch settles and then changes in the next batch; a batch continues each row from the size it already has. The batch lands at the tail when this client's own input caused it (including a subagent child's continuation) or when the reader was following; otherwise the reader's visible content stays still, whoever sent the message. Content above the reading line never slides back down: when the retained answer and the new content cannot fill the viewport, only that deficit remains as bottom space, and new content fills it before following advances again. Reader gestures cancel the automatic target and active native following; resize cannot revive it in the same fold, but new submitted input can. Acknowledged scrolling releases only space that can be removed without clamping the reader. Unloading Chat cancels waiting callbacks and row transitions. Reduced-motion users receive immediate visibility and positioning changes. + +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: fold batches, bottom space, 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 | |---|---|---|---| @@ -146,7 +166,7 @@ Within a process group, wheel, touchstart, and any pointerdown interrupt an acti `useChatReading` owns follow policy, sampled reader input, and semantic memory; `useChatNavigation` owns turn jumps and requests preservation from the viewport. Reading gestures release the paging anchor, but composer clicks, typing, and non-scrolling keys retain it; while a page is still loading, `scrollend` captures the reader's new position. `useChatScroll` coordinates their committed inputs. Explicit navigation carries its measured landing into reading policy, so it does not rediscover the known target with a hit test. -Active-Turn highlighting is approximate: `readVisibleTurn` binary-searches the content column's direct Node/Group boxes and retains the preceding candidate in gaps. It neither hit-tests the document nor searches Group members or all Turn markers. Empty Seats retain zero-height in-flow boxes so outer positions remain ordered without extra spacing. This lookup does not change semantic position capture or paging compensation. +Active-Turn highlighting is approximate: `readVisibleTurn` binary-searches the flow slot's direct Node/Group boxes (or the column's in standalone rendering) and retains the preceding candidate in gaps. It neither hit-tests the document nor searches Group members or all Turn markers. Empty Seats retain zero-height in-flow boxes so outer positions remain ordered without extra spacing. This lookup does not change semantic position capture or paging compensation.
diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 560e37e1fa..27d61eaa9a 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -33,11 +33,19 @@ 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 关闭缩略图。图片加载失败时保留本地化状态与图片说明;不执行重复图片过滤。 -设置 → 通用设置 → 网页链接默认打开方式控制普通点击 Chat HTTP(S) 链接时的目标:「应用内侧边栏」(默认)打开新的右侧 Sidebar Browser tab,「默认浏览器」打开外部标签页。该设置项位于快捷键之后,仅在 Sidebar Browser 可用时显示。若 Sidebar Browser 未注册,两种选择均使用外部浏览器;带修饰键的点击保留原生行为。`ui-chat.linkOpening` 偏好在回环地址浏览器中持久化,设置无法持久化写入时仅在当前进程内生效。已发送的文件引用及消息日志确认调用的 skill 也可在右侧栏打开预览。文件路径使用当前查看的 Session;skill 名称由该 Session 当前的输入触发源解析。两者悬停或聚焦时均使用正文文件链接的虚线下划线。会话、目录和命令标签仍只作为引用展示。 +设置 → 通用设置 → 网页链接默认打开方式控制普通点击 Chat HTTP(S) 链接时的目标:「应用内侧边栏」(默认)打开新的右侧 Sidebar Browser tab,「默认浏览器」打开外部标签页。该设置项位于快捷键之后,仅在 Sidebar Browser 可用时显示。若 Sidebar Browser 未注册,两种选择均使用外部浏览器;带修饰键的点击保留原生行为。已认证浏览器的 `ui-chat.linkOpening` 偏好在 Host 上持久化,设置无法持久化写入时仅在当前进程内生效。已发送的文件引用及消息日志确认调用的 skill 也可在右侧栏打开预览。文件路径使用当前查看的 Session;skill 名称由该 Session 当前的输入触发源解析。两者悬停或聚焦时均使用正文文件链接的虚线下划线。会话、目录和命令标签仍只作为引用展示。 ## Chat 隐藏的行 @@ -60,9 +68,9 @@ 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 接受的设置会校正实时值,因此写入被拒绝或尚未应答时保持所选模式,直到 Host 应答。 偏好菜单在发布新选择之前,先将焦点还给触发按钮,且不引起滚动。 @@ -84,6 +92,8 @@ Chat 末尾为进行中的 Turn 控制行,且该轮尚无可见输入时,第 工作步骤展示模式控制过程组显示与推理预览。简洁、标准、详细模式收起符合条件的已完成轮次,不隐藏最终答案;完全展开模式保留时长或状态抬头,但不支持收起,历史过程行直接显示。[业务规则明细](src/client/conversation-nodes/README.zh.md#display-modes) 统一说明模式表、组头行为、整轮折叠资格、时钟与开合重置。 +工作步骤展示下方的设置行提供[独立的收起时机设置](src/client/conversation-nodes/README.zh.md#collapse-timing),通过相同的 Host profile 配置保存。 + ----- @@ -93,9 +103,11 @@ Chat 通过 `uiConversation.groups` 注册过程 Group Definition。React 通过 `groupPart` 在 Assistant 渲染器中选择推理或回复,不复制 Node 载荷。同一个 callId 的准备、派发与结果阶段由 Tool 节点自己拥有。每个部分有独立的 DOM 锚点用于恢复阅读位置;轮次导航使用原 Node key,落到它的第一个可见部分。展示模式切换以及为完整旧组补入更早成员时,保留组来源、成员父级及 key。原 Node Store 仍是唯一节点数据所有者,替换 Builder 时重新绑定按键订阅,不重挂载容器。模式变化保留尺寸观察器,并复用整轮状态选择器。 +Chat Builder 按节点发布 `bottomSource`:节点可见且属于已加载的最新交互段时为 true,而不只是列表最后一行。节点通过 `groupTree` 声明自己在分组树中的位置;含 `exchange` 节点的轮次开启一个交互段,交互段持续到下一个开启轮次。这些位置由外到内依次为 `exchange`、`input`、`turn`、`process`,定义在 [group-tree.ts](src/client/contract/group-tree.ts);过程分组、整轮折叠和轮次输入判断都读取它们,外部 Definition 声明位置即可放置自己的 Chat 行。交互段起点移动时,只有进入或离开该交互段的轮次中的节点收到通知。Group 读取其首个成员的位置。待发送消息去重与收起判断仍由 Chat 视图处理,不进入 Builder。 + 实时工具 delta 与推理共用按帧合并的发布节奏;持久调用和结果立即发布。原生与嵌套结果保留事件中的展示元数据,使历史文件与命令标签使用执行时的位置。当已读取参数的答案、锚点、位置及可见性均未变化时,重复 delta 保持 Tool 节点不变。Definition 向工具行和分组详情提供同一个懒计算参数读器,无需按工具注册。 -过程组使用稳定的 `div` 布局盒子、滚动正文及不限高的内容盒子,后者报告正文内部的内容增长。业务样式必须适配组内及组边界间距,处理隐藏或空成员以及回答前的间距特例。CSS 变量不属于 Group Definition。 +过程组使用稳定的 `div` 布局盒子、滚动正文及不限高的内容盒子,后者报告正文内部的内容增长。业务样式必须适配组内及组边界间距,处理隐藏或空成员以及回答前的间距特例。`conversation.chat.flow` 插槽添加一个 `display: contents` DOM 锚点;行选择器直接匹配该锚点,不重复匹配其正文容器祖先。运行状态与各行共享父级,使分隔线使用同一套可见兄弟节点规则。锚点自身不产生间距。CSS 变量不属于 Group Definition。 运行中的分组标题、思考预览、工具与命令行、当前重试行以及底部运行状态使用共享的 [TextShimmer](../ui-primitives/README.zh.md#component-catalog)。每行的文字共用一道从左到右的高光,包括折叠的分组标题;图标和悬停箭头保留底色。工具和过程行之间相隔 6px;展开的分组标题与内容之间相隔 8px;Assistant 回复与相邻过程行之间相隔 12px;每轮完成/耗时控件周围保留 16px。隐藏行与空行(包括保留的空 slot 锚点)不产生间距。“深度求索”运行文字保留蓝色底色,并使用主题专用高光扫过文字。 @@ -105,7 +117,7 @@ Chat 通过 `uiConversation.groups` 注册过程 Group Definition。React 通过 每个组拥有本地 `useDisclosure` 状态,组件保持挂载时,模式切换保留该状态。 -`conversation.chat.reasoning-body` 链仅在思考正文展开时提供原始思考文本和流式状态。未被认领的正文使用紧凑 Markdown;认领显示的扩展必须保留查看原文的能力。扩展不替换思考预览或展开策略。 +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,也不改变钩子引用。展示模式切换保留展开状态。 @@ -116,13 +128,21 @@ Chat 节点 slot 为推理与工具注入绑定重置来源的 `useDisclosure` ## 滚动归属 -Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且只在跟随底部时禁用自己滚动区域的浏览器自动锚定。没有读者移动的贴底滚动事件,以及确实到达最底部的读者输入,会立即更新跟随归属,避免后续布局变化使其底部位置失效。其他读者移动即使位于跟随阈值内,也保持待处理直到采样周期或 `scrollend`,防止布局增长抵消小幅滚动操作。提交正文输入或 steering 时立即恢复跟随底部,并清除先前待处理的读者滚动采样。读者跟随底部时,`ResizeObserver` 追随新的底部,并且无需读取行几何就选中最后一个已加载轮次;读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃轮次。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内。 +Chat 等待初始历史就绪后,才允许自动内容、滚动或尺寸更新初始化阅读状态。进行中的 Session 先恢复初始显隐和位置,再允许折叠动画。 + +Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且只在跟随底部时禁用自己滚动区域的浏览器自动锚定。没有读者移动的贴底滚动事件,以及到达底部(容许小于 1px 的取整误差)的读者输入,会立即更新跟随归属,避免后续布局变化使其底部位置失效。其他读者移动即使位于跟随阈值内,也保持待处理直到采样周期或 `scrollend`,防止布局增长抵消小幅滚动操作。采用完成时收起时,提交正文输入或 steering 会立即恢复跟随底部,并清除先前待处理的读者滚动采样。读者跟随底部时,`ResizeObserver` 追随新的底部,并且无需读取行几何就选中最后一个已加载轮次;读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃轮次。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内。 轮次轨道与回到底部按钮位于正文裁剪层外。它们相对共享会话滚动容器做 sticky 定位;Chat 自己持有滚动容器时,则相对 Chat 外框做 absolute 定位。正文扣除水平内边距后的可用宽度不超过 900px 时,隐藏轮次轨道;判断依据不是浏览器视口宽度。 正文根节点使用 `overflow-x: visible; overflow-y: clip`:裁剪纵向溢出,但不创建滚动容器。因此,在没有更近的滚动祖先时,Markdown 代码块的 sticky 头栏和展开的压缩摘要头栏仍以实际会话滚动容器为参照。限高过程组和终端区域保留各自的滚动容器。 -外层文本记录与每个已展开限高组的跟随状态彼此独立。原生动画的中间滚动保留跟随意图;读者手势中断动画,是否继续跟随由实际位移决定。滚动传递可以带动外层,外层再按自身离底距离判断。回到底部按钮只恢复外层跟随。 +外层文本记录与每个已展开限高组的跟随状态彼此独立。原生动画的中间滚动保留跟随意图;只有该滚动容器自身的 `scrollend` 才结束其动画。不支持 `scrollend` 的浏览器可能保留原生跟随目标,直到后续贴底更新或读者手势将其结束。读者手势中断动画,是否继续跟随由实际位移决定。滚动传递可以带动外层,外层再按自身离底距离判断。回到底部按钮只恢复外层跟随。 + +下次消息触发的折叠中,每一批收起行与滚动容器在同一个帧时钟上推进,折叠期间禁用浏览器滚动锚定;不存在「先预留、再跟随」的另一条路径。批次运行期间开始收起或展开的行先保持当前尺寸,等当前批次落定后在下一批中变化;批次从每一行已有的尺寸继续。由本客户端自己的输入(包括子代理会话的 continuation)触发、或读者原本在跟尾时,这一批落到底部;其余情况下,无论消息由谁发出,读者正在看的内容保持不动。阅读线以上的内容不会回滑:保留的正文和新内容填不满视口时,只把差额保留为底部空间,后续新增内容先填满它,再继续跟尾。读者手势取消自动目标及进行中的原生跟随;同一次折叠中的尺寸变化不能恢复它,但新提交的输入可以。已确认的滚动只释放不会造成位置钳制的多余空间。卸载 Chat 时取消等待回调和行过渡。启用减少动态效果偏好时,可见性和定位立即变化。 + +切换工作步骤展示档位时,当前折叠结束后清空底部预留空间,并按所选档位调整滚动范围。原本跟随底部的读者保持在新的底部;其他读者不会被强制拉回底部。 + +折叠协调状态由各自的 viewport 持有,折叠批次、底部空间和空闲回调不会广播到其他 Chat 视图。ChatView 通过本次渲染的 `hookContext`,向 `conversation.chat.flow` 交接一次动画能力。Flow 绑定组内容与组头的行为 hook,负责节点分发,为本地回显提供 Factory renderer,并共享既有 Chat store 与 Session 节点来源。图片入口 Factory 拥有可替换的图片 Slot。布局节点和行内思考接收绑定后的 hook,不接收动画控制器,也不改变内容的父级。通用的可搜索隐藏在绘制前生效,并负责焦点保护及 beforematch;pending 输入对账仍留在 ChatView。 | 外层跟随 | 已展开小组跟随 | 回到底部按钮 | 新增内容 | |---|---|---|---| @@ -146,7 +166,7 @@ Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且 `useChatReading` 负责跟随策略、读者输入采样和语义位置记忆;`useChatNavigation` 负责轮次跳转,并向视口请求位置保持。阅读手势释放分页锚点,composer 内的点击、打字和非滚动按键则保留锚点;分页仍在加载时,`scrollend` 会记录读者的新位置。`useChatScroll` 协调已提交的输入。显式导航把测得的落点交给阅读策略,因此无需通过命中测试重新寻找已知目标。 -活跃轮次高亮采用近似定位:`readVisibleTurn` 对正文容器的直属 Node/Group 布局盒二分,落在间隙时保留前方候选。它不做文档命中测试,也不查询 Group 成员或全部 Turn 标记。空 Seat 保留零高度的流内布局盒,使外层位置有序且不增加间距。这种定位不改变语义位置捕获或分页补偿。 +活跃轮次高亮采用近似定位:`readVisibleTurn` 对 flow 插槽的直属 Node/Group 布局盒二分(独立渲染时使用正文容器的直属布局盒),落在间隙时保留前方候选。它不做文档命中测试,也不查询 Group 成员或全部 Turn 标记。空 Seat 保留零高度的流内布局盒,使外层位置有序且不增加间距。这种定位不改变语义位置捕获或分页补偿。
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 b3939f1f12..3f11a50d9e 100644 --- a/packages/client/ui-chat/package.json +++ b/packages/client/ui-chat/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-chat", "description": "Chat Conversation target, node definitions, renderers, and details surface", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -87,9 +88,7 @@ "@deepseek-ai/dsh-tools": "workspace:*", "@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", + "@tanstack/react-virtual": "3.14.10", "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 e83c851c3b..8aa63aa1f7 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -22,13 +22,16 @@ import type {} from '@deepseek-ai/dsh-client-ui-session/client' import type {} from '@deepseek-ai/dsh-client-ui-settings/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import type { - ChatNodeInjected, ChatScrollPosition, ChatViewInjected, QuotaNoticeInjected, QuotaNoticeState, TurnTailOwnerProps, + ChatFlowDataInjected, ChatFlowInjected, ChatNodeInjected, ChatScrollPosition, ChatViewInjected, + QuotaNoticeInjected, QuotaNoticeState, TurnTailOwnerProps, } from './contract/slots.ts' import type { ChatSnapshot } from './contract/snapshot.ts' import { EMPTY_CHAT_SNAPSHOT } from './contract/snapshot.ts' 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' @@ -43,13 +46,28 @@ import { PerformanceUsageRow, type PerformanceUsageRowInjected } from './setting import { PerformanceUsagePolicy } from './performance-usage.ts' import { useTurnDataValue } from './chat/use-turn-data.ts' import { bindDisclosure } from './chat/use-disclosure.ts' +import { useFlowHidden, useMotionHidden } from './chat/flow-motion.ts' -const CHAT_NODE_INJECT: ChatNodeInjected = { +/** Bind group and header visibility to the viewport of one flow render. */ +export const CHAT_FLOW_INJECT: ChatFlowInjected = { + hooks: { + groupAction: (_standard, { motion }) => function useGroupAction(hidden, reveal) { + return useFlowHidden(hidden, reveal, motion) + }, + groupHeaderAction: (_standard, { motion }) => function useGroupHeaderAction(ref, hidden) { + useMotionHidden(ref, hidden, motion) + }, + }, +} + +/** Bind node-local sources and forward the flow's existing visibility hook. */ +export const CHAT_NODE_INJECT: ChatNodeInjected = { hooks: { turnData: (_standard, { turnData }) => function useTurnData(key) { return useTurnDataValue(turnData, key) }, disclosure: (_standard, { disclosureReset }) => bindDisclosure(disclosureReset), + groupAction: (_standard, { useGroupAction }) => useGroupAction, }, } @@ -147,11 +165,15 @@ export function apply(ctx: Context): void { }, LinkOpeningRow)) }) const transcriptView = new TranscriptViewPolicy(chatSettings, 'dshDesktop' in globalThis ? 'standard' : DEFAULT_TRANSCRIPT_VIEW_MODE) - const presentation = derivePresentationPolicy(transcriptView.mode) + const presentation = derivePresentationPolicy(transcriptView.mode, transcriptView.collapseTiming) const performancePolicy = new PerformanceUsagePolicy(chatSettings) 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', @@ -170,11 +192,38 @@ export function apply(ctx: Context): void { order: 12, locale: NS, inject: (): TranscriptViewRowInjected => ({ - hooks: { transcriptView: transcriptView.mode }, + hooks: { transcriptView: transcriptView.mode, collapseTiming: transcriptView.collapseTiming }, setTranscriptView: (mode) => { transcriptView.setMode(mode) }, + setCollapseTiming: (timing) => { transcriptView.setCollapseTiming(timing) }, }), }, TranscriptViewRow)) + const nodeSources = (binding: SessionBinding): ChatFlowDataInjected => { + const chat = chatSource(binding) + const conversation = ctx.uiConversation.binding(binding) + return { + hooks: { presentation }, + keyedHooks: { + chatNode: key => chat.getSnapshot().nodes.source(key), + chatNodeBottom: key => chat.getSnapshot().nodes.bottomSource(key), + chatNodeProcess: key => chat.getSnapshot().nodes.processSource(key), + chatGroup: key => conversation.snapshot.getSnapshot().views.grouped('chat')?.groupSource(key as GroupKey), + }, + } + } + + ctx.slots.inject('conversation.chat.flow', () => ctx.slots.register({ + name: 'conversation.chat.flow', locale: NS, store: chatStore, + children: { + 'conversation.chat.node': { kind: 'keyed', scope: 'session', inject: CHAT_NODE_INJECT }, + }, + inject: (sessionId: SessionId): ChatFlowDataInjected => { + const binding = ctx.sessions.binding(sessionId) + if (binding === undefined) throw new Error(`ui-chat: unknown session "${sessionId}"`) + return nodeSources(binding) + }, + }, ChatFlow)) + ctx.slots.inject('conversation.view', () => { const disposeView = ctx.slots.register({ name: 'conversation.view', @@ -183,8 +232,7 @@ export function apply(ctx: Context): void { label: () => t('view.chat'), locale: NS, children: { - 'conversation.chat.node': { kind: 'keyed', scope: 'session', inject: CHAT_NODE_INJECT }, - 'conversation.message.images': { kind: 'single', scope: 'session' }, + 'conversation.chat.flow': { kind: 'single', scope: 'session', inject: CHAT_FLOW_INJECT }, }, store: chatStore, inject: (sessionId: SessionId): ChatViewInjected => { @@ -192,14 +240,8 @@ export function apply(ctx: Context): void { if (binding === undefined) throw new Error(`ui-chat: unknown session "${sessionId}"`) const session = binding.session const chat = chatSource(binding) - const conversation = ctx.uiConversation.binding(binding) return { - hooks: { presentation }, - keyedHooks: { - chatNode: key => chat.getSnapshot().nodes.source(key), - chatNodeProcess: key => chat.getSnapshot().nodes.processSource(key), - chatGroup: key => conversation.snapshot.getSnapshot().views.grouped('chat')?.groupSource(key as GroupKey), - }, + ...nodeSources(binding), fileMentions: (owner: TurnTailOwnerProps) => ctx.get('chatFileMentions')?.forClosing(owner, sessionId), // Files open in the right Sidebar, not in a desktop application: the // content stays in the product, beside the conversation that produced @@ -220,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 476565ecbb..22ae5bac70 100644 --- a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx +++ b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx @@ -4,11 +4,10 @@ import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import type { ReactNode } from 'react' import { JsonBlock, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives' import type { MarkdownFileMentions, MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives' -import type { ChatNodeOwnerProps, ChatViewSlotProps, UseDisclosure, UsePresentation } from '../contract/slots.ts' +import type { ChatNodeOwnerProps, ChatViewSlotProps, UseDisclosure, UsePresentation, UseGroupAction } from '../contract/slots.ts' import type { AssistantBlock } from '../contract/snapshot.ts' import { markdownLabels } from '../markdown-labels.ts' import { ReasoningRow } from './ReasoningRow.tsx' -import { useSearchableHidden } from './searchable-hidden.ts' import css from './AssistantMarkdown.module.css' /** @@ -28,7 +27,9 @@ export function localPathMediaUrl(base: string, value: string): string | undefin return fileMediaUrl(base, path) } -export interface AssistantMarkdownProps { +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. */ @@ -37,12 +38,10 @@ export interface AssistantMarkdownProps { streaming: boolean /** Frozen partial of an aborted turn: rendered with a stopped marker. */ interrupted?: boolean | undefined - /** Render consecutive image blocks through the attachment slot. */ - renderMessageImages: ChatNodeOwnerProps['renderMessageImages'] - /** Optional expanded reasoning extension; absent for standalone renderers. */ - renderReasoningBody?: PropsRenderSlots<'conversation.chat.reasoning-body'>['renderSlotChain'] | undefined /** Hide reasoning that belongs to the Turn-level process disclosure. */ reasoningHidden?: boolean | undefined + /** Process hiding bound by the node slot to its current viewport. */ + useGroupAction: UseGroupAction /** Live display policy for reasoning summaries. */ usePresentation: UsePresentation /** Reveal the disclosure that hides this reasoning. */ @@ -53,10 +52,10 @@ export interface AssistantMarkdownProps { t: ChatViewSlotProps['t'] } -/** Reasoning block as the Think variant summary row (figma 39:28304). */ +/** Renders non-blank reasoning blocks as independent disclosures alongside the response. */ export const AssistantMarkdown = memo(function AssistantMarkdown({ - blocks, streaming, interrupted, renderMessageImages, groupPart, useDisclosure, - reasoningHidden = false, usePresentation, revealProcess, mentions, renderReasoningBody, t, + blocks, streaming, interrupted, loadImage, groupPart, useDisclosure, + reasoningHidden = false, usePresentation, revealProcess, mentions, renderSlot, useGroupAction, t, }: AssistantMarkdownProps) { // Stable per locale revision (t identity changes on switch): a fresh object // per render would rebuild MarkdownText's component table every chunk. @@ -93,14 +92,16 @@ export const AssistantMarkdown = memo(function AssistantMarkdown({ ) break case 'reasoning': + if (block.text.trim() === '') break rendered.push( , ) break @@ -120,9 +121,8 @@ export const AssistantMarkdown = memo(function AssistantMarkdown({ } rendered.push( - {renderMessageImages({ - images: group.map(({ attachment }) => ({ attachment })), - align: 'start', + {renderSlot('conversation.chat.message.images', { + images: group.map(({ attachment }) => ({ attachment })), loadImage, align: 'start', })} , ) @@ -154,12 +154,13 @@ export const AssistantMarkdown = memo(function AssistantMarkdown({ ) }) -function ProcessReasoning({ hidden, reveal, children }: { +function ProcessReasoning({ hidden, reveal, useGroupAction, children }: { hidden: boolean reveal?: (() => void) | undefined + useGroupAction: UseGroupAction children: ReactNode }) { - const ref = useSearchableHidden(hidden, reveal ?? NOOP) + const ref = useGroupAction(hidden, reveal ?? NOOP) return
{children}
} diff --git a/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx b/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx index e934c4e708..5f61fe7007 100644 --- a/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx +++ b/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx @@ -4,12 +4,12 @@ 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, useTurnData, turnProcess, openFile, renderMessageImages, fileMentions, - usePresentation, renderSlotChain, t, + node, groupPart, useDisclosure, useGroupAction, useTurnData, turnProcess, openFile, loadImage, fileMentions, + usePresentation, renderSlot, t, }: AssistantNodeViewProps) { const data = node.data const turn = node.location.kind === 'turn' || node.location.kind === 'step' @@ -38,10 +38,11 @@ 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} - renderReasoningBody={renderSlotChain} + renderSlot={renderSlot} revealProcess={revealProcess} mentions={mentions} t={t} diff --git a/packages/client/ui-chat/src/client/chat/ChatFlow.tsx b/packages/client/ui-chat/src/client/chat/ChatFlow.tsx new file mode 100644 index 0000000000..c54e8a108f --- /dev/null +++ b/packages/client/ui-chat/src/client/chat/ChatFlow.tsx @@ -0,0 +1,61 @@ +/** Ordered Chat rows, local echoes, and running status share the flow slot's parent. */ +import { memo } from 'react' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { ChatFlowSlotProps } from '../contract/slots.ts' +import { ChatNodeSeat } from './ChatNodeSeat.tsx' +import { ChatGroupSeat } from './ChatGroupSeat.tsx' +import { PendingSteeringBubble, PendingSubmissionBubble } from './MessageItem.tsx' +import { chatRenderKey } from './render-entry.ts' +import { RunningStatus } from './RunningStatus.tsx' + +/** Render the flow without adding a DOM parent or changing keyed row positions. */ +export const ChatFlow = memo(function ChatFlow({ + entries, pendingInputs, lastInputTurn, deferCollapse, + useSession, useChat, useChatNode, useChatNodeBottom, useChatNodeProcess, useChatGroup, usePresentation, + 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) + const latestTurnAnchor = useChat(snapshot => snapshot.navigation.items().at(-1)?.anchorKey) + const runningStartTime = useChatNode(latestTurnAnchor ?? '', (node) => { + const location = node?.location + return location?.kind === 'turn' || location?.kind === 'step' + ? location.turn.status === 'open' ? location.turn.start?.time : undefined + : undefined + }) + const seatProps = { + nodeStore, useChatNode, useChatNodeBottom, useChatNodeProcess, usePresentation, + useStore, actions, renderSlot, t, useGroupAction, deferCollapse, + cwd, openFile, inspectCall, forkAt, loadImage, fileMentions, + } + const rows = entries.map((entry) => { + switch (entry.kind) { + case 'node': + return + case 'group': + return + default: + return assertNever(entry) + } + }) + const pendingRows = pendingInputs.map(item => 'requestId' in item ? ( + + ) : ( + + )) + const tail = entries.at(-1) + const node = tail?.kind === 'node' ? nodeStore.get(tail.key) : undefined + // An empty opening control follows one local transcript echo, never steering. + // All rows share this keyed list so inserting the control keeps the echo mounted. + if (node?.kind === 'turn-process' && node.location.kind === 'turn' + && node.location.turn.status === 'open' && node.location.turn.turn !== lastInputTurn) { + const index = pendingInputs.findIndex(item => 'requestId' in item && item.placement === 'transcript') + if (index !== -1) rows.splice(rows.length - 1, 0, ...pendingRows.splice(index, 1)) + } + return [...rows, ...pendingRows, ...running ? [] : []] +}) diff --git a/packages/client/ui-chat/src/client/chat/ChatGroupSeat.module.css b/packages/client/ui-chat/src/client/chat/ChatGroupSeat.module.css index f40328906c..c7797443d9 100644 --- a/packages/client/ui-chat/src/client/chat/ChatGroupSeat.module.css +++ b/packages/client/ui-chat/src/client/chat/ChatGroupSeat.module.css @@ -137,3 +137,14 @@ overflow: visible; scrollbar-gutter: auto; } + +/* Member spacing changes share the closing body's timing. */ +:global([data-chat-motion]) .content > :not([data-chat-motion]) { + transition: margin-top 160ms cubic-bezier(0.4, 0, 0.2, 1); +} + +@media (prefers-reduced-motion: reduce) { + :global([data-chat-motion]) .content > :not([data-chat-motion]) { + transition: none; + } +} diff --git a/packages/client/ui-chat/src/client/chat/ChatGroupSeat.tsx b/packages/client/ui-chat/src/client/chat/ChatGroupSeat.tsx index 443cb0407a..cdf34ce2ef 100644 --- a/packages/client/ui-chat/src/client/chat/ChatGroupSeat.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatGroupSeat.tsx @@ -9,12 +9,12 @@ import { import type { GroupKey, NodeReference } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { ProcessActivity } from '../contract/process-groups.ts' import type { ChatStoreState } from '../contract/store.ts' -import type { ChatViewSlotProps } from '../contract/slots.ts' -import { storedTurnProcessEntry } from '../stores.ts' +import type { ChatFlowSlotProps } from '../contract/slots.ts' +import { turnProcessOpen } from '../stores.ts' import { ChatNodeSeat } from './ChatNodeSeat.tsx' +import { hiddenOrCollapsing } from './flow-motion.ts' import { chatRenderKey } from './render-entry.ts' import { processTitle } from './step-process.ts' -import { useSearchableHidden } from './searchable-hidden.ts' import { useDisclosure } from './use-disclosure.ts' import { useProcessScroll } from './use-process-scroll.ts' import css from './ChatGroupSeat.module.css' @@ -22,7 +22,8 @@ import css from './ChatGroupSeat.module.css' type SeatProps = Omit, 'nodeKey' | 'groupPart'> type ChatGroupSeatProps = SeatProps & { readonly groupKey: GroupKey - readonly useChatGroup: ChatViewSlotProps['useChatGroup'] + readonly useChatGroup: ChatFlowSlotProps['useChatGroup'] + readonly useGroupHeaderAction: ChatFlowSlotProps['useGroupHeaderAction'] } const PROCESS_TITLE_MINIMUM_MS = 150 @@ -90,9 +91,9 @@ const GroupMembers = memo(function GroupMembers({ members, ...props }: SeatProps const ProcessGroupHeader = memo(function ProcessGroupHeader({ groupKey, useChatGroup, usePresentation, t, open, bodyId, toggle }: { readonly groupKey: GroupKey - readonly useChatGroup: ChatViewSlotProps['useChatGroup'] - readonly usePresentation: ChatViewSlotProps['usePresentation'] - readonly t: ChatViewSlotProps['t'] + readonly useChatGroup: ChatFlowSlotProps['useChatGroup'] + readonly usePresentation: ChatFlowSlotProps['usePresentation'] + readonly t: ChatFlowSlotProps['t'] readonly open: boolean readonly bodyId: string readonly toggle: () => void @@ -128,38 +129,46 @@ const ProcessGroupHeader = memo(function ProcessGroupHeader({ groupKey, useChatG }) /** Render a process group with local disclosure and the existing outer-Turn visibility. */ -export const ChatGroupSeat = memo(function ChatGroupSeat({ groupKey, useChatGroup, ...props }: ChatGroupSeatProps) { +export const ChatGroupSeat = memo(function ChatGroupSeat({ groupKey, useChatGroup, useGroupHeaderAction, ...props }: ChatGroupSeatProps) { const members = useChatGroup(groupKey, group => group?.members) const turn = useChatGroup(groupKey, group => group?.data.turn) const closed = useChatGroup(groupKey, group => group?.data.closed) const foldCompleted = props.usePresentation(policy => policy.foldCompletedTurns) const { expanded: open, setExpanded: setOpen } = useDisclosure() const firstKey = members?.[0]?.key ?? '' + const bottom = props.useChatNodeBottom(firstKey) + const deferCollapse = bottom === true && props.deferCollapse const presentation = props.useChatNodeProcess(firstKey) const turnLocation = props.useChatNode(firstKey, (node) => { const location = node?.location return location?.kind === 'turn' || location?.kind === 'step' ? location.turn : undefined }) + // Detailed keeps the latest completed Turn flat, like a running one, until the next input. const grouped = props.usePresentation(policy => policy.stepGrouping === 'collapsed' - || (policy.stepGrouping === 'history' && turnLocation?.status !== 'open')) + || (policy.stepGrouping === 'history' && turnLocation?.status !== 'open' && !deferCollapse)) const reason = turnLocation?.end?.data.reason.kind const alwaysOpen = presentation?.turnClosed === false || presentation?.hasInterleavedInput === true || reason === 'aborted' || reason === 'error' const spec = presentation?.spec - const selectStored = useCallback((state: Readonly) => turn === undefined - ? undefined : storedTurnProcessEntry(state, turn), [turn]) - const stored = props.useStore(selectStored) + const selectOpen = useCallback((state: Readonly) => spec !== undefined + && turnProcessOpen(state, spec, deferCollapse), [spec, deferCollapse]) + const storedOpen = props.useStore(selectOpen) const outerHidden = foldCompleted && presentation?.turnClosed === true && spec !== undefined - && !alwaysOpen && stored?.answerStep !== (spec.answerStep ?? 0) + && !alwaysOpen && !storedOpen const revealOuter = useCallback(() => { if (spec !== undefined && !alwaysOpen) props.actions.setTurnProcessOpen(spec.turn, spec.answerStep ?? 0, true) }, [props.actions, spec, alwaysOpen]) - const rootRef = useSearchableHidden(outerHidden, revealOuter) + const rootRef = props.useGroupAction(outerHidden, revealOuter) + // The header appears when a flat latest Turn becomes historical; it grows on the fold clock while the + // body closes. A group whose whole Turn is folding never shows one in the frame it starts closing. + const headerRef = useRef(null) + const deferCompletedTurns = props.usePresentation(policy => policy.collapseTiming === 'next-input') + useGroupHeaderAction(headerRef, !grouped || (deferCompletedTurns && outerHidden)) useEffect(() => { - if (outerHidden && rootRef.current?.hasAttribute('hidden')) setOpen(false) + if (outerHidden && rootRef.current !== null && hiddenOrCollapsing(rootRef.current)) setOpen(false) }, [outerHidden, rootRef, setOpen]) const reveal = useCallback(() => { setOpen(true) }, [setOpen]) - const bodyRef = useSearchableHidden(grouped && !open, reveal) + const bodyRef = props.useGroupAction(grouped && !open, reveal) const contentRef = useRef(null) const bodyId = useId() const { edges, events, initialize } = useProcessScroll(bodyRef, contentRef, open, grouped) @@ -168,14 +177,17 @@ export const ChatGroupSeat = memo(function ChatGroupSeat({ groupKey, useChatGrou setOpen(!open) }, [closed, initialize, open, setOpen]) if (members === undefined) return null - const classes = [css.body, !grouped ? css.expandedBody : '', - grouped && edges.canScrollUp ? css.fadeTop : '', grouped && edges.canScrollDown ? css.fadeBottom : ''] + // The height cap applies only to a group the reader opened; a body that is closing keeps its flat + // height so the transition starts from what is on screen instead of snapping to the cap first. + const capped = grouped && (!deferCompletedTurns || open) + const classes = [css.body, !capped ? css.expandedBody : '', + capped && edges.canScrollUp ? css.fadeTop : '', capped && edges.canScrollDown ? css.fadeBottom : ''] return (
-
----- 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 420298e908..ff3b3fb76c 100644 --- a/packages/client/ui-commands/package.json +++ b/packages/client/ui-commands/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-commands", "description": "Client command surface: global directory cache, '/' source, three command UI kinds, popupSelect registry", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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 a22be7582c..de1c5e1f59 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: ef43c4f149195939 + zh: 49fc6c83fd3a05ce +/deepseek-ai-dsh-client-ui-conversation/sent-user-text: + en: 9912b286384c41d7 + zh: 3e994887c1948677 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 50b5e00a5fb7c2e5 - zh: 91333db3947f395d + en: aab84874b0a00ea5 + zh: 642bacaf76385e83 /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 ec4221995f..627a1872ae 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) @@ -37,7 +38,7 @@ Definitions may share the same read-only Match and Location for one input and li Registration accepts the existing callable `match` or a read-only event-type-to-handler table. The Registry copies table entries and precomputes ordered candidate Sets on registration changes. Function-form Definitions keep their callable API and receive every event; table handlers receive only their declared types. Changing a table requires unregistering and registering again. Legacy assembler adapters with only `entries()` and `fallbackEntry()` retain their original dispatch path. -All accepted Matches update State in order. Repeated updates to one Context are coalesced between flushes. A Context retains its key while kind and id match; Definition-facing Context snapshots remain distinct objects. The fallback handles only inputs not claimed by an ordinary Definition for its target. +All accepted Matches update State in order. Repeated updates to one Context are coalesced between flushes. A Context retains its key while kind and id match; Definition-facing Context snapshots remain distinct objects. The fallback handles only inputs that no ordinary Definition of its target matched. A Definition can return `exclusive: true` from `match()` to claim an event on its target: other Definitions of that target do not receive the event and the target's fallback does not run ([semantics](../../../docs/subsystems/conversation.md#definition-and-typed-chat-payload)). Location lookup indexes Steps by Turn and Step number, so a non-boundary append does not scan the Turn's Step array. Each input's numeric coordinates and resolved Location share one private index record; published Location values remain immutable. Boundary updates, replacement, and prepend keep the indexes aligned with the current timeline. @@ -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,13 +94,15 @@ 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. +Clicking unused space inside an editable composer preserves its current caret or selection when focused, or restores its previous caret or selection when unfocused. Text selection, scrollbars, controls, and embedded overlays keep their own pointer behavior. + Each composer attempt carries its original occurrence time, gesture, delivery intent, and Session model/run-state snapshot through asynchronous command arbitration. The ordinary-message notification fires once before reference serialization, including attachment-only submissions; handled or claimed commands do not notify. Snapshot and notification failures cannot block sending. -Default sends commit optimistically: Enter clears the draft, occurrence table, and undo history in the same transaction, keeps the composer in `plain`, and runs the send as a detached attempt, so typing and further sends continue during the flight. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order in `pendingSubmissions`; Session derives the placement from that mode and its current running state, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint, encodes images through the browser's native `FileReader` data-URL path, and cites staged file receipts. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; Session retires the echo once at its display handoff, correlated by that `rpcId`. Concurrent failures are restored together in submission order until the user edits the restored content; command submissions keep the frozen `submitting` phase. Detached attempts retain their attachment ids through admission and Session scope disposal. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards. Selected generic files enter one FIFO background-upload queue; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents accept pasted and dropped PNG, JPEG, WebP, and GIF images with the same projected limits; a batch containing a generic file, unsupported image format, or directory is refused before intake. They skip local echoes because their transport does not preserve the browser request id. +Default sends commit optimistically: Enter clears the draft, occurrence table, and undo history in the same transaction, keeps the composer in `plain`, and runs the send as a detached attempt, so typing and further sends continue during the flight. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order in `pendingSubmissions`; Session derives the placement from that mode and its current running state, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint, encodes images through the browser's native `FileReader` data-URL path, and cites staged file receipts. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; Session retires the echo once at its display handoff, correlated by that `rpcId`. Concurrent failures are restored together in submission order until the user edits the restored content; command submissions keep the frozen `submitting` phase. Detached attempts retain their attachment ids through admission and Session scope disposal. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards. Selected generic files enter one FIFO background-upload queue; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents accept pasted and dropped PNG, JPEG, WebP, and GIF images with the same projected limits; a batch containing a generic file, unsupported image format, or directory is refused before intake. Their sends register the same local echo; the continuation request carries the echo's `requestId`, which the Host records as the child message's `rpcId`. Queued submission echoes show “Sending…” beside disabled edit, remove, and steer buttons; a collapsed dock keeps the sending status in its header. A matching Host queue row replaces the echo and enables each action according to its normal text-content and running-state requirements. Prompt acknowledgement alone does not enable queue actions. A failed submission removes its echo and displays an error; the composer restores the failed draft when it is empty or still contains the previous automatic restoration, preserving subsequently typed text. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index bb0c423a36..66e5a2865b 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) @@ -37,7 +38,7 @@ kind: "package-reference" 注册入口接受原有可调用的 `match`,或只读的事件类型到处理函数表。Registry 在注册关系变化时复制表条目并预计算有序候选 Set。函数形式的 Definition 保持原有可调用 API,接收全部事件;表中的处理函数只接收已声明类型。修改表需要注销后重新注册。只有 `entries()` 与 `fallbackEntry()` 的旧 assembler 适配器保留原有分发路径。 -所有接受的 Match 按顺序更新 State。两次 flush 之间,同一 Context 的重复更新合批发布。kind 和 id 相同时,Context 保持原有 key;传给 Definition 的 Context 快照仍为独立对象。fallback 只处理未被其目标的普通 Definition 认领的输入。 +所有接受的 Match 按顺序更新 State。两次 flush 之间,同一 Context 的重复更新合批发布。kind 和 id 相同时,Context 保持原有 key;传给 Definition 的 Context 快照仍为独立对象。fallback 只处理其目标上没有普通 Definition 匹配的输入。Definition 可以从 `match()` 返回 `exclusive: true`,在其目标上认领一个事件:该目标的其他 Definition 收不到这个事件,该目标的 fallback 也不运行([语义](../../../docs/subsystems/conversation.zh.md#definition-and-typed-chat-payload))。 Location 查询按 Turn 和 Step 编号索引 Step,因此非边界 append 不扫描 Turn 的 Step 数组。每个输入的数值坐标与解析出的 Location 共用一条私有索引记录;已发布的 Location 值保持不可变。边界更新、完整替换和向前补页使这些索引与当前时间线保持一致。 @@ -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,13 +94,15 @@ 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 插件注册发送、换行、互补投递、命令菜单和引用菜单的固定条目,并在卸载前保留这些键位。 +点击可编辑输入框内的留白时,已聚焦的输入框保留当前光标或选区,未聚焦的输入框恢复上次的光标或选区。文本选择、滚动条、控件和内嵌浮层保持各自的指针交互行为。 + 每次输入框提交都携带原始发生时间、操作来源、投递意图以及会话模型和运行状态快照,贯穿异步命令裁决。普通消息通知在引用序列化前发出一次,纯附件提交也遵循这一规则;已处理或认领的命令不发出通知。快照读取与通知消费异常不能阻断发送。 -默认发送采用乐观提交:Enter 在同一事务里清空草稿、occurrence 表和撤销历史,composer 保持 `plain`,发送作为 detached attempt 运行,发送期间可以继续输入和提交。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),并在 `pendingSubmissions` 中保留图片与文件的选择顺序;Session 根据该模式与当前运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,图片经浏览器原生 `FileReader` data-URL 路径编码,文件则引用已暂存凭证。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;Session 按同一 `rpcId` 关联展示接管,并仅退休回显一次。多个并发发送失败时,在用户编辑还原内容之前按提交顺序合并还原;命令提交保持冻结的 `submitting` 阶段。Detached attempt 持有附件 id,直到 admission 完成或 Session scope 销毁。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡。选中的通用文件进入同一个先进先出的后台上传队列;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理允许粘贴和拖入 PNG、JPEG、WebP、GIF 图片,并沿用相同的投影限制;包含通用文件、不支持的图片格式或目录的批次会在进入草稿前整批拒绝。它们不创建本地回显,因为其 transport 不保留浏览器 request id。 +默认发送采用乐观提交:Enter 在同一事务里清空草稿、occurrence 表和撤销历史,composer 保持 `plain`,发送作为 detached attempt 运行,发送期间可以继续输入和提交。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),并在 `pendingSubmissions` 中保留图片与文件的选择顺序;Session 根据该模式与当前运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,图片经浏览器原生 `FileReader` data-URL 路径编码,文件则引用已暂存凭证。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;Session 按同一 `rpcId` 关联展示接管,并仅退休回显一次。多个并发发送失败时,在用户编辑还原内容之前按提交顺序合并还原;命令提交保持冻结的 `submitting` 阶段。Detached attempt 持有附件 id,直到 admission 完成或 Session scope 销毁。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡。选中的通用文件进入同一个先进先出的后台上传队列;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理允许粘贴和拖入 PNG、JPEG、WebP、GIF 图片,并沿用相同的投影限制;包含通用文件、不支持的图片格式或目录的批次会在进入草稿前整批拒绝。它们的发送同样注册本地回显;continuation 请求携带回显的 `requestId`,Host 把它记录为子会话消息的 `rpcId`。 排队提交的本地回显在禁用的编辑、删除、插话按钮旁显示“发送中…”;折叠后的队列在标题栏保留发送状态。匹配的 Host 队列行替换回显后,各操作按原有的纯文本内容和运行状态要求启用。仅收到提示词确认不会启用队列操作。提交失败会移除回显并显示错误;输入框为空或仍保留上一次自动恢复的内容时,composer 恢复失败草稿,保留用户随后输入的文字。 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 ba27bcef13..839cf822e1 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-conversation", "description": "Target-neutral Conversation assembly, shell, composer, queue, and view navigation", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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,12 +83,10 @@ "@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", + "zod": "4.4.3", "lexical": "^0.49.0", "clsx": "^2.0.0", "@lexical/utils": "^0.49.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/conversation.ts b/packages/client/ui-conversation/src/client/contract/conversation.ts index 8230bda46e..2d871871fc 100644 --- a/packages/client/ui-conversation/src/client/contract/conversation.ts +++ b/packages/client/ui-conversation/src/client/contract/conversation.ts @@ -8,6 +8,16 @@ import type { export interface ConversationMatchResult { readonly id: string readonly role: 'start' | 'update' + /** + * Claim this event on the Definition's target: no other Definition of the + * same target receives it, and that target's unmatched-event fallback does + * not run. Definitions of other targets and Definitions without a target + * still receive it. Two claims on one target, or a claim from a Definition + * without a target, throw during dispatch. A claim returned by the fallback + * itself has no effect, because the fallback runs only when no Definition of + * its target matched. + */ + readonly exclusive?: true } /** Merge-extensible business values published against one Turn. */ diff --git a/packages/client/ui-conversation/src/client/contract/request-inspection.ts b/packages/client/ui-conversation/src/client/contract/request-inspection.ts index 3f0d785b8e..edc2d867d1 100644 --- a/packages/client/ui-conversation/src/client/contract/request-inspection.ts +++ b/packages/client/ui-conversation/src/client/contract/request-inspection.ts @@ -130,8 +130,9 @@ interface RequestViewBase { startedAt: number completedAt: number | null status: 'running' | 'complete' | 'error' + /** Failure detail; with assistant retry metadata, the last failed attempt even while running or after recovery. */ error?: string - /** Stable provider code for localized presentation of known failures. */ + /** Stable provider code for `error`, including retained attempt failures, for localized presentation. */ errorCode?: string providerMetadata?: AssistantProviderMetadataView requestConfig?: AssistantRequestConfig 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/assembler.ts b/packages/client/ui-conversation/src/client/conversation/assembler.ts index 6ead68c793..d50d7d5eaf 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembler.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembler.ts @@ -3,7 +3,7 @@ import type { } from '@deepseek-ai/dsh-api-session-controller/client' import type { LlmAttemptId } from '@deepseek-ai/dsh-llm/brand' import type { - ConversationContextReader, ConversationLocationData, ConversationMatch, + ConversationContextReader, ConversationLocationData, ConversationMatch, ConversationMatchResult, ConversationNodeContext, ConversationNodeDefinition, ConversationPreviousContext, ConversationLocationDataScope, ConversationPublication, ConversationViewBuilder, ConversationStartMatch, @@ -186,6 +186,9 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore private readonly groups = new Map() private readonly pendingGroupStores = new Set>() private readonly activeTargets = new Set() + /** Matches of the event in dispatch, kept by index; dispatch is not reentrant and reuses both arrays. */ + private readonly matchedDefinitions: ConversationNodeDefinition[] = [] + private readonly matchedResults: ConversationMatchResult[] = [] private hasMore = false private replacePending = true private timelineDirty = true @@ -493,37 +496,58 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore ? startMatch ??= conversationMatch(input, role, location) : updateMatch ??= conversationMatch(input, role, location) } - let firstTarget: string | undefined - let secondTarget: string | undefined - let otherTargets: Set | undefined - let publication: ConversationPublication = 'none' + const definitions = this.matchedDefinitions + const results = this.matchedResults + definitions.length = 0 + results.length = 0 const routes = this.eventDefinitions.forEvent?.(event.type) if (routes === undefined) { for (const definition of this.eventDefinitions.entries()) { const result = definition.match(event) if (result === null) continue - // Inline target tracking avoids an additional closure allocation for each event. - /* jscpd:ignore-start */ - if (definition.target !== undefined && definition.target !== firstTarget && definition.target !== secondTarget) { - if (firstTarget === undefined) firstTarget = definition.target - else if (secondTarget === undefined) secondTarget = definition.target - else (otherTargets ??= new Set()).add(definition.target) - } - publication = maximumPublication(publication, accept.call(this, definition, result.id, matchFor(result.role))) - /* jscpd:ignore-end */ + definitions.push(definition) + results.push(result) } } else { for (const { definition, match } of routes) { const result = match(event) if (result === null) continue - if (definition.target !== undefined && definition.target !== firstTarget && definition.target !== secondTarget) { - if (firstTarget === undefined) firstTarget = definition.target - else if (secondTarget === undefined) secondTarget = definition.target - else (otherTargets ??= new Set()).add(definition.target) - } - publication = maximumPublication(publication, accept.call(this, definition, result.id, matchFor(result.role))) + definitions.push(definition) + results.push(result) } } + // Claims are resolved before any acceptance, so the outcome does not depend on registration order. + let claims: Map | undefined + for (let index = 0; index < results.length; index++) { + if ((results[index] as ConversationMatchResult).exclusive !== true) continue + const definition = definitions[index] as ConversationNodeDefinition + const target = definition.target + if (target === undefined) { + throw new Error(`conversation Definition "${definition.kind}" claims ${event.type} at seq ${String(event.seq)} without a target`) + } + const claimant = claims?.get(target) + if (claimant !== undefined) { + throw new Error(`conversation Definitions "${claimant}" and "${definition.kind}" both claim ${event.type} at seq ${String(event.seq)} on target "${target}"`) + } + (claims ??= new Map()).set(target, definition.kind) + } + let firstTarget: string | undefined + let secondTarget: string | undefined + let otherTargets: Set | undefined + let publication: ConversationPublication = 'none' + for (let index = 0; index < results.length; index++) { + const definition = definitions[index] as ConversationNodeDefinition + const result = results[index] as ConversationMatchResult + const target = definition.target + if (target !== undefined && result.exclusive !== true && claims?.has(target) === true) continue + // Inline target tracking avoids an additional closure allocation for each event. + if (target !== undefined && target !== firstTarget && target !== secondTarget) { + if (firstTarget === undefined) firstTarget = target + else if (secondTarget === undefined) secondTarget = target + else (otherTargets ??= new Set()).add(target) + } + publication = maximumPublication(publication, accept.call(this, definition, result.id, matchFor(result.role))) + } const fallback = this.eventDefinitions.fallbackEntry() const target = fallback?.target if (fallback !== undefined && target !== undefined 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/input/editor/claim-decor.ts b/packages/client/ui-conversation/src/client/input/editor/claim-decor.ts index 7e28273305..e0ed9d3e57 100644 --- a/packages/client/ui-conversation/src/client/input/editor/claim-decor.ts +++ b/packages/client/ui-conversation/src/client/input/editor/claim-decor.ts @@ -43,9 +43,14 @@ export function registerClaimDecoration(editor: LexicalEditor, activeToken: () = } if (text.length > token.length) { // Typing at the token boundary lands in the styled node; split the - // overflow back out so only the token itself carries the color. - const [tokenNode] = node.splitText(token.length) + // overflow back out so only the token itself carries the color. The + // split copies the token style onto the overflow; it is cleared in this + // pass because Lexical's normalization merges same-style neighbours + // before the overflow's own transform runs, which would rejoin the two + // halves and loop until Lexical aborts the update. + const [tokenNode, overflow] = node.splitText(token.length) if (tokenNode !== undefined && tokenNode.getStyle() !== TOKEN_STYLE) tokenNode.setStyle(TOKEN_STYLE) + overflow?.setStyle('') return } if (node.getStyle() !== TOKEN_STYLE) node.setStyle(TOKEN_STYLE) 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 &&
, + leftItems: { event.preventDefault() }}>Canceled, + }) + const lexicalFocus = vi.spyOn(shell.editor, 'focus') + const scrollport = view.container.querySelector('[data-input-scroll]')! + const card = view.container.querySelector('[data-composer-card]')! + + expect(fireEvent.mouseDown(textarea, { button: 0 })).toBe(true) + expect(fireEvent.mouseDown(scrollport, { button: 0 })).toBe(true) + expect(fireEvent.mouseDown(view.getByText('Model'), { button: 0 })).toBe(true) + expect(fireEvent.mouseDown(view.getByText('Canceled'), { button: 0 })).toBe(false) + expect(fireEvent.mouseDown(card, { button: 2 })).toBe(true) + expect(lexicalFocus).not.toHaveBeenCalled() + }) + + it('leaves embedded overlay options, status text and scrollbars with the focused search field', () => { + const { view, shell } = bench({ + overlay:
+ +
Model option
+
Loading models
+
, + }) + const search = view.getByRole('textbox', { name: 'Filter models' }) + act(() => { search.focus() }) + const lexicalFocus = vi.spyOn(shell.editor, 'focus') + + for (const target of [ + view.getByRole('option'), view.getByRole('listbox'), view.getByText('Loading models'), + view.container.querySelector('[data-composer-overlay]')!, + ]) { + expect(fireEvent.mouseDown(target, { button: 0 })).toBe(true) + expect(document.activeElement).toBe(search) + } + expect(lexicalFocus).not.toHaveBeenCalled() + }) + + it('keeps a focused editor\'s native caret without restoring an older Lexical selection', () => { + const { view, shell, textarea } = bench() + act(() => { shell.focus() }) + expect(document.activeElement).toBe(textarea) + const lexicalFocus = vi.spyOn(shell.editor, 'focus') + + expect(fireEvent.mouseDown(view.container.querySelector('[data-composer-card]')!, { button: 0 })).toBe(false) + expect(document.activeElement).toBe(textarea) + expect(lexicalFocus).not.toHaveBeenCalled() + }) + + it('leaves portaled menu background presses outside the card alone', () => { + const { view, shell } = bench({ modelEntry: createPortal(
Menu background
, document.body) }) + const lexicalFocus = vi.spyOn(shell.editor, 'focus') + + expect(fireEvent.mouseDown(view.getByText('Menu background'), { button: 0 })).toBe(true) + expect(lexicalFocus).not.toHaveBeenCalled() + }) + + it.each([{ inert: true }, { disabled: true }, { blocked: { reason: 'unavailable' } }])( + 'does not focus an unavailable composer: %j', (options) => { + const { view, shell } = bench(options) + const lexicalFocus = vi.spyOn(shell.editor, 'focus') + + expect(fireEvent.mouseDown(view.container.querySelector('[data-composer-card]')!, { button: 0 })).toBe(true) + expect(lexicalFocus).not.toHaveBeenCalled() + }, + ) + it('focus() returns the keyboard to the editor through Lexical, not a bare DOM focus', () => { const { shell, textarea } = bench() writeDraft(shell, 'draft text') diff --git a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx index e7c997cb61..f1aba8e4e7 100644 --- a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx @@ -13,7 +13,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { - bindSnapshotSelector, conversationSnapshot, sessionSnapshot, + allowAllAccess, bindSnapshotSelector, conversationSnapshot, sessionSnapshot, } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -66,6 +66,7 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled items: [], archivedSessionIds: [], pinnedSessionIds: [], state: 'idle', phase: 'ready', error: null, baselinesReady: true, recentWorkspaceId: undefined, })), + ...allowAllAccess, useProjection: (() => undefined), useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), useInput: bindSnapshotSelector(shell.state), diff --git a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx index d3993c70df..bb089654dd 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx @@ -12,6 +12,7 @@ import './control-row-dom.ts' import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { act, cleanup, fireEvent, render } from '@testing-library/react' +import { $getRoot, $isElementNode, $isTextNode } from 'lexical' import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { InputTriggerService } from '@deepseek-ai/dsh-client-ui-input-trigger/client' @@ -22,7 +23,7 @@ import type { CommandClaim, PickOutcome, SubmitAttachment, SubmitOutcome, } from '../src/client/contract/input.ts' import { - bindSnapshotSelector, conversationSnapshot, makeTranslate, sessionSnapshot, SlotTestRuntime, + allowAllAccess, bindSnapshotSelector, conversationSnapshot, makeTranslate, sessionSnapshot, SlotTestRuntime, } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -164,6 +165,7 @@ async function scopedBench(register?: (inputTriggers: InputTriggerService) => vo items: [], archivedSessionIds: [], pinnedSessionIds: [], state: 'idle', phase: 'ready', error: null, baselinesReady: true, recentWorkspaceId: undefined, })), + ...allowAllAccess, useProjection: (() => undefined), useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), useInput: bindSnapshotSelector(shell.state), @@ -344,6 +346,31 @@ describe('scenario H: backspace breaks the token', () => { expect(b.shell.snapshot.phase).toBe('plain') }) + it('keeps text typed at the end of the claimed token when the browser inserts it natively', async () => { + const b = await bench() + b.type('/goal') + await vi.waitFor(() => { expect(b.controller.menu.getSnapshot().open).toBe(true) }) + fireEvent.keyDown(b.textarea, { key: ' ', keyCode: 32 }) + expect(b.shell.snapshot.phase).toBe('claimed') + b.type('/goal 发布') + // A caret at the token/argument boundary sits at the end of the styled + // token node; native insertion writes there and Lexical syncs the DOM + // text with setTextContent plus a caret select. + act(() => { + b.shell.editor.update(() => { + const paragraph = $getRoot().getFirstChild() + const token = $isElementNode(paragraph) ? paragraph.getFirstChild() : null + if (!$isTextNode(token)) throw new Error('missing token node') + token.setTextContent('/goal 立即') + token.select(8, 8) + }, { discrete: true }) + }) + expect(b.shell.snapshot.draft).toBe('/goal 立即发布') + expect(b.shell.snapshot.phase).toBe('claimed') + act(() => { b.shell.editor.update(() => {}, { discrete: true }) }) + expect(b.view.container.querySelector('[data-lexical-text][style*="business-primary"]')?.textContent).toBe('/goal ') + }) + it('claim releases automatically; the enter after that goes through adjudication again', async () => { const b = await bench() b.type('/goal') diff --git a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx index 756199f8b4..ec93676ff5 100644 --- a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx +++ b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx @@ -17,13 +17,15 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { - bindSnapshotSelector, conversationSnapshot, makeTranslate, + allowAllAccess, bindSnapshotSelector, conversationSnapshot, makeTranslate, } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import type { InputState } from '../src/client/contract/input.ts' import { zh } from '../src/client/locales.ts' import { QueueDock, queueDockEntry, type QueueDockInjected, type QueueDockProps } from '../src/client/queue/QueueDock.tsx' +import type { UserTextInput } from '../src/client/index.ts' +import { createUserTextFixture } from './user-text-component-fixture.client.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 })) as GlobalStandardProps['useResource'] @@ -98,8 +100,14 @@ const t: QueueDockProps['t'] = makeTranslate(zh, commonZh) const usePanelInfo: GlobalStandardProps['usePanelInfo'] = selector => selector({ activePanelId: null }) function kitFor(snapshot: SessionSnapshot, injected: Partial = {}) { + const renderText = createUserTextFixture() + const renderFactorySlot: QueueDockProps['renderFactorySlot'] = (name, owner) => { + if (name !== 'conversation.user.text') throw new Error(`Unexpected queue Factory: ${name}`) + return renderText(owner as UserTextInput) + } return { sessionId: SID, + renderFactorySlot, t, usePanelInfo, useSessions: (() => { throw new Error('unused') }) as SnapshotSelectorHook, @@ -109,6 +117,7 @@ function kitFor(snapshot: SessionSnapshot, injected: Partial createSnapshotStore(new Map()), ), useWorkspaces: (() => { throw new Error('unused') }) as never, + ...allowAllAccess, useProjection: (() => undefined) as never, useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), useChat: (() => { throw new Error('unused') }) as QueueDockProps['useChat'], @@ -434,12 +443,17 @@ describe('QueueDock', () => { expect(view.queryByText('three')).toBeNull() }) - it('flattens and caps previews at 200 code points while preserving complete editable text', () => { - const text = ` before ${'🙂'.repeat(201)} after` + it('displays complete previews with compressed whitespace and CSS ellipsis while preserving editable text', () => { + const text = ` before \n ${'🙂'.repeat(201)} after` const snap = snapshotWith([row('long-preview', text)]) const source = liveSession(snap) - const view = render() - expect(view.getByText(`before ${'🙂'.repeat(193)}…`)).toBeTruthy() + const props = kitFor(snap) + const renderFactory = vi.spyOn(props, 'renderFactorySlot') + const view = render() + expect(renderFactory).toHaveBeenCalledWith('conversation.user.text', { + text, facts: { collapseWhitespace: true, trimWhitespace: true }, interactive: false, ellipsis: true, + }) + expect(view.getByRole('listitem').textContent).toBe(`before ${'🙂'.repeat(201)} after`) fireEvent.click(view.getByLabelText('编辑排队消息')) expect((view.getByRole('textbox') as HTMLTextAreaElement).value).toBe(text) }) diff --git a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts index 6665284ae4..d784e37b90 100644 --- a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts +++ b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts @@ -755,7 +755,7 @@ describe('sendSession submission echo', () => { await b.runtime.dispose() }) - it('sends a subagent continuation without registering an unobservable echo', async () => { + it('echoes a subagent continuation and sends it under the echo request id', async () => { const b = await bench() const session = b.runtime.sessions.binding('s1')!.session const snapshot = session.getSnapshot() @@ -768,8 +768,11 @@ describe('sendSession submission echo', () => { }) const prompt = vi.spyOn(session, 'prompt').mockResolvedValue({ ok: true, value: { accepted: true } }) await expect(b.root.sendSession(session, '继续', [], 'queue')).resolves.toEqual({ kind: 'success' }) - expect(beginSubmission).not.toHaveBeenCalled() - expect(prompt).toHaveBeenCalledWith([{ type: 'text', text: '继续' }], 'queue', undefined) + expect(beginSubmission).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ mode: 'queue', text: '继续' })) + const echo = beginSubmission.mock.results[0] + const requestId = echo?.type === 'return' ? echo.value.requestId : undefined + expect(requestId).toEqual(expect.any(String)) + expect(prompt).toHaveBeenCalledWith([{ type: 'text', text: '继续' }], 'queue', undefined, requestId) await b.runtime.dispose() }) }) diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 7f0225ff33..00a784ac96 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -8,7 +8,7 @@ import type { SessionListState, SessionSnapshot } from '@deepseek-ai/dsh-api-ses import type { WorkspaceSnapshot, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { - bindSnapshotSelector, makeTranslate, RemoteError, sessionSnapshot as sessionFixture, + allowAllAccess, bindSnapshotSelector, makeTranslate, RemoteError, sessionSnapshot as sessionFixture, } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' @@ -223,6 +223,7 @@ function mount( useSessionStatus={useSessionStatus} useSessionRetainInfo={() => undefined} useWorkspaces={props.useWorkspaces} + {...allowAllAccess} useProjection={(() => undefined)} useInput={useInput} inputActions={inputActions} @@ -252,6 +253,7 @@ function mount( useSessionStatus={useSessionStatus} useSessionRetainInfo={() => undefined} useWorkspaces={props.useWorkspaces} + {...allowAllAccess} useProjection={(() => undefined)} useInput={useInput} inputActions={inputActions} @@ -279,6 +281,7 @@ function mount( useSessionStatus={useSessionStatus} useSessionRetainInfo={() => undefined} useWorkspaces={props.useWorkspaces} + {...allowAllAccess} useProjection={(() => undefined)} useInput={useInput} inputActions={inputActions} @@ -337,6 +340,7 @@ function mount( useSessionStatus, useSessionRetainInfo: () => undefined, useWorkspaces: bindSnapshotSelector(workspaces), + ...allowAllAccess, useProjection: (() => undefined), useComposerBlock: select => select(options.composerBlock), useInput, @@ -367,6 +371,7 @@ function mount( useSessionRetainInfo: () => undefined, useResource, useWorkspaces: bindSnapshotSelector(workspaces), + ...allowAllAccess, useProjection: (() => undefined), useInput, inputActions, diff --git a/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx b/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx new file mode 100644 index 0000000000..8a475bc33d --- /dev/null +++ b/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx @@ -0,0 +1,69 @@ +/** Production UserText assembly for component units that supply their own outer Slot seats. */ +import { Context } from '@deepseek-ai/cordis' +import { createElement, type ComponentProps, type ReactNode } from 'react' +import { onTestFinished } from 'vitest' +import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' +import type { UserTextInput, UserTextNodeOwnerProps } from '../src/client/contract/slots.ts' +import type { UserTextNode } from '../src/client/contract/user-text.ts' +import { UserTextRegistry } from '../src/client/conversation/user-text-registry.ts' +import { UserText, PlainUserText, SessionReference } from '../src/client/user-text/UserText.tsx' +import { sessionReferenceRule } from '../src/client/user-text/session-reference-rule.ts' +import { collapseWhitespaceRule, trimWhitespaceRule } from '../src/client/user-text/whitespace-rules.ts' +import { skillReferenceRule } from '../../ui-skill/src/client/user-text-rules.ts' +import { SkillReference } from '../../ui-skill/src/client/SkillReference.tsx' +import { fileReferenceRule, folderReferenceRule } from '../../ui-reference/src/client/user-text-rules.ts' +import { FileReference, FolderReference } from '../../ui-reference/src/client/FileReference.tsx' +import { zh as referenceZh } from '../../ui-reference/src/client/locales.ts' +import { goalCommandReferenceRule } from '../../ui-goal/src/client/user-text-rules.ts' +import { GoalCommandReference } from '../../ui-goal/src/client/GoalCommandReference.tsx' + +/** Actions supplied by the unit's business-injection fixture, not by UserText owner data. */ +interface UserTextFixtureActions { + openFile?: (path: string) => void + openSkill?: (name: string) => void +} + +type UserTextProps = ComponentProps + +/** + * Bind the production evaluator and node components without replacing matching or display behavior. + * Integration tests install the actual Slot registrations separately. + * @param actions - reference operations owned by the surrounding test fixture. + * @returns renderer accepting the production Factory's input fields. + */ +export function createUserTextFixture(actions: UserTextFixtureActions = {}): (input: UserTextInput) => ReactNode { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const registry = new UserTextRegistry(ctx) + for (const rule of [ + sessionReferenceRule, skillReferenceRule, fileReferenceRule, folderReferenceRule, + goalCommandReferenceRule, collapseWhitespaceRule, trimWhitespaceRule, + ]) registry.register(rule) + const useUserTextRevision = bindSnapshotSelector({ + getSnapshot: () => registry.getSnapshot(), + subscribe: listener => registry.subscribe(listener), + }) + const createUserTextEvaluator = () => registry.createEvaluator() + const reportTransformFailure = (error: unknown): never => { throw error } + const openFile = actions.openFile ?? (() => { throw new Error('This fixture has no file navigation action') }) + const openSkill = actions.openSkill ?? (() => { throw new Error('This fixture has no skill navigation action') }) + const t = makeTranslate(referenceZh, commonZh) + const renderSlot: UserTextProps['renderSlot'] = (name: string, input: object, options?: { fallback?: ReactNode }) => { + if (name !== 'conversation.user.text.node') throw new Error(`Unexpected UserText Slot: ${name}`) + const owner = input as UserTextNodeOwnerProps & { node: UserTextNode } + switch (owner.node.id) { + // The production components only read these owner, action and locale seats in these units. + case 'text': return createElement(PlainUserText, owner as ComponentProps) + case 'session': return createElement(SessionReference, owner as ComponentProps) + case 'file': return createElement(FileReference, { ...owner, openFile, t } as ComponentProps) + case 'folder': return createElement(FolderReference, owner as ComponentProps) + case 'skill': return createElement(SkillReference, { ...owner, openSkill } as ComponentProps) + case 'command': return createElement(GoalCommandReference, owner as ComponentProps) + default: return options?.fallback ?? null + } + } + return input => createElement(UserText, { + ...input, useUserTextRevision, createUserTextEvaluator, reportTransformFailure, renderSlot, + } as UserTextProps) +} diff --git a/packages/client/ui-conversation/tests/user-text-reference-composition.client.spec.ts b/packages/client/ui-conversation/tests/user-text-reference-composition.client.spec.ts new file mode 100644 index 0000000000..ec34939582 --- /dev/null +++ b/packages/client/ui-conversation/tests/user-text-reference-composition.client.spec.ts @@ -0,0 +1,112 @@ +/** Real business matchers compose by original position through the data-layer scheduler. */ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import type { UserTextFacts, UserTextRule, UserTextNode, UserTextTransformContext } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { UserTextRegistry } from '../src/client/conversation/user-text-registry.ts' +import { sessionReferenceRule } from '../src/client/user-text/session-reference-rule.ts' +import { fileReferenceRule, folderReferenceRule } from '../../ui-reference/src/client/user-text-rules.ts' +import { skillReferenceRule } from '../../ui-skill/src/client/user-text-rules.ts' +import { goalCommandReferenceRule } from '../../ui-goal/src/client/user-text-rules.ts' + +const RULES = [sessionReferenceRule, fileReferenceRule, folderReferenceRule, skillReferenceRule, goalCommandReferenceRule] + +function setup() { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const registry = new UserTextRegistry(ctx) + const matches = RULES.map((rule) => { + const match = vi.fn((text: string, from: number, context: UserTextTransformContext) => rule.match(text, from, context)) + registry.register({ ...rule, match } satisfies UserTextRule) + return { id: rule.id, match } + }) + return { registry, evaluate: registry.createEvaluator(), matches } +} + +function references(text: string, nodes: readonly UserTextNode[]) { + return nodes.filter(node => node.id !== 'text').map(node => [node.id, text.slice(node.start, node.end), node.data]) +} + +describe('original-text reference competition', () => { + it('keeps an earlier complete file instead of a Session label inside its path', () => { + const { evaluate } = setup() + const text = '参照 @types 修复 @src/@types/react/index.d.ts' + expect(references(text, evaluate({ text, facts: { sessionLabels: ['types'] } }))).toEqual([ + ['session', '@types', { label: 'types' }], + ['file', '@src/@types/react/index.d.ts', { path: 'src/@types/react/index.d.ts', label: 'index.d.ts' }], + ]) + }) + + it('keeps an earlier complete file instead of a wire Session inside its path', () => { + const { evaluate } = setup() + const text = '@src/@[会话一](dsh-session:x)' + expect(references(text, evaluate({ text, facts: {} }))).toEqual([ + ['file', text, { path: 'src/@[会话一](dsh-session:x)', label: '@[会话一](dsh-session:x)' }], + ]) + }) + + it('keeps the quoted file and only recognizes the outside skill', () => { + const { evaluate } = setup() + const text = '/review @"docs /review notes.md"' + expect(references(text, evaluate({ text, facts: { skillNames: ['review'] } }))).toEqual([ + ['skill', '/review', { name: 'review' }], + ['file', '@"docs /review notes.md"', { path: 'docs /review notes.md', label: 'review notes.md' }], + ]) + }) + + it.each([ + ['@会话一@src/a.ts', '@src/a.ts'], ['@会话一/plan', '/plan'], + ])('does not turn the suffix into an original word boundary in %s', (text, tail) => { + const { evaluate } = setup() + expect(evaluate({ text, facts: { sessionLabels: ['会话一'], skillNames: ['plan'] } })).toEqual([ + { id: 'session', start: 0, end: 4, data: { label: '会话一' } }, + { id: 'text', start: 4, end: text.length, data: { text: tail } }, + ]) + }) + + it('preserves real whitespace boundaries and stable same-start Session precedence', () => { + const { evaluate } = setup() + const facts = { sessionLabels: ['会话一', 'types'], skillNames: ['plan'] } + const text = '@会话一 @src/a.ts /plan' + expect(references(text, evaluate({ text, facts }))).toEqual([ + ['session', '@会话一', { label: '会话一' }], ['file', '@src/a.ts', { path: 'src/a.ts', label: 'a.ts' }], + ['skill', '/plan', { name: 'plan' }], + ]) + expect(evaluate({ text: '@types/react/index.d.ts', facts })).toEqual([ + { id: 'session', start: 0, end: 6, data: { label: 'types' } }, + { id: 'text', start: 6, end: 23, data: { text: '/react/index.d.ts' } }, + ]) + }) + + it('queries only Skill after its Facts update, reusing file, folder, Session and command searches', () => { + const { evaluate, matches, registry } = setup() + const text = '/review @"docs /review notes.md"' + const before = evaluate({ text, facts: {} }) + for (const { match } of matches) match.mockClear() + const facts = { skillNames: ['review'] } + const after = evaluate({ text, facts }) + for (const { id, match } of matches) { + expect(match.mock.calls.map(([, from]) => from)).toEqual(id === 'skill' ? [0, 7, text.length] : []) + } + expect(after.find(node => node.id === 'file')).toBe(before.find(node => node.id === 'file')) + expect(after).toEqual(registry.createEvaluator()({ text, facts })) + }) + + it('matches a new evaluator through additions and withdrawals of multiple business Facts', () => { + const { evaluate, registry } = setup() + const texts = [ + '🙂 @会话一 @src/@types/react/index.d.ts /review @docs/', + '/review @"docs /review notes.md" @types/react/index.d.ts', + '@会话一@src/a.ts @会话一/plan @src/@[会话一](dsh-session:x)', + '@多词 /review @src/a.ts /goal', + ] + const factsList: readonly Partial[] = [ + {}, { sessionLabels: ['会话一', 'types'] }, { skillNames: ['review', 'plan'] }, + { sessionLabels: ['会话一', 'types'], skillNames: ['review', 'plan'] }, + { sessionLabels: ['多词 /review', '会话一'], skillNames: ['review'], commands: [{ start: 0, end: 7, name: 'review' }] }, + {}, + ] + for (const text of texts) for (const facts of factsList) { + expect(evaluate({ text, facts })).toEqual(registry.createEvaluator()({ text, facts })) + } + }) +}) diff --git a/packages/client/ui-conversation/tests/user-text-registry.client.spec.ts b/packages/client/ui-conversation/tests/user-text-registry.client.spec.ts new file mode 100644 index 0000000000..0685f7db45 --- /dev/null +++ b/packages/client/ui-conversation/tests/user-text-registry.client.spec.ts @@ -0,0 +1,311 @@ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, expectTypeOf, it, onTestFinished, vi } from 'vitest' +import type { + UserTextDataMap, UserTextEvaluator, UserTextNode, UserTextRule, +} from '@deepseek-ai/dsh-client-ui-conversation/client' +import { UserTextRegistry } from '../src/client/conversation/user-text-registry.ts' + +type JsonValue = string | number | null | readonly string[] | { readonly value: string } + +interface AnnotationData { + readonly label: string + readonly nested?: { readonly values: readonly (string | number | boolean | null)[] } +} + +declare module '@deepseek-ai/dsh-client-ui-conversation/client' { + interface UserTextDataMap { + 'test.annotation': AnnotationData + 'test.json': { readonly value: JsonValue } + 'test.A': { readonly label: string } + 'test.a': { readonly label: string } + 'test.z': { readonly label: string } + '': { readonly label: string } + 'test.function': { readonly callback: () => void } + 'test.date': { readonly date: Date } + 'test.map': { readonly map: Map } + 'test.symbol': { readonly symbol: symbol } + 'test.bigint': { readonly bigint: bigint } + 'test.unknown': { readonly value: unknown } + 'test.nested': { readonly values: readonly { readonly action: () => void }[] } + } + interface UserTextFacts { + readonly testEnabled: boolean + readonly testLabel: string + readonly testNested: NonNullable + readonly testOther: number + readonly testJson: JsonValue + readonly skillNames: readonly string[] + } +} + +declare module '@deepseek-ai/cordis' { + interface Context { userTextTestRegistry: UserTextRegistry } +} + +function setup(): { ctx: Context; registry: UserTextRegistry } { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + return { ctx, registry: new UserTextRegistry(ctx) } +} + +type TestId = 'test.A' | 'test.a' | 'test.z' | '' + +function plain(text: string, start = 0): UserTextNode<'text'> { + return { id: 'text', start, end: start + text.length, data: { text } } +} + +function rule(id: TestId, order: number, needle: string): UserTextRule { + return { id, order, match(text, from) { + const start = text.indexOf(needle, from) + return start < 0 ? undefined : { id, start, end: start + needle.length, data: { label: id } } + } } +} + +function assertCoverage(text: string, nodes: readonly UserTextNode[]): void { + let cursor = 0 + for (const node of nodes) { + expect(node.start).toBe(cursor) + expect(node.end).toBeGreaterThan(node.start) + if (node.id === 'text') expect(node.data.text).toBe(text.slice(node.start, node.end)) + cursor = node.end + } + expect(cursor).toBe(text.length) + expect(JSON.parse(JSON.stringify(nodes))).toEqual(nodes) +} + +describe('UserTextRegistry candidate rules', () => { + it('queries every matcher for empty and nonempty original text', () => { + const { registry } = setup() + const match = vi.fn((_text: string, _from: number) => undefined) + registry.register({ id: 'test.a', order: 0, match }) + const evaluate = registry.createEvaluator() + expectTypeOf(evaluate).toEqualTypeOf() + expect(evaluate({ text: '', facts: {} })).toEqual([]) + const text = ' 原文\r\n\t🙂e\u0301 /path @name ' + const nodes = evaluate({ text, facts: {} }) + expect(nodes).toEqual([plain(text)]) + expect(match.mock.calls.map(([text, from]) => [text, from])).toEqual([['', 0], [text, 0]]) + assertCoverage(text, nodes) + }) + + it.each([ + [rule('test.a', 10, 'bc'), rule('test.z', -1, 'cde'), 'test.a'], + [rule('test.a', -1, 'bc'), rule('test.z', 0, 'bcde'), 'test.a'], + [rule('test.a', 0, 'bc'), rule('test.z', 0, 'bcde'), 'test.a'], + [rule('test.A', 0, 'bc'), rule('test.a', 0, 'bcde'), 'test.A'], + ] as const)('selects by start, then order and code-unit ID independently of load order (%j, %j)', (a, z, id) => { + const { registry: forward } = setup() + const { registry: reverse } = setup() + forward.register(a) + forward.register(z) + reverse.register(z) + reverse.register(a) + const input = { text: 'abcde', facts: {} } + const nodes = forward.createEvaluator()(input) + expect(nodes.filter(node => node.id !== 'text').map(node => node.id)).toEqual([id]) + expect(reverse.createEvaluator()(input)).toEqual(nodes) + }) + + it('has one candidate interface for business and Text nodes', () => { + expectTypeOf().not.toHaveProperty('phase') + expectTypeOf().not.toHaveProperty('transform') + expectTypeOf[0]>().toEqualTypeOf() + expectTypeOf[1]>().toEqualTypeOf() + const { registry } = setup() + registry.register({ id: 'text.replacement', order: 10, match: (text, from) => from > 1 ? undefined : { + id: 'text', start: 1, end: 2, data: { text: text.slice(1, 2), display: 'B' }, + } }) + const nodes = registry.createEvaluator()({ text: 'abc', facts: {} }) + expect(nodes).toEqual([plain('a'), { ...plain('b', 1), data: { text: 'b', display: 'B' } }, plain('c', 2)]) + assertCoverage('abc', nodes) + }) + + it.each(['xyz', '', 'ab'])('rejects a Text candidate whose raw value is %j for the original abc', (raw) => { + const { registry } = setup() + registry.register({ id: 'text.bad', order: 0, match: () => ({ id: 'text', start: 0, end: 3, data: { text: raw, display: 'abc' } }) }) + expect(() => registry.createEvaluator()({ text: 'abc', facts: {} })).toThrow(/text.bad/) + }) + + it('keeps nodes readonly without freezing borrowed payloads', () => { + expectTypeOf>().toEqualTypeOf>>() + expectTypeOf['data']>().toEqualTypeOf<{ readonly text: string; readonly display?: string }>() + const { registry } = setup() + const nested = { values: ['borrowed'] } + const definition: UserTextRule<'test.annotation'> = { + id: 'test.annotation', order: 0, + match: (_text, from, context) => { + if (from > 0) return undefined + const value = context.read('testNested') + if (value === undefined) throw new Error('Missing test payload') + return { id: 'test.annotation', start: 0, end: 1, data: { label: 'x', nested: value } } + }, + } + registry.register(definition) + const nodes = registry.createEvaluator()({ text: 'x', facts: { testNested: nested } }) + if (nodes[0]?.id !== 'test.annotation') throw new Error('Missing annotation') + expect(nodes[0].data.nested).toBe(nested) + for (const value of [definition, nodes, nodes[0], nested, nested.values]) expect(Object.isFrozen(value)).toBe(false) + }) + + it('reuses equivalent nested JSON despite key order and changes only unequal payloads', () => { + const { registry } = setup() + const match = vi.fn((_text: string, from: number, context: Parameters[2]): UserTextNode<'test.annotation'> | undefined => { + if (from > 0) return undefined + const label = context.read('testLabel') ?? 'same' + const version = context.read('testOther') ?? 0 + const nested = { values: ['文字', 3, true, null] } + return { id: 'test.annotation', start: 0, end: 3, data: version % 2 ? { nested, label } : { label, nested } } + }) + registry.register({ id: 'test.annotation', order: 0, match }) + const evaluate = registry.createEvaluator() + const original = evaluate({ text: 'abc', facts: {} }) + expect(evaluate({ text: 'abc', facts: { testOther: 1 } })).toBe(original) + const changed = evaluate({ text: 'abc', facts: { testOther: 2, testLabel: 'changed' } }) + expect(changed[0]?.data).toMatchObject({ label: 'changed' }) + expect(changed).not.toBe(original) + expect(evaluate({ text: 'abc', facts: { testOther: 3, testLabel: 'changed' } })).toBe(changed) + expect(match.mock.calls.map(([, from]) => from)).toEqual([0, 3, 0, 3, 0, 3, 0, 3]) + }) + + it('distinguishes arrays, objects, null and primitive payloads while reusing equal values', () => { + const { registry } = setup() + const match = vi.fn((_text: string, from: number, context: Parameters[2]): UserTextNode<'test.json'> | undefined => { + if (from > 0) return undefined + return { id: 'test.json', start: 0, end: 1, data: { value: context.read('testJson') ?? null } } + }) + registry.register({ id: 'test.json', order: 0, match }) + const evaluate = registry.createEvaluator() + let previous = evaluate({ text: 'x', facts: { testJson: ['value'] } }) + for (const value of [{ value: 'value' }, ['value'], null, 'value', 1] satisfies JsonValue[]) { + const nodes = evaluate({ text: 'x', facts: { testJson: value } }) + expect(nodes).not.toBe(previous) + expect(nodes[0]?.data).toEqual({ value }) + expect(evaluate({ text: 'x', facts: { testJson: value } })).toBe(nodes) + previous = nodes + } + expect(match.mock.calls.map(([, from]) => from)).toEqual([0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]) + }) + + it('constrains declaration-merged JSON payloads recursively', () => { + expectTypeOf['data']>().toExtend() + expectTypeOf().not.toExtend['data']>() + expectTypeOf().not.toExtend['data']>() + expectTypeOf().not.toExtend['data']>() + expectTypeOf().not.toExtend['data']>() + expectTypeOf().not.toExtend['data']>() + expectTypeOf().not.toExtend['data']>() + expectTypeOf().not.toExtend['data']>() + }) + + it.each([ + [-1, 1], [0, 0], [2, 1], [0, 4], [0.5, 1], [0, 1.5], [NaN, 1], [0, Infinity], + ])('rejects invalid UTF-16 range [%s, %s)', (start, end) => { + const { registry } = setup() + registry.register({ id: 'test.a', order: 0, match: () => ({ id: 'test.a', start, end, data: { label: 'bad' } }) }) + expect(() => registry.createEvaluator()({ text: 'abc', facts: {} })).toThrow(/test\.a/) + }) + + it.each([Infinity, -Infinity, NaN])('rejects invalid order %s before publication', (order) => { + const { registry } = setup() + const revision = registry.getSnapshot() + const listener = vi.fn() + registry.subscribe(listener) + expect(() => registry.register(rule('test.a', order, 'x'))).toThrow(/test\.a/) + expect(registry.getSnapshot()).toBe(revision) + expect(listener).not.toHaveBeenCalled() + }) + + it('rejects empty, reserved and duplicate IDs without changing revision', () => { + const { registry } = setup() + registry.register(rule('test.a', 0, 'x')) + const revision = registry.getSnapshot() + expect(() => registry.register(rule('', 0, 'x'))).toThrow(/id|ID/) + expect(() => registry.register({ id: 'text', order: 0, match: () => undefined })).toThrow(/text/) + expect(() => registry.register(rule('test.a', 1, 'x'))).toThrow(/test\.a/) + expect(registry.getSnapshot()).toBe(revision) + }) + + it('publishes monotonic revisions and evaluates current rules without document subscriptions', () => { + const { registry } = setup() + const subscribe = vi.spyOn(registry, 'subscribe') + const evaluate = registry.createEvaluator() + expect(subscribe).not.toHaveBeenCalled() + const revision = registry.getSnapshot() + expectTypeOf(revision).toEqualTypeOf() + const seen: number[] = [] + const unsubscribe = registry.subscribe(() => { seen.push(registry.getSnapshot()) }) + const dispose = registry.register(rule('test.a', 0, 'a')) + expect(registry.getSnapshot()).toBeGreaterThan(revision) + const input = { text: 'abc', facts: {} } + expect(evaluate(input)[0]?.id).toBe('test.a') + dispose() + expect(evaluate(input)).toEqual([plain('abc')]) + expect(seen[1]).toBeGreaterThan(seen[0]!) + dispose() + expect(seen).toHaveLength(2) + unsubscribe() + unsubscribe() + registry.register(rule('test.a', 0, 'b')) + dispose() + expect(evaluate(input)[1]?.id).toBe('test.a') + expect(seen).toHaveLength(2) + }) + + it('removes only the contributing fiber rules and cleans root registrations on disposal', async () => { + const { ctx, registry } = setup() + ctx.provide('userTextTestRegistry', registry) + registry.register(rule('test.a', 0, 'a')) + const feature = ctx.inject(['userTextTestRegistry'], (featureCtx) => { + featureCtx.userTextTestRegistry.register(rule('test.z', 0, 'b')) + }) + await feature.await() + const evaluate = registry.createEvaluator() + expect(evaluate({ text: 'ab', facts: {} }).map(node => node.id)).toEqual(['test.a', 'test.z']) + await feature.dispose() + expect(evaluate({ text: 'ab', facts: {} }).map(node => node.id)).toEqual(['test.a', 'text']) + await ctx.fiber.dispose() + expect(evaluate({ text: 'ab', facts: {} })).toEqual([plain('ab')]) + }) +}) + +describe('sessionReferenceRule', () => { + it('folds wire syntax to JSON label data while retaining the full original range', async () => { + const { sessionReferenceRule } = await import('../src/client/user-text/session-reference-rule.ts') + const { registry } = setup() + registry.register(sessionReferenceRule) + const wire = '@[查看并分析图片](dsh-session:InNlc3Npb24tNDM0)' + const text = `看看 ${wire} 的结论` + const nodes = registry.createEvaluator()({ text, facts: {} }) + expect(nodes).toEqual([ + plain('看看 '), { id: 'session', start: 3, end: 3 + wire.length, data: { label: '查看并分析图片' } }, + plain(' 的结论', 3 + wire.length), + ]) + assertCoverage(text, nodes) + }) + + it('uses exact supplied labels, keeps the longest spelling and preserves repeated occurrences', async () => { + const { sessionReferenceRule } = await import('../src/client/user-text/session-reference-rule.ts') + const { registry } = setup() + registry.register(sessionReferenceRule) + const evaluate = registry.createEvaluator() + const text = '@会话一 收尾 @会话一, @会话 @未知' + const nodes = evaluate({ text, facts: { sessionLabels: ['会话', '会话一', '会话一'] } }) + expect(nodes.filter(node => node.id === 'session').map(node => ({ raw: text.slice(node.start, node.end), data: node.data }))) + .toEqual([ + { raw: '@会话一', data: { label: '会话一' } }, { raw: '@会话一', data: { label: '会话一' } }, + { raw: '@会话', data: { label: '会话' } }, + ]) + assertCoverage(text, nodes) + expect(evaluate({ text: '@会话', facts: {} })).toEqual([plain('@会话')]) + }) + + it('prefers complete wire syntax over an overlapping supplied label', async () => { + const { sessionReferenceRule } = await import('../src/client/user-text/session-reference-rule.ts') + const { registry } = setup() + registry.register(sessionReferenceRule) + const text = '@[a](dsh-session:x)' + expect(registry.createEvaluator()({ text, facts: { sessionLabels: ['[a]'] } })).toEqual([ + { id: 'session', start: 0, end: text.length, data: { label: 'a' } }, + ]) + }) +}) diff --git a/packages/client/ui-conversation/tests/user-text-scheduling.client.spec.ts b/packages/client/ui-conversation/tests/user-text-scheduling.client.spec.ts new file mode 100644 index 0000000000..bc2d2bdd90 --- /dev/null +++ b/packages/client/ui-conversation/tests/user-text-scheduling.client.spec.ts @@ -0,0 +1,435 @@ +/** Candidate scheduling is measured by calls and query offsets, never clocks. */ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import type { + UserTextFacts, UserTextRule, UserTextNode, UserTextTransformContext, +} from '@deepseek-ai/dsh-client-ui-conversation/client' +import { UserTextRegistry } from '../src/client/conversation/user-text-registry.ts' + +interface Range { readonly start: number; readonly end: number; readonly label: string } +type Id = 'schedule.a' | 'schedule.b' | 'schedule.c' +type Field = 'scheduleA' | 'scheduleB' | 'scheduleC' + +declare module '@deepseek-ai/dsh-client-ui-conversation/client' { + interface UserTextDataMap { + 'schedule.a': { readonly label: string } + 'schedule.b': { readonly label: string } + 'schedule.c': { readonly label: string } + } + interface UserTextFacts { + readonly scheduleA: readonly Range[] + readonly scheduleB: readonly Range[] + readonly scheduleC: readonly Range[] + readonly scheduleEnabled: boolean + readonly scheduleOther: number + } +} + +const TEXT = '0123456789'.repeat(4) +const range = (start: number, end: number, label = `${start}:${end}`): Range => ({ start, end, label }) + +function setup(rules: readonly UserTextRule[] = []) { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const registry = new UserTextRegistry(ctx) + for (const rule of rules) registry.register(rule) + return { registry, evaluate: registry.createEvaluator() } +} + +function tracked(id: Id, field: Field, order: number) { + const match = vi.fn((text: string, from: number, context: UserTextTransformContext): UserTextNode | undefined => { + expect(text).toBe(TEXT) + const candidates = context.read(field) ?? [] + let best: Range | undefined + for (const item of candidates) { + if (item.start >= from && (best === undefined || item.start < best.start + || (item.start === best.start && item.end > best.end))) best = item + } + return best === undefined ? undefined : { id, start: best.start, end: best.end, data: { label: best.label } } + }) + const rule: UserTextRule = { id, order, match } + return { rule, match, calls: () => match.mock.calls.map(([, from]) => from) } +} + +function kit() { + const a = tracked('schedule.a', 'scheduleA', 0) + const b = tracked('schedule.b', 'scheduleB', 1) + const c = tracked('schedule.c', 'scheduleC', 2) + const fixture = setup([c.rule, b.rule, a.rule]) + const evaluate = (facts: Readonly>) => fixture.evaluate({ text: TEXT, facts }) + const clear = () => { a.match.mockClear(); b.match.mockClear(); c.match.mockClear() } + return { ...fixture, a, b, c, evaluate, clear } +} + +function business(nodes: readonly UserTextNode[]) { + return nodes.filter(node => node.id !== 'text').map(node => [node.id, node.start, node.end, node.data]) +} + +function coverage(nodes: readonly UserTextNode[], text = TEXT) { + let cursor = 0 + for (const node of nodes) { + expect(node.start).toBe(cursor) + expect(node.end).toBeGreaterThan(cursor) + if (node.id === 'text') expect(node.data.text).toBe(text.slice(node.start, node.end)) + cursor = node.end + } + expect(cursor).toBe(text.length) + expect(JSON.parse(JSON.stringify(nodes))).toEqual(nodes) +} + +describe('UserText candidate scheduling', () => { + it('keeps future candidates and exhausted matchers while advancing only consumed heads', () => { + const k = kit() + const nodes = k.evaluate({ scheduleA: [range(2, 4), range(12, 15)], scheduleB: [range(7, 9), range(18, 20)] }) + expect(k.a.calls()).toEqual([0, 4, 15]) + expect(k.b.calls()).toEqual([0, 9, 20]) + expect(k.c.calls()).toEqual([0]) + expect(nodes.filter(node => node.id !== 'text').map(node => node.start)).toEqual([2, 7, 12, 18]) + coverage(nodes) + }) + + it('queries overlapping heads at the winner end, without enumerating covered candidates', () => { + const k = kit() + const nodes = k.evaluate({ scheduleA: [range(2, 10)], scheduleB: [range(4, 6), range(8, 9), range(12, 14)] }) + expect(k.a.calls()).toEqual([0, 10]) + expect(k.b.calls()).toEqual([0, 10, 14]) + expect(k.c.calls()).toEqual([0]) + expect(nodes.filter(node => node.id !== 'text').map(node => [node.id, node.start])).toEqual([ + ['schedule.a', 2], ['schedule.b', 12], + ]) + coverage(nodes) + }) + + it('retains a candidate exactly at the new cursor and queries once at a consumed text end', () => { + const k = kit() + k.evaluate({ scheduleA: [range(0, 4)], scheduleB: [range(4, TEXT.length)] }) + expect(k.a.calls()).toEqual([0, 4]) + expect(k.b.calls()).toEqual([0, TEXT.length]) + expect(k.c.calls()).toEqual([0]) + }) + + it.each(['', 'plain'])('initializes Facts-free matchers even for %j', (text) => { + const a = vi.fn((_text: string, _from: number) => undefined) + const b = vi.fn((_text: string, _from: number) => undefined) + const { evaluate } = setup([{ id: 'schedule.a', order: 0, match: a }, { id: 'schedule.b', order: 1, match: b }]) + const first = evaluate({ text, facts: {} }) + expect(a.mock.calls.map(([, from]) => from)).toEqual([0]) + expect(b.mock.calls.map(([, from]) => from)).toEqual([0]) + expect(evaluate({ text, facts: { scheduleOther: 1 } })).toBe(first) + expect(a).toHaveBeenCalledOnce() + expect(b).toHaveBeenCalledOnce() + coverage(first, text) + }) + + it('ignores unrelated fields and outer Facts identity without querying any matcher', () => { + const k = kit() + const facts = { scheduleA: [range(2, 4)], scheduleB: [range(7, 9)] } + const before = k.evaluate(facts) + k.clear() + expect(k.evaluate({ ...facts, scheduleOther: 1 })).toBe(before) + expect(k.evaluate({ ...facts, scheduleOther: 2 })).toBe(before) + expect([k.a.calls(), k.b.calls(), k.c.calls()]).toEqual([[], [], []]) + }) + + it('replays only one changed matcher and retains equivalent output identities', () => { + const k = kit() + const facts = { scheduleA: [range(2, 4), range(12, 15)], scheduleB: [range(7, 9), range(18, 20)] } + const before = k.evaluate(facts) + k.clear() + const after = k.evaluate({ ...facts, scheduleA: facts.scheduleA.map(item => ({ ...item })) }) + expect(after).toBe(before) + expect(k.a.calls()).toEqual([0, 4, 15]) + expect(k.b.calls()).toEqual([]) + expect(k.c.calls()).toEqual([]) + }) + + it('changes one payload without calling other matchers or replacing unrelated nodes', () => { + const k = kit() + const facts = { scheduleA: [range(2, 4)], scheduleB: [range(7, 9)] } + const before = k.evaluate(facts) + k.clear() + const after = k.evaluate({ ...facts, scheduleA: [range(2, 4, 'new')] }) + expect(after[1]?.data).toEqual({ label: 'new' }) + expect(after[1]).not.toBe(before[1]) + for (const index of [0, 2, 3, 4]) expect(after[index]).toBe(before[index]) + expect([k.a.calls(), k.b.calls(), k.c.calls()]).toEqual([[0, 4], [], []]) + }) + + it('inserts into old plain text without querying unaffected matchers', () => { + const k = kit() + const facts = { scheduleA: [range(2, 4), range(12, 15)], scheduleB: [range(7, 9), range(18, 20)] } + const before = k.evaluate(facts) + k.clear() + const next = { ...facts, scheduleA: [range(2, 4), range(5, 6), range(12, 15)] } + const after = k.evaluate(next) + expect([k.a.calls(), k.b.calls(), k.c.calls()]).toEqual([[0, 4, 6, 15], [], []]) + for (const node of before.filter(node => node.id === 'schedule.b')) expect(after).toContain(node) + expect(after).toEqual(k.registry.createEvaluator()({ text: TEXT, facts: next })) + coverage(after) + }) + + it('rejects refreshed candidates covered by an unchanged earlier winner without querying that winner', () => { + const k = kit() + const facts = { scheduleA: [range(0, 10)], scheduleB: [] } + const before = k.evaluate(facts) + k.clear() + expect(k.evaluate({ ...facts, scheduleB: [range(4, 6)] })).toBe(before) + expect([k.a.calls(), k.b.calls(), k.c.calls()]).toEqual([[], [0, 10], []]) + }) + + it('queries only an uncovered offset when a refreshed winner extends across another head', () => { + const k = kit() + const facts = { scheduleA: [range(2, 4), range(12, 15)], scheduleB: [range(7, 9), range(18, 20)] } + const before = k.evaluate(facts) + k.clear() + const next = { ...facts, scheduleA: [range(2, 8), range(12, 15)] } + const after = k.evaluate(next) + expect([k.a.calls(), k.b.calls(), k.c.calls()]).toEqual([[0, 8, 15], [8], []]) + expect(after.filter(node => node.id === 'schedule.b').map(node => node.start)).toEqual([18]) + expect(after).toEqual(k.registry.createEvaluator()({ text: TEXT, facts: next })) + k.clear() + expect(k.evaluate(facts)).toEqual(before) + expect(k.b.calls()).toEqual([]) + expect(k.c.calls()).toEqual([]) + }) + + it.each(['remove', 'shrink'] as const)('exposes cached losers and unsearched gaps when a winner changes: %s', (action) => { + const k = kit() + const facts = { + scheduleA: [range(0, 10)], scheduleB: [range(2, 3), range(5, 6), range(12, 14)], scheduleC: [range(4, 5)], + } + k.evaluate(facts) + expect(k.b.calls()).toEqual([0, 10, 14]) + expect(k.c.calls()).toEqual([0, 10]) + k.clear() + const next = { ...facts, scheduleA: action === 'remove' ? [] : [range(0, 2)] } + const after = k.evaluate(next) + expect(k.a.calls()).toEqual(action === 'remove' ? [0] : [0, 2]) + expect(k.b.calls()).toEqual([3, 6]) + expect(k.c.calls()).toEqual([5]) + expect(after.filter(node => node.id === 'schedule.b').map(node => node.start)).toEqual([2, 5, 12]) + expect(after).toEqual(k.registry.createEvaluator()({ text: TEXT, facts: next })) + k.clear() + k.evaluate(facts) + k.clear() + k.evaluate(next) + expect(k.b.calls()).toEqual([]) + expect(k.c.calls()).toEqual([]) + coverage(after) + }) + + it('removes an old early winner even when the new first candidate occurs much later', () => { + const k = kit() + const facts = { scheduleA: [range(2, 4), range(12, 15)], scheduleB: [range(7, 9)] } + k.evaluate(facts) + k.clear() + const next = { ...facts, scheduleA: [range(12, 15)] } + const after = k.evaluate(next) + expect([k.a.calls(), k.b.calls(), k.c.calls()]).toEqual([[0, 15], [], []]) + expect(after[0]).toEqual({ id: 'text', start: 0, end: 7, data: { text: TEXT.slice(0, 7) } }) + expect(after).toEqual(k.registry.createEvaluator()({ text: TEXT, facts: next })) + }) + + it('reconciles two changed matchers together instead of giving update order precedence', () => { + const k = kit() + k.evaluate({ scheduleA: [range(2, 4)], scheduleB: [range(7, 9)] }) + k.clear() + const facts = { scheduleB: [range(2, 5)], scheduleA: [range(7, 10)] } + const after = k.evaluate(facts) + expect([k.a.calls(), k.b.calls(), k.c.calls()]).toEqual([[0, 10], [0, 5], []]) + expect(after.filter(node => node.id !== 'text').map(node => node.id)).toEqual(['schedule.b', 'schedule.a']) + expect(after).toEqual(k.registry.createEvaluator()({ text: TEXT, facts })) + }) + + it('refreshes a matcher once when two of its read fields change', () => { + const match = vi.fn((_text: string, _from: number, context: UserTextTransformContext) => { + context.read('scheduleA') + context.read('scheduleB') + return undefined + }) + const { evaluate } = setup([{ id: 'schedule.a', order: 0, match }]) + evaluate({ text: TEXT, facts: {} }) + match.mockClear() + evaluate({ text: TEXT, facts: { scheduleA: [], scheduleB: [] } }) + expect(match.mock.calls.map(([, from]) => from)).toEqual([0]) + }) + + it('tracks missing fields and replaces conditional dependencies when the cache generation changes', () => { + const match = vi.fn((_text: string, from: number, context: UserTextTransformContext): UserTextNode<'schedule.a'> | undefined => { + if (!context.read('scheduleEnabled')) return undefined + const item = context.read('scheduleA')?.find(item => item.start >= from) + return item === undefined ? undefined : { id: 'schedule.a', start: item.start, end: item.end, data: { label: item.label } } + }) + const { evaluate } = setup([{ id: 'schedule.a', order: 0, match }]) + evaluate({ text: TEXT, facts: {} }) + evaluate({ text: TEXT, facts: { scheduleEnabled: true } }) + const facts = { scheduleEnabled: true, scheduleA: [range(2, 4)] } + expect(business(evaluate({ text: TEXT, facts }))).toEqual([['schedule.a', 2, 4, { label: '2:4' }]]) + expect(match.mock.calls.map(([, from]) => from)).toEqual([0, 0, 0, 4]) + evaluate({ text: TEXT, facts: { ...facts, scheduleEnabled: false } }) + match.mockClear() + evaluate({ text: TEXT, facts: { scheduleEnabled: false, scheduleA: [range(8, 9)] } }) + expect(match).not.toHaveBeenCalled() + }) + + it('tracks reads of losing and no-match queries across a generation', () => { + const k = kit() + const facts = { scheduleA: [range(0, 10)], scheduleB: [range(3, 5)] } + const original = k.evaluate(facts) + k.clear() + const changed = k.evaluate({ ...facts, scheduleB: [range(12, 14)], scheduleC: [range(20, 22)] }) + expect(k.a.calls()).toEqual([]) + expect(k.b.calls()).toEqual([0, 14]) + expect(k.c.calls()).toEqual([0, 22]) + expect(changed[0]).toBe(original[0]) + expect(changed.filter(node => node.id !== 'text').map(node => node.start)).toEqual([0, 12, 20]) + }) + + it('keeps exact-offset failures cached and retries after a missing dependency appears', () => { + const cause = new Error('not ready') + const match = vi.fn((_text: string, from: number, context: UserTextTransformContext): UserTextNode<'schedule.a'> | undefined => { + if (from > 0) return undefined + if (!context.read('scheduleEnabled')) throw cause + return { id: 'schedule.a', start: 0, end: 1, data: { label: 'ready' } } + }) + const { evaluate } = setup([{ id: 'schedule.a', order: 0, match }]) + let failure: unknown + try { evaluate({ text: TEXT, facts: {} }) } catch (error) { failure = error } + expect(failure).toHaveProperty('ruleId', 'schedule.a') + expect(failure).toHaveProperty('cause', cause) + expect(() => evaluate({ text: TEXT, facts: { scheduleOther: 1 } })).toThrow(failure) + expect(match.mock.calls.map(([, from]) => from)).toEqual([0]) + match.mockClear() + expect(evaluate({ text: TEXT, facts: { scheduleEnabled: true } })[0]?.data).toEqual({ label: 'ready' }) + expect(match.mock.calls.map(([, from]) => from)).toEqual([0, 1]) + }) + + it('reuses a failed query only at its exact offset, not as a negative range answer', () => { + const a = tracked('schedule.a', 'scheduleA', 0) + const cause = new Error('offset-three failure') + const b = vi.fn((_text: string, from: number): UserTextNode<'schedule.b'> | undefined => { + if (from === 3) throw cause + return from === 0 ? { id: 'schedule.b', start: 1, end: 2, data: { label: 'hidden' } } : undefined + }) + const { evaluate } = setup([a.rule, { id: 'schedule.b', order: 1, match: b }]) + const old = { scheduleA: [range(0, 3)] } + expect(() => evaluate({ text: TEXT, facts: old })).toThrow(/schedule.b/) + expect(b.mock.calls.map(([, from]) => from)).toEqual([0, 3]) + a.match.mockClear(); b.mockClear() + const moved = evaluate({ text: TEXT, facts: { scheduleA: [range(0, 4)] } }) + expect(moved[0]?.end).toBe(4) + expect(b.mock.calls.map(([, from]) => from)).toEqual([4]) + b.mockClear() + expect(() => evaluate({ text: TEXT, facts: old })).toThrow(/schedule.b/) + expect(b).not.toHaveBeenCalled() + }) + + it('rejects a matcher that moves behind the cursor or produces another rule ID', () => { + const behind = vi.fn((_text: string, _from: number): UserTextNode<'schedule.a'> => ({ + id: 'schedule.a', start: 0, end: 1, data: { label: 'stuck' }, + })) + const first = setup([{ id: 'schedule.a', order: 0, match: behind }]) + expect(() => first.evaluate({ text: TEXT, facts: {} })).toThrow(/schedule.a/) + expect(behind.mock.calls.map(([, from]) => from)).toEqual([0, 1]) + const foreign = setup([{ id: 'schedule.a', order: 0, match: () => ({ + id: 'schedule.b', start: 0, end: 1, data: { label: 'foreign' }, + }) }]) + expect(() => foreign.evaluate({ text: TEXT, facts: {} })).toThrow(/schedule.a/) + }) + + it('closes matcher read contexts on success, throws and invalid asynchronous output', () => { + let escaped: UserTextTransformContext | undefined + const { evaluate } = setup([{ id: 'schedule.a', order: 0, match: (_text, _from, context) => { + escaped = context + if (context.read('scheduleEnabled')) throw new Error('failed') + return undefined + } }]) + evaluate({ text: TEXT, facts: {} }) + expect(() => escaped?.read('scheduleA')).toThrow(/closed/) + expect(() => evaluate({ text: TEXT, facts: { scheduleEnabled: true } })).toThrow(/schedule.a/) + expect(() => escaped?.read('scheduleA')).toThrow(/closed/) + const asyncCase = setup([{ id: 'schedule.a', order: 0, + // @ts-expect-error A matcher must return one synchronous candidate or undefined. + match: (_text, _from, context) => { escaped = context; return Promise.resolve(undefined) }, + }]) + expect(() => asyncCase.evaluate({ text: TEXT, facts: {} })).toThrow(/schedule.a/) + expect(() => escaped?.read('scheduleA')).toThrow(/closed/) + }) + + it('rejects matcher reentrancy without losing a later Facts-driven retry', () => { + const { registry, evaluate } = setup() + const match = vi.fn((_text: string, _from: number, context: UserTextTransformContext) => { + if (context.read('scheduleEnabled')) evaluate({ text: 'nested', facts: {} }) + return undefined + }) + registry.register({ id: 'schedule.a', order: 0, match }) + expect(() => evaluate({ text: TEXT, facts: { scheduleEnabled: true } })).toThrow(/schedule.a/) + expect(evaluate({ text: TEXT, facts: { scheduleEnabled: false } })).toEqual([ + { id: 'text', start: 0, end: TEXT.length, data: { text: TEXT } }, + ]) + expect(match.mock.calls.map(([, from]) => from)).toEqual([0, 0]) + }) + + it('keeps invalidated but unqueried matchers pending across an earlier failure', () => { + const first = vi.fn((_text: string, _from: number, context: UserTextTransformContext) => { + if (context.read('scheduleEnabled')) throw new Error('blocked') + return undefined + }) + const later = tracked('schedule.b', 'scheduleB', 1) + const { evaluate } = setup([{ id: 'schedule.a', order: 0, match: first }, later.rule]) + evaluate({ text: TEXT, facts: { scheduleEnabled: false, scheduleB: [range(2, 4, 'old')] } }) + later.match.mockClear() + const ranges = [range(2, 4, 'new')] + expect(() => evaluate({ text: TEXT, facts: { scheduleEnabled: true, scheduleB: ranges } })).toThrow(/schedule.a/) + expect(later.calls()).toEqual([]) + expect(() => evaluate({ text: TEXT, facts: { scheduleEnabled: true, scheduleB: ranges } })).toThrow(/schedule.a/) + expect(evaluate({ text: TEXT, facts: { scheduleEnabled: false, scheduleB: ranges } })[1]?.data).toEqual({ label: 'new' }) + expect(later.calls()).toEqual([0, 4]) + }) + + it('keeps evaluator query caches isolated and discards them on text changes', () => { + const match = vi.fn((_text: string, _from: number) => undefined) + const { registry, evaluate } = setup([{ id: 'schedule.a', order: 0, match }]) + const other = registry.createEvaluator() + const first = evaluate({ text: 'abc', facts: {} }) + expect(other({ text: 'abc', facts: {} })).not.toBe(first) + expect(match).toHaveBeenCalledTimes(2) + expect(evaluate({ text: 'abc', facts: {} })).toBe(first) + evaluate({ text: 'abcd', facts: {} }) + evaluate({ text: '', facts: {} }) + expect(match.mock.calls.map(([text, from]) => [text, from])).toEqual([['abc', 0], ['abc', 0], ['abcd', 0], ['', 0]]) + }) + + it('reuses independent caches across registration, removal and priority changes', () => { + const a = tracked('schedule.a', 'scheduleA', 0) + const b = tracked('schedule.b', 'scheduleB', 1) + const { registry, evaluate } = setup([a.rule]) + const input = { text: TEXT, facts: { scheduleA: [range(2, 4)], scheduleB: [range(2, 7)] } } + evaluate(input) + a.match.mockClear() + let remove = registry.register(b.rule) + expect(evaluate(input).filter(node => node.id !== 'text').map(node => node.id)).toEqual(['schedule.a']) + expect(a.calls()).toEqual([]) + expect(b.calls()).toEqual([0, 4]) + remove() + evaluate(input) + remove = registry.register({ ...b.rule, order: -1 }) + a.match.mockClear(); b.match.mockClear() + expect(evaluate(input).filter(node => node.id !== 'text').map(node => node.id)).toEqual(['schedule.b']) + expect(a.calls()).toEqual([]) + expect(b.calls()).toEqual([0, 7]) + remove() + expect(evaluate(input).filter(node => node.id !== 'text').map(node => node.id)).toEqual(['schedule.a']) + }) + + it('matches fresh evaluation throughout deterministic additions, removals and overlapping refreshes', () => { + const k = kit() + const variants = [[], [range(0, 10)], [range(2, 4), range(12, 15)], [range(5, 6), range(20, 25)]] + for (const scheduleA of variants) for (const scheduleB of variants) for (const scheduleC of variants) { + const facts = { scheduleA, scheduleB, scheduleC } + const nodes = k.evaluate(facts) + expect(nodes).toEqual(k.registry.createEvaluator()({ text: TEXT, facts })) + coverage(nodes) + } + }) +}) diff --git a/packages/client/ui-conversation/tests/user-text-whitespace.client.spec.ts b/packages/client/ui-conversation/tests/user-text-whitespace.client.spec.ts new file mode 100644 index 0000000000..e254e61ddb --- /dev/null +++ b/packages/client/ui-conversation/tests/user-text-whitespace.client.spec.ts @@ -0,0 +1,190 @@ +/** Whitespace is ordinary Text-producing matching, including scheduling and Facts invalidation. */ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, expectTypeOf, it, onTestFinished, vi } from 'vitest' +import type { UserTextFacts, UserTextNode, UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { UserTextRegistry } from '../src/client/conversation/user-text-registry.ts' +import { collapseWhitespaceRule, trimWhitespaceRule } from '../src/client/user-text/whitespace-rules.ts' +import { sessionReferenceRule } from '../src/client/user-text/session-reference-rule.ts' + +function setup(extra: readonly UserTextRule[] = []) { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const registry = new UserTextRegistry(ctx) + const collapse = vi.fn(collapseWhitespaceRule.match) + const trim = vi.fn(trimWhitespaceRule.match) + registry.register({ ...collapseWhitespaceRule, match: collapse }) + registry.register({ ...trimWhitespaceRule, match: trim }) + for (const rule of extra) registry.register(rule) + return { registry, evaluate: registry.createEvaluator(), collapse, trim } +} + +function visible(nodes: readonly UserTextNode[]): string { + return nodes.map(node => node.id === 'text' ? node.data.display ?? node.data.text : `[${node.id}]`).join('') +} + +function assertSource(text: string, nodes: readonly UserTextNode[]): void { + let cursor = 0 + for (const node of nodes) { + expect(node.start).toBe(cursor) + expect(node.end).toBeGreaterThan(cursor) + if (node.id === 'text') expect(node.data.text).toBe(text.slice(node.start, node.end)) + cursor = node.end + } + expect(cursor).toBe(text.length) + expect(JSON.parse(JSON.stringify(nodes))).toEqual(nodes) +} + +describe('ordinary whitespace matchers', () => { + it('uses the sole rule interface and keeps switches distinct from React props', () => { + expectTypeOf(collapseWhitespaceRule).toExtend() + expectTypeOf(trimWhitespaceRule).toExtend() + expectTypeOf().not.toHaveProperty('transform') + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf() + expectTypeOf().not.toHaveProperty('ellipsis') + expectTypeOf().not.toHaveProperty('interactive') + expect(trimWhitespaceRule.order).toBeLessThan(collapseWhitespaceRule.order) + }) + + it.each(['', ' 原文\r\n\t🙂e\u0301 '])('keeps missing switches as a cached no-match result for %j', (text) => { + const k = setup() + const original = k.evaluate({ text, facts: {} }) + expect(visible(original)).toBe(text) + expect(k.trim.mock.calls.map(([, from]) => from)).toEqual([0]) + expect(k.collapse.mock.calls.map(([, from]) => from)).toEqual([0]) + expect(k.evaluate({ text, facts: { sessionLabels: ['new'] } })).toBe(original) + expect(k.trim).toHaveBeenCalledOnce() + expect(k.collapse).toHaveBeenCalledOnce() + assertSource(text, original) + }) + + it('resolves edge collisions in favor of trim and keeps raw substrings in every Text candidate', () => { + const k = setup() + const text = ' \tA\n B \r' + const nodes = k.evaluate({ text, facts: { collapseWhitespace: true, trimWhitespace: true } }) + expect(nodes).toEqual([ + { id: 'text', start: 0, end: 2, data: { text: ' \t', display: '' } }, + { id: 'text', start: 2, end: 3, data: { text: 'A' } }, + { id: 'text', start: 3, end: 6, data: { text: '\n ', display: ' ' } }, + { id: 'text', start: 6, end: 7, data: { text: 'B' } }, + { id: 'text', start: 7, end: 9, data: { text: ' \r', display: '' } }, + ]) + expect(visible(nodes)).toBe('A B') + expect(k.trim.mock.calls.map(([, from]) => from)).toEqual([0, 2, 9]) + expect(k.collapse.mock.calls.map(([, from]) => from)).toEqual([0, 2, 6, 9]) + assertSource(text, nodes) + }) + + it('refreshes only the switch reader while reusing the competing whitespace query sequence', () => { + const k = setup() + const text = ' \tA\n B \r' + const collapseOnly = k.evaluate({ text, facts: { collapseWhitespace: true } }) + expect(visible(collapseOnly)).toBe(' A B ') + k.trim.mockClear(); k.collapse.mockClear() + const both = k.evaluate({ text, facts: { collapseWhitespace: true, trimWhitespace: true } }) + expect(visible(both)).toBe('A B') + expect(k.trim.mock.calls.map(([, from]) => from)).toEqual([0, 2, 9]) + expect(k.collapse).not.toHaveBeenCalled() + k.trim.mockClear() + expect(k.evaluate({ text, facts: { collapseWhitespace: true, trimWhitespace: false } })).toEqual(collapseOnly) + expect(k.trim.mock.calls.map(([, from]) => from)).toEqual([0]) + expect(k.collapse).not.toHaveBeenCalled() + }) + + it('lets cached collapse candidates win after trim is disabled without repeating their search', () => { + const k = setup() + const text = ' \t\n' + const original = k.evaluate({ text, facts: { collapseWhitespace: true, trimWhitespace: true } }) + expect(visible(original)).toBe('') + expect(k.trim.mock.calls.map(([, from]) => from)).toEqual([0, text.length]) + expect(k.collapse.mock.calls.map(([, from]) => from)).toEqual([0, text.length]) + k.trim.mockClear(); k.collapse.mockClear() + expect(visible(k.evaluate({ text, facts: { collapseWhitespace: true } }))).toBe(' ') + expect(k.trim.mock.calls.map(([, from]) => from)).toEqual([0]) + expect(k.collapse).not.toHaveBeenCalled() + }) + + it('keeps reference whitespace atomic through earlier-start competition, not a processing phase', () => { + const reference = vi.fn(sessionReferenceRule.match) + const k = setup([{ ...sessionReferenceRule, order: 100_000, match: reference }]) + const wire = '@[two words](dsh-session:x)' + const text = ` \t🙂甲\n ${wire} \r\n乙 \t` + const original = k.evaluate({ text, facts: {} }) + reference.mockClear() + const nodes = k.evaluate({ text, facts: { collapseWhitespace: true, trimWhitespace: true } }) + expect(visible(nodes)).toBe('🙂甲 [session] 乙') + expect(nodes.find(node => node.id === 'session')).toBe(original.find(node => node.id === 'session')) + expect(nodes.find(node => node.id === 'session')?.data).toEqual({ label: 'two words' }) + expect(reference).not.toHaveBeenCalled() + assertSource(text, nodes) + }) + + it.each([ + [' \t🙂 \n甲 👨‍👩‍👧‍👦\t 乙🇨🇳 \t', '🙂 甲 👨‍👩‍👧‍👦 乙🇨🇳'], + ['\u00a0甲\r\n乙\u3000', '甲 乙'], + ['甲 乙123', '甲 乙123'], + ['', ''], + ])('preserves emoji and collapses original whitespace in %j', (text, expected) => { + const k = setup() + const facts = { collapseWhitespace: true, trimWhitespace: true } + const nodes = k.evaluate({ text, facts }) + expect(visible(nodes)).toBe(expected) + assertSource(text, nodes) + expect(visible(k.evaluate({ text, facts: { trimWhitespace: true } }))).toBe(text.trim()) + expect(visible(k.evaluate({ text, facts: {} }))).toBe(text) + expect(k.evaluate({ text, facts })).toEqual(k.registry.createEvaluator()({ text, facts })) + }) + + it('ignores unrelated Facts without limiting long original text', () => { + const k = setup() + const text = ` ${'原文🙂\n'.repeat(100)} ` + const facts = { collapseWhitespace: true, trimWhitespace: true } + const nodes = k.evaluate({ text, facts }) + k.trim.mockClear(); k.collapse.mockClear() + expect(k.evaluate({ text, facts: { ...facts, sessionLabels: ['changed'] } })).toBe(nodes) + expect(k.trim).not.toHaveBeenCalled() + expect(k.collapse).not.toHaveBeenCalled() + assertSource(text, nodes) + }) + + it('keeps unchanged output identity when enabled matchers find no replacement', () => { + const k = setup() + const input = { text: '甲 乙123', facts: {} } + const original = k.evaluate(input) + expect(k.evaluate({ ...input, facts: { collapseWhitespace: true, trimWhitespace: true } })).toBe(original) + }) + + it.each([ + [' \n@[a](dsh-session:x) \t @[b](dsh-session:y) \t', '[session] \t [session]'], + ['@[a](dsh-session:x) \t 甲 \n @[b](dsh-session:y)', '[session] \t 甲 \n [session]'], + ['@[a](dsh-session:x) \t 甲 \n', '[session] \t 甲'], + [' \t 甲 \n @[b](dsh-session:y)', '甲 \n [session]'], + ])('does not trim through references or delete internal spacing in %s', (text, expected) => { + const k = setup([sessionReferenceRule]) + const nodes = k.evaluate({ text, facts: { trimWhitespace: true } }) + expect(visible(nodes)).toBe(expected) + assertSource(text, nodes) + }) + + it('handles long interior and trailing whitespace without changing source ranges', () => { + const k = setup() + const middle = `a${' '.repeat(80_000)}b` + expect(visible(k.evaluate({ text: middle, facts: { trimWhitespace: true } }))).toBe(middle) + expect(k.trim.mock.calls.map(([, from]) => from)).toEqual([0]) + k.trim.mockClear() + const trailing = `a${' \t\u00a0'.repeat(20_000)}` + const nodes = k.evaluate({ text: trailing, facts: { trimWhitespace: true } }) + expect(visible(nodes)).toBe('a') + expect(nodes.at(-1)).toEqual({ id: 'text', start: 1, end: trailing.length, + data: { text: trailing.slice(1), display: '' } }) + expect(k.trim.mock.calls.map(([, from]) => from)).toEqual([0, trailing.length]) + assertSource(trailing, nodes) + }) + + it('does not invent another original whitespace-run start inside a consumed run', () => { + const facts: Partial = { collapseWhitespace: true, trimWhitespace: true } + const read = (key: K) => facts[key] + expect(collapseWhitespaceRule.match(' x', 1, { read })).toBeUndefined() + expect(trimWhitespaceRule.match(' x', 1, { read })).toBeUndefined() + }) +}) diff --git a/packages/client/ui-primitives/tests/user-text.client.spec.tsx b/packages/client/ui-conversation/tests/user-text.client.spec.tsx similarity index 65% rename from packages/client/ui-primitives/tests/user-text.client.spec.tsx rename to packages/client/ui-conversation/tests/user-text.client.spec.tsx index 0068ddce56..6a19a22fb4 100644 --- a/packages/client/ui-primitives/tests/user-text.client.spec.tsx +++ b/packages/client/ui-conversation/tests/user-text.client.spec.tsx @@ -3,9 +3,32 @@ * Inline projection of sent user text: decoration adds no block containers, * preserves whitespace, and folds wire session forms to their label. */ -import { describe, expect, it, vi } from 'vitest' -import { fireEvent, render } from '@testing-library/react' -import { projectUserText } from '../src/user-text.tsx' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { cleanup, fireEvent, render } from '@testing-library/react' +import { Context } from '@deepseek-ai/cordis' +import type { ComponentProps } from 'react' +import { UserText } from '../src/client/user-text/UserText.tsx' +import { UserTextRegistry } from '../src/client/conversation/user-text-registry.ts' +import { createUserTextFixture } from './user-text-component-fixture.client.tsx' + +afterEach(cleanup) + +function textView( + text: string, + labels: readonly string[] = [], + slashNames: readonly string[] = [], + slashKind: 'skill' | 'command' = 'skill', + actions?: Parameters[0], +) { + const head = text.split(/\s/u, 1)[0] + const command = slashNames.find(name => head === `/${name}`) + const facts = { + sessionLabels: labels, + ...(slashKind === 'skill' ? { skillNames: slashNames } + : { commands: command === undefined ? [] : [{ start: 0, end: command.length + 1, name: command }] }), + } + return createUserTextFixture(actions)({ text, facts, interactive: actions !== undefined }) +} const project = ( text: string, @@ -13,9 +36,42 @@ const project = ( slashNames: readonly string[] = [], slashKind: 'skill' | 'command' = 'skill', ) => - render(
{projectUserText(text, labels, slashNames, slashKind)}
).container.querySelector('[data-host]')! + render(
{textView(text, labels, slashNames, slashKind)}
).container.querySelector('[data-host]')! + +describe('UserText projection', () => { + it('retains complete original text, reports a cached matching failure once, and recovers', () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const registry = new UserTextRegistry(ctx) + const cause = new Error('matching unavailable') + registry.register({ id: 'session', order: 0, match: (text, from, context) => { + if (from > 0) return undefined + if (context.read('sessionLabels') === undefined) throw cause + return { id: 'session', start: 0, end: text.length, data: { label: 'ready' } } + } }) + const evaluate = registry.createEvaluator() + const report = vi.fn() + const renderSlot = vi.fn(() => recognized output) + const text = ' complete /original\n@reference ' + const props = { + text, facts: {}, createUserTextEvaluator: () => evaluate, + useUserTextRevision: selector => selector(registry.getSnapshot()), + reportTransformFailure: report, renderSlot, + } satisfies Partial> + const view = render(} />) + expect(view.container.textContent).toBe(text) + expect(renderSlot).not.toHaveBeenCalled() + expect(report).toHaveBeenCalledOnce() + expect(report.mock.calls[0]?.[0]).toMatchObject({ ruleId: 'session', cause }) + view.rerender(} facts={{ collapseWhitespace: false }} />) + expect(view.container.textContent).toBe(text) + expect(report).toHaveBeenCalledOnce() + view.rerender(} facts={{ sessionLabels: ['ready'] }} />) + expect(view.getByText('recognized output')).toBeTruthy() + expect(renderSlot).toHaveBeenCalledOnce() + expect(report).toHaveBeenCalledOnce() + }) -describe('projectUserText', () => { it('keeps decorated text inline and preserves whitespace between references', () => { const host = project('反反复复 /dsh-acp-test @执行几个命令测试', ['执行几个命令测试'], ['dsh-acp-test']) expect(host.querySelectorAll('div').length).toBe(0) @@ -23,7 +79,8 @@ describe('projectUserText', () => { const chips = host.querySelectorAll('[data-ref-chip]') expect([...chips].map(c => c.getAttribute('data-ref-chip'))).toEqual(['skill', 'session']) // The whitespace between tokens survives as its own inline run. - const runs = [...host.querySelectorAll('span')].filter(s => !s.hasAttribute('data-ref-chip') && s.closest('[data-ref-chip]') === null) + const runs = [...host.querySelectorAll('span')].filter(s => + s.childElementCount === 0 && !s.hasAttribute('data-ref-chip') && s.closest('[data-ref-chip]') === null) expect(runs.map(r => r.textContent)).toEqual(['反反复复 ', ' ']) }) @@ -108,7 +165,7 @@ describe('projectUserText', () => { it('opens decoded files and loaded skills without activating session, folder, or command references', () => { const openFile = vi.fn() const openSkill = vi.fn() - const view = render(
{projectUserText( + const view = render(
{textView( '@src/a.ts @"notes a.md" /review @history @dir/ @"dir a/"', ['history'], ['review'], 'skill', { openFile, openSkill }, )}
) @@ -118,13 +175,13 @@ describe('projectUserText', () => { expect(openFile.mock.calls).toEqual([['src/a.ts'], ['notes a.md']]) expect(openSkill).toHaveBeenCalledWith('review') expect(view.container.querySelectorAll('button')).toHaveLength(3) - const command = render(
{projectUserText('/help', [], ['help'], 'command', { openFile, openSkill })}
) + const command = render(
{textView('/help', [], ['help'], 'command', { openFile, openSkill })}
) expect(command.container.querySelector('button')).toBeNull() }) it('preserves text-selection gestures and keyboard activation', () => { const openFile = vi.fn() - const view = render(
{projectUserText('@notes.md', [], [], 'skill', { openFile, openSkill: vi.fn() })}
) + const view = render(
{textView('@notes.md', [], [], 'skill', { openFile, openSkill: vi.fn() })}
) const button = view.getByRole('button', { name: 'notes.md' }) const selection = document.getSelection()! const range = document.createRange() diff --git a/packages/client/ui-conversation/tests/views-type-chain.client.spec.tsx b/packages/client/ui-conversation/tests/views-type-chain.client.spec.tsx index 0f1c0045fa..a27dfe1b78 100644 --- a/packages/client/ui-conversation/tests/views-type-chain.client.spec.tsx +++ b/packages/client/ui-conversation/tests/views-type-chain.client.spec.tsx @@ -17,11 +17,10 @@ describe('view-ring type negatives (compile-time; body never runs)', () => { { name: 'conversation.view', id: 'x', key: 'k' }, (_p: ConvViewProps) => null) // 3. Component props must stay within the composed contract: an - // undeclared member cannot be required. + // undeclared member cannot be required. The call stays on one line so + // both compilers anchor the overload failure inside the directive. // @ts-expect-error component demands a prop no share supplies - slots.register( - { name: 'conversation.view', id: 'y' }, - (_p: ConvViewProps & { phantom: number }) => null) + slots.register({ name: 'conversation.view', id: 'y' }, (_p: ConvViewProps & { phantom: number }) => null) // 4. Views receive no renderSlot — the ring's entries declare no children. const renderless = (props: ConvViewProps): ReactNode => { // @ts-expect-error views receive no renderSlot — no sub-slot delegation diff --git a/packages/client/ui-conversation/tsdown.config.ts b/packages/client/ui-conversation/tsdown.config.ts index 6ccfee9612..7aa03cebc1 100644 --- a/packages/client/ui-conversation/tsdown.config.ts +++ b/packages/client/ui-conversation/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-conversation', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-deliverables/locale/en.json b/packages/client/ui-deliverables/locale/en.json new file mode 100644 index 0000000000..109082cbc5 --- /dev/null +++ b/packages/client/ui-deliverables/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-deliverables" + } +} diff --git a/packages/client/ui-deliverables/locale/zh.json b/packages/client/ui-deliverables/locale/zh.json new file mode 100644 index 0000000000..a353e74262 --- /dev/null +++ b/packages/client/ui-deliverables/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "文件变更与交付展示", + "description": "展示修改过的文件、内容对比和交付文件入口。" + } +} diff --git a/packages/client/ui-deliverables/package.json b/packages/client/ui-deliverables/package.json index 1f3f253b10..7667fd8814 100644 --- a/packages/client/ui-deliverables/package.json +++ b/packages/client/ui-deliverables/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-deliverables", "description": "Changed-files card with per-file comparison tabs, delivery cards, and clickable final-response file references for Web", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -61,7 +62,6 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-sidebar-right": "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-primitives": "workspace:*", @@ -83,6 +83,7 @@ "@deepseek-ai/dsh-client-ui-settings": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts", diff --git a/packages/client/ui-deliverables/tests/changes-open.host.spec.ts b/packages/client/ui-deliverables/tests/changes-open.host.spec.ts index 6fda6fed4a..9921990174 100644 --- a/packages/client/ui-deliverables/tests/changes-open.host.spec.ts +++ b/packages/client/ui-deliverables/tests/changes-open.host.spec.ts @@ -69,10 +69,13 @@ async function fixture() { apply: registerPresentOpen, }) const handler = connection.createSharedFetchHandler('/api') - const open = (query = '?sessionId=owner&seq=9&index=0') => handler.fetch(new Request(`http://localhost${CHANGES_OPEN_PATH}${query}`, { method: 'POST' })) - const read = (query = '?sessionId=owner&seq=9') => handler.fetch(new Request(`http://localhost${CHANGED_FILES_PATH}${query}`)) - const compare = (query = '?sessionId=owner&seq=9&index=0') => handler.fetch(new Request(`http://localhost${CHANGES_DIFF_PATH}${query}`)) - return { handler, applications, root, cwd, ctx, data, readEvent, open, read, compare, comparison, diff, opener, outside, summary } + const open = (query = '?sessionId=owner&seq=9&index=0') => handler.fetch(new Request(`http://localhost${CHANGES_OPEN_PATH}${query}`, { method: 'POST' }), connection.browserPeer) + const read = (query = '?sessionId=owner&seq=9') => handler.fetch(new Request(`http://localhost${CHANGED_FILES_PATH}${query}`), connection.browserPeer) + const compare = (query = '?sessionId=owner&seq=9&index=0') => handler.fetch(new Request(`http://localhost${CHANGES_DIFF_PATH}${query}`), connection.browserPeer) + return { + browserPeer: connection.browserPeer, handler, applications, root, cwd, ctx, data, readEvent, open, read, compare, comparison, diff, + opener, outside, summary, + } } describe('change summary route', () => { @@ -203,17 +206,17 @@ describe('changed files native open route', () => { it('queries handlers only after file authorization and forwards explicit application choices', async () => { - const { handler, applications, opener, open, ctx } = await fixture() + const { browserPeer, handler, applications, opener, open, ctx } = await fixture() const url = 'http://localhost/api/changes.open?sessionId=owner&seq=9&index=0' - const response = await handler.fetch(new Request(url)) + const response = await handler.fetch(new Request(url), browserPeer) expect(response.status).toBe(200) expect(await response.json()).toEqual([{ id: 'player', name: 'Player', default: true, icon: null }]) expect(opener).not.toHaveBeenCalled() expect((await open('?sessionId=owner&seq=9&index=0&application=player')).status).toBe(204) expect(opener.mock.lastCall?.[0]).toMatchObject({ application: 'player' }) - expect((await handler.fetch(new Request(url.replace('index=0', 'index=999')))).status).toBe(404) + expect((await handler.fetch(new Request(url.replace('index=0', 'index=999')), browserPeer)).status).toBe(404) vi.spyOn(ctx.fs, 'processPathFromHostPath').mockReturnValue(undefined) - expect((await handler.fetch(new Request(url))).status).toBe(422) + expect((await handler.fetch(new Request(url), browserPeer)).status).toBe(422) expect(applications).toHaveBeenCalledOnce() }) diff --git a/packages/client/ui-deliverables/tests/present-open.host.spec.ts b/packages/client/ui-deliverables/tests/present-open.host.spec.ts index b313ee0aa8..6d6057d204 100644 --- a/packages/client/ui-deliverables/tests/present-open.host.spec.ts +++ b/packages/client/ui-deliverables/tests/present-open.host.spec.ts @@ -54,17 +54,19 @@ async function fixture() { const handler = connection.createSharedFetchHandler('/api') const open = (query = '?sessionId=owner&seq=7&index=0', signal?: AbortSignal) => handler.fetch(new Request( `http://localhost${PRESENT_OPEN_PATH}${query}`, { method: 'POST', signal: signal ?? null }, - )) - return { applications, root, cwd, ctx, fiber, file, session, readEvent, open, opener, handler, resolveAgent } + ), connection.browserPeer) + return { + browserPeer: connection.browserPeer, applications, root, cwd, ctx, fiber, file, session, readEvent, open, opener, handler, resolveAgent, + } } describe('Presented workspace file native open route', () => { it('opens the source itself with current bytes and leaves it intact at disposal', async () => { - const { cwd, open, file, fiber, opener, handler, ctx } = await fixture() + const { browserPeer, cwd, open, file, fiber, opener, handler, ctx } = await fixture() const source = await realpath(join(cwd, file.path)) expect(presentedFileUrl(SessionId('owner'), 7, 0)).toBe('api/present.open?sessionId=owner&seq=7&index=0') - expect((await handler.fetch(new Request(`http://localhost${PRESENT_OPEN_PATH}`))).status).toBe(400) - expect((await handler.fetch(new Request('http://localhost/api/present.download?sessionId=owner&seq=7&index=0'))).status).toBe(404) + expect((await handler.fetch(new Request(`http://localhost${PRESENT_OPEN_PATH}`), browserPeer)).status).toBe(400) + expect((await handler.fetch(new Request('http://localhost/api/present.download?sessionId=owner&seq=7&index=0'), browserPeer)).status).toBe(404) for (const contents of ['current source', 'edited source']) { await writeFile(source, contents) const response = await open() @@ -189,8 +191,8 @@ describe('Presented workspace file native open route', () => { it('reports the serving desktop and reveals only an authorized declared source', async () => { - const { cwd, file, open, opener, handler } = await fixture() - const info = await handler.fetch(new Request('http://localhost/api/present.host')) + const { browserPeer, cwd, file, open, opener, handler } = await fixture() + const info = await handler.fetch(new Request('http://localhost/api/present.host'), browserPeer) expect(await info.json()).toEqual({ name: 'desktop', available: true, fileManager: 'finder' }) expect((await open('?sessionId=owner&seq=7&index=0&action=reveal')).status).toBe(204) expect(opener).toHaveBeenCalledWith({ path: await realpath(join(cwd, file.path)), action: 'reveal' }, expect.any(AbortSignal)) @@ -201,9 +203,9 @@ it('reports the serving desktop and reveals only an authorized declared source', }) it('refuses native actions when the configured Host desktop is unavailable', async () => { - const { ctx, open, opener, handler } = await fixture() + const { browserPeer, ctx, open, opener, handler } = await fixture() vi.spyOn(ctx.sessionController, 'workspaceDesktop').mockReturnValue({ name: 'desktop', available: false, fileManager: 'finder' }) - expect(await (await handler.fetch(new Request('http://localhost/api/present.host'))).json()).toMatchObject({ available: false }) + expect(await (await handler.fetch(new Request('http://localhost/api/present.host'), browserPeer)).json()).toMatchObject({ available: false }) for (const action of ['open', 'reveal']) { expect((await open(`?sessionId=owner&seq=7&index=0&action=${action}`)).status).toBe(409) } @@ -237,16 +239,16 @@ it('uses the deployment workspace root when the viewed Session has no cwd', asyn it('queries handlers only after file authorization and forwards explicit application choices', async () => { - const { handler, applications, opener, open, ctx } = await fixture() + const { browserPeer, handler, applications, opener, open, ctx } = await fixture() const url = 'http://localhost/api/present.open?sessionId=owner&seq=7&index=0' - const response = await handler.fetch(new Request(url)) + const response = await handler.fetch(new Request(url), browserPeer) expect(response.status).toBe(200) expect(await response.json()).toEqual([{ id: 'player', name: 'Player', default: true, icon: null }]) expect(opener).not.toHaveBeenCalled() expect((await open('?sessionId=owner&seq=7&index=0&application=player')).status).toBe(204) expect(opener.mock.lastCall?.[0]).toMatchObject({ application: 'player' }) - expect((await handler.fetch(new Request(url.replace('index=0', 'index=999')))).status).toBe(404) + expect((await handler.fetch(new Request(url.replace('index=0', 'index=999')), browserPeer)).status).toBe(404) vi.spyOn(ctx.fs, 'processPathFromHostPath').mockReturnValue(undefined) - expect((await handler.fetch(new Request(url))).status).toBe(422) + expect((await handler.fetch(new Request(url), browserPeer)).status).toBe(422) expect(applications).toHaveBeenCalledOnce() }) diff --git a/packages/client/ui-deliverables/tsdown.config.ts b/packages/client/ui-deliverables/tsdown.config.ts index 51d0ff8a1e..7aa03cebc1 100644 --- a/packages/client/ui-deliverables/tsdown.config.ts +++ b/packages/client/ui-deliverables/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-deliverables', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-directory-picker-browse/locale/en.json b/packages/client/ui-directory-picker-browse/locale/en.json new file mode 100644 index 0000000000..66fe08e059 --- /dev/null +++ b/packages/client/ui-directory-picker-browse/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-directory-picker-browse" + } +} diff --git a/packages/client/ui-directory-picker-browse/locale/zh.json b/packages/client/ui-directory-picker-browse/locale/zh.json new file mode 100644 index 0000000000..8504fe7c3e --- /dev/null +++ b/packages/client/ui-directory-picker-browse/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "应用内目录选择界面", + "description": "在应用中浏览、创建并选择工作区目录。" + } +} diff --git a/packages/client/ui-directory-picker-browse/package.json b/packages/client/ui-directory-picker-browse/package.json index 0cf7f059f4..2f11a2fcea 100644 --- a/packages/client/ui-directory-picker-browse/package.json +++ b/packages/client/ui-directory-picker-browse/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-directory-picker-browse", "description": "In-app directory browsing surface: the workspace directory-flow owner rendering the host's listing and creation primitives", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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,13 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-client-ui-workspace": "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", "clsx": "^2.0.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts", diff --git a/packages/client/ui-directory-picker-browse/tsdown.config.ts b/packages/client/ui-directory-picker-browse/tsdown.config.ts index 840d57706f..7aa03cebc1 100644 --- a/packages/client/ui-directory-picker-browse/tsdown.config.ts +++ b/packages/client/ui-directory-picker-browse/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-directory-picker-browse', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-directory-picker-native/locale/en.json b/packages/client/ui-directory-picker-native/locale/en.json new file mode 100644 index 0000000000..766bf26c75 --- /dev/null +++ b/packages/client/ui-directory-picker-native/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-directory-picker-native" + } +} diff --git a/packages/client/ui-directory-picker-native/locale/zh.json b/packages/client/ui-directory-picker-native/locale/zh.json new file mode 100644 index 0000000000..37a5e9e944 --- /dev/null +++ b/packages/client/ui-directory-picker-native/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "系统目录选择界面", + "description": "连接工作区选择入口与系统目录选择对话框。" + } +} diff --git a/packages/client/ui-directory-picker-native/package.json b/packages/client/ui-directory-picker-native/package.json index e885f10d56..b9a643fec1 100644 --- a/packages/client/ui-directory-picker-native/package.json +++ b/packages/client/ui-directory-picker-native/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-directory-picker-native", "description": "Native directory-picker surface: the renderless workspace directory-flow occupant driving the local Desktop or Host OS chooser", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -47,12 +48,12 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-workspace": "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" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts", diff --git a/packages/client/ui-directory-picker-native/tsdown.config.ts b/packages/client/ui-directory-picker-native/tsdown.config.ts index 23e5247c7e..7aa03cebc1 100644 --- a/packages/client/ui-directory-picker-native/tsdown.config.ts +++ b/packages/client/ui-directory-picker-native/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-directory-picker-native', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-dockkit/package.json b/packages/client/ui-dockkit/package.json index ca46a2a52a..f976afc870 100644 --- a/packages/client/ui-dockkit/package.json +++ b/packages/client/ui-dockkit/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-dockkit", "description": "Docking layout kit: split-tree engine with invertible operations, and the React components that render and drive it (zero cordis)", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -27,8 +27,6 @@ "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@testing-library/react": "^16.3.3", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "react-dom": "^18.2.0", "react": "^18.2.0", "clsx": "^2.0.0" diff --git a/packages/client/ui-dockkit/tsdown.config.ts b/packages/client/ui-dockkit/tsdown.config.ts index 7e4e7ba807..a6264e0b21 100644 --- a/packages/client/ui-dockkit/tsdown.config.ts +++ b/packages/client/ui-dockkit/tsdown.config.ts @@ -1,6 +1,6 @@ import { staticLinked } from '../tsdown.client.ts' export default staticLinked( - '@deepseek-ai/dsh-client-ui-dockkit', + import.meta.dirname, ['lib/types/index.js'], ) diff --git a/packages/client/ui-goal/README.i18n.yaml b/packages/client/ui-goal/README.i18n.yaml index 628c67f401..0d819456e1 100644 --- a/packages/client/ui-goal/README.i18n.yaml +++ b/packages/client/ui-goal/README.i18n.yaml @@ -18,8 +18,8 @@ en: 4f6e6353d793a0de zh: cde6e470f7dd9057 /deepseek-ai-dsh-client-ui-goal/use-this-package/the-command-input-bubble: - en: 05c5db0eb58dffef - zh: 54e7bea0b810b1b8 + en: 05f0360b6c6dd3e9 + zh: d14c3f15dc4cea5b /deepseek-ai-dsh-client-ui-goal/use-this-package/failures: en: 097bbdd748dc17e5 zh: 867d341d046ba609 diff --git a/packages/client/ui-goal/README.md b/packages/client/ui-goal/README.md index c8fe5c0491..ecdd666241 100644 --- a/packages/client/ui-goal/README.md +++ b/packages/client/ui-goal/README.md @@ -29,7 +29,7 @@ Mount this plugin alongside `ui-conversation` and the goal domain package; the s ### The command-input bubble -Each durable `/goal` run projects as a right-aligned user-style bubble labeled `Command input` (or `指令输入`), rendered before the generic command result row; the leading `/goal` token renders as a command reference chip in the code face through ui-primitives `projectUserText`, and the objective stays plain body text. It carries no timestamp, copy, or branch actions, and reloading reconstructs it from the run. +Each durable `/goal` run projects as a right-aligned user-style bubble labeled `Command input` (or `指令输入`), rendered before the generic command result row; the leading `/goal` token renders as a command reference chip in the code face through the shared `conversation.user.text` Factory and the Goal-owned `command` renderer, using the executed token range in `facts.commands`, and the objective stays plain body text. It carries no timestamp, copy, or branch actions, and reloading reconstructs it from the run. ### Failures diff --git a/packages/client/ui-goal/README.zh.md b/packages/client/ui-goal/README.zh.md index 83d33fe35a..e3c8ef955e 100644 --- a/packages/client/ui-goal/README.zh.md +++ b/packages/client/ui-goal/README.zh.md @@ -29,7 +29,7 @@ Web GUI 的 goal 界面同时显示持久 goal 状态及当前的进程本地激 ### 指令输入气泡 -每条持久的 `/goal` 运行都投影为一个右对齐的用户样式气泡,标签为 `Command input`(或 `指令输入`),渲染在通用命令结果行之前;开头的 `/goal` token 经 ui-primitives 的 `projectUserText` 以等宽代码字体渲染为指令引用 chip,目标文本保持正文字体。它不含时间戳、复制或分支操作,重新加载时会依据运行记录重建。 +每条持久的 `/goal` 运行都投影为一个右对齐的用户样式气泡,标签为 `Command input`(或 `指令输入`),渲染在通用命令结果行之前;开头的 `/goal` token 经共享的 `conversation.user.text` Factory 与 Goal 自有的 `command` renderer,使用 `facts.commands` 中的实际执行 token 范围, 以等宽代码字体渲染为指令引用 chip,目标文本保持正文字体。它不含时间戳、复制或分支操作,重新加载时会依据运行记录重建。 ### 失败 diff --git a/packages/client/ui-goal/locale/en.json b/packages/client/ui-goal/locale/en.json new file mode 100644 index 0000000000..adb8f958d3 --- /dev/null +++ b/packages/client/ui-goal/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-goal" + } +} diff --git a/packages/client/ui-goal/locale/zh.json b/packages/client/ui-goal/locale/zh.json new file mode 100644 index 0000000000..b3b7b06c6c --- /dev/null +++ b/packages/client/ui-goal/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话目标栏", + "description": "在输入框上方展示当前会话的目标和状态。" + } +} diff --git a/packages/client/ui-goal/package.json b/packages/client/ui-goal/package.json index b92d047aa2..07e8d25de9 100644 --- a/packages/client/ui-goal/package.json +++ b/packages/client/ui-goal/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-goal", "description": "Session goal surface: GoalBar docked above the composer, read from the goal session projection", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -61,7 +62,6 @@ "@deepseek-ai/dsh-commands": "workspace:*", "@deepseek-ai/dsh-goal": "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 +69,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/ui-goal/src/client/GoalCommandInputView.tsx b/packages/client/ui-goal/src/client/GoalCommandInputView.tsx index 8d9742d45d..ee5c8e38cf 100644 --- a/packages/client/ui-goal/src/client/GoalCommandInputView.tsx +++ b/packages/client/ui-goal/src/client/GoalCommandInputView.tsx @@ -1,12 +1,14 @@ import { memo } from 'react' -import { projectUserText } from '@deepseek-ai/dsh-client-ui-primitives' -import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { PropsLocale, PropsRenderFactories, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import { GOAL_COMMAND, type GoalCommandInputData } from './goal-command-input.ts' import css from './GoalCommandInputView.module.css' +const GOAL_COMMANDS = [{ start: 0, end: GOAL_COMMAND.length + 1, name: GOAL_COMMAND }] as const + type GoalCommandInputViewProps = PropsRuntime<'conversation.chat.node', 'command-input'> & PropsLocale<'goal'> + & PropsRenderFactories /** * Right-aligned `/goal` input bubble without ordinary message actions. The @@ -15,14 +17,9 @@ type GoalCommandInputViewProps = * the objective, `/goal` mentions included, as plain text. */ export const GoalCommandInputView = memo(function GoalCommandInputView({ - node, t, + node, t, renderFactorySlot, }: GoalCommandInputViewProps) { const data: GoalCommandInputData = node.data - // Only the leading token is the executed command; the rest of the line is - // the objective, where a further `/goal` is prose. - const split = data.text.search(/\s/u) - const head = split === -1 ? data.text : data.text.slice(0, split) - const rest = split === -1 ? '' : data.text.slice(split) return (
- {projectUserText(head, [], [GOAL_COMMAND], 'command')} - {rest !== '' && projectUserText(rest, [])} + {renderFactorySlot('conversation.user.text', { + text: data.text, + facts: { commands: GOAL_COMMANDS }, + interactive: false, + })}
diff --git a/packages/client/ui-goal/src/client/GoalCommandReference.tsx b/packages/client/ui-goal/src/client/GoalCommandReference.tsx new file mode 100644 index 0000000000..cfad9369f5 --- /dev/null +++ b/packages/client/ui-goal/src/client/GoalCommandReference.tsx @@ -0,0 +1,12 @@ +/** Display-only command references; command execution stays with the original command input. */ +import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { ReferenceChip } from '@deepseek-ai/dsh-client-ui-primitives' + +/** + * Render one confirmed command token without adding an activation action. + * @param props - resolved command node and its original spelling. + * @returns a noninteractive inline command chip. + */ +export function GoalCommandReference({ node, raw }: UserTextNodeProps<'command'>) { + return +} diff --git a/packages/client/ui-goal/src/client/index.ts b/packages/client/ui-goal/src/client/index.ts index e6feba92f5..ba15d921e2 100644 --- a/packages/client/ui-goal/src/client/index.ts +++ b/packages/client/ui-goal/src/client/index.ts @@ -31,7 +31,10 @@ import type { GoalActionResult, GoalBarInjected } from './slots.ts' import { createGoalActivationSource } from './activation-source.ts' import { GoalDock } from './GoalBar.tsx' import { GoalCommandInputView } from './GoalCommandInputView.tsx' +import { GoalCommandReference } from './GoalCommandReference.tsx' import { goalCommandInputDefinition } from './goal-command-input.ts' +import { goalCommandReferenceRule } from './user-text-rules.ts' +export type {} from './user-text-rules.ts' import { en, zh, type GoalKey } from './locales.ts' export { GoalBar, GoalDock } from './GoalBar.tsx' @@ -66,8 +69,15 @@ export const inject = ['slots', 'sessions', 'remote', 'remote.goals', 'locale', */ export function apply(ctx: ClientContext): void { ctx.uiConversation.events.register(goalCommandInputDefinition) + ctx.uiConversation.userText.register(goalCommandReferenceRule) ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-goal: dictionaries') + ctx.slots.inject('conversation.user.text.node', () => ctx.slots.register({ + name: 'conversation.user.text.node', + key: 'command', + priority: 100, + }, GoalCommandReference)) + ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({ name: 'conversation.chat.node', key: 'command-input', diff --git a/packages/client/ui-goal/src/client/user-text-rules.ts b/packages/client/ui-goal/src/client/user-text-rules.ts new file mode 100644 index 0000000000..67c4dbe81e --- /dev/null +++ b/packages/client/ui-goal/src/client/user-text-rules.ts @@ -0,0 +1,36 @@ +/** Original-text command candidates restricted to confirmed execution ranges. */ +import type { UserTextRule, UserTextNode } from '@deepseek-ai/dsh-client-ui-conversation/client' + +declare module '@deepseek-ai/dsh-client-ui-conversation/client' { + interface UserTextDataMap { + /** The executed command name, without the leading slash. */ + command: { readonly name: string } + } + + interface UserTextFacts { + /** Confirmed command ranges; repeated command spelling outside them stays plain text. */ + readonly commands: readonly { readonly start: number; readonly end: number; readonly name: string }[] + } +} + +/** Return the nearest exact confirmed command, checking boundaries against the original string. */ +export const goalCommandReferenceRule: UserTextRule<'command'> = { + id: 'command', + order: 20, + match(text, from, context) { + const slash = /(? | undefined + for (const { start, end, name } of commands ?? []) { + if (start < from || end > text.length || text.slice(start, end) !== `/${name}` + || (start !== 0 && !/\s/u.test(text.slice(start - 1, start))) + || (end !== text.length && !/\s/u.test(text.slice(end, end + 1)))) continue + if (best === undefined || start < best.start || (start === best.start && end > best.end)) { + best = { id: 'command', start, end, data: { name } } + } + } + return best + }, +} diff --git a/packages/client/ui-goal/tests/goal-command-input.client.spec.tsx b/packages/client/ui-goal/tests/goal-command-input.client.spec.tsx index ad03572d4c..a6344d47a3 100644 --- a/packages/client/ui-goal/tests/goal-command-input.client.spec.tsx +++ b/packages/client/ui-goal/tests/goal-command-input.client.spec.tsx @@ -3,13 +3,15 @@ import { cleanup, render, within } from '@testing-library/react' import { afterEach, describe, expect, it } from 'vitest' import type { SessionLiveEventEntry } from '@deepseek-ai/dsh-api-session-controller/client' import type { - ConversationNodeDefinition, ConversationViewDefinition, + ConversationNodeDefinition, ConversationViewDefinition, UserTextInput, } from '@deepseek-ai/dsh-client-ui-conversation/client' import { ConversationNodeAssembler } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { ChatConversationViewNode, ChatSnapshot, } from '@deepseek-ai/dsh-client-ui-chat/client' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { PropsRenderFactories } from '@deepseek-ai/dsh-client-ui-slots' +import { createUserTextFixture } from '../../ui-conversation/tests/user-text-component-fixture.client.tsx' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import { commandDefinition } from '@deepseek-ai/dsh-client-ui-chat/src/client/conversation-nodes/command.ts' @@ -22,6 +24,15 @@ import { zh } from '../src/client/locales.ts' afterEach(cleanup) +function textFactories(onInput?: (input: UserTextInput) => void): PropsRenderFactories['renderFactorySlot'] { + const renderText = createUserTextFixture() + return (name, input) => { + if (name !== 'conversation.user.text') throw new Error(`Unexpected Goal Factory: ${name}`) + onInput?.(input as UserTextInput) + return renderText(input as UserTextInput) + } +} + class TestEventDefinitions { entries(): readonly ConversationNodeDefinition[] { return [commandDefinition, goalCommandInputDefinition] @@ -127,7 +138,8 @@ describe('goal command input projection', () => { data: { commandId: 'command-goal', text: '/goal ship it', time: 1_700_000_000_000 }, }, t, - } as unknown as Parameters[0] + renderFactorySlot: textFactories(), + } as Parameters[0] const view = render() const bubble = view.getByRole('group', { name: '指令输入' }) @@ -138,6 +150,21 @@ describe('goal command input projection', () => { expect(chips.map(chip => [chip.getAttribute('data-ref-chip'), chip.textContent])).toEqual([['command', '/goal']]) }) + it('keeps command facts stable when the input row rerenders', () => { + const commands: UserTextInput['facts']['commands'][] = [] + const props = { + node: { key: 'goal-command-input:stable', data: { commandId: 'command-goal', text: '/goal ship it', time: 1 } }, + t: makeTranslate(zh, commonZh), + renderFactorySlot: textFactories((input) => { commands.push(input.facts.commands) }), + } as Parameters[0] + const view = render() + view.rerender() + expect(commands).toHaveLength(2) + expect(commands[0]).toEqual([{ start: 0, end: 5, name: 'goal' }]) + expect(commands[1]).toBe(commands[0]) + expect(view.getByRole('group', { name: '指令输入' }).textContent).toBe('/goal ship it') + }) + it('renders a bare /goal as one command chip and nothing else', () => { const t = makeTranslate(zh, commonZh) const props = { @@ -146,7 +173,8 @@ describe('goal command input projection', () => { data: { commandId: 'command-goal', text: '/goal', time: 1_700_000_000_000 }, }, t, - } as unknown as Parameters[0] + renderFactorySlot: textFactories(), + } as Parameters[0] const view = render() const bubble = view.getByRole('group', { name: '指令输入' }) expect(bubble.textContent).toBe('/goal') @@ -161,7 +189,8 @@ describe('goal command input projection', () => { data: { commandId: 'command-goal', text: '/goal 检查 /goal 的语法', time: 1_700_000_000_000 }, }, t, - } as unknown as Parameters[0] + renderFactorySlot: textFactories(), + } as Parameters[0] const view = render() const bubble = view.getByRole('group', { name: '指令输入' }) expect(bubble.textContent).toBe('/goal 检查 /goal 的语法') diff --git a/packages/client/ui-goal/tests/user-text-rules.client.spec.ts b/packages/client/ui-goal/tests/user-text-rules.client.spec.ts new file mode 100644 index 0000000000..7a1d1fc7c6 --- /dev/null +++ b/packages/client/ui-goal/tests/user-text-rules.client.spec.ts @@ -0,0 +1,99 @@ +import { Context } from '@deepseek-ai/cordis' +import { UserTextRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/user-text-registry.ts' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import type { UserTextFacts, UserTextNode, UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { goalCommandReferenceRule } from '../src/client/user-text-rules.ts' + +declare module '@deepseek-ai/dsh-client-ui-conversation/client' { + interface UserTextDataMap { + 'test.command.blocker': { readonly label: string } + } +} + +function setup(rules: readonly UserTextRule[] = [goalCommandReferenceRule]) { + 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('goalCommandReferenceRule', () => { + it('does not read command facts or rerun without an original slash-token boundary', () => { + const read = vi.fn() + const match = vi.fn((text, from, context) => goalCommandReferenceRule.match(text, from, { + read: (key) => { read(key); return context.read(key) }, + })) + const evaluate = setup([{ ...goalCommandReferenceRule, match }]) + const text = 'plain text prefix/goal' + const before = evaluate({ text, facts: {} }) + expect(evaluate({ text, facts: { commands: [{ start: 0, end: 5, name: 'goal' }] } })).toBe(before) + expect(read).not.toHaveBeenCalled() + expect(match.mock.calls.map(([, from]) => from)).toEqual([0]) + }) + + it('offers confirmed ranges while the scheduler resolves an earlier same-start winner', () => { + const text = '/goal /goal /goal' + const blocker: UserTextNode<'test.command.blocker'> = { + id: 'test.command.blocker', start: 0, end: 5, data: { label: 'claimed' }, + } + const match = vi.fn(goalCommandReferenceRule.match) + const evaluate = setup([ + { id: 'test.command.blocker', order: 0, match: (_text, from) => from === 0 ? blocker : undefined }, + { ...goalCommandReferenceRule, match }, + ]) + const nodes = evaluate({ + text, facts: { commands: [{ start: 0, end: 5, name: 'goal' }, { start: 6, end: 11, name: 'goal' }] }, + }) + expect(nodes[0]).toBe(blocker) + expect(nodes.filter(node => node.id === 'command').map(node => [node.start, node.end])).toEqual([[6, 11]]) + expect(nodes.at(-1)).toEqual({ id: 'text', start: 11, end: text.length, data: { text: ' /goal' } }) + expect(match.mock.calls.map(([, from]) => from)).toEqual([0, 5, 11]) + expect(evaluate({ text, facts: { commands: [{ start: 6, end: 10, name: 'goal' }] } }).filter(node => node.id === 'command')).toEqual([]) + }) + + it('marks only actual command ranges, not repeated command spelling in the body', () => { + const evaluate = setup() + const text = '/goal ship it\nthen discuss /goal again' + const commands = [{ start: 0, end: 5, name: 'goal' }] + const input = { text, facts: { commands } } + const nodes = evaluate(input) + expect(nodes.filter(node => node.id === 'command')).toEqual([ + { id: 'command', start: 0, end: 5, data: { name: 'goal' } }, + ]) + expect(evaluate({ text, facts: { commands } })).toBe(nodes) + expect(JSON.parse(JSON.stringify(nodes))).toEqual(nodes) + expect(evaluate({ text, facts: {} }).filter(node => node.id === 'command')).toEqual([]) + }) + + it('returns one nearest valid range from unordered Facts at each requested offset', () => { + const text = '/goal /goal /goal plain' + const commands = [ + { start: 12, end: 17, name: 'goal' }, { start: 6, end: 17, name: 'goal' }, + { start: 0, end: 5, name: 'goal' }, { start: 6, end: 11, name: 'goal' }, + { start: 0, end: 5, name: 'goal' }, + ] + const facts: Partial = { commands } + const context = { read: (key: K) => facts[key] } + expect(goalCommandReferenceRule.match(text, 0, context)?.start).toBe(0) + expect(goalCommandReferenceRule.match(text, 5, context)?.start).toBe(6) + expect(goalCommandReferenceRule.match(text, 11, context)?.start).toBe(12) + expect(goalCommandReferenceRule.match(text, 17, context)).toBeUndefined() + }) + + it.each([ + [' /goalx', 1, 6], [' /other x/goal', 9, 14], [' /goal', 1, 7], [' /goal', 20, 25], + ] as const)('ignores a nonmatching confirmed range in %s', (text, start, end) => { + const facts: Partial = { commands: [{ start, end, name: 'goal' }] } + expect(goalCommandReferenceRule.match(text, 0, { read: key => facts[key] })).toBeUndefined() + }) + + it('uses original UTF-16 offsets without creating boundaries at the search cursor', () => { + const evaluate = setup() + const text = '🙂 /goal body /goal' + expect(evaluate({ text, facts: { commands: [{ start: 3, end: 8, name: 'goal' }] } }) + .filter(node => node.id === 'command')).toEqual([{ id: 'command', start: 3, end: 8, data: { name: 'goal' } }]) + const facts: Partial = { commands: [{ start: 1, end: 6, name: 'goal' }] } + expect(goalCommandReferenceRule.match('x/goal', 1, { read: key => facts[key] })).toBeUndefined() + }) +}) diff --git a/packages/client/ui-goal/tsdown.config.ts b/packages/client/ui-goal/tsdown.config.ts index 8b16051076..7aa03cebc1 100644 --- a/packages/client/ui-goal/tsdown.config.ts +++ b/packages/client/ui-goal/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-goal', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-input-trigger/locale/en.json b/packages/client/ui-input-trigger/locale/en.json new file mode 100644 index 0000000000..9f4b0f089e --- /dev/null +++ b/packages/client/ui-input-trigger/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-input-trigger" + } +} diff --git a/packages/client/ui-input-trigger/locale/zh.json b/packages/client/ui-input-trigger/locale/zh.json new file mode 100644 index 0000000000..98e40ff417 --- /dev/null +++ b/packages/client/ui-input-trigger/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "输入联想服务", + "description": "识别输入中的 / 和 @,展示并选择对应候选项。" + } +} diff --git a/packages/client/ui-input-trigger/package.json b/packages/client/ui-input-trigger/package.json index 8f69365169..22caff915c 100644 --- a/packages/client/ui-input-trigger/package.json +++ b/packages/client/ui-input-trigger/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-input-trigger", "description": "Input trigger pipeline: '/' and '@' detection, candidate menu, pick routing to registered sources", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@types/react": "~18.3.1", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "@deepseek-ai/dsh-file-reference": "workspace:*", @@ -63,6 +63,7 @@ "clsx": "^2.0.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts", diff --git a/packages/client/ui-input-trigger/tsdown.config.ts b/packages/client/ui-input-trigger/tsdown.config.ts index 86f4bfad7d..7aa03cebc1 100644 --- a/packages/client/ui-input-trigger/tsdown.config.ts +++ b/packages/client/ui-input-trigger/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-input-trigger', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-jobs/README.i18n.yaml b/packages/client/ui-jobs/README.i18n.yaml index 0b6fe4ebae..460e719a36 100644 --- a/packages/client/ui-jobs/README.i18n.yaml +++ b/packages/client/ui-jobs/README.i18n.yaml @@ -24,8 +24,8 @@ en: c34dad62fee63306 zh: 167d9da7928a9488 /deepseek-ai-dsh-client-ui-jobs/understand-the-implementation: - en: 98daaa0c15166ea5 - zh: a37b5db4be2e40fe + en: 4b520a2726f1a600 + zh: e0324fd12713be6e /deepseek-ai-dsh-client-ui-jobs/further-exploration: en: 01eaaecb5850f391 zh: 2eabd14cde191ab8 diff --git a/packages/client/ui-jobs/README.md b/packages/client/ui-jobs/README.md index 713488561d..740ecc1876 100644 --- a/packages/client/ui-jobs/README.md +++ b/packages/client/ui-jobs/README.md @@ -45,7 +45,7 @@ Expanding an observable row opens that job's output observation stream from `ctx
Implementation internals — click to expand -One slot entry in the header actions band (after the preset label) renders the trigger and popover; the popover portals to the document body, so the clipping header column and the right sidebar cannot cut it off, and is placed from its anchor and clamped inside the viewport. All data arrives through `ctx.jobs` — the component holds no transport state. The roster follows the mount: one `useEffect` keeps the session's `job.list` stream open while the control lives. Observation follows visibility: another `useEffect` opens the stream for the expanded row's job and closes it on collapse, unmount, or popover close. +One slot entry in the header actions band (after the preset label) renders the trigger; its popover uses a body-mounted `MenuSurface` with fixed positioning so dock panels and clipping ancestors cannot cover it. The shared anchoring hook tracks scrolling, resizing, and panel-size changes. All data arrives through `ctx.jobs` — the component holds no transport state. The roster follows the mount: one `useEffect` keeps the session's `job.list` stream open while the control lives. Observation follows visibility: another `useEffect` opens the stream for the expanded row's job and closes it on collapse, unmount, or popover close. | File | Role | |---|---| @@ -53,6 +53,8 @@ One slot entry in the header actions band (after the preset label) renders the t | [`src/client/index.ts`](src/client/index.ts) | Slot registration and the dictionaries | | [`src/client/locales.ts`](src/client/locales.ts) | The `job` namespace copy (zh source of truth) | +Background-job rows follow the [standard menu edge geometry](../../../docs/ui-radius.md#nested-hover); controls inside a filled running row retain compact corners. +
----- diff --git a/packages/client/ui-jobs/README.zh.md b/packages/client/ui-jobs/README.zh.md index b593a3773e..25b792f58c 100644 --- a/packages/client/ui-jobs/README.zh.md +++ b/packages/client/ui-jobs/README.zh.md @@ -45,7 +45,7 @@ kind: "package-reference"
实现内幕——点击展开 -头部操作带里的一个 slot 条目(preset 标签之后)渲染触发器与弹出层;弹出层挂载到 document body,因此不会被裁剪的头部列或右侧边栏截断,并按锚点定位、限制在视口内。所有数据经 `ctx.jobs` 到达——组件不持有任何传输状态。名册跟随挂载:一个 `useEffect` 在控件存活期间保持会话的 `job.list` 流打开。观测跟随可见性:另一个 `useEffect` 为展开行的 job 打开流,并在收起、卸载或弹出层关闭时关闭它。 +头部操作带里的一个 slot 条目(preset 标签之后)渲染触发器;弹出层通过挂载到 body 的 `MenuSurface` 固定定位,避免被停靠面板遮挡或被祖先容器裁剪。共享锚点 hook 跟踪滚动、窗口尺寸及面板尺寸变化。所有数据经 `ctx.jobs` 到达——组件不持有任何传输状态。名册跟随挂载:一个 `useEffect` 在控件存活期间保持会话的 `job.list` 流打开。观测跟随可见性:另一个 `useEffect` 为展开行的 job 打开流,并在收起、卸载或弹出层关闭时关闭它。 | 文件 | 角色 | |---|---| @@ -53,6 +53,8 @@ kind: "package-reference" | [`src/client/index.ts`](src/client/index.ts) | slot 注册与词典 | | [`src/client/locales.ts`](src/client/locales.ts) | `job` 命名空间文案(zh 为事实源) | +后台任务行遵循[标准菜单边缘几何](../../../docs/ui-radius.zh.md#nested-hover);带底色运行行内的控件保留紧凑圆角。 +
----- diff --git a/packages/client/ui-jobs/locale/en.json b/packages/client/ui-jobs/locale/en.json new file mode 100644 index 0000000000..7df9995cd8 --- /dev/null +++ b/packages/client/ui-jobs/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-jobs" + } +} diff --git a/packages/client/ui-jobs/locale/zh.json b/packages/client/ui-jobs/locale/zh.json new file mode 100644 index 0000000000..1f9b7ce1fd --- /dev/null +++ b/packages/client/ui-jobs/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "后台任务界面", + "description": "在会话中查看后台任务列表、状态和实时输出。" + } +} diff --git a/packages/client/ui-jobs/package.json b/packages/client/ui-jobs/package.json index 5873ba9d18..66d1762ada 100644 --- a/packages/client/ui-jobs/package.json +++ b/packages/client/ui-jobs/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-jobs", "description": "Session-header background-job list with on-demand streaming record panels", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "type": "module", "main": "lib/index.js", "types": "lib/types/index.d.ts", @@ -15,7 +15,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "scripts": { "bundle": "tsdown", @@ -45,12 +46,11 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-jobs": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", - "@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-jobs/src/client/JobListAction.module.css b/packages/client/ui-jobs/src/client/JobListAction.module.css index 549d34f63c..a2cee8bf77 100644 --- a/packages/client/ui-jobs/src/client/JobListAction.module.css +++ b/packages/client/ui-jobs/src/client/JobListAction.module.css @@ -43,24 +43,27 @@ box-sizing: border-box; display: flex; flex-direction: column; - gap: 1px; width: 500px; max-width: min(560px, calc(100vw - 32px)); max-height: min(480px, calc(100vh - 140px)); - margin: 0; - padding: 3px; - overflow: auto; - list-style: none; - border: 0; - border-radius: var(--dsw-radius-lg); - background: var(--dsw-specific-menu); - backdrop-filter: var(--dsw-menu-backdrop-filter); + overflow: hidden; --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); --dsw-elevation-stroke-color: var(--dsw-alias-border-l1); box-shadow: var(--dsw-elevation-prominent); } +.menuBody { + display: flex; + flex-direction: column; + gap: 1px; + min-height: 0; + margin: 0; + padding: 4px; + overflow: auto; + list-style: none; +} + /* Section labels over the live rows and the settled tail. */ .sectionHeader { display: flex; @@ -155,6 +158,10 @@ background: transparent; } +.rowLineLive .row { + border-radius: var(--dsw-radius-sm); +} + .rowLineLive .row:focus-visible { background: color-mix(in srgb, var(--dsw-alias-label-primary) 6%, transparent); } @@ -229,7 +236,7 @@ min-height: 28px; padding: 4px 7px; border: 0; - border-radius: var(--dsw-radius-sm); + border-radius: var(--dsw-radius-md); background: transparent; color: var(--dsw-alias-label-primary); font-size: 12px; diff --git a/packages/client/ui-jobs/src/client/JobListAction.tsx b/packages/client/ui-jobs/src/client/JobListAction.tsx index ed60e3ca5b..7027483b96 100644 --- a/packages/client/ui-jobs/src/client/JobListAction.tsx +++ b/packages/client/ui-jobs/src/client/JobListAction.tsx @@ -3,7 +3,8 @@ import { createPortal } from 'react-dom' import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { - IconChevronDownOutlineRegular, IconStopFillRegular, StateDot, TerminalBlock, useAnchoredPosition, useDismissOnOutsidePointer, + IconChevronDownOutlineRegular, IconStopFillRegular, MenuSurface, StateDot, TerminalBlock, + useAnchoredPosition, useDismissOnOutsidePointer, type StateDotState, type TerminalBlockLabels, } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsLocale, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' @@ -349,7 +350,7 @@ export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, const [killPhase, setKillPhase] = useState<{ key: string; state: Exclude } | undefined>(undefined) const rootRef = useRef(null) const triggerRef = useRef(null) - const menuRef = useRef(null) + const menuRef = useRef(null) const rows = useMemo(() => ordered(jobs), [jobs]) const liveRows = useMemo(() => rows.filter(isLive), [rows]) @@ -537,36 +538,33 @@ export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, {open ? createPortal( -
    - {liveRows.length > 0 - ? - : null} - {liveRows.map(item)} - {settledRows.length > 0 - ? ( -
  • - - -
  • - ) - : null} - {settledExpanded ? settledRows.map(item) : null} -
, + +
    + {liveRows.length > 0 + ? + : null} + {liveRows.map(item)} + {settledRows.length > 0 + ? ( +
  • + + +
  • + ) + : null} + {settledExpanded ? settledRows.map(item) : null} +
+
, document.body, ) : null} diff --git a/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx b/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx index ab673c2274..e6866c4182 100644 --- a/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx +++ b/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx @@ -10,6 +10,7 @@ import { zh } from '../src/client/locales.ts' afterEach(() => { cleanup() vi.restoreAllMocks() + vi.unstubAllGlobals() vi.useRealTimers() }) @@ -282,19 +283,86 @@ describe('JobListAction observation', () => { expect(writeText).toHaveBeenCalledWith('pnpm run build') }) - it('portals the open list below its trigger and keeps it open on pointer presses inside', () => { - vi.spyOn(HTMLDivElement.prototype, 'getBoundingClientRect').mockReturnValue({ left: 344, bottom: 40 } as DOMRect) + it('anchors the portaled list in viewport coordinates and follows resize and ancestor scroll', () => { + vi.stubGlobal('innerWidth', 700) + vi.stubGlobal('innerHeight', 600) + vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(440) + vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(120) const { container } = render() - openList() + const trigger = screen.getByRole('button', { name: '1 个后台任务运行中' }) + const anchor = vi.spyOn(trigger.parentElement!, 'getBoundingClientRect') + .mockReturnValue(new DOMRect(344, 40, 180, 28)) + fireEvent.click(trigger) + const list = screen.getByRole('list', { name: zh['list.aria'] }) + const menu = list.closest('[data-menu-material]') + expect(menu?.parentElement).toBe(document.body) + expect(container.contains(list)).toBe(false) + expect(menu?.style.left).toBe('248px') + expect(menu?.style.top).toBe('73px') + + vi.stubGlobal('innerWidth', 900) + fireEvent(window, new Event('resize')) + expect(menu?.style.left).toBe('344px') + anchor.mockReturnValue(new DOMRect(80, 110, 180, 28)) + fireEvent.scroll(container) + expect(menu?.style.left).toBe('80px') + expect(menu?.style.top).toBe('143px') + }) + + it('keeps a near-edge anchored list inside both viewport margins', () => { + vi.stubGlobal('innerWidth', 700) + vi.stubGlobal('innerHeight', 600) + vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(600) + vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(120) + render() + const trigger = screen.getByRole('button', { name: '1 个后台任务运行中' }) + vi.spyOn(trigger.parentElement!, 'getBoundingClientRect').mockReturnValue(new DOMRect(4, 540, 180, 28)) + fireEvent.click(trigger) const menu = screen.getByRole('list', { name: zh['list.aria'] }) - // Outside the header's clipping column, so the right sidebar cannot cover it. - expect(container.contains(menu)).toBe(false) - expect(menu.style.left).toBe('344px') - expect(menu.style.top).toBe('45px') - fireEvent.pointerDown(menu) - expect(screen.getByRole('list', { name: zh['list.aria'] })).toBeDefined() + .closest('[data-menu-material]') + expect(menu?.style.left).toBe('12px') + expect(menu?.style.top).toBe('468px') + }) + + it('keeps portaled controls interactive and releases observation on dismissal and unmount', () => { + const stop = vi.fn() + const observe = vi.fn(() => stop) + const { container, unmount } = render() + const trigger = screen.getByRole('button', { name: '1 个后台任务运行中' }) + trigger.focus() + fireEvent.click(trigger) + const list = screen.getByRole('list', { name: zh['list.aria'] }) + expect(container.contains(list)).toBe(false) + const row = screen.getByRole('button', { + name: zh['row.expandAria'].replace('{label}', 'pnpm run build'), + }) + fireEvent.pointerDown(row) + fireEvent.click(row) + expect(screen.getByRole('list', { name: zh['list.aria'] })).toBe(list) + expect(observe).toHaveBeenCalledTimes(1) + expect(stop).not.toHaveBeenCalled() + const kill = screen.getByTitle(zh['kill.stop'].replace('{label}', 'pnpm run build')) + fireEvent.pointerDown(kill) + fireEvent.click(kill) + expect(kill.getAttribute('data-kill-state')).toBe('armed') + expect(screen.getByRole('list', { name: zh['list.aria'] })).toBe(list) + + row.focus() + fireEvent.keyDown(row, { key: 'Escape' }) + expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() + expect(document.activeElement).toBe(trigger) + expect(stop).toHaveBeenCalledTimes(1) + fireEvent.click(trigger) + expect(observe).toHaveBeenCalledTimes(2) fireEvent.pointerDown(document.body) expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() + expect(stop).toHaveBeenCalledTimes(2) + fireEvent.click(trigger) + expect(observe).toHaveBeenCalledTimes(3) + const reopened = screen.getByRole('list', { name: zh['list.aria'] }) + unmount() + expect(document.body.contains(reopened)).toBe(false) + expect(stop).toHaveBeenCalledTimes(3) }) it('ignores other keys while open and closes once the roster empties', () => { @@ -342,7 +410,7 @@ describe('JobListAction observation', () => { render() openList() fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - expect(document.body.querySelector('[data-running]')).not.toBeNull() + expect(screen.getByRole('list', { name: zh['list.aria'] }).querySelector('[data-running]')).not.toBeNull() expect(screen.queryByText(zh['terminal.noOutput'])).toBeNull() }) diff --git a/packages/client/ui-jobs/tsdown.config.ts b/packages/client/ui-jobs/tsdown.config.ts index 550a1fcf58..7aa03cebc1 100644 --- a/packages/client/ui-jobs/tsdown.config.ts +++ b/packages/client/ui-jobs/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-jobs', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-layout/locale/en.json b/packages/client/ui-layout/locale/en.json new file mode 100644 index 0000000000..4ade97b55d --- /dev/null +++ b/packages/client/ui-layout/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-layout" + } +} diff --git a/packages/client/ui-layout/locale/zh.json b/packages/client/ui-layout/locale/zh.json new file mode 100644 index 0000000000..2c3d490308 --- /dev/null +++ b/packages/client/ui-layout/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "应用布局", + "description": "组织导航、会话和侧边面板,并支持拖动调整布局。" + } +} diff --git a/packages/client/ui-layout/package.json b/packages/client/ui-layout/package.json index 7c82975f4e..d13fd01a7c 100644 --- a/packages/client/ui-layout/package.json +++ b/packages/client/ui-layout/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-layout", "description": "Shell plugin: three-column AppFrame with drag handles, ctx.layout viewing-state service (navigation + panels)", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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,12 +54,12 @@ "@deepseek-ai/dsh-client-ui-session": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-client-ui-theme": "workspace:*", - "@types/react": "~18.3.1", "@deepseek-ai/cordis": "workspace:~", "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-layout/tests/app-frame.client.spec.tsx b/packages/client/ui-layout/tests/app-frame.client.spec.tsx index f82cec372a..1dc7cc85b8 100644 --- a/packages/client/ui-layout/tests/app-frame.client.spec.tsx +++ b/packages/client/ui-layout/tests/app-frame.client.spec.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom /** Frame interactions with a real store and explicitly driven browser measurements. */ import type { GlobalStandardProps, RenderOpts } from '@deepseek-ai/dsh-client-ui-slots' -import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, render } from '@testing-library/react' import { AppFrame } from '../src/client/AppFrame.tsx' @@ -99,6 +99,7 @@ function mountFrame(windowWidth = frameWidth) { useSessionRetainInfo={() => undefined} useResource={useResource} useWorkspaces={sel => sel(workspaceState)} + {...allowAllAccess} t={key => key === 'brand.localBuild' ? 'DSH Local Build' : key} /> ) diff --git a/packages/client/ui-layout/tests/apply.client.spec.ts b/packages/client/ui-layout/tests/apply.client.spec.ts index e1b267dc4c..96aac84fd1 100644 --- a/packages/client/ui-layout/tests/apply.client.spec.ts +++ b/packages/client/ui-layout/tests/apply.client.spec.ts @@ -56,11 +56,8 @@ async function bench() { await owner.await() if (ctx === undefined) throw new Error('the fixture owner did not activate') const slotsFiber = ctx.plugin(SlotRegistry) - // Theme registers its Appearance settings row and requires the connection - // seam for persistence; model this bench as a remote, memory-only browser. ctx.provide('locale', new LocaleRuntime(ctx)) await ctx.plugin(ShortcutsService).await() - ctx.provide('connection', { api: { settings: {} }, isLoopback: false } as never) // ui-theme's Appearance row binds a durable scope through these two. ctx.provide('remote', { $on: () => () => {} } as never) ctx.provide('configForms', { developerTools: { enabled: createSnapshotStore(true) }, get: () => stubConfigForm().scope } as never) diff --git a/packages/client/ui-layout/tsdown.config.ts b/packages/client/ui-layout/tsdown.config.ts index 27224c5803..7aa03cebc1 100644 --- a/packages/client/ui-layout/tsdown.config.ts +++ b/packages/client/ui-layout/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-layout', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-message-feedback/locale/en.json b/packages/client/ui-message-feedback/locale/en.json new file mode 100644 index 0000000000..b49bdc23e2 --- /dev/null +++ b/packages/client/ui-message-feedback/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-message-feedback" + } +} diff --git a/packages/client/ui-message-feedback/locale/zh.json b/packages/client/ui-message-feedback/locale/zh.json new file mode 100644 index 0000000000..b984fc9e3e --- /dev/null +++ b/packages/client/ui-message-feedback/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "消息反馈界面", + "description": "提供回复的赞踩按钮及会话反馈弹窗。" + } +} diff --git a/packages/client/ui-message-feedback/package.json b/packages/client/ui-message-feedback/package.json index 68c00c0989..56b07a0c1d 100644 --- a/packages/client/ui-message-feedback/package.json +++ b/packages/client/ui-message-feedback/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-message-feedback", "description": "The Web feedback surface: per-message Like/Dislike in the assistant-message action strip and the feedback dialog behind both ratings and /feedback, backed by the messageFeedback and sessionFeedback Host Remotes", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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-typert-protocol": "workspace:*", "@deepseek-ai/cordis": "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", "@deepseek-ai/dsh-client-ui-chat": "workspace:*", @@ -71,6 +70,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-message-feedback/tsdown.config.ts b/packages/client/ui-message-feedback/tsdown.config.ts index 2137857d99..7aa03cebc1 100644 --- a/packages/client/ui-message-feedback/tsdown.config.ts +++ b/packages/client/ui-message-feedback/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-message-feedback', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index 4d2f30c8c5..f9e88d76d0 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -9,14 +9,14 @@ en: 4cb6feb12e46f3a0 zh: eea39dd76fe1fa8b /deepseek-ai-dsh-client-ui-model-selection/summary: - en: 2fb361ef704528fb - zh: 2537d2afb4d2cb45 + en: 14a351e14b69ca33 + zh: 2f2686efe4832266 /deepseek-ai-dsh-client-ui-model-selection/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-model-selection/use-this-package: - en: 62235f8c8c9e1e7e - zh: c18dc9c38ef9d4f9 + en: ef50e68e7493d0a9 + zh: 3b1faea17b606173 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-and-effort: en: 48f8157ffdfe6e69 zh: 64ec9a533e2aa8f4 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index a073d9ec27..a32460cdb9 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -11,7 +11,7 @@ Desktop product events use the optional [product analytics service](../product-a ## Summary -The Web GUI lets users switch the model and reasoning effort for an existing session through either the `/model` popup or the composer's model control. Both surfaces present the same provider-grouped choices, and the selected model determines the available effort names and default. A complete selection applies to the next request; a running step keeps the model and effort it started with. If the selected model is unavailable, the composer stays disabled until the user selects an available model or that exact model becomes available again. +The Web GUI lets users switch the model and reasoning effort for an existing session through either the `/model` popup or the composer's model control. Both surfaces present the same provider-grouped choices, and the selected model determines the available effort names and default. A complete selection applies to the next request; a running step keeps the model and effort it started with. ## Table of Contents @@ -29,9 +29,9 @@ The Web GUI lets users switch the model and reasoning effort for an existing ses DeepSeek account and API-key routes appear as separate provider groups, each exposing the same configured model catalog. -The unselected model label uses the same regular weight as an available model name and retains the saved reasoning effort caption for existing and new sessions; effort editing requires an available model. Clicking the unselected trigger opens the model list directly; Escape closes it. +When no model is selected or the saved selection is absent from the catalog, the composer shows “Select model” in regular weight and hides the reasoning effort caption. Clicking it opens the model list directly; Escape and Shift+Tab close it. An empty catalog displays “No models available.” -Mount this plugin alongside `ui-conversation` and the commands package; the composer then shows the model seat next to the pending indicator, and `/model` opens the same directory as a popup. While the seat's menu is open, `↑`/`↓` move focus through root and effort rows, or move the model-list highlight without leaving search. Enter and Tab settle the highlighted model or focused row; Escape and `Shift+Tab` leave a drilled pane first and otherwise close back to the trigger. Drilling focuses model search when shown, otherwise the current model or effort row, and going back lands on the cell that opened the pane left. The composer shows the catalog name while the selected model is available, and its saved `provider/model` ID when the model or provider is removed, including account sign-out. The stored provider, model, and reasoning effort remain unchanged. +Mount this plugin alongside `ui-conversation` and the commands package; the composer then shows the model seat next to the pending indicator, and `/model` opens the same directory as a popup. While the seat's menu is open, `↑`/`↓` move focus through root and effort rows, or move the model-list highlight without leaving search. Enter and Tab settle the highlighted model or focused row; Escape and `Shift+Tab` leave a drilled pane first and otherwise close back to the trigger. Drilling focuses model search when shown, otherwise the current model or effort row, and going back lands on the cell that opened the pane left. The composer shows the catalog name while the selected model is available. Removing a model or provider, including account sign-out, preserves the stored provider, model, and reasoning effort without displaying their IDs. Restoring the catalog entry restores its name and effort caption. Mouse selection uses native browser clicks, including their cancellation behavior; a press alone never selects. Opening the root menu focuses its trigger, and clicking the trigger again closes the menu and returns focus there. Root rows and the search-clear button show the same fill for keyboard focus and hover, without a native outline. Selecting a model or effort returns focus to the trigger without a focus ring; leaving the trigger or reopening the menu restores its normal focus indication. While a selection from either entry is pending, focus stays on the trigger, the trigger shows a spinner in place of its chevron, and each row whose value the selection carries shows one in place of its check; a rejected selection leaves the menu open. Tab returns to model search with the current model highlighted when search is shown, otherwise to the current row. diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index bf719d839d..21b13ec2d5 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" ## 概述 -Web GUI 允许用户通过 `/model` 弹窗或 composer 模型控件切换既有会话使用的模型与推理(reasoning)强度。两个界面呈现同一组按提供方分组的选择;所选模型决定可用的推理强度名称与默认值。完整选择从下一次请求开始生效;运行中的步骤保留其启动时的模型与推理强度。所选模型不可用时,composer 保持停用,直到用户选择可用模型或同一模型恢复可用。 +Web GUI 允许用户通过 `/model` 弹窗或 composer 模型控件切换既有会话使用的模型与推理(reasoning)强度。两个界面呈现同一组按提供方分组的选择;所选模型决定可用的推理强度名称与默认值。完整选择从下一次请求开始生效;运行中的步骤保留其启动时的模型与推理强度。 ## 目录 @@ -29,9 +29,9 @@ Web GUI 允许用户通过 `/model` 弹窗或 composer 模型控件切换既有 DeepSeek 账号和 API Key 路由显示为独立提供方分组,各自展示相同的已配置模型目录。 -未选模型文案与可用模型名使用相同的常规字重,并在既有会话与新会话中保留已保存的推理强度显示;调整推理强度需要先选择可用模型。点击未选模型控件直接打开模型列表,Escape 关闭列表。 +未选择模型或已保存的选择不在目录中时,composer 以常规字重显示“请选择模型”,并隐藏推理强度文案。点击后直接打开模型列表,Escape 和 Shift+Tab 关闭列表。目录为空时显示“暂无可用模型” -与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。模型位菜单打开期间,`↑`/`↓` 在根菜单和推理等级行间移动焦点,或在模型列表中移动高亮并让焦点保留在搜索框。Enter 和 Tab 选定高亮模型或聚焦行;Escape 与 `Shift+Tab` 先退出已下钻的面板,否则关闭并回到触发器。下钻时若显示模型搜索框则聚焦搜索框,否则聚焦当前模型或推理强度行,返回则落在打开该面板的格子上。所选模型可用时,composer 显示目录中的模型名称;模型或提供方被删除时(包括账号退登),改为显示已保存的 `provider/model` ID。保存的提供方、模型和推理强度均保持不变。 +与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。模型位菜单打开期间,`↑`/`↓` 在根菜单和推理等级行间移动焦点,或在模型列表中移动高亮并让焦点保留在搜索框。Enter 和 Tab 选定高亮模型或聚焦行;Escape 与 `Shift+Tab` 先退出已下钻的面板,否则关闭并回到触发器。下钻时若显示模型搜索框则聚焦搜索框,否则聚焦当前模型或推理强度行,返回则落在打开该面板的格子上。所选模型可用时,composer 显示目录中的模型名称。模型或提供方被删除时(包括账号退登),保留已保存的提供方、模型和推理强度,但不展示其 ID。目录条目恢复后重新显示名称和推理强度。 鼠标选择沿用浏览器原生点击及其取消行为;仅按下按钮不会选定。打开根菜单时聚焦触发按钮,再次点击触发按钮会关闭菜单并把焦点还给它。根菜单行和搜索清除按钮的键盘焦点与悬停使用相同底色,不显示原生焦点轮廓。选定模型或推理等级后,焦点返回触发按钮但不显示焦点环;焦点离开按钮或重新打开菜单后恢复正常焦点提示。等待任一入口发起的选择结果时,焦点停在触发按钮,触发按钮以加载图标代替下拉箭头,该选择包含的值所在行以加载图标代替勾选标记;选择被拒绝后菜单保持打开。显示模型搜索框时,Tab 返回搜索框并高亮当前模型,否则返回当前选中行。 diff --git a/packages/client/ui-model-selection/locale/en.json b/packages/client/ui-model-selection/locale/en.json new file mode 100644 index 0000000000..5289394629 --- /dev/null +++ b/packages/client/ui-model-selection/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-model-selection" + } +} diff --git a/packages/client/ui-model-selection/locale/zh.json b/packages/client/ui-model-selection/locale/zh.json new file mode 100644 index 0000000000..66c2779ca6 --- /dev/null +++ b/packages/client/ui-model-selection/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "模型选择界面", + "description": "查看可用模型,并切换当前会话使用的模型。" + } +} diff --git a/packages/client/ui-model-selection/package.json b/packages/client/ui-model-selection/package.json index a196c25b3d..f0890efa99 100644 --- a/packages/client/ui-model-selection/package.json +++ b/packages/client/ui-model-selection/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-model-selection", "description": "Model selection over the shared model catalog, Session projection, and session.selectModel", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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,11 +56,9 @@ "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "@types/react": "~18.3.1", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "react-dom": "^18.2.0", - "@types/react-dom": "~18.3.0", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", @@ -69,6 +68,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-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index fbeda5d31e..8d37dab5e3 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -119,11 +119,13 @@ export function ModelSelect( const currentChoice = choices[selectedIndex] const reasoning = currentChoice?.model.reasoning const effectiveEffort = state.current?.reasoningEffort ?? reasoning?.defaultEffort - const effortLabel = reasoning === undefined - ? state.retainedEffort - : effectiveEffort === undefined - ? t('effort.providerDefault') - : reasoning.efforts.find(level => level.id === effectiveEffort)?.name ?? effectiveEffort + const effortLabel = currentChoice === undefined + ? undefined + : reasoning === undefined + ? state.retainedEffort + : effectiveEffort === undefined + ? t('effort.providerDefault') + : reasoning.efforts.find(level => level.id === effectiveEffort)?.name ?? effectiveEffort const effortChoices = useMemo(() => reasoning === undefined ? [] : [ @@ -244,8 +246,8 @@ export function ModelSelect( triggerRef.current?.focus() setQuery('') setHighlightedIndex(null) - if (state.current === null) paneFocus.current = 'drill' - setPane(state.current === null ? 'model' : 'root') + if (currentChoice === undefined) paneFocus.current = 'drill' + setPane(currentChoice === undefined ? 'model' : 'root') setOpen(true) reload() } @@ -297,7 +299,7 @@ export function ModelSelect( if (event.key === 'Escape' && open) { event.preventDefault() // Escape backs out of a drilled pane first, then closes. - if (pane !== 'root' && state.current !== null) back(pane) + if (pane !== 'root' && currentChoice !== undefined) back(pane) else close(true) return } @@ -325,7 +327,7 @@ export function ModelSelect( if (event.key === 'Tab') { if (event.shiftKey) { event.preventDefault() - if (pane !== 'root' && state.current !== null) back(pane) + if (pane !== 'root' && currentChoice !== undefined) back(pane) else close(true) return } @@ -411,15 +413,15 @@ export function ModelSelect( submit(selection) } - const waiting = state.current === null && state.status === 'loading' + const waiting = currentChoice === undefined && state.status === 'loading' const modelLabel = waiting ? t('trigger.loading') : currentChoice?.model.name - ?? (state.current === null ? t('trigger.fallback') : `${state.current.provider}/${state.current.model}`) + ?? t('trigger.fallback') const triggerLabel = effortLabel === undefined ? modelLabel : `${modelLabel} · ${effortLabel}` const triggerAria = waiting ? t('trigger.loading') - : state.current === null + : currentChoice === undefined ? t('trigger.selectAria') : effortLabel === undefined ? t('trigger.aria', { model: modelLabel }) diff --git a/packages/client/ui-model-selection/src/client/locales.ts b/packages/client/ui-model-selection/src/client/locales.ts index a522b55da1..63602c2780 100644 --- a/packages/client/ui-model-selection/src/client/locales.ts +++ b/packages/client/ui-model-selection/src/client/locales.ts @@ -31,7 +31,7 @@ export const zh = { 'search.placeholder': '搜索模型…', 'search.clear': '清除搜索', 'search.empty': '没有匹配的模型。', - 'empty.models': '没有可用的模型。', + 'empty.models': '暂无可用模型', 'empty.efforts': '当前模型未提供推理等级。', } satisfies Record diff --git a/packages/client/ui-model-selection/tests/browser-plugin.client.spec.ts b/packages/client/ui-model-selection/tests/browser-plugin.client.spec.ts index b27163fb16..389b9cfc28 100644 --- a/packages/client/ui-model-selection/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-model-selection/tests/browser-plugin.client.spec.ts @@ -238,7 +238,7 @@ describe('ui-model-selection dual entry', () => { expect(options[0]?.active).toBe(true) expect(options[1]?.active).toBeUndefined() expect(b.popup().searchLabels?.()).toEqual(locale === 'zh' - ? { placeholder: '搜索模型…', empty: '没有可用的模型。', noResults: '没有匹配的模型。' } + ? { placeholder: '搜索模型…', empty: '暂无可用模型', noResults: '没有匹配的模型。' } : { placeholder: 'Search models…', empty: 'No models available.', noResults: 'No matching models.' }) }) diff --git a/packages/client/ui-model-selection/tests/expected/unselected-model.txt b/packages/client/ui-model-selection/tests/expected/unselected-model.txt index 2e251b01d4..d6d4beb3b1 100644 --- a/packages/client/ui-model-selection/tests/expected/unselected-model.txt +++ b/packages/client/ui-model-selection/tests/expected/unselected-model.txt @@ -1 +1 @@ -请选择模型High +请选择模型 diff --git a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx index 470c852ec8..b077cc9093 100644 --- a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx @@ -143,7 +143,7 @@ describe('ModelSelect reasoning effort', () => { .toEqual(['Default', 'Standard']) }) - it('shows the durable model id when the catalog has no matching display name', () => { + it('opens model choices without exposing a saved route absent from the catalog', () => { const directory = createSnapshotStore(state({ current: { provider: 'deepseek-official', model: 'removed-model' }, })) @@ -157,17 +157,21 @@ describe('ModelSelect reasoning effort', () => { t={t} />) - const trigger = screen.getByRole('button', { name: '选择模型,当前 deepseek-official/removed-model' }) - expect(trigger.textContent).toContain('deepseek-official/removed-model') + const trigger = screen.getByRole('button', { name: '请选择模型' }) + expect(trigger.textContent).toBe('请选择模型') fireEvent.click(trigger) expect(screen.queryByRole('menuitem', { name: /推理等级/ })).toBeNull() - fireEvent.click(screen.getByRole('menuitem', { name: /模型/ })) + expect(screen.queryByRole('menuitem', { name: /模型/ })).toBeNull() expect(screen.queryByRole('menuitemradio', { name: 'removed-model' })).toBeNull() expect(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' })).toBeTruthy() expect(screen.queryByText('Fast catalog description')).toBeNull() + expect(select).not.toHaveBeenCalled() + expect(directory.getSnapshot().current).toEqual({ provider: 'deepseek-official', model: 'removed-model' }) + fireEvent.keyDown(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' }), { key: 'Escape' }) + expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() }) - it.each(['model', 'provider'])('keeps the saved id and effort when the selected %s disappears', (removed) => { + it.each(['model', 'provider'])('hides the saved id and effort when the selected %s disappears', (removed) => { const directory = createSnapshotStore(state({ retainedEffort: 'High' })) render() expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toContain('DeepSeek-V4-Flash') @@ -175,14 +179,18 @@ describe('ModelSelect reasoning effort', () => { snapshot.groups = removed === 'provider' ? [] : snapshot.groups.map(group => ({ ...group, models: [] })) snapshot.routable = false }) }) - expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent) - .toMatchInlineSnapshot('"deepseek-official/deepseek-v4-flashHigh"') + const trigger = screen.getByRole('button', { name: '请选择模型' }) + expect(trigger.textContent).toBe('请选择模型') expect(directory.getSnapshot().current).toEqual(state().current) + fireEvent.click(trigger) + expect(screen.getByRole('status').textContent).toBe(zh['empty.models']) + fireEvent.keyDown(trigger, { key: 'Tab', shiftKey: true }) + expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() }) - it('shows loading until the catalog and Session projection are both ready', async () => { + it.each([null, state().current])('shows loading until the catalog and Session projection are both ready (%j)', async (current) => { const directory = createSnapshotStore(state({ - current: null, + current, routable: null, groups: [], status: 'loading', @@ -494,7 +502,6 @@ describe('ModelSelect keyboard walk', () => { />) const trigger = screen.getByRole('button', { name: /选择模型/ }) fireEvent.click(trigger) - fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) expect(screen.queryByRole('searchbox')).toBeNull() expect(document.activeElement).toBe(trigger) @@ -506,12 +513,8 @@ describe('ModelSelect keyboard walk', () => { retry.focus() // A control that is not a row keeps the browser's traversal. expect(fireEvent.keyDown(retry, { key: 'Tab' })).toBe(true) - // Escape still backs out of the pane and then closes the card. fireEvent.keyDown(retry, { key: 'Escape' }) - // Back on the root pane, whose only cell remains (no model means no effort row). - const cell = screen.getAllByRole('menuitem')[0]! - fireEvent.keyDown(cell, { key: 'Escape' }) - expect(screen.queryByRole('menu')).toBeNull() + expect(screen.queryByRole('group', { name: '模型与推理等级' })).toBeNull() }) it('focuses the checked model in a small catalog', () => { @@ -557,7 +560,6 @@ describe('ModelSelect keyboard walk', () => { t={t} />) fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) - fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) const rows = screen.getAllByRole('menuitemradio') expect(rows.every(row => row.getAttribute('aria-checked') === 'false')).toBe(true) expect(screen.queryByRole('searchbox')).toBeNull() @@ -573,7 +575,7 @@ describe('ModelSelect catalog size', () => { load={vi.fn()} select={vi.fn()} t={t} />) const trigger = screen.getByRole('button', { name: /选择模型/ }) fireEvent.click(trigger) - fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + if (count > 0) fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) const rows = screen.queryAllByRole('menuitemradio') expect(rows).toHaveLength(count) if (count > 4) { @@ -608,7 +610,7 @@ describe('ModelSelect catalog size', () => { const directory = createSnapshotStore(state({ groups: modelGroups(5), current })) render() fireEvent.click(screen.getByRole('button', { name: /选择模型/ })) - fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) + if (checked) fireEvent.click(screen.getByRole('menuitem', { name: /^模型/ })) const search = screen.getByRole('searchbox') fireEvent.change(search, { target: { value: 'Model 5' } }) expect(screen.getAllByRole('menuitemradio')).toHaveLength(1) @@ -852,13 +854,13 @@ describe('ModelSelect search', () => { }) }) -it('shows the unselected model control with the inherited effort', async () => { +it('hides the inherited effort until a listed model is selected', async () => { const directory = createSnapshotStore(state({ current: null, routable: false, retainedEffort: 'High' })) render() const trigger = screen.getByRole('button', { name: '请选择模型' }) expect(trigger.hasAttribute('disabled')).toBe(false) await expect(`${trigger.textContent}\n`).toMatchFileSnapshot('./expected/unselected-model.txt') - expect(trigger.textContent).toContain('High') + expect(trigger.textContent).not.toContain('High') fireEvent.click(trigger) expect(screen.queryByRole('menuitem', { name: /模型/ })).toBeNull() expect(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' })).toBeTruthy() @@ -911,8 +913,7 @@ it('restores the account model name after login without changing the saved route render() expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek FlashHigh') act(() => { directory.update((snapshot) => { snapshot.groups = []; snapshot.routable = false }) }) - expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent) - .toMatchInlineSnapshot('"deepseek-account/deepseek-flashHigh"') + expect(screen.getByRole('button', { name: '请选择模型' }).textContent).toBe('请选择模型') act(() => { directory.update((snapshot) => { snapshot.groups = groups; snapshot.routable = true }) }) expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek FlashHigh') expect(directory.getSnapshot().current).toEqual(selected) diff --git a/packages/client/ui-model-selection/tsdown.config.ts b/packages/client/ui-model-selection/tsdown.config.ts index eba18ff11c..7aa03cebc1 100644 --- a/packages/client/ui-model-selection/tsdown.config.ts +++ b/packages/client/ui-model-selection/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-model-selection', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-open-in-app/locale/en.json b/packages/client/ui-open-in-app/locale/en.json new file mode 100644 index 0000000000..7365851f6e --- /dev/null +++ b/packages/client/ui-open-in-app/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-open-in-app" + } +} diff --git a/packages/client/ui-open-in-app/locale/zh.json b/packages/client/ui-open-in-app/locale/zh.json new file mode 100644 index 0000000000..078d8a6924 --- /dev/null +++ b/packages/client/ui-open-in-app/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "外部应用打开界面", + "description": "在会话和文档预览中提供「打开方式」入口。" + } +} diff --git a/packages/client/ui-open-in-app/package.json b/packages/client/ui-open-in-app/package.json index 451e3357c8..54f6f2c287 100644 --- a/packages/client/ui-open-in-app/package.json +++ b/packages/client/ui-open-in-app/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-open-in-app", "description": "Web \"Open In...\" controls: the Session-header split button opening the workspace directory in an installed application, and the document preview's default-application controls for one file", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,9 +23,11 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts", @@ -76,7 +78,6 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-host-open-in-app": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0", "@deepseek-ai/dsh-client-ui-deliverables": "workspace:*", "@deepseek-ai/dsh-native-command": "workspace:*", diff --git a/packages/client/ui-open-in-app/tsdown.config.ts b/packages/client/ui-open-in-app/tsdown.config.ts index 1153b561f6..7aa03cebc1 100644 --- a/packages/client/ui-open-in-app/tsdown.config.ts +++ b/packages/client/ui-open-in-app/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-open-in-app', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-permission-presets/README.i18n.yaml b/packages/client/ui-permission-presets/README.i18n.yaml index 3f24ef0979..f9ae7348ed 100644 --- a/packages/client/ui-permission-presets/README.i18n.yaml +++ b/packages/client/ui-permission-presets/README.i18n.yaml @@ -10,7 +10,7 @@ zh: 74b8ded4da556e81 /deepseek-ai-dsh-client-ui-permission-presets/summary: en: 2591adc4721c0564 - zh: 311292f58621adb6 + zh: 558413d3f819d3af /deepseek-ai-dsh-client-ui-permission-presets/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb @@ -18,14 +18,14 @@ en: 91606bff7da02253 zh: ef68e813d64c89be /deepseek-ai-dsh-client-ui-permission-presets/use-this-package/the-picker: - en: d851eab85fe002bd - zh: 0fdf6eeb1cbd609b + en: 4e5a070ad4321548 + zh: 010063336bd2b8df /deepseek-ai-dsh-client-ui-permission-presets/use-this-package/the-settings-row: en: 5067f6aa12496225 zh: cfa6796684f97535 /deepseek-ai-dsh-client-ui-permission-presets/understand-the-implementation: en: 4089d5bebf3e8bf0 - zh: bc5c3652b0612784 + zh: 22071e6cd6de0ffc /deepseek-ai-dsh-client-ui-permission-presets/further-exploration: en: 9bdbdea03d0e2a96 zh: cc3bf480a0706ef2 @@ -37,7 +37,7 @@ zh: 4fcbc876952d240d /deepseek-ai-dsh-client-ui-permission-presets/known-limitations-and-deferred-work: en: 08cdc0ad196d12c1 - zh: 1b65f5d30e219197 + zh: 157bee9d5b29f470 /deepseek-ai-dsh-client-ui-permission-presets/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-permission-presets/README.md b/packages/client/ui-permission-presets/README.md index 6798cc7f47..50d8b4918c 100644 --- a/packages/client/ui-permission-presets/README.md +++ b/packages/client/ui-permission-presets/README.md @@ -29,7 +29,7 @@ Mount this plugin alongside the settings, commands, and conversation packages. G ### The picker -A pick submits the `/permission ` command line. The argument-bearing form (`/permission ` typed directly) still switches directly; the decoration replaces only the bare invocation. The built-in labels are `Read Only`, `Workspace Write`, `Full access`, and `Auto review` in English and `仅可查看`, `工作区内修改`, `完全权限`, and `Auto review` in Chinese. Explicit host labels remain unchanged, unknown kebab-case names render in title case, and `auto` carries an `EXP` badge plus an experimental-risk confirmation. `custom` is display state, never a target. +A pick submits the `/permission ` command line. The argument-bearing form (`/permission ` typed directly) still switches directly; the decoration replaces only the bare invocation. The built-in labels are `Read Only`, `Workspace Write`, `Full access`, and `Auto review` in English and `仅可查看`, `工作区内修改`, `完全权限`, and `自动审查` in Chinese. Explicit host labels remain unchanged, unknown kebab-case names render in title case, and `auto` carries an `EXP` badge in menu options plus an experimental-risk confirmation. The selected composer control shows the mode without the badge. `custom` is display state, never a target. When the live catalog withdraws a preset, the composer closes its pending confirmation and shows the Session's current value instead of an unavailable optimistic pick. Every catalog invalidation — the payload-free notification or a connection-generation change — closes an open slash picker or its confirmation without consuming the draft, while publishing the result of a read the picker waits for leaves it open with its failure and retry state; reopening reads the current catalog. A submitted command remains busy until its response settles. diff --git a/packages/client/ui-permission-presets/README.zh.md b/packages/client/ui-permission-presets/README.zh.md index 1c603b5eb5..df37cea7ec 100644 --- a/packages/client/ui-permission-presets/README.zh.md +++ b/packages/client/ui-permission-presets/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -为当前 Web 会话或未来会话选择权限预设。通用设置行只更改之后创建会话所用的默认值;composer 与 `/permission` 选择器切换当前会话。默认 Web 提供仅可查看、工作区内修改与完全权限。显式加载实验 Auto integration 后,当前会话选择器会增加带 `EXP` 标记的 Auto review。通过可见选项选择完全权限或 Auto 时,需要分别确认对应风险;完整的 `/permission ` 命令直接执行。宿主通过 Session 投影确认每次变更。 +为当前 Web 会话或未来会话选择权限预设。通用设置行只更改之后创建会话所用的默认值;composer 与 `/permission` 选择器切换当前会话。默认 Web 提供仅可查看、工作区内修改与完全权限。显式加载实验 Auto integration 后,当前会话选择器会增加带 `EXP` 标记的自动审查。通过可见选项选择完全权限或 Auto 时,需要分别确认对应风险;完整的 `/permission ` 命令直接执行。宿主通过 Session 投影确认每次变更。 ## 目录 @@ -29,7 +29,7 @@ kind: "package-reference" ### 选择器 -选中即提交 `/permission ` 命令行。带参形式(直接键入 `/permission `)仍直接切换;装饰只替换裸调用。内置标签在英文界面中是 `Read Only`、`Workspace Write`、`Full access` 和 `Auto review`,在中文界面中是「仅可查看」「工作区内修改」「完全权限」和 `Auto review`。显式 host 标签保持原样,未知 kebab-case 名称渲染为 Title Case;`auto` 带有 `EXP` badge,并在可见选择时要求实验风险确认。`custom` 只是显示状态,绝非目标。 +选中即提交 `/permission ` 命令行。带参形式(直接键入 `/permission `)仍直接切换;装饰只替换裸调用。内置标签在英文界面中是 `Read Only`、`Workspace Write`、`Full access` 和 `Auto review`,在中文界面中是「仅可查看」「工作区内修改」「完全权限」和「自动审查」。显式 host 标签保持原样,未知 kebab-case 名称渲染为 Title Case;`auto` 在菜单选项中带有 `EXP` 标记,并在可见选择时要求实验风险确认。选中后的 composer 控件显示模式,不展示该标记。`custom` 只是显示状态,绝非目标。 实时目录撤销某个预设时,composer 关闭对应的待确认对话框,并用 Session 的当前值替代已不可用的乐观选择。每次目录失效(无 payload 的通知或连接代际变更)会关闭已打开的 slash 选择器或其确认对话框,不消费草稿;而发布某个 picker 正在等待的读取结果时,该 picker 保持打开并保留失败与重试状态;重新打开时读取当前目录。已经提交的命令在响应结束前继续保持忙碌状态。 @@ -45,7 +45,7 @@ kind: "package-reference"
实现细节——点击展开 -General Settings 行经 `ctx.configForms` 读取显式暴露的 `permission` Settings 描述符,并携带描述符 revision 写入一条 `settings.mutate` 路径操作;其 observable 经 slot 系统的 `hooks` compartment 传递,因此 React 钩子绑定归渲染器,推送失效通知会重新获取描述符。该值只在之后创建会话时读取。当前会话界面是挂在宿主 `/permission` 命令上的 popupSelect 装饰(`ctx.commandUi.decorate`):宿主命令保留斜杠菜单行、带参形式与持久生命周期记账,装饰只把裸调用替换为选择器。一个进程级目录会在首次 Remote 读取前订阅无 payload 的目录通知,并且只发布当前连接代际中最新的完整成功结果。胜出的读取失败或连接 reset 会清空旧快照:composer seat 因此隐藏,直到后续既有触发重试,而 slash 选择器保持可用并在弹窗内显示失败与重试;旧连接代际与 dispose 后才返回的结果会被忽略。它的公共 observable 是 `{ value }` 与 `invalidations`(每次目录通知或连接代际变更打一个点);失败仅供命令式加载内部使用。slash popup 与 composer seat 共用这份目录,而 Session `permissions` 投影只提供 `currentValue`。Full access 与 Auto review 各自携带本地化确认文案;Auto 还携带由共享 popup 外壳渲染的 badge。 +General Settings 行经 `ctx.configForms` 读取显式暴露的 `permission` Settings 描述符,并携带描述符 revision 写入一条 `settings.mutate` 路径操作;其 observable 经 slot 系统的 `hooks` compartment 传递,因此 React 钩子绑定归渲染器,推送失效通知会重新获取描述符。该值只在之后创建会话时读取。当前会话界面是挂在宿主 `/permission` 命令上的 popupSelect 装饰(`ctx.commandUi.decorate`):宿主命令保留斜杠菜单行、带参形式与持久生命周期记账,装饰只把裸调用替换为选择器。一个进程级目录会在首次 Remote 读取前订阅无 payload 的目录通知,并且只发布当前连接代际中最新的完整成功结果。胜出的读取失败或连接 reset 会清空旧快照:composer seat 因此隐藏,直到后续既有触发重试,而 slash 选择器保持可用并在弹窗内显示失败与重试;旧连接代际与 dispose 后才返回的结果会被忽略。它的公共 observable 是 `{ value }` 与 `invalidations`(每次目录通知或连接代际变更打一个点);失败仅供命令式加载内部使用。slash popup 与 composer seat 共用这份目录,而 Session `permissions` 投影只提供 `currentValue`。完全权限与自动审查各自携带本地化确认文案;Auto 还携带由共享 popup 外壳渲染的 badge。
@@ -80,7 +80,7 @@ General Settings 行经 `ctx.configForms` 读取显式暴露的 `permission` Set 这些限制界定了当前权限界面。它们是当前包约束,不是通用策略对比或任务积压。 - **设置行仅限 Web**——非 Web 客户端仍可经 `/permission` 切换当前会话,但不会获得这项浏览器贡献。 -- **Auto review 仅限当前会话**——General Settings 行有意省略它,且只有通过可见选择器选择时才显示实验确认;显式键入 `/permission auto` 已经构成明确同意。 +- **自动审查仅限当前会话**——General Settings 行有意省略它,且只有通过可见选择器选择时才显示实验确认;显式键入 `/permission auto` 已经构成明确同意。 - **预设描述来自宿主**——本地化的内置标签旁边可能显示另一种语言编写的描述。 diff --git a/packages/client/ui-permission-presets/locale/en.json b/packages/client/ui-permission-presets/locale/en.json new file mode 100644 index 0000000000..1b460cc8ed --- /dev/null +++ b/packages/client/ui-permission-presets/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-permission-presets" + } +} diff --git a/packages/client/ui-permission-presets/locale/zh.json b/packages/client/ui-permission-presets/locale/zh.json new file mode 100644 index 0000000000..4ea78d980f --- /dev/null +++ b/packages/client/ui-permission-presets/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "权限模式界面", + "description": "设置新会话的默认权限,并切换当前会话的权限模式。" + } +} diff --git a/packages/client/ui-permission-presets/package.json b/packages/client/ui-permission-presets/package.json index d8b6130eeb..e8e8254014 100644 --- a/packages/client/ui-permission-presets/package.json +++ b/packages/client/ui-permission-presets/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-permission-presets", "description": "Permission surfaces: a new-session default in General settings and a current-session /permission popup over the permissions projection", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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,13 +64,13 @@ "@deepseek-ai/dsh-client-ui-input-trigger": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-permission-presets": "workspace:*", - "@types/react": "~18.3.1", "clsx": "^2.0.0", "react": "^18.2.0", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts", diff --git a/packages/client/ui-permission-presets/src/client/PermissionSelect.module.css b/packages/client/ui-permission-presets/src/client/PermissionSelect.module.css index b40748e22e..a3add30afb 100644 --- a/packages/client/ui-permission-presets/src/client/PermissionSelect.module.css +++ b/packages/client/ui-permission-presets/src/client/PermissionSelect.module.css @@ -52,7 +52,7 @@ .optionLabel { display: inline-flex; - align-items: baseline; + align-items: center; gap: 4px; min-width: 0; max-width: 100%; @@ -67,12 +67,10 @@ .badge { flex: none; - align-self: flex-start; - margin-top: -1px; color: var(--dsw-alias-label-tertiary); font-size: 8px; line-height: 10px; - font-weight: 600; + font-weight: 500; letter-spacing: 0.2px; } @@ -85,8 +83,8 @@ transition: transform 120ms ease; } -/* Narrow composer: the trigger collapses to icon + chevron so the row keeps - fitting. Only triggers that actually carry a mode glyph drop their label — +/* Narrow composer: mode text collapses while icons stay visible. + Only triggers that actually carry a mode glyph drop their label — a host-configured mode without one keeps its text as the sole identifier. The 460px cut is the point where the row (attach + modes + model + send) starts squeezing labels; the container is the composer row (InputBar .row — diff --git a/packages/client/ui-permission-presets/src/client/PermissionSelect.tsx b/packages/client/ui-permission-presets/src/client/PermissionSelect.tsx index f34e2b16e9..0281c41a24 100644 --- a/packages/client/ui-permission-presets/src/client/PermissionSelect.tsx +++ b/packages/client/ui-permission-presets/src/client/PermissionSelect.tsx @@ -2,7 +2,7 @@ import { useEffect, useState } from 'react' import type { ReactNode } from 'react' import clsx from 'clsx' import { - IconChevronDownOutlineRegular, Menu, PermissionIconFullAccessRegular, + IconChevronDownOutlineRegular, Menu, PermissionIconAutoReviewRegular, PermissionIconFullAccessRegular, PermissionIconReadOnlyRegular, PermissionIconWorkspaceWriteRegular, RiskConfirmation, } from '@deepseek-ai/dsh-client-ui-primitives' import type { MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives' @@ -29,6 +29,7 @@ const permissionGlyphs = new Map([ ['read-only', ], ['workspace-write', ], [FULL_ACCESS, ], + [AUTO_REVIEW, ], ]) /** Glyph for a permission option value; host-configured names outside the design set get none. */ @@ -112,7 +113,7 @@ export function PermissionSelect({ : ( {label} - {badge} + {badge} ), ...icon === undefined ? {} : { icon }, @@ -159,8 +160,6 @@ export function PermissionSelect({ const confirmationEnable = confirmation === AUTO_REVIEW ? t('auto.confirm.enable') : t('confirm.enable') - const currentBadge = optionBadge(currentValue, t) - const currentAccessibleLabel = currentBadge === undefined ? currentLabel : `${currentLabel} ${currentBadge}` return ( <> @@ -176,7 +175,7 @@ export function PermissionSelect({ + ) : null}
-
    {cards}
+ {cards.length > 0 ?
    {cards}
: null} ) + } return (
- {showsCards + {showsMainList ? (
-
+

{t('title')}

{t('intro')} @@ -1480,6 +1542,14 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode {
) : null} + {showsMoreList ? ( +
+ +

{t('moreTitle')}

+
+ ) : null} {showsCards && state.status === 'loading' ? : null} {showsCards && state.status === 'unavailable' ? (

@@ -1516,7 +1586,7 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode { t={t} resolveText={resolveText} renderSlot={renderSlot} - onBack={() => { setView({ kind: 'package', name: openPkg.name }) }} + onBack={() => { setView({ kind: 'package', name: openPkg.name, ...openPkgInMore ? { from: 'more' } : {} }) }} /> ) : null} @@ -1531,7 +1601,8 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode { configured={ledger.bundles.has(openPkg.name)} configure={configure(openPkg)} renderSlot={renderSlot} - onBack={() => { setView({ kind: 'list' }) }} + inMore={openPkgInMore} + onBack={() => { setView({ kind: openPkgInMore ? 'more' : 'list' }) }} onSetEnabled={(enabled) => { props.setEnabled(openPkg.name, enabled) }} onUninstall={() => { props.uninstall(openPkg.name) }} onUpdate={() => { props.update(openPkg.name) }} @@ -1543,13 +1614,22 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode { ? { setView({ kind: 'list' }) }} /> : null} {loaded && showsCards - ? officialCards.length === 0 && mine.length === 0 && state.status !== 'error' + ? basicCards.length === 0 && official.length === 0 && mine.length === 0 && state.status !== 'error' ?

{t('empty')}

: ( <> - {renderGroup('official', t('officialTitle'), officialCards)} - {renderGroup('bundles', t('bundlesTitle'), mine.map(packageCard))} - {/* A failed package read trails the groups it left incomplete: right under Official on a + {showsMoreList ? ( +
+
    {more.map(packageCard)}
+
+ ) : ( + <> + {renderGroup('basic', t('basicTitle'), basicCards)} + {renderGroup('extensions', t('extensionsTitle'), extensions.map(packageCard))} + {renderGroup('bundles', t('bundlesTitle'), mine.map(packageCard))} + + )} + {/* A failed package read trails the groups it left incomplete: right under the groups on a first-load failure, and after the kept cards when a refresh fails over stale data. */} {state.status === 'error' && !refreshing ? ( @@ -1568,7 +1648,10 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode { ? renderSlot('plugins.bundle.activation', { packageName: activated.name, onDismiss: () => { setActivation(null) }, - onOpenDetails: () => { setActivation(null); setView({ kind: 'package', name: activated.name }) }, + onOpenDetails: () => { + setActivation(null) + setView({ kind: 'package', name: activated.name, ...showsMoreList ? { from: 'more' } : {} }) + }, }, { entryKey: activated.name }) : null} void /** Put a bundle into, or take it out of, the profile's layer list. */ setEnabled: (packageName: string, enabled: boolean) => void - /** Install the host's catalog version while retaining the current selection. */ + /** Remove an installed package and install the host's catalog version, selected as the package was. */ update: (packageName: string) => void /** Ask before removing a package from the profile. */ uninstall: (packageName: string) => void @@ -423,14 +422,6 @@ export function rowKey(entryId: string): string { return `row:${entryId}` } -/** Identify a bundle row independently of equal child ids in other presets. - * @param row Bundle declaration with its optional preset target. - * @returns Stable identity for list and detail navigation. - */ -export function packageRowKey(row: Pick): string { - return row.preset === undefined ? row.rowId : JSON.stringify([row.preset, row.rowId]) -} - /** * One bundle as the page shows it: its rows joined with the Host's entries. * @param bundle - the Host's bundle. @@ -440,17 +431,14 @@ export function packageRowKey(row: Pick): string export function packageView(bundle: BundleInfo, plugins: readonly PluginInfo[]): PackageView { const rows = bundle.rows.map((row): PackageRow => { const live = row.entryId === undefined ? undefined : plugins.find(plugin => plugin.entryId === row.entryId) - const readOnlyReason = row.readOnlyReason ?? live?.readOnlyReason return { rowId: row.rowId, - ...row.preset === undefined ? {} : { preset: row.preset }, moduleName: row.moduleName, - enabled: row.composition === undefined ? live?.enabled ?? false : row.composition.enabled === true, - phase: row.composition?.fiberPhase ?? live?.fiberPhase ?? null, - ...row.composition?.enabled === 'conditional' ? { conditional: true } : {}, + enabled: live?.enabled ?? false, + phase: live?.fiberPhase ?? null, ...row.meta === undefined ? {} : { meta: row.meta }, ...row.entryId === undefined ? {} : { entryId: row.entryId }, - ...readOnlyReason === undefined ? {} : { readOnlyReason }, + ...live?.readOnlyReason === undefined ? {} : { readOnlyReason: live.readOnlyReason }, } }) return { @@ -676,7 +664,24 @@ export class PluginManagerController { }, update: (packageName) => { const pkg = this.getSnapshot().packages.find(pkg => pkg.name === packageName) - if (pkg?.installTarget !== undefined && pkg.availability !== 'installation') this.openCatalogInstall(pkg, pkg.installTarget, pkg.enabled) + const target = pkg?.installTarget + if (pkg === undefined || target === undefined || pkg.availability === 'installation') return + if (!pkg.installed) { + this.openCatalogInstall(pkg, target, pkg.enabled) + return + } + // An installed package is removed before another version is installed. Without HMR a running bundle stays + // installed, and the installation over it waits for the restart. + void this.run(packageName, { packageName, action: 'uninstall' }, async () => { + const removed = await this.ctx.remote.pluginManager.removeBundle(packageName) + if (removed.ok && removed.value.error?.code === 'stop-profile') { + this.openCatalogInstall(pkg, target, pkg.enabled) + return + } + // A failed removal throws; without HMR a removal waits for the restart, and the installation follows it. + this.applied(removed, packageName) + this.openCatalogInstall(pkg, target, pkg.enabled) + }) }, uninstall: (packageName) => { this.pendingConfirm = () => this.run(packageName, { packageName, action: 'uninstall' }, async () => { @@ -1041,6 +1046,7 @@ export class PluginManagerController { installed: result.bundle ?? null, installedVersion: result.version ?? null, restartRequired: result.application === 'restart-required', + ...result.restartReason === undefined ? {} : { restartReason: result.restartReason }, approvedBuilds: result.approvedBuilds ?? [], ...asked, }) @@ -1212,7 +1218,7 @@ export class PluginManagerController { this.patch({ notice: { kind: 'cancelled', seq: ++this.noticeSeq } }) return case 'restart-required': - this.patch({ notice: { kind: 'restart', packageName, seq: ++this.noticeSeq } }) + this.patch({ notice: { kind: 'restart', packageName, reason: result.restartReason, seq: ++this.noticeSeq } }) return case 'overridden': this.patch({ notice: { kind: 'overridden', packageName, seq: ++this.noticeSeq } }) diff --git a/packages/client/ui-plugin-manager/src/client/navigation-store.ts b/packages/client/ui-plugin-manager/src/client/navigation-store.ts index 3b05463238..05c9870638 100644 --- a/packages/client/ui-plugin-manager/src/client/navigation-store.ts +++ b/packages/client/ui-plugin-manager/src/client/navigation-store.ts @@ -1,12 +1,13 @@ /** Plugin page selection shared by the page and cross-plugin navigation. */ import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store' -/** The plugin list or one bundle, official item, or bundle row. */ +/** The main or additional plugin list, or one bundle, official item, or bundle row. */ type View = | { readonly kind: 'list' } - | { readonly kind: 'package'; readonly name: string } + | { readonly kind: 'more' } + | { readonly kind: 'package'; readonly name: string; readonly from?: 'more' } | { readonly kind: 'item'; readonly id: string } - | { readonly kind: 'row'; readonly name: string; readonly rowId: string } + | { readonly kind: 'row'; readonly name: string; readonly rowId: string; readonly from?: 'more' } type NavigationState = { view: View } type NavigationActions = { setView: (draft: NavigationState, view: View) => void } diff --git a/packages/client/ui-plugin-manager/src/client/presentation.ts b/packages/client/ui-plugin-manager/src/client/presentation.ts index 6c01da2e7c..29b5d1c204 100644 --- a/packages/client/ui-plugin-manager/src/client/presentation.ts +++ b/packages/client/ui-plugin-manager/src/client/presentation.ts @@ -1,6 +1,6 @@ /** Display labels and toast sentences for global plugin management. */ -import type { IncompatiblePlugin, ManagementError, Registry } from '@deepseek-ai/dsh-api-remotes/client' +import type { IncompatiblePlugin, ManagementError, Registry, RestartReason } from '@deepseek-ai/dsh-api-remotes/client' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { PluginManagerLocaleKey } from './locales.ts' import type { FailedAction, ManagerNotice, PackageRow, PackageView, PluginManagerFace } from './manager-store.ts' @@ -48,9 +48,9 @@ function registryHost(registry: string): string { const CODE_KEYS = { 'management-required': 'reasonManagementRequired', 'unaddressable': 'reasonUnaddressable', - 'preset-managed': 'reasonPresetManaged', 'unknown-plugin': 'reasonUnknownPlugin', 'invalid-spec': 'reasonInvalidSpec', + 'already-installed': 'reasonAlreadyInstalled', 'ambiguous-install': 'reasonAmbiguousInstall', 'not-bundle': 'reasonNotBundle', 'not-removable': 'reasonNotRemovable', @@ -139,6 +139,27 @@ export function rowText( } } +/** The sentence naming why a change waits for a restart. */ +const RESTART_REASON_KEYS = { + 'no-hmr': 'restartReasonNoHmr', + 'package-moved': 'restartReasonPackageMoved', + 'host-module': 'restartReasonHostModule', + 'unmanaged-plugin': 'restartReasonUnmanagedPlugin', + 'module-comparison': 'restartReasonModuleComparison', +} satisfies Record + +/** + * A restart prompt with its reason. + * @param key - the prompt's sentence, which takes the reason as `{reason}`. + * @param reason - why the change waits for a restart. + * @param t - the manager's translate seat. + * @returns the prompt. + */ +export function restartText(key: 'restartNotice' | 'installDoneRestart', reason: RestartReason | undefined, t: Translate): string { + // A Host that names no reason still asks for the restart. + return t(key, { reason: reason === undefined ? '' : t(RESTART_REASON_KEYS[reason]) }).trimEnd() +} + /** * The sentence one notice shows. * @param notice - the last action's outcome. @@ -147,7 +168,7 @@ export function rowText( */ export function noticeText(notice: ManagerNotice, t: Translate): string { switch (notice.kind) { - case 'restart': return t('restartNotice') + case 'restart': return restartText('restartNotice', notice.reason, t) case 'overridden': return t('overriddenNotice', { name: notice.packageName }) case 'cancelled': return t('installCancelled') case 'refresh-failed': return t('refreshError') diff --git a/packages/client/ui-plugin-manager/src/client/slot-contract.ts b/packages/client/ui-plugin-manager/src/client/slot-contract.ts index f2dce8cc57..b7d734ae6e 100644 --- a/packages/client/ui-plugin-manager/src/client/slot-contract.ts +++ b/packages/client/ui-plugin-manager/src/client/slot-contract.ts @@ -30,10 +30,8 @@ export interface PluginConfigViewProps { /** One row of a bundle as a detail contribution sees it. */ export interface PluginRowRef { - /** Declared row id, or an internal identity for an anonymous scoped insertion. */ + /** The row id as the bundle's patch declares it. */ readonly rowId: string - /** Outer preset row id; absent for a Host row. */ - readonly preset?: string /** The module the row names. */ readonly moduleName: string /** Whether the row's entry runs. */ diff --git a/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx b/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx index 8d5be40efa..dbce0d098f 100644 --- a/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx +++ b/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx @@ -1,14 +1,14 @@ // @vitest-environment jsdom import assert from 'node:assert/strict' import { Context, Service } from '@deepseek-ai/cordis' -import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { cleanup, render } from '@testing-library/react' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { ILayout, PanelInfo } from '@deepseek-ai/dsh-client-ui-layout/client' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' -import { TestRemote, usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, TestRemote, usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime' import * as settings from '@deepseek-ai/dsh-client-ui-settings/client' import { apply, inject, NS, PANEL_ID } from '../src/client/index.ts' import { PluginManagerPage } from '../src/client/PluginManagerPage.tsx' @@ -17,6 +17,7 @@ import { PluginsPanelIcon } from '../src/client/PluginsPanelIcon.tsx' import type { PluginManagerFace } from '../src/client/manager-store.ts' usePinnedBrowserLanguages('zh-CN') +beforeEach(() => { localStorage.clear() }) afterEach(cleanup) async function bench() { @@ -69,6 +70,7 @@ describe('ui-plugin-manager browser plugin', () => { const entry = b.slots.entries('main')[0]! assert(entry.store && 'create' in entry.store) const navigation = entry.store.create() + expect(navigation.getSnapshot()).toEqual({ view: { kind: 'list' } }) b.ctx.pluginNavigation.openBundle('dsh-navigation-test') expect(b.panelInfo.getSnapshot().activePanelId).toBe(PANEL_ID) expect(navigation.getSnapshot()).toEqual({ view: { kind: 'package', name: 'dsh-navigation-test' } }) @@ -76,6 +78,10 @@ describe('ui-plugin-manager browser plugin', () => { expect(navigation.getSnapshot()).toEqual({ view: { kind: 'list' } }) b.selectPanel(PANEL_ID) expect(navigation.getSnapshot()).toEqual({ view: { kind: 'list' } }) + assert(navigation.actions.setView) + navigation.actions.setView({ kind: 'more' }) + b.selectPanel(null) + expect(navigation.getSnapshot()).toEqual({ view: { kind: 'list' } }) b.ctx.pluginNavigation.openBundle('dsh-navigation-test') removeRoot() b.selectPanel(null) @@ -141,7 +147,7 @@ describe('ui-plugin-manager browser plugin', () => { const unread = () => { throw new Error('The sidebar icon must not read application state') } const glyph = render() + useWorkspaces={unread} useResource={unread} {...allowAllAccess} />) expect(glyph.container.querySelector('svg')?.getAttribute('width')).toBe('18') expect(icon.options).toMatchObject({ id: PANEL_ID, order: 0 }) expect(icon.locale).toBe(NS) diff --git a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx index 6c872c6437..a0055f2a56 100644 --- a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx +++ b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx @@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from import { Context } from '@deepseek-ai/cordis' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import type { PluginEntryId, PluginInstallRequestId } from '@deepseek-ai/dsh-api-remotes/client' -import { bindSnapshotSelector, stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, bindSnapshotSelector, stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' import type { ConfigForm, ConfigFormSnapshot, SettingsMirrorSnapshot } from '@deepseek-ai/dsh-client-ui-settings/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' @@ -19,6 +19,7 @@ import { rowKey, type InstallState, type PackageRow, type PackageView, type Plug import { INSTALL_GIT_EXAMPLE, INSTALL_PATH_EXAMPLE, en, zh, type PluginManagerLocaleKey } from '../src/client/locales.ts' import type { PluginActivationOwnerProps, PluginAddActionsProps, PluginDetailProps, PluginsSubject } from '../src/client/slot-contract.ts' +beforeEach(() => { localStorage.clear() }) afterEach(cleanup) const translate = (dict: typeof en): PluginManagerPageProps['t'] => ((key: PluginManagerLocaleKey, params?: Record): string => @@ -138,6 +139,7 @@ function renderTab( useSessionStatus: unusedStandardHook, useSessionRetainInfo: unusedStandardHook, useResource: unusedStandardHook, + ...allowAllAccess, } const navigation = createNavigationStore().create() const props: PluginManagerPageProps = { @@ -183,6 +185,7 @@ function renderTab( return { navigation, hidePage: () => { showPage = false; rerender(contents()) }, + showPage: () => { showPage = true; rerender(contents()) }, props, unmount, store, @@ -500,15 +503,15 @@ describe('PluginManagerPage', () => { busy: ['dsh-protected'], }) const cards = screen.getAllByRole('listitem') - // The Official group comes first. + // Offered extensions precede installed bundles. expect(cards.map(card => card.getAttribute('data-plugin-package'))).toEqual([ '@deepseek-ai/dsh-experimental-agent-team-profile', 'dsh-better-sidebar', 'dsh-broken', 'dsh-protected', '@acme/dsh-tool', 'dsh-selected', ]) expect(cards.map(card => card.getAttribute('data-plugin-status'))).toEqual(['disabled', 'running', 'problem', 'running', 'disabled', 'problem']) - // Each group heads with its title and its bare count; the official bundle carries its beta tag, no official tag. + // Group titles have no counts; the official bundle retains its experimental marker. expect(screen.getByRole('heading', { name: en.bundlesTitle })).toBeTruthy() - expect(screen.getByRole('heading', { name: en.officialTitle })).toBeTruthy() - expect([...document.querySelectorAll('[data-plugin-count]')].map(count => count.textContent)).toEqual(['1', '5']) + expect(screen.getByRole('heading', { name: en.extensionsTitle })).toBeTruthy() + expect(document.querySelector('[data-plugin-count]')).toBeNull() expect(screen.getAllByText(en.statusBeta)).toHaveLength(1) expect(screen.getByRole('switch', { name: en.enableToggle.replace('{name}', '@acme/dsh-tool') })).toHaveProperty('disabled', false) expect(screen.getByText('A sidebar.')).toBeTruthy() @@ -522,7 +525,7 @@ describe('PluginManagerPage', () => { expect(locked.getAttribute('title')).toBe(en.reasonManagementRequired) }) - it('omits built-in profile dependencies from cards and counts while retaining optional and third-party bundles', () => { + it('omits built-in profile dependencies while retaining optional and third-party bundles', () => { renderTab({ packages: [ ...[ @@ -541,7 +544,7 @@ describe('PluginManagerPage', () => { expect(screen.getAllByRole('listitem').map(card => card.getAttribute('data-plugin-package'))).toEqual([ '@deepseek-ai/dsh-experimental-agent-team-profile', '@acme/dsh-base', 'dsh-better-sidebar', ]) - expect([...document.querySelectorAll('[data-plugin-count]')].map(count => count.textContent)).toEqual(['1', '2']) + expect(document.querySelector('[data-plugin-count]')).toBeNull() }) it.each([false, true])('shows an empty list for built-in bundles with errors and installed=%s', (installed) => { @@ -732,55 +735,6 @@ describe('PluginManagerPage', () => { } }) - it('shows distinct preset targets and keeps scoped rows read-only despite a matching root configuration page', () => { - const rows: PackageRow[] = ['preset-standard', 'preset-cordis'].map(preset => ({ - rowId: 'shared', preset, moduleName: 'shared-tool', enabled: true, phase: 'active', - readOnlyReason: 'preset-managed', meta: { title: 'shared' }, - })) - const subjects: PluginsSubject[] = [] - const { actions, setLanguage } = renderTab({ packages: [pkg({ rows })] }, { rows: new Set(['dsh-better-sidebar#shared']) }, { - 'plugins.detail.actions:': (_view, owner) => { - const subject = subjectOf(owner) - if (subject !== undefined) subjects.push(subject) - return null - }, - }) - fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', 'dsh-better-sidebar') })) - const listed = [...document.querySelectorAll('[data-plugin-row]')] - expect(new Set(listed.map(item => item.getAttribute('data-plugin-row'))).size).toBe(2) - expect(subjects.at(-1)).toMatchObject({ kind: 'bundle', pkg: { rows: [ - { rowId: 'shared', preset: 'preset-standard' }, { rowId: 'shared', preset: 'preset-cordis' }, - ] } }) - expect(screen.getByText('preset-standard/shared')).toBeTruthy() - expect(screen.getByText('preset-cordis/shared')).toBeTruthy() - for (const item of listed) { - const toggle = within(item as HTMLElement).getByRole('switch') - expect(toggle).toHaveProperty('disabled', true) - expect(toggle.getAttribute('title')).toBe(en.reasonPresetManaged) - } - expect(screen.queryByRole('button', { name: en.configureRow.replace('{name}', 'shared') })).toBeNull() - expect(actions.setRowEnabled).not.toHaveBeenCalled() - setLanguage(zh) - for (const item of listed) { - expect(within(item as HTMLElement).getByRole('switch').getAttribute('title')).toBe(zh.reasonPresetManaged) - } - }) - - it('shows an unevaluated preset condition without an Off label or switch', () => { - const rows: PackageRow[] = [{ rowId: 'conditional', preset: 'preset-standard', moduleName: 'tool', - enabled: false, conditional: true, phase: null, readOnlyReason: 'preset-managed' }] - const { setLanguage } = renderTab({ packages: [pkg({ rows })] }) - fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', 'dsh-better-sidebar') })) - const item = document.querySelector('[data-plugin-row]')! - expect(within(item).getByText(en.rowStateConditional)).toBeTruthy() - expect(within(item).queryByText(en.partOff)).toBeNull() - expect(within(item).queryByRole('switch')).toBeNull() - expect(item.getAttribute('data-state')).toBeNull() - expect(screen.queryByText(en.partsCountOff.replace('{count}', '1'), { exact: false })).toBeNull() - setLanguage(zh) - expect(within(item).getByText(zh.rowStateConditional)).toBeTruthy() - }) - it('resolves row fields independently from bundle metadata and preserves subpath specifiers', () => { const rows = [ row({ moduleName: '@acme/dsh-sidebar/navigation', meta: { description: { en: 'Navigation description.' } } }), @@ -908,19 +862,52 @@ describe('PluginManagerPage', () => { 'plugins.row.config:dsh-better-sidebar#sidebar': view => view === 'summary' ? 'The sidebar row.' :
, } - it('lists an official plugin after the official bundles with its summary, and opens its page', () => { + it('keeps configuration and installed plugins on the main list and shows all official plugins on the secondary page', () => { + const team = '@deepseek-ai/dsh-experimental-agent-team-profile' renderTab( - { packages: [pkg({ name: '@deepseek-ai/dsh-experimental-agent-team-profile', installed: false, optional: true, removable: false, enabled: false })] }, + { packages: [ + pkg({ name: '@deepseek-ai/dsh-experimental-badge-skill-bundle', official: true, enabled: false }), + pkg({ name: '@deepseek-ai/dsh-experimental-agent-team-profile', installed: false, optional: true, removable: false, enabled: false }), + pkg({ name: '@deepseek-ai/dsh-subagent-claude-code', official: true, availability: 'missing', installed: false, enabled: false }), + pkg({ name: '@deepseek-ai/dsh-subagent-codex', official: true, enabled: false }), + pkg({ name: '@deepseek-ai/dsh-experimental-tool-worktree', official: true, enabled: false }), + pkg({ name: '@acme/new-official', official: true }), + pkg(), + ] }, { items: [{ id: 'bash', label: 'Shell' }] }, bodies, ) - const official = document.querySelector('[data-plugin-group="official"]') as HTMLElement - expect(within(official).getAllByRole('listitem').map(card => card.getAttribute('data-plugin-item') ?? card.getAttribute('data-plugin-package'))) - .toEqual(['@deepseek-ai/dsh-experimental-agent-team-profile', 'bash']) - expect(document.querySelector('[data-plugin-count]')?.textContent).toBe('2') - expect(within(official).getByText('Limits every command.')).toBeTruthy() - // An official plugin has no switch of its own: the Host composes it. - expect(within(official).queryByRole('switch', { name: en.enableToggle.replace('{name}', 'Shell') })).toBeNull() + const basic = document.querySelector('[data-plugin-group="basic"]') as HTMLElement + const extensions = document.querySelector('[data-plugin-group="extensions"]') as HTMLElement + expect(document.querySelector('[data-plugin-group="more"]')).toBeNull() + expect([...document.querySelectorAll('[data-plugin-group]')].map(group => group.getAttribute('data-plugin-group'))) + .toEqual(['basic', 'extensions', 'bundles']) + expect(within(basic).getAllByRole('listitem').map(card => card.getAttribute('data-plugin-item'))).toEqual(['bash']) + expect(within(extensions).getByRole('heading', { name: en.extensionsTitle })).toBeTruthy() + expect(within(extensions).getByRole('button', { name: en.moreAction }).textContent).toBe(en.moreAction) + expect(within(extensions).getAllByRole('listitem').map(card => card.getAttribute('data-plugin-package'))) + .toEqual(['@deepseek-ai/dsh-experimental-agent-team-profile', '@acme/new-official']) + expect(document.querySelector('[data-plugin-count]')).toBeNull() + expect(within(basic).getByText('Limits every command.')).toBeTruthy() + expect(within(basic).queryByRole('switch', { name: en.enableToggle.replace('{name}', 'Shell') })).toBeNull() + fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', team) })) + fireEvent.click(screen.getByRole('button', { name: en.backToList })) + expect(screen.getByRole('heading', { name: en.title, level: 1 })).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: en.moreAction })) + expect(screen.getByRole('heading', { name: en.moreTitle, level: 1 })).toBeTruthy() + expect(screen.queryByRole('heading', { name: en.moreTitle, level: 3 })).toBeNull() + expect([...document.querySelectorAll('[data-plugin-group]')].map(group => group.getAttribute('data-plugin-group'))) + .toEqual(['more']) + const more = document.querySelector('[data-plugin-group="more"]') as HTMLElement + expect(within(more).getAllByRole('listitem').map(card => card.getAttribute('data-plugin-package'))) + .toEqual([team, '@acme/new-official', '@deepseek-ai/dsh-experimental-tool-worktree', '@deepseek-ai/dsh-experimental-badge-skill-bundle', '@deepseek-ai/dsh-subagent-codex', '@deepseek-ai/dsh-subagent-claude-code']) + expect(document.querySelector('[data-plugin-package="dsh-better-sidebar"]')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', team) })) + fireEvent.click(screen.getByRole('button', { name: en.backToPackage.replace('{name}', en.moreTitle) })) + expect(screen.getByRole('heading', { name: en.moreTitle, level: 1 })).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: en.backToList })) + expect(document.querySelector('[data-plugin-group="more"]')).toBeNull() + expect(document.querySelector('[data-plugin-package="dsh-better-sidebar"]')).not.toBeNull() fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', 'Shell') })) const detail = document.querySelector('[data-plugin-item-detail="bash"]') as HTMLElement expect(within(detail).getByRole('heading', { level: 3 }).textContent).toBe('Shell') @@ -928,7 +915,69 @@ describe('PluginManagerPage', () => { expect(within(detail).getByRole('form', { name: 'bash form' })).toBeTruthy() fireEvent.click(within(detail).getByRole('button', { name: en.backToList })) expect(document.querySelector('[data-plugin-item-detail]')).toBeNull() - expect(screen.getByRole('heading', { name: en.officialTitle })).toBeTruthy() + expect(screen.getByRole('heading', { name: en.basicTitle })).toBeTruthy() + }) + + it('returns from package details to the secondary page and retains it across React remounts', () => { + const name = '@deepseek-ai/dsh-experimental-terminal-bundle' + const b = renderTab({ packages: [pkg({ name, official: true, enabled: false })] }) + fireEvent.click(screen.getByRole('button', { name: en.moreAction })) + expect(screen.getByRole('heading', { name: en.moreTitle, level: 1 })).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', name) })) + fireEvent.click(screen.getByRole('button', { name: en.backToPackage.replace('{name}', en.moreTitle) })) + expect(screen.getByRole('heading', { name: en.moreTitle, level: 1 })).toBeTruthy() + b.hidePage() + b.showPage() + expect(screen.getByRole('heading', { name: en.moreTitle, level: 1 })).toBeTruthy() + expect(document.querySelector(`[data-plugin-package="${name}"]`)).not.toBeNull() + fireEvent.click(screen.getByRole('button', { name: en.backToList })) + expect(document.querySelector(`[data-plugin-package="${name}"]`)).toBeNull() + }) + + it('pins a bundle the profile picks onto the main list, in its full-list place', () => { + const team = '@deepseek-ai/dsh-experimental-agent-team-profile' + const first = '@deepseek-ai/dsh-experimental-tool-worktree' + const second = '@deepseek-ai/dsh-experimental-cot-translation-bundle' + const entry = (name: string, enabled: boolean): PackageView => pkg({ name, official: true, enabled }) + const b = renderTab({ packages: [entry(second, true), entry(team, true), entry(first, false)] }) + const cards = (group: 'extensions' | 'more'): (string | null)[] => { + const list = document.querySelector(`[data-plugin-group="${group}"]`) as HTMLElement + return within(list).getAllByRole('listitem').map(card => card.getAttribute('data-plugin-package')) + } + expect(cards('extensions')).toEqual([team, second]) + fireEvent.click(screen.getByRole('button', { name: en.moreAction })) + expect(cards('more')).toEqual([team, first, second]) + fireEvent.click(screen.getByRole('switch', { name: en.enableToggle.replace('{name}', first) })) + expect(b.actions.setEnabled).toHaveBeenCalledWith(first, true) + b.set({ packages: [entry(second, true), entry(team, true), entry(first, true)] }) + expect(cards('more')).toEqual([team, first, second]) + fireEvent.click(screen.getByRole('button', { name: en.backToList })) + expect(cards('extensions')).toEqual([team, first, second]) + fireEvent.click(screen.getByRole('switch', { name: en.enableToggle.replace('{name}', first) })) + expect(b.actions.setEnabled).toHaveBeenCalledWith(first, false) + b.set({ packages: [entry(second, true), entry(team, true), entry(first, false)] }) + expect(cards('extensions')).toEqual([team, second]) + fireEvent.click(screen.getByRole('button', { name: en.moreAction })) + expect(cards('more')).toEqual([team, first, second]) + }) + + it('returns a held-back bundle opened outside the lists to the list that shows it', () => { + const name = '@deepseek-ai/dsh-experimental-terminal-bundle' + const b = renderTab({ packages: [pkg({ name, official: true, enabled: false })] }) + act(() => { b.navigation.actions.setView({ kind: 'package', name }) }) + expect(document.querySelector(`[data-plugin-detail="${name}"]`)).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: en.backToPackage.replace('{name}', en.moreTitle) })) + expect(screen.getByRole('heading', { name: en.moreTitle, level: 1 })).toBeTruthy() + b.set({ packages: [pkg({ name, official: true, enabled: true })] }) + act(() => { b.navigation.actions.setView({ kind: 'package', name }) }) + fireEvent.click(screen.getByRole('button', { name: en.backToList })) + expect(screen.getByRole('heading', { name: en.title, level: 1 })).toBeTruthy() + }) + + it('starts on the main list when the navigation store is recreated', () => { + const first = createNavigationStore().create() + first.actions.setView({ kind: 'more' }) + expect(createNavigationStore().create().getSnapshot()).toEqual({ view: { kind: 'list' } }) }) it('counts an official plugin as content: the empty line waits for a page with nothing at all', () => { @@ -952,9 +1001,10 @@ describe('PluginManagerPage', () => { expect(within(detail).queryByRole('button', { name: en.configureRow.replace('{name}', 'dsh-better-sidebar') })).toBeNull() }) - it('opens a row\'s configuration page from its configure control and leads back to the bundle', () => { + it.each([false, true])('opens row configuration and returns to the bundle and originating list, from secondary page: %s', (fromMore) => { const theme = row({ rowId: 'theme', moduleName: 'dsh-better-sidebar/theme', entryId: 'include:theme' as PluginEntryId }) - renderTab({ packages: [pkg({ rows: [row(), theme] })] }, { rows: new Set(['dsh-better-sidebar#sidebar']) }, bodies) + renderTab({ packages: [pkg({ official: fromMore, rows: [row(), theme] })] }, { rows: new Set(['dsh-better-sidebar#sidebar']) }, bodies) + if (fromMore) fireEvent.click(screen.getByRole('button', { name: en.moreAction })) fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', 'dsh-better-sidebar') })) expect(screen.queryByRole('button', { name: en.configureRow.replace('{name}', 'dsh-better-sidebar/theme') })).toBeNull() fireEvent.click(screen.getByRole('button', { name: en.configureRow.replace('{name}', 'dsh-better-sidebar') })) @@ -967,6 +1017,8 @@ describe('PluginManagerPage', () => { fireEvent.click(within(page).getByRole('button', { name: en.backToPackage.replace('{name}', 'dsh-better-sidebar') })) expect(document.querySelector('[data-plugin-row-detail]')).toBeNull() expect(document.querySelector('[data-plugin-detail="dsh-better-sidebar"]')).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: fromMore ? en.backToPackage.replace('{name}', en.moreTitle) : en.backToList })) + expect(screen.getByRole('heading', { name: fromMore ? en.moreTitle : en.title, level: 1 })).toBeTruthy() }) }) @@ -1441,9 +1493,9 @@ describe('PluginManagerPage', () => { expect(screen.queryByRole('button', { name: en.installEditAria })).toBeNull() fireEvent.click(screen.getByRole('button', { name: en.installEnableNow })) expect(actions.enableInstalled).toHaveBeenCalledTimes(1) - set({ install: { ...IDLE_INSTALL, open: true, spec: '/plugins/dsh-x', phase: 'done', subject, installed: 'dsh-x', restartRequired: true, enabling: true } }) + set({ install: { ...IDLE_INSTALL, open: true, spec: '/plugins/dsh-x', phase: 'done', subject, installed: 'dsh-x', restartRequired: true, restartReason: 'host-module', enabling: true } }) expect(screen.getByRole('button', { name: en.installEnableNow })).toHaveProperty('disabled', true) - expect(screen.getByText(en.installDoneRestart)).toBeTruthy() + expect(screen.getByText(en.installDoneRestart.replace('{reason}', en.restartReasonHostModule))).toBeTruthy() // A run that named no bundle leaves only Done. set({ install: { ...IDLE_INSTALL, open: true, spec: 'dsh-x', phase: 'done', subject: { spec: 'dsh-x', status: 'accepted', kind: 'registry', name: 'dsh-x', bundle: true, registry: null } } }) @@ -1859,13 +1911,14 @@ describe('PluginManagerPage', () => { const descriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollIntoView') Object.defineProperty(Element.prototype, 'scrollIntoView', { value: scrollIntoView, configurable: true }) try { - const { actions, set } = renderTab({ packages: [pkg()] }) + const { actions, set } = renderTab({ packages: [pkg(), pkg({ name: '@deepseek-ai/dsh-experimental-terminal-bundle', official: true })] }) // A package the list does not show has nothing to scroll to; the mark still times out. set({ highlight: 'missing' }) expect(scrollIntoView).not.toHaveBeenCalled() act(() => { vi.advanceTimersByTime(2_400) }) expect(actions.clearHighlight).toHaveBeenCalledTimes(1) set({ highlight: 'dsh-better-sidebar' }) + expect(screen.getByRole('heading', { name: en.title, level: 1 })).toBeTruthy() expect(document.querySelector('[data-plugin-package="dsh-better-sidebar"]')?.hasAttribute('data-plugin-highlight')).toBe(true) expect(scrollIntoView).toHaveBeenCalledWith({ block: 'center', behavior: 'smooth' }) act(() => { vi.advanceTimersByTime(2_400) }) @@ -1879,6 +1932,61 @@ describe('PluginManagerPage', () => { } }) + it('highlights only the visible list and does not extend the mark when navigating or refreshing', () => { + vi.useFakeTimers() + const name = '@deepseek-ai/dsh-experimental-terminal-bundle' + const scrollIntoView = vi.fn() + const descriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollIntoView') + Object.defineProperty(Element.prototype, 'scrollIntoView', { value: scrollIntoView, configurable: true }) + try { + const { actions, set } = renderTab({ packages: [ + pkg({ name, official: true, enabled: false }), + pkg({ name: '@deepseek-ai/dsh-subagent-codex', official: true, enabled: false }), + ] }) + expect(document.querySelector(`[data-plugin-package="${name}"]`)).toBeNull() + set({ highlight: name }) + expect(screen.getByRole('heading', { name: en.title, level: 1 })).toBeTruthy() + expect(scrollIntoView).not.toHaveBeenCalled() + set({ highlight: null }) + fireEvent.click(screen.getByRole('button', { name: en.moreAction })) + set({ highlight: name }) + expect(screen.getByRole('heading', { name: en.moreTitle, level: 1 })).toBeTruthy() + expect(document.querySelector(`[data-plugin-package="${name}"]`)?.hasAttribute('data-plugin-highlight')).toBe(true) + expect(scrollIntoView).toHaveBeenCalledExactlyOnceWith({ block: 'center', behavior: 'smooth' }) + act(() => { vi.advanceTimersByTime(1_600) }) + fireEvent.click(screen.getByRole('button', { name: en.backToList })) + expect(screen.getByRole('heading', { name: en.title, level: 1 })).toBeTruthy() + expect(document.querySelector(`[data-plugin-package="${name}"]`)).toBeNull() + expect(scrollIntoView).toHaveBeenCalledTimes(1) + set({ packages: [pkg({ name, official: true, enabled: false })] }) + act(() => { vi.advanceTimersByTime(799) }) + expect(actions.clearHighlight).not.toHaveBeenCalled() + act(() => { vi.advanceTimersByTime(1) }) + expect(actions.clearHighlight).toHaveBeenCalledTimes(1) + } finally { + if (descriptor === undefined) delete (Element.prototype as { scrollIntoView?: unknown }).scrollIntoView + else Object.defineProperty(Element.prototype, 'scrollIntoView', descriptor) + vi.useRealTimers() + } + }) + + it('keeps edited configuration open and preserves explicit detail navigation after remounting with a highlight', () => { + const b = renderTab({ packages: [pkg()] }, { items: [{ id: 'bash', label: 'Shell' }] }, { + 'plugins.item:bash': view => view === 'page' ? : null, + }) + act(() => { b.navigation.actions.setView({ kind: 'item', id: 'bash' }) }) + const draft = screen.getByRole('textbox', { name: 'Draft setting' }) + fireEvent.change(draft, { target: { value: 'unsaved change' } }) + b.set({ highlight: 'dsh-better-sidebar' }) + expect(screen.getByRole('textbox', { name: 'Draft setting' })).toBe(draft) + expect(draft).toHaveProperty('value', 'unsaved change') + + b.hidePage() + act(() => { b.navigation.actions.setView({ kind: 'package', name: 'dsh-better-sidebar' }) }) + b.showPage() + expect(document.querySelector('[data-plugin-detail="dsh-better-sidebar"]')).not.toBeNull() + }) + it('marks a card without a scrollIntoView to call', () => { vi.useFakeTimers() const descriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollIntoView') @@ -1913,8 +2021,11 @@ describe('PluginManagerPage', () => { it('words every notice as a toast that dismisses itself', () => { vi.useFakeTimers() try { - const { actions, set } = renderTab({ notice: { kind: 'restart', packageName: 'x', seq: 1 } }) - expect(screen.getByRole('alert').textContent).toContain(en.restartNotice) + const { actions, set } = renderTab({ notice: { kind: 'restart', packageName: 'x', reason: 'no-hmr', seq: 1 } }) + expect(screen.getByRole('alert').textContent).toContain(en.restartNotice.replace('{reason}', en.restartReasonNoHmr)) + // A Host that names no reason still asks for the restart. + set({ notice: { kind: 'restart', packageName: 'x', reason: undefined, seq: 4 } }) + expect(screen.getByRole('alert').textContent).toContain(en.restartNotice.replace(' {reason}', '')) set({ notice: { kind: 'overridden', packageName: 'pkg-1', seq: 2 } }) expect(screen.getByRole('alert').textContent).toContain(en.overriddenNotice.replace('{name}', 'pkg-1')) set({ notice: { kind: 'cancelled', seq: 3 } }) @@ -1989,25 +2100,29 @@ describe('PluginManagerPage', () => { }) }) -it('offers bundle-owned guidance only after explicit enablement and navigates to its detail page', () => { - const name = 'dsh-better-sidebar' - const { set, actions } = renderTab({ packages: [pkg({ enabled: false })] }, { bundles: new Set([name]) }, { +it.each([false, true])('opens activation guidance details and returns to the originating list (experimental: %s)', (fromMore) => { + const name = fromMore ? '@deepseek-ai/dsh-experimental-terminal-bundle' : 'dsh-better-sidebar' + const bundle = pkg({ name, official: fromMore }) + const { set, actions } = renderTab({ packages: [{ ...bundle, enabled: false }] }, { bundles: new Set([name]) }, { [`plugins.bundle.activation:${name}`]: (_view, owner) => , [`plugins.bundle.config:${name}`]: () =>
Bundle setup
, }) + if (fromMore) fireEvent.click(screen.getByRole('button', { name: en.moreAction })) expect(screen.queryByText('Go to setup')).toBeNull() - set({ packages: [pkg()] }) + set({ packages: [bundle] }) expect(screen.queryByText('Go to setup')).toBeNull() - set({ packages: [pkg({ enabled: false })] }) + set({ packages: [{ ...bundle, enabled: false }] }) fireEvent.click(screen.getByRole('switch')) expect(actions.setEnabled).toHaveBeenCalledWith(name, true) expect(screen.queryByText('Go to setup')).toBeNull() - set({ packages: [pkg()], busy: [name] }) + set({ packages: [bundle], busy: [name] }) expect(screen.queryByText('Go to setup')).toBeNull() set({ busy: [] }) fireEvent.click(screen.getByText('Go to setup')) expect(screen.getByText('Bundle setup')).toBeTruthy() expect(screen.queryByText('Go to setup')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: fromMore ? en.backToPackage.replace('{name}', en.moreTitle) : en.backToList })) + expect(screen.getByRole('heading', { name: fromMore ? en.moreTitle : en.title, level: 1 })).toBeTruthy() }) it('dismisses activation guidance until the user enables the bundle again', () => { @@ -2030,7 +2145,7 @@ it('dismisses activation guidance until the user enables the bundle again', () = it('supplies the accepted entry values and atomic mutation action to a custom plugin page', () => { const mutate = vi.fn(async () => true) const form: ConfigPageForm = { - state: { status: 'ready', value: { count: 2 }, base: {}, user: {}, revision: 7, writable: true, mode: 'host' }, mutate, + state: { status: 'ready', value: { count: 2 }, base: {}, user: {}, revision: 7, writable: true }, mutate, } renderTab({}, { items: [{ id: 'custom', label: 'Custom' }] }, { 'plugins.item:custom': (view, _owner, supplied) => view === 'summary' ? 'Custom summary' @@ -2050,12 +2165,14 @@ describe('on-demand Official bundles', () => { installTarget: { spec: `${name}@2.0.0`, version: '2.0.0' }, }) - it('keeps one card in Official before installation, after installation, and after removal', () => { + it('keeps one card on the secondary page before installation, after installation, and after removal', () => { const entry = catalog() const { actions, set } = renderTab({ packages: [entry] }) + expect(document.querySelector(`[data-plugin-package="${name}"]`)).toBeNull() + fireEvent.click(screen.getByRole('button', { name: en.moreAction })) const assertOfficial = () => { expect(document.querySelectorAll(`[data-plugin-package="${name}"]`)).toHaveLength(1) - expect(document.querySelector('[data-plugin-group="official"]')?.contains(document.querySelector(`[data-plugin-package="${name}"]`))).toBe(true) + expect(document.querySelector('[data-plugin-group="more"]')?.contains(document.querySelector(`[data-plugin-package="${name}"]`))).toBe(true) expect(document.querySelector('[data-plugin-group="bundles"]')).toBeNull() } assertOfficial() @@ -2074,12 +2191,14 @@ describe('on-demand Official bundles', () => { status: 'accepted', kind: 'registry', name, version: '2.0.0', spec: `${name}@2.0.0`, registry: null, bundle: true, selection: true, saveExact: true, } } }) + fireEvent.click(screen.getByRole('button', { name: en.moreAction })) expect(screen.getByRole('switch', { name: en.enableToggle.replace('{name}', title) }).hasAttribute('disabled')).toBe(true) }) it('offers an explicit update and displays installed and target versions', () => { const entry = { ...catalog(), installed: true, availability: 'profile' as const, removable: true, version: '1.0.0' } const { actions } = renderTab({ packages: [entry] }) + fireEvent.click(screen.getByRole('button', { name: en.moreAction })) expect(screen.getByText(en.statusUpdateAvailable)).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', title) })) const detail = document.querySelector('[data-plugin-detail]') as HTMLElement @@ -2091,6 +2210,7 @@ describe('on-demand Official bundles', () => { it.each([undefined, `${name}@1.0.0`])('retains dependency source=%s beside unavailable status and the update action', (source) => { renderTab({ packages: [{ ...catalog(), ...source === undefined ? {} : { source }, installed: true, removable: true, error: { code: 'operation-error', diagnostic: 'Unreadable package files' } }] }) + fireEvent.click(screen.getByRole('button', { name: en.moreAction })) expect(screen.getByText(en.statusMissingFiles)).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', title) })) const detail = document.querySelector('[data-plugin-detail]') as HTMLElement @@ -2111,6 +2231,7 @@ describe('on-demand Official bundles', () => { const entry: PackageView = { ...catalog(), installed: true, availability: 'profile', removable: true, version: '2.0.0', installTarget: { spec, version: '2.0.0' }, ...source === undefined ? {} : { source } } renderTab({ packages: [entry] }) + fireEvent.click(screen.getByRole('button', { name: en.moreAction })) expect(screen.queryByText(en.statusUpdateAvailable) !== null).toBe(expected) fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', title) })) const detail = document.querySelector('[data-plugin-detail]') as HTMLElement @@ -2123,6 +2244,7 @@ describe('on-demand Official bundles', () => { const { installTarget: _target, ...entry } = catalog() const { actions, set } = renderTab({ packages: [{ ...entry, enabled: true, error: { code: 'operation-error', diagnostic: 'Source package is not built' } }] }) + fireEvent.click(screen.getByRole('button', { name: en.moreAction })) const toggle = screen.getByRole('switch', { name: en.enableToggle.replace('{name}', title) }) expect(toggle.hasAttribute('disabled')).toBe(false) fireEvent.click(toggle) @@ -2133,6 +2255,7 @@ describe('on-demand Official bundles', () => { it('does not present an absent catalog package as built in or as an empty loaded component list', () => { renderTab({ packages: [catalog()] }) + fireEvent.click(screen.getByRole('button', { name: en.moreAction })) fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', title) })) const detail = document.querySelector('[data-plugin-detail]') as HTMLElement expect(within(detail).queryByText(en.sourceBuiltIn)).toBeNull() diff --git a/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts b/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts index 90d8e7a10a..53e3b1d66c 100644 --- a/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts +++ b/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts @@ -8,7 +8,7 @@ import type { BundleInfo, ChangeResult, ManagementError, PluginEntryId, PluginIn import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' import type { ConfigLedger } from '../src/client/config-ledger.ts' -import { offeredRegistries, packageView, packageRowKey, PluginManagerController, rowKey, sortPackages } from '../src/client/manager-store.ts' +import { offeredRegistries, packageView, PluginManagerController, rowKey, sortPackages } from '../src/client/manager-store.ts' const INCOMPATIBLE = { name: 'dsh-late', version: '2.0.0', runtimeVersion: '0.1.0', peers: { '@deepseek-ai/dsh': '^0.2.0' } } const ROW_ENTRY = 'include:sidebar' as PluginEntryId @@ -116,19 +116,6 @@ it('hands a custom page the shared configuration form of its entry', () => { }) describe('packageView', () => { - it('keeps scoped rows read-only with distinct identities and their observed preset state', () => { - const view = packageView({ ...BUNDLE, rows: [ - { rowId: 'shared', preset: 'preset-standard', moduleName: 'tool', readOnlyReason: 'preset-managed', composition: { enabled: true, fiberPhase: 'active' } }, - { rowId: 'shared', preset: 'preset-cordis', moduleName: 'tool', readOnlyReason: 'preset-managed', composition: { enabled: 'conditional', fiberPhase: null } }, - ] }, []) - expect(view.rows).toEqual([ - { rowId: 'shared', preset: 'preset-standard', moduleName: 'tool', enabled: true, phase: 'active', readOnlyReason: 'preset-managed' }, - { rowId: 'shared', preset: 'preset-cordis', moduleName: 'tool', enabled: false, phase: null, conditional: true, readOnlyReason: 'preset-managed' }, - ]) - expect(new Set(view.rows.map(packageRowKey)).size).toBe(2) - expect(packageRowKey({ rowId: 'ordinary' })).toBe('ordinary') - }) - it('joins a bundle with the entries its rows run as', () => { expect(packageView(BUNDLE, PLUGINS)).toEqual({ name: 'dsh-better-sidebar', version: '0.16.0', description: 'A sidebar.', source: 'dsh-better-sidebar@^0.16.0', @@ -763,9 +750,9 @@ describe('PluginManagerController', () => { controller.installProgress({ requestId, phase: 'applying' }) controller.appendLog({ requestId, jobId: 'old', argv: [], cwd: '/p', stream: 'stdout', text: 'late' }) expect(state().install).toMatchObject({ phase: 'starting', runs: [] }) - second.resolve(ok({ ...APPLIED, application: 'restart-required', bundle: 'slow' })) + second.resolve(ok({ ...APPLIED, application: 'restart-required', restartReason: 'no-hmr', bundle: 'slow' })) await vi.waitFor(() => { expect(state().install.phase).toBe('done') }) - expect(state().install).toMatchObject({ installed: 'slow', restartRequired: true }) + expect(state().install).toMatchObject({ installed: 'slow', restartRequired: true, restartReason: 'no-hmr' }) }) it.each(['too-late', 'not-running', 'offline'] as const)('keeps a stop the Host answered %s apart from a stopped run', async (status) => { @@ -1866,7 +1853,7 @@ it.each(['before', 'after'] as const)('reports one Official toggle when inventor expect(track.mock.calls.filter(([event]) => event === 'plugin_toggle')).toHaveLength(1) }) -it.each([true, false])('updates an Official entry with enabled=%s through the same exact installer', async (enabled) => { +it.each([true, false])('updates an Official entry with enabled=%s by removing it, then using the same exact installer', async (enabled) => { const installed: BundleInfo = { ...CATALOG, availability: 'profile', installed: true, version: '1.0.0', enabled, removable: true } const { controller, plugins, face, state } = bench({ listBundles: vi.fn().mockResolvedValue(ok([installed])), installBundle: vi.fn().mockResolvedValue(ok({ ...APPLIED, bundle: CATALOG.name, application: 'restart-required' })), @@ -1875,12 +1862,44 @@ it.each([true, false])('updates an Official entry with enabled=%s through the sa face.update(CATALOG.name) await vi.waitFor(() => { expect(state().install.phase).toBe('done') }) expect(plugins.inspect).not.toHaveBeenCalled() + expect(plugins.removeBundle).toHaveBeenCalledWith(CATALOG.name) + expect(plugins.removeBundle.mock.invocationCallOrder[0]).toBeLessThan(plugins.installBundle.mock.invocationCallOrder[0]!) expect(plugins.installBundle).toHaveBeenCalledWith(CATALOG.installTarget!.spec, { enabled, saveExact: true, requestId: state().install.requestId, registry: null, }) expect(state().install.restartRequired).toBe(true) }) +it('keeps an installed Official entry and installs nothing when its removal for an update fails', async () => { + const installed: BundleInfo = { ...CATALOG, availability: 'profile', installed: true, version: '1.0.0', enabled: true, removable: true } + const { controller, plugins, face, state } = bench({ listBundles: vi.fn().mockResolvedValue(ok([installed])), + removeBundle: vi.fn().mockResolvedValue(ok({ ...APPLIED, application: 'failed', error: { code: 'bundle-in-use' } })), + }) + await controller.load() + face.update(CATALOG.name) + await vi.waitFor(() => { expect(state().notice).toMatchObject({ kind: 'failed', action: 'uninstall' }) }) + expect(plugins.installBundle).not.toHaveBeenCalled() +}) + +it.each([ + ['an unreachable Host', () => refused('ERR_REMOTE', 'connection lost')], + ['a profile without HMR', () => ok({ ...APPLIED, application: 'failed', error: { code: 'stop-profile' } })], +] as const)('installs an Official update only after the removal, except over a running bundle of %s', async (kind, answer) => { + const installed: BundleInfo = { ...CATALOG, availability: 'profile', installed: true, version: '1.0.0', enabled: true, removable: true } + const { controller, plugins, face, state } = bench({ listBundles: vi.fn().mockResolvedValue(ok([installed])), + removeBundle: vi.fn().mockResolvedValue(answer()), + }) + await controller.load() + face.update(CATALOG.name) + if (kind === 'an unreachable Host') { + await vi.waitFor(() => { expect(state().notice).toMatchObject({ kind: 'failed', action: 'uninstall' }) }) + expect(plugins.installBundle).not.toHaveBeenCalled() + } else { + // Without HMR a running bundle stays installed, and the installation over it waits for the restart. + await vi.waitFor(() => { expect(plugins.installBundle).toHaveBeenCalled() }) + } +}) + it('preserves the Official exact target and selection when script approval retries an installation', async () => { const install = vi.fn().mockResolvedValueOnce(ok({ ...APPLIED, application: 'failed', stage: 'install', error: { code: 'operation-error' }, pendingBuilds: ['native-provider'], @@ -1986,6 +2005,7 @@ it.each([true, false])('replaces a same-version registry package with its source await controller.load() face.update(entry.name) await vi.waitFor(() => { expect(state().install.phase).toBe('done') }) + expect(plugins.removeBundle).toHaveBeenCalledWith(CATALOG.name) expect(plugins.installBundle).toHaveBeenCalledWith(spec, { enabled, requestId: state().install.requestId, registry: null }) expect(state().install.subject).toMatchObject({ kind: 'path', spec, selection: enabled }) expect(state().install.restartRequired).toBe(true) diff --git a/packages/client/ui-plugin-manager/tsdown.config.ts b/packages/client/ui-plugin-manager/tsdown.config.ts index 1169a7be7c..620261533c 100644 --- a/packages/client/ui-plugin-manager/tsdown.config.ts +++ b/packages/client/ui-plugin-manager/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-plugin-manager', ['lib/types/index.js'], { hostPhase: true }) +export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 06cd120754..2e59aaf715 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -18,14 +18,14 @@ en: 7bae72c97d0449f5 zh: 4589ecc2b216edc5 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: - en: 66d83132d97e56c6 - zh: fb47139ce1f742fe + en: 6f5457b84fc9db09 + zh: 85993f1c44bfee2c /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: - en: f0e54915b896af5a - zh: 2047520fd321be90 + en: 28ac8f0b1edbcf81 + zh: 5c4c324bf84a282f /deepseek-ai-dsh-client-ui-primitives/use-this-package/rendering-agent-output: - en: 4a1a61bb2d64fe4c - zh: 1b0097fff440c2ef + en: 12fe9d9b1410edef + zh: f2dfdc01170d7cce /deepseek-ai-dsh-client-ui-primitives/use-this-package/localizing-copy: en: 4aef65dea11de083 zh: abc22cd7c65cdf38 @@ -42,8 +42,8 @@ en: 8bbfa14c27f3bfd7 zh: 88f7548ac3a114e1 /deepseek-ai-dsh-client-ui-primitives/understand-the-implementation/geometry-and-overflow: - en: e283bf2366b43879 - zh: d089076d7834e853 + en: 45f4cd1ef96bb6d2 + zh: f264d25b780ad1dc /deepseek-ai-dsh-client-ui-primitives/further-exploration: en: e82b713cdb2f954b zh: a877f34b148f433f diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 509fdd62fe..5b29187be1 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -54,22 +54,23 @@ Check this table before writing a control in a feature package. A plugin cannot | `PathLabel` | Single-line file path with subdued directories, a primary filename, and the full path on hover. Fitting paths align left; clipped paths preserve their suffix with a left-edge fade that updates on path and size changes. | | `StateDot` | Solid green `done`, amber `warning`, red `error`, and neutral-grey `idle` marks in a 10px slot, plus a tertiary-grey 14px rotating `ongoing` loader whose animations pin to document time zero on mount and on every animation restart, such as a list reorder, so every visible loader rotates in phase. `aria-hidden`, so the render site owns the name. `appearance="step"` shows a filled check for completion and a hollow pending circle. | | `ConnectionIndicator` | Inline connection-recovery control across outage, retry, and recovered states. | -| `DisclosureRow` | 24px compact disclosure that lays title and content side by side. The header supplies tertiary at rest and secondary on hover; text and icons inherit it regardless of expandability or open state unless the caller supplies a feature-specific override. Semantic status colors remain explicit. Collapsed rows preview a down chevron on hover, and expanded rows keep an up chevron visible. Memoized with shallow prop comparison; keep callbacks and React-node props stable when their content is unchanged. | +| `DisclosureRow` | 24px compact disclosure that lays title and content side by side. The header supplies tertiary at rest and secondary on hover; text and icons inherit it regardless of expandability or open state unless the caller supplies a feature-specific override. Semantic status colors remain explicit. Collapsed rows preview a down chevron on hover, and expanded rows keep an up chevron visible. `headerAccessory` places an independent action outside the disclosure target and shimmer; with an accessory, the title row shrinks to its content width. Memoized with shallow prop comparison; keep callbacks and React-node props stable when their content is unchanged. | | `TextShimmer` | One left-to-right highlight across a row’s title, separators, summary, and suffix, with a 300ms initial delay, a one-second sweep and a 500ms rest. The mask spans the content width, capped by the visible row and tilts 15° from vertical, with a flat peak and soft edges. The moving decoration stays clipped to the row without enlarging its scrollable area. Base text inherits the caller’s color, including hover changes; the theme supplies the translucent highlight. Place icons and chevrons outside `TextShimmer` so only text and separators receive the highlight. A string child uses the same retained text interface; nested `TextShimmer` instances share the outer animation. Composite children render twice while active and must have no effects or element ids. Mark separators with `data-shimmer-decoration` so their fill receives the highlight. `DisclosureRow` forwards `contentClassName` for the text area and `contentLayoutClassName` for its inner layout. The inert decorative copy is excluded from interaction, selection, and accessibility; text updates retain the animation, and reduced-motion mode keeps the static base. | | `Modal` | Centered dialog over a page mask. A nested dialog can intercept keys with `onKeyDownCapture` before document Escape handlers. The tint and dialog fade in while backdrop blur stays fully applied, honoring reduced motion. Set `backdropBlur={false}` when the caller already blurs the source page. | | `RiskConfirmation` | Sensitive action gated behind an explicit checkbox. | | `Tooltip` | Hover and keyboard-focus text anchored to a cloned child; optional `delayMs` controls hover delay and `focusDelayMs` controls keyboard-focus delay, both defaulting to 0 ms. Optional `portal` rendering escapes clipping containers and ancestor stacking contexts that cap the bubble's z-index. | -| `HoverCard` | Hover preview the pointer can rest on and select from; optional copy button. | +| `HoverCard`, `HoverCardGroup` | Readable, optionally copyable hover preview; a physical list can opt cards into shared first-display dwell and exclusive display. | | `ImageLightbox` | Shared image modal with focus restoration and Escape dismissal. | | `Toast` | Transient top-center banner held for the owner's `holdMs`. | | `SettingsForm`, `SettingsValueField`, `SettingsSecretField` | The frame and the controls of a plugin's settings page: the frame takes its copy as `labels`, saves only on its button, and discards on unmount; a value field shows staged text with the overridden badge and reset; a secret field starts blank, requests no saved-password autofill, and reports only whether a value is configured. | | `SettingsFormModel`, `settingsNumberField`, `settingsTextField` | The staged-edit model behind such a page over a settings scope: drafts are staged and written on save, a field is overridden by its presence in the user layer, and a save that did not land keeps its drafts. | | `JsonTree`, `JsonBlock` | Read-only JSON inspection. | | `MarkdownText`, `MarkdownDelegateProvider`, `CodeBlock` | Untrusted GFM with TeX math, owner-delegated HTTP(S) navigation, and highlighted code. `CodeBlock` accepts opt-in `lineNumbers`; copied source excludes the gutter, and `contentRef` exposes its stable source wrapper to an owner that uses it as a scrollport. Set `showHeader={false}` when the owner supplies its own language and copy toolbar. | +| `UserTextRun`, `ReferenceChip` | Uninterpreted inline text and business-resolved reference labels or activation buttons. | | `CommandText` | Selectable command or argument text; only horizontal overflow adds a named keyboard focus target. | | `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, `WebBlock` | The agent-output card matching each tool-result intent. | | `icons/*`, `FishLogo`, `BrandWordmark`, `ReferenceIconRegular`/`ReferenceIconMedium`, `LinkIconRegular`/`LinkIconMedium` | Glyphs and brand marks. The thinking glyph keeps an inset orbit within its 16px view box. Use `LinkIconMedium` for 14px clickable-link categories and known-site marks. | -| `PermissionIconReadOnlyRegular`/`Medium`, `PermissionIconWorkspaceWriteRegular`/`Medium`, `PermissionIconFullAccessRegular`/`Medium` | Permission-mode glyphs for read-only, workspace-write, and full-access choices. | +| `PermissionIconReadOnlyRegular`/`Medium`, `PermissionIconWorkspaceWriteRegular`/`Medium`, `PermissionIconFullAccessRegular`/`Medium`, `PermissionIconAutoReviewRegular`/`Medium` | Permission-mode glyphs for read-only, workspace-write, full-access, and auto-review choices. | | `PluginArtworkTerminal`/`Loop`/`Subagent`/`Search`/`Default` | Fixed-palette 36×36 plugin artwork; `Terminal` supplies the light-blue prompt in plugin cards and sidebar guide entries. `Default` marks plugins without artwork of their own. Def ids are per-instance, so the same artwork repeats safely on one page. | | `GuideArtworkBrowser`/`Files` | Fixed-palette 36×36 browser and folder artwork for sidebar guide entries. | | `FileTypeIcon`, `classifyFileType`, `fileExtension` | A category-colored 28px file or folder glyph and the shared case-insensitive filename mapping behind it. Code and configuration files use detailed full-color technology glyphs; use `LinkIconMedium` for link-leading glyphs and image previews for image content. | @@ -86,17 +87,19 @@ Writing your own component in your own package is fine when the need is genuinel ### Controls and icons -The catalog above lists what each export is for; this section covers the behavior that props alone do not show. Product icon names omit artboard sizes and end in `Regular` for the supplied one-pixel artwork or `Medium` for the same geometry at a 1.3px stroke; the `size` prop controls rendered dimensions. Named components keep the chosen weight visible at import sites; the library owns stroke geometry instead of consumer CSS overrides. Each product, reference, link, and permission glyph intentionally keeps both weight exports even when the current product uses only one, so callers can choose emphasis without adding another API later; fill-only pairs render identically. `IconWarningOutlineRegular`/`Medium` use a circle; `IconWarningTriangleOutlineRegular`/`Medium` use a rounded triangle. `FishLogo` and `BrandWordmark` fill brand slots. `FileTypeIcon` renders the traditional 28px spreadsheet, folder, HTML, image, Markdown, generic, PDF, PPT, video, and Word glyphs, and uses the imported square technology artwork for the established 48 code and configuration categories. The import replaces artwork only: archive-only categories do not extend `CodeFileType`. `classifyFileType` applies exact filename, prefix, suffix, optional project-context, and extension rules in that order; React names win over TypeScript/JavaScript, Angular suffixes win over their base extension, and a Dart file becomes Flutter only when the supplied project files contain a `pubspec.yaml` with `flutter:`. Markdown and SVG remain traditional Markdown and image files. Spreadsheet mappings include CSV, TSV, Excel workbooks and templates, OpenDocument spreadsheets, and Numbers; KEY maps to slides, while RTF/ODT/Pages map to documents. `fileExtension` exposes the same basename and final-dot parsing for adjacent metadata labels. Traditional glyphs use a solid category-colored sheet with a white mark and translucent white corner; the generic code glyph uses angle brackets and a slash at the supplied 1.35px stroke; the generic file uses a grey sheet and darker grey corner. Callers may override the sheet color through `--dsh-file-type-icon-color`. The full-color technology artwork is the deliberate exception and retains its embedded palette. All glyphs are decorative and carry no label. `LinkIconMedium` is the leading glyph for clickable artifact links — globe, folder, code, image, document, or plain paper, and for a `url` link the mark of a well-known site named by its `href` — the developer sites a transcript usually cites (GitHub, GitLab, npm, PyPI, Stack Overflow, MDN, Wikipedia, Hacker News, YouTube, X, Bilibili, Zhihu, Juejin, CSDN) and mainstream search, video, social, shopping, and reference sites (Google, Baidu, DuckDuckGo, TikTok, Netflix, Spotify, Facebook, Instagram, Reddit, Telegram, WhatsApp, WeChat, QQ, Weibo, Taobao, AliExpress, eBay, Quora, V2EX, Apple) — while `classifyLinkPath` folds the shared file types into that existing six-category vocabulary. `ConnectionIndicator` renders a warning-colored disconnected action whose permanent retry glyph marks the retry action beside the owner-supplied outage label, the shared ongoing loader in the same warning color as its label whose one-to-three dots advance every 500ms independently of retry timing, or a success-colored recovered status. Clicking either warning state requests an immediate reconnect; no hover interaction changes the copy. The pill fades in on appearance, fades out for 150ms before unmounting, and sizes to its current label. Its owner supplies visibility, the recovery hold, localized labels, and the immediate-reconnect callback; the primitive uses no native title tooltip. `useAnchoredPosition` and `useAnchoredMaxHeight` keep floating panels and bottom-anchored overlays clamped to the viewport and following their anchor; anchored overlays and portalled `Menu` add 20px to the frame's published top clearance, or keep 20px in native fullscreen, while preserving their own minimum margins in ordinary browsers. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. Its `preview` variant uses the anchor or `widthAnchorRef` element’s width minus 48px, centers the panel with 24px side insets, and places it above or below the row within the viewport. The panel keeps the frame’s top clearance, caps its height at 420px, and follows content and anchor resizing; Escape or pointer and keyboard activation of the anchor dismisses it. The whole preview fades in and out over 100ms; a closing preview stops receiving pointer input and unmounts after the fade. Re-entering the anchor during the fade restores it. Reduced-motion preferences suppress the transition. Copy labels are required only when copying is enabled. A `Tooltip` nested in the anchor hides that preview while its own hover or focus label is visible; releasing, disabling, or unmounting the nested tooltip restores a still-open preview. `Toast` uses the owner's `holdMs` for both the fade delay and its hold-and-fade lifetime. Rerenders with unchanged `holdMs` do not restart that lifetime; completion uses the latest callback, and fully faded actions cannot receive input. A new component key restarts the banner. `rankByName` is the `/` menu's shared candidate ranker for the command and skill sources: the query must be a case-insensitive ordered subsequence of the name; prefix hits rank first, then alignment score, then source order. Portalled `Menu` lists follow their anchor during dragging and CSS transforms, and stop tracking when closed. `Menu.autoFocus` focuses its first enabled item, supports Arrow Up/Down and Home/End navigation, and focuses the first button in the anchor on Escape; it is opt-in for action menus. +The catalog above lists what each export is for; this section covers the behavior that props alone do not show. Product icon names omit artboard sizes and end in `Regular` for the supplied one-pixel artwork or `Medium` for the same geometry at a 1.3px stroke; the `size` prop controls rendered dimensions. Named components keep the chosen weight visible at import sites; the library owns stroke geometry instead of consumer CSS overrides. Each product, reference, link, and permission glyph intentionally keeps both weight exports even when the current product uses only one, so callers can choose emphasis without adding another API later; fill-only pairs render identically. `IconWarningOutlineRegular`/`Medium` use a circle; `IconWarningTriangleOutlineRegular`/`Medium` use a rounded triangle. `FishLogo` and `BrandWordmark` fill brand slots. `FileTypeIcon` renders the traditional 28px spreadsheet, folder, HTML, image, Markdown, generic, PDF, PPT, video, and Word glyphs, and uses the imported square technology artwork for the established 48 code and configuration categories. The import replaces artwork only: archive-only categories do not extend `CodeFileType`. `classifyFileType` applies exact filename, prefix, suffix, optional project-context, and extension rules in that order; React names win over TypeScript/JavaScript, Angular suffixes win over their base extension, and a Dart file becomes Flutter only when the supplied project files contain a `pubspec.yaml` with `flutter:`. Markdown and SVG remain traditional Markdown and image files. Spreadsheet mappings include CSV, TSV, Excel workbooks and templates, OpenDocument spreadsheets, and Numbers; KEY maps to slides, while RTF/ODT/Pages map to documents. `fileExtension` exposes the same basename and final-dot parsing for adjacent metadata labels. Traditional glyphs use a solid category-colored sheet with a white mark and translucent white corner; the generic code glyph uses angle brackets and a slash at the supplied 1.35px stroke; the generic file uses a grey sheet and darker grey corner. Callers may override the sheet color through `--dsh-file-type-icon-color`. The full-color technology artwork is the deliberate exception and retains its embedded palette. All glyphs are decorative and carry no label. `LinkIconMedium` is the leading glyph for clickable artifact links — globe, folder, code, image, document, or plain paper, and for a `url` link the mark of a well-known site named by its `href` — the developer sites a transcript usually cites (GitHub, GitLab, npm, PyPI, Stack Overflow, MDN, Wikipedia, Hacker News, YouTube, X, Bilibili, Zhihu, Juejin, CSDN) and mainstream search, video, social, shopping, and reference sites (Google, Baidu, DuckDuckGo, TikTok, Netflix, Spotify, Facebook, Instagram, Reddit, Telegram, WhatsApp, WeChat, QQ, Weibo, Taobao, AliExpress, eBay, Quora, V2EX, Apple) — while `classifyLinkPath` folds the shared file types into that existing six-category vocabulary. `ConnectionIndicator` renders a warning-colored disconnected action whose permanent retry glyph marks the retry action beside the owner-supplied outage label, the shared ongoing loader in the same warning color as its label whose one-to-three dots advance every 500ms independently of retry timing, or a success-colored recovered status. Clicking either warning state requests an immediate reconnect; no hover interaction changes the copy. The pill fades in on appearance, fades out for 150ms before unmounting, and sizes to its current label. Its owner supplies visibility, the recovery hold, localized labels, and the immediate-reconnect callback; the primitive uses no native title tooltip. `useAnchoredPosition` and `useAnchoredMaxHeight` keep floating panels and bottom-anchored overlays clamped to the viewport and following their anchor; anchored overlays and portalled `Menu` add 20px to the frame's published top clearance, or keep 20px in native fullscreen, while preserving their own minimum margins in ordinary browsers. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. Its `preview` variant uses the anchor or `widthAnchorRef` element’s width minus 48px, centers the panel with 24px side insets, and places it above or below the row within the viewport. The panel keeps the frame’s top clearance, caps its height at 420px, and follows content and anchor resizing; Escape or pointer and keyboard activation of the anchor dismisses it. The whole preview fades in and out over 100ms; a closing preview stops receiving pointer input and unmounts after the fade. Re-entering the anchor during the fade restores it. Reduced-motion preferences suppress the transition. Copy labels are required only when copying is enabled. `HoverCard` and nested action tooltips display independently; use `Tooltip.portal` to layer the small bubble above the card. A visible nested `Tooltip` suppresses only its enclosing tooltip, not the hover card. `Toast` uses the owner's `holdMs` for both the fade delay and its hold-and-fade lifetime. Rerenders with unchanged `holdMs` do not restart that lifetime; completion uses the latest callback, and fully faded actions cannot receive input. A new component key restarts the banner. `rankByName` is the `/` menu's shared candidate ranker for the command and skill sources: the query must be a case-insensitive ordered subsequence of the name; prefix hits rank first, then alignment score, then source order. Portalled `Menu` lists follow their anchor during dragging and CSS transforms, and stop tracking when closed. `Menu.autoFocus` focuses its first enabled item, supports Arrow Up/Down and Home/End navigation, and focuses the first button in the anchor on Escape; it is opt-in for action menus. `Tooltip` reads the anchor on hover or keyboard focus and fits its bubble from `ResizeObserver` border-box sizes. The bubble stays hidden until its first fit, slides inside the horizontal viewport margin, and flips above or below only when the opposite side fits. Label-size and viewport changes reuse the anchor coordinates; fitting does not synchronously measure the bubble or trigger a React render. Opt-in `openOnClick` also lets an informational button pin the same bubble for reading and associates it with the anchor description. Another click, Escape, Tab, or an outside pointerdown closes it; ordinary action tooltips still dismiss on click. +`HoverCardGroup` owns private state for one mounted physical list. A `HoverCard` with `grouped` shares the first actually displayed card's dwell: subsequent cards replace the current card immediately during the same pointer interaction. The list and its active portaled card form one pointer interaction: the pointer may enter the card to read or copy, then return to another list item for immediate replacement. After the pointer leaves both, the shared dwell resets when the active card closes through its existing pointer-grace and close lifecycle; the group adds no separate timer. Leaving a list with no active card resets the dwell immediately. Opening an inline card by keyboard focus while the pointer is outside the list does not warm the next pointer visit. Exclusive display includes fading previews: ordinary preview dismissal retains its fade, but a group replacement removes the previous card immediately. Cards without `grouped` remain independent. + ### Rendering agent output The nearest `MarkdownDelegateProvider` supplies optional `openExternalLink` and `openFile` navigation callbacks. Nested providers replace the enclosing capabilities, and callback changes reach already-rendered links without rebuilding Markdown. Its `openFile` makes local Markdown links clickable after settlement. Absolute and workspace-relative paths support percent escapes and `#L24` / `#L24-L30` fragments; ranges open at their first line. Literal `?` and `#` in filenames must be percent-encoded. The tooltip uses the decoded path and supplies the accessible name when the label is empty. The callback receives the decoded path and optional line, while the renderer preserves the label and displays a file icon. Without a callback, local links remain text. URL schemes, queries, unsupported fragments, and malformed destinations never reach the file opener. -`MarkdownText` renders untrusted GFM and TeX math, blocks unsafe links and images, and can turn resolved file mentions into explicit controls. A surrounding `MarkdownDelegateProvider` receives sanitized HTTP(S) URLs from ordinary clicks; modified clicks and links outside a provider retain native external-anchor behavior. When the owner passes a `pathImages` vocabulary, image destinations that are local media paths rewrite to displayable URLs on settled renders only (the same streaming gate as file mentions); without a vocabulary, local destinations remain inert alt text. Rewritten images accept HTTP(S), data, blob, and the Desktop `dsh-app://app/api/file` route; authored Desktop URLs remain inert. A load or decode failure replaces the image with its authored alt text, or the original destination when alt is empty; `fileImages` additionally supplies a localized failure prefix. Changing the image source permits a fresh load. While a reply streams, it freezes completed blocks, advances a top-level open fence by completed lines, and highlights that fence from saved Shiki grammar state. Completed token lines enter fixed-size React groups, so later chunks reconcile only the growing group; an unchanged fence retains that DOM when the final full parse resolves cross-document syntax. `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, and `WebBlock` render the matching tool-result intent with copy controls, overflow handling, and ANSI processing where applicable. `JsonTree` and `JsonBlock` inspect JSON values read-only, while `projectUserText` projects sent user text into inline plain runs and reference chips for the message bubble and queue rows. Reference labels inherit the consumer’s wrapping policy: long names wrap within a bubble, while queue previews retain their single-line layout. When supplied with `UserTextReferences`, file and skill references become keyboard-accessible preview buttons using the same hover and focus styling as prose file links; the first pointer click can open a preview, while subsequent clicks and existing text selections retain native selection handling. Keyboard activation opens previews even when text is selected. +`MarkdownText` renders untrusted GFM and TeX math, blocks unsafe links and images, and can turn resolved file mentions into explicit controls. A surrounding `MarkdownDelegateProvider` receives sanitized HTTP(S) URLs from ordinary clicks; modified clicks and links outside a provider retain native external-anchor behavior. When the owner passes a `pathImages` vocabulary, image destinations that are local media paths rewrite to displayable URLs on settled renders only (the same streaming gate as file mentions); without a vocabulary, local destinations remain inert alt text. Rewritten images accept HTTP(S), data, blob, and the Desktop `dsh-app://app/api/file` route; authored Desktop URLs remain inert. A load or decode failure replaces the image with its authored alt text, or the original destination when alt is empty; `fileImages` additionally supplies a localized failure prefix. Changing the image source permits a fresh load. While a reply streams, it freezes completed blocks, advances a top-level open fence by completed lines, and highlights that fence from saved Shiki grammar state. Completed token lines enter fixed-size React groups, so later chunks reconcile only the growing group; an unchanged fence retains that DOM when the final full parse resolves cross-document syntax. `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, and `WebBlock` render the matching tool-result intent with copy controls, overflow handling, and ANSI processing where applicable. `JsonTree` and `JsonBlock` inspect JSON values read-only, while `UserTextRun` renders uninterpreted text and `ReferenceChip` renders business-resolved labels. An explicit `onActivate` makes a chip a keyboard-accessible button; repeated pointer clicks and an existing text selection do not activate it, while keyboard activation remains available. Labels inherit their host’s wrapping policy. Recognition and JSON transforms belong to [ui-conversation](../ui-conversation/README.md#sent-user-text). `MarkdownText` defaults to `variant="body"`. Use `variant="compact"` for secondary content: its 13px text and 20px line height follow the content-size setting, all heading levels use the same size with weight 600, and paragraphs and lists use tighter spacing. Text, links, and code keep the tertiary color; dotted underlines distinguish links. Code headers scroll with their blocks. Tables and math stay enabled at the surrounding text size and scroll horizontally within the available width. Both variants share the parser and streaming cache. @@ -161,7 +164,7 @@ While a reply streams, `MarkdownText` parses incrementally: all but the trailing ### Geometry and overflow -The output cards share one geometry model: `white-space: pre` with horizontal scrolling so column-aligned content keeps its alignment, and a head-plus-tail slice behind an expand button past `maxLines` (default 16) so a long body never stretches the card. `TerminalBlock` uses `CommandText` to keep each authored command line selectable and horizontally scrollable; the prompt and status stay fixed. Only horizontally overflowing text enters the Tab order as a named group, using the owner’s localized `commandLine(line)` label. Text that fits, including wrapped Jobs commands, adds no Tab stop. Size, text, and font changes update focusability without changing the scroll position. `TerminalBlock` parses ANSI into React spans with a per-line column buffer for cursor movement, honoring erase-in-line, tab stops, and character width. Hosts opt out of the shared geometry per surface: rebinding `--dsl-terminal-command-whitespace` / `--dsl-terminal-line-whitespace` to `pre-wrap` wraps commands and output in full with no sideways scroll, `maxLines: Infinity` disables the fold for hosts capping height through `--dsl-terminal-output-max-height` instead, `copyText` overrides the copy payload (and keeps the control rendered before any output), and `runStateDot: false` omits the run-state dot when the surrounding row already carries the state, reclaiming its gutter via `--dsl-terminal-gutter`. The banner divider follows the rendered body, so a running card that streams live output separates its command from the text like a settled card. +The output cards share one geometry model: `white-space: pre` with horizontal scrolling so column-aligned content keeps its alignment, and a head-plus-tail slice behind an expand button past `maxLines` (default 16) so a long body never stretches the card. `TerminalBlock` uses `CommandText` to keep each authored command line selectable and horizontally scrollable; the prompt and status stay fixed. The run-state dot aligns with the first visual command line, including when the command wraps. Only horizontally overflowing text enters the Tab order as a named group, using the owner’s localized `commandLine(line)` label. Text that fits, including wrapped Jobs commands, adds no Tab stop. Size, text, and font changes update focusability without changing the scroll position. `TerminalBlock` parses ANSI into React spans with a per-line column buffer for cursor movement, honoring erase-in-line, tab stops, and character width. Hosts opt out of the shared geometry per surface: rebinding `--dsl-terminal-command-whitespace` / `--dsl-terminal-line-whitespace` to `pre-wrap` wraps commands and output in full with no sideways scroll, `maxLines: Infinity` disables the fold for hosts capping height through `--dsl-terminal-output-max-height` instead, `copyText` overrides the copy payload (and keeps the control rendered before any output), and `runStateDot: false` omits the run-state dot when the surrounding row already carries the state, reclaiming its gutter via `--dsl-terminal-gutter`. `background` defaults to false and carries the call's background flag. For a background call, `running` indicates launch-call progress: Start shows that indicator; the acknowledgement sets `running` to false and leaves the command static without a state dot or assistive label. Background calls omit output, empty-output placeholders, exit pills, and the default output Copy control; an explicit `copyText` override remains available. The banner divider follows the rendered body, so a running card that streams live output separates its command from the text like a settled card. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 1f458060ed..c1593e273b 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -54,22 +54,23 @@ kind: "package-library" | `PathLabel` | 单行文件路径:目录使用弱化颜色,文件名使用主色,悬停可查看完整路径。空间足够时靠左显示;溢出时保留尾部并在左侧渐隐,路径或尺寸变化时更新。 | | `StateDot` | 10px 槽内的绿色 `done`、琥珀色 `warning`、红色 `error`、中性灰色 `idle` 圆点,以及 tertiary 灰色 14px 旋转 `ongoing` loading,其动画在挂载时以及每次动画重启(如列表重排)时固定到文档时间零点,所以所有可见 loading 同相旋转。它是 `aria-hidden` 的,名称由渲染点提供。 `appearance="step"` 以实心勾表示完成、空心圆表示等待。 | | `ConnectionIndicator` | 行内连接恢复控件,覆盖断线、重试与已恢复三种状态。 | -| `DisclosureRow` | 24px 紧凑折叠行,标题与内容左右排列。标题行默认使用 tertiary,悬停时使用 secondary;文字与图标继承该颜色,不受能否展开及开合状态影响,调用方可提供功能专属覆盖。语义状态色保持显式指定。收起时悬停预览向下箭头,展开后持续显示向上箭头。使用浅层 prop 比较进行 memo;内容未变时,保持回调与 React 节点 prop 的引用稳定。 | +| `DisclosureRow` | 24px 紧凑折叠行,标题与内容左右排列。标题行默认使用 tertiary,悬停时使用 secondary;文字与图标继承该颜色,不受能否展开及开合状态影响,调用方可提供功能专属覆盖。语义状态色保持显式指定。收起时悬停预览向下箭头,展开后持续显示向上箭头。`headerAccessory` 将独立操作放在折叠触发区域和流光之外;有此操作时,标题行收窄到内容宽度。使用浅层 prop 比较进行 memo;内容未变时,保持回调与 React 节点 prop 的引用稳定。 | | `TextShimmer` | 同一道高光从左到右扫过一行的标题、分隔符、摘要与后缀:首次等待 300ms,扫动一秒,再静止 500ms。遮罩覆盖内容宽度,并限制在可见行宽内,相对垂直方向倾斜 15°,峰值区域平坦,两侧柔和渐隐。移动的装饰层始终裁剪在行内,不会扩大可滚动区域。底色继承调用方的颜色,包括悬停变化;主题提供半透明高光。图标和箭头放在 `TextShimmer` 外,只有文字和分隔符参与扫光。字符串子节点沿用稳定的文字接口;嵌套的 `TextShimmer` 共用外层动画。活动期间组合子节点渲染两次,因此不得带副作用或元素 id。分隔符标记 `data-shimmer-decoration`,让填色参与扫光。`DisclosureRow` 将 `contentClassName` 传给文字区域,将 `contentLayoutClassName` 传给内部布局。惰性装饰副本不参与交互、选区和无障碍访问;文字更新保留动画,减少动态效果模式保留静态底色。 | | `Modal` | 页面遮罩之上的居中对话框。嵌套对话框可通过 `onKeyDownCapture` 在文档级 Escape 处理器之前拦截按键。 色层与弹窗淡入,背景模糊始终完整生效,并遵循减少动态效果偏好。调用方已模糊源页面时设置 `backdropBlur={false}`。 | | `RiskConfirmation` | 以显式复选框把关的敏感操作确认。 | | `Tooltip` | 锚定在克隆子元素上的悬停与键盘聚焦提示;可选的 `delayMs` 控制悬停延迟,`focusDelayMs` 控制键盘聚焦延迟,均默认为 0 毫秒。可通过 `portal` 渲染到外层,避免被容器裁剪,或受祖先层叠上下文限制其 z-index。 | -| `HoverCard` | 指针可停留、可选中的悬停预览;可选带复制按钮。 | +| `HoverCard`、`HoverCardGroup` | 可阅读、可选带复制按钮的悬停预览;物理列表可选择让卡片共享首次显示等待,并互斥显示。 | | `ImageLightbox` | 共享图片浮层,支持焦点恢复与 Esc 关闭。 | | `Toast` | 顶部居中的瞬时横幅,保持时长由所有者的 `holdMs` 决定。 | | `SettingsForm`、`SettingsValueField`、`SettingsSecretField` | 插件设置页的框架与控件:框架以 `labels` 接收文案,只在按钮点击时保存,卸载即丢弃;值字段显示暂存文本以及已覆盖标签和重置;密文字段每次为空,请求浏览器不要自动填入已保存的密码,只报告是否已配置。 | | `SettingsFormModel`、`settingsNumberField`、`settingsTextField` | 这类页面背后基于设置 scope 的暂存编辑模型:草稿先暂存、保存时写入,字段是否被覆盖看用户层是否含有它,未落地的保存保留草稿。 | | `JsonTree`、`JsonBlock` | 只读 JSON 查看。 | | `MarkdownText`、`MarkdownDelegateProvider`、`CodeBlock` | 不可信 GFM 与 TeX 数学、owner 委托的 HTTP(S) 导航,以及高亮代码。`CodeBlock` 可通过 `lineNumbers` 开启行号;复制的源码不含行号栏,`contentRef` 则向需要把稳定源码包装节点用作滚动区的 owner 提供该节点。调用方提供自己的语言与复制工具栏时,设置 `showHeader={false}`。 | +| `UserTextRun`、`ReferenceChip` | 不做解析的行内文本,以及业务已解析的引用标签或激活按钮。 | | `CommandText` | 可选中的命令或参数文本;仅横向溢出时添加具名的键盘聚焦目标。 | | `TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock`、`WebBlock` | 与各类工具结果意图对应的 agent 输出卡片。 | | `icons/*`、`FishLogo`、`BrandWordmark`、`ReferenceIconRegular`/`ReferenceIconMedium`、`LinkIconRegular`/`LinkIconMedium` | 字形与品牌标识。思考图标的轨道在 16px 视口内保留内边距。`LinkIconMedium` 用于 14px 的可点击链接分类及已知站点标记。 | -| `PermissionIconReadOnlyRegular`/`Medium`、`PermissionIconWorkspaceWriteRegular`/`Medium`、`PermissionIconFullAccessRegular`/`Medium` | 只读、工作区写入与完全访问选项使用的权限模式图形。 | +| `PermissionIconReadOnlyRegular`/`Medium`、`PermissionIconWorkspaceWriteRegular`/`Medium`、`PermissionIconFullAccessRegular`/`Medium`、`PermissionIconAutoReviewRegular`/`Medium` | 只读、工作区写入、完全访问与自动审查选项使用的权限模式图形。 | | `PluginArtworkTerminal`/`Loop`/`Subagent`/`Search`/`Default` | 固定配色的 36×36 插件插画;`Terminal` 为插件卡片和侧边栏开始页入口提供浅蓝色提示符。`Default` 用于没有自有插画的插件。def id 按实例生成,同一插画可在一页中安全重复。 | | `GuideArtworkBrowser`/`Files` | 固定配色的 36×36 浏览器与文件夹插画,用于侧栏引导入口。 | | `FileTypeIcon`、`classifyFileType`、`fileExtension` | 按类别着色的 28px 文件或文件夹图形,以及它背后共享的不区分大小写文件名映射。代码与配置文件使用细分的全彩技术图形;链接前置图形使用 `LinkIconMedium`,图片内容使用图片预览。 | @@ -86,17 +87,19 @@ kind: "package-library" ### 控件与图标 -上面的目录说明每个导出的用途;本节讲 props 本身看不出来的行为。产品图标名称不含画板尺寸,以 `Regular` 表示原始 1px 图形,以 `Medium` 表示同一几何的 1.3px 描边;`size` prop 控制渲染尺寸。具名组件让所选线重在导入处可见;描边几何由组件库拥有,而不是由消费方 CSS 覆盖。每个产品、引用、链接与权限图形都会有意保留两种线重导出,即使当前产品只使用其中一种,也让调用方无需再次扩展 API 就能选择强调程度;仅填充的成对图形外观相同。`IconWarningOutlineRegular`/`Medium` 使用圆形;`IconWarningTriangleOutlineRegular`/`Medium` 使用圆角三角形。`FishLogo` 与 `BrandWordmark` 填充品牌 slot。`FileTypeIcon` 渲染传统的 28px spreadsheet、folder、HTML、image、Markdown、generic、PDF、PPT、video 与 Word 图形,并为现有 48 个代码和配置类别使用导入的方形技术图形。该导入只替换图形:资源包中额外的类别不会扩展 `CodeFileType`。`classifyFileType` 按完整文件名、前缀、后缀、可选项目上下文、扩展名的顺序匹配;React 文件名优先于 TypeScript/JavaScript,Angular 后缀优先于基础扩展名,只有传入的项目文件包含带 `flutter:` 的 `pubspec.yaml` 时 Dart 文件才使用 Flutter。Markdown 与 SVG 仍分别使用传统 Markdown 与图片图形。表格映射包括 CSV、TSV、Excel 工作簿与模板、OpenDocument 表格和 Numbers;KEY 映射为幻灯片,RTF/ODT/Pages 映射为文档。`fileExtension` 为相邻元数据 label 暴露同一套 basename 与最终点号解析。传统图形使用实色分类底板、白色标记和半透明白色折角;通用代码图形使用尖括号与斜线,保留原图 1.35px 描边;通用文件使用灰色底板与较深灰色折角。调用方可通过 `--dsh-file-type-icon-color` 覆盖底板颜色。全彩技术图形是明确例外,会保留其内嵌调色板。所有图形都是装饰性的,不自带 label。`LinkIconMedium` 是可点击产物链接的前置图形——地球、文件夹、代码、图片、文档或纸张,`url` 链接的 `href` 指向已知站点时则改用该站点自己的标记——转写内容常引用的开发者站点(GitHub、GitLab、npm、PyPI、Stack Overflow、MDN、Wikipedia、Hacker News、YouTube、X、Bilibili、知乎、掘金、CSDN),以及主流搜索、视频、社交、购物与参考资料站点(Google、百度、DuckDuckGo、TikTok、Netflix、Spotify、Facebook、Instagram、Reddit、Telegram、WhatsApp、微信、QQ、微博、淘宝、速卖通、eBay、Quora、V2EX、Apple)——`classifyLinkPath` 把共享文件类型折叠进原有六类词汇。`ConnectionIndicator` 可渲染警告色的断联操作(常驻重试图形指明重试动作,断联文案由持有方提供)、与文案使用相同警告色的共享 ongoing loading 加一至三个点以独立于 retry 时序的 500ms 节奏推进的连接中状态,或成功色的恢复状态。点击任一警告状态都会请求立即重连;没有任何悬停交互会改变文案。药丸出现时淡入、卸载前淡出 150ms,宽度随当前 label 自适应。它的持有方提供可见性、恢复驻留时间、本地化 label 与立即重连回调;该原语不使用原生 title tooltip。`useAnchoredPosition` 与 `useAnchoredMaxHeight` 让浮动面板与底部锚定浮层始终钳制在视口内并跟随锚点;锚定浮层与 portal 模式的 `Menu` 在框架发布的顶部占用量上增加 20px,原生全屏时保留 20px,普通浏览器中沿用自身的最小边距。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。其 `preview` 变体使用 anchor 或 `widthAnchorRef` 元素的宽度减去 48px,左右各内缩 24px,并在视口内放置于行的上方或下方。浮层避开框架顶部保留区,高度最多 420px,会跟随内容及 anchor 尺寸变化;Escape 或通过鼠标和键盘激活锚点可将其关闭。整个浮层的淡入和淡出各持续 100ms;关闭中的浮层停止接收指针输入,淡出后卸载。在淡出期间移回锚点可恢复显示。减少动态效果偏好会禁用过渡动画。只有启用复制时才必须提供复制标签。锚点中嵌套的 `Tooltip` 在显示悬停或焦点标签时隐藏该预览;嵌套提示释放、禁用或卸载后,仍处于打开状态的预览会恢复。`Toast` 使用调用方的 `holdMs` 同时控制淡出延迟与停留加淡出的总时长。`holdMs` 未变时,父组件重渲染不会重启该生命周期;完成时调用最新回调,完全淡出的操作不能接收输入。新的组件 key 会重新开始横幅周期。`rankByName` 是 `/` 菜单命令源与 skill(技能)源共享的候选排序器:查询必须是名字的不区分大小写的有序子序列;前缀命中排最前,其次按对齐分数,再按来源顺序。 portal 模式的 `Menu` 列表会在拖动和 CSS 变换期间跟随锚点,并在关闭时停止跟踪。`Menu.autoFocus` 聚焦首个启用项,支持上下方向键与 Home/End 导航,并在 Escape 时聚焦 anchor 内的第一个按钮;操作菜单可显式启用。 +上面的目录说明每个导出的用途;本节讲 props 本身看不出来的行为。产品图标名称不含画板尺寸,以 `Regular` 表示原始 1px 图形,以 `Medium` 表示同一几何的 1.3px 描边;`size` prop 控制渲染尺寸。具名组件让所选线重在导入处可见;描边几何由组件库拥有,而不是由消费方 CSS 覆盖。每个产品、引用、链接与权限图形都会有意保留两种线重导出,即使当前产品只使用其中一种,也让调用方无需再次扩展 API 就能选择强调程度;仅填充的成对图形外观相同。`IconWarningOutlineRegular`/`Medium` 使用圆形;`IconWarningTriangleOutlineRegular`/`Medium` 使用圆角三角形。`FishLogo` 与 `BrandWordmark` 填充品牌 slot。`FileTypeIcon` 渲染传统的 28px spreadsheet、folder、HTML、image、Markdown、generic、PDF、PPT、video 与 Word 图形,并为现有 48 个代码和配置类别使用导入的方形技术图形。该导入只替换图形:资源包中额外的类别不会扩展 `CodeFileType`。`classifyFileType` 按完整文件名、前缀、后缀、可选项目上下文、扩展名的顺序匹配;React 文件名优先于 TypeScript/JavaScript,Angular 后缀优先于基础扩展名,只有传入的项目文件包含带 `flutter:` 的 `pubspec.yaml` 时 Dart 文件才使用 Flutter。Markdown 与 SVG 仍分别使用传统 Markdown 与图片图形。表格映射包括 CSV、TSV、Excel 工作簿与模板、OpenDocument 表格和 Numbers;KEY 映射为幻灯片,RTF/ODT/Pages 映射为文档。`fileExtension` 为相邻元数据 label 暴露同一套 basename 与最终点号解析。传统图形使用实色分类底板、白色标记和半透明白色折角;通用代码图形使用尖括号与斜线,保留原图 1.35px 描边;通用文件使用灰色底板与较深灰色折角。调用方可通过 `--dsh-file-type-icon-color` 覆盖底板颜色。全彩技术图形是明确例外,会保留其内嵌调色板。所有图形都是装饰性的,不自带 label。`LinkIconMedium` 是可点击产物链接的前置图形——地球、文件夹、代码、图片、文档或纸张,`url` 链接的 `href` 指向已知站点时则改用该站点自己的标记——转写内容常引用的开发者站点(GitHub、GitLab、npm、PyPI、Stack Overflow、MDN、Wikipedia、Hacker News、YouTube、X、Bilibili、知乎、掘金、CSDN),以及主流搜索、视频、社交、购物与参考资料站点(Google、百度、DuckDuckGo、TikTok、Netflix、Spotify、Facebook、Instagram、Reddit、Telegram、WhatsApp、微信、QQ、微博、淘宝、速卖通、eBay、Quora、V2EX、Apple)——`classifyLinkPath` 把共享文件类型折叠进原有六类词汇。`ConnectionIndicator` 可渲染警告色的断联操作(常驻重试图形指明重试动作,断联文案由持有方提供)、与文案使用相同警告色的共享 ongoing loading 加一至三个点以独立于 retry 时序的 500ms 节奏推进的连接中状态,或成功色的恢复状态。点击任一警告状态都会请求立即重连;没有任何悬停交互会改变文案。药丸出现时淡入、卸载前淡出 150ms,宽度随当前 label 自适应。它的持有方提供可见性、恢复驻留时间、本地化 label 与立即重连回调;该原语不使用原生 title tooltip。`useAnchoredPosition` 与 `useAnchoredMaxHeight` 让浮动面板与底部锚定浮层始终钳制在视口内并跟随锚点;锚定浮层与 portal 模式的 `Menu` 在框架发布的顶部占用量上增加 20px,原生全屏时保留 20px,普通浏览器中沿用自身的最小边距。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。其 `preview` 变体使用 anchor 或 `widthAnchorRef` 元素的宽度减去 48px,左右各内缩 24px,并在视口内放置于行的上方或下方。浮层避开框架顶部保留区,高度最多 420px,会跟随内容及 anchor 尺寸变化;Escape 或通过鼠标和键盘激活锚点可将其关闭。整个浮层的淡入和淡出各持续 100ms;关闭中的浮层停止接收指针输入,淡出后卸载。在淡出期间移回锚点可恢复显示。减少动态效果偏好会禁用过渡动画。只有启用复制时才必须提供复制标签。`HoverCard` 与嵌套的操作提示独立显示;使用 `Tooltip.portal` 将小气泡置于卡片上层。可见的嵌套 `Tooltip` 只隐藏外层 tooltip,不隐藏悬停卡片。`Toast` 使用调用方的 `holdMs` 同时控制淡出延迟与停留加淡出的总时长。`holdMs` 未变时,父组件重渲染不会重启该生命周期;完成时调用最新回调,完全淡出的操作不能接收输入。新的组件 key 会重新开始横幅周期。`rankByName` 是 `/` 菜单命令源与 skill(技能)源共享的候选排序器:查询必须是名字的不区分大小写的有序子序列;前缀命中排最前,其次按对齐分数,再按来源顺序。 portal 模式的 `Menu` 列表会在拖动和 CSS 变换期间跟随锚点,并在关闭时停止跟踪。`Menu.autoFocus` 聚焦首个启用项,支持上下方向键与 Home/End 导航,并在 Escape 时聚焦 anchor 内的第一个按钮;操作菜单可显式启用。 `Tooltip` 在悬停或键盘聚焦时读取锚点位置,再根据 `ResizeObserver` 提供的边框盒尺寸调整气泡。首次定位前气泡保持隐藏;横向移入视口留白,仅在另一侧容得下时上下翻转。标签尺寸与视口变化复用锚点坐标;定位不会同步测量气泡,也不会触发 React 渲染。 信息按钮可显式启用 `openOnClick`,点击后保持同一个气泡供阅读,并将内容关联为锚点的无障碍描述;再次点击、Escape、Tab 或外部 pointerdown 会关闭。普通操作按钮的 tooltip 仍在点击时关闭。 +`HoverCardGroup` 为一个已挂载的物理列表持有私有状态。设置 `grouped` 的 `HoverCard` 共享首张实际显示卡片的等待:在同一次指针交互中,后续卡片立即替换当前卡片。列表与其当前活动的 portal 卡片构成一次指针交互:指针可进入卡片阅读或复制,再返回其他列表项并立即替换卡片。指针离开两者后,共享等待在活动卡片通过原有指针宽限及关闭生命周期关闭时重置;分组不另设计时器。列表没有活动卡片时,指针离开便立即重置等待。指针位于列表外时,通过键盘聚焦打开行内卡片不会让下一次指针进入跳过等待。互斥显示也包括正在淡出的预览:普通预览关闭保留淡出,但分组内替换会立即移除前一张卡片。未设置 `grouped` 的卡片保持独立。 + ### 渲染 agent 输出 最近的 `MarkdownDelegateProvider` 提供可选的 `openExternalLink` 和 `openFile` 导航回调。嵌套 Provider 替换外层能力,回调变化无需重新构建 Markdown 即可到达已渲染链接。其 `openFile` 使本地 Markdown 链接在落定后可点击。绝对路径和工作区相对路径支持百分号转义以及 `#L24` / `#L24-L30` 片段;范围定位到起始行。文件名中的字面 `?` 和 `#` 必须百分号编码。悬停提示使用解码后的路径,并在标签为空时提供可访问名称。回调接收解码后的路径和可选行号,渲染器保留标签并显示文件图标。不传回调时,本地链接仍为文本。URL 协议、查询串、不支持的片段及格式错误的目标不会传给文件打开器。 -`MarkdownText` 渲染不可信的 GFM 与 TeX 公式、阻止不安全的链接与图片,并可把已解析的文件提及转换为显式控件。外层 `MarkdownDelegateProvider` 会接收普通点击产生的已净化 HTTP(S) URL;带修饰键的点击和 Provider 外的链接保留原生外部 anchor 行为。当 owner 传入 `pathImages` 词表时,本地媒体路径的图片目标只在落定渲染阶段重写为可展示 URL(与 file mentions 相同的流式门);不传词表时本地目标保持惰性 alt 文本。重写后的图片支持 HTTP(S)、data、blob 及桌面端 `dsh-app://app/api/file` 路由;正文直接书写的桌面端 URL 仍保持惰性。加载或解码失败后,图片替换为作者的 alt 文本;alt 为空时显示原始目标路径;`fileImages` 还提供本地化的失败提示前缀。图片源变化后可重新加载。回复流式输出时,它冻结已完成的块、按已完成行推进顶层未闭合 fence,并从保存的 Shiki grammar state 为该 fence 增量高亮。已完成的 token 行进入固定大小的 React 分组,后续分片只 reconcile 正在增长的分组;最终全量解析解决跨文档语法时,未变化的 fence 会保留该 DOM。`TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock` 与 `WebBlock` 把对应的工具结果意图渲染为带复制控件、溢出处理及适用时 ANSI 处理的卡片。`JsonTree` 与 `JsonBlock` 以只读方式检查 JSON 值;`projectUserText` 把已发送的用户文本投影为行内普通文本段与引用 chip,供消息气泡和排队行使用。引用名称继承调用方的换行规则:长名称在气泡内换行,排队预览保持单行布局。传入 `UserTextReferences` 时,文件和 skill 引用成为支持键盘操作的预览按钮,复用正文文件链接的悬停和聚焦样式;第一次指针点击可以打开预览,后续点击和已有选区保留原生选择行为。键盘激活在存在选区时仍可打开预览。 +`MarkdownText` 渲染不可信的 GFM 与 TeX 公式、阻止不安全的链接与图片,并可把已解析的文件提及转换为显式控件。外层 `MarkdownDelegateProvider` 会接收普通点击产生的已净化 HTTP(S) URL;带修饰键的点击和 Provider 外的链接保留原生外部 anchor 行为。当 owner 传入 `pathImages` 词表时,本地媒体路径的图片目标只在落定渲染阶段重写为可展示 URL(与 file mentions 相同的流式门);不传词表时本地目标保持惰性 alt 文本。重写后的图片支持 HTTP(S)、data、blob 及桌面端 `dsh-app://app/api/file` 路由;正文直接书写的桌面端 URL 仍保持惰性。加载或解码失败后,图片替换为作者的 alt 文本;alt 为空时显示原始目标路径;`fileImages` 还提供本地化的失败提示前缀。图片源变化后可重新加载。回复流式输出时,它冻结已完成的块、按已完成行推进顶层未闭合 fence,并从保存的 Shiki grammar state 为该 fence 增量高亮。已完成的 token 行进入固定大小的 React 分组,后续分片只 reconcile 正在增长的分组;最终全量解析解决跨文档语法时,未变化的 fence 会保留该 DOM。`TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock` 与 `WebBlock` 把对应的工具结果意图渲染为带复制控件、溢出处理及适用时 ANSI 处理的卡片。`JsonTree` 与 `JsonBlock` 以只读方式检查 JSON 值;`UserTextRun` 渲染不做解析的文本,`ReferenceChip` 渲染业务已解析的标签。显式传入 `onActivate` 后,胶囊成为可由键盘操作的按钮;重复指针点击和已有文本选区不触发激活,键盘激活仍然可用。标签继承所属容器的换行规则。识别和 JSON 变换由 [ui-conversation](../ui-conversation/README.zh.md#sent-user-text) 负责。 `MarkdownText` 默认为 `variant="body"`。次级内容使用 `variant="compact"`:其 13px 字号与 20px 行高跟随内容字号设置,各级标题保持同一字号并使用 600 字重,段落与列表采用更紧凑的间距。正文、链接和代码均保持 tertiary 颜色,以点状下划线区分链接。代码标题栏随代码块滚动。表格和公式仍然启用,使用周围文字的字号,并在可用宽度内横向滚动。两个变体共享解析器与流式缓存。 @@ -161,7 +164,7 @@ kind: "package-library" ### 几何与溢出 -输出卡片共享同一套几何模型:`white-space: pre` 并横向滚动,让按列对齐的内容保持对齐;超过 `maxLines`(默认 16)时折叠为头部切片加尾部切片,由展开按钮控制,长正文不会撑高卡片。`TerminalBlock` 通过 `CommandText` 让每条原始命令行可选中并横向滚动;提示符和状态保持固定。只有横向溢出的文本以具名 group 进入 Tab 顺序,名称使用 owner 的本地化 `commandLine(line)` 标签。能完整显示的文本(包括 Jobs 中已换行的命令)不会添加 Tab 停靠点。尺寸、文本与字体变化会更新可聚焦状态,不改变滚动位置。`TerminalBlock` 把 ANSI 解析为 React span,并带逐行列缓冲处理光标移动,遵循行内擦除、制表位与字符宽度。宿主可按表层选择退出共享几何:把 `--dsl-terminal-command-whitespace` / `--dsl-terminal-line-whitespace` 重绑为 `pre-wrap` 让命令与输出完整换行且不横向滚动;`maxLines: Infinity` 为改用 `--dsl-terminal-output-max-height` 限高滚动的宿主禁用折叠;`copyText` 覆盖复制载荷(并让控件在任何输出出现之前就保持渲染);`runStateDot: false` 在外围行已携带同一状态时省去状态点,并经 `--dsl-terminal-gutter` 收回其落区。横幅分割线跟随渲染出的正文:正在流式输出的 running 卡片像已结束卡片一样把命令与文本分隔开。 +输出卡片共享同一套几何模型:`white-space: pre` 并横向滚动,让按列对齐的内容保持对齐;超过 `maxLines`(默认 16)时折叠为头部切片加尾部切片,由展开按钮控制,长正文不会撑高卡片。`TerminalBlock` 通过 `CommandText` 让每条原始命令行可选中并横向滚动;提示符和状态保持固定。状态点始终对齐命令的第一个视觉行,包括命令自动折行时。只有横向溢出的文本以具名 group 进入 Tab 顺序,名称使用 owner 的本地化 `commandLine(line)` 标签。能完整显示的文本(包括 Jobs 中已换行的命令)不会添加 Tab 停靠点。尺寸、文本与字体变化会更新可聚焦状态,不改变滚动位置。`TerminalBlock` 把 ANSI 解析为 React span,并带逐行列缓冲处理光标移动,遵循行内擦除、制表位与字符宽度。宿主可按表层选择退出共享几何:把 `--dsl-terminal-command-whitespace` / `--dsl-terminal-line-whitespace` 重绑为 `pre-wrap` 让命令与输出完整换行且不横向滚动;`maxLines: Infinity` 为改用 `--dsl-terminal-output-max-height` 限高滚动的宿主禁用折叠;`copyText` 覆盖复制载荷(并让控件在任何输出出现之前就保持渲染);`runStateDot: false` 在外围行已携带同一状态时省去状态点,并经 `--dsl-terminal-gutter` 收回其落区。`background` 默认为 false,透传调用的后台标志。后台调用的 `running` 表示启动调用进度:Start 显示该指示,回执使 `running` 变为 false,命令保持静态且不显示状态点或辅助标签。后台调用不显示输出、空输出提示、退出状态 pill 或默认输出 Copy 控件,显式 `copyText` 覆盖仍可使用。横幅分割线跟随渲染出的正文:正在流式输出的 running 卡片像已结束卡片一样把命令与文本分隔开。 diff --git a/packages/client/ui-primitives/package.json b/packages/client/ui-primitives/package.json index d1aa264296..2dc72d3b16 100644 --- a/packages/client/ui-primitives/package.json +++ b/packages/client/ui-primitives/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-primitives", "description": "Pure React atoms for the dsh web UI: controls, icons, markdown, and JSON inspectors (zero cordis)", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -24,8 +24,6 @@ "license": "MIT", "devDependencies": { "@deepseek-ai/dsh-client-store": "workspace:*", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-util-code-language": "workspace:*", "react": "^18.2.0", diff --git a/packages/client/ui-primitives/src/DisclosureRow.module.css b/packages/client/ui-primitives/src/DisclosureRow.module.css index 90fc1f8c2d..25934c11f4 100644 --- a/packages/client/ui-primitives/src/DisclosureRow.module.css +++ b/packages/client/ui-primitives/src/DisclosureRow.module.css @@ -13,7 +13,22 @@ min-width: 0; } +.header { + display: flex; + align-items: center; + min-width: 0; +} + +.header[data-has-accessory] { + gap: 8px; +} + +.header[data-has-accessory] .row { + flex: 0 1 auto; +} + .row { + flex: 1 1 auto; position: relative; overflow: hidden; display: flex; diff --git a/packages/client/ui-primitives/src/DisclosureRow.tsx b/packages/client/ui-primitives/src/DisclosureRow.tsx index 7b98eca2fc..024c8777f7 100644 --- a/packages/client/ui-primitives/src/DisclosureRow.tsx +++ b/packages/client/ui-primitives/src/DisclosureRow.tsx @@ -13,13 +13,15 @@ export interface DisclosureRowProps { onToggle: () => void /** Animate the complete header while its owning operation is running. */ running?: boolean | undefined - /** Makes the complete title row the disclosure target. */ + /** Makes the title row the disclosure target; with an accessory, it shrinks to its content width. */ expandOnRowClick?: boolean | undefined /** Replaces the collapsed icon with a chevron while the row is hovered. */ previewChevron?: boolean | undefined /** Keeps `collapsedContent` inline while open. */ keepContentWhenOpen?: boolean | undefined collapsedContent?: ReactNode + /** Independent action beside the title, outside the disclosure target and shimmer. */ + headerAccessory?: ReactNode children?: ReactNode className?: string | undefined rowClassName?: string | undefined @@ -49,6 +51,7 @@ export const DisclosureRow = memo(function DisclosureRow({ previewChevron = expandable, keepContentWhenOpen = false, collapsedContent, + headerAccessory, children, className, rowClassName, @@ -82,35 +85,38 @@ export const DisclosureRow = memo(function DisclosureRow({ return (
-
- {expandable && !rowExpands ? ( - - ) : ( - - {leading} - - )} - - {title} - {(keepContentWhenOpen || !open) && collapsedContent} - +
+
+ {expandable && !rowExpands ? ( + + ) : ( + + {leading} + + )} + + {title} + {(keepContentWhenOpen || !open) && collapsedContent} + +
+ {headerAccessory}
{open && children}
diff --git a/packages/client/ui-primitives/src/HoverCard.tsx b/packages/client/ui-primitives/src/HoverCard.tsx index 4aa1b58652..3b3ab47656 100644 --- a/packages/client/ui-primitives/src/HoverCard.tsx +++ b/packages/client/ui-primitives/src/HoverCard.tsx @@ -1,11 +1,11 @@ -import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' +import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react' import type { CSSProperties, ReactNode, RefObject, SyntheticEvent } from 'react' import clsx from 'clsx' import { createPortal } from 'react-dom' import { writeClipboard } from './clipboard.ts' import { usePointerGrace } from './pointer-grace.ts' import { overlayTopMargin } from './overlay-top-margin.ts' -import { TooltipSuppression } from './Tooltip.tsx' +import { HoverCardGroupContext } from './HoverCardGroup.tsx' import css from './HoverCard.module.css' /** Preview opacity transition and retained lifetime during dismissal. */ @@ -17,7 +17,7 @@ const ANCHOR_GAP = 8 const VIEWPORT_MARGIN = 8 /** - * Render an anchor with a hover-triggered preview card, hidden while a tooltip within the anchor is visible. + * Render an anchor with a hover-triggered preview card independently of nested tooltips. * @param props.anchor - the hover target (rendered in place inside a wrapper span). * @param props.content - card content; the pointer may rest on it, so it is * readable and selectable, but it carries no dismissal affordance of its own. @@ -27,6 +27,8 @@ const VIEWPORT_MARGIN = 8 * @param props.widthAnchorRef - optional element whose width and horizontal position size the preview. * @param props.inline - keep the anchor in prose; show a contained preview on hover or keyboard focus. * @param props.disabled - suppress opening; turning true dismisses an open card. + * @param props.grouped - share first-display dwell across the surrounding list and active portal. + * Group replacement removes the previous card immediately, including a fading preview. * @param props.copyText - optional primary value copied by activation and * included in the card's accessible name. * @param props.copyLabel - localized accessible activation-label prefix. @@ -34,7 +36,7 @@ const VIEWPORT_MARGIN = 8 * @returns anchor wrapper with the conditional portaled card. */ export function HoverCard({ - anchor, content, openDelayMs = 500, disabled = false, + anchor, content, openDelayMs = 500, disabled = false, grouped = false, copyText, copyLabel, copiedLabel, variant = 'compact', widthAnchorRef, inline = false, }: { anchor: ReactNode @@ -43,6 +45,7 @@ export function HoverCard({ content: ReactNode openDelayMs?: number disabled?: boolean + grouped?: boolean variant?: 'compact' | 'preview' widthAnchorRef?: RefObject } & ({ copyText?: string | undefined; copyLabel: string; copiedLabel: string } | { @@ -64,7 +67,9 @@ export function HoverCard({ const [pos, setPos] = useState<{ left: number; top: number; width?: number; maxHeight?: number } | null>(null) const positioned = pos !== null const [copied, setCopied] = useState(false) - const [suppressed, setSuppressed] = useState(false) + const parentGroup = useContext(HoverCardGroupContext) + const group = grouped ? parentGroup : null + const [groupOwner] = useState(() => Symbol('hover-card')) const clearCopied = useCallback(() => { if (copyTimerRef.current !== null) { @@ -83,12 +88,28 @@ export function HoverCard({ const { arm: armClose, cancel: cancelClose } = usePointerGrace(close) - const clearTimer = () => { + const clearTimer = useCallback(() => { if (timerRef.current !== null) { clearTimeout(timerRef.current) timerRef.current = null } - } + }, []) + + const dismissImmediately = useCallback(() => { + clearTimer() + cancelClose() + copyEpochRef.current += 1 + clearCopied() + setPhase('closed') + }, [clearTimer, cancelClose, clearCopied]) + // A fading preview still owns the group's visible card until it unmounts or another card replaces it. + const groupVisible = open && positioned + useLayoutEffect(() => { + if (!groupVisible || group === null) return + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- The visible card's ref is attached before layout effects. + group.shown(groupOwner, dismissImmediately, cardRef.current!) + return () => { group.release(groupOwner) } + }, [group, groupOwner, groupVisible, dismissImmediately]) useEffect(() => { if (!closing) return @@ -193,13 +214,13 @@ export function HoverCard({ // card's real height is measurable, correct the bottom-edge clamp. The // correction converges — a clamped top satisfies the guard, so it runs once. useLayoutEffect(() => { - if (!open || pos === null || variant === 'preview' || inline || suppressed) return + if (!open || pos === null || variant === 'preview' || inline) return /* v8 ignore next -- the card is mounted whenever pos is set, so the ref is attached here. */ const h = cardRef.current?.offsetHeight ?? 0 if (pos.top + h > window.innerHeight - VIEWPORT_MARGIN) { setPos({ left: pos.left, top: window.innerHeight - h - VIEWPORT_MARGIN }) } - }, [open, pos, variant, inline, suppressed]) + }, [open, pos, variant, inline]) const copy = async (text: string): Promise => { if (copied || copyingRef.current) return @@ -223,7 +244,7 @@ export function HoverCard({ cancelClose() close() } - const card = open && pos !== null && !suppressed && ( + const card = open && pos !== null && (
{ setPhase('open') }, openDelayMs) + if (group?.isWarm()) setPhase('open') + else timerRef.current = setTimeout(() => { setPhase('open') }, openDelayMs) }} onPointerLeave={() => { clearTimer() @@ -286,8 +308,8 @@ export function HoverCard({ onPointerDownCapture={dismissFromAnchor} onClickCapture={dismissFromAnchor} > - {anchor} - {open && !suppressed && copyable && {copied ? copiedLabel : ''}} + {anchor} + {open && copyable && {copied ? copiedLabel : ''}} {card !== false && createPortal(card, document.body)} ) diff --git a/packages/client/ui-primitives/src/HoverCardGroup.tsx b/packages/client/ui-primitives/src/HoverCardGroup.tsx new file mode 100644 index 0000000000..163202d813 --- /dev/null +++ b/packages/client/ui-primitives/src/HoverCardGroup.tsx @@ -0,0 +1,72 @@ +import { createContext, useState, type ReactNode } from 'react' + +interface GroupState { + isWarm: () => boolean + enter: (overCard: boolean) => void + leave: () => void + containsCard: (target: EventTarget | null) => boolean + shown: (owner: symbol, dismiss: () => void, element: HTMLElement) => void + release: (owner: symbol) => void +} + +/** Private coordination shared only by opted-in HoverCards inside one mounted group. */ +export const HoverCardGroupContext = createContext(null) + +/** + * Share first-display dwell across a list and its active portal, including the card's existing pointer grace. + * @param props.children - list contents, including opted-in HoverCards. + * @param props.className - classes for the physical list container. + * @returns the list container and its private hover coordinator. + */ +export function HoverCardGroup({ children, className }: { children: ReactNode; className?: string }) { + const [group] = useState(() => { + let pointer: 'outside' | 'list' | 'card' = 'outside' + let warm = false + let active: { owner: symbol; dismiss: () => void; element: HTMLElement } | null = null + return { + isWarm: () => warm, + enter: (overCard) => { + pointer = overCard ? 'card' : 'list' + if (overCard) warm = true + }, + leave: () => { + pointer = 'outside' + // A displayed card owns the grace across the gap; its release ends an outside visit. + if (active === null) warm = false + }, + containsCard: target => target instanceof Node && active !== null && active.element.contains(target), + shown: (owner, dismiss, element) => { + // Keyboard focus can replace the portal under the pointer without a pointer-out event. + if (pointer === 'card') { pointer = 'outside'; warm = false } + if (pointer === 'list') warm = true + const previous = active + active = { owner, dismiss, element } + if (previous !== null && previous.owner !== owner) previous.dismiss() + }, + release: (owner) => { + if (active?.owner !== owner) return + active = null + if (pointer !== 'list') { pointer = 'outside'; warm = false } + }, + } + }) + return ( + +
{ + const overCard = group.containsCard(event.target) + if (event.currentTarget.contains(event.target as Node) || overCard) group.enter(overCard) + }} + onPointerOutCapture={(event) => { + const fromGroup = event.currentTarget.contains(event.target as Node) || group.containsCard(event.target) + const intoGroup = (event.relatedTarget instanceof Node && event.currentTarget.contains(event.relatedTarget)) + || group.containsCard(event.relatedTarget) + if (fromGroup && !intoGroup) group.leave() + }} + > + {children} +
+
+ ) +} diff --git a/packages/client/ui-primitives/src/PermissionIcon.tsx b/packages/client/ui-primitives/src/PermissionIcon.tsx index 4b7c047933..ee480c8c2d 100644 --- a/packages/client/ui-primitives/src/PermissionIcon.tsx +++ b/packages/client/ui-primitives/src/PermissionIcon.tsx @@ -37,6 +37,15 @@ function FullAccessArtwork({ size = 16, className, strokeWidth }: PermissionIcon ) } +function AutoReviewArtwork({ size = 16, className, strokeWidth }: PermissionIconArtworkProps): ReactNode { + return ( + + ) +} + /** * Render the read-only permission icon with a one-pixel stroke. * @param props - Size and optional class. @@ -90,3 +99,21 @@ export function PermissionIconFullAccessRegular(props: IconProps): ReactNode { export function PermissionIconFullAccessMedium(props: IconProps): ReactNode { return } + +/** + * Render the auto-review permission icon with a one-pixel stroke. + * @param props - Size and optional class. + * @returns The regular decorative permission glyph. + */ +export function PermissionIconAutoReviewRegular(props: IconProps): ReactNode { + return +} + +/** + * Render the auto-review permission icon with a 1.3px stroke. + * @param props - Size and optional class. + * @returns The medium decorative permission glyph. + */ +export function PermissionIconAutoReviewMedium(props: IconProps): ReactNode { + return +} diff --git a/packages/client/ui-primitives/src/TerminalBlock.module.css b/packages/client/ui-primitives/src/TerminalBlock.module.css index 71196558b1..5d8998d647 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.module.css +++ b/packages/client/ui-primitives/src/TerminalBlock.module.css @@ -87,11 +87,11 @@ /* Out of flow inside the card's own gutter padding, so the reservation and the dot move together and no consumer margin can pull them apart; the dot neither indents its command nor depends on the command's text metrics to line up. - Centered against the row's line box, not the code font's baseline. */ + Centered against the first visual line box, not the code font's baseline. */ .runState { position: absolute; left: calc(-1 * var(--dsl-terminal-gutter) + 8px); - top: 50%; + top: calc(var(--dsl-terminal-line-height) / 2); transform: translateY(-50%); } diff --git a/packages/client/ui-primitives/src/TerminalBlock.tsx b/packages/client/ui-primitives/src/TerminalBlock.tsx index a6737605a8..19c5c3296e 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.tsx +++ b/packages/client/ui-primitives/src/TerminalBlock.tsx @@ -64,6 +64,12 @@ export interface TerminalBlockProps { * line alone; with output it renders the live text under the running state. */ running?: boolean | undefined + /** + * The call launches background work (default false). `running` describes the + * launch call only; after it returns, retain the command without job status + * or output. An explicit `copyText` override remains available. + */ + background?: boolean | undefined /** Height cap in output lines before the middle collapses (default {@link DEFAULT_TERMINAL_MAX_LINES}); Infinity disables the cap. */ maxLines?: number | undefined /** @@ -172,6 +178,7 @@ export function TerminalBlock({ exitCode, signal, running = false, + background = false, maxLines = DEFAULT_TERMINAL_MAX_LINES, copyText, runStateDot = true, @@ -201,8 +208,9 @@ export function TerminalBlock({ const onToggle = useCallback(() => { setExpanded(value => !value) }, []) - const status = statusText(exitCode, signal, copy) + const status = background ? undefined : statusText(exitCode, signal, copy) const state = runState(running, exitCode, signal, copy) + const showState = runStateDot && (!background || running) // A multi-line command gets one prompt row per line, so a two-command shell // snippet reads as the two commands it is instead of collapsing into one // ellipsized row. A trailing newline is a terminator, not an empty command. @@ -219,7 +227,7 @@ export function TerminalBlock({ const { hidden, capped, headLines, tailLines } = headTailCap(lines.length, maxLines, expanded) // A running command with nothing printed yet is banner-only; once it has // printed, the output streams in under the banner as it would in a terminal. - const body = !running || !empty + const body = !background && (!running || !empty) return (
- {runStateDot && {state.label}} + {showState && {state.label}} {commandLines.map((line, index) => (
{/* One dot for the card, on the first row: the exit status the view carries is the whole call's, and bash reports no per-command status, so a dot per row would assert a per-line outcome nothing here knows. */} - {index === 0 && runStateDot && } + {index === 0 && showState && } {/* The cwd labels the CALL, so only its first row carries it. The view knows one working directory — where the call started — and a later line may well run somewhere else (a `cd` in the @@ -252,7 +260,7 @@ export function TerminalBlock({ ))}
{status !== undefined && {status}} - {(copyText !== undefined || (!running && !empty)) && ( + {(copyText !== undefined || (!background && !running && !empty)) && ( diff --git a/packages/client/ui-primitives/src/Tooltip.tsx b/packages/client/ui-primitives/src/Tooltip.tsx index 6f32ecab90..a15899be3c 100644 --- a/packages/client/ui-primitives/src/Tooltip.tsx +++ b/packages/client/ui-primitives/src/Tooltip.tsx @@ -14,8 +14,8 @@ import { pointerModality } from './input-modality.ts' export type TooltipSide = 'right' | 'bottom' | 'top' /** - * Suppression channel for enclosing tooltip and hover-card anchors: a visible - * tooltip within an anchor withdraws the enclosing preview while its bubble is shown. + * Suppression channel for nested tooltips: a visible descendant tooltip + * withdraws the enclosing tooltip while its bubble is shown. */ export const TooltipSuppression = createContext<((suppressed: boolean) => void) | null>(null) diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 7fe8783d6a..18f9544405 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -33,6 +33,7 @@ export { useAnchoredPosition } from './useAnchoredPosition.ts' export type { AnchoredPositionOptions } from './useAnchoredPosition.ts' export { useDismissOnOutsidePointer } from './useDismissOnOutsidePointer.ts' export { HoverCard } from './HoverCard.tsx' +export { HoverCardGroup } from './HoverCardGroup.tsx' export { ShortcutKeys } from './ShortcutKeys.tsx' export { observeComposition } from './keyboard-composition.ts' export { focusWithoutRing } from './focus.ts' @@ -46,6 +47,7 @@ export { FishLogo, FISH_LOGO_PATH, FISH_LOGO_VIEWBOX } from './FishLogo.tsx' export { BrandWordmark } from './BrandWordmark.tsx' export type { BrandWordmarkProps } from './BrandWordmark.tsx' export { + PermissionIconAutoReviewMedium, PermissionIconAutoReviewRegular, PermissionIconFullAccessMedium, PermissionIconFullAccessRegular, PermissionIconReadOnlyMedium, PermissionIconReadOnlyRegular, PermissionIconWorkspaceWriteMedium, PermissionIconWorkspaceWriteRegular, @@ -58,7 +60,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/hover-card-group.client.spec.tsx b/packages/client/ui-primitives/tests/hover-card-group.client.spec.tsx new file mode 100644 index 0000000000..da4b665096 --- /dev/null +++ b/packages/client/ui-primitives/tests/hover-card-group.client.spec.tsx @@ -0,0 +1,330 @@ +// @vitest-environment jsdom +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { HoverCard } from '../src/HoverCard.tsx' +import { HoverCardGroup } from '../src/HoverCardGroup.tsx' +import { Tooltip } from '../src/Tooltip.tsx' + +beforeEach(() => { vi.useFakeTimers() }) +afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks() }) + +// jsdom lacks PointerEvent; MouseEvent preserves relatedTarget for physical and React ancestry checks. +function move(from: Element, to: Element): void { + fireEvent(from, new MouseEvent('pointerout', { bubbles: true, relatedTarget: to })) + fireEvent(to, new MouseEvent('pointerover', { bubbles: true, relatedTarget: from })) + fireEvent(from, new MouseEvent('mouseout', { bubbles: true, relatedTarget: to })) + fireEvent(to, new MouseEvent('mouseover', { bubbles: true, relatedTarget: from })) +} +function tick(ms: number): void { act(() => { vi.advanceTimersByTime(ms) }) } +function Card({ name, grouped = true, disabled = false }: { name: string; grouped?: boolean; disabled?: boolean }) { + return {name}} + content={details {name}} copyText={name} copyLabel="Copy" copiedLabel="Copied" /> +} + +describe('HoverCardGroup', () => { + it('does not warm the next pointer visit when keyboard focus displays an inline card outside a pointer visit', () => { + const view = render(<> + + + A} + content={details A} /> + + + ) + const outside = screen.getByRole('button', { name: 'outside' }) + const a = screen.getByRole('button', { name: 'A' }) + act(() => { outside.focus() }) + fireEvent.keyDown(outside, { key: 'Tab' }) + // jsdom does not move focus for Tab, so apply its native focus transition without a pointer event. + act(() => { a.focus() }) + expect(document.activeElement).toBe(a) + expect(screen.getByText('details A')).toBeTruthy() + move(document.body, screen.getByText('B')) + expect(screen.queryByText('details B')).toBeNull() + tick(799) + expect(screen.queryByText('details B')).toBeNull() + tick(1) + expect(screen.getByText('details B')).toBeTruthy() + expect(screen.queryByText('details A')).toBeNull() + view.unmount() + expect(vi.getTimerCount()).toBe(0) + }) + + it('waits for the first actual display, then switches instantly within one physical list', () => { + render(gap) + const a = screen.getByText('A') + const b = screen.getByText('B') + const gap = screen.getByText('gap') + move(document.body, a) + tick(799) + expect(screen.queryByText('details A')).toBeNull() + tick(1) + expect(screen.getByText('details A')).toBeTruthy() + move(a, b) + expect(screen.queryByText('details A')).toBeNull() + expect(screen.getByText('details B')).toBeTruthy() + // Repositioning the old anchor must not let it claim ownership again. + fireEvent(window, new Event('resize')) + tick(300) + expect(screen.queryByText('details A')).toBeNull() + expect(screen.getByText('details B')).toBeTruthy() + move(b, gap) + tick(300) + move(gap, a) + expect(screen.getByText('details A')).toBeTruthy() + move(a, document.body) + tick(300) + move(document.body, b) + expect(screen.queryByText('details B')).toBeNull() + tick(799) + expect(screen.queryByText('details B')).toBeNull() + tick(1) + expect(screen.getByText('details B')).toBeTruthy() + }) + + it.each(['pointer exit', 'disabled'] as const)('replaces a preview fading after %s before displaying the next card', (reason) => { + const markup = (disabled = false) => + A} content={details A} /> + gap + + + const view = render(markup()) + const a = screen.getByText('A') + const gap = screen.getByText('gap') + move(document.body, a) + tick(800) + expect(screen.getByText('details A')).toBeTruthy() + move(a, gap) + // Pointer grace expires after 200ms; disabling closes immediately. Both retain the 100ms fade. + if (reason === 'disabled') view.rerender(markup(true)) + else tick(200) + expect(screen.getByText('details A')).toBeTruthy() + move(gap, screen.getByText('B')) + expect(screen.getByText('details B')).toBeTruthy() + expect(screen.queryByText('details A')).toBeNull() + tick(100) + expect(screen.getByText('details B')).toBeTruthy() + }) + + it('keeps cancelled openings cold and shares displayed cards independently of action tooltips', () => { + render() + const a = screen.getByText('A') + const b = screen.getByText('B') + move(document.body, a) + tick(400) + move(a, b) + tick(799) + expect(screen.queryByText('details A')).toBeNull() + expect(screen.queryByText('details B')).toBeNull() + tick(1) + const card = screen.getByText('details B') + const action = screen.getByRole('button', { name: 'action B' }) + move(b, action) + tick(500) + expect(screen.getByRole('tooltip').textContent).toBe('Archive B') + expect(screen.getByText('details B')).toBe(card) + move(action, a) + expect(screen.queryByRole('tooltip')).toBeNull() + expect(screen.getByText('details A')).toBeTruthy() + expect(screen.queryByText('details B')).toBeNull() + }) + + it('shares warmth through readable, copyable portals until the pointer leaves both surfaces', async () => { + const previous = Object.getOwnPropertyDescriptor(navigator, 'clipboard') + const writeText = vi.fn(async () => {}) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + try { + render() + const a = screen.getByText('A') + const b = screen.getByText('B') + move(document.body, a) + tick(800) + const portal = screen.getByRole('button', { name: 'Copy: A' }) + move(a, portal) + tick(500) + expect(portal.isConnected).toBe(true) + await act(async () => { fireEvent.click(portal); await Promise.resolve() }) + expect(writeText).toHaveBeenCalledWith('A') + expect(screen.getByRole('status').textContent).toBe('Copied') + move(portal, b) + expect(screen.getByText('details B')).toBeTruthy() + expect(screen.queryByRole('button', { name: 'Copy: A' })).toBeNull() + const secondPortal = screen.getByRole('button', { name: 'Copy: B' }) + move(b, secondPortal) + move(secondPortal, document.body) + tick(300) + expect(screen.queryByText('details B')).toBeNull() + move(document.body, a) + tick(799) + expect(screen.queryByText('details A')).toBeNull() + tick(1) + expect(screen.getByText('details A')).toBeTruthy() + } finally { + if (previous === undefined) Reflect.deleteProperty(navigator, 'clipboard') + else Object.defineProperty(navigator, 'clipboard', previous) + } + }) + + it('bridges the list-to-card gaps with the active card existing pointer grace', () => { + render() + const a = screen.getByText('A') + const b = screen.getByText('B') + move(document.body, a) + tick(800) + const portal = screen.getByRole('button', { name: 'Copy: A' }) + move(a, document.body) + tick(100) + move(document.body, portal) + tick(500) + expect(portal.isConnected).toBe(true) + move(portal, document.body) + tick(100) + move(document.body, b) + expect(screen.getByText('details B')).toBeTruthy() + expect(screen.queryByText('details A')).toBeNull() + move(b, document.body) + tick(300) + move(document.body, a) + tick(799) + expect(screen.queryByText('details A')).toBeNull() + tick(1) + expect(screen.getByText('details A')).toBeTruthy() + }) + + it('warms a keyboard-open card only when the pointer visits that card', () => { + render( + A} + content={details A} /> + + ) + fireEvent.keyDown(document, { key: 'Tab' }) + act(() => { screen.getByRole('button', { name: 'A' }).focus() }) + const portal = screen.getByText('details A') + move(document.body, portal) + move(portal, screen.getByText('B')) + expect(screen.getByText('details B')).toBeTruthy() + expect(screen.queryByText('details A')).toBeNull() + }) + + it('rejects stale clipboard feedback after a group handoff and return', async () => { + const previous = Object.getOwnPropertyDescriptor(navigator, 'clipboard') + let finishWrite: (() => void) | undefined + const writeText = vi.fn(() => new Promise((resolve) => { finishWrite = resolve })) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + try { + render() + const a = screen.getByText('A') + const b = screen.getByText('B') + move(document.body, a) + tick(800) + fireEvent.keyDown(screen.getByRole('button', { name: 'Copy: A' }), { key: 'Enter' }) + expect(writeText).toHaveBeenCalledWith('A') + move(a, b) + expect(screen.getByText('details B')).toBeTruthy() + move(b, a) + expect(screen.getByText('details A')).toBeTruthy() + await act(async () => { finishWrite?.(); await Promise.resolve() }) + expect(screen.queryByText('Copied')).toBeNull() + expect(screen.getByText('details A')).toBeTruthy() + } finally { + finishWrite?.() + if (previous === undefined) Reflect.deleteProperty(navigator, 'clipboard') + else Object.defineProperty(navigator, 'clipboard', previous) + } + }) + + it('keeps separate groups cold and does not enroll ungrouped cards', () => { + render(<> + ) + const a = screen.getByText('A') + const project = screen.getByText('Project') + const b = screen.getByText('B') + move(document.body, a) + tick(800) + move(a, project) + expect(screen.queryByText('details Project')).toBeNull() + tick(800) + expect(screen.getByText('details Project')).toBeTruthy() + move(project, b) + expect(screen.queryByText('details B')).toBeNull() + tick(800) + expect(screen.getByText('details B')).toBeTruthy() + }) + + it('does not warm a group through a portal belonging to an ungrouped card', () => { + render() + const project = screen.getByText('Project') + const b = screen.getByText('B') + move(document.body, project) + tick(800) + const portal = screen.getByRole('button', { name: 'Copy: Project' }) + move(project, portal) + tick(500) + expect(portal.isConnected).toBe(true) + move(portal, b) + expect(screen.queryByText('details B')).toBeNull() + tick(799) + expect(screen.queryByText('details B')).toBeNull() + tick(1) + expect(screen.getByText('details B')).toBeTruthy() + }) + + it('cools when the active portal is removed from under the pointer', () => { + const markup = (showA: boolean) => + {showA && } + + const view = render(markup(true)) + const a = screen.getByText('A') + move(document.body, a) + tick(800) + const portal = screen.getByRole('button', { name: 'Copy: A' }) + move(a, portal) + view.rerender(markup(false)) + move(portal, screen.getByText('B')) + expect(screen.queryByText('details B')).toBeNull() + tick(800) + expect(screen.getByText('details B')).toBeTruthy() + }) + + it('cools when keyboard focus replaces the portal under the pointer', () => { + render( + A} content={details A} /> + B} content={details B} /> + + ) + const a = screen.getByRole('button', { name: 'A' }) + move(document.body, a) + tick(500) + const portal = screen.getByText('details A') + move(a, portal) + fireEvent.keyDown(document, { key: 'Tab' }) + act(() => { screen.getByRole('button', { name: 'B' }).focus() }) + expect(screen.getByText('details B')).toBeTruthy() + move(portal, screen.getByText('C')) + expect(screen.queryByText('details C')).toBeNull() + tick(800) + expect(screen.getByText('details C')).toBeTruthy() + }) + + it('releases an unmounted active card without cooling its still-mounted list', () => { + const markup = (showA: boolean, groupKey = 'first') => + {showA && } + + const view = render(markup(true)) + const a = screen.getByText('A') + move(document.body, a) + tick(800) + view.rerender(markup(false)) + move(a, screen.getByText('B')) + expect(screen.getByText('details B')).toBeTruthy() + view.rerender(markup(false, 'new')) + move(document.body, screen.getByText('B')) + expect(screen.queryByText('details B')).toBeNull() + tick(800) + expect(screen.getByText('details B')).toBeTruthy() + view.unmount() + expect(vi.getTimerCount()).toBe(0) + }) +}) diff --git a/packages/client/ui-primitives/tests/hover-card.client.spec.tsx b/packages/client/ui-primitives/tests/hover-card.client.spec.tsx index 322cfcb526..e1f76fcd4b 100644 --- a/packages/client/ui-primitives/tests/hover-card.client.spec.tsx +++ b/packages/client/ui-primitives/tests/hover-card.client.spec.tsx @@ -54,7 +54,7 @@ function installClipboard(writeText: (text: string) => Promise): () => voi } describe('HoverCard', () => { - it.each(['disabled', 'unmounted'] as const)('restores its preview after a nested tooltip is %s', (released) => { + it.each(['disabled', 'unmounted'] as const)('keeps its preview mounted while a nested tooltip shows and is then %s', (released) => { const markup = (state: 'active' | 'disabled' | 'unmounted') => ( row{state !== 'unmounted' && ( @@ -70,11 +70,12 @@ describe('HoverCard', () => { act(() => { vi.advanceTimersByTime(500) }) fireEvent.mouseEnter(screen.getByRole('button', { name: 'action' })) expect(screen.getByRole('tooltip').textContent).toBe('Create') - expect(screen.queryByText('card body')).toBeNull() + const card = screen.getByText('card body') + expect(card.isConnected).toBe(true) view.rerender(markup(released)) expect(screen.queryByRole('tooltip')).toBeNull() - expect(screen.getByText('card body')).toBeTruthy() + expect(screen.getByText('card body')).toBe(card) }) it('keeps card content mounted while its own tooltip is visible', () => { diff --git a/packages/client/ui-primitives/tests/icons.client.spec.tsx b/packages/client/ui-primitives/tests/icons.client.spec.tsx index 5c59ff3593..afd9eaea28 100644 --- a/packages/client/ui-primitives/tests/icons.client.spec.tsx +++ b/packages/client/ui-primitives/tests/icons.client.spec.tsx @@ -82,6 +82,7 @@ describe('product icon set', () => { [primitives.PermissionIconReadOnlyRegular, primitives.PermissionIconReadOnlyMedium], [primitives.PermissionIconWorkspaceWriteRegular, primitives.PermissionIconWorkspaceWriteMedium], [primitives.PermissionIconFullAccessRegular, primitives.PermissionIconFullAccessMedium], + [primitives.PermissionIconAutoReviewRegular, primitives.PermissionIconAutoReviewMedium], ] as const for (const [Regular, Medium] of pairs) { const regular = render() 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 26d5cea771..5e93d001eb 100644 --- a/packages/client/ui-reference/package.json +++ b/packages/client/ui-reference/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-reference", "description": "Unified Web @file and @session reference source", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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 b307e41e29..3df300ef5f 100644 --- a/packages/client/ui-renderer/package.json +++ b/packages/client/ui-renderer/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-renderer", "description": "Browser UI renderer: React slot bindings, ctx.uiRenderer, and the assembled application root", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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/bindings.tsx b/packages/client/ui-renderer/src/client/bindings.tsx index 0e0c0c9527..5ecc314320 100644 --- a/packages/client/ui-renderer/src/client/bindings.tsx +++ b/packages/client/ui-renderer/src/client/bindings.tsx @@ -101,13 +101,43 @@ function useAbsentSnapshot( return undefined } -/** Erased open-key selector Hook synthesized from one keyed source family. */ +/** + * Erased open-key selector Hook synthesized from one keyed source family. + * A string second argument names a member: the Hook reads the source the + * resolver returns for `(key, member)` without a selector. + */ export type KeyedSnapshotHook = ( keyOrSelector: string | ((value: unknown) => unknown), - selectorOrEqual?: ((value: unknown) => unknown) | ((left: unknown, right: unknown) => boolean), + memberOrSelectorOrEqual?: string | ((value: unknown) => unknown) | ((left: unknown, right: unknown) => boolean), equal?: (left: unknown, right: unknown) => boolean, ) => unknown +interface KeyedHookCall { + readonly key: string | undefined + readonly member: string | undefined + readonly selector: ((value: unknown) => unknown) | undefined + readonly equal: ((left: unknown, right: unknown) => boolean) | undefined +} + +/** Read the `(key, member)`, `(key, selector?, equal?)`, or `(selector, equal?)` call forms. */ +function keyedHookCall( + defaultKey: string | undefined, + keyOrSelector: Parameters[0], + second: Parameters[1], + equal: Parameters[2], +): KeyedHookCall { + if (typeof keyOrSelector !== 'string') { + return { + key: defaultKey, + member: undefined, + selector: keyOrSelector, + equal: second as ((left: unknown, right: unknown) => boolean) | undefined, + } + } + if (typeof second === 'string') return { key: keyOrSelector, member: second, selector: undefined, equal: undefined } + return { key: keyOrSelector, member: undefined, selector: second as ((value: unknown) => unknown) | undefined, equal } +} + /** * Bind an open-key source family. * @param source - keyed resolver, or absence for an optional scope. @@ -126,13 +156,13 @@ export function keyedObservableHook( const cacheKey = defaultKey ?? NO_DEFAULT_KEY let hook = hooks.get(cacheKey) if (hook === undefined) { - hook = (keyOrSelector, selectorOrEqual, equal) => { - const keyed = typeof keyOrSelector === 'string' - const key = keyed ? keyOrSelector : defaultKey - const selector = (keyed ? selectorOrEqual : keyOrSelector) as ((value: unknown) => unknown) | undefined - const comparison = (keyed ? equal : selectorOrEqual) as ((left: unknown, right: unknown) => boolean) | undefined - const useValue = observableHook(key === undefined ? absentSource : source(key) ?? absentSource) - return useValue(selector ?? identity, comparison) + hook = (keyOrSelector, second, equal) => { + const call = keyedHookCall(defaultKey, keyOrSelector, second, equal) + const resolved = call.key === undefined + ? undefined + : call.member === undefined ? source(call.key) : source(call.key, call.member) + const useValue = observableHook(resolved ?? absentSource) + return useValue(call.selector ?? identity, call.equal) } hooks.set(cacheKey, hook) } @@ -142,11 +172,9 @@ export function keyedObservableHook( const NO_DEFAULT_KEY = Symbol('no default key') const keyedHookCache = new WeakMap>() const identity = (value: unknown): unknown => value -const absentKeyedHook: KeyedSnapshotHook = (keyOrSelector, selectorOrEqual, equal) => { - const keyed = typeof keyOrSelector === 'string' - const selector = (keyed ? selectorOrEqual : keyOrSelector) as ((value: unknown) => unknown) | undefined - const comparison = (keyed ? equal : selectorOrEqual) as ((left: unknown, right: unknown) => boolean) | undefined - return observableHook(absentSource)(selector ?? identity, comparison) +const absentKeyedHook: KeyedSnapshotHook = (keyOrSelector, second, equal) => { + const call = keyedHookCall(undefined, keyOrSelector, second, equal) + return observableHook(absentSource)(call.selector ?? identity, call.equal) } /** Subscribe the tree to the atomically assembled root standard-source roster. */ 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/tests/keyed-hook-member.client.spec.tsx b/packages/client/ui-renderer/tests/keyed-hook-member.client.spec.tsx new file mode 100644 index 0000000000..fdfaecf3d8 --- /dev/null +++ b/packages/client/ui-renderer/tests/keyed-hook-member.client.spec.tsx @@ -0,0 +1,61 @@ +// @vitest-environment jsdom +import { describe, expect, it, vi } from 'vitest' +import { act, renderHook } from '@testing-library/react' +import type { HostObservable, KeyedStandardSource } from '@deepseek-ai/dsh-client-ui-slots' +import { keyedObservableHook } from '../src/client/bindings.tsx' + +function observable(initial: T): HostObservable & { set(next: T): void } { + let value = initial + const listeners = new Set<() => void>() + return { + getSnapshot: () => value, + subscribe: (listener) => { + listeners.add(listener) + return () => { listeners.delete(listener) } + }, + set: (next) => { + value = next + for (const listener of [...listeners]) listener() + }, + } +} + +describe('keyed standard Hooks', () => { + it('reads the resolver\'s (key, member) source when the second argument is a string', () => { + const fork = observable(true) + const whole = observable({ title: 'one' }) + const resolver = vi.fn((key, member) => + member === undefined ? (key === 's1' ? whole : undefined) : (key === 's1' && member === 'session/fork' ? fork : undefined)) + const useAccess = keyedObservableHook(resolver) + + const member = renderHook(() => useAccess('s1', 'session/fork')) + expect(member.result.current).toBe(true) + act(() => { fork.set(false) }) + expect(member.result.current).toBe(false) + expect(resolver).toHaveBeenCalledWith('s1', 'session/fork') + + expect(renderHook(() => useAccess('s1', 'session/missing')).result.current).toBeUndefined() + expect(renderHook(() => useAccess('s1')).result.current).toEqual({ title: 'one' }) + expect(resolver.mock.calls.some(call => call.length === 1 && call[0] === 's1')).toBe(true) + }) + + it('keeps the selector, equality, and default-key call forms', () => { + const whole = observable({ title: 'one', count: 1 }) + const useValue = keyedObservableHook(key => (key === 'k' ? whole : undefined), 'k') + expect(renderHook(() => useValue('k', (value: unknown) => (value as { title: string }).title)).result.current).toBe('one') + expect(renderHook(() => useValue((value: unknown) => (value as { count: number }).count)).result.current).toBe(1) + const equal = vi.fn(() => true) + renderHook(() => useValue('k', (value: unknown) => value, equal)) + act(() => { whole.set({ title: 'two', count: 2 }) }) + expect(equal).toHaveBeenCalled() + const noDefault = keyedObservableHook(key => (key === 'k' ? whole : undefined)) + expect(renderHook(() => noDefault((value: unknown) => value)).result.current).toBeUndefined() + }) + + it('reads undefined for every call form while the source family is absent', () => { + const absent = keyedObservableHook(undefined) + expect(renderHook(() => absent('s1', 'session/fork')).result.current).toBeUndefined() + expect(renderHook(() => absent('s1', (value: unknown) => value ?? 'fallback')).result.current).toBe('fallback') + expect(renderHook(() => absent((value: unknown) => value ?? 'bare')).result.current).toBe('bare') + }) +}) 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..205e4c6b84 100644 --- a/packages/client/ui-schedule/README.i18n.yaml +++ b/packages/client/ui-schedule/README.i18n.yaml @@ -15,14 +15,14 @@ en: d152484eb41ac6b4 zh: 405b30feaf48c087 /deepseek-ai-dsh-client-ui-schedule/use-this-package: - en: c668e3d223102e47 - zh: efedf3996679fb17 + en: edba0e1573f3ce42 + zh: 77875b469d94cc62 /deepseek-ai-dsh-client-ui-schedule/use-this-package/time-zone-data-source: 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..220af1e6c7 100644 --- a/packages/client/ui-schedule/README.md +++ b/packages/client/ui-schedule/README.md @@ -27,6 +27,8 @@ Manage active and inactive tasks from the Automation tasks page and the right Si The shipped Web composition mounts `ui-schedule` with the Host Schedule service. The clock context that supplies the model's current time is preset-owned: `standard`, `cordis`, and `ptc` declare it, and `minimal` declares neither it nor the reminder tools. The Automation tasks sidebar entry opens a global page without selecting or activating a Session. The page header's New action starts a new Session, where the reminder is created by asking the model; the page itself has no creation form. Its task list supports text search and one All, Enabled, and Inactive status filter row; search matches the stored task name, the instruction, and the internal Session id, not a resolved Session title, and the empty state keeps the heading's New action beside the notice. Selecting an active or inactive task opens a second detail level with Rules and Records tabs. Every list row shows the task's stored title with its status, frequency, and next run and never the original Session name; the detail's name control shows the stored title. Rules contains the complete reminder, status, next target for active tasks, original recurrence rule, and task id. Daily rule labels show the saved local time and exact stored IANA zone, preserving nonzero seconds and milliseconds rather than substituting the browser's zone. The Linked session entry in the detail tab strip names the linked Session by its catalog title, falling back to the Session id when no title is available. When the strip cannot fit the tab list beside the labelled entry, the entry becomes an icon button with the same button style as More task actions, with the Session chat icon and a Linked session tooltip that also shows while the entry is disabled; the entry keeps focus when it switches layouts; the tab list scrolls without a visible scrollbar. It opens an available, unarchived Session after metadata loads; pending Session or Workspace metadata, an archived Session, missing Session membership, or a Workspace query error keeps it disabled with an explanation. The click rechecks availability; browsing does not unarchive the Session. Only this action requests Session activation. Deletion is available from the More task actions menu in the detail's top strip, separate from navigation. +The page header keeps the title at its natural width and moves New to another line when the two no longer fit together. The action label stays on one line. + Selecting a task from the list opens Rules; refreshing that task preserves the selected tab. Rules edits an active task's name, instruction, and run time; the edits stay in a local draft until saved, and inactive tasks remain read-only. Unmodified Left/Right arrows cycle the tabs, Home/End select the first/last tab, and keyboard focus follows the selection. The tabs do not consume these keys with Alt, Ctrl, Meta, or Shift. The linked-Session control in the detail tab strip stays available on the Rules tab, and confirmed deletion is available from either view. Rules shows the rule in a Run time card whose rows edit a local draft: Repeat is a menu of Weekly, Monday to Friday, Every day, Every N hours, Every N minutes, Every N seconds, Once, and Custom (cron), a weekly rule adds a Weekday row, a fixed-rate choice edits only the interval quantity in the unit it names, a one-shot rule edits separate Date and Time rows, and Custom (cron) edits one Cron expression row holding a five-field expression, interpreted in the selected time zone. The card parses that expression in the browser and, under the row, shows a localized sentence describing it; an expression the Host would reject shows the localized validation message in place of that sentence and blocks Save. A stored weekly rule whose weekday set is exactly Monday through Friday selects the Monday to Friday choice. The Date row is a read-only trigger showing the staged date as `YYYY/MM/DD` and opening a month calendar with localized weekday headings, month navigation, and a marked today; the draft and the submitted text keep the ISO form; the Time row is a read-only trigger showing one 24-hour clock and opening three scrolling columns of hours, minutes, and seconds with the staged value marked and scrolled into view. A calendar or clock pick stages the draft under the same staged save as every other row, arrow keys walk the open column or grid, Enter stages the marked value, Escape closes the panel and returns focus to its row, and a disabled row cannot open one. Clock rows show whole seconds, an untouched row keeps a stored millisecond value for its submit, and editing a time submits whole-second precision. Time zone is a searchable, height-bounded menu. An unlabeled top block keeps the five most recently selected exact zones in browser-local storage; first use seeds the actual system zone and UTC rather than inferring a location from UI language. The system zone is marked, and the remaining inventory is ordered by current UTC offset and canonical IANA id. Each visible label puts `UTC±HH:MM` before the localized zone name; canonical ids stay internal but remain searchable. Zones that ICU renders with the same offset and localized name share one visible row; every grouped id remains searchable, and an already stored id remains selected instead of being rewritten. The inventory comes from `Intl.supportedValuesOf('timeZone')`, and names come from `Intl.DateTimeFormat(..., { timeZoneName: 'longGeneric' })`: both are browser ICU/CLDR data, not a scraped or product-maintained translation table. There is therefore no crawler or generated zone-name resource to refresh. A third-party locale supplies its ordinary `time.locale` value and automatically receives the corresponding ICU names; only the selector's surrounding UI copy needs translation. When the runtime cannot enumerate zones, a short identifier fallback is offered, and a stored zone outside the offered set is kept. Daily, Weekly, and Cron keep their stored rule and IANA zone, and each frequency line names the zone only when it differs from the host's system zone. A one-shot After/At seeds the date and time from the record's stored zone, or this device's zone when the record stores none, so the seeded clock names the stored instant; changing that zone keeps the entered clock values and changes the instant. A kind the card seeds on selection uses the committed occurrence's clock and the choice's zone, which is the record's stored zone or this device's zone, a seeded weekly rule starts from that occurrence's weekday in that zone, and a seeded cron rule states that occurrence's clock as a daily expression. Every accepts at least 60 whole seconds, independent of time zones. One Save submits the complete expected record with the staged change and preserves the id, original Session, latest receipt, and saved history; [Schedule](../../schedule/schedule/README.md#use-this-package) defines future-target selection, reanchoring, and unchanged-rule no-ops. @@ -67,6 +69,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..88575c4405 100644 --- a/packages/client/ui-schedule/README.zh.md +++ b/packages/client/ui-schedule/README.zh.md @@ -27,6 +27,8 @@ kind: "package-reference" 随发行版交付的 Web 组合把 `ui-schedule` 与 Host Schedule 服务一起挂载。为模型提供当前时间的时钟上下文归 preset 所有:`standard`、`cordis` 与 `ptc` 声明它,`minimal` 既不声明它,也不声明提醒工具。侧栏的自动化任务入口打开全局页面,不选择或激活会话。页面页头的“新建”操作会打开一个新会话,提醒由模型在该会话中创建;页面本身没有创建表单。列表支持文本搜索和一行“全部/已开启/未运行”状态筛选;搜索匹配任务已存储的名称、指令和内部会话 id,不匹配解析出的会话标题,空状态在提示旁保留页头的“新建”操作。选择活动或未运行任务后,进入含“规则”和“任务运行记录”页签的第二层详情。每条列表行显示任务已存储的标题及其状态、频率和下次运行,不显示原会话名称;详情中的名称输入框显示任务已存储的标题。“规则”显示完整提醒、状态、活动任务的下一目标时间、原始重复规则和任务 id。每天的规则标签显示已保存的本地时间与精确的存储 IANA 时区,保留非零秒与毫秒,而不替换为浏览器时区。详情页签条内的“关联会话”入口按会话标题显示,取不到标题时回退显示会话 id。页签条放不下页签列表和带文字的入口时,入口收为与“更多任务操作”同样式的图标按钮,使用会话对话图标,悬停提示“关联会话”,入口禁用时也会显示;切换形态时保留焦点;页签列表可滚动但不显示滚动条。元数据加载后,它可打开可用且未归档的会话;会话或 Workspace 元数据尚未就绪、会话已归档、会话不在列表中或 Workspace 查询失败时,入口保持禁用并显示原因。点击时会重新检查可用性;浏览不会取消会话归档。仅此操作请求激活会话。删除位于详情顶部条带的“更多任务操作”菜单。 +页头按标题的自然宽度排布;标题和“新建”无法并排容纳时,将按钮移到下一行。操作文案保持单行。 + 从列表选择任务时默认打开“规则”;刷新同一任务会保留当前页签。活动任务的“规则”修改名称、指令和运行时间;这些修改保留在本地草稿中直到保存,未运行任务保持只读。不带修饰键的左右方向键循环切换页签,Home/End 选择第一个/最后一个页签,键盘焦点随选择移动。页签不会拦截这些键与 Alt、Ctrl、Meta 或 Shift 的组合。共用的会话入口位于详情页签条内,在“规则”页签可见;确认删除操作在两种页签下都可用。 “规则”在“运行时间”卡片中以行编辑本地草稿:“重复”是含每周、周一至周五、每天、每 N 小时、每 N 分钟、每 N 秒、仅一次和自定义(cron)的菜单,每周规则增加“星期”行,固定速率选项只修改它所属单位的间隔数量,一次性规则用独立的“日期”和“时间”两行编辑目标,自定义(cron)用一行“Cron 表达式”编辑按所选时区解释的 5 字段表达式。卡片在浏览器中解析该表达式,并在该行下方显示描述它的本地化语句;Host 会拒绝的表达式改为显示本地化校验信息,并在解析通过前阻止保存。已存储的每周规则若星期集合恰好为周一至周五,则选中“周一至周五”选项。“日期”行是只读触发器,以 `YYYY/MM/DD` 显示暂存的日期并展开带本地化星期表头、月份切换和今天标记的月历;草稿与提交文本保持 ISO 形态;“时间”行是只读触发器,显示统一的 24 小时时钟,并展开时、分、秒三列可滚动列表,当前值高亮并在打开时滚动到可见。在月历或时钟上点选即按与其他行相同的分阶段保存写入草稿;方向键在打开的列或网格内移动,Enter 选定当前值,Escape 关闭面板并把焦点还给所在行,被禁用的行无法打开面板。时钟行显示到秒,未改动的行在提交时保留已存储的毫秒值,编辑时间时按整秒精度提交。“时区”使用高度受限的可搜索菜单。顶部无标题区域保留浏览器本地最近选过的 5 个准确时区;首次使用按真实系统时区和 UTC 初始化,而不根据界面语言猜测所在地。系统时区带有标记,其余清单按当前 UTC 偏移、再按规范 IANA 标识排序。可见文案把 `UTC±HH:MM` 放在本地化时区名称之前;IANA 标识仅在内部使用,但可用于搜索。ICU 显示成相同偏移和本地化名称的多个时区只占一行;所有被合并的标识仍可用于搜索,任务已保存的标识也会继续作为选中值,不会被改写。时区清单来自 `Intl.supportedValuesOf('timeZone')`,名称来自 `Intl.DateTimeFormat(..., { timeZoneName: 'longGeneric' })`:两者都是浏览器内置的 ICU/CLDR 数据,不是抓取或产品自维护的翻译表。因此没有需要刷新的爬虫或生成时区资源;第三方语言包只需提供常规的 `time.locale` 值,即可自动获得对应的 ICU 名称,仅需翻译选择器周边的 UI 文案。运行时无法枚举时改用简短的标识候选列表,已存储但不在其中的时区会保留。每天、每周和 cron 保留各自已存储的规则与时区,其频率行仅在时区与宿主系统时区不同时标出时区。一次性 After/At 以记录已存储的时区初始化日期和时间;记录未保存时区时取本设备时区,初始钟表值在该时区下仍表示同一瞬时;更改时区会保留输入的钟表值并改变时点。因选择种类而重新初始化的种类使用已提交发生时点的钟表值和该选项的时区,该时区取记录已存储的时区或本设备时区:每周的星期取自该发生时点在该时区下的星期,cron 则把该发生时点的钟表值写成每天执行的表达式。固定间隔至少为 60 整秒,不受时区影响。一次保存以分阶段的变更提交完整预期记录,并保留 id、原会话、最近一次回执及已保存历史;未来目标选择、重新确定起算时间和未变更规则的无写入语义见 [Schedule](../../schedule/schedule/README.zh.md#use-this-package)。 @@ -67,6 +69,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 fa0326641b..08b23740e8 100644 --- a/packages/client/ui-schedule/package.json +++ b/packages/client/ui-schedule/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-schedule", "description": "Host task management page and Session reminder catalog", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "type": "module", "main": "lib/index.js", "types": "lib/types/index.d.ts", @@ -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/TaskManagerPage.module.css b/packages/client/ui-schedule/src/client/TaskManagerPage.module.css index 25b573fcd4..ba3ee2a030 100644 --- a/packages/client/ui-schedule/src/client/TaskManagerPage.module.css +++ b/packages/client/ui-schedule/src/client/TaskManagerPage.module.css @@ -45,9 +45,10 @@ padding: 0 clamp(24px, 4vw, 48px) 48px; } -/* The page name and the creation actions on one line. */ +/* Page title and creation actions. */ .pageHeading { display: flex; + flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 16px; @@ -68,8 +69,9 @@ their titles share one size. The theme carries no size token for this step, which is why every first-level page states the same literal. */ .pageHeading h1 { - flex: 1; + flex: 0 1 auto; min-width: 0; + max-width: 100%; margin: 0; font-size: 20px; line-height: 28px; @@ -82,6 +84,7 @@ flex: none; align-items: center; gap: 16px; + white-space: nowrap; } /* The Plugins toolbar's Add-plugin step: a 32px capsule with the 13px label. */ 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/tests/task-detail.client.spec.tsx b/packages/client/ui-schedule/tests/task-detail.client.spec.tsx index bb6a084780..ff64d41b88 100644 --- a/packages/client/ui-schedule/tests/task-detail.client.spec.tsx +++ b/packages/client/ui-schedule/tests/task-detail.client.spec.tsx @@ -11,7 +11,7 @@ */ import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' @@ -118,6 +118,7 @@ function mount( useSessionStatus: select => select(new Map()), useSessionRetainInfo: () => undefined, useResource: () => { throw new Error('The task manager does not load document resources') }, + ...allowAllAccess, onDelete: vi.fn(async () => 'deleted'), onRetry: vi.fn(async () => {}), onNewTask: vi.fn(), diff --git a/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx index 52158d0ed2..7f29237374 100644 --- a/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx +++ b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx @@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { act, cleanup, fireEvent, isInaccessible, render, screen, waitFor, within } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { bindSnapshotSelector, makeTranslate, RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, bindSnapshotSelector, makeTranslate, RemoteError } from '@deepseek-ai/dsh-client-test-runtime' import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' @@ -174,6 +174,7 @@ function mount( useSessionStatus: select => select(new Map()), useSessionRetainInfo: () => undefined, useResource: () => { throw new Error('The task manager does not load document resources') }, + ...allowAllAccess, onDelete: vi.fn(async () => 'deleted'), onRetry: vi.fn(async () => {}), onNewTask: vi.fn(), @@ -1598,6 +1599,7 @@ describe('Task manager details', () => { useResource={unread} useSessionStatus={unread} useSessionRetainInfo={unread} + {...allowAllAccess} />) } 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..cb4b986e3d --- /dev/null +++ b/packages/client/ui-secret-mask/package.json @@ -0,0 +1,65 @@ +{ + "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", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ] +} 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/README.i18n.yaml b/packages/client/ui-session/README.i18n.yaml index 02db9d6ecb..447f8f489b 100644 --- a/packages/client/ui-session/README.i18n.yaml +++ b/packages/client/ui-session/README.i18n.yaml @@ -12,8 +12,11 @@ en: 75428e0474a073a4 zh: 18f1db4b4c5302e5 /deepseek-ai-dsh-client-ui-session/table-of-contents: - en: b4683d2a53256fda - zh: 4e65ff63dc8c48fe + en: 12e1ffc25a2d6695 + zh: 321156dea1356e55 +/deepseek-ai-dsh-client-ui-session/access-hooks: + en: 619ba442c3e40fb0 + zh: af0206a774ac9bc1 /deepseek-ai-dsh-client-ui-session/model-experience: en: cb2d4451e8bf8520 zh: 6d3adbb930d90c59 diff --git a/packages/client/ui-session/README.md b/packages/client/ui-session/README.md index d10b62ffbc..79ac9f0e73 100644 --- a/packages/client/ui-session/README.md +++ b/packages/client/ui-session/README.md @@ -14,12 +14,18 @@ Running status comes from Host list baselines or status events. Subagent catalog ## Table of Contents +- [Access Hooks](#access-hooks) - [Model Experience](#model-experience) - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) - [Dev Note](#dev-note) ----- + +## Access Hooks + +The package injects the Client `remoteAccess` service and publishes Session access Hooks over its `source()`: the root `useSessionAccess(sessionId, action)` answers on one Session resource, and the Session-scope `useAccess(action)` answers on the bound Session's resource; the `global` resource's answer is a different Hook, `useRemoteAccess(action)`, so neither shadows the other. The SessionMaybe-scope `useAccess(action)` returns `undefined` while no Session is bound, which callers treat as not allowed; a decision on the `global` resource reads `useRemoteAccess` instead. Snapshot semantics belong to [`dsh-api-remote-access`](../../api/remote-access/README.md#client-face). + ## Model Experience diff --git a/packages/client/ui-session/README.zh.md b/packages/client/ui-session/README.zh.md index 95944f55f3..157cc79a7f 100644 --- a/packages/client/ui-session/README.zh.md +++ b/packages/client/ui-session/README.zh.md @@ -14,12 +14,18 @@ kind: "package-reference" ## 目录 +- [访问 Hook](#access-hooks) - [模型体验](#model-experience) - [已知限制与暂缓事项](#known-limitations-and-deferred-work) - [开发备注](#dev-note) ----- + +## 访问 Hook + +本包注入 Client `remoteAccess` 服务,并在其 `source()` 之上发布会话访问 Hook:根作用域的 `useSessionAccess(sessionId, action)` 回答某一个 Session 资源上的访问,Session 作用域的 `useAccess(action)` 回答所绑定 Session 资源上的访问;`global` 资源上的答案是另一个 Hook `useRemoteAccess(action)`,两者互不遮蔽。SessionMaybe 作用域的 `useAccess(action)` 在未绑定 Session 时返回 `undefined`,调用方将其视为不允许;需要 `global` 资源上的判断时读 `useRemoteAccess`。快照语义归 [`dsh-api-remote-access`](../../api/remote-access/README.zh.md#client-face)。 + ## 模型体验 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 6a80f10dc2..8c6c20ccee 100644 --- a/packages/client/ui-session/package.json +++ b/packages/client/ui-session/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-session", "description": "Session Controller adapter for React and session-scoped slots", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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-api-remote-access", "@deepseek-ai/dsh-api-remotes", "@deepseek-ai/dsh-api-session-controller", "@deepseek-ai/dsh-client-ui-renderer" @@ -45,6 +47,7 @@ }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-api-session-controller": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", @@ -54,10 +57,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/src/client/index.ts b/packages/client/ui-session/src/client/index.ts index 5017904d86..29aeebce04 100644 --- a/packages/client/ui-session/src/client/index.ts +++ b/packages/client/ui-session/src/client/index.ts @@ -12,6 +12,7 @@ import type { } from '@deepseek-ai/dsh-api-session-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type { RemoteEndpoint } from '@deepseek-ai/dsh-api-remote-access/client' import { notifySubscribers } from '@deepseek-ai/dsh-client-store' import { WeakMapWithValues } from '@deepseek-ai/dsh-util-values' import { standardHookPropName } from '@deepseek-ai/dsh-client-ui-slots' @@ -158,6 +159,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { useSessions: UseSessions useSessionStatus: UseSessionStatus useSessionRetainInfo: UseSessionRetainInfo + /** Whether the current Peer may call `action` on one Session resource. */ + useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean } interface SessionStandardProps { @@ -167,6 +170,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { sessionId: SessionId /** Host-computed projection values addressed by projection key. */ useProjection: UseProjection + /** Whether the current Peer may call `action` on this Session resource. */ + useAccess: (action: RemoteEndpoint) => boolean } interface SessionMaybeStandardProps { @@ -176,6 +181,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { sessionId: SessionId | undefined /** Host-computed projection values; every key is absent without a Session. */ useProjection: UseProjection + /** The bound Session's access answer; `undefined` without a Session, which callers treat as not allowed. */ + useAccess: (action: RemoteEndpoint) => boolean | undefined } } @@ -660,8 +667,8 @@ function claimStandardProp(kind: StandardMemberKind, name: string, finalProps: S finalProps.add(propName) } -/** Required Controller and renderer services. */ -export const inject = ['sessions', 'slots', 'remote'] +/** Required Controller, renderer, Remote, and access services. */ +export const inject = ['sessions', 'slots', 'remote', 'remoteAccess'] /** * Install the Session root source and scoped adapter. @@ -676,9 +683,18 @@ export function apply(ctx: Context): void { }, keyedHooks: { sessionRetainInfo: key => ctx.sessions.retainInfo(key as SessionId), + sessionAccess: (sessionId, action) => action === undefined + ? undefined + : ctx.remoteAccess.source('session', sessionId, action), }, } satisfies RootStandardSourceContribution) ctx.slots.installScope('session', service.adapter) + service.provide({ + keyedHooks: ['access'], + resolve: binding => ({ + keyedHooks: { access: action => ctx.remoteAccess.source('session', binding.sessionId, action) }, + }), + }) } function sameSessionStatus(left: SessionStatusSnapshot, right: SessionStatusSnapshot): boolean { diff --git a/packages/client/ui-session/tests/status-controller.client.spec.ts b/packages/client/ui-session/tests/status-controller.client.spec.ts index 1bf3bfec88..e2e75adede 100644 --- a/packages/client/ui-session/tests/status-controller.client.spec.ts +++ b/packages/client/ui-session/tests/status-controller.client.spec.ts @@ -14,6 +14,7 @@ it('preserves unlisted child status through metadata updates and main view ackno sessionId: parentId, updatedAt: 1, running: false, blank: false, agentAvailable: true, }] })) mock.remote.session.projections.mockResolvedValue(ok({ + kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ id: childId, createdAt: 1, mode: 'continuable', label: 'Child' }] }, })) diff --git a/packages/client/ui-session/tests/ui-session.client.spec.ts b/packages/client/ui-session/tests/ui-session.client.spec.ts index a91f0e2b9c..ae105e7b8e 100644 --- a/packages/client/ui-session/tests/ui-session.client.spec.ts +++ b/packages/client/ui-session/tests/ui-session.client.spec.ts @@ -715,25 +715,49 @@ describe('ui-session apply', () => { const slots = { provideRoot: vi.fn(), installScope: vi.fn(), + bindStoreScope: vi.fn(), + } + const accessSources = new Map>() + const remoteAccess = { + source: vi.fn((kind: string, id: string, action: string): HostObservable => { + const key = `${kind}:${id}:${action}` + let source = accessSources.get(key) + if (source === undefined) { + source = createSnapshotStore(false) + accessSources.set(key, source) + } + return source + }), } ctx.provide('sessions', bench.sessions) ctx.provide('slots', slots as never) + ctx.provide('remoteAccess', remoteAccess) apply(ctx) expect(ctx.uiSession).toBeInstanceOf(UiSession) const retainInfoMatcher: unknown = expect.any(Function) + const sessionAccessMatcher: unknown = expect.any(Function) expect(slots.provideRoot).toHaveBeenCalledWith({ hooks: { sessions: bench.sessions.list, sessionStatus: ctx.uiSession.sessionStatus, }, - keyedHooks: { sessionRetainInfo: retainInfoMatcher }, + keyedHooks: { sessionRetainInfo: retainInfoMatcher, sessionAccess: sessionAccessMatcher }, }) expect(slots.installScope).toHaveBeenCalledWith('session', ctx.uiSession.adapter) const root = slots.provideRoot.mock.calls[0]![0] as RootStandardSourceContribution expect(root.keyedHooks?.sessionRetainInfo?.(sessionId('s1'))) .toBe(bench.retainInfo(sessionId('s1'))) + // `useSessionAccess(sessionId, action)` reads the Session resource's answer; a call without an action names no source. + expect(root.keyedHooks?.sessionAccess?.(sessionId('s1'), 'session/fork')) + .toBe(remoteAccess.source('session', sessionId('s1'), 'session/fork')) + expect(root.keyedHooks?.sessionAccess?.(sessionId('s1'))).toBeUndefined() + + // The Session scope's `useAccess(action)` reads the bound Session's answer from the same source. + const binding = bench.binding(sessionId('s2')) + const scoped = ctx.uiSession.bindingSource(bench.reference(binding)).getSnapshot() + expect(scoped.keyedHooks.access?.('session/fork')).toBe(remoteAccess.source('session', sessionId('s2'), 'session/fork')) }) it('keeps the Host loader half inert', () => { diff --git a/packages/client/ui-session/tsconfig.json b/packages/client/ui-session/tsconfig.json index de3f6472ee..e38563a19b 100644 --- a/packages/client/ui-session/tsconfig.json +++ b/packages/client/ui-session/tsconfig.json @@ -14,6 +14,9 @@ { "path": "../../api/remotes/tsconfig.client.json" }, + { + "path": "../../api/remote-access/tsconfig.client.json" + }, { "path": "../../api/session-controller/tsconfig.client.json" }, 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/README.i18n.yaml b/packages/client/ui-settings-account/README.i18n.yaml index 65b2cc2812..a0ed274b05 100644 --- a/packages/client/ui-settings-account/README.i18n.yaml +++ b/packages/client/ui-settings-account/README.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-settings-account/README.md /: - en: 1fcba8f273b661fb - zh: 14e1236f84ae39d7 + en: 13d891a226092817 + zh: 90bf6ff56dd3c096 /deepseek-ai-dsh-client-ui-settings-account: en: 9ff7ac2d70f70b59 zh: ded522c4cfd6e040 @@ -15,17 +15,17 @@ en: c26f81e8adf0128b zh: e11ab371f51f66bc /deepseek-ai-dsh-client-ui-settings-account/use-this-package: - en: fe1db216d397749f - zh: f823c2cd43152e66 + en: f73e8f3448239b51 + zh: 88bee1c1f465b906 /deepseek-ai-dsh-client-ui-settings-account/use-this-package/desktop-onboarding: en: c1c4db71fd09ca13 zh: a40c0a01e9951945 /deepseek-ai-dsh-client-ui-settings-account/understand-the-implementation: - en: 93e9874de6ed3a4d - zh: d98ba48e88078eee + en: 149d25b949a24036 + zh: a432400e245bf48b /deepseek-ai-dsh-client-ui-settings-account/further-exploration: - en: a28acdef21b1643a - zh: 5e2e357a6b716274 + en: f5ca95916ef486dc + zh: 1e238d8299e0d838 /deepseek-ai-dsh-client-ui-settings-account/model-experience: en: ee1df7ca3467ee3f zh: 84904a5148da3862 @@ -33,8 +33,8 @@ en: ca3015e252db0114 zh: ebca9253cf15e8e9 /deepseek-ai-dsh-client-ui-settings-account/known-limitations-and-deferred-work: - en: 161a4d95bfdd5181 - zh: b94c3e165e69d23b + en: 7afbd3f7afc20bd8 + zh: f54c57e3d6738c7c /deepseek-ai-dsh-client-ui-settings-account/known-limitations-and-deferred-work/dev-note: en: 2facb0fc2e6c1a9c zh: bd04803f5c9e132c diff --git a/packages/client/ui-settings-account/README.md b/packages/client/ui-settings-account/README.md index c5a3c88397..913eddfa4b 100644 --- a/packages/client/ui-settings-account/README.md +++ b/packages/client/ui-settings-account/README.md @@ -1,5 +1,5 @@ --- -description: "Desktop Account settings display DeepSeek login state and offer browser authorization and cancellation; the sidebar account menu provides Platform sign-out." +description: "Account settings display DeepSeek login state and offer browser authorization and cancellation; the sidebar account menu provides Platform sign-out." kind: "package-reference" --- @@ -28,7 +28,7 @@ A new account-model sign-in-required event displays “Model unavailable. Please ## Use this package -The client activates only inside Desktop, identified by its preload bridge. Plain Web clients keep the standard Settings launcher and API-key onboarding without account login, account settings, or an account-state subscription. +Desktop and plain Web clients both mount the sidebar account launcher, Account settings, the sign-in step of model onboarding, and the account-state subscription. Desktop main opens the authorization page in the system browser. A plain Web client, identified by the absent Desktop preload bridge, sends `login_source` web with its own origin as the callback origin, preopens a tab during the sign-in click, navigates it to the authorization URL with the same `theme` parameter once its attempt receives one, and closes it on failure, expiry, or cancellation; a blocked popup leaves the copy-link route. Embedded Platform pages, Desktop onboarding, and the native device reader stay Desktop-only, so Web Platform links open new tabs. The sidebar and Account settings display circular profile images with diameters of 24px and 32px respectively, with the account icon as fallback when the URL is absent or the image fails to load. The collapsed sidebar centers the avatar in a 36 × 36 px button. Before sign-in the sidebar launcher shows a More row instead, leading with the ellipsis glyph. @@ -42,7 +42,7 @@ Desktop usage, top-up, and onboarding recharge actions open one isolated native Chat offers each live quota failure from a bound Session to the frame-wide `shell.quota-notice` chain from its host in `shell.overlay`, so the notice outlives the Chat panel that reported it. The account entry claims `ACCOUNT_QUOTA`: while an account credential is stored and the shared host entry exists, the Modal offers Cancel and Top up. While a page requested through the shared request channel is showing, the native view covers this document, so the entry paints neither the Modal nor the Toast. A quota failure that arrives while a Settings-opened page is already showing is not retained: it stays subject to newest-notice replacement, and the Modal appears after the viewer returns while that notice is still current. That Modal reports the failure of the original request, not the account's current balance: the top-up re-read is a separate read, and returning neither proves a successful payment nor dismisses the notice on its own. The notice's own Top up is the retained case: it calls `keepOpen()` and requests the `top-up` page through the shared request channel, keeping that notice and its page mounted through later quota failures. With the shared host entry the entry waits for the first account snapshot instead of rendering a Toast that its own timer could discard; a snapshot that reports no stored credential, or a failed account stream with no snapshot, then renders the same neutral warning Toast itself, and without that host entry the entry renders that Toast immediately, instead of relying on the chat host fallback. The entry owns the hold and its page request and releases both when it unmounts, so a later quota failure publishes again without replaying the dropped ones; dismissal or sign-out clears the hold and the page request. Close, Cancel, a sign-out, or leaving the notice's own embedded page takes the notice down without retrying the request. -The account menu's Feedback entry opens the Feishu questionnaire in the system browser. Every click samples its context then: the account UID when the profile is ready and carries an id, the build version as harness_version, and device_info. The device_info value includes the physical screen resolution as screen_resolution=widthxheight, after rounding the screen dimensions multiplied by devicePixelRatio; unavailable screen dimensions omit this entry. Each context field also carries hide_*=1, stale prefill values for these fields are dropped from the configured form URL first, including uid, device_info and harness_version regardless of the configured URL. The URL carries no os_version, device_brand, app_locale or separate screen_resolution parameters; configured prefill and hide parameters for these fields are removed. Tokens and masked contact details stay out, and a signed-out, still-loading, or failed profile leaves prefill_uid out. When the Desktop bridge has no deviceInfo reader, the form opens with navigator.userAgent. Desktop exposes the optional dshDesktop.deviceInfo reader, whose field format the [Desktop README](../../../apps/desktop/README.md) owns; its answer replaces the user agent, a failed read still opens the form with any available screen resolution in device_info, and device_info describes the reported environment rather than a hardware model. Configure contactFormUrl on the ui-settings-account plugin to select another HTTPS form; contactSource defaults to empty until the questionnaire supports a Harness source option. +The account menu's Feedback entry opens the Feishu questionnaire in the system browser. Every click samples its context then: the account UID when the profile is ready and carries an id, the build version as harness_version, and device_info. The device_info value includes the physical screen resolution as screen_resolution=widthxheight, after rounding the screen dimensions multiplied by devicePixelRatio; unavailable screen dimensions omit this entry. Each context field also carries hide_*=1, stale prefill values for these fields are dropped from the configured form URL first, including uid, device_info and harness_version regardless of the configured URL. The URL carries no os_version, device_brand, app_locale or separate screen_resolution parameters; configured prefill and hide parameters for these fields are removed. Tokens and masked contact details stay out, and a signed-out, still-loading, or failed profile leaves prefill_uid out. In a plain browser, or when the Desktop bridge has no deviceInfo reader, the form opens with navigator.userAgent. Desktop exposes the optional dshDesktop.deviceInfo reader, whose field format the [Desktop README](../../../apps/desktop/README.md) owns; its answer replaces the user agent, a failed read still opens the form with any available screen resolution in device_info, and device_info describes the reported environment rather than a hardware model. Configure contactFormUrl on the ui-settings-account plugin to select another HTTPS form; contactSource defaults to empty until the questionnaire supports a Harness source option. Account profile and balance cards share the [settings card material and radius](../../../docs/web-styling.md#corner-radii-and-settings-cards). Usage and top-up links match standard Button geometry; authorization actions use the shared Button. @@ -68,14 +68,14 @@ The welcome page requires Get started. The credit page always appears. A positiv The Account section appears first in Settings only while signed in; it is hidden before account state loads and after sign-out. The plugin owns one Host snapshot stream shared through framework hooks by settings.section and settings.launcher. The launcher opens Settings and offers Sign out only while an account credential is stored. Platform failures leave the menu available for retry. It maintains no independent credential state. -The desktop controller writes progress to `ui-settings-account` through Host settings. Completion first applies `ui-chat.transcriptView` and `ui-chat.performanceUsage` together, then calls the shared Coding Tools preference to persist `ui-settings.enabled`, and finally saves the done marker; a rejected write keeps the flow available for retry. Successful completion reveals the workspace through a 180ms fade; choices and ordinary navigation preview immediately while writes run in order. A failed final queued write restores saved progress and allows retry. Completion waits for queued choices and retains the page until preferences persist; reduced motion skips the fade. Onboarding choices compact, standard, and detailed apply directly to the corresponding Chat work-detail modes. API-key entry and explicit skip select standard; onboarding does not select verbose. Complete Figma illustration layers are bundled as transparent, palette-compressed 3× PNG assets; welcome layers are merged with local sidebar blur; recharge uses a 70% opaque foreground window with local blur of the covered illustration, and headings use the bundled Montserrat brand font; English headings and descriptions use Light (300), except the DeepSeek Harness brand within headings uses Medium (500); card titles retain Regular (400) when selected. English footer navigation uses Light (300). Confirmed onboarding sets a 960px minimum window width and enlarges narrower windows; completion releases the minimum without restoring the previous size. Loading or already-completed onboarding does not resize the window. Empty footer navigation space passes pointer events through to the primary action. Cards exclude native window dragging and own the keyboard focus outline for their checkbox. The account package owns its onboarding overlay and control geometry. Each step and the confirmation dialog has a separate component; the flow coordinates navigation, transitions, and recharge. The overlay hides the workspace while initial account and progress state loads. Question headings and cards follow the Figma positions at 1440 × 920 and 960 × 600, independently of their action buttons. On macOS, content clears the body portal’s inherited no-drag region and a first-child drag band leaves an 8px native resize margin; interactive controls and later dialogs exclude their regions, and a native Platform page disables the underlying onboarding band. The upper workspace popup illustration has an opaque background in both languages and themes; the underlying sidebar omits its selected-row highlight. Welcome keeps its illustration at its original size, repositions and clips the artwork in narrow windows, and reveals the complete illustration on wide windows. The [historical onboarding decision](../../../.agents/notes/archived/feature/2026-09-16-desktop-onboarding.md) owns persistence and presentation trade-offs. +The desktop controller writes progress to `ui-settings-account` through Host settings. Completion first applies `ui-chat.transcriptView` and `ui-chat.performanceUsage` together, then calls the shared Coding Tools preference to persist `ui-settings.enabled`, and finally saves the done marker; a rejected write keeps the flow available for retry. Successful completion reveals the workspace through a 180ms fade; choices and ordinary navigation preview immediately while writes run in order. A failed final queued write restores saved progress and allows retry. Completion waits for queued choices and retains the page until preferences persist; reduced motion skips the fade. Onboarding choices compact, standard, and detailed apply directly to the corresponding Chat work-detail modes. API-key entry and explicit skip select standard; onboarding does not select verbose. Complete Figma illustration layers are bundled as transparent, lossless 3× WebP assets; welcome layers are merged with local sidebar blur; recharge uses a 70% opaque foreground window with local blur of the covered illustration, and headings use the bundled Montserrat brand font; English headings and descriptions use Light (300), except the DeepSeek Harness brand within headings uses Medium (500); card titles retain Regular (400) when selected. English footer navigation uses Light (300). Confirmed onboarding sets a 960px minimum window width and enlarges narrower windows; completion releases the minimum without restoring the previous size. Loading or already-completed onboarding does not resize the window. Empty footer navigation space passes pointer events through to the primary action. Cards exclude native window dragging and own the keyboard focus outline for their checkbox. The account package owns its onboarding overlay and control geometry. Each step and the confirmation dialog has a separate component; the flow coordinates navigation, transitions, and recharge. The overlay hides the workspace while initial account and progress state loads. Question headings and cards follow the Figma positions at 1440 × 920 and 960 × 600, independently of their action buttons. On macOS, content clears the body portal’s inherited no-drag region and a first-child drag band leaves an 8px native resize margin; interactive controls and later dialogs exclude their regions, and a native Platform page disables the underlying onboarding band. The upper workspace popup illustration has an opaque background in both languages and themes; the underlying sidebar omits its selected-row highlight. Welcome keeps its illustration at its original size, repositions and clips the artwork in narrow windows, and reveals the complete illustration on wide windows. The [historical onboarding decision](../../../.agents/notes/archived/feature/2026-09-16-desktop-onboarding.md) owns persistence and presentation trade-offs. ## Further Exploration The [credentials subsystem](../../../docs/subsystems/credentials.md) owns storage APIs; the [architecture](../../../docs/architecture.md) explains application composition. -Account login uses a dismissible dialog before the model onboarding credential editor. The dialog uses a compact, right-aligned action row with the primary action last. The sidebar displays the profile name, falling back to the server-masked phone number or email when the name is absent; it stays blank while the profile is loading. Dialog copy and the sidebar account label are not text-selectable; the copy-link button remains available and restores its label two seconds after each successful copy. Clipboard failures show Copy failed on the link for two seconds without interrupting sign-in. Waiting shows a copyable authorization link and a loading indicator; timeout and failure require an explicit retry. The dialog's Copy sign-in link and the Settings Open link append the resolved Desktop palette as `theme=light` or `theme=dark` from the live theme snapshot, so both routes reach the Platform page in the current application theme without changing the theme preference Platform has saved. Sign-in failures render in that dialog; a failed sign-out keeps the menu open so the user can try again, and the launcher shows no failure of its own. Closing a waiting dialog cancels its Host attempt. The sidebar can reopen the same API-key editor through the settings coordinator. +Account login uses a dismissible dialog before the model onboarding credential editor. The dialog uses a compact, right-aligned action row with the primary action last. The sidebar displays the profile name, falling back to the server-masked phone number or email when the name is absent; it stays blank while the profile is loading. Dialog copy and the sidebar account label are not text-selectable; the copy-link button remains available and restores its label two seconds after each successful copy. Clipboard failures show Copy failed on the link for two seconds without interrupting sign-in. Waiting shows a copyable authorization link and a loading indicator; timeout and failure require an explicit retry. The dialog's Copy sign-in link and the Settings Open link append the resolved application palette as `theme=light` or `theme=dark` from the live theme snapshot, so both routes reach the Platform page in the current application theme without changing the theme preference Platform has saved. Sign-in failures render in that dialog; a failed sign-out keeps the menu open so the user can try again, and the launcher shows no failure of its own. Closing a waiting dialog cancels its Host attempt. The sidebar can reopen the same API-key editor through the settings coordinator. A terminal account-state stream failure appears in the sign-in dialog or Account settings. Plugin unload suppresses late failure reports. @@ -99,10 +99,12 @@ No model request prefix changes. - Profile and recharge-wallet balances use the existing Platform Web endpoints through Host getProfile / getBalance. The page refreshes when opened and after login or reconnect, preserves server-masked contact data, and shows query failures independently without manufacturing a zero balance. Usage and top-up use Host-provided links derived from platformOrigin and the browser’s own login; the links never carry a DSH token. - Completed installations do not reapply defaults or overwrite later user preferences. Completion does not synchronize across devices or create a per-account history. -- Onboarding follows the interface locale and theme, with four Figma PNG illustration sets covering Chinese and English in light and dark appearance. Export canvases include the full illustration geometry; Finder artwork uses the same vertical fade in both themes. +- Onboarding follows the interface locale and theme, with four Figma illustration sets covering Chinese and English in light and dark appearance. Export canvases include the full illustration geometry; Finder artwork uses the same vertical fade in both themes. - The notice copy is server-localized for the UI language in effect when the client reads it. Switching language does not itself re-read the unnotified bonus, so a notice already on screen keeps the copy the server sent for the earlier language until the user refreshes or the account lifecycle restarts. +- Web sign-in needs a loopback HTTP page origin (`localhost`, `127.0.0.1`, or `[::1]`), because the Host accepts only those callback origins. A Web UI reached through `--trusted-host` or an HTTPS reverse proxy still shows the entry, but starting sign-in fails with the generic retry state; such deployments add an API key instead. + - The Platform view’s dialog marks every other document child inert, including the Desktop-owned caption menu host, so the Application and Edit menu stays visible but cannot be operated until the view closes. Exempting that host needs an inertness contract owned by the Desktop. diff --git a/packages/client/ui-settings-account/README.zh.md b/packages/client/ui-settings-account/README.zh.md index 09bc1997bb..0015b1ffe5 100644 --- a/packages/client/ui-settings-account/README.zh.md +++ b/packages/client/ui-settings-account/README.zh.md @@ -1,5 +1,5 @@ --- -description: "Desktop 设置中的账号页面显示 DeepSeek 登录状态,并提供浏览器授权和取消;侧边栏账号菜单提供 Platform 退出登录。" +description: "设置中的账号页面显示 DeepSeek 登录状态,并提供浏览器授权和取消;侧边栏账号菜单提供 Platform 退出登录。" kind: "package-reference" --- @@ -28,7 +28,7 @@ kind: "package-reference" ## 使用此包 -客户端仅在具有 preload 桥接的 Desktop 内启用。普通 Web 客户端保留标准设置入口和 API Key 引导,不显示账号登录和账号设置,也不订阅账号状态。 +Desktop 与普通 Web 客户端都挂载侧边栏账号菜单、账号设置、模型引导中的登录步骤,并订阅账号状态。Desktop 主进程在系统浏览器中打开授权页面。普通 Web 客户端(以缺少 Desktop preload 桥接识别)以 `login_source` web 发起登录,并以自身 origin 作为回调 origin;它在点击登录时预先打开一个标签页,本次尝试获得授权 URL 后带上相同的 `theme` 参数导航该标签页,并在失败、过期或取消时关闭它;弹窗被拦截时仍可使用复制链接。内嵌 Platform 页面、Desktop 引导和原生设备信息读取器仅在 Desktop 中提供,因此 Web 中的 Platform 链接在新标签页打开。 侧边栏和账号设置以正圆图片显示账号头像,直径分别为 24px 和 32px;头像 URL 缺失或图片加载失败时使用账号图标兜底。折叠侧边栏将头像居中放置在 36 × 36 px 的按钮内。登录前侧边栏入口改为「更多」行,以三点图标开头。 @@ -42,7 +42,7 @@ Desktop 的用量、充值与引导充值操作在 48px 返回栏下方打开同 Chat 通过 `shell.overlay` 中的宿主把已绑定 Session 的实时欠费交给全局 `shell.quota-notice` 链,提示的生命周期因此长于上报它的 Chat 面板。账号条目认领 `ACCOUNT_QUOTA`:已存储账号凭证且存在共享宿主条目时,Modal 提供取消和去充值。只要通过该共享请求通道请求的页面正在显示,原生视图就会盖住本页,因此该条目既不绘制 Modal 也不绘制 Toast。在 Account 设置页已打开页面的情况下新到达的欠费不会被保持:它仍受最新提示替换规则约束,返回后若该提示仍是最新一条就显示 Modal。该 Modal 报告的是原始请求的失败,而不是账号当前余额:返回时的重读是一次独立读取,返回本身既不证明支付成功,也不会自动撤下该提示。提示自身的去充值属于被保持的情形:它调用 `keepOpen()` 并通过共享请求通道申请 `top-up` 页面,使该提示与其页面在后续欠费期间保持挂载。存在共享宿主条目时,该条目会等待首个账号快照,而不是渲染一个可能被自身计时器丢弃的 Toast;快照报告未存储凭证,或账号流失败且无快照时,才由该条目自行渲染同一段中立警告 Toast,缺少该宿主条目时则立即渲染该 Toast,而不依赖 Chat 宿主回退。该条目持有保持与页面请求,并在自身卸载时释放二者,因此后续欠费会重新发布而不重放已丢弃的提示;关闭与退出登录也会清除保持和页面请求。关闭、取消、退出登录或离开该提示自己的内嵌页面都会撤下提示,且不会重试请求。 -账号菜单的“意见反馈”入口在系统浏览器中打开飞书问卷。每次点击都按当时的上下文取值:profile ready 且带 id 时的账号 UID、以 harness_version 表示的构建版本,以及 device_info。device_info 以 screen_resolution=宽x高 包含屏幕物理分辨率,尺寸乘以 devicePixelRatio 后四舍五入;屏幕尺寸不可用时省略此项。所有上下文字段同时设置 hide_*=1,配置的表单 URL 中这些字段的 stale prefill 参数先被清除,uid、device_info 与 harness_version 的隐藏参数不依赖配置 URL 的取值。URL 不携带 os_version、device_brand、app_locale 或独立的 screen_resolution 参数;配置 URL 中这些字段的 prefill 与 hide 参数会被移除。不传 token 或脱敏联系方式;未登录、profile 仍在加载或读取失败时都不填写 prefill_uid。Desktop 桥接没有 deviceInfo 读取器时,打开的表单以 navigator.userAgent 作为 device_info。Desktop 端暴露可选的 dshDesktop.deviceInfo 读取器,其字段格式由 [Desktop README](../../../apps/desktop/README.zh.md) 负责;该读取器的结果取代 user-agent,读取失败时仍打开表单,device_info 保留可获取的屏幕分辨率,而 device_info 描述的是上报的环境而非硬件型号。可在 ui-settings-account 插件配置 contactFormUrl,切换到另一个 HTTPS 问卷;问卷支持 Harness 来源选项前,contactSource 默认为空。 +账号菜单的“意见反馈”入口在系统浏览器中打开飞书问卷。每次点击都按当时的上下文取值:profile ready 且带 id 时的账号 UID、以 harness_version 表示的构建版本,以及 device_info。device_info 以 screen_resolution=宽x高 包含屏幕物理分辨率,尺寸乘以 devicePixelRatio 后四舍五入;屏幕尺寸不可用时省略此项。所有上下文字段同时设置 hide_*=1,配置的表单 URL 中这些字段的 stale prefill 参数先被清除,uid、device_info 与 harness_version 的隐藏参数不依赖配置 URL 的取值。URL 不携带 os_version、device_brand、app_locale 或独立的 screen_resolution 参数;配置 URL 中这些字段的 prefill 与 hide 参数会被移除。不传 token 或脱敏联系方式;未登录、profile 仍在加载或读取失败时都不填写 prefill_uid。普通浏览器中,或 Desktop 桥接没有 deviceInfo 读取器时,打开的表单以 navigator.userAgent 作为 device_info。Desktop 端暴露可选的 dshDesktop.deviceInfo 读取器,其字段格式由 [Desktop README](../../../apps/desktop/README.zh.md) 负责;该读取器的结果取代 user-agent,读取失败时仍打开表单,device_info 保留可获取的屏幕分辨率,而 device_info 描述的是上报的环境而非硬件型号。可在 ui-settings-account 插件配置 contactFormUrl,切换到另一个 HTTPS 问卷;问卷支持 Harness 来源选项前,contactSource 默认为空。 账号资料与余额卡片共用[设置卡片材质与圆角](../../../docs/web-styling.zh.md#corner-radii-and-settings-cards)。用量与充值链接与标准 Button 尺寸一致;授权操作使用公共 Button。 @@ -68,14 +68,14 @@ Desktop preload 标记在账号凭证已存储后启用引导。进度属于本 仅登录后在设置导航首位显示账号页;账号状态加载完成前以及退出登录后隐藏该页。 插件持有一条 Host 快照流,通过框架 hook 供 settings.section 和 settings.launcher 共享。入口菜单可打开设置,并仅在已存储账号凭证时提供退出登录。Platform 请求失败时保留菜单,以供重试。插件不维护独立凭证状态。 -桌面控制器通过 Host 设置将进度写入 `ui-settings-account`。完成时先一并应用 `ui-chat.transcriptView` 与 `ui-chat.performanceUsage`,再通过共享代码工作工具偏好保存 `ui-settings.enabled`,最后保存完成标记;写入被拒绝时保留引导以供重试。成功完成后通过 180ms 淡出显露工作区;选择和普通翻页立即预览,写入在后台按顺序执行。队列最后一次写入失败时恢复已保存进度,并允许重试。完成操作会等待选择队列及偏好保存成功,再关闭页面;减少动态效果偏好会跳过淡出。onboarding 选项 compact、standard、detailed 直接应用到对应的 Chat 工作过程模式。API Key 进入与显式跳过均采用 standard;onboarding 不选择 verbose。完整 Figma 示意图层以透明、调色板压缩的 3× PNG 资源打包;欢迎页图层合并并烘焙侧栏局部模糊;充值页前景窗口不透明度为 70%,仅烘焙其覆盖插图区域的模糊,标题使用已打包的 Montserrat 品牌字体,英文标题和描述使用 Light(300),标题中的 DeepSeek Harness 使用 Medium(500);卡片标题选中前后均使用 Regular(400)。英文底部导航使用 Light(300)。确认进入引导后,窗口最小宽度设为 960px,较窄窗口自动放大;完成后解除宽度限制,但不恢复原尺寸。加载中或已完成引导的启动不改变窗口尺寸。底部导航空白区域透过鼠标事件,避免遮挡主操作。卡片区域不参与原生窗口拖动,复选框的键盘焦点仅在卡片外框展示。账号包负责引导覆盖层和控件尺寸样式。每个步骤和确认弹窗各有独立组件,流程组件协调导航、切换动画和充值。初始账号与进度加载期间,覆盖层隐藏工作区。答题标题和卡片独立于操作按钮,位置对齐 Figma 的 1440 × 920 和 960 × 600 断点。macOS 的内容层清除 body 浮层继承的 no-drag,位于内容之前的拖拽层保留 8px 原生缩放边缘;交互控件和后续弹窗排除自身区域;原生平台页面打开时禁用底层引导拖拽层。上方工作区弹窗插画在两种语言和主题下均使用不透明背景,下层侧边栏不绘制选中行高亮。欢迎页保持示意图的原始尺寸,在窄窗口内调整插图位置并裁切,在宽窗口内展示完整插图。[历史引导决策](../../../.agents/notes/archived/feature/2026-09-16-desktop-onboarding.md)记录持久化与展示方面的取舍。 +桌面控制器通过 Host 设置将进度写入 `ui-settings-account`。完成时先一并应用 `ui-chat.transcriptView` 与 `ui-chat.performanceUsage`,再通过共享代码工作工具偏好保存 `ui-settings.enabled`,最后保存完成标记;写入被拒绝时保留引导以供重试。成功完成后通过 180ms 淡出显露工作区;选择和普通翻页立即预览,写入在后台按顺序执行。队列最后一次写入失败时恢复已保存进度,并允许重试。完成操作会等待选择队列及偏好保存成功,再关闭页面;减少动态效果偏好会跳过淡出。onboarding 选项 compact、standard、detailed 直接应用到对应的 Chat 工作过程模式。API Key 进入与显式跳过均采用 standard;onboarding 不选择 verbose。完整 Figma 示意图层以透明、无损编码的 3× WebP 资源打包;欢迎页图层合并并烘焙侧栏局部模糊;充值页前景窗口不透明度为 70%,仅烘焙其覆盖插图区域的模糊,标题使用已打包的 Montserrat 品牌字体,英文标题和描述使用 Light(300),标题中的 DeepSeek Harness 使用 Medium(500);卡片标题选中前后均使用 Regular(400)。英文底部导航使用 Light(300)。确认进入引导后,窗口最小宽度设为 960px,较窄窗口自动放大;完成后解除宽度限制,但不恢复原尺寸。加载中或已完成引导的启动不改变窗口尺寸。底部导航空白区域透过鼠标事件,避免遮挡主操作。卡片区域不参与原生窗口拖动,复选框的键盘焦点仅在卡片外框展示。账号包负责引导覆盖层和控件尺寸样式。每个步骤和确认弹窗各有独立组件,流程组件协调导航、切换动画和充值。初始账号与进度加载期间,覆盖层隐藏工作区。答题标题和卡片独立于操作按钮,位置对齐 Figma 的 1440 × 920 和 960 × 600 断点。macOS 的内容层清除 body 浮层继承的 no-drag,位于内容之前的拖拽层保留 8px 原生缩放边缘;交互控件和后续弹窗排除自身区域;原生平台页面打开时禁用底层引导拖拽层。上方工作区弹窗插画在两种语言和主题下均使用不透明背景,下层侧边栏不绘制选中行高亮。欢迎页保持示意图的原始尺寸,在窄窗口内调整插图位置并裁切,在宽窗口内展示完整插图。[历史引导决策](../../../.agents/notes/archived/feature/2026-09-16-desktop-onboarding.md)记录持久化与展示方面的取舍。 ## 深入探索 [凭证子系统](../../../docs/subsystems/credentials.zh.md)定义存储接口;[架构](../../../docs/architecture.zh.md)说明应用组合。 -账号登录在模型引导的凭证编辑器之前显示可关闭的弹窗。弹窗底部采用紧凑的右对齐横排操作,主操作位于末尾。侧边栏优先显示昵称,缺少昵称时显示服务端返回的脱敏手机号或邮箱;资料加载期间保持留空。 弹窗文字和侧边栏账号状态文字不可选中,复制登录链接按钮始终可用,并在每次复制成功两秒后恢复原文案。剪贴板失败时,链接原位显示“复制失败”两秒,不中断登录。等待状态提供可复制的授权链接和加载图标;超时和失败均须用户手动重试。弹窗的“复制登录链接”和设置页的“打开”链接会从当前主题快照读取 Desktop 生效配色,追加 `theme=light` 或 `theme=dark`,使两条路径都以当前应用主题打开 Platform 页面,且不改变 Platform 已保存的主题偏好。登录失败在该弹窗内呈现;退出登录失败时菜单保持展开以便重试,入口本身不展示失败提示。关闭等待弹窗会取消对应 Host 登录流程。侧边栏通过设置协调器重新打开同一个 API Key 编辑器。 +账号登录在模型引导的凭证编辑器之前显示可关闭的弹窗。弹窗底部采用紧凑的右对齐横排操作,主操作位于末尾。侧边栏优先显示昵称,缺少昵称时显示服务端返回的脱敏手机号或邮箱;资料加载期间保持留空。 弹窗文字和侧边栏账号状态文字不可选中,复制登录链接按钮始终可用,并在每次复制成功两秒后恢复原文案。剪贴板失败时,链接原位显示“复制失败”两秒,不中断登录。等待状态提供可复制的授权链接和加载图标;超时和失败均须用户手动重试。弹窗的“复制登录链接”和设置页的“打开”链接会从当前主题快照读取应用生效配色,追加 `theme=light` 或 `theme=dark`,使两条路径都以当前应用主题打开 Platform 页面,且不改变 Platform 已保存的主题偏好。登录失败在该弹窗内呈现;退出登录失败时菜单保持展开以便重试,入口本身不展示失败提示。关闭等待弹窗会取消对应 Host 登录流程。侧边栏通过设置协调器重新打开同一个 API Key 编辑器。 账户状态流的终止错误会显示在登录对话框或账户设置中。插件卸载后不再报告延迟到达的错误。 @@ -99,10 +99,12 @@ Desktop preload 标记在账号凭证已存储后启用引导。进度属于本 - 资料和充值钱包余额通过 Host getProfile / getBalance 复用已有 Platform Web 接口。页面在打开、登录及重连后刷新,原样显示服务端脱敏后的联系方式,并分别处理查询失败,不将失败显示为零余额。用量和充值使用 Host 按 platformOrigin 派生的链接,并沿用浏览器自身登录态,不携带 DSH token。 - 已完成引导的安装不会重新应用默认值或覆盖用户后续调整的偏好。完成状态不跨设备同步,也不创建逐账号历史。 -- 引导跟随界面语言和主题,使用中文、英文分别搭配浅色、深色外观的四套 Figma PNG 插图。导出画布包含完整插图范围,Finder 插图在两种主题下使用一致的纵向渐变。 +- 引导跟随界面语言和主题,使用中文、英文分别搭配浅色、深色外观的四套 Figma 插图。导出画布包含完整插图范围,Finder 插图在两种主题下使用一致的纵向渐变。 - 通知文案按客户端读取时的界面语言由服务端本地化。切换语言本身不会重新读取未通知赠金,因此已在屏幕上的通知会沿用服务端先前语言下发的文案,直到用户手动刷新或登录生命周期重新开始。 +- Web 登录要求页面 origin 为回环 HTTP(`localhost`、`127.0.0.1` 或 `[::1]`),因为 Host 只接受这些回调 origin。经 `--trusted-host` 或 HTTPS 反向代理访问的 Web UI 仍显示登录入口,但发起登录会进入通用的失败重试状态;这类部署应改为添加 API Key。 + - Platform 视图的弹窗会把文档内其它子节点设为 inert,其中包括 Desktop 拥有的顶栏菜单 host,因此 Application 和 Edit 菜单保持可见,但在视图关闭前无法操作。放行该 host 需要 Desktop 侧提供 inert 契约。 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 95b3ad65b7..f25040ab85 100644 --- a/packages/client/ui-settings-account/package.json +++ b/packages/client/ui-settings-account/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-account", "description": "Manage DeepSeek login and open Platform billing pages", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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/src/client/OnboardingCreditStep.tsx b/packages/client/ui-settings-account/src/client/OnboardingCreditStep.tsx index 7187696217..e0b73f69b8 100644 --- a/packages/client/ui-settings-account/src/client/OnboardingCreditStep.tsx +++ b/packages/client/ui-settings-account/src/client/OnboardingCreditStep.tsx @@ -3,10 +3,10 @@ import type { RefObject } from 'react' import { Button } from '@deepseek-ai/dsh-client-ui-primitives' import type { DesktopOnboardingProps } from './onboarding-contract.ts' import { OnboardingIllustration } from './OnboardingIllustration.tsx' -import art from './assets/onboarding-recharge.png' -import artDark from './assets/onboarding-recharge-dark.png' -import artZh from './assets/onboarding-recharge-zh.png' -import artZhDark from './assets/onboarding-recharge-zh-dark.png' +import art from './assets/onboarding-recharge.webp' +import artDark from './assets/onboarding-recharge-dark.webp' +import artZh from './assets/onboarding-recharge-zh.webp' +import artZhDark from './assets/onboarding-recharge-zh-dark.webp' import css from './DesktopOnboarding.module.css' /** @param props - credit facts, localized content and recharge/navigation actions. @returns the credit step. */ diff --git a/packages/client/ui-settings-account/src/client/OnboardingWelcomeStep.tsx b/packages/client/ui-settings-account/src/client/OnboardingWelcomeStep.tsx index f7c0aabc2f..66629a9f7f 100644 --- a/packages/client/ui-settings-account/src/client/OnboardingWelcomeStep.tsx +++ b/packages/client/ui-settings-account/src/client/OnboardingWelcomeStep.tsx @@ -3,10 +3,10 @@ import type { RefObject } from 'react' import { Button } from '@deepseek-ai/dsh-client-ui-primitives' import type { DesktopOnboardingProps } from './onboarding-contract.ts' import { OnboardingIllustration } from './OnboardingIllustration.tsx' -import art from './assets/onboarding-welcome.png' -import artDark from './assets/onboarding-welcome-dark.png' -import artZh from './assets/onboarding-welcome-zh.png' -import artZhDark from './assets/onboarding-welcome-zh-dark.png' +import art from './assets/onboarding-welcome.webp' +import artDark from './assets/onboarding-welcome-dark.webp' +import artZh from './assets/onboarding-welcome-zh.webp' +import artZhDark from './assets/onboarding-welcome-zh-dark.webp' import css from './DesktopOnboarding.module.css' /** @param props - localized content, focus target and navigation. @returns the welcome step. */ diff --git a/packages/client/ui-settings-account/src/client/SignInDialog.tsx b/packages/client/ui-settings-account/src/client/SignInDialog.tsx index 6fae239b3c..77441cae58 100644 --- a/packages/client/ui-settings-account/src/client/SignInDialog.tsx +++ b/packages/client/ui-settings-account/src/client/SignInDialog.tsx @@ -10,7 +10,7 @@ import css from './SignInDialog.module.css' /** @param props - safe account state, localized copy, and user actions. @returns login dialog. */ export function SignInDialog({ account, colorScheme, start, cancel, close, useApiKey, t }: { account: AccountSnapshot - /** Resolved scheme of the active Desktop theme; the copied link carries it. */ + /** Resolved scheme of the active application theme; the copied link carries it. */ colorScheme: 'light' | 'dark' start: () => Promise cancel: (id: SignInAttemptId) => Promise diff --git a/packages/client/ui-settings-account/src/client/assets.d.ts b/packages/client/ui-settings-account/src/client/assets.d.ts index da6a4dd8ea..db768fc288 100644 --- a/packages/client/ui-settings-account/src/client/assets.d.ts +++ b/packages/client/ui-settings-account/src/client/assets.d.ts @@ -1,7 +1,7 @@ /** Illustration imports are embedded in the account client bundle. */ -declare module '*.png' { - const svg: string - export default svg +declare module '*.webp' { + const url: string + export default url } declare module '*.svg' { const url: string diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-dark.png b/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-dark.png deleted file mode 100644 index 8f484ee1a1..0000000000 Binary files a/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-dark.png and /dev/null differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-dark.webp b/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-dark.webp new file mode 100644 index 0000000000..f2c5290058 Binary files /dev/null and b/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-dark.webp differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-zh-dark.png b/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-zh-dark.png deleted file mode 100644 index 51c579edc7..0000000000 Binary files a/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-zh-dark.png and /dev/null differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-zh-dark.webp b/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-zh-dark.webp new file mode 100644 index 0000000000..99fb9996b2 Binary files /dev/null and b/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-zh-dark.webp differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-zh.png b/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-zh.png deleted file mode 100644 index 0fa9ba310c..0000000000 Binary files a/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-zh.png and /dev/null differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-zh.webp b/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-zh.webp new file mode 100644 index 0000000000..5b09bd55f7 Binary files /dev/null and b/packages/client/ui-settings-account/src/client/assets/onboarding-recharge-zh.webp differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-recharge.png b/packages/client/ui-settings-account/src/client/assets/onboarding-recharge.png deleted file mode 100644 index 2a5fc4f41c..0000000000 Binary files a/packages/client/ui-settings-account/src/client/assets/onboarding-recharge.png and /dev/null differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-recharge.webp b/packages/client/ui-settings-account/src/client/assets/onboarding-recharge.webp new file mode 100644 index 0000000000..772f4c9ded Binary files /dev/null and b/packages/client/ui-settings-account/src/client/assets/onboarding-recharge.webp differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-dark.png b/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-dark.png deleted file mode 100644 index 17c53b32b5..0000000000 Binary files a/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-dark.png and /dev/null differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-dark.webp b/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-dark.webp new file mode 100644 index 0000000000..88d103a5b1 Binary files /dev/null and b/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-dark.webp differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-zh-dark.png b/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-zh-dark.png deleted file mode 100644 index 1ea7058e90..0000000000 Binary files a/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-zh-dark.png and /dev/null differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-zh-dark.webp b/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-zh-dark.webp new file mode 100644 index 0000000000..29a579e5bc Binary files /dev/null and b/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-zh-dark.webp differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-zh.png b/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-zh.png deleted file mode 100644 index 0672b15aac..0000000000 Binary files a/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-zh.png and /dev/null differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-zh.webp b/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-zh.webp new file mode 100644 index 0000000000..971351cc62 Binary files /dev/null and b/packages/client/ui-settings-account/src/client/assets/onboarding-welcome-zh.webp differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-welcome.png b/packages/client/ui-settings-account/src/client/assets/onboarding-welcome.png deleted file mode 100644 index 0f157e7cbd..0000000000 Binary files a/packages/client/ui-settings-account/src/client/assets/onboarding-welcome.png and /dev/null differ diff --git a/packages/client/ui-settings-account/src/client/assets/onboarding-welcome.webp b/packages/client/ui-settings-account/src/client/assets/onboarding-welcome.webp new file mode 100644 index 0000000000..a77f7de6e0 Binary files /dev/null and b/packages/client/ui-settings-account/src/client/assets/onboarding-welcome.webp differ diff --git a/packages/client/ui-settings-account/src/client/authorize-url.ts b/packages/client/ui-settings-account/src/client/authorize-url.ts index eba9e19094..3e701b9de9 100644 --- a/packages/client/ui-settings-account/src/client/authorize-url.ts +++ b/packages/client/ui-settings-account/src/client/authorize-url.ts @@ -1,10 +1,10 @@ -/** Platform authorization links that carry the Desktop palette into the login page. */ +/** Platform authorization links that carry the active application palette into the login page. */ /** - * Add the resolved Desktop palette to a Platform authorization link without + * Add the resolved application palette to a Platform authorization link without * dropping any parameter the Host already put on it. * @param authorizeUrl - authorization URL of the current account attempt. - * @param colorScheme - resolved scheme of the active Desktop theme. + * @param colorScheme - resolved scheme of the active application theme. * @returns the authorization URL carrying `theme=light` or `theme=dark`. */ export function authorizeUrlWithTheme(authorizeUrl: string, colorScheme: 'light' | 'dark'): string { diff --git a/packages/client/ui-settings-account/src/client/browser-login.ts b/packages/client/ui-settings-account/src/client/browser-login.ts new file mode 100644 index 0000000000..3d03d1a9a8 --- /dev/null +++ b/packages/client/ui-settings-account/src/client/browser-login.ts @@ -0,0 +1,76 @@ +/** Browser tab ownership for one UI-initiated authorization attempt. */ +import type { AccountView, SignInAttemptId } from '@deepseek-ai/dsh-deepseek-account/types' + +/** Keeps a preopened browser tab separate from Host authorization state. */ +export class BrowserLogin { + private popup: Window | null = null + private navigated = false + private attempt: SignInAttemptId | undefined + + /** @param destination - maps the Host authorization URL to the page the tab opens, read when the tab navigates. */ + constructor(private readonly destination: (authorizeUrl: string) => string) {} + + /** + * Preopen a tab and bind it to the attempt returned by the Host. + * @param request - authenticated Host start request. + * @param latest - most recent streamed state, including frames received before the response. + * @returns after this UI is following the new attempt. + */ + async start(request: () => Promise, latest: () => AccountView | undefined): Promise { + this.begin() + try { + this.follow(await request()) + this.update(latest()) + } catch (error) { + this.dispose() + throw error + } + } + + /** Preopen a tab during the user's click; blocked popups need the copy-link route. */ + begin(): void { + this.dispose() + this.popup = window.open('about:blank', '_blank') + if (this.popup) this.popup.opener = null + } + + /** + * Bind the preopened tab to its Host attempt. + * @param view - initial RPC response identifying this UI's attempt. + */ + follow(view: AccountView): void { + this.attempt = view.attempt?.id + this.update(view) + } + + /** + * Navigate or close the pending tab when its attempt changes. + * @param view - latest Host state. + */ + update(view: AccountView | undefined): void { + const attempt = view?.attempt + if (attempt?.id !== this.attempt) return + if (attempt && ['failed', 'expired', 'cancelled'].includes(attempt.phase)) { + this.dispose() + return + } + if (attempt?.phase === 'succeeded') { + // A tab that never reached the authorization page stays blank; the Host finished without it. + if (!this.navigated) this.popup?.close() + this.popup = null + this.attempt = undefined + return + } + if (!attempt?.authorizeUrl || this.navigated) return + this.navigated = true + if (this.popup && !this.popup.closed) this.popup.location.replace(this.destination(attempt.authorizeUrl)) + } + + /** Close the owned authorization tab and stop following its attempt. */ + dispose(): void { + this.popup?.close() + this.popup = null + this.attempt = undefined + this.navigated = false + } +} diff --git a/packages/client/ui-settings-account/src/client/index.ts b/packages/client/ui-settings-account/src/client/index.ts index 974626fa04..b28b3e7747 100644 --- a/packages/client/ui-settings-account/src/client/index.ts +++ b/packages/client/ui-settings-account/src/client/index.ts @@ -1,4 +1,4 @@ -/** Desktop account settings registration and reconnecting Remote subscription. */ +/** Account settings registration and reconnecting Remote subscription. */ import type {} from '@deepseek-ai/dsh-client-product-analytics/client' import type { TranscriptViewMode } from '@deepseek-ai/dsh-client-ui-chat/client' import type { Context } from '@deepseek-ai/cordis' @@ -14,6 +14,8 @@ import type { OnboardingChange } from './onboarding-contract.ts' import type { PlatformBridge } from './PlatformOverlay.tsx' import { ContactConfig, CONTACT_CONFIG_GLOBAL } from '../contact-config.ts' import { contactUrl } from './contact-url.ts' +import { authorizeUrlWithTheme } from './authorize-url.ts' +import { BrowserLogin } from './browser-login.ts' import { AccountOnboarding } from './AccountOnboarding.tsx' import { AccountPlatformHost, type AccountPlatformHostInjected } from './AccountPlatformHost.tsx' import { AccountMenu } from './AccountMenu.tsx' @@ -39,14 +41,17 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { /** Services required by account settings. */ export const inject = ['slots', 'locale', 'remote', 'remote.account', 'remote.session', 'theme', 'configForms'] -/** Register account UI only in the Desktop renderer. @param ctx - client plugin context. */ +/** Register account UI in Desktop and plain Web clients. @param ctx - client plugin context. */ export function apply(ctx: Context): void { - if (!('dshDesktop' in globalThis)) return + const desktop = 'dshDesktop' in globalThis ctx.effect(() => ctx.locale.register('settings.account', { en, zh }), 'account: dictionaries') const t = ctx.locale.bind('settings.account') const page = globalThis as Partial> const config = ContactConfig(page[CONTACT_CONFIG_GLOBAL] ?? {}) let snapshot: AccountSnapshot = { view: undefined, details: undefined, failed: false, loginVisible: false } + // Desktop main opens the authorization page natively; a plain browser opens it in a tab it owns. + const browser = new BrowserLogin(url => authorizeUrlWithTheme(url, ctx.theme.getTheme().active.colorScheme)) + ctx.effect(() => () => { browser.dispose() }, 'account: pending browser window') const listeners = new Set<() => void>() const publish = (value: AccountSnapshot) => { snapshot = value; for (const listener of listeners) listener() } /** @returns the client identity for one account call, read at call time so it carries the language and zone in effect then. */ @@ -119,6 +124,7 @@ export function apply(ctx: Context): void { const { notice, ...previous } = snapshot publish({ ...previous, view: frame.value, details: undefined, failed: false, ...(frame.value.status === 'credential-stored' && notice ? { notice } : {}) }) + browser.update(frame.value) frame.accept() if (frame.value.status === 'credential-stored') notices.begin() else notices.end() @@ -176,7 +182,7 @@ export function apply(ctx: Context): void { dshDesktop?: { deviceInfo?: () => Promise } }).dshDesktop?.deviceInfo if (readDeviceInfo === undefined) { - // A Desktop bridge without the optional reader reports the renderer user agent. + // A plain browser, or a Desktop bridge without the optional reader, reports the renderer user agent. openForm(navigator.userAgent) return } @@ -208,11 +214,16 @@ export function apply(ctx: Context): void { const transport = (globalThis as typeof globalThis & { __DSH_TRANSPORT__?: { streamBaseUrl?: string } }).__DSH_TRANSPORT__ - try { + const request = async () => { const result = await ctx.remote.account.startSignIn(client(), - transport?.streamBaseUrl !== undefined ? new URL(transport.streamBaseUrl).origin : window.location.origin, - 'desktop') + desktop && transport?.streamBaseUrl !== undefined ? new URL(transport.streamBaseUrl).origin : window.location.origin, + desktop ? 'desktop' : 'web') if (!result.ok) throw new Error('account start failed') + return result.value + } + try { + if (desktop) await request() + else await browser.start(request, () => snapshot.view) } catch (error) { publish({ ...snapshot, loginFailed: true }) throw error @@ -230,7 +241,7 @@ export function apply(ctx: Context): void { throw result.error }, } - if ('dshDesktop' in globalThis) { + if (desktop) { const controller = new DesktopOnboardingController( ctx.configForms.get(DESKTOP_ONBOARDING_NAMESPACE), ctx.configForms.get<{ transcriptView?: TranscriptViewMode | null; performanceUsage: 'compact' | 'detailed' }>('ui-chat'), diff --git a/packages/client/ui-settings-account/tests/account.client.spec.tsx b/packages/client/ui-settings-account/tests/account.client.spec.tsx index a1c4b9960f..9ed6bac4fc 100644 --- a/packages/client/ui-settings-account/tests/account.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/account.client.spec.tsx @@ -505,7 +505,7 @@ it.each(['initializing', 'waiting-browser', 'exchanging'] as const)('shows %s an expect(operations.cancel).toHaveBeenCalledExactlyOnceWith('attempt') }) -it('opens the authorization link with the active Desktop palette and follows later switches', () => { +it('opens the authorization link with the active application palette and follows later switches', () => { const authorizeUrl = 'https://platform.deepseek.com/dsh/authorize?state=example' const operations = operationsOf({ status: 'signed-out', attempt: { id: 'attempt' as SignInAttemptId, phase: 'waiting-browser', authorizeUrl } }) const element = (theme: ThemeSnapshot) => { }) afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); vi.restoreAllMocks() }) -it('keeps account UI and account RPC inactive in a plain browser, including after reload', async ({ start, mock }) => { +it('registers account sign-in in a plain browser without the Desktop-only surfaces, including after reload', async ({ start }) => { const c = await start() for (const reload of [false, true]) { if (reload) await c.reload(SELF) - await c.flush() - expect(c.ctx.slots.entries('settings.launcher')).toHaveLength(0) - expect(c.ctx.slots.entries('settings.models.sign-in')).toHaveLength(0) - expect(c.ctx.slots.entries('settings.section').some(entry => entry.options.id === 'account')).toBe(false) - expect(quotaNoticeEntry(c)).toBeUndefined() + await c.mock.streams.opened('account/watch', reload ? 2 : 1) + expect(c.ctx.slots.entries('settings.launcher')).toHaveLength(1) + expect(c.ctx.slots.entries('settings.models.sign-in')).toHaveLength(1) + expect(quotaNoticeEntry(c)).toBeDefined() expect(platformHostEntry(c)).toBeUndefined() - expect(mock.log.calls().filter(call => call.endpoint.startsWith('account/'))).toEqual([]) - expect(mock.log.streams().filter(stream => stream.endpoint.startsWith('account/'))).toEqual([]) + expect(c.ctx.slots.entries('shell.overlay').some(entry => entry.options.id === 'desktop-onboarding')).toBe(false) } }, 60_000) @@ -241,15 +239,17 @@ it('coalesces refreshes, publishes independent failures, and rejects stale respo expect(actions.hooks.account.getSnapshot().details?.profile).toEqual({ status: 'failed' }) }, 60_000) -it('uses the Desktop login carrier and exposes operation errors', async ({ start, mock }) => { - vi.spyOn(window, 'open').mockReturnValue(null) - vi.stubGlobal('dshDesktop', {}) +for (const desktop of [false, true]) it(`uses the browser or Desktop login carrier (Desktop: ${desktop}) and exposes operation errors`, async ({ start, mock }) => { + const open = vi.spyOn(window, 'open').mockReturnValue(null) + if (desktop) vi.stubGlobal('dshDesktop', {}) const c = await start() const actions = operations(c) mock.remote.account.startSignIn.mockResolvedValue(ok(view)) await actions.start() expect(mock.remote.account.startSignIn).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en', version: '0.0.0-test' }), - window.location.origin, 'desktop') + window.location.origin, desktop ? 'desktop' : 'web') + // Only a plain browser preopens the authorization tab during the click. + expect(open).toHaveBeenCalledTimes(desktop ? 0 : 1) const failure = { ok: false as const, error: new RemoteError('gateway/internal', 'offline', {}) } mock.remote.account.startSignIn.mockResolvedValueOnce(failure) await expect(actions.start()).rejects.toThrow('account start failed') @@ -264,6 +264,21 @@ it('uses the Desktop login carrier and exposes operation errors', async ({ start await expect(actions.signOut()).rejects.toBe(failure.error) }, 60_000) +it('navigates the preopened browser tab to the themed authorization page', async ({ start, mock }) => { + const replace = vi.fn() + const popup: Pick & { location: Pick } = { closed: false, close: vi.fn(), opener: window, location: { replace } } + // jsdom opens no real tab; the UI only touches these members of the preopened window. + vi.spyOn(window, 'open').mockReturnValue(popup as Window) + const c = await start() + const actions = operations(c) + const attempt = { id: 'attempt' as SignInAttemptId, phase: 'waiting-browser' as const, authorizeUrl: 'https://platform.deepseek.com/dsh/authorize' } + mock.remote.account.startSignIn.mockResolvedValue(ok({ ...view, attempt: { id: attempt.id, phase: 'initializing' } })) + await actions.start() + c.mock.streams.push('account/watch', { ...view, attempt }) + const theme = (c.ctx.get('theme') as ThemeRuntime).getTheme().active.colorScheme + await vi.waitFor(() => { expect(replace).toHaveBeenCalledExactlyOnceWith(`${attempt.authorizeUrl}?theme=${theme}`) }) +}, 60_000) + it('uses the Desktop stream origin and exposes the native platform bridge', async ({ start, mock }) => { vi.stubGlobal('dshDesktop', {}) const c = await start() diff --git a/packages/client/ui-settings-account/tests/browser-login.client.spec.ts b/packages/client/ui-settings-account/tests/browser-login.client.spec.ts new file mode 100644 index 0000000000..7d27c3d33c --- /dev/null +++ b/packages/client/ui-settings-account/tests/browser-login.client.spec.ts @@ -0,0 +1,99 @@ +// @vitest-environment jsdom +/** Browser handoff tracks the initiating attempt and cleans up unused tabs. */ +import { afterEach, expect, it, vi } from 'vitest' +import type { AccountView, SignInAttemptId } from '@deepseek-ai/dsh-deepseek-account/types' +import { BrowserLogin } from '../src/client/browser-login.ts' + +afterEach(() => { vi.restoreAllMocks() }) +function view(phase: NonNullable['phase'], authorizeUrl?: string): AccountView { + return { status: 'signed-out', links: { usageUrl: '', topUpUrl: '' }, + attempt: { id: 'attempt' as SignInAttemptId, phase, ...(authorizeUrl ? { authorizeUrl } : {}) } } +} +function setup() { + const close = vi.fn() + const replace = vi.fn() + const popup: { closed: boolean; opener: unknown; close: typeof close; location: { replace: typeof replace } } = { + closed: false, opener: window, close, location: { replace }, + } + vi.spyOn(window, 'open').mockReturnValue(new Proxy(window, { + get(target, property, receiver): unknown { + if (property === 'closed') return popup.closed + if (property === 'opener') return popup.opener + if (property === 'close') return popup.close + if (property === 'location') return popup.location + return Reflect.get(target, property, receiver) + }, + set(target, property, value: unknown, receiver) { + if (property === 'opener') { popup.opener = value; return true } + return Reflect.set(target, property, value, receiver) + }, + })) + const browser = new BrowserLogin(url => url) + browser.begin() + return { browser, popup, close, replace } +} +it('navigates once when waiting-browser arrives after the initial RPC response', () => { + const { browser, popup, replace, close } = setup() + expect(popup.opener).toBeNull() + browser.follow(view('initializing')) + expect(replace).not.toHaveBeenCalled() + browser.update(view('waiting-browser', 'https://platform.deepseek.com/dsh/authorize')) + browser.update(view('waiting-browser', 'https://platform.deepseek.com/dsh/authorize')) + expect(replace).toHaveBeenCalledExactlyOnceWith('https://platform.deepseek.com/dsh/authorize') + browser.dispose() + expect(close).toHaveBeenCalledOnce() +}) +it('closes the blank tab on request failure without later navigating it', () => { + const { browser, close, replace } = setup() + browser.dispose() + browser.update(view('waiting-browser', 'https://platform.deepseek.com/dsh/authorize')) + expect(close).toHaveBeenCalledOnce() + expect(replace).not.toHaveBeenCalled() +}) +it('retains the manual link route when popup opening is blocked', () => { + vi.spyOn(window, 'open').mockReturnValue(null) + const browser = new BrowserLogin(url => url) + browser.begin() + expect(() => { browser.follow(view('waiting-browser', 'https://platform.deepseek.com/dsh/authorize')) }).not.toThrow() +}) + +it('closes the pending tab when the authenticated start request rejects', async () => { + const { browser, close, replace } = setup() + close.mockClear() + await expect(browser.start(() => Promise.reject(new Error('disconnected')), () => undefined)).rejects.toThrow('disconnected') + expect(close).toHaveBeenCalledTimes(2) + expect(replace).not.toHaveBeenCalled() +}) +it('uses a waiting frame received before the initial response', async () => { + const { browser, replace } = setup() + await browser.start(async () => view('initializing'), () => view('waiting-browser', 'https://platform.deepseek.com/dsh/authorize')) + expect(replace).toHaveBeenCalledExactlyOnceWith('https://platform.deepseek.com/dsh/authorize') +}) + +it.each(['failed', 'expired', 'cancelled'] as const)('closes an already navigated tab on %s', (phase) => { + const { browser, close } = setup() + browser.follow(view('waiting-browser', 'https://platform.deepseek.com/dsh/authorize')) + browser.update(view(phase)) + expect(close).toHaveBeenCalledOnce() +}) +it('leaves success completion to the Platform page', () => { + const { browser, close } = setup() + browser.follow(view('waiting-browser', 'https://platform.deepseek.com/dsh/authorize')) + browser.update(view('succeeded')) + browser.dispose() + expect(close).not.toHaveBeenCalled() +}) +it('closes a blank tab when the Host finishes before it navigates', () => { + const { browser, close } = setup() + browser.follow(view('exchanging')) + browser.update(view('succeeded')) + browser.dispose() + expect(close).toHaveBeenCalledOnce() +}) +it('opens the destination mapped from the authorization URL', () => { + const { replace } = setup() + const browser = new BrowserLogin(url => `${url}?theme=dark`) + browser.begin() + browser.follow(view('waiting-browser', 'https://platform.deepseek.com/dsh/authorize')) + expect(replace).toHaveBeenCalledExactlyOnceWith('https://platform.deepseek.com/dsh/authorize?theme=dark') +}) diff --git a/packages/client/ui-settings-account/tests/onboarding-state.client.spec.ts b/packages/client/ui-settings-account/tests/onboarding-state.client.spec.ts index 55e6b8ef91..480ab21ec7 100644 --- a/packages/client/ui-settings-account/tests/onboarding-state.client.spec.ts +++ b/packages/client/ui-settings-account/tests/onboarding-state.client.spec.ts @@ -64,13 +64,13 @@ async function harness(options: { const progress = new ConfigFormController(ctx, { namespace: DESKTOP_ONBOARDING_NAMESPACE, decode: value => OnboardingSettingsSchema(value as OnboardingSettings), - }, mirror, 'host', schema) + }, mirror, schema) const chat = new ConfigFormController<{ transcriptView: TranscriptViewMode; performanceUsage: 'compact' | 'detailed' }>(ctx, { namespace: 'ui-chat', decode: value => value as { transcriptView: TranscriptViewMode; performanceUsage: 'compact' | 'detailed' }, - }, mirror, 'host', schema) + }, mirror, schema) const developerScope = new ConfigFormController<{ enabled: boolean }>(ctx, { namespace: 'ui-settings', decode: value => value as { enabled: boolean }, - }, mirror, 'host', schema) + }, mirror, schema) const developerTools = new DeveloperToolsPreference(developerScope) const setDeveloperTools = (enabled: boolean) => developerTools.setEnabled(enabled) cleanup.push(() => developerScope.dispose()) diff --git a/packages/client/ui-settings-account/tests/onboarding.client.spec.tsx b/packages/client/ui-settings-account/tests/onboarding.client.spec.tsx index 9d5915fcb5..007aa59644 100644 --- a/packages/client/ui-settings-account/tests/onboarding.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/onboarding.client.spec.tsx @@ -6,7 +6,7 @@ import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import type { ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client' import { AccountOnboarding } from '../src/client/AccountOnboarding.tsx' import type { AccountSnapshot } from '../src/client/AccountSection.tsx' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { en } from '../src/client/locales.ts' afterEach(cleanup) @@ -22,6 +22,7 @@ it('claims onboarding while loading, offers API key fallback, and completes afte const globals: GlobalStandardProps = { usePanelInfo: unused, useSessions: unused, useSessionStatus: unused, useSessionRetainInfo: unused, useResource: unused, useWorkspaces: unused, + ...allowAllAccess, } const props = { ...globals, diff --git a/packages/client/ui-settings-account/tsdown.config.ts b/packages/client/ui-settings-account/tsdown.config.ts index 247d3a8ea8..45af1505d1 100644 --- a/packages/client/ui-settings-account/tsdown.config.ts +++ b/packages/client/ui-settings-account/tsdown.config.ts @@ -3,24 +3,24 @@ 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, plugins: [...(config.plugins ?? []), { name: 'account-onboarding-assets', resolveId(source: string) { - if (!/^\.\/assets\/[^/]+\.(?:svg|png)(\?raw)?$/.test(source)) return null + if (!/^\.\/assets\/[^/]+\.(?:svg|webp)(\?raw)?$/.test(source)) return null const url = new URL(`./src/client/assets/${basename(source)}`, import.meta.url) return fileURLToPath(url) + url.search }, async load(id: string) { - if (!/\/ui-settings-account\/src\/client\/assets\/[^/]+\.(?:svg|png)(\?raw)?$/.test(id.replaceAll('\\', '/'))) return null + if (!/\/ui-settings-account\/src\/client\/assets\/[^/]+\.(?:svg|webp)(\?raw)?$/.test(id.replaceAll('\\', '/'))) return null const path = id.replace(/\?raw$/, '') this.addWatchFile(path) const data = await readFile(path) if (id.endsWith('?raw')) return `export default ${JSON.stringify(data.toString('utf8'))}` - return `export default ${JSON.stringify(`data:${path.endsWith('.png') ? 'image/png' : 'image/svg+xml'};base64,${data.toString('base64')}`)}` + return `export default ${JSON.stringify(`data:${path.endsWith('.webp') ? 'image/webp' : 'image/svg+xml'};base64,${data.toString('base64')}`)}` }, }], }))) satisfies typeof bundle 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 138afab147..8e40a9e8c6 100644 --- a/packages/client/ui-settings-agent-loop/package.json +++ b/packages/client/ui-settings-agent-loop/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-agent-loop", "description": "Settings page of the agent loop on the dsh web client's Plugins page: the parallel tool-call cap of the agent-loop namespace", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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/src/client/index.ts b/packages/client/ui-settings-agent-loop/src/client/index.ts index 161a67949e..bfea143e2a 100644 --- a/packages/client/ui-settings-agent-loop/src/client/index.ts +++ b/packages/client/ui-settings-agent-loop/src/client/index.ts @@ -45,6 +45,6 @@ export function apply(ctx: ClientContext): void { const card = new AgentLoopCardController(ctx.configForms.get(AGENT_LOOP_NS)) ctx.effect(() => () => { card.dispose() }, 'ui-settings-agent-loop: form subscription') ctx.effect(() => ctx.configForms.whileServed([AGENT_LOOP_NS], () => ctx.slots.inject('plugins.item', () => ctx.slots.register({ - name: 'plugins.item', id: 'agent-loop', order: 20, label: () => t('title'), locale: NS, inject: () => card.inject(), + name: 'plugins.item', id: 'agent-loop', order: 30, label: () => t('title'), locale: NS, inject: () => card.inject(), }, AgentLoopCard))), 'ui-settings-agent-loop: page') } diff --git a/packages/client/ui-settings-agent-loop/tests/apply.client.spec.ts b/packages/client/ui-settings-agent-loop/tests/apply.client.spec.ts index 1dc87799dc..63c353cd14 100644 --- a/packages/client/ui-settings-agent-loop/tests/apply.client.spec.ts +++ b/packages/client/ui-settings-agent-loop/tests/apply.client.spec.ts @@ -56,7 +56,7 @@ describe('ui-settings-agent-loop apply', () => { await vi.waitFor(() => { expect(slots.entries('plugins.item')).toHaveLength(1) }) const entry = slots.entries('plugins.item')[0]! - expect(entry.options).toMatchObject({ id: 'agent-loop', order: 20 }) + expect(entry.options).toMatchObject({ id: 'agent-loop', order: 30 }) expect(resolveSlotLabel(entry.options.label)).toBe('Agent 循环') expect(entry.locale).toBe(NS) const face = (entry.inject as () => Pick)() 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/README.i18n.yaml b/packages/client/ui-settings-general/README.i18n.yaml index 85937c4fe6..3a8b6aa02c 100644 --- a/packages/client/ui-settings-general/README.i18n.yaml +++ b/packages/client/ui-settings-general/README.i18n.yaml @@ -21,8 +21,8 @@ en: 8b8a7c6287bb303b zh: 19535112531aedd5 /deepseek-ai-dsh-client-ui-settings-general/use-this-package/opening-the-configuration-file: - en: ca2b4f5ccfbe2705 - zh: bd1dc1d9879d0f0e + en: 597df68b5913e8d7 + zh: bc9114f3e877679a /deepseek-ai-dsh-client-ui-settings-general/use-this-package/onboarding-steps: en: 27f0f6ec55f00228 zh: 69b47ff1efd81c17 @@ -36,8 +36,8 @@ en: e37fb7df883ea356 zh: c972524e56c6d6c2 /deepseek-ai-dsh-client-ui-settings-general/understand-the-implementation/document-availability: - en: 474168eef3339de0 - zh: 254ea21415082dae + en: ff1aec9eb1a87a79 + zh: eb91ab8bef59742d /deepseek-ai-dsh-client-ui-settings-general/understand-the-implementation/host-half: en: 5d722d055516f905 zh: e7a236f0ff84f7ff diff --git a/packages/client/ui-settings-general/README.md b/packages/client/ui-settings-general/README.md index 6e246e990e..c66352ac1c 100644 --- a/packages/client/ui-settings-general/README.md +++ b/packages/client/ui-settings-general/README.md @@ -47,7 +47,7 @@ The General section holds the built-in Coding Tools and Current version rows alo ### Opening the configuration file -On a loopback browser, the shell renders **Open configuration file** only when the Host confirms that a provider-owned local document can be prepared. The action opens that document in the native text editor (bypassing the browser file association on macOS). Remote browsers never register the action and never issue the privileged settings read. +On a loopback browser, the shell renders **Open configuration file** only when the Host confirms that a provider-owned local document can be prepared. The action opens that document in the native text editor (bypassing the browser file association on macOS). Remote browsers never register this native-open action, including on configured public deployments; their preferences persist through the Host settings service. ### Onboarding steps @@ -75,7 +75,7 @@ The shell is an explicit recovery consumer, so it injects Connection directly ra ### Document availability -On a loopback page, the Client loads the provider's `hasDocument` capability through `settings/describe` and renders **Open configuration file** only when the Host confirms that a provider-owned local document can be prepared. The action calls the pathless, browser-authenticated `settings/openSettingsDocument` Remote; the Host resolves the provider path again, materializes an absent document, and hands it to a native text editor (`open -t` on macOS, bypassing a browser file association; the desktop file association on Linux and Windows; Windows association after `wslpath -w` translation on WSL). Open failures keep the action available and render a localized error. Reopening the dialog or reconnecting refreshes availability after a transient read failure or Host topology change. Non-loopback pages retain the Client policy that withholds this native action and its settings read. +On a loopback page, the Client loads the provider's `hasDocument` capability through `settings/describe` and renders **Open configuration file** only when the Host confirms that a provider-owned local document can be prepared. The action calls the pathless, browser-authenticated `settings/openSettingsDocument` Remote; the Host resolves the provider path again, materializes an absent document, and hands it to a native text editor (`open -t` on macOS, bypassing a browser file association; the desktop file association on Linux and Windows; Windows association after `wslpath -w` translation on WSL). Open failures keep the action available and render a localized error. Reopening the dialog or reconnecting refreshes availability after a transient read failure or Host topology change. Non-loopback pages withhold this native action through the Client policy. ### Host half diff --git a/packages/client/ui-settings-general/README.zh.md b/packages/client/ui-settings-general/README.zh.md index 8bf6cc82b6..9d095efb46 100644 --- a/packages/client/ui-settings-general/README.zh.md +++ b/packages/client/ui-settings-general/README.zh.md @@ -47,7 +47,7 @@ Web 与桌面端的通用设置底部显示当前发布版本,使用构建注 ### 打开配置文件 -在回环浏览器上,只有当宿主确认可准备好一份由提供方持有的本地文档时,外壳才渲染**打开配置文件**。该操作会在原生文本编辑器中打开该文档(macOS 上绕过浏览器文件关联)。远程浏览器从不注册该操作,也从不发起这项特权设置读取。 +在回环浏览器上,只有当宿主确认可准备好一份由提供方持有的本地文档时,外壳才渲染**打开配置文件**。该操作会在原生文本编辑器中打开该文档(macOS 上绕过浏览器文件关联)。远程浏览器从不注册这项原生打开操作,配置了公共 URL 的部署也不例外;它们的偏好通过 Host settings 服务持久化。 ### 引导步骤 @@ -75,7 +75,7 @@ Web 与桌面端的通用设置底部显示当前发布版本,使用构建注 ### 文档可用性 -在 loopback 页面上,Client 通过 `settings/describe` 加载提供方的 `hasDocument` 能力,且只有在 Host 确认可准备好一份由提供方持有的本地文档时才渲染**打开配置文件**操作。该操作调用无路径参数且经浏览器认证的 `settings/openSettingsDocument` Remote;Host 会再次解析提供方路径、在文档缺失时将其创建出来,并交给原生文本编辑器(macOS 上使用 `open -t`,绕过浏览器文件关联;Linux 和 Windows 上使用桌面文件关联;WSL 上经 `wslpath -w` 转换后使用 Windows 文件关联)。打开失败时该操作仍可使用,并渲染本地化错误。临时读取失败或 Host 拓扑变化后,重新打开对话框或重新连接会刷新可用性。非 loopback 页面保留 Client 策略,不提供该原生操作及其 settings 读取。 +在 loopback 页面上,Client 通过 `settings/describe` 加载提供方的 `hasDocument` 能力,且只有在 Host 确认可准备好一份由提供方持有的本地文档时才渲染**打开配置文件**操作。该操作调用无路径参数且经浏览器认证的 `settings/openSettingsDocument` Remote;Host 会再次解析提供方路径、在文档缺失时将其创建出来,并交给原生文本编辑器(macOS 上使用 `open -t`,绕过浏览器文件关联;Linux 和 Windows 上使用桌面文件关联;WSL 上经 `wslpath -w` 转换后使用 Windows 文件关联)。打开失败时该操作仍可使用,并渲染本地化错误。临时读取失败或 Host 拓扑变化后,重新打开对话框或重新连接会刷新可用性。非 loopback 页面通过 Client 策略拦下该原生操作。 ### 宿主端 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 bf4b3f8d80..6340c9ba42 100644 --- a/packages/client/ui-settings-general/package.json +++ b/packages/client/ui-settings-general/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-general", "description": "Settings ownerless-copy and product onboarding plugin: the General section, shell trigger/header chrome content, settings dictionaries, and the versioned welcome notice", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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/tests/apply.client.spec.ts b/packages/client/ui-settings-general/tests/apply.client.spec.ts index 6a5d909196..a1df5a7399 100644 --- a/packages/client/ui-settings-general/tests/apply.client.spec.ts +++ b/packages/client/ui-settings-general/tests/apply.client.spec.ts @@ -188,21 +188,59 @@ describe('ui-settings-general apply', () => { await vi.waitFor(() => { expect(c.mock.log.calls('settings/describe')).toHaveLength(3) }) }) - it('withholds the Host document action off-loopback', async ({ mock, start }) => { + it('keeps Host preferences off-loopback and withholds only the native document action', async ({ mock, start }) => { const loopbackUrl = location.href setPageUrl('http://198.51.100.7:3000/') onTestFinished(() => { setPageUrl(loopbackUrl) }) - const { c } = await client(mock, start) + const { c, settings } = await client(mock, start) expect(c.connection.isLoopback).toBe(false) + // The stored Host locale applies off-loopback; only the native document + // action stays loopback-only. + expect(c.ctx.locale.getSnapshot().active).toBe('zh') expect(ownEntries(c, 'settings.action')).toEqual([]) - // Off-loopback settings stay process-local: no describe read, so the browser language stands. - expect(c.mock.log.calls('settings/describe')).toEqual([]) - expect(c.ctx.locale.getSnapshot().active).toBe('en') + const english = localeView('en', 1) + settings.mutate.mockResolvedValueOnce(ok(english)) + c.ctx.locale.setLocale('en') + await vi.waitFor(() => { + expect(settings.mutate.mock.calls).toEqual([ + [LOCALE_SETTINGS_NAMESPACE, [{ op: 'set', path: ['preference'], value: 'en' }], 0], + ]) + }) await c.unload(SELF) await c.flush() for (const [name] of SEATS) expect(ownEntries(c, name)).toEqual([]) }) + it('updates remote locale consumers after Host commits and reconnects', async ({ mock, start }) => { + const originalUrl = location.href + setPageUrl('http://198.51.100.7:3000/') + onTestFinished(() => { setPageUrl(originalUrl) }) + const { c, settings } = await client(mock, start) + expect(c.connection.isLoopback).toBe(false) + expect(c.ctx.locale.getSnapshot().active).toBe('zh') + settings.describe.mockResolvedValue(ok({ + writable: true, hasDocument: false, namespaces: [localeView('en', 1)], + })) + await c.mock.streams.opened('$events', 1) + c.mock.streams.push('$events', { + type: 'emit', event: 'settings/document-updated', args: [LOCALE_SETTINGS_NAMESPACE, 1], + }) + await vi.waitFor(() => { + expect(c.ctx.locale.getSnapshot().active).toBe('en') + expect(generalLabel(c)).toBe('General') + }) + settings.describe.mockResolvedValue(ok({ + writable: true, hasDocument: false, namespaces: [localeView('zh', 2)], + })) + c.connection.reconnect() + await c.mock.streams.opened('$events', 2) + await vi.waitFor(() => { + expect(c.ctx.locale.getSnapshot().active).toBe('zh') + expect(generalLabel(c)).toBe('通用设置') + }) + expect(settings.mutate).not.toHaveBeenCalled() + }) + it('re-registers after a Loader rebuild of the declaring chain (stale disposers must not block)', async ({ mock, start }) => { const { c, settings } = await client(mock, start) const before = SEATS.map(([name]) => ownEntries(c, name)[0]) diff --git a/packages/client/ui-settings-general/tests/components.client.spec.tsx b/packages/client/ui-settings-general/tests/components.client.spec.tsx index ac2e7f000b..ab8a19976d 100644 --- a/packages/client/ui-settings-general/tests/components.client.spec.tsx +++ b/packages/client/ui-settings-general/tests/components.client.spec.tsx @@ -2,7 +2,7 @@ import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, describe, expect, it, vi } from 'vitest' import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { bindSnapshotSelector, RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, bindSnapshotSelector, RemoteError } from '@deepseek-ai/dsh-client-test-runtime' import type { GeneralSectionComponentProps } from '../src/client/GeneralSection.tsx' import { GeneralSection } from '../src/client/GeneralSection.tsx' import { CloseLabel, HeaderContent, TriggerContent } from '../src/client/chrome.tsx' @@ -41,6 +41,7 @@ const useSessionStatus: TriggerContentProps['useSessionStatus'] = selector => se const kit = { useSessions: unusedHook, useSessionStatus, usePanelInfo, useSessionRetainInfo: () => undefined, useResource, useWorkspaces: unusedHook, + ...allowAllAccess, } describe('Desktop collapsed update badge', () => { diff --git a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx index dcf874bcf7..2f46ad2057 100644 --- a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx +++ b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx @@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { useEffect, useState } from 'react' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { createSettingsShellStore } from '../src/client/shell-store.ts' -import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' import { SessionId } from '@deepseek-ai/dsh-session/types' import type { SettingsRootComponentProps } from '../src/client/shell-contract.ts' @@ -104,6 +104,7 @@ function mount({ useSessionStatus, usePanelInfo, useSessionRetainInfo: () => undefined, useResource, useWorkspaces: unusedHook, + ...allowAllAccess, wide, reconnect, openDesktopUpdate: () => {}, diff --git a/packages/client/ui-settings-general/tests/shell.client.spec.ts b/packages/client/ui-settings-general/tests/shell.client.spec.ts index ee90396ccd..1305c915d1 100644 --- a/packages/client/ui-settings-general/tests/shell.client.spec.ts +++ b/packages/client/ui-settings-general/tests/shell.client.spec.ts @@ -109,9 +109,7 @@ describe('ui-settings-general shell', () => { off() }) - it('shows Account first in Desktop while signed in and removes it on sign-out', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - onTestFinished(() => { vi.unstubAllGlobals() }) + it('shows Account first only while signed in and removes it on sign-out', async ({ start }) => { const c = await start() const { sections } = injectedOf(c).hooks await c.mock.streams.opened('account/watch', 1) 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/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index a5c0917a25..cef103488f 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -18,11 +18,11 @@ en: db5aaf7f702e1f0c zh: 409a78c14fb2b6e3 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/api-keys: - en: c2f2a5c06ef20d5b - zh: 49a7eb0b66b4ed53 + en: b39c74c9a874f5d4 + zh: db0dfcc2de9cab53 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: ec0ba62a4e7185b4 - zh: 37d1e1e7a3817d12 + en: 0786af5e4ed58c8a + zh: af94474af0749101 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: 9d533c65c82cd4a4 zh: 0a5da334e127c035 @@ -30,8 +30,8 @@ en: 589397a35f82244e zh: 342fbceee2c173a2 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/extension-slots: - en: 65e9d8822b67b6c2 - zh: 7e83be9defda28ee + en: 79f8f80bdaba73cd + zh: f4d7496b293fbf81 /deepseek-ai-dsh-client-ui-settings-models/understand-the-implementation: en: a87afbec5e339b36 zh: 6348c81af7e650e1 @@ -42,8 +42,8 @@ en: 6e04c00818f014cd zh: 2d57f8d8944e67ed /deepseek-ai-dsh-client-ui-settings-models/understand-the-implementation/onboarding-coordinator: - en: 46dea666dffe8813 - zh: 6f56fdc365fa3642 + en: dc515a31212e477a + zh: 770ba77cd9a69f73 /deepseek-ai-dsh-client-ui-settings-models/further-exploration: en: 20abd8b98b6c20e2 zh: 6dfda7955ce5f33f diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index def38dbba2..6c9548829a 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -43,11 +43,13 @@ Host configuration `credentialOnboarding` defaults to `true`. The Electron prelo API-key inputs start empty and use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. -The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores write-only through `credentials.set` under the profile's reference, deriving `_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material. +The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores write-only through `credentials.set` under the profile's reference, deriving `_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). The field's placeholder and help tooltip use the profile's `apiKeyEnv` when it has one; otherwise they use the environment variables of the route's `nativeAuth`, in lookup order, as the configurable-provider directory reports them. These display hints omit references containing `oauth` (case-insensitively), and describe saved credentials followed by the displayed environment fallbacks. This presentation filter does not change the [credential resolution order](../../../docs/subsystems/credentials.md#resolution), the adapter's complete environment list, or an explicit reference. A filtered explicit reference still has a usable key input with the plain placeholder and no tooltip. A native route that has no key authentication omits the key field and authentication help entirely; an explicit reference still enables the field. A profile without a reference on a route without `nativeAuth`, such as a hand-declared route, shows the plain key placeholder and no tooltip. A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material. + +For a profile with a named credential reference, the editor also shows **API key source** from the page's existing redacted `CredentialInfo` snapshot: saved credentials (`file`), launch environment (`env`), `$cwd/.env` (`project-env`), or `$DSH_HOME/.env` (`user-env`). Refreshing that snapshot updates an open editor without a separate editor probe. Unconfigured references, unknown source ids, and reference-free native authentication show no source label: a derived reference cannot identify the native provider's active credential. The label never receives a credential value or changes field writability. ### Editing a provider -The collapsed 自定义设置 fold carries the curated extras: `baseURL` for both families (the deepseek placeholder shows the public endpoint), each adapter's model catalog, and the **display name** and **API protocol** of a pi-ai route the adapter does not ship. Profile `headers` remain deployment configuration in `cordis.patch.yml` or Cordis config and have no Models-page editor. The Provider ID stays fixed: it is the settings key, the name every other namespace and every logged session references, and the stem of a credential reference the page cannot read back to move. Reasoning effort is deliberately not among the editable fields: it is a per-model capability, so a provider-scoped control could only be set to a value some models reject. Each model row edits `id`, optional display `name`, optional `contextWindow`/`maxTokens`, and input types; unrelated model fields survive edits. +The collapsed 自定义设置 fold carries the curated extras: `baseURL` for both families (the placeholder shows the endpoint the profile resolves to, the public endpoint for deepseek, else the `defaultBaseURL` the configurable-provider directory reports for a pi-ai catalog route), each adapter's model catalog, and the **display name** and **API protocol** of a pi-ai route the adapter does not ship. Profile `headers` remain deployment configuration in `cordis.patch.yml` or Cordis config and have no Models-page editor. The Provider ID stays fixed: it is the settings key, the name every other namespace and every logged session references, and the stem of a credential reference the page cannot read back to move. Reasoning effort is deliberately not among the editable fields: it is a per-model capability, so a provider-scoped control could only be set to a value some models reject. Each model row edits `id`, optional display `name`, optional `contextWindow`/`maxTokens`, and input types; unrelated model fields survive edits. The DeepSeek card edits the `llm-deepseek` endpoint, credentials, and model catalog. It uses Messages, with the default endpoint placeholder `https://api.deepseek.com/anthropic`. @@ -65,7 +67,7 @@ After the versioned notice step completes, the DeepSeek step projects first-run The section declares two seats for plugins distributed outside this repository, typed in [`src/client/slot-contract.ts`](src/client/slot-contract.ts) and exported from `./client`. `settings.models.provider-card` (keyed) renders inside every card that shows a directory row — a saved row's card, its first-run setup posture, and the add-provider draft — dispatched with `entryKey = settingsNs` and owner props carrying the row's `ConfigurableProviderView`, its configured state, and its confirmed api-key credential state, so one registration under an adapter family's namespace receives every card of that family, hand-declared routes included; the hand-declared draft card has no directory row yet and dispatches nothing until saved. `settings.models.footer` (list) renders after the rows and the add controls. A registrant activates through `ctx.slots.inject` with a type-only import of this package's `/client` entry; without registrants both seats render nothing. -The Models page includes **DeepSeek Account** (`deepseek-account`, **DeepSeek 账号** in Chinese). Its editor exposes the shared DeepSeek model catalog without API-key or base-URL inputs, and saves that catalog under the account route's own settings section (`llm-deepseek-account` by default), so an account edit never rewrites the `llm-deepseek` section the official route reads. The account row is hidden when its available model catalog is empty, including before sign-in and after sign-out; it returns when account models become available. +The Models page includes **DeepSeek Account** (`deepseek-account`, **DeepSeek 账号** in Chinese). The row shows a **Signed in** status and offers no editor: the account listing supplies its models, and [model overrides](../../llm/llm-deepseek-account/README.md#use-this-package) live in `cordis.patch.yml`. The account row is hidden when its available model catalog is empty, including before sign-in and after sign-out; it returns when account models become available. ----- @@ -89,7 +91,7 @@ Concurrent `ModelsSettingsStore.load()` callers resolve after the current refres ### Onboarding coordinator -The notice step owns its exact copy in `src/client/locales.ts` and its acknowledgement version in `src/onboarding-copy.ts`; on loopback it compares and writes `ui-settings-general.welcomeNoticeVersion` through the shared configuration form, and only an explicit Continue records the current version. Users who acknowledged an earlier version see the current notice again. A non-loopback browser cannot use that Host-only namespace, so acknowledgement is process-local and the notice returns after reload. The DeepSeek step targets `deepseek-official` in `llm-deepseek` and renders the existing `ProviderEditor` in credential-only mode inside the shared onboarding modal; `credentials.set` stays the only secret write, and no provider settings are changed. +The notice step owns its exact copy in `src/client/locales.ts` and its acknowledgement version in `src/onboarding-copy.ts`. Authenticated browsers compare and write `ui-settings-general.welcomeNoticeVersion` through the shared configuration form; only an explicit Continue records the current version, and an unavailable namespace or a refused write leaves the notice unacknowledged. Users who acknowledged an earlier version see the current notice again. The DeepSeek step targets `deepseek-official` in `llm-deepseek` and renders the existing `ProviderEditor` in credential-only mode inside the shared onboarding modal; `credentials.set` stays the only secret write, and no provider settings are changed. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 0af8ee6abb..c5e80da5c5 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -43,11 +43,13 @@ Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会 API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。 -编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。 +编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。profile 有 `apiKeyEnv` 时,字段的占位文字与帮助提示采用该引用;否则按查找顺序采用可配置提供商目录为该路由报告的 `nativeAuth` 环境变量。这些显示提示会忽略包含 `oauth` 的引用(不区分大小写),并说明优先使用已保存凭据,其后为显示的环境后备。这项显示过滤不改变[凭据解析顺序](../../../docs/subsystems/credentials.zh.md#resolution)、适配器的完整环境变量列表或显式引用。被过滤的显式引用仍有可用的密钥输入框,使用普通占位文字且不显示帮助提示。没有密钥认证的原生路由不显示密钥字段及认证帮助;显式引用仍会启用该字段。路由没有 `nativeAuth`(例如手动声明的路由)且 profile 没有引用时,显示普通的密钥占位文字,且不显示帮助提示。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。 + +profile 有具名凭据引用时,编辑器还会根据页面已有的脱敏 `CredentialInfo` 快照显示 **API 密钥来源**:已保存凭据(`file`)、启动环境(`env`)、`$cwd/.env`(`project-env`)或 `$DSH_HOME/.env`(`user-env`)。快照刷新会更新打开的编辑器,无需单独探测。未配置的引用、未知来源 id 和无引用的原生认证不显示来源标签:派生引用不能说明原生提供商当前采用的凭据。标签从不接收凭据值,也不改变字段的可写性。 ### 编辑提供商 -收起的「自定义设置」折叠区承载精选的额外字段:两个家族都有 `baseURL`(deepseek 的占位符显示公共端点)、各适配器自己的模型目录,以及适配器未提供的 pi-ai 路由的**显示名称**与 **API 协议**。Profile `headers` 仍是 `cordis.patch.yml` 或 Cordis 配置中的部署配置,Models 页面不提供编辑器。Provider ID 保持固定:它是 settings 的键、其他每个 namespace 与每一条已记录会话引用的名字,也是页面读不回、因而搬不走的凭据引用词干。推理等级刻意不在可编辑字段之列:它是按模型的能力,提供商级的控件只可能被设成某些模型会拒绝的值。每个模型行可编辑 `id`、可选显示 `name`、可选 `contextWindow`/`maxTokens` 和输入类型;无关的模型字段在编辑后仍会保留。 +收起的「自定义设置」折叠区承载精选的额外字段:两个家族都有 `baseURL`(占位符显示 profile 解析出的端点,deepseek 即公共端点;没有时显示可配置提供商目录为 pi-ai 内置路由报告的 `defaultBaseURL`)、各适配器自己的模型目录,以及适配器未提供的 pi-ai 路由的**显示名称**与 **API 协议**。Profile `headers` 仍是 `cordis.patch.yml` 或 Cordis 配置中的部署配置,Models 页面不提供编辑器。Provider ID 保持固定:它是 settings 的键、其他每个 namespace 与每一条已记录会话引用的名字,也是页面读不回、因而搬不走的凭据引用词干。推理等级刻意不在可编辑字段之列:它是按模型的能力,提供商级的控件只可能被设成某些模型会拒绝的值。每个模型行可编辑 `id`、可选显示 `name`、可选 `contextWindow`/`maxTokens` 和输入类型;无关的模型字段在编辑后仍会保留。 `llm-deepseek` 的 DeepSeek 卡片编辑端点、凭据和模型目录。它使用 Messages,默认端点占位符为 `https://api.deepseek.com/anthropic`。 @@ -65,7 +67,7 @@ API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求 本分区为仓库外分发的插件声明两个席位,类型定义在 [`src/client/slot-contract.ts`](src/client/slot-contract.ts) 并从 `./client` 导出。`settings.models.provider-card`(keyed)渲染在每张展示目录行的卡片内部——已保存行的卡片、其首次运行 setup 形态、以及「添加提供商」草稿卡——以 `entryKey = settingsNs` 分发,owner props 携带该行的 `ConfigurableProviderView`、其 configured 状态与已确认的 api-key 凭据状态,因此以某适配器家族的 namespace 注册一次即可收到该家族的全部卡片,含手工声明的路由;手工声明的草稿卡尚无目录行,保存之前不分发。`settings.models.footer`(list)渲染在行列表与新增控件之后。注册方通过 `ctx.slots.inject` 激活,并以 type-only import 引入本包 `/client` 入口;没有注册方时两个席位均不渲染任何内容。 -Models 页面包含 **DeepSeek 账号**(`deepseek-account`,英文为 **DeepSeek Account**)。其编辑器展示共享的 DeepSeek 模型目录,不提供 API Key 或 Base URL 输入框;目录保存到账号路由自己的设置段(默认为 `llm-deepseek-account`),因此账号侧的编辑不会改写 official 路由读取的 `llm-deepseek` 段。账号可用模型目录为空时隐藏账号行,包括登录前和退登后;账号模型恢复可用时重新显示。 +Models 页面包含 **DeepSeek 账号**(`deepseek-account`,英文为 **DeepSeek Account**)。该行显示 **已登录** 状态,不提供编辑器:模型来自账号的模型列表,[模型覆盖](../../llm/llm-deepseek-account/README.zh.md#use-this-package)写在 `cordis.patch.yml` 中。账号可用模型目录为空时隐藏账号行,包括登录前和退登后;账号模型恢复可用时重新显示。 ----- @@ -89,7 +91,7 @@ Models 页面包含 **DeepSeek 账号**(`deepseek-account`,英文为 **DeepS ### 引导协调器 -预览版说明在 `src/client/locales.ts` 中持有精确文案,并在 `src/onboarding-copy.ts` 中持有确认版本;回环时它通过既有 settings API 比较并写入 `ui-settings-general.welcomeNoticeVersion`,且只有显式点击「继续」才会记录当前版本。已确认旧版的用户会再次看到当前说明。非回环浏览器无法使用这个仅限宿主的 namespace,因此确认只保留在进程内,刷新后说明会再次出现。DeepSeek 步骤面向 `llm-deepseek` 中的 `deepseek-official`,在共享引导模态框内以仅凭据模式渲染既有 `ProviderEditor`;`credentials.set` 仍是唯一的机密写入,且不改变任何提供商设置。 +预览版说明在 `src/client/locales.ts` 中持有精确文案,并在 `src/onboarding-copy.ts` 中持有确认版本。认证浏览器通过共享配置表单比较并写入 `ui-settings-general.welcomeNoticeVersion`;只有显式点击「继续」才会记录当前版本;命名空间不可用或写入被拒时,声明保持未确认状态。已确认旧版的用户会再次看到当前说明。DeepSeek 步骤面向 `llm-deepseek` 中的 `deepseek-official`,在共享引导模态框内以仅凭据模式渲染既有 `ProviderEditor`;`credentials.set` 仍是唯一的机密写入,且不改变任何提供商设置。 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 3539985eb1..c413289469 100644 --- a/packages/client/ui-settings-models/package.json +++ b/packages/client/ui-settings-models/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-models", "description": "Models settings and shared product-onboarding dialogs over existing settings and credential joins", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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/src/client/ModelsSection.module.css b/packages/client/ui-settings-models/src/client/ModelsSection.module.css index 2074fc6a07..91f5c2e9c0 100644 --- a/packages/client/ui-settings-models/src/client/ModelsSection.module.css +++ b/packages/client/ui-settings-models/src/client/ModelsSection.module.css @@ -113,6 +113,16 @@ background: var(--dsw-alias-state-error-primary); } +.accountStatus { + display: inline-flex; + flex: none; + align-items: center; + gap: 6px; + font-size: 13px; + line-height: 20px; + color: var(--dsw-alias-state-success-primary); +} + .rowActions { display: inline-flex; align-items: center; @@ -265,6 +275,28 @@ color: var(--dsw-alias-label-secondary); } +.helpButton { + width: 16px; + height: 16px; + padding: 0; + border: 0.5px solid var(--dsw-alias-border-l3); + border-radius: 50%; + corner-shape: round; + background: transparent; + color: var(--dsw-alias-label-tertiary); + font: inherit; + font-size: 11px; + line-height: 15px; + text-align: center; + cursor: help; +} + +.helpButton:hover, +.helpButton:focus-visible { + color: var(--dsw-alias-label-primary); + border-color: var(--dsw-alias-label-tertiary); +} + .linkButton { box-sizing: border-box; display: inline-flex; diff --git a/packages/client/ui-settings-models/src/client/ModelsSection.tsx b/packages/client/ui-settings-models/src/client/ModelsSection.tsx index cb5dc86b08..87727ffff1 100644 --- a/packages/client/ui-settings-models/src/client/ModelsSection.tsx +++ b/packages/client/ui-settings-models/src/client/ModelsSection.tsx @@ -25,7 +25,7 @@ import { useId, useState } from 'react' import type { ReactNode } from 'react' import { Button, IconPlusOutlineRegular, Modal, SegmentedControl } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' -import type { SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client' +import type { LlmNativeAuth, SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client' // Type-only: pulls this package's SlotMap merge (the two Models child slots). import type {} from './slot-contract.ts' import { CustomProviderCard } from './CustomProviderCard.tsx' @@ -92,6 +92,10 @@ interface EditorTarget extends ProviderIdentity { credentialRef?: string /** The adapter reports this route as one it does not ship (see {@link ProviderEditorProps.declared}). */ declared?: boolean + /** The route's catalog endpoint (see {@link ProviderEditorProps.defaultBaseURL}). */ + defaultBaseURL?: string + /** The route's native authentication (see {@link ProviderEditorProps.nativeAuth}). */ + nativeAuth?: LlmNativeAuth } /** A dormant directory row the add card can adopt, with its registered namespace. */ @@ -109,7 +113,7 @@ interface CatalogDraft { /** Values that vary around the shared provider-editor rendering. */ interface ProviderEditorRenderProps extends Pick< ProviderEditorProps, - 'namespace' | 'schema' | 'operations' | 't' | 'readOnly' | 'onClose' + 'namespace' | 'schema' | 'operations' | 't' | 'readOnly' | 'onClose' | 'credential' > { target: EditorTarget } @@ -122,6 +126,8 @@ function renderProviderEditor({ target, ...props }: ProviderEditorRenderProps): displayName={target.displayName} settingsPath={target.settingsPath} {...target.declared === true ? { declared: true } : {}} + {...target.defaultBaseURL === undefined ? {} : { defaultBaseURL: target.defaultBaseURL }} + {...target.nativeAuth === undefined ? {} : { nativeAuth: target.nativeAuth }} {...props} /> ) @@ -200,6 +206,8 @@ function targetOf(row: ProviderRow): EditorTarget { ...credentialRef === undefined ? {} : { credentialRef }, // Only declared routes may expose route-owned fields. ...row.entry.declared === true ? { declared: true } : {}, + ...row.entry.defaultBaseURL === undefined ? {} : { defaultBaseURL: row.entry.defaultBaseURL }, + ...row.entry.nativeAuth === undefined ? {} : { nativeAuth: row.entry.nativeAuth }, } } @@ -424,6 +432,7 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS {renderProviderEditor({ target, namespace, + ...row.credential === undefined ? {} : { credential: row.credential }, schema, operations, t, @@ -454,6 +463,15 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS {row.entry.declared === true ? {t('customTag')} : null} + {/* The store keeps the account row only while the account lists models. */} + {row.entry.provider === 'deepseek-account' + ? ( + + + ) + : null} {credentialConfigured ? ( - + {/* The account catalog comes from the account listing; its model overrides live in cordis.patch.yml. */} + {row.entry.provider === 'deepseek-account' + ? null + : ( + + )} {row.removable ? ( + + ) + // A provider with no native key authentication has no key for this field to store. + const keylessNativeAuth = nativeAuth?.env.length === 0 && nativeAuth.oauth + const keyPlaceholder = keyHint === undefined + ? t('keyPlaceholder') + : t('keyPlaceholderFallback').replace('{hint}', () => keyHint) /** What both family editors take: the rows, whose layer owns them, and the two writes. */ const catalogProps = { models, @@ -373,28 +386,31 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { }, onReset: () => { setDraft(current => schema.deletePath(current, ['models'])) }, } - if (accountProvider) return return ( <> -
- {t('keyInput')} - { setKeyDraft(event.target.value) }} - /> - {shownKeyFailure === undefined ? null :

{t(shownKeyFailure)}

} -
+ {keylessNativeAuth + ? null + :
+ + {t('keyInput')} + {authHelp} + + { setKeyDraft(event.target.value) }} + /> + {keySource === undefined ? null : {keySource}} + {shownKeyFailure === undefined ? null :

{t(shownKeyFailure)}

} +
} {props.credentialOnly === true ? null :
{t('customized')}
@@ -433,7 +449,10 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { value={stringAt(draft, 'baseURL') ?? ''} placeholder={family === 'deepseek' ? t('deepSeekBaseUrl') - : stringAt(fallback, 'baseURL') ?? t('baseUrlDefault')} + : (() => { + const baseURL = stringAt(fallback, 'baseURL') ?? props.defaultBaseURL + return baseURL === undefined ? t('baseUrlDefault') : t('baseUrlPlaceholder').replace('{url}', () => baseURL) + })()} aria-describedby={family === 'deepseek' ? `${props.provider}-endpoint-hint` : undefined} aria-label={t('baseUrl')} disabled={disabled} diff --git a/packages/client/ui-settings-models/src/client/WelcomeNotice.tsx b/packages/client/ui-settings-models/src/client/WelcomeNotice.tsx index 51685beb44..798854ab32 100644 --- a/packages/client/ui-settings-models/src/client/WelcomeNotice.tsx +++ b/packages/client/ui-settings-models/src/client/WelcomeNotice.tsx @@ -13,7 +13,7 @@ import css from './WelcomeNotice.module.css' /** Registration-side dependencies of {@link WelcomeNotice}. */ export interface WelcomeNoticeInjected { hooks: { - /** Durable or process-local acknowledgement state. */ + /** Durable acknowledgement state. */ welcome: SnapshotStore } /** Welcome acknowledgement controller. */ diff --git a/packages/client/ui-settings-models/src/client/index.ts b/packages/client/ui-settings-models/src/client/index.ts index bb60baabe8..bf3c7e13e0 100644 --- a/packages/client/ui-settings-models/src/client/index.ts +++ b/packages/client/ui-settings-models/src/client/index.ts @@ -106,8 +106,6 @@ export function apply(ctx: ClientContext): void { schema, t, }) - // The scope's own memory mode is what keeps a remote browser process-local, - // so the store needs no isLoopback branch of its own. const welcomeController = new WelcomeNoticeStore(ctx.configForms.get>(WELCOME_NOTICE_SETTINGS_NAMESPACE)) const welcomeInjected = (): WelcomeNoticeInjected => ({ controller: welcomeController, diff --git a/packages/client/ui-settings-models/src/client/locales.ts b/packages/client/ui-settings-models/src/client/locales.ts index 0ece7ada5e..034c1e7b94 100644 --- a/packages/client/ui-settings-models/src/client/locales.ts +++ b/packages/client/ui-settings-models/src/client/locales.ts @@ -31,19 +31,25 @@ export const en = { savedProvider: 'Saved {provider}.', credentialConfigured: 'API key configured', credentialMissing: 'API key missing', + accountSignedIn: 'Signed in', readOnly: 'The settings document is read-only in this deployment.', loadFailed: 'Loading the provider directory failed', conflict: 'Someone else changed these settings while this card was open. Close it and reopen to edit the current values.', retry: 'Retry', keyInput: 'API key', keyPlaceholder: 'Enter your API key', - keyPlaceholderNative: 'Enter an API key, or leave blank to use environment authentication', - keyStored: 'Configured — enter a new value to replace', - keyEnvLocked: 'Provided by the launch environment (read-only)', + keyPlaceholderFallback: 'Leave blank to keep existing authentication ({hint})', + keyHelp: 'Saved credentials are used first. Environment fallbacks shown here, in order: {env}. Sources are launch environment, $cwd/.env, then $DSH_HOME/.env.', + authHelp: 'Authentication details', + keySourceFile: 'API key source: saved credentials', + keySourceEnv: 'API key source: launch environment', + keySourceProjectEnv: 'API key source: $cwd/.env', + keySourceUserEnv: 'API key source: $DSH_HOME/.env', customized: 'Customized settings', baseUrl: 'Base URL', - baseUrlDefault: 'Provider default', - deepSeekBaseUrl: 'https://api.deepseek.com/anthropic', + baseUrlDefault: 'No default endpoint', + baseUrlPlaceholder: '{url}', + deepSeekBaseUrl: 'https://api.deepseek.com/anthropic (Default to use DEEPSEEK_BASE_URL)', deepSeekEndpointHint: 'Use an API endpoint compatible with Anthropic Messages.', models: 'Models', modelsInherited: 'Using the adapter defaults', @@ -151,19 +157,25 @@ export const zh: { [Key in keyof typeof en]: string } = { savedProvider: '已保存 {provider}。', credentialConfigured: 'API 密钥已配置', credentialMissing: 'API 密钥缺失', + accountSignedIn: '已登录', readOnly: '当前部署的设置文档为只读。', loadFailed: '加载提供商目录失败', conflict: '这张卡片打开期间,这些设置已被其他地方改动。请关闭后重新打开,在当前值上编辑。', retry: '重试', keyInput: 'API 密钥', keyPlaceholder: '输入 API 密钥', - keyPlaceholderNative: '输入 API 密钥,或留空使用环境认证', - keyStored: '已配置——输入新值可替换', - keyEnvLocked: '由启动环境提供(只读)', + keyPlaceholderFallback: '留空时保留现有认证({hint})', + keyHelp: '优先使用已保存的凭据。此处显示的环境后备按以下顺序排列:{env}。来源依次为启动环境、$cwd/.env、$DSH_HOME/.env。', + authHelp: '认证说明', + keySourceFile: 'API 密钥来源:已保存凭据', + keySourceEnv: 'API 密钥来源:启动环境', + keySourceProjectEnv: 'API 密钥来源:$cwd/.env', + keySourceUserEnv: 'API 密钥来源:$DSH_HOME/.env', customized: '自定义设置', baseUrl: 'API 地址', - baseUrlDefault: '提供商默认', - deepSeekBaseUrl: 'https://api.deepseek.com/anthropic', + baseUrlDefault: '没有默认地址', + baseUrlPlaceholder: '{url}', + deepSeekBaseUrl: 'https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)', deepSeekEndpointHint: '请填写兼容 Anthropic Messages 协议的 API 地址。', models: '模型目录', modelsInherited: '正在使用适配器默认模型', diff --git a/packages/client/ui-settings-models/src/client/operations.ts b/packages/client/ui-settings-models/src/client/operations.ts index 8ca6beb798..d8c5d0ac99 100644 --- a/packages/client/ui-settings-models/src/client/operations.ts +++ b/packages/client/ui-settings-models/src/client/operations.ts @@ -7,7 +7,7 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { - CredentialInfo, LlmDiscoveredModel, LlmModelDiscoveryRequest, + LlmDiscoveredModel, LlmModelDiscoveryRequest, SettingsNamespaceView, SettingsPathOpView, } from '@deepseek-ai/dsh-api-remotes/client' @@ -32,12 +32,6 @@ export type ModelDiscoveryOutcome = /** The Host operations the Models page and its cards invoke. */ export interface ModelsOperations { - /** - * Read one credential reference's state. - * @param ref - credential reference name. - * @returns the state, or undefined when the reference is unknown or the read was refused. - */ - describeCredential(ref: string): Promise /** * Store one credential literal under its reference. * @param ref - credential reference name. @@ -81,10 +75,6 @@ export interface ModelsOperations { */ export function createModelsOperations(ctx: ClientContext): ModelsOperations { return { - describeCredential: async (ref) => { - const response = await ctx.remote.credentials.describe([ref]) - return response.ok ? response.value[ref] : undefined - }, storeCredential: async (ref, value) => { const response = await ctx.remote.credentials.set(ref, value) return response.ok ? undefined : response.error.message diff --git a/packages/client/ui-settings-models/src/client/store.ts b/packages/client/ui-settings-models/src/client/store.ts index 52e00bd7eb..4283890eac 100644 --- a/packages/client/ui-settings-models/src/client/store.ts +++ b/packages/client/ui-settings-models/src/client/store.ts @@ -9,7 +9,7 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { - CredentialInfo, LlmConfigurableProvider, LlmProviderInfo, SettingsNamespaceView, + CredentialInfo, LlmConfigurableProvider, LlmNativeAuth, LlmProviderInfo, SettingsNamespaceView, } from '@deepseek-ai/dsh-api-remotes/client' import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -30,6 +30,8 @@ export interface ProviderDirectoryEntry { readonly settingsPath: readonly string[] readonly active: boolean readonly declared?: boolean + readonly defaultBaseURL?: string + readonly nativeAuth?: LlmNativeAuth readonly error?: string } @@ -52,6 +54,8 @@ export function joinProviderDirectory( settingsPath: [...entry.settingsPath], active: active.has(entry.provider), ...entry.declared === undefined ? {} : { declared: entry.declared }, + ...entry.defaultBaseURL === undefined ? {} : { defaultBaseURL: entry.defaultBaseURL }, + ...entry.nativeAuth === undefined ? {} : { nativeAuth: entry.nativeAuth }, ...entry.error === undefined ? {} : { error: entry.error }, })) for (const provider of registered) { @@ -209,7 +213,9 @@ export class ModelsSettingsStore { if (!declared.ok) { this.failLoad(declared.error.message); return } const mirrored = this.describeFace.getSnapshot() if (mirrored.view === undefined) { - this.failLoad(mirrored.error ?? 'settings are unavailable in this browser') + /* v8 ignore next -- SettingsDescribeFace.ensure settles with a view or the read's error */ + if (mirrored.error === null) throw new Error('settings describe settled with neither a view nor an error') + this.failLoad(mirrored.error) return } const providers = joinProviderDirectory(registered.value, declared.value) diff --git a/packages/client/ui-settings-models/src/client/welcome-store.ts b/packages/client/ui-settings-models/src/client/welcome-store.ts index 1de2066ada..49cec92fc1 100644 --- a/packages/client/ui-settings-models/src/client/welcome-store.ts +++ b/packages/client/ui-settings-models/src/client/welcome-store.ts @@ -1,8 +1,6 @@ /** - * Welcome-notice state derived from the welcome settings scope. The scope is - * the transport: a loopback browser follows the durable Host section, while a - * remote browser's memory-mode scope never answers and the acknowledgement - * stays process-local here. + * Welcome-notice state derived from the welcome settings scope: the notice + * follows the Host section and records its acknowledgement through it. */ import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -39,21 +37,16 @@ function assertNever(_value: never): never { throw new Error('unexpected welcome settings status') } -/** Coordinates durable Host acknowledgement or a process-local remote fallback. */ +/** Coordinates the durable Host acknowledgement. */ export class WelcomeNoticeStore { /** uSES-safe state source shared by the registered welcome step. */ readonly store: SnapshotStore = createSnapshotStore({ status: 'idle', acknowledged: false, error: null, }) - private localAcknowledged = false private saving = false private following: (() => void) | undefined - /** - * @param scope - the welcome settings namespace scope; its memory mode is - * what keeps a remote browser process-local. - */ constructor(private readonly scope: ConfigForm) {} /** @@ -67,17 +60,12 @@ export class WelcomeNoticeStore { } /** - * Persist this copy version, or advance only this process for a remote - * browser. Success is judged against the state the write left behind, so a - * refused or failed write reports false after its recovery read settles. - * @returns true when the selected persistence mode holds the acknowledgement. + * Persist this copy version through the scope. Success is judged against the + * state the write left behind, so a refused or failed write reports false + * after its recovery read settles. + * @returns true when the Host holds the acknowledgement. */ async acknowledge(): Promise { - if (this.scope.getSnapshot().mode === 'memory') { - this.localAcknowledged = true - this.derive() - return true - } this.saving = true this.store.update((state) => { state.status = 'saving'; state.error = null }) try { @@ -105,14 +93,6 @@ export class WelcomeNoticeStore { private derive(): void { if (this.saving) return const scope = this.scope.getSnapshot() - if (scope.mode === 'memory') { - this.store.update((state) => { - state.status = 'ready' - state.acknowledged = this.localAcknowledged - state.error = null - }) - return - } switch (scope.status) { case 'loading': this.store.update((state) => { state.status = 'loading'; state.error = null }) diff --git a/packages/client/ui-settings-models/tests/apply.client.spec.ts b/packages/client/ui-settings-models/tests/apply.client.spec.ts index 2372690ba2..f9dac62ceb 100644 --- a/packages/client/ui-settings-models/tests/apply.client.spec.ts +++ b/packages/client/ui-settings-models/tests/apply.client.spec.ts @@ -27,7 +27,7 @@ afterEach(() => { vi.unstubAllGlobals() }) // so browser-language detection never runs and a fresh LocaleRuntime opens on // FALLBACK_LOCALE (en); bench stages zh explicitly on the locale instead. -async function bench(isLoopback = true, mock = RemoteMock.create().load(remoteDefaultResponses), services: object = {}) { +async function bench(mock = RemoteMock.create().load(remoteDefaultResponses), services: object = {}) { onTestFinished(() => { mock.assertNoUnmatched() }) const ctx = new Context() await ctx.plugin(SlotRegistry).await() @@ -49,8 +49,6 @@ async function bench(isLoopback = true, mock = RemoteMock.create().load(remoteDe settings: mock.remote.settings, session: { initializeDefaultModel: vi.fn(async () => ({ ok: true, value: undefined })) }, }) - // The fixed Host facts the settings provider reads its persistence from. - remote.$host = { home: undefined, isLoopback } await ctx.plugin({ inject: [...settingsInject], apply: settingsApply }).await() return { ctx, slots: ctx.get('slots') as SlotRegistry, locale, remote } } @@ -242,22 +240,6 @@ describe('ui-settings-models apply', () => { expect(() => b.locale.register('settings.models', 'zh', {})).not.toThrow() expect(() => b.locale.register('settings.models', 'en', {})).not.toThrow() }) - - it('keeps remote-browser acknowledgement in process memory', async () => { - const b = await bench(false) - declare(b.slots) - await b.ctx.plugin({ inject: [...inject], apply }).await() - const entry = b.slots.entries('settings.onboarding') - .find(candidate => candidate.options.id === 'welcome-notice')! - const injected = ( - entry.inject as unknown as () => import('../src/client/WelcomeNotice.tsx').WelcomeNoticeInjected - )() - - await injected.controller.load() - expect(injected.controller.store.getSnapshot()).toEqual({ - status: 'ready', acknowledged: false, error: null, - }) - }) }) describe('pushed invalidations', () => { @@ -318,7 +300,7 @@ describe('pushed invalidations', () => { } const document = { writable: true, hasDocument: false, namespaces: [namespace] } mock.remote.settings.describe.mockResolvedValue(ok(document)) - const b = await bench(true, mock) + const b = await bench(mock) declare(b.slots) await b.ctx.plugin({ inject: [...inject], apply }).await() const entry = b.slots.entries('settings.onboarding') @@ -348,7 +330,7 @@ describe('pushed invalidations', () => { const describe = mock.remote.settings.describe describe.mockResolvedValue(ok(document)) const listProviders = vi.fn(() => Promise.resolve({ ok: true as const, value: [] })) - const b = await bench(true, mock, { listProviders }) + const b = await bench(mock, { listProviders }) declare(b.slots) await b.ctx.plugin({ inject: [...inject], apply }).await() const entry = b.slots.entries('settings.section') diff --git a/packages/client/ui-settings-models/tests/components.client.spec.tsx b/packages/client/ui-settings-models/tests/components.client.spec.tsx index 588d0eda2d..0b12855e64 100644 --- a/packages/client/ui-settings-models/tests/components.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/components.client.spec.tsx @@ -14,6 +14,7 @@ import { } from '../src/client/ModelsSection.tsx' import type { ModelsSectionInjected, ModelsSectionProps } from '../src/client/ModelsSection.tsx' import { ProviderEditor, pathOps } from '../src/client/ProviderEditor.tsx' +import type { ProviderEditorProps } from '../src/client/ProviderEditor.tsx' import { DeepSeekModelsEditor, formatCapacity, modelDrafts, parseCapacity, validateDeepSeekModels, } from '../src/client/DeepSeekModelsEditor.tsx' @@ -23,7 +24,7 @@ import { deriveKeyRef, ModelsSettingsStore } from '../src/client/store.ts' import { createModelsOperations } from '../src/client/operations.ts' import type { ModelsOperations } from '../src/client/operations.ts' import type { ProviderRow } from '../src/client/store.ts' -import { en, zh } from '../src/client/locales.ts' +import { en } from '../src/client/locales.ts' import { settingsSchema } from './settings-schema.client.ts' afterEach(cleanup) @@ -155,11 +156,6 @@ function wireNamespaces(): SettingsNamespaceView[] { ] } -/** The account provider's settings namespace, under a composition's entry id. */ -function accountNamespace(ns = 'llm-deepseek-account'): SettingsNamespaceView { - return { ...wireNamespaces().find(view => view.ns === 'llm-deepseek-account')!, ns } -} - /** Credentials answers over the Remote carrier, which has no envelope. */ function remoteOk(value: T) { return { ok: true as const, value } @@ -198,8 +194,15 @@ function scriptedFace(overrides: { ]))), listConfigurableProviders: vi.fn(() => Promise.resolve(remoteOk([ { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [], active: true }, - { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'], active: true }, - { provider: 'anthropic', displayName: 'anthropic', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'anthropic'], active: false }, + { + provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'], active: true, + defaultBaseURL: 'https://api.openai.com/v1', nativeAuth: { env: ['OPENAI_API_KEY'], oauth: false }, + }, + { + provider: 'anthropic', displayName: 'anthropic', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'anthropic'], active: false, + defaultBaseURL: 'https://api.anthropic.com', + nativeAuth: { env: ['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY'], oauth: true }, + }, { provider: 'zombie', displayName: 'zombie', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'zombie'], active: false }, { provider: 'broken', displayName: 'broken', settingsNs: 'llm-pi-ai', settingsPath: ['nope', 'x'], active: false }, { provider: 'plain', displayName: 'plain', settingsNs: 'llm-plain', settingsPath: ['profiles', 'plain'], active: false }, @@ -261,6 +264,32 @@ function operationsWith(face: object): ModelsOperations { return bound } +/** The pi-ai namespace with one more route profile stored in the user layer. */ +function piAiNamespaceWith(provider: string, profile: { [key: string]: JsonValue }): SettingsNamespaceView { + const namespace = wireNamespaces().find(view => view.ns === 'llm-pi-ai')! + const providers = { ...(namespace.value as { providers: object }).providers, [provider]: profile } + return { ...namespace, value: { providers }, user: { providers } } +} + +/** Render one pi-ai route's editor with the directory and credential facts the page already holds. */ +function renderPiAiEditor( + provider: string, + namespace: SettingsNamespaceView, + facts: Pick = {}, +): void { + render() +} + +/** Hover the key label's help button and read its tooltip; null when the label has no button. */ +function authHelpText(): string | null { + const button = screen.queryByRole('button', { name: en.authHelp }) + if (button === null) return null + fireEvent.mouseEnter(button) + return screen.getByRole('tooltip').textContent +} + /** One recorded child-slot dispatch: seat name, owner share, kind options. */ type RenderSlotCall = [name: string, owner: Record, opts?: { entryKey?: string }] @@ -871,7 +900,7 @@ describe('ModelsSection', () => { const baseURL = screen.getByLabelText(en.baseUrl) // The deepseek placeholder is pinned to the public endpoint, not the // effective value (which may reflect a launch-environment override). - expect(baseURL.placeholder).toBe('https://api.deepseek.com/anthropic') + expect(baseURL.placeholder).toBe('https://api.deepseek.com/anthropic (Default to use DEEPSEEK_BASE_URL)') fireEvent.change(baseURL, { target: { value: 'https://next2' } }) fireEvent.click(screen.getByText(en.apply)) await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(1) }) @@ -943,7 +972,7 @@ describe('ModelsSection', () => { />) fireEvent.click(screen.getByText(en.customized)) expect(screen.getByLabelText(en.baseUrl).placeholder) - .toBe('https://api.deepseek.com/anthropic') + .toBe('https://api.deepseek.com/anthropic (Default to use DEEPSEEK_BASE_URL)') expect(screen.queryByLabelText(en.customApi)).toBeNull() expect(screen.getByText(en.deepSeekEndpointHint)).toBeTruthy() fireEvent.change(screen.getByLabelText(en.keyInput), { target: { value: 'sk-messages-test' } }) @@ -1355,7 +1384,7 @@ describe('ModelsSection', () => { />) fireEvent.click(screen.getByText(en.customized)) const baseURL = screen.getByLabelText(en.baseUrl) - expect(baseURL.placeholder).toBe('https://api.deepseek.com/anthropic') + expect(baseURL.placeholder).toBe('https://api.deepseek.com/anthropic (Default to use DEEPSEEK_BASE_URL)') fireEvent.change(baseURL, { target: { value: 'https://x' } }) expect(baseURL.value).toBe('https://x') fireEvent.change(baseURL, { target: { value: '' } }) @@ -1384,14 +1413,15 @@ describe('ModelsSection', () => { it('edits a pi-ai profile with the curated fields only', async () => { const { mutate } = await mountSection() fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) })) - // The configured credential shows as the stored placeholder. + // The field names the profile's reference; a stored value stays hidden. const editorKey = await screen.findByLabelText(en.keyInput) - await waitFor(() => { expect(editorKey.placeholder).toBe(en.keyStored) }) + expect(editorKey.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'OPENAI_API_KEY')) // pi-ai carries Base URL too: the stored override shows as the value and - // the effective profile endpoint as its placeholder source. + // the effective profile endpoint, ahead of the catalog's, as its placeholder. fireEvent.click(screen.getByText(en.customized)) const url = screen.getByLabelText(en.baseUrl) expect(url.value).toBe('https://proxy') + expect(url.placeholder).toBe('https://proxy') fireEvent.change(url, { target: { value: 'https://proxy/v2' } }) fireEvent.click(screen.getByText(en.apply)) await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(1) }) @@ -1410,12 +1440,12 @@ describe('ModelsSection', () => { const pick = await screen.findByLabelText(en.provider) expect([...pick.options].map(option => option.value)).toEqual(['anthropic', 'broken', 'plain']) expect(pick.value).toBe('anthropic') - // A dormant profile has no endpoint anywhere: the pi-ai placeholder - // falls back to the provider-default wording. + // A dormant route shows its catalog endpoint and the first variable its + // provider reads; a typed key still stores under the derived reference. fireEvent.click(screen.getByText(en.customized)) - expect(screen.getByLabelText(en.baseUrl).placeholder).toBe(en.baseUrlDefault) + expect(screen.getByLabelText(en.baseUrl).placeholder).toBe('https://api.anthropic.com') const addKey = screen.getByLabelText(en.keyInput) - expect(addKey.placeholder).toBe(en.keyPlaceholderNative) + expect(addKey.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'ANTHROPIC_AUTH_TOKEN')) fireEvent.change(addKey, { target: { value: 'sk-ant' } }) fireEvent.click(screen.getByText(en.apply)) await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(1) }) @@ -1525,7 +1555,7 @@ describe('ModelsSection', () => { renderSlot={() => null} />) const key = await screen.findByLabelText(en.keyInput) - expect(key.placeholder).toBe(en.keyPlaceholder) + expect(key.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'DEEPSEEK_API_KEY')) }) it('tells the user to reopen when another writer moved the namespace first', async () => { @@ -1553,36 +1583,25 @@ describe('ModelsSection', () => { expect(screen.getByText(en.apply)).toBeTruthy() }) - it('surfaces a shadowed credential write on the card', async () => { + it('surfaces a refused credential write on the card', async () => { await mountFirstRun({ - set: vi.fn(() => Promise.resolve(remoteFail('credentials: DEEPSEEK_API_KEY is shadowed by the read-only environment'))), + set: vi.fn(() => Promise.resolve(remoteFail( + 'credentials-local: invalid document at /home/user/.dsh/.credentials.yaml: BAD_INDENT at line 3, column 1', + ))), }) const key = screen.getByLabelText(en.keyInput) fireEvent.change(key, { target: { value: 'sk-live' } }) fireEvent.click(screen.getByText(en.apply)) - await screen.findByText(/shadowed by the read-only environment/) + await screen.findByText(/invalid document at \/home\/user\/\.dsh\/\.credentials\.yaml/) expect(screen.queryByRole('status')).toBeNull() }) - it('locks the key input when the launch environment provides the credential', async () => { - const { face } = await mountSection() - face.credentials.describe.mockImplementation((refs: string[]) => Promise.resolve(remoteOk( - Object.fromEntries(refs.map(ref => [ref, { - configured: ref === 'OPENAI_API_KEY', source: 'env', writable: false, - }])), - ))) - fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) })) - const editorKey = await screen.findByLabelText(en.keyInput) - await waitFor(() => { expect(editorKey.placeholder).toBe(en.keyEnvLocked) }) - expect(editorKey.disabled).toBe(true) - }) - it('keeps a failed credential describe silent and the input usable', async () => { const { face, set } = await mountSection() face.credentials.describe.mockImplementation(() => Promise.resolve(remoteFail('down', 'gateway/internal'))) fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) })) const editorKey = await screen.findByLabelText(en.keyInput) - expect(editorKey.placeholder).toBe(en.keyPlaceholderNative) + expect(editorKey.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'OPENAI_API_KEY')) fireEvent.change(editorKey, { target: { value: 'sk-live' } }) fireEvent.click(screen.getByText(en.apply)) await waitFor(() => { expect(set).toHaveBeenCalledTimes(1) }) @@ -2131,118 +2150,131 @@ describe('apiKeyFailure', () => { }) }) -it.each([en, zh])('edits the account model catalog without credential or endpoint fields', async (copy) => { - const mutate = vi.fn(() => Promise.resolve(remoteOk(accountNamespace()))) - const scripted = scriptedFace({ mutate }) - const ops = operationsWith(scripted.face) - const describe = vi.spyOn(ops, 'describeCredential') - const namespace = accountNamespace() - const onClose = vi.fn() - render( copy[key]} readOnly={false} onClose={onClose} />) - expect(screen.queryByLabelText(copy.keyInput)).toBeNull() - expect(screen.queryByLabelText(copy.baseUrl)).toBeNull() - expect(describe).not.toHaveBeenCalled() - expect(screen.getByDisplayValue('deepseek-v4-flash')).toBeTruthy() - expect(screen.queryByText(content => content.includes(copy.advancedHint))).toBeNull() - await expect(`${document.body.textContent}\n`) - .toMatchFileSnapshot(`./expected/deepseek-account-${copy === en ? 'en' : 'zh'}.txt`) - const set = vi.spyOn(ops, 'storeCredential') - fireEvent.change(screen.getAllByLabelText(new RegExp(copy.modelId))[0]!, { target: { value: 'deepseek-v4-mini' } }) - fireEvent.click(screen.getByText(copy.apply)) - await waitFor(() => { expect(onClose).toHaveBeenCalledWith(true) }) - expect(mutate.mock.calls[0]).toEqual([ - 'llm-deepseek-account', - [{ - op: 'set', - path: ['models'], - value: [ - { - id: 'deepseek-v4-mini', - name: 'DeepSeek-V4-Flash', - description: 'Preserved hidden detail', - contextWindow: 1_000_000, - }, - { id: 'deepseek-v4-pro', name: 'DeepSeek-V4-Pro', contextWindow: 1_000_000 }, - ], - }], - 0, - ]) - expect(set).not.toHaveBeenCalled() +it.each([ + ['file', 'keySourceFile'], ['env', 'keySourceEnv'], + ['project-env', 'keySourceProjectEnv'], ['user-env', 'keySourceUserEnv'], +] as const)('shows the named credential source %s without reading its value', (source, key) => { + renderPiAiEditor('openai', piAiNamespaceWith('openai', { apiKeyEnv: 'OPENAI_API_KEY' }), { + credential: { configured: true, source, writable: true }, + }) + expect(screen.getByText(en[key])).toBeTruthy() + expect(screen.getByLabelText(en.keyInput).value).toBe('') }) -it('keeps the DeepSeek editor for an account route under a renamed settings entry', async () => { - const namespace = accountNamespace('team-account-entry') - const mutate = vi.fn(() => Promise.resolve(remoteOk(namespace))) - const ops = operationsWith(scriptedFace({ mutate }).face) - const set = vi.spyOn(ops, 'storeCredential') - const onClose = vi.fn() - render() - expect(screen.queryByText(content => content.includes(en.advancedHint))).toBeNull() - expect(screen.getByDisplayValue('deepseek-v4-flash')).toBeTruthy() - fireEvent.change(screen.getAllByLabelText(new RegExp(en.modelId))[0]!, { target: { value: 'deepseek-v4-mini' } }) - fireEvent.click(screen.getByText(en.apply)) - await waitFor(() => { expect(onClose).toHaveBeenCalledWith(true) }) - expect(mutate).toHaveBeenCalledWith('team-account-entry', expect.any(Array), 0) - expect(set).not.toHaveBeenCalled() +it.each([ + ['unconfigured', { apiKeyEnv: 'OPENAI_API_KEY' }, { configured: false, source: 'env', writable: true }], + ['unknown source', { apiKeyEnv: 'OPENAI_API_KEY' }, { configured: true, source: 'oauth', writable: true }], + ['native authentication', {}, { configured: true, source: 'file', writable: true }], +] as const)('does not guess a source for %s', (_label, profile, credential) => { + renderPiAiEditor('openai', piAiNamespaceWith('openai', profile), { credential }) + expect(screen.queryByText(/^API key source:/)).toBeNull() + expect(document.body.textContent).not.toMatch(/oauth/i) }) -it('opens the account row from the section and saves to its own namespace', async () => { - const namespace = accountNamespace() - const mutate = vi.fn(() => Promise.resolve(remoteOk(namespace))) - const { controller, set } = await mountSection({ mutate }) - const row = controller.store.getSnapshot().rows[0]! - await act(async () => { controller.store.update((state) => { - state.rows = [{ - ...row, - accountAvailable: true, - entry: { - provider: 'deepseek-account', displayName: en.deepSeekAccount, settingsNs: namespace.ns, settingsPath: [], active: true, - }, - }, ...state.rows] - }) }) - fireEvent.click(screen.getByRole('button', { - name: providerCopy(en.editProvider, { provider: 'deepseek-account', displayName: en.deepSeekAccount }), - })) - expect(screen.getByDisplayValue('deepseek-v4-flash')).toBeTruthy() - fireEvent.change(screen.getAllByLabelText(new RegExp(en.modelId))[0]!, { target: { value: 'deepseek-v4-mini' } }) - fireEvent.click(screen.getByText(en.apply)) - await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(1) }) - expect(mutate.mock.calls[0]).toEqual([ - 'llm-deepseek-account', - [{ - op: 'set', - path: ['models'], - value: [ - { - id: 'deepseek-v4-mini', - name: 'DeepSeek-V4-Flash', - description: 'Preserved hidden detail', - contextWindow: 1_000_000, - }, - { id: 'deepseek-v4-pro', name: 'DeepSeek-V4-Pro', contextWindow: 1_000_000 }, - ], - }], - 0, - ]) - expect(set).not.toHaveBeenCalled() +it('refreshes the open editor source from the page snapshot without an editor probe', async () => { + const { face, controller } = await mountSection() + const reads = face.credentials.describe.mock.calls.length + fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) })) + expect(screen.getByText(en.keySourceFile)).toBeTruthy() + expect(face.credentials.describe).toHaveBeenCalledTimes(reads) + face.credentials.describe.mockImplementation(refs => Promise.resolve(remoteOk( + Object.fromEntries(refs.map(ref => [ref, { configured: true, source: 'env', writable: true }])), + ))) + await act(() => controller.load()) + expect(screen.getByText(en.keySourceEnv)).toBeTruthy() + expect(screen.queryByText(en.keySourceFile)).toBeNull() + expect(face.credentials.describe).toHaveBeenCalledTimes(reads + 1) }) -it('renders the localized account row and supports catalogs without capacity defaults', async () => { +it('keeps an OAuth-only provider on its native authentication path', () => { + renderPiAiEditor('openai-codex', wireNamespaces().find(view => view.ns === 'llm-pi-ai')!, { + nativeAuth: { env: [], oauth: true }, + }) + expect(screen.queryByLabelText(en.keyInput)).toBeNull() + expect(authHelpText()).toBeNull() + expect(document.body.textContent).not.toMatch(/oauth/i) +}) + +it.each([ + ['anthropic', ['ANTHROPIC_API_KEY'], en.keyHelp.replace('{env}', 'ANTHROPIC_API_KEY')], + ['openai', ['OPENAI_API_KEY'], en.keyHelp.replace('{env}', 'OPENAI_API_KEY')], +] as const)('opens authentication help for %s on click and dismisses it with Escape', (provider, env, text) => { + renderPiAiEditor(provider, piAiNamespaceWith(provider, {}), { + nativeAuth: { env: [...env], oauth: true }, + }) + const help = screen.getByLabelText(en.authHelp) + fireEvent.click(help) + const tooltip = screen.getByRole('tooltip') + expect(tooltip.textContent).toBe(text) + expect(help.getAttribute('aria-describedby')).toBe(tooltip.id) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.queryByRole('tooltip')).toBeNull() +}) + +it.each([ + ['an OAuth-only provider', 'openai-codex', 'CODEX_TOKEN', { env: [], oauth: true }], + [ + 'a provider with catalog variables and an OAuth sign-in', 'anthropic', 'TEAM_ANTHROPIC_KEY', + { env: ['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY'], oauth: true }, + ], +] as const)('names the profile reference of %s instead of its native authentication', (_label, provider, ref, nativeAuth) => { + renderPiAiEditor(provider, piAiNamespaceWith(provider, { apiKeyEnv: ref }), { nativeAuth }) + expect(screen.getByLabelText(en.keyInput).placeholder) + .toBe(en.keyPlaceholderFallback.replace('{hint}', ref)) + expect(authHelpText()).toBe(en.keyHelp.replace('{env}', ref)) + expect(document.body.textContent).not.toMatch(/oauth/i) +}) + +it.each([ + [ + 'with an OAuth sign-in', 'anthropic', + { env: ['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY'], oauth: true }, + 'ANTHROPIC_AUTH_TOKEN / ANTHROPIC_API_KEY', + ], + ['without an OAuth sign-in', 'minimax-cn', { env: ['MINIMAX_CN_API_KEY'], oauth: false }, 'MINIMAX_CN_API_KEY'], +] as const)('lists method-neutral fallbacks for a catalog route %s', (_label, provider, nativeAuth, refs) => { + renderPiAiEditor(provider, piAiNamespaceWith(provider, {}), { nativeAuth }) + expect(screen.getByLabelText(en.keyInput).placeholder) + .toBe(en.keyPlaceholderFallback.replace('{hint}', nativeAuth.env[0])) + expect(authHelpText()).toBe(en.keyHelp.replace('{env}', refs)) + expect(document.body.textContent).not.toMatch(/oauth/i) +}) + +it('shows the next method-neutral fallback without modifying native authentication metadata', () => { + const nativeAuth = { env: ['ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY'], oauth: true } + renderPiAiEditor('anthropic', piAiNamespaceWith('anthropic', {}), { nativeAuth }) + expect(screen.getByLabelText(en.keyInput).placeholder) + .toBe(en.keyPlaceholderFallback.replace('{hint}', 'ANTHROPIC_API_KEY')) + expect(authHelpText()).toBe(en.keyHelp.replace('{env}', 'ANTHROPIC_API_KEY')) + expect(nativeAuth.env).toEqual(['ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY']) + expect(document.body.textContent).not.toMatch(/oauth/i) +}) + +it('keeps a method-specific profile reference usable without displaying its name', () => { + renderPiAiEditor('anthropic', piAiNamespaceWith('anthropic', { apiKeyEnv: 'TEAM_OAUTH_TOKEN' }), { + nativeAuth: { env: ['ANTHROPIC_API_KEY'], oauth: true }, + }) + expect(screen.getByLabelText(en.keyInput).placeholder).toBe(en.keyPlaceholder) + expect(authHelpText()).toBeNull() + expect(document.body.textContent).not.toMatch(/oauth/i) +}) + +it('offers a plain key field to a route the adapter reports no authentication or endpoint for', () => { + renderPiAiEditor('zombie', wireNamespaces().find(view => view.ns === 'llm-pi-ai')!) + expect(screen.getByLabelText(en.keyInput).placeholder).toBe(en.keyPlaceholder) + expect(authHelpText()).toBeNull() + fireEvent.click(screen.getByText(en.customized)) + expect(screen.getByLabelText(en.baseUrl).placeholder).toBe(en.baseUrlDefault) +}) + +it('renders the localized account row as signed in without an edit action', async () => { const scripted = scriptedFace({}) - const { controller, view } = await mountFace(scripted) + const { controller } = await mountFace(scripted) const row = controller.store.getSnapshot().rows[0]! await act(async () => { controller.store.update((state) => { state.rows = [{ ...row, accountAvailable: true, entry: { ...row.entry, provider: 'deepseek-account' } }] }) }) - expect(screen.getByText(en.deepSeekAccount)).toBeTruthy() - view.unmount() - const namespace = accountNamespace() - render( {}} />) - expect(screen.queryByLabelText(en.keyInput)).toBeNull() + const item = screen.getByText(en.deepSeekAccount).closest('li')! + expect(within(item).getByText(en.accountSignedIn)).toBeTruthy() + expect(within(item).queryByText(en.edit)).toBeNull() }) diff --git a/packages/client/ui-settings-models/tests/expected/deepseek-account-en.txt b/packages/client/ui-settings-models/tests/expected/deepseek-account-en.txt deleted file mode 100644 index c9841889a6..0000000000 --- a/packages/client/ui-settings-models/tests/expected/deepseek-account-en.txt +++ /dev/null @@ -1 +0,0 @@ -DeepSeek Accountdeepseek-accountModelsUsing the adapter defaultsAdd modelCancelApply diff --git a/packages/client/ui-settings-models/tests/expected/deepseek-account-zh.txt b/packages/client/ui-settings-models/tests/expected/deepseek-account-zh.txt deleted file mode 100644 index e11c2e1969..0000000000 --- a/packages/client/ui-settings-models/tests/expected/deepseek-account-zh.txt +++ /dev/null @@ -1 +0,0 @@ -DeepSeek 账号deepseek-account模型目录正在使用适配器默认模型添加模型取消保存 diff --git a/packages/client/ui-settings-models/tests/model-list-catalog.client.spec.tsx b/packages/client/ui-settings-models/tests/model-list-catalog.client.spec.tsx index a0034f2f7c..1e40a70f1e 100644 --- a/packages/client/ui-settings-models/tests/model-list-catalog.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/model-list-catalog.client.spec.tsx @@ -11,7 +11,6 @@ afterEach(cleanup) function operations(discoverModels: ModelsOperations['discoverModels']): ModelsOperations { return { discoverModels, - describeCredential: vi.fn(), storeCredential: vi.fn(), removeCredential: vi.fn(), writeSettings: vi.fn(), diff --git a/packages/client/ui-settings-models/tests/onboarding-dialog.client.spec.tsx b/packages/client/ui-settings-models/tests/onboarding-dialog.client.spec.tsx index f04b8853b4..a60aff9f8c 100644 --- a/packages/client/ui-settings-models/tests/onboarding-dialog.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/onboarding-dialog.client.spec.tsx @@ -6,7 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import Schema from '@deepseek-ai/schemastery' import type { SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client' import type { JsonValue } from '@deepseek-ai/dsh-util-values' -import { bindSnapshotSelector, RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, bindSnapshotSelector, RemoteError } from '@deepseek-ai/dsh-client-test-runtime' import { DeepSeekOnboardingDialog } from '../src/client/DeepSeekOnboardingDialog.tsx' import type { DeepSeekOnboardingDialogProps } from '../src/client/DeepSeekOnboardingDialog.tsx' import { SettingsDescribeMirror } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-mirror.ts' @@ -152,6 +152,7 @@ function harness(options: { useSessionStatus, usePanelInfo, useSessionRetainInfo: () => undefined, useResource, useWorkspaces: unusedHook, + ...allowAllAccess, controller, useModels: bindSnapshotSelector(controller.store), operations, diff --git a/packages/client/ui-settings-models/tests/store.client.spec.ts b/packages/client/ui-settings-models/tests/store.client.spec.ts index bade6e9d63..0c327d45fe 100644 --- a/packages/client/ui-settings-models/tests/store.client.spec.ts +++ b/packages/client/ui-settings-models/tests/store.client.spec.ts @@ -4,7 +4,28 @@ import type { RpcResponse } from '@deepseek-ai/dsh-api-remotes/client' import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' import { SettingsDescribeMirror } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-mirror.ts' import { settingsSchema } from './settings-schema.client.ts' -import { joinProviderDirectory, ModelsSettingsStore, providerUsable } from '../src/client/store.ts' +import { deriveKeyRef, joinProviderDirectory, ModelsSettingsStore, providerUsable } from '../src/client/store.ts' + +it.each([ + ['anthropic', 'ANTHROPIC_API_KEY'], + ['moonshotai', 'MOONSHOTAI_API_KEY'], + ['moonshotai-cn', 'MOONSHOTAI_CN_API_KEY'], + ['google-vertex', 'GOOGLE_VERTEX_API_KEY'], + ['constructor', 'CONSTRUCTOR_API_KEY'], +])('stores a typed key for route %s under a reference derived from the route id', (provider, ref) => { + expect(deriveKeyRef(provider)).toBe(ref) +}) + +it('carries the endpoint and native authentication the adapter reports onto the row', () => { + const nativeAuth = { env: ['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY'], oauth: true } + expect(joinProviderDirectory([], [{ + provider: 'anthropic', displayName: 'anthropic', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'anthropic'], + defaultBaseURL: 'https://api.anthropic.com', nativeAuth, + }])).toEqual([{ + provider: 'anthropic', displayName: 'anthropic', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'anthropic'], + active: false, defaultBaseURL: 'https://api.anthropic.com', nativeAuth, + }]) +}) it.each([false, true])('retains configuration diagnostics when the route is active: %s', (active) => { expect(joinProviderDirectory(active ? [{ id: 'openai', name: 'openai' }] : [], [{ @@ -439,24 +460,23 @@ describe('edge joins', () => { expect(state.rows[0]?.derivedCredential).toMatchObject({ configured: true }) }) - it('surfaces a settings describe failure', async () => { - const { ctx, mirror } = api({ describeSettings: () => Promise.resolve(remoteFail('settings down')) }) + it('recovers the provider directory when an initial settings failure is retried', async () => { + let settingsCall = 0 + const { ctx, mirror } = api({ + describeSettings: () => Promise.resolve(++settingsCall === 1 + ? remoteFail('settings down') + : remoteOk({ writable: true, hasDocument: false, namespaces: NAMESPACES })), + }) const store = new ModelsSettingsStore(ctx, settingsSchema, mirror) await store.load() expect(store.store.getSnapshot()).toMatchObject({ status: 'error', error: 'settings down' }) - }) - - it('reports a terminally unavailable settings mirror precisely', async () => { - const { ctx } = api() - const store = new ModelsSettingsStore( - ctx, - settingsSchema, - new SettingsDescribeMirror(ctx, 'memory'), - ) await store.load() - expect(store.store.getSnapshot()).toMatchObject({ - status: 'error', - error: 'settings are unavailable in this browser', + const state = store.store.getSnapshot() + expect(state).toMatchObject({ status: 'ready', error: null, writable: true }) + expect(state.rows.find(row => row.entry.provider === 'openai')).toMatchObject({ + configured: true, + apiKeyEnv: 'OPENAI_API_KEY', + credential: { configured: true, writable: true }, }) }) diff --git a/packages/client/ui-settings-models/tests/welcome-notice.client.spec.tsx b/packages/client/ui-settings-models/tests/welcome-notice.client.spec.tsx index 82794a042c..107266f082 100644 --- a/packages/client/ui-settings-models/tests/welcome-notice.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/welcome-notice.client.spec.tsx @@ -2,7 +2,7 @@ import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' -import { bindSnapshotSelector, RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import { allowAllAccess, bindSnapshotSelector, RemoteError } from '@deepseek-ai/dsh-client-test-runtime' import { Context } from '@deepseek-ai/cordis' import { SettingsSchemaService } from '@deepseek-ai/dsh-client-ui-settings/src/client/schema.ts' import { SettingsDescribeMirror } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-mirror.ts' @@ -81,7 +81,6 @@ function mount( ctx, { namespace: WELCOME_NOTICE_SETTINGS_NAMESPACE, decode: decodeWelcomeSection }, mirror, - 'host', schemaService, ) const controller = new WelcomeNoticeStore(scope) @@ -96,6 +95,7 @@ function mount( useSessionStatus, usePanelInfo, useSessionRetainInfo: () => undefined, useResource, useWorkspaces: unusedHook, + ...allowAllAccess, controller, useWelcome: bindSnapshotSelector(controller.store), t: key => zh[key], diff --git a/packages/client/ui-settings-models/tests/welcome-store.client.spec.ts b/packages/client/ui-settings-models/tests/welcome-store.client.spec.ts index ba0e2d16ca..f03d23b912 100644 --- a/packages/client/ui-settings-models/tests/welcome-store.client.spec.ts +++ b/packages/client/ui-settings-models/tests/welcome-store.client.spec.ts @@ -3,8 +3,9 @@ import { Context } from '@deepseek-ai/cordis' import { SettingsSchemaService } from '@deepseek-ai/dsh-client-ui-settings/src/client/schema.ts' import { SettingsDescribeMirror } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-mirror.ts' import { ConfigFormController } from '@deepseek-ai/dsh-client-ui-settings/src/client/config-form.ts' -import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' -import { decodeWelcomeSection, WelcomeNoticeStore } from '../src/client/welcome-store.ts' +import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' +import { apply as applySettings, inject as settingsInject } from '@deepseek-ai/dsh-client-ui-settings/client' +import { decodeWelcomeSection, WelcomeNoticeStore, type WelcomeSection } from '../src/client/welcome-store.ts' import { WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE, WELCOME_NOTICE_VERSION, } from '../src/onboarding-copy.ts' @@ -26,7 +27,7 @@ function rejected(message: string) { function namespace(value: unknown = {}, revision = 0) { return { ns: WELCOME_NOTICE_SETTINGS_NAMESPACE, - schema: {}, + schema: { type: 'object', dict: { [WELCOME_NOTICE_ACK_FIELD]: { type: 'string', meta: {} } } }, value, autoGenerate: true, applies: 'live' as const, secrets: [], @@ -41,36 +42,19 @@ function acknowledgedNamespace(version: string, revision = 1) { /** The welcome store over a real mirror-derived scope and a fake wire. */ function buildWelcome( api: { describe?: ReturnType; mutate?: ReturnType }, - persistence: 'host' | 'memory' = 'host', ) { const ctx = { remote: { settings: api } } as never - const mirror = new SettingsDescribeMirror(ctx, persistence) + const mirror = new SettingsDescribeMirror(ctx) const scope = new ConfigFormController( ctx, { namespace: WELCOME_NOTICE_SETTINGS_NAMESPACE, decode: decodeWelcomeSection }, mirror, - persistence, schemaService, ) return { mirror, controller: new WelcomeNoticeStore(scope) } } describe('WelcomeNoticeStore', () => { - it('acknowledges in memory while Host settings persistence is disabled', async () => { - const describeCall = vi.fn() - const mutate = vi.fn() - const { controller } = buildWelcome({ describe: describeCall, mutate }, 'memory') - - await controller.load() - expect(controller.store.getSnapshot()).toEqual({ status: 'ready', acknowledged: false, error: null }) - await expect(controller.acknowledge()).resolves.toBe(true) - expect(controller.store.getSnapshot()).toEqual({ status: 'ready', acknowledged: true, error: null }) - await controller.load() - expect(controller.store.getSnapshot()).toEqual({ status: 'ready', acknowledged: true, error: null }) - expect(describeCall).not.toHaveBeenCalled() - expect(mutate).not.toHaveBeenCalled() - }) - it('acknowledges only the exact current copy version', async () => { for (const [version, acknowledged] of [ [undefined, false], @@ -108,6 +92,42 @@ describe('WelcomeNoticeStore', () => { expect(describeCall).toHaveBeenCalledTimes(1) }) + it('retains acknowledgement when the settings plugin is recreated', async () => { + let stored = namespace({}, 3) + const ctx = new Context() + new TestRemote(ctx, { + settings: { + describe: vi.fn(async () => ok({ writable: true, hasDocument: false, namespaces: [stored] })), + mutate: vi.fn(async () => { + stored = acknowledgedNamespace(WELCOME_NOTICE_VERSION, 4) + return ok(stored) + }), + }, + }) + const plugin = { inject: [...settingsInject], apply: applySettings } + let controller: WelcomeNoticeStore | undefined + try { + const first = ctx.plugin(plugin) + await first.await() + await ctx.configForms.describe().ensure() + controller = new WelcomeNoticeStore( + ctx.configForms.get(WELCOME_NOTICE_SETTINGS_NAMESPACE)) + await controller.load() + await expect(controller.acknowledge()).resolves.toBe(true) + controller.dispose() + await first.dispose() + await ctx.plugin(plugin).await() + await ctx.configForms.describe().ensure() + controller = new WelcomeNoticeStore( + ctx.configForms.get(WELCOME_NOTICE_SETTINGS_NAMESPACE)) + await controller.load() + expect(controller.store.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: true }) + } finally { + controller?.dispose() + await ctx.fiber.dispose() + } + }) + it('keeps the notice pending while the settings read has not answered', async () => { const describeCall = vi.fn(() => Promise.reject(new Error('offline'))) const { mirror, controller } = buildWelcome({ describe: describeCall }) 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 79657293be..19e37172f5 100644 --- a/packages/client/ui-settings-plugin-inventory/package.json +++ b/packages/client/ui-settings-plugin-inventory/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-plugin-inventory", "description": "Read-only Cordis Loader inventory tab in Web Plugins settings", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -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 ? (