Merge remote-tracking branch 'origin/master' into turtle/plugin-preview-image-e7b209c5fe5a

# Conflicts:
#	packages/experimental/plugin-market-bundle/docs/DETAIL.md
#	packages/experimental/plugin-market-bundle/docs/DETAIL.zh.md
This commit is contained in:
Turtle committed 2026-10-26 14:56:56 +08:00
commit 093457deb0
748 files changed
+19603 -5664

No files matched your search

@@ -21,8 +21,8 @@
en: 985e0eb63f3d1fd6
zh: 337cc44fadc6227e
/agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/build-pipeline-and-artifacts:
en: 9d885e8d58bc8bbb
zh: 41a9779fbdea8a1a
en: 9a4ba22142a7be24
zh: 8553b02a923641a3
/agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/python-sdk-distribution-two-carriers-exe-for-production-node-for-development:
en: b2a740a1ab7a5002
zh: a48be6ca6fc65912
@@ -48,7 +48,7 @@ The [Office kit](2026-09-14-independent-libreoffice-kit.md) and its installed de
### 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 --compress Brotli` once per target → write `deepseek-harness-sdk-runtime-<platform>-<arch>` 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.
[`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 --compress Brotli` once per target, where the vendored pkg patch pins Brotli's quality to 6: pkg passes no options, so its default quality 11 measured 132.8 s against 3.2 s at quality 6 for an archive 12% larger → write `deepseek-harness-sdk-runtime-<platform>-<arch>` 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<repository-version>` 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.
@@ -48,7 +48,7 @@ exe 的 VFS 内是**构建产物形态的真实包树**(各包的 `lib/` + 真
### 构建流水线与产物
[`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 --compress Brotli` → 将 `deepseek-harness-sdk-runtime-<platform>-<arch>` 写入 `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 不会从注册表解析这些未发布名称。 生产部署允许未使用的工作区补丁,因为开发工具可能不属于运行时闭包;闭包内包的补丁应用失败仍会中止部署。工作区安装继续严格校验未使用的补丁。
[`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 --compress Brotli`,其中 vendor 的 pkg 补丁把 Brotli 质量固定为 6:pkg 不传参数时默认质量 11,同一载荷实测 132.8 s,质量 6 为 3.2 s,产物大 12% → 将 `deepseek-harness-sdk-runtime-<platform>-<arch>` 写入 `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<repository-version>` 标签流水线,构建一个 SDK wheel 包和 5 个原生运行时 wheel 包,再由单个串行任务校验并将这 6 个文件发布到项目的 PyPI 注册表。[`python/sdk-runtime` README](../../../../python/sdk-runtime/README.zh.md)负责 Windows 目标及对 Windows arm64 的明确排除。
@@ -27,14 +27,14 @@
en: d5d0d6a57a4fa581
zh: 265973b157f957d9
/agent-note-session-history-control-state-and-remote-event-transport/decision/session-controller:
en: e338ac27490a380f
zh: 12600011ec742e5b
en: f432480a52414d56
zh: 15a3f175b69cdb53
/agent-note-session-history-control-state-and-remote-event-transport/decision/session-controller/activation-policy:
en: 534dcc62a26d305e
zh: 03d64abc0a46bbec
en: 03e24cdee8519a92
zh: 82dc02eb26d7d7f4
/agent-note-session-history-control-state-and-remote-event-transport/decision/session-controller/session-journal:
en: bb710f8cf35f2028
zh: aae2cfb8cd848069
en: 4de2965717900b96
zh: 1d129003824fa6bd
/agent-note-session-history-control-state-and-remote-event-transport/decision/session-controller/session-live-control:
en: a11d627cd68650c3
zh: 9aff565b9f712853
@@ -139,11 +139,11 @@ If a page request is canceled with its physical carrier generation, the journal
`packages/api/session-controller` provides Host `ctx.sessionController` and the generated `ctx.remote.session` namespace.
It owns Session list, search, create, selectModel, rename, fork, prompt, attachment, updateQueue, cancel, page, follow, and control. The Host-generation model catalog is exposed separately through `session/modelCatalog` because it is not Session-specific.
It owns Session list, search, create, selectModel, rename, fork, prompt, attachment, updateQueue, cancel, `events`, the deprecated `page`, `follow`, `control`, plus `observeEvent`, `projections`, `observeProjections`, `state`, `observeState`, and `wait`. The Host-generation model catalog is exposed separately through `session/modelCatalog` because it is not Session-specific.
The package separates agent, commands, control, history, and list controllers internally, but Session identity resolution, activation policy, subagent ownership, and Remote error projection have one public owner.
Other Host Remote namespaces reuse the same identity rules through `ctx.sessionController.inspect()` or `resolveAgent()`; they do not retain a second Session resolver.
Other Host Remote namespaces reuse the same resume-capable identity rules through `ctx.sessionController.resolveAgent()`; they do not retain a second Session resolver.
#### Activation policy
@@ -157,7 +157,8 @@ Each method explicitly selects a cold inspection, live-only lookup, or resume-ca
| `session.page(address)` | attached Session or persistence log | Never resumes an Agent |
| `session.follow(address)` | one live or prepared observation carrying the opening page and projections | Publishes the snapshot first, then promotes an ordinary cold Session once in the background |
| `session.control()` | current attached Agents, pending registry, and process-local registries | Baseline and reconnect do not resume an Agent |
| `session.attachment`, fork source read | authorized durable Session data | A read does not resume an Agent |
| Fork source read | authorized durable Session data | A read does not resume an Agent |
| `session.attachment` | attachment store under the [image access rule](2026-10-23-store-scoped-image-reads.md) | A read does not resume an Agent |
| `session.updateQueue` | live Agent or ordinary persisted Session | Resumes an ordinary cold Session before mutating its Inbox |
| `session.cancel` | only the current live Agent | Does not resume vanished state |
| `models`, `selectModel`, `rename`, `prompt` | command resolves the target Session | Resumes only when the method explicitly permits it |
@@ -173,9 +174,9 @@ Reading titles, lists, and projections does not require an Agent. An observation
#### Session journal
`session.page` returns a history window clipped on message boundaries with contiguous internal sequence numbers. Every request must carry an explicit `throughSeq`; this value comes from the corresponding `session.follow` generation's opening cursor and fixes the read at the same log cut. A tail page without `beforeSeq` must end exactly at `throughSeq`, where `-1` denotes an empty log. `beforeSeq` only selects an older page before that cut and cannot replace the synchronization cursor. `maxMessages` limits user/assistant message count without dropping chunks, tools, or state events between those messages.
`session.events` returns a history window clipped on message boundaries with contiguous internal sequence numbers. `throughSeq` is optional: when omitted, the read selects the observed log end and returns it as the page's inclusive `cursor`; a supplied value fixes the read at that cut. A page without `beforeSeq` ends exactly at the selected cut, where `-1` denotes an empty log. `beforeSeq` only selects an older page before that cut and cannot replace the synchronization cursor. `maxMessages` limits user/assistant message count without dropping chunks, tools, or state events between those messages. The deprecated `session.page` entry returns the same type.
The tail page also carries a projection baseline no later than `throughSeq`; older pages carry only historical entries. The Client merges pages and subsequent live control updates by projection watermark.
A page carries only its records, `hasMore`, and inclusive `cursor`; a projection baseline comes from a follow opening snapshot or the control stream, never from a page. The Client merges pages and subsequent live control updates by projection watermark.
Ordinary Sessions and direct subagents use one `SessionAddress` protocol. A direct-subagent address carries parent Session, child Session, and mode; a cold Host read verifies durable ownership and descriptor rather than authorizing access from the child id alone.
@@ -139,11 +139,11 @@ repair 期间旧 window 保持可读;page 与期间积累的 live entries 拼
`packages/api/session-controller` 提供 Host `ctx.sessionController` 与生成的 `ctx.remote.session` namespace。
它拥有 Session list、search、create、selectModel、rename、fork、prompt、attachment、updateQueue、cancel、page、follow 与 control。Host generation 的 model catalog 通过独立的 `session/modelCatalog` 公开,因为它不属于特定 Session。
它拥有 Session list、search、create、selectModel、rename、fork、prompt、attachment、updateQueue、cancel、`events`、已弃用的 `page`、`follow`、`control`,以及 `observeEvent`、`projections`、`observeProjections`、`state`、`observeState` 与 `wait`。Host generation 的 model catalog 通过独立的 `session/modelCatalog` 公开,因为它不属于特定 Session。
包内的 agent、commands、control、history 与 list controller 分开实现,但 Session 身份解析、激活策略、subagent ownership 和 Remote 错误投影只有一个公开 owner。
其他 Host Remote namespace 通过 `ctx.sessionController.inspect()` 或 `resolveAgent()` 复用同一身份规则,不保留第二份 Session resolver。
其他 Host Remote namespace 通过 `ctx.sessionController.resolveAgent()` 复用同一套允许恢复 Session 的身份规则,不保留第二份 Session resolver。
#### 激活策略
@@ -157,7 +157,8 @@ Session Remote 方法传递 `SessionId` 或 `SessionAddress`,不靠参数类
| `session.page(address)` | attached Session 或 persistence 日志 | 永不恢复 Agent |
| `session.follow(address)` | 一份携带 opening page 与 projection 的 live 或 prepared observation | 先发布 snapshot,再在后台把普通冷 Session 提升一次 |
| `session.control()` | 当前 attached Agent、pending registry 与进程内 registry | baseline 与重连不恢复 Agent |
| `session.attachment`、fork 源读取 | 已授权的持久 Session 数据 | 读取不恢复 Agent |
| Fork 源读取 | 已授权的持久 Session 数据 | 读取不恢复 Agent |
| `session.attachment` | 按[图片访问规则](2026-10-23-store-scoped-image-reads.zh.md)读取附件存储 | 读取不恢复 Agent |
| `session.updateQueue` | live Agent 或普通持久 Session | 修改 Inbox 前恢复普通冷 Session |
| `session.cancel` | 仅命中当前 live Agent | 不为已消失状态恢复 Agent |
| `models`、`selectModel`、`rename`、`prompt` | 命令解析目标 Session | 仅按方法约定显式恢复 |
@@ -173,9 +174,9 @@ Session Remote 方法传递 `SessionId` 或 `SessionAddress`,不靠参数类
#### Session 日志
`session.page` 返回一段按消息边界裁剪、内部 seq 连续的历史窗口。每个请求必须显式携带 `throughSeq`;该值来自对应 `session.follow` generation 的 opening cursor,并把本次读取固定在同一个日志切点。无 `beforeSeq` 的 tail page 必须精确结束于 `throughSeq`,其中 `-1` 表示空日志;`beforeSeq` 只选择该切点之前的更早页面,不能替代同步 cursor。`maxMessages` 限制 user/assistant 消息数,不丢弃这些消息之间的 chunk、tool 或状态事件。
`session.events` 返回一段按消息边界裁剪、内部 seq 连续的历史窗口。`throughSeq` 可省略:省略时选取观察到的日志末尾,并把该切点作为页面的 inclusive `cursor` 返回;显式提供时把本次读取固定在该切点。无 `beforeSeq` 的 page 精确结束于所选切点,其中 `-1` 表示空日志;`beforeSeq` 只选择该切点之前的更早页面,不能替代同步 cursor。`maxMessages` 限制 user/assistant 消息数,不丢弃这些消息之间的 chunk、tool 或状态事件。已弃用的 `session.page` 入口返回同一类型。
tail page 同时携带不晚于 `throughSeq` 的 projection baseline;旧页只携带历史 entries。Client 以 projection watermark 合并 page 与后续 live control 更新。
page 只携带记录、`hasMore` 和 inclusive `cursor`;projection baseline 来自 follow 的开场快照或 control 流,不来自 page。Client 以 projection watermark 合并 page 与后续 live control 更新。
普通 Session 与 direct subagent 使用同一个 `SessionAddress` 协议。direct subagent 地址同时携带父 Session、子 Session 与 mode,Host 冷读时验证持久 ownership 和 descriptor,不能只凭 child id 越权读取。
@@ -51,8 +51,8 @@
en: 51f99cfca9c4c808
zh: ce95bab241d306f7
/agent-note-client-derived-presentation-from-raw-session-tool-events/host-design:
en: 16fd2b3e545ede21
zh: 4d28f52132495441
en: d5e5d1376dc42558
zh: c2f302b2a5d1de39
/agent-note-client-derived-presentation-from-raw-session-tool-events/host-design/performance-constraints:
en: 102b14e3eb9367ff
zh: d391099dbc41db24
@@ -195,9 +195,9 @@ The Client narrows `meta` locally at runtime. Renaming `presentationMeta` to mor
## Host Design
After obtaining source events, `SessionHistoryController.page()` performs only pagination and the existing projection-baseline calculation. Attached Sessions use the projection registry snapshot; detached Sessions use its restore path over the inspected log. History does not mount a preset to change the registered projection set.
After obtaining source events, `HistoryController.history()` performs only pagination and requests projections only for a subagent address that needs descriptor validation. Attached Sessions use the projection registry snapshot; detached Sessions use its restore path over the inspected log. History does not mount a preset to change the registered projection set.
`SessionHistoryController.follow()` retains listener-first setup, opening cursors, gap-free replay, live buffering, cancellation, and teardown. It maintains no additional state for tool events.
`WebController.follow()` retains listener-first setup, opening cursors, gap-free replay, live buffering, cancellation, and teardown. It maintains no additional state for tool events.
The controller has no `presenterScopeFor()`, `viewFor()`, `backscanArgs()`, `parseToolCall()`, or `jsonView()` path. Page state contains no presenter scope or argument resolver; follow state contains no `openCalls`, `fallbackEvents`, or presentation argument resolver. Each page/follow event is wrapped only as `{event}` while addressing, ownership, cursor, sequence, and projection logic remains intact.
@@ -195,9 +195,9 @@ Client 对 `meta` 做局部运行时收窄。是否把 `presentationMeta` 改名
## Host 端设计
`SessionHistoryController.page()` 在取得 source events 后只执行分页与现有 projection baseline 计算。attached Session 使用 projection registry snapshot;detached Session 使用该 registry 对 inspected log 的 restore 路径。history 不通过挂载 preset 改变已注册的 projection 集合。
`HistoryController.history()` 在取得 source events 后只执行分页,并且只有需要校验 descriptor 的 subagent 地址才请求投影。attached Session 使用 projection registry snapshot;detached Session 使用该 registry 对 inspected log 的 restore 路径。history 不通过挂载 preset 改变已注册的 projection 集合。
`SessionHistoryController.follow()` 保留 listener-first、opening cursor、gap-free replay、live buffering、取消和 teardown;它不为工具事件维护额外状态。
`WebController.follow()` 保留 listener-first、opening cursor、gap-free replay、live buffering、取消和 teardown;它不为工具事件维护额外状态。
Controller 不存在 `presenterScopeFor()`、`viewFor()`、`backscanArgs()`、`parseToolCall()` 或 `jsonView()` 路径。page state 不含 presenter scope 或参数 resolver;follow state 不含 `openCalls`、`fallbackEvents` 或 presentation 参数 resolver。每个 page/follow event 只包装成 `{event}`,地址、ownership、cursor、seq 与 projection 逻辑保持完整。
@@ -15,17 +15,17 @@
en: 480284ae1a6ce210
zh: d42c72ada9f019f8
/agent-note-session-observations-and-projection-owned-client-state/decision/observation-is-the-point-read-unit:
en: fac92f8547482a49
zh: 60240c47fbe4611f
en: 283136ae36512767
zh: e342b446c77ae300
/agent-note-session-observations-and-projection-owned-client-state/decision/source-resolution-and-lifetime:
en: e550ae9892474276
zh: fb6a2d9e91ebd4d9
en: bced4b90cb03525d
zh: b0c1ca4bf1064f89
/agent-note-session-observations-and-projection-owned-client-state/decision/projection-execution-boundary:
en: 148de86941b90f41
zh: c065a8e96e28b9d7
en: b3b235fa0250868a
zh: 0bb5eedf14cdafee
/agent-note-session-observations-and-projection-owned-client-state/decision/read-audiences:
en: 888f62659f4d868d
zh: e74491e8c85046ee
en: e394e9480340f69c
zh: 7eea994ee9fa380d
/agent-note-session-observations-and-projection-owned-client-state/decision/replayable-client-facts-are-projection-owned:
en: efded09f0cd30a8e
zh: 5e16580a39ff3359
@@ -48,11 +48,11 @@
en: 8d699dfc22ab5c5f
zh: 8dcd9fc6bd1594db
/agent-note-session-observations-and-projection-owned-client-state/verification:
en: df17217023668428
zh: 88f7da4deffc6bf9
en: 29f364d1031b7d85
zh: 2b193ceb52fb0406
/agent-note-session-observations-and-projection-owned-client-state/alternatives-considered:
en: a25138b4298cda16
zh: 92799a9bd8867d47
en: 90574351058d5d8c
zh: 6aa514cf47495ed2
/agent-note-session-observations-and-projection-owned-client-state/consequences:
en: e1f8bd8fa68de603
zh: 5afcd06f2611bc1e
@@ -24,7 +24,7 @@ The two ownership rules meet at the observation's projection snapshot. Lightweig
flowchart LR
List["list / search"] --> Corpus["SessionQuery corpus"]
Follow["follow"] --> Observe["observeSession"]
Page["page / attachment / fork"] --> Observe
Page["page / fork"] --> Observe
Subagent["subagent list / continuation"] --> Observe
Corpus --> Cache["projection cache hints"]
Cache --> ClientList["Client Session list"]
@@ -46,7 +46,7 @@ flowchart LR
`SessionQueryEngine.observeSession(sessionId, options)` returns a disposable `SessionObservation` containing one source kind, header, contiguous event prefix, cursor, optional projection snapshot, and the durable revision for a prepared source. An attached Session wins. Otherwise the reader's own prepared cache — keyed by `stat().revision` and pinned by observation leases — serves the cold Session, sharing one persistence read (`open(id, 'read')` + `read`) across concurrent observations, including an in-flight cold load.
Every owner disposes its observation. `retain()` creates another lease over the same cut, which lets `session.follow` publish a snapshot and then transfer that exact prepared source to background Agent promotion without rereading the log. A live Session that appears during cold resolution wins before publication; a disappeared live source is retried as cold.
Every owner disposes its observation. `retain()` creates another lease over the same cut, which lets `session.follow` transfer that exact prepared source to background Agent promotion before delivering the snapshot, without rereading the log. A live Session that appears during cold resolution wins before publication; a disappeared live source is retried as cold.
### Source resolution and lifetime
@@ -56,7 +56,7 @@ Live preference is checked both before and after a cold borrow. The second check
Persistence absence maps to Session-not-found only after no attached Session exists. Durable corruption, source-identity conflict, cancellation, and operational persistence failure remain distinct `SessionQueryError` outcomes so API owners can preserve their own public error vocabulary without duplicating source detection.
The observation owns no mutation authority. Its event array is an immutable prefix, and its prepared Session remains unpublished. Promotion is an explicit ownership transfer performed by the Session Controller after it has emitted the opening snapshot; other readers cannot turn an observation into a live Agent.
The observation owns no mutation authority. Its event array is an immutable prefix, and its prepared Session remains unpublished. Promotion is an explicit ownership transfer the Session Controller starts once the opening is computed, before delivering it; other readers cannot turn an observation into a live Agent.
Projection work is deliberately `all | none`. `all` computes every registered projection at the observation's event cursor; `none` leaves projection state untouched. There is no per-key preparation state, `projectionKeys` mode, or cached `viewedState`/`viewedValue` layer. A publisher may filter the completed values for an audience, but the underlying observation is never partly projected.
@@ -72,7 +72,7 @@ The registry owns fold state; each domain owns its `init`, `apply`, `view`, sche
Corpus listing remains a separate lightweight operation. `listSessions()` returns live-preferred headers without materializing every log. Session list first uses live projection state or durable projection-cache rows. Subagent discovery reads parent-catalog projections through exact observations. Session list may take one complete observation for an individually stored artifact within its configured small-log limit when cached metadata cannot establish whether it is blank; a large or unreadable cache miss remains visible with unknown hints.
`session.follow` publishes a required opening snapshot containing header, cursor, the initial event window, and a complete projection baseline. Reconnect replaces the previous generation from another complete snapshot. `session.page` is reserved for older-history reads and gap repair. Observation-only reads never activate an Agent; only an ordinary follow may retain its prepared observation and request promotion after the opening snapshot has been delivered.
`session.follow` publishes a required opening snapshot containing header, cursor, the initial event window, and a complete projection baseline. Reconnect replaces the previous generation from another complete snapshot. `session.page` supports current or fixed-cut history reads, older-history reads, and gap repair. Observation-only reads never activate an Agent; only an activation-enabled ordinary Follow may retain its prepared observation and request promotion once the opening snapshot is computed, before it is delivered. The [snapshot and subscription decision](2026-10-21-session-history-stream-and-snapshot.md) defines the Controller composition and passive subscription semantics.
### Read audiences
@@ -82,9 +82,10 @@ Each public operation chooses one query and projection policy. The choice is par
|---|---|---|---|
| `session.list` | Corpus headers, live state, and cached rows; bounded small-log fallback | Partial hints, or one full small-log observation | Never |
| `session.search` | Corpus authorization plus the configured search provider | None for result listing | Never |
| `session.follow` | One exact observation | All, carried in the opening snapshot | Ordinary cold Session only, after snapshot delivery |
| `session.follow` | One exact observation | All, carried in the opening snapshot | Only with `activate: true`, for an ordinary cold Session once the opening is computed, before delivery |
| `session.page` | One exact observation | None, except projection-backed subagent authorization | Never |
| Attachment and fork source | One exact observation | None unless authorization requires it | Never for the source |
| Fork source | One exact observation | None unless authorization requires it | Never for the source |
| Attachment | Direct store read under the [image access rule](2026-10-23-store-scoped-image-reads.md) | None | Never |
| Subagent list and continuation | Parent-catalog observations for listing; target observations for continuation | All; listing consumes catalog values, continuation consumes identity and inherited values | Never for listing; continuation follows its explicit command semantics |
### Replayable Client facts are projection-owned
@@ -171,7 +172,7 @@ These rules apply to new Session-derived Client state even when a direct event s
## Verification
Persistence and SessionQuery tests pin shared cold loading, cancellation, live-source races, retained observations, disposal, and all-or-none projection calculation. Session Controller and Gateway tests pin snapshot-first opening, replacement reconnect, older-page reads, gap repair, list-cache hints, bounded small-log fallback, and promotion after snapshot delivery.
Persistence and SessionQuery tests pin shared cold loading, cancellation, live-source races, retained observations, disposal, and all-or-none projection calculation. Session Controller and Gateway tests pin snapshot-first opening, replacement reconnect, older-page reads, gap repair, list-cache hints, bounded small-log fallback, and promotion once the opening is computed.
Client tests pin higher-sequence-wins projection storage, title updates, model catalog and selection readiness, preset roster refresh and Session-specific selection, and subagent loading without transient offline presentation. Subagent tests pin parent-catalog order, recursive traversal, branch diagnostics, cancellation, fork isolation, and no Agent activation during listing.
@@ -179,7 +180,7 @@ Client tests pin higher-sequence-wins projection storage, title updates, model c
**Keep source resolution in each consumer.** Rejected because every caller would continue to implement its own live race, persistence error mapping, preparation lifetime, cancellation, and projection cut, allowing both duplicate work and inconsistent results.
**Activate an Agent for every exact read.** Rejected because list, history, attachment, search, and subagent inspection are read operations. Activation loads plugins and changes process state, and it has no natural retirement point for pagination or catalog reads.
**Activate an Agent for every exact read.** Rejected because list, history, search, and subagent inspection are read operations. Activation loads plugins and changes process state, and it has no natural retirement point for pagination or catalog reads.
**Prepare only requested projection keys.** Rejected because a partially projected Session creates another lifecycle state that every cache, restore, plugin-registration, and caller path must track. Projection units are pure and few; computing all registered units for an exact observation is simpler than maintaining `O(E*k)` partial state instead of `O(E*P)` complete state.
@@ -24,7 +24,7 @@ Session 精确读取使用可保留的 `SessionObservation`,向 Client 暴露
flowchart LR
List["list / search"] --> Corpus["SessionQuery corpus"]
Follow["follow"] --> Observe["observeSession"]
Page["page / attachment / fork"] --> Observe
Page["page / fork"] --> Observe
Subagent["subagent list / continuation"] --> Observe
Corpus --> Cache["projection cache hints"]
Cache --> ClientList["Client Session list"]
@@ -46,7 +46,7 @@ flowchart LR
`SessionQueryEngine.observeSession(sessionId, options)` 返回可 dispose(资源释放)的 `SessionObservation`,其中包含同一份 source kind、header、连续事件前缀、cursor、可选 projection snapshot,以及 prepared source 的持久化 revision。已挂载 Session 优先;否则由读取方自己的 prepared cache——以 `stat().revision` 为键、由 observation lease 固定——提供冷 Session,让并发 observation 共享同一次持久化读取(`open(id, 'read')` + `read`),包括尚未完成的冷加载。
每个 owner 都会 dispose 自己的 observation。`retain()` 为同一切面创建另一份 lease,使 `session.follow` 能够先发布 snapshot,再把完全相同的 prepared source 转交给后台 Agent promotion,而无需重读日志。冷解析期间出现的 live Session 会在发布前胜出;已经消失的 live source 会按 cold source 重试。
每个 owner 都会 dispose 自己的 observation。`retain()` 为同一切面创建另一份 lease,使 `session.follow` 能把完全相同的 prepared source 转交给后台 Agent promotion,并在交付 snapshot 前启动它,而无需重读日志。冷解析期间出现的 live Session 会在发布前胜出;已经消失的 live source 会按 cold source 重试。
### 数据源解析与生命周期
@@ -56,7 +56,7 @@ flowchart LR
只有在不存在已挂载 Session 后,persistence absence 才映射为 Session-not-found。持久数据损坏、source identity 冲突、取消和 persistence 操作失败分别保留不同的 `SessionQueryError`,API owner 因而可以维持自身公开错误词汇,而不用重复数据源判定。
Observation 不拥有任何 mutation 权限。其事件数组是不可变前缀,prepared Session 保持未发布。Promotion 是 Session Controller 在 opening snapshot 发出后执行的显式 ownership transfer;其他读方不能把 observation 变成 live Agent。
Observation 不拥有任何 mutation 权限。其事件数组是不可变前缀,prepared Session 保持未发布。Promotion 是 Session Controller 在 opening 计算完成后、交付前启动的显式 ownership transfer;其他读方不能把 observation 变成 live Agent。
Projection 工作明确只有 `all | none` 两种模式。`all` 在 observation 的事件 cursor 上计算所有已注册 projection;`none` 完全不触碰 projection 状态。系统不存在按 key preparation 的状态、`projectionKeys` 模式或额外的 `viewedState`/`viewedValue` cache。发布方可以按 audience 筛选已完成的值,但底层 observation 不会处于只算完部分 projection 的状态。
@@ -72,7 +72,7 @@ Registry 拥有 fold state;各领域拥有自己的 `init`、`apply`、`view`
语料库 list 仍是独立的轻量操作。`listSessions()` 返回 live-preferred header,而不物化每份日志。Session list 先读取 live projection 状态或持久 projection-cache row。Subagent 发现通过精确 observation 读取父目录 projection。当 cache 无法判断 Session 是否为空,且该 Session 拥有的独立产物未超过配置的小日志限制时,Session list 可以执行一次完整 observation;大型或不可读的 cache miss 仍以 hints 未知但 row 可见的方式返回。
`session.follow` 发布必需的 opening snapshot,其中包含 header、cursor、首个事件窗口和完整 projection baseline。重连使用另一份完整 snapshot 替换上一 generation。`session.page` 仅用于旧历史读取与 gap repair。只读 observation 不激活 Agent;只有普通 follow 可以保留 prepared observation,并在 opening snapshot 已交付后请求 promotion。
`session.follow` 发布必需的 opening snapshot,包含 header、cursor、初始事件窗口与完整 projection baseline。重连通过另一份完整快照替换之前的 generation。`session.page` 支持当前或固定切点的历史读取、旧历史分页及缺口修复。只读 Observation 不激活 Agent;只有显式启用激活的普通 Follow 可以在开场计算完成后、交付之前 retain prepared observation 并请求提升。[快照与订阅决策](2026-10-21-session-history-stream-and-snapshot.zh.md)定义 Controller 组合和纯订阅语义。
### 读取 audience
@@ -82,9 +82,10 @@ Registry 拥有 fold state;各领域拥有自己的 `init`、`apply`、`view`
|---|---|---|---|
| `session.list` | Corpus header、live state 和 cached row;有界小日志 fallback | 部分 hints,或一次完整小日志 observation | 从不 |
| `session.search` | Corpus 鉴权加已配置 search provider | 结果列表不计算 | 从不 |
| `session.follow` | 一份精确 observation | 全算,并由 opening snapshot 携带 | 仅普通 cold Session,且在 snapshot 交付后 |
| `session.follow` | 一份精确 observation | 全算,并由 opening snapshot 携带 | 仅 `activate: true` 的普通 cold Session,且在开场计算完成后、交付前 |
| `session.page` | 一份精确 observation | 不计算,但 projection-backed subagent 鉴权除外 | 从不 |
| Attachment 与 fork source | 一份精确 observation | 鉴权不要求时不计算 | source 从不激活 |
| Fork source | 一份精确 observation | 鉴权不要求时不计算 | source 从不激活 |
| Attachment | 按[图片访问规则](2026-10-23-store-scoped-image-reads.zh.md)直接读取存储 | 不计算 | 从不 |
| Subagent list 与 continuation | Listing 观察父目录;continuation 观察目标 | 全算;listing 消费目录值,continuation 消费身份与继承值 | Listing 从不;continuation 遵循显式命令语义 |
### 可回放的 Client 事实归 projection 所有
@@ -171,7 +172,7 @@ Client 本地交互状态也继续留在本地:loading 和 error 状态、打
## 验证
Persistence 与 SessionQuery 测试固定共享冷加载、取消、live-source race、retained observation、dispose 和 all-or-none projection 计算。Session Controller 与 Gateway 测试固定 snapshot-first opening、replacement reconnect、旧分页读取、gap repair、list-cache hints、小日志有界 fallback,以及 snapshot 交付后的 promotion。
Persistence 与 SessionQuery 测试固定共享冷加载、取消、live-source race、retained observation、dispose 和 all-or-none projection 计算。Session Controller 与 Gateway 测试固定 snapshot-first opening、replacement reconnect、旧分页读取、gap repair、list-cache hints、小日志有界 fallback,以及开场计算完成后的 promotion。
Client 测试固定 higher-sequence-wins projection store、title 更新、model catalog 与 selection readiness、preset roster refresh 与 Session 专属选择,以及不会短暂展示离线状态的 subagent loading。Subagent 测试固定父目录顺序、递归遍历、分支诊断、取消、fork 隔离,以及 listing 期间不激活 Agent。
@@ -179,7 +180,7 @@ Client 测试固定 higher-sequence-wins projection store、title 更新、model
**由各消费方继续解析数据源。** 否决,因为每个调用方都需要重复实现 live race、persistence error mapping、preparation lifetime、cancellation 和 projection cut,既会重复工作,也会产生不一致结果。
**每次精确读取都激活 Agent。** 否决,因为 list、history、attachment、search 与 subagent inspection 都是读取操作。Activation 会加载插件并改变进程状态,也没有适合分页或 catalog 读取的自然退出点。
**每次精确读取都激活 Agent。** 否决,因为 list、history、search 与 subagent inspection 都是读取操作。Activation 会加载插件并改变进程状态,也没有适合分页或 catalog 读取的自然退出点。
**只 prepare 被请求的 projection key。** 否决,因为只完成部分 projection 的 Session 会增加一种生命周期状态,所有 cache、restore、plugin registration 和调用路径都必须追踪它。Projection unit 数量少且为纯函数;精确 observation 计算全部已注册 unit,比为了 `O(E*k)` 而维护部分状态、取代 `O(E*P)` 完整状态更简单。
@@ -30,8 +30,8 @@
en: 9d2d50cb76754b74
zh: 9ceed3652475f18d
/agent-note-historical-session-reads-prepare-before-write-publication/decision/follow-and-agent-promotion:
en: 692c29db3e7ab07e
zh: 7da0cfdbc80f407d
en: 46da45b9b63e7298
zh: 3d55099479a80bd9
/agent-note-historical-session-reads-prepare-before-write-publication/problem-to-solution-mapping:
en: e067e187cd4d0a8c
zh: b0c79b635a637296
@@ -102,7 +102,7 @@ No external caller can append before the handle exists. `append`, `flush`, and `
### Follow and Agent promotion
`session.follow` opens history through the read path, restores the Session and projections, emits the opening snapshot, and then starts Agent promotion. Agent resume uses write open, so it waits for publication before the Agent accepts a new turn. History visibility and write readiness are separate timing points without introducing an unpublished append state.
`session.follow` opens history through the read path, restores the Session and projections, starts Agent promotion from the separately retained Observation when the caller requests activation, and then delivers the opening snapshot. Agent resume uses write open, so it waits for publication before the Agent accepts a new turn. History visibility and write readiness are separate timing points without introducing an unpublished append state.
## Problem-to-solution mapping
@@ -102,7 +102,7 @@ Handle 返回前,外部 caller 无法 append。因此 `append`、`flush` 与 `
### Follow 与 Agent promotion
`session.follow` 通过 read path 打开历史、恢复 Session 与 projections、发出 opening snapshot,然后启动 Agent promotion。Agent resume 使用 write open,因此会在 Agent 接收新一轮对话前等待 publication。历史可见与写入就绪成为两个明确时间点,同时不引入 unpublished append state。
`session.follow` 通过 read path 打开历史、恢复 Session 与 projections,在调用方请求激活时先用单独 retain 的 Observation 启动 Agent promotion,再交付 opening snapshot。Agent resume 使用 write open,因此会在 Agent 接收新一轮对话前等待 publication。历史可见与写入就绪成为两个明确时间点,同时不引入 unpublished append state。
## 问题与方案对照
@@ -39,8 +39,8 @@
en: ef015f605f7b00ab
zh: eee9c79faebf3dff
/agent-note-workspace-file-service/alternatives-considered:
en: 8eee658526db4465
zh: 4a655accf6a5c08a
en: c750d88e0e746a99
zh: 9e904ad4172fda49
/agent-note-workspace-file-service/consequences:
en: 246bb7aed62f6c9b
zh: debf6d4129ee477b
@@ -117,7 +117,7 @@ The [resource model](2026-09-05-client-resource-model.md) owns `ctx.resources`,
**Serving navigable workspace documents.** Rejected on origin grounds; the [binary transfer](2026-09-17-workspace-file-binary-transfer.md) returns multipart data while HTML remains isolated in a Blob iframe.
**Log-reachable or workspace-contained authorization for file reads.** The one precedent that sends file content over the wire, command attachments, authorizes only files that appear in the session log. That excludes typed paths, while workspace containment excludes readable files elsewhere on the Session backend. The [workspace file read authority](2026-09-09-workspace-file-read-authority.md) instead makes the backend's read decision authoritative and keeps containment only for workspace-shaped operations.
**Log-reachable or workspace-contained authorization for file reads.** Requiring a Session-log reference excludes typed paths, while workspace containment excludes readable files elsewhere on the Session backend. The [workspace file read authority](2026-09-09-workspace-file-read-authority.md) makes the backend's read decision authoritative and keeps containment only for workspace-shaped operations. Image attachment reads separately follow the [store-level access rule](2026-10-23-store-scoped-image-reads.md).
**Whole-file read and slice for the byte window.** The interim form of `readBytes` read the file from its start to the window's end through `readBytes(target, signal, offset + length)` and sliced. It cannot read a window of a file longer than that end — the seam refuses such a file as too large — so no window could ever report `eof: false`, which contradicts the reason the method exists. Rejected in favour of the `readByteRange` seam, whose bound is the window.
@@ -117,7 +117,7 @@ Client 导出向 `ctx.resources` 注册一个 `ResourceProvider<'file'>`,存
**提供可导航的工作区文档。** 因源隔离问题不采用;[二进制传输](2026-09-17-workspace-file-binary-transfer.zh.md)返回 multipart 数据,HTML 仍隔离在 Blob iframe 中。
**文件读取采用“日志可达”或工作区包含授权。** 唯一把文件内容送过线路的先例——命令附件——只授权出现在会话日志里的文件,这会排除手输路径;工作区包含则会排除 Session 后端其他位置的可读文件。[工作区文件读取权限](2026-09-09-workspace-file-read-authority.zh.md)改为以后端读取决策为准,只对工作区形态的操作保留包含限制。
**文件读取采用“日志可达”或工作区包含授权。** 要求 Session 日志引用会排除手输路径;工作区包含则会排除 Session 后端其他位置的可读文件。[工作区文件读取权限](2026-09-09-workspace-file-read-authority.zh.md)以后端读取决策为准,只对工作区形态的操作保留包含限制。图片附件读取另行遵循[存储范围的访问规则](2026-10-23-store-scoped-image-reads.zh.md)。
**为字节窗口整文件读取再切片。** `readBytes` 的临时形态经 `readBytes(target, signal, offset + length)` 从文件开头读到窗口末端再切片。它读不了比该末端更长的文件的窗口——seam 会以过大拒绝这样的文件——因此没有任何窗口能报告 `eof: false`,与该方法存在的理由相悖。被否,改为以窗口为界的 `readByteRange` seam。
@@ -15,8 +15,8 @@
en: eced414858f08ef9
zh: 40639593b0d5bb6f
/agent-note-fatal-diagnostics-and-desktop-crash-reports/relationship-to-the-desktop-logging-design:
en: 7dc438912d10574a
zh: 07d05f9f17043d67
en: ca4a912437c7b02e
zh: 2c7953ce5e8c196f
/agent-note-fatal-diagnostics-and-desktop-crash-reports/testing:
en: 864a8e71e3b3378b
zh: a71807db24d9409c
@@ -32,7 +32,7 @@ This partially supersedes the [native Desktop fatal recovery](2026-09-15-desktop
## Relationship to the Desktop logging design
The Desktop local logging design (a Worker-owned rolling JSONL log with a closed event vocabulary, redaction, and rate limits) is a continuous-log design and remains future work. It stated that Host stderr and renderer console output are never persisted and that errors reach the log only as fixed categories. This decision carves out one exception: the one-time crash report of a fatal failure keeps the raw error and the retained stderr and console tails, because that raw content is what both field diagnoses needed and the report is bounded (the error section is cut at 256 KiB, the Host diagnostic at 64 KiB, the renderer console tail at 64 KiB), local, owner-only, and written only when the application is already showing its fatal dialog. The dialog names the file so a user knows what they would be sharing. The continuous-log privacy posture is unchanged for anything that is not a crash report.
Desktop continuously persists a bounded plugin-management journal with whitelisted facts, two rotating segments and a bounded write queue; its budgets and failure guarantees belong to the [Desktop README](../../../../apps/desktop/README.md). It excludes raw installation specs, error text and package-manager output. The broader Worker-owned continuous log remains deferred. Fatal crash reports independently retain raw errors and bounded stderr and renderer-console tails because these contain the field-diagnosis evidence; files are local and owner-only where supported. An isolated Worker appends bounded management history after the basic report is saved, preserving access to the basic report when collection fails or is still running. Recent operations provide context, not causal attribution.
## Testing
@@ -32,7 +32,7 @@ macOS 上,启动审计把一组 Web 客户端行列为 `import failed (see con
## 与 Desktop 日志体系设计的关系
Desktop 本地日志设计(Worker 独占写入的滚动 JSONL 日志、封闭事件词汇、脱敏与限流)是持续日志设计,仍是未来工作。它规定 Host stderr 与渲染进程 console 输出永不持久化、错误只以固定分类进入日志。本决定划出一个例外:致命失败的一次性崩溃报告保留原始错误以及保留的 stderr 与 console 尾部,因为两次现场定位需要的正是这些原始内容,而报告有界(error 段截至 256 KiB、Host 诊断 64 KiB、渲染进程 console 尾部 64 KiB)、本地、仅所有者可读,且只在应用已经弹出致命对话框时写入。对话框标明文件名,用户知道自己会分享什么。任何非崩溃报告的内容仍遵循持续日志的隐私姿态。
Desktop 持续保存有界的插件管理日志,使用事实白名单、两个轮换文件段和有界写入队列;预算及失败保障由 [Desktop README](../../../../apps/desktop/README.zh.md) 定义。日志不包含原始安装 spec、错误文本或包管理器输出。更广泛的 Worker 独占持续日志仍属延期工作。致命崩溃报告独立保留原始错误以及有界的 stderr 和渲染进程 console 尾部,因为这些内容包含现场定位证据;文件保存在本地,并在平台支持时仅所有者可读。独立 Worker 在基本报告保存后追加有界管理历史,收集失败或尚未结束时仍可获取基本报告。近期操作提供上下文,不构成因果归因。
## Testing
@@ -9,11 +9,11 @@
en: e42db40b879fdbf4
zh: 6017da9c4da17835
/agent-note-node-ptc-execution-modes-and-in-memory-state/decision:
en: d2d08c54c6520f02
zh: 520a9b3421ff5c65
en: 7b5808a31493ac1e
zh: 8d9c698c41dbf18e
/agent-note-node-ptc-execution-modes-and-in-memory-state/alternatives-considered:
en: 396157a9fc293198
zh: a061f05b4423e26f
/agent-note-node-ptc-execution-modes-and-in-memory-state/consequences:
en: 9b9172f4aafe907f
zh: 022a6bd52d7caf05
en: 56fa39e2958afdff
zh: d04f539437d0c00d
@@ -12,7 +12,7 @@ Interactive automation retains application objects, imported modules and helper
The existing `@deepseek-ai/dsh-ptc-runtime-node` plugin selects its execution mode through `executionMode`. The default `per-call` mode starts a fresh process under the configured file policy. Opt-in `persistent-in-memory` mode keeps a Node REPL process per explicit, object-identity state owner. Both modes provide the same `ctx.ptcRuntime` service. PTC uses the live Agent as owner and awaits release during its context disposal. Changing the configuration reloads the provider and releases its processes. The [sandboxed Node decision](2026-09-11-sandboxed-node-ptc-runtime.md) owns per-call confinement; the [PTC foundation](../feature/2026-06-15-ptc.md) owns tool dispatch and logged model requests.
Mode names describe state retention rather than a process implementation or source syntax. `per-call` retains state for one invocation; `persistent-in-memory` retains it across invocations until the process or owner ends. `durable` names the deferred ability to save and restore execution state across restarts. It is not an accepted configuration value: a future implementation must define its recovery point, recoverable values and external-resource handling before exposing that mode. The [retained-process permission decision](2026-10-08-persistent-ptc-sandbox.md) owns confinement, policy changes and temporary escalation.
The `per-call` and `persistent-in-memory` names describe their fixed state-retention policies: one invocation or across invocations until the process or owner ends. The [Script evaluation decision](2026-10-20-ptc-script-evaluation-and-retention.md) extends these modes with independently configured syntax and retention. `durable` names the deferred ability to save and restore execution state across restarts. It is not an accepted configuration value: a future implementation must define its recovery point, recoverable values and external-resource handling before exposing that mode. The [retained-process permission decision](2026-10-08-persistent-ptc-sandbox.md) owns confinement, policy changes and temporary escalation.
One npm package and one plugin entry keep existing installation and loading paths stable. Communication, binding proxies, JSON encoding and output limits remain package-local modules. The Node provider delegates retained process ownership to an internal execution object, which registers no additional Cordis service. Per-call and in-memory execution keep their distinct lifecycle rules. `programFormat` describes source evaluation independently of retention: a REPL need not retain state. The runtime owns syntax, completion and retention instructions through `executionInstructions`; tools own call arguments, SDK declarations and image attachment. Workflow uses `programFormat` to wrap its program and refuses restricted file policies when the selected runtime cannot enforce them.
@@ -34,4 +34,4 @@ A realm inside the Harness process shares process lifetime with model code and c
Selecting `persistent-in-memory` retains execution state; the [permission decision](2026-10-08-persistent-ptc-sandbox.md) defines its file restrictions. Nested tools keep their normal authorization and logging. Memory and native handles may disappear without a Harness restart. The model must recover from reference or resource errors; the runtime never retries a program automatically.
An idle owner retains a process with no expiration timer. Callers release owners explicitly; ownerless service calls use temporary processes. Programs use REPL statements and a final expression rather than top-level return, and calls for one retained owner cannot overlap. Tool schemas and program guidance follow the selected mode.
An idle owner retains a process with no expiration timer. Callers release owners explicitly; ownerless service calls use temporary processes. The `persistent-in-memory` mode uses REPL statements and a final expression rather than top-level return, and calls for one retained owner cannot overlap. Tool schemas and program guidance follow the selected mode.
@@ -12,7 +12,7 @@ Status: implemented
现有 `@deepseek-ai/dsh-ptc-runtime-node` 插件通过 `executionMode` 选择执行模式。默认的 `per-call` 模式按配置的文件策略启动新进程。显式启用的 `persistent-in-memory` 模式为每个以对象身份标识的状态所有者保留一个 Node REPL 进程。两种模式都提供同一个 `ctx.ptcRuntime` 服务。PTC 使用存活的 Agent 作为所有者,在其上下文销毁时等待释放。修改配置会重载提供方并释放其进程。[Node 沙箱决策](2026-09-11-sandboxed-node-ptc-runtime.zh.md)负责逐次执行的文件约束,[PTC 基础决策](../feature/2026-06-15-ptc.zh.md)负责工具分派与模型请求日志。
模式名称描述状态保留方式,不绑定进程实现或代码语法。`per-call` 只为一次调用保留状态;`persistent-in-memory` 跨调用保留状态,直到进程或所有者结束。`durable` 用于命名未来跨重启保存与恢复执行状态的能力。它不是可接受的配置值:实现必须先明确恢复点、可恢复的值以及外部资源的处理方式,才能公开这个模式。[常驻进程权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)负责文件约束、权限切换与临时提权。
`per-call` 和 `persistent-in-memory` 名称描述各自固定的状态保留策略:只保留一次调用,或跨调用保留至进程或所有者结束。[Script 求值决策](2026-10-20-ptc-script-evaluation-and-retention.zh.md)在这两种模式之外增加独立配置的语法与保留方式。`durable` 用于命名未来跨重启保存与恢复执行状态的能力。它不是可接受的配置值:实现必须先明确恢复点、可恢复的值以及外部资源的处理方式,才能公开这个模式。[常驻进程权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)负责文件约束、权限切换与临时提权。
一个 npm 包和一个插件入口保持现有安装与加载路径稳定。通信、绑定代理、JSON 编码和输出限制继续作为包内模块复用。Node 提供方将保留进程的所有权交给内部执行对象,该对象不注册额外的 Cordis 服务。逐次执行和内存保留各自管理不同的生命周期。`programFormat` 描述代码求值形式,与状态保留独立:REPL 不必跨调用保留状态。运行时通过 `executionInstructions` 负责语法、完成值和状态保留指引;工具层负责调用参数、SDK 声明和图片附加。工作流根据 `programFormat` 包装程序;所选运行时无法执行受限文件策略时,工作流拒绝执行。
@@ -34,4 +34,4 @@ Harness 进程内的独立执行上下文与模型代码共享进程生命周期
选择 `persistent-in-memory` 会保留执行状态;[权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)定义其文件限制。嵌套工具仍遵循原有授权和日志规则。即使 Harness 没有重启,内存和原生句柄也可能丢失。模型需要从引用或资源错误中恢复,运行时不会自动重试程序。
空闲所有者保留一个没有过期计时器的进程。调用方显式释放所有者,没有所有者的服务调用使用临时进程。程序使用 REPL 语句和末尾表达式,不支持顶层 return;同一保留所有者的调用不能重叠。工具 schema 和程序指引跟随所选模式。
空闲所有者保留一个没有过期计时器的进程。调用方显式释放所有者,没有所有者的服务调用使用临时进程。`persistent-in-memory` 模式使用 REPL 语句和末尾表达式,不支持顶层 return;同一保留所有者的调用不能重叠。工具 schema 和程序指引跟随所选模式。
@@ -9,11 +9,11 @@
en: b32a7ce6483b9b48
zh: ec0938ad032b99d8
/agent-note-application-consent-for-native-computer-use/decision:
en: 36c560c24c376f12
zh: 5e4ff72f66574e38
en: b34d24e39879277e
zh: 03363665d4682ddb
/agent-note-application-consent-for-native-computer-use/alternatives-considered:
en: 80cd5fd93a42d937
zh: 2a0e241b1b8c2e1d
en: 18b2c124f1d4e601
zh: 621a6c9512d5612b
/agent-note-application-consent-for-native-computer-use/consequences:
en: 4bda3366af65250a
zh: 7c83561b4db07284
@@ -10,17 +10,15 @@ macOS privileges authorize an execution host, not a user's choice of target appl
## Decision
The CUA executor owns application consent for every object-API and native-tool dispatch. It uses the existing User Questions service for human decisions and the provider's existing profile configuration for saved grants. The existing question UI presents the offered labels; the executor rejects custom text or answers that do not select exactly one offered label. Permission-page icons and names are presentation metadata, excluded from saved identities and model results. General tool approval and operating-system privileges remain separate requirements. Arbitrary persistent PTC code and separately authorized shell tools retain their own execution authority.
The CUA executor owns application consent for every object-API and native-tool dispatch. It uses the existing User Questions service for human decisions and profile-scoped domain storage for saved grants. Its fixed approval presentation reuses the tool-approval card without adopting the session's tool-approval policy. Native icons and names are presentation metadata, excluded from saved identities and model results. General tool approval and operating-system privileges remain separate requirements. Arbitrary persistent PTC code and separately authorized shell tools retain their own execution authority.
System-permission buttons call the native helper on the DSH host and remain available to remote browsers. The [usage documentation](../../../../packages/experimental/cua/README.md#use-this-package) explains where to complete authorization; the page has no persistent remote-access notice.
A saved identity combines the canonical executable path with a verified designated signing requirement, represented by a SHA-256 digest. The path prevents authorization from following a copied application, and the signing requirement distinguishes replacements while allowing matching signed updates. Unverifiable and ad-hoc applications receive session access only, tied to a process instance. Labels do not establish identity.
Application identity is owned by [bundle-ID consent](2026-10-25-cua-bundle-id-consent.md), which supersedes this note's original path/signature choice. That original choice prevented copied or replaced applications from inheriting access, at the cost of separate grants per installation and no saved grants for unsigned applications. Enforcement and human decision ownership remain as described here.
Cold application selection prepares an executable identity and handle without launching. The same consent decision guards the private launch continuation, and the helper checks the executable again before launch and binds the resulting process afterward. Signed selections retain the normal designated-requirement identity; an unverifiable executable uses a content identity for this pending selection and cannot create a saved grant. Preparing metadata before asking avoids starting an application the user refuses.
Cold application selection prepares an executable identity and handle without launching. The same consent decision guards the private launch continuation, and the helper checks the executable again before launch and binds the resulting process afterward. Selections with a bundle identifier retain that identity after launch; an application without one uses its canonical executable path before and after launch and can save that grant. Preparing metadata before asking avoids starting an application the user refuses.
Session decisions are kept in memory by Session ID and application identity. Agent disposal and helper replacement release native handles without discarding these decisions; provider disposal or DSH restart clears them. This scope covers follow-up turns without relying on the model to decide when a user intent has ended.
Selections of the same application within one session are serialized, so a pending question does not produce competing decisions. Saved-grant additions and revocations share one mutation queue and read the current grant list inside it. Provider shutdown cancels writes still waiting for HMR admission; admitted writes settle before disposal completes. Refusals prevent another prompt until the user permits asking again; a restored saved grant takes precedence in both dispatch and the permission-page projection.
Conversation decisions survive provider disposal and DSH restart according to [profile consent storage](2026-10-19-cua-profile-consent-storage.md). That decision owns persistence, migration and cross-process revocation. The executor continues to serialize application selections within a conversation, refuse repeated prompts after denial, and give an explicit long-term grant precedence over conversation refusals.
Revocation invalidates the Agent connections that retain the application's handles, then awaits native cleanup. Reauthorization uses a fresh connection, so old app and window snapshots cannot become valid again. The [native object decision](2026-09-17-experimental-cua-object-api.md) continues to own process identity, coordinate semantics, and separation from the evaluator.
@@ -28,9 +26,9 @@ Revocation invalidates the Agent connections that retain the application's handl
**Trust model instructions or hide controls.** Retained objects and direct tool calls can still reach native operations. The executor must enforce the decision at dispatch.
**Persist application names or unsigned paths.** A replacement can reuse both. Durable grants require a verifiable signing identity; session access supports unsigned development applications without that promise.
**Persist application names or unsigned paths.** A replacement can reuse both. [Bundle-ID consent](2026-10-25-cua-bundle-id-consent.md) owns the identity choices and the decision to share permission between installations.
**Add an approval database or Session control stream.** Profile settings already own user configuration, and User Questions already owns interactive answers. The permission UI observes the provider and its owning settings namespace without another authorization store or event channel.
**Add an approval database or Session control stream.** User Questions already owns interactive answers. The existing domain service provides durable state without introducing a dedicated database or Session control stream; storage tradeoffs are owned by the profile consent decision.
**Disable permission buttons based on the browser address.** A user may operate the DSH host through screen sharing and complete authorization there. Port forwarding and proxies make the address an unreliable indication of whether the browser and DSH run on the same computer.
@@ -10,17 +10,15 @@ macOS 权限授权执行宿主,不能表达用户允许操作哪些目标应
## 决策
CUA 执行器在每次对象 API 和原生工具调用时检查应用授权。人工决定复用 User Questions 服务,长期许可保存在 provider 的现有 profile 配置中。通用工具审批和操作系统权限仍是独立要求。任意 persistent PTC 代码和另行授权的 shell 工具保留各自的执行权限。现有问答界面展示授权选项;执行器拒绝自由文本或未准确选中一个所给选项的回答。权限页图标和名称仅用于展示,不进入保存的身份信息或模型结果。
CUA 执行器在每次对象 API 和原生工具调用时检查应用授权。人工决定复用 User Questions 服务,长期许可保存在按 profile 隔离的存储域中。通用工具审批和操作系统权限仍是独立要求。任意 persistent PTC 代码和另行授权的 shell 工具保留各自的执行权限。 固定审批呈现复用工具审批卡片,同时保留独立于会话工具审批策略的授权规则。本机图标和名称仅用于展示,不进入保存的身份信息或模型结果。
系统权限按钮调用运行 DSH 的电脑上的原生 helper,远程访问时仍可使用。授权地点写在[使用说明](../../../../packages/experimental/cua/README.zh.md#use-this-package)中,页面不常驻远程访问提示。
长期身份由规范化可执行文件路径和经过验证的签名指定要求组成,以 SHA-256 摘要表示。路径阻止许可跟随应用副本,签名要求区分替换程序,并允许符合相同签名要求的更新。签名不可验证或使用 ad-hoc 签名的应用只能获得会话授权,许可绑定进程实例。显示名称不用于确定身份。
应用身份由[Bundle ID 授权](2026-10-25-cua-bundle-id-consent.zh.md)负责,取代本记录原先的路径和签名选择。原选择防止应用副本或替换程序继承许可,代价是各安装副本必须分别授权,未签名应用无法保存长期许可。执行检查和用户决定的所有权仍由本记录规定。
选择尚未运行的应用时,先准备可执行文件身份和句柄,不立即启动。同一授权决定保护内部启动续接,helper 在启动前再次核对可执行文件,并在启动后绑定实际进程。已签名应用沿用签名指定要求身份;签名不可验证的程序使用本次待启动选择的内容身份,不能生成长期许可。先准备元数据再询问,可以避免启动用户拒绝的应用。
选择尚未运行的应用时,先准备可执行文件身份和句柄,不立即启动。同一授权决定保护内部启动续接,helper 在启动前再次核对可执行文件,并在启动后绑定实际进程。有 Bundle ID 的应用在启动后沿用该身份;没有 Bundle ID 的程序在启动前后使用规范化可执行路径,并可保存该许可。先准备元数据再询问,可以避免启动用户拒绝的应用。
会话决定按 Session ID 和应用身份保存在内存中。Agent 销毁或 helper 重建会释放原生句柄,但保留授权决定;提供方卸载或 DSH 重启后清除。会话范围可以覆盖用户的后续指令,无须由模型判断一次用户意图何时结束。
同一会话对同一应用的选择串行执行,避免未完成的问题产生相互冲突的决定。长期许可的新增和撤销共用写入队列,并在队列内读取当前许可列表。提供方关闭时取消尚在等待 HMR 调度的写入,已开始的写入会在销毁完成前结束。拒绝会阻止再次询问,直到用户允许重询;重新添加的长期许可在执行检查和权限页中均优先于旧拒绝记录。
会话决定按[profile 授权存储](2026-10-19-cua-profile-consent-storage.zh.md)的规则,在提供方卸载和 DSH 重启后保留。该记录负责持久化、迁移和跨进程撤销。执行器继续将同一对话对同一应用的选择串行化,拒绝后不再次询问,显式长期许可优先于会话拒绝。
撤销使保留目标应用句柄的 Agent 连接失效,并等待原生清理完成。重新授权使用新连接,因此旧应用对象和窗口快照不能重新生效。[原生对象决策](2026-09-17-experimental-cua-object-api.zh.md)继续负责进程身份、坐标语义和与执行器分离的设计。
@@ -28,9 +26,9 @@ CUA 执行器在每次对象 API 和原生工具调用时检查应用授权。
**依赖模型指引或隐藏控件。** 保留的对象和直接工具调用仍能到达原生操作。执行器必须在派发时检查用户决定。
**保存应用名称或未签名路径。** 替换程序可以复用二者。长期许可需要可验证的签名身份;会话授权支持未签名的开发应用,但不承诺跨进程复用。
**保存应用名称或未签名路径。** 替换程序可以复用二者。身份选择和在安装副本之间共用许可的决定由[Bundle ID 授权](2026-10-25-cua-bundle-id-consent.zh.md)负责。
**新增审批数据库或 Session 控制流。** Profile settings 已负责用户配置,User Questions 已负责交互回答。权限界面查询 provider,并监听其配置 namespace,无须另一份授权存储或事件通道。
**增加审批数据库或 Session 控制流。** User Questions 已经负责交互式回答。现有域服务提供持久状态,无须增加专用数据库或 Session 控制流;存储取舍由 profile 授权存储决策负责。
**根据浏览器访问地址禁用权限按钮。** 用户可能通过屏幕共享操作运行 DSH 的电脑,并在该电脑上完成授权。端口转发和代理使访问地址无法可靠判断浏览器与 DSH 是否运行在同一台电脑上。
@@ -36,8 +36,8 @@
en: d50ae22978165c57
zh: 8c1fcfb7dc2d3367
/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/endpoint-resources:
en: 056a141b31270cba
zh: 3f6caafb3a13c192
en: 582f5f527ecc58c8
zh: 4a4b68361de2dcf0
/agent-note-peer-principals-and-method-level-remote-access-control/decision/method-level-access-control/roles-bindings-and-policies-deepseek-ai-dsh-api-remote-access:
en: e57f396239ea9f56
zh: ddb26278b1521ceb
@@ -241,7 +241,7 @@ The table lists the endpoints #3854 viewers use and where their resources come f
| `llm/listProviders` | `global` | no resource | no |
| `commands/list` | session: `args.agentId` (the Agent lookup's wire field) | Agent lookup `resource: 'session'` | no |
| `goals/get` | session: `args.agentId` | Agent lookup `resource: 'session'` | no |
| `session/attachment` | session: `args.request.sessionId` | default resolver | no |
| `session/attachment` | session: `args.request.sessionId` | default resolver | no: a grant on one Session permits reads from the whole attachment store |
| `skills/list` | session: `args.request.sessionId` | default resolver | no |
| `session/fork` | session: `args.request.sessionId` | default resolver | no |
| `session/prompt` | session: `args.request.sessionId` | default resolver | no |
@@ -251,6 +251,8 @@ The table lists the endpoints #3854 viewers use and where their resources come f
| `session/follow` | same as above | default resolver | no |
| `remoteAccess/follow` | `global` | no resource; remote-access allows it for every principal | no |
For `session/attachment`, `sessionId` identifies the resource for the Gateway check; it does not constrain which image may be read. Once that check permits the call, an image may belong to another Session or no Session, and the handler does not check whether the supplied Session exists. Policy authors must treat this action as access to the whole attachment store, as defined by the [image access rule](2026-10-23-store-scoped-image-reads.md).
A subagent address reads the child transcript, so its resource is the child Session. A Client rereads the projections of known Sessions after a reconnect, including the parent of a subagent Session; a reader without a grant on that parent has its projection read refused. Whether a grant on a parent Session covers its subagent children is the policy's decision, that is, whether it gives a binding for the child Session; the generic layer derives no parent resource.
Methods that need no non-owner access declare nothing, and a method no role lists is refused. The request fields of subagent `prompt` are `parentSessionId` / `childSessionId`, so automatic resolution finds no Session and resolves it to `global`; it must therefore stay out of every `global` role. `session/search` filters its hits per Session inside the method. `subagents/list` is not a Remote endpoint (`SubagentRuntime.list()` carries no `@Remote`).
@@ -241,7 +241,7 @@ export function RemoteScope<This extends object, Args extends unknown[], Result>
| `llm/listProviders` | `global` | 无资源 | 否 |
| `commands/list` | session:`args.agentId`(Agent lookup 的 wire 字段) | Agent lookup `resource: 'session'` | 否 |
| `goals/get` | session:`args.agentId` | Agent lookup `resource: 'session'` | 否 |
| `session/attachment` | session:`args.request.sessionId` | 默认 resolver | 否 |
| `session/attachment` | session:`args.request.sessionId` | 默认 resolver | 否:一条 Session 上的授权允许读取整个附件存储 |
| `skills/list` | session:`args.request.sessionId` | 默认 resolver | 否 |
| `session/fork` | session:`args.request.sessionId` | 默认 resolver | 否 |
| `session/prompt` | session:`args.request.sessionId` | 默认 resolver | 否 |
@@ -251,6 +251,8 @@ export function RemoteScope<This extends object, Args extends unknown[], Result>
| `session/follow` | 同上 | 默认 resolver | 否 |
| `remoteAccess/follow` | `global` | 无资源;remote-access 对任何 principal 放行 | 否 |
对于 `session/attachment`,`sessionId` 指定 Gateway 检查的资源,不限制可读取哪张图片。该检查放行后,图片可以属于其他 Session 或不属于任何 Session,处理函数也不检查请求中的 Session 是否存在。policy 作者必须把此 action 视为整个附件存储的读取权限,具体规则见[图片访问规则](2026-10-23-store-scoped-image-reads.zh.md)。
subagent 地址读取的是子会话转录,因此其资源是子会话。Client 在重连后会重新读取已知会话的 projections,其中包括 subagent 会话的父会话;没有该父会话授权的读者,其 projection 读取被拒。父会话的授权是否覆盖其 subagent 子会话由 policy 决定,即是否为子会话给出 binding;通用层不推导父资源。
不需要非 owner 访问的方法不做任何声明,没有 role 列出它即被拒。subagent `prompt` 的请求字段为 `parentSessionId` / `childSessionId`,自动解析不到会话,解析为 `global`,因此不得放进任何 `global` 级 role;`session/search` 在方法内按会话逐项过滤命中。`subagents/list` 不是 Remote 端点(`SubagentRuntime.list()` 未标 `@Remote`)。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-10-19-cua-profile-consent-storage.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-19-cua-profile-consent-storage.md
/agent-note-durable-computer-use-consent-within-one-profile:
en: b2aa270d586efd93
zh: 99606fa28dc4a752
/agent-note-durable-computer-use-consent-within-one-profile/problem:
en: f2c70036a57ddb41
zh: 9bbbf3dd09d486f5
/agent-note-durable-computer-use-consent-within-one-profile/decision:
en: 11622523090f5d88
zh: 1d0f8ad94645f069
/agent-note-durable-computer-use-consent-within-one-profile/alternatives-considered:
en: 2af74afa3ecaf3b9
zh: 96f7f43c5d1150df
/agent-note-durable-computer-use-consent-within-one-profile/consequences:
en: 66fe232589e46d64
zh: fc69831be76248d9
@@ -0,0 +1,31 @@
# Agent Note: Durable Computer Use consent within one profile
Status: implemented
English | [中文](2026-10-19-cua-profile-consent-storage.zh.md)
## Problem
Application grants stored as plugin configuration make each authorization change depend on configuration reconciliation. Process-local conversation decisions also disappear when the same conversation resumes after a restart. A shared in-memory storage handle cannot observe another process revoking permission.
## Decision
The CUA owner uses the existing domain storage service, with one domain per canonical profile directory. It stores long-term grants and conversation decisions by native application identity. Conversation IDs scope permission without turning it into permission for every conversation. The native identity policy remains owned by [bundle-ID consent](2026-10-25-cua-bundle-id-consent.md); this note replaces only that note's storage and restart-lifetime choices.
Every operation opens fresh domain state while holding the profile's existing file-lock primitive and closes the domain before releasing the lock. Native dispatch and revocation use a separate lock for the selected application. Storage reads and unrelated applications remain available during a native call. Revocation cancels this process's affected work first, then commits after other processes' already-admitted operations have finished. A completed revocation therefore leaves no operation using the old authority. App-wide revocation generations and per-conversation decision revisions prevent an old handle or delayed answer from restoring revoked access.
The JSON backend remains the shipped default. The domain name contains the SHA-256 digest of the canonical profile directory, isolating profiles that share one storage root. Legacy `allowedApps` is imported once; a persisted migration marker prevents an old configuration from restoring a revoked grant. Users can remove that configuration after checking the migrated list. Corrupt or unavailable profile storage fails closed. A composition without a profile has only temporary conversation state.
## Alternatives considered
**Keep authorization in configuration.** It preserves existing storage but retains configuration-write and HMR coupling for runtime application decisions.
**Keep one domain open and rely on change events.** Domain notifications are process-local. Another host could continue to use stale grants after revocation.
**Add a new watcher, revision file or authorization broker.** The existing domain and file-lock primitives provide fresh reads and serialized operation admission without a new shared storage or IPC framework. Operations on the same application are serialized across processes; other applications and their conversation decisions remain independent.
## Consequences
File locks coordinate processes on one machine and PID namespace. A network-mounted profile shared across hosts is unsupported. Revocation may wait for another process's native call to settle. No timer establishes authorization validity.
The permission page still omits conversation-only grants and reads current state on entry, focus, actions and reconnection. Storage changes do not emit configuration events. System permissions remain owned by macOS. Tests cover restart retention, profile isolation, another process's write, cancellation, corrupted data, legacy import and non-resurrection after revocation. Stored conversation records currently require explicit retention management rather than automatic eviction.
@@ -0,0 +1,31 @@
# Agent Note: 同一 profile 内的持久 Computer Use 授权
Status: implemented
[English](2026-10-19-cua-profile-consent-storage.md) | 中文
## 问题
把应用许可保存为插件配置,会让每次授权变更依赖配置重组。只保存在进程内的会话决定,也会在重启后恢复同一对话时丢失。长期持有的内存存储句柄无法观察另一个进程的撤销操作。
## 决策
CUA 使用现有域存储服务,每个 profile 的真实目录对应独立存储域,按本机应用身份保存长期许可和会话决定。对话 ID 限定权限范围,不把本会话许可扩展为所有对话的许可。本机身份规则仍由[Bundle ID 授权](2026-10-25-cua-bundle-id-consent.zh.md)负责,本记录仅替代其中的存储和重启后有效期选择。
每个操作使用现有文件锁,在 profile 锁内打开并读取最新存储状态,关闭域后才释放锁。原生操作和撤销使用单独的目标应用锁;原生调用期间仍可读取存储或访问其他应用。撤销先取消本进程中受影响的工作,再等待其他进程已获准执行的操作结束后提交。因此,撤销完成后不会留下仍使用旧授权的操作。应用级撤销代次和各对话的决定版本,阻止旧句柄或迟到回答恢复被撤销的访问权限。
随附配置继续使用 JSON 后端。域名包含 profile 真实目录的 SHA-256 摘要,隔离共用存储根目录的不同 profile。旧 `allowedApps` 只导入一次,持久化迁移标记阻止旧配置恢复已撤销的许可。用户确认列表迁移完成后可删除旧配置。profile 存储损坏或不可用时拒绝访问。没有 profile 的组合只保留临时会话状态。
## 考虑过的替代方案
**继续将授权保存在配置中。** 可以复用旧存储,但运行时应用决定仍依赖配置写入和 HMR。
**长期打开域并依赖变更事件。** 域事件只在进程内传播,另一个宿主可能在撤销后继续使用旧许可。
**增加新的监听器、版本文件或授权代理。** 现有域存储和文件锁已经能提供最新状态与串行准入,无须增加通用存储或 IPC 框架。不同进程对同一应用的操作串行执行,其他应用及其会话决定保持独立。
## 后果
文件锁协调同一电脑及 PID 命名空间中的进程,不支持跨主机共用网络目录。撤销可能等待其他进程的原生调用结束。授权是否有效不由计时器决定。
权限页仍不显示仅对单个会话生效的许可,在进入页面、返回窗口、完成操作和重连后读取最新状态。存储变更不发送配置事件,系统权限仍归 macOS 管理。测试覆盖重启恢复、profile 隔离、其他进程写入、取消、数据损坏、旧配置导入和撤销后不恢复。已保存的会话记录目前需要显式管理保留期限,不自动淘汰。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-10-20-ptc-script-evaluation-and-retention.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-20-ptc-script-evaluation-and-retention.md
/agent-note-ptc-script-evaluation-and-state-retention:
en: e222c8cda4cee561
zh: 9e624e5643ad2984
/agent-note-ptc-script-evaluation-and-state-retention/problem:
en: 2da844a2a4e1903b
zh: 3b74ba7c1bcdae89
/agent-note-ptc-script-evaluation-and-state-retention/decision:
en: 4beff8714f1d1555
zh: a22019a90989eb66
/agent-note-ptc-script-evaluation-and-state-retention/alternatives-considered:
en: 8ee3f3c7e04b4f25
zh: ac604fa8debcfebf
/agent-note-ptc-script-evaluation-and-state-retention/consequences:
en: 64b7d3a5d247d82b
zh: 6f94d6b37f1ea4c1
@@ -0,0 +1,33 @@
# Agent Note: PTC Script evaluation and state retention
Status: implemented
English | [中文](2026-10-20-ptc-script-evaluation-and-retention.zh.md)
## Problem
Program syntax and memory lifetime answer different questions. A consumer may need Script declarations and completion values while requiring either a fresh environment or retained references. Inferring memory lifetime from REPL syntax prevents that choice.
## Decision
The Node provider adds `executionMode: vm-script` and a separate `scriptPersistence` option, defaulting to false. `PtcRuntime.programFormat` describes accepted syntax; `retainsState` describes owner-scoped memory. Consumers use the latter for persistence controls and guidance. Existing `per-call` and `persistent-in-memory` configurations retain their meanings and defaults.
This extends the mode-naming decision in [best-effort persistent PTC](2026-09-23-best-effort-persistent-ptc.md), whose ownership, non-durability and recovery decisions remain active. The Node provider selects its evaluator once and shares managed process mechanisms across temporary and retained lifetimes. AsyncFunction, REPL and Script remain separate evaluator implementations, so process reuse does not define syntax.
VM Script uses a separate realm inside the managed child process. Top-level await uses the Node.js v26.6.0 REPL transform, with Acorn and acorn-walk supplying parsing and traversal. Detection precedes native compilation because non-strict Script can compile `await` as an identifier. The adapted visitors traverse computed method keys without entering method bodies. The source retains upstream attribution and license; the [package reference](../../../../packages/ptc-runtime/ptc-runtime-node/README.md#known-limitations-and-deferred-work) owns declaration and realm limitations.
## Alternatives considered
**Replace existing modes with Script.** This would change async-function return syntax and REPL declaration behavior for existing consumers. An additional mode preserves those choices while exposing Script semantics.
**Encode syntax and retention in every mode name.** Separate names for fresh and retained Script would repeat syntax choices and encourage consumers to infer persistence from the format. One Script mode and an explicit retention option keep each fact separately observable.
**Use native Script without await conversion.** Native Script cannot evaluate top-level await. Parsing only after native compilation fails also misses valid programs where `await` compiles as an identifier. The Node transform supplies retained declarations and completion handling while keeping its known semantic tradeoffs explicit.
**Own a generic AST walker.** A local walker duplicates traversal provided by acorn-walk and must independently track new Acorn nodes. The maintained walker removes that implementation; only the evaluation-specific visitors remain local.
## Consequences
Script state is best-effort process memory, with the same explicit owner release and sandbox invalidation rules as retained REPL execution. It is neither serialized nor reconstructed by rerunning earlier programs. An uncaught callback exception or unhandled rejection terminates the Script process; programs must await asynchronous work.
The published format union now includes `script`, and custom retained providers must report `retainsState`. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.md) describes consumer migration. Source deployments need the evaluator modules and Acorn packages; private process bundles include those dependencies.
@@ -0,0 +1,33 @@
# Agent Note: PTC Script 求值与状态保留
Status: implemented
[English](2026-10-20-ptc-script-evaluation-and-retention.md) | 中文
## 问题
程序语法和内存生命周期回答不同的问题。消费者可能需要 Script 声明和完成值,同时要求全新环境或保留引用。根据 REPL 语法推断内存生命周期会阻碍这种选择。
## 决策
Node 提供方增加 `executionMode: vm-script` 和独立的 `scriptPersistence` 选项,后者默认为 false。`PtcRuntime.programFormat` 描述接受的语法,`retainsState` 描述按所有者保留的内存。消费者通过后者提供持久化控制和指引。已有 `per-call` 和 `persistent-in-memory` 配置保留原有含义与默认值。
本决策扩展[尽力保留 PTC 状态](2026-09-23-best-effort-persistent-ptc.zh.md)中的模式命名决策;其中的所有权、非持久存储及恢复决策仍然有效。Node 提供方一次性选择求值器,并在临时和保留生命周期之间共用受管进程机制。AsyncFunction、REPL 和 Script 仍是独立的求值器实现,进程复用不决定语法。
VM Script 在受管子进程内使用独立 realm。顶层 await 使用 Node.js v26.6.0 REPL 转换,由 Acorn 和 acorn-walk 提供解析与遍历。在原生编译之前检测 await,因为非严格 Script 可以将 `await` 编译为标识符。适配后的 visitor 遍历方法的计算属性名,但不进入方法体。源码保留上游署名和许可;[包参考](../../../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#known-limitations-and-deferred-work)负责声明与 realm 限制。
## 考虑过的替代方案
**用 Script 替换已有模式。** 这会改变现有消费者的异步函数返回语法和 REPL 声明行为。增加模式可在提供 Script 语义的同时保留已有选择。
**在每个模式名称中同时编码语法与保留方式。** 为全新和保留状态的 Script 分别命名,会重复语法选项,并鼓励消费者根据格式推断持久化。一个 Script 模式加显式保留选项,让两项事实可以分别观测。
**仅使用原生 Script,不转换 await。** 原生 Script 无法求值顶层 await。只在原生编译失败后解析,也会漏掉将 `await` 编译为标识符的有效程序。Node 转换提供声明保留和完成值处理,同时明确其已知语义取舍。
**自行维护通用 AST 遍历器。** 局部遍历器重复 acorn-walk 已提供的遍历功能,还必须独立跟踪新增 Acorn 节点。使用维护中的遍历器可以删除这部分实现,只保留与求值相关的局部 visitor。
## 影响
Script 状态是尽力保留的进程内存,遵循与保留 REPL 相同的显式所有者释放和沙箱失效规则。状态不会序列化,也不会通过重新执行旧程序重建。未捕获的回调异常或未处理的 Promise 拒绝会终止 Script 进程;程序必须等待异步工作。
公开格式联合类型现包含 `script`,自定义保留状态的提供方必须报告 `retainsState`。[升级指南](../../../../docs/upgrade-guide/v0.2.1-rc.2/ptc-script-format/guide.zh.md)说明消费者迁移。源码部署需要求值器模块和 Acorn 包,私有进程 bundle 包含这些依赖。
@@ -0,0 +1,28 @@
# Bilingual-pair consistency record for 2026-10-21-session-history-stream-and-snapshot.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-21-session-history-stream-and-snapshot.md
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation:
en: 0c9a7bc6591feb16
zh: 3606a2c1caffd36f
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/problem:
en: ac1583e7ae1377f8
zh: c60bdbda9ee89144
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision:
en: 45c63df5dac389eb
zh: d72a5bcb94de22f1
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision/reads-and-subscriptions:
en: 38df4f3c4fba2cc9
zh: a34f3376faf26f0c
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision/follow-ordering-and-ownership:
en: 352ff87a3e9cd110
zh: 4ac6366cecfc08a3
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision/state-and-wait:
en: a87c7427582e6b03
zh: b28d2a73b36eb27f
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/alternatives-considered:
en: c5fb06ab9df9e7ad
zh: b20adf151018111c
/agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/consequences:
en: dc1da262b4911a31
zh: 2a4e503696fc477b
@@ -0,0 +1,59 @@
# Agent Note: Session snapshots, passive subscriptions, and Web aggregation
Status: implemented
English | [中文](2026-10-21-session-history-stream-and-snapshot.zh.md)
## Problem
A point read, an event subscription, and a Web conversation opening have different lifetimes. Combining them inside one history controller makes passive observation perform unnecessary reads and gives each aggregate its own acquisition logic. Reading before subscribing also creates a gap that requires another read to repair. The APIs need independent operations that can compose without losing events or duplicating ownership.
## Decision
`SessionController` is the single Session Remote Service. It owns ordinary `HistoryController`, `StateController`, and `WebController` instances, not three additional Cordis Services or Remote namespaces. The implementation separates six operations: history snapshot and observation, projection snapshot and observation, and state snapshot and observation. Follow and Wait compose those capabilities for their callers; the existing `page` entry forwards to the history reader.
### Reads and subscriptions
History reads return chronological records, `hasMore`, and an inclusive cursor. An omitted `throughSeq` selects the observed log end; `beforeSeq` selects older records without changing that read cut. Projection reads return exact sequenced values, sequence-free cache hints when migration is required, or null when the Session is absent. Live projection reads avoid persistence metadata access.
`usingObservation({ sessionId, projection }, signal, callback?)` acquires the existing disposable SessionObservation. A callback borrows it until the callback settles; without a callback the caller owns disposal. Ordinary history, state, and Wait output reads do not request projections. Follow, exact projection reads, and subagent history descriptor validation request them. No read activates an Agent implicitly.
`observeEvent` and `observeProjections` install listeners without acquiring an Observation. Their initial `ready` confirms subscription, not a snapshot cursor, existence, parent-child validity, or Agent readiness. History establishes continuity from its first received event; projection updates replace individual keys and may share a sequence number. `observeState` instead begins with a complete state read and coalesces later Session and Agent invalidations.
History, history observation, and Follow accept Address requests; projection and state operations accept Session IDs. All internal readers and listeners use Session IDs. History and Follow validate Address against their opening Observation at the Controller layer, including the existing subagent descriptor rules. Pure history observation does not acquire a read for entity validation. Gateway resource authorization remains independent: the registered Session resolver extracts the target ID from the request before access is decided.
### Follow ordering and ownership
Follow installs history and optional assistant listeners first, then acquires one projected Observation. It captures the assistant baseline and binding-local arrival ordinal synchronously, sets both cuts, publishes the opening snapshot, and consumes the shared output queue. History notifications at or before the snapshot cursor and assistant notifications at or before the ordinal are discarded at consumption. Later notifications remain ordered without a second history read, background merge pumps, or a tail repair introduced by the opening itself.
`session/created` contributes constructor seed events through the same history buffer. The adapter retains the supplied Session and its captured end position, then reads that in-memory prefix when consumed; it does not acquire another Observation. Each binding owns its subscriptions; a shared output queue belongs to Follow rather than to either listener.
Follow activates only when the caller passes `activate: true`; the Web Client does so explicitly. Background promotion starts once the opening is computed and before it is delivered, and does not promise Agent readiness. Ordinary promotion reuses the existing Agent controller and receives a separately retained Observation. Either Follow releases its opening Observation once the opening is computed, before yielding it; activation continues on the separately retained lease, so the cold entry's reference count drops to that lease alone. Subagent Sessions do not use ordinary promotion.
### State and Wait
State contains the event cursor, active and running flags, the complete readable queue or null, and pending-input kinds. It exposes neither a header nor an internal revision. Gateway owns unsettled Remote events; State samples their detached metadata and classifies approval, question, or other input without copying a request registry.
Wait evaluates complete states, confirms active-Agent quiescence with `whenIdle`, and rejects stale observations using listener-local revisions and Agent/Session identity checks. Session and Agent events wake reads immediately; while waiting, a one-second recheck detects pending input that produces no such event. This avoids adding a Gateway change event, at the cost of polling and bounded sampling delay rather than instantaneous notification. `observeState` does not poll, so pending-only changes need another state invalidation to become visible there.
Wait returns idle, input-required, or timeout with the last state it accepted and bounded assistant output. Output contains only `assistant/message` records in `(afterSeq, state.cursor]`, newest first, and reports truncation only when another eligible record exists. The caller's cancellation signal controls that output read independently of the expired wait deadline. A wait that accepts no state before its deadline fails instead of inventing a state.
## Alternatives considered
**Read history, then subscribe and repair the gap.** Subscription-before-read already captures opening-time increments. A second read adds acquisition and replay obligations without improving that ordering.
**Give pure subscriptions an Observation or ready cursor.** These values conflate subscription readiness with an independently selected read cut. Callers that need both subscribe and buffer first, then read and discard covered increments.
**Keep separate Remote Services for the implementation controllers.** The classes divide behavior, not external service identity. One Session Service owns their composition, resource policy, and Remote entry points.
**Have Gateway interpret pending input or emit Session status.** Gateway only owns Remote event transport and unsettled-event metadata. State owns classification; Wait's periodic sampling avoids adding a transport notification solely for Session waiting.
**Merge assistant and history with independent asynchronous pumps.** One caller-owned buffer retains cross-source arrival order without extra pump cancellation or queue ownership. Snapshot construction and per-binding buffering retain distinct lifetimes.
## Consequences
The standard reads and Web aggregate share one Observation acquisition path, while pure subscriptions remain read-free. The old combined History controller is removed; still-used pagination, validation, and wire helpers remain at their original path. Cancellation, consumer termination, failed opening reads, and Context disposal release subscriptions and owned leases without cancelling Agent execution.
The [Observation decision](2026-08-25-session-observations-and-projection-owned-client-state.md) remains the authority for exact read cuts and projection derivation. The [history and Remote transport decision](2026-08-18-session-history-and-event-transport.md) retains ownership of Client reconnection and transport lifetimes. This decision refines Session API composition rather than replacing either broader decision.
The migrated history, cold-read, and transport tests exercise the new classes, including cursor overlap, assistant ordinal cuts, sequence gaps, subagent validation, and teardown. Slow consumers can still retain queued notifications; silent dropping is not a supported recovery strategy. Independent completion-acknowledged activation is not implemented by these reads or by Follow's background activation option.
@@ -0,0 +1,59 @@
# Agent Note: Session 快照、纯订阅与 Web 聚合
Status: implemented
[English](2026-10-21-session-history-stream-and-snapshot.md) | 中文
## Problem
定点读取、事件订阅和 Web 会话开场具有不同的生命周期。把它们合并在同一个历史控制器中,会使被动观察执行不必要的读取,并让每个聚合各自维护获取数据的逻辑。先读后订阅还会产生需要再次读取来修复的缺口。接口需要相互独立的操作,使组合既不丢事件,也不重复资源所有权。
## Decision
`SessionController` 是唯一的 Session Remote Service。它持有普通的 `HistoryController`、`StateController` 和 `WebController` 实例,而不是额外的三个 Cordis Service 或 Remote namespace。实现分离六个操作:历史快照与观察、投影快照与观察、状态快照与观察。Follow 和 Wait 为调用方组合这些能力;已有的 `page` 入口转发到历史读取器。
### 读取与订阅
历史读取返回时间正序的记录、`hasMore` 和包含末项的游标。省略 `throughSeq` 时选择观察到的日志末尾;`beforeSeq` 只选择更早的记录,不改变读取点位。投影读取返回精确的有序值、需要迁移时无序号的缓存提示,或在 Session 不存在时返回 null。live 投影读取不访问持久化元信息。
`usingObservation({ sessionId, projection }, signal, callback?)` 获取已有的可释放 SessionObservation。有回调时租约借给回调直到其结束;无回调时由调用方释放。普通历史、状态及 Wait 输出读取不请求投影。Follow、精确投影读取和子会话历史 descriptor 校验请求投影。读取不会隐式激活 Agent。
`observeEvent` 和 `observeProjections` 安装监听而不获取 Observation。首个 `ready` 确认订阅生效,不代表快照游标、实体存在、父子关系有效或 Agent 就绪。历史从首个收到的事件建立连续性;投影更新替换单个键,多个更新可以共享序号。`observeState` 则从完整状态读取开始,并合并后续 Session 和 Agent 失效通知。
历史、历史观察和 Follow 接收 Address 请求;投影和状态操作接收 Session ID。所有内部读取器和监听器都使用 Session ID。History 和 Follow 在 Controller 层以开场 Observation 校验 Address,包括已有的子会话 descriptor 规则。纯历史观察不为实体校验获取读取。Gateway 资源授权与之独立:注册的 Session 解析器在访问判定前从请求提取目标 ID。
### Follow 顺序与所有权
Follow 先安装历史和可选 assistant 监听,再获取一份带投影的 Observation。它同步捕获 assistant 基线和绑定局部的到达序号,设置两种截断点,发布开场快照,然后消费共享输出队列。消费时丢弃序号不超过快照游标的历史通知,以及到达序号不超过截断点的 assistant 通知。后续通知保持顺序,无需第二次历史读取、后台合并任务,或由开场自身引入的尾部修复。
`session/created` 经同一历史缓冲提供构造期种子事件。适配器保留收到的 Session 及捕获的末尾位置,在消费时读取对应内存前缀,不获取另一份 Observation。每个绑定拥有自己的订阅;共享输出队列属于 Follow,而不是任一监听器。
只有调用方传入 `activate: true` 时 Follow 才激活;Web Client 显式传入该参数。后台提升在开场计算完成后、交付之前启动,不承诺 Agent 已就绪。普通提升复用已有 Agent controller,并接收单独 retain 的 Observation。两种 Follow 都在开场计算完成后、交付前释放开场 Observation;激活则继续使用单独 retain 的租约,因此冷 entry 的引用计数只剩那一份。子会话不走普通提升。
### 状态与 Wait
State 包含事件游标、active 与 running 标志、完整可读队列或 null,以及待输入种类。它不暴露 header 或内部 revision。Gateway 拥有未结算的 Remote 事件;State 采样独立元数据,将输入分类为 approval、question 或 other,不复制请求注册表。
Wait 判断完整状态,通过 `whenIdle` 确认活跃 Agent 已静止,并通过监听器局部 revision 和 Agent/Session 身份检查拒绝过时观察。Session 和 Agent 事件立即唤醒读取;等待期间每秒重查一次,检测没有产生上述事件的待输入请求。这避免新增 Gateway change 事件,代价是轮询和采样延迟,而非即时通知。`observeState` 不轮询,因此仅有 pending 变化时,需要另一项状态失效通知才会显示更新。
Wait 返回 idle、input-required 或 timeout,以及最后一次被接受的状态和有界 assistant 输出。输出仅包含 `(afterSeq, state.cursor]` 内从新到旧的 `assistant/message` 记录,只有存在另一条符合条件的记录时才报告截断。输出读取使用调用方的取消信号,不受已过期的等待截止信号控制。截止前没有任何状态通过校验的 wait 会失败,不构造虚假的状态。
## Alternatives considered
**先读历史,再订阅并修复缺口。** 先订阅后读取已经捕获开场期间的增量。第二次读取增加资源获取和重放责任,却不改善这个顺序。
**给纯订阅提供 Observation 或 ready 游标。** 这会混淆订阅就绪和独立选取的读取点位。需要两者的调用方先订阅并缓冲,再读取并丢弃已覆盖增量。
**为各实现 Controller 保留独立 Remote Service。** 这些类划分行为,而不是外部服务身份。一个 Session Service 拥有其组合、资源策略和 Remote 入口。
**让 Gateway 解释待输入状态或发送 Session status。** Gateway 只拥有 Remote 事件传输和未结算事件元数据。State 拥有分类;Wait 定期采样,避免仅为 Session 等待增加传输通知。
**用独立异步任务合并 assistant 与历史。** 调用方拥有的单个缓冲保留跨来源到达顺序,不引入额外任务取消或队列所有权。快照构造和各绑定缓冲仍保留不同生命周期。
## Consequences
标准读取和 Web 聚合共享同一 Observation 获取路径,纯订阅不读取数据。旧的合并 History controller 已删除;仍使用的分页、校验和 wire 辅助函数留在原路径。取消、消费者结束、开场读取失败和 Context 释放都会释放订阅及拥有的租约,而不取消 Agent 执行。
[Observation 决策](2026-08-25-session-observations-and-projection-owned-client-state.zh.md)仍拥有精确读取点位和投影派生规则。[历史与 Remote 传输决策](2026-08-18-session-history-and-event-transport.zh.md)继续拥有 Client 重连和传输生命周期。本决策细化 Session API 组合,而不取代上述更广泛的决策。
迁移后的历史、冷读取和传输测试覆盖新类,包括游标重叠、assistant 到达序号截断、序号缺口、子会话校验和释放。慢消费者仍可能积累队列通知;静默丢弃不是支持的恢复策略。这些读取以及 Follow 的后台激活选项均未实现独立的、确认完成后返回的激活接口。
@@ -0,0 +1,22 @@
# Bilingual-pair consistency record for 2026-10-23-store-scoped-image-reads.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-23-store-scoped-image-reads.md
/agent-note-image-reads-use-attachment-store-access:
en: 31c8a0d9016d99af
zh: 05db308dec85db67
/agent-note-image-reads-use-attachment-store-access/problem:
en: ff8886cfa4634163
zh: 46dfdd50638b64c2
/agent-note-image-reads-use-attachment-store-access/decision:
en: 439a3277ee3b169d
zh: c9f1e10254850844
/agent-note-image-reads-use-attachment-store-access/alternatives-considered:
en: 0c7a8319c0c91dc2
zh: 6b7b58b142839571
/agent-note-image-reads-use-attachment-store-access/consequences:
en: a46c3d951077ec7d
zh: 30a0cc5bcb681a21
/agent-note-image-reads-use-attachment-store-access/verification:
en: 89603b3a4c3e12df
zh: f1b01d166f399f87
@@ -0,0 +1,52 @@
# Agent Note: Image reads use attachment-store access
Status: implemented
English | [中文](2026-10-23-store-scoped-image-reads.zh.md)
## Problem
Historical image loading read the requesting Session and searched its event content for every uncached attachment. The search established that the Session referenced the image; it did not locate the bytes, whose storage path already follows from the content-addressed ID. This added work proportional to history length to each image read. The reported loading delay also involved uploads; this finding alone does not identify all of that delay.
## Decision
Session membership is not an image-access restriction. After connection authentication and Gateway permission checks authorize `session/attachment`, every caller may read any image in the same attachment store using a complete `ImageAttachmentRef`, including objects referenced only by other Sessions or not referenced at all. The request retains `sessionId` for the existing Session resource permission check. After that check passes, the handler does not require that Session to exist and does not return `session/not-found` solely because it is absent. No identity receives a separate history-scanning path.
The Client already holds the message's complete image reference and sends it as `attachment` beside `sessionId`. Session Controller delegates directly to the existing `AttachmentStore.readImage(ref)`. Its local provider validates the canonical ID, derives the path within its object directory, verifies SHA-256, and compares the actual format, byte length, width, and height with the supplied reference. A missing, unreadable, corrupt, or mismatched object rejects the operation. No Session history is needed to recover the reference.
The response preserves the supplied reference. Its optional `name` and `originalDimensions` are caller-supplied display information and are not verified against the stored object. The Client's existing historical-image cache continues to own per-Session results and object URLs; the Host adds no image-byte cache.
This rule narrows the readers covered by [Session observations](2026-08-25-session-observations-and-projection-owned-client-state.md) and the [history transport activation policy](2026-08-18-session-history-and-event-transport.md). [Workspace file reads](2026-09-05-workspace-files-service.md) keep their own filesystem authorization.
## Alternatives considered
**Keep a Session-to-image map or projection.** An index removes repeated scans but preserves an access restriction the product does not require, adding derivation, lifetime, and invalidation work.
**Issue signed image tickets.** Tickets add issuance and validation state for the same unnecessary Session-membership restriction.
**Optimize only owner reads.** That gives identities different image-access semantics and leaves the scan cost for permitted non-owner callers without a product requirement.
## Consequences
Knowing a valid image reference and having permission to invoke the endpoint for the supplied Session resource permits reading that object across Sessions. The local ID is the SHA-256 of normalized bytes. For known PNG, JPEG, or WebP bytes that admission preserves unchanged, a caller can calculate the ID, derive the format, byte length, and dimensions, and use an authorized read to test whether the object exists. The required reference fields need not come from a Session log.
Image isolation requires separate Host instances with separate `DSH_HOME` directories. The shipped composition uses one attachment store per Host and does not select a store by Session. Authentication, Gateway action/resource checks, fixed storage paths, digest verification, and explicit failures remain required.
Image reads no longer depend on history length or Session materialization. File reading, integrity verification, encoding, and transport still cost time; this change makes no claim about upload or model inference latency. Existing Session data and fork references need no migration.
## Verification
The read-path invariant is zero Session-history queries or traversal for attachment reads. Coverage must distinguish a permitted cross-Session image read from a denied Gateway call and exercise valid references, invalid IDs, mismatched intrinsic metadata, preserved optional display fields, missing and corrupt objects, old history pages, and inherited fork images. Performance evidence must separate historical scanning, storage work, and transport rather than attribute the entire reported delay to the scan.
The diagnostic is [`image-read.perf.ts`](../../../../packages/api/session-controller/tests/image-read.perf.ts), compiled by its [tsdown configuration](../../../../packages/api/session-controller/tests/image-read.perf.config.ts). The baseline worker pairs the pre-change controller with `{ sessionId, attachmentId: ref.attachmentId }`; the candidate worker pairs the current controller with `{ sessionId, attachment: ref }`. Both use the same image fixtures, workload, and output checks, and run against the same built Local store with `readImage(ref)` verification. From the candidate checkout root, compile and run:
```sh
pnpm exec tsdown --config-loader native --config packages/api/session-controller/tests/image-read.perf.config.ts
(cd packages/api/session-controller && node --expose-gc .dsh-build/image-read/image-read.perf.js --expect-no-history)
```
Run the separately compiled baseline worker without `--expect-no-history`; its diagnostic request must match the baseline controller's ID-only request fields. The baseline negative control adds `--sample typical --expect-no-history` and must fail because that implementation queries and traverses history. The parent process runs each workload in five fresh child processes, each with a loaded Session and a first uncached read of every image. Images are deterministic synthetic 1024 × 768 PNGs; the two workloads contain 120 turns, 960 events, and 8 images, or 2,000 turns, 16,000 events, and 32 images. Fixture writes can leave the operating system's file cache warm.
`controllerMs` covers the direct controller call through base64 return. `storeMs` includes file I/O, SHA-256, and header verification; `snapshotMs` measures history snapshot acquisition separately. `scanAndDispatchMs` is the time before store entry minus `snapshotMs`, so it includes dispatch overhead and is not an isolated scan timer. JSON serialization and loopback HTTP transfer are separate measurements over retained responses. `requestJsonBytes` and `idOnlyRequestJsonBytes` compare serialized request lengths; they do not measure request transmission time. Cold Session restoration, Gateway processing, browser rendering, remote-network latency, upload, and model inference are excluded. PR #7021 records the worker revisions and before/after results under these limits.
The memory endpoints run GC after fixture setup and after all image responses. The Session, admitted image references, and every base64 response remain reachable at the second endpoint. These retained endpoints include setup-owned objects, and peak RSS is cumulative from process start, including fixture generation. They do not measure image-request memory in isolation or impose a retained-memory budget.
@@ -0,0 +1,52 @@
# Agent Note: 图片读取使用附件存储访问权限
Status: implemented
[English](2026-10-23-store-scoped-image-reads.md) | 中文
## Problem
历史图片加载会为每个未缓存的附件读取请求中的 Session,并搜索其事件内容。搜索用于确认 Session 引用了图片;它不负责定位字节,存储路径已经能由内容寻址 ID 推导。每次读图因此增加了与历史长度成正比的工作。用户反馈的加载延迟还涉及上传;这项发现本身不能确定全部延迟的来源。
## Decision
Session 关联不构成图片访问限制。连接身份认证和 Gateway 权限检查允许调用 `session/attachment` 后,任何调用者都可以通过完整的 `ImageAttachmentRef` 读取同一附件存储中的任意图片,包括仅被其他 Session 引用或未被任何 Session 引用的对象。请求保留 `sessionId`,供现有 Session 资源权限检查使用。该检查通过后,处理函数不要求该 Session 存在,也不会仅因其不存在而返回 `session/not-found`。所有身份使用相同的读图路径。
Client 已经持有消息中的完整图片引用,将其作为 `attachment` 与 `sessionId` 一起发送。Session Controller 直接调用已有的 `AttachmentStore.readImage(ref)`。本地提供方校验规范 ID,在自己的对象目录内推导路径,校验 SHA-256,并把实际格式、字节数、宽度和高度与传入引用比对。对象缺失、不可读、损坏或与引用不符时,操作失败。取得引用无需查询 Session 历史。
响应保留传入引用。可选的 `name` 和 `originalDimensions` 是调用方提交的显示信息,不根据存储对象校验。Client 现有的历史图片缓存继续按 Session 管理结果和对象 URL;Host 不增加图片字节缓存。
该规则缩小了 [Session observation](2026-08-25-session-observations-and-projection-owned-client-state.zh.md) 与[历史传输激活策略](2026-08-18-session-history-and-event-transport.zh.md)涵盖的读取范围。[工作区文件读取](2026-09-05-workspace-files-service.zh.md)保留自己的文件系统授权。
## Alternatives considered
**保留 Session 到图片的 Map 或 projection。** 索引可以消除重复扫描,但保留了产品不需要的访问限制,并增加派生、生命周期和失效处理。
**签发图片签名票据。** 票据为同一项不需要的 Session 关联限制增加签发和验证状态。
**只优化 owner 的读取。** 这会让不同身份使用不同的图片访问规则,并让获准调用的非 owner 继续承担扫描成本,没有相应产品需求。
## Consequences
调用方知道有效图片引用,且有权为请求中的 Session 资源调用该接口,就可以跨 Session 读取对象。本地 ID 是规范化字节的 SHA-256。对于准入时原样保留的已知 PNG、JPEG 或 WebP 字节,调用方可以计算 ID,取得格式、字节数和尺寸,并通过获准的读取请求探测对象是否存在。这些必需的引用字段不一定来自 Session 日志。
图片隔离需要独立 Host 实例及各自的 `DSH_HOME` 目录。随附组合在每个 Host 中使用一个附件存储,不会按 Session 选择存储。身份认证、Gateway 操作与资源检查、固定存储路径、摘要校验和明确失败仍是必需的。
图片读取不再依赖历史长度或 Session 物化。文件读取、完整性校验、编码和传输仍有耗时;本次改动不说明上传或模型推理延迟已得到改善。已有 Session 数据和 fork 引用无需迁移。
## Verification
附件读取不得查询或遍历 Session 历史。验证必须区分获准的跨 Session 图片读取与被 Gateway 拒绝的调用,并覆盖正常引用、无效 ID、固有元数据不符、可选显示字段原样保留、缺失和损坏的对象、旧历史页以及 fork 继承图片。性能证据必须区分历史扫描、存储操作和传输,不能把用户反馈的全部延迟归因于扫描。
诊断脚本是 [`image-read.perf.ts`](../../../../packages/api/session-controller/tests/image-read.perf.ts),通过配套的 [tsdown 配置](../../../../packages/api/session-controller/tests/image-read.perf.config.ts)编译。基线 worker 使用改动前的控制器与 `{ sessionId, attachmentId: ref.attachmentId }`;候选 worker 使用当前控制器与 `{ sessionId, attachment: ref }`。两者使用相同图片 fixture、工作量和输出校验,并通过同一套已构建的 Local store 执行 `readImage(ref)` 校验。在候选检出目录的根目录编译并运行:
```sh
pnpm exec tsdown --config-loader native --config packages/api/session-controller/tests/image-read.perf.config.ts
(cd packages/api/session-controller && node --expose-gc .dsh-build/image-read/image-read.perf.js --expect-no-history)
```
运行单独编译的基线 worker 时不带 `--expect-no-history`;诊断请求必须匹配基线控制器仅接收 ID 的请求字段。基线负对照加上 `--sample typical --expect-no-history`,该实现会查询和遍历历史,因此负对照必须失败。父进程为每种工作量运行五个新子进程,每个子进程使用已加载的 Session,并对每张图片执行第一次未缓存读取。图片是确定性合成的 1024 × 768 PNG;两种工作量分别为 120 轮、960 个事件、8 张图片,以及 2,000 轮、16,000 个事件、32 张图片。fixture 写入可能已经预热操作系统的文件缓存。
`controllerMs` 覆盖从直接调用控制器到返回 base64 的时间。`storeMs` 包含文件 I/O、SHA-256 和文件头校验;`snapshotMs` 单独测量取得历史快照的时间。`scanAndDispatchMs` 是进入存储前的时间减去 `snapshotMs`,因此也包含分派开销,不是独立的扫描计时。JSON 序列化和本机回环 HTTP 传输使用保留的响应单独测量。`requestJsonBytes` 与 `idOnlyRequestJsonBytes` 比较序列化后的请求长度,不测量请求传输时间。冷 Session 恢复、Gateway 处理、浏览器渲染、远端网络延迟、上传和模型推理均不在测量范围内。PR #7021 记录 worker 修订,以及在这些限制下测得的修改前后结果。
内存端点在 fixture 准备完成后,以及所有图片响应完成后执行 GC。第二个端点仍保留 Session、已准入的图片引用和每个 base64 响应。这两个保留内存端点包含准备阶段拥有的对象,峰值 RSS 则从进程启动累计,包含 fixture 生成。它们不单独测量图片请求内存,也不规定保留内存预算。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-10-25-cua-bundle-id-consent.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-25-cua-bundle-id-consent.md
/agent-note-macos-consent-shared-by-bundle-identifier:
en: 41cd1b8e2629e049
zh: f1bcef434b6d247f
/agent-note-macos-consent-shared-by-bundle-identifier/problem:
en: bb387fc89c1c578c
zh: 947456baea45cc95
/agent-note-macos-consent-shared-by-bundle-identifier/decision:
en: 7b1bbab1f95b7610
zh: 434e7a3fba81174b
/agent-note-macos-consent-shared-by-bundle-identifier/alternatives-considered:
en: 637b1fd2bafb1b28
zh: 06d882818ffaf800
/agent-note-macos-consent-shared-by-bundle-identifier/consequences:
en: 1af6d29a57ff86e2
zh: 32517607b2fc935f
@@ -0,0 +1,33 @@
# Agent Note: macOS consent shared by bundle identifier
Status: implemented
English | [中文](2026-10-25-cua-bundle-id-consent.zh.md)
## Problem
Users who install multiple versions of one application want one permission decision for that software. Executable paths split those decisions, and signing checks exclude unsigned development applications from saved access.
## Decision
macOS application consent uses the exact, case-sensitive native bundle identifier. The helper hashes `macos:bundle-id:` followed by that identifier into `CuaApplicationId`. When a bundle identifier exists, installation paths, versions and signatures do not distinguish grants. Otherwise, the helper hashes `macos:executable-path:` followed by the canonical executable path. Both identities support saved access; path identities survive restart and in-place updates, while a different path requires a new decision. Conversation decisions and saved grants retain the scopes and revocation behavior of [profile consent storage](2026-10-19-cua-profile-consent-storage.md).
This supersedes the executable/signature identity choice in [application consent](2026-09-26-cua-application-consent.md); that note still owns enforcement and human decisions. The running process path comes from the operating system. A valid runtime bundle identifier does not depend on path-query success. Missing paths omit optional grant metadata; they never substitute a cached catalog path. When both bundle identity and process path are unavailable, consent fails with the path query cause. Process identity must still be verified, and any available process path must match the selected target. Missing catalog path metadata does not block consent when the process path is available. If the runtime bundle identifier is unavailable, a reported application bundle can supply it only when its main executable matches the process path; otherwise the executable path identifies the grant. Native process, executable-location and window checks continue to bind each handle to its selected target. Launch checks reread the bundle identifier and executable path from disk; they do not fingerprint executable content. Replacing bytes at the same path while retaining the identifier or path identity therefore retains consent, including during an approval wait.
The identity prefixes separate new grants from old path/signature, process-instance and executable-content digests. Old grants remain removable but do not grant access to new bundle identities; users decide again before permission covers other installations.
Apple’s [PPPC configuration](https://support.apple.com/guide/deployment/privacy-preferences-policy-control-payload-dep38df53c2a/web) supports bundle-ID or path selectors and separately requires a code-signing requirement. [TN3127](https://developer.apple.com/documentation/technotes/tn3127-inside-code-signing-requirements) explains that designated requirements track code identity across versions, while unsigned and ad-hoc code cannot provide the same stability. DSH adopts the selector alternatives for application management without requiring publisher authentication.
## Alternatives considered
**Bundle identifier and path.** This distinguishes installed copies but requires separate decisions for the multiple versions the user wants to authorize together.
**Bundle identifiers only.** Missing identifiers would exclude otherwise usable applications from saved access. Canonical executable paths supply a stable fallback without using a PID or content hash.
**Verified signing identity.** This distinguishes publishers but denies saved access when signing is absent or cannot be verified. Publisher authentication is outside this application-management policy.
## Consequences
Another program declaring the same bundle identifier or replacing an executable at its approved fallback path inherits consent, including a program created or changed through separately authorized model tools. The worst consequence is observing or controlling an application that the user did not approve separately, within its available data and capabilities. The model cannot supply the authorization identity through the CUA request; the native helper reads it from the selected application. Different bundle identifiers require different decisions, even when users consider them versions of one product.
Revocation applies to every installation sharing the identifier. Tests exercise unsigned copies, different identifiers, missing identifiers with persistent path consent, process restarts, symlink aliases, pending and running identity agreement, shared handle revocation and refusal to widen old grants.
@@ -0,0 +1,33 @@
# Agent Note: 按 Bundle ID 共用 macOS 应用授权
Status: implemented
[English](2026-10-25-cua-bundle-id-consent.md) | 中文
## 问题
用户安装同一应用的多个版本时,希望对这个软件只做一次权限决定。可执行文件路径会拆分这些决定,签名检查也会让未签名的开发版应用无法保存长期授权。
## 决策
macOS 应用授权使用原生应用提供的、区分大小写的完整 Bundle ID。helper 将 `macos:bundle-id:` 和该标识连接后计算摘要,生成 `CuaApplicationId`。有 Bundle ID 时,安装路径、版本和签名不区分授权。否则,helper 对 `macos:executable-path:` 与规范化可执行路径计算摘要。两种身份都支持长期许可;路径身份在重启和原地更新后保持不变,另一个路径需要新的决定。会话决定和长期许可保留[profile 授权存储](2026-10-19-cua-profile-consent-storage.zh.md)规定的范围和撤销行为。
本决策取代[应用授权](2026-09-26-cua-application-consent.zh.md)中的可执行文件和签名身份选择,原记录仍负责执行检查与用户决定。运行进程的可执行路径由操作系统提供。有效的运行时 Bundle ID 不依赖路径查询成功。无法取得路径时省略授权记录中的可选路径信息,不用缓存的应用目录路径代替。Bundle ID 和实际路径均不可用时,授权失败并报告路径查询原因。进程身份仍须验证,可取得的实际路径仍须与所选目标一致。只要能取得实际进程路径,应用目录信息中缺少路径不会阻止授权。运行时无法取得 Bundle ID 时,仅在其报告的应用 bundle 主可执行文件与进程路径一致时读取该标识,否则按可执行路径识别授权。原生进程、可执行文件位置和窗口检查继续把每个句柄绑定到所选目标。启动检查从磁盘重新读取 Bundle ID 和可执行路径,但不计算可执行内容指纹。因此,在相同路径下替换内容且保留相同标识或路径身份时,许可仍会沿用,包括等待用户批准期间的替换。
身份前缀将新授权与旧的路径和签名、进程实例、可执行内容摘要分开。旧授权仍可撤销,但不能授予新 Bundle ID 身份访问权限;许可覆盖其他安装副本前,需要用户重新决定。
Apple 的 [PPPC 配置](https://support.apple.com/guide/deployment/privacy-preferences-policy-control-payload-dep38df53c2a/web)支持 Bundle ID 或路径选择条件,同时另行要求代码签名条件。[TN3127](https://developer.apple.com/documentation/technotes/tn3127-inside-code-signing-requirements)说明了指定要求如何跨版本识别代码,以及未签名和临时签名代码无法提供同等稳定性。DSH 采用这两种选择条件管理应用,不要求验证发布者身份。
## 考虑过的替代方案
**Bundle ID 加路径。** 可以区分安装副本,但用户希望共同授权的多个版本仍需分别确认。
**仅使用 Bundle ID。** 缺少标识会让本可操作的应用无法获得长期许可。规范化可执行路径提供稳定的后备标识,无须使用进程号或内容摘要。
**验证签名身份。** 可以区分发布者,但没有签名或验签失败时无法保存长期授权。发布者身份验证不属于本项应用管理规则。
## 后果
其他程序声明相同 Bundle ID,或替换路径授权对应的可执行文件时,会继承许可,包括通过其他已授权模型工具创建或修改的程序。最坏后果是在应用已有数据和能力范围内,读取或控制用户未单独批准的程序。模型不能在 CUA 请求中提交授权身份,该身份由原生 helper 从实际选中的应用读取。不同 Bundle ID 仍需分别授权,即使用户将它们视为同一产品的不同版本。
撤销作用于同一标识的所有安装副本。测试覆盖未签名副本、不同标识、缺少标识时的持久路径许可、进程重启、符号链接、启动前后身份一致、多个句柄共同撤销,以及不扩大旧授权。
@@ -0,0 +1,37 @@
# Bilingual-pair consistency record for 2026-10-21-floating-window-edge-recovery.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-10-21-floating-window-edge-recovery.md
/agent-note-spring-based-edge-recovery-for-floating-dock-panels:
en: 73438e22c1bef8d3
zh: 5f817eb06259f8ef
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/problem:
en: c3b007f5cce80d8b
zh: c08b07f7e71eaa5f
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision:
en: f88f165ca80a57b8
zh: 98559f2239b03445
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/legal-region-and-displayed-position:
en: 6dea90dc406eacf5
zh: 6ecae0fdad78c855
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/drag-with-resistance:
en: 5214241925b52bc3
zh: bbd66dc72c03f960
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/release-and-spring:
en: ba2b5a3b4923d585
zh: 99544462a464ac50
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/reduced-motion:
en: 7e29bf1c45b5386d
zh: c913a2ce6d1722d1
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/decision/change-scope:
en: 6459103379aefe41
zh: 501dee08a977b6a0
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/testing:
en: da3b2b6781aa99f3
zh: 37e49fa22f72fb84
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/alternatives-considered:
en: 3d901f0f5e270e29
zh: c1fb89b567ea3c70
/agent-note-spring-based-edge-recovery-for-floating-dock-panels/consequences:
en: 360bd69c918f23fe
zh: 48642fd59ad3279b
@@ -0,0 +1,106 @@
# Agent Note: Spring-based edge recovery for floating dock panels
Status: implemented
English | [中文](2026-10-21-floating-window-edge-recovery.zh.md)
## Problem
The dock kit's floating panels are the client's floating windows. `FloatLayer` and the retained `DockLayout` renderer draw them in viewport coordinates through one shared gesture hook, `useFloatGestures`, and the right Sidebar embeds them, so the same panels run in the Web client and inside the Desktop window. Their drag followed the pointer one to one with only a top floor (`--dsh-dockkit-float-top`, which keeps the header below the Windows caption). A panel could therefore be dragged past the left, right or bottom edge until its header was out of reach; a viewport that shrank left a panel outside it; and the creation cascade could place a new panel outside a small viewport. The required behavior is that a panel pushed past an edge visibly resists, and on release is pulled back inside with spring physics instead of being stopped by a wall or left outside.
The reference implementation examined, Claude Desktop, has no portable edge-recovery rule: its Electron fallback corrects an off-screen window once, without animation, on the right and bottom edges only. The behavior had to be designed, not ported.
The change keeps these obligations: a panel header is always reachable; one gesture still records at most one history entry; reduced motion is honored; the persisted Sidebar layout format and every embedder stay unchanged; and the motion is deterministic enough to test without a real browser clock.
## Decision
The behavior lives entirely in `packages/client/ui-dockkit`, inside `useFloatGestures` and the pure engine helpers it calls. Both float renderers take their rectangles from that hook through `rectOf`, so Web and Desktop share the behavior, and no embedder, shell or persisted format changed. The rule extends the floating panels of [right Sidebar docking](2026-09-04-right-sidebar-docking-infrastructure.md) and the fixed-position floating frames of the [retained tab layout](../architecture/2026-09-20-sidebar-retained-tab-layout.md); it supersedes neither note.
### Legal region and displayed position
The legal region of a panel is the viewport (`window.innerWidth` by `window.innerHeight`) with the existing top floor: the Windows caption height plus 20 px when `data-windows-titlebar` is set (20 px in native fullscreen), otherwise 0. `floatBounds` reads only these values and the root's attributes, so starting a gesture forces no layout. `legalFloatRect` projects a rectangle into the region per axis; when a panel is wider or taller than the region it is drawn at the region's size on that axis, so its header controls and its resize corner stay on screen; the stored size is unchanged.
A panel draws at its stored rectangle projected into the viewport. The stored rectangle is never rewritten for the viewport: a shrinking window pushes the panel in without recording an operation, and a growing window returns it toward its stored position. The hook re-reads the bounds at every press and on every window `resize` event, and a gesture in progress uses the new bounds. Persisted layouts that hold off-screen rectangles display inside the viewport without migration.
At rest a panel publishes its rectangle to the `.float` rule as CSS variables through `floatStyle`, and the rule clamps its position and size into the viewport (`100vw` by `100dvh`, which follows `window.innerHeight` as the hook does) and below the caption floor once more; an oversized panel takes the viewport's size there as it does in `legalFloatRect`. A bounds reading the hook has not refreshed, such as one taken before a fullscreen change settles, therefore still leaves the panel inside. A gesture or a return writes its position and size inline, outside the clamp.
### Drag with resistance
A move computes the desired rectangle from the gesture's start rectangle and the pointer travel, then `resistedRect` splits it per axis into the legal projection and the overflow `o` beyond it and draws it at `legal + sign(o) * K * |o| / (K + |o|)` with `K = FLOAT_RESISTANCE = 120` px. The mapping applies on all four edges, including above the top floor, is continuous, has slope 1 at the edge, and approaches `K`:
| pointer overflow (px) | panel displacement past the edge (px) | share of the overflow |
|---|---|---|
| 10 | 9.2 | 92.3% |
| 40 | 30.0 | 75.0% |
| 120 | 60.0 | 50.0% |
| 400 | 92.3 | 23.1% |
A resize clamps the bottom-right corner to the region through `boundedResize` and keeps `FLOAT_MIN_SIZE`; resizing has no resistance, because a corner that lags the pointer reads as a broken handle.
### Release and spring
A release records the legal rectangle: `moveFloat` or `resizeFloat` when it differs from the legal rectangle at the press, otherwise only the raise a click records. A click on a panel drawn projected therefore keeps its stored rectangle. A move or resize therefore records only legal rectangles, and undo restores the pre-gesture position in one step. Panel creation (the drop rectangle of `floatTab` and the cascade) can still store a rectangle outside the viewport; the projection draws it inside. When the panel was drawn outside the legal region, the hook keeps a preview and springs it from where it was drawn to the recorded rectangle, then clears the preview. A release inside the region animates nothing.
The spring in `engine/spring.ts` is underdamped, because its bounce goes inward and is always legal: response 0.32 s and damping ratio 0.72. An overflowing axis starts with the velocity of the drawn panel over the last 100 ms of the drag, so the speed is continuous across the release; it is capped at `SPRING_MAX_VELOCITY` (1500 px/s), and `launchVelocity` caps its outward part at `omega0 * (K - d)` for a drawn overflow `d`. A fling past the edge travels further before it turns back, and because the spring carries an offset `d` with speed `v` at most `d + 0.46 * v / omega0` from its target, the whole return stays within `K` of the edge. An axis that did not overflow keeps still. Per axis the update is:
```
a = -omega0^2 * (x - target) - 2 * zeta * omega0 * v
v = v + a * h
x = x + v * h
```
`stepSpring` integrates in equal substeps of at most `h = 1/480 s`, so the motion does not depend on the frame rate. One `requestAnimationFrame` loop in the hook clamps a frame to 64 ms, ends at the target when a frame gap exceeds 250 ms or 900 ms have passed, and otherwise stops when each axis is within 1 px of the target and slower than 60 px/s. From rest, a 200 px overflow settles in 367 ms with an inward overshoot within one percentage point of the analytic bound `exp(-pi * zeta / sqrt(1 - zeta^2)) = 3.8%`. The integrator is pure and takes `dt`, so the engine keeps its rule of reading no clock.
A press on the grip or the corner during a return cancels it and picks the panel up where it is drawn. A move does so through `unresistedRect`: it inverts the resistance, so zero pointer travel draws the same rectangle. A resize keeps the drawn origin and caps only the corner by the viewport; its release records the legal rectangle and springs the origin inside, as does a resize whose viewport shrank past its origin. Either way a release in place resumes the return without recording a second operation. One hook runs at most one return. A window resize ends a running return at its recorded rectangle, a press on another panel ends it at its target, a change of the panel's record that does not project to the target (an undo, a dock, a close) ends it at the new record on the next frame, and unmounting cancels the pending frame.
### Reduced motion
When `matchMedia('(prefers-reduced-motion: reduce)')` matches, a move clamps to the legal region with no resistance, and release records the legal rectangle with no animation. Environments without `matchMedia` report no preference. The rule only removes motion; it never removes the legality correction.
### Change scope
The change touches one package, `@deepseek-ai/dsh-client-ui-dockkit`, and leaves its exports and `DockIntents` unchanged; the `TabRenderer` contract now states when the kit reuses a body.
| File | Change |
|---|---|
| `packages/client/ui-dockkit/src/engine/geometry.ts` | `FloatBounds`, `FLOAT_RESISTANCE`, `legalFloatRect`, `resistedRect`, `unresistedRect`, `boundedResize` |
| `packages/client/ui-dockkit/src/engine/spring.ts` | the pure spring integrator, its rest predicate `springSettled`, `launchVelocity` and its timing limits |
| `packages/client/ui-dockkit/src/components/FloatLayer.tsx` | `useFloatGestures`: viewport projection, resistance, release spring, drawn-velocity sampling, reduced motion, frame loop and cancellation; `rectOf` and `floatStyle` for both renderers |
| `packages/client/ui-dockkit/src/components/TabLayout.tsx` | draws the hook's displayed rectangle through `floatStyle` |
| `packages/client/ui-dockkit/src/components/TabBody.tsx` | the memoized body every layout (`FloatLayer`, `TabLayout`, `TabPanel`) draws |
| `packages/client/ui-dockkit/src/contract/adapter.ts` | when `TabRenderer` is called again |
| `packages/client/ui-dockkit/src/components/dockkit.module.css` | the resting clamp of position and size on `.float` |
| `packages/client/ui-dockkit/README.md` pair | the edge rule beside the float renderer description |
| `apps/web/tests/sidebar-right.e2e.ts` | a browser case for the resistance and the return |
`ui-sidebar-right` and its persisted layout schema, the `apps/web` source, `apps/desktop`, the shared primitives and the theme are untouched. No dependency was added.
## Testing
`tests/float-bounds.client.spec.ts` covers the projection (inside, each edge, corner, the top floor, an oversized panel), the resistance (the table values, slope 1 at the edge, monotone growth bounded by `K`, independent axes), its inverse and its cap, the bounded resize, and the legal size kept by the resistance and its inverse. `tests/spring.client.spec.ts` covers settling inside the deadline, the overshoot bound, frame-rate independence at 30, 60 and 120 Hz, the effect of release velocity, determinism, and the launch cap keeping every return within `K`. `tests/app-region-styles.client.spec.ts` pins the resting clamp in the stylesheet.
`tests/float-recovery.client.spec.tsx` renders `FloatLayer` over a live controller with hand-driven frames and clock: the resisted preview past an edge, exactly one legal `moveFloat` per release and the spring to it with an inward overshoot, undo in one step, fling against slow push, a fast fling staying within `K`, a drag above the top floor, no animation for a release inside, a push that ends at the stored position, a press mid-return picking the panel up without a jump, the stall snap, the deadline, a body not re-rendered through a drag and its return but re-rendered for a new renderer, a corner press during a return picking the panel up where it is drawn and a resize from there springing in, a resize whose viewport shrank past its origin recording a legal rectangle, with no animation under reduced motion, the 20 px floor on a Windows root without a published caption height, a return yielding to an undo, a close and a press on another panel, unmount cancellation, both reduced-motion answers, the viewport projection on shrink and growth without any intent, a click on a projected panel recording nothing, a window resize during a gesture bounding its release, a resize ending a return, and an off-screen stored rectangle drawn inside. `tests/tab-layout.client.spec.tsx` adds that a float drag re-renders no docked or floating body until the renderer changes, and `components.client.spec.tsx` the same for a `DockSurface` divider drag. The existing `FloatLayer` and `TabLayout` specs still pass with their position assertions read from the resting variables, including the rule that starting a gesture forces no layout read; every changed source file is fully covered. `apps/web/tests/sidebar-right.e2e.ts` drags a Sidebar float past the right and bottom edges in Chromium, checks that the drawn panel stays within 120 px beyond them, waits for the release to settle flush against both edges, then publishes a resting rectangle far outside and larger than the viewport and checks that the stylesheet alone draws it exactly over the viewport.
## Alternatives considered
**Hard clamp at the edge.** Stopping the panel at the viewport edge is the cheapest correct rule, but it feels like hitting a wall and gives no sense of the boundary before contact. It remains as the reduced-motion path.
**Clamp during the drag and rebound on release.** Clamping the drag at the edge and converting the outward pointer speed into an inward bounce keeps every frame inside the viewport. It hides how far the user pushed, so the bounce has no visible cause; the resistance shows the push and still bounds the overflow at 120 px.
**Eased tween on release.** A fixed 240-300 ms ease-out from the released position is predictable, but it carries no velocity, so a fling and a slow push return identically, and a press during it either jumps or restarts. The spring keeps velocity continuous and is interruptible.
**Store the off-screen position and correct it later.** Recording the released rectangle and fixing it on the next render would persist off-screen positions and make undo restore them. Recording the legal rectangle keeps one history entry per gesture with a legal value.
**Rewrite stored rectangles when the viewport shrinks.** Moving panels through operations on resize would add history entries the user never made and change persisted layouts on every window resize. Projecting at render achieves the visible result without either, at the cost of the elastic return described below.
**Native always-on-top OS window.** A real Electron floating window could float above other applications, but only on Desktop; the Web client cannot do it at all, and native frameless dragging gives no per-frame control, so the resistance would be impossible and the spring could only start after release. It is a separate product decision with its own window, IPC and platform work, and this decision does not preclude it.
**Animation library dependency.** A spring library would replace a pure integrator of a few dozen lines and its tests with a new dependency in a statically linked package. The integrator also has to be clock-free for the engine's deterministic tests.
**A shared primitive in `ui-primitives`.** Placing the hook in the primitives package would widen the change to a second package with no second consumer. It can move there when another floating surface needs it.
## Consequences
Floating panels can no longer be lost off screen, in either client, and a push past an edge reads as a pull back rather than a wall. History, persistence and every embedder are unaffected, and the motion is covered by deterministic tests instead of manual checks.
A drag and the spring update the preview through React state, so the layout re-renders on every frame, for up to 900 ms after release as well. Every layout draws tab bodies through `TabBody`, which is memoized on the renderer and the tab record, so such a frame re-renders only the panel frames and headers (the header still calls `renderTabTitle`), never the tab bodies; writing a transform on the panel element directly is the fallback if the remaining cost measures as a problem. A panel pushed in by a shrinking window returns toward its stored position when the window grows, which a user who expects it to stay where it was pushed may find surprising. Content inside a panel, such as a webview, can observe up to 900 ms of motion after release. The constants are tuned for a mouse or trackpad; touch input works through the same pointer events but remains untuned.
@@ -0,0 +1,106 @@
# Agent Note: 悬浮停靠面板的弹簧式边界收回
Status: implemented
[English](2026-10-21-floating-window-edge-recovery.md) | 中文
## 问题
dock kit 的悬浮面板就是客户端里的悬浮窗。`FloatLayer` 与保留式 `DockLayout` 渲染器通过同一个手势 hook `useFloatGestures` 以视口坐标绘制它们,右侧 Sidebar 嵌入了它们,因此同一套面板既运行在 Web 客户端中,也运行在 Desktop 窗口内。它们的拖拽过去一比一跟随指针,只有一个顶部下限(`--dsh-dockkit-float-top`,让标题栏保持在 Windows 标题栏之下)。因此面板可以被拖过左、右或下边界,直到标题栏够不着;视口缩小会把面板留在外面;新建面板的级联位置也可能落在小视口之外。期望行为是:面板被推过边界时可见地受到阻力,松手后以弹簧物理被拉回视口内,而不是像撞墙一样被挡住或被留在外面。
所考察的参考实现 Claude Desktop 没有可移植的边界收回规则:它的 Electron 回退只对屏幕外窗口做一次无动画修正,且只修正右边界和下边界。该行为必须被设计,而不是移植。
变更维持以下义务:面板标题栏始终可达;一个手势仍然最多记录一条历史;遵循减弱动态效果;Sidebar 的持久化布局格式与所有嵌入方保持不变;运动足够确定,无需真实浏览器时钟即可测试。
## 决定
该行为完全位于 `packages/client/ui-dockkit` 内,在 `useFloatGestures` 及其调用的纯 engine 辅助函数中实现。两个悬浮渲染器都通过 `rectOf` 从该 hook 取得矩形,因此 Web 与 Desktop 共享该行为,任何嵌入方、壳或持久化格式都没有改变。该规则扩展了 [右侧 Sidebar 停靠](2026-09-04-right-sidebar-docking-infrastructure.zh.md) 的悬浮面板与 [保留式标签布局](../architecture/2026-09-20-sidebar-retained-tab-layout.zh.md) 的固定定位悬浮框,不取代其中任何一篇。
### 合法区域与显示位置
面板的合法区域是视口(`window.innerWidth` × `window.innerHeight`)加上既有的顶部下限:设置了 `data-windows-titlebar` 时为 Windows 标题栏高度加 20 px(原生全屏时为 20 px),否则为 0。`floatBounds` 只读取这些值和根元素属性,因此开始手势不会触发布局。`legalFloatRect` 逐轴把矩形投影进该区域;面板比区域更宽或更高时,在该轴上按区域尺寸绘制,使标题栏控件和缩放角留在屏幕上;存储的尺寸不变。
面板绘制在其存储矩形投影到视口后的位置。存储矩形从不因视口而被改写:窗口缩小时面板被推入且不记录操作,窗口变大时面板朝存储位置回移。hook 在每次按下和每次窗口 `resize` 事件时重新读取区域,进行中的手势使用新区域。包含屏幕外矩形的持久化布局无需迁移即在视口内显示。
静止时面板通过 `floatStyle` 把矩形以 CSS 变量发布给 `.float` 规则,该规则再次把它的位置和尺寸钳制在视口(`100vw` × `100dvh`;`dvh` 与 hook 读取的 `window.innerHeight` 一致)内并保持在标题栏下限之下;超尺寸面板在这里同样按视口尺寸绘制,与 `legalFloatRect` 一致。因此即使 hook 读到的区域尚未刷新(例如全屏切换完成前读取的值),面板仍在视口内。手势或回弹把位置和尺寸写在行内样式中,不受该钳制。
### 带阻力的拖拽
移动时由手势起始矩形和指针位移计算期望矩形,然后 `resistedRect` 逐轴把它拆分为合法投影与超出它的溢出量 `o`,并绘制在 `legal + sign(o) * K * |o| / (K + |o|)`,其中 `K = FLOAT_RESISTANCE = 120` px。该映射作用于全部四条边,包括顶部下限之上,连续、在边界处斜率为 1、渐近于 `K`:
| 指针溢出(px) | 面板越过边界的位移(px) | 占溢出的比例 |
|---|---|---|
| 10 | 9.2 | 92.3% |
| 40 | 30.0 | 75.0% |
| 120 | 60.0 | 50.0% |
| 400 | 92.3 | 23.1% |
缩放通过 `boundedResize` 把右下角钳制在区域内并保持 `FLOAT_MIN_SIZE`;缩放不加阻力,因为落后于指针的角看起来像坏掉的手柄。
### 松手与弹簧
松手时记录合法矩形:与按下时的合法矩形不同时记录 `moveFloat` 或 `resizeFloat`,否则只记录点击会记录的提升。因此单击以投影绘制的面板会保留其存储矩形。因此移动或缩放只记录合法矩形,撤销一步即可恢复手势前的位置。创建面板(`floatTab` 的落点矩形与级联)仍可能存储视口外的矩形,由投影把它绘制在视口内。若面板绘制在合法区域之外,hook 保留预览,用弹簧把它从绘制位置带到记录的矩形,然后清除预览。在区域内松手不播放动画。
`engine/spring.ts` 中的弹簧是欠阻尼的,因为它的回弹朝向内侧,始终合法:响应时间 0.32 s、阻尼比 0.72。溢出的轴以拖拽最后 100 ms 内绘制面板的速度起步,因此速度在松手前后连续;该速度上限为 `SPRING_MAX_VELOCITY`(1500 px/s),且对绘制溢出量 `d`,`launchVelocity` 把其向外分量限制在 `omega0 * (K - d)` 以内。甩过边界的面板会先走得更远再折返;由于弹簧从偏移 `d`、速度 `v` 出发时距目标至多 `d + 0.46 * v / omega0`,整条回弹轨迹都不超出边界 `K`。没有溢出的轴保持不动。每轴更新为:
```
a = -omega0^2 * (x - target) - 2 * zeta * omega0 * v
v = v + a * h
x = x + v * h
```
`stepSpring` 以等长且不超过 `h = 1/480 s` 的子步积分,因此运动与帧率无关。hook 中唯一的 `requestAnimationFrame` 循环把单帧钳制到 64 ms,帧间隔超过 250 ms 或已过 900 ms 时直接停在目标,否则在每轴距目标 1 px 内且慢于 60 px/s 时停止。从静止开始,200 px 溢出在 367 ms 内稳定,向内过冲与解析上限 `exp(-pi * zeta / sqrt(1 - zeta^2)) = 3.8%` 相差不超过一个百分点。积分器是纯函数并接收 `dt`,因此 engine 保持不读取时钟的规则。
回弹期间按下抓手或右下角会取消回弹,并从绘制位置接住面板。移动通过 `unresistedRect` 做到这一点:它反演阻力,因此零指针位移绘制同一矩形。缩放保留绘制时的原点,只用视口约束右下角;松手时记录合法矩形并用弹簧把原点收回视口,手势中视口缩到原点以内的缩放也是如此。两种情况下原地松手都会恢复回弹且不记录第二次操作。一个 hook 最多运行一个回弹。窗口缩放会让进行中的回弹停在记录的矩形;按下另一个面板会让它停在目标;面板记录的变化若不再投影到目标(撤销、停靠、关闭),会在下一帧让它停在新记录;卸载会取消待处理的帧。
### 减弱动态效果
`matchMedia('(prefers-reduced-motion: reduce)')` 匹配时,移动钳制在合法区域内且无阻力,松手时记录合法矩形且不播放动画。没有 `matchMedia` 的环境视为无偏好。该规则只移除运动,从不移除合法性修正。
### 改动范围
变更只涉及一个包 `@deepseek-ai/dsh-client-ui-dockkit`,其导出与 `DockIntents` 保持不变;`TabRenderer` 的约定写明了套件何时复用标签页内容。
| 文件 | 变更 |
|---|---|
| `packages/client/ui-dockkit/src/engine/geometry.ts` | `FloatBounds`、`FLOAT_RESISTANCE`、`legalFloatRect`、`resistedRect`、`unresistedRect`、`boundedResize` |
| `packages/client/ui-dockkit/src/engine/spring.ts` | 纯弹簧积分器、静止判定函数 `springSettled`、`launchVelocity` 与时间上限 |
| `packages/client/ui-dockkit/src/components/FloatLayer.tsx` | `useFloatGestures`:视口投影、阻力、松手弹簧、绘制速度采样、减弱动态效果、帧循环与取消;供两个渲染器使用的 `rectOf` 与 `floatStyle` |
| `packages/client/ui-dockkit/src/components/TabLayout.tsx` | 通过 `floatStyle` 绘制 hook 给出的显示矩形 |
| `packages/client/ui-dockkit/src/components/TabBody.tsx` | 各布局(`FloatLayer`、`TabLayout`、`TabPanel`)共用的 memo 化标签页内容 |
| `packages/client/ui-dockkit/src/contract/adapter.ts` | `TabRenderer` 何时被再次调用 |
| `packages/client/ui-dockkit/src/components/dockkit.module.css` | `.float` 上位置与尺寸的静止钳制 |
| `packages/client/ui-dockkit/README.md` 对 | 在悬浮渲染器说明旁补充边界规则 |
| `apps/web/tests/sidebar-right.e2e.ts` | 覆盖阻力与回弹的浏览器用例 |
`ui-sidebar-right` 及其持久化布局 schema、`apps/web` 源码、`apps/desktop`、共享基础组件与主题均未改动。没有新增依赖。
## 测试
`tests/float-bounds.client.spec.ts` 覆盖投影(内部、每条边、角、顶部下限、超尺寸面板)、阻力(表中数值、边界处斜率为 1、以 `K` 为上界的单调增长、各轴独立)、其反演与上限,受限缩放,以及阻力与其反演都保持合法尺寸。`tests/spring.client.spec.ts` 覆盖在截止时间内稳定、过冲上限、30/60/120 Hz 下与帧率无关、松手速度的作用、确定性,以及启动速度上限让每条回弹都不超出 `K`。`tests/app-region-styles.client.spec.ts` 固定样式表中的静止钳制。
`tests/float-recovery.client.spec.tsx` 在活的控制器上渲染 `FloatLayer`,帧与时钟由测试手动推进:越过边界时带阻力的预览、每次松手恰好一次合法的 `moveFloat` 以及带向内过冲的弹回、一步撤销、甩出与慢推的对比、快速甩出不超出 `K`、拖过顶部下限、区域内松手不播放动画、推到存储位置的手势、回弹中按下接住面板且不跳变、停顿直接跳转、截止时间、拖拽与回弹期间不重渲染标签页内容而换新渲染函数后重渲染、回弹中按下右下角从绘制位置接住面板、从那里缩放后弹回、手势中视口缩到缩放原点以内时记录合法矩形且减弱动态效果下不播放动画、未发布标题栏高度的 Windows 根元素仍保持 20 px 下限、回弹让位于撤销、关闭与按下另一个面板、卸载取消、两种减弱动态效果答复、视口缩小与变大时的投影且不调用任何 intent、单击投影面板不记录任何操作、手势中窗口缩放约束其松手结果、缩放结束回弹,以及屏幕外存储矩形在视口内绘制。`tests/tab-layout.client.spec.tsx` 新增:悬浮面板拖拽期间停靠与悬浮的标签页内容都不重渲染,直到渲染函数改变;`components.client.spec.tsx` 对 `DockSurface` 拖动分隔条做同样的检查。既有的 `FloatLayer` 与 `TabLayout` 测试在位置断言改为读取静止变量后通过,包括开始手势不做布局读取这一规则;每个改动的源文件都被完全覆盖。`apps/web/tests/sidebar-right.e2e.ts` 在 Chromium 中把 Sidebar 悬浮面板拖过右边界和下边界,检查绘制的面板越过两边均不超过 120 px,等待松手后面板贴合两条边静止,再发布一个远在视口外且大于视口的静止矩形,检查仅靠样式表就把它恰好绘制成覆盖整个视口。
## 考虑过的替代方案
**在边界处硬钳制。** 在视口边界停住面板是成本最低的正确规则,但手感像撞墙,接触之前也感觉不到边界。它保留为减弱动态效果的路径。
**拖拽中钳制、松手时回弹。** 在边界处钳制拖拽,并把向外的指针速度转换为向内的回弹,能让每一帧都留在视口内。但它隐藏了用户推了多远,回弹因此没有可见的起因;阻力显示了推动,同时把溢出限制在 120 px 内。
**松手后的缓动补间。** 从松手位置开始的固定 240–300 ms 缓出补间可预测,但不携带速度,因此甩出与慢推的返回完全相同,补间中按下要么跳变要么重启。弹簧保持速度连续且可打断。
**存储屏幕外位置并在之后修正。** 记录松手矩形、在下一次渲染时修正,会持久化屏幕外位置,并让撤销恢复它们。记录合法矩形则保持每个手势一条历史且值合法。
**视口缩小时改写存储矩形。** 在缩放时通过操作移动面板会增加用户从未做过的历史条目,并在每次窗口缩放时改变持久化布局。渲染时投影无需二者即可得到可见结果,代价是下文描述的弹性返回。
**原生始终置顶 OS 窗口。** 真正的 Electron 悬浮窗可以浮在其他应用之上,但只在 Desktop 上可行;Web 客户端完全无法做到,而且原生无边框拖拽不提供逐帧控制,因此阻力无法实现,弹簧只能在松手后启动。它是一个独立的产品决策,有自己的窗口、IPC 与平台工作,本决定不排斥它。
**动画库依赖。** 弹簧库会用一个静态链接包里的新依赖替换几十行的纯积分器及其测试。积分器还必须不依赖时钟,才能用于 engine 的确定性测试。
**放进 `ui-primitives` 的共享基础组件。** 把 hook 放进基础组件包会把改动扩大到第二个包,而没有第二个使用方。等另一个悬浮界面需要它时再迁移。
## 后果
悬浮面板在两个客户端中都不会再丢失到屏幕外,推过边界读起来是被拉回而不是撞墙。历史、持久化与所有嵌入方不受影响,运动由确定性测试而非手动检查覆盖。
拖拽与弹簧都通过 React state 更新预览,因此布局每帧都会重渲染,松手后最多还会持续 900 ms。各布局都通过 `TabBody` 绘制标签页内容,它以渲染函数和标签记录为键做了 memo,因此这样的一帧只重渲染面板框与标题栏(标题栏仍会调用 `renderTabTitle`),从不重渲染标签页内容;如果剩余成本经测量构成问题,退路是直接在面板元素上写 transform。被缩小窗口推入的面板会在窗口变大时朝存储位置回移,期望它留在被推到位置的用户可能会感到意外。面板内的内容(例如 webview)在松手后可能观察到最多 900 ms 的运动。常量针对鼠标或触控板调优;触控输入经由同样的 pointer 事件可用,但仍未调优。
@@ -9,8 +9,8 @@
en: e5c984fa32cc5e69
zh: 25d5742b2106d830
/agent-note-pr-artifact-builds-and-aggregate-typescript-checks/decision:
en: 8353d57b20ca01c3
zh: e0b74906846d759c
en: 2b047b7d8ffaaeb9
zh: 035e1a99cb0ffe84
/agent-note-pr-artifact-builds-and-aggregate-typescript-checks/alternatives-considered:
en: f61da066f9ddcd62
zh: 816fd6e0063017cd
@@ -20,7 +20,7 @@ The Python executable builder selects `build:artifacts` artifact compilation wit
PR artifact builds in CI invoke the root manifest's `build:artifacts`; a PR that edits these root manifest scripts activates the separate native-addon platform matrix, a trade-off [the build split](2026-10-11-build-artifacts-check-split.md) records. The vendor rehearsal and benchmark lanes invoke the internal build helpers directly.
Job inventory, runner selectors, and benchmark sample counts stay fixed; gate and worker ceilings do not increase. The two compatibility cases run one job at a time; both x64 Python runtime targets start after the keyless Python SDK job succeeds in CI Python. Four Linux lanes, one compatibility job, three Windows lanes, and the Python SDK job permit at most nine worker jobs initially. Once the SDK job finishes, those four Linux lanes, one compatibility job, and three Windows lanes run beside the two runtime targets, permitting at most ten. Each runtime caller's plan and wheel stages precede its target and each use one job. This permits runtime validation to overlap the Node 24.9 build within the original ten-job ceiling. Coverage partitions reuse compact file-cost metadata within their platform and runner pool. Parallel release packing uses pnpm's existing bounded scheduler; serial publication keeps family order.
Benchmark sample counts stay fixed. The Linux artifact consumers emit artifacts only; the aggregate test and script type checks belong to the master lanes, and lint plus duplication run in their own lane, which compiles package declarations because oxlint's type-aware rules read them, so a red lint no longer costs a rerun of the snapshot and artifact consumers. The two compatibility cases run one job at a time; both x64 Python runtime targets start after the keyless Python SDK job succeeds in CI Python. Five Linux lanes, one compatibility job, three Windows lanes, and the Python SDK job permit at most eleven worker jobs initially. Once the SDK job finishes, those five Linux lanes, one compatibility job, and three Windows lanes run beside the two runtime targets, permitting at most eleven. Each runtime caller's plan and wheel stages precede its target and each use one job. This permits runtime validation to overlap the Node 24.9 build within the eleven-job ceiling. Coverage partitions reuse compact file-cost metadata within their platform and runner pool. Parallel release packing uses pnpm's existing bounded scheduler; serial publication keeps family order.
Each Node version runs the same eight source compatibility specs in one serial Vitest invocation. Both file parallelism and the CLI worker limit are fixed to one, and the gate sets `VITEST_MAX_WORKERS=1` because that environment variable overrides Vitest's CLI limit. Files retain fork isolation; the build-backed Node 24.9 lazy-search smoke keeps its separate build dependency. The original seven-spec paired samples preserve all 253 assertion outcomes and reduce startup-only median time from 11.52 to 8.69 seconds, without increasing owned descendant-process peak.
@@ -20,7 +20,7 @@ Python executable builder 在验证 runtime closure 后,通过 `--build-artifa
CI 的 PR 产物构建调用 root manifest 中的 `build:artifacts`;修改 root manifest 中这些 script 的 PR 会激活独立的 native-addon 平台矩阵,[构建拆分](2026-10-11-build-artifacts-check-split.zh.md)记录这一取舍。vendor 演练与 benchmark lane 直接调用内部 build helper。
job 清单、runner 选择和 benchmark sample 数量保持固定;gate 与 worker 上限不提高。两个 compatibility case 每次运行一个 job;两个 x64 Python runtime target 都在 CI Python 中于 keyless Python SDK job 成功后启动。四个 Linux lane、一个 compatibility job、三个 Windows lane 与 Python SDK job,初始最多占用九个 worker job。SDK job 完成后,这四个 Linux lane、一个 compatibility job 与三个 Windows lane 与两个 runtime target 并行,最多占用十个 job。每个 runtime 调用方的 plan 与 wheel 阶段先于其 target,各占一个 job。这允许 runtime 验证与 Node 24.9 构建重叠,同时保持原有十个 job 的上限。覆盖率分区在各自的平台和 runner pool 内复用精简的文件成本元数据。并行 release 打包使用 pnpm 现有的有界调度器;串行发布保持 family 顺序。
benchmark sample 数量保持固定。Linux 产物消费者只产出产物;聚合的 test 与 script 类型检查归 master lane;lint 与 duplication 单独占用一个 lane,该 lane 会先编译包声明(oxlint 的类型感知规则要读它们),因此 lint 变红不再让 snapshot 与 artifact 消费者整体重跑。两个 compatibility case 每次运行一个 job;两个 x64 Python runtime target 都在 CI Python 中于 keyless Python SDK job 成功后启动。五个 Linux lane、一个 compatibility job、三个 Windows lane 与 Python SDK job,初始最多占用十一个 worker job。SDK job 完成后,这五个 Linux lane、一个 compatibility job 与三个 Windows lane 与两个 runtime target 并行,最多占用十一个 job。每个 runtime 调用方的 plan 与 wheel 阶段先于其 target,各占一个 job。这允许 runtime 验证与 Node 24.9 构建重叠,同时保持十一个 job 的上限。覆盖率分区在各自的平台和 runner pool 内复用精简的文件成本元数据。并行 release 打包使用 pnpm 现有的有界调度器;串行发布保持 family 顺序。
每个 Node 版本在一次串行 Vitest 调用中运行相同的八个 source compatibility spec。文件并行和 CLI worker 上限均固定为一,gate 还设置 `VITEST_MAX_WORKERS=1`,因为该环境变量会覆盖 Vitest 的 CLI 上限。文件保持 fork 隔离;依赖构建的 Node 24.9 lazy-search smoke 保留独立的 build 依赖。原来七个 spec 的成对样本保持全部 253 个 assertion outcome,将启动开销比较的 median 从 11.52 秒降至 8.69 秒,且不增加所拥有 descendant process 的峰值。
@@ -12,17 +12,17 @@
en: 34e5bde1535a2bb1
zh: 559deb25b2ec50ba
/agent-note-domain-kv-storage-capability-seam-and-the-workspace-entity/proposal/dsh-storage-the-storage-hub:
en: 191afc01a150e4a0
zh: da3fbc33875a4f60
en: 5eb0b18c2adf5111
zh: 856ee7b1464b8bfc
/agent-note-domain-kv-storage-capability-seam-and-the-workspace-entity/proposal/dsh-storage-json:
en: a18ec1e534a5488b
zh: 2f5beb445e30554b
/agent-note-domain-kv-storage-capability-seam-and-the-workspace-entity/proposal/dsh-storage-sqlite:
en: 6a26dd7ef357db74
zh: 951b31136e2415f9
en: 1a4bebbbf52db7a2
zh: 425c32b0dc17b49e
/agent-note-domain-kv-storage-capability-seam-and-the-workspace-entity/proposal/dsh-domain-the-domain-data-form:
en: 2ee24f36cd93f7dd
zh: 45c83bd745de41f9
en: b99e07359dc78dc8
zh: 4af881d0b6d5b628
/agent-note-domain-kv-storage-capability-seam-and-the-workspace-entity/proposal/future-work-session-side-deletion-design-settled-not-implemented-this-phase:
en: a3824326587b6539
zh: 9736e3060bd57651
@@ -44,9 +44,9 @@ A backend is one **medium owner** (a file-tree root / one db file) exposing prim
The backend contract (asserted clause by clause by the shared conformance suite, one suite for both backends):
1. `open` creates when the medium holds nothing (lazy materialization allowed: may defer to the first write, but `loadAll` must immediately serve empty tables); loads when the medium exists.
2. A stored version ≠ descriptor.version → `StorageError('version-mismatch')`; no migration, no rebuild.
2. Unit-wide checks accept `descriptor.version` and the owner's `compatibleVersions`; other stamps reject with `StorageError('version-mismatch')`. Ordinary compatible reads preserve saved stamps and values. [Domain versioning](../../../../docs/subsystems/storage.md#domain-versioning) defines write stamping and JSON per-record exceptions.
3. Durability: after a write primitive resolves, a process crash followed by a re-open must observe the write in `loadAll`.
4. The backend does not promise write ordering within a unit — **the caller serializes**; the backend only guarantees each single call is atomic (JSON whole-file replace / SQLite single statement).
4. The backend does not promise write ordering within a unit — **the caller serializes**; whole-unit mutations atomically publish their data and current stamp (JSON whole-file replacement / SQLite transaction for batch deletion or advancing the stamp); per-record batches can be partially applied if interrupted before resolution.
5. `deleteRecord` is idempotent; `putRecord` overwrites.
6. Any string key / any JSON value is safe (keys never reach file paths, a structural property).
7. `close` is idempotent; any operation after close → `StorageError('closed')`.
@@ -88,8 +88,8 @@ CREATE TABLE IF NOT EXISTS "u_<unit>_<table>" (
key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT; -- value = record JSON document
```
- Unit versions live in `units` rows; a descriptor mismatch → `version-mismatch`. Row granularity is document-per-row, preserving precise per-key durable updates (the path left open for high-frequency point-update tables like the session sidecar); when query needs appear, JSON1 reads the value column directly.
- Write primitives are single statements and thus atomic; no cross-statement transactions needed (the domain layer has no cross-table transactions, see the out-of-scope list).
- Unit versions live in `units` rows; an unaccepted version rejects with `version-mismatch`. Row granularity is document-per-row, preserving precise per-key durable updates (the path left open for high-frequency point-update tables like the session sidecar); when query needs appear, JSON1 reads the value column directly.
- Current-version single-record writes use single statements. Batch deletes and the first mutation of an accepted older unit use one transaction; the first mutation commits its data and current stamp together. This does not add cross-table domain transactions.
### `dsh-domain`: the domain data form
@@ -117,6 +117,7 @@ export interface DomainTableSpec<K extends string, V> { readonly valueSchema: Zo
export interface DomainSpec {
readonly name: string // ^[a-z][a-z0-9_]*$
readonly version: number
readonly compatibleVersions?: readonly number[]
readonly global?: DomainGlobalSpec<unknown>
readonly tables: Record<string, DomainTableSpec<string, unknown>>
}
@@ -157,8 +158,8 @@ Rules:
- **Single-level mapping**: key → record, no nested tables; hierarchical needs use composite keys or fields inside the value. The two backends stay isomorphic as a result (one JSON object level ↔ one SQLite row).
- **Records are plain data**: immutable, directly JSON-serializable POJOs; values returned by `get`/`entries` must not be mutated in place (TypeScript readonly projection, no runtime freezing). Behavior-carrying domain objects belong to consumer packages.
- **Serialized writes**: one promise chain per domain; `put`/`delete`/`update`/`global.set` all queue on it; `update`'s fn runs on the chain, so concurrency cannot interleave. No active-record (pulling out a mutable object that auto-persists — uncontrollable persist timing, in conflict with the whole-unit atomic-rewrite model).
- **Version fails loud**: a stored version differing from the spec throws outright; no migration, no rebuild (the data is not regenerable; pre-release rejects old formats).
- **Serialized writes**: one promise chain per domain; `put`/`delete`/`deleteMany`/`update`/`global.set` all queue on it; `update`'s fn runs on the chain, so concurrency cannot interleave. No active-record (pulling out a mutable object that auto-persists — uncontrollable persist timing, in conflict with the whole-unit atomic-rewrite model).
- **Version compatibility**: the domain owner declares readable older versions through `compatibleVersions` and decodes historical values with its current schemas. Storage does not convert record values; [domain versioning](../../../../docs/subsystems/storage.md#domain-versioning) defines stamp publication and mixed-generation requirements.
- **Change events**: after each write's durability resolves, emit `domain/changed` (`@mode emit`), one per record, no old value (matching the repository's "new snapshot + operation discriminant" convention, template `goal/changed`); the payload `DomainChanged` is a put/deleted discriminated union — domain + table + key (both `''` for global changes) + operation, with the put branch carrying the new snapshot value and the deleted branch carrying none (`packages/storage/storage-domain/src/events.ts`). This is next phase's RPC push-frame event source. The error vocabulary is `DomainError`, codes: `already-open` / `facet-unsupported` / `invalid-record` (with `{ table, key }`) / `missing-key` / `closed`.
### Future work: session-side deletion (design settled, not implemented this phase)
@@ -44,9 +44,9 @@ host 侧唯一的持久化面是 session 事件日志(`packages/session/sessio
后端约定(共享约定测试逐条断言,两后端同套件):
1. `open` 对不存在的介质创建(懒物化允许:可延迟到首写,但 `loadAll` 立即可用返回空表);对已存在介质载入。
2. 介质上版本 ≠ descriptor.version → `StorageError('version-mismatch')`,不迁移不重建。
2. 单元级检查接受 `descriptor.version` 和拥有方声明的 `compatibleVersions`;其他版本戳以 `StorageError('version-mismatch')` 拒绝。普通兼容读取保留已存版本戳和值。[领域版本](../../../../docs/subsystems/storage.zh.md#domain-versioning)定义写入盖戳和 JSON 逐记录例外。
3. 持久性:写原语 resolve 后进程崩溃再 open,`loadAll` 必须反映该写入。
4. 后端不承诺 unit 内写并发序——**调用方负责串行**;后端只保证单次调用原子(JSON 整文件替换 / SQLite 单语句)。
4. 后端不承诺 unit 内写并发序——**调用方负责串行**;整单元修改原子发布其数据和当前版本戳(JSON 整文件替换 / SQLite 在批量删除或推进版本戳时使用事务);逐记录批次在完成前中断时可能只应用一部分。
5. `deleteRecord` 幂等;`putRecord` 覆写。
6. 任意字符串 key / 任意 JSON 值安全(key 不进文件路径,结构性质)。
7. `close` 幂等;close 后任何操作 → `StorageError('closed')`。
@@ -88,8 +88,8 @@ CREATE TABLE IF NOT EXISTS "u_<unit>_<table>" (
key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT; -- value = record JSON document
```
- unit 版本存 `units` 行,descriptor 不符 → `version-mismatch`。行粒度 document-per-row,保住按 key 精确落盘更新(为 session sidecar 这类高频点更新大表留路);查询需求出现时 JSON1 直查 value 列。
- 写原语单语句即原子,无跨语句事务需求(domain 层无跨表事务,见不做清单)。
- unit 版本存 `units` 行,未接受的版本以 `version-mismatch` 拒绝。行粒度 document-per-row,保住按 key 精确落盘更新(为 session sidecar 这类高频点更新大表留路);查询需求出现时 JSON1 直查 value 列。
- 当前版本的单记录写入使用单条语句。批量删除和对已接受旧单元的首次修改使用一个事务;首次修改一同提交数据和当前版本戳。这不增加跨表领域事务。
### `dsh-domain`:领域数据形式
@@ -117,6 +117,7 @@ export interface DomainTableSpec<K extends string, V> { readonly valueSchema: Zo
export interface DomainSpec {
readonly name: string // ^[a-z][a-z0-9_]*$
readonly version: number
readonly compatibleVersions?: readonly number[]
readonly global?: DomainGlobalSpec<unknown>
readonly tables: Record<string, DomainTableSpec<string, unknown>>
}
@@ -157,8 +158,8 @@ export interface KvTable<K extends string, V> {
- **一级 mapping**:key → 记录,不做嵌套表;层级需求用复合 key 或值内字段。两后端因此同构(JSON object 一层 ↔ SQLite 一行)。
- **记录是纯数据**:可直接 JSON 序列化的不可变 POJO;`get`/`entries` 返回值不得原地改(TypeScript readonly 投影,不做运行时冻结)。带行为的领域对象属于消费方包。
- **写串行**:域内一条 promise 链,`put`/`delete`/`update`/`global.set` 全排队;`update` 的 fn 在链上执行,并发不交错。不做 active-record(取出可变对象自动落盘——落盘时机不可控,与整域原子覆写冲突)。
- **版本 fail loud**:盘上版本与 spec 不符直接报错,不迁移不重建(数据不可再生,pre-release 拒绝旧格式)。
- **写串行**:域内一条 promise 链,`put`/`delete`/`deleteMany`/`update`/`global.set` 全排队;`update` 的 fn 在链上执行,并发不交错。不做 active-record(取出可变对象自动落盘——落盘时机不可控,与整域原子覆写冲突)。
- **版本兼容**:领域拥有方通过 `compatibleVersions` 声明可读的旧版本,并用当前 schema 解码历史值。Storage 不转换记录值;[领域版本](../../../../docs/subsystems/storage.zh.md#domain-versioning)定义版本戳发布和混合代际要求。
- **变更事件**:每次写落盘 resolve 后 emit `domain/changed`(`@mode emit`),逐条发、不带旧值(对齐仓库"新快照 + 操作判别"惯例,范本 `goal/changed`);payload `DomainChanged` 是 put/deleted 判别联合——域名 + 表名 + key(global 变更两者为 `''`)+ operation,put 支带新快照 value、deleted 支无 value(`packages/storage/storage-domain/src/events.ts`)。此为下期 RPC 推帧的事件源。错误词汇 `DomainError`,码表:`already-open` / `facet-unsupported` / `invalid-record`(带 `{ table, key }`)/ `missing-key` / `closed`。
### Future work:session 侧删除(设计定案,本期不实施)
+3
View File
@@ -13,3 +13,6 @@ docs/persistence-schema.json linguist-generated=true
docs/persistence-changes/*.schema.json linguist-generated=true
docs/persistence-changes/releases/*.schema.json linguist-generated=true
docs/persistence-changes/historical-formats/*.schema.json linguist-generated=true
# Unified patch blank context lines require their leading space.
patches/*.patch whitespace=-blank-at-eol
+2
View File
@@ -4,4 +4,6 @@ Run jobs on Windows runners (`windows-*` labels) under native `pwsh`. Native Win
The manual [Windows packaging workflow](workflows/windows-package.yml) uses the dedicated self-hosted Windows x64 label `dsh-win-package-trial` under native `pwsh`; preserve this routing separately from the automatic CI lanes.
The merge checks run from three workflows named `Policy`, which run on `pull_request_target` so their definitions come from master, and call the `deepseek-harness-check` action directly: `pr-check-on-head-branch.yml` on pull-request updates gives `Policy / Master Change` and `Policy / Pre-Merge Check`, `pr-check-after-approve.yml` on pull-request updates and submitted or dismissed reviews gives `Policy / Approve Check` and `Policy / Reviewer Evaluate`, and `pr-check-on-base-branch.yml` on master pushes re-runs the head-branch checks as `Policy / Recheck`. Branch rules require those check names, so keep the job names and the workflow name. Each check reads its mode from a repository variable: `MERGE_POLICY_MASTER_DIFF`, `MERGE_POLICY_PRE_MERGE`, `MERGE_POLICY_HEAD_DIFF`, and `MERGE_POLICY_REVIEW`, each `off` (skip), `report` (run without failing the job), or `block` (fail the job); a missing value or an unknown one counts as `report`. `Policy / Pre-Merge Check` merges the commit `Policy / Master Change` reports, so it runs only after that job and stays off while `MERGE_POLICY_MASTER_DIFF` is `off`; a merge it cannot do and a build that fails both follow its own mode, so `report` warns and skips the build while `block` fails the job.
The manual Desktop publication workflow selects a successful package run and attempt, then routes each retained build through `DESKTOP_PUBLISH_RUNNERS` to its original machine's unique label. Keep Windows run steps on native PowerShell and Mac run steps on the default POSIX shell; shared entrypoints are Node scripts. Test and production jobs use separate `desktop-test` and `desktop-production` approval Environments after a credential-free preparation job.
@@ -264,6 +264,10 @@ jobs:
- name: Build single-exe
env:
DSH_BUILD_CLIENT_PROFILE: official
# Brotli runs at quality 9 through the vendored pkg patch: the same
# payload measured 16.3 s at quality 9 against 132.8 s at pkg's default
# quality 11, for an archive 10% larger. Which quality each lane uses is
# therefore not a workflow choice.
run: >-
pnpm exec tsx scripts/build-exe-for-python-sdk.ts --targets=${{ matrix.target }}
${{ inputs.ci && github.event_name == 'pull_request' && '--build-artifacts' || '' }}
+30 -4
View File
@@ -3,7 +3,9 @@ name: Build PR preview
# Every push to a pull request publishes that pull request's preview to
# Cloudflare Pages under its own branch alias, behind Cloudflare Access. The
# upload carries build products only: the workflow never grants the deployment
# platform access to this repository's sources.
# platform access to this repository's sources. This lane also owns the
# aggregate test and script type checks that the required Linux consumers no
# longer repeat on every pull request.
on:
pull_request:
@@ -32,7 +34,13 @@ env:
jobs:
preview:
runs-on: ubuntu-24.04
# The required outcome is the build, which runs four TypeScript programs
# (Host and Client package compilation, then each face's aggregate test and
# script check) after the Typert pass. Publishing is best effort: transport,
# Access, and comment failures warn instead of failing the check.
runs-on: >-
${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404'
|| 'ubuntu-24.04' }}
name: cloudflare pages preview
steps:
- uses: actions/[email protected]
@@ -70,8 +78,11 @@ jobs:
# apps/web consumes workspace packages as built lib products, and
# build:preview packs the image through the packer's installed bin
# (lib/bin.js), so neither half exists before the artifact build runs.
- name: Build workspace
run: pnpm run build:artifacts
# The required Linux consumers emit artifacts only; the complete build
# here also runs the aggregate test and script checks, which share the
# Typert output and the two package compilations.
- name: Build workspace and check aggregate programs
run: pnpm run build
- name: Build the preview page and pack the VFS image
env:
@@ -88,6 +99,8 @@ jobs:
cp apps/web/dist/preview.html apps/web/dist/index.html
- name: Upload to Cloudflare Pages
id: upload
continue-on-error: true
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
@@ -112,6 +125,8 @@ jobs:
# Accept-Encoding is sent because a browser sends it; the assertion is
# about what the platform does with a body that is already compressed.
- name: Verify the protected deployment serves the image
id: verify
continue-on-error: true
env:
CF_ACCESS_CLIENT_ID: ${{ secrets.CF_ACCESS_CLIENT_ID }}
CF_ACCESS_CLIENT_SECRET: ${{ secrets.CF_ACCESS_CLIENT_SECRET }}
@@ -151,6 +166,8 @@ jobs:
# idempotent: a pull request opened before this workflow existed never
# sees an `opened` event, and every later push must not restate the URL.
- name: Comment the preview URL
id: comment
continue-on-error: true
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.number }}
@@ -168,3 +185,12 @@ jobs:
"$marker" \
"[Preview for #$PR](https://pr-$PR.${CF_PROJECT}.pages.dev) (requires Cloudflare Access sign-in)" \
| gh pr comment "$PR" --body-file -
# Publishing stays outside the required verdict: a Cloudflare, Access, or
# comment failure warns, while a build failure still fails this check.
- name: Report preview publication failures
if: steps.upload.outcome == 'failure' || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'
run: |
message='preview publication failed; the build passed, see the upload, verify, and comment steps'
echo "::warning::$message"
echo "$message" >> "$GITHUB_STEP_SUMMARY"
+72 -3
View File
@@ -202,12 +202,81 @@ jobs:
path: .coverage-times.json
key: coverage-times-Linux-${{ runner.environment }}-${{ vars.DSH_CI_FAILOVER_LINUX || 'enterprise' }}-${{ github.run_id }}-${{ github.run_attempt }}
# Lint and duplication get their own lane instead of riding the artifact
# consumers: a red lint no longer costs the snapshot and artifact consumers a
# full rerun. The lane compiles package declarations because oxlint's
# type-aware rules read them.
node-24-lint:
if: github.event_name == 'pull_request'
runs-on: >-
${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-8vcpu-ubuntu-2404'
|| vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
&& github.event.pull_request.user.login != 'dependabot[bot]'
&& fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
|| 'dsh-ubuntu-24-04-16core' }}
name: node 24 / lint
env:
# Shared hosts expose host CPUs, not an isolated allocation.
DSH_GATE_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }}
DSH_OXLINT_THREADS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }}
steps:
# Runner cleanup owns tool caches and fixtures, including cancelled runs.
- name: Use runner-owned temporary storage
run: |
echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV"
- uses: actions/[email protected]
with:
persist-credentials: false
- name: Redirect Node compile cache to runner temp
run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV"
- uses: pnpm/[email protected]
with:
dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
- uses: actions/[email protected]
with:
node-version: ${{ env.PRIMARY_NODE_VERSION }}
- name: Configure pnpm store path
id: pnpm-store
run: |
store_root="$HOME/.local/share/pnpm/store"
echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
echo "path=$store_path" >> "$GITHUB_OUTPUT"
- uses: actions/cache/[email protected]
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
with:
path: ${{ steps.pnpm-store.outputs.path }}
key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
- name: Install (immutable)
run: pnpm install --frozen-lockfile
# oxlint's type-aware rules resolve workspace imports through the package
# declarations, so this lane compiles them without bundling anything.
- name: Compile package declarations
run: pnpm run typecheck
- name: Run lint and duplication
run: pnpm run check:ci:lint:contracts-ready
node-24-bench:
if: github.event_name == 'pull_request'
runs-on: ubuntu-24.04
runs-on: >-
${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404'
|| 'ubuntu-24.04' }}
name: node 24 / benchmarks
# Wall-clock budgets need an otherwise idle runner, so this job runs the
# benchmark lane alone instead of joining a concurrent gate aggregate.
# benchmark lane alone instead of joining a concurrent gate aggregate, and
# keeps its own two-file parallelism inside that runner. The self-hosted
# failover pool is shared, so the benchmarks stay on hosted Linux there.
timeout-minutes: 20
steps:
- uses: actions/[email protected]
@@ -503,7 +572,7 @@ jobs:
&& github.event.pull_request.user.login != 'dependabot[bot]'
&& fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
|| 'ubuntu-latest' }}
needs: [node-24, node-24-coverage, node-24-bench, node-24-consumers, node-compat]
needs: [node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-consumers, node-compat]
if: ${{ !cancelled() && github.event_name == 'pull_request' }}
steps:
- name: Fail if any needed job did not succeed
+1 -1
View File
@@ -122,6 +122,6 @@ jobs:
DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }}
DEEPSEEK_BASE_URL: https://api.deepseek.com/anthropic
DSH_PRIMARY_RUNTIME: ${{ github.workspace }}/.cache/e2e-office/primary-runtime
DSH_E2E_MAX_WORKERS: 4
DSH_E2E_MAX_WORKERS: 6
DSH_EXAMPLE_MODE: lib
run: pnpm run test:e2e
@@ -0,0 +1,94 @@
name: Policy
on:
pull_request_target:
branches: [master]
types: [opened, synchronize, reopened, ready_for_review]
pull_request_review:
types: [submitted, dismissed]
permissions:
contents: read
pull-requests: read
concurrency:
group: pr-check-after-approve-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
approve:
name: Approve Check
# Each check runs only while its repository variable is neither empty nor `off`; otherwise the job is skipped.
if: ${{ vars.MERGE_POLICY_HEAD_DIFF != '' && vars.MERGE_POLICY_HEAD_DIFF != 'off' }}
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
pull-requests: read
steps:
# The head checkout is only the Git repository the check fetches into; it needs no files and runs no code.
- uses: actions/[email protected]
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 1
filter: blob:none
sparse-checkout: README.md
sparse-checkout-cone-mode: false
- uses: actions/[email protected]
with:
node-version: '24'
package-manager-cache: false
- uses: deepseek-harness/deepseek-harness-check@master
env:
CHECK_MODE: ${{ vars.MERGE_POLICY_HEAD_DIFF }}
with:
check: head-diff
base-branch: ${{ github.event.pull_request.base.ref }}
head-sha: ${{ github.event.pull_request.head.sha }}
pr-number: ${{ github.event.pull_request.number }}
pr-author: ${{ github.event.pull_request.user.login }}
review:
name: Reviewer Evaluate
if: ${{ vars.MERGE_POLICY_REVIEW != '' && vars.MERGE_POLICY_REVIEW != 'off' }}
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
pull-requests: read
# The check posts its verdict as a check run of its own.
checks: write
steps:
# The head checkout is only the Git repository the check fetches into; it needs no files and runs no code.
- uses: actions/[email protected]
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 1
filter: blob:none
sparse-checkout: README.md
sparse-checkout-cone-mode: false
- uses: actions/[email protected]
with:
node-version: '24'
package-manager-cache: false
# The check app's token makes the review check run its own row instead of joining this workflow's suite.
- id: token
continue-on-error: true
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1
with:
client-id: ${{ vars.DSH_APPROVAL_APP_CLIENT_ID }}
private-key: ${{ secrets.DSH_APPROVAL_APP_PRIVATE_KEY }}
owner: deepseek-harness
repositories: deepseek-harness
permission-checks: write
- uses: deepseek-harness/deepseek-harness-check@master
env:
CHECK_MODE: ${{ vars.MERGE_POLICY_REVIEW }}
CHECK_TOKEN: ${{ steps.token.outputs.token }}
with:
check: review
base-branch: ${{ github.event.pull_request.base.ref }}
head-sha: ${{ github.event.pull_request.head.sha }}
pr-number: ${{ github.event.pull_request.number }}
pr-author: ${{ github.event.pull_request.user.login }}
@@ -0,0 +1,30 @@
name: Policy
on:
push:
branches: [master]
workflow_dispatch:
permissions: {}
concurrency:
group: pr-check-on-base-branch-${{ github.ref_name }}
jobs:
recheck:
name: Recheck
# Re-runs the head-branch checks, so it follows their variables.
if: ${{ vars.MERGE_POLICY_MASTER_DIFF != '' && vars.MERGE_POLICY_MASTER_DIFF != 'off' || vars.MERGE_POLICY_PRE_MERGE != '' && vars.MERGE_POLICY_PRE_MERGE != 'off' }}
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
actions: write
contents: read
pull-requests: read
steps:
- uses: actions/[email protected]
with:
node-version: '24'
package-manager-cache: false
- uses: deepseek-harness/deepseek-harness-check@master
with:
check: recheck
base-branch: ${{ github.ref_name }}
recheck-label-token: ${{ secrets.DSH_RECHECK_LABEL_TOKEN }}
@@ -0,0 +1,107 @@
name: Policy
on:
pull_request_target:
branches: [master]
types: [opened, synchronize, reopened, ready_for_review, review_requested, auto_merge_enabled, labeled]
permissions:
contents: read
concurrency:
group: pr-check-on-head-branch-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
master:
name: Master Change
# Each check runs only while its repository variable is neither empty nor `off`; otherwise the job is skipped.
if: ${{ vars.MERGE_POLICY_MASTER_DIFF != '' && vars.MERGE_POLICY_MASTER_DIFF != 'off' && !github.event.pull_request.draft }}
runs-on: ubuntu-latest
timeout-minutes: 15
outputs:
base_sha: ${{ steps.check.outputs.base_sha }}
since: ${{ steps.check.outputs.since }}
steps:
# The head checkout is only the Git repository the check fetches into; it needs no files and runs no code.
- uses: actions/[email protected]
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 1
filter: blob:none
sparse-checkout: README.md
sparse-checkout-cone-mode: false
- uses: actions/[email protected]
with:
node-version: '24'
package-manager-cache: false
- id: check
uses: deepseek-harness/deepseek-harness-check@master
env:
CHECK_MODE: ${{ vars.MERGE_POLICY_MASTER_DIFF }}
with:
check: master-diff
base-branch: ${{ github.event.pull_request.base.ref }}
head-sha: ${{ github.event.pull_request.head.sha }}
pre-merge:
name: Pre-Merge Check
needs: master
if: ${{ vars.MERGE_POLICY_PRE_MERGE != '' && vars.MERGE_POLICY_PRE_MERGE != 'off' && needs.master.result == 'success' }}
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 60
# This job installs and compiles the pull request: it reads contents only and receives no secret.
permissions:
contents: read
steps:
- uses: actions/[email protected]
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 1
# Merging is the precondition of the build below, so a failure here warns and skips it in `report` mode and fails
# in `block` mode.
- id: merge
name: Merge the checked base-branch commit
env:
CHECK_MODE: ${{ vars.MERGE_POLICY_PRE_MERGE }}
BASE_SHA: ${{ needs.master.outputs.base_sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
SINCE: ${{ needs.master.outputs.since }}
run: |
stop() {
if [ "$CHECK_MODE" = block ]; then
echo "::error title=Pre-Merge Check::$1"
exit 1
fi
echo "::warning title=Pre-Merge Check::$1"
exit 0
}
if [[ ! "$BASE_SHA" =~ ^[0-9a-f]{40}$ || ! "$SINCE" =~ ^[0-9]+$ ]]; then
stop "the master diff check reported no base commit, so nothing was merged or compiled"
fi
git fetch --no-tags --no-write-fetch-head --shallow-since="$SINCE" origin "$HEAD_SHA" "$BASE_SHA" ||
stop "the base commit $BASE_SHA could not be fetched, so nothing was merged or compiled"
git -c user.name=pr-check -c [email protected] merge --no-ff --no-edit -m "Merge $BASE_SHA into $HEAD_SHA" "$BASE_SHA" ||
stop "the pull request cannot merge $BASE_SHA; merge master into it and push, then this check runs again"
echo "merged=true" >> "$GITHUB_OUTPUT"
- uses: pnpm/[email protected]
if: steps.merge.outputs.merged == 'true'
- uses: actions/[email protected]
if: steps.merge.outputs.merged == 'true'
with:
node-version: '24'
package-manager-cache: false
- name: Run the pre-merge command
if: steps.merge.outputs.merged == 'true'
env:
CHECK_MODE: ${{ vars.MERGE_POLICY_PRE_MERGE }}
run: |
if ! bash -euxo pipefail -c 'pnpm install --frozen-lockfile && pnpm exec tsx scripts/compile-referenced-projects.ts host-contracts && pnpm exec tsx scripts/compile-referenced-projects.ts client'; then
if [ "$CHECK_MODE" = block ]; then
echo "::error title=Pre-Merge Check::the merged tree does not install or compile"
exit 1
fi
echo "::warning title=Pre-Merge Check::the merged tree does not install or compile; this check does not block"
fi
+16 -6
View File
@@ -30,7 +30,8 @@ jobs:
name: Dependency layout
# Persistent runners accept only trusted, credential-free rehearsals.
runs-on: >-
${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404'
|| vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
&& github.repository == 'deepseek-harness/deepseek-harness'
&& github.actor != 'dependabot[bot]'
&& ((github.event_name == 'push' && github.ref == 'refs/heads/master')
@@ -80,11 +81,20 @@ jobs:
- name: Install (immutable)
run: pnpm install --frozen-lockfile
- name: Verify dependency policy
run: pnpm run verify-package-dependencies
- name: Verify npm install layout
run: pnpm run verify-npm-install-layout
# The two verifications read different inputs (manifests versus an npm
# install in a scratch directory), so they run beside each other.
- name: Verify dependency policy and npm install layout
run: |
pnpm run verify-package-dependencies &
dependencies_pid=$!
pnpm run verify-npm-install-layout &
layout_pid=$!
dependencies_status=0
wait "$dependencies_pid" || dependencies_status=$?
layout_status=0
wait "$layout_pid" || layout_status=$?
if (( dependencies_status != 0 )); then exit "$dependencies_status"; fi
exit "$layout_status"
pack:
name: Pack npm tarballs
+1
View File
@@ -75,6 +75,7 @@ External packages installed for runtime use or embedded in distributed Host or b
| [`@xterm/xterm`](https://github.com/xtermjs/xterm.js) | MIT |
| [`@yarnpkg/parsers`](https://github.com/yarnpkg/berry) | BSD-2-Clause |
| [`acorn`](https://github.com/acornjs/acorn) | MIT |
| [`acorn-walk`](https://github.com/acornjs/acorn) | MIT |
| [`ajv`](https://github.com/ajv-validator/ajv) | MIT |
| [`anser`](https://github.com/IonicaBizau/anser) | MIT |
| [`big.js`](https://github.com/MikeMcl/big.js) | MIT |
+6 -1
View File
@@ -29,6 +29,7 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur
writeFileSync(join(root, 'package.json'), '{"type":"module"}')
writeFileSync(join(modules, 'dsh-app-boot', 'package.json'), '{"type":"module","exports":"./index.js"}')
writeFileSync(join(modules, 'dsh-app-boot', 'index.js'), `
export class StartupError extends Error {}
export const loadProfileDirectory = () => ({ skippedBundles: [] });
export const reportSkippedBundles = () => {};
export const loadLayeredEnv = () => ({});
@@ -64,7 +65,11 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur
const boot = await new Promise<{
packageManager: { command: string; args: string[]; env: Record<string, string> }
}>((resolve, reject) => {
child.once('message', resolve)
child.on('message', (message) => {
if (typeof message === 'object' && message !== null && 'type' in message && message.type === 'booting' && 'packageManager' in message) {
resolve(message as { packageManager: { command: string; args: string[]; env: Record<string, string> } })
}
})
child.once('error', reject)
child.once('exit', (code) => { reject(new Error(`Host exited before booting: ${String(code)} ${stderr}`)) })
})
@@ -1,4 +1,4 @@
/** Account catalog diagnostics preserve the shipped ACP profile's JSON-RPC stream. */
/** Account catalog and MCP resource-listing diagnostics keep the shipped ACP profile's stdout JSON-RPC only. */
import { once } from 'node:events'
import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'
import { createServer } from 'node:http'
@@ -6,10 +6,22 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk'
import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server'
import { launchAcpTestAgent, type AgentUnderTest, type LaunchedAcpTestAgent } from '@deepseek-ai/dsh-session-snapshot'
import { expect, it } from 'vitest'
import { cleanupAcpExampleTest } from './cleanup.ts'
const repoRoot = fileURLToPath(new URL('../../../../../../', import.meta.url))
const binScript = join(repoRoot, 'apps/cli/src/bin.ts')
const tsconfigPath = join(repoRoot, 'tsconfig.json')
/** Parse every stdout line as a JSON-RPC frame; a diagnostic line fails the parse with its leading text. */
function jsonRpcFrames(launched: LaunchedAcpTestAgent): Record<string, unknown>[] {
const frames = launched.rawStdout().trim().split('\n').map(line => JSON.parse(line) as Record<string, unknown>)
for (const frame of frames) expect(frame).toMatchObject({ jsonrpc: '2.0' })
return frames
}
it('keeps account model-listing diagnostics on stderr during API-key session creation', async () => {
const cwd = await mkdtemp(join(tmpdir(), 'dsh-acp-stdout-'))
const token = 'acp-catalog-fixture-token'
@@ -100,3 +112,48 @@ it('keeps account model-listing diagnostics on stderr during API-key session cre
if (failures.length > 0) throw new AggregateError(failures, 'ACP catalog test cleanup failed')
}
})
it('keeps MCP resource-listing diagnostics off stdout for a tools-only client server', async () => {
const cwd = await mkdtemp(join(tmpdir(), 'dsh-acp-stdout-'))
const llm = await startMockLlmServer({
sequence: ['tool_call_success', 'success'],
toolName: 'list_mcp_resources',
toolArguments: JSON.stringify({ server: 'fixture' }),
})
let launched: LaunchedAcpTestAgent | undefined
try {
const configPath = join(cwd, 'mcp.patch.yml')
await writeFile(configPath, JSON.stringify([
{ id: 'llm-deepseek', config: { baseURL: llm.baseURL, models: [{ id: 'fixture-api-key-model' }] } },
{ id: 'acp', config: { provider: 'deepseek-official', model: 'fixture-api-key-model' } },
{ id: 'session-persistence-jsonl', config: { root: join(cwd, 'sessions'), compression: 'none' } },
]) + '\n')
launched = launchAcpTestAgent({
agent: { binScript, configPath, profile: 'acp', tsconfigPath },
cwd,
env: { DEEPSEEK_API_KEY: 'acp-fixture-api-key', DEEPSEEK_BASE_URL: llm.baseURL, DSH_TELEMETRY_DISABLED: '1' },
})
await launched.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
// The fixture server advertises only the tools capability.
const mcpServer = join(repoRoot, 'packages/mcp/mcp-client/tests/fixture-server.ts')
const created = await launched.client.newSession({
cwd, mcpServers: [{ name: 'fixture', command: process.execPath, args: [mcpServer], env: [] }],
})
await expect(launched.client.prompt({
sessionId: created.sessionId,
prompt: [{ type: 'text', text: 'list the fixture resources' }],
})).resolves.toEqual({ stopReason: 'end_turn' })
expect(launched.updates).toContainEqual(expect.objectContaining({ sessionUpdate: 'tool_call_update', status: 'completed' }))
await launched.client.closeSession({ sessionId: created.sessionId })
await launched.close()
expect(launched.child.exitCode).toBe(0)
expect(llm.requests.map(request => request.behavior)).toEqual(['tool_call_success', 'success'])
expect(jsonRpcFrames(launched).length).toBeGreaterThanOrEqual(5)
} finally {
const cleanup = await Promise.allSettled([cleanupAcpExampleTest(launched, cwd), llm.close()])
const failures: unknown[] = []
for (const result of cleanup) if (result.status === 'rejected') failures.push(result.reason)
if (failures.length > 0) throw new AggregateError(failures, 'ACP MCP test cleanup failed')
}
})
+2 -1
View File
@@ -25,7 +25,8 @@
"@deepseek-ai/dsh-tool-workspace-dependencies": "workspace:*",
"@deepseek-ai/dsh-skill-office": "workspace:*",
"@deepseek-ai/dsh-deepseek-account": "workspace:*",
"@deepseek-ai/dsh-workspace": "workspace:*"
"@deepseek-ai/dsh-workspace": "workspace:*",
"@deepseek-ai/dsh-plugin-manager": "workspace:*"
},
"devDependencies": {
"@deepseek-ai/cordis-plugin-loader": "workspace:~",
+59
View File
@@ -0,0 +1,59 @@
/** Bounded Host failure details sent to the Desktop crash reporter. */
import { inspect } from 'node:util'
import { StartupError } from '@deepseek-ai/dsh-app-boot'
/** Maximum characters carried by one fatal diagnostic, including its truncation notice. */
export const MAX_FATAL_DIAGNOSTIC_CHARS = 64 * 1024
/** Original-error budget when startup metadata needs space in the same report. */
const MAX_ORIGINAL_ERROR_CHARS = 8 * 1024
/** Startup entry details leave room for composition and provider observations. */
const MAX_STARTUP_ENTRY_CHARS = 8 * 1024
/**
* Render the original error and explicitly selected startup metadata.
* Selected metadata excludes configuration values and arbitrary startup logger arguments.
* @param error - Failure received by the Host entry point.
* @returns Bounded text with an explicit notice when the report is shortened.
*/
export function formatFatalDiagnostic(error: unknown): string {
const original = inspect(error, { depth: 4, maxArrayLength: 50 })
const sections: string[] = []
const seen = new Set<Error>()
function visit(value: unknown): void {
if (!(value instanceof Error) || seen.has(value)) return
seen.add(value)
if (value instanceof StartupError) {
if (value.startup !== undefined) {
sections.push(`Configuration file: ${value.startup.configurationPath}`)
}
const entries = inspect(value.entries, { depth: 6, maxArrayLength: null, maxStringLength: 4096 })
sections.push('--- startup entries ---', entries.length <= MAX_STARTUP_ENTRY_CHARS ? entries
: `${entries.slice(0, MAX_STARTUP_ENTRY_CHARS).replace(/[\uD800-\uDBFF]$/u, '')}\n… (startup entries truncated at ${MAX_STARTUP_ENTRY_CHARS} characters)`)
if (value.composition !== undefined) {
const { plugins, services, omittedPlugins, omittedServices } = value.composition
const sources = [...new Set(plugins.map(plugin => plugin.source))]
sections.push('--- startup composition ---',
'Provider lists contain observed registrations only; an empty list means the provider is unknown.',
'Source identifies the Loader tree, not necessarily the overriding patch.',
`Omitted plugin rows: ${omittedPlugins}; omitted missing-service observations: ${omittedServices}.`,
'--- missing services ---', ...services.map(service => JSON.stringify(service)),
'--- plugin sources (sourceIndex) ---', ...sources.map((source, index) => JSON.stringify({ index, source })),
'--- plugins (inactive first) ---', ...plugins.map(({ source, ...plugin }) => JSON.stringify({ ...plugin, sourceIndex: sources.indexOf(source) })))
} else {
sections.push('Startup composition diagnostic unavailable.')
}
}
visit(value.cause)
if (value instanceof AggregateError) value.errors.forEach(visit)
}
visit(error)
sections.unshift(sections.length === 0 || original.length <= MAX_ORIGINAL_ERROR_CHARS ? original
: `${original.slice(0, MAX_ORIGINAL_ERROR_CHARS).replace(/[\uD800-\uDBFF]$/u, '')}\n… (original error truncated at ${MAX_ORIGINAL_ERROR_CHARS} characters)`)
const text = sections.join('\n')
if (text.length <= MAX_FATAL_DIAGNOSTIC_CHARS) return text
const notice = `\n… (Host diagnostic truncated at ${MAX_FATAL_DIAGNOSTIC_CHARS} characters)`
return text.slice(0, MAX_FATAL_DIAGNOSTIC_CHARS - notice.length).replace(/[\uD800-\uDBFF]$/u, '') + notice
}
+8 -5
View File
@@ -1,7 +1,9 @@
/** Launch the Desktop profile through the Web application and report its URL to Electron. */
import { delimiter, join } from 'node:path'
import { inspect } from 'node:util'
import { randomUUID } from 'node:crypto'
import type { PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
import { formatFatalDiagnostic } from './fatal-diagnostic.ts'
import { loadLayeredEnv, loadProfileDirectory, reportSkippedBundles } from '@deepseek-ai/dsh-app-boot'
import { runProfile } from '@deepseek-ai/dsh/profile-boot'
import type {} from '@deepseek-ai/dsh-client-connection'
@@ -15,8 +17,11 @@ import { installDesktopUpdateTaskControl } from './update-tasks.ts'
import { installDesktopQuitInspection } from './quit-inspection.ts'
import { installPlatformSessionPublisher } from './platform-session.ts'
import { installOfficeEngineResolution } from './office-engine.ts'
import { installOperationDiagnostics } from './operation-diagnostics.ts'
async function main(): Promise<void> {
const runId = randomUUID() as PluginOperationRunId
if (process.connected) process.send?.({ type: 'starting', runId }, (error) => { if (error !== null) console.error(error) })
const runtimeDir = process.argv[2] as string
const projectDir = process.argv[3] as string
installOfficeEngineResolution(runtimeDir)
@@ -123,6 +128,7 @@ async function main(): Promise<void> {
})
process.once('disconnect', () => { void stop() })
const { ctx } = await application
installOperationDiagnostics(ctx, record => send({ type: 'plugin-operation', record }), 32, runId)
control.updateTasks = installDesktopUpdateTaskControl(ctx)
control.quitInspection = installDesktopQuitInspection(ctx)
await ctx.plugin(desktopOffice, {
@@ -137,16 +143,13 @@ async function main(): Promise<void> {
if (process.connected) process.send?.({ type: 'ready', url, injections: ctx.webServer.collectIndexInjections(ctx.connection.browserPeer) }, (error) => { if (error !== null) console.error(error) })
}
/** Upper bound of the startup diagnostic carried over IPC; the head holds the message and stack. */
const MAX_FATAL_DIAGNOSTIC_CHARS = 64 * 1024
if (import.meta.main) {
main().catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error)
// The shell receives the complete inspected error here, not through stderr:
// stderr bytes and this IPC message race, and the shell reports the first
// failure it sees.
const diagnostic = inspect(error, { depth: 4, maxArrayLength: 50 }).slice(0, MAX_FATAL_DIAGNOSTIC_CHARS)
const diagnostic = formatFatalDiagnostic(error)
if (process.connected) process.send?.({ type: 'fatal', message, diagnostic }, (error) => { if (error !== null) console.error(error) })
console.error(error)
process.exitCode = 1
@@ -0,0 +1,34 @@
/** Bounded delivery of management facts to the shell which owns durable diagnostics. */
import type { Context } from '@deepseek-ai/cordis'
import { parsePluginOperationRecord, type PluginOperationRecord, type PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
/**
* Observe manager operations after Host startup, with bounded concurrent IPC deliveries.
* @param ctx - Context owning the subscription and its pending deliveries.
* @param send - IPC transport promise which settles when delivery succeeds or fails.
* @param maxPending - Maximum number of outstanding deliveries; excess events are counted and omitted.
* @param runId - Host lifetime identity announced before profile startup.
*/
export function installOperationDiagnostics(
ctx: Context, send: (record: PluginOperationRecord) => Promise<void>, maxPending: number, runId: PluginOperationRunId,
): void {
if (!Number.isSafeInteger(maxPending) || maxPending < 1) throw new RangeError('Invalid diagnostic delivery budget')
const pending = new Set<Promise<void>>()
let dropped = 0
let closed = false
ctx.on('plugin-manager/operation', (operation) => {
if (closed || pending.size >= maxPending) { dropped++; return }
const record = parsePluginOperationRecord({ runId, operation, transportDropped: dropped })
if (record === undefined) { dropped++; return }
const delivery = Promise.resolve().then(async () => {
try { await send(record) }
catch (_error) { dropped++ /* IPC failure does not change the management operation. */ }
})
pending.add(delivery)
void delivery.then(() => { pending.delete(delivery) })
})
ctx.effect(() => async () => {
closed = true
await Promise.allSettled(pending)
})
}
@@ -0,0 +1,105 @@
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, onTestFinished } from 'vitest'
import { boot, StartupError } from '@deepseek-ai/dsh-app-boot'
import { formatFatalDiagnostic, MAX_FATAL_DIAGNOSTIC_CHARS } from '../src/fatal-diagnostic.ts'
import { renderCrashReport } from '../../desktop/src/crash-report.ts'
it.each([
['import', 'throw new Error("qualification-import-failure")'],
['initialize', 'export function apply() { throw new Error("qualification-initialize-failure", { cause: new Error("qualification-root-cause") }) }'],
])('retains real plugin %s failure evidence in the Desktop report after Loader disposal', async (stage, source) => {
const directory = await mkdtemp(join(tmpdir(), 'desktop-plugin-failure-'))
onTestFinished(async () => { await rm(directory, { recursive: true, force: true }) })
await writeFile(join(directory, 'failure.mjs'), source + '\n')
const config = join(directory, 'cordis.yml')
await writeFile(config, '- id: agent-loop\n name: ./failure.mjs\n')
const failure: unknown = await boot('diagnostic-test', config).then(async (ctx) => {
await ctx.fiber.dispose()
throw new Error('Expected fixture plugin to fail startup')
}, (error: unknown) => error)
expect(failure).toBeInstanceOf(StartupError)
const diagnostic = formatFatalDiagnostic(failure)
const report = renderCrashReport({ source: 'host', phase: 'startup', error: failure,
hostDiagnostic: diagnostic, rendererConsole: [], operationHistoryPlanned: true,
time: new Date('2026-10-19T00:00:00Z'),
app: { name: 'qualification', version: 'test', platform: 'win32', arch: 'x64', electron: 'test', node: process.version, locale: 'zh-CN' },
})
expect(report).toContain(`qualification-${stage}-failure`)
expect(report).toContain('./failure.mjs')
expect(report).toContain('--- startup composition ---')
if (stage === 'initialize') expect(report).toContain('qualification-root-cause')
})
it('includes non-enumerable startup entries without copying arbitrary startup logger arguments', () => {
const error = new StartupError('required plugin did not activate', [{
id: 'agent-loop', module: '@deepseek-ai/dsh-agent-loop', required: true, fiberState: undefined,
outcome: { kind: 'pending', missing: ['agents', 'sessions'] },
}])
error.startup = { configurationPath: '/profile/cordis.yml', messages: [{
ts: 1, name: 'plugin', type: 'warn', args: ['private-plugin-output'],
}] }
const report = formatFatalDiagnostic(new Error('Host startup failed', { cause: error }))
expect(report).toContain('--- startup entries ---')
expect(report).toContain('@deepseek-ai/dsh-agent-loop')
expect(report).toContain("missing: [ 'agents', 'sessions' ]")
expect(report).toContain('Configuration file: /profile/cordis.yml')
expect(report).not.toContain('private-plugin-output')
})
it('marks truncation within the complete IPC budget and preserves Unicode', () => {
const error = new Error('😀'.repeat(MAX_FATAL_DIAGNOSTIC_CHARS))
const report = formatFatalDiagnostic(error)
expect(report.length).toBeLessThanOrEqual(MAX_FATAL_DIAGNOSTIC_CHARS)
expect(report).toContain('Host diagnostic truncated at 65536 characters')
expect(report.isWellFormed()).toBe(true)
})
it('keeps missing-service evidence ahead of a truncated plugin inventory', () => {
const error = new StartupError('failure '.repeat(2000), [{
id: 'waiting-entry', module: './waiting.mjs', required: true, fiberState: undefined,
outcome: { kind: 'pending', missing: ['agents'] },
}])
error.startup = { configurationPath: '/profile/critical-cordis.yml', messages: [] }
error.composition = {
services: [{ consumer: 'agent-loop', service: 'agents', providers: [] }],
plugins: Array.from({ length: 256 }, (_, index) => ({
id: `plugin-${index}`, module: 'long-package-name'.repeat(30), version: '1.0.0',
state: 'disabled', source: '/profile/cordis.yml', missing: [],
})),
omittedPlugins: 3, omittedServices: 2,
}
const report = formatFatalDiagnostic(error)
expect(report).toContain('original error truncated at 8192 characters')
expect(report).toContain('Configuration file: /profile/critical-cordis.yml')
expect(report).toContain('waiting-entry')
expect(report).toContain('"service":"agents","providers":[]')
expect(report).toContain('Omitted plugin rows: 3; omitted missing-service observations: 2.')
expect(report).toContain('"source":"/profile/cordis.yml"')
expect(report).toContain('Host diagnostic truncated at 65536 characters')
expect(report.length).toBeLessThanOrEqual(MAX_FATAL_DIAGNOSTIC_CHARS)
})
it('terminates traversal through cyclic and aggregate causes', () => {
const error = new AggregateError([], 'cycle')
error.errors.push(error)
error.cause = error
expect(formatFatalDiagnostic(error)).toContain('cycle')
})
it.each(['many entries', 'long stack'])('retains composition evidence after %s', (scenario) => {
const failure = new Error('startup failure')
failure.stack = 'x'.repeat(70000)
const error = new StartupError('startup failed', scenario === 'long stack'
? [{ id: 'failed', module: './failed.mjs', required: true, fiberState: undefined, outcome: { kind: 'failed', error: failure } }]
: Array.from({ length: 256 }, (_, index) => ({ id: `pending-${index}`, module: 'module'.repeat(60), required: true, fiberState: undefined, outcome: { kind: 'pending' as const, missing: ['agents'] } })))
error.startup = { configurationPath: '/profile/cordis.yml', messages: [] }
error.composition = { plugins: [{ id: 'provider', module: 'example', version: '1.0.0', state: 'active', source: '/profile/cordis.yml', missing: [] }], services: [{ consumer: 'consumer', service: 'agents', providers: [] }], omittedPlugins: 0, omittedServices: 0 }
const report = formatFatalDiagnostic(error)
expect(report).toContain('Configuration file: /profile/cordis.yml')
expect(report).toContain('startup entries truncated')
expect(report).toContain('"service":"agents"')
expect(report).toContain('"version":"1.0.0"')
expect(report.length).toBeLessThanOrEqual(65536)
})
@@ -0,0 +1,41 @@
import { Context } from '@deepseek-ai/cordis'
import type { PluginOperation } from '@deepseek-ai/dsh-plugin-manager/types'
import type { PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
import { expect, it, onTestFinished, vi } from 'vitest'
import { installOperationDiagnostics } from '../src/operation-diagnostics.ts'
const operation: PluginOperation = {
id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9' as PluginOperation['id'],
time: '2026-10-19T00:00:00.000Z', reason: 'plugin', phase: 'started', target: 'managed', stage: 'enable',
}
const runId = 'c254ab28-97c9-4382-95e6-2db9c66f98c8' as PluginOperationRunId
it('bounds outstanding deliveries and drains them on context disposal', async () => {
const ctx = new Context()
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
onTestFinished(async () => { release.resolve(undefined); await ctx.fiber.dispose() })
const send = vi.fn(async () => { entered.resolve(undefined); await release.promise })
installOperationDiagnostics(ctx, send, 1, runId)
ctx.emit('plugin-manager/operation', operation)
await entered.promise
for (let i = 0; i < 1000; i++) ctx.emit('plugin-manager/operation', operation)
expect(send).toHaveBeenCalledTimes(1)
expect(send).toHaveBeenCalledWith(expect.objectContaining({ runId }))
let stopped = false
const stopping = ctx.fiber.dispose().then(() => { stopped = true })
await Promise.resolve(undefined)
expect(stopped).toBe(false)
release.resolve(undefined)
await stopping
ctx.emit('plugin-manager/operation', operation)
expect(send).toHaveBeenCalledTimes(1)
})
it('contains transport rejections during teardown', async () => {
const ctx = new Context()
onTestFinished(async () => { await ctx.fiber.dispose() })
installOperationDiagnostics(ctx, async () => { throw new Error('disconnected') }, 1, runId)
ctx.emit('plugin-manager/operation', operation)
await expect(ctx.fiber.dispose()).resolves.toBeUndefined()
})
+3
View File
@@ -31,6 +31,9 @@
{
"path": "../../packages/credentials/deepseek-account"
},
{
"path": "../../packages/boot/plugin-manager"
},
{
"path": "../../packages/fs/fs"
},
+6 -6
View File
@@ -12,11 +12,11 @@
en: 7bc8bf30de693222
zh: e85993d8852b6cab
/deepseek-harness-desktop/table-of-contents:
en: 05fd227f99ee535a
zh: 60d7d62bc0026973
en: 127ea90553cb6af7
zh: 7b1c5aec8558c684
/deepseek-harness-desktop/application-overview:
en: e9b22f232837e131
zh: fc5f3834b969d2d2
en: b57525e17b9638ab
zh: 274fe8344f7c2202
/deepseek-harness-desktop/terminal-command:
en: 5f2d25a1d8472647
zh: 2acb5c5d7d1917e2
@@ -36,8 +36,8 @@
en: 160b500cdcd6a39a
zh: 6c267f1762ec3689
/deepseek-harness-desktop/installation-ownership/runtime-and-plugin-activation:
en: a1a47b09f4a72ba4
zh: 7b1cf27f0b72cf31
en: 4951cd3ee659eb33
zh: 96bdd6358dad587a
/deepseek-harness-desktop/installation-ownership/host-environment:
en: 98cf848762482d48
zh: 74f9100a39ec8c2f
+5 -8
View File
@@ -18,6 +18,7 @@ Desktop runs the Harness workspace in a native application. This reference cover
- [Key technical decisions](#key-technical-decisions)
- [Bundled command runtime](#bundled-command-runtime)
- [Installation ownership](#installation-ownership)
- [Recovery and diagnostics](docs/diagnostics/README.md)
- [Develop](#develop)
- [Package](#package)
- [Windows installer interface](#windows-installer-interface)
@@ -30,6 +31,8 @@ Desktop runs the Harness workspace in a native application. This reference cover
## Application overview
Electron caches the last confirmed UI language in `userData/desktop/locale-cache` so startup recovery dialogs can use it before Host settings are available. Missing, invalid, or unreadable caches fall back to the system language; cache write failures do not block startup. A successful Host startup or a UI language change refreshes the cache. Until then, a changed system language may differ from the cached language.
Desktop analytics follows the [product collection policy](../../packages/client/product-analytics/README.md), including its live application setting. Web usage is excluded. Update installation waits for its local analytics intake before locking API admission and stopping the Host. Intake has a one-second deadline; failure does not prevent installation, and collector delivery is not awaited.
The desktop application is an Electron shell around the complete dsh Web application. An Electron RunAsNode child starts the shared profile runner, and Electron immediately loads the packaged Web entry at `dsh-app://app/`. Its shared loading page waits for Host boot injections, then starts the client without navigating to another document. Electron forwards application HTTP requests to the authenticated Web Host, dropping connection-level response headers (`transfer-encoding`, `connection`, `keep-alive`) that describe the Node fetch rather than the resource, and marking plugin bundle responses `no-store` because their per-launch revisions would only accumulate in Chromium's disk cache; WebSocket streams connect to that Host with credentials attached only for the owned application window. Node IPC carries boot injections, readiness, and shutdown. Desktop listens on an OS-assigned port by default, so it cannot collide with Web’s `3080` or a reserved port; a `webserver.config.port` patch can override it.
@@ -40,7 +43,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.
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.
Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/dependencies/pnpm`, without the native packages of other targets. 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.
@@ -172,13 +175,7 @@ The signed `resources/app.asar/dsh/desktop-runtime.json` binds the shell version
The [Web plugin UI](../../packages/client/ui-plugin-manager/README.md) owns the management interface. Desktop profile initialization and recovery preserve installed plugin files.
Fatal main-window creation, main-document loading, preload, renderer, Web initialization, or backend failures open one native recovery dialog per application process. It shows a bounded tail of the first error, notes any truncation, and offers Exit, Restart, and Disable third-party plugins, back up profile patch, and restart. Startup failures retain the Web loading page and spinner; runtime failures retain the current page. Expected shutdowns, cancelled navigation, and ordinary requests do not trigger recovery. The shared Web plugin manager reports package-operation errors; Host startup failures after plugin changes enter native recovery. There is no startup timeout heuristic. A listener failure containing `listen EADDRINUSE` replaces the diagnostics and reinstall advice with guidance to quit other running DSH instances, and offers only Exit and Restart.
Native dialog details include at most 1,200 UTF-16 code units and eight diagnostic lines, plus the path of the crash report described below when one was written. Host error diagnostics retain only the last 64 Ki characters written to stderr. Earlier output is discarded so a long-running Host does not grow the shell’s diagnostic buffer indefinitely.
Before the first fatal dialog opens, Electron writes a crash report to the platform logs directory (`app.getPath('logs')`: `~/Library/Logs/DeepSeek Harness` on macOS, `logs` under the application’s `userData` directory on Windows and Linux), waiting at most one second for the write; a slow or failed write shows the dialog without a path. The file `crash-<UTC time>-<source>.log` records the source (`host` for a Host exit, `web-boot` for a renderer boot failure, `renderer` for a renderer or document failure, `main` for a shell error), whether the backend had reached ready, application and runtime versions, the error with its enumerable properties and cause chain (cut at 256 KiB), the Host’s own inspected error (at most 64 KiB) when the Host reported a startup failure over IPC before exiting, and the primary window’s recent error-level console output (at most 64 KiB). A Host exit report therefore contains the retained stderr tail, which may include plugin output. A fatal failure during shutdown writes a report without opening a dialog. Files are owner-only where the platform supports it; startup keeps the ten newest reports and removes older ones without touching other files in the directory.
Recovery waits for Host shutdown before changing plugin activation. The native recovery action calls the shared app-boot recovery function under the profile transaction lock. It disables third-party bundles and renames the profile’s `cordis.patch.yml` to `cordis.patch.yml.bak-<timestamp>` (with an ordinal on collisions) without parsing it; the next startup creates an empty patch. Installed packages and earlier backups remain. The home-level patch is unchanged. The Electron console records the backup path (or its absence) and the unchanged home-level patch. Invalid profile data, rename failures, or write failures are reported as recovery-operation errors; completed changes remain, and Desktop does not restart as though recovery succeeded. Desktop has no profile-reset action or emergency HTML document.
Desktop fatal failures use native recovery with Exit, Restart, Disable third-party plugins, back up profile patch, and restart, and Get diagnostic report. See [recovery and diagnostics](docs/diagnostics/README.md) for triggers, report locations and contents, recent operation records, and shutdown limits.
### Host environment
+5 -8
View File
@@ -18,6 +18,7 @@ Desktop 在原生应用中运行 Harness 工作区。本参考文档说明应用
- [关键技术决策](#key-technical-decisions)
- [内置命令运行时](#bundled-command-runtime)
- [安装归属](#installation-ownership)
- [故障恢复与诊断](docs/diagnostics/README.zh.md)
- [开发](#develop)
- [打包](#package)
- [Windows 安装界面](#windows-installer-interface)
@@ -30,6 +31,8 @@ Desktop 在原生应用中运行 Harness 工作区。本参考文档说明应用
## 应用概览
Electron 在 `userData/desktop/locale-cache` 缓存最近确认的界面语言,使启动恢复弹窗在 Host 设置尚不可用时也能使用该语言。缓存缺失、无效或不可读时回退到系统语言;缓存写入失败不阻断启动。Host 成功启动或界面语言变更时会刷新缓存;在此之前,变更后的系统语言可能与缓存语言不同。
桌面埋点遵循[产品采集策略](../../packages/client/product-analytics/README.zh.md)及其动态应用配置,不包含 Web 使用情况。安装更新会等待该操作的本地埋点接收请求结束,再锁定 API 准入并停止 Host。接收请求的时限为一秒,失败不会阻止安装,也不等待收集端完成发送。
桌面应用是完整 dsh Web 应用外的一层 Electron 壳。Electron RunAsNode 子进程启动共享 profile runner,Electron 立即从 `dsh-app://app/` 加载打包内的 Web 入口。共享加载页等待 Host 启动注入,然后在同一文档中启动客户端。Electron 将应用 HTTP 请求转发给已认证的 Web Host,转发时丢弃描述 Node fetch 连接而非资源本身的响应头(`transfer-encoding`、`connection`、`keep-alive`),并把插件 bundle 响应标记为 `no-store`,因为其每次启动都变化的 revision 只会在 Chromium 磁盘缓存中累积;WebSocket 流连接到该 Host,仅为归属的应用窗口附加凭据。Node IPC 承载启动注入、就绪与关闭。Desktop 默认监听系统分配的端口,因此不会与 Web 的 `3080` 或系统保留端口冲突;可通过 `webserver.config.port` patch 覆盖。
@@ -40,7 +43,7 @@ Desktop 绑定 `127.0.0.1`,即 Electron 为就绪 URL 与 WebSocket 凭据过
Desktop 的本地原生目录流程打开绑定应用窗口的 Electron 文件夹对话框,并先恢复、显示和聚焦该窗口。并发请求共用一个对话框;取消不返回路径,失败后可以重试。普通 Web 使用 Host 选择器。浏览模式列出 Host 目录。Linux 缺少 zenity 或 kdialog 时,自动选择使用浏览模式,不使用 Electron 对话框。
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。
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 功能返回栏下方的视口。
@@ -172,13 +175,7 @@ macOS 上自定义菜单保留 Electron 的标准 Window 菜单及应用隐藏
[Web 插件 UI](../../packages/client/ui-plugin-manager/README.zh.md)负责管理界面。Desktop profile 初始化和恢复保留已安装插件文件。
主窗口创建、主文档加载、preload、渲染器、Web 初始化或后端的致命失败,会在每个应用进程中打开一次原生恢复对话框。对话框显示首次错误末尾的限长摘要,标明截断情况,并提供退出、重启、禁用第三方插件、备份 profile patch 并重启。启动失败保留 Web 加载页和动画;运行中失败保留当前页面。预期关闭、取消导航和普通请求错误不会触发恢复。共享 Web 插件管理器报告包操作错误;插件变更后的 Host 启动失败会进入原生恢复。不通过启动超时推断故障。 包含 `listen EADDRINUSE` 的监听失败以退出其他正在运行的 DSH 实例的提示替代诊断和重装建议,仅提供退出和重启。
原生弹窗详情最多包含 1,200 个 UTF-16 代码单元和八行诊断,若已写入下述崩溃报告则附上其路径。Host 错误诊断仅保留 stderr 输出的最后 64 Ki 个字符。更早的输出会被丢弃,避免长期运行的 Host 使壳的诊断缓冲区无限增长。
首个致命弹窗打开前,Electron 会向平台日志目录(`app.getPath('logs')`:macOS 为 `~/Library/Logs/DeepSeek Harness`,Windows 与 Linux 为应用 `userData` 目录下的 `logs`)写入一份崩溃报告,最多等待写入一秒;写入缓慢或失败时弹窗不带路径。文件 `crash-<UTC 时间>-<source>.log` 记录来源(`host` 为 Host 退出、`web-boot` 为渲染进程启动失败、`renderer` 为渲染进程或文档失败、`main` 为壳自身错误)、后端是否已就绪、应用与运行时版本、包含可枚举属性与 cause 链的错误(截至 256 KiB)、Host 在退出前通过 IPC 报告启动失败时自己的 inspect 错误(最多 64 KiB),以及主窗口最近的 error 级 console 输出(最多 64 KiB)。因此 Host 退出报告包含保留的 stderr 尾部,其中可能含有插件输出。关闭过程中的致命失败只写报告、不弹窗。平台支持时文件仅所有者可读;启动时保留最新十份报告并删除更早的,不触碰目录中的其他文件。
恢复操作等待 Host 关闭后才修改插件启用状态。原生恢复操作在 profile 事务锁内调用共享 app-boot 恢复函数。它禁用第三方 bundle,并将 profile 的 `cordis.patch.yml` 重命名为 `cordis.patch.yml.bak-<timestamp>`(重名时追加序号),无需解析;下次启动创建空 patch。已安装包和已有备份保留。home 级 patch 不变。Electron 控制台记录备份路径(或原文件不存在)以及 home 级 patch 未修改。profile 数据无效、重命名失败或写入失败会作为恢复操作错误报告;已完成的修改保留,Desktop 不会假装恢复成功后重启。Desktop 不提供 profile 重置操作或应急 HTML 文档。
Desktop 的致命故障通过原生恢复对话框提供退出、重启、禁用第三方插件并备份 profile patch 后重启,以及获取诊断报告。触发范围、报告位置与内容、近期操作记录和退出限制见[故障恢复与诊断](docs/diagnostics/README.zh.md)。
### Host 环境
@@ -0,0 +1,28 @@
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write apps/desktop/docs/diagnostics/README.md
/:
en: 29d76ee1849cd8fd
zh: a2b8cbabe79557f9
/desktop-recovery-and-diagnostics:
en: 4d4fd8a92047e5c6
zh: 15ec51d703ccd70b
/desktop-recovery-and-diagnostics/summary:
en: e61d0f55e426aa6f
zh: dc13c7e054eac9d1
/desktop-recovery-and-diagnostics/table-of-contents:
en: 8f3a2a84eaf575af
zh: 3087306f10e7c2cf
/desktop-recovery-and-diagnostics/recover-from-a-failure:
en: 9d0645dba352979d
zh: e1556207a04d9a71
/desktop-recovery-and-diagnostics/report-contents:
en: 1a2eb71ac2dccf63
zh: 5cf59639d3e49591
/desktop-recovery-and-diagnostics/recent-operation-records:
en: f1c19c1516a51ab6
zh: b350f7c18086d274
/desktop-recovery-and-diagnostics/collection-and-shutdown:
en: bac4a49f63d4aaf8
zh: df1ae908ee2148e1
+76
View File
@@ -0,0 +1,76 @@
---
description: "Use this reference when recovering Desktop failures or collecting reports; it explains report contents, operation history, and shutdown limits."
---
# Desktop recovery and diagnostics
English | [中文](README.zh.md)
## Summary
This reference describes Desktop native failure recovery, diagnostic reports, recent plugin operation records, and collection and shutdown limits.
## Table of Contents
- [Recover from a failure](#recovery)
- [Report contents](#report-contents)
- [Recent operation records](#operation-records)
- [Collection and shutdown](#collection-and-shutdown)
<a id="recovery"></a>
## Recover from a failure
Fatal main-window creation, main-document loading, preload, renderer, Web initialization, or backend failures open one native recovery dialog per application process. It shows a bounded tail of the first error, notes any truncation, and offers “Exit”, “Restart”, “Disable third-party plugins, back up profile patch, and restart”, and “Get diagnostic report” while report writing is pending or after it succeeds. Startup failures retain the Web loading page and spinner; runtime failures retain the current page. Expected shutdowns, cancelled navigation, and ordinary requests do not trigger recovery. The shared Web plugin manager reports package-operation errors; Host startup failures after plugin changes enter native recovery. There is no startup timeout heuristic. A listener failure containing `listen EADDRINUSE` replaces the diagnostics and reinstall advice with guidance to quit other running DSH instances, and offers “Exit”, “Restart”, and “Get diagnostic report” while report writing is pending or after it succeeds.
Recovery uses the last confirmed Desktop language from the local cache before Host settings are available; an absent or invalid cache falls back to system languages.
Recovery waits for Host shutdown before changing plugin activation. The native recovery action calls the shared app-boot recovery function under the profile transaction lock. It disables third-party bundles and renames the profile’s `cordis.patch.yml` to `cordis.patch.yml.bak-<timestamp>` (with an ordinal on collisions) without parsing it; the next startup creates an empty patch. Installed packages and earlier backups remain. The home-level patch is unchanged. The Electron console records the backup path (or its absence) and the unchanged home-level patch. Invalid profile data, rename failures, or write failures are reported as recovery-operation errors; completed changes remain, and Desktop does not restart as though recovery succeeded. Desktop has no profile-reset action or emergency HTML document.
<a id="report-contents"></a>
## Report contents
Native dialog details include at most 1,200 UTF-16 code units and eight diagnostic lines, plus the crash report path or its pending/unavailable status. Retrieving a pending or unavailable report preserves any recovery-operation failure headline and details. Configuration paths and startup entries precede the composition inventory so plugin rows cannot displace them when output is truncated. Host error diagnostics retain only the last 64 Ki characters written to stderr. Earlier output is discarded so a long-running Host does not grow the shell’s diagnostic buffer indefinitely.
Before the first fatal dialog opens, Electron writes a crash report to the platform logs directory (`app.getPath('logs')`: `~/Library/Logs/DeepSeek Harness` on macOS, `logs` under the application’s `userData` directory on Windows and Linux), waiting at most one second for the write; a slow or failed write shows the dialog with an explicit pending or unavailable status. Get diagnostic report checks the same write and reveals a saved file in the system file manager without restarting or stopping the Host; a write that completes after the initial deadline remains available. The user attaches that file to a support ticket. The attachment contains the original failure; later recovery-operation errors remain in the dialog and require a separate screenshot. Retrieving a saved report shows its sharing or reveal-failure heading while retaining the recovery error details. If writing fails, the dialog hides Get diagnostic report and suggests providing a screenshot.
The file `crash-<UTC time>-<source>.log` records the source (`host` for a Host exit, `web-boot` for a renderer boot failure, `renderer` for a renderer or document failure, `main` for a shell error), whether the backend had reached ready, application and runtime versions, the error with its enumerable properties and cause chain (cut at 256 KiB), the Host’s own error and explicitly selected startup metadata (at most 64 Ki characters, including a truncation notice; startup errors reserve space for metadata by limiting the original error and startup-entry details to 8 Ki characters each, with explicit truncation notices) when the Host reported a startup failure over IPC before exiting, and the primary window’s recent error-level console output (at most 64 KiB).
A Host exit report therefore contains the retained stderr tail, which may include plugin output. A fatal failure during shutdown writes a report without opening a dialog. Files are owner-only where the platform supports it; startup keeps the ten newest reports and removes older ones without touching other files in the directory.
<a id="operation-records"></a>
## Recent operation records
Operation records and the application single-instance lock are isolated by `userData`; the shared platform logs directory does not store operation records. The reader only reads the two operation files under `userData/plugin-operations`. Repairing an unfinished append preserves complete lines in the current segment and the previous segment.
Version-exemption changes reuse the bundle enable/disable record fields. When the exemption and installed versions match, the record cannot distinguish an exemption change from a bundle toggle.
Host `transportDropped` is a lower bound as of the last successful delivery; Desktop rejects malformed or mismatched-run records without adding them to that counter.
The journal retains two 256 KiB segments, accepts records up to 4 KiB, and bounds queued writes to 64 KiB.
Exit, recovery restart and installer preparation wait at most 500 ms for queued writes; a timeout disables further writes and later drains return immediately without another wait, while an already-issued OS request may still settle.
Records cover manager operations observed after Host startup, not direct CLI commands or manual file changes. Package-manager output remains in its existing detailed logs and is not copied into this summary. Missing records, a start without an end, and damaged history do not establish a successful operation. This collection does not diagnose kernel hangs, OOM or native crashes.
Persistence failures also disable the writer for the rest of this shell lifetime, including after recovery or installer failure. This bounds repeated failing I/O and avoids appending behind an uncertain partial write. Restarting the application creates a new writer. Omission and repair counters cover only the current shell lifetime. Retained segments provide a larger local troubleshooting window than the deliberately smaller report attachment.
<a id="collection-and-shutdown"></a>
## Collection and shutdown
After saving the basic report, the shell attempts to append recent plugin-management records in an isolated Worker packaged as `lib/operation-report-worker.js` inside `app.asar`. The completion marker and omission counters distinguish a finished collection from missing or partial material.
The Host announces its run ID before profile loading; reported Host errors carry that ID as `hostRunId`, matching operation records from the same lifetime. Failure before this announcement leaves the run identity unknown. Recent operations are context, not proof of cause.
Collection reads only two owned files under `userData/plugin-operations`, at most 64 KiB and 100 records; the complete appended section is limited to 64 KiB.
The 500 ms collection budget reserves its final 100 ms for cooperative cancellation before requesting forced Worker termination; completion waits for its exit. Application exit, recovery exit or restart, and confirmed update installation also cancel collection and wait at most 500 ms for Worker exit. A rejected shutdown cleanup is logged without skipping the remaining cleanup waits. Shutdown prevents late basic-report saves from starting another collector. An update installation failure permits future collection again.
Worker messages interrupt collection between bounded records; an in-flight file open, stat, read or close must settle, and synchronous parsing cannot be preempted within one record. The final append uses an abort signal but can leave partial bytes. Forced termination remains the fallback when cooperative cleanup does not finish.
The basic report remains available independently. Only one collector runs at a time; concurrent reports keep their basic content without an auxiliary section. A rejected termination request does not release that slot until exit is observed. Get diagnostic report can reveal the basic file before the append finishes. The completion marker confirms only that collection ended, not that all operations were captured; queued bytes and omission counters describe missing material.
See [local verification](../../tests/README.md#verification-diagnostics) for fault setup and acceptance steps, and the [Desktop README](../../README.md) for the application overview and development entry points.
@@ -0,0 +1,76 @@
---
description: "排查 Desktop 故障或收集报告时阅读,了解恢复操作、报告内容、操作历史和退出限制。"
---
# Desktop 故障恢复与诊断
[English](README.md) | 中文
## 概述
本参考文档说明 Desktop 的原生故障恢复、诊断报告、近期插件操作记录,以及采集和退出时的限制。
## 目录
- [遇到故障怎么办](#recovery)
- [报告包含什么](#report-contents)
- [近期操作记录](#operation-records)
- [采集与退出行为](#collection-and-shutdown)
<a id="recovery"></a>
## 遇到故障怎么办
主窗口创建、主文档加载、preload、渲染器、Web 初始化或后端的致命失败,会在每个应用进程中打开一次原生恢复对话框。对话框显示首次错误末尾的限长摘要,标明截断情况,并提供“退出”“重启”“禁用第三方插件、备份 profile patch 并重启”,以及报告仍在保存或已保存时的“获取诊断报告”。启动失败保留 Web 加载页和动画;运行中失败保留当前页面。预期关闭、取消导航和普通请求错误不会触发恢复。共享 Web 插件管理器报告包操作错误;插件变更后的 Host 启动失败会进入原生恢复。不通过启动超时推断故障。包含 `listen EADDRINUSE` 的监听失败以退出其他正在运行的 DSH 实例的提示替代诊断和重装建议,提供“退出”“重启”,以及报告仍在保存或已保存时的“获取诊断报告”。
Host 设置可用前,恢复对话框使用本地缓存中最后确认的 Desktop 语言;缓存不存在或无效时回退到系统语言。
恢复操作等待 Host 关闭后才修改插件启用状态。原生恢复操作在 profile 事务锁内调用共享 app-boot 恢复函数。它禁用第三方 bundle,并将 profile 的 `cordis.patch.yml` 重命名为 `cordis.patch.yml.bak-<timestamp>`(重名时追加序号),无需解析;下次启动创建空 patch。已安装包和已有备份保留。home 级 patch 不变。Electron 控制台记录备份路径(或原文件不存在)以及 home 级 patch 未修改。profile 数据无效、重命名失败或写入失败会作为恢复操作错误报告;已完成的修改保留,Desktop 不会假装恢复成功后重启。Desktop 不提供 profile 重置操作或应急 HTML 文档。
<a id="report-contents"></a>
## 报告包含什么
原生弹窗详情最多包含 1,200 个 UTF-16 代码单元和八行诊断,并附上崩溃报告路径或仍在保存、无法保存的状态。获取仍在保存或无法保存的报告时,保留恢复操作失败的标题和详情。配置路径和启动条目排在组合清单之前,避免输出截断时被插件记录挤掉。Host 错误诊断仅保留 stderr 输出的最后 64 Ki 个字符。更早的输出会被丢弃,避免长期运行的 Host 使壳的诊断缓冲区无限增长。
首个致命弹窗打开前,Electron 会向平台日志目录(`app.getPath('logs')`:macOS 为 `~/Library/Logs/DeepSeek Harness`,Windows 与 Linux 为应用 `userData` 目录下的 `logs`)写入一份崩溃报告,最多等待写入一秒;写入缓慢或失败时明确显示仍在保存或无法保存。“获取诊断报告”检查同一次写入,并在系统文件管理器中定位已保存的文件,不停止 Host 或重启;超过首次等待期限后写入完成的文件仍可获取。用户可将文件作为工单附件。附件只包含最初的故障;后续恢复操作错误保留在对话框中,需要另行截图。获取已保存报告会显示分享或打开失败的标题,同时保留恢复错误详情。写入失败时隐藏获取报告按钮,并提示提供窗口截图。
文件 `crash-<UTC 时间>-<source>.log` 记录来源(`host` 为 Host 退出、`web-boot` 为渲染进程启动失败、`renderer` 为渲染进程或文档失败、`main` 为壳自身错误)、后端是否已就绪、应用与运行时版本、包含可枚举属性与 cause 链的错误(截至 256 KiB)、Host 在退出前通过 IPC 报告启动失败时的错误及显式选择的启动元数据(最多 64 Ki 个字符,包含截断提示;启动错误的原始错误文本和启动条目详情分别限制为 8 Ki 个字符,并明确标注截断,为结构化元数据保留空间),以及主窗口最近的 error 级 console 输出(最多 64 KiB)。
因此 Host 退出报告包含保留的 stderr 尾部,其中可能含有插件输出。关闭过程中的致命失败只写报告、不弹窗。平台支持时文件仅所有者可读;启动时保留最新十份报告并删除更早的,不触碰目录中的其他文件。
<a id="operation-records"></a>
## 近期操作记录
操作记录目录与应用单实例锁均按 `userData` 隔离;共享平台日志目录不用于保存操作记录。读取器只读取 `userData/plugin-operations` 下的两个操作记录文件。修复未写完的尾行时保留当前段的完整行与上一段。
版本豁免变更复用 bundle 启停记录字段。豁免版本与安装版本相同时,记录无法区分豁免变更与 bundle 开关。
Host 的 `transportDropped` 只表示最近一次成功发送时的计数下界;Desktop 拒绝的非法或运行 ID 不匹配记录不计入该值。
操作历史保留两个 256 KiB 文件段,单条记录不超过 4 KiB,排队写入不超过 64 KiB。
退出、恢复重启和安装准备最多等待排队写入 500 ms;超时会停用后续写入,此后的排空调用立即返回,不会再次等待;但已经发出的操作系统请求仍可能随后结束。
记录覆盖 Host 启动后观察到的管理器操作,不包含直接执行的 CLI 命令或手工文件修改。包管理器输出保留在原有详细日志中,不复制到摘要。缺失记录、只有开始没有结束的操作以及损坏的历史,都不能说明操作已成功。此收集不诊断内核卡死、OOM 或原生崩溃。
持久化失败也会在本次壳生命周期内停用写入,包括恢复或安装器失败后继续运行的情况,以限制重复失败的 I/O,并避免在可能残缺的写入后追加记录。重启应用会创建新写入器。遗漏和修复计数仅覆盖当前壳生命周期。保留文件段提供比报告附件更大的本地排障历史窗口。
<a id="collection-and-shutdown"></a>
## 采集与退出行为
基本报告保存后,壳会尝试通过独立 Worker 追加近期插件管理记录;该 Worker 以 `lib/operation-report-worker.js` 打包在 `app.asar` 中。完成标记和遗漏计数用于区分已完成收集与缺失或不完整的材料。
Host 在加载 profile 前报告运行 ID;Host 错误中的 `hostRunId` 与该次运行的操作记录使用同一标识。在此通知之前发生的失败,其运行标识仍为未知。近期操作只是上下文,不是因果证据。
收集只读取 `userData/plugin-operations` 下归其管理的两个文件,最多读取 64 KiB 和 100 条记录;完整追加内容不超过 64 KiB。
500 ms 收集预算中的最后 100 ms 用于协作取消,随后才请求强制终止 Worker;只有 Worker 退出后才确认收集结束。应用退出、恢复退出或重启、确认安装更新也会取消收集,并最多等待 500 ms 确认 Worker 退出。退出清理中的拒绝会被记录,但不会跳过其他清理等待。退出过程中,延迟保存完成的基本报告不会再启动收集器。更新安装失败后可再次收集。
Worker 在有界记录之间处理取消消息;已经发出的文件打开、状态读取、读取或关闭操作必须等待完成,单条记录的同步解析不能被抢占。最后的追加写入传入取消信号,但仍可能留下部分字节。协作清理未及时完成时仍需强制终止。
基本报告独立可用。同时只运行一个收集器;并发报告保留基本内容,不追加辅助部分。终止请求被拒绝时,必须观察到退出才能释放该名额。“获取诊断报告”可能在追加完成前定位基本文件。完成标记仅表示收集结束,不表示捕获了全部操作;排队字节数和遗漏计数说明缺失材料。
故障构造与验收步骤见[本地验证](../../tests/README.zh.md#verification-diagnostics);应用概览与开发入口见 [Desktop README](../../README.zh.md)。
+2
View File
@@ -84,6 +84,8 @@
"@deepseek-ai/dsh-client-shortcuts": "workspace:*",
"@deepseek-ai/dsh-atomic-write": "workspace:*",
"@deepseek-ai/dsh-client-product-analytics": "workspace:*",
"@deepseek-ai/dsh-plugin-manager": "workspace:*",
"zod": "4.4.3",
"@deepseek-ai/dsh-util-file-drag": "workspace:*"
}
}
@@ -139,6 +139,7 @@ export function createElectronBuilderConfig(
},
files: [
'lib/main.js',
'lib/operation-report-worker.js',
'lib/welcome/**/*',
'lib/preload-app.cjs',
'lib/preload-mandatory.cjs',
+5
View File
@@ -29,6 +29,8 @@ export interface CrashReportApp {
/** Inputs of {@link renderCrashReport} and {@link writeCrashReport}. */
export interface CrashReportInput {
/** The shell will attempt an independently bounded operation-history append after saving this report. */
readonly operationHistoryPlanned?: boolean
readonly source: CrashReportSource
readonly phase: CrashReportPhase
readonly error: unknown
@@ -125,6 +127,9 @@ export function renderCrashReport(input: CrashReportInput): string {
...(input.hostDiagnostic === undefined ? [] : ['--- host diagnostic (as reported by the Host process) ---', input.hostDiagnostic, '']),
'--- renderer console (error level, oldest first) ---',
consoleSection,
...(input.operationHistoryPlanned === true ? ['', '--- auxiliary diagnostics ---',
'Operation history is best effort. Without its completion marker below, it is unavailable or incomplete.',
'Recent operations are context only. Missing records do not establish that no changes occurred.'] : []),
'',
].join('\n')
}
+51 -23
View File
@@ -12,10 +12,14 @@ interface RecoveryOperations {
disablePlugins(): Promise<void>
exit(): void
restart(): void
/** Reveal an existing report in the system file manager; reject if it is no longer available. */
revealReport(path: string): Promise<void>
/** Persist the complete diagnostic; resolves with the file path, or `undefined` when nothing was written. */
writeReport(error: unknown, source: CrashReportSource): Promise<string | undefined>
}
type ReportState = { kind: 'pending' } | { kind: 'failed' } | { kind: 'ready'; path: string }
/** Upper bound on waiting for the crash report before the dialog opens. */
export const CRASH_REPORT_WAIT_MS = 1_000
@@ -25,28 +29,28 @@ const DETAIL_BUDGET = 1200
/** Tail lines of the error kept in the dialog; the report file holds the rest. */
const DETAIL_TAIL_LINES = 8
/**
* Compose the dialog detail: the error's last lines (prefixed by the
* shortening notice when they are not the whole error), then the report path
* when one was written, then the reinstall advice. The report line does not
* depend on shortening: a short error that was persisted names its file too.
/** At most eight error-tail lines; status, advice and truncation notice share the detail character budget.
* The message heading has its own field.
*/
function dialogDetail(error: string, messages: DesktopMessages, reportPath: string | undefined): string {
function dialogDetail(error: string, messages: DesktopMessages, reportState: ReportState): string {
const advice = `\n\n${messages.startupReinstallAdvice}`
const report = reportLine(messages, reportPath)
const report = reportLine(messages, reportState)
const tail = error.split(/\r\n|[\n\r\u2028\u2029]/u).slice(-DETAIL_TAIL_LINES).join('\n')
const budget = DETAIL_BUDGET - advice.length - report.length - messages.diagnosticTruncated.length - 1
const shortened = tail.slice(-budget).replace(/^[\uDC00-\uDFFF]/u, '')
return `${shortened === error ? error : `${messages.diagnosticTruncated}\n${shortened}`}${report}${advice}`
}
function reportLine(messages: DesktopMessages, reportPath: string | undefined): string {
return reportPath === undefined ? '' : `\n${formatDesktopMessage(messages.reportWrittenTo, { path: reportPath })}`
function reportLine(messages: DesktopMessages, state: ReportState): string {
if (state.kind === 'pending') return `\n${messages.reportPending}`
if (state.kind === 'failed') return `\n${messages.reportUnavailable}`
return `\n${formatDesktopMessage(messages.reportWrittenTo, { path: state.path })}`
}
/** Deduplicates fatal reports while keeping explicit recovery-operation failures actionable. */
export class DesktopFatalRecovery {
private reported = false
private reportState: ReportState = { kind: 'pending' }
/** @param operations - Native presentation, report persistence, and application-owned shutdown operations. */
constructor(private readonly operations: RecoveryOperations) {}
@@ -57,7 +61,7 @@ export class DesktopFatalRecovery {
/**
* Show the first fatal error; later reports cannot replace it or open another dialog.
* The crash report is written first, bounded by {@link CRASH_REPORT_WAIT_MS}, so the dialog can name it;
* a slow or failed write shows the dialog without a path.
* a slow or failed write shows its status. Retrieving a report rechecks the same write.
* @param error - Fatal failure, including nested diagnostic causes.
* @param source - Where the failure surfaced, recorded in the report.
* @returns Completion of the user's recovery action; duplicate reports resolve immediately.
@@ -66,25 +70,42 @@ export class DesktopFatalRecovery {
if (this.reported) return
this.reported = true
const messages = this.operations.messages()
const reportPath = await this.persist(error, source)
const report = this.persist(error, source)
await this.waitForReport(report)
let detail = desktopErrorState(error).message
let message = messages.fatalSummary
for (;;) {
const addressInUse = /\blisten EADDRINUSE\b/u.test(detail)
const buttons = addressInUse
? [messages.exitApplication, messages.restartApplication]
: [messages.exitApplication, messages.restartApplication, messages.disableThirdPartyPlugins]
const reportButton = this.reportState.kind === 'failed' ? undefined : buttons.length
if (reportButton !== undefined) buttons.push(messages.getDiagnosticReport)
const { response } = await this.operations.show({
type: 'error',
title: messages.startupFailed,
message,
detail: addressInUse
? `${messages.startupAddressInUse}${reportLine(messages, reportPath)}`
: dialogDetail(detail, messages, reportPath),
buttons: addressInUse
? [messages.exitApplication, messages.restartApplication]
: [messages.exitApplication, messages.restartApplication, messages.disableThirdPartyPlugins],
? `${messages.startupAddressInUse}${reportLine(messages, this.reportState)}`
: dialogDetail(detail, messages, this.reportState),
buttons,
defaultId: 1,
cancelId: 0,
noLink: true,
})
if (response === reportButton) {
await this.waitForReport(report)
if (this.reportState.kind === 'ready') {
try {
await this.operations.revealReport(this.reportState.path)
message = messages.reportShareHint
} catch (failure) {
console.error('dsh desktop: could not reveal crash report', failure)
message = messages.reportRevealFailed
}
}
continue
}
if (response === 0) {
try { await this.operations.stop() } catch (failure) { console.error(failure) }
this.operations.exit()
@@ -103,16 +124,23 @@ export class DesktopFatalRecovery {
}
}
private async persist(error: unknown, source: CrashReportSource): Promise<string | undefined> {
let timer: ReturnType<typeof setTimeout> | undefined
private async persist(error: unknown, source: CrashReportSource): Promise<void> {
try {
return await Promise.race([
this.operations.writeReport(error, source),
new Promise<undefined>((resolve) => { timer = setTimeout(() => { resolve(undefined) }, CRASH_REPORT_WAIT_MS) }),
])
const path = await this.operations.writeReport(error, source)
this.reportState = path === undefined ? { kind: 'failed' } : { kind: 'ready', path }
} catch (failure) {
console.error('dsh desktop: crash report failed', failure)
return undefined
this.reportState = { kind: 'failed' }
}
}
private async waitForReport(report: Promise<void>): Promise<void> {
let timer: ReturnType<typeof setTimeout> | undefined
try {
await Promise.race([
report,
new Promise<void>((resolve) => { timer = setTimeout(resolve, CRASH_REPORT_WAIT_MS) }),
])
} finally {
clearTimeout(timer)
}
+26 -2
View File
@@ -2,8 +2,10 @@
import { spawn, type ChildProcess } from 'node:child_process'
import { join } from 'node:path'
import { z } from 'zod'
import type { PlatformSession } from '@deepseek-ai/dsh-deepseek-account'
import { desktopNodeEnvironment } from './node-environment.ts'
import { parsePluginOperationRecord, type PluginOperationRecord, type PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
interface ReadyEvent {
readonly type: 'ready'
@@ -23,7 +25,10 @@ interface PlatformSessionEvent {
readonly session: PlatformSession | null
}
type DesktopHostEvent = ReadyEvent | FatalEvent | PlatformSessionEvent | { readonly type: 'shutdown-complete' } | {
type DesktopHostEvent = ReadyEvent | FatalEvent | PlatformSessionEvent | {
readonly type: 'starting'
readonly runId: PluginOperationRunId
} | { readonly type: 'shutdown-complete' } | {
readonly type: 'file-drag-resource'
readonly requestId: number
readonly resource: { readonly path: string; readonly sha256: string; readonly size: number } | null
@@ -54,11 +59,14 @@ export interface DesktopQuitInspection {
export const QUIT_INSPECTION_DEADLINE_MS = 2_000
const MAX_HOST_DIAGNOSTIC_CHARS = 64 * 1024
const runIdSchema = z.uuid()
function isDesktopHostEvent(message: unknown): message is DesktopHostEvent {
if (typeof message !== 'object' || message === null || !('type' in message)) return false
const candidate = message as Record<string, unknown>
switch (candidate.type) {
case 'starting':
return runIdSchema.safeParse(candidate.runId).success
case 'shutdown-complete':
return true
case 'ready':
@@ -148,6 +156,7 @@ export class DesktopHostFatalError extends Error {
/** One Web backend running under the Electron executable in Node mode. */
export class DesktopHostProcess {
private runId: PluginOperationRunId | undefined
private child: ChildProcess | undefined
private readyResolve!: (ready: DesktopHostReady) => void
private readyReject!: (error: Error) => void
@@ -177,6 +186,7 @@ export class DesktopHostProcess {
* `office-skills` resources fail Host startup.
* @param packageManager - Bundled pnpm entry and Node launcher directory, scoped to package operations.
* @param onPlatformSession - Private credential updates for embedded Platform views.
* @param onPluginOperation - Optional diagnostic sink; malformed records are ignored without failing the Host.
*/
constructor(
private readonly node: string,
@@ -189,6 +199,7 @@ export class DesktopHostProcess {
private readonly packageManager?: { readonly pnpm: string; readonly nodeBin: string },
private readonly onPlatformSession?: (session: PlatformSession | null) => void,
private readonly onPluginOperation?: (record: PluginOperationRecord) => void,
) {}
/**
@@ -216,12 +227,24 @@ export class DesktopHostProcess {
child.stderr?.on('data', (chunk: string) => { this.stderr = (this.stderr + chunk).slice(-MAX_HOST_DIAGNOSTIC_CHARS) })
child.stdout?.pipe(process.stdout)
child.on('message', (message: unknown) => {
if (typeof message === 'object' && message !== null && 'type' in message && message.type === 'plugin-operation') {
const record = 'record' in message ? parsePluginOperationRecord(message.record) : undefined
if (record !== undefined && record.runId === this.runId) {
try { this.onPluginOperation?.(record) }
catch (_error) {
// Diagnostic persistence cannot invalidate the Host's business IPC channel.
console.error('desktop plugin operation diagnostic sink failed')
}
}
return
}
if (!isDesktopHostEvent(message)) {
this.fail(new Error('dsh desktop host sent an invalid IPC event'))
child.kill('SIGTERM')
return
}
if (message.type === 'ready') this.readyResolve({ url: message.url, injections: message.injections })
if (message.type === 'starting') this.runId = message.runId
else if (message.type === 'ready') this.readyResolve({ url: message.url, injections: message.injections })
else if (message.type === 'platform-session') this.onPlatformSession?.(message.session)
else if (message.type === 'shutdown-complete') {
if (this.stopping) this.shutdownCompleted = true
@@ -344,6 +367,7 @@ export class DesktopHostProcess {
}
private fail(error: Error): void {
if (this.runId !== undefined) Object.assign(error, { hostRunId: this.runId })
this.onPlatformSession?.(null)
this.readyReject(error)
for (const request of this.controlRequests.values()) request.reject(error)
+38
View File
@@ -0,0 +1,38 @@
/** Last confirmed shell language, available even when the Host cannot start. */
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { resolveDesktopLocale, type DesktopLocale } from './locale.ts'
/**
* Read the last confirmed language without requiring Host settings.
* @param userData - Electron userData directory.
* @returns Cached language, or undefined when missing, invalid or unreadable.
*/
export function readDesktopLocaleCache(userData: string): DesktopLocale['id'] | undefined {
try {
const value = readFileSync(join(userData, 'desktop', 'locale-cache'), 'utf8').trim()
const locale = resolveDesktopLocale(value)
if (locale.id === value) return locale.id
throw new Error('expected a canonical Desktop locale id')
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
console.warn('desktop locale cache: using system language because the cache could not be read', error)
}
return undefined
}
}
/**
* Remember a confirmed language; write failure leaves the active language unchanged.
* @param userData - Electron userData directory.
* @param locale - Language confirmed by Host settings or the owned renderer.
*/
export function writeDesktopLocaleCache(userData: string, locale: DesktopLocale['id']): void {
try {
const directory = join(userData, 'desktop')
mkdirSync(directory, { recursive: true, mode: 0o700 })
writeFileSync(join(directory, 'locale-cache'), `${locale}\n`, { mode: 0o600 })
} catch (error) {
console.warn('desktop locale cache: language could not be saved for the next startup', error)
}
}
+40
View File
@@ -61,6 +61,11 @@ export const en = {
startupAddressInUse: 'Another DSH instance (such as dsh web or the desktop app) is running. They cannot start at the same time. Quit the other running DSH instance, then restart.',
diagnosticTruncated: '… Error details shortened.',
reportWrittenTo: 'Diagnostic report: {path}',
getDiagnosticReport: 'Get diagnostic report',
reportPending: 'The diagnostic report is still being saved. Choose Get diagnostic report to check again.',
reportUnavailable: 'The diagnostic report could not be saved. You can provide a screenshot of this dialog when requesting support.',
reportShareHint: 'The report location has been opened. Attach the selected file to your support ticket.',
reportRevealFailed: 'The report location could not be opened. Use the path below to find the file.',
startupReinstallAdvice: 'If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.',
exitApplication: 'Exit',
restartApplication: 'Restart',
@@ -235,6 +240,11 @@ export const zh = {
startupAddressInUse: '有其他正在运行的 DSH(如其他 dsh web、桌面端),无法同时启动,请退出其他正在运行的 DSH 后重启。',
diagnosticTruncated: '… 错误详情已截短。',
reportWrittenTo: '诊断报告:{path}',
getDiagnosticReport: '获取诊断报告',
reportPending: '诊断报告仍在保存,可点击“获取诊断报告”再次检查。',
reportUnavailable: '诊断报告未能保存,反馈问题时可提供此窗口的截图。',
reportShareHint: '已打开报告位置,请将选中的文件附在支持工单中。',
reportRevealFailed: '无法打开报告位置,请通过下方路径查找文件。',
startupReinstallAdvice: '如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。',
exitApplication: '退出',
restartApplication: '重启',
@@ -407,6 +417,11 @@ export const ja = {
startupAddressInUse: '別の DSH インスタンス (dsh web やデスクトップアプリなど) が実行中です。同時に起動することはできません。実行中の他の DSH インスタンスを終了してから再起動してください。',
diagnosticTruncated: '… エラー詳細は省略されています。',
reportWrittenTo: '診断レポート: {path}',
getDiagnosticReport: '診断レポートを取得',
reportPending: '診断レポートを保存中です。「診断レポートを取得」を選択して再度確認してください。',
reportUnavailable: '診断レポートを保存できませんでした。サポートへのお問い合わせ時に、このダイアログのスクリーンショットを提供できます。',
reportShareHint: 'レポートの保存場所を開きました。選択されたファイルをサポートチケットに添付してください。',
reportRevealFailed: 'レポートの保存場所を開けませんでした。以下のパスからファイルを探してください。',
startupReinstallAdvice: 'アプリケーションファイルが見つからないか破損している場合は、アプリケーションを閉じて再インストールしてください。タスクは別途保存されています。',
exitApplication: '終了',
restartApplication: '再起動',
@@ -579,6 +594,11 @@ export const es = {
startupAddressInUse: 'Se está ejecutando otra instancia de DSH (como la web de dsh o la aplicación de escritorio). No pueden empezar al mismo tiempo. Salga de la otra instancia DSH en ejecución y luego reinicie.',
diagnosticTruncated: '… Detalles del error acortados.',
reportWrittenTo: 'Informe de diagnóstico: {path}',
getDiagnosticReport: 'Obtener informe de diagnóstico',
reportPending: 'El informe de diagnóstico se está guardando. Seleccione Obtener informe de diagnóstico para volver a comprobarlo.',
reportUnavailable: 'No se pudo guardar el informe de diagnóstico. Puede proporcionar una captura de pantalla de este diálogo al solicitar asistencia.',
reportShareHint: 'Se ha abierto la ubicación del informe. Adjunte el archivo seleccionado a su solicitud de asistencia.',
reportRevealFailed: 'No se pudo abrir la ubicación del informe. Use la ruta que aparece a continuación para encontrar el archivo.',
startupReinstallAdvice: 'Si faltan archivos de la aplicación o están dañados, ciérrela y vuelva a instalarla. Sus tareas se almacenan por separado.',
exitApplication: 'Salir',
restartApplication: 'Reiniciar',
@@ -751,6 +771,11 @@ export const fr = {
startupAddressInUse: "Une autre instance DSH (telle que le Web dsh ou l'application de bureau) est en cours d'exécution. Ils ne peuvent pas démarrer en même temps. Quittez l'autre instance DSH en cours d'exécution, puis redémarrez.",
diagnosticTruncated: '… Détails de l’erreur raccourcis.',
reportWrittenTo: 'Rapport de diagnostic : {path}',
getDiagnosticReport: 'Obtenir le rapport de diagnostic',
reportPending: 'Le rapport de diagnostic est en cours d’enregistrement. Sélectionnez Obtenir le rapport de diagnostic pour vérifier à nouveau.',
reportUnavailable: 'Le rapport de diagnostic n’a pas pu être enregistré. Vous pouvez fournir une capture d’écran de cette boîte de dialogue lorsque vous contactez l’assistance.',
reportShareHint: 'L’emplacement du rapport a été ouvert. Joignez le fichier sélectionné à votre demande d’assistance.',
reportRevealFailed: 'L’emplacement du rapport n’a pas pu être ouvert. Utilisez le chemin ci-dessous pour trouver le fichier.',
startupReinstallAdvice: "Si les fichiers de l'application sont manquants ou endommagés, fermez l'application et réinstallez-la. Vos tâches sont stockées séparément.",
exitApplication: 'Quitter',
restartApplication: 'Redémarrer',
@@ -923,6 +948,11 @@ export const de = {
startupAddressInUse: 'Eine andere DSH-Instanz (z. B. dsh Web oder die Desktop-App) wird ausgeführt. Sie können nicht gleichzeitig starten. Beenden Sie die andere laufende DSH-Instanz und starten Sie sie neu.',
diagnosticTruncated: '… Fehlerdetails gekürzt.',
reportWrittenTo: 'Diagnosebericht: {path}',
getDiagnosticReport: 'Diagnosebericht abrufen',
reportPending: 'Der Diagnosebericht wird noch gespeichert. Wählen Sie „Diagnosebericht abrufen“, um ihn erneut zu prüfen.',
reportUnavailable: 'Der Diagnosebericht konnte nicht gespeichert werden. Sie können bei einer Supportanfrage einen Screenshot dieses Dialogs bereitstellen.',
reportShareHint: 'Der Speicherort des Berichts wurde geöffnet. Fügen Sie die ausgewählte Datei Ihrer Supportanfrage bei.',
reportRevealFailed: 'Der Speicherort des Berichts konnte nicht geöffnet werden. Verwenden Sie den folgenden Pfad, um die Datei zu finden.',
startupReinstallAdvice: 'Wenn Anwendungsdateien fehlen oder beschädigt sind, schließen Sie die Anwendung und installieren Sie sie erneut. Ihre Aufgaben werden separat gespeichert.',
exitApplication: 'Beenden',
restartApplication: 'Neustart',
@@ -1095,6 +1125,11 @@ export const ru = {
startupAddressInUse: 'Другой экземпляр DSH (например, веб-приложение dsh или настольное приложение) запущен. Они не могут начаться одновременно. Закройте другой работающий экземпляр DSH, а затем перезапустите.',
diagnosticTruncated: '… Подробности об ошибках сокращены.',
reportWrittenTo: 'Диагностический отчет: {path}',
getDiagnosticReport: 'Получить диагностический отчет',
reportPending: 'Диагностический отчет еще сохраняется. Выберите «Получить диагностический отчет», чтобы проверить еще раз.',
reportUnavailable: 'Не удалось сохранить диагностический отчет. При обращении в службу поддержки можно приложить снимок экрана этого диалогового окна.',
reportShareHint: 'Открыта папка с отчетом. Прикрепите выбранный файл к обращению в службу поддержки.',
reportRevealFailed: 'Не удалось открыть папку с отчетом. Найдите файл по указанному ниже пути.',
startupReinstallAdvice: 'Если файлы приложения отсутствуют или повреждены, закройте приложение и переустановите его. Ваши задачи хранятся отдельно.',
exitApplication: 'Выход',
restartApplication: 'Перезапустить',
@@ -1267,6 +1302,11 @@ export const pt = {
startupAddressInUse: 'Outra instância DSH (como dsh web ou aplicativo de desktop) está em execução. Eles não podem começar ao mesmo tempo. Saia da outra instância DSH em execução e reinicie.',
diagnosticTruncated: '… Detalhes do erro reduzidos.',
reportWrittenTo: 'Relatório de diagnóstico: {path}',
getDiagnosticReport: 'Obter relatório de diagnóstico',
reportPending: 'O relatório de diagnóstico ainda está sendo salvo. Selecione Obter relatório de diagnóstico para verificar novamente.',
reportUnavailable: 'Não foi possível salvar o relatório de diagnóstico. Você pode fornecer uma captura de tela desta caixa de diálogo ao solicitar suporte.',
reportShareHint: 'O local do relatório foi aberto. Anexe o arquivo selecionado à sua solicitação de suporte.',
reportRevealFailed: 'Não foi possível abrir o local do relatório. Use o caminho abaixo para encontrar o arquivo.',
startupReinstallAdvice: 'Se os arquivos do aplicativo estiverem ausentes ou danificados, feche o aplicativo e reinstale-o. Suas tarefas são armazenadas separadamente.',
exitApplication: 'Sair',
restartApplication: 'Reiniciar',
+90 -19
View File
@@ -2,7 +2,7 @@ import type { ProductEventMap, ProductEvent } from '@deepseek-ai/dsh-client-prod
import { WINDOWS_TITLEBAR_HEIGHT } from './windows-layout.ts'
/** Electron shell: desktop project ownership, custom protocol, windows, and lifecycle. */
import { readFile, writeFile } from 'node:fs/promises'
import { access, readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
@@ -41,6 +41,8 @@ import { DesktopCommandManager } from './command-management.ts'
import { serveWebDocument, authenticateWebHost, forwardWebRequest } from './web-document.ts'
import { DesktopFatalRecovery } from './fatal-recovery.ts'
import { pruneCrashReports, RendererConsoleTail, writeCrashReport, type CrashReportSource } from './crash-report.ts'
import { OperationJournal } from './operation-journal.ts'
import { runOperationReportJob, type OperationReportJobResult } from './operation-report-job.ts'
import { openWelcomeWindow } from './welcome-window.ts'
import { WELCOME_IPC, needsWelcome, type WelcomeNotice } from './welcome-api.ts'
import { connectDesktopWelcome, type DesktopWelcomeBackend } from './welcome-backend.ts'
@@ -55,6 +57,7 @@ import { desktopClientMetadata, desktopClientVersion } from './client-metadata.t
import { DesktopMandatoryUpdateWindow } from './mandatory-update-window.ts'
import { DesktopPolicyTestAuth } from './policy-test-auth.ts'
import { readDesktopSettings } from './settings.ts'
import { readDesktopLocaleCache, writeDesktopLocaleCache } from './locale-cache.ts'
import { DesktopUpdateDialog, type UpdateDialogOptions } from './update-dialog.ts'
import { readDesktopRuntime } from './runtime-tree.ts'
import { DesktopBrowserGuests } from './browser-guests.ts'
@@ -65,14 +68,14 @@ import { DesktopTray } from './tray.ts'
import { DesktopBackgroundNotice } from './background-notice.ts'
let focusPrimaryWindow = (): void => {}
let stopForRecovery = async (): Promise<void> => {}
let stopForRecovery = async (): Promise<void> => { await stopOperationReports() }
let shuttingDown = false
/**
* Set by quit entries that must not ask: crash recovery exit and restart, and the
* development restart command. The installer handoff has its own before-quit branch.
*/
let skipQuitConfirmation = false
let windowsLanguage: string | undefined
let windowsLanguage: string | undefined = readDesktopLocaleCache(app.getPath('userData'))
/**
* Whether the backend has reached ready: false until the first ready, back to
* false when a restart returns it to starting, frozen during shutdown so a
@@ -106,10 +109,39 @@ const recovery = new DesktopFatalRecovery({
exit: () => { quitWithoutConfirmation() },
restart: () => { app.relaunch(); quitWithoutConfirmation() },
writeReport: (error, source) => persistCrashReport(error, source),
revealReport: async (path) => { await access(path); shell.showItemInFolder(path) },
})
let operationJournal: OperationJournal | undefined
let operationReportJob: Promise<OperationReportJobResult> | undefined
let operationReportAbort: AbortController | undefined
let operationReportsStopping = false
let operationReportStop: Promise<void> | undefined
/** Bound application shutdown waiting without claiming that an unresponsive Worker has exited. */
function stopOperationReports(): Promise<void> {
operationReportStop ??= waitForOperationReports()
return operationReportStop
}
async function waitForOperationReports(): Promise<void> {
operationReportsStopping = true
operationReportAbort?.abort()
const job = operationReportJob
if (job === undefined) return
let timer: ReturnType<typeof setTimeout> | undefined
try {
const exited = await Promise.race([job.then(() => true), new Promise<false>((resolve) => {
timer = setTimeout(() => { resolve(false) }, 500)
})])
if (!exited) console.error('dsh desktop: operation report Worker has not exited; continuing shutdown')
} finally { clearTimeout(timer) }
}
function persistCrashReport(error: unknown, source: CrashReportSource): Promise<string | undefined> {
return writeCrashReport(app.getPath('logs'), {
const directory = app.getPath('logs')
const report = writeCrashReport(directory, {
operationHistoryPlanned: !shuttingDown && !operationReportsStopping,
source,
phase: backendReady ? 'running' : 'startup',
error,
@@ -121,6 +153,17 @@ function persistCrashReport(error: unknown, source: CrashReportSource): Promise<
},
time: new Date(),
})
void report.then((path) => {
if (path !== undefined && operationReportJob === undefined && !shuttingDown && !operationReportsStopping) {
operationReportAbort = new AbortController()
operationReportJob = runOperationReportJob({ reportPath: path, directory: join(app.getPath('userData'), 'plugin-operations'),
limits: { bytes: 64 * 1024, recordBytes: 4096, records: 100, outputBytes: 64 * 1024 },
journal: operationJournal?.status() ?? null,
}, { timeoutMs: 500, cancellationGraceMs: 100 }, operationReportAbort.signal)
void operationReportJob.finally(() => { operationReportJob = undefined; operationReportAbort = undefined })
}
}).catch((_error: unknown) => { /* Basic persistence failure is owned by fatal recovery. */ })
return report
}
function reportFatal(error: unknown, source: CrashReportSource): void {
@@ -130,7 +173,12 @@ function reportFatal(error: unknown, source: CrashReportSource): void {
void persistCrashReport(error, source)
return
}
void recovery.report(error, source).catch((failure: unknown) => { console.error(failure); app.exit(1) })
void recovery.report(error, source).catch(async (failure: unknown) => {
console.error(failure)
shuttingDown = true
await stopOperationReports()
app.exit(1)
})
}
protocol.registerSchemesAsPrivileged([{
@@ -374,7 +422,8 @@ async function main(): Promise<void> {
let updateStopFailure: DesktopHostUncleanExitError | undefined
let updateState: DesktopUpdateState = { phase: 'idle' }
const systemLanguages = app.getPreferredSystemLanguages()
let locale = resolveDesktopStartupLocale(null, systemLanguages)
let locale = windowsLanguage === undefined
? resolveDesktopStartupLocale(null, systemLanguages) : resolveDesktopLocale(windowsLanguage)
windowsLanguage = locale.id
let mandatoryPolicy: DesktopMandatoryUpdatePolicy | undefined
let mandatoryUI: DesktopMandatoryUpdateWindow | undefined
@@ -470,7 +519,12 @@ async function main(): Promise<void> {
const host = new DesktopHostProcess(resources.node, resources.dsh, activeProject,
hostInspectPort, { ...hostEnvironment, DSH_CLIENT_VERSION: desktopClientVersion() }, onFailure,
primaryRuntime,
resources, (next) => { platformView.setSession(next) })
resources, (next) => { platformView.setSession(next) }, (record) => {
operationJournal ??= new OperationJournal(join(app.getPath('userData'), 'plugin-operations'), {
segmentBytes: 256 * 1024, recordBytes: 4096, queuedBytes: 64 * 1024,
})
operationJournal.enqueue(JSON.stringify(record))
})
return {
start: async () => {
const ready = await host.start()
@@ -565,6 +619,10 @@ async function main(): Promise<void> {
fileDragStopped = false
}
const restoreHost = state.failedOperation === 'install' && updateStoppedHost && !quitting
if (state.failedOperation === 'install' && !quitting) {
operationReportsStopping = shuttingDown
operationReportStop = undefined
}
shellInstallerOwnsQuit = false
updateStoppedHost = false
if (restoreHost) {
@@ -593,7 +651,11 @@ async function main(): Promise<void> {
if (backend.host === undefined || welcomeBackend === undefined) throw new Error('desktop welcome: backend unavailable')
return welcomeBackend.read()
}
stopForRecovery = () => backend.close()
stopForRecovery = async () => {
const reports = stopOperationReports()
try { await backend.close() }
finally { await Promise.all([operationJournal?.drain(500), reports]) }
}
const reconcileBackend = (): Promise<void> => {
startup ??= (async () => {
@@ -651,14 +713,17 @@ async function main(): Promise<void> {
await disposeFileDrag().catch((error: unknown) => { console.error(error) })
requireCleanStop = true
updateStopFailure = undefined
await backend.stop()
await Promise.all([backend.stop(), stopOperationReports()])
updateStoppedHost = true
// The backend's async cleanup callback can assign this after the reset above.
const stopFailure = updateStopFailure as DesktopHostUncleanExitError | undefined
if (stopFailure !== undefined) throw new DesktopUpdatePreparationError('stop-failed', locale.messages.updateStopFailed, stopFailure.message)
await operationJournal?.drain(500)
updateJournal?.action('install-confirmed')
shellInstallerOwnsQuit = true
} catch (error) {
operationReportsStopping = shuttingDown
operationReportStop = undefined
if (!updateStoppedHost) await host.updateTasks('unlock').catch((unlockError: unknown) => { console.error(unlockError) })
throw error
} finally {
@@ -793,6 +858,7 @@ async function main(): Promise<void> {
if (window === undefined || event.sender !== window.webContents || event.senderFrame !== window.webContents.mainFrame
|| typeof next !== 'string') return
const current = resolveDesktopStartupLocale(next, systemLanguages)
writeDesktopLocaleCache(app.getPath('userData'), current.id)
if (current.id === locale.id) return
locale = current
platformView.notifyLocaleChanged()
@@ -1076,13 +1142,11 @@ async function main(): Promise<void> {
Menu.buildFromTemplate(items).popup({ window, x: Math.round(x * zoom), y: Math.round(y * zoom), callback: resolve })
})
})
ipcMain.on(DESKTOP_IPC.windowsAppearance, (event, language: unknown, color: unknown, symbolColor: unknown) => {
ipcMain.on(DESKTOP_IPC.windowsAppearance, (event, _language: unknown, color: unknown, symbolColor: unknown) => {
if (mainWindow === undefined || event.sender !== mainWindow.webContents
|| event.senderFrame !== mainWindow.webContents.mainFrame) return
if (!event.senderFrame.url.startsWith(`${SCHEME}://app/`)) return
if (typeof language === 'string' && /^[a-zA-Z]+(?:-[a-zA-Z0-9]+)*$/u.test(language)) {
windowsLanguage = language
}
// Document lang starts as English before Host locale bootstrap; only localeChanged owns shell language.
// Empty colors precede client stylesheet installation; only CSS color values cross IPC.
const validColor = (value: unknown): value is string => typeof value === 'string'
&& /^(?:#[\da-f]{3,8}|rgba?\([\d.,%\s]+\))$/iu.test(value)
@@ -1236,6 +1300,7 @@ async function main(): Promise<void> {
const state = await readWelcomeState()
if (isQuitting() || backend.state.phase !== 'ready') return
locale = resolveDesktopStartupLocale(state.localePreference, systemLanguages)
writeDesktopLocaleCache(app.getPath('userData'), locale.id)
windowsLanguage = locale.id
refreshApplicationMenu()
if (!enteredWorkspace && needsWelcome({ loggedIn: state.loggedIn, hasApiKey: state.hasApiKey })) {
@@ -1288,11 +1353,15 @@ async function main(): Promise<void> {
updateSchedule.dispose()
updateDialog.dispose()
mandatoryUI?.dispose()
void Promise.all([Promise.resolve(mandatoryPolicy?.dispose()).then(() => policyAuth?.dispose()), backend.close(),
// A Platform cleanup failure is logged without cutting the remaining Host shutdown short.
platformView.dispose().catch((error: unknown) => { console.error(error) }),
disposeFileDrag().catch((error: unknown) => { console.error(error) })])
.catch((error: unknown) => { console.error(error) }).finally(() => { app.quit() })
void Promise.all([stopOperationReports(), Promise.resolve(mandatoryPolicy?.dispose()).then(() => policyAuth?.dispose()),
backend.close().then(async () => { await operationJournal?.drain(500) }, async (error: unknown) => {
await operationJournal?.drain(500)
throw error
}),
platformView.dispose(),
disposeFileDrag(),
].map(cleanup => cleanup.catch((error: unknown) => { console.error(error) })))
.then(() => { app.quit() })
}
app.on('before-quit', (event) => {
if (shellInstallerOwnsQuit) {
@@ -1381,7 +1450,9 @@ if (ownsDesktopInstance) void app.whenReady().then(main).catch(async (error: unk
await writeFile(diagnosticFile, `${error instanceof Error ? error.stack ?? message : message}\n`).catch(() => undefined)
}
reportFatal(error, 'main')
}).catch((error: unknown) => {
}).catch(async (error: unknown) => {
console.error(error)
shuttingDown = true
await stopOperationReports()
app.exit(1)
})
+120
View File
@@ -0,0 +1,120 @@
/** Bounded, cancellable reads of Desktop-owned plugin operation history. */
import { open } from 'node:fs/promises'
import { join } from 'node:path'
import { setImmediate } from 'node:timers/promises'
import { parsePluginOperationRecord, type PluginOperationRecord } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
/** Resource budgets for auxiliary history collection, independent of basic crash report writing. */
export interface OperationHistoryReadLimits {
readonly bytes: number
readonly recordBytes: number
readonly records: number
}
/** Collection facts; incomplete history must not be interpreted as absence of plugin changes. */
export interface OperationHistoryReadResult {
readonly records: readonly PluginOperationRecord[]
readonly bytesRead: number
/** Distinct files from which at least one byte was read. */
readonly filesRead: number
readonly truncated: boolean
readonly invalidRecords: number
readonly unavailableFiles: number
readonly cancelled: boolean
}
/**
* Read only the bounded tails of the two owned history files, newest segment first.
* Cancellation is observed between bounded records after yielding to Worker messages and stops subsequent I/O and parsing.
* An already-issued OS read must settle before its handle closes.
* @param directory - Desktop's operation history directory; unrelated files are never enumerated.
* @param limits - Positive byte, record-size and record-count budgets.
* @param signal - Caller-owned collection deadline or shutdown cancellation.
* @returns Partial records and explicit omissions; filesystem failures never reject the collection.
*/
export async function readOperationHistory(
directory: string,
limits: OperationHistoryReadLimits,
signal: AbortSignal,
): Promise<OperationHistoryReadResult> {
if (![limits.bytes, limits.recordBytes, limits.records].every(value => Number.isSafeInteger(value) && value > 0)) {
throw new RangeError('Operation history budgets must be positive safe integers')
}
await setImmediate()
const cancelled = (): boolean => signal.aborted
const records: PluginOperationRecord[] = []
let bytesRead = 0
const seenFiles = new Set<string>()
let truncated = false
let invalidRecords = 0
let unavailableFiles = 0
for (const name of ['operations.jsonl', 'operations.previous.jsonl']) {
if (cancelled()) break
try {
await using handle = await open(join(directory, name), 'r')
if (cancelled()) break
const fileStat = await handle.stat()
if (cancelled()) break
if (!fileStat.isFile()) {
unavailableFiles++
continue
}
const identity = `${String(fileStat.dev)}:${String(fileStat.ino)}`
if (seenFiles.has(identity)) {
truncated = true
continue
}
if (fileStat.size > 0 && (bytesRead >= limits.bytes || records.length >= limits.records)) {
truncated = true
break
}
const readLength = Math.min(fileStat.size, limits.bytes - bytesRead)
const readStart = fileStat.size - readLength
const buffer = Buffer.alloc(readLength)
let readOffset = 0
while (readOffset < readLength && !cancelled()) {
const read = await handle.read(buffer, readOffset, Math.min(16 * 1024, readLength - readOffset), readStart + readOffset)
bytesRead += read.bytesRead
if (read.bytesRead === 0) break
readOffset += read.bytesRead
}
if (readOffset > 0) seenFiles.add(identity)
if (cancelled()) break
truncated ||= readStart > 0 || readOffset < readLength
// An unterminated last record can still be in flight; never parse it as a committed record.
if (readOffset === 0) continue
let lineEnd = buffer.lastIndexOf(10, readOffset - 1)
if (lineEnd !== readOffset - 1) truncated = true
while (lineEnd >= 0 && records.length < limits.records && !cancelled()) {
await setImmediate()
if (cancelled()) break
const previousLineEnd = lineEnd === 0 ? -1 : buffer.lastIndexOf(10, lineEnd - 1)
if (previousLineEnd < 0 && readStart > 0) {
truncated = true
break
}
const recordBytes = lineEnd - previousLineEnd - 1
if (recordBytes > limits.recordBytes) {
invalidRecords++
} else if (recordBytes > 0) {
try {
const value: unknown = JSON.parse(buffer.subarray(previousLineEnd + 1, lineEnd).toString('utf8'))
const record = parsePluginOperationRecord(value)
if (record === undefined) invalidRecords++
else records.push(record)
} catch (_error) {
// A corrupt record does not invalidate independently delimited older records.
invalidRecords++
}
}
lineEnd = previousLineEnd
}
if (lineEnd >= 0) truncated = true
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') unavailableFiles++
}
}
return { records, bytesRead, filesRead: seenFiles.size, truncated, invalidRecords, unavailableFiles, cancelled: cancelled() }
}
+208
View File
@@ -0,0 +1,208 @@
/** Single-shell, bounded persistence for already-projected operation diagnostics. */
import { mkdir, open, rename, stat, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
/** Budgets include serialized JSON and its line delimiter. */
export interface OperationJournalLimits {
readonly segmentBytes: number
readonly recordBytes: number
readonly queuedBytes: number
}
/** In-memory omissions for the current shell lifetime; missing records never imply no operations occurred. */
export interface OperationJournalStatus {
readonly dropped: number
readonly failed: number
readonly queuedBytes: number
readonly disabled: boolean
/** Damaged or oversized segments repaired; their lost record count is unknown. */
readonly repairedSegments: number
}
/** Owns two known files and one serial writer; the owning shell must exclude other writers. */
export class OperationJournal {
private readonly queue: string[] = []
private queuedBytes = 0
private dropped = 0
private failed = 0
private repairedSegments = 0
private disabled = false
private closed = false
private writing: Promise<void> | undefined
private initialized = false
private readonly abort = new AbortController()
/**
* @param directory - Directory reserved for the shell's operation journal.
* @param limits - Positive byte budgets, with recordBytes no greater than either other budget.
*/
constructor(
private readonly directory: string,
private readonly limits: OperationJournalLimits,
) {
if (![limits.segmentBytes, limits.recordBytes, limits.queuedBytes].every(value => Number.isSafeInteger(value) && value > 0)
|| limits.recordBytes > limits.segmentBytes || limits.recordBytes > limits.queuedBytes) {
throw new RangeError('Invalid operation journal budgets')
}
}
/**
* Queue one prevalidated, whitelisted JSON record without awaiting disk I/O.
* @param record - An already serialized JSON object without literal line delimiters.
* @returns Whether the record was accepted; disk failures are reported separately by status().
*/
enqueue(record: string): boolean {
const line = record + '\n'
const bytes = Buffer.byteLength(line)
if (this.closed || this.disabled || bytes > this.limits.recordBytes
|| bytes + this.queuedBytes > this.limits.queuedBytes || /[\r\n]/u.test(record)) {
this.dropped++
return false
}
this.queue.push(line)
this.queuedBytes += bytes
this.startWriter()
return true
}
/** @returns Current queue occupancy and omission counters. */
status(): OperationJournalStatus {
return {
dropped: this.dropped,
failed: this.failed,
queuedBytes: this.queuedBytes,
disabled: this.disabled,
repairedSegments: this.repairedSegments,
}
}
/** Stop accepting records and await completion of the owned writer. */
async close(): Promise<void> {
this.closed = true
while (this.writing !== undefined) await this.writing
}
/**
* Wait for queued records during shutdown or installer handoff without holding the application indefinitely.
* @param timeoutMs - Waiting budget before disabling the writer and cancelling subsequent I/O.
* @returns True after the queue settles successfully; false immediately when disabled, or on failure or deadline.
* False does not confirm that an issued OS request has settled.
*/
async drain(timeoutMs: number): Promise<boolean> {
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1) throw new RangeError('Invalid journal drain deadline')
if (this.disabled) return false
let timer: ReturnType<typeof setTimeout> | undefined
try {
return await Promise.race([
(async () => {
while (this.writing !== undefined) await this.writing
return !this.disabled
})(),
new Promise<false>((resolve) => {
timer = setTimeout(() => {
this.disabled = true
this.abort.abort()
resolve(false)
}, timeoutMs)
}),
])
} finally {
clearTimeout(timer)
}
}
private startWriter(): void {
this.writing ??= this.writeQueue().finally(() => {
this.writing = undefined
if (this.queue.length > 0) this.startWriter()
})
}
private async writeQueue(): Promise<void> {
try {
await mkdir(this.directory, { recursive: true, mode: 0o700 })
this.abort.signal.throwIfAborted()
const current = join(this.directory, 'operations.jsonl')
const previous = join(this.directory, 'operations.previous.jsonl')
if (!this.initialized) {
await this.prepareSegments(current, previous)
this.initialized = true
}
for (let line = this.queue[0]; line !== undefined; line = this.queue[0]) {
this.abort.signal.throwIfAborted()
const bytes = Buffer.byteLength(line)
let size = 0
try {
size = (await stat(current)).size
}
catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
this.abort.signal.throwIfAborted()
if (size > this.limits.segmentBytes) {
// An oversized pre-existing segment is not copied into the bounded retained history.
await writeFile(current, '', { mode: 0o600 })
this.repairedSegments++
} else if (size + bytes > this.limits.segmentBytes) {
await rename(current, previous)
}
this.abort.signal.throwIfAborted()
await writeFile(current, line, { flag: 'a', mode: 0o600, signal: this.abort.signal })
this.queue.shift()
this.queuedBytes -= bytes
}
} catch (_error) {
// A failed append may have written a partial line; disable this writer rather than concatenate another record.
this.disabled = true
this.failed += this.queue.length
this.queue.length = 0
this.queuedBytes = 0
}
}
private async prepareSegments(current: string, previous: string): Promise<void> {
try {
const size = (await stat(previous)).size
this.abort.signal.throwIfAborted()
if (size > this.limits.segmentBytes) {
await writeFile(previous, '', { mode: 0o600 })
this.repairedSegments++
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
this.abort.signal.throwIfAborted()
{
await using handle = await open(current, 'r+').catch((error: unknown) => {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
this.abort.signal.throwIfAborted()
return open(current, 'wx+', 0o600)
})
this.abort.signal.throwIfAborted()
const size = (await handle.stat()).size
this.abort.signal.throwIfAborted()
if (size > this.limits.segmentBytes) {
await handle.truncate(0)
this.repairedSegments++
} else if (size > 0) {
const byte = Buffer.alloc(1)
const read = await handle.read(byte, 0, 1, size - 1)
if (read.bytesRead !== 1 || byte[0] !== 10) {
const buffer = Buffer.alloc(size)
let offset = 0
while (offset < size) {
this.abort.signal.throwIfAborted()
const chunk = await handle.read(buffer, offset, size - offset, offset)
if (chunk.bytesRead === 0) break
offset += chunk.bytesRead
}
this.abort.signal.throwIfAborted()
// Keep committed lines in both segments; only the unfinished append is discarded.
await handle.truncate(buffer.subarray(0, offset).lastIndexOf(10) + 1)
this.repairedSegments++
}
}
}
this.abort.signal.throwIfAborted()
}
}
+106
View File
@@ -0,0 +1,106 @@
/** Worker lifetime for an auxiliary report; completion includes worker exit. */
import { Worker } from 'node:worker_threads'
import type { OperationReportLimits } from './operation-report.ts'
import type { OperationJournalStatus } from './operation-journal.ts'
/** Facts passed to the isolated collector after the basic report is saved. */
export interface OperationReportJobInput {
readonly reportPath: string
readonly directory: string
readonly limits: OperationReportLimits
readonly journal: OperationJournalStatus | null
}
/** Collection and cooperative shutdown share one total budget. */
export interface OperationReportJobOptions {
/** Deadline for requesting forced termination, including Worker startup. */
readonly timeoutMs: number
/** Reserved part of timeoutMs for cancellation and resource cleanup. */
readonly cancellationGraceMs: number
}
/** Cancellation can leave a partial append; the independently saved basic report remains valid. */
export interface OperationReportJobResult {
readonly appended: boolean
readonly timedOut: boolean
readonly cancelled: boolean
}
/**
* Collect history, request cooperative cancellation, then force termination if cleanup exceeds its budget.
* @param input - Bounded collection request for an existing basic report.
* @param options - Total deadline and the cleanup window reserved within it.
* @param signal - Application shutdown or recovery cancellation; an already-aborted signal prevents startup.
* @returns Append outcome only after Worker exit; cancellation or termination requests alone do not confirm exit.
*/
export async function runOperationReportJob(
input: OperationReportJobInput,
options: OperationReportJobOptions,
signal: AbortSignal,
): Promise<OperationReportJobResult> {
const { timeoutMs, cancellationGraceMs } = options
if (!Number.isSafeInteger(timeoutMs) || !Number.isSafeInteger(cancellationGraceMs)
|| cancellationGraceMs < 1 || timeoutMs <= cancellationGraceMs) throw new RangeError('Invalid operation report deadlines')
if (signal.aborted) return { appended: false, timedOut: false, cancelled: true }
const terminationDeadline = performance.now() + timeoutMs
let worker: Worker
try {
worker = new Worker(new URL('./operation-report-worker.js', import.meta.url), {
workerData: input,
resourceLimits: {
maxOldGenerationSizeMb: 32,
maxYoungGenerationSizeMb: 8,
stackSizeMb: 2,
},
})
}
catch (_error) {
return { appended: false, timedOut: false, cancelled: false }
}
return new Promise((resolve) => {
let appended = false
let failed = false
let timedOut = false
let cancelled = false
let terminationTimer: ReturnType<typeof setTimeout> | undefined
const terminateWorker = (): void => {
void worker.terminate().catch(() => {
failed = true
})
}
const requestCancellation = (): void => {
if (cancelled) return
cancelled = true
clearTimeout(collectionTimer)
try {
worker.postMessage('cancel')
}
catch (_error) {
failed = true
}
terminationTimer = setTimeout(terminateWorker, Math.max(0, Math.min(cancellationGraceMs, terminationDeadline - performance.now())))
}
const collectionTimer = setTimeout(() => {
timedOut = true
requestCancellation()
}, Math.max(0, terminationDeadline - performance.now() - cancellationGraceMs))
signal.addEventListener('abort', requestCancellation, { once: true })
worker.on('message', (message: unknown) => {
appended = message === true
})
worker.once('error', () => {
failed = true
})
worker.once('exit', (code) => {
clearTimeout(collectionTimer)
clearTimeout(terminationTimer)
signal.removeEventListener('abort', requestCancellation)
resolve({ appended: appended && code === 0 && !failed && !cancelled, timedOut, cancelled })
})
if (signal.aborted) requestCancellation()
})
}
@@ -0,0 +1,36 @@
/** Isolated auxiliary-report I/O; the shell owns termination and observes worker exit. */
import { parentPort, workerData } from 'node:worker_threads'
import { z } from 'zod'
import { appendOperationReport } from './operation-report.ts'
const positive = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
const input = z.object({
reportPath: z.string(),
directory: z.string(),
limits: z.object({
bytes: positive,
recordBytes: positive,
records: positive,
outputBytes: positive,
}),
journal: z.object({
dropped: z.number().int().nonnegative(),
failed: z.number().int().nonnegative(),
repairedSegments: z.number().int().nonnegative(),
queuedBytes: z.number().int().nonnegative(),
disabled: z.boolean(),
}).nullable(),
}).parse(workerData)
const cancellation = new AbortController()
const cancel = (message: unknown): void => {
if (message === 'cancel') cancellation.abort()
}
parentPort?.on('message', cancel)
try {
const appended = await appendOperationReport(input.reportPath, input.directory, input.limits, cancellation.signal, input.journal)
parentPort?.postMessage(appended)
} finally {
parentPort?.off('message', cancel)
parentPort?.close()
}
+62
View File
@@ -0,0 +1,62 @@
/** Best-effort operation history appended only after the independent basic report exists. */
import { writeFile } from 'node:fs/promises'
import { setImmediate } from 'node:timers/promises'
import { readOperationHistory, type OperationHistoryReadLimits } from './operation-history.ts'
import type { OperationJournalStatus } from './operation-journal.ts'
/** Read budgets and the complete appended section's UTF-8 byte budget. */
export interface OperationReportLimits extends OperationHistoryReadLimits {
readonly outputBytes: number
}
/**
* Append a bounded summary without rewriting the basic report's bytes.
* A missing completion marker means the auxiliary section is unavailable or incomplete.
* @param reportPath - Successfully saved basic report.
* @param directory - Owned operation history directory.
* @param limits - Read and parse budgets.
* @param signal - Collection deadline or shutdown cancellation; already-issued OS I/O must settle.
* @param journal - Current writer status, or null when this shell has not received operation records.
* @returns Whether the complete auxiliary section was appended.
*/
export async function appendOperationReport(
reportPath: string,
directory: string,
limits: OperationReportLimits,
signal: AbortSignal,
journal: OperationJournalStatus | null,
): Promise<boolean> {
try {
if (!Number.isSafeInteger(limits.outputBytes) || limits.outputBytes < 1) return false
const cancelled = (): boolean => signal.aborted
const history = await readOperationHistory(directory, limits, signal)
if (cancelled()) return false
const { records, ...facts } = history
const renderHeader = (omitted: number): string => '\n--- recent plugin operations (context, not proof of cause) ---\n'
+ JSON.stringify({ journal, ...facts, outputRecordsOmitted: omitted }).slice(0, -1) + ',"records":['
const completionFooter = ']}\n--- operation history collection complete; consult omission counters above ---\n'
let outputBytes = Buffer.byteLength(renderHeader(records.length) + completionFooter)
if (outputBytes > limits.outputBytes) return false
const encodedRecords: string[] = []
for (const record of records) {
await setImmediate()
if (cancelled()) return false
const encodedRecord = JSON.stringify(record)
const additionalBytes = Buffer.byteLength(encodedRecord) + (encodedRecords.length === 0 ? 0 : 1)
if (outputBytes + additionalBytes > limits.outputBytes) break
encodedRecords.push(encodedRecord)
outputBytes += additionalBytes
}
const reportSection = renderHeader(records.length - encodedRecords.length) + encodedRecords.join(',') + completionFooter
await setImmediate()
if (cancelled()) return false
await writeFile(reportPath, reportSection, { flag: 'a', signal })
return true
} catch (_error) {
// The independently written basic report remains usable, including after a partial append.
return false
}
}
+15 -12
View File
@@ -2,27 +2,30 @@
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write apps/desktop/tests/README.md
/desktop-local-update-verification:
en: 194f1f0f1ca90743
zh: 773ca28e04c8911f
/desktop-local-update-verification/summary:
/desktop-local-verification:
en: 5056a9b4d24c1880
zh: 4d0c9d8e5f69d153
/desktop-local-verification/summary:
en: 94559f431b0b2151
zh: 1a22166a2bc59686
/desktop-local-update-verification/table-of-contents:
en: 86afdf78fa613876
zh: 66fad143d99e999f
/desktop-local-update-verification/update-dialog-themes:
/desktop-local-verification/table-of-contents:
en: fa9e3048995c0e3c
zh: ef30232afa4ba125
/desktop-local-verification/fault-report-verification:
en: a418eb04ce93b1ee
zh: 1ec04872a66ce1b7
/desktop-local-verification/update-dialog-themes:
en: d086c3b38ce623f1
zh: 8327c31092f5f174
/desktop-local-update-verification/native-overlay-visibility:
/desktop-local-verification/native-overlay-visibility:
en: 6f4de4503748f3e2
zh: 648370375f16e463
/desktop-local-update-verification/manual-walkthrough:
/desktop-local-verification/manual-walkthrough:
en: c4b4ee8763d8464a
zh: ee2159bc08966592
/desktop-local-update-verification/evidence:
/desktop-local-verification/evidence:
en: dcb2473264c825d4
zh: cebb2832efa15974
/desktop-local-update-verification/open-verification:
/desktop-local-verification/open-verification:
en: 20e9ea47acb1ff50
zh: acce24b56d57e12c
+15 -1
View File
@@ -1,4 +1,4 @@
# Desktop local update verification
# Desktop local verification
English | [中文](README.zh.md)
@@ -10,12 +10,26 @@ Installed qualification can opt into `DSH_DESKTOP_UPDATE_JOURNAL_DIR`, an absolu
## Table of Contents
- [Fault-report verification](#verification-diagnostics)
- [Update dialog themes](#verification-theme)
- [Native overlay visibility](#verification-overlay)
- [Evidence](#verification-evidence)
- [Manual walkthrough](#verification-interactive)
- [Open verification](#verification-open)
<a id="verification-diagnostics"></a>
## Fault-report verification
See [recovery and diagnostics](../docs/diagnostics/README.md) for product behavior and limitations.
Use a disposable profile and separate Electron `userData` with the actual packaged client. Construct a minimal local bundle with `package.json`, `dsh.bundle.patch` pointing to `cordis.patch.yml`, and an optional plugin module; archive it as a local `.tgz`. These packages deliberately break the application and must not be published or installed in a daily profile.
Exercise import and plugin-initialization exceptions, an asynchronous exception after `appReady`, and a nonzero Host exit. A patch disabling the `agent`, `session`, `llm`, and `tools` providers exercises missing-service diagnostics. To check cross-restart history, select that bundle through `pluginManager`, then restart the same profile. Runtime scenarios require observing actual client readiness; `appReady` alone does not establish that the window is visible.
Check the original error and cause or exit code, operation and Host run IDs across restart, report-collection completion and omissions, file retrieval from the native dialog, and startup after plugin recovery. Record the package version and source commit; successful package generation or a management result alone does not establish client functionality. Restore protocol associations and stop test processes afterward.
For resource checks, use large sparse history files, unrelated files, dense records, and malformed or unfinished lines. Measure setup separately from collection in fresh processes, recording actual bytes read, output size, time, and peak memory. To check Worker cancellation, a test-only module hook can hold an asynchronous file open after writing an entry marker. Confirm that marker, observe Worker exit after the deadline, and compare the basic report bytes. This does not reproduce a kernel-hung system call or establish packaged-client behavior.
<a id="verification-theme"></a>
## Update dialog themes
+15 -1
View File
@@ -1,4 +1,4 @@
# Desktop 本地更新验证
# Desktop 本地验证
[English](README.md) | 中文
@@ -10,12 +10,26 @@
## 目录
- [故障报告验证](#verification-diagnostics)
- [更新弹窗主题](#verification-theme)
- [原生浮层可见性](#verification-overlay)
- [验证证据](#verification-evidence)
- [手动演练](#verification-interactive)
- [待验证事项](#verification-open)
<a id="verification-diagnostics"></a>
## 故障报告验证
产品行为与限制见[故障恢复与诊断](../docs/diagnostics/README.zh.md)。
使用可丢弃的 profile、独立的 Electron `userData` 和实际打包客户端。构造最小本地组合包:`package.json` 的 `dsh.bundle.patch` 指向 `cordis.patch.yml`,需要执行代码时再加入插件模块,然后打成可本地安装的 `.tgz`。这些包会故意使应用出错,不得发布或安装到日常 profile。
分别构造模块导入异常、插件初始化异常、`appReady` 后的异步异常,以及 Host 非零退出。用 patch 禁用 `agent`、`session`、`llm`、`tools` 提供者,检查服务缺失诊断。跨重启场景通过 `pluginManager` 选入该组合包,再重启同一 profile。运行期场景须实际观察客户端就绪;`appReady` 不代表窗口已经显示。
检查原始错误与 cause 或退出码、跨重启的操作 ID 和 Host 运行 ID、报告收集完成标记与遗漏信息、原生弹窗中的文件获取,以及禁用插件恢复后的启动。记录安装包版本和源码提交;生成测试包成功或管理操作返回成功,都不能代替客户端功能验证。测试后恢复协议关联并退出测试进程。
资源验证可构造大型稀疏历史文件、大量无关文件、密集记录,以及损坏行和未完成行。在独立新进程中测量,分开记录数据构造与收集开销,并核对实际读取量、输出大小、耗时和峰值内存。验证 Worker 取消时,可用仅测试加载的模块钩子在写入进入标记后挂起异步文件打开操作;先确认标记,再观察期限到达后的 Worker 退出,并逐字节核对基本报告。该方法不模拟内核系统调用卡死,也不代替打包客户端验证。
<a id="verification-theme"></a>
## 更新弹窗主题
@@ -1,5 +1,6 @@
DeepSeek Harness is unavailable
The application could not start or stopped unexpectedly.
Another DSH instance (such as dsh web or the desktop app) is running. They cannot start at the same time. Quit the other running DSH instance, then restart.
The diagnostic report could not be saved. You can provide a screenshot of this dialog when requesting support.
Exit
Restart
@@ -1,5 +1,6 @@
DeepSeek Harness 无法使用
应用无法启动或已意外停止。
有其他正在运行的 DSH(如其他 dsh web、桌面端),无法同时启动,请退出其他正在运行的 DSH 后重启。
诊断报告未能保存,反馈问题时可提供此窗口的截图。
退出
重启
@@ -2,6 +2,7 @@ DeepSeek Harness is unavailable
The application could not start or stopped unexpectedly.
Desktop Host failed
Plugin initialization failed
The diagnostic report could not be saved. You can provide a screenshot of this dialog when requesting support.
If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.
Exit
@@ -8,3 +8,4 @@ If application files are missing or damaged, close the application and reinstall
Exit
Restart
Disable third-party plugins, back up profile patch, and restart
Get diagnostic report
Loaded 100 of 748 files, more files were not shown because too many files have changed in this diff. Show more