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-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-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-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-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..f12b7ff463 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,8 +12,8 @@ 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 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..ccb70a68ab 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. 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..c75bc1c411 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 条件导出仍是不同入口;运行时解析不会合并包的双重实现。 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-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/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-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/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/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 fa6ebb70a1..b37a1ca4ba 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. diff --git a/.agents/skills/dsh-code-review/SKILL.md b/.agents/skills/dsh-code-review/SKILL.md index e75ca07744..ff242b4819 100644 --- a/.agents/skills/dsh-code-review/SKILL.md +++ b/.agents/skills/dsh-code-review/SKILL.md @@ -7,10 +7,17 @@ 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. @@ -33,7 +40,7 @@ description: Use when reviewing a pull request in the deepseek-harness repo — - **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. - **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.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. +- **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-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-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/workflows/build-exe-for-python-sdk.yml b/.github/workflows/build-exe-for-python-sdk.yml index 9ea51311b6..2d4d3f59f6 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' diff --git a/AGENTS.md b/AGENTS.md index c29ff51cff..f1bfcf9aeb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -150,6 +150,7 @@ Real-API tests/demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, and - **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)). @@ -162,7 +163,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/apps/cli/package.json b/apps/cli/package.json index e7291abcc7..b841d617f0 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" }, 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/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 2d82f686ea..783cd52d85 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/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 apps/desktop/README.md /deepseek-harness-desktop: - en: 001b7d11c237078b - zh: eda6b580dc224c7f + en: 5b8518fd5e0030ef + zh: 02efee59c39647dc /deepseek-harness-desktop/terminal-command: en: bef92953c237363f zh: d21d6effd21b8c00 @@ -15,8 +15,8 @@ en: 069fdfd72d2ea26a zh: 76ae549d43c99bb4 /deepseek-harness-desktop/key-technical-decisions/bundled-workspace-dependencies: - en: 0f9b6c1d6761d108 - zh: 77127063f244c361 + en: 1a3023b9ca699757 + zh: 45ebed9f64fa4e32 /deepseek-harness-desktop/bundled-command-runtime: en: 09f0b75af9f0ed14 zh: 60bbc2e67d5e87a8 @@ -51,8 +51,8 @@ en: 5f05072ec82cc62d zh: a3d63b58d1ef2db7 /deepseek-harness-desktop/package/runtime-file-selection: - en: e7c1eb8e78fe46e3 - zh: b7ea497dd75be524 + en: 66898d7b99807291 + zh: dfbbbb607ad2709f /deepseek-harness-desktop/package/upload-updates: en: f48baa680e841b0d zh: 25ded1aeaac6dad1 @@ -66,8 +66,8 @@ en: 64836513eb7eda6e zh: 6ebb9184a7aa51de /deepseek-harness-desktop/package/desktop-runtime-preparation: - en: 32ef30fc38462109 - zh: 093b1b57d084f5bb + en: 9a71990bee9867a7 + zh: 76c5c1fdff6e6908 /deepseek-harness-desktop/updates: en: 41d0f50eb7173342 zh: ce940ef3cbcc6fa5 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index c9d14c4511..c43ff167a8 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -12,7 +12,7 @@ The first application-menu command, **About DeepSeek Harness**, opens Electron's 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. @@ -70,7 +70,9 @@ The payload follows the Desktop release. `runtime.json` records the Desktop vers The private Desktop `runtime/bin` directory is added only to package-installation processes, not the Host PATH inherited by PTC and agent shells. This tool does not change PATH, environment variables or user package-manager configuration. pnpm retains its own defaults and user settings for global packages, executable entries and its store, including native errors when the environment does not support global installation. There is no separate dependency updater. [The primary-runtime decision](../../.agents/notes/implemented/feature/2026-09-14-desktop-primary-runtime.md) records these choices. -Node prepares the bundled interpreters and Python libraries without a system Python or pip. [The download lock](../../scripts/primary-runtime/lock.json) pins interpreter archives, Python distribution versions and target-specific wheel URLs and hashes; the shared builder resolves pnpm from the root development dependency pin. The root package-manager version and the Desktop pin are checked for agreement. Wheel filenames and distribution versions must agree for every target. Preserve key order within the selected target, wheel records and distribution map, plus wheel-entry order; these affect payload identity, while top-level lock key order does not. Library wheels unpack into site-packages, retaining auxiliary files under each wheel's `.data/scripts` directory without generating command wrappers. Other installation schemes are rejected. Native-target checks verify the locked wheel set and versions, permit the interpreter's bundled pip, and check the Python version, Office document read/write operations and dependency completeness without writing bytecode after staging cleanup and again after macOS signing. The standalone Node executable receives the JIT entitlement required by V8; the x64 target also receives `com.apple.security.cs.allow-unsigned-executable-memory` for executable code pages, including under Rosetta. ARM64 Node and Office helpers retain JIT-only permissions. Cross-target execution and signed installation require the target release host. Both `dev:desktop` and `start:desktop` prepare `.desktop-build/targets//runtime/primary-runtime` before launching Electron; first use may download locked dependencies. An unfinished preparation cannot report a successful launcher exit. +Node prepares the bundled interpreters and Python libraries without a system Python or pip. [The download lock](../../scripts/primary-runtime/lock.json) pins interpreter archives, Python distribution versions and target-specific wheel URLs and hashes; the shared builder resolves pnpm from the root development dependency pin. The root package-manager version and the Desktop pin are checked for agreement. Wheel filenames and distribution versions must agree for every target. Preserve key order within the selected target, wheel records and distribution map, plus wheel-entry order; these affect payload identity, while top-level lock key order does not. Library wheels unpack into site-packages, retaining auxiliary files under each wheel's `.data/scripts` directory without generating command wrappers. Other installation schemes are rejected. macOS signs the versioned Python executable once, retaining the [two interpreter aliases](../../packages/skill/tool-workspace-dependencies/README.md) in external resources and installed copies. POSIX native-target checks require relative interpreter aliases. All native-target checks exercise command names, child execution and a pip-enabled venv, verify the locked wheel set and versions, permit the interpreter's bundled pip, and check the Python version, Office document read/write operations and dependency completeness without writing bytecode after staging cleanup and again after macOS signing. The standalone Node executable receives the JIT entitlement required by V8; the x64 target also receives `com.apple.security.cs.allow-unsigned-executable-memory` for executable code pages, including under Rosetta. ARM64 Node and Office helpers retain JIT-only permissions. Cross-target execution and signed installation require the target release host. Both `dev:desktop` and `start:desktop` prepare `.desktop-build/targets//runtime/primary-runtime` before launching Electron; first use may download locked dependencies. An unfinished preparation cannot report a successful launcher exit. + +The shared Desktop/SDK runtime builder omits directories named `tests` beneath NumPy and pandas before copying or signing the payload, and removes their rows from each distribution’s `RECORD`. It retains `numpy.testing`, `pandas.testing`, `pandas._testing`, native extensions and licenses. Complete upstream suites are unavailable; native checks verify the retained testing APIs, absence of test directories and existence of recorded files. | Decision | Why | Direct consequence | |---|---|---| @@ -272,7 +274,9 @@ The served `time` is the real packing time, so pnpm 11's default 24-hour `minimu ### Runtime file selection -Desktop packs workspace packages locally and installs external dependencies through the target's bundled Node and pnpm. [Desktop's file policy](scripts/runtime-file-policy.ts) then filters the immutable `resources/app.asar/dsh/node_modules` copy before signing and integrity sealing. It omits TypeScript declarations, recognized JavaScript/CSS/TypeScript source maps, TypeScript build caches, Domino's test directory, selected native compiler outputs, and node-pty prebuilds for other platforms. 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. +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). @@ -443,7 +447,7 @@ Desktop [patch policy](scripts/runtime-patch-policy.ts) explicitly classifies ev 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 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. +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. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index d5c52ebc1b..c09fd062ae 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -12,7 +12,7 @@ Desktop 绑定 `127.0.0.1`,即 Electron 为就绪 URL 与 WebSocket 凭据过 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 功能返回栏下方的视口。 @@ -72,7 +72,9 @@ Desktop 默认注册 `office-docx`、`office-pptx` 和 `office-xlsx`。这些技 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、测试目录已移除,以及清单所列文件存在。 | 决策 | 原因 | 直接结果 | |---|---|---| @@ -274,7 +276,9 @@ pnpm run dev:bundle-registry ### 运行时文件筛选 -Desktop 在本地打包工作区包,并通过目标捆绑的 Node 和 pnpm 安装外部依赖。[Desktop 文件策略](scripts/runtime-file-policy.ts)随后在签名和完整性封装前过滤不可变的 `resources/app.asar/dsh/node_modules` 副本。它排除 TypeScript 声明、已识别的 JavaScript/CSS/TypeScript source map、TypeScript 构建缓存、Domino 测试目录、选定的原生编译器输出和其他平台的 node-pty 预构建文件。它保留运行时 JavaScript、原生模块及其 DLL/EXE 辅助文件、WASM、未知资源、许可证和 notices。依赖清单在完整性封装前经过 electron-builder 的元数据清理,确保归档保持已记录的字节。该策略不修改 npm tarball、捆绑的包管理器或用户安装的插件文件。 +Desktop 在本地打包工作区包,并通过目标捆绑的 Node 和 pnpm 安装外部依赖。[Desktop 文件策略](scripts/runtime-file-policy.ts)随后在签名和完整性封装前过滤不可变的 `resources/app.asar/dsh/node_modules` 副本。它排除 TypeScript 声明、已识别的 JavaScript/CSS/TypeScript source map、TypeScript 构建缓存、Domino 测试目录及 Yarn 开发元数据、选定的原生编译器输出和其他平台的 node-pty 预构建文件。非 Windows 目标还会排除 `node-pty/third_party/conpty`;Windows 目标保留该目录。它保留运行时 JavaScript、目标平台的原生模块及其 DLL/EXE 辅助文件、WASM、未知资源、许可证和 notices。依赖清单在完整性封装前经过 electron-builder 的元数据清理,确保归档保持已记录的字节。该策略不修改 npm tarball、捆绑的包管理器或用户安装的插件文件。 + +[Electron 外壳文件清单](scripts/electron-builder-config.mjs)从单独收集的 `resources/app.asar/node_modules` 依赖中排除已识别的 JavaScript/CSS/TypeScript source map 和 TypeScript 构建缓存。这些排除规则保留运行时代码、原生模块、WASM、数据文件(包括普通 `.map` 资源)、许可证和 notices;[外壳归档测试](tests/shell-file-selection.spec.ts)检查保留文件的字节和排除项。 [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。 @@ -445,7 +449,7 @@ Desktop [补丁策略](scripts/runtime-patch-policy.ts) 将每份工作区补丁 Desktop 依赖 overrides 在补丁策略模块中单独声明,不从补丁版本推导。pi-ai 约束使运行时版本保持在共享补丁已验证的版本。Desktop 仍会在每次构建时重新解析运行时锁文件,再通过 `--frozen-lockfile` 安装;不同构建之间的依赖解析尚不保证可复现。CLI 打包安装测试及其他交付流程保留各自的配置。 -每条打包命令都会构建仓库,打包以 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 沿用已验证的目标描述符,不使用构建宿主的架构。签名安装包、公证、已安装应用升级和各目标原生模块的验收需要发布环境。 +每条打包命令都会构建仓库,打包以 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;配置缺失或不匹配会阻止移入产物,因而也会阻止上传。 diff --git a/apps/desktop/electron-builder.config.d.mts b/apps/desktop/electron-builder.config.d.mts index 4e978ec00f..a4d0739791 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 ['**/*'] }, ] diff --git a/apps/desktop/package.json b/apps/desktop/package.json index fb8cee6fdd..563f60a858 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", @@ -68,7 +68,7 @@ "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", diff --git a/apps/desktop/scripts/electron-builder-config.mjs b/apps/desktop/scripts/electron-builder-config.mjs index f08b783865..747d20d841 100644 --- a/apps/desktop/scripts/electron-builder-config.mjs +++ b/apps/desktop/scripts/electron-builder-config.mjs @@ -135,6 +135,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: ['**/*'] }, 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-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/prepare-dsh.ts b/apps/desktop/scripts/prepare-dsh.ts index e40cac98c4..808b8ae8b5 100644 --- a/apps/desktop/scripts/prepare-dsh.ts +++ b/apps/desktop/scripts/prepare-dsh.ts @@ -43,7 +43,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 } @@ -158,7 +158,7 @@ async function main(): Promise { } if (process.platform === 'darwin' && process.env.DSH_DESKTOP_UNSIGNED !== '1') { await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'sign:dsh-native', () => signMacOSRuntime(DSH_OUTPUT_ROOT, resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env), target.arch, join(BUILD_PATHS.root, 'signature-cache'))) - await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'sign:primary-native', () => signMacOSRuntime(join(RUNTIME_ROOT, 'primary-runtime'), resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env), target.arch, join(BUILD_PATHS.root, 'signature-cache'))) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'sign:primary-native', () => signMacOSRuntime(join(RUNTIME_ROOT, 'primary-runtime'), resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env), target.arch, join(BUILD_PATHS.root, 'signature-cache'), 'primary')) } await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:manifests', () => prepareRuntimeManifests(DSH_OUTPUT_ROOT)) await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:primary-smoke', async () => smokePrimaryRuntime(join(RUNTIME_ROOT, 'primary-runtime'))) diff --git a/apps/desktop/scripts/prepare-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/runtime-file-policy.ts b/apps/desktop/scripts/runtime-file-policy.ts index 1bc16b2a1c..14b0e2a186 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' @@ -34,6 +34,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/smoke-runtime.ts b/apps/desktop/scripts/smoke-runtime.ts index f15f10a928..dec4f8fbc6 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,6 +92,15 @@ 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 { @@ -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/src/main.ts b/apps/desktop/src/main.ts index 38585675b1..1202670a3e 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -155,7 +155,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 } 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/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 f9b6ca9279..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') @@ -162,7 +136,7 @@ try { const builtin = requireRuntime('node-addon-require-builtin') assert.equal(typeof builtin.requireBuiltin('internal/modules/esm/loader').getOrInitializeCascadedLoader, 'function') console.error('runtime payload: pnpm') - checkPnpm() + await checkPnpm(resourcesRuntime) console.error('runtime payload: koffi') checkKoffi() console.error('runtime payload: sharp') 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/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.spec.ts b/apps/desktop/tests/macos-signature.spec.ts index d39ee99cb9..186b597b07 100644 --- a/apps/desktop/tests/macos-signature.spec.ts +++ b/apps/desktop/tests/macos-signature.spec.ts @@ -93,9 +93,9 @@ describe('desktop macOS release signature', () => { 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', diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index fff39c38ef..d9a8f3103b 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -443,6 +443,21 @@ 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') diff --git a/apps/desktop/tests/runtime-file-policy.spec.ts b/apps/desktop/tests/runtime-file-policy.spec.ts index 76f5c8d95e..ed478b42f6 100644 --- a/apps/desktop/tests/runtime-file-policy.spec.ts +++ b/apps/desktop/tests/runtime-file-policy.spec.ts @@ -27,6 +27,8 @@ it('omits development artifacts while preserving executable modules, assets and 'node-pty/prebuilds/win32-x64/conpty.pdb', '@koromix/koffi-win32-x64/win32_x64/koffi.lib', '@mixmark-io/domino/test/entities.html', + '@mixmark-io/domino/.yarn/plugins/@yarnpkg/plugin-version.cjs', + '@mixmark-io/domino/.yarn/versions/release.yml', '@deepseek-ai/libreoffice-kit-wasm/assets/soffice.data', '@deepseek-ai/libreoffice-kit-darwin-arm64/bin/libreoffice-kit', '.modules.yaml', '.pnpm-workspace-state-v1.json', '.bin/tool', '.pnpm/cache', @@ -45,6 +47,8 @@ it('omits development artifacts while preserving executable modules, assets and 'node-pty/third_party/conpty/win10-x64/OpenConsole.exe', '@koromix/koffi-win32-x64/win32_x64/koffi.node', '@mixmark-io/domino/lib/HTMLParser.js', '@mixmark-io/domino/lib/EntityParser.js', + '@mixmark-io/domino/LICENSE', '@mixmark-io/domino/package.json', + 'example/.yarn/runtime.cjs', '@mixmark-io/domino/.yarn-data.json', '@img/sharp-win32-x64/lib/libvips-42.dll', '@deepseek-ai/libreoffice-kit-win32-x64/bin/libreoffice-kit.exe', '@deepseek-ai/libreoffice-kit-win32-x64/sources/core-source.json', @@ -73,6 +77,8 @@ it('omits development artifacts while preserving executable modules, assets and it('applies package-specific rules inside scoped and nested dependency containers', () => { expect(desktopRuntimeFileExclusion('outer/node_modules/@mixmark-io/domino/test/data.html', windows, 'win32-x64')).toBeDefined() + expect(desktopRuntimeFileExclusion('outer/node_modules/@mixmark-io/domino/.yarn/plugin.cjs', windows, 'win32-x64')).toBeDefined() + expect(desktopRuntimeFileExclusion('@mixmark-io/domino/.yarn', windows, 'win32-x64')).toBeDefined() expect(desktopRuntimeFileExclusion('outer\\node_modules\\node-pty\\prebuilds\\win32-arm64\\conpty.node', windows, 'win32-x64')).toBeDefined() expect(desktopRuntimeFileExclusion('outer/node_modules/unrelated/test/data.html', windows, 'win32-x64')).toBeUndefined() expect(desktopRuntimeFileExclusion('outer/fs-ext/build/Release/fs_ext.lib', windows, 'win32-x64')).toBeUndefined() @@ -85,6 +91,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/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/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 f44baf5c4c..0b44c5cd00 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" }, 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/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/chat-scroll-contract.e2e.ts b/apps/web/tests/chat-scroll-contract.e2e.ts index a7b5bc4b7a..955d251ab7 100644 --- a/apps/web/tests/chat-scroll-contract.e2e.ts +++ b/apps/web/tests/chat-scroll-contract.e2e.ts @@ -6,15 +6,15 @@ import { access, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import type { Browser, Page } from 'playwright' +import type { Browser, Page, Route } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import type { StreamChunk } from '@deepseek-ai/dsh-llm' -import { ToolCallId } from '@deepseek-ai/dsh-llm' +import { ToolCallId, createAssistantMessage, createUserMessage } from '@deepseek-ai/dsh-llm' import type { AssistantStreamFrame } from '@deepseek-ai/dsh-agent' import type { ReplayEntry, ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay' import type { SessionEvent } from '@deepseek-ai/dsh-session' -import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session' import { createChatScrollFixture, type ChatScrollFixture } from './chat-scroll-fixture.ts' import { launchWebScaffold, @@ -28,7 +28,7 @@ import { expandOwningTurnProcess, newEnglishPage, openSettings, saveFailureShot const MODE = webSnapshotMode() const HISTORY_SESSION_ID = 'chat-scroll-history-e2e' -const TOOL_SESSION_ID = 'chat-scroll-tool-e2e' +const TOOL_SESSION_ID = SessionId('chat-scroll-tool-e2e') const RESTORE_SESSION_A_ID = 'chat-scroll-restore-a-e2e' const RESTORE_SESSION_B_ID = 'chat-scroll-restore-b-e2e' const REPLAY_CONTEXT_WINDOW = 10_000_000 @@ -47,7 +47,7 @@ const TOOL_READY_FILE = '.chat-scroll-tool-ready' const TOOL_RELEASE_FILE = '.chat-scroll-tool-release' const INPUTS_SESSION_ID = 'chat-scroll-inputs-e2e' const RAIL_SESSION_ID = 'chat-scroll-rail-e2e' -const FLING_SESSION_ID = 'chat-scroll-fling-e2e' +const FLING_SESSION_ID = SessionId('chat-scroll-fling-e2e') const LIVE_FLING_PROMPT = 'CHAT_SCROLL_FLING_USER Keep streaming while I fling back through older output.' const LIVE_FLING_FIRST = 'CHAT_SCROLL_FLING_STREAM_FIRST' const LIVE_FLING_DONE = 'CHAT_SCROLL_FLING_STREAM_DONE' @@ -74,6 +74,22 @@ const INPUTS_FIXTURE = createChatScrollFixture({ title: 'CHAT_SCROLL_INPUTS non-wheel reader input session', }) +interface FoldMotionSample { + readonly t: number + readonly ordinaryGrowth: boolean + readonly top: number + readonly bodyY: number + readonly earlierY: number + readonly messageY: number | null + readonly stepY: number | null + readonly flowHeight: number + readonly height: number + readonly spacer: number + readonly folding: boolean + readonly raceApplied: boolean + readonly composerTop: number +} + interface ScrollGeometry { readonly distanceFromBottom: number readonly scrollTop: number @@ -95,6 +111,8 @@ interface ScrollWorld { interface ScrollWorldOptions { readonly failureShot: string + /** Install a controllable browser clock before boot; omitted worlds use real time. */ + readonly controlledClock?: boolean readonly paceMs?: number readonly replay?: ReplayOverrideDoc readonly seeds: readonly { fixture: ChatScrollFixture; id: string }[] @@ -190,6 +208,7 @@ async function launchScrollWorld(options: ScrollWorldOptions): Promise { events.push(event) }) scaffold.ctx.on('agent/assistant-stream', ({ frame }) => { assistantFrames.push(frame) }) page = await newEnglishPage(browser, 900) + if (options.controlledClock) await page.clock.install() const tripwire = watchConsole(page) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) @@ -525,115 +544,674 @@ describe('web e2e: long Chat scroll contract', () => { await browser?.close() }) - it.skipIf(MODE === 'record')('merges a large process fold with new-input following without returning downward', async () => { - const fixture = createChatScrollFixture({ markerPrefix: 'FOLD', title: 'CHAT_FOLD_INPUT', turns: 8 }) - const input = 'CHAT_FOLD_NEXT_INPUT' - const artifactRoot = fileURLToPath(new URL('../../../.artifacts/fold-input-e2e/', import.meta.url)) - await mkdir(artifactRoot, { recursive: true }) - const evidence = await mkdtemp(join(artifactRoot, 'run-')) + 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: 'web-e2e-fold-input-motion', - replay: [replayEntry(textStream('CHAT_FOLD_REPLY', 'CHAT_FOLD_DONE', 2))], - seeds: [{ fixture, id: 'chat-fold-input-e2e' }], + 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' }) - await openSeed(page, fixture, fixture.markers.assistant(8)) - await openSettings(page, 'en') - await page.getByRole('dialog', { name: 'Settings', exact: true }) - .getByText('When to Collapse Work Details', { exact: true }).locator('../..') - .getByRole('button', { name: 'On completion', exact: true }).click() - await page.getByRole('menuitem', { name: 'On next message', exact: true }).click() - await page.keyboard.press('Escape') - for (const index of [1, 2]) { - const row = page.locator(`[data-chat-call-id="chat-scroll-008-${index}"] [data-sample="bash"]`) - await row.click() - await expect.poll(() => row.getAttribute('aria-expanded')).toBe('true') - } - await wheelTranscript(page, -600) - await page.getByRole('button', { name: 'Back to bottom', exact: true }).click() - await expectBottom(page) - const beforeHeight = await page.locator('[data-chat-flow]:has(> [data-slot="conversation.chat.flow"])') - .evaluate(element => element.getBoundingClientRect().height) - const release = holdTextAfter(world, 0) - const trace = page.evaluate(marker => new Promise<{ - readonly t: number - readonly top: number - readonly messageY: number - readonly columnHeight: number - readonly spacer: number - readonly folding: boolean - }[]>((resolve) => { - const host = document.querySelector('[data-conversation-scroll]')! - const column = host.querySelector('[data-chat-flow]:has(> [data-slot="conversation.chat.flow"])')! - const samples: { t: number; top: number; messageY: number; columnHeight: number; spacer: number; folding: boolean }[] = [] - let frame = 0 - let timer = 0 - const sample = (): void => { - const message = Array.from(column.querySelectorAll('*')) - .find(element => element.children.length === 0 && element.textContent === marker) - if (message === undefined) return - samples.push({ t: performance.now(), top: host.scrollTop, messageY: message.getBoundingClientRect().top, - columnHeight: column.getBoundingClientRect().height, - spacer: Number.parseFloat(host.querySelector('[data-chat-turn-spacer]')?.style.height ?? '') || 0, - folding: column.querySelector('[data-chat-motion="collapse"]') !== null }) + const 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() }) } - const tick = (): void => { - timer = window.setTimeout(() => { sample(); frame = requestAnimationFrame(tick) }, 0) - } - host.addEventListener('dsh-test-fold-stop', () => { - cancelAnimationFrame(frame) - window.clearTimeout(timer) - sample() - host.removeAttribute('data-fold-probe-ready') - resolve(samples) - }, { once: true }) - host.setAttribute('data-fold-probe-ready', '') - frame = requestAnimationFrame(tick) - }), input) - await page.locator('[data-fold-probe-ready]').waitFor() - let settled: ReturnType | undefined - try { - await page.locator('[data-composer-input][contenteditable="true"]').last().fill(input) - await page.getByRole('button', { name: 'Send message', exact: true }).click() - settled = world.scaffold.whenTurnSettled(30_000) - await page.getByText(input, { exact: true }).waitFor() - await expect.poll(() => page.locator('[data-chat-motion="collapse"]').count()).toBe(0) - await expectBottom(page) + 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 { - await page.locator('[data-conversation-scroll]').evaluate(host => host.dispatchEvent(new Event('dsh-test-fold-stop'))) + const settled = replyStarted ? world.scaffold.whenTurnSettled() : undefined release() await settled } - const samples = await trace - expect(samples.length).toBeGreaterThan(4) - const first = samples[0]! - let minimum = first.messageY - let reversal = 0 - let maximumScroll = first.top - let viewportBacktrack = 0 - for (const sample of samples) { - minimum = Math.min(minimum, sample.messageY) - if (first.messageY - minimum > 4) reversal = Math.max(reversal, sample.messageY - minimum) - maximumScroll = Math.max(maximumScroll, sample.top) - viewportBacktrack = Math.max(viewportBacktrack, maximumScroll - sample.top) - } - const last = samples.at(-1)! - const afterHeight = last.columnHeight - await writeFile(join(evidence, 'motion.json'), JSON.stringify({ beforeHeight, afterHeight, reversal, viewportBacktrack, samples }, null, 2)) - await page.screenshot({ path: join(evidence, 'settled.png') }) - console.log(`fold-input e2e: message reversal=${reversal}px, viewport backtrack=${viewportBacktrack}px, spacer=${last.spacer}px, evidence=${evidence}`) - expect(beforeHeight - afterHeight).toBeGreaterThan(250) - expect(first.messageY - minimum).toBeGreaterThan(40) - expect(reversal).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) - expect(viewportBacktrack).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) - expect(Math.abs(last.spacer - (beforeHeight - afterHeight))).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) - await expectBottom(page) assertClean(world) }) - }, 180_000) + }) + + 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({ @@ -1017,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 { @@ -1249,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/composer-focus.e2e.ts b/apps/web/tests/composer-focus.e2e.ts new file mode 100644 index 0000000000..85de7c7346 --- /dev/null +++ b/apps/web/tests/composer-focus.e2e.ts @@ -0,0 +1,132 @@ +/** 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() + await page.keyboard.insertText('alpha beta gamma') + 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))}`) + } + + 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/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index 52a3fd09a3..b6ec46c361 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -96,14 +96,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/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 7275ed50b2..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 @@ -2,7 +2,7 @@ - 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/preferences.expected.md b/apps/web/tests/expected/cot-translation/preferences.expected.md index f4735cc02e..14f544b50b 100644 --- a/apps/web/tests/expected/cot-translation/preferences.expected.md +++ b/apps/web/tests/expected/cot-translation/preferences.expected.md @@ -2,7 +2,7 @@ - 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/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/menu-material/session-menu.expected.md b/apps/web/tests/expected/menu-material/session-menu.expected.md index 88405f3950..ebb1786386 100644 --- a/apps/web/tests/expected/menu-material/session-menu.expected.md +++ b/apps/web/tests/expected/menu-material/session-menu.expected.md @@ -3,3 +3,4 @@ - menuitem "Rename" - menuitem "Fork session" - menuitem "Archive session" + - menuitem "Copy Session ID" diff --git a/apps/web/tests/expected/navigation-panes/command-wrap.expected.md b/apps/web/tests/expected/navigation-panes/command-wrap.expected.md new file mode 100644 index 0000000000..cafac4c6df --- /dev/null +++ b/apps/web/tests/expected/navigation-panes/command-wrap.expected.md @@ -0,0 +1,14 @@ +[ + { + "colorScheme": "light", + "wrapped": true, + "text": "echo NAVIGATION_OK", + "copiedText": "echo NAVIGATION_OK" + }, + { + "colorScheme": "dark", + "wrapped": true, + "text": "echo NAVIGATION_OK", + "copiedText": "echo NAVIGATION_OK" + } +] diff --git a/apps/web/tests/expected/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/seeded-history/blank-reasoning.expected.md b/apps/web/tests/expected/seeded-history/blank-reasoning.expected.md new file mode 100644 index 0000000000..ab493a1aff --- /dev/null +++ b/apps/web/tests/expected/seeded-history/blank-reasoning.expected.md @@ -0,0 +1,4 @@ +- button "Think" [expanded] +- paragraph: The user wants me to read a.txt and b.txt, then reply with "DONE". Let me do both reads in parallel. + +- Reasoning rows: 1 diff --git a/apps/web/tests/expected/settings-chrome/plugin-instances.expected.md b/apps/web/tests/expected/settings-chrome/plugin-instances.expected.md index b4584b0486..239b4855e7 100644 --- a/apps/web/tests/expected/settings-chrome/plugin-instances.expected.md +++ b/apps/web/tests/expected/settings-chrome/plugin-instances.expected.md @@ -1,18 +1,20 @@ - list: - listitem: - - button "tool-subagent-control, 已启用": - - strong: tool-subagent-control - - text: Globally named send_message, interrupt_agent, and list_agents tools over ctx.subagents continuations + - button "子智能体控制工具, tool-subagent-control, 已启用": + - strong: 子智能体控制工具 + - text: 让 AI 向子智能体发送消息或中断其运行。 + - code: tool-subagent-control - listitem: - - button "tool-subagent-control/list-agents, tool-subagent-list-agents, 已启用": - - strong: tool-subagent-control/list-agents + - button "子智能体列表工具, tool-subagent-list-agents, 已启用": + - strong: 子智能体列表工具 - code: tool-subagent-list-agents - listitem: - - button "tool-subagent, 已启用": - - strong: tool-subagent - - text: Model-facing subagent delegation tool over the ctx.subagents seam + - button "子智能体委派工具, tool-subagent, 已启用": + - strong: 子智能体委派工具 + - text: 让 AI 将任务交给子智能体,并获取运行结果。 + - code: tool-subagent - listitem: - - button "tool-subagent, tool-subagent-fork, 已启用": - - strong: tool-subagent - - text: Model-facing subagent delegation tool over the ctx.subagents seam + - button "子智能体委派工具, tool-subagent-fork, 已启用": + - strong: 子智能体委派工具 + - text: 让 AI 将任务交给子智能体,并获取运行结果。 - code: tool-subagent-fork diff --git a/apps/web/tests/expected/settings-chrome/plugins.expected.md b/apps/web/tests/expected/settings-chrome/plugins.expected.md index 20e096a308..22b5bc2c80 100644 --- a/apps/web/tests/expected/settings-chrome/plugins.expected.md +++ b/apps/web/tests/expected/settings-chrome/plugins.expected.md @@ -1,4 +1,5 @@ - listitem: - - button "tool-subagent, 已启用": - - strong: tool-subagent - - text: Model-facing subagent delegation tool over the ctx.subagents seam + - button "子智能体委派工具, tool-subagent, 已启用": + - strong: 子智能体委派工具 + - text: 让 AI 将任务交给子智能体,并获取运行结果。 + - code: tool-subagent diff --git a/apps/web/tests/expected/shell-command-details/background-long-token.expected.md b/apps/web/tests/expected/shell-command-details/background-long-token.expected.md new file mode 100644 index 0000000000..c9e1765740 --- /dev/null +++ b/apps/web/tests/expected/shell-command-details/background-long-token.expected.md @@ -0,0 +1,3 @@ +- button "Bash Start the diagnostic worker" [expanded] +- text: {{workspace}} node ./scripts/start-worker.mjs --workspace=/tmp/diagnostics/long-workspace-name-for-background-command-details --log-level=debug --trace-tag=background-shell-full-command-selection --include=worker,lifecycle,transport,subscriptions --output=/tmp/diagnostics/background-worker.log --token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +- button "Inspect" diff --git a/apps/web/tests/expected/shell-command-details/background.expected.md b/apps/web/tests/expected/shell-command-details/background.expected.md index ffc21b3098..1b579bfa11 100644 --- a/apps/web/tests/expected/shell-command-details/background.expected.md +++ b/apps/web/tests/expected/shell-command-details/background.expected.md @@ -1,5 +1,3 @@ - button "Bash Start the diagnostic worker" [expanded] -- text: IN -- group "Command arguments": "{ \"command\": \"node ./scripts/start-worker.mjs --workspace=/tmp/diagnostics/long-workspace-name-for-background-command-details --log-level=debug --trace-tag=background-shell-full-command-selection --include=worker,lifecycle,transport,subscriptions --output=/tmp/diagnostics/background-worker.log\", \"description\": \"Start the diagnostic worker\", \"run_in_background\": true }" -- text: OUT started background job bash-1 +- text: {{workspace}} node ./scripts/start-worker.mjs --workspace=/tmp/diagnostics/long-workspace-name-for-background-command-details --log-level=debug --trace-tag=background-shell-full-command-selection --include=worker,lifecycle,transport,subscriptions --output=/tmp/diagnostics/background-worker.log - button "Inspect" diff --git a/apps/web/tests/expected/shell-command-details/foreground-multiline.expected.md b/apps/web/tests/expected/shell-command-details/foreground-multiline.expected.md new file mode 100644 index 0000000000..05fadfea88 --- /dev/null +++ b/apps/web/tests/expected/shell-command-details/foreground-multiline.expected.md @@ -0,0 +1,5 @@ +- button "Bash Start the diagnostic worker" [expanded] +- text: Done {{workspace}} node ./scripts/start-worker.mjs --workspace=/tmp/diagnostics/long-workspace-name-for-background-command-details --log-level=debug --trace-tag=background-shell-full-command-selection --include=worker,lifecycle,transport,subscriptions --output=/tmp/diagnostics/background-worker.log --token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx $ echo done +- button "Copy" +- text: done +- button "Inspect" diff --git a/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md b/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md index 88405f3950..ebb1786386 100644 --- a/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md +++ b/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md @@ -3,3 +3,4 @@ - menuitem "Rename" - menuitem "Fork session" - menuitem "Archive session" + - menuitem "Copy Session ID" diff --git a/apps/web/tests/fixtures/plugins/fixture-live-client/client.js b/apps/web/tests/fixtures/plugins/fixture-live-client/client.js index 6a6f8b9777..7736cb2949 100644 --- a/apps/web/tests/fixtures/plugins/fixture-live-client/client.js +++ b/apps/web/tests/fixtures/plugins/fixture-live-client/client.js @@ -89,7 +89,7 @@ window.__ModuleLoader__.load({ ) }) ctx.slots.inject('sidebar.workspaces.session.menu.item', function* () { - // The shipped rows end at archive (400); these follow as one group, + // The shipped rows end at Session ID (450); these follow as one group, // opened by the export row's hairline. yield registerSessionAction('fixture.export-session', 500, 'exportSession', true) yield registerSessionAction('fixture.copy-session-id', 600, 'copySessionId', false) diff --git a/apps/web/tests/katex-fonts.spec.ts b/apps/web/tests/katex-fonts.spec.ts new file mode 100644 index 0000000000..1e7d2f47c5 --- /dev/null +++ b/apps/web/tests/katex-fonts.spec.ts @@ -0,0 +1,75 @@ +import { readFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { transform } from 'lightningcss' +import { build, loadConfigFromFile } from 'vite' +import { expect, it, onTestFinished } from 'vitest' + +const require = createRequire(new URL('../../../packages/client/ui-primitives/package.json', import.meta.url)) +const stylesheet = require.resolve('katex/dist/katex.min.css') + +/** Build a stylesheet with the application's asset plugins without writing artifacts. */ +async function bundleStyle(source: { path: string } | { package: string; css: string }) { + const root = await mkdtemp(join(tmpdir(), 'katex-fonts-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + let input: string + if ('path' in source) input = source.path + else { + input = join(root, 'node_modules', source.package, 'dist', 'katex.min.css') + await mkdir(dirname(input), { recursive: true }) + await writeFile(input, source.css) + await writeFile(join(dirname(input), 'font.woff'), 'fixture font') + } + const loaded = await loadConfigFromFile({ command: 'build', mode: 'production' }, fileURLToPath(new URL('../vite.config.ts', import.meta.url))) + if (!loaded) throw new Error('Expected the Web build configuration') + // The product isolation check requires the full application's HTML entry. + const plugins = (loaded.config.plugins ?? []).flat().filter(plugin => !(plugin && typeof plugin === 'object' + && 'name' in plugin && plugin.name === 'dsh-product-web-bundle-isolation')) + const result = await build({ + ...loaded.config, configFile: false, plugins, + root, logLevel: 'silent', + build: { write: false, cssMinify: false, assetsInlineLimit: 0, rollupOptions: { input } }, + }) + if ('on' in result) throw new Error('Expected a completed build') + return (Array.isArray(result) ? result : [result]).flatMap(bundle => bundle.output) +} + +/** Normalize layout CSS independently of emitted font URLs and format fallbacks. */ +function layoutCss(css: string): string { + return transform({ + filename: 'layout.css', code: Buffer.from(css), minify: true, + visitor: { Rule: { 'font-face'(rule) { + rule.value.properties = rule.value.properties.filter(property => property.type !== 'source') + return rule + } } }, + }).code.toString() +} + +it('ships all KaTeX WOFF2 faces with identical font bytes and layout styles', async () => { + const output = await bundleStyle({ path: stylesheet }) + const fonts = output.filter(asset => asset.type === 'asset' && /\.(?:woff2?|ttf)$/u.test(asset.fileName)) + expect(fonts).toHaveLength(20) + for (const font of fonts) { + expect(font.fileName).toMatch(/\.woff2$/u) + if (font.type !== 'asset') throw new Error('Expected a font asset') + const name = font.names[0]! + expect(Buffer.from(font.source)).toEqual(await readFile(join(dirname(stylesheet), 'fonts', name))) + } + const css = output.find(asset => asset.type === 'asset' && asset.fileName.endsWith('.css')) + if (css?.type !== 'asset') throw new Error('Expected a stylesheet asset') + const text = Buffer.from(css.source).toString() + expect(text).not.toMatch(/\.(?:woff|ttf)["')]/u) + expect(layoutCss(text)).toBe(layoutCss(await readFile(stylesheet, 'utf8'))) +}) + +it.each(['src: url(font.woff) format("woff");', ''])('rejects a KaTeX face without WOFF2 (src=%s)', async (source) => { + await expect(bundleStyle({ package: 'katex', css: `@font-face { font-family: KaTeX_Main; ${source} }` })) + .rejects.toThrow('KaTeX font face requires a WOFF2 source') +}) + +it('preserves older font formats in unrelated stylesheets', async () => { + const output = await bundleStyle({ package: 'other', css: '@font-face { font-family: Other; src: url(font.woff) format("woff"); }' }) + expect(output.some(asset => asset.type === 'asset' && asset.fileName.endsWith('.woff'))).toBe(true) +}) diff --git a/apps/web/tests/markdown-file-links.e2e.ts b/apps/web/tests/markdown-file-links.e2e.ts index e7acd74152..3b9cb9879b 100644 --- a/apps/web/tests/markdown-file-links.e2e.ts +++ b/apps/web/tests/markdown-file-links.e2e.ts @@ -1,18 +1,66 @@ /** Cold-replayed Markdown references open Session files through the shipped Web composition. */ import { mkdir, readFile, writeFile } from 'node:fs/promises' -import { join } from 'node:path' +import { basename, join } from 'node:path' import { fileURLToPath } from 'node:url' import { chromium, type Browser, type Page } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { ToolCallId, createAssistantMessage, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm' +import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session' +import { sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' +import type {} from '@deepseek-ai/dsh-session-title' import { assertFixtureInventory, captureStableAria, compareOrRefreshGolden, launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' -import { newEnglishPage, saveFailureShot } from './support.ts' +import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/markdown-file-links', import.meta.url)) const MODE = webSnapshotMode() +/** Build live test input with a parent-path link and a read result naming the same Host file. */ +function parentPathFixture(path: string): string { + const session = Session.create(SessionId('parent-file-links-source')) + session.append('turn/start', { turn: 1 }) + const user = session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Read the parent-path file and link lines 24 and 30.' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + session.append('session/title', { title: 'Parent file links', messageSeqs: [user.seq], source: { kind: 'fallback' } }) + session.append('step/start', { turn: 1, step: 1 }) + const callId = ToolCallId('parent-file-read') + const args = JSON.stringify({ file_path: path, offset: 24, limit: 7 }) + session.append('assistant/message', { + turn: 1, step: 1, stream: [], + message: createAssistantMessage({ + content: [{ type: 'tool-call', id: callId, name: 'read', arguments: args }], + source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + }), + }, { surfaceOp: 'append' }) + const call = session.append('tool/call', { turn: 1, step: 1, callId, name: 'read', arguments: args }) + session.append('tool/result', { + turn: 1, step: 1, meta: { path: '{{cwd}}/parent.txt' }, + message: createToolResultMessage({ callId, content: [{ type: 'text', text: 'parent line 24\n' }], isError: false }), + }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) + session.append('step/end', { turn: 1, step: 1 }) + session.append('step/start', { turn: 1, step: 2 }) + session.append('assistant/message', { + turn: 1, step: 2, stream: [], + message: createAssistantMessage({ + content: [{ type: 'text', text: `[Parent file:24–30](<${path}#L24-L30>) · [Parent file:30](<${path}#L30>)` }], + source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + }), + }, { surfaceOp: 'append' }) + session.append('step/end', { turn: 1, step: 2 }) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + return [ + JSON.stringify({ + type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 0, + cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0, + }), + ...session.snapshotEvents().map(event => JSON.stringify(event)), + '', + ].join('\n') +} + describe('web e2e: Markdown file links', () => { let scaffold: WebScaffold let browser: Browser @@ -78,4 +126,55 @@ describe('web e2e: Markdown file links', () => { expect(tripwire.warnings).toEqual([]) await assertFixtureInventory(SNAPSHOT_DIR, ['session.v3.jsonl', 'links.expected.md', 'preview.expected.md']) }) + + it('opens parent-path prose and read-card links while retaining each address across reload', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-parent-file-links')) + // Return through the parent into this owned temp root; no shared parent file is created. + const path = `../${basename(scaffold.workspaceCwd)}/parent.txt` + await writeFile(join(scaffold.workspaceCwd, 'parent.txt'), + Array.from({ length: 60 }, (_, i) => `parent line ${i + 1}\n`).join('')) + const id = await seedSession(scaffold, parentPathFixture(path), 'parent-file-links') + await page.reload({ waitUntil: 'load' }) + const workspace = page.getByRole('treeitem').first() + await workspace.waitFor() + if (await workspace.getAttribute('aria-expanded') !== 'true') await workspace.click() + await page.locator(`[data-row-key="session:${id}"]`).click() + + const source = page.getByRole('button', { name: 'Parent file:24–30', exact: true }) + await source.click() + const column = page.locator('[data-rightbar-col]') + const stored = () => page.evaluate(key => localStorage.getItem(key), `dsh.sidebar-right.v1.${id}`) + const address = sessionFileAddress(id, path) + await expect.poll(() => column.locator('[data-textpreview-target="24"]').textContent()).toBe('parent line 24\n') + await expect.poll(() => column.locator('[data-textpreview-path]').textContent()).toBe(join(scaffold.workspaceCwd, 'parent.txt')) + await expect.poll(stored).toContain(address) + const tabs = column.locator('[data-dockkit-tab-title]') + expect(await tabs.allTextContents()).toEqual(['parent.txt']) + + const later = page.getByRole('button', { name: 'Parent file:30', exact: true }) + await later.focus() + await later.press('Enter') + await expect.poll(() => column.locator('[data-textpreview-target="30"]').textContent()).toBe('parent line 30\n') + expect(await tabs.allTextContents()).toEqual(['parent.txt']) + + await page.reload({ waitUntil: 'load' }) + await expect.poll(() => column.locator('[data-textpreview-path]').textContent()).toBe(join(scaffold.workspaceCwd, 'parent.txt')) + await expect.poll(stored).toContain(address) + await source.click() + await expect.poll(() => column.locator('[data-textpreview-target="24"]').textContent()).toBe('parent line 24\n') + expect(await tabs.allTextContents()).toEqual(['parent.txt']) + + const readCardLink = page.locator('[data-tool="read"] button').filter({ hasText: 'parent.txt' }) + await expandOwningTurnProcess(page, readCardLink) + await readCardLink.click() + await expect.poll(() => column.locator('[data-textpreview-path]').textContent()).toBe(join(scaffold.workspaceCwd, 'parent.txt')) + await expect.poll(() => column.locator('[data-textpreview-target="24"]').textContent()).toBe('parent line 24\n') + // The Host-reported path and the unresolved prose path are distinct resource identities. + expect(await tabs.allTextContents()).toEqual(['parent.txt', 'parent.txt']) + await expect.poll(stored).toContain(sessionFileAddress(id, 'parent.txt')) + await source.click() + expect(await tabs.allTextContents()).toEqual(['parent.txt', 'parent.txt']) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) }) diff --git a/apps/web/tests/math-rendering.e2e.ts b/apps/web/tests/math-rendering.e2e.ts index 5e7d11d7fd..d7fa2b8873 100644 --- a/apps/web/tests/math-rendering.e2e.ts +++ b/apps/web/tests/math-rendering.e2e.ts @@ -122,6 +122,13 @@ describe('web e2e: settled Markdown math rendering', () => { await expect.poll(() => page.locator('.katex').count(), { timeout: 10_000 }).toBe(6) await expect.poll(() => page.locator('.katex-display').count(), { timeout: 10_000 }).toBe(2) expect(await page.locator('.katex-error').count()).toBe(0) + const fonts = await page.evaluate(async () => { + const faces = [...document.fonts].filter(face => face.family.includes('KaTeX_')) + await Promise.all(faces.map(face => face.load())) + return faces.map(face => face.status) + }) + expect(fonts).toHaveLength(20) + expect(fonts.every(status => status === 'loaded')).toBe(true) await expect.poll( () => page.getByText('1 turns 1 steps', { exact: false }).count(), { timeout: 10_000 }, diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index d121cbf579..75202aea47 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -20,7 +20,7 @@ import { launchWebScaffold, recordFixture, seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts' -import { expectSelectableTerminalCommand } from './terminal-command-browser.ts' +import { expectWrappedTerminalCommand } from './terminal-command-browser.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/navigation-panes', import.meta.url)) const SEED = join(SNAPSHOT_DIR, 'session.v3.jsonl') @@ -29,6 +29,7 @@ const TIMING_EXPECTED = join(SNAPSHOT_DIR, 'timing.expected.md') const SEARCH_EXPECTED = join(SNAPSHOT_DIR, 'search-results.expected.md') const TERMINAL_EXPECTED = join(SNAPSHOT_DIR, 'terminal-card.expected.md') const CODE_CARD_DIR = fileURLToPath(new URL('./expected/navigation-panes', import.meta.url)) +const COMMAND_WRAP_EXPECTED = join(CODE_CARD_DIR, 'command-wrap.expected.md') const CODE_CARD_EXPECTED = join(CODE_CARD_DIR, 'code-card.expected.md') const MODE = webSnapshotMode() const SEED_ID = 'navigation-panes-web-e2e' @@ -472,7 +473,8 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { if (await bashRow.getAttribute('aria-expanded') !== 'true') await bashRow.click() const card = page.locator('[data-sample="bash"] ~ div [data-terminal]').first() await card.waitFor({ timeout: 15_000 }) - await expectSelectableTerminalCommand(page, card, 'echo NAVIGATION_OK', 300) + const commandWrap = await expectWrappedTerminalCommand(page, card, 'echo NAVIGATION_OK', 300) + await compareOrRefreshGolden(COMMAND_WRAP_EXPECTED, JSON.stringify(commandWrap, null, 2), MODE) // Real layout, not jsdom's stub (which computes no geometry at all): // squeeze the output pane below its content width and the line must keep // its single row and overflow sideways instead of folding. Soft-wrapping @@ -547,7 +549,7 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { }, 60_000) it.skipIf(MODE === 'record')('keeps the recorded fixture inventory exact', async () => { - await assertFixtureInventory(CODE_CARD_DIR, ['code-card.expected.md']) + await assertFixtureInventory(CODE_CARD_DIR, ['code-card.expected.md', 'command-wrap.expected.md']) await assertFixtureInventory(SNAPSHOT_DIR, [ 'session.v3.jsonl', 'search-results.expected.md', 'trajectory.expected.md', 'terminal-card.expected.md', 'timing.expected.md', diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index 30fc3ee99a..c6f965d806 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, @@ -278,20 +279,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', 'missing.expected.md', 'models.expected.md', 'default-models.expected.md', 'empty.expected.md'], ) }) }) 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/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index ac2f8c72f7..2b1fa6df62 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -37,6 +37,8 @@ import { } from '@deepseek-ai/dsh-experimental-webworker-runtime' import { VFS_EXAMPLE_SESSION_IDS, + VFS_EXAMPLE_REASONING, + VFS_EXAMPLE_WRAPPED_COMMAND, buildVfsExampleFiles, } from '../../../packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts' import { captureStableAria, compareOrRefreshGolden, webSnapshotMode } from './scaffold.ts' @@ -455,6 +457,57 @@ async function bootPreview(origin: string, browser: Browser): Promise { await page.getByText('Update to-do list', { exact: true }).waitFor() await page.getByText('Error: ENOENT: no such file, open missing.txt', { exact: true }).waitFor() + const reasoning = page.locator('[data-variant="think"]') + await expect.poll(() => reasoning.count()).toBe(VFS_EXAMPLE_REASONING.length) + for (const [index, text] of VFS_EXAMPLE_REASONING.entries()) { + const row = reasoning.nth(index) + await row.getByRole('button').click() + await row.getByText(text.split('\n\n').at(-1)!, { exact: true }).waitFor({ state: 'visible' }) + } + + const wrappedCall = page.locator('[data-chat-call-id="preview-wrapped-bash"]') + await wrappedCall.locator('[data-sample="bash"]').click() + const terminal = wrappedCall.locator('[data-terminal]') + const originalWidth = await terminal.evaluate(element => element.style.width) + try { + await terminal.evaluate((element) => { element.style.width = '380px' }) + const commands = terminal.locator('[data-command-text]') + expect(await commands.allTextContents()).toEqual(VFS_EXAMPLE_WRAPPED_COMMAND.slice(0, -1).split('\n')) + await commands.first().scrollIntoViewIfNeeded() + const geometry = await commands.first().evaluate((element) => { + const prompt = element.parentElement! + const header = element.closest('[class*="_header_"]')! + header.scrollTop = 0 + const dot = prompt.querySelector('[data-state="done"]') + if (dot === null) throw new Error('wrapped preview command has no successful status dot') + const range = document.createRange() + range.selectNodeContents(element) + const lines = [...range.getClientRects()].filter(rect => rect.width > 0 && rect.height > 0) + const marker = dot.getBoundingClientRect() + const viewport = header.getBoundingClientRect() + return { + wrapped: new Set(lines.map(rect => Math.round(rect.top))).size > 1, + whitespace: getComputedStyle(element).whiteSpace, + alignmentError: Math.abs(marker.top + marker.height / 2 + - (prompt.getBoundingClientRect().top + Number.parseFloat(getComputedStyle(prompt).lineHeight) / 2)), + visible: marker.top >= viewport.top && marker.bottom <= viewport.bottom, + } + }) + expect(geometry.wrapped).toBe(true) + expect(geometry.whitespace).toBe('pre-wrap') + expect(geometry.alignmentError).toBeLessThanOrEqual(1) + expect(geometry.visible).toBe(true) + expect(await terminal.locator('[data-state="done"]').count()).toBe(1) + } finally { + await terminal.evaluate((element, width) => { element.style.width = width }, originalWidth) + } + + await page.getByRole('button', { name: 'Parent workspace guide:1–8', exact: true }).click() + const preview = page.locator('[data-rightbar-col]') + await expect.poll(() => preview.locator('[data-textpreview-path]').textContent()).toBe('/dsh/workspace/PREVIEW.md') + await preview.getByRole('heading', { name: 'Preview Workspace', exact: true }).waitFor({ state: 'visible' }) + expect(await preview.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['PREVIEW.md']) + const subagents = page.getByRole('button', { name: '2 subagents', exact: true }) await subagents.waitFor({ timeout: 15_000 }) await subagents.hover() diff --git a/apps/web/tests/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/scaffold.ts b/apps/web/tests/scaffold.ts index 8009cf4453..f1524ed0a5 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -887,10 +887,10 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/seeded-history', import.meta.url)) +const REASONING_EXPECTED_DIR = fileURLToPath(new URL('./expected/seeded-history', import.meta.url)) const SEED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url)) const UI_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/ui.expected.md', import.meta.url)) const UI_EXPANDED_EXPECTED = fileURLToPath( @@ -856,11 +857,68 @@ describe('web e2e: seeded history renders through cold resume', () => { await terminal.getByRole('textbox', { name: 'Terminal', exact: true }).waitFor() }) + it.skipIf(MODE === 'record')('omits blank reasoning rows around recorded text in an appended fixture turn', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-blank-reasoning')) + const session = scaffold.ctx.sessions.get(SessionId(SEED_ID)) + if (session === undefined) throw new Error('seeded session is unavailable') + const events = session.snapshotEvents() + const recorded = events.flatMap(event => event.type === 'assistant/message' ? event.data.message.content : []) + .find(block => block.type === 'reasoning' && block.text.trim() !== '') + if (recorded?.type !== 'reasoning') throw new Error('seeded history requires recorded reasoning text') + const previousEnd = events.findLast(event => event.type === 'turn/end') + if (previousEnd?.type !== 'turn/end') throw new Error('seeded history requires a closed turn') + const turn = previousEnd.data.turn + 1 + const answer = 'BLANK_REASONING_FIXTURE_DONE' + // The blank blocks are a test condition around authentic recorded text, not model output. + session.append('turn/start', { turn }) + session.append('step/start', { turn, step: 1 }) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Show recorded reasoning surrounded by blank blocks.' }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + const message = session.append('assistant/message', { + turn, step: 1, stream: [], + message: createMessage({ + role: 'assistant', + source: { kind: 'model', provider: 'fixture', model: 'fixture' }, + content: [ + { type: 'reasoning', text: '' }, + { type: 'reasoning', text: recorded.text }, + { type: 'reasoning', text: ' \t\r\n' }, + { type: 'reasoning', text: '' }, + { type: 'text', text: answer }, + ], + }), + }, { surfaceOp: 'append' }) + session.append('step/end', { turn, step: 1 }) + session.append('turn/end', { turn, reason: { kind: 'completed' } }) + await scaffold.ctx.sessions.flush(session) + await page.getByText(answer, { exact: true }).waitFor({ timeout: 10_000 }) + const selector = `[data-chat-turn="${turn}"][data-chat-group-part="reasoning"]` + const rows = page.locator(selector).locator('[data-variant="think"]') + await expect.poll(() => rows.count(), { timeout: 10_000 }).toBe(1) + await expandOwningTurnProcess(page, rows.first()) + const toggle = rows.getByRole('button').first() + expect(await toggle.getAttribute('aria-expanded')).toBe('false') + await toggle.click() + await expect.poll(() => toggle.getAttribute('aria-expanded')).toBe('true') + const body = rows.locator('[data-markdown-variant="compact"]') + await body.waitFor({ state: 'visible' }) + expect(await body.innerText()).not.toBe('') + expect(message.data.message.content[1]).toEqual({ type: 'reasoning', text: recorded.text }) + await compareOrRefreshGolden(join(REASONING_EXPECTED_DIR, 'blank-reasoning.expected.md'), [ + await captureStableAria(page, selector, scaffold.workspaceCwd), + '', + `- Reasoning rows: ${await rows.count()}`, + ].join('\n'), MODE) + }) + it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', async () => { // No replay fixture was installed and the llm seam is open — any stray // stream would have failed the turn loudly. Cleanliness pins the wire. expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) + await assertFixtureInventory(REASONING_EXPECTED_DIR, ['blank-reasoning.expected.md']) await assertFixtureInventory(SNAPSHOT_DIR, [ 'command-row.expected.md', 'feedback-row.expected.md', 'file-preview.expected.md', 'session.v3.jsonl', 'sticky-geometry.expected.md', 'thinking-expanded.expected.md', diff --git a/apps/web/tests/settings-chrome.e2e.ts b/apps/web/tests/settings-chrome.e2e.ts index 2b64c107fc..6d6fd3e808 100644 --- a/apps/web/tests/settings-chrome.e2e.ts +++ b/apps/web/tests/settings-chrome.e2e.ts @@ -163,8 +163,8 @@ describe('web e2e: settings modal and General preferences', () => { expect(await enabledRows.count()).toBeGreaterThan(0) expect(await enabledRows.getByText('已启用', { exact: true }).count()).toBe(0) expect(await dialog.locator('[data-plugin-scope="global"] [role="img"][aria-label="运行中"]').count()).toBe(0) - expect(await dialog.locator('[data-plugin-count]').getAttribute('data-plugin-count')) - .toBe(String(expectedPluginCount)) + expect(await dialog.getByText('由 Agent 预设按会话组成', { exact: true }).count()).toBe(1) + expect(await dialog.getByText('系统与所有会话共用', { exact: true }).count()).toBe(1) expect(await dialog.getByRole('button', { name: '内置插件', exact: true }).getAttribute('aria-current')).toBe('true') // One contribution shows as the page itself, without a tab row. expect(await dialog.getByRole('tab').count()).toBe(0) @@ -182,17 +182,11 @@ describe('web e2e: settings modal and General preferences', () => { ] as const for (const [entryId, status] of instanceRows) { const row = dialog.locator(`[data-plugin-scope="preset"] [data-plugin-entry="${entryId}"]`) - // An id that repeats the title adds nothing, so its card shows no chip and its name omits it. - const repeatsTitle = entryId === 'tool-subagent' - const name = repeatsTitle ? `tool-subagent, ${status}` : `tool-subagent, ${entryId}, ${status}` + const name = `子智能体委派工具, ${entryId}, ${status}` const trigger = row.getByRole('button', { name, exact: true }) await trigger.waitFor({ timeout: 10_000 }) expect(await trigger.getAttribute('aria-expanded')).toBe('false') const identity = row.locator('code') - if (repeatsTitle) { - expect(await identity.count()).toBe(0) - continue - } expect(await identity.textContent()).toBe(entryId) expect(await identity.getAttribute('title')).toBe(entryId) } @@ -204,7 +198,7 @@ describe('web e2e: settings modal and General preferences', () => { ) await compareOrRefreshGolden(PLUGIN_INSTANCES_EXPECTED, instancesSnapshot, MODE) await dialog.getByRole('button', { - name: 'tool-subagent, tool-subagent-fork, 已启用', + name: '子智能体委派工具, tool-subagent-fork, 已启用', exact: true, }).click() expect(await dialog.locator('[data-plugin-entry="tool-subagent-fork"] button') @@ -943,7 +937,7 @@ describe('web e2e: settings modal and General preferences', () => { }) }) -describe('web e2e: browser-local collapse timing preference', () => { +describe('web e2e: Host-backed collapse timing preference', () => { let scaffold: WebScaffold let browser: Browser const uiWait = { timeout: 10_000 } @@ -974,11 +968,12 @@ describe('web e2e: browser-local collapse timing preference', () => { title: 'When to Collapse Work Details', completion: 'On completion', nextInput: 'On next message', description: 'Choose when to automatically collapse work details', }, - ] as const)('keeps $locale collapse timing on $theme only for the current Client', async (copy) => { + ] as const)('persists $locale collapse timing on $theme across Clients', async (copy) => { const contextOptions = { viewport: { width: 1680, height: 1000 }, locale: copy.browserLocale, colorScheme: copy.theme, timezoneId: 'Asia/Shanghai', } + await scaffold.ctx.settings.update('ui-chat', { collapseTiming: 'completion' }) const context = await browser.newContext(contextOptions) onTestFinished(() => context.close()) const page = await context.newPage() @@ -1076,19 +1071,23 @@ describe('web e2e: browser-local collapse timing preference', () => { await menu.waitFor({ state: 'hidden' }) await page.setViewportSize({ width: 1680, height: 1000 }) await timing.getByRole('button', { name: copy.nextInput, exact: true }).waitFor() - expect(await readPersistence()).toEqual(before) + await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value, uiWait) + .toMatchObject({ transcriptView: 'detailed', collapseTiming: 'next-input' }) + const saved = await readPersistence() + expect(saved.host).not.toBe(before.host) + expect(saved.storage).toEqual(before.storage) await dialog.getByRole('button', { name: copy.close, exact: true }).click() await openSettings(page, copy.locale) await timing.getByRole('button', { name: copy.nextInput, exact: true }).waitFor() - expect(await readPersistence()).toEqual(before) + expect(await readPersistence()).toEqual(saved) await dialog.getByRole('button', { name: copy.close, exact: true }).click() const warningStart = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) await openSettings(page, copy.locale) - await timing.getByRole('button', { name: copy.completion, exact: true }).waitFor() + await timing.getByRole('button', { name: copy.nextInput, exact: true }).waitFor() acknowledgeReloadConnectionLoss(tripwire, warningStart) - expect(await readPersistence()).toEqual(before) + expect(await readPersistence()).toEqual(saved) if (screenshotDir !== undefined) { await page.screenshot({ path: join(screenshotDir, 'reloaded.png'), fullPage: true }) } @@ -1100,10 +1099,10 @@ describe('web e2e: browser-local collapse timing preference', () => { await openSettings(sharedPage, copy.locale) const sharedTiming = sharedPage.getByRole('dialog', { name: copy.settings, exact: true }) .getByText(copy.title, { exact: true }).locator('../..') - await sharedTiming.getByRole('button', { name: copy.completion, exact: true }).waitFor() + await sharedTiming.getByRole('button', { name: copy.nextInput, exact: true }).waitFor() const sharedPersistence = await readPersistence(sharedPage) - expect(sharedPersistence.host).toBe(before.host) - expect(sharedPersistence.settings).toEqual(before.settings) + expect(sharedPersistence.host).toBe(saved.host) + expect(sharedPersistence.settings).toEqual(saved.settings) expect(sharedPersistence.storage.local).toEqual(before.storage.local) if (screenshotDir !== undefined) { await sharedPage.screenshot({ path: join(screenshotDir, 'shared-tab.png'), fullPage: true }) @@ -1119,22 +1118,24 @@ describe('web e2e: browser-local collapse timing preference', () => { await openSettings(isolatedPage, copy.locale) const isolatedTiming = isolatedPage.getByRole('dialog', { name: copy.settings, exact: true }) .getByText(copy.title, { exact: true }).locator('../..') - await isolatedTiming.getByRole('button', { name: copy.completion, exact: true }).waitFor() + await isolatedTiming.getByRole('button', { name: copy.nextInput, exact: true }).waitFor() const isolatedPersistence = await readPersistence(isolatedPage) - expect(isolatedPersistence.host).toBe(before.host) - expect(isolatedPersistence.settings).toEqual(before.settings) + expect(isolatedPersistence.host).toBe(saved.host) + expect(isolatedPersistence.settings).toEqual(saved.settings) if (screenshotDir !== undefined) { await isolatedPage.screenshot({ path: join(screenshotDir, 'isolated-context.png'), fullPage: true }) } - expect(await readPersistence()).toEqual(before) - await timing.getByRole('button', { name: copy.completion, exact: true }).click() - await page.getByRole('menuitem', { name: copy.nextInput, exact: true }).click() + expect(await readPersistence()).toEqual(saved) await timing.getByRole('button', { name: copy.nextInput, exact: true }).click() await page.getByRole('menuitem', { name: copy.completion, exact: true }).click() await timing.getByRole('button', { name: copy.completion, exact: true }).waitFor() - expect(await readPersistence()).toEqual(before) - expect(settingsWrites).toEqual([]) + await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value, uiWait) + .toMatchObject({ transcriptView: 'detailed', collapseTiming: 'completion' }) + expect((await readPersistence()).storage).toEqual(before.storage) + await sharedTiming.getByRole('button', { name: copy.completion, exact: true }).waitFor() + await isolatedTiming.getByRole('button', { name: copy.completion, exact: true }).waitFor() + expect(settingsWrites.length).toBeGreaterThan(0) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) expect(sharedTripwire.pageErrors).toEqual([]) diff --git a/apps/web/tests/shell-command-details.e2e.ts b/apps/web/tests/shell-command-details.e2e.ts index a219fb6941..f9c50ad056 100644 --- a/apps/web/tests/shell-command-details.e2e.ts +++ b/apps/web/tests/shell-command-details.e2e.ts @@ -8,21 +8,22 @@ import { seedSession, watchConsole, webSnapshotMode, } from './scaffold.ts' import { expandOwningTurnProcess, newEnglishPage } from './support.ts' -import { expectCommandFocusAfterResize, expectSelectableCommandText } from './terminal-command-browser.ts' +import { expectFirstLineTerminalState, expectWrappedCommandText } from './terminal-command-browser.ts' const COMMAND = 'node ./scripts/start-worker.mjs --workspace=/tmp/diagnostics/long-workspace-name-for-background-command-details --log-level=debug --trace-tag=background-shell-full-command-selection --include=worker,lifecycle,transport,subscriptions --output=/tmp/diagnostics/background-worker.log' const ARGS = { command: COMMAND, description: 'Start the diagnostic worker', run_in_background: true } const OUTPUT = 'started background job bash-1' -const EXPECTED = fileURLToPath(new URL('./expected/shell-command-details/background.expected.md', import.meta.url)) +const LONG_ARGS = { ...ARGS, command: `${COMMAND} --token=${'x'.repeat(1024)}` } -/** A settled background launch acknowledgement rendered from durable call arguments. */ -function backgroundFixture(): string { +/** A settled shell call rendered from durable arguments and its original result. */ +function shellFixture(arguments_: typeof ARGS, output: string): string { const session = Session.create(SessionId('shell-command-details-source')) const callId = ToolCallId('shell-command-details-background') - const args = JSON.stringify(ARGS) + const args = JSON.stringify(arguments_) session.append('turn/start', { turn: 1 }) session.append('user/message', createUserMessage({ - content: [{ type: 'text', text: 'Start the diagnostic worker in the background.' }], + content: [{ type: 'text', text: arguments_.run_in_background + ? 'Start the diagnostic worker in the background.' : 'Run the diagnostic worker.' }], source: { kind: 'user' }, }), { surfaceOp: 'append' }) session.append('step/start', { turn: 1, step: 1 }) @@ -36,7 +37,7 @@ function backgroundFixture(): string { const call = session.append('tool/call', { turn: 1, step: 1, callId, name: 'bash', arguments: args }) session.append('tool/result', { turn: 1, step: 1, - message: createToolResultMessage({ callId, content: [{ type: 'text', text: OUTPUT }], isError: false }), + message: createToolResultMessage({ callId, content: [{ type: 'text', text: output }], isError: false }), }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) session.append('step/end', { turn: 1, step: 1 }) session.append('step/start', { turn: 1, step: 2 }) @@ -56,10 +57,18 @@ function backgroundFixture(): string { ].join('\n') } -it('expands a background Bash launch to selectable arguments and its original acknowledgement', async () => { +it.each([ + { name: 'background', args: ARGS, output: OUTPUT }, + { name: 'background-long-token', args: LONG_ARGS, output: OUTPUT }, + { + name: 'foreground-multiline', + args: { ...LONG_ARGS, command: `${LONG_ARGS.command}\necho done\n`, run_in_background: false }, + output: 'done\n[exit code: 0]', + }, +])('expands $name to wrapped commands with only foreground output', async ({ name, args, output }) => { const scaffold = await launchWebScaffold({}) try { - await seedSession(scaffold, backgroundFixture(), 'shell-command-details-browser') + await seedSession(scaffold, shellFixture(args, output), 'shell-command-details-browser') const browser = await chromium.launch() try { const page = await newEnglishPage(browser) @@ -76,25 +85,52 @@ it('expands a background Bash launch to selectable arguments and its original ac expect(await row.getAttribute('aria-expanded')).toBe('false') await row.click() const card = row.locator('..') - const input = card.locator('[data-command-text]') + const commands = card.locator('[data-command-text]') + const input = commands.first() await input.waitFor() - expect(await input.textContent()).toBe(JSON.stringify(ARGS, null, 2)) - expect(await card.getByText(OUTPUT, { exact: true }).count()).toBe(1) - expect(await card.locator('[data-terminal]').count()).toBe(0) + const background = args.run_in_background + const selectableText = args.command.split('\n')[0]! + const inputSection = card.locator('[data-terminal] [class*="_header_"]') + expect(await input.textContent()).toBe(selectableText) + if (background) { + expect(await commands.allTextContents()).toEqual([args.command]) + expect(await card.locator('[data-terminal]').count()).toBe(1) + expect(await card.getByText(OUTPUT, { exact: true }).count()).toBe(0) + expect(await card.locator('[data-terminal][data-body], [data-terminal][data-running], [data-terminal] [data-state]').count()).toBe(0) + expect(await card.getByRole('button', { name: 'Copy', exact: true }).count()).toBe(0) + } else { + expect(await commands.allTextContents()).toEqual([selectableText, 'echo done']) + expect(await card.locator('[data-terminal]').count()).toBe(1) + expect(await card.getByText('done', { exact: true }).count()).toBe(1) + } expect(await card.getByRole('button', { name: 'Inspect', exact: true }).count()).toBe(1) for (const colorScheme of ['light', 'dark'] as const) { await page.emulateMedia({ colorScheme }) await expect.poll(() => page.locator('body').evaluate(element => element.hasAttribute('data-ds-dark-theme'))).toBe(colorScheme === 'dark') - for (const width of ['', '380px']) { + for (const width of ['', '380px', '']) { await card.evaluate((element, value) => { element.style.width = value }, width) - await input.scrollIntoViewIfNeeded() - await expectSelectableCommandText(page, input, COMMAND, 'Command arguments') - await expectCommandFocusAfterResize(card, input) + if (!background && width === '380px') await expectFirstLineTerminalState(card.locator('[data-terminal]'), 'done') + await expectWrappedCommandText(page, input, selectableText, inputSection) + expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + if (name !== 'background') { + expect(await inputSection.evaluate(element => element.scrollHeight > element.clientHeight)).toBe(true) + await inputSection.evaluate((element) => { element.scrollTop = 0 }) + await row.focus() + await page.keyboard.press('Tab') + const focusTarget = background ? inputSection : card.getByRole('button', { name: 'Copy', exact: true }) + expect(await focusTarget.evaluate(element => document.activeElement === element)).toBe(true) + await page.keyboard.press('End') + await expect.poll(() => inputSection.evaluate(element => + element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true) + await page.keyboard.press('Home') + await expect.poll(() => inputSection.evaluate(element => element.scrollTop)).toBe(0) + } } await card.evaluate((element) => { element.style.width = '' }) } await page.emulateMedia({ colorScheme: null }) - await compareOrRefreshGolden(EXPECTED, + const expected = fileURLToPath(new URL(`./expected/shell-command-details/${name}.expected.md`, import.meta.url)) + await compareOrRefreshGolden(expected, await captureStableAria(page, '[data-chat-call-id="shell-command-details-background"]', scaffold.workspaceCwd), webSnapshotMode()) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) @@ -105,3 +141,94 @@ it('expands a background Bash launch to selectable arguments and its original ac await scaffold.close() } }) + +it.each([ + { name: 'bash', background: false }, + { name: 'pwsh', background: false }, + { name: 'bash', background: true }, + { name: 'pwsh', background: true }, +] as const)('keeps the $name command mounted through settlement (background=$background)', async ({ name, background }) => { + const scaffold = await launchWebScaffold({}) + try { + const id = await seedSession(scaffold, shellFixture(ARGS, OUTPUT), 'shell-status-dot-browser') + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl) + await page.getByRole('treeitem').first().click() + await page.getByRole('treeitem').nth(1).click() + await page.locator('[data-sample="bash"]').waitFor({ state: 'attached' }) + const resolved = await scaffold.ctx.sessionController.resolveAgent(id) + if ('error' in resolved) throw resolved.error + const session = resolved.agent.session + const callId = ToolCallId(`status-dot-${name}-${background ? 'background' : 'foreground'}`) + const args = JSON.stringify({ command: LONG_ARGS.command, description: `Long ${name} command`, run_in_background: background }) + session.append('turn/start', { turn: 2 }) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Show a long running command.' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + session.append('step/start', { turn: 2, step: 1 }) + session.append('assistant/message', { + turn: 2, step: 1, stream: [], + message: createAssistantMessage({ + content: [{ type: 'tool-call', id: callId, name, arguments: args }], + source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + }), + }, { surfaceOp: 'append' }) + const call = session.append('tool/call', { turn: 2, step: 1, callId, name, arguments: args }) + await scaffold.ctx.sessions.flush(session) + const callRow = page.locator(`[data-chat-call-id="${callId}"]`) + const toggle = callRow.locator('[data-expandable]').first() + await toggle.waitFor({ state: 'attached' }) + await expandOwningTurnProcess(page, toggle) + await toggle.click() + const card = callRow.locator('[data-terminal]') + await card.waitFor() + await card.evaluate((element) => { element.style.width = '380px' }) + await card.scrollIntoViewIfNeeded() + const header = card.locator('[class*="_header_"]') + const mountedCard = await card.elementHandle() + if (mountedCard === null) throw new Error('Running command card is not mounted') + expect(await header.evaluate(element => element.scrollHeight > element.clientHeight)).toBe(true) + expect(await card.getByRole('button', { name: 'Copy', exact: true }).count()).toBe(0) + for (const state of ['ongoing', 'done'] as const) { + if (state === 'done') { + session.append('tool/result', { + turn: 2, step: 1, + message: createToolResultMessage({ + callId, content: [{ type: 'text', text: background ? OUTPUT : 'status dot output\n[exit code: 0]' }], isError: false, + }), + }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) + session.append('step/end', { turn: 2, step: 1 }) + session.append('turn/end', { turn: 2, reason: { kind: 'completed' } }) + await scaffold.ctx.sessions.flush(session) + } + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }) + await expect.poll(() => page.locator('body').evaluate(element => + element.hasAttribute('data-ds-dark-theme'))).toBe(colorScheme === 'dark') + if (background && state === 'done') { + await expect.poll(() => card.getAttribute('data-running')).toBeNull() + expect(await card.evaluate((element, previous) => element === previous, mountedCard)).toBe(true) + expect(await toggle.getAttribute('aria-expanded')).toBe('true') + expect(await card.getAttribute('data-body')).toBeNull() + expect(await card.getAttribute('data-running')).toBeNull() + expect(await card.locator('[data-state]').count()).toBe(0) + } else await expectFirstLineTerminalState(card, state) + expect(await card.locator('[data-command-text]').textContent()).toBe(LONG_ARGS.command) + } + } + expect(await card.getByText('status dot output', { exact: true }).count()).toBe(background ? 0 : 1) + expect(await card.getByText(OUTPUT, { exact: true }).count()).toBe(0) + expect(await card.getByRole('button', { name: 'Copy', exact: true }).count()).toBe(background ? 0 : 1) + expect(await callRow.getByRole('button', { name: 'Inspect', exact: true }).count()).toBe(1) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index 49fe63b3d0..2324f0ae2b 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -567,7 +567,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = Math.round(clickAreaBox!.x - menuBox!.x), Math.round(menuBox!.x + menuBox!.width - clickAreaBox!.x - clickAreaBox!.width), // The outer menu padding insets the scrollable tree rows. - ]).toEqual([3, 3]) + ]).toEqual([4, 4]) await compareOrRefreshGolden( BRANCHLESS_EXPECTED, await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), diff --git a/apps/web/tests/terminal-command-browser.ts b/apps/web/tests/terminal-command-browser.ts index a1ebb77850..fb715cecea 100644 --- a/apps/web/tests/terminal-command-browser.ts +++ b/apps/web/tests/terminal-command-browser.ts @@ -64,6 +64,138 @@ export async function expectSelectableTerminalCommand(page: Page, card: Locator, } } +/** + * Select and copy text that wraps through the consumer's own stylesheet. + * @param page - Browser page that owns the text. + * @param command - One authored command line or the complete formatted arguments. + * @param expected - Exact selectable text, including authored whitespace. + * @param scrollport - Existing vertical scroll container around the text. + * @returns Observed wrapping and native clipboard text for a semantic snapshot. + */ +export async function expectWrappedCommandText( + page: Page, command: Locator, expected: string, scrollport: Locator, +): Promise<{ wrapped: boolean; text: string | null; copiedText: string }> { + expect(await command.textContent()).toBe(expected) + expect(await command.evaluate(element => getComputedStyle(element).whiteSpace)).toBe('pre-wrap') + await expectNoCommandTabStop(command) + const wrapped = await command.evaluate((element, value) => { + const text = element.firstChild + if (!(text instanceof Text)) throw new Error('Command has no text node') + const longest = value.split('\n').reduce((a, b) => a.length >= b.length ? a : b) + const offset = value.indexOf(longest) + const range = document.createRange() + range.setStart(text, offset) + range.setEnd(text, offset + longest.length) + const rows = [...range.getClientRects()].filter(rect => rect.width > 0 && rect.height > 0) + .map(rect => Math.round(rect.top)) + return new Set(rows).size > 1 + }, expected) + expect(wrapped).toBe(true) + expect(await scrollport.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + const originalScrollTop = await scrollport.evaluate(element => element.scrollTop) + const geometry = () => command.evaluate((element) => { + const text = element.firstChild + if (!(text instanceof Text) || text.length === 0) throw new Error('Command has no text node') + const first = document.createRange() + first.setStart(text, 0) + first.setEnd(text, 1) + const last = document.createRange() + last.setStart(text, text.length - 1) + last.setEnd(text, text.length) + const head = first.getBoundingClientRect() + const tail = last.getBoundingClientRect() + return { head: { x: head.left, y: head.top + head.height / 2 }, tail: { x: tail.right, y: tail.top + tail.height / 2 } } + }) + try { + await scrollport.scrollIntoViewIfNeeded() + await scrollport.evaluate((element) => { element.scrollTop = 0 }) + const start = await geometry() + const viewport = await scrollport.boundingBox() + if (viewport === null) throw new Error('Command scrollport is not visible') + await page.mouse.move(start.head.x + 0.1, start.head.y) + await page.mouse.down() + try { + if (start.tail.y > viewport.y + viewport.height) { + await page.mouse.move(start.head.x + 0.1, viewport.y + viewport.height - 2) + await page.mouse.wheel(0, await scrollport.evaluate(element => element.scrollHeight)) + await expect.poll(async () => (await geometry()).tail.y < viewport.y + viewport.height).toBe(true) + } + const end = await geometry() + await page.mouse.move(end.tail.x - 0.1, end.tail.y, { steps: 5 }) + } finally { + await page.mouse.up() + } + await expect.poll(() => page.evaluate(() => document.getSelection()?.toString())).toBe(expected) + await page.context().grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(page.url()).origin }) + const sentinel = `${expected}\nclipboard-before-copy` + await page.evaluate(value => navigator.clipboard.writeText(value), sentinel) + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(sentinel) + await page.keyboard.press('ControlOrMeta+C') + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(expected) + return { wrapped, text: await command.textContent(), copiedText: await page.evaluate(() => navigator.clipboard.readText()) } + } finally { + await scrollport.evaluate((element, top) => { element.scrollTop = top }, originalScrollTop) + await command.evaluate(() => { document.getSelection()?.removeAllRanges() }) + } +} + +/** + * Verify a chat terminal wraps at a narrow width without changing its text. + * @param page - Browser page that owns the card. + * @param card - Chat terminal card with consumer-owned wrapping styles. + * @param expected - Complete single authored command line. + * @param width - Narrow card width that forces soft wrapping. + * @returns Observed command wrapping and copied text in both themes. + */ +export async function expectWrappedTerminalCommand(page: Page, card: Locator, expected: string, width: number) { + const originalWidth = await card.evaluate(element => element.style.width) + const command = card.locator('[data-command-text]').first() + const header = card.locator('[class*="_header_"]').first() + const observations: ({ colorScheme: 'light' | 'dark' } & Awaited>)[] = [] + try { + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }) + await expect.poll(() => page.locator('body').evaluate(element => element.hasAttribute('data-ds-dark-theme'))).toBe(colorScheme === 'dark') + await card.evaluate((element, value) => { element.style.width = `${value}px` }, width) + observations.push({ colorScheme, ...await expectWrappedCommandText(page, command, expected, header) }) + expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + await card.evaluate((element, value) => { element.style.width = value }, originalWidth) + await expectNoCommandTabStop(command) + expect(await command.textContent()).toBe(expected) + } + return observations + } finally { + await card.evaluate((element, value) => { element.style.width = value }, originalWidth) + await page.emulateMedia({ colorScheme: null }) + } +} + +/** + * Verify a terminal's status dot remains visible beside the first visual command line. + * @param card - Terminal card with its command banner scrolled to the start. + * @param state - Expected running or settled state. + * @returns Resolves after the dot fits inside the banner and aligns with the first line. + */ +export async function expectFirstLineTerminalState(card: Locator, state: 'ongoing' | 'done'): Promise { + const dot = card.locator('[class*="_runState_"][data-state]') + await expect.poll(() => dot.getAttribute('data-state')).toBe(state) + const geometry = await dot.evaluate((element) => { + const prompt = element.closest('[class*="_promptLine_"]') + const header = element.closest('[class*="_header_"]') + if (prompt === null || header === null) throw new Error('Terminal status has no prompt banner') + const bounds = element.getBoundingClientRect() + const viewport = header.getBoundingClientRect() + return { + visible: bounds.top >= viewport.top && bounds.bottom <= viewport.bottom + && bounds.left >= viewport.left && bounds.right <= viewport.right, + center: bounds.top + bounds.height / 2, + firstLineCenter: prompt.getBoundingClientRect().top + Number.parseFloat(getComputedStyle(prompt).lineHeight) / 2, + } + }) + expect(geometry.visible).toBe(true) + expect(geometry.center).toBeCloseTo(geometry.firstLineCenter, 1) +} + /** * Verify a resized command drops its explicit keyboard stop when all text fits. * @param container - Width owner of the command. diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 9c0350a2be..f9269cd333 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -114,7 +114,7 @@ "tests/desktop-onboarding.e2e.ts", "tests/bonus-notice.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", @@ -135,6 +135,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", 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/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..d85a74ff21 100644 --- a/docs/api-gateway.i18n.yaml +++ b/docs/api-gateway.i18n.yaml @@ -4,7 +4,7 @@ # 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 @@ -22,7 +22,10 @@ zh: 2b70b61b1ff1fbb0 /api-gateway/development-mode: en: ba090d76471dd663 - zh: fcddcb232de98248 + zh: edf362f71b73eaf0 /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..0fb3edcb79 100644 --- a/docs/api-gateway.md +++ b/docs/api-gateway.md @@ -163,3 +163,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..81b504685e 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` 调用。 @@ -156,6 +158,8 @@ 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 与发布构建也使用同一顺序。 + + ## 边界 Remote 处理单请求单结果的一元方法调用,以及项沿 Host → Client 方向流动、而 Client 的项经 `this.ctx.invocation.uplink()` 到达正在运行的 Host 方法的流方法。会话事件流、分页、增量 reduce、projection 和实体子流仍需要独立的数据协议与注册模型;即使它们复用 Connection,也不应伪装成 Remote 方法或放入调用描述符。 @@ -163,3 +167,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/config-catalog.md b/docs/config-catalog.md index 954f287d70..087c2d0012 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1381,7 +1381,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 diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index cd8dc2da00..ee898ff635 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1383,7 +1383,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 diff --git a/docs/defensive-patterns.i18n.yaml b/docs/defensive-patterns.i18n.yaml deleted file mode 100644 index 61e5aec2f2..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: 3275390293995f44 - zh: 4d143e99a2a7c8cb -/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 25ec826913..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 - -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. - -## 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 c21a87cb28..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,也不让后续监听器失去执行机会。监听器的所有者必须按[错误处理规范](../.agents/skills/dsh-error-handling/SKILL.md#catch-recover-or-stop)处置其修改的状态;仅捕获异常不会恢复状态。 - -## 绝不将环境变量或可预测路径暴露给不可信输出 - -启动的命令应使用经过清理的环境变量,移除名称匹配 `*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..e36bfb5699 --- /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: e5613ec07023429d + zh: 9272c9ae5718060a +/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..25281e96fb --- /dev/null +++ b/docs/defensive-patterns/remote-and-api.md @@ -0,0 +1,114 @@ +# 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 four 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; and existing method and field names are additive. 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, and a rename breaks every caller in the same change. + +- **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.`. +- **Not covered.** A method without the decorator stays an ordinary service method with in-process callers; the four 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..1a9c291d9c --- /dev/null +++ b/docs/defensive-patterns/remote-and-api.zh.md @@ -0,0 +1,114 @@ +# 远程与 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;既有的方法与字段名只增不改。每项纪律消除一类不同的缺陷——壳方法藏起真正暴露的是哪个操作,手写的第二份类型会与生成结果漂移,输出侧 decode 在 Gateway 已有的 codec 之外再造一条结果路径,改名则让所有调用方在同一次变更里一起断掉。 + +- **标能力方法。** 标注落在执行该操作的具体方法上(`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.` 暴露的名字。 +- **不覆盖。** 不带该标注的方法仍是有进程内调用者的普通 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.zh.md b/docs/development.zh.md index 3154c4d988..5446ee3a89 100644 --- a/docs/development.zh.md +++ b/docs/development.zh.md @@ -109,6 +109,7 @@ pnpm run build `pnpm run hygiene` 包含 `publint`(用构建出的 `lib/*.js` 文件校验包入口点)和 `verify-node-next-types`(用一个临时的 NodeNext 消费方校验构建出的声明文件)。新 worktree 在 `pnpm run build` 运行之前没有打包的 JS 和声明文件;普通提交和推送无需构建,除非所选检查会使用这些产物。 + ### 环境变量 真实的 DeepSeek 适配器和需要密钥的 agent 演示从环境变量或仓库根目录一个被 gitignore 的 `.env` 文件读取凭证: diff --git a/docs/subsystems/conversation.i18n.yaml b/docs/subsystems/conversation.i18n.yaml index b8f7380bbf..d53eb92d3b 100644 --- a/docs/subsystems/conversation.i18n.yaml +++ b/docs/subsystems/conversation.i18n.yaml @@ -16,7 +16,7 @@ zh: 787ad4d04b79adaf /conversation-assembly/replayable-event-families: en: c216e2df128b8cb9 - zh: e61312f1f280332d + zh: c039cf84b0d86ad8 /conversation-assembly/definition-and-typed-chat-payload: en: 5f24557a050d1df0 zh: 47735627f802b6fa diff --git a/docs/subsystems/conversation.zh.md b/docs/subsystems/conversation.zh.md index 7115bb90b8..7678e2b78c 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 插件。 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.zh.md b/docs/subsystems/core.zh.md index 582a817f1f..beb65f2c60 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)** 中。 + + ## 全仓通用类型模式 两个模式在每个子系统中反复出现,只在此处记录一次。 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 f56417148e..7c6f634157 100644 --- a/docs/subsystems/ptc-runtime.i18n.yaml +++ b/docs/subsystems/ptc-runtime.i18n.yaml @@ -12,8 +12,8 @@ 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 afcf5237a9..d9ad8138a0 100644 --- a/docs/subsystems/ptc-runtime.md +++ b/docs/subsystems/ptc-runtime.md @@ -177,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. diff --git a/docs/subsystems/ptc-runtime.zh.md b/docs/subsystems/ptc-runtime.zh.md index 64134149d2..ba747b5369 100644 --- a/docs/subsystems/ptc-runtime.zh.md +++ b/docs/subsystems/ptc-runtime.zh.md @@ -177,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. 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/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 aec206af8c..1dd04a5ab9 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -10,7 +10,7 @@ zh: 441ed13ff3f81d2a /web-client-slots/cardinality-and-scope: en: 5b0ada069239576b - zh: 7e71ced7f17d78a6 + zh: 84e1e6b253d1461e /web-client-slots/component-inputs: en: 9cb70abb2e39b958 zh: cd4b6f1705d90e17 @@ -18,11 +18,11 @@ en: 2fcfc55fbac80f72 zh: ea3016f394c56b07 /web-client-slots/developer-provided-injection: - en: 4fb5222bb2b064e7 - zh: b961f792052b4ce5 -/web-client-slots/current-hierarchy: - en: 8a4cc4b8608ce0f6 - zh: 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 c0fa352a4f..30f8acedb4 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -108,92 +108,84 @@ The owner of a slot may put an `inject` face in the child declaration when every Use owner props for values already known at one render occurrence, registration `inject` for one entry's callbacks and private observables, slot-level `inject` for a capability controlled by the slot owner, and a declared store for mutable view state shared across entries or preserved across remounts. React nodes compose through child slots, not through injected values. -## Current hierarchy + -The hierarchy below is the shipped declaration tree. A child exists only while the named parent entry is mounted; optional feature entries can therefore make a subtree appear or disappear as one lifecycle unit. +## Conversation hierarchy + +The following Conversation paths distinguish declaration owners from reusable Factory roots; unrelated shell positions are omitted. An entry owns its declared children, while a Factory owns its child declarations for the lifetime of its registered definition. Bracketed names identify the default React components; a plain React descendant can render its owner's Slot. Factory calls are references to independent reusable definitions, not new Slot declarations. ```text -root -├─ sidebar -│ ├─ sidebar.brand.mark -│ ├─ sidebar.brand.name -│ ├─ sidebar.panellist -│ ├─ sidebar.footer.action -│ ├─ sidebar.workspaces -│ │ ├─ sidebar.workspaces.directoryFlow -│ │ ├─ sidebar.workspaces.session.menu.item -│ │ └─ sidebar.workspaces.session.row.action -│ └─ sidebar.settings -│ ├─ settings.trigger -│ ├─ settings.header -│ ├─ settings.action -│ ├─ settings.close -│ ├─ settings.onboarding -│ └─ settings.section -│ ├─ settings.general.item -│ ├─ settings.models.provider-card -│ ├─ settings.models.footer -│ └─ settings.plugins.tab -├─ main -│ ├─ plugins.add.actions -│ ├─ plugins.item -│ ├─ plugins.bundle.config -│ ├─ plugins.row.config -│ ├─ plugins.detail.actions -│ ├─ plugins.detail.badge -│ ├─ plugins.detail.section -│ └─ main.conversation -│ ├─ conversation.session -│ │ └─ conversation.view -│ │ ├─ conversation.chat.flow -│ │ │ ├─ conversation.chat.node -│ │ │ │ ├─ conversation.chat.assistant-actions -│ │ │ │ ├─ conversation.chat.reasoning.body -│ │ │ │ ├─ conversation.chat.commandview -│ │ │ │ ├─ conversation.chat.turnTail -│ │ │ │ └─ tool.call.toolview -│ │ │ │ ├─ tool.call.images -│ │ │ │ └─ tool.view.cordis -│ │ │ └─ conversation.message.images -│ │ └─ conversation.trajectory.images -│ ├─ conversation.header -│ │ ├─ conversation.header.leading -│ │ └─ conversation.session.header -│ │ ├─ conversation.session.header.lineage -│ │ ├─ conversation.session.header.actions -│ │ ├─ conversation.session.header.utilities -│ │ └─ conversation.session.header.corner -│ ├─ conversation.composer -│ │ ├─ conversation.approval.detail -│ │ └─ conversation.plan-review.actions -│ ├─ conversation.composer.bar -│ │ ├─ conversation.input.attachments -│ │ ├─ conversation.input.permission -│ │ ├─ conversation.input.plan -│ │ └─ conversation.input.model -│ ├─ conversation.input.overlay -│ ├─ conversation.input.dock -│ ├─ conversation.composer.dock -│ ├─ conversation.input.left -│ ├─ conversation.input.right -│ ├─ conversation.hero.brand.mark -│ ├─ conversation.hero.workspace -│ │ └─ conversation.hero.workspace.directoryFlow -│ └─ conversation.hero.agentPreset -├─ rightbar -│ └─ rightbar.session -│ ├─ sidebar.right.pane.tab -│ │ ├─ sidebar.right.tab.guide -│ │ └─ sidebar.right.tab.guide.entry -│ ├─ sidebar.right.pane.tab.title -│ └─ sidebar.right.tab.menu.item -├─ shell.bottom -├─ shell.leading -└─ shell.overlay - └─ shell.quota-notice +root [AppFrame] +└─ main[key=conversation] [ConversationPanel] + └─ main.conversation [ConversationRoot / ConversationMainPanel] + ├─ conversation.header [ConversationHeader] + │ ├─ conversation.header.leading + │ └─ conversation.session.header [ConversationSessionHeader] + │ ├─ conversation.session.header.lineage + │ ├─ conversation.session.header.actions + │ ├─ conversation.session.header.utilities + │ └─ conversation.session.header.corner + └─ calls Factory: conversation.content + +Factory: conversation.content [ConversationContent] +├─ conversation.session [ConversationSession / DefaultConversationViews] +│ └─ conversation.view +│ ├─ id=chat [ChatView] +│ │ └─ conversation.chat.flow [ChatFlow] +│ │ └─ conversation.chat.node [ChatNodeSeat dispatch] +│ │ ├─ key=user,steering [UserMessageNodeView] +│ │ │ └─ calls Factory: conversation.chat.user.content +│ │ ├─ key=assistant-step [AssistantNodeView / AssistantMarkdown] +│ │ │ ├─ conversation.chat.message.images [MessageImages] +│ │ │ └─ conversation.chat.reasoning.body [DefaultReasoningBody] +│ │ │ └─ calls Factory: conversation.chat.reasoning.content +│ │ ├─ key=tool-call [ToolCallTree] +│ │ │ └─ tool.call.toolview +│ │ │ └─ key=read_image [ReadImageRow / ToolRow] +│ │ │ └─ tool.call.images [MessageImages] +│ │ ├─ key=command-input [GoalCommandInputView] +│ │ │ └─ calls Factory: conversation.user.text +│ │ ├─ key=command [CommandNodeView] +│ │ │ └─ conversation.chat.commandview +│ │ └─ key=turn-tail [TurnTailNodeView] +│ │ ├─ conversation.chat.turnTail +│ │ └─ conversation.chat.assistant-actions +│ └─ id=trajectory [TrajectoryView / TrajectoryTable] +│ └─ conversation.trajectory.images [MessageImages] +├─ conversation.composer +│ ├─ conversation.approval.detail +│ └─ conversation.plan-review.actions +├─ conversation.composer.bar [InputBar] +│ ├─ conversation.input.attachments +│ ├─ conversation.input.permission +│ ├─ conversation.input.plan +│ ├─ conversation.input.model +│ ├─ conversation.input.overlay +│ ├─ conversation.composer.dock +│ ├─ conversation.input.left +│ └─ conversation.input.right +├─ conversation.input.dock +│ └─ id=queue [QueueDock] +│ └─ calls Factory: conversation.user.text +├─ conversation.hero.brand.mark +├─ conversation.hero.workspace +│ └─ conversation.hero.workspace.directoryFlow +└─ conversation.hero.agentPreset + +Factory: conversation.chat.user.content [UserContent] +├─ conversation.chat.user.images [MessageImages] +└─ calls Factory: conversation.user.text + +Factory: conversation.user.text [UserText] +└─ conversation.user.text.node [keyed, inline] + +Factory: conversation.images.content [MessageImagesContent / ImageGallery] +Factory: conversation.chat.reasoning.content [ReasoningContent / MarkdownText] ``` -The generated Client inspect catalog is the exhaustive contract for each key: cardinality, scope, owner props, standard props, current occupants, declaration owner, and replacement risk. A running dynamic package can query the live tree and an exact key with `cordis_inspect what:"client"`; the source catalog is generated from `SlotMap` declarations and `slots.register()` call sites by `pnpm run gen-client-catalog`. +All four image Slots default to `MessageImages`, which calls `conversation.images.content` with the caller's image references and authorized loader. User and output image replacements are independent. The `conversation.user.text` Factory is shared by user content, Queue, and Goal; its `inline: true` keyed Slot renders span anchors and inline error placeholders rather than block wrappers. + +The generated [Client inspect catalog](../../packages/extensions/cordis-client-runner/src/client/slot-catalog.ts) covers all shell branches and is the exhaustive contract for each key: cardinality, scope, owner props, standard props, current occupants, declaration owner, and replacement risk. A running dynamic package can query the live tree and an exact key with `cordis_inspect what:"client"`; the source catalog is generated from `SlotMap` declarations and `slots.register()` call sites by `pnpm run gen-client-catalog`. ## Extension rules diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index 3689583543..a660f720e4 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,不要重新抄写成员。 @@ -108,92 +110,86 @@ Renderer 还会根据声明的 store 创建 `useStore`,并根据声明的 loca 一次渲染时 owner 已知的值走 owner props;单个 entry 的 callback 与私有 observable 走注册项 `inject`;由 slot owner 控制、所有 occupant 共享的能力走 slot 级 `inject`;需要跨 entry 共享或跨重新挂载保留的可变视图状态走声明的 store。React node 通过 child slot 组合,不通过注入值传递。 -## 当前层级 + -下图是当前发布组合的声明树。只有具名 parent entry 已挂载时,其 child 才存在;因此可选功能 entry 可以作为一个生命周期单元让整棵子树出现或消失。 +## Conversation 层级 + +下面的 Conversation 路径区分声明所有者与可复用 Factory 根,省略无关的外壳位置。条目拥有其声明的子 Slot;Factory 在其定义注册期间拥有子 Slot 声明。方括号标出默认 React 组件,普通 React 后代组件可以渲染其所有者的 Slot。Factory 调用指向独立的可复用定义,不是新的 Slot 声明。 ```text -root -├─ sidebar -│ ├─ sidebar.brand.mark -│ ├─ sidebar.brand.name -│ ├─ sidebar.panellist -│ ├─ sidebar.footer.action -│ ├─ sidebar.workspaces -│ │ ├─ sidebar.workspaces.directoryFlow -│ │ ├─ sidebar.workspaces.session.menu.item -│ │ └─ sidebar.workspaces.session.row.action -│ └─ sidebar.settings -│ ├─ settings.trigger -│ ├─ settings.header -│ ├─ settings.action -│ ├─ settings.close -│ ├─ settings.onboarding -│ └─ settings.section -│ ├─ settings.general.item -│ ├─ settings.models.provider-card -│ ├─ settings.models.footer -│ └─ settings.plugins.tab -├─ main -│ ├─ plugins.add.actions -│ ├─ plugins.item -│ ├─ plugins.bundle.config -│ ├─ plugins.row.config -│ ├─ plugins.detail.actions -│ ├─ plugins.detail.badge -│ ├─ plugins.detail.section -│ └─ main.conversation -│ ├─ conversation.session -│ │ └─ conversation.view -│ │ ├─ conversation.chat.flow -│ │ │ ├─ conversation.chat.node -│ │ │ │ ├─ conversation.chat.assistant-actions -│ │ │ │ ├─ conversation.chat.reasoning.body -│ │ │ │ ├─ conversation.chat.commandview -│ │ │ │ ├─ conversation.chat.turnTail -│ │ │ │ └─ tool.call.toolview -│ │ │ │ ├─ tool.call.images -│ │ │ │ └─ tool.view.cordis -│ │ │ └─ conversation.message.images -│ │ └─ conversation.trajectory.images -│ ├─ conversation.header -│ │ ├─ conversation.header.leading -│ │ └─ conversation.session.header -│ │ ├─ conversation.session.header.lineage -│ │ ├─ conversation.session.header.actions -│ │ ├─ conversation.session.header.utilities -│ │ └─ conversation.session.header.corner -│ ├─ conversation.composer -│ │ ├─ conversation.approval.detail -│ │ └─ conversation.plan-review.actions -│ ├─ conversation.composer.bar -│ │ ├─ conversation.input.attachments -│ │ ├─ conversation.input.permission -│ │ ├─ conversation.input.plan -│ │ └─ conversation.input.model -│ ├─ conversation.input.overlay -│ ├─ conversation.input.dock -│ ├─ conversation.composer.dock -│ ├─ conversation.input.left -│ ├─ conversation.input.right -│ ├─ conversation.hero.brand.mark -│ ├─ conversation.hero.workspace -│ │ └─ conversation.hero.workspace.directoryFlow -│ └─ conversation.hero.agentPreset -├─ rightbar -│ └─ rightbar.session -│ ├─ sidebar.right.pane.tab -│ │ ├─ sidebar.right.tab.guide -│ │ └─ sidebar.right.tab.guide.entry -│ ├─ sidebar.right.pane.tab.title -│ └─ sidebar.right.tab.menu.item -├─ shell.bottom -├─ shell.leading -└─ shell.overlay - └─ shell.quota-notice +root [AppFrame] +└─ main[key=conversation] [ConversationPanel] + └─ main.conversation [ConversationRoot / ConversationMainPanel] + ├─ conversation.header [ConversationHeader] + │ ├─ conversation.header.leading + │ └─ conversation.session.header [ConversationSessionHeader] + │ ├─ conversation.session.header.lineage + │ ├─ conversation.session.header.actions + │ ├─ conversation.session.header.utilities + │ └─ conversation.session.header.corner + └─ calls Factory: conversation.content + +Factory: conversation.content [ConversationContent] +├─ conversation.session [ConversationSession / DefaultConversationViews] +│ └─ conversation.view +│ ├─ id=chat [ChatView] +│ │ └─ conversation.chat.flow [ChatFlow] +│ │ └─ conversation.chat.node [ChatNodeSeat dispatch] +│ │ ├─ key=user,steering [UserMessageNodeView] +│ │ │ └─ calls Factory: conversation.chat.user.content +│ │ ├─ key=assistant-step [AssistantNodeView / AssistantMarkdown] +│ │ │ ├─ conversation.chat.message.images [MessageImages] +│ │ │ └─ conversation.chat.reasoning.body [DefaultReasoningBody] +│ │ │ └─ calls Factory: conversation.chat.reasoning.content +│ │ ├─ key=tool-call [ToolCallTree] +│ │ │ └─ tool.call.toolview +│ │ │ └─ key=read_image [ReadImageRow / ToolRow] +│ │ │ └─ tool.call.images [MessageImages] +│ │ ├─ key=command-input [GoalCommandInputView] +│ │ │ └─ calls Factory: conversation.user.text +│ │ ├─ key=command [CommandNodeView] +│ │ │ └─ conversation.chat.commandview +│ │ └─ key=turn-tail [TurnTailNodeView] +│ │ ├─ conversation.chat.turnTail +│ │ └─ conversation.chat.assistant-actions +│ └─ id=trajectory [TrajectoryView / TrajectoryTable] +│ └─ conversation.trajectory.images [MessageImages] +├─ conversation.composer +│ ├─ conversation.approval.detail +│ └─ conversation.plan-review.actions +├─ conversation.composer.bar [InputBar] +│ ├─ conversation.input.attachments +│ ├─ conversation.input.permission +│ ├─ conversation.input.plan +│ ├─ conversation.input.model +│ ├─ conversation.input.overlay +│ ├─ conversation.composer.dock +│ ├─ conversation.input.left +│ └─ conversation.input.right +├─ conversation.input.dock +│ └─ id=queue [QueueDock] +│ └─ calls Factory: conversation.user.text +├─ conversation.hero.brand.mark +├─ conversation.hero.workspace +│ └─ conversation.hero.workspace.directoryFlow +└─ conversation.hero.agentPreset + +Factory: conversation.chat.user.content [UserContent] +├─ conversation.chat.user.images [MessageImages] +└─ calls Factory: conversation.user.text + +Factory: conversation.user.text [UserText] +└─ conversation.user.text.node [keyed, inline] + +Factory: conversation.images.content [MessageImagesContent / ImageGallery] +Factory: conversation.chat.reasoning.content [ReasoningContent / MarkdownText] ``` -生成的 Client inspect catalog 是每个 key 的完整参考,包含 cardinality、scope、owner props、标准 props、当前 occupant、声明 owner 与替换风险。运行中的动态包可以用 `cordis_inspect what:"client"` 查询实时树与某个精确 key;源码 catalog 由 `pnpm run gen-client-catalog` 根据 `SlotMap` 声明和 `slots.register()` 调用点生成。 +四个图片 Slot 默认均填入 `MessageImages`,由它携带调用者的图片引用和授权 loader 调用 `conversation.images.content`。用户与输出图片的替换互不影响。`conversation.user.text` Factory 由用户内容、Queue 和 Goal 共用;其 `inline: true` keyed Slot 使用 span 锚点及行内错误占位,而不是块级包装。 + +生成的 [Client inspect catalog](../../packages/extensions/cordis-client-runner/src/client/slot-catalog.ts) 是包含所有外壳分支及每个 key 的完整参考,包含 cardinality、scope、owner props、标准 props、当前 occupant、声明 owner 与替换风险。运行中的动态包可以用 `cordis_inspect what:"client"` 查询实时树与某个精确 key;源码 catalog 由 `pnpm run gen-client-catalog` 根据 `SlotMap` 声明和 `slots.register()` 调用点生成。 + + ## 扩展规则 diff --git a/docs/subsystems/workspace.i18n.yaml b/docs/subsystems/workspace.i18n.yaml index 7701312154..bf01196282 100644 --- a/docs/subsystems/workspace.i18n.yaml +++ b/docs/subsystems/workspace.i18n.yaml @@ -9,8 +9,8 @@ en: d61a7e78bbc1fb56 zh: 8397869f70cd5b28 /workspaces/the-workspace-entity: - en: 697698bc46adc477 - zh: 73d073933ed68c53 + en: ce5b65fb4d0b0c7b + zh: aa332a17810d583a /workspaces/the-registry-ctx-workspaceregistry: en: 73b54ccf836b7f46 zh: 7ee93ba8bb0a616a diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index e501d7b7bb..8e69b7c597 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -25,9 +25,10 @@ Consumers see only the `Workspace` interface; the implementation stays package-p ```ts type-equiv /** * One workspace: a stable id over an existing directory, a display title, and - * an ordered candidate account of sessions. Membership requires both an id in - * that account and a session header whose canonical cwd equals the workspace - * path. Consumers only see this interface; the implementation stays private. + * an ordered candidate account of sessions. Membership validates header cwd + * against the workspace path, but preserves an existing account when its + * fully qualified cwd is missing. Consumers only see this interface; the + * implementation stays private. */ interface Workspace { /** Stable record id (generated uuid). */ @@ -54,8 +55,11 @@ interface Workspace { * prepended at attach, explicit reordering goes through * `insertSessionBefore`, and activity never reorders. The durable candidate * account is filtered synchronously: missing headers, invalid cwd values, - * and canonical cwd mismatches are never returned. A subsequent workspace - * mutation prunes those filtered candidates durably. + * and canonical cwd mismatches are never returned. A fully qualified cwd + * whose realpath or directory stat fails with ENOENT preserves an existing + * candidate, including a dangling symlink; other filesystem failures do not. + * A subsequent mutation prunes filtered candidates, not missing-directory + * candidates. This does not admit new sessions or recreate directories. */ readonly sessionIds: readonly SessionId[] @@ -113,7 +117,7 @@ interface Workspace { } ``` -Ownership truth is the record's ordered `sessionIds`, never derived from session cwd — but membership requires both: an id on the account and a header whose canonical cwd equals the workspace path, so one session structurally belongs to at most one workspace. Failed writes reject (`insertSessionBefore` account errors as `WorkspaceMoveInvalidError`, storage failures as plain errors); every accepted mutation stamps `updatedAt` and durably prunes candidates that no longer pass the membership check. +Ownership truth is the record's ordered `sessionIds`, never derived from session cwd. Membership validates the recorded header cwd against the workspace path; an existing candidate remains owned when its fully qualified cwd fails resolution or directory stat with `ENOENT`. This preserves missing-directory and dangling-symlink accounts without admitting new sessions. Failed writes reject (`insertSessionBefore` account errors as `WorkspaceMoveInvalidError`, storage failures as plain errors); every accepted mutation stamps `updatedAt` and durably prunes candidates that no longer pass the membership check. ## The registry: `ctx.workspaceRegistry` diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 868712b4c9..4c15fc2ffd 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -25,9 +25,10 @@ type WorkspaceId = Branded<'WorkspaceId'> ```ts type-equiv /** * One workspace: a stable id over an existing directory, a display title, and - * an ordered candidate account of sessions. Membership requires both an id in - * that account and a session header whose canonical cwd equals the workspace - * path. Consumers only see this interface; the implementation stays private. + * an ordered candidate account of sessions. Membership validates header cwd + * against the workspace path, but preserves an existing account when its + * fully qualified cwd is missing. Consumers only see this interface; the + * implementation stays private. */ interface Workspace { /** Stable record id (generated uuid). */ @@ -54,8 +55,11 @@ interface Workspace { * prepended at attach, explicit reordering goes through * `insertSessionBefore`, and activity never reorders. The durable candidate * account is filtered synchronously: missing headers, invalid cwd values, - * and canonical cwd mismatches are never returned. A subsequent workspace - * mutation prunes those filtered candidates durably. + * and canonical cwd mismatches are never returned. A fully qualified cwd + * whose realpath or directory stat fails with ENOENT preserves an existing + * candidate, including a dangling symlink; other filesystem failures do not. + * A subsequent mutation prunes filtered candidates, not missing-directory + * candidates. This does not admit new sessions or recreate directories. */ readonly sessionIds: readonly SessionId[] @@ -113,7 +117,7 @@ interface Workspace { } ``` -所有权的真源是记录中有序的 `sessionIds`,绝不从会话 cwd 派生——但成员资格要求两者同时成立:账本上有其 id,且 header 的规范 cwd 等于工作区路径,因此一个会话在结构上至多属于一个工作区。失败的写入会拒绝(`insertSessionBefore` 的账本错误以 `WorkspaceMoveInvalidError` 拒绝,存储失败以普通错误拒绝);每次被接受的变更都盖上 `updatedAt` 时间戳,并持久修剪不再通过成员资格检查的候选项。 +所有权的真源是记录中有序的 `sessionIds`,绝不从会话 cwd 派生。成员资格将记录的 header cwd 与工作区路径校验;已有候选的完全限定 cwd 在路径解析或目录 stat 时返回 `ENOENT`,仍保留其归属。这会保留目录缺失或符号链接失效时的记账关系,但不会接纳新会话。失败的写入会拒绝(`insertSessionBefore` 的账本错误以 `WorkspaceMoveInvalidError` 拒绝,存储失败以普通错误拒绝);每次被接受的变更都盖上 `updatedAt` 时间戳,并持久修剪不再通过成员资格检查的候选项。 ## 注册表:`ctx.workspaceRegistry` diff --git a/docs/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/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/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/package.json b/package.json index 9a56e4005b..fc55ddc23f 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", @@ -239,6 +239,7 @@ "@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/semver": "^7.8.0", "@types/spdx-expression-parse": "^4.0.0", @@ -263,6 +264,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 5a9e332ce9..ee019fe922 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/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 ae3bfe24a1..fd3a002a5d 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", @@ -44,7 +46,7 @@ ], "license": "MIT", "dependencies": { - "zod": "^4.4.3" + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", 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 0ee56662b0..d4469cf8cd 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", @@ -75,6 +77,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/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 f9fd59429b..a82912d8bf 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", @@ -67,7 +69,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/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 f09b9a96ae..1ac78ce12f 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", @@ -86,7 +88,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/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 b18ac92fbe..436b151bbb 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", @@ -73,7 +75,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:~", 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 ded8c8bf22..6c72102b61 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", @@ -45,7 +47,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/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 9b67bd26cc..d9ade0d77a 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": { @@ -60,7 +61,7 @@ "@deepseek-ai/schemastery": "workspace:~", "@xterm/headless": "^6.0.0", "@xterm/addon-serialize": "^0.14.0", - "zod": "^4.4.3" + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/dsh-subprocess": "workspace:*", @@ -84,6 +85,7 @@ "@deepseek-ai/dsh-working-directory": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.js", diff --git a/packages/api/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 118a4772a9..ac9d45a3e1 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", @@ -72,7 +74,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:~", 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 01a35b7da2..f77a965ad0 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:~" @@ -74,6 +75,7 @@ "@deepseek-ai/dsh-util-workspace-path": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.js", diff --git a/packages/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 810513ab0e..f40c826a40 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,19 @@ "main": "lib/index.js", "types": "lib/types/index.d.ts", "exports": { - ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, - "files": ["lib/index.js", "lib/types/**/*.d.ts"], + "files": [ + "locale/*.json", + "lib/index.js", + "lib/types/**/*.d.ts" + ], "license": "MIT", "peerDependencies": { "@deepseek-ai/dsh-attachment": "workspace:*", @@ -28,7 +36,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 e119eb4700..be1f97916f 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/package.json b/packages/boot/app-boot/package.json index 2050837c3b..a7a8e5646e 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" }, diff --git a/packages/boot/cmdline/package.json b/packages/boot/cmdline/package.json index c6ea6cb37a..7d8f6d2b37 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/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 346d9d4442..9d5e4dd44e 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" ], diff --git a/packages/boot/hmr/README.i18n.yaml b/packages/boot/hmr/README.i18n.yaml index 4f1eef45bf..0c7fcc7a1f 100644 --- a/packages/boot/hmr/README.i18n.yaml +++ b/packages/boot/hmr/README.i18n.yaml @@ -21,8 +21,8 @@ en: 45ee194ad781d603 zh: b3d7fcd8ed73717c /deepseek-ai-dsh-hmr/understand-the-implementation: - en: 227c3c99c3c4b597 - zh: 853b656340cb8bce + en: 8c19121bdb5176c1 + zh: 8a01a60ecca6175c /deepseek-ai-dsh-hmr/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 diff --git a/packages/boot/hmr/README.md b/packages/boot/hmr/README.md index 513abc07b2..97ee67c8e9 100644 --- a/packages/boot/hmr/README.md +++ b/packages/boot/hmr/README.md @@ -54,7 +54,7 @@ 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. diff --git a/packages/boot/hmr/README.zh.md b/packages/boot/hmr/README.zh.md index ba99733ccf..a7a9f84b1b 100644 --- a/packages/boot/hmr/README.zh.md +++ b/packages/boot/hmr/README.zh.md @@ -54,7 +54,7 @@ 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 时会关闭监听器并取消等待启动的重载。配置监听器在当前事务上下文之外启动,使后续通知可以进入队列。 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 9460462734..5c86376b65 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" ], @@ -37,7 +39,7 @@ }, "dependencies": { "@babel/code-frame": "^7.29.0", - "chokidar": "^4.0.3", + "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/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/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/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 c6fc6af78a..756d5adb93 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", @@ -61,7 +65,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": { diff --git a/packages/browser-use/browser-use/package.json b/packages/browser-use/browser-use/package.json index 8178f5d01d..88f9365e81 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 d1d12860c2..525414a75b 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..9e3f03eefc 100644 --- a/packages/bundle/base/cordis.patch.yml +++ b/packages/bundle/base/cordis.patch.yml @@ -328,7 +328,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 be152900d3..fa80fcfb55 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" }, diff --git a/packages/bundle/headless/package.json b/packages/bundle/headless/package.json index cf2dc9f38f..1eea38a9f0 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/sdk-app/README.i18n.yaml b/packages/bundle/sdk-app/README.i18n.yaml index ca0a12fc89..fb39b99573 100644 --- a/packages/bundle/sdk-app/README.i18n.yaml +++ b/packages/bundle/sdk-app/README.i18n.yaml @@ -15,8 +15,8 @@ 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 diff --git a/packages/bundle/sdk-app/README.md b/packages/bundle/sdk-app/README.md index e2615fc435..a149ec1254 100644 --- a/packages/bundle/sdk-app/README.md +++ b/packages/bundle/sdk-app/README.md @@ -33,7 +33,7 @@ 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. ----- diff --git a/packages/bundle/sdk-app/README.zh.md b/packages/bundle/sdk-app/README.zh.md index 610f4bef5c..f244072935 100644 --- a/packages/bundle/sdk-app/README.zh.md +++ b/packages/bundle/sdk-app/README.zh.md @@ -33,7 +33,7 @@ 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)。 ----- diff --git a/packages/bundle/sdk-app/cordis.patch.yml b/packages/bundle/sdk-app/cordis.patch.yml index 1c0beaae95..004a81ce9b 100644 --- a/packages/bundle/sdk-app/cordis.patch.yml +++ b/packages/bundle/sdk-app/cordis.patch.yml @@ -29,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 fdfc1d2ad3..389582f50c 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/package.json b/packages/bundle/sdk-minimal/package.json index df59eaae4d..e952695405 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" }, 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 81c3782121..dd002b596b 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", + "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", diff --git a/packages/bundle/web-app/presets/cordis.patch.yml b/packages/bundle/web-app/presets/cordis.patch.yml index 277176f1a0..8c8d567ae3 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. diff --git a/packages/bundle/web-app/presets/ptc.patch.yml b/packages/bundle/web-app/presets/ptc.patch.yml index 1aed4cb9e9..8e1ec1fb70 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. diff --git a/packages/bundle/web-app/presets/standard.patch.yml b/packages/bundle/web-app/presets/standard.patch.yml index f2a9e080fe..6a42d0a351 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. diff --git a/packages/client/AGENTS.md b/packages/client/AGENTS.md index 2d39d6b3ca..3d38aa71fd 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) @@ -73,11 +76,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. @@ -150,7 +153,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/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 b233722f10..21e395fb6f 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/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 eecaa28d28..7c5f43b873 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", @@ -62,7 +64,7 @@ "lib/typert.remote-client.d.ts" ], "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/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 373c176123..3fd0ca2c4d 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/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 a1577330a2..e04ed4efd9 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": { @@ -60,6 +61,7 @@ "@deepseek-ai/schemastery": "workspace:~" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" 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 497adf5366..c9d0440c04 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/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 a7a8b4cddc..a8240ccc6b 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", @@ -77,6 +79,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/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 531d64def9..1790c6ac68 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/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 76f34297ec..8bc13120c6 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/store/package.json b/packages/client/store/package.json index e6284b5e8c..a0b08df37f 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/tsdown.client.ts b/packages/client/tsdown.client.ts index 2e8c06b18e..9d9053ded3 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -490,7 +490,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..4205a9cf81 100644 --- a/packages/client/ui-agent-preset/README.i18n.yaml +++ b/packages/client/ui-agent-preset/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: b3ad7867f23dad1c /deepseek-ai-dsh-client-ui-agent-preset/use-this-package: - en: d616984e840f036e - zh: 3e7c97c7d10669eb + en: a21296842d6e18da + zh: 75f3a6a79691884f /deepseek-ai-dsh-client-ui-agent-preset/understand-the-implementation: en: b3221ef8bc6d8096 zh: 68cb05566249da10 diff --git a/packages/client/ui-agent-preset/README.md b/packages/client/ui-agent-preset/README.md index 09df3e46f3..75f778ff62 100644 --- a/packages/client/ui-agent-preset/README.md +++ b/packages/client/ui-agent-preset/README.md @@ -29,7 +29,7 @@ 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. diff --git a/packages/client/ui-agent-preset/README.zh.md b/packages/client/ui-agent-preset/README.zh.md index 7514fc9953..735d008239 100644 --- a/packages/client/ui-agent-preset/README.zh.md +++ b/packages/client/ui-agent-preset/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" 关闭通用设置中的代码工作工具后,新会话选择器和设置页列表提供标准、创造和自定义预设;开启后还提供 PTC 和极简模式。两种状态下均保留默认值选择和创造入口。选择健康定义作为默认值也会同步当前新任务页面的空白会话。Creator 入口开启一个使用 `cordis` preset 的新任务。 -关闭代码工作工具时,沿用现有 Developer tools 订阅清空所有尚未应用的选择。关闭状态被接受后,使用 Host 持久化设置的连接会将已保存的内置 PTC 或极简默认值回退为标准模式。已保存的标准、创造和自定义默认值(包括有名称的 PTC 或极简覆盖项)保持不变。关闭后用户仍可重新选择可用预设。已有会话保留所选模式;新会话使用当前默认值。即使已有会话的模式不在菜单中,其标签仍会显示。重新开启代码工作工具不会恢复原默认值或已清除的选择。使用内存设置的远程连接不会改写 Host 的默认值。标准模式缺失或损坏时,默认值保持不变,并显示错误。 +关闭代码工作工具时,沿用现有 Developer tools 订阅清空所有尚未应用的选择。关闭状态被接受后,每个已认证浏览器都会将已保存的内置 PTC 或极简默认值回退为标准模式。已保存的标准、创造和自定义默认值(包括有名称的 PTC 或极简覆盖项)保持不变。关闭后用户仍可重新选择可用预设。已有会话保留所选模式;新会话使用当前默认值。即使已有会话的模式不在菜单中,其标签仍会显示。重新开启代码工作工具不会恢复原默认值或已清除的选择。标准模式缺失或损坏时,默认值保持不变,并显示错误。 已知的内置预设提供只读的模式说明与使用示例对话框。各页签保留各自的滚动位置;关闭后焦点回到打开它的操作。帮助不会改变新任务默认值。默认徽标取代卡片的分组徽标,预设 id 显示在标题旁。指南文案与示例归本包所有。 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 d65a284667..3549bf1ad5 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": { @@ -71,6 +72,7 @@ "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-agent-preset/src/client/index.ts b/packages/client/ui-agent-preset/src/client/index.ts index 184b7fd791..1abeb855be 100644 --- a/packages/client/ui-agent-preset/src/client/index.ts +++ b/packages/client/ui-agent-preset/src/client/index.ts @@ -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() 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..aa52b2c3d7 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 => { @@ -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() 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-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 4d8ef679e1..19e91693f8 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": { @@ -64,6 +65,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-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 e37afaf50d..4937ea4263 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", @@ -46,6 +48,7 @@ "@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 +62,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-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 b4587a84ac..263c0eef6a 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": { @@ -53,6 +54,7 @@ "react-dom": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 1be8b3526e..3077ce4752 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: 0c63ffa8f245050e - zh: f421d1a569b16c3d + en: 4cd7c81d70d2f365 + zh: 18eca6d16e44b6c2 /deepseek-ai-dsh-client-ui-chat/grouped-rendering: - en: 8b2586e6b9f188a7 - zh: 6687f9e67432d04f + en: 106438891c5175ce + zh: 34dd30092f34f49b /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: 838659819e09413d - zh: 43c754f34c193fff + en: 3f4e6c161b4583bb + zh: e4265bb2bce8eb1c /deepseek-ai-dsh-client-ui-chat/model-experience: en: c17b4dd43a61c569 zh: f7414309810c3a08 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index a0e84873c3..b80ec590d6 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,7 +92,7 @@ When Chat ends with an open Turn control and that Turn has no visible input, the Work-details modes control process-group display and reasoning previews. Compact, Standard, and Detailed fold eligible completed Turns without hiding the final answer; Verbose retains the duration/status header without a collapse action and shows historical process rows directly. The [business-rule reference](src/client/conversation-nodes/README.md#display-modes) contains the mode table, title behavior, whole-Turn eligibility, clocks, and disclosure resets. -The Settings row below Work details offers an [independent collapse-timing preference](src/client/conversation-nodes/README.md#collapse-timing). +The Settings row below Work details offers an [independent collapse-timing preference](src/client/conversation-nodes/README.md#collapse-timing), saved through the same Host profile configuration. ----- @@ -109,7 +117,7 @@ Scroll-edge fades initialize when `ResizeObserver` reports the open group's layo Each group owns local `useDisclosure` state that survives mode changes while its component stays mounted. -The session-scoped `conversation.chat.reasoning.body` single Slot offers the original reasoning text and streaming state only when its body is expanded. Its official entry registers at priority 100 and calls the `conversation.chat.reasoning.content` Factory. A replacement uses a lower priority number and may call that same Factory with original or derived text. The root-scoped Factory requires no Session and fixes compact typography. Its optional `labels` accepts complete `MarkdownLabels` unchanged; omission uses Chat's localized defaults. The host supplies no inline fallback or plugin action state. Display extensions must preserve access to the original text and own their controls inside their Body wrapper. Extensions do not replace the reasoning preview or its disclosure policy. +The session-scoped `conversation.chat.reasoning.body` single Slot offers the original reasoning text and streaming state only when its body is expanded. Its official entry registers at priority 100 and calls the `conversation.chat.reasoning.content` Factory. A replacement uses a lower priority number and may call that same Factory with original or derived text. The root-scoped Factory requires no Session and fixes compact typography. Its optional `labels` accepts complete `MarkdownLabels` unchanged; omission uses Chat's localized defaults. The host supplies no inline fallback or plugin action state. Display extensions must preserve access to the original text and own their controls inside their Body wrapper. Extensions do not replace the reasoning preview or its disclosure policy. The [reasoning display rules](src/client/conversation-nodes/README.md#display-modes) define which blocks produce rows. The Chat-node slot injects a reset-bound `useDisclosure` Hook for reasoning and tools. Intermediate renderers forward it without subscribing; each invocation owns independent open state. Source callbacks retain their receiver and stable identity. When an enclosing Turn actually hides a process member, its seat resets those disclosures without replacing component keys or changing the Hook reference. Display-mode changes preserve their open state. @@ -120,6 +128,8 @@ Process rows share one text and icon color in every Work details mode: tertiary ## Scroll ownership +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. @@ -130,7 +140,9 @@ Outer transcript following and each open capped group's following are independen Next-message folding combines row closure and tail following in one cancellable task, with browser scroll anchoring disabled during the fold. If the removed height exceeds the new content's height, the difference remains as bottom space rather than reducing the scroll offset to chase the unpadded content floor. This applies even when the conversation already exceeds the viewport. New content fills the retained space before following advances again; a smaller fold leaves only the remaining forward distance to scroll. Reader gestures cancel the task and active native following; resize cannot revive a cancelled task in the same fold, but new submitted input can. Off-bottom readers retain their position, and acknowledged scrolling releases only space that can be removed without clamping them. Unloading Chat cancels waiting callbacks and row transitions. Reduced-motion users receive immediate visibility and positioning changes. -Fold coordination is viewport-local: reservations and idle callbacks never broadcast to other Chat views. ChatView supplies its motion capability once to `conversation.chat.flow` through the render's `hookContext`. Flow binds the group and header behavior hooks, owns node and image rendering, and shares the existing Chat store and Session node sources. Layout nodes and inline reasoning receive the bound hooks without receiving the motion controller or changing content parents. Generic searchable hiding applies before paint and owns focus protection and beforematch handling; pending-input reconciliation remains in ChatView. +Changing Work details clears reserved bottom space after active folds finish and reconciles the scroll range with the selected mode. Readers already following the tail stay at the new bottom; other readers are not forced to follow. + +Fold coordination is viewport-local: reservations and idle callbacks never broadcast to other Chat views. ChatView supplies its motion capability once to `conversation.chat.flow` through the render's `hookContext`. Flow binds the group and header behavior hooks, owns node dispatch, supplies Factory rendering for local echoes, and shares the existing Chat store and Session node sources. The image entry Factory owns the replaceable image Slot. Layout nodes and inline reasoning receive the bound hooks without receiving the motion controller or changing content parents. Generic searchable hiding applies before paint and owns focus protection and beforematch handling; pending-input reconciliation remains in ChatView. | Outer follows | Open group follows | Back-to-bottom button | New content | |---|---|---|---| diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index b1ea0eb081..c07cd9c21c 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,7 +92,7 @@ Chat 末尾为进行中的 Turn 控制行,且该轮尚无可见输入时,第 工作步骤展示模式控制过程组显示与推理预览。简洁、标准、详细模式收起符合条件的已完成轮次,不隐藏最终答案;完全展开模式保留时长或状态抬头,但不支持收起,历史过程行直接显示。[业务规则明细](src/client/conversation-nodes/README.zh.md#display-modes) 统一说明模式表、组头行为、整轮折叠资格、时钟与开合重置。 -工作步骤展示下方的设置行提供[独立的收起时机设置](src/client/conversation-nodes/README.zh.md#collapse-timing)。 +工作步骤展示下方的设置行提供[独立的收起时机设置](src/client/conversation-nodes/README.zh.md#collapse-timing),通过相同的 Host profile 配置保存。 ----- @@ -109,7 +117,7 @@ Chat Builder 按节点发布 `bottomSource`:节点可见且属于已加载时 每个组拥有本地 `useDisclosure` 状态,组件保持挂载时,模式切换保留该状态。 -Session 作用域的 `conversation.chat.reasoning.body` single Slot 仅在思考正文展开时提供原始思考文本和流式状态。官方条目以优先级 100 注册,并调用 `conversation.chat.reasoning.content` Factory。替换项使用更小的优先级数值,可向同一个 Factory 传入原文或派生显示文本。root 作用域的 Factory 不要求 Session,并固定使用紧凑排版。其可选 `labels` 原样接受完整的 `MarkdownLabels`,省略时使用 Chat 的默认本地化文案。宿主不提供内联 fallback 或插件操作状态。显示扩展必须保留查看原文的能力,并在自己的 Body 包装内维护控件。扩展不替换思考预览或展开策略。 +Session 作用域的 `conversation.chat.reasoning.body` single Slot 仅在思考正文展开时提供原始思考文本和流式状态。官方条目以优先级 100 注册,并调用 `conversation.chat.reasoning.content` Factory。替换项使用更小的优先级数值,可向同一个 Factory 传入原文或派生显示文本。root 作用域的 Factory 不要求 Session,并固定使用紧凑排版。其可选 `labels` 原样接受完整的 `MarkdownLabels`,省略时使用 Chat 的默认本地化文案。宿主不提供内联 fallback 或插件操作状态。显示扩展必须保留查看原文的能力,并在自己的 Body 包装内维护控件。扩展不替换思考预览或展开策略。哪些块生成思考行由[思考展示规则](src/client/conversation-nodes/README.zh.md#display-modes)定义。 Chat 节点 slot 为推理与工具注入绑定重置来源的 `useDisclosure` 钩子。中间 renderer 只透传、不订阅,每次调用拥有独立展开状态。来源回调保留接收对象及稳定引用。外层轮次实际隐藏过程成员时,所在节点重置这些开合状态,不替换组件 key,也不改变钩子引用。展示模式切换保留展开状态。 @@ -120,6 +128,8 @@ Chat 节点 slot 为推理与工具注入绑定重置来源的 `useDisclosure` ## 滚动归属 +Chat 等待初始历史就绪后,才允许自动内容、滚动或尺寸更新初始化阅读状态。进行中的 Session 先恢复初始显隐和位置,再允许折叠动画。 + Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且只在跟随底部时禁用自己滚动区域的浏览器自动锚定。没有读者移动的贴底滚动事件,以及到达底部(容许小于 1px 的取整误差)的读者输入,会立即更新跟随归属,避免后续布局变化使其底部位置失效。其他读者移动即使位于跟随阈值内,也保持待处理直到采样周期或 `scrollend`,防止布局增长抵消小幅滚动操作。采用完成时收起时,提交正文输入或 steering 会立即恢复跟随底部,并清除先前待处理的读者滚动采样。读者跟随底部时,`ResizeObserver` 追随新的底部,并且无需读取行几何就选中最后一个已加载轮次;读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃轮次。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内。 轮次轨道与回到底部按钮位于正文裁剪层外。它们相对共享会话滚动容器做 sticky 定位;Chat 自己持有滚动容器时,则相对 Chat 外框做 absolute 定位。正文扣除水平内边距后的可用宽度不超过 900px 时,隐藏轮次轨道;判断依据不是浏览器视口宽度。 @@ -130,7 +140,9 @@ Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且 下次消息触发的折叠与跟尾属于同一个可取消任务,折叠期间禁用浏览器滚动锚定。如果移除的高度大于新增内容的高度,差值保留为底部空间,不通过减小滚动偏移追到未含预留空间的内容底部;对话总高度已经超过视口时也遵循此规则。后续新增内容先填充保留区域,填满后才继续跟尾;折叠高度较小时,仅滚动剩余的向前距离。读者手势取消该任务及进行中的原生跟随;同一次折叠中的尺寸变化不能恢复已取消的任务,但新提交的输入可以。离底读者保留位置,已确认的滚动只释放不会造成位置钳制的多余空间。卸载 Chat 时取消等待回调和行过渡。启用减少动态效果偏好时,可见性和定位立即变化。 -折叠协调状态由各自的 viewport 持有,空间预留和空闲回调不会广播到其他 Chat 视图。ChatView 通过本次渲染的 `hookContext`,向 `conversation.chat.flow` 交接一次动画能力。Flow 绑定组内容与组头的行为 hook,负责节点和图片渲染,并共享既有 Chat store 与 Session 节点来源。布局节点和行内思考接收绑定后的 hook,不接收动画控制器,也不改变内容的父级。通用的可搜索隐藏在绘制前生效,并负责焦点保护及 beforematch;pending 输入对账仍留在 ChatView。 +切换工作步骤展示档位时,当前折叠结束后清空底部预留空间,并按所选档位调整滚动范围。原本跟随底部的读者保持在新的底部;其他读者不会被强制拉回底部。 + +折叠协调状态由各自的 viewport 持有,空间预留和空闲回调不会广播到其他 Chat 视图。ChatView 通过本次渲染的 `hookContext`,向 `conversation.chat.flow` 交接一次动画能力。Flow 绑定组内容与组头的行为 hook,负责节点分发,为本地回显提供 Factory renderer,并共享既有 Chat store 与 Session 节点来源。图片入口 Factory 拥有可替换的图片 Slot。布局节点和行内思考接收绑定后的 hook,不接收动画控制器,也不改变内容的父级。通用的可搜索隐藏在绘制前生效,并负责焦点保护及 beforematch;pending 输入对账仍留在 ChatView。 | 外层跟随 | 已展开小组跟随 | 回到底部按钮 | 新增内容 | |---|---|---|---| diff --git a/packages/client/ui-chat/locale/en.json b/packages/client/ui-chat/locale/en.json new file mode 100644 index 0000000000..a07944e34f --- /dev/null +++ b/packages/client/ui-chat/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-chat" + } +} diff --git a/packages/client/ui-chat/locale/zh.json b/packages/client/ui-chat/locale/zh.json new file mode 100644 index 0000000000..bece9e8048 --- /dev/null +++ b/packages/client/ui-chat/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "聊天内容展示", + "description": "渲染聊天消息、工具内容和相关详情。" + } +} diff --git a/packages/client/ui-chat/package.json b/packages/client/ui-chat/package.json index 432346bf9d..911f15930d 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,7 +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", + "@tanstack/react-virtual": "3.14.10", "@types/react": "~18.3.1", "@types/react-dom": "~18.3.0", "react": "^18.2.0", @@ -99,6 +100,7 @@ "@deepseek-ai/schemastery": "workspace:~" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-chat/src/chat-settings.ts b/packages/client/ui-chat/src/chat-settings.ts index c4c6ce3b95..8e76bb29ed 100644 --- a/packages/client/ui-chat/src/chat-settings.ts +++ b/packages/client/ui-chat/src/chat-settings.ts @@ -8,6 +8,18 @@ export const CHAT_SETTINGS_NAMESPACE = 'ui-chat' /** Field carrying the work-details presentation mode. */ export const TRANSCRIPT_VIEW_FIELD = 'transcriptView' +/** Field carrying the independent work-details collapse timing. */ +export const COLLAPSE_TIMING_FIELD = 'collapseTiming' + +/** Available points when a completed Turn returns to its historical presentation. */ +export const COLLAPSE_TIMINGS = ['completion', 'next-input'] as const + +/** When a completed Turn returns to its historical presentation. */ +export type CollapseTiming = typeof COLLAPSE_TIMINGS[number] + +/** Preserve completion-time folding when no timing preference is saved. */ +export const DEFAULT_COLLAPSE_TIMING: CollapseTiming = 'completion' + /** Work-details presentation modes a user can choose. */ export const TRANSCRIPT_VIEW_MODES = ['compact', 'standard', 'detailed', 'verbose'] as const @@ -50,6 +62,8 @@ export const DEFAULT_LINK_OPENING: LinkOpening = 'sidebar' export interface ChatSettings { /** Work-details preference; absence uses the client default, and legacy saved values remain accepted. */ transcriptView?: TranscriptViewMode | typeof LEGACY_TRANSCRIPT_VIEW_MODE | typeof LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE | null + /** Independent collapse timing; absence preserves completion-time folding. */ + collapseTiming?: CollapseTiming /** Detail level for composer statistics and completed-Turn usage. */ performanceUsage: PerformanceUsageMode /** Default destination for Chat HTTP(S) links. */ @@ -58,6 +72,7 @@ export interface ChatSettings { /** Durable Chat schema; also the wire envelope the browser scope validates against. */ export const ChatSettingsFields = { + [COLLAPSE_TIMING_FIELD]: z.union([...COLLAPSE_TIMINGS]).default(DEFAULT_COLLAPSE_TIMING), linkOpening: z.union(['sidebar', 'new-tab']).default(DEFAULT_LINK_OPENING), performanceUsage: z.union([...PERFORMANCE_USAGE_MODES]).default(DEFAULT_PERFORMANCE_USAGE), // Missing and unrecognized modes defer to the client's default. diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index eabd566256..8aa63aa1f7 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -31,6 +31,7 @@ import { ApprovalCommand } from './chat/ApprovalCommand.tsx' import { ChatView } from './chat/ChatView.tsx' import { ChatFlow } from './chat/ChatFlow.tsx' import { registerChatNodeRenderers } from './chat/register-node-renderers.ts' +import { UserContent } from './chat/UserContent.tsx' import { ActivityPill, UsagePill } from './chat/StatsPills.tsx' import { registerConversationNodes } from './conversation-nodes/register.ts' import { QuotaNoticeHost } from './chat/QuotaNoticeHost.tsx' @@ -169,6 +170,10 @@ export function apply(ctx: Context): void { ctx.effect(() => () => { transcriptView.dispose(); performancePolicy.dispose() }) const performanceUsage = performancePolicy.mode registerChatNodeRenderers(ctx, performanceUsage, presentation) + ctx.slots.registerFactory({ + name: 'conversation.chat.user.content', scope: 'session', locale: NS, + children: { 'conversation.chat.user.images': { kind: 'single', scope: 'session' } }, + }, UserContent) ctx.slots.inject('settings.general.item', () => ctx.slots.register({ name: 'settings.general.item', @@ -211,7 +216,6 @@ export function apply(ctx: Context): void { name: 'conversation.chat.flow', locale: NS, store: chatStore, children: { 'conversation.chat.node': { kind: 'keyed', scope: 'session', inject: CHAT_NODE_INJECT }, - 'conversation.message.images': { kind: 'single', scope: 'session' }, }, inject: (sessionId: SessionId): ChatFlowDataInjected => { const binding = ctx.sessions.binding(sessionId) @@ -258,11 +262,6 @@ export function apply(ctx: Context): void { else ctx.sidebarRight.openResource(url, { params: { line: options.line } }) await Promise.resolve() }, - openSkill: (name) => { - const scope = ctx.sessions.scope(sessionId) - if (scope === undefined) return - ctx.get('inputTriggers')?.sessionOf(scope).openReference('skill', { ref: `/${name}` }) - }, openExternalLink: (url) => { if (linkOpening.getSnapshot() === 'sidebar' && ctx.get('sidebarRightTabs')?.get('browser') !== undefined) { ctx.sidebarRight.openTab('browser', { params: { url } }) diff --git a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx index dcc1141b47..22ae5bac70 100644 --- a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx +++ b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx @@ -27,7 +27,9 @@ export function localPathMediaUrl(base: string, value: string): string | undefin return fileMediaUrl(base, path) } -export interface AssistantMarkdownProps extends Pick, 'renderSlot'> { +export interface AssistantMarkdownProps extends + Pick, 'renderSlot'>, + Pick { /** Render only the requested business portion, preserving original block indexes. */ groupPart?: string | undefined /** Stable Hook forwarded to each independently expandable reasoning block. */ @@ -36,8 +38,6 @@ export interface AssistantMarkdownProps extends Pick - {renderMessageImages({ - images: group.map(({ attachment }) => ({ attachment })), - align: 'start', + {renderSlot('conversation.chat.message.images', { + images: group.map(({ attachment }) => ({ attachment })), loadImage, align: 'start', })} , ) diff --git a/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx b/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx index b77dffb7f1..5f61fe7007 100644 --- a/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx +++ b/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx @@ -4,11 +4,11 @@ import type { ChatNodeViewProps, PresentationInjected, TurnTailOwnerProps } from import { AssistantMarkdown } from './AssistantMarkdown.tsx' type AssistantNodeViewProps = ChatNodeViewProps<'assistant-step'> & InjectFace - & PropsRenderSlots<'conversation.chat.reasoning.body'> + & PropsRenderSlots<'conversation.chat.reasoning.body' | 'conversation.chat.message.images'> /** Streaming, settled, and interrupted Assistant states share one keyed renderer instance. */ export const AssistantNodeView = memo(function AssistantNodeView({ - node, groupPart, useDisclosure, useGroupAction, useTurnData, turnProcess, openFile, renderMessageImages, fileMentions, + node, groupPart, useDisclosure, useGroupAction, useTurnData, turnProcess, openFile, loadImage, fileMentions, usePresentation, renderSlot, t, }: AssistantNodeViewProps) { const data = node.data @@ -38,7 +38,7 @@ export const AssistantNodeView = memo(function AssistantNodeView({ useDisclosure={useDisclosure} streaming={data.status === 'running'} interrupted={data.status === 'interrupted'} - renderMessageImages={renderMessageImages} + loadImage={loadImage} reasoningHidden={reasoningHidden} useGroupAction={useGroupAction} usePresentation={usePresentation} diff --git a/packages/client/ui-chat/src/client/chat/ChatFlow.tsx b/packages/client/ui-chat/src/client/chat/ChatFlow.tsx index 1b8306ee5f..c54e8a108f 100644 --- a/packages/client/ui-chat/src/client/chat/ChatFlow.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatFlow.tsx @@ -1,6 +1,5 @@ /** Ordered Chat rows, local echoes, and running status share the flow slot's parent. */ -import { memo, useCallback } from 'react' -import type { RenderMessageImages } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { memo } from 'react' import { assertNever } from '@deepseek-ai/dsh-util-values' import type { ChatFlowSlotProps } from '../contract/slots.ts' import { ChatNodeSeat } from './ChatNodeSeat.tsx' @@ -13,8 +12,8 @@ import { RunningStatus } from './RunningStatus.tsx' export const ChatFlow = memo(function ChatFlow({ entries, pendingInputs, lastInputTurn, deferCollapse, useSession, useChat, useChatNode, useChatNodeBottom, useChatNodeProcess, useChatGroup, usePresentation, - useStore, actions, renderSlot, t, useGroupAction, useGroupHeaderAction, - cwd, openFile, openSkill, inspectCall, forkAt, loadImage, fileMentions, + useStore, actions, renderSlot, renderFactorySlot, t, useGroupAction, useGroupHeaderAction, + cwd, openFile, inspectCall, forkAt, loadImage, fileMentions, }: ChatFlowSlotProps) { const nodeStore = useChat(snapshot => snapshot.nodes) const running = useSession(snapshot => snapshot.running) @@ -25,14 +24,10 @@ export const ChatFlow = memo(function ChatFlow({ ? location.turn.status === 'open' ? location.turn.start?.time : undefined : undefined }) - const renderMessageImages = useCallback( - owner => renderSlot('conversation.message.images', { ...owner, loadImage }), - [loadImage, renderSlot], - ) const seatProps = { nodeStore, useChatNode, useChatNodeBottom, useChatNodeProcess, usePresentation, useStore, actions, renderSlot, t, useGroupAction, deferCollapse, - cwd, openFile, openSkill, inspectCall, forkAt, loadImage, renderMessageImages, fileMentions, + cwd, openFile, inspectCall, forkAt, loadImage, fileMentions, } const rows = entries.map((entry) => { switch (entry.kind) { @@ -48,10 +43,10 @@ export const ChatFlow = memo(function ChatFlow({ }) const pendingRows = pendingInputs.map(item => 'requestId' in item ? ( + loadImage={loadImage} renderFactorySlot={renderFactorySlot} t={t} /> ) : ( + loadImage={loadImage} renderFactorySlot={renderFactorySlot} t={t} /> )) const tail = entries.at(-1) const node = tail?.kind === 'node' ? nodeStore.get(tail.key) : undefined diff --git a/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx b/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx index 4bc1947dca..9b076678a3 100644 --- a/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx @@ -47,8 +47,8 @@ function turnOf(node: ChatNode | undefined): number | undefined { */ export const ChatNodeSeat = memo(function ChatNodeSeat({ nodeKey, groupPart, useChatNode, useChatNodeProcess, usePresentation, - cwd, openFile, openSkill, inspectCall, forkAt, - loadImage, renderMessageImages, fileMentions, useStore, actions, renderSlot, t, useChatNodeBottom, deferCollapse, useGroupAction, + cwd, openFile, inspectCall, forkAt, + loadImage, fileMentions, useStore, actions, renderSlot, t, useChatNodeBottom, deferCollapse, useGroupAction, }: ChatNodeSeatProps) { const bottom = useChatNodeBottom(nodeKey) const node = useChatNode(nodeKey) @@ -127,16 +127,14 @@ export const ChatNodeSeat = memo(function ChatNodeSeat({ ...groupPart === undefined ? {} : { groupPart }, cwd, openFile, - openSkill, inspectCall, forkAt, loadImage, - renderMessageImages, fileMentions, turnProcess, }, [ - node, groupPart, cwd, openFile, openSkill, inspectCall, forkAt, - loadImage, renderMessageImages, fileMentions, turnProcess, + node, groupPart, cwd, openFile, inspectCall, forkAt, + loadImage, fileMentions, turnProcess, ]) if (routedNode === undefined || owner === null) return null // Runtime dispatch owns the correlation: every Node's discriminant is the diff --git a/packages/client/ui-chat/src/client/chat/ChatView.module.css b/packages/client/ui-chat/src/client/chat/ChatView.module.css index 5ff669c1fb..6696330f0a 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.module.css +++ b/packages/client/ui-chat/src/client/chat/ChatView.module.css @@ -101,6 +101,11 @@ transition: margin-top 160ms cubic-bezier(0.4, 0, 0.2, 1); } +.column[data-input-fold] > :not([data-chat-motion]), +.column[data-input-fold] > :global([data-slot="conversation.chat.flow"]) > :not([data-chat-motion]) { + transition: none; +} + @media (prefers-reduced-motion: reduce) { .column[data-chat-motion] > :not([data-chat-motion]), .column[data-chat-motion] > :global([data-slot="conversation.chat.flow"]) > :not([data-chat-motion]) { diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index 4d3d3fda52..3b528dc47a 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -59,7 +59,7 @@ const MOTION_TAIL_MS = 800 */ export function ChatView({ useSession, useChat, useConversation, useSessions, renderSlot, - sessionId, openFile, openSkill, openExternalLink, loadOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, fileMentions, + sessionId, openFile, openExternalLink, loadOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, fileMentions, usePresentation, useProjection, t, }: ChatViewSlotProps) { const order = useChat(s => s.order) @@ -68,6 +68,7 @@ export function ChatView({ ?? order.map(key => ({ kind: 'node', key: key as NodeKey })), [groupedEntries, order]) const nodeStore = useChat(s => s.nodes) const deferCompletedTurns = usePresentation(policy => policy.collapseTiming === 'next-input') + const transcriptView = usePresentation(policy => policy.mode) // The rail's items are accumulated in the Chat snapshot, so this selector is // both the data and its change signal: the array identity moves only when a // Turn enters, leaves, or changes its preview. @@ -189,6 +190,7 @@ export function ChatView({ steeringId, submissionId: visibleSubmissions.at(-1)?.requestId ?? null, loadedTurns: turnNavigationItems, + transcriptView, }) const flowContext = useMemo(() => ({ motion: scroll.motion }), [scroll.motion]) @@ -221,17 +223,17 @@ export function ChatView({
)} - + {renderSlot('conversation.chat.flow', { entries, pendingInputs, lastInputTurn, deferCollapse, - cwd, openFile: requestOpenFile, openSkill, inspectCall, forkAt, loadImage, fileMentions, + cwd, openFile: requestOpenFile, inspectCall, forkAt, loadImage, fileMentions, }, { hookContext: flowContext })} {/* No pending placeholders: questions (ui-user-questions) and approvals (ApprovalPanel) both take over the composer, so a flow card would double-render the same wait. */}
- {/* Room added when rows above the reader close, given back only as content grows (use-chat-viewport). */} + {/* Fold room is reclaimed by viewport scroll, content-growth, and display-mode policies. */}
diff --git a/packages/client/ui-chat/src/client/chat/MessageItem.module.css b/packages/client/ui-chat/src/client/chat/MessageItem.module.css index 5d19483335..3bacafab47 100644 --- a/packages/client/ui-chat/src/client/chat/MessageItem.module.css +++ b/packages/client/ui-chat/src/client/chat/MessageItem.module.css @@ -326,7 +326,7 @@ min-height: 64px; padding: 8px 12px; border: 0.5px solid var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.12)); - border-radius: var(--dsw-radius-xl); + border-radius: var(--dsw-radius-lg); background: var(--dsw-specific-input-major, transparent); box-sizing: border-box; } diff --git a/packages/client/ui-chat/src/client/chat/MessageItem.tsx b/packages/client/ui-chat/src/client/chat/MessageItem.tsx index 9005150af0..a2d394c106 100644 --- a/packages/client/ui-chat/src/client/chat/MessageItem.tsx +++ b/packages/client/ui-chat/src/client/chat/MessageItem.tsx @@ -1,28 +1,29 @@ -import { Fragment, memo, useEffect, useMemo, useState } from 'react' +import { memo, useEffect, useMemo, useState } from 'react' import type { ReactNode } from 'react' import type { PendingSubmission } from '@deepseek-ai/dsh-api-session-controller/client' -import type { MessageImageSource } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { fileExtension, FileTypeIcon, fileSizeText, JsonBlock, projectUserText, StateDot, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives' -import type { ChatNodeOwnerProps, ChatNodeViewProps, ChatViewSlotProps } from '../contract/slots.ts' +import type { PropsRenderFactories } from '@deepseek-ai/dsh-client-ui-slots' +import type { UserTextFacts } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { JsonBlock, StateDot, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives' +import type { + ChatNodeOwnerProps, ChatNodeViewProps, ChatViewSlotProps, UserContentAttachment, UserContentData, UserContentInput, +} from '../contract/slots.ts' import type { ModelRetryNode, TurnErrorNode, UserMessageNode } from '../contract/snapshot.ts' import { CompactionItem } from './CompactionItem.tsx' import { ContextInjectionRow } from './ContextInjectionRow.tsx' import { MessageIconActions } from './MessageIconActions.tsx' import css from './MessageItem.module.css' +const EMPTY_TEXT_FACTS: Readonly> = {} + type UserImage = Extract type UserFile = Extract -type PresentedAttachment = - | { readonly type: 'image'; readonly image: MessageImageSource } - | { readonly type: 'file'; readonly file: UserFile['attachment'] } - function contentParts(content: readonly unknown[]): { text: string - attachments: PresentedAttachment[] + attachments: UserContentAttachment[] rest: unknown[] } { const texts: string[] = [] - const attachments: PresentedAttachment[] = [] + const attachments: UserContentAttachment[] = [] const rest: unknown[] = [] for (const block of content) { const b = block as { type?: string; text?: string; attachment?: unknown } @@ -160,11 +161,11 @@ function TurnMaxTokensItem({ t }: { /** Right-aligned bubble shared by user and steering rows. */ function UserStyleBubble({ - content, renderMessageImages, actions, pending = false, echo = false, referenceLabels = [], skillNames = [], - previewAttachments, references, t, + content, loadImage, renderFactorySlot, actions, pending = false, echo = false, referenceLabels, skillNames, + previewAttachments, facts: inputFacts = EMPTY_TEXT_FACTS, interactive = false, }: { content: readonly unknown[] - renderMessageImages: ChatNodeOwnerProps['renderMessageImages'] + renderFactorySlot: PropsRenderFactories['renderFactorySlot'] /** Optional IconActions (or similar) below the bubble; receives the joined text. */ actions?: (text: string) => ReactNode /** Whether this is the Host-authoritative pre-admission steering projection. */ @@ -176,59 +177,35 @@ function UserStyleBubble({ /** Skill names the step's `skill-invocation` injections loaded for this message. */ skillNames?: readonly string[] /** Local submission-echo attachments replacing the content-derived attachment sequence. */ - previewAttachments?: readonly PresentedAttachment[] - references?: Pick - t: ChatViewSlotProps['t'] -}): ReactNode { - const { text, attachments: contentAttachments, rest } = contentParts(content) - const attachments = previewAttachments ?? contentAttachments - const compactImages = attachments.length > 1 - const truncated = (total: number): string => t('json.truncated', { total }) - const showBubble = text !== '' || rest.length > 0 + previewAttachments?: readonly UserContentAttachment[] + /** Inputs used by text transforms, separate from row and rendering props. */ + facts?: Readonly> +} & Pick & Pick): ReactNode { + const parts = useMemo(() => contentParts(content), [content]) + const prepared = useMemo(() => ({ + text: parts.text, + attachments: previewAttachments ?? parts.attachments, + extraBlocks: parts.rest, + ...(referenceLabels === undefined ? {} : { referenceLabels }), + }), [parts, previewAttachments, referenceLabels]) + const facts = useMemo>>(() => ({ + ...inputFacts, + ...(referenceLabels === undefined ? {} : { sessionLabels: referenceLabels }), + ...(skillNames === undefined ? {} : { skillNames }), + }), [inputFacts, referenceLabels, skillNames]) return (
-
- {attachments.length > 0 && ( -
- {attachments.map((attachment, index) => attachment.type === 'image' - ? ( - - {renderMessageImages({ - images: [attachment.image], - align: 'end', - compact: compactImages, - })} - - ) - : ( - - - - {attachment.file.name} - - {[fileExtension(attachment.file.name).toUpperCase().slice(0, 8), fileSizeText(attachment.file.bytes)] - .filter(Boolean).join(' ')} - - - - ))} -
- )} - {showBubble &&
- {projectUserText(text, referenceLabels, skillNames, 'skill', references)} - {rest.map((block, i) => )} -
} - {referenceLabels.length > 0 && ( -
- {t('message.referenceSummary', { labels: referenceLabels.join(t('message.referenceSeparator')) })} -
- )} -
- {actions?.(text)} + {renderFactorySlot('conversation.chat.user.content', { + content: prepared, + loadImage, + facts, + interactive, + })} + {actions?.(prepared.text)}
) } @@ -236,20 +213,20 @@ function UserStyleBubble({ /** * Render one Host-authoritative pending steering item with the same visual * language as its eventual durable transcript node. - * @param props - Pending message content and conversation translator. + * @param props - pending content, authorized image loader, and Factory/locale seats. * @returns the pending steering bubble. */ -export function PendingSteeringBubble({ content, renderMessageImages, t }: { +export function PendingSteeringBubble({ content, loadImage, renderFactorySlot, t }: { content: readonly unknown[] - renderMessageImages: ChatNodeOwnerProps['renderMessageImages'] + renderFactorySlot: PropsRenderFactories['renderFactorySlot'] t: ChatViewSlotProps['t'] -}): ReactNode { +} & Pick): ReactNode { return ( ( ): ReactNode { const content = useMemo( () => (submission.text === '' ? [] : [{ type: 'text', text: submission.text }]), [submission.text], ) - const previewAttachments = useMemo( + const previewAttachments = useMemo( () => submission.attachments.map(attachment => attachment.type === 'image' ? { type: 'image', @@ -299,10 +276,10 @@ export function PendingSubmissionBubble({ submission, renderMessageImages, t }: ( ) { const data = node.data return ( ( ) { + const { text, attachments, extraBlocks, referenceLabels = EMPTY_LABELS } = content + const compactImages = attachments.length > 1 + const truncated = (total: number): string => t('json.truncated', { total }) + const showBubble = text !== '' || extraBlocks.length > 0 + return ( +
+ {attachments.length > 0 && ( +
+ {attachments.map((attachment, index) => attachment.type === 'image' + ? ( + + {renderSlot('conversation.chat.user.images', { + images: [attachment.image], loadImage, align: 'end', compact: compactImages, + })} + + ) + : ( + + + + {attachment.file.name} + + {[fileExtension(attachment.file.name).toUpperCase().slice(0, 8), fileSizeText(attachment.file.bytes)] + .filter(Boolean).join(' ')} + + + + ))} +
+ )} + {showBubble &&
+ {renderFactorySlot('conversation.user.text', { text, facts, interactive, ellipsis })} + {extraBlocks.map((block, index) => ( + + ))} +
} + {referenceLabels.length > 0 && ( +
+ {t('message.referenceSummary', { labels: referenceLabels.join(t('message.referenceSeparator')) })} +
+ )} +
+ ) +} diff --git a/packages/client/ui-chat/src/client/chat/flow-motion.ts b/packages/client/ui-chat/src/client/chat/flow-motion.ts index 2804a93b77..9705f1f22a 100644 --- a/packages/client/ui-chat/src/client/chat/flow-motion.ts +++ b/packages/client/ui-chat/src/client/chat/flow-motion.ts @@ -1,7 +1,7 @@ /** - * Fade-then-close transitions owned by one Chat viewport. Rows fade before their boxes close; - * the owner reserves removed height and holds scrolling until that viewport's folds finish. - * Motion is opt-in under `[data-chat-motion]`, respects reduced motion, and clears temporary styles. + * Fold transitions owned by one Chat viewport. Input folds coordinate box sizes and scrolling on + * one frame clock; other folds use CSS transitions. Motion is opt-in under `[data-chat-motion]`, + * respects reduced motion, and clears temporary styles. */ import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react' import { useSearchableHidden, type HiddenTransition } from './searchable-hidden.ts' @@ -24,12 +24,53 @@ export interface FlowMotionRows { cancelMotion(element: HTMLElement): void } +/** Geometry captured before one input-owned fold changes its boxes. */ +export interface InputFoldBox { + readonly element: HTMLElement + readonly height: number + readonly marginTop: number + readonly closing: boolean +} + +/** The viewport follows the same progress that changes the folded boxes. */ +export interface InputFoldDriver { + /** + * Capture geometry before the frame clock changes the boxes. + * @param boxes - non-nested boxes whose layout changes on this clock. + */ + begin(boxes: readonly InputFoldBox[]): void + /** + * Reserve scroll range before box writes; omit when the driver needs no pre-write compensation. + * @param progress - shared eased progress from zero to one. + * @param cancelled - automatic following has stopped; reader-position compensation still applies. + */ + prepare?(progress: number, cancelled: boolean): void + /** + * Apply viewport geometry after box writes, even when automatic following is cancelled. + * @param progress - shared eased progress from zero to one. + * @param cancelled - preserve the reader's position rather than applying the automatic target. + * @returns actual scrollTop displacement from the batch start, for closing-content visual compensation. + */ + frame(progress: number, cancelled: boolean): number + /** + * Release temporary geometry after the last frame or cancellation. + * @param cancelled - clean up without reacquiring follow ownership or committing an obsolete landing. + */ + finish(cancelled: boolean): void +} + /** Animation lifetime and fold coordination for one viewport. */ export interface FlowMotion extends FlowMotionRows { /** @returns whether a row owned by this viewport is closing. */ foldActive(): boolean /** @param listener - callback after the last fold. @returns cancellation for a pending callback. */ onFoldIdle(listener: () => void): () => void + /** @param driver - one input-owned viewport motion. @returns whether an active fold was adopted. */ + followInput(driver: InputFoldDriver): boolean + /** Stop input-owned scrolling while letting its closing rows finish. */ + cancelInput(): void + /** @returns whether a coordinated fold currently owns layout and scrolling. */ + inputActive(): boolean /** Cancel owned animations and pending work when the viewport detaches. */ clear(): void } @@ -66,6 +107,101 @@ export function createFlowMotion(reserve: (px: number) => void, foldingChanged: const pendingReserve = new Set() let pendingGrowth = 0 let reserveScheduled = false + const boxes = new Map void; finish: () => void }>() + let inputDriver: InputFoldDriver | null = null + let inputFrame: number | null = null + let inputBatch = false + let clearEpoch = 0 + let inputCleanup: (() => void) | null = null + let activeDriver: InputFoldDriver | null = null + let cancelEmptyBatch: (() => void) | null = null + + function cancelInput(): void { inputDriver = null } + + function followInput(driver: InputFoldDriver): boolean { + if (folding === 0) return false + if (inputBatch) { + inputDriver = activeDriver + return true + } + inputDriver = driver + scheduleReserve() + return true + } + + function runInputBatch(): void { + const driver = inputDriver + if (driver === null || inputBatch) return + const owned = [...boxes.values()] + const batch = owned.filter(box => box.element.parentElement?.closest('[data-chat-motion="collapse"]') === null) + .sort((left, right) => left.element.compareDocumentPosition(right.element) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1) + if (!batch.some(box => box.closing)) return + inputBatch = true + activeDriver = driver + driver.begin(batch) + inputCleanup = () => { driver.finish(true) } + for (const box of owned) box.take() + for (const box of batch) { + box.element.style.transition = 'none' + box.element.style.height = `${box.closing ? box.height : 0}px` + box.element.style.marginTop = `${box.closing ? box.marginTop : 0}px` + box.element.style.opacity = box.closing ? '1' : '0' + } + const reduced = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches + let started: number | undefined + let displacement = 0 + cancelEmptyBatch = () => { + if (batch.some(box => box.closing && boxes.get(box.element) === box)) return + if (inputFrame !== null) cancelAnimationFrame(inputFrame) + inputFrame = null + inputBatch = false + activeDriver = null + inputDriver = null + inputCleanup = null + cancelEmptyBatch = null + for (const box of owned) if (boxes.get(box.element) === box) box.finish() + driver.finish(true) + } + const tick = (now: number): void => { + inputFrame = null + started ??= now + const elapsed = reduced ? CLOSE_DELAY_MS + CLOSE_MS : now - started + const linear = Math.min(1, Math.max(0, (elapsed - CLOSE_DELAY_MS) / CLOSE_MS)) + const progress = linear * linear * (3 - 2 * linear) + driver.prepare?.(progress, inputDriver !== driver) + for (const box of batch) { + if (boxes.get(box.element) !== box) continue + const remaining = box.closing ? 1 - progress : progress + box.element.style.height = `${box.height * remaining}px` + box.element.style.marginTop = `${box.marginTop * remaining}px` + box.element.style.opacity = box.closing ? String(Math.max(0, 1 - elapsed / FADE_OUT_MS)) : String(progress) + } + displacement = driver.frame(progress, inputDriver !== driver) + let removedBefore = 0 + for (const box of batch) { + if (boxes.get(box.element) !== box) continue + if (box.closing) { + // Transforming the closing box changes its pixels, not its flow contribution. + box.element.style.translate = `0 ${displacement + removedBefore}px` + removedBefore += (box.height + box.marginTop) * progress + } else removedBefore -= (box.height + box.marginTop) * progress + } + if (linear < 1) { + inputFrame = requestAnimationFrame(tick) + return + } + for (const box of owned) box.finish() + inputBatch = false + activeDriver = null + inputCleanup = null + cancelEmptyBatch = null + const cancelled = inputDriver !== driver + if (!cancelled) inputDriver = null + driver.finish(cancelled) + } + if (reduced) tick(0) + else inputFrame = requestAnimationFrame(tick) + } function foldActive(): boolean { return folding > 0 } @@ -77,6 +213,18 @@ export function createFlowMotion(reserve: (px: number) => void, foldingChanged: function flushReserve(): void { reserveScheduled = false + if (inputDriver !== null && !inputBatch) { + pendingReserve.clear() + pendingGrowth = 0 + runInputBatch() + return + } + if (typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches) { + pendingReserve.clear() + pendingGrowth = 0 + for (const box of [...boxes.values()]) box.finish() + return + } let total = -pendingGrowth pendingGrowth = 0 for (const element of pendingReserve) { @@ -92,7 +240,8 @@ export function createFlowMotion(reserve: (px: number) => void, foldingChanged: if (reserveScheduled) return reserveScheduled = true // After the whole commit's collapses and reveals have started, before any box changes size. - queueMicrotask(flushReserve) + const epoch = clearEpoch + queueMicrotask(() => { if (epoch === clearEpoch) flushReserve() }) } function foldStarted(): void { @@ -113,18 +262,21 @@ export function createFlowMotion(reserve: (px: number) => void, foldingChanged: element.removeEventListener('transitionend', onEnd) clearTimeout(timer) running.delete(element) + boxes.delete(element) const { style } = element style.height = '' style.marginTop = '' style.opacity = '' style.overflow = '' style.transition = '' + style.translate = '' delete element.dataset.chatMotion } function cancelMotion(element: HTMLElement): void { pendingReserve.delete(element) running.get(element)?.() + cancelEmptyBatch?.() } function collapse(element: HTMLElement, done: () => void): void { @@ -168,6 +320,8 @@ export function createFlowMotion(reserve: (px: number) => void, foldingChanged: } element.addEventListener('transitionend', onEnd) running.set(element, cancel) + boxes.set(element, { element, height, marginTop, closing: true, finish, + take: () => { element.removeEventListener('transitionend', onEnd); clearTimeout(timer) } }) } function reveal(element: HTMLElement): void { @@ -200,16 +354,28 @@ export function createFlowMotion(reserve: (px: number) => void, foldingChanged: const timer = setTimeout(finish, CLOSE_DELAY_MS + CLOSE_MS + SETTLE_SLACK_MS) element.addEventListener('transitionend', onEnd) running.set(element, finish) + boxes.set(element, { element, height, marginTop, closing: false, finish, + take: () => { element.removeEventListener('transitionend', onEnd); clearTimeout(timer) } }) } function clear(): void { + clearEpoch++ + reserveScheduled = false + inputDriver = null + activeDriver = null + inputBatch = false + if (inputFrame !== null) cancelAnimationFrame(inputFrame) + inputFrame = null + inputCleanup?.() + inputCleanup = null + cancelEmptyBatch = null foldIdleListeners.clear() pendingReserve.clear() pendingGrowth = 0 for (const cancel of [...running.values()]) cancel() } - return { collapse, reveal, cancelMotion, foldActive, onFoldIdle, clear } + return { collapse, reveal, cancelMotion, foldActive, onFoldIdle, followInput, cancelInput, inputActive: () => inputBatch, clear } } function useFlowTransition(motion: FlowMotionRows | undefined, grow: boolean): HiddenTransition | undefined { @@ -219,11 +385,12 @@ function useFlowTransition(motion: FlowMotionRows | undefined, grow: boolean): H current.current = null }, [motion]) const transition = useCallback((element, hidden, commit) => { - const animate = current.current === element && motionEnabled(element) + const mounted = current.current === element + const animate = mounted && motionEnabled(element) current.current = element if (hidden) { if (hiddenOrCollapsing(element)) return - if (animate && motion !== undefined) motion.collapse(element, commit) + if (mounted && element.closest(MOTION_SCOPE) !== null && motion !== undefined) motion.collapse(element, commit) else commit() return } diff --git a/packages/client/ui-chat/src/client/chat/register-node-renderers.ts b/packages/client/ui-chat/src/client/chat/register-node-renderers.ts index a5d4f9bc7a..7e58223287 100644 --- a/packages/client/ui-chat/src/client/chat/register-node-renderers.ts +++ b/packages/client/ui-chat/src/client/chat/register-node-renderers.ts @@ -51,7 +51,10 @@ export function registerChatNodeRenderers( name: 'conversation.chat.node', key: 'assistant-step', locale: NS, - children: { 'conversation.chat.reasoning.body': { kind: 'single', scope: 'session' } }, + children: { + 'conversation.chat.reasoning.body': { kind: 'single', scope: 'session' }, + 'conversation.chat.message.images': { kind: 'single', scope: 'session' }, + }, inject: () => ({ hooks: { presentation } }), }, AssistantNodeView)) ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({ diff --git a/packages/client/ui-chat/src/client/chat/use-chat-reading.ts b/packages/client/ui-chat/src/client/chat/use-chat-reading.ts index 85561c8fb8..3d3c6ae048 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-reading.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-reading.ts @@ -87,6 +87,17 @@ export class ChatReading { this.commit(landing, true, this.viewport.latestTurn) } + /** + * Follow submitted input on the active fold's animation clock. + * @returns whether this input joined a closing batch instead of starting another scroll animation. + */ + followInputFold(): boolean { + this.cancelPending() + return this.viewport.followInputFold(this.follow, (landing) => { + this.commit(landing, true, this.viewport.latestTurn) + }) + } + /** Stop a native follow animation where it is; the next sampled position decides follow intent. */ interruptFollow(): void { this.viewport.interruptFollow(this.follow) diff --git a/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts b/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts index b695e7d0fe..8f867de148 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts @@ -1,5 +1,6 @@ /** Composes viewport operations, reading policy, and history navigation for Chat. */ import { useCallback, useLayoutEffect, useMemo, useRef, type RefObject } from 'react' +import type { TranscriptViewMode } from '../../chat-settings.ts' import type { ChatSnapshot } from '../contract/snapshot.ts' import type { ChatViewSlotProps } from '../contract/slots.ts' import { useChatNavigation, type ChatNavigation, type ChatNavigationInput } from './use-chat-navigation.ts' @@ -19,6 +20,8 @@ export interface ChatScrollInput extends ChatNavigationInput { readonly running: boolean /** Enable the browser-local delayed-fold experiment and its input reveal animation. */ readonly deferCompletedTurns: boolean + /** A changed work-details preference resets fold reservations after the layout settles. */ + readonly transcriptView: TranscriptViewMode readonly loadedTurns: ReturnType } @@ -33,7 +36,8 @@ interface ChatScrollState extends ChatReadingState { } /** - * Coordinate scroll policy after Chat content commits. + * Coordinate scroll policy after Chat content commits. Initial history must be ready + * before automatic scroll or resize handling can initialize reading state and fold motion. * New submitted input supersedes pending reader sampling. * @param input - current Chat content, scroll memory, and history operations. * @returns element refs, visible reading state, and navigation callbacks. @@ -41,7 +45,7 @@ interface ChatScrollState extends ChatReadingState { export function useChatScroll(input: ChatScrollInput): ChatScrollState { const { ready, order, firstSeq, lastKey, lastIsUser, steeringId, submissionId, running, deferCompletedTurns, - loadedTurns, chatScroll, hasMore, loadingOlder, loadOlder, loadThrough, + loadedTurns, chatScroll, hasMore, loadingOlder, loadOlder, loadThrough, transcriptView, } = input const { viewport, listRef, columnRef } = useChatViewport() const { reading, state } = useChatReading(viewport, chatScroll, loadedTurns.at(-1)?.turn ?? null) @@ -60,6 +64,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { cancelFollow.current = null }, []) const cancelPendingFollow = useCallback(() => { + viewport.motion.cancelInput() clearPendingFollow() // Retain a cancelled wait until this fold ends, so resize cannot reacquire follow ownership. if (viewport.motion.foldActive()) { @@ -67,7 +72,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { } }, [clearPendingFollow, viewport]) const followAfterFold = useCallback(() => { - if (cancelFollow.current !== null) return + if (cancelFollow.current !== null || viewport.motion.inputActive()) return reading.interruptFollow() cancelFollow.current = viewport.motion.onFoldIdle(() => { cancelFollow.current = null @@ -78,6 +83,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const processContent = useCallback(() => { const current = content.current.input + if (!current.ready && !content.current.opened) return const previous = content.current.applied const ownInput = (current.lastIsUser && current.lastKey !== previous?.lastKey) || (current.steeringId !== null && current.steeringId !== previous?.steeringId @@ -95,8 +101,8 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { if (ownInput) { clearPendingFollow() navigation.cancel() - if (current.deferCompletedTurns && viewport.motion.foldActive()) followAfterFold() - else reading.followTail(current.deferCompletedTurns ? 'smooth' : 'instant') + if (current.deferCompletedTurns && reading.followInputFold()) return + reading.followTail(current.deferCompletedTurns ? 'smooth' : 'instant') return } if (navigation.contentCommitted()) { @@ -117,6 +123,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { useLayoutEffect(() => { const disconnectViewport = viewport.connect({ scroll: (event) => { + if (!content.current.opened) return if (!event.movedByReader && viewport.motion.foldActive()) return reading.onScroll(event) }, @@ -127,6 +134,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { interact: () => { navigation.cancel() }, intent: () => { cancelPendingFollow(); reading.interruptFollow() }, resize: () => { + if (!content.current.opened) return if (navigation.contentCommitted()) { navigation.reconcile() return @@ -154,7 +162,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const previous = content.current.input content.current.input = { ready, order, lastKey, lastIsUser, steeringId, submissionId, running, loadedTurns, chatScroll, - deferCompletedTurns, ...navigationInput, + deferCompletedTurns, transcriptView, ...navigationInput, } if (!deferCompletedTurns) { cancelPendingFollow() @@ -165,12 +173,24 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { if (layoutChanged) viewport.invalidate() viewport.reclaimBelow() processContent() - if (layoutChanged) reading.refreshActiveTurn() + if (layoutChanged && content.current.opened) reading.refreshActiveTurn() }, [ viewport, reading, processContent, navigationInput, ready, order, lastKey, lastIsUser, - steeringId, submissionId, running, loadedTurns, chatScroll, deferCompletedTurns, cancelPendingFollow, + steeringId, submissionId, running, loadedTurns, chatScroll, deferCompletedTurns, transcriptView, cancelPendingFollow, ]) + const previousView = useRef(transcriptView) + useLayoutEffect(() => { + if (previousView.current === transcriptView) return + previousView.current = transcriptView + cancelPendingFollow() + reading.interruptFollow() + return viewport.motion.onFoldIdle(() => { + viewport.resetBelow() + if (content.current.opened) reading.onResize() + }) + }, [transcriptView, viewport, reading, cancelPendingFollow]) + const returnToBottom = useCallback(() => { cancelPendingFollow() navigation.cancel() diff --git a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts index 6a895fd527..ad6de91901 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts @@ -160,6 +160,113 @@ export class ChatViewport { this.setSpacer(this.spacerHeight() + px) } + /** + * Join an input-caused fold and its tail movement on the fold's frame clock. + * @param follow - the existing reader's follow controller. + * @param settled - commits follow ownership after the final geometry is installed. + * @returns whether a closing batch owns this input. + */ + followInputFold(follow: ScrollFollow, settled: (landing: ViewportLanding) => void): boolean { + const elements = this.elements + if (elements === null) return false + this.interruptFollow(follow) + let start = 0 + let target = 0 + let removed = 0 + let initialHeight = 0 + let originalRoom = 0 + let finalRoom = 0 + let growth = 0 + let base = 0 + let previousColumnHeight = 0 + let previousProgress = 0 + let segmentProgress = 0 + let segmentTop = 0 + return this.motion.followInput({ + begin: (boxes) => { + const viewport = elements.scroller.getBoundingClientRect() + const metrics = scrollMetrics(elements.scroller) + start = metrics.top + originalRoom = this.spacerHeight() + initialHeight = Math.max(elements.column.offsetHeight, elements.scroller.scrollHeight - originalRoom) + let above = 0 + for (const box of boxes) { + const amount = box.height + box.marginTop + if (box.closing) { + removed += amount + const top = box.element.getBoundingClientRect().top - box.marginTop + above += Math.max(0, Math.min(amount, viewport.top - top)) + } else growth += amount + } + const finalHeight = initialHeight - removed + growth + base = Math.max(0, start - above) + segmentTop = start + previousColumnHeight = elements.column.offsetHeight + target = Math.max(base, Math.max(0, finalHeight - metrics.height)) + finalRoom = target === 0 ? 0 : Math.max(0, target + metrics.height - finalHeight) + elements.column.dataset.inputFold = '' + // This reserve only prevents an intermediate clamp; the final frame installs the exact deficit. + this.setSpacer(Math.max(originalRoom, finalRoom, removed)) + follow.setFollowing(true) + }, + prepare: (progress, cancelled) => { + if (this.elements !== elements) return + const added = elements.column.offsetHeight - previousColumnHeight + if (added !== 0) { + initialHeight += added + const finalHeight = initialHeight - removed + growth + target = Math.max(base, finalHeight - elements.scroller.clientHeight, 0) + finalRoom = target === 0 ? 0 : Math.max(0, target + elements.scroller.clientHeight - finalHeight) + segmentTop = elements.scroller.scrollTop + segmentProgress = previousProgress + } + const remaining = segmentProgress === 1 ? 1 : (progress - segmentProgress) / (1 - segmentProgress) + const top = cancelled ? elements.scroller.scrollTop : segmentTop + (target - segmentTop) * remaining + const currentHeight = initialHeight + (growth - removed) * progress + const room = Math.max(cancelled ? 0 : finalRoom, top + elements.scroller.clientHeight - currentHeight) + // Growing the room before shrinking boxes avoids a native clamp between writes. + this.setSpacer(Math.max(this.spacerHeight(), room)) + }, + frame: (progress, cancelled) => { + if (this.elements !== elements) return 0 + const remaining = segmentProgress === 1 ? 1 : (progress - segmentProgress) / (1 - segmentProgress) + const top = cancelled ? elements.scroller.scrollTop : segmentTop + (target - segmentTop) * remaining + const currentHeight = initialHeight + (growth - removed) * progress + const room = Math.max(cancelled ? 0 : finalRoom, top + elements.scroller.clientHeight - currentHeight) + elements.scroller.scrollTop = top + this.setSpacer(room) + if (!cancelled) this.observation = { top: elements.scroller.scrollTop, landing: null } + previousColumnHeight = elements.column.offsetHeight + previousProgress = progress + return elements.scroller.scrollTop - start + }, + finish: (cancelled) => { + if (this.elements !== elements) return + // Commit the final sibling margins while their input-fold transition override still applies. + void elements.column.offsetHeight + delete elements.column.dataset.inputFold + if (cancelled) { + const metrics = scrollMetrics(elements.scroller) + const height = elements.scroller.scrollHeight - this.spacerHeight() + this.setSpacer(metrics.top === 0 ? 0 : Math.max(0, metrics.top + metrics.height - height)) + this.invalidate() + return + } + this.setSpacer(finalRoom) + const metrics = scrollMetrics(elements.scroller) + const landing = { metrics, position: null, turn: this.latestTurn } + this.observation = { top: metrics.top, landing } + settled(landing) + }, + }) + } + + /** Clear fold reservations after a display-mode change, allowing the scroll range to shrink. */ + resetBelow(): void { + this.setSpacer(0) + this.invalidate() + } + /** * Give reserved room back after acknowledged scrolling or content growth without clamping the reader. * Holds still during folds and unsampled movement; following includes the room that remains. diff --git a/packages/client/ui-chat/src/client/contract/slots.ts b/packages/client/ui-chat/src/client/contract/slots.ts index 52d7786e20..9bce65619b 100644 --- a/packages/client/ui-chat/src/client/contract/slots.ts +++ b/packages/client/ui-chat/src/client/contract/slots.ts @@ -3,15 +3,16 @@ import type { RefObject } from 'react' import type { MessageId } from '@deepseek-ai/dsh-llm/brand' import type { SessionId, SessionSeq } from '@deepseek-ai/dsh-session/types' import type { PendingSubmission } from '@deepseek-ai/dsh-api-session-controller/client' +import type { FileAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { InboxState } from '@deepseek-ai/dsh-agent/types' import type { CommandNode, CompactionSummaryNode, ConversationLocationDataStore, ConversationTurnDataMap, ConversationGroupData, GroupSnapshot, - MessageImageLoader, MessageImagesOwnerProps, RenderEntry, RenderMessageImages, TurnLocation, + MessageImageLoader, MessageImageSource, MessageImagesOwnerProps, RenderEntry, TurnLocation, UserTextFacts, UserTextInput, } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { HostObservable, InjectFace, KeyedSnapshotSelectorHook, PropsLocale, PropsRenderSlots, PropsRuntime, - PropsStore, SlotHookFactory, SnapshotSelectorHook, + PropsRenderFactories, PropsStore, SlotHookFactory, SnapshotSelectorHook, } from '@deepseek-ai/dsh-client-ui-slots' import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { MarkdownFileMentions, MarkdownLabels } from '@deepseek-ai/dsh-client-ui-primitives' @@ -209,24 +210,39 @@ export interface ChatNodeOwnerProps { /** Renderer-owned Node portion selected by the grouping Definition. */ groupPart?: string cwd?: string | undefined - /** Open the current source file of a skill referenced by a sent message. */ - openSkill: (name: string) => void openFile: (path: string, options?: OpenFileOptions) => void inspectCall: ((callId: ToolCallId) => void) | undefined forkAt: (seq: number) => void - /** - * Session-authorized image loader, down-threaded from the Chat view so a - * chat-node renderer can render the attachment presentation slot directly - * with only the durable references plus this loader, instead of receiving a - * rendering closure. - */ + /** Session-authorized image loader supplied by the Chat view. */ loadImage: MessageImageLoader - renderMessageImages: RenderMessageImages fileMentions: (owner: TurnTailOwnerProps) => MarkdownFileMentions | undefined /** Turn-process state when this Node belongs to a projected Turn. */ turnProcess?: TurnProcessOwnerProps | undefined } +/** One attachment in the original user-message display order. */ +export type UserContentAttachment = + | { readonly type: 'image'; readonly image: MessageImageSource } + | { readonly type: 'file'; readonly file: FileAttachmentRef } + +/** Prepared user contents without row identity, admission state, time, or actions. */ +export interface UserContentData { + readonly text: string + readonly attachments: readonly UserContentAttachment[] + /** Blocks not represented by text or attachment presentation. */ + readonly extraBlocks: readonly unknown[] + /** Labels displayed in the caller-provided reference summary. */ + readonly referenceLabels?: readonly string[] +} + +/** Public content rendering input; reference renderers own their injected actions. */ +export interface UserContentInput extends Pick, + Pick { + readonly content: UserContentData + /** Transform inputs passed unchanged to UserText, separate from summary and rendering props. */ + readonly facts: Readonly> +} + /** Shared presentation state for one Turn-process answer generation. */ export interface TurnProcessOwnerProps { /** Process content eligible to share one Turn-level disclosure. */ @@ -247,7 +263,7 @@ export interface PresentationInjected { /** Full props of one keyed Chat renderer. */ export type ChatNodeViewProps = - PropsRuntime<'conversation.chat.node', Kind> & PropsLocale<'chat'> + PropsRuntime<'conversation.chat.node', Kind> & PropsLocale<'chat'> & PropsRenderFactories /** Command-row owner share. */ export interface CommandRowOwnerProps { @@ -292,8 +308,6 @@ export interface ChatViewInjected { /** Resolve one optional group without subscribing the root View to its data. */ chatGroup: (key: string) => ObservableSnapshot> | undefined> | undefined } - /** Open the current source file of a skill referenced by a sent message. */ - openSkill: (name: string) => void /** Open one HTTP(S) message link at the selected destination, using an external tab if Sidebar Browser is unavailable. */ openExternalLink: (url: string) => void openFile: (path: string, options?: OpenFileOptions) => Promise @@ -314,7 +328,7 @@ export type ChatFlowDataInjected = Pick { + 'cwd' | 'openFile' | 'inspectCall' | 'forkAt' | 'loadImage' | 'fileMentions'> { readonly entries: readonly RenderEntry[] readonly pendingInputs: readonly (PendingSubmission | InboxState['next-step'][number])[] readonly lastInputTurn: number | undefined @@ -324,7 +338,8 @@ export interface ChatFlowOwnerProps extends Pick - & PropsRenderSlots<'conversation.chat.node' | 'conversation.message.images'> + & PropsRenderSlots<'conversation.chat.node'> + & PropsRenderFactories & PropsStore & InjectFace & PropsLocale<'chat'> @@ -337,8 +352,9 @@ export type ChatViewSlotProps = & InjectFace & PropsLocale<'chat'> -/** Full props of the durable-message image renderer. */ -export type MessageImagesProps = PropsRuntime<'conversation.message.images'> & PropsLocale<'conversation'> +/** Full props shared by the user and output image entries. */ +export type MessageImagesProps = + PropsRuntime<'conversation.chat.user.images' | 'conversation.chat.message.images'> & PropsRenderFactories declare module '@deepseek-ai/dsh-client-ui-slots' { interface SessionStandardProps { @@ -352,6 +368,13 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } interface SlotFactoryMap { + /** Prepared user text, attachments, and references inside a caller-owned message row. */ + 'conversation.chat.user.content': { + scope: 'session' + props: UserContentInput + locale: 'chat' + children: { 'conversation.chat.user.images': { kind: 'single'; scope: 'session' } } + } /** Session-independent reasoning Markdown with Chat labels and compact typography. */ 'conversation.chat.reasoning.content': { scope: 'root' @@ -387,7 +410,9 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { * supplies image references, an authorized loader, and alignment. A * registration replaces the shipped gallery; without one, images are omitted. */ - 'conversation.message.images': { kind: 'single'; scope: 'session'; owner: MessageImagesOwnerProps } + 'conversation.chat.message.images': { kind: 'single'; scope: 'session'; owner: MessageImagesOwnerProps } + /** User-message images, including pending and local-echo previews, independently replaceable from output images. */ + 'conversation.chat.user.images': { kind: 'single'; scope: 'session'; owner: MessageImagesOwnerProps } /** * Command row keyed by the command name. The component receives the folded * command lifecycle and linked compaction when present. Reusing a key diff --git a/packages/client/ui-chat/src/client/conversation-nodes/README.i18n.yaml b/packages/client/ui-chat/src/client/conversation-nodes/README.i18n.yaml index a26c18c63a..5a6a4824ad 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/README.i18n.yaml +++ b/packages/client/ui-chat/src/client/conversation-nodes/README.i18n.yaml @@ -30,14 +30,14 @@ en: ada5a60d2c46f6a8 zh: f3eaeb5cb4d9b3de /chat-conversation-node-rules/display-modes/defaults-and-saving-preferences: - en: 71249bd1ef74a307 - zh: 9c8273ffd8823afa + en: b25bf00ce3a6a119 + zh: 0ab47a4014ea5e1e /chat-conversation-node-rules/display-modes/collapse-timing: - en: c31be5bb8cb77dc7 - zh: 9550ab598119076f + en: d87667e4d1729e51 + zh: 014a14ebb16ac798 /chat-conversation-node-rules/display-modes/group-title-rules: - en: 5b40d65e660549b7 - zh: 09b6894aa00154e7 + en: 2392290662bc69e8 + zh: 8872d651c07a8f4c /chat-conversation-node-rules/process-grouping: en: c2650489ded57503 zh: f2554d74e75ae0f9 diff --git a/packages/client/ui-chat/src/client/conversation-nodes/README.md b/packages/client/ui-chat/src/client/conversation-nodes/README.md index f823ed9b65..02bb1f08d4 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/README.md +++ b/packages/client/ui-chat/src/client/conversation-nodes/README.md @@ -131,15 +131,17 @@ Work details uses the Host setting `ui-chat.transcriptView`. The client reads it - Legacy `normal` and `expanded` values display as `detailed`, without automatically rewriting the saved values on disk. - When the setting is missing, `null`, or invalid, Desktop uses `standard` and non-Desktop Web uses `detailed`. Each client also uses its default before Host settings arrive; invalid values in other settings still fail validation. -Reading a default does not automatically save configuration. When the user changes modes, the selected value is saved through Host settings; memory mode does not write to disk. Desktop onboarding writes preferences according to its rules when completed or skipped. +Reading a default does not automatically save configuration. When the user changes modes, the selected value is saved through Host settings and stays process-local when settings cannot persist writes. Desktop onboarding writes preferences according to its rules when completed or skipped. ### Collapse timing -Settings → General → Collapse work details appears directly below Work details and is independent of the display mode. On completion is the default and retains immediate folding and tail positioning. On next message enables delayed folding and its coordinated transitions. The choice lasts for the current Client instance: closing Settings preserves it; reloading or reopening the app resets it to On completion. It never writes Host settings, browser storage, or Session data. +Settings → General → Collapse work details appears directly below Work details and is independent of the display mode. On completion is the default and retains immediate folding and tail positioning. On next message enables delayed folding and its coordinated transitions. The choice is saved as `ui-chat.collapseTiming` through the same Host profile settings as Work details and is restored after reload or reopening the app. Profiles without a saved value use On completion without writing that default. It does not write browser storage or Session data. With On next message, the latest Turn keeps its running presentation after completion: Compact and Standard retain their process headers, and Detailed retains its flat process rows. A pending ordinary transcript submission or a newer Turn ends this exemption without clearing the reader's manual whole-Turn choice. Inner disclosures reset only when their outer process actually hides. Queued input and steering alone do not end it. The latest Turn of a reopened Session also receives the exemption; manual whole-Turn choices still take precedence. Switching back to On completion ends the exemption immediately. +When a new message triggers a fold, process details close and the transcript follows the new message in one upward movement, without a second scroll after the fold. Off-screen steps do not add bottom space; only the space needed to preserve the visible movement remains when the retained answer and new message cannot fill it. Content added during the fold updates its remaining movement. Reopening every closing row cancels that movement and releases obsolete bottom space. A reading gesture interrupts automatic following; finishing the fold does not resume it. + Verbose retains its flat process rows under either timing. Failed, stopped, and interleaved-input Turns retain their existing whole-Turn eligibility rules; delayed folding can still postpone Detailed's conversion from flat rows to historical groups. ### Group-title rules @@ -183,7 +185,7 @@ Group headers show a category icon, replace it with a down arrow on hover or key An open capped group follows content growth only while its own scroll position is at the bottom. Scrolling away pauses that group's following; returning to the bottom resumes it, independently of outer transcript following. Manually opening an unclosed group starts at the bottom and follows growth; manually opening a closed group starts at the top with following disabled, even when its initial content fits without scrolling. Closing the group in the data or restoring its height cap through a mode change does not reset an already-open reader's position. Browser find retains its own reveal position. -Individual reasoning starts collapsed, including while streaming. All modes preview the latest paragraph whose first line ends with a newline; an unfinished single line has no preview. Later text in that paragraph does not change the preview. After settlement, the mode table applies. Expanded reasoning uses compact Markdown typography. +Only reasoning blocks with non-whitespace text produce individual rows; each retains its original text and expands independently. A blank streaming tail produces no row and does not transfer its running state to an earlier block. Individual reasoning starts collapsed, including while streaming. All modes preview the latest paragraph whose first line ends with a newline; an unfinished single line has no preview. Later text in that paragraph does not change the preview. After settlement, the mode table applies. Expanded reasoning uses compact Markdown typography. Switching modes retains manually opened groups and inner disclosures. It changes visibility and sizing without recreating the message rows. Detailed and Verbose do not open every individual disclosure. Only Verbose keeps the whole Turn open. diff --git a/packages/client/ui-chat/src/client/conversation-nodes/README.zh.md b/packages/client/ui-chat/src/client/conversation-nodes/README.zh.md index 886427a49a..600b02c266 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/README.zh.md +++ b/packages/client/ui-chat/src/client/conversation-nodes/README.zh.md @@ -131,15 +131,17 @@ description: "Chat 过程分组与活动摘要的明细业务规则。" - 旧值 `normal` 和 `expanded` 均按 `detailed` 展示,不自动改写磁盘中的值。 - 未配置、值为 `null` 或无效时,Desktop 使用 `standard`,非 Desktop Web 使用 `detailed`。Host 设置到达前也使用各自的默认值;其他设置的无效值仍会校验失败。 -读取默认值不会自动保存配置。用户切换模式时,通过 Host 设置保存所选值;内存模式不写磁盘。Desktop onboarding 完成或跳过时,按引导规则写入偏好。 +读取默认值不会自动保存配置。用户切换模式时,通过 Host 设置保存所选值;设置无法持久化写入时仅在当前进程内生效。Desktop onboarding 完成或跳过时,按引导规则写入偏好。 ### 收起时机 -设置 → 通用设置 → 过程收起时机位于工作步骤展示正下方,与展示模式独立。「完成时收起」是默认值,保留立即折叠和即时跟尾定位;「下次发送时收起」启用延后折叠及其协调过渡。选择仅在当前 Client 实例内有效:关闭设置面板后保留,刷新或重新打开应用时恢复为「完成时收起」。此偏好不写入 Host 设置、浏览器存储或 Session 数据。 +设置 → 通用设置 → 过程收起时机位于工作步骤展示正下方,与展示模式独立。「完成时收起」是默认值,保留立即折叠和即时跟尾定位;「下次发送时收起」启用延后折叠及其协调过渡。选择以 `ui-chat.collapseTiming` 保存到与工作步骤展示相同的 Host profile 设置,刷新或重新打开应用后会恢复。未保存此值的 profile 使用「完成时收起」,不会自动写入默认值。此偏好不写入浏览器存储或 Session 数据。 选择「下次发送时收起」后,最新轮次完成时保留运行中的呈现:简洁和标准保留过程组头,详细保留平铺过程行。普通 transcript 输入进入待发送状态,或出现更新轮次时,取消这项例外,但保留用户对整轮的手动开合选择。只有外层过程实际隐藏时,才重置内部开合。排队输入和单独的 steering 不会取消例外。重新打开 Session 时,其最新轮次也享有例外;整轮的手动开合选择仍优先。切回「完成时收起」会立即取消例外。 +新消息触发折叠时,过程收起与跟随新消息合为一次向上运动,折叠结束后不再追加滚动。屏幕外的步骤不增加底部补白;只有保留的正文和新消息无法填满可见内容移动所需空间时,才保留必要差额。折叠期间新增的内容会更新剩余运动;重新展开全部正在收起的行时,取消该运动并释放失效的底部补白。阅读手势会中断自动跟随,折叠结束不会重新接管。 + 完全展开模式在两种时机下都保留平铺过程行。失败、停止和含插入输入的轮次沿用原有整轮折叠资格;延后折叠仍可推迟详细模式从平铺行转换为历史分组的时机。 ### 组标题规则 @@ -183,7 +185,7 @@ description: "Chat 过程分组与活动摘要的明细业务规则。" 已展开的限高组仅在自己的滚动位置处于底部时跟随内容增长。滚离底部暂停该组跟随,滚回底部后恢复,与外层文本记录的跟随状态独立。手动展开未关闭的组时定位到底部并跟随增长;手动展开已关闭的组时从顶部开始且不启用跟随,即使初始内容无需滚动即可容纳。数据中的组变为已关闭,或通过模式切换恢复限高时,不重置已展开组的阅读位置。浏览器查找沿用自身的展开定位。 -单个推理初始收起,包括流式输出期间。四档都预览最近一个首行以换行结束的段落;未完成的单行没有预览,该段落后续文本不改变预览。结算后按上表展示。展开的推理使用紧凑 Markdown 排版。 +只有含非空白文本的推理块生成独立行,各自保留原文并独立展开。空白流式尾块不生成行,也不将运行状态转移给前面的块。单个推理初始收起,包括流式输出期间。四档都预览最近一个首行以换行结束的段落;未完成的单行没有预览,该段落后续文本不改变预览。结算后按上表展示。展开的推理使用紧凑 Markdown 排版。 切换模式保留手动展开的组和内部开合状态,只改变显隐与尺寸,不重建消息行。详细和完全展开都不表示自动打开每个内部控件;只有完全展开模式始终展开整轮。 diff --git a/packages/client/ui-chat/src/client/index.ts b/packages/client/ui-chat/src/client/index.ts index a725061f89..09edabb684 100644 --- a/packages/client/ui-chat/src/client/index.ts +++ b/packages/client/ui-chat/src/client/index.ts @@ -37,7 +37,7 @@ export type { ChatFlowDataInjected, ChatFlowHookContext, ChatFlowInjected, ChatFlowOwnerProps, ChatFlowSlotProps, UseGroupHeaderAction, CommandRowOwnerProps, CommandRowProps, MessageImagesProps, OpenFileOptions, PresentationInjected, QuotaNoticeCode, QuotaNoticeHostProps, QuotaNoticeInjected, QuotaNoticeOwnerProps, QuotaNoticeState, - ReasoningBodyOwnerProps, ReasoningContentInput, + ReasoningBodyOwnerProps, ReasoningContentInput, UserContentAttachment, UserContentData, UserContentInput, TurnProcessOwnerProps, TurnTailOwnerProps, UseChat, UseChatNodeTurnData, UseDisclosure, UsePresentation, UseGroupAction, } from './contract/slots.ts' export type { diff --git a/packages/client/ui-chat/src/client/performance-usage.ts b/packages/client/ui-chat/src/client/performance-usage.ts index b0313649a7..158860efb4 100644 --- a/packages/client/ui-chat/src/client/performance-usage.ts +++ b/packages/client/ui-chat/src/client/performance-usage.ts @@ -1,4 +1,4 @@ -/** Performance detail preference with process-local choices on memory-only settings scopes. */ +/** Performance detail preference, live immediately and reconciled with accepted Host settings. */ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client' import { DEFAULT_PERFORMANCE_USAGE, type ChatSettings, type PerformanceUsageMode } from '../chat-settings.ts' @@ -9,7 +9,7 @@ export class PerformanceUsagePolicy { /** Current choice, reconciled with accepted Host settings when available. */ readonly mode = createSnapshotStore(DEFAULT_PERFORMANCE_USAGE) - /** @param host - Chat settings scope, durable on loopback and memory-only elsewhere. */ + /** @param host - Chat settings scope persisted through the Host. */ constructor(private readonly host: ConfigForm) { const adopt = (): void => { const accepted = host.getSnapshot().value?.performanceUsage @@ -23,7 +23,7 @@ export class PerformanceUsagePolicy { dispose(): void { this.unsubscribe() } /** - * Publish a choice immediately and persist it when the scope supports writes. + * Publish a choice immediately and queue its Host write. * @param mode - Statistics detail selected by the user. */ setMode(mode: PerformanceUsageMode): void { diff --git a/packages/client/ui-chat/src/client/presentation-policy.ts b/packages/client/ui-chat/src/client/presentation-policy.ts index 04deade5dd..0bb38c7cdd 100644 --- a/packages/client/ui-chat/src/client/presentation-policy.ts +++ b/packages/client/ui-chat/src/client/presentation-policy.ts @@ -1,19 +1,14 @@ -/** Chat presentation derived from Host-backed detail and in-memory collapse timing. */ +/** Chat presentation derived from Host-backed detail and collapse timing. */ import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' -import type { TranscriptViewMode } from '../chat-settings.ts' - -/** Available points when a completed Turn returns to its historical presentation. */ -export const COLLAPSE_TIMINGS = ['completion', 'next-input'] as const - -/** When a completed Turn returns to its historical presentation. */ -export type CollapseTiming = typeof COLLAPSE_TIMINGS[number] +import type { CollapseTiming, TranscriptViewMode } from '../chat-settings.ts' +export { COLLAPSE_TIMINGS, type CollapseTiming } from '../chat-settings.ts' /** Presentation capabilities that one work-details mode enables. */ export interface ChatPresentationPolicy { - /** Mode this policy was derived from; for diagnostics, never for branching in renderers. */ + /** Preference identity for layout resets and diagnostics; renderers select the capabilities below. */ readonly mode: TranscriptViewMode - /** Browser-local experiment; completion retains the default immediate folding and scrolling. */ + /** Saved collapse timing; completion retains the default immediate folding and scrolling. */ readonly collapseTiming: CollapseTiming /** Whether a normally completed Turn folds its process rows behind the whole-Turn control. */ readonly foldCompletedTurns: boolean @@ -73,7 +68,7 @@ const TIMING_POLICIES = { /** * Resolve a stable policy for one detail mode and collapse timing. * @param mode - persisted work-details mode. - * @param collapseTiming - in-memory timing; defaults to immediate completion folding. + * @param collapseTiming - persisted timing; defaults to immediate completion folding. * @returns the same policy object for the same pair of choices. */ export function presentationPolicyFor( @@ -84,9 +79,9 @@ export function presentationPolicyFor( } /** - * Combine Host-backed detail and in-memory timing without owning subscriptions. + * Combine Host-backed detail and persisted timing without owning subscriptions. * @param mode - live work-details mode. - * @param collapseTiming - live, in-memory collapse timing. + * @param collapseTiming - live Host-backed collapse timing. * @returns observable policy whose subscriptions follow both preferences. */ export function derivePresentationPolicy( diff --git a/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx b/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx index a770217041..d438e25c1d 100644 --- a/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx +++ b/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx @@ -12,12 +12,12 @@ export interface TranscriptViewRowInjected { hooks: { /** Persisted work-details preference bound as useTranscriptView. */ transcriptView: SnapshotStore - /** Browser-local timing bound as useCollapseTiming. */ + /** Persisted collapse timing bound as useCollapseTiming. */ collapseTiming: SnapshotStore } /** Change the work-details presentation. */ setTranscriptView: (mode: TranscriptViewMode) => void - /** Retain collapse timing for this Client lifetime without changing Host settings. */ + /** Persist collapse timing independently of the work-details mode. */ setCollapseTiming: (timing: CollapseTiming) => void } @@ -40,7 +40,7 @@ const COLLAPSE_LABELS = { } as const satisfies Record /** - * Render work-details and browser-local collapse-timing selectors. + * Render the independent, Host-backed work-details and collapse-timing selectors. * @param props - composed Settings slot props. * @returns the preference row. */ diff --git a/packages/client/ui-chat/src/client/transcript-view.ts b/packages/client/ui-chat/src/client/transcript-view.ts index 4e311ff076..83928e2e8f 100644 --- a/packages/client/ui-chat/src/client/transcript-view.ts +++ b/packages/client/ui-chat/src/client/transcript-view.ts @@ -1,9 +1,10 @@ -/** Host-backed work details and independent, in-memory collapse timing. */ +/** Independent work-details preferences backed by the same Host configuration form. */ import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client' import type { CollapseTiming } from './presentation-policy.ts' import { + COLLAPSE_TIMING_FIELD, DEFAULT_COLLAPSE_TIMING, DEFAULT_TRANSCRIPT_VIEW_MODE, LEGACY_TRANSCRIPT_VIEW_MODE, LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE, TRANSCRIPT_VIEW_FIELD, type ChatSettings, type TranscriptViewMode, } from '../chat-settings.ts' @@ -13,8 +14,8 @@ export class TranscriptViewPolicy { private readonly unsubscribe: () => void /** Reactive current mode, including the client default before Host settings arrive. */ readonly mode: SnapshotStore - /** Independent Client-lifetime choice; each new instance starts with completion-time folding. */ - readonly collapseTiming: SnapshotStore = createSnapshotStore('completion') + /** Reactive collapse timing, defaulting to completion until Host settings arrive. */ + readonly collapseTiming: SnapshotStore = createSnapshotStore(DEFAULT_COLLAPSE_TIMING) /** * @param host - durable Chat settings scope. @@ -43,11 +44,13 @@ export class TranscriptViewPolicy { } /** - * Keep collapse timing in memory without writing Host or browser storage. + * Publish and persist collapse timing without changing the work-details mode. * @param timing - immediate completion folding or deferred folding at the next input. */ setCollapseTiming(timing: CollapseTiming): void { + if (this.collapseTiming.getSnapshot() === timing) return this.collapseTiming.set(timing) + void this.host.set(COLLAPSE_TIMING_FIELD, timing) } /** Adopt the latest accepted Host section without writing it back. */ @@ -58,5 +61,7 @@ export class TranscriptViewPolicy { const mode = saved === LEGACY_TRANSCRIPT_VIEW_MODE || saved === LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE ? 'detailed' : saved ?? this.defaultMode if (this.mode.getSnapshot() !== mode) this.mode.set(mode) + const timing = section.collapseTiming ?? DEFAULT_COLLAPSE_TIMING + if (this.collapseTiming.getSnapshot() !== timing) this.collapseTiming.set(timing) } } diff --git a/packages/client/ui-chat/src/index.ts b/packages/client/ui-chat/src/index.ts index 2380110127..e5876b8392 100644 --- a/packages/client/ui-chat/src/index.ts +++ b/packages/client/ui-chat/src/index.ts @@ -2,7 +2,7 @@ import type {} from '@deepseek-ai/dsh-settings' import type { Volatile, Context } from '@deepseek-ai/cordis' -import type { ChatSettings, LinkOpening, PerformanceUsageMode } from './chat-settings.ts' +import type { ChatSettings, CollapseTiming, LinkOpening, PerformanceUsageMode } from './chat-settings.ts' import z from '@deepseek-ai/schemastery' import { TRANSCRIPT_VIEW_FIELD } from './chat-settings.ts' @@ -18,6 +18,8 @@ export { export interface Config { /** Completed turn transcript presentation. */ transcriptView: Volatile + /** When completed work details return to their historical presentation. */ + collapseTiming: Volatile /** Performance and usage detail level. */ performanceUsage: Volatile /** Default destination for Chat HTTP(S) links. */ @@ -27,6 +29,7 @@ export interface Config { /** Live preferences projected to the browser. */ export const Config = z.object({ [TRANSCRIPT_VIEW_FIELD]: ChatSettingsFields[TRANSCRIPT_VIEW_FIELD].volatile(), + collapseTiming: ChatSettingsFields.collapseTiming.volatile(), performanceUsage: ChatSettingsFields['performanceUsage'].volatile(), linkOpening: ChatSettingsFields.linkOpening.volatile(), }) diff --git a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx index 7eee5bcff7..2898fab578 100644 --- a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx @@ -137,7 +137,7 @@ async function bench(initialSettings?: ChatSettings, withBrowserRegistry = true, } describe('Chat inject API', () => { - it('projects independent Settings choices without saving timing to Host settings', async () => { + it('projects independent Settings choices and saves timing to Host settings', async () => { const b = await bench() try { const row = b.runtime.slots.entries('settings.general.item') @@ -149,12 +149,12 @@ describe('Chat inject API', () => { expect(presentation.getSnapshot()).toMatchObject({ mode: 'detailed', collapseTiming: 'completion' }) setCollapseTiming('next-input') expect(presentation.getSnapshot()).toMatchObject({ mode: 'detailed', collapseTiming: 'next-input' }) - expect(b.chatSettings.set).not.toHaveBeenCalled() - b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed' }, revision: 1, writable: true }) + expect(b.chatSettings.set).toHaveBeenCalledWith('collapseTiming', 'next-input') + b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed', collapseTiming: 'next-input' }, revision: 1, writable: true }) expect(presentation.getSnapshot()).toMatchObject({ mode: 'standard', collapseTiming: 'next-input' }) setCollapseTiming('completion') expect(presentation.getSnapshot()).toMatchObject({ mode: 'standard', collapseTiming: 'completion' }) - expect(b.chatSettings.set).not.toHaveBeenCalled() + expect(b.chatSettings.set).toHaveBeenLastCalledWith('collapseTiming', 'completion') expect(b.session.prompt).not.toHaveBeenCalled() expect(b.session.cancel).not.toHaveBeenCalled() } finally { @@ -368,7 +368,7 @@ describe('Chat inject API', () => { const open = vi.spyOn(window, 'open').mockImplementation(() => null) try { const { injected } = b.chatViewApi(b.rootReference) - b.chatSettings.publish({ mode: 'memory', status: 'unavailable' }) + b.chatSettings.publish({ status: 'unavailable' }) b.chatSettings.set.mockResolvedValueOnce(false) b.linkPreference.setLinkOpening('new-tab') b.chatSettings.publish({ value: undefined }) @@ -387,20 +387,14 @@ describe('Chat inject API', () => { } }) - it('routes sent skill previews through the viewed Session source and tolerates an absent provider', async () => { + it('leaves skill preview injection to the skill reference owner', async () => { const b = await bench() - const { injected } = b.chatViewApi(b.rootReference) - injected.openSkill('review') - const openReference = vi.fn(() => true) - const sessionOf = vi.fn(() => ({ openReference })) - b.runtime.ctx.provide('inputTriggers', { sessionOf } as never) - injected.openSkill('review') - expect(sessionOf).toHaveBeenCalledWith(b.runtime.sessions.scope(ROOT)) - expect(openReference).toHaveBeenCalledWith('skill', { ref: '/review' }) - vi.spyOn(b.runtime.sessions, 'scope').mockReturnValueOnce(undefined) - injected.openSkill('review') - expect(openReference).toHaveBeenCalledTimes(1) - await b.runtime.dispose() + try { + const { injected } = b.chatViewApi(b.rootReference) + expect(injected).not.toHaveProperty('openSkill') + } finally { + await b.runtime.dispose() + } }) it('keeps a relative path under the Session without a cwd, and addresses a path outside the workspace absolutely', async () => { diff --git a/packages/client/ui-chat/tests/assistant-markdown-path-images.client.spec.tsx b/packages/client/ui-chat/tests/assistant-markdown-path-images.client.spec.tsx index e37c569f03..c366be70e6 100644 --- a/packages/client/ui-chat/tests/assistant-markdown-path-images.client.spec.tsx +++ b/packages/client/ui-chat/tests/assistant-markdown-path-images.client.spec.tsx @@ -3,15 +3,15 @@ import { cleanup, render } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { AssistantMarkdown, localPathMediaUrl } from '../src/client/chat/AssistantMarkdown.tsx' import { useDetailedPresentation } from './presentation-fixture.client.ts' +import { unusedImageLoader } from './reasoning-component-fixture.tsx' import { useDisclosure } from '../src/client/chat/use-disclosure.ts' import { useSearchableHidden } from '../src/client/chat/searchable-hidden.ts' -import type { ChatNodeOwnerProps, ChatViewSlotProps } from '../src/client/contract/slots.ts' +import type { ChatViewSlotProps } from '../src/client/contract/slots.ts' import type { AssistantBlock } from '../src/client/contract/snapshot.ts' afterEach(() => { cleanup(); vi.restoreAllMocks() }) const t = ((_key: string) => 'label') as ChatViewSlotProps['t'] -const renderMessageImages = (() => null) as ChatNodeOwnerProps['renderMessageImages'] function textBlock(text: string): AssistantBlock { return { kind: 'text', text } @@ -63,7 +63,7 @@ describe('AssistantMarkdown local-path images', () => { usePresentation={useDetailedPresentation} blocks={[textBlock('See ![diagram](/tmp/graph.png) for the layout.')]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} t={t} />, ) @@ -81,7 +81,7 @@ describe('AssistantMarkdown local-path images', () => { usePresentation={useDetailedPresentation} blocks={[textBlock('See ![diagram](relative.png).')]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} t={t} />, ) diff --git a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx index 46c0bda457..c449d30d89 100644 --- a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx @@ -30,6 +30,7 @@ import { CHAT_SETTINGS_NAMESPACE, type ChatSettings } from '../src/chat-settings import { ActivityPill, UsagePill } from '../src/client/chat/StatsPills.tsx' import { createFlowMotion } from '../src/client/chat/flow-motion.ts' import { CHAT_FLOW_INJECT, CHAT_NODE_INJECT } from '../src/client/apply.ts' +import { UserContent } from '../src/client/chat/UserContent.tsx' declare module '@deepseek-ai/dsh-client-ui-conversation/client' { interface ConversationTurnDataMap { @@ -101,6 +102,7 @@ describe('Chat apply wiring', () => { expect(entry).not.toHaveProperty('CHAT_FLOW_INJECT') expect(entry).not.toHaveProperty('CHAT_NODE_INJECT') expect(entry).not.toHaveProperty('ChatFlow') + expect(entry).not.toHaveProperty('UserContent') }) it('registers the frame-wide quota notice host and keeps the failure row injection-free', async () => { @@ -140,23 +142,37 @@ describe('Chat apply wiring', () => { await b.runtime.dispose() }) - it('owns node and image rendering through the flow slot with the shared Chat store', async () => { + it('owns node dispatch in the shared flow and image Slots in their domain renderers', async () => { const b = await bench() onTestFinished(() => b.runtime.dispose()) + b.runtime.renderRoot() expect(b.runtime.slots.spec('conversation.chat.flow')).toMatchObject({ kind: 'single', scope: 'session' }) const view = b.runtime.slots.entries('conversation.view')[0] const flow = b.runtime.slots.entries('conversation.chat.flow')[0] + const assistant = b.runtime.slots.entries('conversation.chat.node').find(entry => entry.options.key === 'assistant-step') + const userContent = b.runtime.factoryOf('conversation.chat.user.content') + expect(userContent).toMatchObject({ scope: 'session', locale: 'chat', component: UserContent }) + expect(userContent.children?.['conversation.chat.user.images']).toMatchObject({ kind: 'single', scope: 'session' }) + expect(assistant?.children?.['conversation.chat.message.images']).toMatchObject({ kind: 'single', scope: 'session' }) + expect(userContent.store).toBeUndefined() + expect(userContent.inject).toBeUndefined() expect(view?.children?.['conversation.chat.flow']).toBeDefined() expect(view?.children?.['conversation.chat.node']).toBeUndefined() - expect(view?.children?.['conversation.message.images']).toBeUndefined() + expect(view?.children?.['conversation.chat.message.images']).toBeUndefined() + expect(view?.children?.['conversation.chat.user.images']).toBeUndefined() expect(flow?.children?.['conversation.chat.node']).toBeDefined() - expect(flow?.children?.['conversation.message.images']).toBeDefined() + expect(flow?.children?.['conversation.chat.message.images']).toBeUndefined() + expect(flow?.children?.['conversation.chat.user.images']).toBeUndefined() + expect(userContent.children?.['conversation.chat.message.images']).toBeUndefined() + expect(assistant?.children?.['conversation.chat.user.images']).toBeUndefined() expect(flow?.store).toBeDefined() expect(flow?.store).toBe(view?.store) await b.chat.dispose() expect(b.runtime.slots.spec('conversation.chat.flow')).toBeUndefined() expect(b.runtime.slots.spec('conversation.chat.node')).toBeUndefined() - expect(b.runtime.slots.spec('conversation.message.images')).toBeUndefined() + expect(b.runtime.slots.spec('conversation.chat.message.images')).toBeUndefined() + expect(b.runtime.slots.spec('conversation.chat.user.images')).toBeUndefined() + expect(() => b.runtime.factoryOf('conversation.chat.user.content')).toThrow('no definition') }) it('lets another registrant replace one composer stats pill by id', async () => { @@ -200,7 +216,7 @@ describe('Chat apply wiring', () => { expect(face.hooks.transcriptView.getSnapshot()).toBe('compact') }) - it('resets in-memory collapse timing when the Chat plugin remounts', async () => { + it('restores saved collapse timing when the Chat plugin remounts', async () => { const b = await bench() try { const row = b.runtime.slots.entries('settings.general.item') @@ -211,8 +227,8 @@ describe('Chat apply wiring', () => { expect(hooks.collapseTiming.getSnapshot()).toBe('completion') setCollapseTiming('next-input') expect(hooks.collapseTiming.getSnapshot()).toBe('next-input') - expect(b.chatSettings.set).not.toHaveBeenCalled() - b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed' }, revision: 1, writable: true }) + expect(b.chatSettings.set).toHaveBeenCalledExactlyOnceWith('collapseTiming', 'next-input') + b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed', collapseTiming: 'next-input' }, revision: 1, writable: true }) expect(hooks.transcriptView.getSnapshot()).toBe('standard') expect(hooks.collapseTiming.getSnapshot()).toBe('next-input') expect(b.runtime.slots.entries('settings.general.item').map(entry => entry.options.id)) @@ -226,9 +242,9 @@ describe('Chat apply wiring', () => { const remounted = remountedRow.inject!() const remountedHooks = remounted.hooks as TranscriptViewRowInjected['hooks'] expect(remountedHooks.collapseTiming).not.toBe(hooks.collapseTiming) - expect(remountedHooks.collapseTiming.getSnapshot()).toBe('completion') + expect(remountedHooks.collapseTiming.getSnapshot()).toBe('next-input') expect(remountedHooks.transcriptView.getSnapshot()).toBe('standard') - expect(b.chatSettings.set).not.toHaveBeenCalled() + expect(b.chatSettings.set).toHaveBeenCalledExactlyOnceWith('collapseTiming', 'next-input') expect(b.runtime.slots.entries('settings.general.item').map(entry => entry.options.id)) .toEqual(['transcript-view', 'link-opening', 'composer-enter', 'performance-usage']) } finally { diff --git a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx index 7954e2cb45..fa922ee1e1 100644 --- a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx @@ -7,7 +7,7 @@ import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts import type { ChatConversationViewNode, ConversationNode, } from '@deepseek-ai/dsh-client-ui-chat/client' -import type { ChatNodeViewProps } from '../src/client/contract/slots.ts' +import type { ChatNodeViewProps, UserContentInput } from '../src/client/contract/slots.ts' import { formatMessageClock, msUntilNextLocalMidnight, startOfLocalDay, } from '../src/client/chat/message-chrome.ts' @@ -15,8 +15,10 @@ import { CompactionNodeView, ContextMessageNodeView, RetryNodeView, UnknownNodeView, UserMessageNodeView, } from '../src/client/chat/MessageItem.tsx' -import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' +import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx' import { useDetailedPresentation } from './presentation-fixture.client.ts' +import { unusedImageLoader } from './reasoning-component-fixture.tsx' +import { createUserContentFixture } from './user-content-component-fixture.tsx' import { useDisclosure } from '../src/client/chat/use-disclosure.ts' import { useSearchableHidden } from '../src/client/chat/searchable-hidden.ts' import { ActivityPill, UsagePill, type StatPillProps } from '../src/client/chat/StatsPills.tsx' @@ -30,7 +32,9 @@ afterEach(() => { }) const t: ChatNodeViewProps['t'] = makeTranslate(zh, commonZh) -const renderMessageImages: AssistantMarkdownProps['renderMessageImages'] = () => null +const renderUserImages: Parameters>[1] = () => null +let renderUserContent: ReturnType +beforeEach(() => { renderUserContent = createUserContentFixture() }) const RETRY_ID = 'retry-fixture' as Extract['retryId'] // Recency scans the whole transcript; a detached fixture is its own latest row. @@ -67,9 +71,14 @@ function MessageItem({ node, t: translate, referenceLabels, skillNames }: Messag } : node, } - const props = { - node: viewNode, t: translate, renderMessageImages, openFile: vi.fn(), openSkill: vi.fn(), useChat: useDetachedChat, - } as unknown as ChatNodeViewProps + const renderUserFactory: ChatNodeViewProps['renderFactorySlot'] = (name, input) => { + if (name !== 'conversation.chat.user.content') throw new Error(`Unexpected user Factory: ${name}`) + return renderUserContent(input as UserContentInput, renderUserImages, translate) + } + const props: Partial> & { node: ChatConversationViewNode } = { + node: viewNode, t: translate, loadImage: unusedImageLoader, renderFactorySlot: renderUserFactory, + openFile: vi.fn(), useChat: useDetachedChat, + } switch (node.kind) { case 'user': case 'steering': @@ -168,16 +177,21 @@ describe('MessageItem arms', () => { // Same-day clock: construct "today at 14:24" so the label stays `HH:mm`. const now = new Date() const time = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 14, 24).getTime() - render( + const view = render( , ) expect(screen.getByText('14:24')).toBeTruthy() expect(screen.getByRole('button', { name: '复制' })).toBeTruthy() + const stack = view.getByText('hello bubble').closest('div')?.parentElement + expect(stack?.parentElement).toBe(view.container.firstElementChild) + expect(stack?.contains(screen.getByText('14:24'))).toBe(false) + expect(stack?.contains(screen.getByRole('button', { name: '复制' }))).toBe(false) + expect(stack?.nextElementSibling?.contains(screen.getByRole('button', { name: '复制' }))).toBe(true) expect(screen.queryByRole('button', { name: '在新对话中分支' })).toBeNull() expect(screen.queryByRole('button', { name: '编辑' })).toBeNull() fireEvent.click(screen.getByRole('button', { name: '复制' })) @@ -1051,7 +1065,7 @@ describe('small branch tails', () => { t={t} blocks={[{ kind: 'reasoning', text: 'one-liner' }]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.getByText('one-liner')).toBeTruthy() diff --git a/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx b/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx index 8af4596b19..b212f91940 100644 --- a/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx @@ -26,7 +26,7 @@ function ScrollHarness({ input, onMotion }: { const state = useChatScroll(input) useLayoutEffect(() => { onMotion(state.motion) }, [onMotion, state.motion]) return <> -
+
@@ -34,7 +34,7 @@ function ScrollHarness({ input, onMotion }: { } -function mountScroll(deferCompletedTurns = true) { +function mountScroll(deferCompletedTurns = true, initial: Partial = {}) { let input: ChatScrollInput = { ready: true, order: [], @@ -45,12 +45,14 @@ function mountScroll(deferCompletedTurns = true) { submissionId: null, running: false, deferCompletedTurns, + transcriptView: 'verbose', loadedTurns: [], hasMore: false, loadingOlder: false, loadOlder: vi.fn(), loadThrough: vi.fn(async () => {}), chatScroll: { read: () => null, save: vi.fn() }, + ...initial, } const callbacks: { motion?: FlowMotionRows; resize?: () => void } = {} class Observer implements ResizeObserver { @@ -98,7 +100,243 @@ function mountScroll(deferCompletedTurns = true) { } } +const visibleFoldCases = [ + { name: 'E/E', earlier: 2400, steps: 1000, body: 400, viewport: 800, top: 800, input: 80, target: 2080, room: 0 }, + { name: 'E/T', earlier: 600, steps: 1000, body: 100, viewport: 800, top: 200, input: 80, target: 200, room: 220 }, + { name: 'E/B', earlier: 500, steps: 200, body: 400, viewport: 800, top: 200, input: 80, target: 200, room: 20 }, + { name: 'T/T', earlier: 500, steps: 2000, body: 100, viewport: 800, top: 900, input: 80, target: 500, room: 620 }, + { name: 'T/B', earlier: 500, steps: 1200, body: 400, viewport: 800, top: 1200, input: 80, target: 500, room: 320 }, + { name: 'B/B', earlier: 2400, steps: 1600, body: 1000, viewport: 800, top: 4200, input: 80, target: 2680, room: 0 }, + { name: 'short content', earlier: 100, steps: 300, body: 100, viewport: 800, top: 0, input: 80, target: 0, room: 0 }, + { name: 'larger input', earlier: 2000, steps: 300, body: 600, viewport: 800, top: 2100, input: 400, target: 2200, room: 0 }, + { name: 'body fills viewport', earlier: 900, steps: 300, body: 800, viewport: 800, top: 1200, input: 40, target: 940, room: 0 }, + { name: 'steps fill viewport', earlier: 900, steps: 800, body: 0, viewport: 800, top: 900, input: 0, target: 900, room: 800 }, + { name: 'input fills visible steps', earlier: 900, steps: 300, body: 500, viewport: 800, top: 900, input: 300, target: 900, room: 0 }, + { name: 'no steps', earlier: 900, steps: 0, body: 500, viewport: 800, top: 600, input: 40, target: 640, room: 0 }, + { name: 'input taller than viewport', earlier: 900, steps: 1200, body: 100, viewport: 800, top: 1400, input: 1200, target: 1400, room: 0 }, + { name: 'small viewport', earlier: 200, steps: 900, body: 100, viewport: 300, top: 900, input: 30, target: 200, room: 170 }, +] as const + +function mountVisibleFold(test: typeof visibleFoldCases[number], reduced: boolean) { + let inputHeight = 0 + let submission = 0 + let top: number = test.top + let motion: FlowMotionRows | undefined + const onMotion = (value: FlowMotionRows): void => { motion = value } + let input: ChatScrollInput = { + ready: false, order: [], firstSeq: null, lastKey: null, lastIsUser: false, + steeringId: null, submissionId: null, running: false, deferCompletedTurns: true, + transcriptView: 'detailed', loadedTurns: [], hasMore: false, loadingOlder: false, + loadOlder: vi.fn(), loadThrough: vi.fn(async () => {}), chatScroll: { read: () => null, save: vi.fn() }, + } + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: reduced }))) + const view = render() + const scroller = within(view.container).getByTestId('scrollport') + const column = within(view.container).getByTestId('column') + const spacer = scroller.querySelector('[data-chat-turn-spacer]')! + const row = document.createElement('div') + const glyph = document.createElement('span') + glyph.textContent = 'step text' + row.append(glyph) + column.append(row) + const rowHeight = () => row.hidden ? 0 : (row.style.transition !== '' && row.style.transition !== 'none') || row.style.height === '' + ? test.steps : Number.parseFloat(row.style.height) + const room = () => Number.parseFloat(spacer.style.height) || 0 + const contentHeight = () => test.earlier + rowHeight() + test.body + inputHeight + const floor = () => Math.max(0, contentHeight() + room() - test.viewport) + const scrollTo = vi.fn((options: ScrollToOptions) => { + scroller.scrollTop = options.top ?? scroller.scrollTop + }) + Object.defineProperties(scroller, { + clientHeight: { get: () => test.viewport }, + scrollHeight: { get: () => Math.max(test.viewport, contentHeight() + room()) }, + scrollTop: { + get: () => { top = Math.max(0, Math.min(top, floor())); return top }, + set: (value: number) => { top = Math.max(0, Math.min(value, floor())) }, + }, + scrollTo: { value: scrollTo }, + getBoundingClientRect: { value: () => ({ top: 0, bottom: test.viewport, height: test.viewport }) }, + }) + Object.defineProperties(row, { + offsetHeight: { get: rowHeight }, + getBoundingClientRect: { value: () => ({ top: test.earlier - top, bottom: test.earlier - top + rowHeight(), height: rowHeight() }) }, + }) + Object.defineProperties(column, { + offsetHeight: { get: contentHeight }, + getBoundingClientRect: { value: () => ({ top: -top, bottom: contentHeight() - top, height: contentHeight() }) }, + }) + input = { ...input, ready: true } + view.rerender() + top = test.top + scrollTo.mockClear() + return { + scroller, row, room, scrollTo, + reopenAll(verbose = false) { + act(() => { motion?.cancelMotion(row) }) + row.hidden = false + if (verbose) { + input = { ...input, transcriptView: 'verbose' } + view.rerender() + } + }, + growDuringFold(height: number, newSubmission: boolean) { + inputHeight += height + input = newSubmission + ? { ...input, submissionId: 'second-distinct-input' } + : { ...input, order: ['new-stream-content'], running: true } + view.rerender() + }, + cancelReading() { + fireEvent.wheel(scroller, { deltaY: -20 }) + scroller.scrollTop -= 20 + fireEvent.scroll(scroller) + return scroller.scrollTop + }, + updateInput() { + input = { ...input, submissionId: null, lastKey: 'durable-input', lastIsUser: true } + view.rerender() + }, + bodyTop: () => test.earlier + rowHeight() - top, + submit() { + inputHeight += test.input + row.hidden = false + submission++ + act(() => { + motion?.collapse(row, () => { row.hidden = true }) + }) + input = { ...input, submissionId: `visible-fold-input-${submission}` } + view.rerender() + }, + } +} + +describe.each([false, true])('visible input-fold matrix (reduced=%s)', (reduced) => { + it.each(visibleFoldCases)('$name lands with only the required visible room', async (test) => { + const h = mountVisibleFold(test, reduced) + const positions = [h.bodyTop()] + h.submit() + await act(async () => { await Promise.resolve() }) + for (let frame = 0; frame < 24; frame++) { + act(() => { vi.advanceTimersByTime(16) }) + positions.push(h.bodyTop()) + } + expect(h.scroller.scrollTop).toBeCloseTo(test.target, 5) + expect(h.room()).toBeCloseTo(test.room, 5) + if (test.steps > 0) expect(h.scrollTo.mock.calls.some(([options]) => options.behavior === 'smooth')).toBe(false) + for (let i = 1; i < positions.length; i++) expect(positions[i]!).toBeLessThanOrEqual(positions[i - 1]! + 0.01) + const end = h.bodyTop() + act(() => { vi.advanceTimersByTime(500) }) + expect(h.bodyTop()).toBe(end) + }) +}) + +it('consumes a prior legal fold deficit instead of accumulating whole steps on the next input', async () => { + const test = visibleFoldCases.find(test => test.name === 'T/B')! + const h = mountVisibleFold(test, false) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(400) }) + expect(h.room()).toBe(320) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(400) }) + expect(h.scroller.scrollTop).toBe(500) + expect(h.room()).toBe(240) + expect(h.scrollTo).not.toHaveBeenCalled() +}) + +it('retains the reader position without clamping after an input fold is interrupted', async () => { + const test = visibleFoldCases.find(test => test.name === 'B/B')! + const h = mountVisibleFold(test, false) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(112) }) + const readingTop = h.cancelReading() + act(() => { vi.advanceTimersByTime(400) }) + expect(h.scroller.scrollTop).toBe(readingTop) + expect(h.scrollTo.mock.calls.some(([options]) => options.behavior === 'smooth')).toBe(false) +}) + +it.each([false, true])('stops obsolete viewport writes when every closing row reopens (verbose=%s)', async (verbose) => { + const test = visibleFoldCases.find(test => test.name === 'T/B')! + const h = mountVisibleFold(test, false) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(112) }) + h.reopenAll(verbose) + await act(async () => { await Promise.resolve() }) + const position = h.scroller.scrollTop + act(() => { vi.advanceTimersByTime(400) }) + expect(h.room()).toBe(0) + expect(h.scroller.scrollTop).toBe(position) + expect(h.row.hidden).toBe(false) + expect(h.row.style.height).toBe('') + expect(h.scroller.querySelector('[data-input-fold]')).toBeNull() + expect(h.scrollTo.mock.calls.some(([options]) => options.behavior === 'smooth')).toBe(false) +}) + +it.each([false, true])('absorbs new height before the active fold finishes (new submission=%s)', async (newSubmission) => { + const test = visibleFoldCases.find(test => test.name === 'B/B')! + const h = mountVisibleFold(test, false) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(112) }) + h.growDuringFold(320, newSubmission) + await act(async () => { await Promise.resolve() }) + const positions = [h.bodyTop()] + for (let frame = 0; frame < 12; frame++) { + act(() => { vi.advanceTimersByTime(16) }) + positions.push(h.bodyTop()) + } + expect(h.scroller.scrollTop).toBe(test.target + 320) + expect(h.room()).toBe(0) + for (let i = 1; i < positions.length; i++) expect(positions[i]!).toBeLessThanOrEqual(positions[i - 1]! + 0.01) + const settled = h.scroller.scrollTop + act(() => { vi.advanceTimersByTime(500) }) + expect(h.scroller.scrollTop).toBe(settled) + expect(h.scrollTo.mock.calls.some(([options]) => options.behavior === 'smooth')).toBe(false) +}) + +it('keeps one active fold when the local echo becomes its durable input', async () => { + const test = visibleFoldCases.find(test => test.name === 'B/B')! + const h = mountVisibleFold(test, false) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(96) }) + const halfway = h.bodyTop() + h.updateInput() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(400) }) + expect(h.scroller.scrollTop).toBe(test.target) + expect(h.room()).toBe(0) + expect(h.bodyTop()).toBeLessThanOrEqual(halfway) + expect(h.scrollTo.mock.calls.some(([options]) => options.behavior === 'smooth')).toBe(false) +}) + describe('Chat scroll collapse timing', () => { + it.each(['resize', 'scroll', 'history', 'input', 'preference'] as const)( + 'waits for initial history before initializing a running view after %s', (change) => { + const h = mountScroll(true, { ready: false, running: true }) + expect(h.scroller.dataset.initialized).toBe('false') + if (change === 'resize') h.resize() + else if (change === 'scroll') fireEvent.scroll(h.scroller) + else if (change === 'history') h.update({ order: ['history'], lastKey: 'history' }) + else if (change === 'input') h.update({ submissionId: 'pending-input' }) + else h.update({ transcriptView: 'standard' }) + expect(h.scroller.dataset.initialized).toBe('false') + expect(h.scroller.scrollTop).toBe(0) + expect(h.scrollTo).not.toHaveBeenCalled() + + h.update({ ready: true }) + expect(h.scroller.dataset.initialized).toBe('true') + expect(h.scroller.scrollTop).toBe(600) + expect(h.scrollTo).not.toHaveBeenCalled() + h.grow(1_200) + h.resize() + expect(h.scroller.scrollTop).toBe(800) + }, + ) + it('does not defer one viewport\'s submitted input behind another viewport\'s fold', () => { const first = mountScroll() const second = mountScroll() @@ -123,51 +361,90 @@ describe('Chat scroll collapse timing', () => { } }) - it('coalesces submitted inputs into one follow after the last row closes', () => { + it('coalesces submitted inputs into one frame-owned fold', async () => { const h = mountScroll() h.startFold() h.update({ submissionId: 'first' }) h.update({ submissionId: 'second' }) expect(h.scrollTo).not.toHaveBeenCalled() expect(h.scroller.scrollTop).toBe(0) - h.finishFold() - expect(h.scrollTo).toHaveBeenCalledExactlyOnceWith({ top: 600, behavior: 'smooth' }) + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(400) }) + expect(h.scrollTo).not.toHaveBeenCalled() + expect(h.scroller.scrollTop).toBe(520) expect(h.scroller.style.overflowAnchor).toBe('') }) - it('keeps excess collapse as bottom room without reversing the scrollport', async () => { - const h = mountScroll() - h.scroller.scrollTop = 600 - h.startFold() + it('keeps only the visible deficit when submitted input is smaller than the fold', async () => { + const test = visibleFoldCases.find(test => test.name === 'T/B')! + const h = mountVisibleFold(test, false) + h.submit() await act(async () => { await Promise.resolve() }) - h.grow(1_060) - h.update({ submissionId: 'new-input' }) - h.grow(1_020) - act(() => { vi.advanceTimersByTime(20) }) - expect(h.scroller.scrollTop).toBe(600) - h.grow(980) - act(() => { vi.advanceTimersByTime(20) }) - expect(h.scroller.scrollTop).toBe(600) - fireEvent.scroll(h.scroller) - expect(h.scroller.scrollTop).toBe(600) - h.finishFold() - expect(h.scroller.scrollTop).toBe(600) + act(() => { vi.advanceTimersByTime(400) }) + expect(h.scroller.scrollTop).toBe(500) + expect(h.room()).toBe(320) expect(h.scrollTo).not.toHaveBeenCalled() - expect(h.scroller.querySelector('[data-chat-turn-spacer]')?.style.height).toBe('20px') }) - it('follows only the distance left after a smaller fold', async () => { + it.each([false, true])('clears mode-change bottom space after the fold (reader interrupts=%s)', async (interrupt) => { const h = mountScroll() - h.scroller.scrollTop = 600 + h.resize() + h.startFold() + h.update({ transcriptView: 'standard' }) + await act(async () => { await Promise.resolve() }) + const spacer = h.scroller.querySelector('[data-chat-turn-spacer]')! + expect(spacer.style.height).toBe('80px') + h.grow(920) + if (interrupt) { + fireEvent.wheel(h.scroller, { deltaY: -100 }) + h.scroller.scrollTop = 400 + fireEvent.scroll(h.scroller) + } + h.finishFold() + expect(spacer.style.height).toBe('') + expect(h.scroller.scrollHeight).toBe(920) + expect(h.scroller.scrollTop).toBe(interrupt ? 400 : 520) + expect(h.row.hidden).toBe(true) + h.resize() + expect(spacer.style.height).toBe('') + }) + + it('clears a previous fold reservation on an idle mode change', async () => { + const h = mountScroll() + h.resize() h.startFold() await act(async () => { await Promise.resolve() }) - h.grow(1_200) - h.update({ submissionId: 'new-input' }) - h.grow(1_120) - act(() => { vi.advanceTimersByTime(20) }) - expect(h.scroller.scrollTop).toBe(600) + h.grow(920) h.finishFold() - expect(h.scrollTo).toHaveBeenCalledExactlyOnceWith({ top: 720, behavior: 'smooth' }) + h.resize() + expect(h.scroller.querySelector('[data-chat-turn-spacer]')!.style.height).toBe('80px') + h.update({ transcriptView: 'standard' }) + expect(h.scroller.querySelector('[data-chat-turn-spacer]')!.style.height).toBe('') + expect(h.scroller.scrollTop).toBe(520) + }) + + it('keeps the latest mode reset when preferences change before a fold finishes', async () => { + const h = mountScroll() + h.resize() + h.startFold() + h.update({ transcriptView: 'standard' }) + await act(async () => { await Promise.resolve() }) + h.update({ transcriptView: 'detailed' }) + h.grow(920) + h.finishFold() + expect(h.scroller.querySelector('[data-chat-turn-spacer]')!.style.height).toBe('') + expect(h.scroller.scrollTop).toBe(520) + }) + + it('combines the remaining input distance with the smaller fold', async () => { + const test = visibleFoldCases.find(test => test.name === 'larger input')! + const h = mountVisibleFold(test, false) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(400) }) + expect(h.scroller.scrollTop).toBe(2200) + expect(h.room()).toBe(0) + expect(h.scrollTo).not.toHaveBeenCalled() }) it.each(['wheel', 'touchstart', 'pointerdown', 'keydown'] as const)( @@ -200,7 +477,9 @@ describe('Chat scroll collapse timing', () => { h.update({ order: ['streaming-change'], running: true }) if (newInput) h.update({ submissionId: 'second' }) h.finishFold() - if (newInput) expect(h.scrollTo).toHaveBeenCalledExactlyOnceWith({ top: 600, behavior: 'smooth' }) + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(400) }) + if (newInput) expect(h.scroller.scrollTop).toBe(520) else { expect(h.scrollTo).not.toHaveBeenCalled() expect(h.scroller.scrollTop).toBe(420) diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index 2357acedc9..d248901ed5 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -2,7 +2,8 @@ import type { ProcessGroupData } from '../src/client/contract/process-groups.ts' import type { InboxState } from '@deepseek-ai/dsh-agent/types' -import type { GlobalStandardProps, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import { MessageId } from '@deepseek-ai/dsh-llm/brand' +import type { GlobalStandardProps, PropsRenderFactories, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { useEffect, useMemo } from 'react' @@ -12,7 +13,7 @@ import type { ChatViewSlotProps, CommandNode, CompactionSummaryNode, ContextMessageNode, ConversationNode, LegacyConversationSlice, ModelRetryNode, StartedToolCall, SteeringMessageNode, ToolCallBlock, ToolResultNode, TurnErrorNode, TurnMaxTokensNode, - TranscriptViewMode, UserMessageNode, + TranscriptViewMode, UserContentInput, UserMessageNode, } from '@deepseek-ai/dsh-client-ui-chat/client' import type { SessionListState, SessionSnapshot, @@ -54,6 +55,7 @@ import type { TurnProcessSpec } from '../src/client/contract/turn-process.ts' import { chatSnapshotFixture } from './chat-snapshot-fixture.client.ts' import { installTurnNavigatorObserver } from './turn-navigator-fixture.ts' import { renderReasoningSlot } from './reasoning-component-fixture.tsx' +import { createUserContentFixture } from './user-content-component-fixture.tsx' import { ConversationGroupStore } from '../../ui-conversation/src/client/conversation/group-store.ts' function installGroupedSnapshot( @@ -261,6 +263,13 @@ declare const flowDispatch: ChatViewSlotProps['renderSlot'] type NodeRenderer = typeof nodeDispatch<'conversation.chat.node'> type FlowRenderer = typeof flowDispatch<'conversation.chat.flow'> type ImageRenderer = (owner: MessageImagesOwnerProps) => React.ReactNode +type HarnessStandardProps = ChatViewSlotProps & PropsRenderFactories + +function isImageOwner(owner: object): owner is MessageImagesOwnerProps { + return 'images' in owner && Array.isArray(owner.images) + && 'loadImage' in owner && typeof owner.loadImage === 'function' + && 'align' in owner && (owner.align === 'start' || owner.align === 'end') +} type ToolOwner = Pick & { readonly callId: string readonly toolName: string @@ -270,12 +279,9 @@ type ToolOwner = Pick & { const renderCommandSlot: React.ComponentProps['renderSlot'] = (_key, _owner, opts) => opts?.fallback ?? null const renderTurnTailSlot: React.ComponentProps['renderSlot'] = () => null -const assistantSlots: Pick, 'renderSlot'> = { - renderSlot: renderReasoningSlot, -} function HarnessChatFlow({ standard, owner, hookContext, renderSlot }: { - readonly standard: ChatViewSlotProps + readonly standard: HarnessStandardProps readonly owner: ChatFlowOwnerProps readonly hookContext: ChatFlowHookContext readonly renderSlot: ChatFlowSlotProps['renderSlot'] @@ -288,13 +294,14 @@ function HarnessChatFlow({ standard, owner, hookContext, renderSlot }: { return } -function HarnessChatNode({ standard, owner, hookContext, usePerformanceUsage, toolOwners, fallback }: { - readonly standard: ChatViewSlotProps +function HarnessChatNode({ standard, owner, hookContext, usePerformanceUsage, toolOwners, fallback, renderAssistantSlot }: { + readonly standard: HarnessStandardProps readonly owner: RoutedChatNodeOwner readonly hookContext: ChatNodeHookContext readonly usePerformanceUsage: React.ComponentProps['usePerformanceUsage'] readonly toolOwners: ToolOwner[] readonly fallback: React.ReactNode + readonly renderAssistantSlot: React.ComponentProps['renderSlot'] }) { const hooks = useMemo(() => ({ useTurnData: CHAT_NODE_INJECT.hooks.turnData(standard, hookContext), @@ -311,7 +318,7 @@ function HarnessChatNode({ standard, owner, hookContext, usePerformanceUsage, to case 'context': return case 'assistant-step': - return + return case 'command': return case 'manual-compaction': @@ -392,7 +399,8 @@ function makeHarness( key => grouped?.groupSource(key as GroupKey) ?? absentGroup, ) const openFile = vi.fn<(path: string) => Promise>().mockResolvedValue(undefined) - const openSkill = vi.fn<(name: string) => void>() + const openUserFile = vi.fn<(path: string) => void>() + const renderUserContent = createUserContentFixture({ openFile: openUserFile }) const loadOlder = vi.fn() const loadThrough = vi.fn<(seq: number) => Promise>().mockResolvedValue(undefined) // Mutable outline holder: tests swap the value and drive a re-render via set(). @@ -415,11 +423,19 @@ function makeHarness( const usePerformanceUsage = bindSnapshotSelector(performanceUsage) let nodeSlotOverride: NodeRenderer | undefined let imageSlotOverride: ImageRenderer | undefined + const renderImages = (name: string, owner: object, options?: { fallback?: React.ReactNode }) => { + if ((name !== 'conversation.chat.user.images' && name !== 'conversation.chat.message.images') || !isImageOwner(owner)) { + throw new Error(`Unexpected Chat image Slot: ${name}`) + } + return imageSlotOverride?.(owner) ?? options?.fallback ?? null + } + const renderAssistantSlot: React.ComponentProps['renderSlot'] = (name, owner, options) => + name === 'conversation.chat.message.images' ? renderImages(name, owner, options) : renderReasoningSlot(name, owner, options) const renderNodeSlot: NodeRenderer = (key, owner, opts) => { if (nodeSlotOverride !== undefined) return nodeSlotOverride(key, owner, opts) return + toolOwners={toolOwners} fallback={opts.fallback} renderAssistantSlot={renderAssistantSlot} /> } const renderFlowSlot: ChatFlowSlotProps['renderSlot'] = (key: string, owner: object, opts?: { fallback?: React.ReactNode @@ -428,11 +444,12 @@ function makeHarness( if (key === 'conversation.chat.node') { return renderNodeSlot(key, owner as RoutedChatNodeOwner, opts as Parameters[2]) } - if (key === 'conversation.message.images') { - return imageSlotOverride?.(owner as MessageImagesOwnerProps) ?? opts?.fallback ?? null - } throw new Error(`Undeclared flow child: ${key}`) } + const renderFactorySlot: PropsRenderFactories['renderFactorySlot'] = (name, owner) => { + if (name !== 'conversation.chat.user.content') throw new Error(`Unexpected Chat Factory: ${name}`) + return renderUserContent(owner as UserContentInput, renderImages, props.t) + } const renderSlot: FlowRenderer = (key, owner, opts) => { if (key !== 'conversation.chat.flow') throw new Error(`Undeclared ChatView child: ${key}`) if ('renderSlot' in owner || 'useStore' in owner || 'actions' in owner) { @@ -443,7 +460,8 @@ function makeHarness( // SessionProvider seat arrives with the session-scope child declaration; // ChatView never invokes it (pass-through stub). const SessionProviderStub: ChatViewSlotProps['SessionProvider'] = ({ children }) => <>{children} - const props: ChatViewSlotProps = { + const props: HarnessStandardProps = { + renderFactorySlot, usePanelInfo: selector => selector({ activePanelId: null }), sessionId: SID, useSession: bindSnapshotSelector(session.source), @@ -487,7 +505,6 @@ function makeHarness( openView, completeViewRequest: () => {}, openFile, - openSkill, openExternalLink: vi.fn(), loadOlder, loadThrough, @@ -518,7 +535,7 @@ function makeHarness( } return { set, setSession: session.set, setChat: chatSource.set, ChatView, props, - openFile, openSkill, loadOlder, loadThrough, openView, + openFile, openUserFile, loadOlder, loadThrough, openView, setOutline: (value: unknown) => { outlineValue = value }, chatScroll, forkAt, toolOwners, setPerformanceUsage: (mode: 'compact' | 'detailed') => { performanceUsage.set(mode) }, @@ -1851,6 +1868,32 @@ describe('ChatView', () => { expect(h.forkAt).toHaveBeenCalledWith(3) })) + it('keeps pending file mentions non-interactive until admission enables the reference injector', () => { + const pending: InboxState['next-step'][number] = { + id: MessageId('pending-file-mention'), role: 'user', source: { kind: 'user' }, + content: [{ type: 'text', text: 'Read @src/review.ts' }], + } + const h = makeHarness({}, { testInbox: { 'next-turn': [], 'next-step': [pending] }, running: true }) + const view = render() + const mention = view.getByText('review.ts') + expect(mention.closest('[data-pending-steering]')).not.toBeNull() + expect(view.queryByRole('button', { name: 'review.ts' })).toBeNull() + fireEvent.click(mention) + expect(h.openUserFile).not.toHaveBeenCalled() + expect(h.openFile).not.toHaveBeenCalled() + act(() => { + h.setSession({ testInbox: { 'next-turn': [], 'next-step': [] } }) + h.setChat({ nodes: [{ + kind: 'steering', messageId: pending.id, seq: 1, time: 1_000, + content: pending.content, source: pending.source, + }] }) + }) + expect(view.container.querySelector('[data-pending-steering]')).toBeNull() + fireEvent.click(view.getByRole('button', { name: 'review.ts' })) + expect(h.openUserFile).toHaveBeenCalledWith('src/review.ts') + expect(h.openFile).not.toHaveBeenCalled() + }) + it('keeps a later pending occurrence visible when it reuses a durable MessageId', () => { const pending = { id: 'steer-occurrence-later' as never, diff --git a/packages/client/ui-chat/tests/config.host.spec.ts b/packages/client/ui-chat/tests/config.host.spec.ts index a7fa8fa80a..b3ebb9b698 100644 --- a/packages/client/ui-chat/tests/config.host.spec.ts +++ b/packages/client/ui-chat/tests/config.host.spec.ts @@ -14,9 +14,9 @@ describe('ui-chat Host settings', () => { const configuration = await liveConfig(ctx, { Config, apply }) const { fiber } = configuration - expect(plainConfig(configuration.fiber.config)).toEqual({ performanceUsage: 'detailed', linkOpening: 'sidebar' }) + expect(plainConfig(configuration.fiber.config)).toEqual({ performanceUsage: 'detailed', linkOpening: 'sidebar', collapseTiming: 'completion' }) await configuration.update({ transcriptView: 'normal' }) - expect(plainConfig(configuration.fiber.config)).toEqual({ transcriptView: 'normal', performanceUsage: 'detailed', linkOpening: 'sidebar' }) + expect(plainConfig(configuration.fiber.config)).toEqual({ transcriptView: 'normal', performanceUsage: 'detailed', linkOpening: 'sidebar', collapseTiming: 'completion' }) for (const mode of ['expanded', 'compact', 'standard', 'detailed', 'verbose']) { await configuration.update({ transcriptView: mode }) expect(plainConfig(configuration.fiber.config)).toMatchObject({ transcriptView: mode }) @@ -35,6 +35,21 @@ describe('ui-chat Host settings', () => { await fiber.dispose() }) + it('validates collapse timing and restores its saved config independently of work details', async () => { + const ctx = new Context() + const configuration = await liveConfig(ctx, { Config, apply }) + expect(plainConfig(configuration.fiber.config)).toMatchObject({ collapseTiming: 'completion' }) + await configuration.update({ transcriptView: 'compact', collapseTiming: 'next-input' }) + const saved = plainConfig(configuration.fiber.config) + if (typeof saved !== 'object' || saved === null) throw new Error('expected saved configuration object') + expect(saved).toMatchObject({ transcriptView: 'compact', collapseTiming: 'next-input' }) + await expect(configuration.update({ collapseTiming: 'never' })).rejects.toThrow() + await configuration.fiber.dispose() + const restored = await liveConfig(ctx, { Config, apply }, saved) + expect(plainConfig(restored.fiber.config)).toMatchObject({ transcriptView: 'compact', collapseTiming: 'next-input' }) + await restored.fiber.dispose() + }) + it('loads without a settings provider', async () => { const ctx = new Context() await expect(ctx.plugin({ Config, apply }).await()).resolves.toBeDefined() diff --git a/packages/client/ui-chat/tests/coverage-tails.client.spec.tsx b/packages/client/ui-chat/tests/coverage-tails.client.spec.tsx index cf7b24532c..241a0faded 100644 --- a/packages/client/ui-chat/tests/coverage-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/coverage-tails.client.spec.tsx @@ -6,12 +6,12 @@ import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' import { useDetailedPresentation } from './presentation-fixture.client.ts' +import { unusedImageLoader } from './reasoning-component-fixture.tsx' import { useDisclosure } from '../src/client/chat/use-disclosure.ts' import { useSearchableHidden } from '../src/client/chat/searchable-hidden.ts' import { zh } from '../src/client/locale.ts' const t: AssistantMarkdownProps['t'] = makeTranslate(zh, commonZh) -const renderMessageImages: AssistantMarkdownProps['renderMessageImages'] = () => null afterEach(cleanup) @@ -27,7 +27,7 @@ describe('tails', () => { { kind: 'other', block: { type: 'mystery' } }, ]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.getByText('思考')).toBeTruthy() @@ -40,7 +40,7 @@ describe('tails', () => { blocks={[{ kind: 'text', text: 'partial words' }]} streaming={false} interrupted - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(stopped.getByText('已停止')).toBeTruthy() @@ -55,14 +55,14 @@ describe('tails', () => { t={t} blocks={[{ kind: 'tool-call', callId: 'c', name: 'todo_write', argsRaw: '{}' }]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(empty.container.firstChild).toBeNull() const blank = render( null} useDisclosure={useDisclosure} useGroupAction={useSearchableHidden} usePresentation={useDetailedPresentation} - t={t} blocks={[]} streaming={false} renderMessageImages={renderMessageImages} />, + t={t} blocks={[]} streaming={false} loadImage={unusedImageLoader} />, ) expect(blank.container.firstChild).toBeNull() }) diff --git a/packages/client/ui-chat/tests/flow-motion.client.spec.tsx b/packages/client/ui-chat/tests/flow-motion.client.spec.tsx index 38c771bdbc..5eb8c2f853 100644 --- a/packages/client/ui-chat/tests/flow-motion.client.spec.tsx +++ b/packages/client/ui-chat/tests/flow-motion.client.spec.tsx @@ -210,6 +210,22 @@ describe('flow motion', () => { expect(reserve).toHaveBeenCalledExactlyOnceWith(200) }) + it('does not rewrite a reopened row after its input-fold ownership is cancelled', async () => { + vi.useFakeTimers() + const row = rowWithHeight(180) + const done = vi.fn() + motion.collapse(row, done) + motion.followInput({ begin: vi.fn(), frame: () => -20, finish: vi.fn() }) + await Promise.resolve() + vi.advanceTimersByTime(96) + motion.cancelMotion(row) + expectCleared(row) + vi.advanceTimersByTime(400) + expectCleared(row) + expect(row.style.translate).toBe('') + expect(done).not.toHaveBeenCalled() + }) + it('clears pending reservations and idle work with its owner', async () => { const row = rowWithHeight(80) const idle = vi.fn() @@ -307,13 +323,14 @@ describe.each([ expect(vi.getTimerCount()).toBe(0) }) - it.each([false, true])('hides immediately without motion when reduced motion is %s', (reduced) => { + it.each([false, true])('hides before the next paint when reduced motion is %s', async (reduced) => { vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: reduced }))) const onReveal = vi.fn() const view = render(
) const row = view.getByTestId('motion-row') Object.defineProperty(row, 'offsetHeight', { value: 80 }) view.rerender(
) + await act(async () => { await Promise.resolve() }) expect(row.getAttribute('hidden')).toBe(hiddenValue) expectCleared(row) expect(motion.foldActive()).toBe(false) diff --git a/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx b/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx index 801bc01176..a15de80592 100644 --- a/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx @@ -6,6 +6,7 @@ import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-tes import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' import { useDetailedPresentation } from './presentation-fixture.client.ts' +import { unusedImageLoader } from './reasoning-component-fixture.tsx' import { useDisclosure } from '../src/client/chat/use-disclosure.ts' import { useSearchableHidden } from '../src/client/chat/searchable-hidden.ts' import { ActivityPill, UsagePill, type StatPillProps } from '../src/client/chat/StatsPills.tsx' @@ -13,7 +14,6 @@ import { zh } from '../src/client/locale.ts' import { chatSnapshotFixture } from './chat-snapshot-fixture.client.ts' const t: AssistantMarkdownProps['t'] = makeTranslate(zh, commonZh) -const renderMessageImages: AssistantMarkdownProps['renderMessageImages'] = () => null afterEach(() => { cleanup() @@ -29,7 +29,7 @@ describe('render branch tails', () => { t={t} blocks={[{ kind: 'reasoning', text: 'done thinking' }, { kind: 'text', text: 'answer' }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) // reasoning at index 0 with a later block: running is false → ok state. @@ -72,7 +72,7 @@ describe('render branch tails', () => { t={t} blocks={[{ kind: 'reasoning', text: 'still thinking' }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.container.querySelector('[data-state="running"]')).not.toBeNull() diff --git a/packages/client/ui-chat/tests/image-labels.client.spec.tsx b/packages/client/ui-chat/tests/image-labels.client.spec.tsx index 9fdf281e40..e37b5ec2c6 100644 --- a/packages/client/ui-chat/tests/image-labels.client.spec.tsx +++ b/packages/client/ui-chat/tests/image-labels.client.spec.tsx @@ -1,12 +1,13 @@ // @vitest-environment jsdom -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { cleanup, render } from '@testing-library/react' import { AttachmentId } from '@deepseek-ai/dsh-attachment' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { makeTranslate, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' -import type { RenderMessageImages } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx' +import type { MessageImagesOwnerProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' import { useDetailedPresentation } from './presentation-fixture.client.ts' import { useDisclosure } from '../src/client/chat/use-disclosure.ts' import { useSearchableHidden } from '../src/client/chat/searchable-hidden.ts' @@ -25,10 +26,11 @@ const attachment = { name: 'history.png', } -type MessageImagesRenderOwner = Parameters[0] - -function imageRenderer(calls: MessageImagesRenderOwner[]): RenderMessageImages { - return (owner) => { +async function renderImages(blocks: AssistantMarkdownProps['blocks'], calls: MessageImagesOwnerProps[]) { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + const loadImage = vi.fn(async () => 'blob:history') + runtime.slots.inject('conversation.chat.message.images', () => runtime.slots.register({ name: 'conversation.chat.message.images' }, (owner: MessageImagesOwnerProps) => { calls.push(owner) return (
@@ -39,63 +41,94 @@ function imageRenderer(calls: MessageImagesRenderOwner[]): RenderMessageImages { })}
) - } + })) + await runtime.sessions.add({ id: 'image-labels' }) + const session = runtime.sessions.retainFor(runtime.ctx, SessionId('image-labels')) + await runtime.root.declare({ + 'conversation.chat.reasoning.body': { kind: 'single', scope: 'session' }, + 'conversation.chat.message.images': { kind: 'single', scope: 'session' }, + }, ({ renderSlot, SessionProvider }) => ( + + + + )) + return { view: runtime.renderRoot(), loadImage } } describe('assistant image slot handoff', () => { - it('passes one image group and its message alignment to the renderer', () => { - const calls: MessageImagesRenderOwner[] = [] - const view = render( - null} useDisclosure={useDisclosure} useGroupAction={useSearchableHidden} - usePresentation={useDetailedPresentation} - t={t} - blocks={[{ kind: 'image', attachment }]} - streaming={false} - renderMessageImages={imageRenderer(calls)} - />, - ) + it('passes one image group and its message alignment to the renderer', async () => { + const calls: MessageImagesOwnerProps[] = [] + const { view, loadImage } = await renderImages([{ kind: 'image', attachment }], calls) expect(view.getByTestId('message-images').getAttribute('data-align')).toBe('start') expect(calls).toHaveLength(1) expect(calls[0]?.images).toEqual([{ attachment }]) + expect(calls[0]?.loadImage).toBe(loadImage) + expect(view.getByText('history.png')).toBeTruthy() }) - it('merges consecutive image blocks into one group and splits groups at text', () => { - const calls: MessageImagesRenderOwner[] = [] - const view = render( - null} useDisclosure={useDisclosure} useGroupAction={useSearchableHidden} - usePresentation={useDetailedPresentation} - t={t} - blocks={[ - { kind: 'image', attachment }, - { kind: 'image', attachment }, - { kind: 'text', text: 'between' }, - { kind: 'image', attachment }, - ]} - streaming={false} - renderMessageImages={imageRenderer(calls)} - />, + it('updates one message loader without changing its sibling or remounting either gallery', () => { + const firstLoader = vi.fn(async () => 'blob:first') + const nextLoader = vi.fn(async () => 'blob:next') + const siblingLoader = vi.fn(async () => 'blob:sibling') + const firstRenderer = vi.fn((_key: string, _owner: object) => first gallery) + const siblingRenderer = vi.fn((_key: string, _owner: object) => sibling gallery) + const props = { + blocks: [{ kind: 'image', attachment }], streaming: false, t, + useDisclosure, useGroupAction: useSearchableHidden, + usePresentation: useDetailedPresentation, + } satisfies Omit + const content = (loadImage: AssistantMarkdownProps['loadImage']) => ( + <> + + + ) + const view = render(content(firstLoader)) + const firstGallery = view.getByText('first gallery') + const siblingGallery = view.getByText('sibling gallery') + const owner = { images: [{ attachment }], align: 'start' } + expect(firstRenderer).toHaveBeenLastCalledWith('conversation.chat.message.images', { + ...owner, loadImage: firstLoader, + }) + expect(siblingRenderer).toHaveBeenLastCalledWith('conversation.chat.message.images', { + ...owner, loadImage: siblingLoader, + }) + + view.rerender(content(nextLoader)) + + expect(firstRenderer).toHaveBeenLastCalledWith('conversation.chat.message.images', { + ...owner, loadImage: nextLoader, + }) + expect(siblingRenderer).toHaveBeenLastCalledWith('conversation.chat.message.images', { + ...owner, loadImage: siblingLoader, + }) + expect(view.getByText('first gallery')).toBe(firstGallery) + expect(view.getByText('sibling gallery')).toBe(siblingGallery) + }) + + it('merges consecutive image blocks into one group and splits groups at text', async () => { + const calls: MessageImagesOwnerProps[] = [] + const { view } = await renderImages([ + { kind: 'image', attachment }, + { kind: 'image', attachment }, + { kind: 'text', text: 'between' }, + { kind: 'image', attachment }, + ], calls) const galleries = view.getAllByTestId('message-images') expect(galleries).toHaveLength(2) expect(galleries.map(gallery => gallery.getAttribute('data-count'))).toEqual(['2', '1']) expect(calls.map(call => call.images.length)).toEqual([2, 1]) }) - it('keeps the renderer output at the image block position between text blocks', () => { - const calls: MessageImagesRenderOwner[] = [] - const view = render( - null} useDisclosure={useDisclosure} useGroupAction={useSearchableHidden} - usePresentation={useDetailedPresentation} - t={t} - blocks={[ - { kind: 'text', text: 'before' }, - { kind: 'image', attachment }, - { kind: 'text', text: 'after' }, - ]} - streaming={false} - renderMessageImages={imageRenderer(calls)} - />, - ) + it('keeps the renderer output at the image block position between text blocks', async () => { + const calls: MessageImagesOwnerProps[] = [] + const { view } = await renderImages([ + { kind: 'text', text: 'before' }, + { kind: 'image', attachment }, + { kind: 'text', text: 'after' }, + ], calls) const image = view.getByTestId('message-images') const before = view.getByText('before') const after = view.getByText('after') diff --git a/packages/client/ui-chat/tests/performance-usage.client.spec.ts b/packages/client/ui-chat/tests/performance-usage.client.spec.ts index 0ab9bde440..42a8e8f4e9 100644 --- a/packages/client/ui-chat/tests/performance-usage.client.spec.ts +++ b/packages/client/ui-chat/tests/performance-usage.client.spec.ts @@ -5,9 +5,9 @@ import type { ChatSettings } from '../src/chat-settings.ts' import { PerformanceUsagePolicy } from '../src/client/performance-usage.ts' describe('PerformanceUsagePolicy', () => { - it('keeps explicit choices live when a memory-only scope cannot persist them', () => { + it('keeps an explicit choice live while the Host write is pending or refused', () => { const host = stubConfigForm() - host.publish({ mode: 'memory', status: 'ready' }) + host.publish({ status: 'ready' }) const policy = new PerformanceUsagePolicy(host.scope) expect(policy.mode.getSnapshot()).toBe('detailed') policy.setMode('compact') diff --git a/packages/client/ui-chat/tests/reasoning-component-fixture.tsx b/packages/client/ui-chat/tests/reasoning-component-fixture.tsx index fb2f6ea879..c2e0543f3c 100644 --- a/packages/client/ui-chat/tests/reasoning-component-fixture.tsx +++ b/packages/client/ui-chat/tests/reasoning-component-fixture.tsx @@ -10,15 +10,21 @@ import { zh } from '../src/client/locale.ts' const t = makeTranslate(zh, commonZh) +/** Reject attachment loads in component fixtures without durable images. */ +export const unusedImageLoader: AssistantMarkdownProps['loadImage'] = async () => { + throw new Error('This component fixture has no durable image attachments') +} + function content(input: ReasoningContentInput) { // The component only reads these inputs; unused framework seats are exercised in assembly tests. return createElement(ReasoningContent, { ...input, t } as ComponentProps) } /** Render the production child component without emulating a registry or its dispatch. */ -export const renderReasoningSlot = ( - (_key: 'conversation.chat.reasoning.body', input: ReasoningContentInput) => content(input) -) as AssistantMarkdownProps['renderSlot'] +export const renderReasoningSlot: AssistantMarkdownProps['renderSlot'] = (key: string, input: object) => { + if (key !== 'conversation.chat.reasoning.body') throw new Error(`Unexpected reasoning Slot: ${key}`) + return content(input as ReasoningContentInput) +} /** Supply the official component at the Factory call seam of a standalone component unit. */ export const renderReasoningFactory: PropsRenderFactories['renderFactorySlot'] = (name, input) => { diff --git a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx index fbd21baf11..29ad9a4e4d 100644 --- a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx +++ b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from 'vitest' -import { renderReasoningSlot as renderSlot } from './reasoning-component-fixture.tsx' +import { renderReasoningSlot as renderSlot, unusedImageLoader } from './reasoning-component-fixture.tsx' import { act, cleanup, fireEvent, render } from '@testing-library/react' import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -19,7 +19,119 @@ afterEach(() => { }) const t = makeTranslate(zh, commonZh) -const renderMessageImages: AssistantMarkdownProps['renderMessageImages'] = () => null + +describe('AssistantMarkdown reasoning blocks', () => { + const props = { + renderSlot, useDisclosure, useGroupAction: useSearchableHidden, + usePresentation: useDetailedPresentation, loadImage: unusedImageLoader, t, + } + + it.each([false, true])('omits blank blocks without trimming body text when streaming=%s', (streaming) => { + const text = '\n **Visible reasoning**\n\nOriginal body \n' + const texts = ['', ' \t\r\n', text, ''] + const blocks = Object.freeze(texts.map(text => Object.freeze({ kind: 'reasoning' as const, text }))) + const calls = vi.fn() + const extension: AssistantMarkdownProps['renderSlot'] = (key, owner, options) => { + calls(key, owner) + return renderSlot(key, owner, options) + } + const view = render() + expect(view.getAllByRole('button')).toHaveLength(1) + expect(view.container.querySelectorAll('[data-variant="think"]')).toHaveLength(1) + fireEvent.click(view.getByRole('button')) + expect(calls).toHaveBeenCalledWith('conversation.chat.reasoning.body', { text, running: false }) + expect(view.getByText('Visible reasoning').tagName).toBe('STRONG') + expect(blocks.map(block => block.text)).toEqual(texts) + }) + + it.each([false, true])('waits for non-whitespace reasoning when streaming=%s', (streaming) => { + const view = render() + expect(view.queryAllByRole('button')).toHaveLength(0) + for (const text of [' ', '\t', '\r\n', ' \t\r\n', '\u00a0']) { + view.rerender() + expect(view.queryAllByRole('button')).toHaveLength(0) + } + view.rerender() + expect(view.getAllByRole('button')).toHaveLength(1) + }) + + it('retains an expanded earlier row when a blank streaming tail receives text', () => { + const first = { kind: 'reasoning' as const, text: 'First thought\n\nEarlier body' } + const blank = { kind: 'reasoning' as const, text: ' \t\r\n' } + const view = render() + const earlierToggle = view.getByRole('button') + const earlierRow = earlierToggle.closest('[data-variant="think"]') + expect(earlierRow?.getAttribute('data-state')).toBe('ok') + expect(view.queryByText('运行中')).toBeNull() + fireEvent.click(earlierToggle) + const earlierBody = view.getByText('Earlier body') + + const tail = { kind: 'reasoning' as const, text: 'An unfinished tail' } + const blocks = [first, blank, tail] + view.rerender() + const toggles = view.getAllByRole('button') + expect(toggles).toHaveLength(2) + expect(toggles[0]).toBe(earlierToggle) + expect(view.getByText('Earlier body')).toBe(earlierBody) + expect(earlierToggle.getAttribute('aria-expanded')).toBe('true') + expect(earlierRow?.getAttribute('data-state')).toBe('ok') + const tailToggle = toggles[1]! + const tailRow = tailToggle.closest('[data-variant="think"]') + expect(tailRow?.getAttribute('data-state')).toBe('running') + expect(view.queryByText(tail.text)).toBeNull() + fireEvent.click(tailToggle) + expect(view.getByText(tail.text)).toBeTruthy() + expect(earlierToggle.getAttribute('aria-expanded')).toBe('true') + + view.rerender() + const settledToggles = view.getAllByRole('button') + expect(settledToggles).toHaveLength(2) + expect(settledToggles[0]).toBe(earlierToggle) + expect(settledToggles[1]).toBe(tailToggle) + expect(view.getByText('Earlier body')).toBe(earlierBody) + expect(tailRow?.getAttribute('data-state')).toBe('ok') + expect(tailToggle.getAttribute('aria-expanded')).toBe('true') + fireEvent.click(tailToggle) + expect(earlierToggle.getAttribute('aria-expanded')).toBe('true') + expect(tailToggle.getAttribute('aria-expanded')).toBe('false') + }) + + it.each(['Partial thought', '', ' \t\r\n'])('retains the stopped marker with blank reasoning around %j', (text) => { + const blocks = ['', text, ' \t\r\n'].map(text => ({ kind: 'reasoning' as const, text })) + const view = render() + expect(view.queryAllByRole('button')).toHaveLength(text.trim() === '' ? 0 : 1) + expect(view.getByText(t('message.stopped'))).toBeTruthy() + expect(view.queryByText('运行中')).toBeNull() + }) + + it('keeps non-blank rows and their expanded bodies across modes, excluding them from the response part', () => { + const mode = createSnapshotStore('compact') + const usePresentation = bindSnapshotSelector(derivePresentationPolicy(mode, createSnapshotStore('completion'))) + const blocks: AssistantMarkdownProps['blocks'] = [ + { kind: 'reasoning', text: '' }, + { kind: 'reasoning', text: 'Mode thought\n\nMode body' }, + { kind: 'reasoning', text: ' \t\r\n' }, + { kind: 'text', text: 'Answer' }, + ] + const view = render() + const toggle = view.getByRole('button') + fireEvent.click(toggle) + const body = view.getByText('Mode body') + for (const next of ['standard', 'detailed', 'verbose', 'compact'] as const) { + act(() => { mode.set(next) }) + expect(view.getAllByRole('button')).toHaveLength(1) + expect(view.getByRole('button')).toBe(toggle) + expect(toggle.getAttribute('aria-expanded')).toBe('true') + expect(view.getByText('Mode body')).toBe(body) + expect(view.queryByText('Answer')).toBeNull() + } + view.rerender() + expect(view.queryAllByRole('button')).toHaveLength(0) + expect(view.getByText('Answer')).toBeTruthy() + }) +}) describe('ReasoningRow', () => { it('offers only text and streaming state to the standard Body Slot after expansion', () => { @@ -111,20 +223,20 @@ describe('ReasoningRow', () => { const view = render( , + t={t} blocks={[reasoning]} streaming loadImage={unusedImageLoader} />, ) expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('false') fireEvent.click(view.getByText('思考')) view.rerender( , + t={t} blocks={[reasoning, nextBlock]} streaming loadImage={unusedImageLoader} />, ) expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true') view.rerender( , + t={t} blocks={[reasoning, nextBlock]} streaming={false} loadImage={unusedImageLoader} />, ) expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true') expect(view.getByText(/Check persistence/)).toBeTruthy() @@ -139,7 +251,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text: 'Inspect the session\nDetails\n\nNewest reasoning tokens\n' }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.getByText('运行中')).toBeTruthy() @@ -153,7 +265,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text: 'Inspect the session\nDetails\n\nNewest reasoning tokens\nMore details\n\nChecking boundaries' }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.getByText('Newest reasoning tokens').closest('[data-streaming]') @@ -167,7 +279,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.getByText('Checking boundaries')).toBeTruthy() @@ -179,7 +291,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text }]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) const settledSummary = view.getByText('Inspect the session') @@ -195,7 +307,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text: 'Inspect the session\nCheck persistence' }]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) const row = view.getByRole('button') @@ -226,7 +338,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text }]} streaming={streaming} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) @@ -247,7 +359,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text }]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) const summary = view.getByText('# Section 1') @@ -273,7 +385,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text: first }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) fireEvent.click(view.getByText('思考')) @@ -286,7 +398,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.getByRole('heading', { name: 'Investigation' })).toBe(heading) @@ -301,7 +413,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text: 'Inspect the session\nCheck persistence' }]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) fireEvent.click(view.getByText('思考')) @@ -321,7 +433,7 @@ describe('ReasoningRow', () => { { kind: 'text', text: 'Answer' }, ]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) // Collapsed: no `data-open`, so the sticky rule's gate never matches. diff --git a/packages/client/ui-chat/tests/transcript-view-policy.client.spec.ts b/packages/client/ui-chat/tests/transcript-view-policy.client.spec.ts index e7c84f9a42..05fc6401ed 100644 --- a/packages/client/ui-chat/tests/transcript-view-policy.client.spec.ts +++ b/packages/client/ui-chat/tests/transcript-view-policy.client.spec.ts @@ -7,7 +7,7 @@ import { TranscriptViewPolicy } from '../src/client/transcript-view.ts' afterEach(() => { vi.restoreAllMocks() }) describe('TranscriptViewPolicy', () => { - it('defaults to completion and changes timing without reading or writing browser storage', () => { + it('defaults to completion and persists explicit timing without reading or writing browser storage', () => { const storageReads = vi.spyOn(Storage.prototype, 'getItem').mockReturnValue('"next-input"') const storageWrites = vi.spyOn(Storage.prototype, 'setItem') const storageRemovals = vi.spyOn(Storage.prototype, 'removeItem') @@ -32,7 +32,9 @@ describe('TranscriptViewPolicy', () => { expect(timingChanged).toHaveBeenCalledTimes(2) expect(policy.mode.getSnapshot()).toBe('detailed') expect(modeChanged).not.toHaveBeenCalled() - expect(host.set).not.toHaveBeenCalled() + expect(host.set).toHaveBeenCalledTimes(2) + expect(host.set).toHaveBeenNthCalledWith(1, 'collapseTiming', 'next-input') + expect(host.set).toHaveBeenNthCalledWith(2, 'collapseTiming', 'completion') expect(storageReads).not.toHaveBeenCalled() expect(storageWrites).not.toHaveBeenCalled() expect(storageRemovals).not.toHaveBeenCalled() @@ -44,18 +46,19 @@ describe('TranscriptViewPolicy', () => { } }) - it('starts each instance with completion timing while adopting the accepted Host mode', () => { + it('restores both saved preferences in each new instance', () => { const host = stubConfigForm() host.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed' }, revision: 1, writable: true }) const first = new TranscriptViewPolicy(host.scope) try { first.setCollapseTiming('next-input') + host.publish({ value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed', collapseTiming: 'next-input' }, revision: 2 }) const second = new TranscriptViewPolicy(host.scope) try { expect(first.collapseTiming.getSnapshot()).toBe('next-input') - expect(second.collapseTiming.getSnapshot()).toBe('completion') + expect(second.collapseTiming.getSnapshot()).toBe('next-input') expect(second.mode.getSnapshot()).toBe('standard') - expect(host.set).not.toHaveBeenCalled() + expect(host.set).toHaveBeenCalledExactlyOnceWith('collapseTiming', 'next-input') } finally { second.dispose() } @@ -65,21 +68,21 @@ describe('TranscriptViewPolicy', () => { expect(host.listenerCount()).toBe(0) }) - it('adopts Host mode updates without overriding the local timing choice', () => { + it('adopts independent Host mode and timing updates without writing them back', () => { const host = stubConfigForm() const policy = new TranscriptViewPolicy(host.scope) try { policy.setCollapseTiming('next-input') - host.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'compact', performanceUsage: 'detailed' }, revision: 1, writable: true }) + host.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'compact', performanceUsage: 'detailed', collapseTiming: 'next-input' }, revision: 1, writable: true }) expect(policy.mode.getSnapshot()).toBe('compact') expect(policy.collapseTiming.getSnapshot()).toBe('next-input') policy.setMode('verbose') expect(policy.collapseTiming.getSnapshot()).toBe('next-input') - expect(host.set).toHaveBeenCalledExactlyOnceWith('transcriptView', 'verbose') + expect(host.set).toHaveBeenNthCalledWith(2, 'transcriptView', 'verbose') host.publish({ value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed' }, revision: 2 }) expect(policy.mode.getSnapshot()).toBe('standard') - expect(policy.collapseTiming.getSnapshot()).toBe('next-input') - expect(host.set).toHaveBeenCalledTimes(1) + expect(policy.collapseTiming.getSnapshot()).toBe('completion') + expect(host.set).toHaveBeenCalledTimes(2) } finally { policy.dispose() } diff --git a/packages/client/ui-chat/tests/user-content-component-fixture.tsx b/packages/client/ui-chat/tests/user-content-component-fixture.tsx new file mode 100644 index 0000000000..eb6670fb33 --- /dev/null +++ b/packages/client/ui-chat/tests/user-content-component-fixture.tsx @@ -0,0 +1,27 @@ +/** Production user content for component units; registry integration uses SlotTestRuntime. */ +import { createElement, type ComponentProps } from 'react' +import type { PropsLocale, PropsRenderFactories, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import type { UserTextInput } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { createUserTextFixture } from '../../ui-conversation/tests/user-text-component-fixture.client.tsx' +import type { UserContentInput } from '../src/client/contract/slots.ts' +import { UserContent } from '../src/client/chat/UserContent.tsx' + +/** + * Bind real text parsing and business renderers for one component-test lifetime. + * @param actions - reference operations supplied by the test's node-injection fixture. + * @returns renderer accepting prepared content, the user-image Slot seat, and Chat locale. + */ +export function createUserContentFixture(actions?: Parameters[0]) { + const renderUserText = createUserTextFixture(actions) + return ( + input: UserContentInput, + renderSlot: PropsRenderSlots<'conversation.chat.user.images'>['renderSlot'], + t: PropsLocale<'chat'>['t'], + ) => { + const renderFactory: PropsRenderFactories['renderFactorySlot'] = (name, owner) => { + if (name !== 'conversation.user.text') throw new Error(`Unexpected user content Factory: ${name}`) + return renderUserText(owner as UserTextInput) + } + return createElement(UserContent, { ...input, renderSlot, renderFactorySlot: renderFactory, t } as ComponentProps) + } +} diff --git a/packages/client/ui-chat/tests/user-content.client.spec.tsx b/packages/client/ui-chat/tests/user-content.client.spec.tsx new file mode 100644 index 0000000000..1a93864a41 --- /dev/null +++ b/packages/client/ui-chat/tests/user-content.client.spec.tsx @@ -0,0 +1,279 @@ +// @vitest-environment jsdom +import { useState, type ReactNode } from 'react' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { act, cleanup, fireEvent, type RenderResult, within } from '@testing-library/react' +import { AttachmentId, type FileAttachmentRef, type ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts' +import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' +import type { PropsRenderFactories, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { UserContentAttachment, UserContentData, UserContentInput } from '../src/client/contract/slots.ts' +import { UserContent } from '../src/client/chat/UserContent.tsx' +import { en, NS, zh } from '../src/client/locale.ts' +import type { UserTextInjected } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { UserTextRegistry } from '../../ui-conversation/src/client/conversation/user-text-registry.ts' +import { UserText, PlainUserText, SessionReference } from '../../ui-conversation/src/client/user-text/UserText.tsx' +import { sessionReferenceRule } from '../../ui-conversation/src/client/user-text/session-reference-rule.ts' +import { collapseWhitespaceRule, trimWhitespaceRule } from '../../ui-conversation/src/client/user-text/whitespace-rules.ts' +import { fileReferenceRule, folderReferenceRule } from '../../ui-reference/src/client/user-text-rules.ts' +import { FileReference, FolderReference } from '../../ui-reference/src/client/FileReference.tsx' +import { en as referenceEn, zh as referenceZh } from '../../ui-reference/src/client/locales.ts' +import { skillReferenceRule } from '../../ui-skill/src/client/user-text-rules.ts' +import { SkillReference } from '../../ui-skill/src/client/SkillReference.tsx' + +afterEach(cleanup) + +const image: ImageAttachmentRef = { + attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), + mediaType: 'image/png', bytes: 68, width: 640, height: 320, name: 'history.png', +} +const file: FileAttachmentRef = { + attachmentId: AttachmentId(`sha256:${'b'.repeat(64)}`), name: 'notes.txt', bytes: 23, +} +const durable: UserContentAttachment = { type: 'image', image: { attachment: image } } +const preview: UserContentAttachment = { + type: 'image', image: { preview: { url: 'blob:local-preview', name: 'preview.png', width: 4, height: 3 } }, +} +const filePart: UserContentAttachment = { type: 'file', file } +const empty: UserContentData = { text: '', attachments: [], extraBlocks: [] } +type RenderSeats = PropsRenderSlots<'conversation.approval.detail'> & PropsRenderFactories + +async function bench() { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + const locale = new LocaleRuntime(runtime.ctx) + runtime.ctx.provide('locale', locale) + locale.register('common', { en: commonEn, zh: commonZh }) + locale.register(NS, { en, zh }) + locale.register('reference', { en: referenceEn, zh: referenceZh }) + locale.setLocale('en') + runtime.slots.installLocale(locale) + const imageCalls: PropsRuntime<'conversation.chat.user.images'>[] = [] + const openFile = vi.fn<(path: string) => void>() + const openSkill = vi.fn<(name: string) => void>() + await runtime.mount({ inject: ['slots'], apply: (ctx) => { + const userText = new UserTextRegistry(ctx) + for (const rule of [ + sessionReferenceRule, fileReferenceRule, folderReferenceRule, skillReferenceRule, + collapseWhitespaceRule, trimWhitespaceRule, + ]) { + userText.register(rule) + } + ctx.slots.registerFactory({ + name: 'conversation.user.text', scope: 'session', + children: { 'conversation.user.text.node': { kind: 'keyed', scope: 'session', inline: true } }, + inject: (): UserTextInjected => ({ + hooks: { userTextRevision: { + getSnapshot: () => userText.getSnapshot(), subscribe: listener => userText.subscribe(listener), + } }, + createUserTextEvaluator: () => userText.createEvaluator(), + reportTransformFailure: (error: unknown): never => { throw error }, + }), + }, UserText) + ctx.slots.register({ name: 'conversation.user.text.node', key: 'text' }, PlainUserText) + ctx.slots.register({ name: 'conversation.user.text.node', key: 'session' }, SessionReference) + ctx.slots.register({ name: 'conversation.user.text.node', key: 'file', locale: 'reference', + inject: () => ({ openFile }) }, FileReference) + ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder' }, FolderReference) + ctx.slots.register({ name: 'conversation.user.text.node', key: 'skill', inject: () => ({ openSkill }) }, SkillReference) + ctx.slots.inject('conversation.chat.user.images', () => ctx.slots.register({ name: 'conversation.chat.user.images' }, function ImageProbe(props) { + imageCalls.push(props) + const source = props.images[0] + if (source === undefined) throw new Error('User content must pass one image to the image Slot') + const name = 'attachment' in source ? source.attachment.name : source.preview.name + return snapshot.sessionId)}>{name} + })) + } }) + const mountContent = () => runtime.mount({ inject: ['slots'], apply: (ctx) => { + ctx.slots.registerFactory({ + name: 'conversation.chat.user.content', scope: 'session', locale: NS, + children: { 'conversation.chat.user.images': { kind: 'single', scope: 'session' } }, + }, UserContent) + } }) + const owner = await mountContent() + await runtime.sessions.add({ id: 'user-content' }) + const session = runtime.sessions.retainFor(runtime.ctx, SessionId('user-content')) + const captured: { seats?: RenderSeats; setContent?: (content: ReactNode) => void } = {} + await runtime.root.declare({ + 'conversation.approval.detail': { kind: 'single', scope: 'session' }, + }, function TestRoot(props) { + const [content, setContent] = useState(null) + captured.seats = props + captured.setContent = setContent + return content + }) + const view = runtime.renderRoot() + const { seats, setContent } = captured + if (seats === undefined || setContent === undefined) throw new Error('User content fixture root did not render') + const { SessionProvider } = seats + const factory = (input: UserContentInput) => seats.renderFactorySlot('conversation.chat.user.content', input) + const render = (content: ReactNode, scoped = true): RenderResult => { + const update = (next: ReactNode): void => { + act(() => { setContent(scoped ? {next} : next) }) + } + update(content) + return { ...view, rerender: update } + } + const loadImage = vi.fn(async () => 'blob:loaded') + return { runtime, locale, owner, mountContent, factory, render, loadImage, imageCalls, SessionProvider, openFile, openSkill } +} + +describe('user Content Factory', () => { + it('renders prepared text directly without a row, admission markers, time, or copy controls', async () => { + const b = await bench() + const text = '**literal user text**\nsecond line' + const view = b.render(b.factory({ content: { ...empty, text }, facts: {}, loadImage: b.loadImage })) + const textNode = view.getByText('**literal user text** second line') + expect(textNode.textContent).toBe(text) + const root = view.container.querySelector('[data-slot="root"]') + expect(textNode.closest('div')?.parentElement).toBe(root?.firstElementChild) + expect(root?.children).toHaveLength(1) + expect(view.container.querySelector('strong, time, [role="status"], [data-pending-steering], [data-submission-echo]')).toBeNull() + expect(view.queryAllByRole('button')).toHaveLength(0) + expect(view.container.querySelector('[data-message-attachments]')).toBeNull() + expect(b.runtime.factoryOf('conversation.chat.user.content')).toMatchObject({ + component: UserContent, scope: 'session', locale: 'chat', + }) + }) + + it('keeps mixed files, durable images, and local previews in their prepared order through its user-image Slot', async () => { + const b = await bench() + const content: UserContentData = { + ...empty, text: 'Prepared text', attachments: [filePart, durable, { type: 'file', file: { ...file, name: 'last.md' } }, preview], + } + const view = b.render(b.factory({ content, facts: {}, loadImage: b.loadImage })) + const attachments = view.container.querySelector('[data-message-attachments]') + expect([...attachments?.children ?? []].map(child => child.textContent)).toEqual([ + 'notes.txtTXT 23B', 'history.png', 'last.mdMD 23B', 'preview.png', + ]) + expect(view.getByTitle('notes.txt')).toBeTruthy() + expect(view.getByText('Prepared text')).toBeTruthy() + const durableCall = b.imageCalls.find(call => call.images[0] === durable.image) + const previewCall = b.imageCalls.find(call => call.images[0] === preview.image) + expect(durableCall?.images).toEqual([durable.image]) + expect(previewCall?.images).toEqual([preview.image]) + for (const call of [durableCall, previewCall]) { + expect(call).toMatchObject({ align: 'end', compact: true, loadImage: b.loadImage }) + } + expect(b.loadImage).not.toHaveBeenCalled() + }) + + it.each([ + { label: 'one durable image', attachments: [durable], compact: false }, + { label: 'one preview', attachments: [preview], compact: false }, + { label: 'one file and one image', attachments: [filePart, durable], compact: true }, + { label: 'one preview and one file', attachments: [preview, filePart], compact: true }, + ])('uses all attachments to choose compact images: $label', async ({ attachments, compact }) => { + const b = await bench() + const view = b.render(b.factory({ content: { ...empty, attachments }, facts: {}, loadImage: b.loadImage })) + expect(view.getAllByTestId('image')).toHaveLength(1) + expect(b.imageCalls[0]).toMatchObject({ compact, align: 'end', loadImage: b.loadImage }) + expect(view.queryAllByRole('button')).toHaveLength(0) + expect(view.container.querySelector('[data-slot="root"]')?.firstElementChild?.children).toHaveLength(1) + }) + + it('reuses one prepared value in unrelated parents while nested images inherit each Session', async () => { + const b = await bench() + await b.runtime.sessions.add({ id: 'other-user-content' }) + const other = b.runtime.sessions.retainFor(b.runtime.ctx, SessionId('other-user-content')) + const content: UserContentData = Object.freeze({ + text: 'Already prepared', attachments: Object.freeze([preview]), extraBlocks: Object.freeze([]), + }) + const input: UserContentInput = { content, facts: {}, loadImage: b.loadImage } + const { SessionProvider } = b + const view = b.render(<> +
{b.factory(input)}
+ + ) + for (const [parent, sessionId] of [['first', 'user-content'], ['second', 'other-user-content']] as const) { + const section = within(view.getByTestId(parent)) + expect(section.getByText('Already prepared')).toBeTruthy() + expect(section.getByTestId('image').getAttribute('data-session')).toBe(sessionId) + expect(section.getByTestId('image').getAttribute('data-current-session')).toBe(sessionId) + } + expect(b.imageCalls.every(call => call.images[0] === preview.image)).toBe(true) + }) + + it('binds live Chat locale labels for reference summaries and opaque extra blocks', async () => { + const b = await bench() + const block = { type: 'future-block', value: 'x'.repeat(20_001) } + const content: UserContentData = { ...empty, extraBlocks: [block], referenceLabels: ['Alpha', 'Beta'] } + const view = b.render(b.factory({ content, facts: {}, loadImage: b.loadImage })) + expect(view.getByText('Referenced session · Alpha, Beta')).toBeTruthy() + fireEvent.click(view.getByRole('button', { name: '▸ Extra content block' })) + expect(view.container.querySelector('pre')?.textContent).toContain('"type": "future-block"') + expect(view.container.querySelector('pre')?.textContent).toContain( + `… truncated, ${JSON.stringify(block, null, 2).length} characters total`, + ) + act(() => { b.locale.setLocale('zh') }) + expect(view.getByText('引用会话 · Alpha、Beta')).toBeTruthy() + expect(view.getByRole('button', { name: '▾ 附加内容块' })).toBeTruthy() + expect(view.container.querySelector('pre')?.textContent).toContain( + `… 已截断,共 ${JSON.stringify(block, null, 2).length} 字符`, + ) + }) + + it('opens file and skill references through their own injectors only in interactive content', async () => { + const b = await bench() + const labels = ['Alpha'] + const content: UserContentData = { + ...empty, text: 'Read @"src/my file.ts" with /review and @Alpha', referenceLabels: labels, + } + const facts = { sessionLabels: labels, skillNames: ['review'] } + const view = b.render(b.factory({ content, facts, loadImage: b.loadImage, interactive: true })) + fireEvent.click(view.getByRole('button', { name: 'my file.ts' })) + fireEvent.click(view.getByRole('button', { name: '/review' })) + expect(b.openFile).toHaveBeenCalledWith('src/my file.ts') + expect(b.openSkill).toHaveBeenCalledWith('review') + expect(view.queryByRole('button', { name: 'Alpha' })).toBeNull() + view.rerender(b.factory({ content, facts, loadImage: b.loadImage })) + expect(view.queryAllByRole('button')).toHaveLength(0) + for (const label of ['my file.ts', '/review', 'Alpha']) fireEvent.click(view.getByText(label, { exact: true })) + expect(b.openFile).toHaveBeenCalledTimes(1) + expect(b.openSkill).toHaveBeenCalledTimes(1) + expect(view.container.querySelectorAll('[data-ref-chip]')).toHaveLength(3) + }) + + it('keeps an empty prepared value empty', async () => { + const b = await bench() + const view = b.render(b.factory({ content: empty, facts: {}, loadImage: b.loadImage })) + expect(view.container.textContent).toBe('') + const root = view.container.querySelector('[data-slot="root"]') + expect(root?.children).toHaveLength(1) + expect(root?.firstElementChild?.children).toHaveLength(0) + expect(view.container.querySelector('[data-message-attachments]')).toBeNull() + expect(view.queryAllByRole('button')).toHaveLength(0) + expect(b.imageCalls).toHaveLength(0) + }) + + it('removes live content on owner disposal and renders it again after registration', async () => { + const b = await bench() + const view = b.render(b.factory({ content: { ...empty, text: 'Reusable content' }, facts: {}, loadImage: b.loadImage })) + expect(view.getByText('Reusable content')).toBeTruthy() + await b.owner.dispose() + expect(view.queryByText('Reusable content')).toBeNull() + expect(() => b.runtime.factoryOf('conversation.chat.user.content')).toThrow('no definition') + await b.mountContent() + expect(view.getByText('Reusable content')).toBeTruthy() + }) + + it('requires a Session binding even when the prepared value has no images', async () => { + const b = await bench() + const message = "strict session factory 'conversation.chat.user.content' rendered without a scope binding" + const suppressExpectedError = (event: ErrorEvent): void => { + if (event.error instanceof Error && event.error.message === message) event.preventDefault() + } + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + window.addEventListener('error', suppressExpectedError) + try { + expect(() => b.render(b.factory({ content: { ...empty, text: 'Unbound content' }, facts: {}, loadImage: b.loadImage }), false)) + .toThrow(message) + } finally { + window.removeEventListener('error', suppressExpectedError) + error.mockRestore() + } + }) +}) diff --git a/packages/client/ui-chat/tests/views-type-chain.client.spec.tsx b/packages/client/ui-chat/tests/views-type-chain.client.spec.tsx index 5fe31820f6..44ac8f2362 100644 --- a/packages/client/ui-chat/tests/views-type-chain.client.spec.tsx +++ b/packages/client/ui-chat/tests/views-type-chain.client.spec.tsx @@ -17,8 +17,8 @@ describe('Chat View type chain', () => { void chat.openFile({ turnSeq: 1, callId: 'c' }) // @ts-expect-error ChatView renders only its flow child. chat.renderSlot('conversation.chat.node', {}, { hookContext: nodeContext }) - // @ts-expect-error Image rendering belongs to the flow. - chat.renderSlot('conversation.message.images', {}) + // @ts-expect-error Output images belong to the Assistant node entry. + chat.renderSlot('conversation.chat.message.images', {}) // @ts-expect-error Flow owner data cannot override the flow's render authority. void flowOwner.renderSlot // @ts-expect-error Node renderers receive the bound hook, not the viewport controller. diff --git a/packages/client/ui-commands/README.i18n.yaml b/packages/client/ui-commands/README.i18n.yaml index 6177afb95c..97fd762cc1 100644 --- a/packages/client/ui-commands/README.i18n.yaml +++ b/packages/client/ui-commands/README.i18n.yaml @@ -27,8 +27,8 @@ en: 4feecdbec0c3f39e zh: 618944ecade8a3a2 /deepseek-ai-dsh-client-ui-commands/understand-the-implementation: - en: 3aeeba6c91c3ef19 - zh: d3afb3df6d15e17b + en: dbd2d83fb5e57ff3 + zh: 6e2e837f6a08f2fb /deepseek-ai-dsh-client-ui-commands/further-exploration: en: 409c04f534d23de7 zh: 165022d7a0a554eb diff --git a/packages/client/ui-commands/README.md b/packages/client/ui-commands/README.md index 8bf2cdc958..a3f56ab147 100644 --- a/packages/client/ui-commands/README.md +++ b/packages/client/ui-commands/README.md @@ -59,6 +59,8 @@ Popup selection panels fill the composer overlay's width, matching the slash men Each command-directory fetch requires an existing retained Client Session and waits for its initial history open to succeed before sending `commands.list`. A temporary `commandCatalog` reference holds that Session until the fetch settles. An unretained Session or a failed open rejects without sending the RPC, so background catalog refreshes do not reopen closed Sessions. +Popup selection uses the [standard menu inset and item radii](../../../docs/ui-radius.md#nested-hover). + ----- diff --git a/packages/client/ui-commands/README.zh.md b/packages/client/ui-commands/README.zh.md index 792611b54e..8c36427041 100644 --- a/packages/client/ui-commands/README.zh.md +++ b/packages/client/ui-commands/README.zh.md @@ -59,6 +59,8 @@ composer 携带图片或通用文件提交时,只有声明了 `input.attachmen 每次命令目录拉取都要求客户端已持有该会话,并等待首次历史打开成功后才发送 `commands.list`。临时的 `commandCatalog` 引用持续持有会话,直到拉取结束。未被持有的会话或打开失败会直接拒绝,不发送 RPC,因此后台目录刷新不会重新打开已关闭的会话。 +弹出选择面板使用[标准菜单的内缩与菜单项圆角](../../../docs/ui-radius.zh.md#nested-hover)。 + ----- diff --git a/packages/client/ui-commands/locale/en.json b/packages/client/ui-commands/locale/en.json new file mode 100644 index 0000000000..e7d16ed4e8 --- /dev/null +++ b/packages/client/ui-commands/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-commands" + } +} diff --git a/packages/client/ui-commands/locale/zh.json b/packages/client/ui-commands/locale/zh.json new file mode 100644 index 0000000000..ea7b9303f5 --- /dev/null +++ b/packages/client/ui-commands/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "命令选择界面", + "description": "在输入框中提供斜杠命令菜单和相关操作界面。" + } +} diff --git a/packages/client/ui-commands/package.json b/packages/client/ui-commands/package.json index ecedb1d9f8..c78a7e0495 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": { @@ -66,6 +67,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-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index a22be7582c..720a609bd5 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -12,14 +12,17 @@ en: bac0bf0d7330f3b1 zh: 84a895f4b26d8490 /deepseek-ai-dsh-client-ui-conversation/table-of-contents: - en: 9c1c4905952fea5e - zh: d1506dd6fc1018d1 + en: eef4f18c3972ccc4 + zh: 6be65c6ac84ce497 /deepseek-ai-dsh-client-ui-conversation/conversation-assembly: - en: 1d2a3a7f98c2cc9b - zh: f895dd5e9f91e0a9 + en: 6aefa09bb22fdf81 + zh: 0641c4196437cf53 +/deepseek-ai-dsh-client-ui-conversation/sent-user-text: + en: 9912b286384c41d7 + zh: 3e994887c1948677 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 50b5e00a5fb7c2e5 - zh: 91333db3947f395d + en: ddabf2f192114e62 + zh: 31370ed6d5149409 /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: bb1244310f5c0382 zh: 824b84077432b559 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index ec4221995f..76e507caa8 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -16,6 +16,7 @@ Desktop product events use the optional [product analytics service](../product-a ## Table of Contents - [Conversation assembly](#conversation-assembly) +- [Sent user text](#sent-user-text) - [Shell and standard props](#shell-and-standard-props) - [Temporary composer entries](#temporary-composer-entries) - [Model Experience](#model-experience) @@ -49,13 +50,24 @@ Group registration rejects a missing View target. Removing an already registered Target packages declaration-merge their snapshot and Location data maps, then register with `ctx.uiConversation.events.register(...)` and `ctx.uiConversation.views.register(...)`. A target reads its Session-owned source with `ctx.uiConversation.binding(binding).target(targetId)`. Registrations are Cordis effects and their returned disposers remove the contribution from the same registry. The shared request inspection serves every target: `ctx.uiConversation.inspectSystemPrompt(previous, event)` interprets system messages and positional replacements as immutable loaded-surface state. It selects the last nonempty surviving system node in surface order, retains only surviving replacement positions for chained rewrites, and withholds the prompt after an unindexed older endpoint until prepend replay supplies its order. Target-owned Definitions retain historical cards independently. `ctx.uiConversation.inspectRequestPrompt(previous, header, system)` classifies request changes against that effective prompt; ordinary messages and stream chunks require no system-state work. + +## Sent user text + +`UiConversation.userText` registers synchronous `match(text, from, context)` rules. Each call offers one business or Text candidate; the evaluator selects the earliest start and uses `order` and stable ID only for same-start ties. Each caller owns its query cache. `Context.read(key)` invalidates only readers of changed Facts, while future candidates and no-match results are reused within their recorded search ranges. Inputs and outputs use readonly types without runtime freezing. See the [UserText types](src/client/contract/user-text.ts) and [design decision](../../../.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.md). + +Businesses extend `UserTextDataMap` and `UserTextFacts` on this package's `/client` entry, register a matcher through `ctx.uiConversation.userText`, and contribute their renderer to `conversation.user.text.node`. The session-scoped `conversation.user.text` Factory owns this inline keyed Slot. Whitespace rules also return ordinary Text candidates through the same scheduler; trim wins same-start edge collisions with collapse. Node registrations supply their own actions; `interactive` and CSS `ellipsis` remain React Props. Missing renderers display the original fragment; matching failures retain the complete original text and report the rule error. + +Queue previews enable whitespace collapsing and document-edge trimming, retain emoji, and use CSS ellipsis without truncating the input. Editing and copying retain the original text; native attachments use their separate presentation. + ## Shell and standard props -The shared image slot props keep display choices separate from durable references: `thumbnail` requests a contained attachment-list thumbnail, while `compact` requests a cropped gallery tile. An optional per-image `label` supplies the accessible display name; loading and cache identity still use the original attachment reference. [ui-attachment](../ui-attachment/README.md) owns rendering and the lightbox. +The shared image slot props keep display choices separate from durable references: `thumbnail` requests a contained attachment-list thumbnail, while `compact` requests a cropped gallery tile. An optional per-image `label` supplies the accessible display name; loading and cache identity still use the original attachment reference. `MessageImagesContentInput` adds optional complete `MessageImageLabels` for the root-scoped `conversation.images.content` Factory. Message, tool, and Factory inputs carry the view's authorized `loadImage` callback explicitly; loading and URL caching remain with the resource owner. [ui-attachment](../ui-attachment/README.md) provides this Factory and owns rendering and the lightbox. The composer measures its expanded control groups after size, content, visibility, or font-loading changes. If they cannot share a line, the row sets `--dsh-composer-model-text-display: none` and `--dsh-composer-model-icon-display: block` for the model seat; their defaults are `block` and `none`. Wrapping remains available if even the icon cannot fit. +The context meter follows the [statistics-control radius](../../../docs/ui-radius.md#radius-scale). + The context-occupancy button shows a ring and percentage below the input card, after the Session statistics. Clicking it opens the token breakdown in a panel kept inside the viewport, including when no statistics are shown; the button stays hidden until context usage and capacity are available. With Coding Tools off, the shell hides only Trajectory; other plugin-contributed Views remain available. The View tab bar is hidden when fewer than two Views are available. Turning Coding Tools off while Trajectory is active returns to Chat; stored View preferences and recorded Session data remain intact. Turning it on makes Trajectory available again. View owners receive the available roster so their navigation actions can follow the same visibility. @@ -82,10 +94,12 @@ 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. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index bb0c423a36..0f5afe0458 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -16,6 +16,7 @@ kind: "package-reference" ## 目录 - [Conversation 组装](#conversation-assembly) +- [已发送用户文本](#sent-user-text) - [Shell 与标准 props](#shell-and-standard-props) - [临时 composer entry](#temporary-composer-entries) - [模型体验](#model-experience) @@ -49,13 +50,24 @@ Group 注册时缺少 View 目标会报错。已注册的 View Definition 被移 target package 通过 declaration merge 扩展 snapshot 与 Location data map,再调用 `ctx.uiConversation.events.register(...)` 和 `ctx.uiConversation.views.register(...)`。target 通过 `ctx.uiConversation.binding(binding).target(targetId)` 读取其 Session-owned source。注册属于 Cordis effect,返回的 disposer 从同一个 registry 移除 contribution。共享的请求检查服务于每个 target:`ctx.uiConversation.inspectSystemPrompt(previous, event)` 将系统消息与位置替换解释为不可变的已加载 surface 状态。它按 surface 顺序选择最后一个非空的存活系统节点,为连续重写只保留存活的替换位置;遇到未建立索引的更早端点后,提示词保持不可用,直到向前补页回放提供其顺序。target 自有的 Definition 独立保留历史卡片。`ctx.uiConversation.inspectRequestPrompt(previous, header, system)` 根据该有效提示词分类请求变更;普通消息与流式分片无需处理系统状态。 + +## 已发送用户文本 + +`UiConversation.userText` 注册同步 `match(text, from, context)` 规则。每次调用提供一个业务或 Text 候选;计算器选择起点最早的候选,仅在同起点时使用 `order` 和稳定 ID。每个调用者拥有自己的查询缓存。`Context.read(key)` 只使变化 Facts 的读取者失效,未来候选和无匹配结果在已记录的搜索范围内复用。输入和输出使用 readonly 类型,不在运行时冻结。详见 [UserText 类型](src/client/contract/user-text.ts)与[设计决策](../../../.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.zh.md)。 + +业务扩展本包 `/client` 入口的 `UserTextDataMap` 和 `UserTextFacts`,通过 `ctx.uiConversation.userText` 注册匹配器,并向 `conversation.user.text.node` 贡献 renderer。Session 作用域的 `conversation.user.text` Factory 拥有这个行内 keyed Slot。空白规则也通过同一调度器返回普通 Text 候选,trim 在同起点的边缘空白冲突中胜过 collapse。节点注册自行提供动作,`interactive` 和 CSS `ellipsis` 仍为 React Props。缺少 renderer 时显示原文片段,匹配失败时保留完整原文并报告规则错误。 + +Queue 预览启用空白折叠和文档边缘 trim,保留 emoji,并使用 CSS 省略而不截断输入。编辑和复制保留原文;原生附件使用独立的展示路径。 + ## Shell 与标准 props -共享图片插槽属性将展示选择与持久化引用分开:`thumbnail` 请求完整缩放的附件列表缩略图,`compact` 请求裁剪的图片方块。每张图片可通过可选的 `label` 提供无障碍展示名称;加载和缓存标识仍使用原始附件引用。[ui-attachment](../ui-attachment/README.zh.md) 负责渲染与灯箱。 +共享图片插槽属性将展示选择与持久化引用分开:`thumbnail` 请求完整缩放的附件列表缩略图,`compact` 请求裁剪的图片方块。每张图片可通过可选的 `label` 提供无障碍展示名称;加载和缓存标识仍使用原始附件引用。`MessageImagesContentInput` 为 root 作用域的 `conversation.images.content` Factory 增加可选的完整 `MessageImageLabels`。消息、工具及 Factory 输入显式携带视图提供的授权 `loadImage` 回调;读取和 URL 缓存仍由资源所有者负责。[ui-attachment](../ui-attachment/README.zh.md) 提供该 Factory,负责渲染与灯箱。 控件组的尺寸、内容、可见性或字体加载状态变化后,composer 测量展开状态下的控件组。若无法排在同一行,控制栏为模型位设置 `--dsh-composer-model-text-display: none` 和 `--dsh-composer-model-icon-display: block`;两者默认值分别为 `block` 和 `none`。若连图标也放不下,仍允许换行。 +上下文占用率入口遵循[统计控件圆角规则](../../../docs/ui-radius.zh.md#radius-scale)。 + 上下文占用按钮在输入卡片下方、会话统计右侧显示圆环和百分比。点击按钮可在视口内的面板查看 token 构成,没有统计项时面板也不会越界;上下文用量和容量尚不可用时,按钮保持隐藏。 关闭代码工作工具时,外壳仅隐藏 Trajectory;其他插件贡献的 View 仍然可用。可用 View 少于两个时隐藏 View 标签栏。在 Trajectory 激活时关闭代码工作工具会返回 Chat;已保存的 View 偏好和 Session 记录保持不变。开启后,Trajectory 恢复可用。View 所有者接收可用列表,使导航操作跟随相同的可见性。 @@ -82,10 +94,12 @@ 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。 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 af91420381..1576ea9f49 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": { @@ -87,7 +88,7 @@ "@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 +101,7 @@ "@deepseek-ai/dsh-client-product-analytics": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 9994c4e9ae..3e34d83b4b 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -14,10 +14,13 @@ import type {} from '@deepseek-ai/dsh-client-ui-session/client' import type {} from '@deepseek-ai/dsh-client-ui-settings/client' import type { ShortcutCommandId, ShortcutFixedCommand } from '@deepseek-ai/dsh-client-shortcuts/client' import { UiConversation } from './conversation/assembly.ts' +import { UserText, PlainUserText, SessionReference } from './user-text/UserText.tsx' +import { sessionReferenceRule } from './user-text/session-reference-rule.ts' +import { collapseWhitespaceRule, trimWhitespaceRule } from './user-text/whitespace-rules.ts' import type { ViewTab } from './contract/views.ts' import type { ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, - ConversationSessionInjected, DraftFileUploads, + ConversationSessionInjected, DraftFileUploads, UserTextInjected, } from './contract/slots.ts' import type { InputNotice } from './contract/input.ts' import type { ReferenceInsert } from './contract/draft-editor.ts' @@ -156,6 +159,30 @@ export function apply(ctx: Context, config: Config = Config({})): void { const maxConcurrentFileUploads = config.maxConcurrentFileUploads as number const workspaceNavigation = ctx.get('uiWorkspace') as unknown as WorkspaceNavigation const uiConversation = new UiConversation(ctx, sessions) + uiConversation.userText.register(sessionReferenceRule) + uiConversation.userText.register(collapseWhitespaceRule) + uiConversation.userText.register(trimWhitespaceRule) + slots.registerFactory({ + name: 'conversation.user.text', + scope: 'session', + children: { + 'conversation.user.text.node': { kind: 'keyed', scope: 'session', inline: true }, + }, + inject: (): UserTextInjected => ({ + hooks: { + userTextRevision: { + getSnapshot: () => uiConversation.userText.getSnapshot(), + subscribe: listener => uiConversation.userText.subscribe(listener), + }, + }, + createUserTextEvaluator: () => uiConversation.userText.createEvaluator(), + reportTransformFailure: (error) => { console.error('[ui-conversation] user-text transformation failed:', error) }, + }), + }, UserText) + slots.inject('conversation.user.text.node', function* () { + yield slots.register({ name: 'conversation.user.text.node', key: 'text', priority: 100 }, PlainUserText) + yield slots.register({ name: 'conversation.user.text.node', key: 'session', priority: 100 }, SessionReference) + }) ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-conversation: dictionaries') const t = ctx.locale.bind(NS) diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index 5564aea9b6..9abf5afb1c 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -3,6 +3,7 @@ import type { ReactNode, RefObject } from 'react' import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' import type { FileUploadReceiptId } from '@deepseek-ai/dsh-client-file-upload/client' +import type { ImageLightboxLabels } from '@deepseek-ai/dsh-client-ui-primitives' import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { MaybeSnapshotSelectorHook, ObservableSnapshot, SnapshotSelectorHook, @@ -22,6 +23,7 @@ import type { createConversationStore } from '../stores.ts' import type { BusyEnterBehavior } from './composer-submission.ts' import type { ConversationSnapshot } from './snapshot.ts' import type { ViewTab } from './views.ts' +import type { UserTextDocumentInput, UserTextEvaluator, UserTextId, UserTextNode } from './user-text.ts' /** Browser-owned draft attachment that has not crossed the durable Host boundary. */ export type ComposerAttachment = ComposerImageAttachment | ComposerFileAttachment @@ -117,8 +119,53 @@ export interface MessageImagesOwnerProps { thumbnail?: boolean } -/** Slot-backed renderer used by Conversation targets without importing an attachment implementation. */ -export type RenderMessageImages = (owner: Omit) => ReactNode +/** Message-image strings the owner resolves from its own locale namespace. */ +export interface MessageImageLabels { + /** Fallback display name for an unnamed image. */ + image: string + /** Thumbnail tooltip inviting the original-image preview. */ + open: string + /** Accessible thumbnail label; receives the image's display name. */ + openNamed: (label: string) => string + /** Loading placeholder shown until bytes resolve. */ + loading: string + /** Retry-control label shown when the load fails. */ + loadFailed: string + /** Lightbox strings forwarded to the opened preview. */ + lightbox: ImageLightboxLabels +} + +/** Root-scoped image gallery input with explicit reading authority and optional caller copy. */ +export interface MessageImagesContentInput extends MessageImagesOwnerProps { + readonly labels?: MessageImageLabels +} + +/** Transform inputs and independently controlled rendering behavior. */ +export interface UserTextInput extends UserTextDocumentInput { + /** Enable renderer-owned reference actions; omitted values keep references read-only. */ + readonly interactive?: boolean + /** Use CSS single-line overflow ellipsis without shortening source text. */ + readonly ellipsis?: boolean +} + +/** Rule invalidation and document evaluation supplied by the data layer. */ +export interface UserTextInjected { + hooks: { userTextRevision: ObservableSnapshot } + /** Each invocation creates a caller-owned data-layer cache without registry subscriptions. */ + createUserTextEvaluator: () => UserTextEvaluator + /** Report a failed rule while the original text remains visible. */ + reportTransformFailure: (error: unknown) => void +} + +/** JSON-only owner data common to every business text node. */ +export interface UserTextNodeOwnerProps { + readonly raw: string + readonly interactive: boolean +} + +/** Complete props for the selected business node, including its Session scope. */ +export type UserTextNodeProps = + PropsRuntime<'conversation.user.text.node', Id> /** Selector hook over the current Session's assembled Conversation. */ export type UseConversation = SnapshotSelectorHook @@ -126,7 +173,33 @@ export type UseConversation = SnapshotSelectorHook export type UseConversationViews = SnapshotSelectorHook declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotFactoryMap { + /** Parse one original text and render its business nodes through the owned keyed Slot. */ + 'conversation.user.text': { + scope: 'session' + props: UserTextInput + inject: UserTextInjected + children: { + 'conversation.user.text.node': { kind: 'keyed'; scope: 'session'; inline: true } + } + } + /** Official reusable gallery, with explicit authorized loading and optional caller copy. */ + 'conversation.images.content': { + scope: 'root' + props: MessageImagesContentInput + locale: 'conversation' + } + } + interface SlotMap { + /** One business-owned inline renderer for a pure JSON text node. */ + 'conversation.user.text.node': { + kind: 'keyed' + scope: 'session' + inline: true + owner: UserTextNodeOwnerProps + keyProps: { [Id in UserTextId]: { node: UserTextNode } } + } /** Conversation shell beneath its root-scoped main-panel entry. */ 'main.conversation': { kind: 'single'; scope: 'session-maybe' } /** Strict per-Session Conversation body. */ diff --git a/packages/client/ui-conversation/src/client/contract/user-text.ts b/packages/client/ui-conversation/src/client/contract/user-text.ts new file mode 100644 index 0000000000..4b6f68e621 --- /dev/null +++ b/packages/client/ui-conversation/src/client/contract/user-text.ts @@ -0,0 +1,63 @@ +/** Readonly JSON candidates, forward matching, and tracked caller Facts. */ +import type { UserTextDataMap, UserTextFacts } from '../index.ts' + +/** Registered business IDs plus the document-owned `text` ID. */ +export type UserTextId = Extract + +type JsonPayload = T extends string | number | boolean | null ? T + : T extends (...args: never[]) => unknown ? never + : T extends readonly unknown[] ? { readonly [K in keyof T]: JsonPayload } + : T extends object ? { readonly [K in keyof T]: JsonPayload } + : never + +/** Original UTF-16 text and readonly Facts; absence is observable through `context.read`. */ +export interface UserTextDocumentInput { + readonly text: string + readonly facts: Readonly> +} + +/** Discriminated JSON node over a nonempty half-open UTF-16 range in the original text. */ +export type UserTextNode = { + [Id in K]: { + readonly id: Id + readonly start: number + readonly end: number + readonly data: JsonPayload + } +}[K] + +/** Facts reader valid only during its owning synchronous query; never retain it. */ +export interface UserTextTransformContext { + /** + * Record a field dependency, including an absent value; throws after the call returns or throws. + * @param key - field of the caller's readonly Facts snapshot. + * @returns the borrowed readonly value, or undefined when absent. + */ + read(key: K): UserTextFacts[K] | undefined +} + +/** One forward matcher for business references or Text replacements; order only resolves same-start candidates. */ +export interface UserTextRule { + readonly id: Id + /** Finite ascending priority; equal values use stable ID ordering, never plugin load order. */ + readonly order: number + /** + * Find one nearest original-text candidate at or after `from`, resolving own same-start alternatives deterministically. + * Search uses original lexical boundaries, not the beginning of a sliced suffix. Queries are independent of accepted nodes. + * @param text - complete original text; neither this string nor caller Facts may be mutated. + * @param from - inclusive original UTF-16 start offset, advancing within one reconciliation. + * @param context - synchronous Facts reader; all retained queries contribute dependencies. + * @returns one nonempty node using this rule's ID or `text`, or undefined when no later candidate exists. + * Text candidates preserve the exact source substring and may supply `data.display`. + */ + match(this: void, text: string, from: number, context: UserTextTransformContext): (UserTextNode & { readonly id: Id }) | UserTextNode<'text'> | undefined +} + +/** + * Reconcile one document using current rules and independently cached candidate queries. + * Reentrant calls throw. Failures carry ruleId and cause without publishing partial output; + * failed queries retry when their offset, definition, original text, or read Facts change. + * @param input - original text and readonly JSON Facts; fields are compared with Object.is. + * @returns readonly nodes covering the text, or [] for empty text; equivalent results retain identities. + */ +export type UserTextEvaluator = (input: UserTextDocumentInput) => readonly UserTextNode[] diff --git a/packages/client/ui-conversation/src/client/conversation/assembly.ts b/packages/client/ui-conversation/src/client/conversation/assembly.ts index edc182f530..b6cfcd6318 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembly.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembly.ts @@ -24,6 +24,7 @@ import { ConversationEventRegistry } from './event-registry.ts' import { HistoricalImageCache } from './historical-images.ts' import { ConversationViewRegistry } from './view-registry.ts' import { ConversationGroupRegistry } from './group-registry.ts' +import { UserTextRegistry } from './user-text-registry.ts' /** Observable faces published for one Session's Conversation assembly. */ export interface ConversationBinding { @@ -190,6 +191,8 @@ export class UiConversation extends Service { readonly views: ConversationViewRegistry /** Business grouping rules over already materialized target Nodes. */ readonly groups: ConversationGroupRegistry + /** Pure text rules and parser snapshots, independent of durable Session assembly. */ + readonly userText: UserTextRegistry private readonly bindings = new WeakMapWithValues() private readonly images: HistoricalImageCache @@ -202,6 +205,7 @@ export class UiConversation extends Service { this.events = new ConversationEventRegistry(ctx) this.views = new ConversationViewRegistry(ctx) this.groups = new ConversationGroupRegistry(ctx, this.views) + this.userText = new UserTextRegistry(ctx) this.images = new HistoricalImageCache(ctx, sessions) const rebuild = (): void => { for (const record of this.bindings.values) record.binding.rebuild() diff --git a/packages/client/ui-conversation/src/client/conversation/user-text-document.ts b/packages/client/ui-conversation/src/client/conversation/user-text-document.ts new file mode 100644 index 0000000000..e8c6b19b8a --- /dev/null +++ b/packages/client/ui-conversation/src/client/conversation/user-text-document.ts @@ -0,0 +1,244 @@ +/** Per-document candidate reconciliation, query coverage, tracked Facts and JSON identity reuse. */ +import type { UserTextFacts } from '../index.ts' +import type { + UserTextDocumentInput, UserTextNode, UserTextRule, UserTextTransformContext, +} from '../contract/user-text.ts' + +type FactKey = keyof UserTextFacts + +class UserTextTransformError extends Error { + constructor(readonly ruleId: string, cause: unknown) { + super(`user-text rule "${ruleId}" failed to evaluate`, { cause }) + this.name = 'UserTextTransformError' + } +} + +interface Query { + readonly from: number + readonly node: UserTextNode | undefined + readonly error: UserTextTransformError | undefined +} + +interface Matcher { + readonly definition: UserTextRule + readonly reads: Map + queries: readonly Query[] +} + +interface Traversal { + readonly matcher: Matcher + readonly added: Query[] + index: number + head: Query | undefined +} + +/** Data-layer cache owned by one caller; initialization and refresh share one reconciliation. */ +export class UserTextDocument { + private text: string | undefined + private rules: readonly UserTextRule[] | undefined + private initial: readonly UserTextNode[] = [] + private output: readonly UserTextNode[] = [] + private readonly matchers = new Map() + private complete = false + private evaluating = false + + /** + * Reconcile original text using current rule definitions and valid query records. + * @param input - original text and readonly Facts, compared by fields actually read. + * @param rules - unique definitions ordered by ascending order and stable ID. + * @returns complete readonly nodes; failures retain caches but publish no partial result. + */ + evaluate(input: UserTextDocumentInput, rules: readonly UserTextRule[]): readonly UserTextNode[] { + if (this.evaluating) throw new Error('user-text document evaluation cannot be reentrant') + this.evaluating = true + try { + const { changed, matchers } = this.prepare(input, rules) + if (!changed && this.complete) return this.output + this.complete = false + this.output = alignNodes(this.reconcile(input, matchers), this.output, this.initial) + this.complete = true + return this.output + } finally { + this.evaluating = false + } + } + + private prepare(input: UserTextDocumentInput, rules: readonly UserTextRule[]): { changed: boolean; matchers: Matcher[] } { + let changed = this.rules !== rules + if (this.text !== input.text) { + changed = true + this.text = input.text + this.matchers.clear() + this.initial = input.text.length === 0 ? [] : [textNode(input.text, 0, input.text.length)] + this.output = this.initial + } + const ids = new Set(rules.map(rule => rule.id)) + const matchers: Matcher[] = [] + for (const definition of rules) { + let matcher = this.matchers.get(definition.id) + if (matcher === undefined || matcher.definition !== definition || factsChanged(matcher.reads, input)) { + matcher = { definition, queries: [], reads: new Map() } + this.matchers.set(definition.id, matcher) + changed = true + } + matchers.push(matcher) + } + for (const id of this.matchers.keys()) if (!ids.has(id)) this.matchers.delete(id) + this.rules = rules + return { changed, matchers } + } + + private reconcile(input: UserTextDocumentInput, matchers: readonly Matcher[]): readonly UserTextNode[] { + const traversals: Traversal[] = matchers.map(matcher => ({ matcher, added: [], index: -1, head: undefined })) + const nodes: UserTextNode[] = [] + let cursor = 0 + try { + while (true) { + let winner: UserTextNode | undefined + for (const traversal of traversals) { + const node = nextCandidate(traversal, input, cursor) + // Definitions arrive in stable priority order; earlier starts always take precedence. + if (node !== undefined && (winner === undefined || node.start < winner.start)) winner = node + } + if (winner === undefined) { + if (cursor < input.text.length) nodes.push(textNode(input.text, cursor, input.text.length)) + return nodes + } + if (cursor < winner.start) nodes.push(textNode(input.text, cursor, winner.start)) + nodes.push(winner) + cursor = winner.end + } + } finally { + for (const { matcher, added } of traversals) { + if (added.length > 0) matcher.queries = mergeQueries(matcher.queries, added) + } + } + } + +} + +function factsChanged(reads: ReadonlyMap, input: UserTextDocumentInput): boolean { + for (const [key, value] of reads) if (!Object.is(value, input.facts[key])) return true + return false +} + +function withFacts(input: UserTextDocumentInput, reads: Map, run: (context: UserTextTransformContext) => T): T { + let active = true + try { + return run({ + read: (key: K): UserTextFacts[K] | undefined => { + if (!active) throw new Error('user-text transform context is closed; read is synchronous only') + const value = input.facts[key] + reads.set(key, value) + return value + }, + }) + } finally { + active = false + } +} + +function nextCandidate(traversal: Traversal, input: UserTextDocumentInput, cursor: number): UserTextNode | undefined { + const { matcher } = traversal + if (traversal.head === undefined || (traversal.head.node !== undefined && traversal.head.node.start < cursor)) { + let next = matcher.queries[traversal.index + 1] + while (next !== undefined && next.from <= cursor) { + traversal.index++ + next = matcher.queries[traversal.index + 1] + } + const recorded = matcher.queries[traversal.index] + if (recorded !== undefined && (recorded.error !== undefined + ? recorded.from === cursor : recorded.node === undefined || recorded.node.start >= cursor)) { + traversal.head = recorded + } else { + let node: UserTextNode | undefined + let error: UserTextTransformError | undefined + try { + node = withFacts(input, matcher.reads, context => matcher.definition.match(input.text, cursor, context)) + if (node !== undefined) validateCandidate(input.text, matcher.definition.id, cursor, node) + } catch (cause) { + error = new UserTextTransformError(matcher.definition.id, cause) + } + traversal.head = { from: cursor, node, error } + traversal.added.push(traversal.head) + } + } + if (traversal.head.error !== undefined) throw traversal.head.error + return traversal.head.node +} + +function validateCandidate(text: string, ruleId: string, from: number, node: UserTextNode): void { + if (!Number.isInteger(node.start) || !Number.isInteger(node.end) + || node.start < from || node.end <= node.start || node.end > text.length) { + throw new Error(`invalid candidate range [${node.start}, ${node.end}); expected a nonempty range from ${from} to ${text.length}`) + } + if (node.id === 'text') { + if (node.data.text !== text.slice(node.start, node.end)) throw new Error('text candidate must preserve its original substring') + } else if (node.id !== ruleId) { + throw new Error(`candidate must use rule ID "${ruleId}" or text`) + } +} + +function mergeQueries(previous: readonly Query[], added: readonly Query[]): readonly Query[] { + if (previous.length === 0) return added + const merged: Query[] = [] + const remaining = previous.values() + let old = remaining.next().value + // New queries only fill offsets not covered by retained records. + for (const query of added) { + while (old !== undefined && old.from < query.from) { + merged.push(old) + old = remaining.next().value + } + merged.push(query) + } + while (old !== undefined) { + merged.push(old) + old = remaining.next().value + } + return merged +} + +function textNode(text: string, start: number, end: number): UserTextNode<'text'> { + return { id: 'text', start, end, data: { text: text.slice(start, end) } } +} + +function alignNodes( + output: readonly UserTextNode[], previous: readonly UserTextNode[], input: readonly UserTextNode[], +): readonly UserTextNode[] { + let previousIndex = 0 + let inputIndex = 0 + let aligned: UserTextNode[] | undefined + for (const [index, node] of output.entries()) { + let inputNode = input[inputIndex] + while (inputNode && inputNode.start < node.start) inputNode = input[++inputIndex] + let previousNode = previous[previousIndex] + while (previousNode && previousNode.start < node.start) previousNode = previous[++previousIndex] + const reused = inputNode && equalNode(node, inputNode) ? inputNode + : previousNode && equalNode(node, previousNode) ? previousNode : node + if (reused !== node && !aligned) aligned = output.slice(0, index) + aligned?.push(reused) + } + const nodes = aligned ?? output + if (equalElements(nodes, previous)) return previous + return equalElements(nodes, input) ? input : nodes +} + +function equalElements(left: readonly UserTextNode[], right: readonly UserTextNode[]): boolean { + return left === right || (left.length === right.length && left.every((node, index) => node === right[index])) +} + +function equalNode(left: UserTextNode, right: UserTextNode): boolean { + return Object.is(left, right) || (left.id === right.id && left.start === right.start && left.end === right.end + && equalJson(left.data, right.data)) +} + +function equalJson(left: unknown, right: unknown): boolean { + if (Object.is(left, right)) return true + if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') return false + if (Array.isArray(left) !== Array.isArray(right)) return false + const keys = Object.keys(left) + if (keys.length !== Object.keys(right).length) return false + return keys.every(key => Object.hasOwn(right, key) + && equalJson(Reflect.get(left, key), Reflect.get(right, key))) +} diff --git a/packages/client/ui-conversation/src/client/conversation/user-text-registry.ts b/packages/client/ui-conversation/src/client/conversation/user-text-registry.ts new file mode 100644 index 0000000000..3dd1f04c61 --- /dev/null +++ b/packages/client/ui-conversation/src/client/conversation/user-text-registry.ts @@ -0,0 +1,51 @@ +/** Effect-owned user-text rules and their revision; document caches belong only to evaluator callers. */ +import type { UserTextEvaluator, UserTextRule } from '../contract/user-text.ts' +import { ConversationDefinitionRegistry } from './definition-registry.ts' +import { UserTextDocument } from './user-text-document.ts' + +/** Observable rule revision with no retained documents or document subscriptions. */ +export class UserTextRegistry extends ConversationDefinitionRegistry { + private rules: readonly UserTextRule[] = [] + private revision = 0 + + /** + * Register a uniquely named rule; invalid IDs, duplicate IDs and non-finite order throw before publication. + * @param rule - readonly synchronous candidate matcher with a nonempty ID other than the reserved `text` ID. + * @returns idempotent disposer; removal synchronously publishes a new revision. + */ + register(rule: UserTextRule): () => void { + if (rule.id.length === 0) throw new Error('user-text rule ID must not be empty') + if (rule.id === 'text') throw new Error('user-text rule "text" is reserved for original text') + if (!Number.isFinite(rule.order)) throw new Error(`user-text rule "${rule.id}" order must be finite`) + return this.registerDefinition( + rule.id, + rule, + `user-text rule "${rule.id}" is already registered`, + `uiConversation.userText.register(${JSON.stringify(rule.id)})`, + ) + } + + /** + * Create an independent document evaluator; it reads current rules at each call and never subscribes. + * @returns callback owning its document cache, released when the caller releases the callback. + */ + createEvaluator(): UserTextEvaluator { + const document = new UserTextDocument() + return input => document.evaluate(input, this.rules) + } + + /** + * Read the observable rule revision. + * @returns monotonic revision, stable until a successful registration or disposal. + */ + getSnapshot(): number { + return this.revision + } + + protected override refresh(): void { + this.rules = [...this.definitions.values()].sort((a, b) => + a.order - b.order || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) + this.revision++ + super.refresh() + } +} diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 2b9e30d332..229aea31cc 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -1,4 +1,28 @@ -/** Browser Conversation assemble core, React adapter, shell, and input plugin. */ +/** Browser Conversation assemble core, React adapter, shell, input, and text projection plugin. */ +export type {} from './user-text/session-reference-rule.ts' + +/** Declaration-merged node payloads; IDs also identify the corresponding keyed renderer. */ +export interface UserTextDataMap { + text: { + /** Exact original substring; display transforms never change source text or UTF-16 coordinates. */ + readonly text: string + /** Optional display-only text; absence renders the original substring, while an empty string hides it. */ + readonly display?: string + } +} + +/** Caller-supplied JSON business facts and text-transform flags, never services or actions; absent flags are disabled. */ +export interface UserTextFacts { + /** Collapse whitespace runs in ordinary display text to one space. */ + readonly collapseWhitespace: boolean + /** Remove display whitespace only at the document's outer edges, without crossing business nodes. */ + readonly trimWhitespace: boolean +} + +export type { + UserTextDocumentInput, UserTextEvaluator, UserTextId, UserTextNode, UserTextRule, UserTextTransformContext, +} from './contract/user-text.ts' +export type { UserTextRegistry } from './conversation/user-text-registry.ts' export { apply, Config, inject } from './apply.ts' export type { Config as ConversationConfig } from './apply.ts' export { UiConversation } from './conversation/assembly.ts' @@ -67,7 +91,8 @@ export type { ConversationWidthControlsInputProps, ConversationWidthControlsProps, ConversationStore, ConvViewOwnerProps, ConvViewProps, EmptyWorkspaceOwnerProps, HeroAgentPresetOwnerProps, HeroBrandMarkOwnerProps, InputControlOwnerProps, InputZone, - MessageImageLoader, MessageImageSource, MessageImagesOwnerProps, RenderMessageImages, UseConversation, + MessageImageLabels, MessageImageLoader, MessageImageSource, MessageImagesContentInput, MessageImagesOwnerProps, UseConversation, + UserTextInput, UserTextInjected, UserTextNodeOwnerProps, UserTextNodeProps, UseConversationViews, } from './contract/slots.ts' export type { diff --git a/packages/client/ui-conversation/src/client/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/queue-dock.client.spec.tsx b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx index 756199f8b4..be31f70fb4 100644 --- a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx +++ b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx @@ -24,6 +24,8 @@ 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, @@ -434,12 +442,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/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-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 174fcf3f72..be986d9f63 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": { @@ -83,6 +84,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-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 557ca70801..f8802bca27 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": { @@ -60,6 +61,7 @@ "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-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 727c9f22b2..c1d7acd92d 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": { @@ -53,6 +54,7 @@ "react-dom": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-dockkit/package.json b/packages/client/ui-dockkit/package.json index e42a8d828f..30b92e8b1b 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" }, 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 b1cac92875..4408b4ce11 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": { @@ -69,6 +70,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-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 280dbdaaad..2cbaa42e92 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": { @@ -63,6 +64,7 @@ "clsx": "^2.0.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-jobs/README.i18n.yaml b/packages/client/ui-jobs/README.i18n.yaml index 0b6fe4ebae..c037d0003a 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: 4f18681e6209c2d7 + zh: 4472b22583ce8d39 /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..524c9d14b5 100644 --- a/packages/client/ui-jobs/README.md +++ b/packages/client/ui-jobs/README.md @@ -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..a749206857 100644 --- a/packages/client/ui-jobs/README.zh.md +++ b/packages/client/ui-jobs/README.zh.md @@ -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 7cd9351e30..d69c2c231e 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", @@ -51,6 +52,7 @@ "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..f3f2286163 100644 --- a/packages/client/ui-jobs/src/client/JobListAction.module.css +++ b/packages/client/ui-jobs/src/client/JobListAction.module.css @@ -48,7 +48,7 @@ max-width: min(560px, calc(100vw - 32px)); max-height: min(480px, calc(100vh - 140px)); margin: 0; - padding: 3px; + padding: 4px; overflow: auto; list-style: none; border: 0; @@ -155,6 +155,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 +233,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-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 9c04a714ca..3ecf9b5ae2 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": { @@ -59,6 +60,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-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-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 df6cb6895e..35dad7870b 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": { @@ -71,6 +72,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-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index 4d2f30c8c5..5b631ca046 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -15,8 +15,8 @@ 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..ffa4457597 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -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..b1ea95f2d7 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -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 90a4f1dbcb..b932b7de41 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": { @@ -69,6 +70,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-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 e1b15cdf72..3f2544d42f 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" 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 48e196a2eb..3628ee6b9e 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": { @@ -70,6 +71,7 @@ "@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({ diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 7fe8783d6a..cb95776fa6 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -46,6 +46,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 +59,7 @@ export { FileTypeIcon, classifyFileType, fileExtension } from './FileTypeIcon.ts export type { CodeFileType, FileType, FileTypeIconProps, FileTypeKind, FileTypeProjectContext, } from './FileTypeIcon.tsx' -export { projectUserText, type UserTextReferences } from './user-text.tsx' +export { UserTextRun, ReferenceChip, type UserTextRunProps, type ReferenceChipProps } from './user-text.tsx' export { Tooltip } from './Tooltip.tsx' export type { TooltipSide } from './Tooltip.tsx' export { pointerModality } from './input-modality.ts' diff --git a/packages/client/ui-primitives/src/user-text.tsx b/packages/client/ui-primitives/src/user-text.tsx index 01289a4334..20d29f3b84 100644 --- a/packages/client/ui-primitives/src/user-text.tsx +++ b/packages/client/ui-primitives/src/user-text.tsx @@ -1,156 +1,56 @@ -/** - * Display projection of reference forms in sent user text (bubble and queue - * rows). The logged model text remains the single truth; this is presentation - * only. Inline references follow the consumer's wrapping policy and keep long - * labels within its width. Four decoration sources, by precedence: the wire session form - * `@[label](dsh-session:...)` folds to its label; exact session labels - * supplied by an adjacent recall decorate their bare `@label` mention; plain - * `@name` word-boundary tokens decorate by shape alone; and a plain `/name` - * token decorates only when the caller names it — a skill the host actually - * loaded for that message (ui-chat reads the step's `skill-invocation` - * injections) or the command a command-input bubble echoes — so `/123` or a - * stray `/word` stays plain text. A `/name` token is whitespace-bounded like - * the host skill gesture (`dsh-tool-skill`): it ends at whitespace or the - * text end, so slash paths (`/nfs-hg/xxx`, `/plan.md`) and punctuation-glued - * tokens (`/plan。`) stay plain even for a loaded name. - */ +/** Inline text and reference presentation; business rules supply resolved JSON data and actions. */ import type { ReactNode } from 'react' import clsx from 'clsx' -import { ReferenceIconRegular } from './ReferenceIcon.tsx' +import { ReferenceIconRegular, type ReferenceIconKind } from './ReferenceIcon.tsx' import css from './user-text.module.css' import markdownCss from './markdown/MarkdownText.module.css' -/** The wire form a session chip serializes to; label is the display text. */ -const SESSION_WIRE_RE = /@\[([^\]\n]+)\]\(dsh-session:[^)\s]+\)/gu - -/** Sentence punctuation a bare `@name` token may carry without being part of the reference. */ -const TRAILING_PUNCTUATION_RE = /[.,;:!?,。;:!?]+$/u - -interface DecorationRange { - readonly start: number - readonly end: number - /** Matched source text (hover title). */ - readonly label: string - readonly kind: 'session' | 'plain' - /** Pre-resolved display text (wire folds); derived from label when absent. */ - readonly display?: string -} - -/** Optional navigation supplied by consumers that can preview references. */ -export interface UserTextReferences { - /** Open a file path decoded from an `@` mention. */ - openFile: (path: string) => void - /** Open the source of a skill loaded for this message. */ - openSkill: (name: string) => void +/** Plain text follows the wrapping and typography of its host. */ +export interface UserTextRunProps { + readonly text: string } /** - * Split one sent text into inline plain runs and reference chips. - * @param text - the logged model text of the message or queue row. - * @param sessionLabels - exact session mention labels associated by an adjacent recall. - * @param slashNames - names a `/name` token may decorate as: the skills the - * host loaded for this message, or the command a command bubble echoes - * (unsent queue rows pass none). - * @param slashKind - the chip kind those tokens render as. - * @param references - optional file and skill preview actions; session and command tokens stay labels. - * @returns inline nodes covering the whole text. + * Render an uninterpreted inline text run. + * @param props - text retained verbatim from the caller's document. + * @returns one inline run without Markdown or reference recognition. */ -export function projectUserText( - text: string, - sessionLabels: readonly string[], - slashNames: readonly string[] = [], - slashKind: 'skill' | 'command' = 'skill', - references?: UserTextReferences, -): ReactNode { - const ranges: DecorationRange[] = [] - SESSION_WIRE_RE.lastIndex = 0 - let wire: RegExpExecArray | null - while ((wire = SESSION_WIRE_RE.exec(text)) !== null) { - ranges.push({ - start: wire.index, - end: wire.index + wire[0].length, - label: wire[0], - kind: 'session', - display: wire[1] as string, // non-optional capture in SESSION_WIRE_RE - }) - } - for (const rawLabel of [...new Set(sessionLabels)].sort((a, b) => b.length - a.length)) { - const label = `@${rawLabel}` - let start = text.indexOf(label) - while (start >= 0) { - ranges.push({ start, end: start + label.length, label, kind: 'session' }) - start = text.indexOf(label, start + label.length) - } - } - // A `/` token ends at whitespace or the text end like the host skill - // gesture; only `@` tokens shed sentence punctuation below. - const re = /(^|\s)(\/[\w-]+(?=\s|$)|@"[^"\n]+"|@[^\s]+)/gu - let m: RegExpExecArray | null - while ((m = re.exec(text)) !== null) { - const tokenStart = m.index + (m[1] as string).length // (^|\s) captures '' at line start - const rawLabel = m[2] as string // non-optional alternation capture - const label = rawLabel.startsWith('@"') - ? rawLabel - : rawLabel.replace(TRAILING_PUNCTUATION_RE, '') - if (label.length <= 1) continue - if (label.startsWith('/') && !slashNames.includes(label.slice(1))) continue - ranges.push({ start: tokenStart, end: tokenStart + label.length, label, kind: 'plain' }) - } - const rankOf = (range: DecorationRange): number => range.kind === 'session' ? 0 : 1 - ranges.sort((a, b) => a.start - b.start || rankOf(a) - rankOf(b) || b.end - a.end) - const parts: ReactNode[] = [] - let cursor = 0 - const pushPlain = (from: number, to: number): void => { - parts.push({text.slice(from, to)}) - } - for (const range of ranges) { - if (range.start < cursor) continue - const { start: tokenStart, end, label, kind } = range - if (tokenStart > cursor) pushPlain(cursor, tokenStart) - const referenceKind = kind === 'session' - ? 'session' - : label.startsWith('@') - ? label.replace(/^@"|"$/gu, '').endsWith('/') ? 'folder' : 'file' - : undefined - const displayLabel = range.display - ?? (referenceKind === undefined - ? label - : referenceKind === 'session' - ? label.slice(1) - : label.slice(1).replace(/^"|"$/gu, '').split(/[\\/]/u).filter(Boolean).at(-1) ?? label.slice(1)) - const contents = <> - {referenceKind !== undefined && ( - - )} - {displayLabel} - - const open = references === undefined ? undefined - : referenceKind === 'file' - ? () => { references.openFile(label.slice(1).replace(/^"|"$/gu, '')) } - : referenceKind === undefined && slashKind === 'skill' - ? () => { references.openSkill(label.slice(1)) } - : undefined - const className = clsx(css.refChip, referenceKind === undefined && css.slashChip) - parts.push(open === undefined - ? - {contents} - - : ) - cursor = end - } - if (parts.length === 0) return {text} - if (cursor < text.length) pushPlain(cursor, text.length) - return <>{parts} +export function UserTextRun({ text }: UserTextRunProps): ReactNode { + return {text} +} + +/** Presentation selected by a reference renderer, independent of its matching grammar. */ +export interface ReferenceChipProps { + readonly appearance: ReferenceIconKind | 'skill' | 'command' + readonly label: string + readonly title: string + /** Absent for display-only references and previews. */ + readonly onActivate?: () => void +} + +/** + * Render a reference label or its explicitly supplied activation action. + * Text selection and repeated pointer clicks do not activate the reference. + * @param props - resolved visual fields and optional action from the owning renderer. + * @returns an inline label, or a keyboard-accessible button when activation is supplied. + */ +export function ReferenceChip({ appearance, label, title, onActivate }: ReferenceChipProps): ReactNode { + const slash = appearance === 'skill' || appearance === 'command' + const contents = <> + {!slash && } + {label} + + const className = clsx(css.refChip, slash && css.slashChip) + return onActivate === undefined + ? {contents} + : } diff --git a/packages/client/ui-primitives/tests/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-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 cee0b99508..fad641b3fe 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,12 @@ "@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:*", + "@types/react": "~18.3.1", + "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 +70,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-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 347920cc81..37afaebac6 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": { @@ -51,6 +52,7 @@ "use-sync-external-store": "1.6.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-renderer/src/client/scoped-slots.tsx b/packages/client/ui-renderer/src/client/scoped-slots.tsx index 24bb7f6bd3..89ab67fb19 100644 --- a/packages/client/ui-renderer/src/client/scoped-slots.tsx +++ b/packages/client/ui-renderer/src/client/scoped-slots.tsx @@ -10,7 +10,7 @@ import { SlotOwnershipError, StaleAuthorizationError, standardHookPropName, type ChainRenderOpts, type HostObservable, type KeyedStandardSource, type LocaleFace, type RenderFactorySlot, type RenderOpts, type ScopedStandardSourceBinding, type SessionAreaProps, type SessionProviderComponent, type SlotRenderer, - type SlotRendererHost, type SlotScope, type SlotScopeAdapter, type StandardSourceBinding, + type SlotEntryDef, type SlotRendererHost, type SlotScope, type SlotScopeAdapter, type SlotSpec, type StandardSourceBinding, type StoredEntry, type StoredFactory, type Translate, } from '@deepseek-ai/dsh-client-ui-slots' import { @@ -21,6 +21,7 @@ import { import { SlotAssemblyError } from './errors.ts' type InjectedProps = Record +type SlotAnchorTag = 'div' | 'span' type SlotHookFactory = (standard: InjectedProps, hookContext: unknown) => unknown type SlotHookFactories = Readonly> @@ -79,7 +80,7 @@ function boundRenderSlot(host: SlotRendererHost, entry: StoredEntry): RenderSlot if (declared.kind === 'chain') { throw new SlotOwnershipError(`slot '${key}' is declared 'chain' — use renderSlotChain`) } - return + return } renderSlotCache.set(entry, binding) } @@ -108,7 +109,7 @@ function boundRenderSlotChain(host: SlotRendererHost, entry: StoredEntry): Rende if (declared.kind !== 'chain') { throw new SlotOwnershipError(`slot '${key}' is declared '${declared.kind}', not 'chain' — use renderSlot`) } - return + return } renderSlotChainCache.set(entry, binding) } @@ -128,7 +129,7 @@ function boundFactoryRenderSlot(host: SlotRendererHost, definition: StoredFactor const declared = definition.children?.[key] if (declared === undefined) throw new SlotOwnershipError(`slot '${key}' is not declared by this Factory`) if (declared.kind === 'chain') throw new SlotOwnershipError(`slot '${key}' is declared 'chain' — use renderSlotChain`) - return + return } factoryRenderSlotCache.set(definition, binding) return binding @@ -146,7 +147,7 @@ function boundFactoryRenderSlotChain(host: SlotRendererHost, definition: StoredF if (declared.kind !== 'chain') { throw new SlotOwnershipError(`slot '${key}' is declared '${declared.kind}', not 'chain' — use renderSlot`) } - return + return } factoryRenderSlotChainCache.set(definition, binding) return binding @@ -402,7 +403,7 @@ function sessionGenerationKeyOf(binding: ScopedStandardSourceBinding): number { * the outlet then owns the crash face). */ class SlotErrorBoundary extends Component< - { slotKey: string; onEntryError: (error: unknown) => void; children: ReactNode }, { failed: boolean } + { slotKey: string; anchor?: SlotAnchorTag; onEntryError: (error: unknown) => void; children: ReactNode }, { failed: boolean } > { override state = { failed: false } static getDerivedStateFromError(error: unknown): { failed: boolean } { @@ -414,7 +415,8 @@ class SlotErrorBoundary extends Component< this.props.onEntryError(error) } override render(): ReactNode { - if (this.state.failed) return
+ const Anchor = this.props.anchor ?? 'div' + if (this.state.failed) return return this.props.children } } @@ -1024,8 +1026,9 @@ function FactoryOutlet({ name, inputProps, slots: selected = EMPTY_FACTORY_SELEC ) } -function StrictSessionEntry({ slotKey, entry, ownerProps, slotInjected, hookContext, hasHookContext, onEntryError }: { +function StrictSessionEntry({ slotKey, anchor, entry, ownerProps, slotInjected, hookContext, hasHookContext, onEntryError }: { slotKey: string + anchor: SlotAnchorTag entry: StoredEntry ownerProps: object slotInjected: BoundSlotInject @@ -1041,7 +1044,7 @@ function StrictSessionEntry({ slotKey, entry, ownerProps, slotInjected, hookCont // Per-session remount rides this key; per-entry remount rides the outer // element's entry-identity key (the outlet's guarded() call). return ( - + - {renderOutletContent(host, slotKey, ownerProps, opts, scopeBinding)} -
+ + {spec === undefined ? null : renderOutletContent(host, slotKey, ownerProps, opts, scopeBinding, spec)} + ) } @@ -1098,14 +1106,11 @@ function renderOutletContent( ownerProps: object, opts: (RenderOpts & ChainRenderOpts) | undefined, scopeBinding: StandardSourceBinding, + spec: SlotSpec, ): ReactNode { - const spec = host.specOf(slotKey) - // Undeclared (or no-longer-declared) keys render empty: a declaring entry's - // unload returns the slot to the undeclared state while retained elements - // may still be mounted — natural empty, not an ownership failure. - if (!spec) return null + const Anchor = spec.inline === true ? 'span' : 'div' if (spec.kind === 'chain' && opts?.fallbackOnly === true) { - return renderChainResult(slotKey, null, opts) + return renderChainResult(slotKey, null, opts, Anchor) } if (spec.scope === 'session' && scopeBinding.key === undefined) { throw new SlotAssemblyError(`strict session slot '${slotKey}' rendered without a scope binding`) @@ -1130,6 +1135,7 @@ function renderOutletContent( ? ( ) : ( - + {spec.scope === 'session-maybe' ? (
+ const deadCell = () => if (spec.kind === 'single') { const entry = host.entriesOfSlot(slotKey)[0] @@ -1211,7 +1217,7 @@ function renderOutletContent( break } } - return renderChainResult(slotKey, elected, opts) + return renderChainResult(slotKey, elected, opts, Anchor) } // list: one row per id cell — the cell's shadowing winner, or the crash // face once every entry of the cell abdicated (a dry cell must not @@ -1239,7 +1245,7 @@ function renderOutletContent( <> {list.map((item, i) => item.entry !== undefined ? guarded(item.entry, `e${entryKeyOf(item.entry)}`) - :
)} + : )} ) } @@ -1249,16 +1255,17 @@ function renderChainResult( slotKey: string, elected: ReactNode, opts: (RenderOpts & ChainRenderOpts) | undefined, + Anchor: SlotAnchorTag, ): ReactNode { if (!opts?.overlay) return elected ?? <>{opts?.fallback ?? null} return ( <> -
{opts.fallback ?? null} -
+
{elected} ) diff --git a/packages/client/ui-renderer/tests/inline-slots.client.spec.tsx b/packages/client/ui-renderer/tests/inline-slots.client.spec.tsx new file mode 100644 index 0000000000..15fc5056bd --- /dev/null +++ b/packages/client/ui-renderer/tests/inline-slots.client.spec.tsx @@ -0,0 +1,123 @@ +// @vitest-environment jsdom +import { useState, type ReactNode } from 'react' +import { act, cleanup, fireEvent } from '@testing-library/react' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import type { PropsRenderFactories, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + 'spec.inline.single': { kind: 'single'; scope: 'root'; inline: true } + 'spec.inline.keyed': { kind: 'keyed'; scope: 'root'; inline: true } + 'spec.inline.list': { kind: 'list'; scope: 'root'; inline: true } + 'spec.inline.chain': { kind: 'chain'; scope: 'root'; inline: true; owner: { enabled: boolean } } + 'spec.inline.child': { kind: 'single'; scope: 'root'; inline: true } + 'spec.inline.block': { kind: 'single'; scope: 'root' } + } + interface SlotFactoryMap { + 'spec.inline.factory': { + scope: 'root' + children: { 'spec.inline.child': { kind: 'single'; scope: 'root'; inline: true } } + } + } +} + +afterEach(cleanup) + +async function setup() { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + return runtime +} + +function Crashed(): never { + throw new Error('inline entry failed') +} + +describe('inline Slot anchors', () => { + it('keeps inline anchors and exhausted cells as spans while ordinary Slots remain divs', async () => { + const runtime = await setup() + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + await runtime.root.declare({ + 'spec.inline.single': { kind: 'single', scope: 'root', inline: true }, + 'spec.inline.keyed': { kind: 'keyed', scope: 'root', inline: true }, + 'spec.inline.list': { kind: 'list', scope: 'root', inline: true }, + 'spec.inline.block': { kind: 'single', scope: 'root' }, + }, ({ renderSlot }) => <> + {renderSlot('spec.inline.single', {})} + {renderSlot('spec.inline.keyed', {}, { entryKey: 'failed' })} + {renderSlot('spec.inline.list', {})} + {renderSlot('spec.inline.block', {}, { fallback: Ordinary fallback })} + ) + runtime.slots.register({ name: 'spec.inline.single' }, Crashed) + runtime.slots.register({ name: 'spec.inline.keyed', key: 'failed' }, Crashed) + runtime.slots.register({ name: 'spec.inline.list', id: 'failed' }, Crashed) + const view = runtime.renderRoot() + await act(async () => {}) + for (const name of ['spec.inline.single', 'spec.inline.keyed', 'spec.inline.list'] as const) { + const anchor = view.container.querySelector(`[data-slot="${name}"]`) + expect(anchor?.tagName).toBe('SPAN') + expect(anchor?.querySelector('[data-slot-error]')?.tagName).toBe('SPAN') + expect(runtime.slots.entries(name)).toHaveLength(1) + } + expect(view.container.querySelector('[data-slot="spec.inline.block"]')?.tagName).toBe('DIV') + expect(view.getByText('Ordinary fallback')).toBeTruthy() + }) + + it('uses span overlay fallbacks and span error boundaries for inline chains', async () => { + const runtime = await setup() + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + await runtime.root.declare({ + 'spec.inline.chain': { kind: 'chain', scope: 'root', inline: true }, + }, ({ renderSlotChain }) => { + const [enabled, setEnabled] = useState(false) + return <> + + {renderSlotChain('spec.inline.chain', { enabled }, { + fallback: Fallback, overlay: true, fallbackOnly: !enabled, + })} + + }) + runtime.slots.register({ name: 'spec.inline.chain', select: ({ enabled }) => enabled ? {} : null }, Crashed) + const view = runtime.renderRoot() + const fallback = view.container.querySelector('[data-chain-overlay-fallback]')! + expect(fallback.tagName).toBe('SPAN') + expect(fallback.style.display).toBe('contents') + fireEvent.click(view.getByRole('button', { name: 'Enable' })) + expect(view.container.querySelector('[data-chain-overlay-fallback]')).toBe(fallback) + expect(fallback.style.display).toBe('none') + expect(view.container.querySelector('[data-slot-error="spec.inline.chain"]')?.tagName).toBe('SPAN') + }) + + it('retains the inline child anchor after its Factory declaration is disposed', async () => { + const runtime = await setup() + let retained: ReactNode = null + const dispose = runtime.slots.registerFactory({ + name: 'spec.inline.factory', scope: 'root', + children: { 'spec.inline.child': { kind: 'single', scope: 'root', inline: true } }, + }, ({ renderSlot }) => { + retained = renderSlot('spec.inline.child', {}, { fallback: Child fallback }) + return retained + }) + runtime.slots.register({ name: 'spec.inline.child' }, () => Child) + await runtime.root.declare({}, ({ renderFactorySlot }: PropsRuntime<'root'> & PropsRenderFactories) => { + const [hold, setHold] = useState(false) + return <> + + {hold ? retained : renderFactorySlot('spec.inline.factory', {})} + + }) + const view = runtime.renderRoot() + expect(view.getByText('Child')).toBeTruthy() + fireEvent.click(view.getByRole('button', { name: 'Retain child' })) + const anchor = view.container.querySelector('[data-slot="spec.inline.child"]')! + expect(anchor.tagName).toBe('SPAN') + await act(async () => { dispose() }) + expect(view.container.querySelector('[data-slot="spec.inline.child"]')).toBe(anchor) + expect(anchor.textContent).toBe('') + expect(view.queryByText('Child fallback')).toBeNull() + expect(runtime.slots.entries('spec.inline.child')).toHaveLength(0) + }) +}) diff --git a/packages/client/ui-schedule/README.i18n.yaml b/packages/client/ui-schedule/README.i18n.yaml index 21244ecf66..50241a25d1 100644 --- a/packages/client/ui-schedule/README.i18n.yaml +++ b/packages/client/ui-schedule/README.i18n.yaml @@ -21,8 +21,8 @@ en: 6bd6882dbbbefcb0 zh: 03aa15f1a65d13dc /deepseek-ai-dsh-client-ui-schedule/understand-the-implementation: - en: a03a551e0ed96c6b - zh: a85efe7db56b7df3 + en: 959145f9a08c3913 + zh: caae642a82d2acd3 /deepseek-ai-dsh-client-ui-schedule/further-exploration: en: 06e265120b05dbf5 zh: 08ab1ef979b8ea40 diff --git a/packages/client/ui-schedule/README.md b/packages/client/ui-schedule/README.md index 9f60a11b1c..2731187fae 100644 --- a/packages/client/ui-schedule/README.md +++ b/packages/client/ui-schedule/README.md @@ -67,6 +67,8 @@ A restored task tab carries no navigation parameters, because the Sidebar persis Subscriptions exist only while the framework observes a source. The final unsubscribe releases event listeners and invalidates pending responses. Components receive framework-bound `useCatalog` hooks and explicit action callbacks. The mounted Records view reads `schedule.history` with the selected task's original Session binding; catalog and list responses omit full history. Components own disposable search, filtering, selection, confirmation, and history-page state. Reminder records remain Host-owned and do not come from historical Session projections or browser-local demo data. +Task menus use the [standard menu geometry](../../../docs/ui-radius.md#nested-hover), including keyboard-highlighted rows. Created-task cards follow the [file-card family](../../../docs/ui-radius.md#radius-scale) for their radius and icon-tile material. + diff --git a/packages/client/ui-schedule/README.zh.md b/packages/client/ui-schedule/README.zh.md index 29c127bad3..cd027ea2ea 100644 --- a/packages/client/ui-schedule/README.zh.md +++ b/packages/client/ui-schedule/README.zh.md @@ -67,6 +67,8 @@ kind: "package-reference" 仅在框架观察数据源期间订阅。最后一个订阅取消时释放事件监听,并使尚未完成的响应失效。组件接收框架绑定的 `useCatalog` hook 和明确的操作回调。已挂载的任务运行记录视图使用所选任务的原会话绑定读取 `schedule.history`;目录和列表响应不包含完整历史。组件拥有可丢弃的搜索、筛选、选择、确认和历史分页状态。提醒记录由 Host 拥有,不来自历史会话投影或浏览器本地演示数据。 +任务菜单使用[标准菜单几何](../../../docs/ui-radius.zh.md#nested-hover),包含键盘高亮行。已创建任务卡片的圆角和图标底框材质遵循[文件卡片家族](../../../docs/ui-radius.zh.md#radius-scale)。 + diff --git a/packages/client/ui-schedule/package.json b/packages/client/ui-schedule/package.json index 0d65fc8977..2ec4f63955 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", diff --git a/packages/client/ui-schedule/src/client/ScheduleCreateCard.module.css b/packages/client/ui-schedule/src/client/ScheduleCreateCard.module.css index 551dee0b93..a56588c1d4 100644 --- a/packages/client/ui-schedule/src/client/ScheduleCreateCard.module.css +++ b/packages/client/ui-schedule/src/client/ScheduleCreateCard.module.css @@ -1,7 +1,4 @@ -/* schedule_create transcript card: clock, task title, frequency, open action. - The box is the delivery card's (ui-deliverables Deliverables.module.css - `.file`): the same fill/hover pair, 60px row, 8/10 padding, and 18px corner, - with one inset overlay button making the whole row open the task. */ +/* Created-task cards follow the file-card treatment in docs/ui-radius.md. */ .card { --card-fill: var(--dsw-static-neutral-50); @@ -15,7 +12,7 @@ padding: 8px 10px; overflow: hidden; border: 0.5px solid var(--dsw-alias-border-l1); - border-radius: 18px; + border-radius: var(--dsw-radius-lg); background: var(--card-fill); color: var(--dsw-alias-label-primary); transition: background-color 120ms ease; @@ -59,8 +56,6 @@ pointer-events: none; } -/* The clock glyph sits in the delivery card's icon frame (`.fileIcon`): a - 40px bordered 10px-corner square on the card's own fill. */ .leading { display: grid; flex: none; @@ -68,12 +63,16 @@ box-sizing: border-box; width: 40px; height: 40px; - border: 0.5px solid var(--dsw-alias-border-l2); + border: 0.5px solid var(--dsw-alias-border-l1); border-radius: 10px; - background: var(--card-fill); + background: color-mix(in srgb, var(--dsw-static-neutral-00) 50%, transparent); color: var(--dsw-alias-label-secondary); } +:global(body[data-ds-dark-theme]) .leading { + background: color-mix(in srgb, var(--dsw-static-neutral-00) 5%, transparent); +} + .leading svg { flex: none; } @@ -118,7 +117,7 @@ white-space: nowrap; } -/* The open control keeps the primitive's outlined capsule geometry and stays +/* The open control keeps the primitive's compact outlined geometry and stays its own target over the row-wide overlay. */ .openButton { flex: none; diff --git a/packages/client/ui-schedule/src/client/TaskMenu.module.css b/packages/client/ui-schedule/src/client/TaskMenu.module.css index 91fa09e354..5ddd158c37 100644 --- a/packages/client/ui-schedule/src/client/TaskMenu.module.css +++ b/packages/client/ui-schedule/src/client/TaskMenu.module.css @@ -10,12 +10,12 @@ .list { /* min-widths below are the design's outer card widths — include the pad. */ box-sizing: border-box; - padding: 3px; + padding: 4px; display: flex; flex-direction: column; gap: 0; border: 0; - border-radius: 16px; + border-radius: var(--dsw-radius-lg); background: var(--dsw-specific-menu); backdrop-filter: var(--dsw-menu-backdrop-filter); --dsw-elevation-stroke-color: var(--dsw-alias-border-l1); @@ -88,7 +88,7 @@ min-height: 34px; padding: 6px 8px; border: none; - border-radius: 8px; + border-radius: var(--dsw-radius-md); background: transparent; cursor: pointer; font-size: 13px; diff --git a/packages/client/ui-schedule/tests/schedule-create-card.client.spec.tsx b/packages/client/ui-schedule/tests/schedule-create-card.client.spec.tsx index 9a295266ba..58a5f134a6 100644 --- a/packages/client/ui-schedule/tests/schedule-create-card.client.spec.tsx +++ b/packages/client/ui-schedule/tests/schedule-create-card.client.spec.tsx @@ -284,11 +284,9 @@ describe('ScheduleCreateCard', () => { expect(frequency).toMatch(/color:\s*var\(--dsw-alias-label-tertiary\);/) expect(frequency).toMatch(/font-size:\s*10px;/) expect(frequency).toMatch(/line-height:\s*16px;/) - // The box is the delivery card's (ui-deliverables `.file`): fill/hover pair, - // 8/10 padding, 18px corner, and a 60px row (8px insets around 44px). const card = /\.card\s*\{([^}]*)\}/.exec(stylesheet)?.[1] ?? '' expect(card).toMatch(/padding:\s*8px 10px;/) - expect(card).toMatch(/border-radius:\s*18px;/) + expect(card).toMatch(/border-radius:\s*var\(--dsw-radius-lg\);/) expect(card).toMatch(/background:\s*var\(--card-fill\);/) expect(stylesheet).toMatch(/\.card:has\(\.cardOpen\):hover\s*\{[^}]*background:\s*var\(--card-hover\);/) expect(stylesheet).toMatch(/\.row\s*\{[^}]*min-height:\s*44px;/) diff --git a/packages/client/ui-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 e0d1b55faa..a55f45f712 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,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -58,6 +59,7 @@ "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-account/README.i18n.yaml b/packages/client/ui-settings-account/README.i18n.yaml index 65b2cc2812..8c9126dd3c 100644 --- a/packages/client/ui-settings-account/README.i18n.yaml +++ b/packages/client/ui-settings-account/README.i18n.yaml @@ -21,8 +21,8 @@ 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 @@ -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: d5c9f1ec3d81715b + zh: 93f66ba21737c50c /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..b2893573d9 100644 --- a/packages/client/ui-settings-account/README.md +++ b/packages/client/ui-settings-account/README.md @@ -68,7 +68,7 @@ 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 @@ -99,7 +99,7 @@ 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. diff --git a/packages/client/ui-settings-account/README.zh.md b/packages/client/ui-settings-account/README.zh.md index 09bc1997bb..e8fbf2895d 100644 --- a/packages/client/ui-settings-account/README.zh.md +++ b/packages/client/ui-settings-account/README.zh.md @@ -68,7 +68,7 @@ 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)记录持久化与展示方面的取舍。 ## 深入探索 @@ -99,7 +99,7 @@ Desktop preload 标记在账号凭证已存储后启用引导。进度属于本 - 资料和充值钱包余额通过 Host getProfile / getBalance 复用已有 Platform Web 接口。页面在打开、登录及重连后刷新,原样显示服务端脱敏后的联系方式,并分别处理查询失败,不将失败显示为零余额。用量和充值使用 Host 按 platformOrigin 派生的链接,并沿用浏览器自身登录态,不携带 DSH token。 - 已完成引导的安装不会重新应用默认值或覆盖用户后续调整的偏好。完成状态不跨设备同步,也不创建逐账号历史。 -- 引导跟随界面语言和主题,使用中文、英文分别搭配浅色、深色外观的四套 Figma PNG 插图。导出画布包含完整插图范围,Finder 插图在两种主题下使用一致的纵向渐变。 +- 引导跟随界面语言和主题,使用中文、英文分别搭配浅色、深色外观的四套 Figma 插图。导出画布包含完整插图范围,Finder 插图在两种主题下使用一致的纵向渐变。 - 通知文案按客户端读取时的界面语言由服务端本地化。切换语言本身不会重新读取未通知赠金,因此已在屏幕上的通知会沿用服务端先前语言下发的文案,直到用户手动刷新或登录生命周期重新开始。 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 ed21b99671..4465baf5cd 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": { @@ -73,6 +74,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-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/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/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/tsdown.config.ts b/packages/client/ui-settings-account/tsdown.config.ts index 247d3a8ea8..08f459e8f7 100644 --- a/packages/client/ui-settings-account/tsdown.config.ts +++ b/packages/client/ui-settings-account/tsdown.config.ts @@ -10,17 +10,17 @@ export default ((options) => bundle(options).map(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 4ab203ecbf..744a50bbec 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": { @@ -58,6 +59,7 @@ "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" 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 ddba8ede7b..01d3748a6f 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": { @@ -75,6 +76,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-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index a5c0917a25..8cd95f4015 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -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..a13f58ed78 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -89,7 +89,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..5509ac386b 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -89,7 +89,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 0f4aa17a27..a6eb4914dc 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": { @@ -64,6 +65,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/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/store.ts b/packages/client/ui-settings-models/src/client/store.ts index 52e00bd7eb..0b4d53fb8d 100644 --- a/packages/client/ui-settings-models/src/client/store.ts +++ b/packages/client/ui-settings-models/src/client/store.ts @@ -209,7 +209,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/store.client.spec.ts b/packages/client/ui-settings-models/tests/store.client.spec.ts index bade6e9d63..50b3064979 100644 --- a/packages/client/ui-settings-models/tests/store.client.spec.ts +++ b/packages/client/ui-settings-models/tests/store.client.spec.ts @@ -439,24 +439,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..09cb3bb49d 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 @@ -81,7 +81,6 @@ function mount( ctx, { namespace: WELCOME_NOTICE_SETTINGS_NAMESPACE, decode: decodeWelcomeSection }, mirror, - 'host', schemaService, ) const controller = new WelcomeNoticeStore(scope) 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-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 b4f868e424..2ad924fadd 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": { @@ -65,6 +66,7 @@ "@deepseek-ai/dsh-client-store": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.module.css b/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.module.css index be3aa42773..5836c2b56a 100644 --- a/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.module.css +++ b/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.module.css @@ -300,17 +300,6 @@ font-variant-numeric: tabular-nums; } -/* A middle dot with equal space on both sides separates the subtitle's parts. */ -.groupSub > * + *::before { - content: '·'; - padding: 0 6px; - color: var(--dsw-alias-label-tertiary); -} - -.failedCount { - color: var(--dsw-alias-state-error-primary); -} - /* The preset switcher trigger mirrors the General-settings selector pill. */ .switcher { display: inline-flex; @@ -415,13 +404,6 @@ height: 12px; } -.enabledIn { - display: flex; - flex-wrap: wrap; - align-items: baseline; - gap: 4px 10px; -} - .card[data-failed='true'] { border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent); } diff --git a/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.tsx b/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.tsx index 57810b993a..8138b0d397 100644 --- a/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.tsx +++ b/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.tsx @@ -413,18 +413,7 @@ export function PluginInventorySettingsTab( facts={providers !== undefined ? [ [t('configuration'), t('presetProvidedDetail')], - [t('enabledIn'), ( - - {providers.map(preset => presetName(preset)).join(' · ')} - - - )], + [t('enabledIn'), providers.map(preset => presetName(preset)).join(' · ')], ] : [ [t('configuration'), t(entry.enabled ? 'enabledTag' : 'disabledTag')], @@ -527,12 +516,7 @@ export function PluginInventorySettingsTab( />
-

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

+

{t('presetSubtitle')}

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

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

+

{t('globalSubtitle')}

{globalEffectiveOpen && globalCount > 0 ? (
    {filteredFailed.map(entry => globalRowCard(entry))} diff --git a/packages/client/ui-settings-plugin-inventory/src/client/locales.ts b/packages/client/ui-settings-plugin-inventory/src/client/locales.ts index 3fb7662a86..d535c07a9a 100644 --- a/packages/client/ui-settings-plugin-inventory/src/client/locales.ts +++ b/packages/client/ui-settings-plugin-inventory/src/client/locales.ts @@ -15,7 +15,6 @@ export const zh = { emptySearch: '没有匹配的插件。', presetTitle: '会话插件', presetSubtitle: '由 Agent 预设按会话组成', - countUnit: '个', switcherLabel: '选择要查看的 Agent 预设', presetOptionDefault: '{name}(默认)', presetOptionBroken: '{name}(加载失败)', @@ -23,9 +22,7 @@ export const zh = { globalSubtitle: '系统与所有会话共用', presetProvidedDetail: '全局已停用,由 Agent 预设按会话提供', enabledIn: '启用于', - viewInPreset: '去预设分组查看', matchesInOtherPresets: '其他预设中还有 {count} 个匹配:', - failedCountLabel: '个失败', enabledTag: '已启用', disabledTag: '已停用', conditionalTag: '条件启用', @@ -62,7 +59,6 @@ export const en = { emptySearch: 'No matching plugins.', presetTitle: 'Session plugins', presetSubtitle: 'Composed per session by agent presets', - countUnit: 'plugins', switcherLabel: 'Choose the agent preset to inspect', presetOptionDefault: '{name} (default)', presetOptionBroken: '{name} (failed to load)', @@ -70,9 +66,7 @@ export const en = { globalSubtitle: 'Shared by the system and every session', presetProvidedDetail: 'Disabled globally; agent presets provide it per session', enabledIn: 'Enabled in', - viewInPreset: 'View in the preset group', matchesInOtherPresets: '{count} more matches in other presets: ', - failedCountLabel: 'failed', enabledTag: 'Enabled', disabledTag: 'Disabled', conditionalTag: 'Conditional', diff --git a/packages/client/ui-settings-plugin-inventory/tests/components.client.spec.tsx b/packages/client/ui-settings-plugin-inventory/tests/components.client.spec.tsx index 9a87e8d6d8..cd4e5acd14 100644 --- a/packages/client/ui-settings-plugin-inventory/tests/components.client.spec.tsx +++ b/packages/client/ui-settings-plugin-inventory/tests/components.client.spec.tsx @@ -193,6 +193,8 @@ describe('PluginInventorySettingsTab', () => { const { locale, pageProps } = localizedProps(list) const view = render() await screen.findByRole('searchbox', { name: en.search }) + expect(screen.getByText(en.presetSubtitle).textContent).toBe(en.presetSubtitle) + expect(screen.getByText(en.globalSubtitle).textContent).toBe(en.globalSubtitle) fireEvent.click(globalToggle()) const global = screen.getByRole('button', { name: 'Navigation, include:global-navigation, Enabled' }) const preset = screen.getByRole('button', { name: 'Session runner, include:preset-runner, Enabled' }) @@ -209,6 +211,8 @@ describe('PluginInventorySettingsTab', () => { locale.setLocale('zh') view.rerender() + expect(screen.getByText(zh.presetSubtitle).textContent).toBe(zh.presetSubtitle) + expect(screen.getByText(zh.globalSubtitle).textContent).toBe(zh.globalSubtitle) expect(screen.getByRole('button', { name: '导航, include:global-navigation, 已启用' })).toBeTruthy() expect(screen.getByRole('button', { name: '会话执行器, include:preset-runner, 已启用' })).toBeTruthy() expect(screen.getByText('全局导航控件')).toBeTruthy() @@ -321,8 +325,7 @@ describe('PluginInventorySettingsTab', () => { ]) fireEvent.keyDown(document, { key: 'Escape' }) expect(screen.queryAllByRole('menuitem')).toHaveLength(0) - expect(screen.getByText(en.presetSubtitle)).toBeTruthy() - expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('6') + expect(screen.getByText(en.presetSubtitle).textContent).toBe(en.presetSubtitle) // The preset group starts open with its rows while the larger global plane stays folded. expect(presetToggle().getAttribute('aria-expanded')).toBe('true') @@ -338,8 +341,7 @@ describe('PluginInventorySettingsTab', () => { expect(screen.queryByRole('img', { name: en.unobserved })).toBeNull() expect(globalToggle().getAttribute('aria-expanded')).toBe('false') - expect(view.container.querySelector('[data-plugin-count]')?.getAttribute('data-plugin-count')).toBe('7') - expect(screen.getByText(`1 ${en.failedCountLabel}`)).toBeTruthy() + expect(screen.getByText(en.globalSubtitle).textContent).toBe(en.globalSubtitle) // A preset row expands into its source facts. fireEvent.click(screen.getByRole('button', { name: 'pwsh, Conditional' })) @@ -484,14 +486,14 @@ describe('PluginInventorySettingsTab', () => { } pickPreset('ptc') - expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('3') + expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(3) fireEvent.click(screen.getByRole('button', { name: 'tool-bash, bash, Enabled' })) // An unnamed preset labels its source by id. expect(screen.getByText(en.fromPreset).nextElementSibling?.textContent).toBe('ptc') pickPreset('坏预设 (failed to load)') expect(screen.getByRole('alert').textContent).toBe('the composition file is missing') - expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('0') + expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(0) }) it('folds the preset group on demand and reopens it for a search', async () => { @@ -500,10 +502,10 @@ describe('PluginInventorySettingsTab', () => { expect(toggle.getAttribute('aria-expanded')).toBe('true') expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(6) - // The header keeps its count while the rows are folded away. + // The explanatory subtitle remains visible while the rows are folded away. fireEvent.click(toggle) expect(toggle.getAttribute('aria-expanded')).toBe('false') - expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('6') + expect(screen.getByText(en.presetSubtitle).textContent).toBe(en.presetSubtitle) expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(0) fireEvent.change(screen.getByRole('searchbox', { name: en.search }), { target: { value: 'pwsh' } }) @@ -542,28 +544,15 @@ describe('PluginInventorySettingsTab', () => { expect(screen.getByText('Localized standard · Localized ptc')).toBeTruthy() }) - it('jumps from a preset-provided row to the preset that enables it', async () => { - await renderReady() - fireEvent.click(screen.getByRole('button', { name: en.switcherLabel })) - fireEvent.click(screen.getByRole('menuitem', { name: 'ptc' })) - - fireEvent.click(globalToggle()) - fireEvent.click(screen.getByRole('button', { name: 'tool-bash, bash-host, Via presets' })) - fireEvent.click(screen.getByRole('button', { name: en.viewInPreset })) - expect(screen.getByRole('button', { name: en.switcherLabel }).textContent) - .toBe('标准模式 (default)') - }) - it('searches across scopes and points at matches in other presets', async () => { const view = await renderReady() const search = screen.getByRole('searchbox', { name: en.search }) fireEvent.change(search, { target: { value: 'tool-bash' } }) // Searching forces the collapsed global plane and drawer open. - expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('1') - expect(view.container.querySelector('[data-plugin-count]')?.getAttribute('data-plugin-count')).toBe('1') + expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(1) + expect(view.container.querySelectorAll('[data-plugin-scope="global"] li')).toHaveLength(1) expect(screen.getByText(en.presetEnabledTag)).toBeTruthy() - expect(screen.queryByText(`1 ${en.failedCountLabel}`)).toBeNull() const hint = screen.getByText((text: string) => text.startsWith('2 more matches')) expect(hint).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: 'ptc' })) @@ -571,13 +560,13 @@ describe('PluginInventorySettingsTab', () => { // A match visible only in another preset keeps the pointer without rows. fireEvent.change(search, { target: { value: 'crashy' } }) - expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('0') + expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(0) expect(screen.getByText((text: string) => text.startsWith('1 more matches'))).toBeTruthy() expect(screen.queryByText(en.emptySearch)).toBeNull() // A match on a Loader entry id only reaches the global plane. fireEvent.change(search, { target: { value: '8a1b2c3d' } }) - expect(view.container.querySelector('[data-plugin-count]')?.getAttribute('data-plugin-count')).toBe('1') + expect(view.container.querySelectorAll('[data-plugin-scope="global"] li')).toHaveLength(1) expect(screen.queryByText((text: string) => text.includes('more matches'))).toBeNull() fireEvent.change(search, { target: { value: 'not-a-plugin' } }) diff --git a/packages/client/ui-settings-plugins/locale/en.json b/packages/client/ui-settings-plugins/locale/en.json new file mode 100644 index 0000000000..bbe7eea9a3 --- /dev/null +++ b/packages/client/ui-settings-plugins/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-plugins" + } +} diff --git a/packages/client/ui-settings-plugins/locale/zh.json b/packages/client/ui-settings-plugins/locale/zh.json new file mode 100644 index 0000000000..71ab797452 --- /dev/null +++ b/packages/client/ui-settings-plugins/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "内置插件设置入口", + "description": "提供设置中的内置插件入口及其功能标签页。" + } +} diff --git a/packages/client/ui-settings-plugins/package.json b/packages/client/ui-settings-plugins/package.json index 0f32affb06..a2a4492ad6 100644 --- a/packages/client/ui-settings-plugins/package.json +++ b/packages/client/ui-settings-plugins/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-plugins", "description": "Built-in plugins settings section for the dsh web client: the Settings navigation entry and the tab chrome feature-owned tabs register into", - "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,6 +55,7 @@ "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-session-log/locale/en.json b/packages/client/ui-settings-session-log/locale/en.json new file mode 100644 index 0000000000..3f4017f7d2 --- /dev/null +++ b/packages/client/ui-settings-session-log/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-session-log" + } +} diff --git a/packages/client/ui-settings-session-log/locale/zh.json b/packages/client/ui-settings-session-log/locale/zh.json new file mode 100644 index 0000000000..fc41c18589 --- /dev/null +++ b/packages/client/ui-settings-session-log/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话日志上传设置", + "description": "设置是否随 DeepSeek 官方模型 API 请求上传会话日志。" + } +} diff --git a/packages/client/ui-settings-session-log/package.json b/packages/client/ui-settings-session-log/package.json index 32fb45425d..d3fe0aede2 100644 --- a/packages/client/ui-settings-session-log/package.json +++ b/packages/client/ui-settings-session-log/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-session-log", "description": "General settings control for Session-log upload with DeepSeek API requests", - "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,6 +61,7 @@ "@types/react-dom": "~18.3.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-session-log/tests/upload.client.spec.tsx b/packages/client/ui-settings-session-log/tests/upload.client.spec.tsx index 955d767892..4ddc52d85e 100644 --- a/packages/client/ui-settings-session-log/tests/upload.client.spec.tsx +++ b/packages/client/ui-settings-session-log/tests/upload.client.spec.tsx @@ -14,7 +14,7 @@ afterEach(cleanup) function fixture(writable = true) { const formState = createSnapshotStore>({ - status: 'ready', value: { enabled: true }, base: {}, user: {}, revision: 0, writable, mode: 'host', + status: 'ready', value: { enabled: true }, base: {}, user: {}, revision: 0, writable, }) const set = vi.fn(async (_field: string, enabled: unknown) => { formState.update((state) => { state.value = { enabled: enabled === true } }) diff --git a/packages/client/ui-settings-shell/locale/en.json b/packages/client/ui-settings-shell/locale/en.json new file mode 100644 index 0000000000..f43265d805 --- /dev/null +++ b/packages/client/ui-settings-shell/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-shell" + } +} diff --git a/packages/client/ui-settings-shell/locale/zh.json b/packages/client/ui-settings-shell/locale/zh.json new file mode 100644 index 0000000000..aed59177c8 --- /dev/null +++ b/packages/client/ui-settings-shell/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "命令执行设置", + "description": "配置命令执行超时和输出长度上限。" + } +} diff --git a/packages/client/ui-settings-shell/package.json b/packages/client/ui-settings-shell/package.json index 017b51260c..f2d48c2aa4 100644 --- a/packages/client/ui-settings-shell/package.json +++ b/packages/client/ui-settings-shell/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-shell", "description": "Settings page of the shell executor on the dsh web client's Plugins page: the command timeout and the per-stream output cap of the shell 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": { @@ -58,6 +59,7 @@ "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-subagent/locale/en.json b/packages/client/ui-settings-subagent/locale/en.json new file mode 100644 index 0000000000..08e121d1c3 --- /dev/null +++ b/packages/client/ui-settings-subagent/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-subagent" + } +} diff --git a/packages/client/ui-settings-subagent/locale/zh.json b/packages/client/ui-settings-subagent/locale/zh.json new file mode 100644 index 0000000000..1498349fa6 --- /dev/null +++ b/packages/client/ui-settings-subagent/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "子智能体设置", + "description": "配置委派深度、并发数量和可选模型。" + } +} diff --git a/packages/client/ui-settings-subagent/package.json b/packages/client/ui-settings-subagent/package.json index 0899660cd8..fa5d97b680 100644 --- a/packages/client/ui-settings-subagent/package.json +++ b/packages/client/ui-settings-subagent/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-subagent", "description": "Settings page of Subagent delegation on the dsh web client's Plugins page: recursion depth, parallel capacity, and the models agents may choose for subagents", - "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,6 +60,7 @@ "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-web-search/locale/en.json b/packages/client/ui-settings-web-search/locale/en.json new file mode 100644 index 0000000000..5c0a85691f --- /dev/null +++ b/packages/client/ui-settings-web-search/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-web-search" + } +} diff --git a/packages/client/ui-settings-web-search/locale/zh.json b/packages/client/ui-settings-web-search/locale/zh.json new file mode 100644 index 0000000000..e450e1004c --- /dev/null +++ b/packages/client/ui-settings-web-search/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "网页搜索设置", + "description": "配置 DeepSeek 网页搜索的密钥、服务地址和请求预算。" + } +} diff --git a/packages/client/ui-settings-web-search/package.json b/packages/client/ui-settings-web-search/package.json index 5cdf2fdfe7..a858c70745 100644 --- a/packages/client/ui-settings-web-search/package.json +++ b/packages/client/ui-settings-web-search/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-web-search", "description": "Settings page of the DeepSeek web-search provider on the dsh web client's Plugins page: its API key, endpoint, and per-request search budget", - "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,6 +60,7 @@ "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings/README.i18n.yaml b/packages/client/ui-settings/README.i18n.yaml index b5488bea3e..2b1ae7c2f5 100644 --- a/packages/client/ui-settings/README.i18n.yaml +++ b/packages/client/ui-settings/README.i18n.yaml @@ -18,8 +18,8 @@ en: 2417d8409aad6ca7 zh: 449eee623a2f334b /deepseek-ai-dsh-client-ui-settings/use-this-package/configuration-forms: - en: 5bda0401a6a4f158 - zh: 6778a64d3e2a7453 + en: c2b31046779bab9e + zh: ce183f67e63114b3 /deepseek-ai-dsh-client-ui-settings/use-this-package/following-served-namespaces: en: 2edd420502bebce1 zh: 6624abe01110c012 @@ -33,8 +33,8 @@ en: d756fe51d9456fb4 zh: 41de582aace7332f /deepseek-ai-dsh-client-ui-settings/understand-the-implementation/the-describe-mirror: - en: ea274a9480884a7f - zh: bbaf650e04646c04 + en: 0cd270ddcac46776 + zh: 4e03bf1d153b3f04 /deepseek-ai-dsh-client-ui-settings/understand-the-implementation/shared-entry-writes: en: 11a73ab8e9280b81 zh: f0e72a05959e3f32 @@ -51,8 +51,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-client-ui-settings/known-limitations-and-deferred-work: - en: d8ef5c4f3a48e05f - zh: 7c335dc8543249c6 + en: f74ad1a2cc849b42 + zh: 1320e40dcdb0b208 /deepseek-ai-dsh-client-ui-settings/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-settings/README.md b/packages/client/ui-settings/README.md index 0a7113c921..b43b91a829 100644 --- a/packages/client/ui-settings/README.md +++ b/packages/client/ui-settings/README.md @@ -29,9 +29,11 @@ Feature plugins use this package to store and edit their preferences without re- ### Configuration forms -`ctx.configForms.developerTools` owns the Coding Tools switch and the shared Web and desktop preference `ui-settings.enabled`, defaulting to `true`. Its `enabled` observable publishes accepted choices and `setEnabled` uses the same ordered settings writes. Desktop and loopback Web persist to the Host document; remote Web keeps this choice in one browser-local observable until reload without issuing Host writes. This controls presentation and HTML preview permissions, not Host authorization or Session recording. Host-backed clients keep developer features disabled until the first accepted schema-resolved value arrives; missing or failed initial responses do not enable them. Later refreshes retain the last accepted choice. +`ctx.configForms.developerTools` owns the Coding Tools switch and the shared Web and desktop preference `ui-settings.enabled`, defaulting to `true`. Its `enabled` observable publishes accepted choices and `setEnabled` uses the same ordered settings writes. Desktop and every authenticated Web browser persist to the Host document. This controls presentation and HTML preview permissions, not Host authorization or Session recording. Host-backed clients keep developer features disabled until the first accepted schema-resolved value arrives; missing or failed initial responses do not enable them. Later refreshes retain the last accepted choice. -Feature adapters use `ctx.configForms.get(entryId)` to obtain accepted values and a write queue shared by every editor of that Host entry. Snapshots contain resolved `value`, inherited `base`, raw `user`, revision, writability, and persistence mode. `set` and `unset` submit one operation; `mutate` submits one atomic operation list. Staged editors pass the revision read before editing; conflicts preserve their drafts. Unsetting removes the override and restores inheritance. +Feature adapters use `ctx.configForms.get(entryId)` to obtain accepted values and a write queue shared by every editor of that Host entry. Snapshots contain resolved `value`, inherited `base`, raw `user`, revision, and writability. `set` and `unset` submit one operation; `mutate` submits one atomic operation list. Staged editors pass the revision read before editing; conflicts preserve their drafts. Unsetting removes the override and restores inheritance. + +A configuration form persists through the Host settings service for every authenticated browser; the [authenticated-browser Host preferences note](../../../.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.md) owns that policy. `settings.describe.writable` is the authority on whether a write is accepted. ### Following served namespaces @@ -59,7 +61,7 @@ The package realizes one ownership rule: the browser keeps one shared mirror of ### The describe mirror -The Host Config of the `ui-settings` entry declares the default-on `enabled` preference. The Client plugin injects `remote` with its `settings` namespace, resolves Host persistence once from the fixed `remote.$host` facts, and owns the one `settings.describe` reader in the browser: a shared mirror refreshed on every forwarded `settings/document-updated` event and on `connection/reset` (the first connection included, closing the window where a commit lands between the eager read and the SSE subscription). Cross-namespace surfaces read it through `ctx.configForms.describe()`, a read/fold face (`getSnapshot`/`subscribe`/`ensure`, plus `acceptView` folding a write answer in). +The Host Config of the `ui-settings` entry declares the default-on `enabled` preference. The Client plugin injects `remote` with its `settings` namespace and owns the one `settings.describe` reader in the browser: a shared mirror refreshed on every forwarded `settings/document-updated` event and on `connection/reset` (the first connection included, closing the window where a commit lands between the eager read and the SSE subscription). Cross-namespace surfaces read it through `ctx.configForms.describe()`, a read/fold face (`getSnapshot`/`subscribe`/`ensure`, plus `acceptView` folding a write answer in). ### Shared entry writes @@ -101,9 +103,9 @@ None; this package neither assembles nor sends a provider request. -These limits define where the settings transport cannot reach; they are current package constraints. +These limits define the settings transport's reach and who shares a settings document; they are current package constraints. -- **Non-loopback pages get no durable settings** — this Client keeps Host persistence disabled there, so a form starts `unavailable` and never crosses the wire; form writes are inert even though Connection authentication covers the API. The shared Coding Tools preference instead provides browser-local changes. +- **Host preferences are shared across authenticated entries** — browsers accessing the same settings document share its persisted preferences, rather than retaining per-browser choices. ### Dev Note diff --git a/packages/client/ui-settings/README.zh.md b/packages/client/ui-settings/README.zh.md index 193d764637..463ec9fd15 100644 --- a/packages/client/ui-settings/README.zh.md +++ b/packages/client/ui-settings/README.zh.md @@ -29,9 +29,11 @@ kind: "package-reference" ### 配置表单 -`ctx.configForms.developerTools` 管理代码工作工具开关与 Web 和桌面端共享的偏好 `ui-settings.enabled`,默认为 `true`。其 `enabled` 可观察值发布已接受的选择,`setEnabled` 使用相同的有序设置写入。桌面端和回环 Web 将设置持久化到 Host 文档;远程 Web 将此选择保存在单个浏览器本地可观察值中,刷新后重置,不发送 Host 写入。此设置控制界面展示和 HTML 预览权限,不控制 Host 授权或 Session 记录。 使用 Host 偏好的客户端在首个经过 schema 解析并接受的值到达前保持开发者功能关闭;首次响应缺失或失败不会启用它们。后续刷新保留已接受的选择。 +`ctx.configForms.developerTools` 管理代码工作工具开关与 Web 和桌面端共享的偏好 `ui-settings.enabled`,默认为 `true`。其 `enabled` 可观察值发布已接受的选择,`setEnabled` 使用相同的有序设置写入。桌面端和每个已认证的 Web 浏览器都将设置持久化到 Host 文档。此设置控制界面展示和 HTML 预览权限,不控制 Host 授权或 Session 记录。 使用 Host 偏好的客户端在首个经过 schema 解析并接受的值到达前保持开发者功能关闭;首次响应缺失或失败不会启用它们。后续刷新保留已接受的选择。 -功能适配器使用 `ctx.configForms.get(entryId)` 获取该 Host 条目所有编辑器共享的已接受值和写入队列。快照包含解析后的 `value`、继承 `base`、原始 `user`、修订号、可写性和持久化模式。`set` 与 `unset` 提交单个操作,`mutate` 提交一个原子操作列表。暂存编辑器传入编辑前读取的修订号;冲突时保留草稿。清除操作移除覆盖并恢复继承。 +功能适配器使用 `ctx.configForms.get(entryId)` 获取该 Host 条目所有编辑器共享的已接受值和写入队列。快照包含解析后的 `value`、继承 `base`、原始 `user`、修订号和可写性。`set` 与 `unset` 提交单个操作,`mutate` 提交一个原子操作列表。暂存编辑器传入编辑前读取的修订号;冲突时保留草稿。清除操作移除覆盖并恢复继承。 + +配置表单对每个已认证浏览器都通过 Host settings 服务持久化;该策略由[已认证浏览器 Host 偏好笔记](../../../.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.zh.md)拥有。写入是否被接受由 `settings.describe.writable` 决定。 ### 跟随被服务的命名空间 @@ -59,7 +61,7 @@ kind: "package-reference" ### Describe 镜像 -`ui-settings` 条目的 Host Config 声明默认开启的 `enabled` 偏好。Client 插件注入 `remote` 及其 `settings` 命名空间,从固定的 `remote.$host` 事实一次性解析 Host 持久化模式,并持有浏览器中唯一的 `settings.describe` 读取方:一面共享镜像,在每次转发的 `settings/document-updated` 事件与 `connection/reset` 时刷新(首次连接也包含在内,关闭「提交落在急切读取与 SSE 订阅之间」的窗口)。跨命名空间表面通过 `ctx.configForms.describe()` 读它,这是一个读取/折叠面(`getSnapshot`/`subscribe`/`ensure`,另有把写应答折入的 `acceptView`)。 +`ui-settings` 条目的 Host Config 声明默认开启的 `enabled` 偏好。Client 插件注入 `remote` 及其 `settings` 命名空间,并持有浏览器中唯一的 `settings.describe` 读取方:一面共享镜像,在每次转发的 `settings/document-updated` 事件与 `connection/reset` 时刷新(首次连接也包含在内,关闭「提交落在急切读取与 SSE 订阅之间」的窗口)。跨命名空间表面通过 `ctx.configForms.describe()` 读它,这是一个读取/折叠面(`getSnapshot`/`subscribe`/`ensure`,另有把写应答折入的 `acceptView`)。 ### 共享条目写入 @@ -101,9 +103,9 @@ kind: "package-reference" -这些限制说明设置传输层够不到的地方;它们是当前包约束。 +这些限制说明设置传输层的覆盖范围以及谁共享同一份 settings 文档;它们是当前包约束。 -- **非 loopback 页面没有持久化设置**:本 Client 在那里禁用 Host 持久化,因此 表单以 `unavailable` 起步且从不跨线路;尽管 Connection 认证覆盖 API,表单写入仍在那里无效。共享的代码工作工具偏好单独提供浏览器本地变更。 +- **Host 偏好由各认证入口共享**:访问同一 settings 文档的浏览器共享其持久化偏好,而非各自保存浏览器偏好。 ### 开发备注 diff --git a/packages/client/ui-settings/locale/en.json b/packages/client/ui-settings/locale/en.json new file mode 100644 index 0000000000..71db5ec901 --- /dev/null +++ b/packages/client/ui-settings/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings" + } +} diff --git a/packages/client/ui-settings/locale/zh.json b/packages/client/ui-settings/locale/zh.json new file mode 100644 index 0000000000..1373f51e13 --- /dev/null +++ b/packages/client/ui-settings/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "设置界面框架", + "description": "提供设置页面的基础表单和插件扩展位置。" + } +} diff --git a/packages/client/ui-settings/package.json b/packages/client/ui-settings/package.json index e1cc80cd17..772529a9eb 100644 --- a/packages/client/ui-settings/package.json +++ b/packages/client/ui-settings/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings", "description": "Settings domain base plugin: shared configuration forms and the canonical settings slot-type contract", - "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,6 +54,7 @@ "@deepseek-ai/dsh-util-values": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings/src/client/config-form-types.ts b/packages/client/ui-settings/src/client/config-form-types.ts index 6276618562..41fc3bf738 100644 --- a/packages/client/ui-settings/src/client/config-form-types.ts +++ b/packages/client/ui-settings/src/client/config-form-types.ts @@ -8,8 +8,7 @@ import type { SettingsPathOpView } from '@deepseek-ai/dsh-api-remotes/client' export interface ConfigFormSnapshot { /** * `loading` until the first accepted section, `ready` while one stands, and - * `unavailable` when the namespace is not exposed to this client or the - * connection keeps preferences process-local (memory mode). + * `unavailable` when the namespace is not exposed to this client. */ status: 'loading' | 'ready' | 'unavailable' /** Last accepted schema-resolved section; undefined before the first acceptance. */ @@ -27,10 +26,8 @@ export interface ConfigFormSnapshot { user: unknown /** Namespace revision fencing the next write; undefined before the first Host view. */ revision: number | undefined - /** Whether the Host document accepts writes; memory mode never does. */ + /** Whether the Host document accepts writes. */ writable: boolean - /** `host` syncs with the Host document; `memory` keeps a remote browser process-local. */ - mode: 'host' | 'memory' } /** @@ -47,7 +44,7 @@ export interface ConfigForm { subscribe(listener: () => void): () => void /** * Queue one atomic namespace mutation. All operations share one revision - * fence, Host validation, persistence decision, and recovery read. Supplying + * fence, Host validation, and recovery read. Supplying * `expectedRevision` preserves an earlier read as the fence instead of using * the latest queued or mirrored revision. * @param ops - ordered field operations copied when queued. diff --git a/packages/client/ui-settings/src/client/config-form.ts b/packages/client/ui-settings/src/client/config-form.ts index cf77536a97..7e64f9f990 100644 --- a/packages/client/ui-settings/src/client/config-form.ts +++ b/packages/client/ui-settings/src/client/config-form.ts @@ -52,7 +52,7 @@ export class ConfigFormController implements ConfigForm { private tail: Promise = Promise.resolve() private writeGeneration = 0 private disposed = false - private readonly unsubscribe: (() => void) | undefined + private readonly unsubscribe: () => void /** * Revision answered by a superseded write still ahead of the mirror: the * mirror only folds the LATEST settlement in, so a queued successor takes @@ -65,29 +65,24 @@ export class ConfigFormController implements ConfigForm { * namespace carries this form's writes (reads ride the mirror). * @param spec - namespace identity and optional narrowing decoder. * @param mirror - the shared describe mirror this form derives from. - * @param persistence - client-selected Host persistence; non-loopback pages may remain process-local. * @param schema - settings-owned schema operations. */ constructor( private readonly ctx: Context, private readonly spec: ConfigFormSpec, private readonly mirror: SettingsDescribeMirror, - private readonly persistence: 'host' | 'memory', private readonly schema: SettingsSchemaService, ) { this.store = createSnapshotStore>({ - status: persistence === 'host' ? 'loading' : 'unavailable', + status: 'loading', value: undefined, base: undefined, user: undefined, revision: undefined, writable: false, - mode: persistence, }) - if (persistence === 'host') { - this.unsubscribe = mirror.subscribe(() => { this.derive() }) - this.derive() - } + this.unsubscribe = mirror.subscribe(() => { this.derive() }) + this.derive() } /** @returns the current sync snapshot (stable reference until the next change). */ @@ -167,12 +162,12 @@ export class ConfigFormController implements ConfigForm { async dispose(): Promise { this.disposed = true this.writeGeneration += 1 - this.unsubscribe?.() + this.unsubscribe() await this.tail } private enqueue(operation: () => Promise): Promise { - if (this.persistence === 'memory' || this.disposed) return Promise.resolve(false) + if (this.disposed) return Promise.resolve(false) const task = this.tail.then(async () => { if (this.disposed) return false return await operation() @@ -244,7 +239,6 @@ export class ConfigForms extends Service { readonly developerTools: DeveloperToolsPreference private readonly mirror: SettingsDescribeMirror private readonly schema: SettingsSchemaService - private readonly persistence: 'host' | 'memory' /** * The PROVIDING fiber, kept because a Service reads `ctx` as its *consumer's* * fiber: letting a shared form write through the caller's context would make @@ -254,19 +248,16 @@ export class ConfigForms extends Service { /** * @param ctx - the providing plugin's context. - * @param config - the shared describe mirror every shared form derives from, - * the settings-owned schema operations, and the Host persistence the provider - * resolved from `remote.$host`. + * @param config - the shared describe mirror every shared form derives from + * and the settings-owned schema operations. */ constructor(ctx: Context, config: { mirror: SettingsDescribeMirror schema: SettingsSchemaService - persistence: 'host' | 'memory' }) { super(ctx, 'configForms') this.mirror = config.mirror this.schema = config.schema - this.persistence = config.persistence this.owner = ctx this.developerTools = new DeveloperToolsPreference(this.get(DEVELOPER_TOOLS_NAMESPACE)) ctx.effect(() => async () => { @@ -294,7 +285,7 @@ export class ConfigForms extends Service { const existing = this.forms.get(entryId) if (existing !== undefined) return existing as ConfigFormController const form = new ConfigFormController( - this.owner, { namespace: entryId }, this.mirror, this.persistence, this.schema, + this.owner, { namespace: entryId }, this.mirror, this.schema, ) this.forms.set(entryId, form) void this.mirror.ensure() diff --git a/packages/client/ui-settings/src/client/developer-tools.ts b/packages/client/ui-settings/src/client/developer-tools.ts index d74de75956..52eb1242d0 100644 --- a/packages/client/ui-settings/src/client/developer-tools.ts +++ b/packages/client/ui-settings/src/client/developer-tools.ts @@ -1,5 +1,5 @@ /** One accepted preference drives every developer-tool consumer. */ -import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { DeveloperToolsSettings } from '../developer-tools-settings.ts' import type { ConfigForm } from './config-form-types.ts' @@ -7,13 +7,12 @@ import type { ConfigForm } from './config-form-types.ts' export class DeveloperToolsPreference { /** Accepted enablement, observable through renderer-bound hooks. */ readonly enabled: ObservableSnapshot - private readonly local = createSnapshotStore(true) /** * @param scope - settings-owned namespace controller. */ constructor(private readonly scope: ConfigForm) { - this.enabled = scope.getSnapshot().mode === 'memory' ? this.local : { + this.enabled = { getSnapshot: () => scope.getSnapshot().value?.enabled ?? false, subscribe: (listener) => { let previous = this.enabled.getSnapshot() @@ -28,15 +27,11 @@ export class DeveloperToolsPreference { } /** - * Persist a Host choice with ordered writes, or update the shared browser-local choice. + * Persist the choice on the Host with ordered writes. * @param enabled - requested developer-tool mode. - * @returns settlement after local publication or Host acceptance; rejects after a refused write recovers. + * @returns settlement after Host acceptance; rejects after a refused write recovers. */ async setEnabled(enabled: boolean): Promise { - if (this.scope.getSnapshot().mode === 'memory') { - this.local.set(enabled) - return - } if (!await this.scope.set('enabled', enabled)) throw new Error('Developer tools preference was not saved') } } diff --git a/packages/client/ui-settings/src/client/index.ts b/packages/client/ui-settings/src/client/index.ts index 151a94d3fa..e6182781c8 100644 --- a/packages/client/ui-settings/src/client/index.ts +++ b/packages/client/ui-settings/src/client/index.ts @@ -1,7 +1,7 @@ /** Shared configuration forms and their Host describe mirror. */ import type { Context } from '@deepseek-ai/cordis' -// Type-only: the ctx.remote merge, the fixed Host facts, and the carrier's -// `connection/reset` lifecycle event, all through the assembly package. +// Type-only: the ctx.remote merge and the carrier's `connection/reset` +// lifecycle event, all through the assembly package. import type {} from '@deepseek-ai/dsh-api-remotes/client' // Type-only pair supplying `$on` and its key face without dragging a build // artifact into the Host graph (rationale beside the same pair in @@ -35,9 +35,9 @@ export const inject = ['remote', 'remote.settings'] */ export function apply(ctx: Context): void { const schema = new SettingsSchemaService(ctx) - // Every form uses the persistence mode resolved from the connected Host. - const persistence = ctx.remote.$host.isLoopback ? 'host' : 'memory' - const mirror = new SettingsDescribeMirror(ctx, persistence) + // Persistence policy: every authenticated browser persists through the Host document + // (.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.md). + const mirror = new SettingsDescribeMirror(ctx) ctx.effect(() => { const disposers = [ ctx.remote.$on('settings/document-updated', () => { void mirror.load() }), @@ -50,5 +50,5 @@ export function apply(ctx: Context): void { void mirror.ensure() return () => { for (const dispose of disposers) dispose() } }, 'ui-settings: describe mirror invalidations') - new ConfigForms(ctx, { mirror, schema, persistence }) + new ConfigForms(ctx, { mirror, schema }) } diff --git a/packages/client/ui-settings/src/client/settings-mirror.ts b/packages/client/ui-settings/src/client/settings-mirror.ts index 761a3f141c..8cdf37512d 100644 --- a/packages/client/ui-settings/src/client/settings-mirror.ts +++ b/packages/client/ui-settings/src/client/settings-mirror.ts @@ -26,11 +26,11 @@ export interface SettingsDescribeView { /** Mirror state every derived settings surface renders from. */ export interface SettingsMirrorSnapshot { /** - * `unavailable` is the terminal non-loopback state; `ready` persists across - * later failed refreshes (the held view keeps serving); `idle` means no - * answer is held and no read is running, so `ensure` will start one. + * `ready` persists across later failed refreshes (the held view keeps serving); + * `idle` means no answer is held and no read is running, so `ensure` will + * start one. */ - status: 'idle' | 'loading' | 'ready' | 'unavailable' + status: 'idle' | 'loading' | 'ready' /** The last good answer; undefined until the first success. */ view: SettingsDescribeView | undefined /** The latest refresh failure message, cleared by the next success. */ @@ -52,8 +52,8 @@ export interface SettingsDescribeFace { */ subscribe(listener: () => void): () => void /** - * Resolve once an answer is held (or the mirror is terminally unavailable), - * reading only from `idle`. + * Resolve once an answer is held, reading only from `idle`. A settled mirror + * holds either a view or the read's error. * @returns settlement of the current or newly started read, if any. */ ensure(): Promise @@ -79,14 +79,10 @@ export class SettingsDescribeMirror implements SettingsDescribeFace { /** * @param ctx - the providing plugin's context, whose `remote.settings` * namespace answers the describe read. - * @param persistence - client-selected Host persistence; non-loopback pages may remain process-local. */ - constructor( - private readonly ctx: ClientContext, - private readonly persistence: 'host' | 'memory' = 'host', - ) { + constructor(private readonly ctx: ClientContext) { this.store = createSnapshotStore({ - status: persistence === 'host' ? 'idle' : 'unavailable', + status: 'idle', view: undefined, error: null, }) @@ -112,7 +108,6 @@ export class SettingsDescribeMirror implements SettingsDescribeFace { * @returns settlement after this call's freshness is reflected. */ load(): Promise { - if (this.persistence === 'memory') return Promise.resolve() if (this.inFlight !== undefined) { this.rerun = true return this.inFlight @@ -124,13 +119,10 @@ export class SettingsDescribeMirror implements SettingsDescribeFace { } /** - * Resolve once an answer is held (or the mirror is terminally unavailable), - * reading only from `idle`. The cheap idempotent entry for surfaces that - * render on first use. + * Resolve once an answer is held, reading only from `idle`. * @returns settlement of the current or newly started read, if any. */ ensure(): Promise { - if (this.persistence === 'memory') return Promise.resolve() if (this.inFlight !== undefined) return this.inFlight if (this.getSnapshot().status === 'idle') return this.load() return Promise.resolve() diff --git a/packages/client/ui-settings/tests/config-form.client.spec.ts b/packages/client/ui-settings/tests/config-form.client.spec.ts index 3f185baf4f..e106af17ca 100644 --- a/packages/client/ui-settings/tests/config-form.client.spec.ts +++ b/packages/client/ui-settings/tests/config-form.client.spec.ts @@ -63,14 +63,14 @@ function deferred() { return { promise, resolve, reject } } -/** A host-mode mirror plus a controller derived from it, over one scripted context. */ +/** A mirror plus a controller derived from it, over one scripted context. */ function derivedScope( api: { describe?: ReturnType; mutate?: ReturnType }, spec: { namespace: string; decode?: (section: unknown) => UiTestSettings | undefined } = { namespace: 'ui-test' }, ) { const ctx = ctxWith(api) const mirror = new SettingsDescribeMirror(ctx) - const scope = new ConfigFormController(ctx, spec, mirror, 'host', settingsSchema) + const scope = new ConfigFormController(ctx, spec, mirror, settingsSchema) return { mirror, scope } } @@ -89,11 +89,11 @@ describe('ConfigFormController', () => { const describeCall = vi.fn().mockResolvedValueOnce(described({ preference: 'dark' }, 3)) const { mirror, scope } = derivedScope({ describe: describeCall }) expect(scope.getSnapshot()).toEqual({ - status: 'loading', value: undefined, revision: undefined, writable: false, mode: 'host', + status: 'loading', value: undefined, revision: undefined, writable: false, }) await mirror.load() expect(scope.getSnapshot()).toEqual({ - status: 'ready', value: { preference: 'dark' }, revision: 3, writable: true, mode: 'host', + status: 'ready', value: { preference: 'dark' }, revision: 3, writable: true, }) }) @@ -239,8 +239,8 @@ describe('ConfigFormController', () => { const mutate = vi.fn().mockResolvedValueOnce(ok(view({ preference: 'dark' }, 5))) const ctx = ctxWith({ describe: describeCall, mutate }) const mirror = new SettingsDescribeMirror(ctx) - const writer = new ConfigFormController(ctx, { namespace: 'ui-test' }, mirror, 'host', settingsSchema) - const sibling = new ConfigFormController(ctx, { namespace: 'ui-test' }, mirror, 'host', settingsSchema) + const writer = new ConfigFormController(ctx, { namespace: 'ui-test' }, mirror, settingsSchema) + const sibling = new ConfigFormController(ctx, { namespace: 'ui-test' }, mirror, settingsSchema) await mirror.load() await writer.set('preference', 'dark') expect(describeCall).toHaveBeenCalledTimes(1) @@ -424,7 +424,7 @@ describe('ConfigFormController', () => { }, } as never const scope = new ConfigFormController( - ctxWith({}), { namespace: 'ui-test' }, mirror, 'host', settingsSchema) + ctxWith({}), { namespace: 'ui-test' }, mirror, settingsSchema) expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'dark' }, revision: 1 }) await scope.dispose() @@ -437,23 +437,6 @@ describe('ConfigFormController', () => { expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'dark' }, revision: 1 }) }) - it('keeps a remote browser in memory mode without Host calls', async () => { - const describeCall = vi.fn() - const mutate = vi.fn() - const ctx = ctxWith({ describe: describeCall, mutate }) - const mirror = new SettingsDescribeMirror(ctx, 'memory') - const scope = new ConfigFormController( - ctx, { namespace: 'ui-test' }, mirror, 'memory', settingsSchema) - expect(scope.getSnapshot()).toEqual({ - status: 'unavailable', value: undefined, revision: undefined, writable: false, mode: 'memory', - }) - await mirror.load() - await scope.set('preference', 'dark') - await scope.dispose() - expect(describeCall).not.toHaveBeenCalled() - expect(mutate).not.toHaveBeenCalled() - }) - it('carries the composition base and the user layer into the snapshot', async () => { const layered: SettingsNamespaceView = { ...view({ preference: 'dark' }, 3), @@ -522,7 +505,7 @@ describe('ConfigForms.get', () => { let theme!: ConfigForm let locale!: ConfigForm new TestRemote(ctx, { settings: { describe: describeCall } }) - await ctx.plugin(ConfigForms, { mirror, schema: settingsSchema, persistence: 'host' }).await() + await ctx.plugin(ConfigForms, { mirror, schema: settingsSchema }).await() expect(ctx.configForms.describe()).toBe(mirror) const fiber = ctx.plugin({ inject: ['remote', 'configForms'], @@ -543,22 +526,4 @@ describe('ConfigForms.get', () => { expect(theme.getSnapshot()).toMatchObject({ revision: 1 }) }) - it('binds a remote browser in memory mode without starting a settings read', async () => { - const describeCall = vi.fn() - const mirror = new SettingsDescribeMirror(ctxWith({ describe: describeCall }), 'memory') - const ctx = new Context() - let scope!: ConfigForm - new TestRemote(ctx, { settings: { describe: describeCall } }) - await ctx.plugin(ConfigForms, { mirror, schema: settingsSchema, persistence: 'memory' }).await() - const fiber = ctx.plugin({ - inject: ['remote', 'configForms'], - apply: (plugin: Context) => { - scope = plugin.configForms.get('ui-test') - }, - }) - await fiber.await() - expect(scope.getSnapshot()).toMatchObject({ status: 'unavailable', mode: 'memory', writable: false }) - await fiber.dispose() - expect(describeCall).not.toHaveBeenCalled() - }) }) diff --git a/packages/client/ui-settings/tests/developer-tools.client.spec.ts b/packages/client/ui-settings/tests/developer-tools.client.spec.ts index 373c491dfe..77eac74052 100644 --- a/packages/client/ui-settings/tests/developer-tools.client.spec.ts +++ b/packages/client/ui-settings/tests/developer-tools.client.spec.ts @@ -63,20 +63,15 @@ describe('developer tools settings', () => { expect(ctx.configForms.developerTools.enabled.getSnapshot()).toBe(false) }) - it('shares one remote-browser preference across consumers and disposes it with the plugin', async () => { + it('shares one preference instance across consumers and disposes it with the plugin', async () => { const ctx = new Context() onTestFinished(() => ctx.fiber.dispose()) - const describeCall = vi.fn() - const remote = new TestRemote(ctx, { settings: { describe: describeCall } }) - remote.$host = { home: undefined, isLoopback: false } + const describeCall = vi.fn().mockResolvedValue({ ok: true, value: { writable: true, hasDocument: true, namespaces: [] } }) + new TestRemote(ctx, { settings: { describe: describeCall } }) const fiber = ctx.plugin({ inject, apply: clientApply }) await fiber.await() const preference = ctx.configForms.developerTools - expect(fiber.ctx.configForms.developerTools.enabled).toBe(preference.enabled) - expect(preference.enabled.getSnapshot()).toBe(true) - await preference.setEnabled(true) - expect(fiber.ctx.configForms.developerTools.enabled.getSnapshot()).toBe(true) - expect(describeCall).not.toHaveBeenCalled() + expect(fiber.ctx.configForms.developerTools).toBe(preference) await fiber.dispose() expect(ctx.get('configForms')).toBeUndefined() }) @@ -97,24 +92,6 @@ describe('developer tools settings', () => { }) }) -it('keeps remote browser choices local and publishes only changed values', async () => { - const host = stubConfigForm() - host.publish({ mode: 'memory' }) - const preference = new DeveloperToolsPreference(host.scope) - const notify = vi.fn() - const dispose = preference.enabled.subscribe(notify) - expect(preference.enabled.getSnapshot()).toBe(true) - await preference.setEnabled(false) - expect(preference.enabled.getSnapshot()).toBe(false) - await preference.setEnabled(false) - expect(notify).toHaveBeenCalledOnce() - await preference.setEnabled(true) - expect(preference.enabled.getSnapshot()).toBe(true) - expect(notify).toHaveBeenCalledTimes(2) - expect(host.set).not.toHaveBeenCalled() - dispose() -}) - it('ignores host revisions that do not change enablement', () => { const host = stubConfigForm() const preference = new DeveloperToolsPreference(host.scope) diff --git a/packages/client/ui-settings/tests/plugin.client.spec.ts b/packages/client/ui-settings/tests/plugin.client.spec.ts index 446ba9add8..3c4c0c8933 100644 --- a/packages/client/ui-settings/tests/plugin.client.spec.ts +++ b/packages/client/ui-settings/tests/plugin.client.spec.ts @@ -1,16 +1,33 @@ import { Context } from '@deepseek-ai/cordis' -import { describe, expect, it, vi } from 'vitest' +import z from '@deepseek-ai/schemastery' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import type { SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client' import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime' import { apply, inject } from '../src/client/index.ts' import { SettingsSchemaService } from '../src/client/schema.ts' import { ConfigForms } from '../src/client/config-form.ts' +const schema = z.object({ preference: z.string().required() }).toJSON() + +function described(preference: string, revision: number) { + const namespace: SettingsNamespaceView = { + ns: 'ui-test', + schema: JSON.parse(JSON.stringify(schema)) as SettingsNamespaceView['schema'], + value: { preference }, + autoGenerate: true, + applies: 'live', + secrets: [], + revision, + } + return { ok: true as const, value: { writable: true, hasDocument: true, namespaces: [namespace] } } +} + function bench() { - const describeCall = vi.fn().mockResolvedValue({ - ok: true, value: { writable: true, hasDocument: true, namespaces: [] }, - }) + const describeCall = vi.fn().mockResolvedValue(described('light', 0)) const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) const remote = new TestRemote(ctx, { settings: { describe: describeCall } }) + remote.$host = { home: undefined, isLoopback: false } return { ctx, describeCall, remote, fiber: ctx.plugin({ inject: [...inject], apply }) } } @@ -23,14 +40,24 @@ describe('settings domain base plugin', () => { await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(1) }) }) - it('refreshes the mirror on document commits and connection resets, once each', async () => { + it('refreshes remote ConfigForm values and revisions on document commits and connection resets', async () => { const { ctx, describeCall, remote, fiber } = bench() await fiber.await() - await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(1) }) - remote.emit('settings/document-updated', ['ui-test', 0]) - await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(2) }) + await ctx.configForms.describe().ensure() + const scope = ctx.configForms.get<{ preference: string }>('ui-test') + expect(scope.getSnapshot()).toMatchObject({ + status: 'ready', value: { preference: 'light' }, revision: 0, writable: true, + }) + describeCall.mockResolvedValue(described('dark', 1)) + remote.emit('settings/document-updated', ['ui-test', 1]) + await vi.waitFor(() => { + expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'dark' }, revision: 1 }) + }) + describeCall.mockResolvedValue(described('system', 2)) ctx.emit('connection/reset') - await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(3) }) + await vi.waitFor(() => { + expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'system' }, revision: 2 }) + }) }) it('fiber disposal retires the service and its invalidation subscriptions', async () => { diff --git a/packages/client/ui-settings/tests/settings-mirror.client.spec.ts b/packages/client/ui-settings/tests/settings-mirror.client.spec.ts index e44c3297dd..4262261399 100644 --- a/packages/client/ui-settings/tests/settings-mirror.client.spec.ts +++ b/packages/client/ui-settings/tests/settings-mirror.client.spec.ts @@ -94,15 +94,6 @@ describe('SettingsDescribeMirror', () => { expect(describeCall).toHaveBeenCalledTimes(1) }) - it('memory persistence is terminally unavailable and never touches the wire', async () => { - const describeCall = vi.fn() - const mirror = new SettingsDescribeMirror(ctxWith(describeCall), 'memory') - await mirror.ensure() - await mirror.load() - expect(mirror.getSnapshot()).toEqual({ status: 'unavailable', view: undefined, error: null }) - expect(describeCall).not.toHaveBeenCalled() - }) - it('acceptView folds one write answer into the held view without a wire read', async () => { const describeCall = vi.fn() .mockResolvedValueOnce(described([view('theme', 1), view('locale', 4)])) diff --git a/packages/client/ui-settings/tests/while-served.client.spec.ts b/packages/client/ui-settings/tests/while-served.client.spec.ts index c61286e741..eff63911f7 100644 --- a/packages/client/ui-settings/tests/while-served.client.spec.ts +++ b/packages/client/ui-settings/tests/while-served.client.spec.ts @@ -25,7 +25,7 @@ async function bench(namespaces: readonly string[]) { const ctx = new Context() new TestRemote(ctx, { settings: { describe: describeCall } }) const mirror = new SettingsDescribeMirror({ remote: { settings: { describe: describeCall } } } as never) - await ctx.plugin(ConfigForms, { mirror, schema: new SettingsSchemaService(ctx), persistence: 'host' }).await() + await ctx.plugin(ConfigForms, { mirror, schema: new SettingsSchemaService(ctx) }).await() return { ctx, mirror, describeCall } } diff --git a/packages/client/ui-shortcuts/locale/en.json b/packages/client/ui-shortcuts/locale/en.json new file mode 100644 index 0000000000..0602a25dff --- /dev/null +++ b/packages/client/ui-shortcuts/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-shortcuts" + } +} diff --git a/packages/client/ui-shortcuts/locale/zh.json b/packages/client/ui-shortcuts/locale/zh.json new file mode 100644 index 0000000000..ad7f1dab37 --- /dev/null +++ b/packages/client/ui-shortcuts/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "快捷键设置界面", + "description": "查看、录入和修改键盘快捷键。" + } +} diff --git a/packages/client/ui-shortcuts/package.json b/packages/client/ui-shortcuts/package.json index 72204436f3..b014f63904 100644 --- a/packages/client/ui-shortcuts/package.json +++ b/packages/client/ui-shortcuts/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-shortcuts", "description": "Keyboard shortcut reference, recording, and local preference editing", - "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,6 +62,7 @@ "@deepseek-ai/dsh-client-test-runtime": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-sidebar-browser/locale/en.json b/packages/client/ui-sidebar-browser/locale/en.json new file mode 100644 index 0000000000..6294ad3b9e --- /dev/null +++ b/packages/client/ui-sidebar-browser/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-sidebar-browser" + } +} diff --git a/packages/client/ui-sidebar-browser/locale/zh.json b/packages/client/ui-sidebar-browser/locale/zh.json new file mode 100644 index 0000000000..111b8f6dc6 --- /dev/null +++ b/packages/client/ui-sidebar-browser/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "浏览器面板", + "description": "在右侧面板中打开和浏览网页。" + } +} diff --git a/packages/client/ui-sidebar-browser/package.json b/packages/client/ui-sidebar-browser/package.json index b97e65024b..7306f7a40d 100644 --- a/packages/client/ui-sidebar-browser/package.json +++ b/packages/client/ui-sidebar-browser/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-browser", "description": "Sandboxed Web browser tabs for the right Sidebar", - "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,6 +67,7 @@ "react-dom": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-sidebar-documentpreview/README.i18n.yaml b/packages/client/ui-sidebar-documentpreview/README.i18n.yaml index 6a35e6a8d7..67ad419821 100644 --- a/packages/client/ui-sidebar-documentpreview/README.i18n.yaml +++ b/packages/client/ui-sidebar-documentpreview/README.i18n.yaml @@ -15,11 +15,11 @@ en: 0dd8c3a22e28aacf zh: c27c11bf4b5cceba /deepseek-ai-dsh-client-ui-sidebar-documentpreview/what-it-registers: - en: a8eaf01a3a3390ee - zh: ddea36dbcc4a0159 + en: 54a50f4a3a6e4d45 + zh: af905ed570812432 /deepseek-ai-dsh-client-ui-sidebar-documentpreview/addresses: - en: 949156aa02ec8b07 - zh: d3675754e2a37b5d + en: 57942270e23d3a8e + zh: 6617124e652b3f67 /deepseek-ai-dsh-client-ui-sidebar-documentpreview/how-it-reads: en: b056bbe0f74fe328 zh: fd9ac88f08825afc diff --git a/packages/client/ui-sidebar-documentpreview/README.md b/packages/client/ui-sidebar-documentpreview/README.md index 588a95a7e0..51e23e2208 100644 --- a/packages/client/ui-sidebar-documentpreview/README.md +++ b/packages/client/ui-sidebar-documentpreview/README.md @@ -28,7 +28,7 @@ Preview files in the right Sidebar and choose among registered renderers. Markdo ## What it registers -- **The type** — `ctx.sidebarRightTabs.register(...)` with id `@deepseek-ai/dsh-client-ui-sidebar-documentpreview` (this implementation's identity in the tab system, and the key its body registers under), kind `text`, pattern `dsh-resource://file/**`, band `fallback`. `canOpen` accepts only Session addresses, whose paths may be relative or absolute; bare `absolute` addresses are not claimed. A type registered at the `extension` or `builtin` band for a narrower pattern (say `*.png`) takes those addresses; other supported files land here. The whole address is the content identity, so two files with one name in different directories, or one path under two sessions, are two tabs; the decoded basename is the tab title, and the keyed `sidebar.right.pane.tab.title` seat places its extension-specific `FileTypeIcon` before that title. +- **The type** — `ctx.sidebarRightTabs.register(...)` with id `@deepseek-ai/dsh-client-ui-sidebar-documentpreview` (this implementation's identity in the tab system, and the key its body registers under), kind `text`, a whole-address file-resource pattern, band `fallback`. `canOpen` accepts only Session addresses, whose paths may be relative or absolute; bare `absolute` addresses are not claimed. A type registered at the `extension` or `builtin` band for a narrower pattern (say `*.png`) takes those addresses; other supported files land here. The whole address is the content identity, so two files with one name in different directories, or one path under two sessions, are two tabs; the decoded basename is the tab title, and the keyed `sidebar.right.pane.tab.title` seat places its extension-specific `FileTypeIcon` before that title. - **The body** — the keyed `sidebar.right.pane.tab` seat under the type's id. Its fixed header shows the Host's absolute path when available, otherwise the requested path; the shared [`PathLabel`](../ui-primitives/README.md#component-catalog) subdues directories, preserves a clipped path’s trailing characters with a left-edge fade, and exposes the full value on hover. A dropdown appears when multiple supported renderers are available. Plain text is offered only for text-compatible sources; a single renderer shows no viewer control. A known binary container suffix without a registered renderer shows the file-type icon and an unsupported-preview message under the path header, without issuing a read. Two Session-scoped list child slots hand the previewed file to other plugins once its metadata reports a Host path, both with `absolutePath` as the owner prop: `sidebar.right.tab.document.actions` renders after the header's own controls in every state that shows the header, and `sidebar.right.tab.document.unpreviewable` renders in the unsupported empty state and in the empty state of a readable file the preview cannot render (`not-text`, `too-large`), where Retry would otherwise stand; a carrier or unclassified read failure keeps Retry, and a missing or non-regular path offers only its explanation. The shipped occupant of both is [`ui-open-in-app`](../ui-open-in-app/README.md). A wrap toggle appears only when the selected renderer declares `wrap: true`; its glyph describes the mode the click selects, and the per-tab preference starts on. Reload stays in this header, not the Sidebar's tab strip. Automatic refresh defaults to enabled; its separate toggle is hidden, with state, labels, styles, and toggle logic retained. The body reaches every pane edge; each renderer owns its content inset and may own an inner scrollport. This intentionally differs from the Files tab's 2px right-side scrollbar offset: previews keep the full pane width so edge-to-edge HTML and code scrollports end at the pane edge. - **Shared loading and view state**, session-scoped and bucketed by tab id. The store holds accumulated pages or complete bytes, read and observed versions, pending Resource changes, automatic-refresh state, loading/failure state, renderer choice, scroll offset, wrap, and the answered navigation revision. The ordinary inject face calls Remote readers and writes through declared store actions. Reloads and loading-mode changes retire older requests; the tab's abort signal forgets its state. @@ -39,7 +39,7 @@ Document implementations register metadata with `ctx.documentPreviews.register({ ## Addresses -A tab uses the Session address built by `fileAddressFor`, carrying a relative or absolute path. `hostFileOf(address)` takes the Session only from that address, with no external Session argument; neither current nor Tab Session is borrowed. The Host resolves file and related paths through the Session filesystem, whose backend controls read authority. Metadata for the same complete address is shared by every UI, including Global components. The [Workspace Files README](../../api/workspace-files/README.md) owns these rules; renderer selection does not change the navigation address. +A tab uses the Session address built by `fileAddressFor`, carrying a relative or absolute path. Routing preserves `.` and `..` path segments in the address and its content identity; the Host resolves them. `hostFileOf(address)` takes the Session only from that address, with no external Session argument; neither current nor Tab Session is borrowed. The Host resolves file and related paths through the Session filesystem, whose backend controls read authority. Metadata for the same complete address is shared by every UI, including Global components. The [Workspace Files README](../../api/workspace-files/README.md) owns these rules; renderer selection does not change the navigation address. After all text pages load, Markdown images use the authenticated `/api/file` route for absolute file paths and paths relative to the source document's directory. Relative images wait for the Host's absolute document path. URL escapes are decoded once; query and fragment suffixes are excluded from the filename. HTTP(S) images retain their authored URLs, and failed image loads show alt text. Local images require an HTTP(S) application base URL; image files are not added to automatic-refresh dependencies. diff --git a/packages/client/ui-sidebar-documentpreview/README.zh.md b/packages/client/ui-sidebar-documentpreview/README.zh.md index 89d90091f5..1c5be3fdc3 100644 --- a/packages/client/ui-sidebar-documentpreview/README.zh.md +++ b/packages/client/ui-sidebar-documentpreview/README.zh.md @@ -28,7 +28,7 @@ kind: "package-reference" ## 注册了什么 -- **类型** —— `ctx.sidebarRightTabs.register(...)`,id 为 `@deepseek-ai/dsh-client-ui-sidebar-documentpreview`(这个实现在 tab 系统中的身份,也是其正文注册所用的键),kind `text`,pattern `dsh-resource://file/**`,档位 `fallback`。`canOpen` 只接受 Session 地址,其中路径可为相对或绝对路径;不认领裸 `absolute` 地址。在 `extension` 或 `builtin` 档以更窄 pattern(比如 `*.png`)注册的类型接走那些地址;其他受支持文件落到这里。整个地址就是内容身份,所以不同目录下同名的两个文件、或同一路径在两个会话之下,是两个 tab;解码后的 basename 是 tab 标题,keyed slot `sidebar.right.pane.tab.title` 会在标题前放置按扩展名选择的 `FileTypeIcon`。 +- **类型** —— `ctx.sidebarRightTabs.register(...)`,id 为 `@deepseek-ai/dsh-client-ui-sidebar-documentpreview`(这个实现在 tab 系统中的身份,也是其正文注册所用的键),kind `text`,匹配完整文件资源地址的 pattern,档位 `fallback`。`canOpen` 只接受 Session 地址,其中路径可为相对或绝对路径;不认领裸 `absolute` 地址。在 `extension` 或 `builtin` 档以更窄 pattern(比如 `*.png`)注册的类型接走那些地址;其他受支持文件落到这里。整个地址就是内容身份,所以不同目录下同名的两个文件、或同一路径在两个会话之下,是两个 tab;解码后的 basename 是 tab 标题,keyed slot `sidebar.right.pane.tab.title` 会在标题前放置按扩展名选择的 `FileTypeIcon`。 - **正文** —— keyed slot `sidebar.right.pane.tab`,键为类型的 id。固定头部在可用时显示 Host 的绝对路径,否则显示请求路径;共享的 [`PathLabel`](../ui-primitives/README.zh.md#component-catalog) 弱化目录颜色,以左侧渐隐保留被裁剪路径的尾部字符,并在悬停时展示完整值。有多个受支持的渲染器时才显示下拉菜单。仅文本兼容的源文件提供纯文本选项;只有一个渲染器时不显示查看器控件。已知的二进制容器后缀没有注册渲染器时,在路径头部下方显示文件类型图标和不支持预览的说明,并且不会发起读取。两个 Session 作用域的 list 子 slot 在文件元数据报出 Host 路径后把当前文件交给其他插件,owner prop 为 `absolutePath`:`sidebar.right.tab.document.actions` 在每个显示头部的状态里渲染在头部自有控件之后;`sidebar.right.tab.document.unpreviewable` 渲染在不支持预览的空态里,以及可读但本预览无法渲染的文件(`not-text`、`too-large`)的空态里,占据原本放重试的位置;载体或未分类的读取失败仍保留重试,不存在或非普通文件的路径只给说明。两者已发布的占位者都是 [`ui-open-in-app`](../ui-open-in-app/README.zh.md)。仅当所选渲染器声明 `wrap: true` 时显示换行开关;图标表示点击后切换到的模式,该偏好按 tab 保存,初始开启。重新载入仍在此头部,不放入 Sidebar 的 tab 条。自动刷新默认开启;独立开关暂时隐藏,状态、文案、样式与切换逻辑保留。正文贴合格的每条边,各渲染器自行提供内容留白,并可拥有内部滚动区。这与 Files tab 右侧预留 2px 滚动条间距的布局有意不同:Preview 使用格的完整宽度,使贴边 HTML 与代码滚动区终止于格的边缘。 - **共享加载与视图状态**,会话作用域、按 tab id 分桶。store 持有累计页或完整字节、读取与观察版本、待处理 Resource 变化、自动刷新状态、加载/失败状态、渲染器选择、滚动位置、换行和已响应的导航 revision。普通 inject face 调用 Remote 读取,并经声明的 store action 写入。重新载入和加载模式变化会淘汰旧请求;tab 的中止信号清理其状态。 @@ -39,7 +39,7 @@ kind: "package-reference" ## 地址 -tab 使用 `fileAddressFor` 构造的 Session 地址,携带相对或绝对路径。`hostFileOf(address)` 仅从地址取得 Session,不接收外部 Session 参数,也不借用当前或 Tab Session。Host 通过 Session 文件系统解析文件及关联路径,由该后端控制读取权限。任何 UI(包括 Global 组件)都共享同一完整地址的元数据。[Workspace Files README](../../api/workspace-files/README.zh.md) 定义这些规则;渲染器选择不改变导航地址。 +tab 使用 `fileAddressFor` 构造的 Session 地址,携带相对或绝对路径。路由在地址及其内容身份中保留 `.` 与 `..` 路径段,由 Host 解析。`hostFileOf(address)` 仅从地址取得 Session,不接收外部 Session 参数,也不借用当前或 Tab Session。Host 通过 Session 文件系统解析文件及关联路径,由该后端控制读取权限。任何 UI(包括 Global 组件)都共享同一完整地址的元数据。[Workspace Files README](../../api/workspace-files/README.zh.md) 定义这些规则;渲染器选择不改变导航地址。 全部文本分页加载完成后,Markdown 图片通过已鉴权的 `/api/file` 路由读取绝对文件路径,以及相对于源文档所在目录的路径。相对图片等待 Host 返回文档绝对路径。URL 转义只解码一次;查询参数与片段后缀不计入文件名。HTTP(S) 图片保留原始 URL,加载失败的图片显示 alt 文本。本地图片要求应用基址为 HTTP(S) URL;图片文件不加入自动刷新依赖。 diff --git a/packages/client/ui-sidebar-documentpreview/locale/en.json b/packages/client/ui-sidebar-documentpreview/locale/en.json new file mode 100644 index 0000000000..7d7f557f9a --- /dev/null +++ b/packages/client/ui-sidebar-documentpreview/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-sidebar-documentpreview" + } +} diff --git a/packages/client/ui-sidebar-documentpreview/locale/zh.json b/packages/client/ui-sidebar-documentpreview/locale/zh.json new file mode 100644 index 0000000000..8673bde417 --- /dev/null +++ b/packages/client/ui-sidebar-documentpreview/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "文档预览面板", + "description": "在右侧面板预览文档、表格、代码、图片和网页等文件。" + } +} diff --git a/packages/client/ui-sidebar-documentpreview/package.json b/packages/client/ui-sidebar-documentpreview/package.json index de0132b03f..96a17e69c8 100644 --- a/packages/client/ui-sidebar-documentpreview/package.json +++ b/packages/client/ui-sidebar-documentpreview/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-documentpreview", "description": "Extensible Sidebar previews for Office documents, spreadsheets, Markdown, code, images, PDF, HTML, and plain text", - "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,7 +68,6 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-office-to-pdf": "workspace:*", "@deepseek-ai/dsh-host-webserver": "workspace:*", - "@deepseek-ai/dsh-office-to-pdf": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", "@fortune-sheet/core": "1.0.4", @@ -89,6 +89,7 @@ "yaml": "^2.9.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/client.*.js", diff --git a/packages/client/ui-sidebar-documentpreview/src/client/definition.ts b/packages/client/ui-sidebar-documentpreview/src/client/definition.ts index 7f2892cffd..914616e0fb 100644 --- a/packages/client/ui-sidebar-documentpreview/src/client/definition.ts +++ b/packages/client/ui-sidebar-documentpreview/src/client/definition.ts @@ -46,7 +46,8 @@ export function textDefinition(): SidebarRightTabDefinition { return { id: TEXTPREVIEW_ID, kind: TEXTPREVIEW_KIND, - patterns: ['dsh-resource://file/**'], + // A character-class repetition includes literal dot segments that globstar excludes. + patterns: ['dsh-resource://file/[\\s\\S]+'], priority: 'fallback', canOpen: address => parseFileAddress(address)?.scope === 'session', title: basenameOf, diff --git a/packages/client/ui-sidebar-documentpreview/tests/definition.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/definition.client.spec.ts index 63984f41ca..a842b76b24 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/definition.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/definition.client.spec.ts @@ -9,7 +9,7 @@ */ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import { sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' +import { parseFileAddress, sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' import { SidebarRightTabRegistry } from '@deepseek-ai/dsh-client-ui-sidebar-right/src/client/tab-registry.ts' import { TEXTPREVIEW_ID, TEXTPREVIEW_KIND, basenameOf, textDefinition } from '../src/client/definition.ts' @@ -32,7 +32,7 @@ describe('textDefinition', () => { const definition = textDefinition() expect(definition.id).toBe(TEXTPREVIEW_ID) expect(definition.kind).toBe(TEXTPREVIEW_KIND) - expect(definition.patterns).toEqual(['dsh-resource://file/**']) + expect(definition.patterns).toEqual(['dsh-resource://file/[\\s\\S]+']) expect(definition.priority).toBe('fallback') expect(definition.title('dsh-resource://file/session/s-1/work/README.md')).toBe('README.md') // Reads require an addressed Session, even when the file path is absolute. @@ -66,6 +66,51 @@ describe('text type in the registry', () => { } }) + it.each([ + '../AGENTS.md', + '../../AGENTS.md', + 'dir/../AGENTS.md', + 'dir/./AGENTS.md', + '/workspace/../AGENTS.md', + 'C:/workspace/../AGENTS.md', + '//host/share/workspace/../AGENTS.md', + '', + ])('claims unresolved Session paths without rewriting their identity: %s', (path) => { + const tabs = registry() + const address = sessionFileAddress('s-1', path) + expect(tabs.claim(address)).toEqual({ kind: TEXTPREVIEW_KIND, contentId: address, title: basenameOf(address) }) + expect(tabs.claim(address).contentId).toBe(address) + expect(parseFileAddress(address)).toEqual({ scope: 'session', sessionId: 's-1', path }) + }) + + it.each([ + ['./AGENTS.md', './AGENTS.md'], + ['%2e%2E/AGENTS.md', '../AGENTS.md'], + ['dir/%2E/AGENTS.md', 'dir/./AGENTS.md'], + ['%252e%252e/AGENTS.md', '%2e%2e/AGENTS.md'], + ['../a%20b%23c%3F.txt?ignored=1#section', '../a b#c?.txt'], + ])('claims an authored address while decoding its path once: %s', (encoded, path) => { + const tabs = registry() + const address = `dsh-resource://file/session/s%2F1/${encoded}` + expect(tabs.claim(address).contentId).toBe(address) + expect(parseFileAddress(address)).toEqual({ scope: 'session', sessionId: 's/1', path }) + }) + + it.each([ + 'dsh-resource://file/session', + 'dsh-resource://file/session//../a.md', + 'dsh-resource://file/session/s-1', + 'dsh-resource://file/session/%/../a.md', + 'dsh-resource://file/session/s-1/../%ZZ.md', + 'DSH-RESOURCE://file/session/s-1/../a.md', + 'dsh-resource://File/session/s-1/../a.md', + ])('keeps the Session parser veto after matching a file prefix: %s', (address) => { + const tabs = registry() + expect(tabs.candidates(address)).toEqual([]) + expect(() => tabs.claim(address)).toThrow('no registered tab type claims') + expect(() => tabs.claim(address, TEXTPREVIEW_KIND)).toThrow(`tab type "${TEXTPREVIEW_KIND}" refuses`) + }) + it.each([ 'dsh-resource://file/shared/team/notes.md', 'dsh-resource://file/absolute/home/me/notes.md', @@ -86,6 +131,38 @@ describe('text type in the registry', () => { expect(tabs.candidates('dsh-resource://file/session/s-1/w/logo.png').map(type => type.kind)).toEqual(['image', TEXTPREVIEW_KIND]) }) + it.each(['builtin', 'extension'] as const)('yields parent paths to the %s band and honors its veto', (priority) => { + const tabs = registry() + const address = sessionFileAddress('s-1', '../AGENTS.md') + const release = tabs.register({ + id: 'test/markdown', kind: 'markdown', patterns: ['*.md'], priority, title: () => 'Markdown', + }) + expect(tabs.candidates(address).map(type => type.kind)).toEqual(['markdown', TEXTPREVIEW_KIND]) + expect(tabs.claim(address)).toEqual({ kind: 'markdown', contentId: address, title: 'Markdown' }) + release() + tabs.register({ + id: 'test/markdown', kind: 'markdown', patterns: ['*.md'], priority, canOpen: () => false, title: () => 'Markdown', + }) + expect(tabs.claim(address).kind).toBe(TEXTPREVIEW_KIND) + }) + + it('ranks the file declaration by its literal length within the fallback band', () => { + const tabs = registry() + tabs.register({ + id: 'test/shorter', kind: 'shorter', patterns: ['dsh-resource://file/**/*.*'], priority: 'fallback', title: () => 'Shorter', + }) + const releaseLonger = tabs.register({ + id: 'test/longer', kind: 'longer', patterns: ['dsh-resource://file/session/**/*.md'], priority: 'fallback', title: () => 'Longer', + }) + tabs.register({ ...textDefinition(), id: 'test/tied', kind: 'tied' }) + const address = sessionFileAddress('s-1', 'AGENTS.md') + // Specificity uses the literal pattern length, not the size of its accepted address set. + expect(tabs.candidates(address).map(type => type.kind)).toEqual(['longer', TEXTPREVIEW_KIND, 'tied', 'shorter']) + expect(tabs.claim(address).kind).toBe('longer') + releaseLonger() + expect(tabs.claim(address).kind).toBe(TEXTPREVIEW_KIND) + }) + it('does not claim addresses of other schemes', () => { const tabs = registry() expect(() => tabs.claim('sidebar://guide')).toThrow('no registered tab type claims') diff --git a/packages/client/ui-sidebar-files/locale/en.json b/packages/client/ui-sidebar-files/locale/en.json new file mode 100644 index 0000000000..6da0972151 --- /dev/null +++ b/packages/client/ui-sidebar-files/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-sidebar-files" + } +} diff --git a/packages/client/ui-sidebar-files/locale/zh.json b/packages/client/ui-sidebar-files/locale/zh.json new file mode 100644 index 0000000000..577a5725c3 --- /dev/null +++ b/packages/client/ui-sidebar-files/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "文件浏览面板", + "description": "浏览工作区目录,并在右侧面板中打开文件。" + } +} diff --git a/packages/client/ui-sidebar-files/package.json b/packages/client/ui-sidebar-files/package.json index 791ed03364..1e1a929d11 100644 --- a/packages/client/ui-sidebar-files/package.json +++ b/packages/client/ui-sidebar-files/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-files", "description": "Workspace file tree tab type for the right Sidebar: lazy directory listing over the workspaceFiles Remote namespace, opening files into the Sidebar", - "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": { @@ -70,6 +71,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-sidebar-right/locale/en.json b/packages/client/ui-sidebar-right/locale/en.json new file mode 100644 index 0000000000..4187616d33 --- /dev/null +++ b/packages/client/ui-sidebar-right/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-sidebar-right" + } +} diff --git a/packages/client/ui-sidebar-right/locale/zh.json b/packages/client/ui-sidebar-right/locale/zh.json new file mode 100644 index 0000000000..22281c9e82 --- /dev/null +++ b/packages/client/ui-sidebar-right/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "右侧面板", + "description": "管理右侧面板的展开状态、内容和导航。" + } +} diff --git a/packages/client/ui-sidebar-right/package.json b/packages/client/ui-sidebar-right/package.json index 406c3322ac..cfac61654c 100644 --- a/packages/client/ui-sidebar-right/package.json +++ b/packages/client/ui-sidebar-right/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-right", "description": "Right Sidebar: the docking surface's session-bound state, its panel and header expand control, and the navigation service over it", - "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": { @@ -70,11 +71,12 @@ "picomatch": "^4.0.7", "clsx": "^2.0.0", "@deepseek-ai/dsh-util-crypto": "workspace:*", - "zod": "^4.4.3", + "zod": "4.4.3", "@deepseek-ai/dsh-client-shortcuts": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-sidebar-terminal/locale/en.json b/packages/client/ui-sidebar-terminal/locale/en.json new file mode 100644 index 0000000000..d6ab2b3980 --- /dev/null +++ b/packages/client/ui-sidebar-terminal/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-sidebar-terminal" + } +} diff --git a/packages/client/ui-sidebar-terminal/locale/zh.json b/packages/client/ui-sidebar-terminal/locale/zh.json new file mode 100644 index 0000000000..ca36d8da54 --- /dev/null +++ b/packages/client/ui-sidebar-terminal/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "终端面板", + "description": "在右侧面板中使用交互式命令终端。" + } +} diff --git a/packages/client/ui-sidebar-terminal/package.json b/packages/client/ui-sidebar-terminal/package.json index 713c3e9c77..e872e94014 100644 --- a/packages/client/ui-sidebar-terminal/package.json +++ b/packages/client/ui-sidebar-terminal/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-terminal", "description": "Interactive shell tabs for the right Sidebar", - "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": { @@ -73,6 +74,7 @@ "@deepseek-ai/dsh-client-shortcuts": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/client.*.js", diff --git a/packages/client/ui-sidebar/locale/en.json b/packages/client/ui-sidebar/locale/en.json new file mode 100644 index 0000000000..dbf02a834f --- /dev/null +++ b/packages/client/ui-sidebar/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-sidebar" + } +} diff --git a/packages/client/ui-sidebar/locale/zh.json b/packages/client/ui-sidebar/locale/zh.json new file mode 100644 index 0000000000..5a3da3ba14 --- /dev/null +++ b/packages/client/ui-sidebar/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话侧栏", + "description": "展示会话列表,提供搜索、分组和状态提示。" + } +} diff --git a/packages/client/ui-sidebar/package.json b/packages/client/ui-sidebar/package.json index 092797ec13..d3a6116c6f 100644 --- a/packages/client/ui-sidebar/package.json +++ b/packages/client/ui-sidebar/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar", "description": "Sidebar plugin: session multi-level tree, search, grouping, state dots", - "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": { @@ -66,6 +67,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-skill/README.i18n.yaml b/packages/client/ui-skill/README.i18n.yaml index 3f5d54b740..8d82e8e675 100644 --- a/packages/client/ui-skill/README.i18n.yaml +++ b/packages/client/ui-skill/README.i18n.yaml @@ -30,8 +30,8 @@ en: 1a02a85859f851c7 zh: 03bd48b83c4a287c /deepseek-ai-dsh-client-ui-skill/understand-the-implementation/registration: - en: 1965ad3169b7fd97 - zh: efc23c44ad1d2765 + en: 4b06a66c56d19ff9 + zh: d9c8d118f73d89bb /deepseek-ai-dsh-client-ui-skill/further-exploration: en: 54198f095d0cc569 zh: 4eba4413e159967b diff --git a/packages/client/ui-skill/README.md b/packages/client/ui-skill/README.md index 08d2e1137c..4340f3f78e 100644 --- a/packages/client/ui-skill/README.md +++ b/packages/client/ui-skill/README.md @@ -59,6 +59,8 @@ Each catalog fetch requires an existing retained Client Session and waits for it The `/client` exports are the plugin body (`apply`/`inject`) only; the source object is internal to the registration effect. The tool row registers the `skill` wire name in ui-tool's keyed `tool.call.toolview` slot. +For sent text, the plugin registers a UserText matcher that returns one next original-text candidate using caller-confirmed `skillNames` and owns the `skill` entry in `conversation.user.text.node`. The renderer receives `openSkill` from its own Session-bound injection and delegates to this source’s preview operation, not to Chat owner props. Non-interactive previews remain labels. [UserText](../ui-conversation/README.md#sent-user-text) owns evaluation and node dispatch. + ----- diff --git a/packages/client/ui-skill/README.zh.md b/packages/client/ui-skill/README.zh.md index e07a59326b..d18c52f30d 100644 --- a/packages/client/ui-skill/README.zh.md +++ b/packages/client/ui-skill/README.zh.md @@ -59,6 +59,8 @@ source 不实现任何裁决钩子,也没有引用 codec:pick 落下字面 `/client` 导出接口只有插件主体(`apply`/`inject`);source 对象是注册 effect 的内部实现。工具行把 `skill` wire 名称注册进 ui-tool 的 keyed `tool.call.toolview` slot。 +对于已发送文本,插件注册使用调用方已确认 `skillNames`、返回原文中下一个候选的 UserText 匹配器,并拥有 `conversation.user.text.node` 中的 `skill` 条目。renderer 从自身绑定 Session 的 Injection 接收 `openSkill`,委托本 source 的预览操作,而非 Chat owner props。不可交互的预览仍为标签。[UserText](../ui-conversation/README.zh.md#sent-user-text) 拥有求值与节点分发。 + ----- diff --git a/packages/client/ui-skill/locale/en.json b/packages/client/ui-skill/locale/en.json new file mode 100644 index 0000000000..d61c3ff256 --- /dev/null +++ b/packages/client/ui-skill/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-skill" + } +} diff --git a/packages/client/ui-skill/locale/zh.json b/packages/client/ui-skill/locale/zh.json new file mode 100644 index 0000000000..a30c0c2fdf --- /dev/null +++ b/packages/client/ui-skill/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "技能引用与展示", + "description": "在会话中提供技能引用和技能调用展示。" + } +} diff --git a/packages/client/ui-skill/package.json b/packages/client/ui-skill/package.json index b4e69169b7..78a34d32ad 100644 --- a/packages/client/ui-skill/package.json +++ b/packages/client/ui-skill/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-skill", "description": "Web skill references and the dedicated skill tool row", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,13 +23,15 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { "inject": [ "@deepseek-ai/dsh-api-session-controller", "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-conversation", "@deepseek-ai/dsh-client-ui-renderer", "@deepseek-ai/dsh-client-ui-tool", "@deepseek-ai/dsh-client-ui-input-trigger", @@ -53,6 +55,7 @@ "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-input-trigger": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", @@ -69,6 +72,7 @@ "@deepseek-ai/dsh-util-workspace-path": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-skill/src/client/SkillReference.tsx b/packages/client/ui-skill/src/client/SkillReference.tsx new file mode 100644 index 0000000000..fef9d71a3e --- /dev/null +++ b/packages/client/ui-skill/src/client/SkillReference.tsx @@ -0,0 +1,28 @@ +/** Skill-reference presentation with activation owned by this keyed entry's Session injection. */ +import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { ReferenceChip } from '@deepseek-ai/dsh-client-ui-primitives' + +/** Session-bound preview action; accepting a preview is not a completion promise. */ +export interface SkillReferenceInjected { + /** + * Ask the skill source to preview a confirmed name in this entry's Session. + * @param name - skill name without its slash. + */ + readonly openSkill: (name: string) => void +} + +type SkillReferenceProps = UserTextNodeProps<'skill'> & SkillReferenceInjected + +/** + * Render a skill chip; previews omit activation even when the entry has an injected action. + * @param props - resolved node, raw token, interaction mode, and Session-bound preview action. + * @returns an inline skill label or interactive chip. + */ +export function SkillReference({ node, raw, interactive, openSkill }: SkillReferenceProps) { + return { openSkill(node.data.name) } } : {})} + /> +} diff --git a/packages/client/ui-skill/src/client/index.ts b/packages/client/ui-skill/src/client/index.ts index 2b6cd12ea2..ee67b91e4c 100644 --- a/packages/client/ui-skill/src/client/index.ts +++ b/packages/client/ui-skill/src/client/index.ts @@ -44,7 +44,11 @@ import { rankByName } from '@deepseek-ai/dsh-client-ui-primitives' import type {} from '@deepseek-ai/dsh-client-locale/client' // Type-only: pulls the SlotRegistry service merge (ctx.slots). import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import { SkillRow } from './SkillRow.tsx' +import { SkillReference, type SkillReferenceInjected } from './SkillReference.tsx' +import { skillReferenceRule } from './user-text-rules.ts' +export type {} from './user-text-rules.ts' import { en, NS, zh, type SkillKey } from './locales.ts' declare module '@deepseek-ai/dsh-api-session-controller/client' { @@ -70,7 +74,7 @@ interface CatalogFetch { } /** Required services: reference source faces plus the tool-row and locale registries. */ -export const inject = ['inputTriggers', 'sessions', 'slots', 'locale', 'remote', 'remote.skills', 'sidebarRight'] +export const inject = ['inputTriggers', 'sessions', 'slots', 'locale', 'remote', 'remote.skills', 'sidebarRight', 'uiConversation'] /** * Client plugin body: register the '/' source, dictionaries, and keyed tool row. @@ -78,6 +82,7 @@ export const inject = ['inputTriggers', 'sessions', 'slots', 'locale', 'remote', */ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-skill: dictionaries') + ctx.uiConversation.userText.register(skillReferenceRule) ctx.slots.inject('tool.call.toolview', () => ctx.slots.register( { name: 'tool.call.toolview', key: 'skill', locale: NS }, SkillRow, @@ -156,7 +161,7 @@ export function apply(ctx: ClientContext): void { // locale service's own fallback ladder; candidate-time reads stay plain text. const t = ctx.locale.bind(NS) - const source: InputTriggerSource = { + const source = { trigger: '/', name: 'skill', order: 2, @@ -223,7 +228,20 @@ export function apply(ctx: ClientContext): void { // line client-side before it ever becomes a prompt. return { text: `/${candidate.name} ` } }, - } + } satisfies InputTriggerSource + + ctx.slots.inject('conversation.user.text.node', () => ctx.slots.register({ + name: 'conversation.user.text.node', + key: 'skill', + priority: 100, + inject: (sessionId): SkillReferenceInjected => ({ + openSkill: (name) => { + if (sessions.scope(sessionId) === undefined) return + source.openReference({ sessionId }, { ref: `/${name}` }) + }, + }), + }, SkillReference)) + const inputTriggers = ctx.get('inputTriggers') as InputTriggerServiceContract // A preset decides which skill providers an agent reads, so a switched // session's cached catalog belongs to the composition it no longer runs. diff --git a/packages/client/ui-skill/src/client/user-text-rules.ts b/packages/client/ui-skill/src/client/user-text-rules.ts new file mode 100644 index 0000000000..96e07f1369 --- /dev/null +++ b/packages/client/ui-skill/src/client/user-text-rules.ts @@ -0,0 +1,36 @@ +/** Original-text skill candidates restricted to caller-confirmed names. */ +import type { UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client' + +declare module '@deepseek-ai/dsh-client-ui-conversation/client' { + interface UserTextDataMap { + /** A skill name confirmed for this message, without the leading slash. */ + skill: { readonly name: string } + } + + interface UserTextFacts { + /** Resolved skill names; absence supplies no skill references. */ + readonly skillNames: readonly string[] + } +} + +/** Return one nearest confirmed slash token, retaining its original word boundaries. */ +export const skillReferenceRule: UserTextRule<'skill'> = { + id: 'skill', + order: 20, + match(text, from, context) { + const tokens = /(? null) const capture: PresentationCapture = { slots, @@ -80,11 +88,11 @@ async function bench(list: ListFn, addressed?: SessionId, opening: Pick { await fiber.dispose() }) await fiber.await() - return { ctx, source: captured!, remote, fiber, openResource, sessions } + return { ctx, source: captured!, remote, fiber, openResource, sessions, presentation } } const CATALOG: SkillRow[] = [ @@ -114,11 +122,12 @@ const req = (query: string, signal?: AbortSignal) => describe('apply', () => { it('declares the services it binds', () => { - expect(inject).toEqual(['inputTriggers', 'sessions', 'slots', 'locale', 'remote', 'remote.skills', 'sidebarRight']) + expect(inject).toEqual(['inputTriggers', 'sessions', 'slots', 'locale', 'remote', 'remote.skills', 'sidebarRight', 'uiConversation']) }) it('registers the dedicated skill row and its locale dictionaries', async () => { const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) ctx.provide('sidebarRight', { openResource: vi.fn() }) ctx.provide('inputTriggers', { registerSource: () => () => {} }) ctx.provide('sessions', { subagentAddress: () => undefined }) @@ -157,6 +166,7 @@ describe('apply', () => { it('registers the "/" skill source; disposal frees the name (HMR safety)', async () => { const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) ctx.provide('sidebarRight', { openResource: vi.fn() }) // InputTriggerService itself injects 'sessions'; the stub unblocks its fiber. ctx.provide('sessions', {}) @@ -460,6 +470,31 @@ describe('reference preview', () => { { name: 'virtual', description: 'Virtual' }, ] + it('routes sent skill previews through the reference entry’s own Session and ignores an absent scope', async () => { + const b = await bench(listOk(rows)) + const entry = b.presentation.slots.entries('conversation.user.text.node').find(row => row.options.key === 'skill') + expect(entry?.component).toBe(SkillReference) + if (entry?.inject === undefined) throw new Error('Skill reference injector was not registered') + const injectReference = entry.inject as ( + ...params: InjectParams<'conversation.user.text.node', undefined> + ) => Pick + const openReference = vi.spyOn(b.source, 'openReference') + const first = injectReference(sid('first')) + const second = injectReference(sid('second')) + first.openSkill('review') + await b.source.candidates(proj('first'), req('')) + expect(openReference).toHaveBeenLastCalledWith(proj('first'), { ref: '/review' }) + expect(b.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/first//skills/review/SKILL.md') + second.openSkill('review') + await b.source.candidates(proj('second'), req('')) + expect(openReference).toHaveBeenLastCalledWith(proj('second'), { ref: '/review' }) + expect(b.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/second//skills/review/SKILL.md') + vi.spyOn(b.sessions, 'scope').mockReturnValueOnce(undefined) + first.openSkill('review') + expect(openReference).toHaveBeenCalledTimes(2) + expect(b.openResource).toHaveBeenCalledTimes(2) + }) + it('finishes the first click after a shared warm fetch and reloads after reconnect', async () => { const gate = Promise.withResolvers() const list = vi.fn().mockReturnValueOnce(gate.promise).mockImplementation(listOk(rows)) diff --git a/packages/client/ui-skill/tests/user-text-rules.client.spec.ts b/packages/client/ui-skill/tests/user-text-rules.client.spec.ts new file mode 100644 index 0000000000..a6958ab233 --- /dev/null +++ b/packages/client/ui-skill/tests/user-text-rules.client.spec.ts @@ -0,0 +1,72 @@ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import type { UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { UserTextRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/user-text-registry.ts' +import { skillReferenceRule } from '../src/client/user-text-rules.ts' + +function setup(rule: UserTextRule = skillReferenceRule) { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const registry = new UserTextRegistry(ctx) + registry.register(rule) + return registry.createEvaluator() +} + +describe('skillReferenceRule', () => { + it('does not read names or rerun when text has no slash-token candidate', () => { + const read = vi.fn() + const match = vi.fn['match']>((text, from, context) => skillReferenceRule.match(text, from, { + read: (key) => { read(key); return context.read(key) }, + })) + const evaluate = setup({ ...skillReferenceRule, match }) + const text = 'plain text /review.md /path/to/file' + const before = evaluate({ text, facts: {} }) + expect(evaluate({ text, facts: { skillNames: ['review', 'path'] } })).toBe(before) + expect(read).not.toHaveBeenCalled() + expect(match).toHaveBeenCalledOnce() + }) + + it('reacts to missing names appearing and retains node identities when unrelated names are added', () => { + const match = vi.fn['match']>((text, from, context) => skillReferenceRule.match(text, from, context)) + const evaluate = setup({ ...skillReferenceRule, match }) + const text = 'use /review now' + expect(evaluate({ text, facts: {} }).every(node => node.id === 'text')).toBe(true) + const before = evaluate({ text, facts: { skillNames: ['review'] } }) + const after = evaluate({ text, facts: { skillNames: ['review', 'unrelated'] } }) + expect(after).toBe(before) + expect(after.find(node => node.id === 'skill')).toBe(before.find(node => node.id === 'skill')) + expect(match.mock.calls.map(([, from]) => from)).toEqual([0, 0, 11, 0, 11]) + }) + + it('recognizes only names explicitly resolved for this message', () => { + const evaluate = setup() + const text = '用 /review 再 /test-skill\n/review' + const input = Object.freeze({ text, facts: Object.freeze({ skillNames: Object.freeze(['review', 'test-skill', 'review']) }) }) + const nodes = evaluate(input) + expect(nodes.filter(node => node.id === 'skill').map(node => ({ raw: text.slice(node.start, node.end), data: node.data }))).toEqual([ + { raw: '/review', data: { name: 'review' } }, { raw: '/test-skill', data: { name: 'test-skill' } }, + { raw: '/review', data: { name: 'review' } }, + ]) + expect(JSON.parse(JSON.stringify(nodes))).toEqual(nodes) + expect(evaluate({ text, facts: {} })).toEqual([{ id: 'text', start: 0, end: text.length, data: { text } }]) + expect(evaluate({ text, facts: { skillNames: [] } }).every(node => node.id === 'text')).toBe(true) + }) + + it('requires whitespace or text boundaries and never strips attached punctuation', () => { + const evaluate = setup() + const text = '/x /x.md /x/path /path /x。 /x, (/x) prefix/x\t/x\n/x' + const nodes = evaluate({ text, facts: { skillNames: ['x'] } }) + expect(nodes.filter(node => node.id === 'skill').map(node => [node.start, node.end, text.slice(node.start, node.end)])).toEqual([ + [0, 2, '/x'], [text.indexOf('\t/x') + 1, text.indexOf('\t/x') + 3, '/x'], + [text.lastIndexOf('/x'), text.length, '/x'], + ]) + for (const input of [ + { text: '/path /x.md /x', facts: {} }, + { text: '/path /x.md /x。', facts: { skillNames: ['x'] } }, + { text: '/nfs-hg/path /root-dir/ /plan.md /plan。', facts: { skillNames: ['nfs-hg', 'root-dir', 'plan'] } }, + { text: '/plan.md /nfs-hg/path /plan。', facts: { skillNames: ['plan.md', 'nfs-hg/path', 'plan。'] } }, + ]) { + expect(evaluate(input).every(node => node.id === 'text')).toBe(true) + } + }) +}) diff --git a/packages/client/ui-skill/tsconfig.json b/packages/client/ui-skill/tsconfig.json index 18b2f4d062..276da77105 100644 --- a/packages/client/ui-skill/tsconfig.json +++ b/packages/client/ui-skill/tsconfig.json @@ -26,6 +26,9 @@ { "path": "../ui-renderer" }, + { + "path": "../ui-conversation/tsconfig.client.json" + }, { "path": "../ui-tool" }, diff --git a/packages/client/ui-slots/README.i18n.yaml b/packages/client/ui-slots/README.i18n.yaml index c19da5d570..af812bc333 100644 --- a/packages/client/ui-slots/README.i18n.yaml +++ b/packages/client/ui-slots/README.i18n.yaml @@ -18,8 +18,8 @@ en: 05691d44a0c6c48f zh: 434033d5761297f3 /deepseek-ai-dsh-client-ui-slots/use-this-package/reusable-component-factories: - en: 301de67bf2779ae6 - zh: 6e9d405ee1063d53 + en: 71cbe7aa26f3ff80 + zh: 0e35265d4d95cc36 /deepseek-ai-dsh-client-ui-slots/use-this-package/the-five-framework-props-shares: en: 45e2933a5e084956 zh: 938deedaf489f892 diff --git a/packages/client/ui-slots/README.md b/packages/client/ui-slots/README.md index 599d7c6371..fc4bfaf6ec 100644 --- a/packages/client/ui-slots/README.md +++ b/packages/client/ui-slots/README.md @@ -29,7 +29,7 @@ Compose UI through this package whenever you write a client plugin: register a c ### Reusable Component Factories -Use a Component Factory when one package defines an assembly that unrelated parents render independently. Declare its complete type in `SlotFactoryMap`, install the definition with `ctx.slots.registerFactory()`, render occurrences through the injected `renderFactorySlot()`, and select each declared local Component through the call's `slots` option. The definition reads that choice through `useFactorySlot(name, fallback)`. +A designer may choose a Component Factory for a component or assembly they consider reusable, even with one current caller; unrelated parents, separate packages, and additional injection or local slots are not prerequisites. A one-off component need not use a Factory. Declare its complete type in `SlotFactoryMap`, install the definition with `ctx.slots.registerFactory()`, render occurrences through the injected `renderFactorySlot()`, and select each declared local Component through the call's `slots` option. The definition reads that choice through `useFactorySlot(name, fallback)`. Factory `children` remain ordinary global Slots and must match `SlotMap`, while local `slots` select one Component per occurrence. An occurrence inherits its render-position scope; `renderFactorySlot()` does not accept a Session identity. Shared Store handles use ordinary scope resolution. A Store factory stays lazy until an occurrence first materializes, then creates one handle for that render position and rejects a persistent Store spec whose key would collide across occurrences. diff --git a/packages/client/ui-slots/README.zh.md b/packages/client/ui-slots/README.zh.md index 3bfa4c3aab..b08b278328 100644 --- a/packages/client/ui-slots/README.zh.md +++ b/packages/client/ui-slots/README.zh.md @@ -29,7 +29,7 @@ kind: "package-library" ### 可复用 Component Factory -当一个包定义装配、而互不相关的 parents 需要独立渲染它时,使用 Component Factory。在 `SlotFactoryMap` 中声明完整类型,通过 `ctx.slots.registerFactory()` 安装 definition,通过注入的 `renderFactorySlot()` 渲染 occurrences,并通过调用的 `slots` 选项选择每个已声明的局部 Component。definition 通过 `useFactorySlot(name, fallback)` 读取该选择。 +设计者认为组件或装配可复用时,即使当前只有一个调用方,也可以选择 Component Factory;互不相关的父级、不同的包、额外注入或局部 slot 都不是前提。一次性组件不必使用 Factory。在 `SlotFactoryMap` 中声明完整类型,通过 `ctx.slots.registerFactory()` 安装 definition,通过注入的 `renderFactorySlot()` 渲染 occurrences,并通过调用的 `slots` 选项选择每个已声明的局部 Component。definition 通过 `useFactorySlot(name, fallback)` 读取该选择。 Factory `children` 仍是普通全局 Slots 且必须与 `SlotMap` 匹配,而局部 `slots` 为每个 occurrence 选择一个 Component。occurrence 继承其渲染位置的 scope;`renderFactorySlot()` 不接受 Session identity。共享 Store handle 使用普通 scope 解析。Store factory 保持 lazy,直到 occurrence 首次物化时才为该渲染位置创建一个 handle;若持久化 Store spec 会让 persistence key 在 occurrences 之间冲突,renderer 会拒绝它。 diff --git a/packages/client/ui-slots/package.json b/packages/client/ui-slots/package.json index 7e7e9c28fb..96aa83737a 100644 --- a/packages/client/ui-slots/package.json +++ b/packages/client/ui-slots/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-slots", "description": "Slot registry pure core: typed ordinary Slots and reusable Component Factories, derived props, Store seats, and renderer installation", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-slots/src/index.ts b/packages/client/ui-slots/src/index.ts index 6e94643107..85c7d676cc 100644 --- a/packages/client/ui-slots/src/index.ts +++ b/packages/client/ui-slots/src/index.ts @@ -116,6 +116,8 @@ export interface SlotScopeTargetMap {} export interface SlotEntryDef { kind: SlotKind scope: SlotScope + /** Use span anchors and error placeholders for inline content; omitted uses div. */ + inline?: true owner?: object /** * Optional keyed-entry prop table. A keyed registration contributes one @@ -163,6 +165,8 @@ export interface SlotFactoryDef { export type SlotSpec = { kind: E['kind'] scope: E['scope'] + /** Use span anchors and error placeholders for inline content; omitted uses div. */ + inline?: true } & ('inject' extends keyof E ? E extends { inject: infer Injected extends object } ? { inject: Injected } diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index 5bf8a6dee4..7cd80f156c 100644 --- a/packages/client/ui-subagent/README.i18n.yaml +++ b/packages/client/ui-subagent/README.i18n.yaml @@ -36,8 +36,8 @@ en: b817e9907392f59c zh: e42feb97d572a989 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/composer-election: - en: 1c15af4dd7c0b791 - zh: f789737ab4dd8cb2 + en: 13c33af89ba0942e + zh: 00374c7944728ae2 /deepseek-ai-dsh-client-ui-subagent/further-exploration: en: 1766e9012e307178 zh: f3ee637f5941aae5 diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md index 30cea03817..76e0106c68 100644 --- a/packages/client/ui-subagent/README.md +++ b/packages/client/ui-subagent/README.md @@ -71,6 +71,8 @@ One-shot children always elect a read-only composer. A continuable child elects Unknown-mode catalog rows remain visible and clickable, using the child id when no label is available. Their composer is read-only until child history establishes a supported mode; a read failure is reported in the child conversation. +Lineage-menu highlights follow the [standard menu edge geometry](../../../docs/ui-radius.md#nested-hover); tree disclosure controls retain their separate left gutter. + ----- diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md index 0479608885..6bb19ef56c 100644 --- a/packages/client/ui-subagent/README.zh.md +++ b/packages/client/ui-subagent/README.zh.md @@ -71,6 +71,8 @@ one-shot child 始终选用只读编辑器。可继续 child 仅在其确切 par 模式未知的目录项仍可见、可点击,没有标签时显示子会话 id。读取子历史并确认受支持模式前,输入区保持只读;读取失败在该子会话中报告。 +会话树菜单高亮遵循[标准菜单边缘几何](../../../docs/ui-radius.zh.md#nested-hover);树形展开控件保留独立的左侧空间。 + ----- diff --git a/packages/client/ui-subagent/locale/en.json b/packages/client/ui-subagent/locale/en.json new file mode 100644 index 0000000000..143f7912c3 --- /dev/null +++ b/packages/client/ui-subagent/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-subagent" + } +} diff --git a/packages/client/ui-subagent/locale/zh.json b/packages/client/ui-subagent/locale/zh.json new file mode 100644 index 0000000000..7a018e4d03 --- /dev/null +++ b/packages/client/ui-subagent/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "子智能体会话界面", + "description": "查看和跳转子智能体会话,并支持继续对话和 @ 引用。" + } +} diff --git a/packages/client/ui-subagent/package.json b/packages/client/ui-subagent/package.json index 77876b327d..caf8ee1949 100644 --- a/packages/client/ui-subagent/package.json +++ b/packages/client/ui-subagent/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-subagent", "description": "Subagent conversation catalog, continuation routing UI, and '@' 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": { @@ -74,6 +75,7 @@ "@deepseek-ai/dsh-client-ui-workspace": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css index 19e1378313..4fc2a6f8f5 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css @@ -97,7 +97,7 @@ width: 336px; max-width: min(400px, calc(100vw - 32px)); max-height: min(560px, calc(100vh - 140px)); - padding: 3px; + padding: 4px; overflow: hidden; border-radius: var(--dsw-radius-lg); --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); @@ -146,7 +146,7 @@ min-height: 44px; padding: 6px 7px 6px 9px; border: 0; - border-radius: var(--dsw-radius-lg); + border-radius: var(--dsw-radius-md); background: transparent; color: var(--dsw-alias-label-primary); font-size: 12px; @@ -171,7 +171,7 @@ min-width: 0; margin: -6px -7px -6px; padding: 6px 7px; - border-radius: var(--dsw-radius-lg); + border-radius: var(--dsw-radius-md); } .rowActivitySlot { diff --git a/packages/client/ui-theme/README.i18n.yaml b/packages/client/ui-theme/README.i18n.yaml index b485bb3eb2..d828a43c5a 100644 --- a/packages/client/ui-theme/README.i18n.yaml +++ b/packages/client/ui-theme/README.i18n.yaml @@ -9,17 +9,17 @@ en: 06c7d7624947a72a zh: ac4ca82984564825 /deepseek-ai-dsh-client-ui-theme/summary: - en: caf6bc13d14dd556 - zh: dc516b595733b697 + en: d9832b31c4cb3ca4 + zh: f2ec42bb5ae66188 /deepseek-ai-dsh-client-ui-theme/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-theme/use-this-package: - en: 219aaf8d2eadee85 - zh: f3bc1a5cfb3bfee5 + en: 5a279269e31713c1 + zh: dcd5c31fbdfd63e2 /deepseek-ai-dsh-client-ui-theme/use-this-package/appearance-and-font-size: - en: 5232d0517dfff80b - zh: 72abb7a9c4fa3ebb + en: ebf89ea31593f49c + zh: 06c98ba30ec3bb6b /deepseek-ai-dsh-client-ui-theme/use-this-package/fonts: en: b45d5b48ca799c3a zh: af65514b3759204f @@ -39,11 +39,11 @@ en: bf76e7c34a331595 zh: 5accd0260ef7c61e /deepseek-ai-dsh-client-ui-theme/understand-the-implementation/preference-persistence: - en: 7280ae0a30d26142 - zh: 5f2ba9a479fd4453 + en: b1f0b0bce5e53bae + zh: 26ded298f85834ae /deepseek-ai-dsh-client-ui-theme/further-exploration: - en: 10664fe91f2ca00b - zh: 086f8dffdc223c22 + en: 7d5b953aaeeaf591 + zh: ff4bccb0f196f2b9 /deepseek-ai-dsh-client-ui-theme/model-experience: en: 3120df665299c634 zh: 1d9f365d091d0d2a diff --git a/packages/client/ui-theme/README.md b/packages/client/ui-theme/README.md index 8f57dd4be2..1ed77be835 100644 --- a/packages/client/ui-theme/README.md +++ b/packages/client/ui-theme/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -`dsh-client-ui-theme` lets Web GUI users choose `light`, `dark`, or `system`, and set the font and font size of text, code, and the terminal separately in Settings. A loopback client stores these values in the `ui-theme` settings namespace, which the local provider persists in `$DSH_HOME/cordis.patch.yml` by default. The plugin resolves `system` through `prefers-color-scheme` and publishes immutable `ThemeSnapshot`s; ui-layout applies each snapshot to the document. The package also ships the `--dsw-*` token stylesheets and injects a synchronous bootstrap so the selected palette, font size, and fonts apply before the shell loads. Third-party themes can register alias-token overrides through `ctx.theme`. +`dsh-client-ui-theme` lets Web GUI users choose `light`, `dark`, or `system`, and set the font and font size of text, code, and the terminal separately in Settings. Every authenticated browser stores these values in the `ui-theme` settings namespace, which the local provider persists in `$DSH_HOME/cordis.patch.yml` by default. The plugin resolves `system` through `prefers-color-scheme` and publishes immutable `ThemeSnapshot`s; ui-layout applies each snapshot to the document. The package also ships the `--dsw-*` token stylesheets and injects a synchronous bootstrap so the selected palette, font size, and fonts apply before the shell loads. Third-party themes can register alias-token overrides through `ctx.theme`. ## Table of Contents @@ -25,11 +25,11 @@ English | [中文](README.zh.md) ## Use this package -Users switch the color scheme, font sizes, and fonts from rows in Settings (General section); the choices persist across restarts on a loopback browser. Feature plugins consume the current snapshot through `ctx.theme` and read the `--dsw-*` tokens in CSS; they do not manage theme state themselves. +Users switch the color scheme, font sizes, and fonts from rows in Settings (General section); the choices persist across restarts in every authenticated browser. Feature plugins consume the current snapshot through `ctx.theme` and read the `--dsw-*` tokens in CSS; they do not manage theme state themselves. ### Appearance and font size -The plugin registers Appearance preference cubes and the text font-size stepper in the General section. A More font settings button after the stepper expands a region below it, collapsed on every settings open, with a font row for each of text, code, and the terminal, plus the code and terminal font-size steppers. The text stepper accepts integer values from 10 through 22 px and defaults to 14 px. It changes conversation headings and base text by the same increment, including the user bubble and composer draft; flow-row titles, summaries, and tables follow one step under the body size, while small text keeps a fixed size. The code stepper (10–16 px, default 11) sets the code-block size; inline code stays 1 px larger, and the small tool-output variant uses the same size. The terminal stepper (10–20 px, default 13) sets the sidebar terminal cell font size; changing it keeps the shell and output and refits the grid. Each accepted change writes through the Host settings API. Rapid changes serialize in gesture order with namespace revisions, and a rejected latest write reloads the durable values. Non-loopback pages keep these choices process-local. +The plugin registers Appearance preference cubes and the text font-size stepper in the General section. A More font settings button after the stepper expands a region below it, collapsed on every settings open, with a font row for each of text, code, and the terminal, plus the code and terminal font-size steppers. The text stepper accepts integer values from 10 through 22 px and defaults to 14 px. It changes conversation headings and base text by the same increment, including the user bubble and composer draft; flow-row titles, summaries, and tables follow one step under the body size, while small text keeps a fixed size. The code stepper (10–16 px, default 11) sets the code-block size; inline code stays 1 px larger, and the small tool-output variant uses the same size. The terminal stepper (10–20 px, default 13) sets the sidebar terminal cell font size; changing it keeps the shell and output and refits the grid. Each accepted change writes through the Host settings API. Rapid changes serialize in gesture order with namespace revisions, and a rejected latest write reloads the durable values. ### Fonts @@ -91,7 +91,7 @@ The `--dsw-alias-turn-trigger-*` tokens provide separate resting and hover backg ### Preference persistence -The service provides itself immediately with the schema defaults on a loopback browser, then loads the `ui-theme` namespace and writes each accepted theme, font-size, or font-family change through the Host settings API. Pushed settings changes and reconnects refetch the namespace. While its own writes are pending, the service ignores refetched sections, so an echo of an earlier write cannot revert a later change; it adopts the durable section once the writes settle. Non-loopback pages do not create that Host-backed scope. The persistence boundary is owned by the [Host-backed preferences reference](../ui-settings/README.md). +The service provides itself immediately with the schema defaults, then loads the `ui-theme` namespace and writes each accepted theme, font-size, or font-family change through the Host settings API. Pushed settings changes and reconnects refetch the namespace. While its own writes are pending, the service ignores refetched sections, so an echo of an earlier write cannot revert a later change; it adopts the durable section once the writes settle. The persistence boundary is owned by the [Host-backed preferences reference](../ui-settings/README.md). @@ -106,7 +106,7 @@ These pages cover the layout presenter, the token consumers, and the styling rul - [ui-sidebar](../ui-sidebar/README.md) — a consumer of the scrollbar rebinding contract. - [ui-conversation](../ui-conversation/README.md) — a consumer of `--dsh-scrollbar-width` for the composer seat. - [Web styling](../../../docs/web-styling.md) — the authoritative styling rules for web client components. -- [historical Host-backed preferences](../../../.agents/notes/archived/bug-fix/2026-08-06-host-backed-web-preferences.md) — the persistence boundary decision. +- [Authenticated-browser Host preferences](../../../.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.md) — the persistence policy decision. ----- diff --git a/packages/client/ui-theme/README.zh.md b/packages/client/ui-theme/README.zh.md index e35467355e..bac4c7f3a3 100644 --- a/packages/client/ui-theme/README.zh.md +++ b/packages/client/ui-theme/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -`dsh-client-ui-theme` 让 Web GUI 用户在设置中选择 `light`、`dark` 或 `system`,并分别设置正文、代码与终端的字体和字号。回环客户端把这些值存入 `ui-theme` 设置命名空间,本地提供方默认将其持久化到 `$DSH_HOME/cordis.patch.yml`。插件通过 `prefers-color-scheme` 解析 `system` 并发布不可变的 `ThemeSnapshot`;ui-layout 把每份快照应用到文档。本包还提供 `--dsw-*` token 样式表,并注入同步引导,使所选调色板、字号与字体在外壳加载前生效。第三方主题可通过 `ctx.theme` 注册别名 token 覆盖。 +`dsh-client-ui-theme` 让 Web GUI 用户在设置中选择 `light`、`dark` 或 `system`,并分别设置正文、代码与终端的字体和字号。每个已认证浏览器都把这些值存入 `ui-theme` 设置命名空间,本地提供方默认将其持久化到 `$DSH_HOME/cordis.patch.yml`。插件通过 `prefers-color-scheme` 解析 `system` 并发布不可变的 `ThemeSnapshot`;ui-layout 把每份快照应用到文档。本包还提供 `--dsw-*` token 样式表,并注入同步引导,使所选调色板、字号与字体在外壳加载前生效。第三方主题可通过 `ctx.theme` 注册别名 token 覆盖。 ## 目录 @@ -25,11 +25,11 @@ kind: "package-reference" ## 使用本包 -用户从设置(「通用」分区)的各行中切换配色方案、字号与字体;在回环浏览器上,这些选择都会跨重启持久化。功能插件通过 `ctx.theme` 消费当前快照,并在 CSS 中读取 `--dsw-*` token;它们不自行管理主题状态。 +用户从设置(「通用」分区)的各行中切换配色方案、字号与字体;在每个已认证浏览器中,这些选择都会跨重启持久化。功能插件通过 `ctx.theme` 消费当前快照,并在 CSS 中读取 `--dsw-*` token;它们不自行管理主题状态。 ### 外观与字号 -插件在「通用」分区注册外观偏好方块与正文字号步进器。步进器后的「更多字体设置」按钮在其下方展开一个区域,每次打开设置时均为折叠状态,其中包含正文、代码与终端各自的字体行,以及代码与终端的字号步进器。正文步进器接受 10 至 22 px 的整数,默认值为 14 px。它以相同增量调整会话标题与基础文本,包括用户气泡与 composer 草稿;流内行的标题、摘要与表格跟随比正文低一档的字号,小号文本保持固定字号。代码步进器(10–16 px,默认 11)设置代码块字号;行内代码保持大 1 px,工具输出的小号变体使用相同字号。终端步进器(10–20 px,默认 13)设置侧栏终端的单元格字号;修改后保留 shell 与输出,并重新适配网格。每次通过的变更都经 Host settings API 写入。连续快速变更按操作顺序携带命名空间 revision 串行写入,最新写入被拒时重新加载持久值。非 loopback 页面把这些选择都保留在进程内。 +插件在「通用」分区注册外观偏好方块与正文字号步进器。步进器后的「更多字体设置」按钮在其下方展开一个区域,每次打开设置时均为折叠状态,其中包含正文、代码与终端各自的字体行,以及代码与终端的字号步进器。正文步进器接受 10 至 22 px 的整数,默认值为 14 px。它以相同增量调整会话标题与基础文本,包括用户气泡与 composer 草稿;流内行的标题、摘要与表格跟随比正文低一档的字号,小号文本保持固定字号。代码步进器(10–16 px,默认 11)设置代码块字号;行内代码保持大 1 px,工具输出的小号变体使用相同字号。终端步进器(10–20 px,默认 13)设置侧栏终端的单元格字号;修改后保留 shell 与输出,并重新适配网格。每次通过的变更都经 Host settings API 写入。连续快速变更按操作顺序携带命名空间 revision 串行写入,最新写入被拒时重新加载持久值。 ### 字体 @@ -91,7 +91,7 @@ kind: "package-reference" ### 偏好持久化 -在 loopback 浏览器上,服务先以 schema 默认值立即提供自身,随后加载 `ui-theme` 命名空间,并把每次通过的主题、字号或字体变更经 Host settings API 写入。收到推送的设置变更时或重连后都会重新拉取该命名空间。自身写入尚未完成时,服务忽略重新拉取的配置段,避免较早写入的回显覆盖之后的修改;写入全部完成后再采用持久配置段。非 loopback 页面不会创建该 Host-backed scope。该持久化边界由 [Host 支撑的偏好参考](../ui-settings/README.zh.md) 拥有。 +服务先以 schema 默认值立即提供自身,随后加载 `ui-theme` 命名空间,并把每次通过的主题、字号或字体变更经 Host settings API 写入。收到推送的设置变更时或重连后都会重新拉取该命名空间。自身写入尚未完成时,服务忽略重新拉取的配置段,避免较早写入的回显覆盖之后的修改;写入全部完成后再采用持久配置段。该持久化边界由 [Host 支撑的偏好参考](../ui-settings/README.zh.md) 拥有。 @@ -106,7 +106,7 @@ kind: "package-reference" - [ui-sidebar](../ui-sidebar/README.zh.md)——滚动条重新绑定约定的消费方。 - [ui-conversation](../ui-conversation/README.zh.md)——为 composer 席位消费 `--dsh-scrollbar-width` 的消费方。 - [Web 样式](../../../docs/web-styling.zh.md)——Web 客户端组件的权威样式规则。 -- [历史Host 支撑的偏好](../../../.agents/notes/archived/bug-fix/2026-08-06-host-backed-web-preferences.md)——持久化边界决策。 +- [已认证浏览器 Host 偏好](../../../.agents/notes/implemented/bug-fix/2026-09-15-authenticated-browser-host-preferences.zh.md)——持久化策略决策。 ----- diff --git a/packages/client/ui-theme/locale/en.json b/packages/client/ui-theme/locale/en.json new file mode 100644 index 0000000000..d377165424 --- /dev/null +++ b/packages/client/ui-theme/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-theme" + } +} diff --git a/packages/client/ui-theme/locale/zh.json b/packages/client/ui-theme/locale/zh.json new file mode 100644 index 0000000000..82eccc9825 --- /dev/null +++ b/packages/client/ui-theme/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "界面主题", + "description": "提供浅色、深色和跟随系统的主题设置。" + } +} diff --git a/packages/client/ui-theme/package.json b/packages/client/ui-theme/package.json index 2e43211b92..d66ddbf105 100644 --- a/packages/client/ui-theme/package.json +++ b/packages/client/ui-theme/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-theme", "description": "Theme plugin: Host bootstrap for the pre-plugin palette; DOM-free ThemeRuntime for light/dark/system state; --dsw-* token styles and Appearance settings row", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -24,7 +24,8 @@ }, "./src/*": "./src/*", "./package.json": "./package.json", - "./brand-font.css": "./lib/styles/brand-font.css" + "./brand-font.css": "./lib/styles/brand-font.css", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -61,6 +62,7 @@ "@deepseek-ai/dsh-settings": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/styles", diff --git a/packages/client/ui-theme/tests/apply.client.spec.ts b/packages/client/ui-theme/tests/apply.client.spec.ts index b49e22c548..9bb2ef9db0 100644 --- a/packages/client/ui-theme/tests/apply.client.spec.ts +++ b/packages/client/ui-theme/tests/apply.client.spec.ts @@ -169,7 +169,7 @@ describe('ui-theme apply', () => { await vi.waitFor(() => { expect(b.mutate).toHaveBeenCalledTimes(3) }) }) - it('loads Host settings at boot, refreshes its namespace, and keeps remote browsers process-local', async () => { + it('loads Host settings at boot, refreshes its namespace, and persists for a trusted remote page', async () => { const b = await bench() // The shared mirror read once at bench time; a Host-side change reaches it // through the document invalidation, exactly as production announces one. @@ -192,14 +192,15 @@ describe('ui-theme apply', () => { b.ctx.emit('connection/reset') await vi.waitFor(() => { expect(theme.getTheme().preference).toBe('dark') }) + // A non-loopback page persists through the same path as loopback. const remote = await bench(false) declareItems(remote.slots) await remote.ctx.plugin({ inject: [...inject], apply }).await() const remoteTheme = remote.ctx.get('theme') as ThemeRuntime remoteTheme.setTheme('dark') - await Promise.resolve() - expect(remote.describe).not.toHaveBeenCalled() - expect(remote.mutate).not.toHaveBeenCalled() + await vi.waitFor(() => { + expect(remote.mutate).toHaveBeenCalledWith(THEME_SETTINGS_NAMESPACE, [{ op: 'set', path: ['preference'], value: 'dark' }], 0) + }) }) it('activates before a slow settings refresh and converges when it settles', async () => { diff --git a/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json b/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json index 2f962a9444..274fc5b552 100644 --- a/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json +++ b/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json @@ -5,6 +5,9 @@ "ui-deliverables/src/client/Deliverables.module.css": [ ".fileIcon: border-radius: 10px" ], + "ui-plan/src/client/PlanPreview.module.css": [ + ".cardIcon: border-radius: 10px" + ], "ui-schedule/src/client/ClockPicker.module.css": [ ".option: border-radius: 10px" ], @@ -23,7 +26,6 @@ ".deleteButton: border-radius: 6px" ], "ui-schedule/src/client/ScheduleCreateCard.module.css": [ - ".card: border-radius: 18px", ".leading: border-radius: 10px" ], "ui-schedule/src/client/TaskManagerPage.module.css": [ @@ -42,10 +44,6 @@ ".delivery: border-radius: 8px", ".linkedSession: border-radius: 14px" ], - "ui-schedule/src/client/TaskMenu.module.css": [ - ".list: border-radius: 16px", - ".item: border-radius: 8px" - ], "ui-settings-account/src/client/AccountNotice.module.css": [ ".card: border-radius: 16px" ], diff --git a/packages/client/ui-tool/README.i18n.yaml b/packages/client/ui-tool/README.i18n.yaml index 04158a1ca7..7facde8709 100644 --- a/packages/client/ui-tool/README.i18n.yaml +++ b/packages/client/ui-tool/README.i18n.yaml @@ -21,8 +21,8 @@ en: 2e3c306b13d3bc25 zh: 77127f01763b3976 /deepseek-ai-dsh-client-ui-tool/use-this-package/built-in-views: - en: 4d885fc693b497f4 - zh: 2f68d9ea92f2ebd6 + en: 3643ffbb8cf80e4c + zh: b49654dc3b94b2be /deepseek-ai-dsh-client-ui-tool/understand-the-implementation: en: 00bc7b0c84edc603 zh: 1cfcf5b435248a91 diff --git a/packages/client/ui-tool/README.md b/packages/client/ui-tool/README.md index c8f88095b1..cf1d9d1d78 100644 --- a/packages/client/ui-tool/README.md +++ b/packages/client/ui-tool/README.md @@ -51,7 +51,7 @@ Every registered view receives the explicit `preparing`, `start`, and `result` p File-tool rows prefer a complete `file_path`; other generic rows, including search and unregistered tools, prefer a non-empty `description` before their variant-specific argument fallback. Read `args` during rendering or view construction: a preparing reader grows in place, and only previously observed answer changes trigger subsequent block publication. -This package owns the generic fallback and the built-in shell/pwsh, read, read_image, write/edit, running `str_replace_editor` `create`/`str_replace`, grep/glob, web, todo, question, and PTC dispatch presentations. Structured cards derive directly from first-party raw event fields; Host `presentCall` and `presentResult` values never enter the Client. Running atomic rows share one left-to-right highlight across their titles, separators, summaries, and suffixes, while settled rows stay static. Running and settled foreground standard `bash`/`pwsh` and `terminal_send` calls use terminal cards at the root and in PTC dispatch children, subject to the same argument, result, and error checks. Persistent `bash`/`pwsh` calls use terminal cards only while running. Shell output ending in a recognized spill-policy notice uses expandable generic output in shell rows and generic output in Details; a displaced or omitted exit marker cannot establish success. Settled persistent-shell results stay generic because reset and partial-output diagnostics do not always describe one process exit status; root persistent results are expandable. Background Bash calls expand to their original arguments and job acknowledgement. Their input scrolls horizontally without soft wrapping and remains selectable; only horizontal overflow adds a named keyboard focus target. Inspect is available when provided. The acknowledgement does not report the job's exit status. A native or PTC dispatch failure carrying `AUTO_REVIEW_DENIED` shows the Auto review verdict in its collapsed row and one normalized not-executed reason when expanded; a missing or whitespace-only reason uses localized fallback text. `ui-skill` demonstrates a business-owned registration for `skill`. +This package owns the generic fallback and the built-in shell/pwsh, read, read_image, write/edit, running `str_replace_editor` `create`/`str_replace`, grep/glob, web, todo, question, and PTC dispatch presentations. Structured cards derive directly from first-party raw event fields; Host `presentCall` and `presentResult` values never enter the Client. Running atomic rows share one left-to-right highlight across their titles, separators, summaries, and suffixes, while settled rows stay static. Running and settled foreground standard `bash`/`pwsh` and `terminal_send` calls use terminal cards at the root and in PTC dispatch children, subject to the same argument, result, and error checks. Persistent `bash`/`pwsh` calls use terminal cards only while running. Shell output ending in a recognized spill-policy notice uses expandable generic output in shell rows and generic output in Details; a displaced or omitted exit marker cannot establish success. Settled persistent-shell results stay generic because reset and partial-output diagnostics do not always describe one process exit status; root persistent results are expandable. Valid explicit background `bash`/`pwsh` calls use the terminal Start presentation; a successful launch acknowledgement retains the command and cwd in a static command-only card without output or execution status. Launch failures retain generic arguments and errors, while background `terminal_send` stays generic. Inspect preserves the original arguments and acknowledgement; later job output is not attached to this card ([decision](../../../.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.md)). Expanded terminal commands and background inputs wrap to the available width while preserving authored line breaks and selectable text; terminal output keeps its column-preserving layout. Only horizontal overflow adds a named keyboard focus target. Inspect is available when provided. The acknowledgement does not report the job's exit status. A native or PTC dispatch failure carrying `AUTO_REVIEW_DENIED` shows the Auto review verdict in its collapsed row and one normalized not-executed reason when expanded; a missing or whitespace-only reason uses localized fallback text. `ui-skill` demonstrates a business-owned registration for `skill`. Question rows pair answers with questions by id, using the tool result or the `userQuestions` projection for late replies. An answerable call has a button to reopen its panel. Once a late reply is in the agent Inbox, the row shows its submitted answers; “View answers” expands its read-only transcript while admission is pending. A settled call with answers opens the panel read-only. Closed calls without answers and invalid records offer no button. Cancelled and interrupted rows show their verdict without inventing answers. If no panel provider accepts the button action, it expands the row. Unsupported or ambiguous input falls back to flattened Tool text. diff --git a/packages/client/ui-tool/README.zh.md b/packages/client/ui-tool/README.zh.md index 6b0d28087b..607fae545a 100644 --- a/packages/client/ui-tool/README.zh.md +++ b/packages/client/ui-tool/README.zh.md @@ -51,7 +51,7 @@ owner 载荷为 `ToolCallOwnerProps`:`callId`、`toolName`、`phase` 判别字 文件工具行优先使用完整的 `file_path`;其他通用行(包括搜索和未注册的工具)优先使用非空 `description`,再回退到各自类别的参数摘要。应在渲染或构造视图时读取 `args`:准备态读器原地增长,后续仅在已观察答案变化时重新发布块。 -本包拥有 generic fallback,以及 shell/pwsh、read、read_image、write/edit、运行中的 `str_replace_editor` `create`/`str_replace`、grep/glob、web、todo、question 与 PTC dispatch 的内置展示。结构化卡片直接从第一方原始 event 字段派生;Host `presentCall` 与 `presentResult` 值不会进入 Client。运行中的原子工具行以同一道高光从左到右扫过标题、分隔符、摘要与后缀;已完成行保持静态。运行中与已完成的前台标准 `bash`/`pwsh` 和 `terminal_send` 调用,无论位于根还是 PTC dispatch 子调用中,都在通过相同的参数、结果和错误检查后使用 terminal 卡片。持久 `bash`/`pwsh` 调用仅在运行中使用 terminal 卡片。以已识别的 spill 策略提示结尾的 shell 输出,在 shell 行中使用可展开的 generic 输出,在 Details 中使用 generic 输出;位置被改变或被省略的退出标记无法证明成功。已完成的持久 shell 结果保持 generic 展示,因为 reset 与部分输出诊断不一定描述单个进程的退出状态;根调用的持久 shell 结果可展开。后台 Bash 调用可展开查看原始参数与后台任务回执。输入内容可横向滚动,不自动折行,并可选中;仅横向溢出时添加具名的键盘聚焦目标。提供 Inspect 时也可使用。回执不表示后台任务的退出状态。带有 `AUTO_REVIEW_DENIED` 的原生或 PTC dispatch 失败会在折叠行显示 Auto review 裁决,展开时显示一行归一化后的“未执行”原因;原因缺失或只有空白时使用本地化 fallback 文案。`ui-skill` 展示了业务包自行拥有的 `skill` 注册项。 +本包拥有 generic fallback,以及 shell/pwsh、read、read_image、write/edit、运行中的 `str_replace_editor` `create`/`str_replace`、grep/glob、web、todo、question 与 PTC dispatch 的内置展示。结构化卡片直接从第一方原始 event 字段派生;Host `presentCall` 与 `presentResult` 值不会进入 Client。运行中的原子工具行以同一道高光从左到右扫过标题、分隔符、摘要与后缀;已完成行保持静态。运行中与已完成的前台标准 `bash`/`pwsh` 和 `terminal_send` 调用,无论位于根还是 PTC dispatch 子调用中,都在通过相同的参数、结果和错误检查后使用 terminal 卡片。持久 `bash`/`pwsh` 调用仅在运行中使用 terminal 卡片。以已识别的 spill 策略提示结尾的 shell 输出,在 shell 行中使用可展开的 generic 输出,在 Details 中使用 generic 输出;位置被改变或被省略的退出标记无法证明成功。已完成的持久 shell 结果保持 generic 展示,因为 reset 与部分输出诊断不一定描述单个进程的退出状态;根调用的持久 shell 结果可展开。合法的主动后台 `bash`/`pwsh` 调用使用 terminal Start 展示;成功启动回执后,静态仅命令卡片保留 command 和 cwd,不显示输出或执行状态。启动失败保留通用参数与错误展示,后台 `terminal_send` 仍为 generic。Inspect 保留原始参数及回执,后续 job 输出不接回此卡片([决定](../../../.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.zh.md))。展开的终端命令与后台输入按可用宽度自动折行,保留原有换行和可选文本;终端输出保持按列对齐的排版。仅横向溢出时添加具名的键盘聚焦目标。提供 Inspect 时也可使用。回执不表示后台任务的退出状态。带有 `AUTO_REVIEW_DENIED` 的原生或 PTC dispatch 失败会在折叠行显示 Auto review 裁决,展开时显示一行归一化后的“未执行”原因;原因缺失或只有空白时使用本地化 fallback 文案。`ui-skill` 展示了业务包自行拥有的 `skill` 注册项。 问题行按 id 配对问题与答案;答案来自工具结果,迟到回答则来自 `userQuestions` 投影。可回答的调用提供按钮以重新打开面板。迟到回复进入 agent Inbox 后,问题行显示已提交的答案;等待准入期间,「查看回答」展开只读的行内记录。带有答案的已结算调用则以只读方式打开面板。没有答案的已关闭调用和无效记录不提供按钮。已取消和已中断的行显示裁决,不虚构答案。若面板提供方不接受按钮操作,点击会展开该行。不受支持或含糊的输入回退为压平的工具文本。 diff --git a/packages/client/ui-tool/locale/en.json b/packages/client/ui-tool/locale/en.json new file mode 100644 index 0000000000..a071d79746 --- /dev/null +++ b/packages/client/ui-tool/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-tool" + } +} diff --git a/packages/client/ui-tool/locale/zh.json b/packages/client/ui-tool/locale/zh.json new file mode 100644 index 0000000000..2eb3bc4b7c --- /dev/null +++ b/packages/client/ui-tool/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工具调用展示", + "description": "展示工具调用过程、嵌套关系和各工具的结果界面。" + } +} diff --git a/packages/client/ui-tool/package.json b/packages/client/ui-tool/package.json index 6058888f57..28eaf9342b 100644 --- a/packages/client/ui-tool/package.json +++ b/packages/client/ui-tool/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-tool", "description": "Client Tool call-tree renderer and keyed per-tool presentation slot", - "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": { @@ -80,6 +81,7 @@ "@deepseek-ai/dsh-user-questions": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css b/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css index 5be4d641be..acf675a13e 100644 --- a/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css +++ b/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css @@ -304,6 +304,7 @@ --dsl-terminal-font: var(--dsw-font-markdown-code-block-small); --dsl-terminal-line-height: 18px; --dsl-terminal-output-max-height: 224px; + --dsl-terminal-command-whitespace: pre-wrap; border: 0.5px solid var(--dsw-alias-border-l1); } diff --git a/packages/client/ui-tool/src/client/tool/models/terminal-card-model.ts b/packages/client/ui-tool/src/client/tool/models/terminal-card-model.ts index d6fe0fa3e0..6331f89592 100644 --- a/packages/client/ui-tool/src/client/tool/models/terminal-card-model.ts +++ b/packages/client/ui-tool/src/client/tool/models/terminal-card-model.ts @@ -44,7 +44,7 @@ export interface TerminalCardModel { * The locale-neutral props {@link TerminalBlock} draws. The render site adds * `command` after resolving {@link copy} through its locale seat. */ - card: Pick + card: Pick /** * Verbatim Tool data or semantic `terminal_send` data. Product copy stays * unresolved until a render site supplies its locale seat. @@ -55,7 +55,7 @@ export interface TerminalCardModel { } interface LocalizedTerminalCardModel { - readonly card: Pick + readonly card: Pick readonly description: string | undefined } @@ -288,8 +288,9 @@ function parseExitStatus(text: string): { output: string; exitCode?: number; sig /** * Derive terminal props for supported shell and terminal-send calls, including * nested PTC dispatch calls. Standard shell results parse their final status - * marker; persistent shell results, spill previews, background calls, errors, - * and malformed input use the generic path. {@link isSettledPersistentShellCall} lets that generic + * marker. Successful background shell launches retain only their command after + * settlement; persistent shell results, spill previews, background terminal sends, + * errors, and malformed input use the generic path. {@link isSettledPersistentShellCall} lets that generic * persistent result remain expandable without inventing one process status. * @param block - running or settled Tool block. * @param sessionCwd - original workspace root used only for old results without recorded cwd. @@ -302,7 +303,7 @@ export function terminalCardModel( const parsed = parsedToolCall(block) if (parsed === null) return null const call = shellCall(parsed.name, parsed.args) ?? terminalSendCall(parsed.name, parsed.args) - if (call === null || call.background) return null + if (call === null || (call.kind === 'terminal-send' && call.background)) return null const copy: TerminalCardModel['copy'] = call.kind === 'shell' ? { kind: 'shell', command: call.command, description: call.description } @@ -322,10 +323,14 @@ export function terminalCardModel( exitCode: undefined, signal: undefined, running: true, + ...(call.kind === 'shell' && call.background ? { background: call.background } : {}), }, } } if (block.isError || (call.kind === 'shell' && call.persistent) || isSpilledShellCall(block)) return null + if (call.kind === 'shell' && call.background) { + return { copy, card: { cwd, running: false, background: call.background } } + } const output = singleResultText(block) if (output === undefined) return null const status = call.kind === 'terminal-send' ? { output } : parseExitStatus(output) diff --git a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css index e6ba3f505e..52792b8722 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css +++ b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css @@ -16,6 +16,7 @@ --dsl-terminal-font: var(--dsw-font-markdown-code-block-small); --dsl-terminal-line-height: 18px; --dsl-terminal-output-max-height: 224px; + --dsl-terminal-command-whitespace: pre-wrap; margin: 4px 0 4px 4px; border: 0.5px solid var(--dsw-alias-border-l1); } @@ -78,6 +79,7 @@ } .commandInput { + --dsl-command-whitespace: pre-wrap; color: var(--dsw-alias-label-secondary); } diff --git a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx index f23e369d0b..52ffd1555a 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx @@ -57,9 +57,8 @@ export const BashRow = memo(function BashRow({ toolName, block, sessionId, useSe const status = stateStatus(state, t) const { expanded, toggle: toggleExpand } = useDisclosure() const background = isBackgroundShellCall(block) - // Background launches expose their acknowledgement without assigning the - // job an exit status. Failures, persistent results, and spill previews also - // keep the generic input/output presentation. + // Failed or interrupted background launches retain raw input/output, as do + // other execution failures, persistent results, and spill previews. const genericBody = terminal === null && (model.state === 'error' || isSettledPersistentShellCall(block) || isSpilledShellCall(block) || background) && (model.bodyRaw !== null || model.output !== null) diff --git a/packages/client/ui-tool/tests/terminal-card.client.spec.tsx b/packages/client/ui-tool/tests/terminal-card.client.spec.tsx index a891bad758..24117339cd 100644 --- a/packages/client/ui-tool/tests/terminal-card.client.spec.tsx +++ b/packages/client/ui-tool/tests/terminal-card.client.spec.tsx @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { useDisclosure } from '@deepseek-ai/dsh-client-ui-chat/src/client/chat/use-disclosure.ts' -import { cleanup, fireEvent, render } from '@testing-library/react' +import { act, cleanup, fireEvent, render } from '@testing-library/react' import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { StartedToolCall, ToolResultNode } from '@deepseek-ai/dsh-client-ui-chat/client' @@ -264,8 +264,35 @@ describe('terminalCardModel', () => { }))).not.toBeNull() }) - it('returns null for background, errors, malformed args, unsupported tools, and non-text results', () => { - expect(terminalCardModel(running({ argsRaw: shellArgs({ run_in_background: true }) }))).toBeNull() + it.each(['bash', 'pwsh'])('derives %s background launch commands without treating acknowledgement as output', (name) => { + const argsRaw = shellArgs({ run_in_background: true, workdir: '/requested' }) + for (const parentCallId of [undefined, 'parent']) { + const parent = parentCallId === undefined ? {} : { parentCallId } + expect(terminalCardModel(running({ name, argsRaw, ...parent }))).toEqual({ + copy: { kind: 'shell', command: 'ls -la', description: 'List files' }, + card: { cwd: '/requested', running: true, background: true, output: undefined, exitCode: undefined, signal: undefined }, + }) + for (const content of [[], [{ type: 'text' as const, text: 'started background job bash-1\n[exit code: 7]' }]]) { + const block = settled({ call: { name, argsRaw }, ...parent, meta: { cwd: '/recorded' }, content }) + const model = terminalCardModel(block)! + expect(model).toEqual({ + copy: { kind: 'shell', command: 'ls -la', description: 'List files' }, + card: { cwd: '/recorded', running: false, background: true }, + }) + expect(terminalFailed(model)).toBe(false) + expect(localizeTerminalCardModel(model, t).card).toEqual({ + command: 'ls -la', cwd: '/recorded', running: false, background: true, + }) + expect(terminalCardModel({ ...block, isError: true })).toBeNull() + expect(block.content).toBe(content) + } + } + }) + + it('returns null for background terminal sends, errors, malformed args, unsupported tools, and non-text results', () => { + expect(terminalCardModel(running({ name: 'terminal_send', argsRaw: JSON.stringify({ + sessionId: 'pty-3', text: 'make', run_in_background: true, + }) }))).toBeNull() expect(terminalCardModel(settled({ isError: true }))).toBeNull() expect(terminalCardModel(running({ argsRaw: '{' }))).toBeNull() expect(terminalCardModel(running({ name: 'read' }))).toBeNull() @@ -405,12 +432,13 @@ describe('chat row terminal body', () => { expect(view.getByText(command)).toBeTruthy() }) - it('a non-terminal call keeps the args-JSON text body', () => { + it('a background terminal_send keeps the args-JSON text body', () => { const view = render() + call: { name: 'terminal_send', argsRaw: JSON.stringify({ sessionId: 'pty-3', text: 'make', run_in_background: true }) }, + }))} toolName="terminal_send" />) toggleRow(view) - expect(view.getByText(/"command"/)).toBeTruthy() + expect(view.getByText(/"sessionId"/)).toBeTruthy() + expect(view.container.querySelector('[data-terminal]')).toBeNull() }) it('malformed empty args use the generic output body', () => { @@ -527,45 +555,112 @@ describe('BashRow terminal card', () => { expect(view.container.querySelectorAll('[class*="_ioText_"]')[1]?.textContent).toBe(output) }) - it.each([undefined, 'dispatch-parent'])('expands a background launch and its acknowledgement without reporting a job exit (parent: %s)', (parentCallId) => { - const command = 'pnpm --filter @deepseek-ai/dsh-client-ui-tool run build --watch --verbose' - const args = { command, description: 'Wait', run_in_background: true } - const argsRaw = JSON.stringify(args) + it.each([ + ['bash', undefined], ['bash', 'dispatch-parent'], ['pwsh', undefined], ['pwsh', 'dispatch-parent'], + ] as const)('keeps the %s background command open after launch without reporting job status (parent: %s)', (name, parentCallId) => { + const command = ` node worker.mjs --trace=${'background-worker-'.repeat(24)}\n\tprintf "done"\n` + const argsRaw = shellArgs({ command, description: 'Wait', workdir: '/workspace/app', run_in_background: true }) const inspect = vi.fn() const parent = parentCallId === undefined ? {} : { parentCallId } - const view = render() - const row = view.container.querySelector('[data-sample="bash"]')! + const renderRow = (block: StartedToolCall | ToolResultNode) => { + const props = { ...rowProps(block), toolName: name, inspect } + return name === 'bash' ? : + } + const view = render(renderRow(running({ name, argsRaw, ...parent }))) + const row = view.getByRole('button') expect(view.getByText('Wait')).toBeTruthy() expect(row.getAttribute('aria-expanded')).toBe('false') - - fireEvent.keyDown(row, { key: 'Enter' }) - - expect(row.getAttribute('aria-expanded')).toBe('true') - expect(view.container.querySelector('[data-command-text]')?.textContent) - .toBe(JSON.stringify(args, null, 2)) - expect(view.container.querySelector('[data-command-text]')?.hasAttribute('tabindex')).toBe(false) - expect(view.queryByText('输出')).toBeNull() - expect(view.container.querySelector('[data-terminal]')).toBeNull() + if (name === 'bash') fireEvent.keyDown(row, { key: 'Enter' }) + else fireEvent.click(row) + const terminal = view.container.querySelector('[data-terminal]') + const firstCommand = view.container.querySelector('[data-command-text]') + expect(terminal).not.toBeNull() + expect(runStateOf(view.container)).toBe('ongoing') + expect([...view.container.querySelectorAll('[data-command-text]')].map(line => line.textContent)) + .toEqual(command.slice(0, -1).split('\n')) + expect(view.getByText('app')).toBeTruthy() + expect(view.queryByText('无输出')).toBeNull() + expect(view.queryByRole('button', { name: '复制' })).toBeNull() const acknowledgement = 'started background job job-1' - view.rerender() - + const result = settled({ call: { name, argsRaw }, ...parent, meta: { cwd: '/workspace/app' }, + content: [{ type: 'text', text: acknowledgement }] }) + view.rerender(renderRow(result)) expect(row.getAttribute('aria-expanded')).toBe('true') - expect(view.container.querySelector('[data-command-text]')?.textContent) - .toBe(JSON.stringify(args, null, 2)) - expect(view.getByText(acknowledgement)).toBeTruthy() - expect(view.container.querySelector('[data-terminal], [data-state="done"]')).toBeNull() + expect(view.container.querySelector('[data-terminal]')).toBe(terminal) + expect(view.container.querySelector('[data-command-text]')).toBe(firstCommand) + expect(view.container.querySelector('[data-terminal] [data-state], [data-running]')).toBeNull() + expect(view.queryByText('运行中')).toBeNull() + expect(view.queryByText('已完成')).toBeNull() + expect(view.queryByText('无输出')).toBeNull() + expect(view.queryByText(acknowledgement)).toBeNull() + expect(view.queryByRole('button', { name: '复制' })).toBeNull() + expect(result.call?.argsRaw).toBe(argsRaw) + expect(result.content).toEqual([{ type: 'text', text: acknowledgement }]) fireEvent.click(view.getByRole('button', { name: t('row.inspect') })) expect(inspect).toHaveBeenCalledOnce() fireEvent.click(row) expect(row.getAttribute('aria-expanded')).toBe('false') + if (name === 'bash') fireEvent.keyDown(row, { key: ' ' }) + else fireEvent.click(row) + expect(row.getAttribute('aria-expanded')).toBe('true') + expect(view.container.querySelector('[data-command-text]')?.textContent).toBe(command.split('\n')[0]) expect(view.queryByText(acknowledgement)).toBeNull() }) + it.each([ + ['bash', false], ['bash', true], ['pwsh', false], ['pwsh', true], + ] as const)('keeps %s launch failures on the original generic body (interrupted: %s)', (name, interrupted) => { + const argsRaw = shellArgs({ run_in_background: true }) + const renderRow = (block: StartedToolCall | ToolResultNode) => { + const props = { ...rowProps(block), toolName: name } + return name === 'bash' ? : + } + const view = render(renderRow(running({ name, argsRaw }))) + const row = view.getByRole('button') + fireEvent.click(row) + view.rerender(renderRow(settled({ call: { name, argsRaw }, isError: true, + ...interrupted ? { error: { name: 'Interrupted', code: 'interrupted' } } : {}, + content: [{ type: 'text', text: 'Launch did not finish' }] }))) + expect(row.getAttribute('aria-expanded')).toBe('true') + expect(view.container.querySelector('[data-terminal]')).toBeNull() + expect(view.getByText(/"run_in_background": true/)).toBeTruthy() + expect(view.getAllByText('Launch did not finish').length).toBeGreaterThan(0) + expect(view.container.querySelector(`[data-state="${interrupted ? 'stopped' : 'error'}"]`)).not.toBeNull() + }) + + it.each(['BashRow', 'GenericToolCard'] as const)('%s preserves authored command lines and copies only raw output', async (renderer) => { + const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard') + const writeText = vi.fn().mockResolvedValue(undefined) + const lines = [` node worker.mjs --trace=${'command-token-'.repeat(24)} `, '', '\tprintf "done"'] + const command = `${lines.join('\n')}\n` + const output = ' first\tcolumn\n\nlast \n' + const props = rowProps(settled({ + call: { name: 'bash', argsRaw: shellArgs({ command }) }, + content: [{ type: 'text', text: `${output}\n[exit code: 0]` }], + })) + vi.useFakeTimers() + try { + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + const view = render(renderer === 'BashRow' ? : ) + fireEvent.click(view.container.querySelector('[data-expandable]')!) + expect([...view.container.querySelectorAll('[data-command-text]')].map(line => line.textContent)).toEqual(lines) + expect(view.getByText(' first\tcolumn', RAW)).toBeTruthy() + expect(view.getByText('last ', RAW)).toBeTruthy() + await act(async () => { fireEvent.click(view.getByRole('button', { name: '复制' })) }) + expect(writeText).toHaveBeenCalledOnce() + expect(writeText).toHaveBeenCalledWith(output) + await act(async () => { await vi.runOnlyPendingTimersAsync() }) + } finally { + cleanup() + vi.clearAllTimers() + vi.useRealTimers() + if (clipboard === undefined) Reflect.deleteProperty(navigator, 'clipboard') + else Object.defineProperty(navigator, 'clipboard', clipboard) + } + }) + it('keeps malformed shell arguments collapsed even when background execution is requested', () => { const view = render( null, inspectCall: vi.fn(), forkAt: vi.fn(), loadImage: vi.fn(() => Promise.reject(new Error('not used'))), diff --git a/packages/client/ui-tool/tests/tool-row-styles.client.spec.ts b/packages/client/ui-tool/tests/tool-row-styles.client.spec.ts index 399c588713..33cf6d52be 100644 --- a/packages/client/ui-tool/tests/tool-row-styles.client.spec.ts +++ b/packages/client/ui-tool/tests/tool-row-styles.client.spec.ts @@ -1,9 +1,4 @@ -/** - * The one-line contract of the ToolRow summary line as CSS text. jsdom has no - * layout, so the rendering specs (chat-tool-row.spec.tsx) can pin which spans - * exist but not whether a narrow row still fits on one line; these read the - * declarations the layout depends on. - */ +/** Consumer-local command wrapping and collapsed summary declarations; jsdom has no layout. */ import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -12,15 +7,31 @@ const css = readFileSync(fileURLToPath(new URL('../src/client/tool/components/To /** Declarations only: the sheet's prose names the properties it explains. */ const declarationText = css.replace(/\/\*[\s\S]*?\*\//g, ' ') -function declarations(selector: string): string[] { +function declarations(selector: string, sheet = declarationText): string[] { // Anchored at a rule boundary: an unanchored match would silently read a // compound rule that merely contains the selector (`.root:hover .summarySuffix`) // if one ever lands above the base rule. - const rule = new RegExp(`(?:^|\\})\\s*\\${selector}\\s*\\{([^{}]*)\\}`).exec(declarationText) - if (rule === null) throw new Error(`ToolRow.module.css has no \`${selector}\` rule`) + const rule = new RegExp(`(?:^|\\})\\s*\\${selector}\\s*\\{([^{}]*)\\}`).exec(sheet) + if (rule === null) throw new Error(`Stylesheet has no \`${selector}\` rule`) return (rule[1] ?? '').split(';').map(part => part.trim()).filter(Boolean) } +describe('expanded command wrapping', () => { + it.each([ + ['../src/client/tool/toolviews/bash-sample.module.css', '.terminal', '--dsl-terminal-command-whitespace'], + ['../src/client/tool/toolviews/bash-sample.module.css', '.commandInput', '--dsl-command-whitespace'], + ['../src/client/tool/components/ToolRow.module.css', '.terminalBody', '--dsl-terminal-command-whitespace'], + ] as const)('%s opts %s into command wrapping only', (path, selector, property) => { + const sheet = readFileSync(fileURLToPath(new URL(path, import.meta.url)), 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, ' ') + expect(declarations(selector, sheet)).toContain(`${property}: pre-wrap`) + expect(sheet).not.toContain('--dsl-terminal-line-whitespace') + expect(declarations('.summary', sheet)).toEqual(expect.arrayContaining([ + 'white-space: nowrap', 'overflow: hidden', 'text-overflow: ellipsis', + ])) + }) +}) + describe('ToolRow.module.css summary line', () => { it.each([ ['ToolRow', '../src/client/tool/components/ToolRow.module.css'], diff --git a/packages/client/ui-trajectory/README.i18n.yaml b/packages/client/ui-trajectory/README.i18n.yaml index 153776c82e..6db4c334a3 100644 --- a/packages/client/ui-trajectory/README.i18n.yaml +++ b/packages/client/ui-trajectory/README.i18n.yaml @@ -18,8 +18,8 @@ en: 4bd17d05b8385675 zh: 5174e27f754f2a03 /deepseek-ai-dsh-client-ui-trajectory/use-this-package/inspecting-records: - en: e4ba2d9cab2fb258 - zh: 7db041270420b2ba + en: 130d568589ae108e + zh: 2a52a19499e9c0a7 /deepseek-ai-dsh-client-ui-trajectory/use-this-package/the-timing-overview: en: 0f4ee2189324ac06 zh: 12e76fed22c09bc1 diff --git a/packages/client/ui-trajectory/README.md b/packages/client/ui-trajectory/README.md index eaf559d464..6a9fa9698d 100644 --- a/packages/client/ui-trajectory/README.md +++ b/packages/client/ui-trajectory/README.md @@ -31,7 +31,7 @@ Open the Trajectory tab in the conversation's view ring to inspect agent activit Calls are identified by their recorded tool name. For `run_code`, the row shows the program description and the inspector opens numbered, highlighted source. The Code tab provides wrapping, a `{}` toggle for the original JSON arguments, and exact source copying, including trailing newlines. Copying the original arguments retains their recorded JSON whitespace. Each newly opened code view takes the last wrapping choice; changing it leaves other open views as they are. Output preserves the recorded text, using a tree for complete JSON objects or arrays. Highlighting uses only an unambiguous TypeScript or Python hint in the recorded tool schema; missing or conflicting hints leave plain source. -Selection, timeline navigation, folding, and search cover the React-visible window. Request numbers and cumulative usage cover the complete resident snapshot. Selecting a record opens a local inspector for token usage, duration, Input, Output, Timing, and durable images. Image URLs use the Conversation-owned per-session cache, so Chat and Trajectory share one authorized read per attachment. A user record shows both nonzero image and ordinary-file counts beside its text, including attachment-only records. A standalone compaction request appears chronologically in its own `Between turns` section, while a numbered compaction remains inside its owning turn. +Selection, timeline navigation, folding, and search cover the React-visible window. Request numbers and cumulative usage cover the complete resident snapshot. Selecting a record opens a local inspector for token usage, duration, Input, Output, Timing, and durable images. Image URLs use the Conversation-owned per-session cache, so Chat and Trajectory share one authorized read per attachment. The Trajectory view declares `conversation.trajectory.images`; ledger children call this Slot through the framework `renderSlot` seat, passing image references, display options, and the authorized loader explicitly. Its official `MessageImages` entry calls the shared `conversation.images.content` Factory. A user record shows both nonzero image and ordinary-file counts beside its text, including attachment-only records. A standalone compaction request appears chronologically in its own `Between turns` section, while a numbered compaction remains inside its owning turn. Summary and Preview share one ordered attachment list after the message text, preserving repeated references. Each row shows a contained image thumbnail or file-type icon, the recorded filename (a localized numbered label for unnamed images), and recorded size, type, and image dimensions where available. Zero-byte files retain their size, and truncated filenames expose the full name in a tooltip. Images open the existing lightbox. Raw keeps content-block order and unrendered text, with images and files in initially collapsed disclosures containing their complete recorded fields. diff --git a/packages/client/ui-trajectory/README.zh.md b/packages/client/ui-trajectory/README.zh.md index 2cfc3d7ca3..c37632a926 100644 --- a/packages/client/ui-trajectory/README.zh.md +++ b/packages/client/ui-trajectory/README.zh.md @@ -31,7 +31,7 @@ Trajectory 标签页让你以按轮次组织的事件记录表和交互式时间 调用按已记录的工具名识别。对于 `run_code`,记录行展示程序说明,检查器显示带行号和语法高亮的源码。“代码”页提供换行、查看原始 JSON 参数的 `{}` 切换按钮,以及保留末尾换行的源码原样复制。复制原始参数时保留记录中 JSON 的空白。每个新打开的代码视图采用上次选择的换行状态;切换时,其他已打开视图保持原状。输出保留记录中的文本,完整 JSON 对象或数组使用树形展示。高亮只采用已记录工具 Schema 中明确且无冲突的 TypeScript 或 Python 提示;提示缺失或冲突时显示纯文本源码。 -选择、时间线导航、折叠与搜索只覆盖 React 可见窗口。请求编号与累计用量覆盖完整的驻留快照。选择记录会打开局部检查器,查看 token 用量、耗时、输入、输出、计时与持久保留的图片。图片 URL 使用 Conversation 拥有的逐会话缓存,因此 Chat 与 Trajectory 对每个附件共享一次已授权读取。用户记录会在文本旁同时显示非零的图片与普通文件数量,仅含附件的记录也显示这些数量。独立运行的压缩请求会按时间顺序显示在自己的 `Between turns` 区段中,而带编号的压缩仍位于其所属轮次内。 +选择、时间线导航、折叠与搜索只覆盖 React 可见窗口。请求编号与累计用量覆盖完整的驻留快照。选择记录会打开局部检查器,查看 token 用量、耗时、输入、输出、计时与持久保留的图片。图片 URL 使用 Conversation 拥有的逐会话缓存,因此 Chat 与 Trajectory 对每个附件共享一次已授权读取。Trajectory 视图声明 `conversation.trajectory.images`;账本子组件通过框架 `renderSlot` 席位调用该 Slot,显式传入图片引用、显示参数及授权 loader。官方 `MessageImages` 条目调用共享的 `conversation.images.content` Factory。用户记录会在文本旁同时显示非零的图片与普通文件数量,仅含附件的记录也显示这些数量。独立运行的压缩请求会按时间顺序显示在自己的 `Between turns` 区段中,而带编号的压缩仍位于其所属轮次内。 概述与预览共用正文之后的有序附件列表,保留重复引用。每行展示完整缩放的图片缩略图或文件类型图标、已记录的文件名(未命名图片使用本地化的编号名称),以及可用的已记录大小、类型和图片尺寸。零字节文件保留大小显示,截断的文件名通过提示显示完整名称。图片打开现有灯箱。原始内容保留内容块顺序和未渲染文本,图片与文件使用默认折叠的展开项,包含完整的已记录字段。 diff --git a/packages/client/ui-trajectory/locale/en.json b/packages/client/ui-trajectory/locale/en.json new file mode 100644 index 0000000000..f1f5eb2fb6 --- /dev/null +++ b/packages/client/ui-trajectory/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-trajectory" + } +} diff --git a/packages/client/ui-trajectory/locale/zh.json b/packages/client/ui-trajectory/locale/zh.json new file mode 100644 index 0000000000..3591dbed97 --- /dev/null +++ b/packages/client/ui-trajectory/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "运行轨迹", + "description": "按轮次查看消息、工具调用、耗时和 Token 等运行记录。" + } +} diff --git a/packages/client/ui-trajectory/package.json b/packages/client/ui-trajectory/package.json index f184db05d2..1db5a4637d 100644 --- a/packages/client/ui-trajectory/package.json +++ b/packages/client/ui-trajectory/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-trajectory", "description": "Trajectory event ledger with an interactive timing overview: pure-consumer plugin registering into the conversation ViewMap (no service)", - "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": { @@ -68,10 +69,11 @@ "@deepseek-ai/dsh-client-ui-session": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", - "@tanstack/react-virtual": "^3.14.10", + "@tanstack/react-virtual": "3.14.10", "diff": "^9.0.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx b/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx index 33c8ee1b91..4cf15a0847 100644 --- a/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx +++ b/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx @@ -23,9 +23,10 @@ import { writeClipboard, } from '@deepseek-ai/dsh-client-ui-primitives' import type { JsonTreeLabels, JsonTreeProps, MarkdownLabels } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import { structuredPatch } from 'diff' import type { - AssistantRequestConfig, ConversationPromptSnapshot, RenderMessageImages, + AssistantRequestConfig, ConversationPromptSnapshot, MessageImageLoader, } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { AssistantMetricDetail, TrajectoryCellKind, TrajectoryCellProps, TrajectorySourceBlock, @@ -392,7 +393,9 @@ export interface TrajectoryTableProps { /** Trajectory locale seat. */ t: TrajectoryTranslate /** Slot-backed durable image renderer shared with the Chat gallery. */ - renderImages: RenderMessageImages + renderSlot: PropsRenderSlots<'conversation.trajectory.images'>['renderSlot'] + /** Session-bound loader for durable message image attachments. */ + loadImage: MessageImageLoader /** Session-global request numbers for the request groups visible in this context. */ requestNumbers?: readonly TrajectoryRequestNumber[] /** Grouped records in display order. */ @@ -1238,12 +1241,14 @@ function recordAttachments( function RecordAttachments({ blocks, preview, - renderImages, + renderSlot, + loadImage, t, }: { blocks: readonly TrajectorySourceBlock[] | undefined preview: boolean - renderImages: RenderMessageImages + renderSlot: PropsRenderSlots<'conversation.trajectory.images'>['renderSlot'] + loadImage: MessageImageLoader t: TrajectoryTranslate }) { const attachments = recordAttachments(blocks, t) @@ -1256,10 +1261,11 @@ function RecordAttachments({ {attachments.map(({ block, index, name, metadata }) => (
  • {block.attachment !== undefined - ? renderImages({ + ? renderSlot('conversation.trajectory.images', { images: [{ attachment: block.attachment, label: name }], align: 'start', thumbnail: true, + loadImage, }) : }
    @@ -1474,14 +1480,16 @@ function ToolOutputBlocks({ error, errorDetail, preview, - renderImages, + renderSlot, + loadImage, }: { blocks: readonly TrajectorySourceBlock[] error: boolean /** Failure name and code preserved beside image-only error content. */ errorDetail?: string | undefined preview: boolean - renderImages: RenderMessageImages + renderSlot: PropsRenderSlots<'conversation.trajectory.images'>['renderSlot'] + loadImage: MessageImageLoader }) { return (
    - {renderImages({ images: [{ attachment: block.attachment }], align: 'start' })} + {renderSlot('conversation.trajectory.images', { images: [{ attachment: block.attachment }], align: 'start', loadImage })}
    ) : block.content !== '' @@ -1514,7 +1522,8 @@ function MarkdownRecordContent({ thinkingExpanded, onThinkingExpandedChange, onOpenCall, - renderImages, + renderSlot, + loadImage, t, }: { record: TableRecord @@ -1523,7 +1532,8 @@ function MarkdownRecordContent({ thinkingExpanded: boolean onThinkingExpandedChange: (expanded: boolean) => void onOpenCall: (callId: string) => void - renderImages: RenderMessageImages + renderSlot: PropsRenderSlots<'conversation.trajectory.images'>['renderSlot'] + loadImage: MessageImageLoader t: TrajectoryTranslate }) { if (record.cell.sourceBlocks?.length && record.cell.sourceBlocks.every(block => @@ -1593,7 +1603,8 @@ function MarkdownRecordContent({
    @@ -1623,7 +1634,8 @@ function MarkdownRecordContent({ t={t} /> )} - +
) } @@ -1692,14 +1704,16 @@ function RecordPayload({ record, direction, preview = false, - renderImages, + renderSlot, + loadImage, stringWrapping, t, }: { record: TableRecord direction: 'input' | 'output' preview?: boolean - renderImages: RenderMessageImages + renderSlot: PropsRenderSlots<'conversation.trajectory.images'>['renderSlot'] + loadImage: MessageImageLoader stringWrapping: JsonTreeProps['stringWrapping'] t: TrajectoryTranslate }) { @@ -1740,7 +1754,8 @@ function RecordPayload({ error={error} errorDetail={error ? value : undefined} preview={preview} - renderImages={renderImages} + renderSlot={renderSlot} + loadImage={loadImage} /> ) } @@ -2070,7 +2085,8 @@ function OverviewSection({ export function TrajectoryTable({ t, stringWrapping, - renderImages, + renderSlot, + loadImage, requestNumbers: sessionRequestNumbers, turns, streamingCells = [], @@ -3294,7 +3310,8 @@ export function TrajectoryTable({ > { activateTab('rendered') }}> {selected.cell.inputDetail && ( { activateTab('input') }}> - + )} {selected.cell.outputDetail && ( { activateTab('output') }}> - + )} { activateTab('schema') }}> @@ -3470,7 +3488,8 @@ export function TrajectoryTable({ {!promptSelected && selected !== undefined && activeTab === 'rendered' && ( + ? : )} {!promptSelected && selected !== undefined && activeTab === 'output' && ( selectedProgram === undefined - ? + ? : )} {!promptSelected && selected !== undefined && activeTab === 'schema' && ( diff --git a/packages/client/ui-trajectory/src/client/TrajectoryView.tsx b/packages/client/ui-trajectory/src/client/TrajectoryView.tsx index 0a4b50c9d4..e36386e819 100644 --- a/packages/client/ui-trajectory/src/client/TrajectoryView.tsx +++ b/packages/client/ui-trajectory/src/client/TrajectoryView.tsx @@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { - AssistantBlock, AssistantMessageNode, ConvViewProps, MessageImageLoader, RenderMessageImages, + AssistantBlock, AssistantMessageNode, ConvViewProps, MessageImageLoader, ToolCallBlock, } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { InjectFace, PropsLocale, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' @@ -133,14 +133,10 @@ export function TrajectoryView({ useSession, useTrajectory, useDuration, loadOlder, loadImage, setActualDuration, viewRequest, completeViewRequest, renderSlot, t, jsonStringWrapping, }: ConvViewProps - & PropsRenderSlots<'conversation.trajectory.images'> + & Pick, 'renderSlot'> & InjectFace & PropsLocale<'trajectory'>) { const [collapsedTurns, setCollapsedTurns] = useState>(EMPTY_TURN_IDS) - const renderImages = useCallback( - owner => renderSlot('conversation.trajectory.images', { ...owner, loadImage }), - [loadImage, renderSlot], - ) const [collapsedAssistants, setCollapsedAssistants] = useState>(EMPTY_RECORD_IDS) const [timelineSelection, setTimelineSelection] = useState(null) @@ -554,7 +550,8 @@ export function TrajectoryView({ ...jsonStringWrapping, label: t('record.wrapLines'), }} - renderImages={renderImages} + renderSlot={renderSlot} + loadImage={loadImage} requestNumbers={requestNumbers} turns={timelineTurns} streamingCells={streamingCells} diff --git a/packages/client/ui-trajectory/src/client/index.ts b/packages/client/ui-trajectory/src/client/index.ts index 935a43ff2c..0b438d1aae 100644 --- a/packages/client/ui-trajectory/src/client/index.ts +++ b/packages/client/ui-trajectory/src/client/index.ts @@ -82,9 +82,7 @@ export function apply(ctx: Context): void { order: 10, locale: NS, label: () => t('view.trajectory'), - children: { - 'conversation.trajectory.images': { kind: 'single', scope: 'session' }, - }, + children: { 'conversation.trajectory.images': { kind: 'single', scope: 'session' } }, inject: (sessionId: SessionId): TrajectoryViewInjected => { const session = ctx.sessions.binding(sessionId)?.session if (session === undefined) { diff --git a/packages/client/ui-trajectory/tests/client-bundle.client.spec.ts b/packages/client/ui-trajectory/tests/client-bundle.client.spec.ts index 8a6751993a..6bdac1f28f 100644 --- a/packages/client/ui-trajectory/tests/client-bundle.client.spec.ts +++ b/packages/client/ui-trajectory/tests/client-bundle.client.spec.ts @@ -50,6 +50,7 @@ describe('tsdown client artifact', () => { ['react', await import('react')], ['react/jsx-runtime', await import('react/jsx-runtime')], ['react-dom', await import('react-dom')], + ['@tanstack/react-virtual', await import('@tanstack/react-virtual')], ['@deepseek-ai/dsh-client-store', await import('@deepseek-ai/dsh-client-store')], ['@deepseek-ai/dsh-client-ui-conversation/client', await import('@deepseek-ai/dsh-client-ui-conversation/client')], ['@deepseek-ai/dsh-client-ui-primitives', await import('@deepseek-ai/dsh-client-ui-primitives')], diff --git a/packages/client/ui-trajectory/tests/code-inspector.client.spec.tsx b/packages/client/ui-trajectory/tests/code-inspector.client.spec.tsx index fab29e0637..ab9bd12d41 100644 --- a/packages/client/ui-trajectory/tests/code-inspector.client.spec.tsx +++ b/packages/client/ui-trajectory/tests/code-inspector.client.spec.tsx @@ -26,7 +26,7 @@ function Harness({ cell = CELL, getDefault = () => false, setDefault = () => {} }) { return null} t={t} + renderSlot={() => null} loadImage={async () => 'blob:unused'} t={t} stringWrapping={{ label: 'Wrap lines', getDefault, setDefault }} collapsedTurns={new Set()} onToggleTurn={() => {}} collapsedAssistants={new Set()} onToggleAssistant={() => {}} diff --git a/packages/client/ui-trajectory/tests/table.client.spec.tsx b/packages/client/ui-trajectory/tests/table.client.spec.tsx index 1401a5a67c..188b96bb5f 100644 --- a/packages/client/ui-trajectory/tests/table.client.spec.tsx +++ b/packages/client/ui-trajectory/tests/table.client.spec.tsx @@ -1,17 +1,23 @@ // @vitest-environment jsdom /** Trajectory ledger selection, details, status, and fold behavior. */ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { AttachmentId } from '@deepseek-ai/dsh-attachment' -import type { ComponentProps } from 'react' -import type { RenderMessageImages } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { useState, type ComponentProps, type ReactNode } from 'react' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import type { MessageImageLoader, MessageImagesOwnerProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import { TrajectoryTable as LocalizedTrajectoryTable } from '../src/client/TrajectoryTable.tsx' import { deriveTrajectoryLayout, type TrajectoryTurnModel } from '../src/client/layout.ts' import { trajectoryRecordId } from '../src/client/trajectory-record.ts' import { t, tZh } from './locale.client.ts' -const renderImagesStub: RenderMessageImages = ({ images }) => ( +const loadImage: MessageImageLoader = async () => 'blob:trajectory' +const renderNoImages: PropsRenderSlots<'conversation.trajectory.images'>['renderSlot'] = () => null + +const RecordImages = ({ images }: MessageImagesOwnerProps) => (
{images.map((image, index) => ( (
) +async function imageSlotFixture() { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + await runtime.sessions.add({ id: 'trajectory-images' }) + const session = runtime.sessions.retainFor(runtime.ctx, SessionId('trajectory-images')) + type Seats = PropsRenderSlots<'conversation.trajectory.images'> + const captured: { seats?: Seats; setContent?: (content: ReactNode) => void } = {} + await runtime.root.declare({ 'conversation.trajectory.images': { kind: 'single', scope: 'session' } }, function TestRoot(props) { + const [content, setContent] = useState(null) + captured.seats = props + captured.setContent = setContent + const { SessionProvider } = props + return {content} + }) + runtime.slots.register({ name: 'conversation.trajectory.images' }, RecordImages) + const view = runtime.renderRoot() + const { seats, setContent } = captured + if (seats === undefined || setContent === undefined) throw new Error('trajectory image fixture root did not render') + return { + renderSlot: seats.renderSlot, + render: (content: ReactNode) => { + act(() => { setContent(content) }) + return view + }, + } +} + +type TableProps = ComponentProps + function TrajectoryTable( - props: Omit, 't' | 'renderImages'> - & { renderImages?: RenderMessageImages }, + props: Omit + & Partial>, ) { const inferred: Array[number] & { firstIndex: number }> = [] for (const turn of props.turns) { @@ -58,7 +93,7 @@ function TrajectoryTable( .map(({ firstIndex: _firstIndex, ...request }, index) => ({ ...request, number: index + 1 })) return ( { render( ()} onToggleTurn={() => {}} @@ -963,7 +998,7 @@ describe('TrajectoryTable', () => { }] const table = (status: 'running' | 'complete' | 'error') => ( { it.each([['English', t, 'Attachments', 'Image 1', 'Summary', 'Preview', 'Raw'], ['Chinese', tZh, '附件', '图片 1', '概述', '预览', '原始内容']] as const)( 'keeps mixed attachments ordered and raw fields complete in %s', - (_locale, translate, listLabel, imageLabel, summaryTab, previewTab, rawTab) => { + async (_locale, translate, listLabel, imageLabel, summaryTab, previewTab, rawTab) => { const attachment = { attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), mediaType: 'image/png' as const, @@ -1132,8 +1167,10 @@ describe('TrajectoryTable', () => { partial: null, runningCalls: [], }, translate) - const renderImages = vi.fn(renderImagesStub) - const view = render() + const { render, renderSlot: slotRenderer } = await imageSlotFixture() + const renderSlot = vi.fn((name: 'conversation.trajectory.images', owner: object) => slotRenderer(name, owner as MessageImagesOwnerProps)) + const view = render() fireEvent.click(view.container.querySelector('[data-trajectory-row-key]')!) for (const tab of [summaryTab, previewTab]) { fireEvent.click(screen.getByRole('tab', { name: tab })) @@ -1142,7 +1179,9 @@ describe('TrajectoryTable', () => { expect(names).toEqual([imageLabel, file.name, imageLabel.replace('1', '2')]) expect(within(list).getByText('TXT · 0B')).toBeTruthy() expect(within(list).getAllByText('image/png · 68B · 40 × 800')).toHaveLength(2) - expect(renderImages).toHaveBeenCalledWith({ images: [{ attachment, label: imageLabel }], align: 'start', thumbnail: true }) + expect(renderSlot).toHaveBeenCalledWith('conversation.trajectory.images', { + images: [{ attachment, label: imageLabel }], align: 'start', thumbnail: true, loadImage, + }) } fireEvent.click(screen.getByRole('tab', { name: rawTab })) expect(screen.queryByTestId('record-images')).toBeNull() @@ -1158,15 +1197,16 @@ describe('TrajectoryTable', () => { }, ) - it('renders a tool-result image through the shared gallery in the Result tab', () => { + it('renders a tool-result image through the shared gallery in the Result tab', async () => { + const { render, renderSlot } = await imageSlotFixture() const attachment = { - attachmentId: `sha256:${'b'.repeat(64)}`, + attachmentId: AttachmentId(`sha256:${'b'.repeat(64)}`), mediaType: 'image/png', bytes: 68, width: 320, height: 640, name: 'capture.png', - } as unknown as NonNullable< + } satisfies NonNullable< NonNullable[number]['attachment'] > const turns: readonly TrajectoryTurnModel[] = [{ @@ -1184,7 +1224,7 @@ describe('TrajectoryTable', () => { }], }] - render() + render() fireEvent.click(screen.getByRole('row', { name: /TOOL/ })) fireEvent.click(screen.getByRole('tab', { name: 'Result' })) @@ -1194,15 +1234,16 @@ describe('TrajectoryTable', () => { .toBe(String(attachment.attachmentId)) }) - it('keeps the failure name beside an image-only error result', () => { + it('keeps the failure name beside an image-only error result', async () => { + const { render, renderSlot } = await imageSlotFixture() const attachment = { - attachmentId: `sha256:${'c'.repeat(64)}`, + attachmentId: AttachmentId(`sha256:${'c'.repeat(64)}`), mediaType: 'image/png', bytes: 68, width: 320, height: 320, name: 'failed.png', - } as unknown as NonNullable< + } satisfies NonNullable< NonNullable[number]['attachment'] > const turns: readonly TrajectoryTurnModel[] = [{ @@ -1221,7 +1262,7 @@ describe('TrajectoryTable', () => { }], }] - render() + render() fireEvent.click(screen.getByRole('row', { name: /TOOL/ })) fireEvent.click(screen.getByRole('tab', { name: 'Result' })) diff --git a/packages/client/ui-trajectory/tests/views.client.spec.tsx b/packages/client/ui-trajectory/tests/views.client.spec.tsx index e9557677df..2f5dd4a45e 100644 --- a/packages/client/ui-trajectory/tests/views.client.spec.tsx +++ b/packages/client/ui-trajectory/tests/views.client.spec.tsx @@ -7,7 +7,7 @@ * event ledger with its timing overview, and fiber disposal removes the tab. * Timeline projection and inclusive focus edge cases ride along. */ -import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' +import type { GlobalStandardProps, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { createElement, type ComponentProps, type FC, type ReactNode } from 'react' @@ -245,7 +245,6 @@ function standaloneProps( completeViewRequest: () => {}, // Image seats the outlet would bake: standalone renders omit the gallery. renderSlot: () => null, - SessionProvider: ({ children }) => <>{children}, loadImage: () => Promise.reject(new Error('standalone views load no images')), // The locale seat the outlet would inject for the declared namespace. t: tZh, @@ -387,13 +386,16 @@ function mount(fixture: Awaited>) { const trajectory = injected as TrajectoryViewInjected return { loadOlder: trajectory.loadOlder, + loadImage: trajectory.loadImage, setActualDuration: trajectory.setActualDuration, useDuration: bindSnapshotSelector(trajectory.hooks.duration), t: tZh, } })() : injected - const viewProps: ConvViewProps = { ...owner, ...standardProps } + const viewProps: ConvViewProps & Pick, 'renderSlot'> = { + ...owner, ...standardProps, renderSlot: () => null, + } return ( null, inspectCall: vi.fn(), forkAt: vi.fn(), loadImage: vi.fn(() => Promise.reject(new Error('not used'))), diff --git a/packages/client/ui-workflow-run/locale/en.json b/packages/client/ui-workflow-run/locale/en.json new file mode 100644 index 0000000000..ed487bf62e --- /dev/null +++ b/packages/client/ui-workflow-run/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-workflow-run" + } +} diff --git a/packages/client/ui-workflow-run/locale/zh.json b/packages/client/ui-workflow-run/locale/zh.json new file mode 100644 index 0000000000..319be876a6 --- /dev/null +++ b/packages/client/ui-workflow-run/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工作流运行展示", + "description": "在会话中展示工作流运行记录及其成员详情。" + } +} diff --git a/packages/client/ui-workflow-run/package.json b/packages/client/ui-workflow-run/package.json index 79d2efd4fb..472f10f962 100644 --- a/packages/client/ui-workflow-run/package.json +++ b/packages/client/ui-workflow-run/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-workflow-run", "description": "Durable workflow-run Conversation Node and nested member disclosure for dsh 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": { @@ -44,6 +45,7 @@ "watch": "tsdown --watch" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx b/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx index 18d5ff95b8..3fa00ccc54 100644 --- a/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx +++ b/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx @@ -363,12 +363,10 @@ function panelProps(data: WorkflowRunChatData, sessions = listState(), openSessi useTurnData: () => undefined, useDisclosure: () => { throw new Error('unused') }, useGroupAction: () => { throw new Error('unused') }, - openSkill: vi.fn(), openFile: () => {}, inspectCall: () => {}, forkAt: () => {}, loadImage: () => Promise.reject(new Error('not used')), - renderMessageImages: () => null, fileMentions: () => undefined, openSession, t: makeTranslate(zh), diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index cf3f7896bd..c0e34eb2e3 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -27,8 +27,8 @@ en: 9eab3bfbaf98c987 zh: 54e7e141dae5c9e8 /deepseek-ai-dsh-client-ui-workspace/use-this-package/managing-sessions: - en: cafc87e8e0ac4058 - zh: 4c35bc5bfa24ba6c + en: e96b714aeb6dcd03 + zh: 75b63aa2cafbb57a /deepseek-ai-dsh-client-ui-workspace/use-this-package/pending-interactions: en: 9fb88260380bf093 zh: 3bace2b96ecd4a82 @@ -42,8 +42,8 @@ en: 868904dbfb5713f8 zh: 225906bfef7398bf /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation/session-row-actions: - en: a3b80d0e844d2929 - zh: 85fe5dfb2968b491 + en: 24d196702ca9a5a0 + zh: 351b4896a0217ac1 /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation/session-row-actions/packaged-client-plugin: en: 36934671b80b11ae zh: 8e0aea6162e35e77 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index e1dbed75c4..1616f3a27c 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -51,13 +51,15 @@ Collapsed search is one header action beside the view and add actions: activatin ### Managing sessions -The Session row's Rename action opens a dialog prefilled with the row's display title; confirming an unchanged title is deliberately allowed — it pins the current automatic title against regeneration. Double-clicking a title also opens Rename; for an unarchived Session, the preceding clicks open its conversation. Rename uses a temporary `workspaceOperation` reference and awaits its initial history opening. The row's Fork action reads ordinary cold history normally. When the Host reports that source migration is required, an app-wide Toast offers to open that Session; the action only navigates and does not retry fork. A successful fork uses the source's last completed turn and increments the inherited persisted title through Session Controller without retaining the child, opening its history, or changing selection. Workspace Delete opens a confirmation that states the retention boundary; success removes the group while its Sessions remain under Ungrouped. Pin, Rename, Fork, and Archive are themselves entries of the `sidebar.workspaces.session.menu.item` list (pin and archive also of `sidebar.workspaces.session.row.action`), so a client plugin's action takes whatever position its `order` gives it. +The final built-in item in a Session row's "..." menu is Copy Session ID. It closes the menu and copies the complete ID directly, without opening a dialog. Clipboard success or failure appears in the global toast; a failed copy can be retried from the menu. Copying does not retain the Session, load its history, or call the Host. + +The Session row's Rename action opens a dialog prefilled with the row's display title; confirming an unchanged title is deliberately allowed — it pins the current automatic title against regeneration. Double-clicking a title also opens Rename; for an unarchived Session, the preceding clicks open its conversation. Rename uses a temporary `workspaceOperation` reference and awaits its initial history opening. The row's Fork action reads ordinary cold history normally. When the Host reports that source migration is required, an app-wide Toast offers to open that Session; the action only navigates and does not retry fork. A successful fork uses the source's last completed turn and increments the inherited persisted title through Session Controller without retaining the child, opening its history, or changing selection. Workspace Delete opens a confirmation that states the retention boundary; success removes the group while its Sessions remain under Ungrouped. Pin, Rename, Fork, Archive, and Copy Session ID are themselves entries of the `sidebar.workspaces.session.menu.item` list (pin and archive also of `sidebar.workspaces.session.row.action`), so a client plugin's action takes whatever position its `order` gives it. Archive commits without a confirmation dialog for a quiet Session and retains the Session's account position. A Session with running work is the one case that asks first: the Host refuses the plain archive and names that work, and the sidebar opens a stop-and-archive dialog listing it by family — the turn in progress, running subagents, background jobs, scheduled reminders, each with its labels — with the restore path stated; confirming asks the Host to stop the work the way the stop button does and archives once the archive set is durable, while the stops settle in the background, and cancelling leaves the Session running and visible. View options control visibility through one explicit three-way choice: Hide archived (the default) hides archived Sessions, All conversations (show archived) includes them, and Archived only hides ordinary Sessions and drops Workspaces without an archived Session; in tree grouping, children of a dropped Workspace nest under the nearest shown ancestor. Visible archived rows are grayed and carry an accessible explanation that they cannot be opened until restored; Rename, Fork, and Unarchive remain available. A successful archive shows a notice with an undo action and — while archived rows are hidden — a "filter archived sessions" action that switches the filter to All conversations (show archived); a stop-and-archive shows the same notice under its own wording, and undo restores the Session without resuming the stopped work. Unarchive removes the archive mark without restoring a pin or changing the saved position. An empty list shows a centered glyph-over-text placeholder; the Archived-only view names its own emptiness (No archived sessions yet) and adds a View other sessions text action that switches the filter back to Hide archived. Session update times use the tertiary label color, including on archived rows. A Session title wider than its row is clipped with an ellipsis at rest. Hovering the row scrolls the title to its far edge — the incremented title of a fork, for example — and reveals it without the ellipsis; leaving the row returns the title to its start. -The keyboard reference exposes New Session, Search sessions, Add workspace, Rename session, Fork session, and Archive session. Desktop defaults use the platform's primary modifier, with Mod+K for search; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves these commands unbound until configured. Button tooltips and Session row menus display the effective bindings. Clicking a menu item targets that row; pressing its shortcut targets the main Session. Desktop and Windows/macOS Web rename use Mod+Alt+G, leaving Mod+Shift+R to browser reload. Rename requires a nonblank main Conversation with no modal obscuring it; a retained Session behind another main panel is unavailable. Other Windows and macOS Desktop bindings also execute from terminal input and modal dialogs; other environments follow the command's region and modal restrictions. Search and rename requests belong to this package; input drafts remain in the browser. The directory picker rejects another open while selection or Workspace adoption is pending. Fork captures the retained main-view Session, for which navigation has requested history opening, and keeps automatic migration. It uses the row action's Host operation to select its last completed turn, without loading older Client history. Missing or blank Sessions are unavailable; the Host rejects a source with no completed turn. A rejected shortcut fork preserves the current selection, displays a localized notification, and can be retried; unexpected failures also retain diagnostic logging. +The keyboard reference exposes New Session, Search sessions, Add workspace, Rename session, Fork session, and Archive session. Desktop defaults use the platform's primary modifier, with Mod+K for search; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves these commands unbound until configured. Button tooltips and Session row menus display the effective bindings. Clicking a menu item targets that row; pressing its shortcut targets the main Session. Desktop and Windows/macOS Web rename use Mod+Alt+G, leaving Mod+Shift+R to browser reload. Rename requires a nonblank main Conversation with no modal obscuring it; a retained Session behind another main panel is unavailable. Other Windows and macOS Desktop bindings also execute from terminal input and modal dialogs; other environments follow the command's region and modal restrictions. Search and rename requests belong to this package; input drafts remain in the browser. The directory picker rejects another open while selection or Workspace adoption is pending. Fork captures the retained main-view Session, for which navigation has requested history opening, and keeps automatic migration. It uses the row action's Host operation to select its last completed turn, without loading older Client history. Missing or blank Sessions are unavailable; the Host rejects a source with no completed turn. A rejected shortcut fork preserves the current selection, displays a localized notification, and can be retried; unexpected failures also retain diagnostic logging. Its notification shares the frame-wide Workspace notice channel: only the latest notice remains visible, and removing the browsing region does not dismiss it. ### Pending interactions @@ -97,10 +99,12 @@ Each registration declares a **directory-flow child hole** (`single` kind: `conv ### Session row actions -The Session row's "..." menu and its hover buttons are two `list` slots declared by the WorkspaceBrowser entry: `sidebar.workspaces.session.menu.item` and `sidebar.workspaces.session.row.action`. Every menu row and every hover button is an entry, this package's own actions included: `apply` registers `pin` (menu 100, button 200), `rename` (200), `fork` (300), and `archive` (menu 400, button 100) the way a client plugin registers its actions, so a plugin action lands wherever its `order` says, and reusing a shipped id at another `priority` shadows that action. +The Session row's "..." menu and its hover buttons are two `list` slots declared by the WorkspaceBrowser entry: `sidebar.workspaces.session.menu.item` and `sidebar.workspaces.session.row.action`. Every menu row and every hover button is an entry, this package's own actions included: `apply` registers `pin` (menu 100, button 200), `rename` (200), `fork` (300), `archive` (menu 400, button 100), and `session-id` (450) the way a client plugin registers its actions, so a plugin action lands wherever its `order` says, and reusing a shipped id at another `priority` shadows that action. An entry receives only the row identity (`sessionId`, `displayTitle`) and owns everything else. It reads the Host state it cares about through its own injected hooks (the pin and archive sets, as Sets derived once per Workspace snapshot), decides its own visibility (pin renders nothing on an archived row, because the Host keeps the two sets exclusive), carries its whole behavior in its registration's `inject` face (a pin also fronts the Session in its saved orders; an archive raises the notice), and raises its own surfaces: the rename dialog, the stop-and-archive dialog, and the row-action notice are this package's `shell.overlay` entries, fed by the requests the actions inject. A menu entry renders one `role="menuitem"` button (this package's rows use `MenuItemButton` from ui-primitives, which adds the host styling and `separatorBefore` for a group start; the hairline comes and goes with the row) and dismisses the menu through the slot-level `useMenuOpenState` hook, the menu's own open state bound from the row's render occurrence; a hover button entry renders one icon button, and the strip keeps its clicks from opening the row. The browser passes no action callbacks to its rows; its remaining verbs are the search results' restore button and the title double-click, which raises the same rename request. +The existing notice overlay dispatches `workspace.toast` by notice kind. Keyed registrations inject localized display mappings and their own actions; only archive notices subscribe to the viewing filter. They render the package-local `workspace.toast.content` Factory, which reuses the Toast primitive once for all presentations. The existing notice state, display sequence, latest-notice replacement, and dismissal remain shared; locale or filter changes do not restart the same notice's timer. + #### Packaged client plugin Declare `ui-workspace`, `ui-slots`, `ui-renderer`, `client-locale`, and `ui-primitives` as browser/type development dependencies according to the Client dependency policy. The type-only `ui-workspace/client` import loads this package's `SlotMap` declaration; without it, an independently compiled plugin does not know the slot keys. Keep the Component at module scope and own visible copy in the contributing package's locale namespace. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index a1e1a0fd5a..dd4a932f68 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -51,13 +51,15 @@ kind: "package-reference" ### 管理会话 -Session 行内的 Rename 操作打开一个以该行显示标题预填的对话框;确认未修改的标题是有意允许的——这正是把当前自动标题钉住、不再被重新生成覆盖的手势。双击标题也会打开 Rename;对于未归档 Session,先发生的点击会打开其对话。Rename 使用临时 `workspaceOperation` reference,并等待首次历史打开。行内 Fork 正常读取普通冷历史。Host 报告源会话需要迁移时,应用级 Toast 提供打开该会话的操作;该操作仅导航,不重试 fork。成功的 fork 在源会话最后一个已完成轮次处创建分支,通过 Session Controller 递增继承的持久化标题,不 retain 子会话、不打开其历史,也不改变选择。Workspace 行内的 Delete 操作会打开确认框,说明保留边界;成功后该分组被移除,其 Session 则留在 Ungrouped 下。Pin、Rename、Fork、Archive 本身就是 `sidebar.workspaces.session.menu.item` 列表的条目(pin 与 archive 同时也是 `sidebar.workspaces.session.row.action` 的条目),因此客户端插件的 action 由其 `order` 决定落在哪个位置。 +Session 行“...”菜单的最后一个内置项为“复制 Session ID”。点击后关闭菜单并直接复制完整 ID,不打开对话框。复制成功或失败通过全局提示反馈;失败时可从菜单重试。复制不会 retain 会话、加载历史或调用 Host。 + +Session 行内的 Rename 操作打开一个以该行显示标题预填的对话框;确认未修改的标题是有意允许的——这正是把当前自动标题钉住、不再被重新生成覆盖的手势。双击标题也会打开 Rename;对于未归档 Session,先发生的点击会打开其对话。Rename 使用临时 `workspaceOperation` reference,并等待首次历史打开。行内 Fork 正常读取普通冷历史。Host 报告源会话需要迁移时,应用级 Toast 提供打开该会话的操作;该操作仅导航,不重试 fork。成功的 fork 在源会话最后一个已完成轮次处创建分支,通过 Session Controller 递增继承的持久化标题,不 retain 子会话、不打开其历史,也不改变选择。Workspace 行内的 Delete 操作会打开确认框,说明保留边界;成功后该分组被移除,其 Session 则留在 Ungrouped 下。Pin、Rename、Fork、Archive 和复制 Session ID 本身就是 `sidebar.workspaces.session.menu.item` 列表的条目(pin 与 archive 同时也是 `sidebar.workspaces.session.row.action` 的条目),因此客户端插件的 action 由其 `order` 决定落在哪个位置。 对静止的 Session,Archive 不经确认对话框直接提交,并保留 Session 的记账位置。仍有工作在跑的 Session 是唯一会先询问的情形:Host 拒绝普通归档并列出这些工作,侧栏随即打开"停止并归档"对话框,按族列出——进行中的回合、运行中的子代理、后台任务、定时提醒,各带名称——并写明恢复路径;确认后请 Host 按停止按钮同样的方式停止这些工作,归档集合持久化后即完成归档,停止在后台收敛;取消则让 Session 继续运行并保持可见。视图选项以一组显式三选一控制显隐:隐藏已归档(默认项)隐藏已归档 Session,全部对话(显示已归档)将其纳入列表,仅显示已归档则隐藏普通 Session,并丢弃没有归档 Session 的 Workspace;树形分组下,被丢弃 Workspace 的子级挂到最近一个仍显示的祖先下。可见的归档行置灰,并提供无障碍说明,告知取消归档后才能打开;Rename、Fork 与取消归档仍然可用。归档成功后的提示提供"撤销"动作,并在归档行仍被隐藏时附带"筛选已归档会话"动作,后者直接把筛选切到全部对话(显示已归档);停止并归档显示同样的提示但措辞不同,撤销只恢复 Session,不会让被停止的工作继续。取消归档移除归档标记,但不恢复置顶,也不改变保存的位置。列表为空时显示居中的"图标在上、文字在下"占位;仅显示已归档视图用自己的文案(暂无已归档会话),并附"查看其他会话"文字按钮,点击把筛选切回隐藏已归档。 会话更新时间使用 tertiary 文本色,包括已归档行。标题宽于所在行时,静止状态以省略号裁切。把指针停在行上,标题会滚动到远端——例如 fork 递增后的标题——并在揭示时不显示省略号;指针离开后标题回到开头。 -快捷键速查提供新建会话、搜索会话、添加工作区、重命名会话、分叉会话和归档会话。桌面默认使用平台的主修饰键,搜索为 Mod+K;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 在用户配置前不绑定这些命令。按钮提示和会话行菜单显示当前有效绑定。点击菜单项操作该行,按快捷键操作主会话。Desktop 和 Windows/macOS Web 的重命名均使用 Mod+Alt+G,将 Mod+Shift+R 留给浏览器刷新。重命名要求主区域正在显示非空会话,且没有模态对话框遮挡;切换到其他主面板后,后台保留的会话不可作为重命名目标。其他 Windows 和 macOS Desktop 绑定也可从终端输入区域和模态对话框中执行;其他环境遵循命令的区域和模态限制。搜索和重命名的打开请求归本包管理,输入草稿保留在浏览器中。目录选择或工作区接纳尚未结束时,目录选择器拒绝重复打开。分叉捕获主视图已持有并发起历史打开的会话,保留自动迁移;它使用与行菜单相同的 Host 操作选择最近已完成轮次,不读取更早的 Client 历史。没有会话或会话为空时不可用;没有已完成轮次的源会话由 Host 拒绝。快捷键分叉被拒绝时保留当前选择、显示本地化提示,并允许重试;非预期失败还会保留诊断日志。 +快捷键速查提供新建会话、搜索会话、添加工作区、重命名会话、分叉会话和归档会话。桌面默认使用平台的主修饰键,搜索为 Mod+K;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 在用户配置前不绑定这些命令。按钮提示和会话行菜单显示当前有效绑定。点击菜单项操作该行,按快捷键操作主会话。Desktop 和 Windows/macOS Web 的重命名均使用 Mod+Alt+G,将 Mod+Shift+R 留给浏览器刷新。重命名要求主区域正在显示非空会话,且没有模态对话框遮挡;切换到其他主面板后,后台保留的会话不可作为重命名目标。其他 Windows 和 macOS Desktop 绑定也可从终端输入区域和模态对话框中执行;其他环境遵循命令的区域和模态限制。搜索和重命名的打开请求归本包管理,输入草稿保留在浏览器中。目录选择或工作区接纳尚未结束时,目录选择器拒绝重复打开。分叉捕获主视图已持有并发起历史打开的会话,保留自动迁移;它使用与行菜单相同的 Host 操作选择最近已完成轮次,不读取更早的 Client 历史。没有会话或会话为空时不可用;没有已完成轮次的源会话由 Host 拒绝。快捷键分叉被拒绝时保留当前选择、显示本地化提示,并允许重试;非预期失败还会保留诊断日志。该提示共用应用级 Workspace 通知通道:只显示最新提示,移除浏览区域不会关闭它。 ### 待处理交互 @@ -97,10 +99,12 @@ Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `works ### Session 行 action -Session 行的 "..." 菜单和行尾悬停按钮是 WorkspaceBrowser 注册项声明的两个 `list` slot:`sidebar.workspaces.session.menu.item` 与 `sidebar.workspaces.session.row.action`。每一个菜单行、每一个悬停按钮都是条目,本包自己的 action 也不例外:`apply` 以客户端插件注册自己 action 的同一方式注册 `pin`(菜单 100、按钮 200)、`rename`(200)、`fork`(300)、`archive`(菜单 400、按钮 100),因此插件 action 落在其 `order` 所指的位置,以另一个 `priority` 复用内置 id 则遮蔽该 action。 +Session 行的 "..." 菜单和行尾悬停按钮是 WorkspaceBrowser 注册项声明的两个 `list` slot:`sidebar.workspaces.session.menu.item` 与 `sidebar.workspaces.session.row.action`。每一个菜单行、每一个悬停按钮都是条目,本包自己的 action 也不例外:`apply` 以客户端插件注册自己 action 的同一方式注册 `pin`(菜单 100、按钮 200)、`rename`(200)、`fork`(300)、`archive`(菜单 400、按钮 100)和 `session-id`(450),因此插件 action 落在其 `order` 所指的位置,以另一个 `priority` 复用内置 id 则遮蔽该 action。 条目只接收行身份(`sessionId`、`displayTitle`),其余一切自己负责:用自己注入的 hook 读自己关心的 Host 状态(置顶与归档集合,以每次 Workspace 快照只派生一次的 Set 形式),自己决定是否显示(Host 规定归档与置顶互斥,所以 pin 在归档行上不渲染),整套行为放在注册项自己的 `inject` face 里(置顶成功后顺带把会话推到保存顺序最前,归档成功后发提示),浮层也自己带——重命名对话框、停止并归档对话框和行 action 的提示是本包注册在 `shell.overlay` 的条目,由 action 注入的请求驱动。菜单条目渲染一个 `role="menuitem"` 的按钮(本包自己的行用 ui-primitives 的 `MenuItemButton`,它带宿主样式,开启新分组的行加 `separatorBefore`,分隔线随行一起出现和消失),并通过 slot 级 `useMenuOpenState` hook(菜单自身的打开状态,从该行的渲染出现处绑定)关闭菜单;悬停按钮条目渲染一个图标按钮,按钮条会拦住点击、不让它打开该行。browser 不再向行传任何 action 回调,它剩下的动作只有搜索结果里的恢复按钮和标题双击,后者发出的是同一个重命名请求。 +现有通知浮层按通知 kind 分派 `workspace.toast`。各 keyed 注册注入本地化展示映射与自己的操作,只有归档通知订阅查看筛选状态。它们渲染包内的 `workspace.toast.content` Factory,所有展示共用一处 Toast primitive。现有通知状态、显示序号、最新提示替换及关闭逻辑仍共享;语言或筛选变化不会重新启动同一条提示的计时。 + #### 打包客户端插件 按照 Client 依赖规则,将 `ui-workspace`、`ui-slots`、`ui-renderer`、`client-locale` 与 `ui-primitives` 声明为浏览器/类型开发依赖。纯类型的 `ui-workspace/client` import 会加载本包的 `SlotMap` 声明;缺少该 import 时,独立编译的插件不会知道这些 slot key。Component 保持模块级稳定身份;用户可见文案由贡献包自己的 locale namespace 持有。 diff --git a/packages/client/ui-workspace/locale/en.json b/packages/client/ui-workspace/locale/en.json new file mode 100644 index 0000000000..077d51787e --- /dev/null +++ b/packages/client/ui-workspace/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-workspace" + } +} diff --git a/packages/client/ui-workspace/locale/zh.json b/packages/client/ui-workspace/locale/zh.json new file mode 100644 index 0000000000..d61486204e --- /dev/null +++ b/packages/client/ui-workspace/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工作区选择界面", + "description": "在侧栏和新会话页面中选择工作区。" + } +} diff --git a/packages/client/ui-workspace/package.json b/packages/client/ui-workspace/package.json index f062d8392c..5c74cd71b7 100644 --- a/packages/client/ui-workspace/package.json +++ b/packages/client/ui-workspace/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-workspace", "description": "Workspace picker plugin: one WorkspacePicker registered into the sidebar and empty-state workspace 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": { @@ -82,6 +83,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-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index 568368dc63..d00b3658d8 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -26,8 +26,8 @@ * row of a Session's "..." menu is an entry of * `sidebar.workspaces.session.menu.item`, and every hover button at the row's * end is an entry of `sidebar.workspaces.session.row.action`. The shipped - * actions — pin, rename, fork, archive — are ordinary entries this package - * registers from `apply`, each carrying its own behavior in its own inject + * actions — pin, rename, fork, archive, copy ID — are ordinary entries + * registered from `apply`, each carrying its own behavior in its own inject * face and reading its own Host state through hooks that face injects, so a * client plugin's action lands beside them by `order` and needs nothing from * the browser beyond the row identity. @@ -53,6 +53,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ShortcutCatalogEntry } from '@deepseek-ai/dsh-client-shortcuts/client' import type { WorkspaceShortcutState } from '../shortcuts.ts' import type { StartSessionOptions } from '../navigation.ts' +import type {} from './toast.ts' import type { createWorkspaceViewStore } from '../stores.ts' /** @@ -136,8 +137,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { /** * The rows of one Session's "..." menu, in ascending `order`. ui-workspace * registers the shipped rows here — `pin` (100), `rename` (200), `fork` - * (300), `archive` (400) — so a plugin row is placed by its own `order` - * among them. Use a package-namespaced `id`; reusing a shipped id at + * (300), `archive` (400), and `session-id` (450) — so a plugin row is placed + * by its own `order` among them. Use a package-namespaced `id`; reusing a shipped id at * another `priority` shadows that row. Each entry renders one * `role="menuitem"` `
) } diff --git a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx index b082a36f29..fae564a45b 100644 --- a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx +++ b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx @@ -1,92 +1,14 @@ -/** - * The `shell.overlay` entry for Workspace and Session notices. - * One notice is visible at a time; a parent rerender does not extend its hold. - */ -import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives' -import { assertNever } from '@deepseek-ai/dsh-util-values' -import type { RowToastProps, RowToastState } from '../contract/slots.ts' +/** The existing overlay dispatches the latest Workspace notice to its keyed presentation. */ +import type { RowToastProps } from '../contract/slots.ts' +import type {} from '../contract/toast.ts' /** - * Hold for the notices that take longer to read than a one-line warning: the - * archive and fork recovery actions, and a refused Session creation quoting the Host's reason. + * Dispatch the current notice without interpreting its business payload. + * @param props - Current notice, dismissal, and the declared keyed renderer. + * @returns The selected notice presentation, or nothing. */ -const LONG_TOAST_HOLD_MS = 6000 - -/** - * Render an operation notice, retaining recovery actions for six seconds. - * @param props - notice and viewing sources, dismissal and recovery callbacks, and localized copy. - * @returns the notice on display, or null. - */ -export function RowActionToast({ useToast, useStore, dismissToast, undoArchive, showArchived, openForkSource, t }: RowToastProps) { - const toast = useToast(current => current) - const archivedRowsVisible = useStore(state => (state.archivedFilter ?? 'default') !== 'default') - if (toast === null) return null - if (toast.kind === 'forkRequiresOpen') { - return ( - } - holdMs={LONG_TOAST_HOLD_MS} - actions={[{ - label: t('toast.openForkSource'), - onClick: () => { dismissToast(); openForkSource(toast.sessionId) }, - }]} - onDone={dismissToast} - /> - ) - } - if (toast.kind === 'archived' || toast.kind === 'stoppedAndArchived') { - const { sessionId } = toast - return ( - { dismissToast(); undoArchive(sessionId) } }, - ...archivedRowsVisible ? [] : [ - { prefix: t('toast.archivedOr'), label: t('toast.archivedFilter'), onClick: () => { dismissToast(); showArchived() } }, - ], - ]} - onDone={dismissToast} - /> - ) - } - if (toast.kind === 'createFailed') { - return ( - } - holdMs={LONG_TOAST_HOLD_MS} - onDone={dismissToast} - /> - ) - } - return ( - } - onDone={dismissToast} - /> - ) -} - -/** The copy of one plain warning, keyed by the notice kind the union closes over. */ -function plainNoticeText( - toast: Exclude, - t: RowToastProps['t'], -): string { - switch (toast.kind) { - case 'pinFailed': return t('toast.pinFailed') - case 'unpinFailed': return t('toast.unpinFailed') - case 'defaultWorkspaceFailed': return t('defaultWorkspace.failed') - case 'archivedNotOpenable': return t('toast.archivedNotOpenable') - /* v8 ignore next 2 -- closed-union backstop; only reached if a notice kind is forged */ - default: - return assertNever(toast) - } +export function RowActionToast({ useToast, dismissToast, renderSlot }: RowToastProps) { + const notice = useToast(current => current) + if (notice === null) return null + return renderSlot('workspace.toast', { ...notice, dismissToast }, { entryKey: notice.kind }) } diff --git a/packages/client/ui-workspace/src/client/session-actions/SessionId.tsx b/packages/client/ui-workspace/src/client/session-actions/SessionId.tsx new file mode 100644 index 0000000000..da292e67b3 --- /dev/null +++ b/packages/client/ui-workspace/src/client/session-actions/SessionId.tsx @@ -0,0 +1,20 @@ +/** Copy the row's Session ID without opening its history. */ +import { IconCopyOutlineRegular, MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' +import type { SessionIdInjected, SessionMenuItemProps } from '../contract/slots.ts' + +/** + * Copy the complete ID after dismissing the row menu. + * @param props - Row identity, menu dismissal, clipboard action, and locale. + * @returns The final built-in menu item. + */ +export function SessionIdMenuItem({ sessionId, useMenuOpenState, copySessionId, t }: SessionMenuItemProps) { + const [, setMenuOpen] = useMenuOpenState() + return ( + } onSelect={() => { + setMenuOpen(false) + void copySessionId(sessionId) + }}> + {t('menu.sessionId')} + + ) +} diff --git a/packages/client/ui-workspace/src/client/shortcuts.ts b/packages/client/ui-workspace/src/client/shortcuts.ts index 52296c1434..ed9852b81a 100644 --- a/packages/client/ui-workspace/src/client/shortcuts.ts +++ b/packages/client/ui-workspace/src/client/shortcuts.ts @@ -13,7 +13,6 @@ export interface WorkspaceShortcutState { readonly addRequested: boolean readonly directoryBusy: boolean readonly renameTarget: { readonly sessionId: SessionId; readonly currentTitle: string } | null - readonly forkError: { readonly reason: 'unavailable' | 'failed'; readonly seq: number } | null } interface WorkspaceShortcutControls { @@ -24,8 +23,6 @@ interface WorkspaceShortcutControls { directoryBusy: (busy: boolean) => void rename: (sessionId: SessionId, currentTitle: string) => void closeRename: () => void - forkFailed: (reason: 'unavailable' | 'failed') => void - dismissForkError: () => void } /** @@ -34,9 +31,8 @@ interface WorkspaceShortcutControls { */ export function createWorkspaceShortcutControls(): WorkspaceShortcutControls { const state = createSnapshotStore({ - searchRequest: 0, addRequested: false, directoryBusy: false, renameTarget: null, forkError: null, + searchRequest: 0, addRequested: false, directoryBusy: false, renameTarget: null, }) - let forkErrorSeq = 0 return { state, search: () => { state.set({ ...state.getSnapshot(), searchRequest: state.getSnapshot().searchRequest + 1 }) }, @@ -47,11 +43,6 @@ export function createWorkspaceShortcutControls(): WorkspaceShortcutControls { state.set({ ...state.getSnapshot(), renameTarget: { sessionId, currentTitle } }) }, closeRename: () => { state.set({ ...state.getSnapshot(), renameTarget: null }) }, - forkFailed: (reason) => { - forkErrorSeq += 1 - state.set({ ...state.getSnapshot(), forkError: { reason, seq: forkErrorSeq } }) - }, - dismissForkError: () => { state.set({ ...state.getSnapshot(), forkError: null }) }, } } @@ -62,12 +53,14 @@ export function createWorkspaceShortcutControls(): WorkspaceShortcutControls { * @param navigation - session creation and forking from the pointer controls' navigation service. * @param controls - browser-owned opening requests. * @param archiveSession - shared archive action, including running-work confirmation and notices. + * @param reportForkFailure - publish a classified failure through the frame-wide notice channel. */ export function installWorkspaceShortcuts( ctx: Context, navigation: Pick, controls: ReturnType, archiveSession: (sessionId: SessionId) => void, + reportForkFailure: (reason: 'unavailable' | 'failed') => void, ): void { const t = ctx.locale.bind('workspace') const current = () => Object.values(ctx.sessions.list.getSnapshot().byId) @@ -110,7 +103,7 @@ export function installWorkspaceShortcuts( // Client plugin bundles do not share error-class identity. const unavailable = error instanceof Error && error.name === 'SessionForkError' && (error as SessionForkError).rpcError.code === 'session/fork-unavailable' - controls.forkFailed(unavailable ? 'unavailable' : 'failed') + reportForkFailure(unavailable ? 'unavailable' : 'failed') if (!unavailable) console.warn('session fork rejected:', error) }) } } diff --git a/packages/client/ui-workspace/src/client/toast/Toast.tsx b/packages/client/ui-workspace/src/client/toast/Toast.tsx new file mode 100644 index 0000000000..fea6c6d109 --- /dev/null +++ b/packages/client/ui-workspace/src/client/toast/Toast.tsx @@ -0,0 +1,44 @@ +/** One presentation Factory and the adapters for keyed Workspace notices. */ +import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { ArchiveToastEntryProps, ToastEntryProps, WorkspaceToastProps } from '../contract/toast.ts' + +/** + * Render one notice using the shared Factory. + * @param props - Keyed payload, injected display mapping, locale, and Factory renderer. + * @returns The shared Toast occurrence. + */ +export function ToastEntry

>(props: ToastEntryProps

) { + const { dismissToast, display, t, renderFactorySlot, seq } = props + return renderFactorySlot('workspace.toast.content', { ...display(props, t, dismissToast), seq, onDone: dismissToast }) +} + +/** + * Keep the archive filter action reactive without subscribing unrelated notices. + * @param props - Archive notice, display mapping, and the existing viewing store. + * @returns The shared Toast occurrence with its current actions. + */ +export function ArchiveToastEntry(props: ArchiveToastEntryProps) { + const { dismissToast, display, filterAction, useStore, t, renderFactorySlot, seq } = props + const archivedVisible = useStore(state => (state.archivedFilter ?? 'default') !== 'default') + const fields = display(props, t, dismissToast) + return renderFactorySlot('workspace.toast.content', { + ...fields, + actions: [...fields.actions ?? [], ...archivedVisible ? [] : [filterAction(t, dismissToast)]], + seq, + onDone: dismissToast, + }) +} + +/** + * Present plain display data with the shared primitive's timing and portal. + * @param props - Localized display fields, display identity, and dismissal. + * @returns One Toast, remounted only for a new display identity. + */ +export function WorkspaceToast({ seq, text, tone, holdMs, actions, onDone }: WorkspaceToastProps) { + return } : {}} + {...holdMs === undefined ? {} : { holdMs }} + {...actions === undefined ? {} : { actions }} /> +} diff --git a/packages/client/ui-workspace/src/client/toast/register.ts b/packages/client/ui-workspace/src/client/toast/register.ts new file mode 100644 index 0000000000..efadbf89c2 --- /dev/null +++ b/packages/client/ui-workspace/src/client/toast/register.ts @@ -0,0 +1,104 @@ +/** Business-owned mappings into the keyed Workspace Toast slot. */ +import type { Context } from '@deepseek-ai/cordis' +import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { RowToastActions, WorkspaceViewStoreHandle } from '../contract/slots.ts' +import type { ArchiveToastInjected, ToastDisplayInjected } from '../contract/toast.ts' +import { ArchiveToastEntry, ToastEntry, WorkspaceToast } from './Toast.tsx' + +/** Register notice presentations with their business-owned display fields and actions. + * @param ctx - Workspace plugin context. + * @param viewStore - Viewing store, read only by archive notices. + * @param actions - Archive and source-opening callbacks. + */ +export function registerToasts( + ctx: Context, + viewStore: WorkspaceViewStoreHandle, + actions: Pick, +): void { + const archiveFilterAction: ArchiveToastInjected['filterAction'] = (t, dismiss) => ({ + prefix: t('toast.archivedOr'), label: t('toast.archivedFilter'), + onClick: () => { dismiss(); actions.showArchived() }, + }) + ctx.slots.registerFactory({ name: 'workspace.toast.content', scope: 'root' }, WorkspaceToast) + ctx.slots.inject('workspace.toast', function* () { + yield ctx.slots.register({ + name: 'workspace.toast', key: 'sessionIdCopied', locale: 'workspace', + inject: (): ToastDisplayInjected<'sessionIdCopied'> => ({ + display: (_notice, t) => ({ text: t('toast.sessionIdCopied'), tone: 'success' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'sessionIdCopyFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'sessionIdCopyFailed'> => ({ + display: (_notice, t) => ({ text: t('toast.sessionIdCopyFailed'), tone: 'warning' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'pinFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'pinFailed'> => ({ + display: (_notice, t) => ({ text: t('toast.pinFailed'), tone: 'warning' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'unpinFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'unpinFailed'> => ({ + display: (_notice, t) => ({ text: t('toast.unpinFailed'), tone: 'warning' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'archivedNotOpenable', locale: 'workspace', + inject: (): ToastDisplayInjected<'archivedNotOpenable'> => ({ + display: (_notice, t) => ({ text: t('toast.archivedNotOpenable'), tone: 'warning' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'defaultWorkspaceFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'defaultWorkspaceFailed'> => ({ + display: (_notice, t) => ({ text: t('defaultWorkspace.failed'), tone: 'warning' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'shortcutForkFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'shortcutForkFailed'> => ({ + display: (notice, t) => ({ + text: t(notice.reason === 'unavailable' ? 'shortcut.noCompletedTurn' : 'shortcut.forkFailed'), tone: 'plain', + }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'createFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'createFailed'> => ({ + display: (notice, t) => ({ text: t('toast.createFailed', { message: notice.message }), tone: 'warning', holdMs: 6000 }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'forkRequiresOpen', locale: 'workspace', + inject: (): ToastDisplayInjected<'forkRequiresOpen'> => ({ + display: (notice, t, dismiss) => ({ + text: t('toast.forkRequiresOpen'), tone: 'warning', holdMs: 6000, + actions: [{ label: t('toast.openForkSource'), onClick: () => { dismiss(); actions.openForkSource(notice.sessionId) } }], + }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'archived', locale: 'workspace', store: viewStore, + inject: (): ArchiveToastInjected => ({ + display: (notice, t, dismiss) => ({ + text: t('toast.archived'), tone: 'success', holdMs: 6000, + actions: [{ label: t('toast.archivedUndo'), onClick: () => { dismiss(); actions.undoArchive(notice.sessionId) } }], + }), + filterAction: archiveFilterAction, + }), + }, ArchiveToastEntry) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'stoppedAndArchived', locale: 'workspace', store: viewStore, + inject: (): ArchiveToastInjected => ({ + display: (notice, t, dismiss) => ({ + text: t('toast.stoppedAndArchived'), tone: 'success', holdMs: 6000, + actions: [{ label: t('toast.archivedUndo'), onClick: () => { dismiss(); actions.undoArchive(notice.sessionId) } }], + }), + filterAction: archiveFilterAction, + }), + }, ArchiveToastEntry) + }) +} diff --git a/packages/client/ui-workspace/tests/apply.client.spec.ts b/packages/client/ui-workspace/tests/apply.client.spec.ts index 0e1024f119..af8b5622ba 100644 --- a/packages/client/ui-workspace/tests/apply.client.spec.ts +++ b/packages/client/ui-workspace/tests/apply.client.spec.ts @@ -8,7 +8,8 @@ import { SessionForkError } from '@deepseek-ai/dsh-api-session-controller/client import type { WorkspaceId, WorkspaceSnapshot, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' -import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import type { PropsRenderSlots, StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import type { ShortcutCommand } from '@deepseek-ai/dsh-client-shortcuts/client' import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { apply, inject } from '@deepseek-ai/dsh-client-ui-workspace/client' @@ -16,7 +17,7 @@ import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from '@deepsee import { type ArchiveSessionInjected, type ForkSessionInjected, menuOpenStateFactory, type PinSessionInjected, type RenameSessionInjected, type RowToastInjected, type SessionArchiveConfirmInjected, type SessionRenameDialogInjected, - type WorkspaceViewStoreHandle, + type SessionIdInjected, type WorkspaceViewStoreHandle, } from '../src/client/contract/slots.ts' import { WorkspaceBrowser } from '../src/client/rows/WorkspaceBrowser.tsx' import { ArchiveSessionMenuItem, ArchiveSessionRowButton, SessionArchiveConfirmDialog } from '../src/client/session-actions/ArchiveSession.tsx' @@ -24,6 +25,8 @@ import { ForkSessionMenuItem } from '../src/client/session-actions/ForkSession.t import { PinSessionMenuItem, PinSessionRowButton } from '../src/client/session-actions/PinSession.tsx' import { RenameSessionMenuItem, SessionRenameDialog } from '../src/client/session-actions/RenameSession.tsx' import { RowActionToast } from '../src/client/session-actions/RowActionToast.tsx' +import type { ArchiveToastInjected, ToastDisplayInjected } from '../src/client/contract/toast.ts' +import { SessionIdMenuItem } from '../src/client/session-actions/SessionId.tsx' import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx' import { FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts' import { UNGROUPED_KEY } from '../src/client/tree.ts' @@ -53,7 +56,14 @@ const workspaceState = ( async function bench() { const ctx = new Context() - ctx.provide('shortcuts', { register: () => () => {}, catalog: createSnapshotStore([]) }) + const commands = new Map() + ctx.provide('shortcuts', { + register: (command: ShortcutCommand) => { + commands.set(command.id, command) + return () => { commands.delete(command.id) } + }, + catalog: createSnapshotStore([]), + }) ctx.provide('uiConversation', {}) await ctx.plugin(SlotRegistry).await() const create = vi.fn(async (input: { name: string } | { path: string }) => ({ @@ -148,7 +158,7 @@ async function bench() { locale.setLocale('zh') ctx.provide('locale', locale) return { - ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, + ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, commands, retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory, pinSession, unpinSession, workspacesSubscribe, initializeDefault, history, scope, sessionOf, setWorkspaces: (snapshot: WorkspaceSnapshot): void => { workspaceSnapshot = snapshot }, @@ -170,6 +180,11 @@ function declare(slots: SlotRegistry, ...names: HoleName[]): () => void { return slots.register({ name: 'root', children } as never, () => null) } +/** Own the sidebar declaration independently of the frame-wide overlay in lifecycle tests. */ +function SidebarDeclarationOwner({ renderSlot }: PropsRenderSlots<'sidebar.workspaces'>) { + return renderSlot('sidebar.workspaces', { wide: true, expandSidebar: () => {} }) +} + /** The one entry registered under `id` in a list. */ function entry(slots: SlotRegistry, key: RowListName, id: string): StoredEntry { const found = slots.entries(key).find(candidate => candidate.options.id === id) @@ -234,7 +249,7 @@ describe('ui-workspace apply', () => { await Promise.resolve() expect(after.slots.entries('conversation.hero.workspace')[0]!.component).toBe(WorkspacePicker) // The row actions follow the browser's own declaration, whenever it lands. - expect(after.slots.entries(MENU_ITEM)).toHaveLength(4) + expect(after.slots.entries(MENU_ITEM)).toHaveLength(5) expect(after.slots.entries(ROW_ACTION)).toHaveLength(2) expect(after.slots.entries('shell.overlay')).toHaveLength(3) }) @@ -257,6 +272,7 @@ describe('ui-workspace apply', () => { ['rename', 200, RenameSessionMenuItem, 'workspace'], ['fork', 300, ForkSessionMenuItem, 'workspace'], ['archive', 400, ArchiveSessionMenuItem, 'workspace'], + ['session-id', 450, SessionIdMenuItem, 'workspace'], ]) expect(rows(ROW_ACTION)).toEqual([ ['archive', 100, ArchiveSessionRowButton, 'workspace'], @@ -265,17 +281,22 @@ describe('ui-workspace apply', () => { expect(rows('shell.overlay')).toEqual([ ['workspace.session-rename', undefined, SessionRenameDialog, 'workspace'], ['workspace.session-archive', undefined, SessionArchiveConfirmDialog, 'workspace'], - ['workspace.row-toast', undefined, RowActionToast, 'workspace'], + ['workspace.row-toast', undefined, RowActionToast, undefined], ]) - // The browser and the row toast declare the same viewing-store handle, - // which hands out one instance: the browser's injected callbacks write - // view state through it and the toast reads the archived filter from it. - // The row actions and the other overlay surfaces declare none. + // Only archive notice entries share the browser's viewing store. const browser = b.slots.entries('sidebar.workspaces')[0]! expect(browser.store).toBeDefined() expect(viewInstance(b.slots)).toBe(viewInstance(b.slots)) const rowToastEntry = entry(b.slots, 'shell.overlay', 'workspace.row-toast') - expect(rowToastEntry.store).toBe(browser.store) + expect(rowToastEntry.store).toBeUndefined() + expect(b.slots.entries('workspace.toast').map(row => row.options.key)).toEqual([ + 'sessionIdCopied', 'sessionIdCopyFailed', 'pinFailed', 'unpinFailed', 'archivedNotOpenable', + 'defaultWorkspaceFailed', 'shortcutForkFailed', 'createFailed', 'forkRequiresOpen', 'archived', 'stoppedAndArchived', + ]) + for (const registration of b.slots.entries('workspace.toast')) { + expect(registration.locale).toBe('workspace') + expect(registration.store).toBe(['archived', 'stoppedAndArchived'].includes(String(registration.options.key)) ? browser.store : undefined) + } for (const registration of [...b.slots.entries(MENU_ITEM), ...b.slots.entries(ROW_ACTION), ...b.slots.entries('shell.overlay')]) { if (registration === rowToastEntry) continue expect(registration.store).toBeUndefined() @@ -287,6 +308,77 @@ describe('ui-workspace apply', () => { } }) + it.each([true, false])('copies an ID directly without loading its Session (clipboard accepted: %s)', async (accepted) => { + const b = await bench() + onTestFinished(() => b.ctx.fiber.dispose()) + declare(b.slots, 'sidebar.workspaces', 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const action = faceOf(entry(b.slots, MENU_ITEM, 'session-id')) as SessionIdInjected + const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + const writeText = vi.fn(async () => { + if (!accepted) throw new Error('clipboard denied') + }) + vi.stubGlobal('navigator', { clipboard: { writeText } }) + onTestFinished(() => { vi.unstubAllGlobals() }) + await action.copySessionId(sid('cold-session')) + expect(writeText).toHaveBeenCalledExactlyOnceWith('cold-session') + expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: accepted ? 'sessionIdCopied' : 'sessionIdCopyFailed' }) + expect(b.retain).not.toHaveBeenCalled() + expect(b.using).not.toHaveBeenCalled() + expect(b.binding).not.toHaveBeenCalled() + }) + + it('publishes shortcut fork failures through the same latest-notice source as row actions', async () => { + const b = await bench() + onTestFinished(() => b.ctx.fiber.dispose()) + declare(b.slots, 'shell.overlay') + const removeBrowser = b.slots.register({ + name: 'shell.overlay', id: 'test-sidebar-owner', + children: { 'sidebar.workspaces': { kind: 'single', scope: 'root' } }, + }, SidebarDeclarationOwner) + await b.ctx.plugin({ inject: [...inject], apply }).await() + b.setSessions(sessionState([{ ...summary('source', 1), retainedBy: { mainView: 1 } }])) + const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected + const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warning.mockRestore() }) + const invoke = () => { + const resolution = b.commands.get('session.fork')!.resolve({ region: 'page', modal: null, target: null }) + if (resolution.status !== 'handled') throw new Error('the source must be available') + resolution.run() + } + + browser.notifyArchivedNotOpenable() + expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'archivedNotOpenable' }) + b.fork.mockRejectedValueOnce(new SessionForkError( + new RemoteError('session/fork-unavailable', 'no completed turn', { sessionId: sid('source') }), sid('source'), + )) + invoke() + await vi.waitFor(() => { + expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'shortcutForkFailed', reason: 'unavailable' }) + }) + expect(b.fork).toHaveBeenCalledExactlyOnceWith({ sessionId: sid('source'), increaseTitle: true }) + expect(warning).not.toHaveBeenCalled() + const unavailable = toast.hooks.toast.getSnapshot() + b.fork.mockRejectedValueOnce(new Error('connection closed')) + invoke() + await vi.waitFor(() => { + expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'shortcutForkFailed', reason: 'failed' }) + }) + expect(toast.hooks.toast.getSnapshot()).not.toBe(unavailable) + expect(warning).toHaveBeenCalledExactlyOnceWith('session fork rejected:', expect.any(Error)) + const failure = toast.hooks.toast.getSnapshot() + removeBrowser() + expect(b.slots.entries('sidebar.workspaces')).toEqual([]) + expect(entry(b.slots, 'shell.overlay', 'workspace.row-toast').component).toBe(RowActionToast) + expect(toast.hooks.toast.getSnapshot()).toBe(failure) + browser.notifyArchivedNotOpenable() + expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'archivedNotOpenable' }) + toast.dismissToast() + expect(toast.hooks.toast.getSnapshot()).toBeNull() + expect(browser).not.toHaveProperty('dismissForkError') + }) + it('derives the pinned and archived Sets from the Workspace snapshot, rebuilt only when it changes', async () => { const b = await bench() b.setWorkspaces(workspaceState([workspace('alpha', ['one', 'two'])], [sid('two')], [sid('one')])) @@ -472,17 +564,19 @@ describe('ui-workspace apply', () => { unsubscribe() expect(view.getSnapshot().archivedFilter).toBe('default') - toast.showArchived() + const archived = b.slots.entries('workspace.toast').find(row => row.options.key === 'archived')! + const archiveDisplay = faceOf(archived) as ArchiveToastInjected + archiveDisplay.filterAction(b.locale.bind('workspace'), toast.dismissToast).onClick() expect(view.getSnapshot().archivedFilter).toBe('show') - toast.undoArchive(sid('one')) + archiveDisplay.display({ kind: 'archived', sessionId: sid('one'), seq: 1 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick() expect(unarchiveSession).toHaveBeenCalledWith('one') // A rejected undo is a console diagnostic. const rejection = new Error('unarchive exploded') unarchiveSession.mockRejectedValueOnce(rejection) const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) try { - toast.undoArchive(sid('two')) + archiveDisplay.display({ kind: 'archived', sessionId: sid('two'), seq: 2 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick() await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith('session unarchive rejected:', rejection) }) } finally { warn.mockRestore() @@ -594,7 +688,8 @@ describe('ui-workspace apply', () => { expect(b.retain).not.toHaveBeenCalled() expect(b.selectPanel).not.toHaveBeenCalled() toast.dismissToast() - toast.openForkSource(sid('source')) + ;(faceOf(b.slots.entries('workspace.toast').find(row => row.options.key === 'forkRequiresOpen')!) as ToastDisplayInjected<'forkRequiresOpen'>) + .display({ kind: 'forkRequiresOpen', sessionId: sid('source'), seq: 1 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick() expect(b.retain).toHaveBeenCalledExactlyOnceWith('source', { source: 'mainView' }) expect(b.selectPanel).toHaveBeenCalledExactlyOnceWith(null) expect(b.fork).toHaveBeenCalledOnce() @@ -621,7 +716,8 @@ describe('ui-workspace apply', () => { if (timing === 'after the notice') b.setWorkspaces(workspaceState([], [sid('source')])) toast.dismissToast() - toast.openForkSource(sid('source')) + ;(faceOf(b.slots.entries('workspace.toast').find(row => row.options.key === 'forkRequiresOpen')!) as ToastDisplayInjected<'forkRequiresOpen'>) + .display({ kind: 'forkRequiresOpen', sessionId: sid('source'), seq: 1 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick() expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'archivedNotOpenable', seq: 2 }) expect(b.retain).not.toHaveBeenCalled() @@ -764,7 +860,7 @@ describe('ui-workspace apply', () => { declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace', 'shell.overlay') const fiber = b.ctx.plugin({ inject: [...inject], apply }) await fiber.await() - expect(b.slots.entries(MENU_ITEM)).toHaveLength(4) + expect(b.slots.entries(MENU_ITEM)).toHaveLength(5) expect(b.slots.entries(ROW_ACTION)).toHaveLength(2) expect(b.slots.entries('shell.overlay')).toHaveLength(3) await fiber.dispose() @@ -776,5 +872,7 @@ describe('ui-workspace apply', () => { expect(b.slots.entries(MENU_ITEM)).toHaveLength(0) expect(b.slots.entries(ROW_ACTION)).toHaveLength(0) expect(b.slots.entries('shell.overlay')).toHaveLength(0) + expect(b.slots.entries('workspace.toast')).toHaveLength(0) + expect(b.slots.snapshot('factory:workspace.toast.content')).toEqual([]) }) }) diff --git a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx index 0187272d53..274f595533 100644 --- a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx @@ -14,7 +14,7 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' * (session.spec.ts#rename), the entries' own arms with * session-actions.client.spec, the row's list rendering with rows.client.spec. */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { act, cleanup, fireEvent, waitFor, within } from '@testing-library/react' import type { ISession } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/client' @@ -111,7 +111,7 @@ describe('session rename through the assembled browser', () => { }, ) } - // `order` places plugin rows after the shipped rows (100/200/300/400) + // `order` places plugin rows after the shipped rows (100/200/300/400/450) // even when the later registration has the lower shadowing priority // assigned to dynamic browser packages; the first plugin row opens the // plugin group with a hairline. @@ -123,7 +123,7 @@ describe('session rename through the assembled browser', () => { const trigger = within(row as HTMLElement).getByLabelText('会话“Persisted title”的操作') fireEvent.click(trigger) expect(view.getAllByRole('menuitem').map(item => item.textContent)).toEqual([ - '置顶会话', '重命名', '分叉会话', '归档会话', 'Export action', 'Last action', + '置顶会话', '重命名', '分叉会话', '归档会话', '复制 Session ID', 'Export action', 'Last action', ]) expect(view.getAllByRole('separator')).toHaveLength(1) const last = view.getByRole('menuitem', { name: 'Last action' }) @@ -140,6 +140,18 @@ describe('session rename through the assembled browser', () => { expect(view.queryByRole('menu')).toBeNull() await act(async () => { await Promise.resolve() }) expect(document.activeElement).toBe(trigger) + const writeText = vi.fn(async () => {}) + const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard') + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + onTestFinished(() => { + if (clipboard === undefined) Reflect.deleteProperty(navigator, 'clipboard') + else Object.defineProperty(navigator, 'clipboard', clipboard) + }) + fireEvent.click(trigger) + fireEvent.click(view.getByRole('menuitem', { name: '复制 Session ID' })) + expect(view.queryByRole('menu')).toBeNull() + expect(writeText).toHaveBeenCalledExactlyOnceWith(SID) + await view.findByText('Session ID 已复制') await runtime.dispose() }) diff --git a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx index 44e01f8671..35e40222e2 100644 --- a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx +++ b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx @@ -1,22 +1,25 @@ // @vitest-environment jsdom /** * The shipped Session row actions rendered directly with hand-built props: - * the pin, rename, fork, and archive menu rows, the archive and pin hover - * buttons, and the two `shell.overlay` surfaces they raise (rename dialog, - * row notice). Every action reads its own injected hooks and calls its own - * injected callbacks; what those callbacks do is apply.client.spec's + * the menu rows, hover buttons, dialogs, and global notices. Every action + * reads its own injected hooks and calls its own injected callbacks; + * what those callbacks do is apply.client.spec's * subject. The browser and the slot machinery stay out; the assembled * chain lives in rename-assembly.client.spec. */ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceId, WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { GlobalStandardProps, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { GlobalStandardProps, PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import { bindSnapshotSelector, makeTranslate, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { registerToasts } from '../src/client/toast/register.ts' +import { ArchiveToastEntry } from '../src/client/toast/Toast.tsx' +import type { ArchiveToastEntryProps } from '../src/client/contract/toast.ts' import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import type { @@ -30,6 +33,7 @@ import { ForkSessionMenuItem } from '../src/client/session-actions/ForkSession.t import { PinSessionMenuItem, PinSessionRowButton } from '../src/client/session-actions/PinSession.tsx' import { RenameSessionMenuItem, SessionRenameDialog } from '../src/client/session-actions/RenameSession.tsx' import { RowActionToast } from '../src/client/session-actions/RowActionToast.tsx' +import { SessionIdMenuItem } from '../src/client/session-actions/SessionId.tsx' import { createWorkspaceViewStore } from '../src/client/stores.ts' import { en, zh } from '../src/client/locales.ts' import { ShortcutRegistry } from '../../shortcuts/src/client/registry.ts' @@ -109,6 +113,19 @@ function callOrder(fn: { mock: { invocationCallOrder: readonly number[] } }, nth return fn.mock.invocationCallOrder[nth] ?? Number.POSITIVE_INFINITY } +describe('Session ID action', () => { + it.each([t, tEn])('dismisses the menu before copying the complete row ID', (translate) => { + const { state, setMenuOpen } = openMenu() + const sessionId = sid('session-c4421b66-252e-44c0-80ed-6e320abeba25') + const copySessionId = vi.fn(async () => {}) + render() + fireEvent.click(screen.getByRole('menuitem', { name: translate('menu.sessionId') })) + expect(setMenuOpen).toHaveBeenCalledWith(false) + expect(copySessionId).toHaveBeenCalledExactlyOnceWith(sessionId) + expect(callOrder(setMenuOpen)).toBeLessThan(callOrder(copySessionId)) + }) +}) + describe('pin action', () => { /** The pin share over fixed membership: the bound Set hooks and the two callbacks the entries call. */ const pinShare = (pinned: readonly string[] = [], archived: readonly string[] = []) => ({ @@ -488,9 +505,28 @@ declare module '@deepseek-ai/dsh-workspace/types' { } } +function ToastFrame({ renderSlot }: PropsRenderSlots<'shell.overlay'>) { + return renderSlot('shell.overlay', {}) +} + describe('RowActionToast', () => { + it('adds the archive filter action when the display mapping supplies no actions', () => { + const instance = createWorkspaceViewStore().create() + const dismissToast = vi.fn() + const showArchived = vi.fn() + const filter = { label: 'Show archived', onClick: showArchived } + const renderFactorySlot = vi.fn(() => null) + render( ({ text: 'Archived', tone: 'success' })} filterAction={() => filter} />) + expect(renderFactorySlot).toHaveBeenCalledWith('workspace.toast.content', { + text: 'Archived', tone: 'success', actions: [filter], seq: 1, onDone: dismissToast, + }) + }) + /** The notice surface over a test-owned notice source; dismissal clears the notice the way apply does. */ - function toastSurface( + async function toastSurface( viewState: { archivedFilter?: 'default' | 'show' | 'only' } = { archivedFilter: 'default' }, translate = t, ) { @@ -506,28 +542,59 @@ describe('RowActionToast', () => { const undoArchive = vi.fn() const showArchived = vi.fn() const openForkSource = vi.fn() - render( - , - ) + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + const locale = new LocaleRuntime(runtime.ctx) + locale.setLocale(translate === tEn ? 'en' : 'zh') + locale.register('workspace', { en, zh }) + runtime.ctx.provide('locale', locale) + runtime.slots.installLocale(locale) + await runtime.root.declare({ 'shell.overlay': { kind: 'list', scope: 'root' } }, ToastFrame) + registerToasts(runtime.ctx, { + ...createWorkspaceViewStore(), + create: () => ({ + ...instance, store: view, + getSnapshot: () => view.getSnapshot(), + subscribe: listener => view.subscribe(listener), + }), + }, { + undoArchive, showArchived, openForkSource, + }) + runtime.slots.register({ + name: 'shell.overlay', id: 'workspace.row-toast', + children: { 'workspace.toast': { kind: 'keyed', scope: 'root' } }, + inject: () => ({ hooks: { toast }, dismissToast }), + }, RowActionToast) + runtime.renderRoot() let seq = 0 const notify = (notice: RowToast): void => { act(() => { toast.set({ ...notice, seq: ++seq }) }) } - return { dismissToast, undoArchive, showArchived, openForkSource, notify } + return { dismissToast, undoArchive, showArchived, openForkSource, notify, locale, view } } - it('renders nothing without a notice', () => { - toastSurface() + it('updates locale and archive actions without restarting the same notice', async () => { + const { notify, locale, view, dismissToast } = await toastSurface() + vi.useFakeTimers() + try { + notify({ kind: 'archived', sessionId: sid('one') }) + const alert = screen.getByRole('alert') + act(() => { vi.advanceTimersByTime(3000) }) + act(() => { locale.setLocale('en'); view.set({ ...view.getSnapshot(), archivedFilter: 'show' }) }) + expect(screen.getByRole('alert')).toBe(alert) + expect(alert.textContent).toContain('Session archived') + expect(screen.queryByRole('button', { name: 'filter archived sessions' })).toBeNull() + act(() => { vi.advanceTimersByTime(3999) }) + expect(dismissToast).not.toHaveBeenCalled() + act(() => { vi.advanceTimersByTime(1) }) + expect(dismissToast).toHaveBeenCalledOnce() + } finally { + vi.useRealTimers() + } + }) + + it('renders nothing without a notice', async () => { + await toastSurface() expect(screen.queryByRole('alert')).toBeNull() expect(document.body.textContent).toBe('') }) @@ -535,8 +602,8 @@ describe('RowActionToast', () => { it.each([ ['zh', t, '请先打开原会话完成迁移,再创建分支', '打开原会话'], ['en', tEn, 'Open the original session to complete migration before creating a branch.', 'Open original session'], - ] as const)('keeps the %s fork notice after menu unmount and opens only on its action', (_locale, translate, message, action) => { - const { dismissToast, openForkSource, notify } = toastSurface(undefined, translate) + ] as const)('keeps the %s fork notice after menu unmount and opens only on its action', async (_locale, translate, message, action) => { + const { dismissToast, openForkSource, notify } = await toastSurface(undefined, translate) const { state, setMenuOpen } = openMenu() const forkSession = vi.fn((sessionId: SessionId) => { notify({ kind: 'forkRequiresOpen', sessionId }) }) const menu = render() @@ -558,16 +625,73 @@ describe('RowActionToast', () => { expect(screen.queryByRole('alert')).toBeNull() }) - it('the stopped-and-archived notice offers the same undo and filter actions under its own wording', () => { - const { undoArchive, notify } = toastSurface() + it.each([t, tEn])('reports clipboard success and failure through the global toast', async (translate) => { + const { notify } = await toastSurface(undefined, translate) + notify({ kind: 'sessionIdCopied' }) + expect(screen.getByRole('alert').textContent).toBe(translate('toast.sessionIdCopied')) + notify({ kind: 'sessionIdCopyFailed' }) + expect(screen.getByRole('alert').textContent).toBe(translate('toast.sessionIdCopyFailed')) + }) + + it.each([t, tEn])('replaces other notices with plain shortcut fork failures and only keeps the latest', async (translate) => { + const { dismissToast, notify } = await toastSurface(undefined, translate) + vi.useFakeTimers() + try { + notify({ kind: 'archived', sessionId: sid('one') }) + act(() => { vi.advanceTimersByTime(1000) }) + notify({ kind: 'shortcutForkFailed', reason: 'unavailable' }) + const first = screen.getByRole('alert') + expect(first.textContent).toBe(translate('shortcut.noCompletedTurn')) + expect(first.querySelector('svg')).toBeNull() + expect(first.querySelector('button')).toBeNull() + act(() => { vi.advanceTimersByTime(3000) }) + expect(screen.getByRole('alert')).toBe(first) + notify({ kind: 'shortcutForkFailed', reason: 'failed' }) + const retry = screen.getByRole('alert') + expect(retry).not.toBe(first) + expect(retry.textContent).toBe(translate('shortcut.forkFailed')) + expect(retry.querySelector('svg')).toBeNull() + act(() => { vi.advanceTimersByTime(3999) }) + expect(screen.getAllByRole('alert')).toEqual([retry]) + expect(dismissToast).not.toHaveBeenCalled() + act(() => { vi.advanceTimersByTime(1) }) + expect(dismissToast).toHaveBeenCalledOnce() + expect(screen.queryByRole('alert')).toBeNull() + + notify({ kind: 'shortcutForkFailed', reason: 'failed' }) + act(() => { vi.advanceTimersByTime(1000) }) + notify({ kind: 'sessionIdCopied' }) + const latest = screen.getByRole('alert') + expect(latest.textContent).toBe(translate('toast.sessionIdCopied')) + act(() => { vi.advanceTimersByTime(3000) }) + expect(screen.getAllByRole('alert')).toEqual([latest]) + expect(dismissToast).toHaveBeenCalledOnce() + act(() => { vi.advanceTimersByTime(1000) }) + expect(screen.queryByRole('alert')).toBeNull() + } finally { + vi.useRealTimers() + } + }) + + it('the stopped-and-archived notice offers the same undo and filter actions under its own wording', async () => { + const { dismissToast, undoArchive, showArchived, notify } = await toastSurface() notify({ kind: 'stoppedAndArchived', sessionId: sid('one') }) expect(screen.getByRole('alert').textContent).toBe('已停止并归档,可撤销或筛选已归档会话') fireEvent.click(screen.getByRole('button', { name: '撤销' })) expect(undoArchive).toHaveBeenCalledWith(sid('one')) + expect(callOrder(dismissToast)).toBeLessThan(callOrder(undoArchive)) + + notify({ kind: 'stoppedAndArchived', sessionId: sid('two') }) + fireEvent.click(screen.getByRole('button', { name: '筛选已归档会话' })) + expect(dismissToast).toHaveBeenCalledTimes(2) + expect(showArchived).toHaveBeenCalledOnce() + expect(callOrder(dismissToast, 1)).toBeLessThan(callOrder(showArchived)) + expect(undoArchive).toHaveBeenCalledOnce() + expect(screen.queryByRole('alert')).toBeNull() }) - it('the archived notice takes itself down, then undoes the archive or shows the archived rows', () => { - const { dismissToast, undoArchive, showArchived, notify } = toastSurface() + it('the archived notice takes itself down, then undoes the archive or shows the archived rows', async () => { + const { dismissToast, undoArchive, showArchived, notify } = await toastSurface() notify({ kind: 'archived', sessionId: sid('one') }) expect(screen.getByRole('alert').textContent).toBe('会话已归档,可撤销或筛选已归档会话') fireEvent.click(screen.getByRole('button', { name: '撤销' })) @@ -586,14 +710,14 @@ describe('RowActionToast', () => { expect(screen.queryByRole('alert')).toBeNull() }) - it('treats a view without a persisted filter as the hidden default and keeps the filter action', () => { - const { notify } = toastSurface({}) + it('treats a view without a persisted filter as the hidden default and keeps the filter action', async () => { + const { notify } = await toastSurface({}) notify({ kind: 'archived', sessionId: sid('one') }) expect(screen.getByRole('alert').textContent).toBe('会话已归档,可撤销或筛选已归档会话') }) - it.each(['show', 'only'] as const)('omits the filter action while the %s filter already shows archived rows', (archivedFilter) => { - const { notify } = toastSurface({ archivedFilter }) + it.each(['show', 'only'] as const)('omits the filter action while the %s filter already shows archived rows', async (archivedFilter) => { + const { notify } = await toastSurface({ archivedFilter }) notify({ kind: 'archived', sessionId: sid('one') }) expect(screen.getByRole('alert').textContent).toBe('会话已归档,可撤销') expect(screen.queryByRole('button', { name: '筛选已归档会话' })).toBeNull() @@ -605,10 +729,10 @@ describe('RowActionToast', () => { ['unpinFailed', '取消置顶失败,请稍后重试'], ['archivedNotOpenable', '已归档对话暂时无法查看,请取消归档后查看'], ['defaultWorkspaceFailed', '无法创建默认工作区,请通过“选择工作区”选择文件夹'], - ] as const)('shows the %s warning and takes it down when its hold ends', (kind, text) => { + ] as const)('shows the %s warning and takes it down when its hold ends', async (kind, text) => { + const { dismissToast, notify } = await toastSurface() vi.useFakeTimers() try { - const { dismissToast, notify } = toastSurface() notify({ kind }) const alert = screen.getByRole('alert') expect(alert.textContent).toBe(text) @@ -621,10 +745,10 @@ describe('RowActionToast', () => { } }) - it('shows a refused creation with the Host reason and holds it as long as the archived notice', () => { + it('shows a refused creation with the Host reason and holds it as long as the archived notice', async () => { + const { dismissToast, notify } = await toastSurface() vi.useFakeTimers() try { - const { dismissToast, notify } = toastSurface() notify({ kind: 'createFailed', message: 'agent-preset/invalid: agent-presets: preset "broken" failed to mount' }) const alert = screen.getByRole('alert') expect(alert.textContent).toBe('新建会话失败:agent-preset/invalid: agent-presets: preset "broken" failed to mount') @@ -639,10 +763,10 @@ describe('RowActionToast', () => { } }) - it('the archived notice holds longer than a plain notice, and a repeat restarts its hold', () => { + it('the archived notice holds longer than a plain notice, and a repeat restarts its hold', async () => { + const { dismissToast, notify } = await toastSurface() vi.useFakeTimers() try { - const { dismissToast, notify } = toastSurface() notify({ kind: 'archived', sessionId: sid('one') }) act(() => { vi.advanceTimersByTime(4000) }) expect(screen.getByRole('alert')).toBeTruthy() diff --git a/packages/client/ui-workspace/tests/shortcuts.client.spec.ts b/packages/client/ui-workspace/tests/shortcuts.client.spec.ts index 6a11c44b56..50caf09818 100644 --- a/packages/client/ui-workspace/tests/shortcuts.client.spec.ts +++ b/packages/client/ui-workspace/tests/shortcuts.client.spec.ts @@ -54,14 +54,16 @@ async function bench(runtime: 'web' | 'desktop' = 'desktop', platform: ShortcutP startSession: vi.fn(), forkSession: vi.fn(async () => 'fork-child' as SessionId), archiveSession: vi.fn(async (_sessionId: SessionId) => {}), } const controls = createWorkspaceShortcutControls() + const reportForkFailure = vi.fn() const fiber = ctx.plugin((scoped) => { - installWorkspaceShortcuts(scoped, navigation, controls, (id) => { void navigation.archiveSession(id) }) + installWorkspaceShortcuts(scoped, navigation, controls, + (id) => { void navigation.archiveSession(id) }, reportForkFailure) }) await fiber.await() const select = (id: string) => { list.set({ ...list.getSnapshot(), byId: { [sid('a')]: row('a', id === 'a'), [sid('b')]: row('b', id === 'b'), } }) } - return { ctx, fiber, registry, commands, navigation, controls, list, directory, select, history, loadOlder, panelInfo } + return { ctx, fiber, registry, commands, navigation, controls, reportForkFailure, list, directory, select, history, loadOlder, panelInfo } } afterEach(() => { vi.restoreAllMocks() }) @@ -188,12 +190,11 @@ describe('workspace shortcut ownership', () => { )) const invoke = () => b.registry.dispatch(key('KeyF', { alt: true }), context, vi.fn()) expect(invoke().status).toBe('handled') - await vi.waitFor(() => { expect(b.controls.state.getSnapshot().forkError).toMatchObject({ reason: 'unavailable' }) }) + await vi.waitFor(() => { expect(b.reportForkFailure).toHaveBeenCalledExactlyOnceWith('unavailable') }) expect(warning).not.toHaveBeenCalled() - b.controls.dismissForkError() b.navigation.forkSession.mockRejectedValueOnce(new Error('connection closed')) expect(invoke().status).toBe('handled') - await vi.waitFor(() => { expect(b.controls.state.getSnapshot().forkError).toMatchObject({ reason: 'failed' }) }) + await vi.waitFor(() => { expect(b.reportForkFailure).toHaveBeenNthCalledWith(2, 'failed') }) expect(warning).toHaveBeenCalledOnce() b.list.set({ ...b.list.getSnapshot(), byId: { [sid('a')]: { ...row('a', true), running: true } } }) expect(invoke().status).toBe('handled') diff --git a/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx index f88dd51e96..40b9a97a6d 100644 --- a/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx @@ -11,13 +11,12 @@ import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/c import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' -import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts' import type { DirectoryFlowOwnerProps, WorkspaceBrowserProps } from '../src/client/contract/slots.ts' import { createWorkspaceShortcutControls } from '../src/client/shortcuts.ts' import { createWorkspaceViewStore, FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts' import { UNGROUPED_KEY } from '../src/client/tree.ts' import { WorkspaceBrowser } from '../src/client/rows/WorkspaceBrowser.tsx' -import { en, zh } from '../src/client/locales.ts' +import { zh } from '../src/client/locales.ts' // Every fixture carries the resource hook the resources plugin merges into GlobalStandardProps. const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined, reload: () => {} })) as GlobalStandardProps['useResource'] @@ -114,7 +113,6 @@ function mount(overrides: Partial = {}) { closeAddWorkspace: controls.closeAdd, setDirectoryBusy: controls.directoryBusy, requestSessionRename: controls.rename, - dismissForkError: controls.dismissForkError, wide: true, expandSidebar: vi.fn(), useSessions: hook(sessionState([])), @@ -151,19 +149,6 @@ function rerender(b: ReturnType, overrides: Partial { - it.each([{ messages: en, common: commonEn }, { messages: zh, common: commonZh }])('shows localized fork failures and dismisses them', ({ messages, common }) => { - const b = mount({ t: makeTranslate(messages, common) }) - act(() => { b.controls.forkFailed('unavailable') }) - const first = screen.getByRole('alert') - expect(first.textContent).toBe(messages['shortcut.noCompletedTurn']) - act(() => { b.controls.dismissForkError(); b.controls.forkFailed('unavailable') }) - expect(screen.getByRole('alert')).not.toBe(first) - act(() => { b.controls.forkFailed('failed') }) - expect(screen.getByRole('alert').textContent).toBe(messages['shortcut.forkFailed']) - act(() => { b.controls.dismissForkError() }) - expect(screen.queryByRole('alert')).toBeNull() - }) - it.each(['workspace', 'flat', 'ungrouped'] as const)('keeps %s recency independent of arrival order and saved manual positions', (mode) => { localStorage.clear() const preferences = createWorkspaceViewStore().create() diff --git a/packages/client/web/README.i18n.yaml b/packages/client/web/README.i18n.yaml index 816b541cd8..7037ec70a4 100644 --- a/packages/client/web/README.i18n.yaml +++ b/packages/client/web/README.i18n.yaml @@ -15,17 +15,17 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-web/use-this-package: - en: 0c8b98946feedb0f - zh: ae10ae7b9ecbf89c + en: 8778e166024b9628 + zh: 777d6923db199337 /deepseek-ai-dsh-client-web/use-this-package/what-boot-looks-like: en: f3b01aa878764e5c zh: f02eab65d441bfe0 /deepseek-ai-dsh-client-web/use-this-package/the-boot-page: - en: add354591107b80d - zh: 41136254a00d785e + en: 1757ef1631612ff5 + zh: d2d3fd0313908c12 /deepseek-ai-dsh-client-web/use-this-package/the-shared-module-table: - en: 8380cd70b861a3a8 - zh: 5a331deb7ad8fca1 + en: 33b256e108a7bd6a + zh: 3b2b1368721803b7 /deepseek-ai-dsh-client-web/use-this-package/configuration: en: 942959cb40ee31a1 zh: 9c86ac2cf6a13976 diff --git a/packages/client/web/README.md b/packages/client/web/README.md index 8fbbd89fa1..42b6c63efc 100644 --- a/packages/client/web/README.md +++ b/packages/client/web/README.md @@ -31,6 +31,8 @@ Static application pages install `__DSH_BOOT_READY__` before the entry runs. The The shell base styles apply automatic CJK/Latin spacing to ordinary content in supporting browsers. Semantic code and terminal, diff, read, and search output containers retain literal source spacing and column alignment; browsers without `text-autospace` support ignore both declarations. +Web and Desktop mathematical rendering requires WOFF2 support. The [Web build](../../../apps/web/katex-fonts.ts) retains every KaTeX font face in WOFF2 and omits WOFF/TTF fallbacks; a face without WOFF2 rejects the build. Font glyphs, weights, styles, and layout rules are preserved. + ### What boot looks like Boot runs in two stages: the module stage adopts the parser-loaded bootstrap batch, builds the module system from the Host-provided boot graph, and prefetches the `immediately` tier through the shared application-batch URL, which executes once. The plugin stage then activates every graph entry and waits for all of them before handing the marked boot DOM to the UI renderer, which hydrates it and switches to the complete UI. @@ -39,9 +41,12 @@ Boot runs in two stages: the module stage adopts the parser-loaded bootstrap bat The boot page uses plain DOM and local CSS, so bundle and plugin-activation failures remain visible: it shows one spinner node whose CSS arc grows as entries activate, and reports per-entry status. The spinner and its animation phase persist until the full UI replaces the boot page. A plugin that fails import or activation is reported by name with the reason (missing service, import failure, or state) instead of a blank page. The console contains the original import error. + ### The shared module table -`PLATFORM_MODULES` (in `src/platform.ts`) names the shell-seeded shared modules — React, Cordis, and static UI libraries — and together with `PRELOADED_CLIENT_EXTERNALS` (the parser-preloaded runtime row) defines the implicit external baseline every dynamic bundle resolves against. `dsh.client.external` adds only exact non-baseline requests; see [shared modules and the module graph](../AGENTS.md#shared-modules-and-the-module-graph). +`PLATFORM_MODULES` (in `src/platform.ts`) names the shell-seeded shared modules — React, Cordis, Zod (`zod`), TanStack Virtual (`@tanstack/react-virtual`), and static UI libraries — and together with `PRELOADED_CLIENT_EXTERNALS` (the parser-preloaded runtime row) defines the implicit external baseline every dynamic bundle resolves against. `dsh.client.external` adds only exact non-baseline requests; see [shared modules and the module graph](../AGENTS.md#shared-modules-and-the-module-graph). + +Built-in and installed browser plugins in the same page receive the same module instances. The shell supplies the dependency versions declared in this package's `package.json`; the module table does not negotiate versions per plugin. External plugins that use these modules must target a host that provides the required specifiers and APIs, and keep those imports external when building their client bundle. Inlined dependencies remain private to their bundle; Host code and Workers resolve their dependencies separately. ### Configuration diff --git a/packages/client/web/README.zh.md b/packages/client/web/README.zh.md index 4e64bf2978..31ff77c606 100644 --- a/packages/client/web/README.zh.md +++ b/packages/client/web/README.zh.md @@ -31,6 +31,8 @@ kind: "package-library" 外壳基础样式会在支持的浏览器中为普通内容自动添加中西文间距。语义化代码以及终端、diff、读取和搜索输出容器会保留源码中的原始间距和列对齐;不支持 `text-autospace` 的浏览器会忽略这两项声明。 +Web 和 Desktop 的数学公式渲染要求支持 WOFF2。[Web 构建](../../../apps/web/katex-fonts.ts)以 WOFF2 保留全部 KaTeX 字体样式,并排除 WOFF/TTF 后备格式;任一字体样式缺少 WOFF2 都会使构建失败。字体的字形、字重、样式和布局规则保持不变。 + ### 启动过程是怎样的 启动分两个阶段:模块阶段接纳 parser 已加载的 bootstrap 批次,从 Host 提供的启动图构建模块系统,并通过只执行一次的共享 application 批次 URL 预取 `immediately` 层级。插件阶段随后激活每个图 entry 并等待全部就绪,之后才把带标记的启动 DOM 交给 UI 渲染器,由它 hydrate 并切换到完整 UI。 @@ -39,9 +41,12 @@ kind: "package-library" 启动页只使用原生 DOM 与本地 CSS,因此 bundle 与插件激活失败保持可见:它显示一个 spinner 节点,其 CSS 圆弧随 entry 激活而增长,并逐 entry 报告状态。spinner 及其动画相位会一直保留,直到完整 UI 替换启动页。导入或激活失败的插件会按名称报告并给出原因(缺失服务、导入失败或状态),而不是白屏。控制台包含原始导入错误。 + ### 共享模块表 -`PLATFORM_MODULES`(位于 `src/platform.ts`)列出外壳预置的共享模块——React、Cordis 与静态 UI 库——并与 `PRELOADED_CLIENT_EXTERNALS`(parser 预载的运行时行)一起定义每个动态 bundle 解析所依据的隐式 external 基座。`dsh.client.external` 只添加基座之外的精确请求;参见[共享模块与模块图](../AGENTS.md#shared-modules-and-the-module-graph)。 +`PLATFORM_MODULES`(位于 `src/platform.ts`)列出外壳预置的共享模块——React、Cordis、Zod(`zod`)、TanStack Virtual(`@tanstack/react-virtual`)与静态 UI 库——并与 `PRELOADED_CLIENT_EXTERNALS`(parser 预载的运行时行)一起定义每个动态 bundle 解析所依据的隐式 external 基座。`dsh.client.external` 只添加基座之外的精确请求;参见[共享模块与模块图](../AGENTS.md#shared-modules-and-the-module-graph)。 + +同一页面中的内置浏览器插件和已安装的浏览器插件获得相同的模块实例。外壳提供本包 `package.json` 声明的依赖版本,模块表不会为每个插件协商版本。使用这些模块的外部插件必须以提供所需模块标识符和 API 的宿主为目标,并在构建客户端 bundle 时将相应导入保留为 external。内联依赖仍归各自 bundle 私有;Host 代码与 Worker 单独解析其依赖。 ### 配置 diff --git a/packages/client/web/package.json b/packages/client/web/package.json index ceb21773d5..e3733a87e5 100644 --- a/packages/client/web/package.json +++ b/packages/client/web/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-web", "description": "Web boot kernel: static module table, Cordis loader, framework-free boot page, and UI-renderer handoff", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -40,7 +40,9 @@ "react": "^18.2.0", "react-dom": "^18.2.0", "typescript": "^6.0.3", - "@deepseek-ai/dsh-host-webserver": "workspace:*" + "@deepseek-ai/dsh-host-webserver": "workspace:*", + "zod": "4.4.3", + "@tanstack/react-virtual": "3.14.10" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" diff --git a/packages/client/web/src/platform.ts b/packages/client/web/src/platform.ts index 2549966986..3103555215 100644 --- a/packages/client/web/src/platform.ts +++ b/packages/client/web/src/platform.ts @@ -7,6 +7,7 @@ /** The module specifiers the shell shares into the frozen module table. */ export const PLATFORM_MODULES = [ 'react', 'react/jsx-runtime', 'react-dom', 'react-dom/client', '@deepseek-ai/cordis', + 'zod', '@tanstack/react-virtual', '@deepseek-ai/dsh-client-store', '@deepseek-ai/dsh-client-ui-slots', '@deepseek-ai/dsh-client-ui-primitives', diff --git a/packages/client/web/src/seed.ts b/packages/client/web/src/seed.ts index d41f338d42..bbba6643f3 100644 --- a/packages/client/web/src/seed.ts +++ b/packages/client/web/src/seed.ts @@ -11,6 +11,8 @@ import * as ReactJsxRuntime from 'react/jsx-runtime' import * as ReactDom from 'react-dom' import * as ReactDomClient from 'react-dom/client' import * as Cordis from '@deepseek-ai/cordis' +import * as Zod from 'zod' +import * as ReactVirtual from '@tanstack/react-virtual' import * as ClientStore from '@deepseek-ai/dsh-client-store' import * as UiSlots from '@deepseek-ai/dsh-client-ui-slots' import * as UiPrimitives from '@deepseek-ai/dsh-client-ui-primitives' @@ -31,6 +33,8 @@ export function getStaticModules(): Record { 'react-dom': ReactDom, 'react-dom/client': ReactDomClient, '@deepseek-ai/cordis': Cordis, + 'zod': Zod, + '@tanstack/react-virtual': ReactVirtual, '@deepseek-ai/dsh-client-store': ClientStore, '@deepseek-ai/dsh-client-ui-slots': UiSlots, '@deepseek-ai/dsh-client-ui-primitives': UiPrimitives, diff --git a/packages/compaction/command-compact/locale/en.json b/packages/compaction/command-compact/locale/en.json new file mode 100644 index 0000000000..6a900164f6 --- /dev/null +++ b/packages/compaction/command-compact/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "command-compact" + } +} diff --git a/packages/compaction/command-compact/locale/zh.json b/packages/compaction/command-compact/locale/zh.json new file mode 100644 index 0000000000..a2145890a2 --- /dev/null +++ b/packages/compaction/command-compact/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "上下文压缩命令", + "description": "让用户通过命令主动压缩当前会话上下文。" + } +} diff --git a/packages/compaction/command-compact/package.json b/packages/compaction/command-compact/package.json index 3fbfb59544..3f83a85414 100644 --- a/packages/compaction/command-compact/package.json +++ b/packages/compaction/command-compact/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-command-compact", "description": "Human-facing slash command for explicit session compaction", - "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" ], diff --git a/packages/compaction/compaction-basic/locale/en.json b/packages/compaction/compaction-basic/locale/en.json new file mode 100644 index 0000000000..78fd31f32f --- /dev/null +++ b/packages/compaction/compaction-basic/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "compaction-basic" + } +} diff --git a/packages/compaction/compaction-basic/locale/zh.json b/packages/compaction/compaction-basic/locale/zh.json new file mode 100644 index 0000000000..352616d5fe --- /dev/null +++ b/packages/compaction/compaction-basic/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "上下文压缩", + "description": "在上下文达到阈值时,使用模型总结历史内容。" + } +} diff --git a/packages/compaction/compaction-basic/package.json b/packages/compaction/compaction-basic/package.json index 4eba2ada7b..67f90972ba 100644 --- a/packages/compaction/compaction-basic/package.json +++ b/packages/compaction/compaction-basic/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-compaction-basic", "description": "Token-meter-driven compaction policy and LLM summarization backend for the DeepSeek Harness", - "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" ], diff --git a/packages/compaction/compaction-image-offload/locale/en.json b/packages/compaction/compaction-image-offload/locale/en.json new file mode 100644 index 0000000000..8cfed647b9 --- /dev/null +++ b/packages/compaction/compaction-image-offload/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "compaction-image-offload" + } +} diff --git a/packages/compaction/compaction-image-offload/locale/zh.json b/packages/compaction/compaction-image-offload/locale/zh.json new file mode 100644 index 0000000000..87047960d2 --- /dev/null +++ b/packages/compaction/compaction-image-offload/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "历史图片卸载", + "description": "将超出模型图片预算的历史图片替换为附件引用,再重试请求。" + } +} diff --git a/packages/compaction/compaction-image-offload/package.json b/packages/compaction/compaction-image-offload/package.json index 67b3dc20e7..c0e0435ad6 100644 --- a/packages/compaction/compaction-image-offload/package.json +++ b/packages/compaction/compaction-image-offload/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-compaction-image-offload", "description": "Durable image offload for image-capable routes: replace over-budget request images with placeholders and retry", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -22,9 +22,11 @@ "./projection": { "types": "./lib/types/projection.d.ts", "default": "./lib/types/projection.js" - } + }, + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/compaction/compaction-tool-result-pruner/locale/en.json b/packages/compaction/compaction-tool-result-pruner/locale/en.json new file mode 100644 index 0000000000..ad406873b1 --- /dev/null +++ b/packages/compaction/compaction-tool-result-pruner/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "compaction-tool-result-pruner" + } +} diff --git a/packages/compaction/compaction-tool-result-pruner/locale/zh.json b/packages/compaction/compaction-tool-result-pruner/locale/zh.json new file mode 100644 index 0000000000..bfe5aa3a57 --- /dev/null +++ b/packages/compaction/compaction-tool-result-pruner/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工具结果精简", + "description": "在上下文压力较大时,精简过长的工具输出并保留首尾内容。" + } +} diff --git a/packages/compaction/compaction-tool-result-pruner/package.json b/packages/compaction/compaction-tool-result-pruner/package.json index b8cd3f2062..4ba34defc8 100644 --- a/packages/compaction/compaction-tool-result-pruner/package.json +++ b/packages/compaction/compaction-tool-result-pruner/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-compaction-tool-result-pruner", "description": "Replay-safe model-free head/middle/tail pruning for tool-result surface nodes", - "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" ], diff --git a/packages/compaction/compaction/package.json b/packages/compaction/compaction/package.json index 8f9c368f70..61027e194d 100644 --- a/packages/compaction/compaction/package.json +++ b/packages/compaction/compaction/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-compaction", "description": "Abstract compaction service seam (ctx.compaction) for the DeepSeek Harness", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/computer-use/computer-use/package.json b/packages/computer-use/computer-use/package.json index db8daf5fbe..a9e50ee220 100644 --- a/packages/computer-use/computer-use/package.json +++ b/packages/computer-use/computer-use/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-computer-use", "description": "Exclusive named computer-use provider registration", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/context/agent-instructions/locale/en.json b/packages/context/agent-instructions/locale/en.json new file mode 100644 index 0000000000..816d9020ab --- /dev/null +++ b/packages/context/agent-instructions/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "agent-instructions" + } +} diff --git a/packages/context/agent-instructions/locale/zh.json b/packages/context/agent-instructions/locale/zh.json new file mode 100644 index 0000000000..0bb7fd9f4c --- /dev/null +++ b/packages/context/agent-instructions/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工作区指令加载", + "description": "读取 AGENTS.md、CLAUDE.md 等文件,为 AI 提供工作区规则。" + } +} diff --git a/packages/context/agent-instructions/package.json b/packages/context/agent-instructions/package.json index 16f68d3634..cd365762ac 100644 --- a/packages/context/agent-instructions/package.json +++ b/packages/context/agent-instructions/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent-instructions", "description": "Workspace context loader for AGENTS.md/CLAUDE.md instruction files", - "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" ], diff --git a/packages/context/file-reference-local/locale/en.json b/packages/context/file-reference-local/locale/en.json new file mode 100644 index 0000000000..bdb13b8300 --- /dev/null +++ b/packages/context/file-reference-local/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "file-reference-local" + } +} diff --git a/packages/context/file-reference-local/locale/zh.json b/packages/context/file-reference-local/locale/zh.json new file mode 100644 index 0000000000..3762795210 --- /dev/null +++ b/packages/context/file-reference-local/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "本地文件引用", + "description": "提供本地文件的搜索和引用能力。" + } +} diff --git a/packages/context/file-reference-local/package.json b/packages/context/file-reference-local/package.json index 5cb1646286..25ff5de92c 100644 --- a/packages/context/file-reference-local/package.json +++ b/packages/context/file-reference-local/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-file-reference-local", "description": "Local-filesystem ctx.fileReferences provider with bounded fuzzy indexes", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,9 +23,11 @@ "default": "./lib/types/search.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/context/file-reference/package.json b/packages/context/file-reference/package.json index 125f4f7b10..ac1d645312 100644 --- a/packages/context/file-reference/package.json +++ b/packages/context/file-reference/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-file-reference", "description": "File-reference discovery contract and shared @file grammar", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/context/session-reference/locale/en.json b/packages/context/session-reference/locale/en.json new file mode 100644 index 0000000000..5ce3c4233b --- /dev/null +++ b/packages/context/session-reference/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "session-reference" + } +} diff --git a/packages/context/session-reference/locale/zh.json b/packages/context/session-reference/locale/zh.json new file mode 100644 index 0000000000..57f311219c --- /dev/null +++ b/packages/context/session-reference/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "跨会话引用", + "description": "为 AI 提供其他会话的只读内容快照。" + } +} diff --git a/packages/context/session-reference/package.json b/packages/context/session-reference/package.json index 9b8572ca85..3daff8f14d 100644 --- a/packages/context/session-reference/package.json +++ b/packages/context/session-reference/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-session-reference", "description": "Cross-session snapshot references and durable untrusted model context (ctx.sessionReferenceResolver)", - "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", @@ -47,7 +49,7 @@ "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/context/time-context/package.json b/packages/context/time-context/package.json index 0f778f8591..13f2be32e6 100644 --- a/packages/context/time-context/package.json +++ b/packages/context/time-context/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-time-context", "description": "Durable per-step context with the current time and elapsed time", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -31,7 +31,7 @@ "dependencies": { "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/context/tmux-context/package.json b/packages/context/tmux-context/package.json index fc3834a07d..e6c68f4554 100644 --- a/packages/context/tmux-context/package.json +++ b/packages/context/tmux-context/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tmux-context", "description": "Opt-in durable per-step context with this agent's tmux pane and window location", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -28,7 +28,7 @@ "license": "MIT", "dependencies": { "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/dsh-agent": "workspace:*", diff --git a/packages/core/agent-default-model/locale/en.json b/packages/core/agent-default-model/locale/en.json new file mode 100644 index 0000000000..f186bd3011 --- /dev/null +++ b/packages/core/agent-default-model/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "agent-default-model" + } +} diff --git a/packages/core/agent-default-model/locale/zh.json b/packages/core/agent-default-model/locale/zh.json new file mode 100644 index 0000000000..6b68fb5e2c --- /dev/null +++ b/packages/core/agent-default-model/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "默认模型", + "description": "为新建智能体提供默认模型选择。" + } +} diff --git a/packages/core/agent-default-model/package.json b/packages/core/agent-default-model/package.json index 7acef9bb27..a179669090 100644 --- a/packages/core/agent-default-model/package.json +++ b/packages/core/agent-default-model/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent-default-model", "description": "Default model selection shared by Agent entry points", - "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" ], diff --git a/packages/core/agent-loop/locale/en.json b/packages/core/agent-loop/locale/en.json new file mode 100644 index 0000000000..d0db02ecc5 --- /dev/null +++ b/packages/core/agent-loop/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "agent-loop" + } +} diff --git a/packages/core/agent-loop/locale/zh.json b/packages/core/agent-loop/locale/zh.json new file mode 100644 index 0000000000..b21c2b149c --- /dev/null +++ b/packages/core/agent-loop/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "智能体运行循环", + "description": "协调模型请求、工具调用和后续步骤,推进智能体任务。" + } +} diff --git a/packages/core/agent-loop/package.json b/packages/core/agent-loop/package.json index 1e1678594f..47f0791833 100644 --- a/packages/core/agent-loop/package.json +++ b/packages/core/agent-loop/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent-loop", "description": "The concrete agent loop plugin for the DeepSeek Harness", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -18,9 +18,11 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], @@ -40,7 +42,7 @@ "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" }, "devDependencies": { "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", diff --git a/packages/core/agent-tool-presentation/locale/en.json b/packages/core/agent-tool-presentation/locale/en.json new file mode 100644 index 0000000000..f8dd1865fc --- /dev/null +++ b/packages/core/agent-tool-presentation/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "agent-tool-presentation" + } +} diff --git a/packages/core/agent-tool-presentation/locale/zh.json b/packages/core/agent-tool-presentation/locale/zh.json new file mode 100644 index 0000000000..804d500211 --- /dev/null +++ b/packages/core/agent-tool-presentation/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工具调用方式", + "description": "选择智能体通过原生工具或 PTC 代码来调用工具。" + } +} diff --git a/packages/core/agent-tool-presentation/package.json b/packages/core/agent-tool-presentation/package.json index 99aafd9731..466465b75a 100644 --- a/packages/core/agent-tool-presentation/package.json +++ b/packages/core/agent-tool-presentation/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent-tool-presentation", "description": "Agent-plane presentation selector: composes one agent's tools as PTC mode or native tool calls", - "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" ], diff --git a/packages/core/agent/locale/en.json b/packages/core/agent/locale/en.json new file mode 100644 index 0000000000..62656fe619 --- /dev/null +++ b/packages/core/agent/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "agent" + } +} diff --git a/packages/core/agent/locale/zh.json b/packages/core/agent/locale/zh.json new file mode 100644 index 0000000000..0ec511ecc3 --- /dev/null +++ b/packages/core/agent/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "智能体管理", + "description": "管理智能体实例及其运行上下文和事件。" + } +} diff --git a/packages/core/agent/package.json b/packages/core/agent/package.json index f33481fc28..deb3a08154 100644 --- a/packages/core/agent/package.json +++ b/packages/core/agent/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent", "description": "Agent interface, registry, initiator scope, and event vocabulary for the DeepSeek Harness", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,9 +23,11 @@ "default": "./lib/types/types.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/core/scope/package.json b/packages/core/scope/package.json index 29d8d56bf0..b5503b6424 100644 --- a/packages/core/scope/package.json +++ b/packages/core/scope/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-scope", "description": "Scoped-context registration primitive (scope tags, scope-filtered event dispatch) for the DeepSeek Harness", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/core/session/locale/en.json b/packages/core/session/locale/en.json new file mode 100644 index 0000000000..c7519b7bc7 --- /dev/null +++ b/packages/core/session/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "session" + } +} diff --git a/packages/core/session/locale/zh.json b/packages/core/session/locale/zh.json new file mode 100644 index 0000000000..acf2adf883 --- /dev/null +++ b/packages/core/session/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话记录", + "description": "记录会话中的消息、工具调用和运行事件。" + } +} diff --git a/packages/core/session/package.json b/packages/core/session/package.json index 68fec8f3d6..3f062803cc 100644 --- a/packages/core/session/package.json +++ b/packages/core/session/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-session", "description": "Event-sourced session store for the DeepSeek Harness", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -31,9 +31,11 @@ "./surface": { "types": "./lib/types/surface.d.ts", "default": "./lib/types/surface.js" - } + }, + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/core/system-prompt/locale/en.json b/packages/core/system-prompt/locale/en.json new file mode 100644 index 0000000000..1bf4f235c8 --- /dev/null +++ b/packages/core/system-prompt/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "system-prompt" + } +} diff --git a/packages/core/system-prompt/locale/zh.json b/packages/core/system-prompt/locale/zh.json new file mode 100644 index 0000000000..2b29254c25 --- /dev/null +++ b/packages/core/system-prompt/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "系统提示词组装", + "description": "汇总各插件提供的系统提示词内容。" + } +} diff --git a/packages/core/system-prompt/package.json b/packages/core/system-prompt/package.json index 951ec3fb95..0e3ec253ea 100644 --- a/packages/core/system-prompt/package.json +++ b/packages/core/system-prompt/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-system-prompt", "description": "System prompt assembly registry for the DeepSeek Harness", - "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" ], diff --git a/packages/core/tools/locale/en.json b/packages/core/tools/locale/en.json new file mode 100644 index 0000000000..c9a7634507 --- /dev/null +++ b/packages/core/tools/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "tools" + } +} diff --git a/packages/core/tools/locale/zh.json b/packages/core/tools/locale/zh.json new file mode 100644 index 0000000000..eb3227360e --- /dev/null +++ b/packages/core/tools/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工具注册与执行", + "description": "管理可用工具及其调用执行流程。" + } +} diff --git a/packages/core/tools/package.json b/packages/core/tools/package.json index 1e4fa8ba01..caa9985b76 100644 --- a/packages/core/tools/package.json +++ b/packages/core/tools/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tools", "description": "Tool registry and execution pipeline for the DeepSeek Harness", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -27,9 +27,11 @@ "default": "./lib/types/presentation.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/credentials/authorization/locale/en.json b/packages/credentials/authorization/locale/en.json new file mode 100644 index 0000000000..8994ac6ecc --- /dev/null +++ b/packages/credentials/authorization/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "authorization" + } +} diff --git a/packages/credentials/authorization/locale/zh.json b/packages/credentials/authorization/locale/zh.json new file mode 100644 index 0000000000..bdf3420d15 --- /dev/null +++ b/packages/credentials/authorization/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "授权流程服务", + "description": "组织需要用户参与的登录和凭据授权流程。" + } +} diff --git a/packages/credentials/authorization/package.json b/packages/credentials/authorization/package.json index 8ceffd30dc..f0c692c7aa 100644 --- a/packages/credentials/authorization/package.json +++ b/packages/credentials/authorization/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-authorization", "description": "Authorization seam (ctx.authorization): plugin-owned flows that obtain a credential through a conversation with the human", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,9 +23,11 @@ "default": "./lib/types/types.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/credentials/credentials-local/locale/en.json b/packages/credentials/credentials-local/locale/en.json new file mode 100644 index 0000000000..04f0645da2 --- /dev/null +++ b/packages/credentials/credentials-local/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "credentials-local" + } +} diff --git a/packages/credentials/credentials-local/locale/zh.json b/packages/credentials/credentials-local/locale/zh.json new file mode 100644 index 0000000000..1c3eb9d615 --- /dev/null +++ b/packages/credentials/credentials-local/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "本地凭据存储", + "description": "保存 API 密钥等凭据,并按优先级读取环境变量和本地凭据文件。" + } +} diff --git a/packages/credentials/credentials-local/package.json b/packages/credentials/credentials-local/package.json index 93276c131e..501e8515ce 100644 --- a/packages/credentials/credentials-local/package.json +++ b/packages/credentials/credentials-local/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-credentials-local", "description": "File-backed credentials provider ($DSH_HOME/.env under the live process environment) for the DeepSeek Harness", - "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" ], @@ -34,7 +36,7 @@ "@deepseek-ai/cordis": "workspace:~" }, "dependencies": { - "chokidar": "^4.0.3", + "chokidar": "5.0.0", "@deepseek-ai/schemastery": "workspace:~", "yaml": "^2.9.0" }, diff --git a/packages/credentials/credentials/package.json b/packages/credentials/credentials/package.json index e6f5d79399..e14d7f0067 100644 --- a/packages/credentials/credentials/package.json +++ b/packages/credentials/credentials/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-credentials", "description": "Abstract credential seam (ctx.credentials): settings carry references to secrets, providers own the values", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/credentials/deepseek-account-platform/locale/en.json b/packages/credentials/deepseek-account-platform/locale/en.json new file mode 100644 index 0000000000..542b6b880f --- /dev/null +++ b/packages/credentials/deepseek-account-platform/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "deepseek-account-platform" + } +} diff --git a/packages/credentials/deepseek-account-platform/locale/zh.json b/packages/credentials/deepseek-account-platform/locale/zh.json new file mode 100644 index 0000000000..86bbe95c12 --- /dev/null +++ b/packages/credentials/deepseek-account-platform/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "DeepSeek 账号登录", + "description": "通过浏览器完成 DeepSeek 账号登录授权。" + } +} diff --git a/packages/credentials/deepseek-account-platform/package.json b/packages/credentials/deepseek-account-platform/package.json index 381954457a..fbd24caa37 100644 --- a/packages/credentials/deepseek-account-platform/package.json +++ b/packages/credentials/deepseek-account-platform/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-deepseek-account-platform", "description": "Authorize DeepSeek accounts through browser PKCE", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,9 +23,11 @@ "default": "./lib/types/types.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" @@ -47,6 +49,6 @@ }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" } } diff --git a/packages/credentials/deepseek-account/package.json b/packages/credentials/deepseek-account/package.json index c1b7867842..702347596b 100644 --- a/packages/credentials/deepseek-account/package.json +++ b/packages/credentials/deepseek-account/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-deepseek-account", "description": "Read account state and resolve official API credentials", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/deliverables/tool-present/locale/en.json b/packages/deliverables/tool-present/locale/en.json new file mode 100644 index 0000000000..6efec8a8e1 --- /dev/null +++ b/packages/deliverables/tool-present/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "tool-present" + } +} diff --git a/packages/deliverables/tool-present/locale/zh.json b/packages/deliverables/tool-present/locale/zh.json new file mode 100644 index 0000000000..c884f69fdd --- /dev/null +++ b/packages/deliverables/tool-present/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "文件交付工具", + "description": "让 AI 将工作区文件明确标记为本轮交付内容。" + } +} diff --git a/packages/deliverables/tool-present/package.json b/packages/deliverables/tool-present/package.json index 8bbd9e427b..6876a3ac26 100644 --- a/packages/deliverables/tool-present/package.json +++ b/packages/deliverables/tool-present/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-present", "description": "Explicit workspace file delivery declarations for the DeepSeek Harness", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,10 +23,12 @@ "default": "./lib/types/types.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "license": "MIT", "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/deliverables/workspace-changes/locale/en.json b/packages/deliverables/workspace-changes/locale/en.json new file mode 100644 index 0000000000..909d083bde --- /dev/null +++ b/packages/deliverables/workspace-changes/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "workspace-changes" + } +} diff --git a/packages/deliverables/workspace-changes/locale/zh.json b/packages/deliverables/workspace-changes/locale/zh.json new file mode 100644 index 0000000000..da51fea706 --- /dev/null +++ b/packages/deliverables/workspace-changes/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工作区变更记录", + "description": "记录每轮任务的文件变化,供逐文件比较。" + } +} diff --git a/packages/deliverables/workspace-changes/package.json b/packages/deliverables/workspace-changes/package.json index 5fc5f7ae86..fef51365a2 100644 --- a/packages/deliverables/workspace-changes/package.json +++ b/packages/deliverables/workspace-changes/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-workspace-changes", "description": "Per-turn workspace file changes recorded from git working-tree snapshots and whole-file captures, with per-file comparisons, for the DeepSeek Harness", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -23,10 +23,12 @@ "default": "./lib/types/types.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "license": "MIT", "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/document/office-to-pdf/locale/en.json b/packages/document/office-to-pdf/locale/en.json new file mode 100644 index 0000000000..574f708afe --- /dev/null +++ b/packages/document/office-to-pdf/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "office-to-pdf" + } +} diff --git a/packages/document/office-to-pdf/locale/zh.json b/packages/document/office-to-pdf/locale/zh.json new file mode 100644 index 0000000000..6a6243be60 --- /dev/null +++ b/packages/document/office-to-pdf/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Office 转 PDF", + "description": "将 Word、Excel 和 PowerPoint 等文档转换为 PDF,供预览使用。" + } +} diff --git a/packages/document/office-to-pdf/package.json b/packages/document/office-to-pdf/package.json index 26cc2f353c..eaf703ac3a 100644 --- a/packages/document/office-to-pdf/package.json +++ b/packages/document/office-to-pdf/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-office-to-pdf", "description": "Shared Office-to-PDF conversion with bounded queues and caching", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -32,9 +32,11 @@ "./typert": { "types": "./lib/typert.host.d.ts", "default": "./lib/typert.host.js" - } + }, + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts", @@ -59,6 +61,6 @@ "@deepseek-ai/schemastery": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "zod": "^4.4.3" + "zod": "4.4.3" } } diff --git a/packages/experimental/agent-team-profile/package.json b/packages/experimental/agent-team-profile/package.json index 0d907efdd8..3ab45ccad5 100644 --- a/packages/experimental/agent-team-profile/package.json +++ b/packages/experimental/agent-team-profile/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-agent-team-profile", "description": "Agent Teams collaboration, tools, and Web UI in one experimental bundle", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "icon": "./icon.svg", "publishConfig": { "access": "public" diff --git a/packages/experimental/agent-team/package.json b/packages/experimental/agent-team/package.json index 926a547376..2dde22ee3a 100644 --- a/packages/experimental/agent-team/package.json +++ b/packages/experimental/agent-team/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-agent-team", "description": "Implicit-root Agent Teams roster, direct peer messaging, and shared task DAG", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -40,7 +40,7 @@ "dependencies": { "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3" + "zod": "4.4.3" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/experimental/api-speech-to-text/locale/en.json b/packages/experimental/api-speech-to-text/locale/en.json new file mode 100644 index 0000000000..13dc1e6fad --- /dev/null +++ b/packages/experimental/api-speech-to-text/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Speech transcription API", + "description": "Provide speech transcription for browser clients." + } +} diff --git a/packages/experimental/api-speech-to-text/locale/zh.json b/packages/experimental/api-speech-to-text/locale/zh.json new file mode 100644 index 0000000000..ffcca2e772 --- /dev/null +++ b/packages/experimental/api-speech-to-text/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "语音转写接口", + "description": "为浏览器提供录音转写接口。" + } +} diff --git a/packages/experimental/api-speech-to-text/package.json b/packages/experimental/api-speech-to-text/package.json index 2c02c9443a..ea84596773 100644 --- a/packages/experimental/api-speech-to-text/package.json +++ b/packages/experimental/api-speech-to-text/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-api-speech-to-text", "description": "Authenticated experimental speech transcription for browser clients", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -20,6 +20,7 @@ }, "./src/*": "./src/*", "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json", "./types": { "types": "./lib/types/types.d.ts", "default": "./lib/types/types.js" @@ -34,6 +35,7 @@ } }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts", @@ -45,7 +47,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/experimental/auto-review/README.i18n.yaml b/packages/experimental/auto-review/README.i18n.yaml index b94783d099..93e5fd4cd1 100644 --- a/packages/experimental/auto-review/README.i18n.yaml +++ b/packages/experimental/auto-review/README.i18n.yaml @@ -18,8 +18,8 @@ en: 8f9e85817f05aa4d zh: f60136fb39abcf29 /deepseek-ai-dsh-experimental-auto-review/use-this-package/install-into-a-profile: - en: 63f8f1baa0fb2655 - zh: 6bc64160f6d02114 + en: cf146a773e8c7010 + zh: 57f7e9be7b257fcc /deepseek-ai-dsh-experimental-auto-review/use-this-package/what-you-get: en: 556e89c0055ae9cc zh: 75afbcb9a2af6467 diff --git a/packages/experimental/auto-review/README.md b/packages/experimental/auto-review/README.md index d2ae55e7e6..779339fd48 100644 --- a/packages/experimental/auto-review/README.md +++ b/packages/experimental/auto-review/README.md @@ -35,7 +35,7 @@ From this source checkout, install the package into the Web profile through the pnpm dsh plugin --profile web add ./packages/experimental/auto-review ``` -The CLI initializes the profile when needed and appends this package's declared patch after the base and Web layers. Reconciliation activates the patch as a profile layer; a package without `dsh.bundle.patch` is only an installed dependency. Select `Auto review` with its superscript `EXP` badge in the composer or `/permission` picker and confirm the current-session risk dialog. An explicit `/permission auto` command switches directly. General settings and future-session defaults do not offer Auto. +The CLI initializes the profile when needed and appends this package's declared patch after the base and Web layers. Reconciliation activates the patch as a profile layer; a package without `dsh.bundle.patch` is only an installed dependency. Select `Auto review` with its `EXP` badge in the composer menu or `/permission` picker and confirm the current-session risk dialog. An explicit `/permission auto` command switches directly. General settings and future-session defaults do not offer Auto. Remove the layer through the same CLI: diff --git a/packages/experimental/auto-review/README.zh.md b/packages/experimental/auto-review/README.zh.md index 5f7c1d5718..15656e5ab5 100644 --- a/packages/experimental/auto-review/README.zh.md +++ b/packages/experimental/auto-review/README.zh.md @@ -35,7 +35,7 @@ kind: "package-bundle" pnpm dsh plugin --profile web add ./packages/experimental/auto-review ``` -CLI 会在需要时初始化 profile,并将本包声明的 patch 追加到 base 与 Web 层之后。Reconciliation 将 patch 激活为 profile 层;没有 `dsh.bundle.patch` 的包只是已安装依赖。在 composer 或 `/permission` 选择器中选择带右上标 `EXP` 的 `Auto review`,并确认当前会话风险对话框。显式 `/permission auto` 命令直接切换。通用设置与未来会话默认值不提供 Auto。 +CLI 会在需要时初始化 profile,并将本包声明的 patch 追加到 base 与 Web 层之后。Reconciliation 将 patch 激活为 profile 层;没有 `dsh.bundle.patch` 的包只是已安装依赖。在 composer 菜单或 `/permission` 选择器中选择带 `EXP` 标记的「自动审查」,并确认当前会话风险对话框。显式 `/permission auto` 命令直接切换。通用设置与未来会话默认值不提供 Auto。 通过同一 CLI 移除此层: diff --git a/packages/experimental/auto-review/package.json b/packages/experimental/auto-review/package.json index fa458f0726..0e224849cc 100644 --- a/packages/experimental/auto-review/package.json +++ b/packages/experimental/auto-review/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-auto-review", "description": "Per-tool LLM authorization review for the DeepSeek Harness Auto permission preset", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "icon": "./icon.svg", "repository": { "type": "git", diff --git a/packages/experimental/badge-skill-bundle/icon.svg b/packages/experimental/badge-skill-bundle/icon.svg index f93a3b591d..7bd7490b92 100644 --- a/packages/experimental/badge-skill-bundle/icon.svg +++ b/packages/experimental/badge-skill-bundle/icon.svg @@ -1 +1,6 @@ - + + + + + + diff --git a/packages/experimental/badge-skill-bundle/package.json b/packages/experimental/badge-skill-bundle/package.json index 7853f04167..a3d065bb7e 100644 --- a/packages/experimental/badge-skill-bundle/package.json +++ b/packages/experimental/badge-skill-bundle/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-badge-skill-bundle", "description": "Offer the powered-by-DSH badge as a discoverable skill.", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "icon": "./icon.svg", "publishConfig": { "access": "public" diff --git a/packages/experimental/browser-use-chrome-devtools-mcp/package.json b/packages/experimental/browser-use-chrome-devtools-mcp/package.json index cee92d700c..335ad0d1ce 100644 --- a/packages/experimental/browser-use-chrome-devtools-mcp/package.json +++ b/packages/experimental/browser-use-chrome-devtools-mcp/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-browser-use-chrome-devtools-mcp", "description": "Experimental per-Session Chromium browser tools through chrome-devtools-mcp", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/browser-use-playwright-mcp/package.json b/packages/experimental/browser-use-playwright-mcp/package.json index 8f006c5310..f07fa1098c 100644 --- a/packages/experimental/browser-use-playwright-mcp/package.json +++ b/packages/experimental/browser-use-playwright-mcp/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-browser-use-playwright-mcp", "description": "Experimental per-Session Chromium browser tools through @playwright/mcp", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/browser-use-runtime/package.json b/packages/experimental/browser-use-runtime/package.json index ebefaf7e56..24e68569e6 100644 --- a/packages/experimental/browser-use-runtime/package.json +++ b/packages/experimental/browser-use-runtime/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-browser-use-runtime", "description": "Session-owned browser resource lifecycles and MCP integration for experimental providers", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/browser-use-stagehand-native/README.i18n.yaml b/packages/experimental/browser-use-stagehand-native/README.i18n.yaml index d65d51165d..e6668a0d43 100644 --- a/packages/experimental/browser-use-stagehand-native/README.i18n.yaml +++ b/packages/experimental/browser-use-stagehand-native/README.i18n.yaml @@ -24,8 +24,8 @@ en: fea3ad16a77fc478 zh: cf551a8a2d183f93 /deepseek-ai-dsh-experimental-browser-use-stagehand-native/understand-the-implementation: - en: ba13e1703d5aaca4 - zh: 91db415ed074307c + en: 123351a7c3d46f3e + zh: bf1cc2628edeb8d7 /deepseek-ai-dsh-experimental-browser-use-stagehand-native/further-exploration: en: eff8f4541eb26ca7 zh: 76a61fe9bd48df2a diff --git a/packages/experimental/browser-use-stagehand-native/README.md b/packages/experimental/browser-use-stagehand-native/README.md index 61f6c82c0a..ec1922366f 100644 --- a/packages/experimental/browser-use-stagehand-native/README.md +++ b/packages/experimental/browser-use-stagehand-native/README.md @@ -90,7 +90,7 @@ env -u NODE_USE_ENV_PROXY DSH_STAGEHAND_E2E=1 pnpm exec vitest run --config vite The host owns each launched Chromium process and its temporary profile before waiting for CDP readiness. Chromium receives the standard scrubbed child environment, preserving paths, locale, and proxy settings while excluding credential-shaped variables and DSH identity. Both modes connect the SDK inside a dedicated Worker. The Worker receives no ambient environment except the explicit source TypeScript configuration path, so its CDP connection does not inherit host proxy settings. SDK close waits for active operations. Cleanup terminates the connection Worker after the configured SDK grace; launch also kills and awaits its owned Chromium process before removing the profile. Attached external browsers remain open. Cleanup failures follow the [ownership limits](#known-limitations-and-deferred-work) below. -The [native runtime](src/native.ts) passes the explicit model configuration to Stagehand's public initialization API. Stagehand owns the model requests, response validation, and token accounting inside its browser extension. DSH records browser tool inputs and returned data, including SDK result metadata, through the existing Session log. Underlying inference request/response capture and integration into DSH Session usage accounting are deferred. +The [native runtime](src/native.ts) passes the explicit model configuration to Stagehand's public initialization API. The adapter pins Zod to the version required by Stagehand because extraction passes Zod schemas to the SDK. Stagehand owns the model requests, response validation, and token accounting inside its browser extension. DSH records browser tool inputs and returned data, including SDK result metadata, through the existing Session log. Underlying inference request/response capture and integration into DSH Session usage accounting are deferred. diff --git a/packages/experimental/browser-use-stagehand-native/README.zh.md b/packages/experimental/browser-use-stagehand-native/README.zh.md index cc64481db9..47f7e908d6 100644 --- a/packages/experimental/browser-use-stagehand-native/README.zh.md +++ b/packages/experimental/browser-use-stagehand-native/README.zh.md @@ -90,7 +90,7 @@ env -u NODE_USE_ENV_PROXY DSH_STAGEHAND_E2E=1 pnpm exec vitest run --config vite 宿主在等待 CDP 就绪前即拥有启动的 Chromium 进程及其临时配置目录。Chromium 接收标准清理后的子进程环境,保留路径、区域设置和代理配置,排除凭据形式的变量及 DSH 身份信息。两种模式都在独立 Worker 中连接 SDK。Worker 除显式的源码 TypeScript 配置路径外不接收宿主环境,因此其 CDP 连接不继承宿主代理设置。SDK 关闭会等待活动操作。清理在配置的 SDK 宽限时间后终止连接 Worker;启动模式还会终止并等待自有 Chromium 进程退出,再移除配置目录。外部连接的浏览器保持运行。清理失败遵循下方的[所有权限制](#known-limitations-and-deferred-work)。 -[原生运行时](src/native.ts)将显式模型配置传入 Stagehand 的公开初始化 API。Stagehand 在其浏览器扩展中负责模型请求、响应验证与 token 计量。DSH 通过现有 Session 日志记录浏览器工具输入和返回数据,包括 SDK 结果元数据。底层推理请求/响应捕获及其与 DSH Session 用量计量的集成均属暂缓工作。 +[原生运行时](src/native.ts)将显式模型配置传入 Stagehand 的公开初始化 API。适配器将 Zod 固定为 Stagehand 要求的版本,因为提取操作会向 SDK 传递 Zod schema。Stagehand 在其浏览器扩展中负责模型请求、响应验证与 token 计量。DSH 通过现有 Session 日志记录浏览器工具输入和返回数据,包括 SDK 结果元数据。底层推理请求/响应捕获及其与 DSH Session 用量计量的集成均属暂缓工作。 diff --git a/packages/experimental/browser-use-stagehand-native/package.json b/packages/experimental/browser-use-stagehand-native/package.json index ea9dd3142b..1b9632f111 100644 --- a/packages/experimental/browser-use-stagehand-native/package.json +++ b/packages/experimental/browser-use-stagehand-native/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-browser-use-stagehand-native", "description": "Experimental Stagehand browser tools with separately configured native models", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -44,7 +44,7 @@ "@deepseek-ai/dsh-mcp-client": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "zod": "^4.4.3", + "zod": "4.4.3", "@deepseek-ai/dsh-subprocess": "workspace:*", "@puppeteer/browsers": "3.2.2" }, diff --git a/packages/experimental/claude-code-mods/package.json b/packages/experimental/claude-code-mods/package.json index 21b9d18317..13ea2530f6 100644 --- a/packages/experimental/claude-code-mods/package.json +++ b/packages/experimental/claude-code-mods/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-claude-code-mods", "description": "Experimental bridge: load Claude Code mods (hooks modules) and run their hook chains on DeepSeek Harness extension points", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-agent-team/package.json b/packages/experimental/client-ui-agent-team/package.json index d1d727a400..73a171a53d 100644 --- a/packages/experimental/client-ui-agent-team/package.json +++ b/packages/experimental/client-ui-agent-team/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-client-ui-agent-team", "description": "Web Agent Teams roster, task board, and teammate navigation", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-claude-code-mods/package.json b/packages/experimental/client-ui-claude-code-mods/package.json index 0fa362cc1b..64416f9042 100644 --- a/packages/experimental/client-ui-claude-code-mods/package.json +++ b/packages/experimental/client-ui-claude-code-mods/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-client-ui-claude-code-mods", "description": "Web band above the prompt for Claude Code mods: draws each session's mod tree and sends button presses back to the bridge", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-cot-translation/package.json b/packages/experimental/client-ui-cot-translation/package.json index 90117ed048..9dcc42cc82 100644 --- a/packages/experimental/client-ui-cot-translation/package.json +++ b/packages/experimental/client-ui-cot-translation/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-client-ui-cot-translation", "description": "Optional machine translation of expanded reasoning, preserving original Session text", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-cot-translation/tests/mount.client.spec.ts b/packages/experimental/client-ui-cot-translation/tests/mount.client.spec.ts index 8731bcc974..ddd02ab7d2 100644 --- a/packages/experimental/client-ui-cot-translation/tests/mount.client.spec.ts +++ b/packages/experimental/client-ui-cot-translation/tests/mount.client.spec.ts @@ -146,10 +146,9 @@ it('loads the browser entry through its generated optional Remote contribution', }) -it.each(['loading', 'memory'] as const)('uses Host Google preferences while the settings form is %s', async (mode) => { +it('uses Host Google preferences while the settings form is loading', async () => { const preferences: CotTranslationPreferences = { provider: 'google', targetLanguage: 'ja' } const b = await fixture(false, preferences) - if (mode === 'memory') b.scope.publish({ status: 'unavailable', mode: 'memory', value: undefined }) try { const fiber = b.ctx.plugin({ inject: [...inject], apply: ctx => mountTranslation(ctx, contribution) }) await fiber diff --git a/packages/experimental/client-ui-voice-input/locale/en.json b/packages/experimental/client-ui-voice-input/locale/en.json new file mode 100644 index 0000000000..4f4aa36248 --- /dev/null +++ b/packages/experimental/client-ui-voice-input/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Voice recording", + "description": "Record speech and insert editable text into the conversation draft." + } +} diff --git a/packages/experimental/client-ui-voice-input/locale/zh.json b/packages/experimental/client-ui-voice-input/locale/zh.json new file mode 100644 index 0000000000..8f714c3f5a --- /dev/null +++ b/packages/experimental/client-ui-voice-input/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "录音输入", + "description": "录制语音,将识别结果填入会话草稿,支持编辑后发送。" + } +} diff --git a/packages/experimental/client-ui-voice-input/package.json b/packages/experimental/client-ui-voice-input/package.json index ede23b2d00..2c8aec199d 100644 --- a/packages/experimental/client-ui-voice-input/package.json +++ b/packages/experimental/client-ui-voice-input/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-client-ui-voice-input", "description": "Record speech and insert editable text into the conversation draft", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -20,12 +20,14 @@ }, "./src/*": "./src/*", "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json", "./client": { "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" } }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/experimental/computer-use-cua-driver-mcp/package.json b/packages/experimental/computer-use-cua-driver-mcp/package.json index b058a5c6b8..c03cfe0262 100644 --- a/packages/experimental/computer-use-cua-driver-mcp/package.json +++ b/packages/experimental/computer-use-cua-driver-mcp/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-computer-use-cua-driver-mcp", "description": "Experimental computer use through an installed Cua Driver MCP executable", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/computer-use-cua-driver-native/package.json b/packages/experimental/computer-use-cua-driver-native/package.json index e9055c9bb4..f1f7ebcbd2 100644 --- a/packages/experimental/computer-use-cua-driver-native/package.json +++ b/packages/experimental/computer-use-cua-driver-native/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-computer-use-cua-driver-native", "description": "Experimental computer-use provider embedding the Cua Driver native npm SDK", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -38,7 +38,7 @@ "@deepseek-ai/dsh-mcp-client": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", "@trycua/cua-driver": "0.28.0", - "zod": "^4.4.3" + "zod": "4.4.3" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/experimental/cot-translation-bundle/icon.svg b/packages/experimental/cot-translation-bundle/icon.svg index a0668aa95b..659d331adf 100644 --- a/packages/experimental/cot-translation-bundle/icon.svg +++ b/packages/experimental/cot-translation-bundle/icon.svg @@ -1,5 +1,16 @@ - - - - + + + + + + + + + + + + + + + diff --git a/packages/experimental/cot-translation-bundle/package.json b/packages/experimental/cot-translation-bundle/package.json index d723a94941..c0ed237a52 100644 --- a/packages/experimental/cot-translation-bundle/package.json +++ b/packages/experimental/cot-translation-bundle/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-cot-translation-bundle", "description": "Experimental machine translation of expanded reasoning", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "icon": "./icon.svg", "publishConfig": { "access": "public" diff --git a/packages/experimental/hook-protocol/package.json b/packages/experimental/hook-protocol/package.json index 1195c9de2c..16016ee13a 100644 --- a/packages/experimental/hook-protocol/package.json +++ b/packages/experimental/hook-protocol/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-hook-protocol", "description": "Shared Claude Code / Codex hook wire protocol: matcher engine, stdin/exit-code/stdout codec, multi-hook merge, and hook/* session events", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/hooks-claude-code/package.json b/packages/experimental/hooks-claude-code/package.json index 9799278af9..99015f344d 100644 --- a/packages/experimental/hooks-claude-code/package.json +++ b/packages/experimental/hooks-claude-code/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-hooks-claude-code", "description": "Bridge plugin: run a Claude Code hooks.json / settings hook config on the DeepSeek Harness interception seams", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/hooks-codex/package.json b/packages/experimental/hooks-codex/package.json index e4eac2a937..61ddc09cbd 100644 --- a/packages/experimental/hooks-codex/package.json +++ b/packages/experimental/hooks-codex/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-hooks-codex", "description": "Bridge plugin: run a Codex hooks.json hook config on the DeepSeek Harness interception seams", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/hooks-codex/src/index.ts b/packages/experimental/hooks-codex/src/index.ts index 8dc76fef58..139a99de6d 100644 --- a/packages/experimental/hooks-codex/src/index.ts +++ b/packages/experimental/hooks-codex/src/index.ts @@ -106,7 +106,7 @@ export function apply(ctx: Context, config: Config): void { // SessionStart is the one emit-shaped (detached) point Codex has: track its // run chains so disposal aborts a still-running hook process and drains the - // continuation (docs/defensive-patterns.md: dispose must reach quiescence). + // continuation (docs/defensive-patterns/general.md: dispose must reach quiescence). const detached = createDetachedRuns() ctx.effect(() => () => detached.drain(), 'hooks-codex: drain detached hook runs') diff --git a/packages/experimental/inspector-profile/icon.svg b/packages/experimental/inspector-profile/icon.svg index 5d50e0fa5a..7e1b599c02 100644 --- a/packages/experimental/inspector-profile/icon.svg +++ b/packages/experimental/inspector-profile/icon.svg @@ -1,12 +1,23 @@ - - - - + + + + + + + - - - + + + + + + + + + + + diff --git a/packages/experimental/inspector-profile/package.json b/packages/experimental/inspector-profile/package.json index 8a043b0a09..2528bcbfcd 100644 --- a/packages/experimental/inspector-profile/package.json +++ b/packages/experimental/inspector-profile/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-inspector-profile", "description": "Optional Web bundle for raw Session logs and Chat node inspection", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "icon": "./icon.svg", "publishConfig": { "access": "public" diff --git a/packages/experimental/inspector/icon.svg b/packages/experimental/inspector/icon.svg index 5d50e0fa5a..7e1b599c02 100644 --- a/packages/experimental/inspector/icon.svg +++ b/packages/experimental/inspector/icon.svg @@ -1,12 +1,23 @@ - - - - + + + + + + + - - - + + + + + + + + + + + diff --git a/packages/experimental/inspector/package.json b/packages/experimental/inspector/package.json index 225e54565f..4177a94c8a 100644 --- a/packages/experimental/inspector/package.json +++ b/packages/experimental/inspector/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-inspector", "description": "Experimental cross-realm CDP hub for Host debugging and Client Runtime inspection", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "icon": "./icon.svg", "publishConfig": { "access": "public" diff --git a/packages/experimental/ptc-runtime-python/package.json b/packages/experimental/ptc-runtime-python/package.json index 026dce8443..ef3eed920b 100644 --- a/packages/experimental/ptc-runtime-python/package.json +++ b/packages/experimental/ptc-runtime-python/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-ptc-runtime-python", "description": "CPython subprocess implementation of the DeepSeek Harness PTC execution seam", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "repository": { "type": "git", "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", diff --git a/packages/experimental/ptc-runtime-python/src/index.ts b/packages/experimental/ptc-runtime-python/src/index.ts index e34eeaf73b..1e12cd1e5f 100644 --- a/packages/experimental/ptc-runtime-python/src/index.ts +++ b/packages/experimental/ptc-runtime-python/src/index.ts @@ -1124,7 +1124,7 @@ export class PythonPtcRuntime extends PtcRuntime { // child can dispatch. `namespace.functions` is caller-supplied, so it may // expose members through getters or a Proxy; reading one of them inside // the fd-3 `data` callback would throw OUTSIDE the dispatcher's try and - // terminate the host (defensive-patterns contain-callback-exceptions). + // terminate the host (docs/defensive-patterns/general.md contain-callback-exceptions). // Reading every member here, in run()'s synchronous validation segment, // turns that throw into the seam-misuse rejection run() reserves for // malformed bindings. The snapshot is also the single key set the boot diff --git a/packages/experimental/ralph-bundle/package.json b/packages/experimental/ralph-bundle/package.json index f36ebb0eec..c0bc8b9385 100644 --- a/packages/experimental/ralph-bundle/package.json +++ b/packages/experimental/ralph-bundle/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-ralph-bundle", "description": "Run explicitly requested repeated work with fresh agents.", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "icon": "./icon.svg", "publishConfig": { "access": "public" diff --git a/packages/experimental/session-inspector/package.json b/packages/experimental/session-inspector/package.json index 9a9b2aa39e..e9fc0837bc 100644 --- a/packages/experimental/session-inspector/package.json +++ b/packages/experimental/session-inspector/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-session-inspector", "description": "Experimental virtualized Session log and live Chat group/node inspectors", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/session-search/icon.svg b/packages/experimental/session-search/icon.svg index c15c9846f7..bab706489c 100644 --- a/packages/experimental/session-search/icon.svg +++ b/packages/experimental/session-search/icon.svg @@ -1 +1,11 @@ - + + + + + + + + + + + diff --git a/packages/experimental/session-search/package.json b/packages/experimental/session-search/package.json index e563a02406..a405f03d08 100644 --- a/packages/experimental/session-search/package.json +++ b/packages/experimental/session-search/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-session-search", "description": "Give Agents tools to search and read earlier sessions from the current workspace.", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "icon": "./icon.svg", "publishConfig": { "access": "public" diff --git a/packages/experimental/session-title-all-prompts-llm/package.json b/packages/experimental/session-title-all-prompts-llm/package.json index ba782a31d4..0aff79b846 100644 --- a/packages/experimental/session-title-all-prompts-llm/package.json +++ b/packages/experimental/session-title-all-prompts-llm/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-session-title-all-prompts-llm", "description": "All-user-messages LLM provider plugin for DeepSeek Harness session titles", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/session-titles-bundle/icon.svg b/packages/experimental/session-titles-bundle/icon.svg index 1b0d19004b..5cba79b160 100644 --- a/packages/experimental/session-titles-bundle/icon.svg +++ b/packages/experimental/session-titles-bundle/icon.svg @@ -1 +1,11 @@ - + + + + + + + + + + + diff --git a/packages/experimental/session-titles-bundle/package.json b/packages/experimental/session-titles-bundle/package.json index 5232bea10c..0a7a9bc841 100644 --- a/packages/experimental/session-titles-bundle/package.json +++ b/packages/experimental/session-titles-bundle/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-session-titles-bundle", "description": "Refresh session titles as new human prompts arrive.", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "icon": "./icon.svg", "publishConfig": { "access": "public" diff --git a/packages/experimental/skill-badge/README.i18n.yaml b/packages/experimental/skill-badge/README.i18n.yaml index 1265a6ca82..b595cfef5e 100644 --- a/packages/experimental/skill-badge/README.i18n.yaml +++ b/packages/experimental/skill-badge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-skill-badge/use-this-package: - en: a559a5ed8a76e342 - zh: 6558f9af8d6c9625 + en: 0da087eb29c565b0 + zh: ec86044ef1255440 /deepseek-ai-dsh-skill-badge/use-this-package/when-to-choose-it: en: 4e424f3ab2a8b5b1 zh: e38162f15f0a8354 diff --git a/packages/experimental/skill-badge/README.md b/packages/experimental/skill-badge/README.md index 25bc5dd02e..3b0e0eeef5 100644 --- a/packages/experimental/skill-badge/README.md +++ b/packages/experimental/skill-badge/README.md @@ -27,6 +27,8 @@ Agents can load the official "powered by dsh" badge skill from this bundled prov Enable the plugin to make the `dsh-badge` skill available in the session skill catalog; the model can then load it like any other skill and follow its instructions for adding a "powered by dsh" badge. +In Plugins, this component is named **DSH** and uses the DSH tag icon. Its skill is named `dsh-badge`. + ### When to choose it Choose this provider when content produced with DeepSeek Harness should carry official attribution badges, and the deployment wants the badge skill available to agents without storing it in a local skill directory. Skip it when the badge is irrelevant to the deployment. The default composition omits the plugin; installation and an explicit active row are required. diff --git a/packages/experimental/skill-badge/README.zh.md b/packages/experimental/skill-badge/README.zh.md index 7beeb177e5..9c25477422 100644 --- a/packages/experimental/skill-badge/README.zh.md +++ b/packages/experimental/skill-badge/README.zh.md @@ -27,6 +27,8 @@ agent(智能体)可以通过该内置提供方加载官方「powered by dsh 启用插件即可让 `dsh-badge` skill 出现在会话 skill 目录中;随后模型可以像加载任何其他 skill 一样加载它,并遵循其指令添加「powered by dsh」徽章。 +在插件页面中,此组件显示为 **DSH**,并使用 DSH 标签图标。它提供的 skill 名称为 `dsh-badge`。 + ### 何时选择 当用 DeepSeek Harness 生成的内容应携带官方署名徽章、且部署方希望该徽章 skill 对 agent 可用而无需存入本地 skill 目录时,选择此提供方。当徽章与部署无关时,请跳过。默认组合省略此插件;使用它需要安装包并显式插入活动行。 diff --git a/packages/experimental/skill-badge/icon.svg b/packages/experimental/skill-badge/icon.svg new file mode 100644 index 0000000000..7bd7490b92 --- /dev/null +++ b/packages/experimental/skill-badge/icon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/packages/experimental/skill-badge/locale/en.json b/packages/experimental/skill-badge/locale/en.json new file mode 100644 index 0000000000..2c3c652416 --- /dev/null +++ b/packages/experimental/skill-badge/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "DSH", + "description": "Provide the official powered-by-DSH badge skill." + } +} diff --git a/packages/experimental/skill-badge/locale/zh.json b/packages/experimental/skill-badge/locale/zh.json new file mode 100644 index 0000000000..79c486b476 --- /dev/null +++ b/packages/experimental/skill-badge/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "DSH", + "description": "提供官方 powered-by-DSH 徽章技能。" + } +} diff --git a/packages/experimental/skill-badge/package.json b/packages/experimental/skill-badge/package.json index fdc2588323..21e93aea42 100644 --- a/packages/experimental/skill-badge/package.json +++ b/packages/experimental/skill-badge/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-skill-badge", "description": "Bundled dsh badge skill provider for DeepSeek Harness", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -18,9 +18,13 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, + "icon": "./icon.svg", "files": [ + "icon.svg", + "locale/*.json", "lib/index.js", "assets", "lib/types/**/*.d.ts" diff --git a/packages/experimental/skill-badge/tests/skill-badge.spec.ts b/packages/experimental/skill-badge/tests/skill-badge.spec.ts index f66e1bb9dc..f788164c4d 100644 --- a/packages/experimental/skill-badge/tests/skill-badge.spec.ts +++ b/packages/experimental/skill-badge/tests/skill-badge.spec.ts @@ -29,6 +29,19 @@ describe('dsh-skill-badge', () => { expect(await ctx.skills.list()).toEqual([]) }) + it('presents the component as DSH with the bundle tag artwork in both locales', async () => { + expect(JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'))).toMatchObject({ + icon: './icon.svg', + exports: { './locale/*.json': './locale/*.json' }, + }) + for (const language of ['en', 'zh']) { + expect(JSON.parse(await readFile(new URL(`../locale/${language}.json`, import.meta.url), 'utf8'))) + .toMatchObject({ meta: { title: 'DSH' } }) + } + expect(await readFile(new URL('../icon.svg', import.meta.url), 'utf8')) + .toBe(await readFile(new URL('../../badge-skill-bundle/icon.svg', import.meta.url), 'utf8')) + }) + it('ships the official 726×120 PNG unchanged', async () => { const image = await readFile(new URL('../assets/dsh-badge.png', import.meta.url)) expect(image.readUInt32BE(16)).toBe(726) diff --git a/packages/experimental/speech-to-text-sensevoice/locale/en.json b/packages/experimental/speech-to-text-sensevoice/locale/en.json new file mode 100644 index 0000000000..7e216a5a62 --- /dev/null +++ b/packages/experimental/speech-to-text-sensevoice/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Local SenseVoice recognition", + "description": "Transcribe recordings into text locally with SenseVoice." + } +} diff --git a/packages/experimental/speech-to-text-sensevoice/locale/zh.json b/packages/experimental/speech-to-text-sensevoice/locale/zh.json new file mode 100644 index 0000000000..e650c4410c --- /dev/null +++ b/packages/experimental/speech-to-text-sensevoice/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "SenseVoice 本地识别", + "description": "使用本机 SenseVoice 将录音转写为文字。" + } +} diff --git a/packages/experimental/speech-to-text-sensevoice/package.json b/packages/experimental/speech-to-text-sensevoice/package.json index f5889577ec..f1217e5475 100644 --- a/packages/experimental/speech-to-text-sensevoice/package.json +++ b/packages/experimental/speech-to-text-sensevoice/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-speech-to-text-sensevoice", "description": "Local SenseVoice ONNX transcription with a managed sherpa-onnx process", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -20,12 +20,14 @@ }, "./src/*": "./src/*", "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json", "./worker": { "types": "./lib/types/worker.d.ts", "default": "./lib/worker.js" } }, "files": [ + "locale/*.json", "lib/index.js", "lib/worker.js", "runtime/assets.json", @@ -35,7 +37,7 @@ "dependencies": { "@deepseek-ai/schemastery": "workspace:~", "@deepseek-ai/dsh-timeout": "workspace:*", - "zod": "^4.4.3", + "zod": "4.4.3", "sherpa-onnx-node": "1.13.8" }, "peerDependencies": { diff --git a/packages/experimental/speech-to-text/locale/en.json b/packages/experimental/speech-to-text/locale/en.json new file mode 100644 index 0000000000..7615fe7abc --- /dev/null +++ b/packages/experimental/speech-to-text/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Speech recognition", + "description": "Manage speech transcription and select a recognition service." + } +} diff --git a/packages/experimental/speech-to-text/locale/zh.json b/packages/experimental/speech-to-text/locale/zh.json new file mode 100644 index 0000000000..a383d395ba --- /dev/null +++ b/packages/experimental/speech-to-text/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "语音识别", + "description": "管理语音转写服务,并选择识别服务。" + } +} diff --git a/packages/experimental/speech-to-text/package.json b/packages/experimental/speech-to-text/package.json index aae9285419..c119558c2e 100644 --- a/packages/experimental/speech-to-text/package.json +++ b/packages/experimental/speech-to-text/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-speech-to-text", "description": "Experimental speech recognition with independently selectable providers", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -20,6 +20,7 @@ }, "./src/*": "./src/*", "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json", "./types": { "types": "./lib/types/types.d.ts", "default": "./lib/types/types.js" @@ -30,6 +31,7 @@ } }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/experimental/terminal-bundle/package.json b/packages/experimental/terminal-bundle/package.json index 18d5e3822b..4f09c47dfc 100644 --- a/packages/experimental/terminal-bundle/package.json +++ b/packages/experimental/terminal-bundle/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-terminal-bundle", "description": "Keep shell processes alive across tool calls.", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "icon": "./icon.svg", "publishConfig": { "access": "public" diff --git a/packages/experimental/tool-agent-team/package.json b/packages/experimental/tool-agent-team/package.json index 95222ce232..d00265adeb 100644 --- a/packages/experimental/tool-agent-team/package.json +++ b/packages/experimental/tool-agent-team/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-tool-agent-team", "description": "Scoped model-facing Agent Teams tools over ctx.agentTeams", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/tool-ralph/locale/en.json b/packages/experimental/tool-ralph/locale/en.json new file mode 100644 index 0000000000..fb6feb52e6 --- /dev/null +++ b/packages/experimental/tool-ralph/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "tool-ralph" + } +} diff --git a/packages/experimental/tool-ralph/locale/zh.json b/packages/experimental/tool-ralph/locale/zh.json new file mode 100644 index 0000000000..5e9601ee1f --- /dev/null +++ b/packages/experimental/tool-ralph/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Ralph 迭代工具", + "description": "围绕同一目标逐轮运行新的子智能体,并传递上一轮的简要报告。" + } +} diff --git a/packages/experimental/tool-ralph/package.json b/packages/experimental/tool-ralph/package.json index 3458cc12db..c7d94eb28a 100644 --- a/packages/experimental/tool-ralph/package.json +++ b/packages/experimental/tool-ralph/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-ralph", "description": "Model-facing fresh-agent Ralph loop over the workflow and subagent seams", - "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" ], diff --git a/packages/experimental/tool-session-query/package.json b/packages/experimental/tool-session-query/package.json index c2708f81bc..32f3903015 100644 --- a/packages/experimental/tool-session-query/package.json +++ b/packages/experimental/tool-session-query/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-session-query", "description": "Workspace-authorized model-facing session history search, trace, and event read tools", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/tool-terminal/package.json b/packages/experimental/tool-terminal/package.json index c3140c8ea5..11ee72a485 100644 --- a/packages/experimental/tool-terminal/package.json +++ b/packages/experimental/tool-terminal/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-terminal", "description": "Six model-facing persistent PTY tools with owner isolation and generic background-job integration", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/tool-worktree/icon.svg b/packages/experimental/tool-worktree/icon.svg index 69cc03bf5e..b8e63a6b81 100644 --- a/packages/experimental/tool-worktree/icon.svg +++ b/packages/experimental/tool-worktree/icon.svg @@ -1,6 +1,18 @@ - - - - - + + + + + + + + + + + + + + + + + diff --git a/packages/experimental/tool-worktree/package.json b/packages/experimental/tool-worktree/package.json index 80c110c98d..b670ecf50c 100644 --- a/packages/experimental/tool-worktree/package.json +++ b/packages/experimental/tool-worktree/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-tool-worktree", "description": "Model tool that creates and enters a new Git worktree", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/translator/package.json b/packages/experimental/translator/package.json index 0111d23db6..31f2c3da09 100644 --- a/packages/experimental/translator/package.json +++ b/packages/experimental/translator/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-translator", "description": "Machine translation with reusable Session results", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/voice-input-bundle/package.json b/packages/experimental/voice-input-bundle/package.json index 846db038ad..d7935dc51e 100644 --- a/packages/experimental/voice-input-bundle/package.json +++ b/packages/experimental/voice-input-bundle/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-voice-input-bundle", "description": "Experimental voice input with local SenseVoice; downloads its runtime on first use", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "icon": "./icon.svg", "publishConfig": { "access": "public" diff --git a/packages/experimental/webhook-github/package.json b/packages/experimental/webhook-github/package.json index f1f5c2c14a..710d0de493 100644 --- a/packages/experimental/webhook-github/package.json +++ b/packages/experimental/webhook-github/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-webhook-github", "description": "Signed GitHub HTTP webhook adapter for the DeepSeek Harness webhook runtime", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/webhook/package.json b/packages/experimental/webhook/package.json index 3674193d07..742e04231b 100644 --- a/packages/experimental/webhook/package.json +++ b/packages/experimental/webhook/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-webhook", "description": "Fire-and-forget webhook rule runtime that creates Workspace-backed DeepSeek Harness Sessions", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/webworker-packer/package.json b/packages/experimental/webworker-packer/package.json index 27220fa0b3..ca5ac4da53 100644 --- a/packages/experimental/webworker-packer/package.json +++ b/packages/experimental/webworker-packer/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-webworker-packer", "description": "Build-time packer for the browser runtime's base VFS image and ordered data-overlay archives", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/webworker-packer/tests/preview.spec.ts b/packages/experimental/webworker-packer/tests/preview.spec.ts index f3b5937ab9..0e0c7f7e12 100644 --- a/packages/experimental/webworker-packer/tests/preview.spec.ts +++ b/packages/experimental/webworker-packer/tests/preview.spec.ts @@ -42,7 +42,7 @@ function restore(bytes: Uint8Array | undefined) { } describe('Node preparation of Preview Session data', () => { - it('packs strictly migrated current successors beside every unchanged example file', () => { + it('packs current Sessions and migrated children beside every unchanged example file', () => { const fixture = previewFixtures(repoRoot)[0]! const original = packVfsOverlay(fixture.trees) const projected = packPreviewFixture(fixture.trees) @@ -50,15 +50,13 @@ describe('Node preparation of Preview Session data', () => { expect(currentFiles).toHaveLength(3) for (const [path, bytes] of Object.entries(original.files)) expect(projected.files[path], path).toEqual(bytes) for (const path of currentFiles) { - const sourcePath = path.replace(/\/session\.v\d+\.jsonl$/u, '/session.v3.jsonl') - const historical = restore(original.files[sourcePath]) const current = restore(projected.files[path]) - const appended = path.includes('/preview-showcase/') ? [ - { version: 0, childId: 'preview-architecture-review', childCreatedAt: 1787472100000, mode: 'one-shot', label: 'Review preview architecture' }, - { version: 0, childId: 'preview-follow-up-builder', childCreatedAt: 1787472200000, mode: 'continuable', label: 'Continue preview verification' }, - ].map((data, index) => ({ type: 'subagent/catalog', seq: historical.events.length + index, - time: historical.events.at(-1)!.time, data })) : [] - expect(current).toEqual({ ...historical, events: [...historical.events, ...appended] }) + if (original.files[path] !== undefined) { + expect(projected.files[path]).toEqual(original.files[path]) + } else { + const sourcePath = path.replace(/\/session\.v\d+\.jsonl$/u, '/session.v3.jsonl') + expect(current).toEqual(restore(original.files[sourcePath])) + } expect(JSON.parse(text(projected.files[path]).split('\n')[0]!)).toMatchObject({ version: currentVersion }) } expect(packPreviewFixture(fixture.trees).image).toEqual(projected.image) diff --git a/packages/experimental/webworker-runtime/README.i18n.yaml b/packages/experimental/webworker-runtime/README.i18n.yaml index d70dd93cb7..3ac3336a7a 100644 --- a/packages/experimental/webworker-runtime/README.i18n.yaml +++ b/packages/experimental/webworker-runtime/README.i18n.yaml @@ -15,8 +15,8 @@ en: 4e53164159b5ce41 zh: 89582dc0294d0776 /deepseek-ai-dsh-experimental-webworker-runtime/use-this-package: - en: 6dd3d8495bc6ee61 - zh: 71f7da310233a37b + en: aed3c07b75b29e34 + zh: b609ae0f5796aa34 /deepseek-ai-dsh-experimental-webworker-runtime/model-experience: en: 61fce9b4c7dc96e6 zh: dc2d931063a38327 diff --git a/packages/experimental/webworker-runtime/README.md b/packages/experimental/webworker-runtime/README.md index 8394296bf2..2f5619640f 100644 --- a/packages/experimental/webworker-runtime/README.md +++ b/packages/experimental/webworker-runtime/README.md @@ -32,7 +32,7 @@ Three build artifacts and one source-owned process layer: - **`src/shell/` (the worker's own process layer)** — a browser worker cannot fork, so `node:child_process` is not a stub but an implementation: `spawn` starts the command in its own Web Worker — this same bundle, told by its first frame to be a shell process — and reports it through the `ChildProcess` surface the subprocess service consumes. The command runs off the host's thread, `SIGKILL` terminates it whatever it is doing, and it reaches the VFS only by message (the host serves those frames). Worker platform executables preserve native-package protocols such as Landlock without replacing their JavaScript packages or coupling their implementations to `node:child_process`; `xdg-open` sends one VFS text file to the page's read-only viewer, so desktop-opener actions such as **Open configuration file** show the file in the page; ordinary commands use the package's evaluator and coreutils command table. The grammar is `@yarnpkg/parsers`' `parseShell`, while `execSync`/`fork` still refuse because they need a real process. - **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` fetches each combo on first demand, embeds its tunnel-only source map as a Base64 data URL, and executes the script as a Blob. The worker's unsolicited `view-text` frame opens the page's modal text viewer. The tunnel also exposes fetch-shaped transport, the independent file-upload carrier, and the API client. Request frames preserve Blob bodies through structured clone and transfer `ReadableStream` ownership. The Host Worker streams both forms into the route, so neither browser thread creates a complete byte array for a generic-file upload. A Remote stream's uplink crosses as `stream-uplink-item` / `stream-uplink-end` frames into an unbounded `TunnelUplink` that drops items arriving after `end`: the page and its worker are one trusted same-origin boundary, so the Host inbox cap does not apply. -Acceptance lives in `apps/web/tests/preview-boot.e2e.ts`, which serves the real built pages and drives the pre-boot chooser plus Worker activation in headless Chromium. The empty selection exercises first-run startup. The `vfs-example` overlay supplies ordinary workspace files and plaintext persistence artifacts for cold Workspace/Session discovery, tool presentation, subagent navigation, and history paging without a model request. The [packer](../webworker-packer/README.md) prepares current-generation successors from committed historical logs in Node; those source logs remain byte-identical in the overlay. The fixture generator owns the acceptance test's current projection cache. The chooser reserves WebFS as a separate user-authorized source; that provider does not read the built-in fixture. +Acceptance lives in `apps/web/tests/preview-boot.e2e.ts`, which serves the real built pages and drives the pre-boot chooser plus Worker activation in headless Chromium. The empty selection exercises first-run startup. The `vfs-example` overlay supplies ordinary workspace files and plaintext persistence artifacts for cold Workspace/Session discovery, tool presentation, subagent navigation, and history paging without a model request. The showcase mixes empty, whitespace-only, and non-empty reasoning with a long multiline command and a parent-path file link; these are authored fixtures, not live model output. The [packer](../webworker-packer/README.md) prepares current-generation successors from committed historical logs in Node; those source logs remain byte-identical in the overlay. The fixture generator owns the acceptance test's current projection cache. The chooser reserves WebFS as a separate user-authorized source; that provider does not read the built-in fixture. The [built-bundle import sweep](tests/compile/transform-corpus-check.ts) checks bare Node imports after the library build. Its Dockkit exception accepts Node’s unknown-`.css`-extension refusal for any stylesheet rather than one pinned path; another extension, error code, or message, and an unexpectedly successful exempt import, remain errors. diff --git a/packages/experimental/webworker-runtime/README.zh.md b/packages/experimental/webworker-runtime/README.zh.md index b63f81247b..dffbb30718 100644 --- a/packages/experimental/webworker-runtime/README.zh.md +++ b/packages/experimental/webworker-runtime/README.zh.md @@ -32,7 +32,7 @@ kind: "package-library" - **`src/shell/`(worker 自己的进程层)**——浏览器 worker 无法 fork,所以 `node:child_process` 不是 stub 而是实现:`spawn` 把命令放进它自己的 Web Worker——就是这同一个束,由首帧告诉它「你是 shell 进程」——并以 subprocess 服务消费的 `ChildProcess` 面报告结果。命令不占宿主线程,`SIGKILL` 不管它在干什么都能终止它,而它只能靠消息触达 VFS(由宿主应答这些帧)。Worker 平台 executable 在不替换 JavaScript 包、也不把具体实现耦合进 `node:child_process` 的情况下保持 Landlock 等 native 包协议;`xdg-open` 把一个 VFS 文本文件交给页面的只读查看器,因此 **打开配置文件** 等桌面打开操作会在页面内显示该文件;普通命令使用本包的求值器与 coreutils 命令表。语法来自 `@yarnpkg/parsers` 的 `parseShell`,而 `execSync`/`fork` 依然拒绝,因为它们需要真进程。 - **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时获取 combo、把仅 tunnel 可达的 sourcemap 内嵌为 Base64 data URL,再以 Blob 执行脚本。worker 主动发出的 `view-text` 帧会打开页面的模态文本查看器。Tunnel 还暴露 fetch 形式的传输、独立文件上传载体和 API 客户端。请求帧通过结构化克隆保留 Blob 请求体,并转移 `ReadableStream` 的所有权。Host Worker 将两种请求体都逐块送入路由,因此通用文件上传不会在任何浏览器线程创建完整字节数组。Remote 流的上行以 `stream-uplink-item` / `stream-uplink-end` 帧进入没有上限的 `TunnelUplink`,`end` 之后到达的项被丢弃:页面与其 worker 是同一个可信的同源边界,Host 的 inbox 上限在此不适用。 -验收在 `apps/web/tests/preview-boot.e2e.ts`:静态服务真实构建页面,在 headless Chromium 里驱动 pre-boot 选择面板与 Worker 激活。空白选择验证首次启动;`vfs-example` overlay 提供普通 workspace 文件与明文 persistence 产物,无需模型请求即可验证 Workspace/Session 冷发现、工具呈现、subagent 导航和历史分页。[打包器](../webworker-packer/README.zh.md)在 Node 中根据已提交的历史日志准备当前代后继文件;这些源日志在 overlay 中逐字节保持不变。fixture 生成器负责验收测试的当前投影缓存。选择面板为 WebFS 保留独立的用户授权来源;该 provider 不读取内置 fixture。 +验收在 `apps/web/tests/preview-boot.e2e.ts`:静态服务真实构建页面,在 headless Chromium 里驱动 pre-boot 选择面板与 Worker 激活。空白选择验证首次启动;`vfs-example` overlay 提供普通 workspace 文件与明文 persistence 产物,无需模型请求即可验证 Workspace/Session 冷发现、工具呈现、subagent 导航和历史分页。showcase 混排空字符串、纯空白与非空推理块,并包含多行长命令和父路径文件链接;这些是人工构造的 fixture,不是真实模型输出。[打包器](../webworker-packer/README.zh.md)在 Node 中根据已提交的历史日志准备当前代后继文件;这些源日志在 overlay 中逐字节保持不变。fixture 生成器负责验收测试的当前投影缓存。选择面板为 WebFS 保留独立的用户授权来源;该 provider 不读取内置 fixture。 [已构建 bundle 导入检查](tests/compile/transform-corpus-check.ts)在库构建后检查裸 Node 导入。Dockkit 例外接受 Node 针对任意样式表报告的未知 `.css` 扩展名错误,而不限定某一固定路径;其他扩展名、错误码或消息,以及意外成功的豁免导入,仍然报错。 diff --git a/packages/experimental/webworker-runtime/package.json b/packages/experimental/webworker-runtime/package.json index 2fd84363f7..8605766f06 100644 --- a/packages/experimental/webworker-runtime/package.json +++ b/packages/experimental/webworker-runtime/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-webworker-runtime", "description": "Browser-only harness runtime: in-memory VFS, module transform and loader, postMessage tunnel, and the dedicated Web Worker assembly, with the Node-compatibility layer that lets the host tree run unchanged", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, @@ -64,7 +64,7 @@ "@deepseek-ai/node-addon-system": "workspace:~", "@types/picomatch": "^4.0.3", "@types/readable-stream": "^4.0.24", - "chokidar": "^5.0.0" + "chokidar": "5.0.0" }, "files": [ "lib/index.js", diff --git a/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-showcase/session.v4.jsonl b/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-showcase/session.v4.jsonl new file mode 100644 index 0000000000..abed3fcfd9 --- /dev/null +++ b/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-showcase/session.v4.jsonl @@ -0,0 +1,204 @@ +{"type":"session","version":4,"id":"preview-showcase","createdAt":1787472000000,"cwd":"/dsh/workspace","isSeeded":false,"delegationDepth":0,"agentPreset":"standard"} +{"type":"turn/start","data":{"turn":1},"seq":0,"time":1787472000000} +{"type":"user/message","data":{"id":"preview-user-01","role":"user","content":[{"type":"text","text":"History checkpoint 01: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":1,"time":1787472000001} +{"type":"session/title","data":{"title":"WebWorker Preview Showcase","messageSeqs":[],"source":{"kind":"user"}},"seq":2,"time":1787472000002} +{"type":"step/start","data":{"turn":1,"step":1},"seq":3,"time":1787472000003} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"id":"preview-assistant-01","role":"assistant","content":[{"type":"text","text":"Checkpoint 01 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 01 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 01 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":4,"time":1787472000004} +{"type":"step/end","data":{"turn":1,"step":1},"seq":5,"time":1787472000005} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}},"seq":6,"time":1787472000006} +{"type":"turn/start","data":{"turn":2},"seq":7,"time":1787472000007} +{"type":"user/message","data":{"id":"preview-user-02","role":"user","content":[{"type":"text","text":"History checkpoint 02: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":8,"time":1787472000008} +{"type":"step/start","data":{"turn":2,"step":1},"seq":9,"time":1787472000009} +{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"id":"preview-assistant-02","role":"assistant","content":[{"type":"text","text":"Checkpoint 02 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 02 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 02 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":10,"time":1787472000010} +{"type":"step/end","data":{"turn":2,"step":1},"seq":11,"time":1787472000011} +{"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}},"seq":12,"time":1787472000012} +{"type":"turn/start","data":{"turn":3},"seq":13,"time":1787472000013} +{"type":"user/message","data":{"id":"preview-user-03","role":"user","content":[{"type":"text","text":"History checkpoint 03: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":14,"time":1787472000014} +{"type":"step/start","data":{"turn":3,"step":1},"seq":15,"time":1787472000015} +{"type":"assistant/message","data":{"turn":3,"step":1,"message":{"id":"preview-assistant-03","role":"assistant","content":[{"type":"text","text":"Checkpoint 03 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 03 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 03 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":16,"time":1787472000016} +{"type":"step/end","data":{"turn":3,"step":1},"seq":17,"time":1787472000017} +{"type":"turn/end","data":{"turn":3,"reason":{"kind":"completed"}},"seq":18,"time":1787472000018} +{"type":"turn/start","data":{"turn":4},"seq":19,"time":1787472000019} +{"type":"user/message","data":{"id":"preview-user-04","role":"user","content":[{"type":"text","text":"History checkpoint 04: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":20,"time":1787472000020} +{"type":"step/start","data":{"turn":4,"step":1},"seq":21,"time":1787472000021} +{"type":"assistant/message","data":{"turn":4,"step":1,"message":{"id":"preview-assistant-04","role":"assistant","content":[{"type":"text","text":"Checkpoint 04 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 04 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 04 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":22,"time":1787472000022} +{"type":"step/end","data":{"turn":4,"step":1},"seq":23,"time":1787472000023} +{"type":"turn/end","data":{"turn":4,"reason":{"kind":"completed"}},"seq":24,"time":1787472000024} +{"type":"turn/start","data":{"turn":5},"seq":25,"time":1787472000025} +{"type":"user/message","data":{"id":"preview-user-05","role":"user","content":[{"type":"text","text":"History checkpoint 05: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":26,"time":1787472000026} +{"type":"step/start","data":{"turn":5,"step":1},"seq":27,"time":1787472000027} +{"type":"assistant/message","data":{"turn":5,"step":1,"message":{"id":"preview-assistant-05","role":"assistant","content":[{"type":"text","text":"Checkpoint 05 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 05 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 05 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":28,"time":1787472000028} +{"type":"step/end","data":{"turn":5,"step":1},"seq":29,"time":1787472000029} +{"type":"turn/end","data":{"turn":5,"reason":{"kind":"completed"}},"seq":30,"time":1787472000030} +{"type":"turn/start","data":{"turn":6},"seq":31,"time":1787472000031} +{"type":"user/message","data":{"id":"preview-user-06","role":"user","content":[{"type":"text","text":"History checkpoint 06: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":32,"time":1787472000032} +{"type":"step/start","data":{"turn":6,"step":1},"seq":33,"time":1787472000033} +{"type":"assistant/message","data":{"turn":6,"step":1,"message":{"id":"preview-assistant-06","role":"assistant","content":[{"type":"text","text":"Checkpoint 06 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 06 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 06 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":34,"time":1787472000034} +{"type":"step/end","data":{"turn":6,"step":1},"seq":35,"time":1787472000035} +{"type":"turn/end","data":{"turn":6,"reason":{"kind":"completed"}},"seq":36,"time":1787472000036} +{"type":"turn/start","data":{"turn":7},"seq":37,"time":1787472000037} +{"type":"user/message","data":{"id":"preview-user-07","role":"user","content":[{"type":"text","text":"History checkpoint 07: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":38,"time":1787472000038} +{"type":"step/start","data":{"turn":7,"step":1},"seq":39,"time":1787472000039} +{"type":"assistant/message","data":{"turn":7,"step":1,"message":{"id":"preview-assistant-07","role":"assistant","content":[{"type":"text","text":"Checkpoint 07 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 07 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 07 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":40,"time":1787472000040} +{"type":"step/end","data":{"turn":7,"step":1},"seq":41,"time":1787472000041} +{"type":"turn/end","data":{"turn":7,"reason":{"kind":"completed"}},"seq":42,"time":1787472000042} +{"type":"turn/start","data":{"turn":8},"seq":43,"time":1787472000043} +{"type":"user/message","data":{"id":"preview-user-08","role":"user","content":[{"type":"text","text":"History checkpoint 08: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":44,"time":1787472000044} +{"type":"step/start","data":{"turn":8,"step":1},"seq":45,"time":1787472000045} +{"type":"assistant/message","data":{"turn":8,"step":1,"message":{"id":"preview-assistant-08","role":"assistant","content":[{"type":"text","text":"Checkpoint 08 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 08 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 08 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":46,"time":1787472000046} +{"type":"step/end","data":{"turn":8,"step":1},"seq":47,"time":1787472000047} +{"type":"turn/end","data":{"turn":8,"reason":{"kind":"completed"}},"seq":48,"time":1787472000048} +{"type":"turn/start","data":{"turn":9},"seq":49,"time":1787472000049} +{"type":"user/message","data":{"id":"preview-user-09","role":"user","content":[{"type":"text","text":"History checkpoint 09: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":50,"time":1787472000050} +{"type":"step/start","data":{"turn":9,"step":1},"seq":51,"time":1787472000051} +{"type":"assistant/message","data":{"turn":9,"step":1,"message":{"id":"preview-assistant-09","role":"assistant","content":[{"type":"text","text":"Checkpoint 09 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 09 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 09 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":52,"time":1787472000052} +{"type":"step/end","data":{"turn":9,"step":1},"seq":53,"time":1787472000053} +{"type":"turn/end","data":{"turn":9,"reason":{"kind":"completed"}},"seq":54,"time":1787472000054} +{"type":"turn/start","data":{"turn":10},"seq":55,"time":1787472000055} +{"type":"user/message","data":{"id":"preview-user-10","role":"user","content":[{"type":"text","text":"History checkpoint 10: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":56,"time":1787472000056} +{"type":"step/start","data":{"turn":10,"step":1},"seq":57,"time":1787472000057} +{"type":"assistant/message","data":{"turn":10,"step":1,"message":{"id":"preview-assistant-10","role":"assistant","content":[{"type":"text","text":"Checkpoint 10 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 10 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 10 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":58,"time":1787472000058} +{"type":"step/end","data":{"turn":10,"step":1},"seq":59,"time":1787472000059} +{"type":"turn/end","data":{"turn":10,"reason":{"kind":"completed"}},"seq":60,"time":1787472000060} +{"type":"turn/start","data":{"turn":11},"seq":61,"time":1787472000061} +{"type":"user/message","data":{"id":"preview-user-11","role":"user","content":[{"type":"text","text":"History checkpoint 11: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":62,"time":1787472000062} +{"type":"step/start","data":{"turn":11,"step":1},"seq":63,"time":1787472000063} +{"type":"assistant/message","data":{"turn":11,"step":1,"message":{"id":"preview-assistant-11","role":"assistant","content":[{"type":"text","text":"Checkpoint 11 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 11 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 11 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":64,"time":1787472000064} +{"type":"step/end","data":{"turn":11,"step":1},"seq":65,"time":1787472000065} +{"type":"turn/end","data":{"turn":11,"reason":{"kind":"completed"}},"seq":66,"time":1787472000066} +{"type":"turn/start","data":{"turn":12},"seq":67,"time":1787472000067} +{"type":"user/message","data":{"id":"preview-user-12","role":"user","content":[{"type":"text","text":"History checkpoint 12: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":68,"time":1787472000068} +{"type":"step/start","data":{"turn":12,"step":1},"seq":69,"time":1787472000069} +{"type":"assistant/message","data":{"turn":12,"step":1,"message":{"id":"preview-assistant-12","role":"assistant","content":[{"type":"text","text":"Checkpoint 12 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 12 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 12 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":70,"time":1787472000070} +{"type":"step/end","data":{"turn":12,"step":1},"seq":71,"time":1787472000071} +{"type":"turn/end","data":{"turn":12,"reason":{"kind":"completed"}},"seq":72,"time":1787472000072} +{"type":"turn/start","data":{"turn":13},"seq":73,"time":1787472000073} +{"type":"user/message","data":{"id":"preview-user-13","role":"user","content":[{"type":"text","text":"History checkpoint 13: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":74,"time":1787472000074} +{"type":"step/start","data":{"turn":13,"step":1},"seq":75,"time":1787472000075} +{"type":"assistant/message","data":{"turn":13,"step":1,"message":{"id":"preview-assistant-13","role":"assistant","content":[{"type":"text","text":"Checkpoint 13 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 13 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 13 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":76,"time":1787472000076} +{"type":"step/end","data":{"turn":13,"step":1},"seq":77,"time":1787472000077} +{"type":"turn/end","data":{"turn":13,"reason":{"kind":"completed"}},"seq":78,"time":1787472000078} +{"type":"turn/start","data":{"turn":14},"seq":79,"time":1787472000079} +{"type":"user/message","data":{"id":"preview-user-14","role":"user","content":[{"type":"text","text":"History checkpoint 14: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":80,"time":1787472000080} +{"type":"step/start","data":{"turn":14,"step":1},"seq":81,"time":1787472000081} +{"type":"assistant/message","data":{"turn":14,"step":1,"message":{"id":"preview-assistant-14","role":"assistant","content":[{"type":"text","text":"Checkpoint 14 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 14 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 14 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":82,"time":1787472000082} +{"type":"step/end","data":{"turn":14,"step":1},"seq":83,"time":1787472000083} +{"type":"turn/end","data":{"turn":14,"reason":{"kind":"completed"}},"seq":84,"time":1787472000084} +{"type":"turn/start","data":{"turn":15},"seq":85,"time":1787472000085} +{"type":"user/message","data":{"id":"preview-user-15","role":"user","content":[{"type":"text","text":"History checkpoint 15: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":86,"time":1787472000086} +{"type":"step/start","data":{"turn":15,"step":1},"seq":87,"time":1787472000087} +{"type":"assistant/message","data":{"turn":15,"step":1,"message":{"id":"preview-assistant-15","role":"assistant","content":[{"type":"text","text":"Checkpoint 15 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 15 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 15 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":88,"time":1787472000088} +{"type":"step/end","data":{"turn":15,"step":1},"seq":89,"time":1787472000089} +{"type":"turn/end","data":{"turn":15,"reason":{"kind":"completed"}},"seq":90,"time":1787472000090} +{"type":"turn/start","data":{"turn":16},"seq":91,"time":1787472000091} +{"type":"user/message","data":{"id":"preview-user-16","role":"user","content":[{"type":"text","text":"History checkpoint 16: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":92,"time":1787472000092} +{"type":"step/start","data":{"turn":16,"step":1},"seq":93,"time":1787472000093} +{"type":"assistant/message","data":{"turn":16,"step":1,"message":{"id":"preview-assistant-16","role":"assistant","content":[{"type":"text","text":"Checkpoint 16 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 16 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 16 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":94,"time":1787472000094} +{"type":"step/end","data":{"turn":16,"step":1},"seq":95,"time":1787472000095} +{"type":"turn/end","data":{"turn":16,"reason":{"kind":"completed"}},"seq":96,"time":1787472000096} +{"type":"turn/start","data":{"turn":17},"seq":97,"time":1787472000097} +{"type":"user/message","data":{"id":"preview-user-17","role":"user","content":[{"type":"text","text":"History checkpoint 17: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":98,"time":1787472000098} +{"type":"step/start","data":{"turn":17,"step":1},"seq":99,"time":1787472000099} +{"type":"assistant/message","data":{"turn":17,"step":1,"message":{"id":"preview-assistant-17","role":"assistant","content":[{"type":"text","text":"Checkpoint 17 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 17 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 17 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":100,"time":1787472000100} +{"type":"step/end","data":{"turn":17,"step":1},"seq":101,"time":1787472000101} +{"type":"turn/end","data":{"turn":17,"reason":{"kind":"completed"}},"seq":102,"time":1787472000102} +{"type":"turn/start","data":{"turn":18},"seq":103,"time":1787472000103} +{"type":"user/message","data":{"id":"preview-user-18","role":"user","content":[{"type":"text","text":"History checkpoint 18: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":104,"time":1787472000104} +{"type":"step/start","data":{"turn":18,"step":1},"seq":105,"time":1787472000105} +{"type":"assistant/message","data":{"turn":18,"step":1,"message":{"id":"preview-assistant-18","role":"assistant","content":[{"type":"text","text":"Checkpoint 18 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 18 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 18 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":106,"time":1787472000106} +{"type":"step/end","data":{"turn":18,"step":1},"seq":107,"time":1787472000107} +{"type":"turn/end","data":{"turn":18,"reason":{"kind":"completed"}},"seq":108,"time":1787472000108} +{"type":"turn/start","data":{"turn":19},"seq":109,"time":1787472000109} +{"type":"user/message","data":{"id":"preview-user-19","role":"user","content":[{"type":"text","text":"History checkpoint 19: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":110,"time":1787472000110} +{"type":"step/start","data":{"turn":19,"step":1},"seq":111,"time":1787472000111} +{"type":"assistant/message","data":{"turn":19,"step":1,"message":{"id":"preview-assistant-19","role":"assistant","content":[{"type":"text","text":"Checkpoint 19 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 19 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 19 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":112,"time":1787472000112} +{"type":"step/end","data":{"turn":19,"step":1},"seq":113,"time":1787472000113} +{"type":"turn/end","data":{"turn":19,"reason":{"kind":"completed"}},"seq":114,"time":1787472000114} +{"type":"turn/start","data":{"turn":20},"seq":115,"time":1787472000115} +{"type":"user/message","data":{"id":"preview-user-20","role":"user","content":[{"type":"text","text":"History checkpoint 20: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":116,"time":1787472000116} +{"type":"step/start","data":{"turn":20,"step":1},"seq":117,"time":1787472000117} +{"type":"assistant/message","data":{"turn":20,"step":1,"message":{"id":"preview-assistant-20","role":"assistant","content":[{"type":"text","text":"Checkpoint 20 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 20 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 20 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":118,"time":1787472000118} +{"type":"step/end","data":{"turn":20,"step":1},"seq":119,"time":1787472000119} +{"type":"turn/end","data":{"turn":20,"reason":{"kind":"completed"}},"seq":120,"time":1787472000120} +{"type":"turn/start","data":{"turn":21},"seq":121,"time":1787472000121} +{"type":"user/message","data":{"id":"preview-user-21","role":"user","content":[{"type":"text","text":"History checkpoint 21: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":122,"time":1787472000122} +{"type":"step/start","data":{"turn":21,"step":1},"seq":123,"time":1787472000123} +{"type":"assistant/message","data":{"turn":21,"step":1,"message":{"id":"preview-assistant-21","role":"assistant","content":[{"type":"text","text":"Checkpoint 21 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 21 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 21 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":124,"time":1787472000124} +{"type":"step/end","data":{"turn":21,"step":1},"seq":125,"time":1787472000125} +{"type":"turn/end","data":{"turn":21,"reason":{"kind":"completed"}},"seq":126,"time":1787472000126} +{"type":"turn/start","data":{"turn":22},"seq":127,"time":1787472000127} +{"type":"user/message","data":{"id":"preview-user-22","role":"user","content":[{"type":"text","text":"History checkpoint 22: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":128,"time":1787472000128} +{"type":"step/start","data":{"turn":22,"step":1},"seq":129,"time":1787472000129} +{"type":"assistant/message","data":{"turn":22,"step":1,"message":{"id":"preview-assistant-22","role":"assistant","content":[{"type":"text","text":"Checkpoint 22 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 22 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 22 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":130,"time":1787472000130} +{"type":"step/end","data":{"turn":22,"step":1},"seq":131,"time":1787472000131} +{"type":"turn/end","data":{"turn":22,"reason":{"kind":"completed"}},"seq":132,"time":1787472000132} +{"type":"turn/start","data":{"turn":23},"seq":133,"time":1787472000133} +{"type":"user/message","data":{"id":"preview-user-23","role":"user","content":[{"type":"text","text":"History checkpoint 23: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":134,"time":1787472000134} +{"type":"step/start","data":{"turn":23,"step":1},"seq":135,"time":1787472000135} +{"type":"assistant/message","data":{"turn":23,"step":1,"message":{"id":"preview-assistant-23","role":"assistant","content":[{"type":"text","text":"Checkpoint 23 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 23 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 23 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":136,"time":1787472000136} +{"type":"step/end","data":{"turn":23,"step":1},"seq":137,"time":1787472000137} +{"type":"turn/end","data":{"turn":23,"reason":{"kind":"completed"}},"seq":138,"time":1787472000138} +{"type":"turn/start","data":{"turn":24},"seq":139,"time":1787472000139} +{"type":"user/message","data":{"id":"preview-user-24","role":"user","content":[{"type":"text","text":"History checkpoint 24: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":140,"time":1787472000140} +{"type":"step/start","data":{"turn":24,"step":1},"seq":141,"time":1787472000141} +{"type":"assistant/message","data":{"turn":24,"step":1,"message":{"id":"preview-assistant-24","role":"assistant","content":[{"type":"text","text":"Checkpoint 24 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 24 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 24 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":142,"time":1787472000142} +{"type":"step/end","data":{"turn":24,"step":1},"seq":143,"time":1787472000143} +{"type":"turn/end","data":{"turn":24,"reason":{"kind":"completed"}},"seq":144,"time":1787472000144} +{"type":"turn/start","data":{"turn":25},"seq":145,"time":1787472000145} +{"type":"user/message","data":{"id":"preview-user-25","role":"user","content":[{"type":"text","text":"History checkpoint 25: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":146,"time":1787472000146} +{"type":"step/start","data":{"turn":25,"step":1},"seq":147,"time":1787472000147} +{"type":"assistant/message","data":{"turn":25,"step":1,"message":{"id":"preview-assistant-25","role":"assistant","content":[{"type":"text","text":"Checkpoint 25 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 25 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 25 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":148,"time":1787472000148} +{"type":"step/end","data":{"turn":25,"step":1},"seq":149,"time":1787472000149} +{"type":"turn/end","data":{"turn":25,"reason":{"kind":"completed"}},"seq":150,"time":1787472000150} +{"type":"turn/start","data":{"turn":26},"seq":151,"time":1787472000151} +{"type":"user/message","data":{"id":"preview-user-26","role":"user","content":[{"type":"text","text":"History checkpoint 26: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":152,"time":1787472000152} +{"type":"step/start","data":{"turn":26,"step":1},"seq":153,"time":1787472000153} +{"type":"assistant/message","data":{"turn":26,"step":1,"message":{"id":"preview-assistant-26","role":"assistant","content":[{"type":"text","text":"Checkpoint 26 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 26 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 26 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":154,"time":1787472000154} +{"type":"step/end","data":{"turn":26,"step":1},"seq":155,"time":1787472000155} +{"type":"turn/end","data":{"turn":26,"reason":{"kind":"completed"}},"seq":156,"time":1787472000156} +{"type":"turn/start","data":{"turn":27},"seq":157,"time":1787472000157} +{"type":"user/message","data":{"id":"preview-user-27","role":"user","content":[{"type":"text","text":"History checkpoint 27: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":158,"time":1787472000158} +{"type":"step/start","data":{"turn":27,"step":1},"seq":159,"time":1787472000159} +{"type":"assistant/message","data":{"turn":27,"step":1,"message":{"id":"preview-assistant-27","role":"assistant","content":[{"type":"text","text":"Checkpoint 27 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 27 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 27 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":160,"time":1787472000160} +{"type":"step/end","data":{"turn":27,"step":1},"seq":161,"time":1787472000161} +{"type":"turn/end","data":{"turn":27,"reason":{"kind":"completed"}},"seq":162,"time":1787472000162} +{"type":"turn/start","data":{"turn":28},"seq":163,"time":1787472000163} +{"type":"user/message","data":{"id":"preview-user-28","role":"user","content":[{"type":"text","text":"History checkpoint 28: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":164,"time":1787472000164} +{"type":"step/start","data":{"turn":28,"step":1},"seq":165,"time":1787472000165} +{"type":"assistant/message","data":{"turn":28,"step":1,"message":{"id":"preview-assistant-28","role":"assistant","content":[{"type":"text","text":"Checkpoint 28 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 28 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 28 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":166,"time":1787472000166} +{"type":"step/end","data":{"turn":28,"step":1},"seq":167,"time":1787472000167} +{"type":"turn/end","data":{"turn":28,"reason":{"kind":"completed"}},"seq":168,"time":1787472000168} +{"type":"turn/start","data":{"turn":29},"seq":169,"time":1787472000169} +{"type":"user/message","data":{"id":"preview-gallery-user","role":"user","content":[{"type":"text","text":"Show the seeded workspace, tool cards, subagents, and pagination in one tour."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":170,"time":1787472000170} +{"type":"step/start","data":{"turn":29,"step":1},"seq":171,"time":1787472000171} +{"type":"assistant/message","data":{"turn":29,"step":1,"message":{"id":"preview-gallery-tools","role":"assistant","content":[{"type":"reasoning","text":""},{"type":"reasoning","text":" \t\n"},{"type":"reasoning","text":"I will inspect the deterministic workspace and collect each preview surface."},{"type":"reasoning","text":""},{"type":"reasoning","text":"Check the Chat presentation\n\nI will inspect the wrapped command, its first-line status, and the parent-path file link."},{"type":"reasoning","text":"\n "},{"type":"tool-call","id":"preview-read","name":"read","arguments":"{\"file_path\":\"PREVIEW.md\"}"},{"type":"tool-call","id":"preview-write","name":"write","arguments":"{\"file_path\":\"src/preview.ts\",\"content\":\"export const previewStatus = 'ready'\\n\\nexport const previewFeatures = ['tools', 'subagents', 'pagination'] as const\\n\"}"},{"type":"tool-call","id":"preview-bash","name":"bash","arguments":"{\"command\":\"printf 'preview ready\\\\n'\",\"description\":\"Print the preview readiness marker\"}"},{"type":"tool-call","id":"preview-wrapped-bash","name":"bash","arguments":"{\"command\":\"printf 'preview command fixture\\\\n' # wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-\\nprintf 'wrap complete\\\\n'\\n\",\"description\":\"Show wrapped command and first-line status\"}"},{"type":"tool-call","id":"preview-glob","name":"glob","arguments":"{\"pattern\":\"**/*\",\"path\":\".\"}"},{"type":"tool-call","id":"preview-grep","name":"grep","arguments":"{\"pattern\":\"preview\",\"path\":\".\",\"include\":\"*.{md,ts,json}\"}"},{"type":"tool-call","id":"preview-web-search","name":"web_search","arguments":"{\"queries\":[\"Web Worker filesystem compatibility\"]}"},{"type":"tool-call","id":"preview-todo","name":"todo_write","arguments":"{\"todos\":[{\"content\":\"Inspect tool cards\",\"status\":\"completed\"},{\"content\":\"Open both subagents\",\"status\":\"completed\"},{\"content\":\"Load earlier history\",\"status\":\"in_progress\"}]}"},{"type":"tool-call","id":"preview-subagent","name":"subagent","arguments":"{\"description\":\"Continue preview verification\",\"prompt\":\"Check the remaining preview cases.\",\"run_in_background\":true}"},{"type":"tool-call","id":"preview-subagent-fork","name":"subagent_fork","arguments":"{\"description\":\"Review preview architecture\",\"prompt\":\"Review the fixture architecture.\",\"run_in_background\":false}"},{"type":"tool-call","id":"preview-failure","name":"read","arguments":"{\"file_path\":\"missing.txt\"}"}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":0,"dt":[],"texts":[""]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":""}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":1,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":1,"dt":[],"texts":[" \t\n"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":1,"block":{"type":"reasoning","text":" \t\n"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":2,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":2,"dt":[],"texts":["I will inspect the deterministic workspace and collect each preview surface."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":2,"block":{"type":"reasoning","text":"I will inspect the deterministic workspace and collect each preview surface."}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":3,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":3,"dt":[],"texts":[""]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":3,"block":{"type":"reasoning","text":""}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":4,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":4,"dt":[],"texts":["Check the Chat presentation\n\nI will inspect the wrapped command, its first-line status, and the parent-path file link."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":4,"block":{"type":"reasoning","text":"Check the Chat presentation\n\nI will inspect the wrapped command, its first-line status, and the parent-path file link."}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":5,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":5,"dt":[],"texts":["\n "]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":5,"block":{"type":"reasoning","text":"\n "}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":6,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":6,"dt":[],"id":"preview-read","name":"read","args":["{\"file_path\":\"PREVIEW.md\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":6,"block":{"type":"tool-call","id":"preview-read","name":"read","arguments":"{\"file_path\":\"PREVIEW.md\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":7,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":7,"dt":[],"id":"preview-write","name":"write","args":["{\"file_path\":\"src/preview.ts\",\"content\":\"export const previewStatus = 'ready'\\n\\nexport const previewFeatures = ['tools', 'subagents', 'pagination'] as const\\n\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":7,"block":{"type":"tool-call","id":"preview-write","name":"write","arguments":"{\"file_path\":\"src/preview.ts\",\"content\":\"export const previewStatus = 'ready'\\n\\nexport const previewFeatures = ['tools', 'subagents', 'pagination'] as const\\n\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":8,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":8,"dt":[],"id":"preview-bash","name":"bash","args":["{\"command\":\"printf 'preview ready\\\\n'\",\"description\":\"Print the preview readiness marker\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":8,"block":{"type":"tool-call","id":"preview-bash","name":"bash","arguments":"{\"command\":\"printf 'preview ready\\\\n'\",\"description\":\"Print the preview readiness marker\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":9,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":9,"dt":[],"id":"preview-wrapped-bash","name":"bash","args":["{\"command\":\"printf 'preview command fixture\\\\n' # wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-\\nprintf 'wrap complete\\\\n'\\n\",\"description\":\"Show wrapped command and first-line status\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":9,"block":{"type":"tool-call","id":"preview-wrapped-bash","name":"bash","arguments":"{\"command\":\"printf 'preview command fixture\\\\n' # wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-\\nprintf 'wrap complete\\\\n'\\n\",\"description\":\"Show wrapped command and first-line status\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":10,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":10,"dt":[],"id":"preview-glob","name":"glob","args":["{\"pattern\":\"**/*\",\"path\":\".\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":10,"block":{"type":"tool-call","id":"preview-glob","name":"glob","arguments":"{\"pattern\":\"**/*\",\"path\":\".\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":11,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":11,"dt":[],"id":"preview-grep","name":"grep","args":["{\"pattern\":\"preview\",\"path\":\".\",\"include\":\"*.{md,ts,json}\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":11,"block":{"type":"tool-call","id":"preview-grep","name":"grep","arguments":"{\"pattern\":\"preview\",\"path\":\".\",\"include\":\"*.{md,ts,json}\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":12,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":12,"dt":[],"id":"preview-web-search","name":"web_search","args":["{\"queries\":[\"Web Worker filesystem compatibility\"]}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":12,"block":{"type":"tool-call","id":"preview-web-search","name":"web_search","arguments":"{\"queries\":[\"Web Worker filesystem compatibility\"]}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":13,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":13,"dt":[],"id":"preview-todo","name":"todo_write","args":["{\"todos\":[{\"content\":\"Inspect tool cards\",\"status\":\"completed\"},{\"content\":\"Open both subagents\",\"status\":\"completed\"},{\"content\":\"Load earlier history\",\"status\":\"in_progress\"}]}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":13,"block":{"type":"tool-call","id":"preview-todo","name":"todo_write","arguments":"{\"todos\":[{\"content\":\"Inspect tool cards\",\"status\":\"completed\"},{\"content\":\"Open both subagents\",\"status\":\"completed\"},{\"content\":\"Load earlier history\",\"status\":\"in_progress\"}]}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":14,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":14,"dt":[],"id":"preview-subagent","name":"subagent","args":["{\"description\":\"Continue preview verification\",\"prompt\":\"Check the remaining preview cases.\",\"run_in_background\":true}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":14,"block":{"type":"tool-call","id":"preview-subagent","name":"subagent","arguments":"{\"description\":\"Continue preview verification\",\"prompt\":\"Check the remaining preview cases.\",\"run_in_background\":true}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":15,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":15,"dt":[],"id":"preview-subagent-fork","name":"subagent_fork","args":["{\"description\":\"Review preview architecture\",\"prompt\":\"Review the fixture architecture.\",\"run_in_background\":false}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":15,"block":{"type":"tool-call","id":"preview-subagent-fork","name":"subagent_fork","arguments":"{\"description\":\"Review preview architecture\",\"prompt\":\"Review the fixture architecture.\",\"run_in_background\":false}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":16,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":16,"dt":[],"id":"preview-failure","name":"read","args":["{\"file_path\":\"missing.txt\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":16,"block":{"type":"tool-call","id":"preview-failure","name":"read","arguments":"{\"file_path\":\"missing.txt\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append","seq":172,"time":1787472000172} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-read","name":"read","arguments":"{\"file_path\":\"PREVIEW.md\"}"},"seq":173,"time":1787472000173} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-read-result","role":"tool","toolCallId":"preview-read","source":{"kind":"tool","callId":"preview-read"},"content":[{"type":"text","text":"PREVIEW.md\nfile\n\n1: # Preview Workspace\n2: \n3: This deterministic workspace is bundled with the browser-only preview.\n4: \n5: - `src/preview.ts` is the file changed by the example write result.\n6: - `data/tasks.json` mirrors the completed preview checklist.\n7: - `.agents/skills/preview-tour/SKILL.md` proves dot directories survive image packing.\n8: \n9: Refresh the preview to restore these image bytes.\n\n(End of file - total 9 lines)\n"}],"isError":false},"meta":{"path":"PREVIEW.md","offset":1,"lines":[{"number":1,"text":"# Preview Workspace"},{"number":2,"text":""},{"number":3,"text":"This deterministic workspace is bundled with the browser-only preview."},{"number":4,"text":""},{"number":5,"text":"- `src/preview.ts` is the file changed by the example write result."},{"number":6,"text":"- `data/tasks.json` mirrors the completed preview checklist."},{"number":7,"text":"- `.agents/skills/preview-tour/SKILL.md` proves dot directories survive image packing."},{"number":8,"text":""},{"number":9,"text":"Refresh the preview to restore these image bytes."}],"totalLines":9,"lang":"md"}},"surfaceOp":"append","seq":174,"time":1787472000174} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-write","name":"write","arguments":"{\"file_path\":\"src/preview.ts\",\"content\":\"export const previewStatus = 'ready'\\n\\nexport const previewFeatures = ['tools', 'subagents', 'pagination'] as const\\n\"}"},"seq":175,"time":1787472000175} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-write-result","role":"tool","toolCallId":"preview-write","source":{"kind":"tool","callId":"preview-write"},"content":[{"type":"text","text":"src/preview.ts\nfile\n\nUpdated file\n"}],"isError":false},"meta":{"diffs":[{"path":"src/preview.ts","oldText":"export const previewStatus = 'draft'\n","newText":"export const previewStatus = 'ready'\n\nexport const previewFeatures = ['tools', 'subagents', 'pagination'] as const\n"}]}},"surfaceOp":"append","seq":176,"time":1787472000176} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-bash","name":"bash","arguments":"{\"command\":\"printf 'preview ready\\\\n'\",\"description\":\"Print the preview readiness marker\"}"},"seq":177,"time":1787472000177} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-bash-result","role":"tool","toolCallId":"preview-bash","source":{"kind":"tool","callId":"preview-bash"},"content":[{"type":"text","text":"preview ready\n"}],"isError":false}},"surfaceOp":"append","seq":178,"time":1787472000178} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-wrapped-bash","name":"bash","arguments":"{\"command\":\"printf 'preview command fixture\\\\n' # wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-\\nprintf 'wrap complete\\\\n'\\n\",\"description\":\"Show wrapped command and first-line status\"}"},"seq":179,"time":1787472000179} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-wrapped-bash-result","role":"tool","toolCallId":"preview-wrapped-bash","source":{"kind":"tool","callId":"preview-wrapped-bash"},"content":[{"type":"text","text":"preview command fixture\nwrap complete\n[exit code: 0]"}],"isError":false}},"surfaceOp":"append","seq":180,"time":1787472000180} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-glob","name":"glob","arguments":"{\"pattern\":\"**/*\",\"path\":\".\"}"},"seq":181,"time":1787472000181} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-glob-result","role":"tool","toolCallId":"preview-glob","source":{"kind":"tool","callId":"preview-glob"},"content":[{"type":"text","text":"PREVIEW.md\ndata/tasks.json\nsrc/preview.ts"}],"isError":false},"meta":{"shape":"paths","paths":["PREVIEW.md","data/tasks.json","src/preview.ts"],"truncated":false,"total":3}},"surfaceOp":"append","seq":182,"time":1787472000182} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-grep","name":"grep","arguments":"{\"pattern\":\"preview\",\"path\":\".\",\"include\":\"*.{md,ts,json}\"}"},"seq":183,"time":1787472000183} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-grep-result","role":"tool","toolCallId":"preview-grep","source":{"kind":"tool","callId":"preview-grep"},"content":[{"type":"text","text":"PREVIEW.md:3:This deterministic workspace is bundled with the browser-only preview.\nsrc/preview.ts:1:export const previewStatus = 'ready'"}],"isError":false},"meta":{"shape":"matches","files":[{"path":"PREVIEW.md","matches":[{"lineNumber":3,"line":"This deterministic workspace is bundled with the browser-only preview."}]},{"path":"src/preview.ts","matches":[{"lineNumber":1,"line":"export const previewStatus = 'ready'"}]}],"truncated":false,"total":2}},"surfaceOp":"append","seq":184,"time":1787472000184} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-web-search","name":"web_search","arguments":"{\"queries\":[\"Web Worker filesystem compatibility\"]}"},"seq":185,"time":1787472000185} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-web-search-result","role":"tool","toolCallId":"preview-web-search","source":{"kind":"tool","callId":"preview-web-search"},"content":[{"type":"text","text":"Browser workers can host deterministic in-memory filesystems.\n\nSources:\n1. MDN Web Workers API — https://developer.mozilla.org/docs/Web/API/Web_Workers_API"}],"isError":false},"meta":{"sources":[{"url":"https://developer.mozilla.org/docs/Web/API/Web_Workers_API","title":"Web Workers API","snippet":"Web Workers run scripts in background threads."}],"truncated":false,"answer":"Browser workers can host deterministic in-memory filesystems."}},"surfaceOp":"append","seq":186,"time":1787472000186} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-todo","name":"todo_write","arguments":"{\"todos\":[{\"content\":\"Inspect tool cards\",\"status\":\"completed\"},{\"content\":\"Open both subagents\",\"status\":\"completed\"},{\"content\":\"Load earlier history\",\"status\":\"in_progress\"}]}"},"seq":187,"time":1787472000187} +{"type":"todo/write","data":{"todos":[{"content":"Inspect tool cards","status":"completed"},{"content":"Open both subagents","status":"completed"},{"content":"Load earlier history","status":"in_progress"}]},"seq":188,"time":1787472000188} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-todo-result","role":"tool","toolCallId":"preview-todo","source":{"kind":"tool","callId":"preview-todo"},"content":[{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 2 completed."}],"isError":false}},"surfaceOp":"append","seq":189,"time":1787472000189} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-subagent","name":"subagent","arguments":"{\"description\":\"Continue preview verification\",\"prompt\":\"Check the remaining preview cases.\",\"run_in_background\":true}"},"seq":190,"time":1787472000190} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-subagent-result","role":"tool","toolCallId":"preview-subagent","source":{"kind":"tool","callId":"preview-subagent"},"content":[{"type":"text","text":"started subagent preview-follow-up-builder"}],"isError":false}},"surfaceOp":"append","seq":191,"time":1787472000191} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-subagent-fork","name":"subagent_fork","arguments":"{\"description\":\"Review preview architecture\",\"prompt\":\"Review the fixture architecture.\",\"run_in_background\":false}"},"seq":192,"time":1787472000192} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-subagent-fork-result","role":"tool","toolCallId":"preview-subagent-fork","source":{"kind":"tool","callId":"preview-subagent-fork"},"content":[{"type":"text","text":"The preview fixture remains separate from user-owned WebFS data."}],"isError":false}},"surfaceOp":"append","seq":193,"time":1787472000193} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-failure","name":"read","arguments":"{\"file_path\":\"missing.txt\"}"},"seq":194,"time":1787472000194} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-failure-result","role":"tool","toolCallId":"preview-failure","source":{"kind":"tool","callId":"preview-failure"},"content":[{"type":"text","text":"Error: ENOENT: no such file, open missing.txt"}],"isError":true},"error":{"name":"FsError","code":"ENOENT"}},"surfaceOp":"append","seq":195,"time":1787472000195} +{"type":"subagent/catalog","data":{"version":0,"childId":"preview-architecture-review","childCreatedAt":1787472100000,"mode":"one-shot","label":"Review preview architecture"},"seq":196,"time":1787472000196} +{"type":"subagent/catalog","data":{"version":0,"childId":"preview-follow-up-builder","childCreatedAt":1787472200000,"mode":"continuable","label":"Continue preview verification"},"seq":197,"time":1787472000197} +{"type":"step/end","data":{"turn":29,"step":1},"seq":198,"time":1787472000198} +{"type":"step/start","data":{"turn":29,"step":2},"seq":199,"time":1787472000199} +{"type":"assistant/message","data":{"turn":29,"step":2,"message":{"id":"preview-gallery-final","role":"assistant","content":[{"type":"text","text":"## Preview tour complete\n\nThe workspace, specialized tool cards, two subagent histories, and an earlier history page are ready to inspect.\n\nThis is fixture-authored demonstration data, not a live model run. Open [Parent workspace guide:1–8](<../workspace/PREVIEW.md#L1-L8>) to inspect the same workspace file through a parent path."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["## Preview tour complete\n\nThe workspace, specialized tool cards, two subagent histories, and an earlier history page are ready to inspect.\n\nThis is fixture-authored demonstration data, not a live model run. Open [Parent workspace guide:1–8](<../workspace/PREVIEW.md#L1-L8>) to inspect the same workspace file through a parent path."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"## Preview tour complete\n\nThe workspace, specialized tool cards, two subagent histories, and an earlier history page are ready to inspect.\n\nThis is fixture-authored demonstration data, not a live model run. Open [Parent workspace guide:1–8](<../workspace/PREVIEW.md#L1-L8>) to inspect the same workspace file through a parent path."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":200,"time":1787472000200} +{"type":"step/end","data":{"turn":29,"step":2},"seq":201,"time":1787472000201} +{"type":"turn/end","data":{"turn":29,"reason":{"kind":"completed"}},"seq":202,"time":1787472000202} diff --git a/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/storages/session_projcache.json b/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/storages/session_projcache.json index 3ecdae0660..d26f67472b 100644 --- a/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/storages/session_projcache.json +++ b/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/storages/session_projcache.json @@ -8,7 +8,7 @@ "sessions": { "preview-showcase": { "identity": { - "formatVersion": 3, + "formatVersion": 4, "createdAt": 1787472000000, "cwd": "/dsh/workspace", "isSeeded": false, @@ -17,7 +17,7 @@ "rows": { "title": { "ver": 1, - "seq": 198, + "seq": 202, "val": "WebWorker Preview Showcase" } } diff --git a/packages/experimental/webworker-runtime/tests/node/chokidar.spec.ts b/packages/experimental/webworker-runtime/tests/node/chokidar.spec.ts index 9d78737a09..389cd6ebab 100644 --- a/packages/experimental/webworker-runtime/tests/node/chokidar.spec.ts +++ b/packages/experimental/webworker-runtime/tests/node/chokidar.spec.ts @@ -23,10 +23,10 @@ interface ChokidarFixture { const CHOKIDAR_FIXTURES: readonly ChokidarFixture[] = [ { - label: 'Chokidar 4 from credentials', + label: 'Chokidar 5 from credentials', consumerManifest: 'packages/credentials/credentials-local/package.json', - chokidarFiles: ['package.json', 'esm/package.json', 'esm/index.js', 'esm/handler.js'], - readdirpFiles: ['package.json', 'esm/package.json', 'esm/index.js'], + chokidarFiles: ['package.json', 'index.js', 'handler.js'], + readdirpFiles: ['package.json', 'index.js'], }, { label: 'Chokidar 5 from skill-filesystem', diff --git a/packages/experimental/webworker-runtime/tests/vfs-example-fixture.spec.ts b/packages/experimental/webworker-runtime/tests/vfs-example-fixture.spec.ts index 8ae9dcf6fa..5e588839a4 100644 --- a/packages/experimental/webworker-runtime/tests/vfs-example-fixture.spec.ts +++ b/packages/experimental/webworker-runtime/tests/vfs-example-fixture.spec.ts @@ -14,6 +14,8 @@ import { buildVfsExampleFiles, VFS_EXAMPLE_OLDEST_MESSAGE, VFS_EXAMPLE_ROOT, + VFS_EXAMPLE_REASONING, + VFS_EXAMPLE_WRAPPED_COMMAND, VFS_EXAMPLE_SCHEDULE_IDS, VFS_EXAMPLE_SESSION_IDS, VFS_EXAMPLE_TAIL_MESSAGE, @@ -59,27 +61,29 @@ function textOf(event: SessionEvent): string { } describe('WebWorker preview VFS example', () => { - it('retains V3 inputs that strictly restore to the deterministic current output', () => { + it('keeps the current showcase and strictly restorable historical child inputs beside their predecessors', () => { const expected = buildVfsExampleFiles() const currentName = generationLogFilename(SESSION_FORMAT_VERSION, 'none') - const committedPath = (path: string): string => path.endsWith(`/${currentName}`) + const main = `home/sessions/--dsh-workspace--/${VFS_EXAMPLE_SESSION_IDS.main}/` + const committedPath = (path: string): string => path.endsWith(`/${currentName}`) && !path.startsWith(main) ? `${path.slice(0, -currentName.length)}session.v3.jsonl` : path const predecessors = Object.values(VFS_EXAMPLE_SESSION_IDS) .map(id => `home/sessions/--dsh-workspace--/${id}/session.v2.jsonl`) + predecessors.push(`${main}session.v3.jsonl`) expect(filesUnder(VFS_EXAMPLE_ROOT)).toEqual([...expected.keys()].map(committedPath).concat(predecessors).sort()) for (const [path, content] of expected) { - if (path === 'home/storages/session_projcache.json') continue const committed = readFileSync(join(VFS_EXAMPLE_ROOT, committedPath(path)), 'utf8') - if (path.endsWith(`/${currentName}`)) { + if (path.endsWith(`/${currentName}`) && !path.startsWith(main)) { expect(restoreSession(committed, 3), path).toEqual(restoreSession(content, SESSION_FORMAT_VERSION)) } else { expect(committed, path).toBe(content) + if (path.startsWith(main)) restoreSession(committed, SESSION_FORMAT_VERSION) } } }) - it('retains V3 cache identity while the generated cache uses the current writer', () => { + it('keeps the projection cache aligned with the current showcase writer and tail', () => { const committed = JSON.parse(readFileSync( join(VFS_EXAMPLE_ROOT, 'home/storages/session_projcache.json'), 'utf8', @@ -101,12 +105,10 @@ describe('WebWorker preview VFS example', () => { const generatedText = buildVfsExampleFiles().get('home/storages/session_projcache.json') if (generatedText === undefined) throw new Error('missing generated VFS example projection cache') const generated = JSON.parse(generatedText) as typeof committed - const expectedCurrent = structuredClone(committed) - for (const session of Object.values(expectedCurrent.tables.sessions)) { - expect(session.identity.formatVersion).toBe(3) - session.identity.formatVersion = SESSION_FORMAT_VERSION - } - expect(generated).toEqual(expectedCurrent) + expect(generated).toEqual(committed) + expect(generated.tables.sessions[VFS_EXAMPLE_SESSION_IDS.main]?.rows.title).toMatchObject({ + seq: readSession(VFS_EXAMPLE_SESSION_IDS.main).events.at(-1)?.seq, + }) expect(generated.unit).toEqual({ name: projectionCacheDomainSpec.name, version: projectionCacheDomainSpec.version, @@ -180,6 +182,46 @@ describe('WebWorker preview VFS example', () => { expect(events.some(event => event.type === 'tool/result' && event.data.message.isError === true)).toBe(true) }) + it('preserves the 28-turn history prefix and both child catalog identities', () => { + const main = readSession(VFS_EXAMPLE_SESSION_IDS.main) + const child = readSession(VFS_EXAMPLE_SESSION_IDS.oneShot) + const historical = restoreSession(readFileSync(join(VFS_EXAMPLE_ROOT, + `home/sessions/--dsh-workspace--/${VFS_EXAMPLE_SESSION_IDS.main}/session.v3.jsonl`), 'utf8'), 3) + const prefix = main.events.slice(0, child.inheritedEventCount) + expect(prefix.filter(event => event.type === 'turn/start')).toHaveLength(28) + expect(prefix).toEqual(historical.events.slice(0, child.inheritedEventCount)) + expect(child.events.slice(0, child.inheritedEventCount)).toEqual(prefix) + expect(main.events.filter(event => event.type === 'subagent/catalog').map(event => event.data)).toEqual([ + { version: 0, childId: VFS_EXAMPLE_SESSION_IDS.oneShot, childCreatedAt: 1_787_472_100_000, + mode: 'one-shot', label: 'Review preview architecture' }, + { version: 0, childId: VFS_EXAMPLE_SESSION_IDS.continuable, childCreatedAt: 1_787_472_200_000, + mode: 'continuable', label: 'Continue preview verification' }, + ]) + }) + + it('carries mixed reasoning, a wrapped command, and an authored parent-path link in the existing tour', () => { + const { events } = readSession(VFS_EXAMPLE_SESSION_IDS.main) + const gallery = events.find(event => event.type === 'assistant/message' && event.data.message.id === 'preview-gallery-tools') + if (gallery?.type !== 'assistant/message') throw new Error('missing preview gallery message') + const reasoning = gallery.data.message.content.flatMap(block => block.type === 'reasoning' ? [block.text] : []) + expect(reasoning).toEqual(['', ' \t\n', VFS_EXAMPLE_REASONING[0], '', VFS_EXAMPLE_REASONING[1], '\n ']) + expect(reasoning.filter(text => text.trim() !== '')).toEqual(VFS_EXAMPLE_REASONING) + const call = events.find(event => event.type === 'tool/call' && event.data.callId === 'preview-wrapped-bash') + if (call?.type !== 'tool/call') throw new Error('missing wrapped command call') + expect(JSON.parse(call.data.arguments)).toEqual({ + command: VFS_EXAMPLE_WRAPPED_COMMAND, description: 'Show wrapped command and first-line status', + }) + expect(VFS_EXAMPLE_WRAPPED_COMMAND.split('\n')[0]?.length).toBeGreaterThan(400) + expect(VFS_EXAMPLE_WRAPPED_COMMAND.endsWith('\n')).toBe(true) + expect(events.find(event => event.type === 'tool/result' && event.data.message.source.callId === 'preview-wrapped-bash')) + .toMatchObject({ data: { message: { isError: false, content: [{ type: 'text', text: 'preview command fixture\nwrap complete\n[exit code: 0]' }] } } }) + const tail = events.findLast(event => event.type === 'assistant/message') + if (tail === undefined) throw new Error('missing preview tour tail') + expect(textOf(tail)).toContain(`## ${VFS_EXAMPLE_TAIL_MESSAGE}`) + expect(textOf(tail)).toContain('[Parent workspace guide:1–8](<../workspace/PREVIEW.md#L1-L8>)') + expect(textOf(tail)).toContain('fixture-authored demonstration data, not a live model run') + }) + it('restores one-shot and continuable child Sessions with durable descriptors', () => { const expected = [ [VFS_EXAMPLE_SESSION_IDS.oneShot, 'one-shot'], diff --git a/packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts b/packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts index fd00a86139..2f015bf246 100644 --- a/packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts +++ b/packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts @@ -17,6 +17,7 @@ import { import { projectionCacheDomainSpec } from '@deepseek-ai/dsh-session-projection-cache' import { scheduleDomain } from '@deepseek-ai/dsh-schedule' import { snapshotSubagentDescriptor, SUBAGENT_DESCRIPTOR_VERSION } from '@deepseek-ai/dsh-subagent' +import { SUBAGENT_CATALOG_VERSION } from '@deepseek-ai/dsh-subagent/src/catalog.ts' /** Root copied by the preview image's repository adapter. */ export const VFS_EXAMPLE_ROOT = fileURLToPath(new URL('./fixtures/vfs-example', import.meta.url)) @@ -37,6 +38,15 @@ export const VFS_EXAMPLE_OLDEST_MESSAGE = 'History checkpoint 01: verify determi /** Settled tail marker used by browser acceptance and the demonstration GIF. */ export const VFS_EXAMPLE_TAIL_MESSAGE = 'Preview tour complete' +/** Non-empty reasoning bodies surrounded by empty and whitespace-only fixture blocks. */ +export const VFS_EXAMPLE_REASONING = [ + 'I will inspect the deterministic workspace and collect each preview surface.', + 'Check the Chat presentation\n\nI will inspect the wrapped command, its first-line status, and the parent-path file link.', +] as const + +/** Authored long command and a second line for wrapping and status-dot acceptance. */ +export const VFS_EXAMPLE_WRAPPED_COMMAND = `printf 'preview command fixture\\n' # ${'wrapped-argument-'.repeat(28)}\nprintf 'wrap complete\\n'\n` + /** Durable task ids for the Host Schedule rows seeded into the preview's `DSH_HOME`. */ export const VFS_EXAMPLE_SCHEDULE_IDS = { daily: 'preview-daily-digest', @@ -211,6 +221,12 @@ function galleryCalls(): GalleryCall[] { args: { command: "printf 'preview ready\\n'", description: 'Print the preview readiness marker' }, result: 'preview ready\n', }, + { + id: 'preview-wrapped-bash', + name: 'bash', + args: { command: VFS_EXAMPLE_WRAPPED_COMMAND, description: 'Show wrapped command and first-line status' }, + result: 'preview command fixture\nwrap complete\n[exit code: 0]', + }, { id: 'preview-glob', name: 'glob', @@ -327,7 +343,8 @@ function mainLog(): { log.add(userMessage('preview-gallery-user', 'Show the seeded workspace, tool cards, subagents, and pagination in one tour.')) log.add({ type: 'step/start', data: { turn, step: 1 } }) log.add(assistantMessage('preview-gallery-tools', turn, 1, [ - { type: 'reasoning', text: 'I will inspect the deterministic workspace and collect each preview surface.' }, + ...['', ' \t\n', VFS_EXAMPLE_REASONING[0], '', VFS_EXAMPLE_REASONING[1], '\n '] + .map(text => ({ type: 'reasoning', text })), ...calls.map(call => ({ type: 'tool-call', id: call.id, name: call.name, arguments: JSON.stringify(call.args) })), ])) for (const call of calls) { @@ -355,11 +372,17 @@ function mainLog(): { surfaceOp: 'append', }) } + for (const child of [ + { childId: VFS_EXAMPLE_SESSION_IDS.oneShot, childCreatedAt: CREATED_AT + 100_000, mode: 'one-shot', label: 'Review preview architecture' }, + { childId: VFS_EXAMPLE_SESSION_IDS.continuable, childCreatedAt: CREATED_AT + 200_000, mode: 'continuable', label: 'Continue preview verification' }, + ] as const) { + log.add({ type: 'subagent/catalog', data: { version: SUBAGENT_CATALOG_VERSION, ...child } }) + } log.add({ type: 'step/end', data: { turn, step: 1 } }) log.add({ type: 'step/start', data: { turn, step: 2 } }) log.add(assistantMessage('preview-gallery-final', turn, 2, [{ type: 'text', - text: `## ${VFS_EXAMPLE_TAIL_MESSAGE}\n\nThe workspace, specialized tool cards, two subagent histories, and an earlier history page are ready to inspect.`, + text: `## ${VFS_EXAMPLE_TAIL_MESSAGE}\n\nThe workspace, specialized tool cards, two subagent histories, and an earlier history page are ready to inspect.\n\nThis is fixture-authored demonstration data, not a live model run. Open [Parent workspace guide:1–8](<../workspace/PREVIEW.md#L1-L8>) to inspect the same workspace file through a parent path.`, }])) log.add({ type: 'step/end', data: { turn, step: 2 } }) log.add({ type: 'turn/end', data: { turn, reason: { kind: 'completed' } } }) diff --git a/packages/experimental/worktree/README.i18n.yaml b/packages/experimental/worktree/README.i18n.yaml index daddade30d..1d89944016 100644 --- a/packages/experimental/worktree/README.i18n.yaml +++ b/packages/experimental/worktree/README.i18n.yaml @@ -30,8 +30,8 @@ en: 6826dfaadb24f3da zh: 2e2ee715247fc015 /deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work: - en: a30c8288cb571461 - zh: e94cf8507f4b8b54 + en: 0adcf97622e86f3b + zh: 8bcdc336011cd7e1 /deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work/dev-note: en: ad12746a6cc96d8a zh: 66275f30a35c88e4 diff --git a/packages/experimental/worktree/README.md b/packages/experimental/worktree/README.md index 54e0a25b86..117bd50dae 100644 --- a/packages/experimental/worktree/README.md +++ b/packages/experimental/worktree/README.md @@ -83,9 +83,9 @@ This package contributes no prompt text. Its consumers own the appended tool res - **Retained artifacts** — leaving a worktree keeps its branch and files. Setup failures can also retain partial artifacts; removal, pruning, and branch deletion belong to the user or another consumer. -- **Local revisions only** — creation does not fetch commits or missing partial-clone objects, initialize submodules, install dependencies, or copy uncommitted files. Missing local objects cause creation to fail. +- **Local revisions only** — creation does not fetch commits or missing partial-clone objects, initialize submodules, install dependencies, or copy uncommitted files. On Git that meets the execution requirements, missing local objects cause creation to fail. - **Filtered representations** — checkout skips configured filters to avoid executing repository-configured programs or triggering implicit downloads. Git LFS pointers and encrypted blobs stay in their stored representation; hydration or decryption is a separate user-controlled operation. -- **Execution requirements** — the subprocess provider must offer Git 2.45 or newer and Node in the same execution world as the filesystem provider. Git must support `--no-lazy-fetch`; unsupported executables fail before directory allocation. The existing sandbox must permit all checkout and shared Git metadata writes. +- **Execution requirements** — the subprocess provider must offer Git and Node in the same execution world as the filesystem provider. Git must honor `GIT_NO_LAZY_FETCH`, which Git 2.45 and the 2.39.4, 2.40.2, 2.41.1, 2.42.2, 2.43.4, and 2.44.1 maintenance releases do; older releases ignore it and proceed instead of failing, so creation can fetch missing partial-clone objects from a promisor remote. The `git --no-lazy-fetch` option would reject these releases, but it exists only in Git 2.45 and later and also rejects the patched maintenance releases. The existing sandbox must permit all checkout and shared Git metadata writes. ### Dev Note diff --git a/packages/experimental/worktree/README.zh.md b/packages/experimental/worktree/README.zh.md index 5f12a876f5..3f952697dd 100644 --- a/packages/experimental/worktree/README.zh.md +++ b/packages/experimental/worktree/README.zh.md @@ -83,9 +83,9 @@ Git 与目录分配通过挂载的子进程及沙箱提供方执行,沿用调 - **保留产物**——离开工作树会保留其分支和文件。初始化失败也可能留下部分产物;移除、清理注册信息与删除分支由用户或其他消费方负责。 -- **仅限本地提交**——创建操作不会获取远端提交或部分克隆中缺失的对象、初始化子模块、安装依赖或复制未提交文件。本地对象缺失时,创建失败。 +- **仅限本地提交**——创建操作不会获取远端提交或部分克隆中缺失的对象、初始化子模块、安装依赖或复制未提交文件。Git 满足执行要求时,本地对象缺失会导致创建失败。 - **过滤器处理前的内容**——检出时跳过已配置的过滤器,以避免执行仓库配置的程序或隐式下载。Git LFS 指针与加密 blob 保持存储时的形式;拉取实体内容或解密由用户另行执行。 -- **执行要求**——子进程提供方必须在与文件系统提供方相同的执行环境中提供 Git 2.45 或更新版本以及 Node。Git 必须支持 `--no-lazy-fetch`;不支持的可执行程序会在分配目录前报错。现有沙箱必须允许写入检出目录与共享 Git 元数据。 +- **执行要求**——子进程提供方必须在与文件系统提供方相同的执行环境中提供 Git 与 Node。Git 必须识别 `GIT_NO_LAZY_FETCH`:Git 2.45 及 2.39.4、2.40.2、2.41.1、2.42.2、2.43.4、2.44.1 维护版本均支持;更早的版本会忽略该变量并继续执行而不报错,因此创建操作可能从 promisor 远程获取缺失的部分克隆对象。`git --no-lazy-fetch` 选项会拒绝这些版本,但它仅在 Git 2.45 及以后存在,也会拒绝上述已修补的维护版本。现有沙箱必须允许写入检出目录与共享 Git 元数据。 ### 开发备注 diff --git a/packages/experimental/worktree/package.json b/packages/experimental/worktree/package.json index 493ddce15b..637bdf5e28 100644 --- a/packages/experimental/worktree/package.json +++ b/packages/experimental/worktree/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-worktree", "description": "Creates a named Git worktree and changes the calling Session working directory", - "version": "0.2.1-alpha.1", + "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/worktree/src/index.ts b/packages/experimental/worktree/src/index.ts index 508b347ef0..71095313a0 100644 --- a/packages/experimental/worktree/src/index.ts +++ b/packages/experimental/worktree/src/index.ts @@ -21,7 +21,7 @@ export interface Config { directory?: string /** Prefix for automatically generated branch and checkout names. */ namePrefix?: string - /** Git 2.45 or newer executable name or absolute execution-world path. */ + /** Executable name or absolute execution-world path of a Git release that honors `GIT_NO_LAZY_FETCH`. */ gitCommand?: string /** Node executable used for sandboxed directory allocation. */ nodeCommand?: string @@ -129,7 +129,7 @@ export class WorktreeService extends Service { const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session }) const run = (directory: string, args: string[], allowedExitCodes?: number[], env?: NodeJS.ProcessEnv) => runCommand( this.ctx, this.config, policy, directory, - [this.config.gitCommand, '--no-lazy-fetch', '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', ...args], + [this.config.gitCommand, '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', ...args], signal, allowedExitCodes, env, ) await run(cwd, ['check-ref-format', `refs/heads/${branch}`]) diff --git a/packages/experimental/worktree/src/process.ts b/packages/experimental/worktree/src/process.ts index ee90b13805..74c8fa1c1b 100644 --- a/packages/experimental/worktree/src/process.ts +++ b/packages/experimental/worktree/src/process.ts @@ -56,7 +56,7 @@ export async function runCommand( const child = ctx.subprocess.spawn({ argv: wrapped, cwd, - env: { ...GIT_ENV, GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', ...env }, + env: { ...GIT_ENV, GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', GIT_NO_LAZY_FETCH: '1', ...env }, signal: timeout.signal, graceMs: config.graceMs, stdio: { diff --git a/packages/extensions/cordis-client-runner/locale/en.json b/packages/extensions/cordis-client-runner/locale/en.json new file mode 100644 index 0000000000..2722f3c653 --- /dev/null +++ b/packages/extensions/cordis-client-runner/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "cordis-client-runner" + } +} diff --git a/packages/extensions/cordis-client-runner/locale/zh.json b/packages/extensions/cordis-client-runner/locale/zh.json new file mode 100644 index 0000000000..96dd065277 --- /dev/null +++ b/packages/extensions/cordis-client-runner/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "动态插件浏览器运行器", + "description": "加载并运行临时动态插件的浏览器部分。" + } +} diff --git a/packages/extensions/cordis-client-runner/package.json b/packages/extensions/cordis-client-runner/package.json index 57f0f6e8b0..cb0a743583 100644 --- a/packages/extensions/cordis-client-runner/package.json +++ b/packages/extensions/cordis-client-runner/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-cordis-client-runner", "description": "Browser half of dynamic dual-half plugin packages: event subscription, closure evaluation, guard facade, and loader entries", - "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": { @@ -56,6 +57,7 @@ "@deepseek-ai/dsh-util-values": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts index 4ff7bd728d..136e4863e5 100644 --- a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts @@ -957,7 +957,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SlotEntryDef', - declaration: 'export interface SlotEntryDef {\n kind: SlotKind;\n scope: SlotScope;\n owner?: object;\n keyProps?: Record;\n hookContext?: unknown;\n inject?: object;\n}', + declaration: 'export interface SlotEntryDef {\n kind: SlotKind;\n scope: SlotScope;\n inline?: true;\n owner?: object;\n keyProps?: Record;\n hookContext?: unknown;\n inject?: object;\n}', }, { name: 'SlotFactoryMap', @@ -993,7 +993,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SlotSpec', - declaration: 'export type SlotSpec = {\n kind: E[\'kind\'];\n scope: E[\'scope\'];\n} & (\'inject\' extends keyof E ? E extends {\n inject: infer Injected extends object;\n} ? {\n inject: Injected;\n} : {\n inject?: object;\n} : {\n inject?: never;\n});', + declaration: 'export type SlotSpec = {\n kind: E[\'kind\'];\n scope: E[\'scope\'];\n inline?: true;\n} & (\'inject\' extends keyof E ? E extends {\n inject: infer Injected extends object;\n} ? {\n inject: Injected;\n} : {\n inject?: object;\n} : {\n inject?: never;\n});', }, { name: 'SnapshotSelectorHook', diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index e134f1d984..f2b019e70e 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -176,7 +176,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.assistant-actions\', () => ctx.slots.register(\n { name: \'conversation.chat.assistant-actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:414', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:439', }, { key: 'conversation.chat.commandview', @@ -224,7 +224,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.commandview\', () => ctx.slots.register(\n { name: \'conversation.chat.commandview\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:396', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:421', }, { key: 'conversation.chat.flow', @@ -234,7 +234,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ doc: 'Ordered Chat rows and local echoes with viewport-bound visibility hooks.', registerOptions: [], ownerProps: [ - '/** Ordered rows and reconciled local echoes rendered inside one Chat viewport. */\nexport interface ChatFlowOwnerProps extends Pick {\n readonly entries: readonly RenderEntry[]\n readonly pendingInputs: readonly (PendingSubmission | InboxState[\'next-step\'][number])[]\n readonly lastInputTurn: number | undefined\n readonly deferCollapse: boolean\n}', + '/** Ordered rows and reconciled local echoes rendered inside one Chat viewport. */\nexport interface ChatFlowOwnerProps extends Pick {\n readonly entries: readonly RenderEntry[]\n readonly pendingInputs: readonly (PendingSubmission | InboxState[\'next-step\'][number])[]\n readonly lastInputTurn: number | undefined\n readonly deferCollapse: boolean\n}', ], ownerPropsReferences: [ 'ChatNodeOwnerProps', @@ -267,7 +267,50 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.flow\', () => ctx.slots.register(\n { name: \'conversation.chat.flow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:365', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:388', + }, + { + key: 'conversation.chat.message.images', + kind: 'single', + scope: 'session', + summary: 'Renderer for one consecutive group of durable message images.', + doc: 'Renderer for one consecutive group of durable message images. The owner\nsupplies image references, an authorized loader, and alignment. A\nregistration replaces the shipped gallery; without one, images are omitted.', + registerOptions: [], + ownerProps: [ + '/** Message image group handed to the optional attachment presentation plugin. */\nexport interface MessageImagesOwnerProps {\n /** Durable references or submission-echo previews in source order. */\n images: readonly MessageImageSource[]\n /** Session-authorized image URL loader for the durable arm. */\n loadImage: MessageImageLoader\n /** Horizontal placement inside the owning record. */\n align: \'start\' | \'end\'\n /** Force every image into the compact message-attachment tile size. */\n compact?: boolean\n /** Fixed, uncropped thumbnail for an attachment list row. */\n thumbnail?: boolean\n}', + ], + ownerPropsReferences: [ + 'Message', + 'MessageImageLoader', + 'MessageImageSource', + ], + standardProps: [ + 'useResource: UseResource', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useWorkspaces: SnapshotSelectorHook', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'conversation.chat.node\' (client-ui-chat), so it exists while that entry is mounted', + occupants: [ + 'client-ui-attachment MessageImages', + ], + replaceRisk: 'shadows-shipped-ui', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.message.images\', () => ctx.slots.register(\n { name: \'conversation.chat.message.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:413', }, { key: 'conversation.chat.node', @@ -284,13 +327,12 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ }, ], ownerProps: [ - '/** Stable owner currency delivered to a keyed Chat renderer. */\nexport interface ChatNodeOwnerProps {\n /** Renderer-owned Node portion selected by the grouping Definition. */\n groupPart?: string\n cwd?: string | undefined\n /** Open the current source file of a skill referenced by a sent message. */\n openSkill: (name: string) => void\n openFile: (path: string, options?: OpenFileOptions) => void\n inspectCall: ((callId: ToolCallId) => void) | undefined\n forkAt: (seq: number) => void\n /**\n * Session-authorized image loader, down-threaded from the Chat view so a\n * chat-node renderer can render the attachment presentation slot directly\n * with only the durable references plus this loader, instead of receiving a\n * rendering closure.\n */\n loadImage: MessageImageLoader\n renderMessageImages: RenderMessageImages\n fileMentions: (owner: TurnTailOwnerProps) => MarkdownFileMentions | undefined\n /** Turn-process state when this Node belongs to a projected Turn. */\n turnProcess?: TurnProcessOwnerProps | undefined\n}', + '/** Stable owner currency delivered to a keyed Chat renderer. */\nexport interface ChatNodeOwnerProps {\n /** Renderer-owned Node portion selected by the grouping Definition. */\n groupPart?: string\n cwd?: string | undefined\n openFile: (path: string, options?: OpenFileOptions) => void\n inspectCall: ((callId: ToolCallId) => void) | undefined\n forkAt: (seq: number) => void\n /** Session-authorized image loader supplied by the Chat view. */\n loadImage: MessageImageLoader\n fileMentions: (owner: TurnTailOwnerProps) => MarkdownFileMentions | undefined\n /** Turn-process state when this Node belongs to a projected Turn. */\n turnProcess?: TurnProcessOwnerProps | undefined\n}', ], ownerPropsReferences: [ 'MarkdownFileMentions', 'MessageImageLoader', 'OpenFileOptions', - 'RenderMessageImages', 'TurnProcessOwnerProps', 'TurnTailOwnerProps', ], @@ -338,7 +380,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.node\', () => ctx.slots.register(\n { name: \'conversation.chat.node\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:377', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:400', }, { key: 'conversation.chat.reasoning.body', @@ -378,7 +420,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.reasoning.body\', () => ctx.slots.register(\n { name: \'conversation.chat.reasoning.body\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:402', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:427', }, { key: 'conversation.chat.turnTail', @@ -440,7 +482,50 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.turnTail\', () => ctx.slots.register(\n { name: \'conversation.chat.turnTail\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:408', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:433', + }, + { + key: 'conversation.chat.user.images', + kind: 'single', + scope: 'session', + summary: 'User-message images, including pending and local-echo previews, independently replaceable from output images.', + doc: 'User-message images, including pending and local-echo previews, independently replaceable from output images.', + registerOptions: [], + ownerProps: [ + '/** Message image group handed to the optional attachment presentation plugin. */\nexport interface MessageImagesOwnerProps {\n /** Durable references or submission-echo previews in source order. */\n images: readonly MessageImageSource[]\n /** Session-authorized image URL loader for the durable arm. */\n loadImage: MessageImageLoader\n /** Horizontal placement inside the owning record. */\n align: \'start\' | \'end\'\n /** Force every image into the compact message-attachment tile size. */\n compact?: boolean\n /** Fixed, uncropped thumbnail for an attachment list row. */\n thumbnail?: boolean\n}', + ], + ownerPropsReferences: [ + 'Message', + 'MessageImageLoader', + 'MessageImageSource', + ], + standardProps: [ + 'useResource: UseResource', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useWorkspaces: SnapshotSelectorHook', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'factory \'conversation.chat.user.content\' (client-ui-chat), so it exists while that definition is registered', + occupants: [ + 'client-ui-attachment MessageImages', + ], + replaceRisk: 'shadows-shipped-ui', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.user.images\', () => ctx.slots.register(\n { name: \'conversation.chat.user.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:415', }, { key: 'conversation.composer', @@ -492,7 +577,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer\', () => ctx.slots.register(\n { name: \'conversation.composer\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:187', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:260', }, { key: 'conversation.composer.bar', @@ -531,7 +616,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.bar\', () => ctx.slots.register(\n { name: \'conversation.composer.bar\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:207', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:280', }, { key: 'conversation.composer.dock', @@ -588,7 +673,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.dock\', () => ctx.slots.register(\n { name: \'conversation.composer.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:199', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:272', }, { key: 'conversation.header', @@ -623,7 +708,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.header\', () => ctx.slots.register(\n { name: \'conversation.header\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:139', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:212', }, { key: 'conversation.header.leading', @@ -652,7 +737,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.header.leading\', () => ctx.slots.register(\n { name: \'conversation.header.leading\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:168', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:241', }, { key: 'conversation.hero.agentPreset', @@ -689,7 +774,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.agentPreset\', () => ctx.slots.register(\n { name: \'conversation.hero.agentPreset\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:193', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:266', }, { key: 'conversation.hero.brand.mark', @@ -718,7 +803,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.brand.mark\', () => ctx.slots.register(\n { name: \'conversation.hero.brand.mark\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:191', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:264', }, { key: 'conversation.hero.workspace', @@ -751,7 +836,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.workspace\', () => ctx.slots.register(\n { name: \'conversation.hero.workspace\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:189', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:262', }, { key: 'conversation.hero.workspace.directoryFlow', @@ -783,7 +868,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.workspace.directoryFlow\', () => ctx.slots.register(\n { name: \'conversation.hero.workspace.directoryFlow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:118', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:119', }, { key: 'conversation.input.activity', @@ -824,7 +909,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.activity\', () => ctx.slots.register(\n { name: \'conversation.input.activity\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:205', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:278', }, { key: 'conversation.input.attachments', @@ -865,7 +950,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.attachments\', () => ctx.slots.register(\n { name: \'conversation.input.attachments\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:209', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:282', }, { key: 'conversation.input.dock', @@ -929,7 +1014,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.dock\', () => ctx.slots.register(\n { name: \'conversation.input.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:195', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:268', }, { key: 'conversation.input.left', @@ -983,7 +1068,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.left\', () => ctx.slots.register(\n { name: \'conversation.input.left\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:201', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:274', }, { key: 'conversation.input.model', @@ -1022,7 +1107,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model\', () => ctx.slots.register(\n { name: \'conversation.input.model\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:223', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:296', }, { key: 'conversation.input.overlay', @@ -1080,7 +1165,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.overlay\', () => ctx.slots.register(\n { name: \'conversation.input.overlay\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:197', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:270', }, { key: 'conversation.input.permission', @@ -1119,7 +1204,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.permission\', () => ctx.slots.register(\n { name: \'conversation.input.permission\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:217', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:290', }, { key: 'conversation.input.plan', @@ -1158,7 +1243,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.plan\', () => ctx.slots.register(\n { name: \'conversation.input.plan\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:215', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:288', }, { key: 'conversation.input.right', @@ -1212,50 +1297,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.right\', () => ctx.slots.register(\n { name: \'conversation.input.right\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:203', - }, - { - key: 'conversation.message.images', - kind: 'single', - scope: 'session', - summary: 'Renderer for one consecutive group of durable message images.', - doc: 'Renderer for one consecutive group of durable message images. The owner\nsupplies image references, an authorized loader, and alignment. A\nregistration replaces the shipped gallery; without one, images are omitted.', - registerOptions: [], - ownerProps: [ - '/** Message image group handed to the optional attachment presentation plugin. */\nexport interface MessageImagesOwnerProps {\n /** Durable references or submission-echo previews in source order. */\n images: readonly MessageImageSource[]\n /** Session-authorized image URL loader for the durable arm. */\n loadImage: MessageImageLoader\n /** Horizontal placement inside the owning record. */\n align: \'start\' | \'end\'\n /** Force every image into the compact message-attachment tile size. */\n compact?: boolean\n /** Fixed, uncropped thumbnail for an attachment list row. */\n thumbnail?: boolean\n}', - ], - ownerPropsReferences: [ - 'Message', - 'MessageImageLoader', - 'MessageImageSource', - ], - standardProps: [ - 'useResource: UseResource', - 'useWorkspaces: SnapshotSelectorHook', - 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', - 'useSessionStatus: UseSessionStatus', - 'useSessionRetainInfo: UseSessionRetainInfo', - 'useWorkspaces: SnapshotSelectorHook', - 'useChat: UseChat', - 'useConversation: UseConversation', - 'useInput: SnapshotSelectorHook', - 'inputActions: InputActions', - 'useSession: SessionSnapshotSelector', - 'sessionId: SessionId', - 'useProjection: UseProjection', - 'useTrajectory: UseTrajectory', - ], - keyDomain: '', - hookContext: '', - slotInject: '', - declaredBy: 'an entry in \'conversation.chat.flow\' (client-ui-chat), so it exists while that entry is mounted', - occupants: [ - 'client-ui-attachment MessageImages', - ], - replaceRisk: 'shadows-shipped-ui', - example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.message.images\', () => ctx.slots.register(\n { name: \'conversation.message.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:390', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:276', }, { key: 'conversation.plan-review.actions', @@ -1350,7 +1392,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session\', () => ctx.slots.register(\n { name: \'conversation.session\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:133', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:206', }, { key: 'conversation.session.header', @@ -1387,7 +1429,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header\', () => ctx.slots.register(\n { name: \'conversation.session.header\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:141', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:214', }, { key: 'conversation.session.header.actions', @@ -1448,7 +1490,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.actions\', () => ctx.slots.register(\n { name: \'conversation.session.header.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:156', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:229', }, { key: 'conversation.session.header.corner', @@ -1487,7 +1529,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.corner\', () => ctx.slots.register(\n { name: \'conversation.session.header.corner\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:179', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:252', }, { key: 'conversation.session.header.lineage', @@ -1528,7 +1570,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.lineage\', () => ctx.slots.register(\n { name: \'conversation.session.header.lineage\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:150', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:223', }, { key: 'conversation.session.header.utilities', @@ -1588,7 +1630,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.utilities\', () => ctx.slots.register(\n { name: \'conversation.session.header.utilities\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:162', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:235', }, { key: 'conversation.trajectory.images', @@ -1633,6 +1675,57 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.trajectory.images\', () => ctx.slots.register(\n { name: \'conversation.trajectory.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', source: 'packages/client/ui-trajectory/src/client/trajectory-contract.ts:103', }, + { + key: 'conversation.user.text.node', + kind: 'keyed', + scope: 'session', + summary: 'One business-owned inline renderer for a pure JSON text node.', + doc: 'One business-owned inline renderer for a pure JSON text node.', + registerOptions: [ + { + name: 'key', + requirement: 'required', + type: 'string', + doc: 'Your cell key: the entry renders where the owner dispatches this exact key. Registering an already-occupied key replaces that occupant.', + }, + ], + ownerProps: [ + '/** JSON-only owner data common to every business text node. */\nexport interface UserTextNodeOwnerProps {\n readonly raw: string\n readonly interactive: boolean\n}', + ], + ownerPropsReferences: [], + standardProps: [ + 'useResource: UseResource', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useWorkspaces: SnapshotSelectorHook', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useTrajectory: UseTrajectory', + ], + keyDomain: 'fixed by the owner\'s key table { [Id in UserTextId]: { node: UserTextNode } }, already taken: command, file, folder, session, skill, text', + hookContext: '', + slotInject: '', + declaredBy: 'factory \'conversation.user.text\' (client-ui-conversation), so it exists while that definition is registered', + occupants: [ + 'client-ui-conversation PlainUserText key \'text\'', + 'client-ui-conversation SessionReference key \'session\'', + 'client-ui-goal GoalCommandReference key \'command\'', + 'client-ui-reference FileReference key \'file\'', + 'client-ui-reference FolderReference key \'folder\'', + 'client-ui-skill SkillReference key \'skill\'', + ], + replaceRisk: 'shadows-shipped-ui', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.user.text.node\', () => ctx.slots.register(\n { name: \'conversation.user.text.node\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:196', + }, { key: 'conversation.view', kind: 'list', @@ -1692,7 +1785,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.view\', () => ctx.slots.register(\n { name: \'conversation.view\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:185', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:258', }, { key: 'deliverables.file.actions', @@ -1884,7 +1977,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'main.conversation\', () => ctx.slots.register(\n { name: \'main.conversation\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:131', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:204', }, { key: 'plugins.add.actions', @@ -3020,7 +3113,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'shell.quota-notice\', () => ctx.slots.register(\n { name: \'shell.quota-notice\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:422', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:447', }, { key: 'sidebar', @@ -3871,7 +3964,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.session.row.hover\', () => ctx.slots.register(\n { name: \'sidebar.session.row.hover\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:135', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:136', }, { key: 'sidebar.session.row.leading', @@ -3923,7 +4016,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.session.row.leading\', () => ctx.slots.register(\n { name: \'sidebar.session.row.leading\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:130', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:131', }, { key: 'sidebar.settings', @@ -4046,14 +4139,14 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.workspaces.directoryFlow\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.directoryFlow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:120', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:121', }, { key: 'sidebar.workspaces.session.menu.item', kind: 'list', scope: 'root', summary: 'The rows of one Session\'s "..." menu, in ascending `order`.', - doc: 'The rows of one Session\'s "..." menu, in ascending `order`. ui-workspace\nregisters the shipped rows here — `pin` (100), `rename` (200), `fork`\n(300), `archive` (400) — so a plugin row is placed by its own `order`\namong them. Use a package-namespaced `id`; reusing a shipped id at\nanother `priority` shadows that row. Each entry renders one\n`role="menuitem"` `= 0) { + durations.set(record.file, record.duration) + } } } return durations @@ -479,13 +488,15 @@ export class CoveragePartitionCoordinator { } /** - * Run every partition before one merged threshold check. + * Run every partition and verify its test-file inventory before one merged threshold check. + * Failed runs retain inventories, partition configs, and test reports in coverage/.partitioned. * @returns zero only when every partition and the merge command succeed. */ public async run(): Promise { await removeOwnedTree(join(this.root, 'coverage')) await mkdir(this.blobsRoot, { recursive: true }) + let succeeded = false try { const assignments = await this.assignFiles() this.assertNonEmptyAssignments(assignments) @@ -506,13 +517,16 @@ export class CoveragePartitionCoordinator { // run, but the completed partitions' timings are still worth keeping. this.persistDurations(this.partitions) await this.assertCompleteBlobSet(commands) + await this.assertCompleteTestFiles(assignments) const mergeCommand = this.mergeCommand() console.log(`coverage-partitions: start ${mergeCommand.label}`) const mergeResult = await this.runCommand(mergeCommand) - return results.some(commandFailed) || commandFailed(mergeResult) ? 1 : 0 + succeeded = !results.some(commandFailed) && !commandFailed(mergeResult) + return succeeded ? 0 : 1 } finally { - await removeOwnedTree(this.temporaryRoot) + if (succeeded) await removeOwnedTree(this.temporaryRoot) + else console.error(`coverage-partitions: diagnostics retained at ${this.relativePath(this.temporaryRoot)}`) } } @@ -559,7 +573,7 @@ export class CoveragePartitionCoordinator { // values (`--testTimeout 5000`) must never be mistaken for filters. const separator = this.vitestArgs.indexOf('--') const filters = separator >= 0 ? this.vitestArgs.slice(separator + 1) : [] - const inventory = await collectInstrumentedFiles(this.root, this.pnpmEntrypoint, filters) + const inventory = await collectInstrumentedFiles(this.root, this.pnpmEntrypoint, join(this.temporaryRoot, 'inventory.json'), filters) files = inventory.files this.projectOf = inventory.projectOf weights = readFileDurations(this.root) @@ -651,6 +665,30 @@ export class CoveragePartitionCoordinator { throw new Error(`coverage partitions produced ${JSON.stringify(actual)}; expected ${JSON.stringify(expected)}.`) } } + + /** Require each compact timing report to account for every assigned file exactly once. */ + private async assertCompleteTestFiles(assignments: readonly (readonly string[])[]): Promise { + await Promise.all(assignments.map(async (expected, index) => { + const path = join(this.temporaryRoot, `partition-${index + 1}.times.json`) + const report: unknown = JSON.parse(await readFile(path, 'utf8')) + if (!Array.isArray(report)) { + throw new Error(`coverage partition report ${path} must contain file timing records`) + } + const actual = report.map((result: unknown) => { + if (result === null || typeof result !== 'object' || !('file' in result) || typeof result.file !== 'string') { + throw new Error(`coverage partition report ${path} contains a test result without a filename`) + } + return result.file + }) + const observed = new Set(actual) + const assigned = new Set(expected) + const missing = expected.filter(file => !observed.has(file)) + const unexpected = actual.filter(file => !assigned.has(file)) + if (missing.length > 0 || unexpected.length > 0 || observed.size !== actual.length) { + throw new Error(`coverage partition ${index + 1}: missing files ${JSON.stringify(missing)}; unexpected files ${JSON.stringify(unexpected)}; duplicate results ${actual.length - observed.size}`) + } + })) + } } /** Spawn one pnpm-backed command without a platform shell. */ diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index 2eba3f4c17..f301060236 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -1,10 +1,9 @@ { - "AGENTS.md": 1960, - "docs/AGENTS.md": 1320, + "AGENTS.md": 2080, + "docs/AGENTS.md": 1430, "docs/architecture.md": 2410, "docs/cordis-primer.md": 600, - "docs/defensive-patterns.md": 550, "docs/testing.md": 1350, - "packages/AGENTS.md": 750, + "packages/AGENTS.md": 810, "packages/README.md": 994 } diff --git a/scripts/fixtures/python-sdk-office.mjs b/scripts/fixtures/python-sdk-office.mjs index 1f11e2cdbf..1b11a089f4 100644 --- a/scripts/fixtures/python-sdk-office.mjs +++ b/scripts/fixtures/python-sdk-office.mjs @@ -15,7 +15,7 @@ export async function apply(ctx, config) { if (json === undefined) throw new Error('Office skill did not supply CLI paths') const { libreofficeKit: { node, cli } } = JSON.parse(json) const options = { env: { ...process.env, PATH: '' }, timeout: 120_000 } - const capabilities = await promisify(execFile)(node, [cli, 'capabilities'], options) + const capabilities = await promisify(execFile)(node, [cli, 'capabilities', '--json'], options) await promisify(execFile)(node, [cli, 'convert', '--input', config.input, '--output', config.output + '.cli.pdf'], options) const pdf = await readFile(config.output + '.cli.pdf') if (pdf.subarray(0, 5).toString() !== '%PDF-') throw new Error('Skill CLI did not create a PDF') diff --git a/scripts/no-unknown-casts.baseline.json b/scripts/no-unknown-casts.baseline.json index c836c82030..1b80295601 100644 --- a/scripts/no-unknown-casts.baseline.json +++ b/scripts/no-unknown-casts.baseline.json @@ -474,9 +474,6 @@ "bfa9b3c146cb954091623aa0ceddd08e3d346a8fd1651168021397e4d7750f1d": 2, "f5a208f3ac88b7d5c0de75f72c4a4652b85e21f4ebddf397bd2ff3265a66f6e2": 2 }, - "packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx": { - "12a4fcbcbe9194fe012835a6c0346eab98441db62b74da62f80a8cd510774c5a": 1 - }, "packages/client/ui-chat/tests/chat-view.client.spec.tsx": { "6061de0a1e01547eb1abf9d4e1b5fa79fda112fa35dda980775491123413dcce": 3, "6787497d471fc8faaa78ffcbd497c36ceba82c1b8ee16d0d450b405ad4dddc25": 1 @@ -552,11 +549,6 @@ "5f1a0867b42cf35dac7fdf5839e3a39c2384c5b3b03142e799a36733ad96b9da": 1, "8342608ac37fdc653b6e751e7192472328c9d1baecf1f66d79a65529db5c4d6a": 1 }, - "packages/client/ui-goal/tests/goal-command-input.client.spec.tsx": { - "1c1b6199197153a573f0fe4407b8558555422b0d50dbbba17b25b3ca93c61c4d": 1, - "ac130009bd2e1d0af0c730a148e5e01a5a504bf712c43692bc62a8084c73e148": 1, - "c94a4dd0df97005875a97b9228b3f536765ee6d31872ee05e69677da27086124": 1 - }, "packages/client/ui-input-trigger/tests/apply.client.spec.ts": { "fc590cb703f599e5bb15f23909cedddeb2a77cb2cad0d4b9b8e664a62c46f44e": 1 }, @@ -625,7 +617,7 @@ }, "packages/client/ui-settings-models/tests/apply.client.spec.ts": { "0464c472dfc74994388bf63a6b3c110df506ce44fe47a5040e93c67a5eb3b4ae": 1, - "04984a2ce1486250236e638e0197da0a1a840855ed3975c59130a85358c7e5fe": 5, + "04984a2ce1486250236e638e0197da0a1a840855ed3975c59130a85358c7e5fe": 4, "5c8c41ba658c0576bea6c34b1226c27e7b0328c03c9eea0d6c920f940c9d8f5b": 1 }, "packages/client/ui-settings-models/tests/components.client.spec.tsx": { @@ -784,10 +776,6 @@ "efed1d00d0f288a0c2716c88ee57ba53ace8f627abba4bd2c20de596755b5bad": 1, "f37cbef85628f8df72f3d455868ac0715105f463a9bd858f10e2cb5f984baefb": 1 }, - "packages/client/ui-trajectory/tests/table.client.spec.tsx": { - "8230c12479e8aa0eb39efd18be824c802edff5965e6e4f062089753e65f2e7cf": 1, - "bfc698b45e3bff20b13dd4dc94cca8df3902a5d534fc57e80306ad2c9e96e4b7": 1 - }, "packages/client/ui-trajectory/tests/views.client.spec.tsx": { "958ba19bf4d19e2dd44b271fa784091302bd3a2fdf291db6839fc49da543c5cf": 2 }, diff --git a/scripts/primary-runtime/prepare.spec.ts b/scripts/primary-runtime/prepare.spec.ts index 6100bc2b5b..1fc0ddd07c 100644 --- a/scripts/primary-runtime/prepare.spec.ts +++ b/scripts/primary-runtime/prepare.spec.ts @@ -1,6 +1,6 @@ import { readFileSync } from 'node:fs' import { createHash } from 'node:crypto' -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { basename, join } from 'node:path' import { zipSync } from 'fflate' @@ -55,13 +55,29 @@ it('reports missing distribution metadata before trying to execute a stale nativ } finally { await rm(root, { recursive: true, force: true }) } }) +// Native Windows payloads require python.exe rather than POSIX interpreter aliases. +it.skipIf(process.platform === 'win32')('rejects expanded interpreter aliases in the native payload smoke', async () => { + const root = await mkdtemp(join(tmpdir(), 'primary-expanded-aliases-')) + try { + await writeFile(join(root, 'runtime.json'), JSON.stringify({ desktopVersion: '1', platform: process.platform, arch: process.arch, + python: '3.12.14', pythonPackages: { numpy: '2.3.5' } })) + await mkdir(join(root, 'dependencies/python/bin'), { recursive: true }) + for (const name of ['python', 'python3', 'python3.12']) await writeFile(join(root, 'dependencies/python/bin', name), 'interpreter') + expect(() => { smokePrimaryRuntime(root) }).toThrow('Python commands must be relative aliases') + } finally { await rm(root, { recursive: true, force: true }) } +}) + it('extracts a hash-verified cached library without a Python installer or network request', async () => { const root = await mkdtemp(join(tmpdir(), 'desktop-wheel-')) try { const hash = createHash('sha256').update(libraryWheel).digest('hex') const archive = join(root, hash) await writeFile(archive, libraryWheel) + const original = await stat(archive) expect(await downloadPrimaryRuntimeAsset('https://unused.invalid/library.whl', hash, root)).toBe(archive) + const reused = await stat(archive) + expect(reused.ino).toBe(original.ino) + expect(reused.mtimeMs).toBe(original.mtimeMs) await unpackPrimaryRuntimeWheel(archive, join(root, 'site-packages')) expect(await readFile(join(root, 'site-packages/sample.py'), 'utf8')).toBe('sample = 42\n') await writeFile(archive, 'corrupt archive') diff --git a/scripts/primary-runtime/prepare.ts b/scripts/primary-runtime/prepare.ts index a156a7564a..fb46a26ce5 100644 --- a/scripts/primary-runtime/prepare.ts +++ b/scripts/primary-runtime/prepare.ts @@ -1,8 +1,8 @@ /** Prepare pinned, relocatable script interpreters without installing into the build host. */ import { execFileSync } from 'node:child_process' -import { createHash } from 'node:crypto' -import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { createHash, randomUUID } from 'node:crypto' +import { cpSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, renameSync, rmSync, writeFileSync } from 'node:fs' import { cp } from 'node:fs/promises' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' @@ -10,30 +10,101 @@ import { dirname, join, resolve } from 'node:path' import { parseArgs } from 'node:util' import extractZip from 'extract-zip' import { x as extractTar } from 'tar' -import { parsePrimaryRuntime, workspaceDependencyPaths, type PrimaryRuntimeManifest } from '../../packages/skill/tool-workspace-dependencies/src/index.ts' +import { copyPrimaryRuntime, parsePrimaryRuntime, workspaceDependencyPaths, type PrimaryRuntimeManifest } from '@deepseek-ai/dsh-tool-workspace-dependencies' import lock from './lock.json' with { type: 'json' } +import { prunePrimaryRuntimePythonTests } from './prune-python-tests.ts' /** * Download or reuse an archive only when its bytes match the release lock. * @param url - Locked archive URL. - * @param sha256 - Expected SHA-256 digest. + * @param sha256 - Expected hexadecimal digest for the selected algorithm. * @param cache - Download cache directory. + * @param algorithm - Digest algorithm; npm archives use SHA-512. * @returns Verified local archive path. */ -export async function downloadPrimaryRuntimeAsset(url: string, sha256: string, cache: string): Promise { +export async function downloadPrimaryRuntimeAsset(url: string, sha256: string, cache: string, algorithm: 'sha256' | 'sha512' = 'sha256'): Promise { + mkdirSync(cache, { recursive: true }) const destination = join(cache, sha256) let bytes: Buffer + let cached = true try { bytes = readFileSync(destination) } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error - const response = await fetch(url) + cached = false + const timeout = Number(process.env.DSH_RESOURCE_DOWNLOAD_TIMEOUT_MS ?? '300000') + if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 2_147_483_647) throw new Error('DSH_RESOURCE_DOWNLOAD_TIMEOUT_MS must be an integer from 1 to 2147483647') + const response = await fetch(url, { signal: AbortSignal.timeout(timeout) }) if (!response.ok) throw new Error(`primary runtime download: ${String(response.status)} ${url}`) bytes = Buffer.from(await response.arrayBuffer()) } - if (createHash('sha256').update(bytes).digest('hex') !== sha256) throw new Error(`primary runtime download: checksum mismatch for ${url}`) - writeFileSync(destination, bytes) + if (createHash(algorithm).update(bytes).digest('hex') !== sha256) { + rmSync(destination, { force: true }) + throw new Error(`primary runtime download: checksum mismatch for ${url}`) + } + if (cached) return destination + const temporary = join(cache, `.${randomUUID()}`) + try { + writeFileSync(temporary, bytes) + renameSync(temporary, destination) + } finally { + rmSync(temporary, { force: true }) + } return destination } +/** Pinned npm tarball, without dependency resolution or lifecycle scripts. */ +export interface RuntimeNpmArchive { + /** Exact published package name. */ + readonly name: string + /** Exact published version. */ + readonly version: string + /** Registry tarball URL. */ + readonly url: string + /** npm SHA-512 integrity. */ + readonly integrity: string +} + +/** + * Download and unpack one locked npm package without running its scripts. + * @param artifact - Published tarball identity and integrity. + * @param destination - Empty package directory. + * @param cache - Verified archive cache. + * @returns Resolves after package identity validation. + */ +export async function downloadRuntimeNpmPackage(artifact: RuntimeNpmArchive, destination: string, cache: string): Promise { + if (!/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(artifact.integrity)) throw new Error(`runtime download: invalid integrity for ${artifact.name}`) + const checksum = Buffer.from(artifact.integrity.slice(7), 'base64').toString('hex') + const archive = await downloadPrimaryRuntimeAsset(artifact.url, checksum, cache, 'sha512') + mkdirSync(destination, { recursive: true }) + await extractTar({ file: archive, cwd: destination, strip: 1 }) + const installed = JSON.parse(readFileSync(join(destination, 'package.json'), 'utf8')) as { name?: string; version?: string } + if (installed.name !== artifact.name || installed.version !== artifact.version) throw new Error(`runtime download: package identity mismatch for ${artifact.name}`) +} + +/** + * Prepare the locked standalone Node independently of Python and pnpm. + * @param target - Target interpreter platform. + * @param destination - Directory receiving bin/node and LICENSE. + * @param cache - Verified archive cache. + * @returns Resolves after extracting the interpreter. + */ +export async function downloadNodeRuntime(target: PrimaryRuntimeTarget, destination: string, cache: string): Promise { + const artifact = lock.targets[target] + const filename = `node-v${lock.nodeVersion}-${artifact.nodeArchive}` + const archive = await downloadPrimaryRuntimeAsset(`https://nodejs.org/dist/v${lock.nodeVersion}/${filename}`, artifact.nodeSha256, cache) + const staging = mkdtempSync(join(tmpdir(), 'dsh-node-')) + try { + if (target === 'win-x64') await extractZip(archive, { dir: staging }) + else await extractTar({ file: archive, cwd: staging }) + const source = join(staging, filename.replace(/\.(?:zip|tar\.gz)$/u, '')) + mkdirSync(join(destination, 'bin'), { recursive: true }) + cpSync(join(source, ...(target === 'win-x64' ? ['node.exe'] : ['bin', 'node'])), + join(destination, 'bin', target === 'win-x64' ? 'node.exe' : 'node')) + cpSync(join(source, 'LICENSE'), join(destination, 'LICENSE')) + } finally { + rmSync(staging, { recursive: true, force: true }) + } +} + async function pythonArchive(target: keyof typeof lock.targets, cache: string): Promise { const artifact = lock.targets[target] const filename = `cpython-${lock.pythonVersion}+${lock.pythonRelease}-${artifact.pythonTarget}-install_only_stripped.tar.gz` @@ -54,7 +125,7 @@ export function primaryRuntimePayloadDigest( // Identity preserves key order within the selected target, wheel records and distribution map, plus wheel-entry order. // Bump format when extraction or assembly changes payload bytes without changing locked inputs. return createHash('sha256').update(JSON.stringify({ - format: 4, target, pythonVersion, pythonRelease, nodeVersion: pnpmVersion === undefined ? undefined : nodeVersion, + format: 7, target, pythonVersion, pythonRelease, nodeVersion: pnpmVersion === undefined ? undefined : nodeVersion, artifact: runtimeLock.targets[target], wheels, pythonPackages, pnpm: pnpmVersion, })).digest('hex') } @@ -91,7 +162,7 @@ export async function prepareOfficeSkillAssets(source: string, destination: stri /** A locked interpreter and wheel target. */ export type PrimaryRuntimeTarget = keyof typeof lock.targets -/** Build-only inputs shared by Desktop and SDK carriers. */ +/** Resource preparation inputs shared by builds and explicit SDK downloads. */ export interface PreparePrimaryRuntimeOptions { /** Target whose archives and wheels are downloaded. */ readonly target: PrimaryRuntimeTarget @@ -101,6 +172,10 @@ export interface PreparePrimaryRuntimeOptions { readonly cache: string /** Carrier release recorded in the legacy desktopVersion manifest field. */ readonly version: string + /** Locked npm pnpm tarball for installed carriers; build hosts otherwise copy their installed pnpm. */ + readonly pnpmArchive?: RuntimeNpmArchive + /** Ordinary filesystem Office assets; build hosts otherwise resolve the workspace package. */ + readonly skillSource?: string /** Omit Node.js and pnpm for carriers providing only Python. */ readonly pythonOnly?: boolean } @@ -113,7 +188,6 @@ export interface PreparePrimaryRuntimeOptions { export async function preparePrimaryRuntime(options: PreparePrimaryRuntimeOptions): Promise { const { target } = options const paths = { runtime: resolve(options.output), downloads: resolve(options.cache) } - const artifact = lock.targets[target] mkdirSync(paths.runtime, { recursive: true }) mkdirSync(paths.downloads, { recursive: true }) const staging = mkdtempSync(join(tmpdir(), 'dsh-primary-')) @@ -123,23 +197,18 @@ export async function preparePrimaryRuntime(options: PreparePrimaryRuntimeOption mkdirSync(dependencies, { recursive: true }) let pnpmVersion: string | undefined if (!options.pythonOnly) { - const nodeFilename = `node-v${lock.nodeVersion}-${artifact.nodeArchive}` - const nodeArchive = await downloadPrimaryRuntimeAsset(`https://nodejs.org/dist/v${lock.nodeVersion}/${nodeFilename}`, artifact.nodeSha256, paths.downloads) - const unpackedNode = join(staging, 'node') - mkdirSync(unpackedNode) - if (target === 'win-x64') await extractZip(nodeArchive, { dir: unpackedNode }) - else await extractTar({ file: nodeArchive, cwd: unpackedNode }) - const nodeSource = join(unpackedNode, nodeFilename.replace(/\.(?:zip|tar\.gz)$/u, '')) - mkdirSync(join(dependencies, 'node', 'bin'), { recursive: true }) - mkdirSync(join(dependencies, 'node', 'node_modules')) - writeFileSync(join(dependencies, 'node', 'node_modules', 'README.txt'), 'Reserved for bundled Node packages. pnpm uses its default installation directories.\n') - cpSync(join(nodeSource, ...(target === 'win-x64' ? ['node.exe'] : ['bin', 'node'])), - join(dependencies, 'node', 'bin', target === 'win-x64' ? 'node.exe' : 'node')) - cpSync(join(nodeSource, 'LICENSE'), join(dependencies, 'node', 'LICENSE')) - const require = createRequire(import.meta.url) - const pnpmManifest = require.resolve('pnpm') - pnpmVersion = (JSON.parse(readFileSync(pnpmManifest, 'utf8')) as { version: string }).version - await cp(dirname(pnpmManifest), join(dependencies, 'pnpm'), { recursive: true, dereference: true }) + const node = join(dependencies, 'node') + await downloadNodeRuntime(target, node, paths.downloads) + mkdirSync(join(node, 'node_modules')) + writeFileSync(join(node, 'node_modules', 'README.txt'), 'Reserved for bundled Node packages. pnpm uses its default installation directories.\n') + if (options.pnpmArchive !== undefined) { + pnpmVersion = options.pnpmArchive.version + await downloadRuntimeNpmPackage(options.pnpmArchive, join(dependencies, 'pnpm'), paths.downloads) + } else { + const pnpmManifest = createRequire(import.meta.url).resolve('pnpm') + pnpmVersion = (JSON.parse(readFileSync(pnpmManifest, 'utf8')) as { version: string }).version + await cp(dirname(pnpmManifest), join(dependencies, 'pnpm'), { recursive: true, dereference: true }) + } } await extractTar({ file: await pythonArchive(target, paths.downloads), cwd: dependencies }) const manifest: PrimaryRuntimeManifest = { @@ -152,18 +221,19 @@ export async function preparePrimaryRuntime(options: PreparePrimaryRuntimeOption pythonPackages: lock.pythonPackages, } const entries = workspaceDependencyPaths(output, manifest) - for (const wheel of [...artifact.wheels, ...lock.wheels]) { + for (const wheel of [...lock.targets[target].wheels, ...lock.wheels]) { await unpackPrimaryRuntimeWheel(await downloadPrimaryRuntimeAsset(wheel.url, wheel.sha256, paths.downloads), entries.pythonPackages) } + prunePrimaryRuntimePythonTests(entries.pythonPackages) writeFileSync(join(output, 'runtime.json'), `${JSON.stringify(manifest, undefined, 2)}\n`) const destination = join(paths.runtime, 'primary-runtime') rmSync(destination, { recursive: true, force: true }) - await cp(output, destination, { recursive: true, dereference: true }) + await copyPrimaryRuntime(output, destination, manifest) } finally { rmSync(staging, { recursive: true, force: true }) } - const require = createRequire(import.meta.url) - await prepareOfficeSkillAssets(join(dirname(require.resolve('@deepseek-ai/dsh-skill-office/package.json')), 'assets'), + const assets = options.skillSource ?? join(dirname(createRequire(import.meta.url).resolve('@deepseek-ai/dsh-skill-office/package.json')), 'assets') + await prepareOfficeSkillAssets(assets, join(paths.runtime, 'office-skills')) } @@ -179,6 +249,16 @@ export function smokePrimaryRuntime(root: string, environment: NodeJS.ProcessEnv if (manifest.platform !== process.platform || manifest.arch !== process.arch) return if (Object.keys(manifest.pythonPackages).length === 0) throw new Error('primary runtime: missing Python distribution versions; prepare the payload before running its smoke checks.') const entries = workspaceDependencyPaths(root, manifest) + if (manifest.platform !== 'win32') { + const interpreter = `python${manifest.python.split('.').slice(0, 2).join('.')}` + for (const name of ['python', 'python3']) { + const path = join(dirname(entries.python), name) + if (!lstatSync(path).isSymbolicLink() || readlinkSync(path) !== interpreter) { + throw new Error(`primary runtime: Python commands must be relative aliases of ${interpreter}`) + } + } + if (!lstatSync(join(dirname(entries.python), interpreter)).isFile()) throw new Error('primary runtime: versioned Python must be a regular file') + } const options = { stdio: 'inherit', timeout: 120_000, env: environment } as const execFileSync(entries.python, ['-I', '-B', '-c', 'import decimal, xml.parsers.expat, lzma, uuid, numpy, pandas; assert numpy.arange(4).sum() == 6; assert pandas.DataFrame({"n": [1, 2]}).n.sum() == 3'], options) execFileSync(entries.python, ['-I', '-B', join(import.meta.dirname, 'smoke.py'), JSON.stringify(manifest.pythonPackages), diff --git a/scripts/primary-runtime/prune-python-tests.spec.ts b/scripts/primary-runtime/prune-python-tests.spec.ts new file mode 100644 index 0000000000..25b59f3e3c --- /dev/null +++ b/scripts/primary-runtime/prune-python-tests.spec.ts @@ -0,0 +1,85 @@ +import { createHash } from 'node:crypto' +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { zipSync } from 'fflate' +import { expect, it } from 'vitest' +import lock from './lock.json' with { type: 'json' } +import { unpackPrimaryRuntimeWheel } from './prepare.ts' +import { prunePrimaryRuntimePythonTests } from './prune-python-tests.ts' + +const records = { + numpy: `numpy-${lock.pythonPackages.numpy}.dist-info/RECORD`, + pandas: `pandas-${lock.pythonPackages.pandas}.dist-info/RECORD`, +} + +it('removes only NumPy/pandas test directories and keeps retained wheel files and RECORD hashes', async () => { + const root = await mkdtemp(join(tmpdir(), 'primary-python-pruning-')) + try { + const removed = [ + 'numpy/tests/test_numpy.py', 'numpy/_core/tests/test_core.py', 'numpy/_core/tests/data/values,small.csv', + 'numpy/testing/tests/test_utils.py', 'pandas/tests/io/test_excel.py', 'pandas/tests/io/data/workbook.xlsx', + ] + const retained = [ + 'numpy/__init__.py', 'numpy/_core/_multiarray_tests.so', 'numpy/_core/_multiarray_tests.pyd', + 'numpy/testing/__init__.py', 'numpy/_core/tests.py', 'numpy/data/values,small.csv', + 'pandas/__init__.py', 'pandas/testing.py', 'pandas/_testing/__init__.py', 'pandas/_libs/testing.pyd', + `numpy-${lock.pythonPackages.numpy}.dist-info/licenses/LICENSE.txt`, + `pandas-${lock.pythonPackages.pandas}.dist-info/LICENSE`, + 'other/tests/test_other.py', 'numpy_extra/tests/test_extra.py', + ] + const files = Object.fromEntries([...removed, ...retained].map(path => [path, Buffer.from(`contents of ${path}\n`)])) + // Quoted paths exercise RECORD's CSV encoding even when a filename contains a comma. + const row = (path: string): string => `"${path}",sha256=${createHash('sha256').update(files[path]!).digest('base64url')},${files[path]!.length}\n` + for (const [name, record] of Object.entries(records)) { + const paths = [...removed, ...retained].filter(path => path.startsWith(`${name}/`) || path.startsWith(`${name}-`)) + files[record] = Buffer.from(`${paths.map(row).join('')}${record},,\n`) + } + const archive = join(root, 'libraries.whl') + const sitePackages = join(root, 'site-packages') + const wheel = Buffer.from(zipSync(files)) + await writeFile(archive, wheel) + await unpackPrimaryRuntimeWheel(archive, sitePackages) + await mkdir(join(sitePackages, 'numpy/empty/tests'), { recursive: true }) + + prunePrimaryRuntimePythonTests(sitePackages) + + for (const path of [...removed, 'numpy/tests', 'numpy/empty/tests', 'pandas/tests']) { + await expect(readFile(join(sitePackages, path))).rejects.toMatchObject({ code: 'ENOENT' }) + } + for (const path of retained) expect(await readFile(join(sitePackages, path))).toEqual(files[path]) + for (const [name, record] of Object.entries(records)) { + const lines = (await readFile(join(sitePackages, record), 'utf8')).trimEnd().split('\n') + const expected = retained.filter(path => path.startsWith(`${name}/`) || path.startsWith(`${name}-`)) + expect(lines).toHaveLength(expected.length + 1) + for (const path of expected) { + const expectedRow = row(path).trimEnd() + expect(lines).toContain(path.includes(',') ? expectedRow : expectedRow.replace(`"${path}"`, path)) + } + expect(lines).toContain(`${record},,`) + } + expect(await readFile(archive)).toEqual(wheel) + const before = await Promise.all(Object.values(records).map(record => readFile(join(sitePackages, record)))) + prunePrimaryRuntimePythonTests(sitePackages) + expect(await Promise.all(Object.values(records).map(record => readFile(join(sitePackages, record))))).toEqual(before) + } finally { + await rm(root, { recursive: true, force: true }) + } +}) + +it.each(['"unterminated,,\n', 'numpy/tests/test_numpy.py,\n', '', ',,\n'])( + 'rejects malformed installed-file records before deleting that distribution\'s tests: %j', async (record) => { + const root = await mkdtemp(join(tmpdir(), 'primary-python-record-')) + try { + await mkdir(join(root, `numpy-${lock.pythonPackages.numpy}.dist-info`)) + await writeFile(join(root, records.numpy), record) + await mkdir(join(root, 'numpy/tests'), { recursive: true }) + const testFile = join(root, 'numpy/tests/test_numpy.py') + await writeFile(testFile, 'test fixture\n') + expect(() => { prunePrimaryRuntimePythonTests(root) }).toThrow('invalid wheel RECORD') + expect(await readFile(testFile, 'utf8')).toBe('test fixture\n') + } finally { + await rm(root, { recursive: true, force: true }) + } + }, +) diff --git a/scripts/primary-runtime/prune-python-tests.ts b/scripts/primary-runtime/prune-python-tests.ts new file mode 100644 index 0000000000..a953ca9afb --- /dev/null +++ b/scripts/primary-runtime/prune-python-tests.ts @@ -0,0 +1,41 @@ +/** Remove upstream Python test suites from the staged primary runtime. */ + +import { readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import Papa from 'papaparse' +import lock from './lock.json' with { type: 'json' } + +function removeTestDirectories(root: string, directory: string): string[] { + const removed: string[] = [] + for (const entry of readdirSync(join(root, directory), { withFileTypes: true })) { + if (!entry.isDirectory()) continue + const path = `${directory}/${entry.name}` + if (entry.name === 'tests') { + rmSync(join(root, path), { recursive: true }) + removed.push(path) + } else { + removed.push(...removeTestDirectories(root, path)) + } + } + return removed +} + +/** + * Prune NumPy/pandas tests and their RECORD rows, preserving testing helpers and native extensions. + * @param sitePackages - Staged site-packages directory containing the locked wheels. + * @throws If a locked distribution's RECORD is missing or malformed. + */ +export function prunePrimaryRuntimePythonTests(sitePackages: string): void { + for (const name of ['numpy', 'pandas'] as const) { + const record = join(sitePackages, `${name}-${lock.pythonPackages[name]}.dist-info`, 'RECORD') + const { data, errors } = Papa.parse(readFileSync(record, 'utf8'), { delimiter: ',', skipEmptyLines: true }) + if (errors.length > 0 || data.length === 0 + || !data.every((row): row is [string, string, string] => row.length === 3 && Boolean(row[0]))) { + throw new Error(`primary runtime: invalid wheel RECORD: ${record}`) + } + const removed = removeTestDirectories(sitePackages, name) + if (removed.length === 0) continue + const retained = data.filter(([path]) => !removed.some(directory => path.startsWith(`${directory}/`))) + writeFileSync(record, `${Papa.unparse(retained, { newline: '\n' })}\n`) + } +} diff --git a/scripts/primary-runtime/smoke.py b/scripts/primary-runtime/smoke.py index 232d67e108..7abac34ab6 100644 --- a/scripts/primary-runtime/smoke.py +++ b/scripts/primary-runtime/smoke.py @@ -1,6 +1,8 @@ """Exercise the relocated Office payload with its own isolated interpreter.""" +import csv import importlib.metadata +import io import json from pathlib import Path import re @@ -9,6 +11,8 @@ import sys import tempfile import numpy +# NumPy testing helpers require this native extension even without upstream test directories. +import numpy._core._multiarray_tests import pandas from docx import Document from docx.shared import Inches as DocxInches @@ -21,9 +25,31 @@ from pptx.enum.chart import XL_CHART_TYPE from pptx.util import Inches +def check_interpreters(): + """Exercise command aliases, child execution and a pip-enabled virtual environment.""" + executable = Path(sys.executable) + names = [executable.name] if sys.platform == "win32" else ["python", "python3", f"python{sys.version_info.major}.{sys.version_info.minor}"] + for name in names: + interpreter = executable.with_name(name) + subprocess.run([ + str(interpreter), "-I", "-B", "-c", + "import subprocess, sys; from pathlib import Path; " + "assert Path(sys.executable) == Path(sys.argv[1]); " + "subprocess.run([sys.executable, '-I', '-B', '-c', 'import ssl, sqlite3, ctypes'], check=True, timeout=30)", + str(interpreter), + ], check=True, timeout=60) + with tempfile.TemporaryDirectory(prefix="dsh python venv ") as directory: + environment = Path(directory) / "environment" + subprocess.run([str(executable.with_name(names[0])), "-I", "-B", "-m", "venv", str(environment)], check=True, timeout=60) + python = environment / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") + subprocess.run([str(python), "-I", "-B", "-c", "import sys; assert sys.prefix != sys.base_prefix"], check=True, timeout=30) + subprocess.run([str(python), "-I", "-B", "-m", "pip", "check"], check=True, timeout=30) + + def main(): """Check installed versions and read back editable Office documents.""" assert sys.version_info[:3] == tuple(map(int, sys.argv[2].split("."))), sys.version + check_interpreters() versions = json.loads(sys.argv[1]) # Only pip belongs to the interpreter baseline; all other distributions must be declared. # Each target's native release-host smoke must confirm this baseline. @@ -38,6 +64,16 @@ def main(): assert actual == expected, (name, actual, expected) assert numpy.arange(4).sum() == 6 assert pandas.DataFrame({"n": [1, 2]}).n.sum() == 3 + numpy.testing.assert_allclose(numpy.arange(4), [0, 1, 2, 3]) + pandas.testing.assert_frame_equal(pandas.DataFrame({"n": [1, 2]}), pandas.DataFrame({"n": [1, 2]})) + for library in (numpy, pandas): + root = Path(library.__file__).parent + assert not any(path.is_dir() for path in root.rglob("tests")), root + distribution = importlib.metadata.distribution(library.__name__) + record = distribution.read_text("RECORD") + assert record, library.__name__ + for file, _hash, _size in csv.reader(io.StringIO(record)): + assert distribution.locate_file(file).is_file(), file with tempfile.TemporaryDirectory(prefix="dsh-office-smoke-") as directory: root = Path(directory) diff --git a/scripts/python-runtime-download.spec.ts b/scripts/python-runtime-download.spec.ts new file mode 100644 index 0000000000..7d3b1bcfa4 --- /dev/null +++ b/scripts/python-runtime-download.spec.ts @@ -0,0 +1,135 @@ +/** Explicit resource acquisition through the Python carrier's private dispatcher. */ +import { spawn } from 'node:child_process' +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile, copyFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { expect, it } from 'vitest' + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'dsh-resource-download-')) + const bootstrap = join(root, 'node', 'runtime-bootstrap.mjs') + const platform = process.platform === 'darwin' ? 'macos' : process.platform === 'win32' ? 'win' : process.platform + const resources = join(root, `${platform}-${process.arch}`) + const cache = join(root, 'cache') + async function file(path: string, content: string) { + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, content) + } + await file(join(resources, 'downloads.json'), JSON.stringify({ identity: 'a'.repeat(64), office: [], pnpm: {} })) + await mkdir(dirname(bootstrap), { recursive: true }) + await copyFile(new URL('../python/sdk-runtime/runtime-bootstrap.mjs', import.meta.url), bootstrap) + await file(join(root, 'node/node_modules/@deepseek-ai/dsh-http-proxy/package.json'), '{"type":"module","exports":"./index.mjs"}') + await file(join(root, 'node/node_modules/@deepseek-ai/dsh-http-proxy/index.mjs'), 'export async function installProxyFromEnvironment(env) { if (typeof env.get !== "function") throw new Error("missing environment lookup"); return async () => {} }') + await file(join(root, 'node/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/package.json'), '{"type":"module","exports":{"./runner":"./runner.mjs"}}') + await file(join(root, 'node/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/runner.mjs'), '') + await file(join(root, 'node/node_modules/@deepseek-ai/dsh/package.json'), '{"type":"module"}') + await file(join(root, 'node/node_modules/@deepseek-ai/dsh/lib/bin.js'), 'export async function runCli() { if (process.argv[2]) { console.log(JSON.stringify({ argv: process.argv.slice(2) })); return } console.log(JSON.stringify({ primary: process.env.DSH_BUNDLED_PRIMARY_RUNTIME, office: process.env.DSH_BUNDLED_OFFICE_CLI })) }') + await file(join(root, 'node/primary-runtime.mjs'), ` + import { mkdir, writeFile } from 'node:fs/promises'; + import { join } from 'node:path'; + export async function downloadNodeRuntime(target, destination) { + if (process.env.DSH_RUNTIME_DOWNLOAD !== undefined) throw new Error("private selector leaked"); + await mkdir(join(destination, 'bin'), { recursive: true }); + await writeFile(join(destination, 'bin', process.platform === 'win32' ? 'node.exe' : 'node'), 'node'); + } + export async function preparePrimaryRuntime({ output }) { + if (process.env.DSH_RUNTIME_DOWNLOAD !== undefined) throw new Error("private selector leaked"); + await mkdir(join(output, 'primary-runtime'), { recursive: true }); + await writeFile(join(output, 'primary-runtime/runtime.json'), '{}'); + } + `) + await file(join(root, 'node/office-sidecar.mjs'), ` + import { mkdir, writeFile } from 'node:fs/promises'; + import { join } from 'node:path'; + export async function downloadOfficeSidecar(packages, destination) { + const directory = join(destination, 'node_modules/@deepseek-ai/libreoffice-kit/lib'); + await mkdir(directory, { recursive: true }); + await writeFile(join(directory, 'cli.js'), 'cli'); + if (process.env.DSH_FIXTURE_FAIL) throw new Error('fixture download failed'); + if (process.env.DSH_FIXTURE_BARRIER) { + process.stderr.write('ready\\n'); + await new Promise(resolve => process.stdin.once('data', resolve)); + process.stdin.pause(); + } + } + `) + function run(resource?: string, extra: NodeJS.ProcessEnv = {}, args: string[] = []) { + const child = spawn(process.execPath, [bootstrap, ...args], { + env: { ...process.env, DSH_RESOURCE_CACHE: cache, DSH_RUNTIME_DOWNLOAD: resource, DSH_BUNDLED_PRIMARY_RUNTIME: undefined, + DSH_OFFICE_SIDECAR: undefined, DSH_BUNDLED_OFFICE_CLI: undefined, ...extra }, + stdio: ['pipe', 'pipe', 'pipe'], + }) + let stdout = '', stderr = '' + child.stdout.on('data', (data) => { stdout += String(data) }) + let reportReady: (() => void) | undefined + let failReady: ((error: Error) => void) | undefined + const ready = extra.DSH_FIXTURE_BARRIER === undefined ? Promise.resolve() + : new Promise((resolve, reject) => { reportReady = resolve; failReady = reject }) + child.stderr.on('data', (data) => { stderr += String(data); if (stderr.includes('ready\n')) reportReady?.() }) + const done = new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => { + child.once('error', reject) + child.once('close', (code) => { failReady?.(new Error(`download exited before readiness: ${stderr}`)); resolve({ code, stdout, stderr }) }) + }) + return { child, ready, done } + } + return { root, cache, run } +} + +it('starts without downloading, independently downloads either resource, and reuses completed caches', async () => { + const { root, cache, run } = await fixture() + try { + expect(await run().done).toMatchObject({ code: 0, stdout: '{}\n' }) + await expect(readdir(cache)).rejects.toMatchObject({ code: 'ENOENT' }) + const primary = await run('primary').done + expect(primary.code, primary.stderr).toBe(0) + expect(JSON.parse(primary.stdout)).toBe(join(cache, 'a'.repeat(64), 'primary', 'primary-runtime')) + await expect(readdir(join(cache, 'a'.repeat(64), 'office'))).rejects.toMatchObject({ code: 'ENOENT' }) + const office = await run('office').done + expect(office.code, office.stderr).toBe(0) + const location = JSON.parse(office.stdout) as string + expect(await readFile(join(location, 'node_modules/@deepseek-ai/libreoffice-kit/lib/cli.js'), 'utf8')).toBe('cli') + expect(await run('office', { DSH_FIXTURE_FAIL: '1' }).done).toMatchObject({ code: 0, stdout: office.stdout }) + } finally { await rm(root, { recursive: true, force: true }) } +}) + +it('cleans failed staging and allows an explicit retry', async () => { + const { root, cache, run } = await fixture() + try { + const failed = await run('office', { DSH_FIXTURE_FAIL: '1' }).done + expect(failed.code).toBe(1) + expect(failed.stderr).toContain('fixture download failed') + expect(await readdir(join(cache, 'a'.repeat(64)))).toEqual([]) + expect((await run('office').done).code).toBe(0) + } finally { await rm(root, { recursive: true, force: true }) } +}) + +it('publishes one complete cache when two processes download concurrently', async () => { + const { root, cache, run } = await fixture() + const jobs = [run('office', { DSH_FIXTURE_BARRIER: '1' }), run('office', { DSH_FIXTURE_BARRIER: '1' })] + try { + await Promise.all(jobs.map(job => job.ready)) + for (const job of jobs) job.child.stdin.end('continue') + const results = await Promise.all(jobs.map(job => job.done)) + for (const result of results) expect(result.code, result.stderr).toBe(0) + expect(results[0]!.stdout).toBe(results[1]!.stdout) + expect(await readdir(join(cache, 'a'.repeat(64)))).toEqual(['office']) + } finally { + for (const job of jobs) if (job.child.exitCode === null && job.child.signalCode === null) job.child.kill() + await Promise.allSettled(jobs.map(job => job.done)) + await rm(root, { recursive: true, force: true }) + } +}) + + +it('leaves ordinary CLI arguments to the CLI and rejects an invalid private download selector', async () => { + const { root, cache, run } = await fixture() + try { + expect(await run(undefined, {}, ['--download-office']).done).toMatchObject({ + code: 0, stdout: JSON.stringify({ argv: ['--download-office'] }) + '\n', + }) + const rejected = await run('invalid').done + expect(rejected.code).toBe(1) + expect(rejected.stderr).toContain('DSH_RUNTIME_DOWNLOAD must select office or primary') + await expect(readdir(cache)).rejects.toMatchObject({ code: 'ENOENT' }) + } finally { await rm(root, { recursive: true, force: true }) } +}) diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index d79a0a3f88..417edb67d2 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -884,10 +884,18 @@ def main() -> None: def smoke_sdk_authoring(base_url: str, executable: Path, update_snapshots: bool) -> None: """Query the bundled Python and switch skills without replacing that environment.""" + + with tempfile.TemporaryDirectory(prefix="dsh-sdk-authoring-cache-") as cache_directory: + _smoke_sdk_authoring_cached(base_url, executable, update_snapshots, Path(cache_directory)) + + +def _smoke_sdk_authoring_cached(base_url: str, executable: Path, update_snapshots: bool, cache: Path) -> None: from deepseek_harness import DeepSeekHarness - resources = executable.with_name(executable.name.removeprefix("deepseek-harness-sdk-runtime-").removesuffix(".exe")) - manifest = json.loads((resources / "primary-runtime/runtime.json").read_text()) + cache_environment = {**os.environ, "DSH_RESOURCE_CACHE": str(cache), "DSH_RUNTIME_DOWNLOAD": "primary"} + primary = Path(json.loads(subprocess.check_output([str(executable)], encoding="utf-8", env=cache_environment))) + resources = primary.parent + manifest = json.loads((primary / "runtime.json").read_text()) for mode in ("default", "replacement", "disabled"): with tempfile.TemporaryDirectory(prefix="dsh-sdk-authoring-") as temporary: root = Path(temporary).resolve() @@ -903,7 +911,7 @@ def smoke_sdk_authoring(base_url: str, executable: Path, update_snapshots: bool) provider="deepseek-official", model="smoke-model", cwd=str(root), dsh_bin=str(executable), dsh_home=str(home), patches=(str(patch),), api_key="sk-keyless-smoke", base_url=base_url, - env={"DSH_PERMISSION_MODE": "danger-full-access", "DSH_TELEMETRY_DISABLED": "1"}, + env={"DSH_PERMISSION_MODE": "danger-full-access", "DSH_TELEMETRY_DISABLED": "1", "DSH_RESOURCE_CACHE": str(cache)}, request_timeout_seconds=60, ) as harness: result = harness.run(AUTHORING_PROMPT, session_id="authoring") @@ -958,7 +966,9 @@ def smoke_sdk_office(executable: Path) -> None: shutil.copytree(source, destination) else: shutil.copy2(source, destination) - office = root / f"{stem}-office" + cache_environment = {**os.environ, "DSH_RESOURCE_CACHE": str(root / "cache")} + office = Path(json.loads(subprocess.check_output([str(relocated)], encoding="utf-8", env={**cache_environment, "DSH_RUNTIME_DOWNLOAD": "office"}))) + assert not (office.parent / "primary").exists(), "Office download unexpectedly prepared the authoring environment" adapter = office / "node_modules/@deepseek-ai/libreoffice-kit/package.json" native = stem.removeprefix("deepseek-harness-sdk-runtime-").replace("win-", "win32-").replace("macos-", "darwin-") declared = json.loads(adapter.read_text(encoding="utf-8")).get("optionalDependencies", {}) @@ -997,7 +1007,7 @@ def smoke_sdk_office(executable: Path) -> None: patches=(str(patch),), api_key="sk-keyless-smoke", base_url="http://127.0.0.1:9", - env={"DSH_PERMISSION_MODE": "danger-full-access", "DSH_TELEMETRY_DISABLED": "1"}, + env={"DSH_PERMISSION_MODE": "danger-full-access", "DSH_TELEMETRY_DISABLED": "1", "DSH_RESOURCE_CACHE": str(root / "cache")}, # The startup plugin awaits a converter with a 120-second deadline before JSON-RPC is ready. initialize_timeout_seconds=180, request_timeout_seconds=180, @@ -1007,10 +1017,32 @@ def smoke_sdk_office(executable: Path) -> None: if result["backend"] != expected_backend: raise AssertionError(f"Office conversion did not use {expected_backend}: {result}") if not result["moduleUrl"].startswith(office.as_uri() + "/"): - raise AssertionError(f"Office module was not loaded from the relocated wheel: {result}") + raise AssertionError(f"Office module was not loaded from the downloaded sidecar: {result}") pdf = output.read_bytes() if len(pdf) < 100 or not pdf.startswith(b"%PDF-"): raise AssertionError(f"Office conversion produced an invalid PDF at {output}") + workbook = root / "input.xlsx" + with zipfile.ZipFile(workbook, "w", compression=zipfile.ZIP_DEFLATED) as archive: + archive.writestr("[Content_Types].xml", '') + archive.writestr("_rels/.rels", '') + archive.writestr("xl/workbook.xml", '') + archive.writestr("xl/_rels/workbook.xml.rels", '') + archive.writestr("xl/worksheets/sheet1.xml", '1+20') + subprocess.run([sys.executable, "-c", """ +import sys, zipfile +from pathlib import Path +from xml.etree import ElementTree +from deepseek_harness.office import convert, render_images, recalculate +root = Path(sys.argv[1]) +assert convert(root / 'document.docx', root / 'python.pdf').backend == sys.argv[2] +rendered = render_images(root / 'python.pdf', root / 'images', pages=[1]) +assert rendered.images and rendered.images[0].path.read_bytes().startswith(b'\\x89PNG') +recalculate(root / 'input.xlsx', root / 'calculated.xlsx') +with zipfile.ZipFile(root / 'calculated.xlsx') as archive: + sheet = ElementTree.fromstring(archive.read('xl/worksheets/sheet1.xml')) + assert sheet.find('.//{*}c[@r="A1"]/{*}v').text == '3' +""", str(root), expected_backend], env={name: value for name, value in cache_environment.items() if name != "DSH_OFFICE_SIDECAR"}, check=True, timeout=180) + assert not (office.parent / "primary").exists(), "Python Office API unexpectedly downloaded authoring resources" print(f"smoke-python-runtime: relocated Office {result['backend']} DOCX produced {len(pdf)} PDF bytes") @@ -1336,6 +1368,8 @@ def smoke_sdk_dynamic_tools(base_url: str, executable: Path, update_snapshots: b "DSH_PERMISSION_MODE": "danger-full-access", "DSH_TELEMETRY_DISABLED": "1", "HOME": str(user_home), "USERPROFILE": str(user_home), "DSH_AGENTS_HOME": str(user_home / ".agents"), + # Pin the tool baseline independently of optional resources in the host cache. + "DSH_PRIMARY_RUNTIME": "", }, api_key="sk-keyless-smoke", base_url=base_url, request_timeout_seconds=60, ) as harness: @@ -2307,11 +2341,17 @@ def build_dynamic_tools_snapshot_files( assert changes == [[], [{"type": "tool_addition", "tool": {"type": "tool_reference", "name": "snapshot_ping"}}], []], changes assert requests[1]["messages"][:len(requests[0]["messages"])] == requests[0]["messages"], "tool addition changed earlier messages" replacements = [(str(cwd), "{{cwd}}"), (result.session_id, "{{session}}")] + header_references = {header["seq"]: f"{{{{header:{index + 1}}}}}" for index, header in enumerate(headers)} + snapshot_events = [ + {**event, "data": {**event["data"], "headerSeq": header_references[event["data"]["headerSeq"]]}} + if event["type"] == "developer/message" and "headerSeq" in event["data"] else event + for event in events if event["type"] in {"request/header", "request/context", "developer/message"} + ] evidence = { "finalResponse": result.final_response, "declarations": declarations, "requestToolChanges": changes, - "events": [event for event in events if event["type"] in {"request/header", "request/context", "developer/message"}], + "events": snapshot_events, "toolCalls": calls, "pingResult": ping, } diff --git a/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json b/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json index 7a8a75aa85..d93f0c33c1 100644 --- a/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json +++ b/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json @@ -56,7 +56,6 @@ "job_list", "job_output", "list_agents", - "load_workspace_dependencies", "read", "read_image", "send_message", @@ -87,7 +86,7 @@ }, { "type": "request/header", - "seq": 20, + "seq": 19, "time": 0, "data": { "header": { @@ -113,7 +112,6 @@ "job_list", "job_output", "list_agents", - "load_workspace_dependencies", "read", "read_image", "send_message", @@ -135,7 +133,7 @@ }, { "type": "developer/message", - "seq": 21, + "seq": 20, "time": 0, "data": { "turn": 1, @@ -153,13 +151,13 @@ "role": "developer", "id": "{{messageId}}" }, - "headerSeq": 20 + "headerSeq": "{{header:2}}" }, "surfaceOp": "append" }, { "type": "request/header", - "seq": 28, + "seq": 26, "time": 0, "data": { "header": { @@ -185,7 +183,6 @@ "job_list", "job_output", "list_agents", - "load_workspace_dependencies", "read", "read_image", "send_message", @@ -206,7 +203,7 @@ }, { "type": "developer/message", - "seq": 29, + "seq": 27, "time": 0, "data": { "turn": 1, diff --git a/scripts/verify-package-meta.spec.ts b/scripts/verify-package-meta.spec.ts index 1aaea96429..3227c18c04 100644 --- a/scripts/verify-package-meta.spec.ts +++ b/scripts/verify-package-meta.spec.ts @@ -1,11 +1,13 @@ /** Plugin metadata checks use private source-only packages and real resource exports. */ -import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, beforeEach, expect, it } from 'vitest' import { packageMetaProblems } from './verify-package-meta.ts' +const validSvg = '' + let root: string let dir: string beforeEach(() => { @@ -26,7 +28,7 @@ function json(path: string, contents: unknown): void { function manifest(fields: object = {}): void { json('package.json', { - name: '@test/plugin', + name: '@deepseek-ai/dsh-test-plugin', description: 'Package description', type: 'module', exports: { '.': './lib/index.js', './package.json': './package.json', './locale/*.json': './locale/*.json' }, @@ -46,14 +48,89 @@ it('does not require locale resources for exported package name and description' it.each(['legacy.svg', './legacy.svg'])('accepts a manifest-only icon %s', (icon) => { manifest({ icon, files: ['legacy.svg'] }) - file('legacy.svg', 'legacy') + file('legacy.svg', validSvg) expect(packageMetaProblems(root)).toEqual([]) }) +it.each(['manifest', 'export'])('accepts SVG geometry and local references selected by %s', (selection) => { + manifest({ + ...selection === 'manifest' ? { icon: './icon.svg' } : {}, + exports: { './package.json': './package.json', './icon': './icon.svg' }, files: ['icon.svg'], + }) + file('icon.svg', validSvg.replace('', ''), 'well-formed XML'], + ['wrong root', validSvg.replaceAll('svg', 'g'), 'svg root'], + ['wrong namespace', validSvg.replace('http://www.w3.org/2000/svg', 'urn:other'), 'SVG namespace'], + ['toolbar canvas', validSvg.replace('0 0 36 36', '0 0 16 16'), 'viewBox="0 0 36 36"'], + ['toolbar width', validSvg.replace('width="36"', 'width="16"'), 'width="36"'], + ['toolbar height', validSvg.replace('height="36"', 'height="16"'), 'height="36"'], + ['missing definition', validSvg.replace('url(#ink)', 'url(#missing)'), 'must name a local id'], + ['external definition', validSvg.replace('url(#ink)', 'url(https://example.test/ink.svg#ink)'), 'must name a local id'], + ['external href', validSvg.replace(']+\/>/u, ''), 'must contain geometry'], + ...['script', 'style', 'image', 'foreignObject', 'text', 'animate', 'animateTransform', 'animateMotion', 'set'] + .map(tag => [tag, validSvg.replace('', `<${tag} />`), 'self-contained geometry']), +])('rejects SVG %s through metadata verification', (_name, source, diagnostic) => { + manifest({ icon: './icon.svg', files: ['icon.svg'] }) + file('icon.svg', source) + const problems = packageMetaProblems(root) + expect(problems).toHaveLength(1) + expect(problems[0]).toContain(`${join(dir, 'icon.svg')}:`) + expect(problems[0]).toContain(diagnostic) +}) + +it('validates the selected ./icon SVG fallback without a manifest icon', () => { + manifest({ exports: { './package.json': './package.json', './icon': './icon.svg' }, files: ['icon.svg'] }) + file('icon.svg', validSvg.replace('width="36"', 'width="16"')) + expect(packageMetaProblems(root)).toEqual([`${realpathSync(join(dir, 'icon.svg'))}: SVG icon must use width="36" height="36" viewBox="0 0 36 36"`]) +}) + +it('validates the manifest icon instead of the lower-priority SVG export', () => { + manifest({ icon: './icon.svg', exports: { './package.json': './package.json', './icon': './fallback.svg' }, files: ['icon.svg', 'fallback.svg'] }) + file('icon.svg', validSvg) + file('fallback.svg', 'not XML') + expect(packageMetaProblems(root)).toEqual([]) +}) + +it.each(['png', 'jpg', 'jpeg', 'webp'].flatMap(extension => ['manifest', 'export'].map(selection => ({ extension, selection }))))( + 'keeps $extension bytes opaque for $selection icons', ({ extension, selection }) => { + manifest({ + ...selection === 'manifest' ? { icon: `./icon.${extension}` } : {}, + exports: { './package.json': './package.json', './icon': `./icon.${extension}` }, files: [`icon.${extension}`], + }) + file(`icon.${extension}`, 'opaque raster bytes') + expect(packageMetaProblems(root)).toEqual([]) + }, +) + +it.each(['@local/demo', '@deepseek-ai/other'])('keeps nonofficial %s SVGs outside official artwork conventions', (name) => { + manifest({ name, icon: './icon.svg', files: ['icon.svg'] }) + file('icon.svg', '') + expect(packageMetaProblems(root)).toEqual([]) +}) + +it('checks official artwork in named nested packages', () => { + manifest({ exports: { '.': './entry.js' }, files: ['nested'] }) + json('nested/package.json', { + name: '@deepseek-ai/dsh-nested', exports: { './icon': './icon.svg' }, files: ['icon.svg'], + }) + file('nested/icon.svg', validSvg.replace('width="36"', 'width="16"')) + expect(packageMetaProblems(root)).toEqual([ + `${realpathSync(join(dir, 'nested/icon.svg'))}: SVG icon must use width="36" height="36" viewBox="0 0 36 36"`, + ]) +}) + it('reads the manifest image and still rejects an unresolvable lower-priority export', () => { manifest({ icon: './legacy.svg', files: ['legacy.svg'], exports: { './package.json': './package.json', './icon': '../invalid.svg' } }) - file('legacy.svg', 'legacy') + file('legacy.svg', validSvg) expect(packageMetaProblems(root)).toEqual([`${join(dir, 'package.json')}: exports["./icon"] must resolve to a file`]) }) @@ -62,7 +139,7 @@ it.each([['display'], ['display/manifest.json'], ['display/logo.svg']]) manifest({ files, exports: { './package.json': './display/manifest.json' } }) json('display/manifest.json', { icon: './logo.svg' }) - file('display/logo.svg', 'legacy') + file('display/logo.svg', validSvg) const problems = packageMetaProblems(root).join('\n') if (files.includes('display')) expect(problems).toBe('') else expect(problems).toContain(`files must include ${files.includes('display/manifest.json') ? 'display/logo.svg' : 'display/manifest.json'}`) @@ -71,15 +148,15 @@ it.each([['display'], ['display/manifest.json'], ['display/logo.svg']]) it('requires the root manifest icon declaration to remain accessible', () => { manifest({ icon: './legacy.svg', files: ['legacy.svg'], exports: { './icon': './legacy.svg' } }) - file('legacy.svg', 'legacy') + file('legacy.svg', validSvg) expect(packageMetaProblems(root).join('\n')).toContain('exports must expose its icon declaration') }) it.each([null, false, '', './missing.svg'])('diagnoses legacy icon %j despite a valid fallback export', (icon) => { manifest({ icon, files: ['fallback.svg'], exports: { './package.json': './package.json', './icon': './fallback.svg' } }) - file('fallback.svg', 'fallback') - expect(packageMetaProblems(root).join('\n')).toContain('Plugin metadata for @test/plugin:') + file('fallback.svg', validSvg) + expect(packageMetaProblems(root).join('\n')).toContain('Plugin metadata for @deepseek-ai/dsh-test-plugin:') }) it.each([undefined, ['art'], ['art/*.webp'], ['./art/icon.webp']])('accepts an exported icon without other resources: %j', (files) => { @@ -96,7 +173,7 @@ it.each([['lib'], ['art', '!art/icon.webp']])('rejects an exported icon omitted it.each([false, 1, '', './icon.gif', '/tmp/icon.svg', './missing.png', '../outside.svg'])('validates exported icon targets: %j', (icon) => { manifest({ exports: { './icon': icon } }) - expect(packageMetaProblems(root).join('\n')).toMatch(/Plugin metadata for @test\/plugin:|exports\["\.\/icon"\] must resolve to a file/u) + expect(packageMetaProblems(root).join('\n')).toMatch(/Plugin metadata for @deepseek-ai\/dsh-test-plugin:|exports\["\.\/icon"\] must resolve to a file/u) }) it.each([['assets'], ['lib']])('checks publication of the Node-selected conditional icon: %j', (...files) => { @@ -116,8 +193,8 @@ it('ignores package.json exported at a subpath plugin address', () => { it.each([['search.svg'], ['lib']])('reads and publishes a subpath icon export: %j', (...files) => { manifest({ icon: './root.svg', exports: { './package.json': './package.json', './search': './search.js', './search/icon': './search.svg' }, files: ['root.svg', ...files] }) - file('root.svg', 'root') - file('search.svg', 'search') + file('root.svg', validSvg) + file('search.svg', validSvg) const problems = packageMetaProblems(root) if (files.includes('search.svg')) expect(problems).toEqual([]) else expect(problems).toEqual([`${join(dir, 'package.json')}: files must include search.svg`]) @@ -165,8 +242,8 @@ it.each([ files: ['locale', 'icon.svg'], ...fields, }) json('examples/nested/locale/en.json', { meta: { title } }) - file('examples/nested/icon.svg', '') - file('examples/nested/fallback.svg', '') + file('examples/nested/icon.svg', validSvg) + file('examples/nested/fallback.svg', validSvg) const problems = packageMetaProblems(root) if (expected === undefined) expect(problems).toEqual([]) else expect(problems.join('\n')).toContain(expected) @@ -255,7 +332,7 @@ it('does not read built locale JSON while checking a source icon declaration', ( icon: './icon.svg', files: ['icon.svg'], exports: { './package.json': './package.json', './locale/en.json': './lib/locale/en.json' }, }) - file('icon.svg', '') + file('icon.svg', validSvg) file('lib/locale/en.json', '{') json('locale/en.json', { meta: { title: 'Plugin' } }) const problems = packageMetaProblems(root).join('\n') @@ -270,7 +347,7 @@ it.each(['lib', 'tests'])('rejects an icon declaration when its only locale is e }) file(`${directory}/locale/en.json`, '{}') const problems = packageMetaProblems(root).join('\n') - expect(problems).toContain('@test/plugin: icon metadata requires locale resources to resolve to source JSON') + expect(problems).toContain('@deepseek-ai/dsh-test-plugin: icon metadata requires locale resources to resolve to source JSON') expect(problems).not.toContain('Plugin metadata for') }) @@ -594,7 +671,7 @@ it('reports metadata failures from more than one workspace package', () => { json('locale/en.json', { meta: { title: 'Second' } }) json('locale/zh.json', { meta: { description: '' } }) const problems = packageMetaProblems(root).join('\n') - expect(problems).toContain('@test/plugin') + expect(problems).toContain('@deepseek-ai/dsh-test-plugin') expect(problems).toContain('@test/second') }) @@ -603,6 +680,6 @@ it.each([[], ['locale']])('rejects a display manifest in build output without re if (locales.length > 0) json('locale/en.json', { meta: { title: 'Plugin' } }) file('lib/display.json', '{') const problems = packageMetaProblems(root).join('\n') - expect(problems).toContain('@test/plugin/package.json: display manifest must resolve to source JSON') + expect(problems).toContain('@deepseek-ai/dsh-test-plugin/package.json: display manifest must resolve to source JSON') expect(problems).not.toContain('Plugin metadata for') }) diff --git a/scripts/verify-package-meta.ts b/scripts/verify-package-meta.ts index a7fdd34f1a..0d0188530e 100644 --- a/scripts/verify-package-meta.ts +++ b/scripts/verify-package-meta.ts @@ -1,8 +1,9 @@ -/** Validate source locale metadata, Node resource exports, and package publication selections. */ +/** Validate source locale metadata, official SVG artwork, Node resource exports, and publication selections. */ import { globSync, readFileSync, realpathSync } from 'node:fs' import { basename, dirname, join, matchesGlob, relative, resolve } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' +import { JSDOM } from 'jsdom' import { readPluginMeta, resolvePluginResource } from '../packages/boot/app-boot/src/package-meta.ts' interface Manifest { @@ -72,7 +73,46 @@ function published(file: string, files: string[]): boolean { && !files.some(pattern => pattern.startsWith('!') && covered(pattern.slice(1))) } -function packageProblems(manifestPath: string): string[] { +/** Structural artwork conventions only; not an SVG sanitizer or a rendered-pixel check. */ +function svgArtworkProblems(icon: string, parser: DOMParser): string[] { + const prefix = 'data:image/svg+xml;base64,' + if (!icon.startsWith(prefix)) return [] + const document = parser.parseFromString(Buffer.from(icon.slice(prefix.length), 'base64').toString('utf8'), 'image/svg+xml') + if (document.querySelector('parsererror') !== null) return ['SVG icon must contain well-formed XML'] + const svg = document.documentElement + if (svg.localName !== 'svg' || svg.namespaceURI !== 'http://www.w3.org/2000/svg') { + return ['SVG icon must have an svg root in the SVG namespace'] + } + const problems: string[] = [] + if (svg.getAttribute('viewBox') !== '0 0 36 36' || svg.getAttribute('width') !== '36' || svg.getAttribute('height') !== '36') { + problems.push('SVG icon must use width="36" height="36" viewBox="0 0 36 36"') + } + if (svg.querySelector('path, rect, circle, ellipse, line, polyline, polygon') === null) { + problems.push('SVG icon must contain geometry') + } + if (svg.querySelector('script, style, image, foreignObject, text, animate, animateTransform, animateMotion, set') !== null) { + problems.push('SVG icon must use self-contained geometry without scripts, styles, images, foreignObject, text, or animation') + } + const elements = [svg, ...svg.querySelectorAll('*')] + const ids = elements.flatMap(element => element.hasAttribute('id') ? [element.id] : []) + const uniqueIds = new Set(ids) + if (uniqueIds.size !== ids.length) problems.push('SVG icon must use unique ids') + for (const element of elements) { + for (const attribute of element.attributes) { + if (/^on/iu.test(attribute.name)) problems.push(`SVG icon must not use event handler ${attribute.name}`) + const references = [...attribute.value.matchAll(/url\(([^)]+)\)/gu)].map(match => (match[1] ?? '').replace(/['"]/gu, '').trim()) + if (attribute.localName === 'href') references.push(attribute.value) + for (const reference of references) { + if (!reference.startsWith('#') || !uniqueIds.has(reference.slice(1))) { + problems.push(`SVG icon reference ${reference} must name a local id`) + } + } + } + } + return problems +} + +function packageProblems(manifestPath: string, parser: DOMParser): string[] { const problems: string[] = [] const dir = realpathSync(dirname(manifestPath)) const pkg = JSON.parse(readFileSync(manifestPath, 'utf8')) as Manifest @@ -152,6 +192,9 @@ function packageProblems(manifestPath: string): string[] { : displayManifest !== undefined && typeof iconDocument?.icon === 'string' ? resolve(dirname(displayManifest), iconDocument.icon) : lookup(`${specifier}/icon`) + if (pkg.name.startsWith('@deepseek-ai/dsh-') && meta?.icon !== undefined) { + problems.push(...svgArtworkProblems(meta.icon, parser).map(problem => `${iconTarget ?? specifier}: ${problem}`)) + } for (const target of [displayManifest, iconTarget]) { if (target === undefined) continue const file = relative(dir, target).replaceAll('\\', '/') @@ -209,18 +252,26 @@ function packageProblems(manifestPath: string): string[] { })) continue problems.push(`${manifestPath}: exports must expose ${document.file} as a plugin locale resource with an en.json discovery baseline`) } - return problems.concat(children.flatMap(child => packageProblems(join(dir, child.file)))) + return problems.concat(children.flatMap(child => packageProblems(join(dir, child.file), parser))) } /** * Check workspace and named nested package metadata without evaluating plugin entries or reading built output. + * Selected SVG icons in @deepseek-ai/dsh-* packages follow official artwork conventions. + * Other packages and supported raster icons keep their metadata and publication checks. * @param root - repository or fixture root. - * @returns diagnostics for an empty package corpus, invalid metadata, inaccessible resources, or omitted publication files. + * @returns diagnostics for an empty package corpus, invalid metadata or SVG artwork, inaccessible resources, or omitted publication files. */ export function packageMetaProblems(root: string): string[] { const manifests = globSync('packages/*/*/package.json', { cwd: root }).map(path => path.replaceAll('\\', '/')) if (manifests.length === 0) return [`${root}: no workspace package manifests found`] - return manifests.flatMap(path => packageProblems(join(root, path))) + const { window } = new JSDOM() + try { + const parser = new window.DOMParser() + return manifests.flatMap(path => packageProblems(join(root, path), parser)) + } finally { + window.close() + } } if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { @@ -229,6 +280,6 @@ if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath( console.error(problems.join('\n')) process.exitCode = 1 } else { - console.log('verify-package-meta: plugin locale metadata, resource exports, and publication files are valid.') + console.log('verify-package-meta: plugin locale metadata, SVG artwork, resource exports, and publication files are valid.') } } diff --git a/snapshots/sdk/tool-error-details/system-prompt.expected.md b/snapshots/sdk/tool-error-details/system-prompt.expected.md index 1d7989e180..c7bcdec744 100644 --- a/snapshots/sdk/tool-error-details/system-prompt.expected.md +++ b/snapshots/sdk/tool-error-details/system-prompt.expected.md @@ -360,7 +360,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/session/advanced-toolchain/system-prompt.expected.md b/snapshots/session/advanced-toolchain/system-prompt.expected.md index b8b874cec2..c97a5b8fcb 100644 --- a/snapshots/session/advanced-toolchain/system-prompt.expected.md +++ b/snapshots/session/advanced-toolchain/system-prompt.expected.md @@ -375,7 +375,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/session/both-mode-turn/system-prompt.expected.md b/snapshots/session/both-mode-turn/system-prompt.expected.md index 2c3daed342..d58e71a227 100644 --- a/snapshots/session/both-mode-turn/system-prompt.expected.md +++ b/snapshots/session/both-mode-turn/system-prompt.expected.md @@ -327,7 +327,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/session/mcp-resources-ptc/system-prompt.expected.md b/snapshots/session/mcp-resources-ptc/system-prompt.expected.md index 168684cc1f..e9b26ca33b 100644 --- a/snapshots/session/mcp-resources-ptc/system-prompt.expected.md +++ b/snapshots/session/mcp-resources-ptc/system-prompt.expected.md @@ -356,7 +356,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/session/ptc-node-read-only/system-prompt.expected.md b/snapshots/session/ptc-node-read-only/system-prompt.expected.md index b8950c4116..2801645046 100644 --- a/snapshots/session/ptc-node-read-only/system-prompt.expected.md +++ b/snapshots/session/ptc-node-read-only/system-prompt.expected.md @@ -331,7 +331,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/session/ptc-node-workspace/system-prompt.expected.md b/snapshots/session/ptc-node-workspace/system-prompt.expected.md index b8950c4116..2801645046 100644 --- a/snapshots/session/ptc-node-workspace/system-prompt.expected.md +++ b/snapshots/session/ptc-node-workspace/system-prompt.expected.md @@ -331,7 +331,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/session/ptc-persistent/system-prompt.expected.md b/snapshots/session/ptc-persistent/system-prompt.expected.md index b8950c4116..2801645046 100644 --- a/snapshots/session/ptc-persistent/system-prompt.expected.md +++ b/snapshots/session/ptc-persistent/system-prompt.expected.md @@ -331,7 +331,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/session/ptc-policy-change/system-prompt.expected.md b/snapshots/session/ptc-policy-change/system-prompt.expected.md index b4650e5a05..19204006b3 100644 --- a/snapshots/session/ptc-policy-change/system-prompt.expected.md +++ b/snapshots/session/ptc-policy-change/system-prompt.expected.md @@ -329,7 +329,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/session/ptc-python-turn/system-prompt.expected.md b/snapshots/session/ptc-python-turn/system-prompt.expected.md index 6b014fafa8..6e5a4c7a78 100644 --- a/snapshots/session/ptc-python-turn/system-prompt.expected.md +++ b/snapshots/session/ptc-python-turn/system-prompt.expected.md @@ -158,7 +158,7 @@ class ExitPlanModeArgs(TypedDict): # Additional keys beyond those declared are allowed. class ExitPlanModeOutput(TypedDict): - approved: Literal[True] + approved: bool class GetGoalOutput1(TypedDict): goal: None diff --git a/snapshots/session/ptc-read-image/system-prompt.expected.md b/snapshots/session/ptc-read-image/system-prompt.expected.md index 40e9fc9f78..052b90fb17 100644 --- a/snapshots/session/ptc-read-image/system-prompt.expected.md +++ b/snapshots/session/ptc-read-image/system-prompt.expected.md @@ -327,7 +327,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/session/ptc-turn/system-prompt.expected.md b/snapshots/session/ptc-turn/system-prompt.expected.md index b8950c4116..2801645046 100644 --- a/snapshots/session/ptc-turn/system-prompt.expected.md +++ b/snapshots/session/ptc-turn/system-prompt.expected.md @@ -331,7 +331,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/web/auto-review-approval/ui.expected.md b/snapshots/web/auto-review-approval/ui.expected.md index 71cc3eb2b2..4d29eebaea 100644 --- a/snapshots/web/auto-review-approval/ui.expected.md +++ b/snapshots/web/auto-review-approval/ui.expected.md @@ -18,9 +18,7 @@ - 'button "Tool call Error: Auto review of tool \"mystery\" failed; its body was not executed: auto-review: reviewer ended with error UNKNOWN: provider unavailable"' - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" -- 'button "Access mode, current: Auto review EXP"': - - text: Auto review - - superscript: EXP +- 'button "Access mode, current: Auto review"': Auto review - button "Select model, current DeepSeek-V4-Flash": DeepSeek-V4-Flash - button "Send message" [disabled] - button "1 turns 2 steps" @@ -49,9 +47,7 @@ - button "Inspect" - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" -- 'button "Access mode, current: Auto review EXP"': - - text: Auto review - - superscript: EXP +- 'button "Access mode, current: Auto review"': Auto review - button "Select model, current DeepSeek-V4-Flash": DeepSeek-V4-Flash - button "Send message" [disabled] - button "1 turns 2 steps" diff --git a/snapshots/web/auto-review-denial/ui.expected.md b/snapshots/web/auto-review-denial/ui.expected.md index d3172476e3..45a660ffb2 100644 --- a/snapshots/web/auto-review-denial/ui.expected.md +++ b/snapshots/web/auto-review-denial/ui.expected.md @@ -19,9 +19,7 @@ - button "Bash Rejected by Auto review" - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" -- 'button "Access mode, current: Auto review EXP"': - - text: Auto review - - superscript: EXP +- 'button "Access mode, current: Auto review"': Auto review - button "Select model, current DeepSeek-V4-Flash": DeepSeek-V4-Flash - button "Send message" [disabled] - button "1 turns 2 steps" @@ -51,9 +49,7 @@ - button "Inspect" - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" -- 'button "Access mode, current: Auto review EXP"': - - text: Auto review - - superscript: EXP +- 'button "Access mode, current: Auto review"': Auto review - button "Select model, current DeepSeek-V4-Flash": DeepSeek-V4-Flash - button "Send message" [disabled] - button "1 turns 2 steps" @@ -110,9 +106,7 @@ - tabpanel "Result": "AutoReviewDeniedError: AUTO_REVIEW_DENIED Error: Auto review rejected tool \"bash\"; its body was not executed" - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" -- 'button "Access mode, current: Auto review EXP"': - - text: Auto review - - superscript: EXP +- 'button "Access mode, current: Auto review"': Auto review - button "Select model, current DeepSeek-V4-Flash": DeepSeek-V4-Flash - button "Send message" [disabled] - button "1 turns 2 steps" diff --git a/snapshots/web/official-subagent-bundle/system-prompt.expected.md b/snapshots/web/official-subagent-bundle/system-prompt.expected.md index cdfc1df2b4..18d698da61 100644 --- a/snapshots/web/official-subagent-bundle/system-prompt.expected.md +++ b/snapshots/web/official-subagent-bundle/system-prompt.expected.md @@ -429,7 +429,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/web/optional-string-editor/system-prompt.expected.md b/snapshots/web/optional-string-editor/system-prompt.expected.md index ff2c0b7262..489eae47e2 100644 --- a/snapshots/web/optional-string-editor/system-prompt.expected.md +++ b/snapshots/web/optional-string-editor/system-prompt.expected.md @@ -437,7 +437,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/web/ptc-round/system-prompt.expected.md b/snapshots/web/ptc-round/system-prompt.expected.md index c0ca0dd175..1f96806224 100644 --- a/snapshots/web/ptc-round/system-prompt.expected.md +++ b/snapshots/web/ptc-round/system-prompt.expected.md @@ -420,7 +420,7 @@ interface ToolOutputMap { after: string; }; exit_plan_mode: { - approved: true; + approved: boolean; }; get_goal: { goal: null; diff --git a/snapshots/web/question-composer/queued.expected.md b/snapshots/web/question-composer/queued.expected.md index 25f73a3b5c..a9d5643aae 100644 --- a/snapshots/web/question-composer/queued.expected.md +++ b/snapshots/web/question-composer/queued.expected.md @@ -19,7 +19,7 @@ - button "Inspect" - list: - listitem: - - text: "{\"kind\":\"answer_to_pending_question\",\"tool\":\"ask_user_question\",\"callId\":\"call_00_Cijldc88LYmVPCXYUsRq1617\",\"questions\":[{\"id\":\"color\",\"question\":\"Which color do you prefer?\",\"header\":\"Pick one\",\"mult…" + - text: "{\"kind\":\"answer_to_pending_question\",\"tool\":\"ask_user_question\",\"callId\":\"call_00_Cijldc88LYmVPCXYUsRq1617\",\"questions\":[{\"id\":\"color\",\"question\":\"Which color do you prefer?\",\"header\":\"Pick one\",\"multi_select\":true,\"options\":[{\"label\":\"Blue\",\"description\":\"A cool recessive hue that reads as calm and trustworthy in long reading sessions and dense dashboards.\"},{\"label\":\"Green\",\"description\":\"A restful mid-spectrum hue with the highest perceived brightness, easiest on the eye over long sessions.\"}]}],\"answers\":[{\"id\":\"color\",\"selected\":[\"Green\"],\"custom\":\"Answered after the timeout\"}]}" - button "Edit queued message" - button "Remove queued message" - button "Steer queued message" [disabled] diff --git a/tsconfig.host.json b/tsconfig.host.json index 68c54e061e..f18e30d8f0 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -11,6 +11,7 @@ "apps/web/tests/collapse-timing.e2e.ts", "apps/web/tests/chat-flow-layout.e2e.ts", "apps/web/product-isolation.ts", + "apps/web/katex-fonts.ts", "apps/web/tests/connection-recovery.e2e.ts", "apps/web/tests/server-restart.e2e.ts", "apps/web/tests/shortcuts.e2e.ts", @@ -99,7 +100,7 @@ "apps/web/tests/desktop-onboarding.e2e.ts", "apps/web/tests/bonus-notice.e2e.ts", "apps/web/tests/onboarding-usable-provider.e2e.ts", - "apps/web/tests/remote-welcome.e2e.ts", + "apps/web/tests/remote-settings.e2e.ts", "apps/web/tests/public-mount.e2e.ts", "apps/web/tests/workspace-new-session-folding.e2e.ts", "apps/web/tests/workspace-management.e2e.ts", @@ -127,6 +128,7 @@ "apps/web/tests/present.e2e.ts", "apps/web/tests/present-svg.e2e.ts", "apps/web/tests/composer-draft-scroll.e2e.ts", + "apps/web/tests/composer-focus.e2e.ts", "apps/web/tests/composer-placeholder.e2e.ts", "apps/web/tests/context-meter.e2e.ts", "apps/web/tests/cordis-tool-round.e2e.ts", diff --git a/vendor/README.md b/vendor/README.md index 71cd648b03..1765056c37 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -58,6 +58,8 @@ Keep this log exhaustive — every divergence from upstream must be listed. 23. **`loader/src/config/entry.ts` module identity**: retains each entry's raw import result as `moduleNamespace`, before plugin export normalization. HMR matches that object to Node's cached module namespace and updates it after a successful reload. `EntryTree.import()` keeps its existing arguments and return value; `loader/README.md` documents the additive field. +24. **`timer/locale/{en,zh}.json` display metadata**: local English and Chinese titles and descriptions for the Settings plugin inventory. `timer/package.json` exports and publishes these locale resources. + ## Sync procedure To update a vendored package from upstream: diff --git a/vendor/timer/locale/en.json b/vendor/timer/locale/en.json new file mode 100644 index 0000000000..525d713f46 --- /dev/null +++ b/vendor/timer/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "timer" + } +} diff --git a/vendor/timer/locale/zh.json b/vendor/timer/locale/zh.json new file mode 100644 index 0000000000..b87792d105 --- /dev/null +++ b/vendor/timer/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "计时服务", + "description": "为其他插件提供延时和周期执行能力。" + } +} diff --git a/vendor/timer/package.json b/vendor/timer/package.json index 5f7ad6ccc9..94b4fe0691 100644 --- a/vendor/timer/package.json +++ b/vendor/timer/package.json @@ -19,13 +19,15 @@ "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", - "src" + "src", + "locale" ], "author": "Shigma ", "license": "MIT",