Merge branch 'feat/mcp-oauth' into feat/mcp-tool-loading

This commit is contained in:
gengruilin committed 2026-11-03 13:15:58 +08:00
commit 0e856b5ebd
326 files changed
+4098 -999

No files matched your search

@@ -9,8 +9,8 @@
en: 386864a282e5ad58
zh: a4ea75ec70eb7778
/agent-note-shared-native-cua-process-with-agent-scoped-state/decision:
en: 11bab6870c3d802f
zh: a22114f2217a3a41
en: 60ec2276ed0bff33
zh: 5fb48cc787194254
/agent-note-shared-native-cua-process-with-agent-scoped-state/alternatives-considered:
en: 883f71387f599160
zh: 4b5f1450be799397
@@ -12,7 +12,7 @@ On macOS 26.6.2, replayd derives capture-client identity from the executable pat
One user shares a native service per executable content digest across Agents and Hosts. A version lock elects the service; an additional canonical-executable-path lock prevents different builds published at one path from running together. Locks remain held until process exit. The managed startup command hands service lifetime to its client connections, and the last connection's completed cleanup ends the service. The diagnostic stdin/stdout entry proxies to this same service.
The service runs as a signed application launched through LaunchServices. Directly spawning the executable inherits its launcher’s TCC responsibility, so it cannot give the helper independent system permissions. A launch lock serializes discovery and startup. Complete signed applications use immutable content-addressed directories: replacing an executable used by a live process would violate both path-lock ownership and code-signature integrity. Ad-hoc builds can require fresh grants when their code hash changes; a stable bundle identifier alone does not preserve those grants. Installed packages retain their distributed signatures.
The service runs as a signed application launched through LaunchServices. Directly spawning the executable inherits its launcher’s TCC responsibility, so it cannot give the helper independent system permissions. A launch lock serializes discovery and startup. Complete signed applications use immutable content-addressed directories: replacing an executable used by a live process would violate both path-lock ownership and code-signature integrity. Ad-hoc builds can require fresh grants when their code hash changes; a stable bundle identifier alone does not preserve those grants. Source checkouts can keep grants with the [development signing identity](2026-10-29-cua-dev-signing-identity.md). Installed packages retain their distributed signatures.
Each Agent connection owns its application handles, AX snapshots, limits and cancellation state. An app handle grants no exclusive use of the application. A FIFO orders complete desktop operations, including clipboard transactions, while response writes are independent. Agent disposal retires only its connection. The [object API decision](2026-09-17-experimental-cua-object-api.md) retains evaluator independence and coordinate semantics; the [consent decision](2026-09-26-cua-application-consent.md) retains application authorization.
@@ -12,7 +12,7 @@ Status: implemented
同一用户的多个 Agent 和 Host 按可执行文件内容摘要共享原生服务。版本锁选出服务实例,规范化可执行路径上的另一把锁阻止发布在同一路径的不同构建同时运行。进程退出才释放锁。受管启动命令将服务生命期交给客户端连接,最后一条连接清理完成后服务退出。诊断用 stdin/stdout 入口也代理到同一个服务。
服务通过 LaunchServices 以已签名应用运行。直接启动可执行文件会继承启动器的 TCC 责任,无法让 helper 独立取得系统权限。启动锁串行处理发现与启动。完整签名应用保存在不可变的内容寻址目录中,替换运行中进程的可执行文件会破坏路径锁的归属与代码签名完整性。临时签名构建的代码哈希变化后可能需要重新授权,固定 Bundle ID 不能保证保留授权。安装版保留分发时的签名。
服务通过 LaunchServices 以已签名应用运行。直接启动可执行文件会继承启动器的 TCC 责任,无法让 helper 独立取得系统权限。启动锁串行处理发现与启动。完整签名应用保存在不可变的内容寻址目录中,替换运行中进程的可执行文件会破坏路径锁的归属与代码签名完整性。临时签名构建的代码哈希变化后可能需要重新授权,固定 Bundle ID 不能保证保留授权。源码检出可以用[开发签名身份](2026-10-29-cua-dev-signing-identity.zh.md)保留授权。安装版保留分发时的签名。
每条 Agent 连接独立持有应用句柄、AX 快照、资源限制和取消状态。持有 app 句柄不代表独占应用。FIFO 队列串行执行包含剪贴板事务的完整桌面操作,响应写入独立进行。Agent 销毁只释放自己的连接。[对象接口决策](2026-09-17-experimental-cua-object-api.zh.md)继续负责执行器独立性及坐标语义,[授权决策](2026-09-26-cua-application-consent.zh.md)继续负责应用许可。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-10-29-cua-dev-signing-identity.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-29-cua-dev-signing-identity.md
/agent-note-development-signing-identity-for-source-built-cua-helpers:
en: 472c4efd47184a32
zh: 49f64628531970e9
/agent-note-development-signing-identity-for-source-built-cua-helpers/problem:
en: a24857a312482724
zh: dbac75d363670e86
/agent-note-development-signing-identity-for-source-built-cua-helpers/decision:
en: d2265f9ec5fb7a79
zh: 05da2479b024a4bb
/agent-note-development-signing-identity-for-source-built-cua-helpers/alternatives-considered:
en: e30db5bc9c7aab43
zh: fa84883b5527334e
/agent-note-development-signing-identity-for-source-built-cua-helpers/consequences:
en: fb0e8fe44890bdf9
zh: d9e9ace1a4c10060
@@ -0,0 +1,35 @@
# Agent Note: Development signing identity for source-built CUA helpers
Status: implemented
English | [中文](2026-10-29-cua-dev-signing-identity.zh.md)
## Problem
Source checkouts compile `DSH Computer Use.app` with an ad-hoc signature. macOS stores Accessibility and Screen Recording grants for a bundle identifier with the designated requirement of the granted code, and an ad-hoc requirement is the code hash. Every changed build and every other worktree therefore needs new grants, and these builds shared the release helper's bundle identifier and replaced its grant entry.
## Decision
The Host builds source checkouts as a development variant with bundle identifier `com.deepseek.harness.computer-use.dev` and name `DSH Computer Use Dev`, in `DSH Computer Use Dev.app`. The macOS privacy list and the helper’s reported launch application use the bundle filename, so that filename also includes Dev. The release variant and its packaging are unchanged. Grants stay with the helper application launched through LaunchServices, as the [shared helper decision](2026-10-09-cua-shared-native-helper.md) requires.
`sourceSigning` belongs to the macOS provider and accepts only default `ad-hoc` or `{ identity, keychain }` selecting an existing certificate and absolute keychain path. Builds do not create, unlock or remove identities. Developer credentials stay separate from the user-facing DSH home, which stores only the certificate selection; the shared `cua` package owns no macOS signing configuration.
The [developer signing skill](../../../skills/dsh-cua-macos-signing/SKILL.md) guides Agents through creating, reusing and unlocking an isolated identity under `~/.cua-macos-keys/`, then selecting its fingerprint and keychain path in user configuration. The tool stores a random password in a `0600` file, permits codesign access, and adds the dedicated keychain to the user search list. A file lock serializes setup and removal for that directory; a missing keychain with an existing record is preserved and rejected. A directory marker limits identity management to explicitly claimed, initially empty directories. Unexpected files or symlinked identity entries stop setup and removal before changes, so a developer-selected path cannot erase unrelated contents.
Certificate signatures embed a signing time even without a timestamp server. Development publication records which generation each unsigned bundle and identity produced, then selects that generation again instead of re-signing, so identical sources keep one executable digest and one shared service. The cache uses certificate fingerprints; explicit certificate names are not reused because renewal can change the certificate behind a name. Signing failures stop publication. Developer setup diagnostics omit passwords and complete command arguments. The build CLI defaults to `--identity -` and accepts an existing certificate with `--identity` and optional `--keychain` for release packaging.
## Alternatives considered
**Grant the launching terminal.** Launching the service directly makes macOS attribute permissions to the terminal or editor that started DSH. Every program that application runs, including commands run by the model, then has the permissions.
**Automatically create a fixed identity during source builds.** This makes ordinary startup create developer private keys and ties their lifetime to user data. An explicit developer workflow preserves the option to reduce repeated grants while keeping identity creation, removal and selection under developer control.
**Self-signed identity in the login keychain.** The login keychain is already unlocked and on the search list, but allowing `codesign` to use a new key there without a dialog requires the user's login password.
**Add the keychain to the search list only while signing.** The release packaging script does this for one invocation. Concurrent builds in several worktrees would read and restore the user list over each other, and a stopped build would leave the entry behind anyway.
**A stable launcher that spawns each worktree's helper.** Grants would follow the launcher, but any local process could ask it to run an arbitrary executable with those grants, which is the same exposure as the stored key without a signature check.
## Consequences
Development builds signed by the same certificate share a signing requirement; actual permission retention after grants, rebuilds and worktree changes still requires verification. Other processes of the same user can read the stored password and sign with that identity; the release helper has a different bundle identifier. Deleting DSH home removes its selection, not the developer identity; deleting the identity requires clearing every configuration that references it. The real-signing e2e checks reuse, unlocking, requirements across output directories and search-list restoration after removal.
@@ -0,0 +1,35 @@
# Agent Note: 源码构建的 CUA helper 使用开发签名身份
Status: implemented
[English](2026-10-29-cua-dev-signing-identity.md) | 中文
## 问题
源码检出用临时签名编译 `DSH Computer Use.app`。macOS 按 Bundle ID 和被授权代码的指定要求保存辅助功能与屏幕录制授权,临时签名的指定要求就是代码哈希。因此每次构建内容变化、每换一个 worktree,都需要重新授权;这些构建还与正式 helper 共用 Bundle ID,会替换正式版的授权条目。
## 决策
Host 以开发版构建源码检出,Bundle ID 为 `com.deepseek.harness.computer-use.dev`,名称为 `DSH Computer Use Dev`,应用包文件名为 `DSH Computer Use Dev.app`。macOS 隐私列表和 helper 返回的启动应用名称使用应用包文件名,因此文件名也需包含 Dev。正式版及其打包流程不变。按[共享 helper 决策](2026-10-09-cua-shared-native-helper.zh.md)的要求,授权仍归经 LaunchServices 启动的 helper 应用。
`sourceSigning` 由 macOS provider 定义,只接受默认的 `ad-hoc` 和指定已有证书及钥匙串绝对路径的 `{ identity, keychain }`。构建不创建、解锁或移除身份。开发者凭据与面向用户的 DSH home 分开,后者只保存选择证书的配置;共享 `cua` 包不持有 macOS 签名配置。
[开发者签名 skill](../../../skills/dsh-cua-macos-signing/SKILL.md)指导 Agent 在 `~/.cua-macos-keys/` 创建、复用和解锁独立身份,将证书指纹和钥匙串路径写入用户配置。工具把随机密码存入 `0600` 文件,允许 codesign 访问私钥,并把专用钥匙串加入用户搜索列表。文件锁让同一目录的初始化和移除串行执行;已有记录但钥匙串缺失时保留记录并报错。目录标记将身份管理限制在明确占用的初始空目录中。发现无关文件或身份文件软链接时,初始化和移除都会在修改前停止,避免开发者指定的路径导致无关内容被删除。
即使不使用时间戳服务器,证书签名也包含签名时间。开发构建记录每份未签名内容与身份对应的已签名目录,再次构建相同内容时复用该目录,保持可执行文件摘要和共享服务一致。缓存使用证书指纹;按证书名称选择时每次签名,避免续期后复用旧证书。签名失败会中止发布。开发者工具的诊断不包含密码或完整命令参数;构建 CLI 默认 `--identity -`,支持指定证书,正式打包也可省略 `--keychain`。
## 考虑过的替代方案
**把权限交给启动终端。** 直接启动服务时,macOS 把权限归属到启动 DSH 的终端或编辑器。该应用运行的所有程序,包括模型执行的命令,都会带上这些权限。
**源码构建自动创建固定身份。** 这会让普通启动生成开发者私钥,并把身份生命周期绑定到用户数据目录。显式开发者操作保留了减少重新授权的选择,也让证书的创建、移除和使用范围由开发者决定。
**把自签名身份放进登录钥匙串。** 登录钥匙串已解锁且在搜索列表中,但要让 `codesign` 不弹窗地使用其中的新私钥,需要用户的登录密码。
**只在签名期间把钥匙串加入搜索列表。** 正式打包脚本对单次调用这样处理。多个 worktree 并发构建时会互相覆盖读取和恢复的列表,构建被中断时条目也会残留。
**用固定的启动器运行各 worktree 的 helper。** 授权会跟随启动器,但任何本机进程都能让它带着这些授权运行任意可执行文件,暴露面与保存的私钥相同,还少了签名检查。
## 后果
同一证书签出的开发构建共用签名要求;授权后重建和跨 worktree 的实际权限保持仍需验证。同一用户的进程可读取保存的密码并使用该身份签名,正式 helper 使用不同的 Bundle ID。删除 DSH home 只移除配置,不删除开发者身份;删除该身份后应清理所有引用它的配置。真实签名 e2e 验证复用、解锁、不同输出目录的签名要求和移除后的搜索列表恢复。
@@ -12,8 +12,8 @@
en: 47b44ed9313c2ccf
zh: 7ad254f8ef88351d
/agent-note-subagent-end-turn-guidance-stays-in-the-delegation-paragraph/alternatives-considered:
en: d52fa1af379dea5b
zh: 4e404994f7a607dc
en: 3153c1e7563a3357
zh: 9841db2b0156075b
/agent-note-subagent-end-turn-guidance-stays-in-the-delegation-paragraph/verification:
en: be076216381ea64d
zh: 2da8d9819c20e2fe
@@ -29,7 +29,7 @@ The sentence stays one literal line. Rewording `the next result starts a new tur
**Move the guidance into the tool description.** The paragraph is assembled from the set of visible delegation tools and lists their names; the tool description describes one tool. Moving the sentence changes ownership without changing the behavior it prevents.
**Restore every prompt phrase reverted together with this sentence.** The read guidance and the `run_code` argument order are separate decisions with their own evidence; this note records only the delegation paragraph.
**Restore every prompt phrase reverted together with this sentence.** The read guidance ([2026-10-26 note](2026-10-26-read-guidance-line-ranges.md)) and the `run_code` argument order are separate decisions with their own evidence; this note records only the delegation paragraph.
## Verification
@@ -29,7 +29,7 @@ Status: implemented
**把说明移进工具描述。** 这段指导按可见委派工具集合组装并列出工具名,工具描述只描述单个工具。移动这句会改变归属,但不改变它阻止的行为。
**把与这句一起被回退的所有提示词都恢复。** read 指导与 `run_code` 参数顺序是各自有证据的独立决定;本记录只覆盖委派段。
**把与这句一起被回退的所有提示词都恢复。** read 指导([2026-10-26 note](2026-10-26-read-guidance-line-ranges.zh.md))与 `run_code` 参数顺序是各自有证据的独立决定;本记录只覆盖委派段。
## 验证
@@ -0,0 +1,22 @@
# Bilingual-pair consistency record for 2026-10-26-read-guidance-line-ranges.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md
/agent-note-read-guidance-names-shell-readers-and-line-ranges:
en: 1926710614598539
zh: b0106d4a6a2d648d
/agent-note-read-guidance-names-shell-readers-and-line-ranges/problem:
en: 4189d516419d8d12
zh: 30d8496064dd44e3
/agent-note-read-guidance-names-shell-readers-and-line-ranges/decision:
en: 34f18307f7ad87af
zh: 21c466c6ce6c598d
/agent-note-read-guidance-names-shell-readers-and-line-ranges/alternatives-considered:
en: aea7ffb1159ab81a
zh: 4842ca79dc30654d
/agent-note-read-guidance-names-shell-readers-and-line-ranges/verification:
en: cbc16bfba4abe862
zh: 9a71e6c020c01f69
/agent-note-read-guidance-names-shell-readers-and-line-ranges/consequences:
en: cf55161ea197a7a9
zh: fa10ca413f8fd726
@@ -0,0 +1,35 @@
# Agent Note: Read guidance names shell readers and line ranges
Status: implemented
English | [中文](2026-10-26-read-guidance-line-ranges.zh.md)
## Problem
The read guidance named only `cat` as the shell command the read tool replaces, and described `offset`/`limit` as continuing a large file rather than reading a line range. #6057 recorded a long Session reading ranges with `sed -n X,Yp` 60 times. #6054 added `sed`, `head`, `tail`, and the line-range wording; a later prompt revert removed them together with unrelated changes.
The 2026-10-23 evaluation of the SDK profile (native tools, six benchmarks) measured this sentence as the only change: Pass@1 mean −0.03pp and Pass@3 mean +0.70pp over the five benchmarks that report Pass@3 (ProgramBench-New has none) versus the base commit, with mixed step and token deltas (ProgramBench-New −15.5 steps, Terminal-Bench-v4 +13.5 steps). The PTC mode runs did not include this variant; the section renders in every request where `read` is visible.
## Decision
Restore the #6054 wording, byte-identical: `Use the read tool — not shell commands like cat, sed, head, or tail — to inspect text files. Use offset and limit to read a line range or continue a large file.` The read tool and its guidance are owned by `@deepseek-ai/dsh-tool-fs`; write and edit guidance are unchanged.
## Alternatives considered
**Rely on the read tool schema.** The schema already documents `offset` and `limit`, but #6057 shows the model chose `sed` while that schema existed; the guidance is the only model-visible place that names `sed`, `head`, and `tail`.
**Restore every prompt phrase reverted together with this sentence.** The subagent end-turn sentence, the `run_code` argument order, the PTC syntax ownership, and the SDK persona are separate decisions; the first is already restored ([subagent end-turn note](2026-10-21-subagent-end-turn-guidance.md)), and the others carry their own evidence.
**Say "line range" without naming shell commands.** The observed failure was choosing shell commands, so the sentence names them.
## Verification
- `packages/fs/tool-fs/tests/tools.spec.ts` asserts the rendered guidance text.
- Every recorded `system-prompt*.expected.md` sidecar that renders the read guidance carries the restored sentence: `test:snapshot` replays the session and SDK set, and `pnpm run test:web:ci` replays the `snapshots/web` set (the `node 24 / snapshots and artifacts` lane runs both). Two pinned historical sidecars (`web/cordis-tool-round`, `web/schedule-catalog`) retain their recorded text.
- The evaluation above measured this single change on the native SDK profile.
## Consequences
- Every request with the read tool carries three more command names and a line-range clause, about 10 tokens.
- The model is directed to the read tool for line ranges instead of `cat`, `sed`, `head`, or `tail`.
- The benchmark measured this sentence as neutral; keeping it rests on the #6057 production observation, not on a measured quality gain.
@@ -0,0 +1,35 @@
# Agent Note: read 指导点名 shell 读取命令与行区间
Status: implemented
[English](2026-10-26-read-guidance-line-ranges.md) | 中文
## 问题
read 指导只把 `cat` 点名为 read 工具替代的 shell 命令,并把 `offset`/`limit` 描述成继续读大文件,而不是读行区间。#6057 记录了一个长 Session 用 `sed -n X,Yp` 读行区间 60 次。#6054 增加了 `sed`、`head`、`tail` 和行区间措辞;后来的一次提示词回退把它们和不相关的改动一起删掉了。
2026-10-23 对 SDK profile(native 工具、六个 benchmark)的评测里,这句是唯一改动:相对 base commit,Pass@1 均值 −0.03pp、Pass@3 均值 +0.70pp(该均值取报告 Pass@3 的五个 benchmark;ProgramBench-New 没有 Pass@3),步数与 token 变化方向不一(ProgramBench-New −15.5 步、Terminal-Bench-v4 +13.5 步)。PTC 模式的运行没有包含这个变体;只要 `read` 可见,这段就会进入每个请求。
## 决策
逐字恢复 #6054 的措辞:`Use the read tool — not shell commands like cat, sed, head, or tail — to inspect text files. Use offset and limit to read a line range or continue a large file.` read 工具及其指导归 `@deepseek-ai/dsh-tool-fs` 所有;write 与 edit 的指导不变。
## 考虑过的替代方案
**只依赖 read 工具 schema。** schema 已经写明 `offset` 与 `limit`,但 #6057 显示在那个 schema 存在时模型仍选择 `sed`;指导是唯一点名 `sed`、`head`、`tail` 的模型可见位置。
**把与这句一起被回退的所有提示词都恢复。** subagent 结束本轮句、`run_code` 参数顺序、PTC 语法归属、SDK persona 是各自独立的决定;第一项已经恢复([subagent 结束本轮 note](2026-10-21-subagent-end-turn-guidance.zh.md)),其余各有自己的证据。
**只说“行区间”,不点名 shell 命令。** 观测到的失败就是模型选择 shell 命令,所以这句点名它们。
## 验证
- `packages/fs/tool-fs/tests/tools.spec.ts` 断言渲染出的指导文本。
- 所有渲染 read 指导的 `system-prompt*.expected.md` sidecar 都带有恢复后的句子:`test:snapshot` 回放 session 与 SDK 集合,`pnpm run test:web:ci` 回放 `snapshots/web` 集合(`node 24 / snapshots and artifacts` lane 两条都跑)。两个显式 pin 的历史 sidecar(`web/cordis-tool-round`、`web/schedule-catalog`)保留录制文本。
- 上面的评测在 native SDK profile 上只改了这一句进行测量。
## 影响
- 只要 read 工具存在,每个请求多三个命令名和一句行区间说明,约 10 token。
- 模型读行区间时被引导到 read 工具,而不是 `cat`、`sed`、`head`、`tail`。
- benchmark 上这句测得为中性;保留它依据的是 #6057 的生产观测,而不是测到的质量收益。
@@ -9,8 +9,8 @@
en: 7115cbaefaa11d2d
zh: 23aff8797a651a36
/agent-note-settings-driven-mcp-server-manager/decision:
en: 44c2e3e6b7a6bc87
zh: fe83a4ffb0975678
en: 8b86221d251817c0
zh: 226856b72417ac4a
/agent-note-settings-driven-mcp-server-manager/alternatives-considered:
en: daad4acd963926cc
zh: 152f3d35a4fe3309
@@ -12,7 +12,7 @@ Installed application plugins also bring their own servers. Each must add its se
## Decision
`packages/mcp/mcp-manager` is a service plugin (`ctx.mcpServers`) that owns the volatile `servers` configuration and reconciles a fleet of ordinary `dsh-mcp-client` child instances; `packages/mcp/mcp-client` owns connection supervision, status, probing, and per-attempt startup budgets.
`packages/mcp/mcp-manager` is a service plugin (`ctx.mcpManager`) that owns the volatile `servers` configuration and reconciles a fleet of ordinary `dsh-mcp-client` child instances; `packages/mcp/mcp-client` owns connection supervision, status, probing, and per-attempt startup budgets.
**Configuration is volatile Config, and CRUD needs no new API.** Settings projects the manager entry’s Config under its Loader id; ConfigEditor owns profile persistence, inheritance, and revision checks. Settings edits retain inherited servers, and resetting an inherited entry restores its base value. Direct profile patches replace the complete `servers` map. Loader commits the reference before notifying the manager’s existing reconcile queue.
@@ -12,7 +12,7 @@ Status: implemented
## 决策
`packages/mcp/mcp-manager` 是一个服务插件(`ctx.mcpServers`),拥有 volatile `servers` 配置并对一支普通 `dsh-mcp-client` 子实例编队做对账;`packages/mcp/mcp-client` 拥有连接监督、状态、探测与逐次启动预算。
`packages/mcp/mcp-manager` 是一个服务插件(`ctx.mcpManager`),拥有 volatile `servers` 配置并对一支普通 `dsh-mcp-client` 子实例编队做对账;`packages/mcp/mcp-client` 拥有连接监督、状态、探测与逐次启动预算。
**配置由 volatile Config 提供,CRUD 不需要新 API。** Settings 按管理器条目的 Loader id 展示其 Config;ConfigEditor 拥有 profile 持久化、继承和 revision 检查。Settings 编辑保留继承的服务器,重置继承条目会恢复其基层值。直接编写 profile patch 会替换完整 `servers` 映射。Loader 先提交引用,再通知管理器现有的协调队列。
@@ -0,0 +1,78 @@
---
name: dsh-cua-macos-signing
description: Proactively recommend a personal fixed signing key to macOS DSH developers using Computer Use from source, rebuilding the helper, or switching worktrees, even before they ask about repeated permissions. After they choose it, generate or reuse the key outside DSH home and configure its path. Also handles unlocking and removal; installed release users do not need this setup.
---
# macOS CUA development signing
## Recognize developer use and recommend signing
When a macOS developer uses DSH Computer Use from a source checkout, proactively recommend a reusable personal signing identity. Relevant signals include launching DSH from source, rebuilding the helper, preparing another worktree, or investigating repeated permission prompts. The developer does not need to be editing CUA code, and does not need to ask about certificates first. Before a cross-worktree permission-retention test, establish that both builds select the same fixed identity.
Use the task context and available configuration to choose the recommendation. If an identity is already configured, recommend reusing it and unlock it when needed; do not propose another key for each worktree. If signing is unset or `ad-hoc`, briefly explain that code-hash changes can require fresh grants, recommend creating one local identity under `~/.cua-macos-keys/`, and offer to configure `cordis.patch.yml` to select it. Mention that the first macOS grant remains manual. Follow the authorization rule below before creating keys or editing configuration; a recommendation alone does not authorize setup.
For example: “Since you are using Computer Use from source and switching worktrees, I recommend creating one personal signing identity and reusing it across builds to reduce repeated authorization. I can generate it under `~/.cua-macos-keys/` and configure this DSH home to use it. You will still grant macOS permissions once.” Adapt the wording to the user's language and task.
Do not recommend developer keys merely because a user is using the installed DSH app, working on an unrelated repository, or developing without Computer Use. If they choose to keep ad-hoc signing, continue their task and do not repeat the recommendation without a relevant change in circumstances.
## Understand the signing choices
Source builds default to `sourceSigning: ad-hoc`. They need no developer certificate. An ad-hoc designated requirement includes the code hash, so changed binaries, clean rebuilds, or different worktrees can require fresh Accessibility and Screen Recording grants even when their sources are unchanged. For developers who want fewer repeated grants, configure one fixed certificate and use it across builds. The first grant is still manual; verify actual permission retention rather than claiming that matching signatures alone prove it.
The [macOS provider](../../../packages/experimental/cua-macos/README.md#use-this-package) owns the two configuration choices: `ad-hoc`, or `{ identity, keychain }`. The build consumes an existing certificate; it never creates or unlocks one. Developer key material stays outside DSH home. DSH home stores only the configuration selecting it.
## Create or reuse an identity
Run from a repository checkout on macOS with the selected Apple command-line tools. An explicit request to set up developer signing or reduce repeated development grants authorizes setup and the corresponding local configuration edit. For advice-only requests, explain the choices without creating an identity.
```sh
python3 .agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py setup
```
The script creates or reuses `~/.cua-macos-keys/dev/signing.keychain-db`, stores its password and certificate fingerprint in the adjacent `identity.json` with mode `0600`, and keeps the directory private. It adds only its dedicated keychain to the user search list and enables `codesign` access without prompting for the login password. A sibling `dev.lock` serializes setup and removal across worktrees; custom directory names keep their full name before `.lock`. Supply `--directory <absolute identity directory>` when the developer chose another location outside DSH home and the checkout.
Setup claims only a new or empty directory and writes `.dsh-cua-macos-signing` as its ownership marker. Setup and removal refuse directories without that marker, unexpected entries, or symlinked identity files before changing keychains or identity files. Preserve unmarked identities from earlier tooling; do not add a marker automatically. They can still be selected as existing user keychains.
Setup prints only the certificate fingerprint and absolute keychain path as JSON. Keep the password record out of chat, logs, commits, and configuration. Other processes running as this user can read the stored password and use this development identity; this is the local developer setup's access model.
If an existing record is damaged or its keychain/certificate is missing, setup stops. Do not silently replace that identity: replacement changes the certificate and can require new grants. Follow the reported remove/setup commands only when identity replacement is authorized.
## Configure the source build
Resolve the DSH home used by the developer (`DSH_HOME`, otherwise `~/.dsh`). Merge the two printed values into its `cordis.patch.yml`, targeting the entry that loads `@deepseek-ai/dsh-experimental-cua-macos`. The shipped entry ID is `cua`:
```yaml
- id: cua
config:
sourceSigning:
identity: "<fingerprint printed by setup>"
keychain: "/Users/<user>/.cua-macos-keys/dev/signing.keychain-db"
```
Use the printed absolute path, not a literal `~`. Preserve unrelated patches and every existing field in this entry's effective config: a Cordis patch replaces the complete `config` object rather than deep-merging it. If the provider has `helperPath`, source signing is bypassed; remove that override only when the developer intends to test the source-built helper. Ensure the profile actually loads the provider before adding a patch for its ID.
Launch through the developer's existing `dsh` profile. The home-level patch shares the selection across profiles and worktrees that use that home. Other DSH homes can explicitly select the same certificate. Record the paths changed and the selected public fingerprint, never the password.
## Unlock and verify
After a restart or a manual keychain lock, rerun `setup`; it unlocks and reuses the existing identity. Do not ask the developer for the login-keychain password or store one. A source build does not automatically unlock the keychain and can fail or prompt if it is locked.
Grant Accessibility and Screen Recording to `DSH Computer Use Dev.app` in System Settings. Call `getCapabilities`, change and rebuild the Swift helper, then test another worktree with the same configuration. Report the observed permission flags for each step. Matching `codesign -d -r- <application>` requirements confirm signature continuity but do not replace the permission checks.
For a temporary, permission-free signing mechanism check, run:
```sh
python3 .agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py
```
It creates an isolated identity, tests reuse and unlocking, signs changed binaries, then removes its keychain and checks search-list restoration. Run it without concurrent keychain-list mutations.
## Remove an identity
First remove the selecting configuration or set `sourceSigning: ad-hoc` in each affected home. For an authorized removal, run:
```sh
python3 .agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py remove
```
Use the same `--directory` for a custom location. Removal deletes only the marked identity’s files and its search-list entry, then removes the empty directory; the empty sibling lock remains so waiting processes still coordinate. Deleting DSH home alone leaves the developer identity intact. System Settings permission entries are separate; remove them only when requested.
@@ -0,0 +1,77 @@
"""Real development signing keeps one designated requirement across changed builds.
Creates a temporary development identity, adds its keychain to the user search list for the duration
of the check, and removes both afterwards. No system permission or password dialog is requested.
"""
import importlib.util
import json
from pathlib import Path
import plistlib
import subprocess
import sys
import tempfile
NATIVE = Path(__file__).resolve().parents[4] / "packages/experimental/cua-macos/native"
def module(name):
spec = importlib.util.spec_from_file_location(name, NATIVE / "build_app.py" if name == "build_app" else Path(__file__).with_name("signing_identity.py"))
loaded = importlib.util.module_from_spec(spec)
spec.loader.exec_module(loaded)
return loaded
def requirement(application):
output = subprocess.run(["/usr/bin/codesign", "-d", "-r-", str(application)], check=True, capture_output=True, text=True)
return next(line.split("=> ", 1)[1] for line in (output.stdout + output.stderr).splitlines() if "designated =>" in line)
def main():
builder, signing = module("build_app"), module("dev_signing")
before = signing.user_keychains()
with tempfile.TemporaryDirectory(prefix="cua-dev-signing-e2e-") as temporary:
root = Path(temporary)
directory = root / "keys/dev"
try:
command = [sys.executable, str(Path(__file__).with_name("signing_identity.py")), "setup", "--directory", str(directory)]
configuration = json.loads(subprocess.run(command, check=True, capture_output=True, text=True).stdout)
identity = signing.setup(directory)
assert configuration == {"identity": identity.sha1, "keychain": str(identity.keychain.resolve())}
assert signing.setup(directory) == identity
sha1, keychain = identity.sha1, identity.keychain
assert (directory / "identity.json").stat().st_mode & 0o777 == 0o600
signing.security("lock-keychain", str(keychain))
assert signing.setup(directory) == identity, "setup must unlock an existing developer keychain"
requirements = []
for status in (0, 1):
(root / "main.c").write_text(f"int main(void) {{ return {status}; }}\n")
subprocess.run(["/usr/bin/xcrun", "clang", "-o", str(root / "helper"), str(root / "main.c")], check=True)
executable = builder.publish(root / "helper", root / f"checkout-{status}", sha1, NATIVE / "Info.plist", "dev", keychain)
application = executable.parents[2]
assert application.name == "DSH Computer Use Dev.app", application
subprocess.run(["/usr/bin/codesign", "--verify", "--strict", str(application)], check=True)
info = plistlib.loads((application / "Contents/Info.plist").read_bytes())
assert info["CFBundleIdentifier"] == "com.deepseek.harness.computer-use.dev", info
requirements.append((application, requirement(application)))
(first, first_requirement), (second, second_requirement) = requirements
assert first != second, "changed builds must publish separate generations"
assert first_requirement == second_requirement, requirements
assert "certificate leaf" in first_requirement and "cdhash" not in first_requirement, first_requirement
subprocess.run(["/usr/bin/codesign", "--verify", f"-R={first_requirement}", str(second)], check=True)
selected = json.loads((root / "checkout-1/current.json").read_text())["bundle"]
assert second.parent.name == selected
for index, (certificate, selected_keychain) in enumerate(((sha1, keychain), (signing.COMMON_NAME, keychain))):
custom = builder.publish(root / "helper", root / f"custom-{index}", certificate, NATIVE / "Info.plist", "dev", selected_keychain)
assert requirement(custom.parents[2]) == first_requirement
print(f"PASS: developer setup reuses and unlocks its identity; configured signatures across changed builds share {first_requirement}")
finally:
try:
signing.remove(directory)
finally:
# This fixture owns the temporary directory even if ownership validation fails.
signing.clear_identity(directory)
assert signing.user_keychains() == before, "the user keychain search list was not restored"
if __name__ == "__main__":
main()
@@ -0,0 +1,258 @@
"""Manage an explicitly requested developer identity outside DSH home.
macOS keeps Accessibility and Screen Recording grants for a bundle identifier together with the
designated requirement of the signature that was granted. An ad-hoc signature's requirement is the
code hash, so every changed build loses the grant. A certificate signature's requirement names the
bundle identifier and the certificate, preserving the requirement across changed builds.
The identity lives in a dedicated keychain whose password is stored beside it with owner-only
permissions, so developer setup can unlock it without a system dialog. Any process running as the same
user can read that password and sign code that inherits the development grants; the grants belong
to the development bundle identifier only, never to the release helper.
"""
import argparse
from contextlib import contextmanager
from dataclasses import dataclass
import fcntl
import json
import os
from pathlib import Path
import re
import secrets
import shlex
import subprocess
import sys
import tempfile
COMMON_NAME = "DSH Computer Use Dev (local)"
OWNER_MARKER = ".dsh-cua-macos-signing"
OWNER_VERSION = "1\n"
SECURITY = "/usr/bin/security"
OPENSSL = "/usr/bin/openssl"
SETUP_COMMAND = "python3 .agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py setup"
REMOVE_COMMAND = "python3 .agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py remove"
CERTIFICATE_CONFIG = f"""[req]
distinguished_name = subject
x509_extensions = extensions
prompt = no
[subject]
CN = {COMMON_NAME}
[extensions]
basicConstraints = critical,CA:false
keyUsage = critical,digitalSignature
extendedKeyUsage = critical,codeSigning
"""
@dataclass(frozen=True)
class SigningIdentity:
"""An unlocked certificate identity that codesign can use without user interaction."""
sha1: str
keychain: Path
def private_command(command, **kwargs):
"""Run signing tools without exposing secret arguments or their echoed output in diagnostics."""
operation = f"{Path(command[0]).name} {command[1]}"
try:
return subprocess.run(command, check=True, capture_output=True, text=True, timeout=60, **kwargs).stdout
except subprocess.CalledProcessError as error:
raise RuntimeError(f"{operation} failed (exit {error.returncode})") from None
except subprocess.TimeoutExpired:
raise RuntimeError(f"{operation} timed out after 60 seconds") from None
except OSError as error:
raise RuntimeError(f"{operation} could not run (errno {error.errno})") from None
def security(*args):
return private_command([SECURITY, *args])
@contextmanager
def identity_lock(directory):
"""Serialize setup and removal across worktrees; the lock inode survives identity removal."""
directory.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
with os.fdopen(os.open(directory.parent / f"{directory.name}.lock", os.O_WRONLY | os.O_CREAT, 0o600), "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
yield
def user_keychains():
"""Read the user keychain search list that codesign consults for identities."""
return [line.strip().strip('"') for line in security("list-keychains", "-d", "user").splitlines() if line.strip()]
def listed(keychain, keychains):
"""Compare canonical paths; security reports /private/var for /var and resolves other links."""
return any(os.path.realpath(path) == os.path.realpath(keychain) for path in keychains)
def record_path(directory):
return directory / "identity.json"
def keychain_path(directory):
return directory / "signing.keychain-db"
def default_directory():
"""Keep developer credentials independent of DSH profiles, homes, and worktrees."""
return Path.home() / ".cua-macos-keys" / "dev"
def owned_directory(directory, create=False):
"""Refuse unowned or mixed-content directories before changing files or keychains."""
marker = directory / OWNER_MARKER
if create:
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
if not any(directory.iterdir()):
directory.chmod(0o700)
with os.fdopen(os.open(marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as file:
file.write(OWNER_VERSION)
if not directory.exists():
return
if marker.is_symlink() or not marker.is_file() or marker.read_bytes() != OWNER_VERSION.encode():
raise RuntimeError(f"Refusing unowned signing directory: {directory}; choose a new or empty dedicated directory")
allowed = {OWNER_MARKER, record_path(directory).name, record_path(directory).with_suffix(".tmp").name, keychain_path(directory).name}
for entry in directory.iterdir():
# security creates empty .flXXXXXXXX locks and removes them with delete-keychain.
system_lock = re.fullmatch(r"\.fl[0-9A-Fa-f]{8}", entry.name) and entry.is_file() and entry.stat().st_size == 0
if (entry.name not in allowed and not system_lock) or entry.is_symlink() or not entry.is_file():
raise RuntimeError(f"Refusing signing directory with unrelated entries: {directory}; preserve those entries before retrying")
def load(directory):
"""Unlock the configured identity before signing.
Returns None when setup has not run. Raises when setup ran but its keychain is missing or no
longer on the search list, because signing would otherwise fail or prompt for a password.
"""
directory_argument = shlex.quote(str(directory))
setup_command = f"{SETUP_COMMAND} --directory {directory_argument}"
remove_command = f"{REMOVE_COMMAND} --directory {directory_argument}"
record = record_path(directory)
if not record.exists():
return None
try:
fields = json.loads(record.read_text())
valid = isinstance(fields, dict) and isinstance(fields.get("password"), str) and isinstance(fields.get("sha1"), str) and bool(fields["password"]) and bool(fields["sha1"])
except (ValueError, OSError):
valid = False
if not valid:
raise RuntimeError(f"Computer Use development signing record is invalid; run {remove_command}, then {setup_command}")
keychain = keychain_path(directory)
if not keychain.is_file():
raise RuntimeError(f"Computer Use development signing keychain is missing: {keychain}; run {remove_command}, then {setup_command}")
if not listed(keychain, user_keychains()):
raise RuntimeError(f"Computer Use development signing keychain is not on the user keychain search list; run {setup_command}")
# A locked keychain makes codesign show a password dialog, so unlock it explicitly every time.
security("unlock-keychain", "-p", fields["password"], str(keychain))
if fields["sha1"] not in security("find-identity", str(keychain)):
raise RuntimeError(f"Computer Use development signing certificate is missing; run {remove_command}, then {setup_command}")
return SigningIdentity(sha1=fields["sha1"], keychain=keychain)
def create_certificate(directory, password):
"""Create the key pair inside the dedicated keychain and return the certificate SHA-1."""
keychain = keychain_path(directory)
with tempfile.TemporaryDirectory(prefix=".certificate-", dir=directory) as temporary:
work = Path(temporary)
(work / "openssl.cnf").write_text(CERTIFICATE_CONFIG)
export_password = secrets.token_hex(16)
for command in (
["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", "key.pem", "-out", "certificate.pem",
"-days", "3650", "-config", "openssl.cnf"],
["pkcs12", "-export", "-inkey", "key.pem", "-in", "certificate.pem", "-out", "identity.p12",
"-passout", f"pass:{export_password}"],
):
private_command([OPENSSL, *command], cwd=work)
fingerprint = private_command([OPENSSL, "x509", "-in", "certificate.pem", "-noout", "-fingerprint", "-sha1"], cwd=work)
security("create-keychain", "-p", password, str(keychain))
security("unlock-keychain", "-p", password, str(keychain))
# No arguments disables the inactivity timeout and lock on sleep.
security("set-keychain-settings", str(keychain))
security("import", str(work / "identity.p12"), "-k", str(keychain), "-P", export_password, "-T", "/usr/bin/codesign")
# Without a partition list, codesign asks the user to allow access to the private key.
security("set-key-partition-list", "-S", "apple-tool:,apple:", "-s", "-k", password, str(keychain))
match = re.search(r"=([0-9A-F:]+)", fingerprint)
if match is None:
raise RuntimeError("openssl returned no certificate fingerprint")
sha1 = match.group(1).replace(":", "")
if sha1 not in security("find-identity", str(keychain)):
raise RuntimeError("the imported development signing identity is not usable")
return sha1
def setup(directory):
"""Create an identity only without a record; preserve recorded identities when their keychain is missing."""
with identity_lock(directory):
return setup_locked(directory)
def setup_locked(directory):
owned_directory(directory, create=True)
keychain = keychain_path(directory)
if record_path(directory).exists():
if keychain.is_file():
keychains = user_keychains()
if not listed(keychain, keychains):
security("list-keychains", "-d", "user", "-s", *keychains, str(keychain))
return load(directory)
clear_identity(directory)
password = secrets.token_hex(32)
sha1 = create_certificate(directory, password)
security("list-keychains", "-d", "user", "-s", *user_keychains(), str(keychain))
record = record_path(directory)
with os.fdopen(os.open(record.with_suffix(".tmp"), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as file:
json.dump({"sha1": sha1, "password": password}, file)
file.write("\n")
os.replace(record.with_suffix(".tmp"), record)
return load(directory)
def remove(directory):
"""Delete the keychain, its search-list entry and the stored password."""
with identity_lock(directory):
remove_locked(directory)
def remove_locked(directory):
owned_directory(directory)
clear_identity(directory)
if directory.exists():
(directory / OWNER_MARKER).unlink()
directory.rmdir()
def clear_identity(directory):
"""Remove only the identity files and its exact keychain search-list entry."""
keychain = keychain_path(directory)
keychains = user_keychains()
if listed(keychain, keychains):
security("list-keychains", "-d", "user", "-s", *[path for path in keychains if not listed(keychain, [path])])
if keychain.exists():
security("delete-keychain", str(keychain))
record_path(directory).unlink(missing_ok=True)
record_path(directory).with_suffix(".tmp").unlink(missing_ok=True)
def main():
parser = argparse.ArgumentParser(description="Manage the local signing identity for source-built Computer Use applications.")
parser.add_argument("action", choices=["setup", "remove"])
parser.add_argument("--directory", type=Path, default=default_directory(), help="identity directory; defaults to ~/.cua-macos-keys/dev")
args = parser.parse_args()
directory = args.directory.expanduser().resolve()
if args.action == "setup":
identity = setup(directory)
print(json.dumps({"identity": identity.sha1, "keychain": str(identity.keychain)}, indent=2))
else:
remove(directory)
print("Removed the development signing identity; remove its sourceSigning configuration before the next build")
if __name__ == "__main__":
try:
main()
except RuntimeError as error:
print(error, file=sys.stderr)
sys.exit(1)
@@ -0,0 +1,335 @@
"""Development signing setup keeps one unlocked identity on the user keychain search list."""
import contextlib
import io
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location("dev_signing", Path(__file__).with_name("signing_identity.py"))
signing = importlib.util.module_from_spec(spec)
spec.loader.exec_module(signing)
class FakeSecurity:
"""Record security commands and model the user search list."""
def __init__(self, keychains):
self.keychains = list(keychains)
self.commands = []
def __call__(self, *args):
self.commands.append(args)
if args[:3] == ("list-keychains", "-d", "user") and len(args) == 3:
return "".join(f' "{path}"\n' for path in self.keychains)
if args[:4] == ("list-keychains", "-d", "user", "-s"):
self.keychains = list(args[4:])
if args[0] == "delete-keychain":
Path(args[1]).unlink()
if args[0] == "find-identity":
return "ABC123 NEW456"
return ""
class DevelopmentSigningTests(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory(prefix="cua-dev-signing-")
self.addCleanup(temporary.cleanup)
self.root = Path(temporary.name).resolve()
self.directory = self.root / "signing"
self.keychain = self.directory / "signing.keychain-db"
self.login = "/Users/example/Library/Keychains/login.keychain-db"
def configure(self, listed=True):
self.directory.mkdir(mode=0o700)
(self.directory / signing.OWNER_MARKER).write_text(signing.OWNER_VERSION)
self.keychain.write_bytes(b"keychain")
(self.directory / "identity.json").write_text(json.dumps({"sha1": "ABC123", "password": "secret"}))
return self.fake([self.login, str(self.keychain)] if listed else [self.login])
def fake(self, keychains):
security = FakeSecurity(keychains)
patcher = patch.object(signing, "security", security)
patcher.start()
self.addCleanup(patcher.stop)
return security
def test_setup_and_remove_preserve_unowned_directory_contents(self):
security = self.fake([self.login])
self.directory.mkdir()
unrelated = self.directory / "notes.txt"
unrelated.write_text("keep this document")
for operation in (signing.setup, signing.remove):
with self.subTest(operation=operation.__name__):
with self.assertRaisesRegex(RuntimeError, "Refusing unowned signing directory"):
operation(self.directory)
self.assertEqual(unrelated.read_text(), "keep this document")
self.assertEqual(list(self.directory.iterdir()), [unrelated])
self.assertEqual(security.commands, [])
def test_unrelated_files_in_an_owned_directory_block_setup_and_removal(self):
security = self.configure()
unrelated = self.directory / "notes.txt"
unrelated.write_text("keep this document")
before = {p.name: p.read_bytes() for p in self.directory.iterdir()}
for operation in (signing.setup, signing.remove):
with self.subTest(operation=operation.__name__):
with self.assertRaisesRegex(RuntimeError, "unrelated entries"):
operation(self.directory)
self.assertEqual({p.name: p.read_bytes() for p in self.directory.iterdir()}, before)
self.assertEqual(security.commands, [])
def test_system_keychain_locks_are_removed_by_security(self):
security = self.configure()
lock = self.directory / ".flD3051040"
lock.touch()
def remove_keychain(*args):
result = security(*args)
if args[0] == "delete-keychain":
lock.unlink()
return result
with patch.object(signing, "security", side_effect=remove_keychain):
signing.remove(self.directory)
self.assertFalse(self.directory.exists())
def test_nonempty_files_with_a_system_lock_name_are_preserved(self):
security = self.configure()
lock = self.directory / ".flD3051040"
lock.write_text("unrelated contents")
for operation in (signing.setup, signing.remove):
with self.assertRaisesRegex(RuntimeError, "unrelated entries"):
operation(self.directory)
self.assertEqual(lock.read_text(), "unrelated contents")
self.assertEqual(security.commands, [])
def test_missing_or_invalid_marker_cannot_adopt_an_existing_identity(self):
security = self.configure()
marker = self.directory / signing.OWNER_MARKER
for contents in (None, "different tool", "\ufffd"):
if contents is None:
marker.unlink()
else:
marker.write_text(contents)
for operation in (signing.setup, signing.remove):
with self.assertRaisesRegex(RuntimeError, "unowned signing directory"):
operation(self.directory)
self.assertTrue(self.keychain.is_file())
self.assertEqual(security.commands, [])
def test_symlinked_identity_files_do_not_delete_another_directorys_data(self):
security = self.configure()
outside = self.root / "outside.keychain-db"
outside.write_bytes(b"other identity")
self.keychain.unlink()
self.keychain.symlink_to(outside)
for operation in (signing.setup, signing.remove):
with self.assertRaisesRegex(RuntimeError, "unrelated entries"):
operation(self.directory)
self.assertEqual(outside.read_bytes(), b"other identity")
self.assertEqual(security.commands, [])
def test_empty_directory_gets_an_ownership_marker_before_generation(self):
self.fake([self.login])
self.directory.mkdir()
with patch.object(signing, "create_certificate", side_effect=RuntimeError("generation interrupted")):
with self.assertRaisesRegex(RuntimeError, "generation interrupted"):
signing.setup(self.directory)
self.assertEqual((self.directory / signing.OWNER_MARKER).read_text(), signing.OWNER_VERSION)
signing.remove(self.directory)
self.assertFalse(self.directory.exists())
def test_removing_the_only_search_entry_leaves_no_unrelated_entries_to_restore(self):
security = self.configure()
security.keychains = [str(self.keychain)]
signing.remove(self.directory)
self.assertEqual(security.keychains, [])
self.assertFalse(self.directory.exists())
def test_dotted_identity_directories_keep_separate_lock_files(self):
directories = [self.root / name for name in ("dev", "dev.keys", "keys.v1", "keys.v2")]
for directory in directories:
with signing.identity_lock(directory):
pass
self.assertEqual({p.name for p in self.root.iterdir()}, {f"{p.name}.lock" for p in directories})
def test_default_identity_is_outside_dsh_home(self):
home = self.root / "user"
with patch.object(Path, "home", return_value=home):
for value in ("", str(self.root / "custom-dsh-home")):
with patch.dict(signing.os.environ, {"DSH_HOME": value}):
self.assertEqual(signing.default_directory(), home / ".cua-macos-keys/dev")
self.assertFalse(home.exists())
def test_setup_and_remove_target_the_explicit_identity_directory(self):
directory = self.root / "keys/dev"
identity = signing.SigningIdentity("ABC123", directory / "signing.keychain-db")
for action in ("setup", "remove"):
with patch.object(signing.sys, "argv", ["signing_identity.py", action, "--directory", str(directory)]), \
patch.object(signing, action, return_value=identity) as operation, contextlib.redirect_stdout(io.StringIO()) as output:
signing.main()
operation.assert_called_once_with(directory)
if action == "setup":
self.assertEqual(json.loads(output.getvalue()), {"identity": "ABC123", "keychain": str(identity.keychain)})
def test_missing_setup_leaves_builds_unconfigured(self):
self.fake([self.login])
self.assertIsNone(signing.load(self.directory))
def test_load_unlocks_the_keychain_before_returning_the_identity(self):
security = self.configure()
identity = signing.load(self.directory)
self.assertEqual((identity.sha1, identity.keychain), ("ABC123", self.keychain))
self.assertIn(("unlock-keychain", "-p", "secret", str(self.keychain)), security.commands)
def test_listed_keychains_match_through_symbolic_links(self):
(self.root / "alias").symlink_to(self.root, target_is_directory=True)
self.configure()
signing.security.keychains = [self.login, str(self.root / "alias/signing/signing.keychain-db")]
self.assertEqual(signing.load(self.directory).sha1, "ABC123")
def test_unlisted_or_missing_keychains_fail_with_the_setup_command(self):
security = self.configure(listed=False)
with self.assertRaisesRegex(RuntimeError, "search list; run python3"):
signing.load(self.directory)
self.keychain.unlink()
with self.assertRaisesRegex(RuntimeError, "keychain is missing"):
signing.load(self.directory)
self.assertFalse(any(command[0] == "unlock-keychain" for command in security.commands))
def test_setup_relists_an_existing_identity_without_creating_another(self):
security = self.configure(listed=False)
with patch.object(signing, "create_certificate") as create:
self.assertEqual(signing.setup(self.directory).sha1, "ABC123")
create.assert_not_called()
self.assertEqual(security.keychains, [self.login, str(self.keychain)])
def test_setup_replaces_only_an_incomplete_owned_identity(self):
security = self.configure()
(self.directory / "identity.json").unlink()
def create(directory, password):
self.keychain.write_bytes(b"new keychain")
return "NEW456"
with patch.object(signing, "create_certificate", side_effect=create):
identity = signing.setup(self.directory)
self.assertEqual(identity.sha1, "NEW456")
self.assertEqual(self.keychain.read_bytes(), b"new keychain")
self.assertEqual(oct((self.directory / "identity.json").stat().st_mode & 0o777), "0o600")
self.assertEqual(oct(self.directory.stat().st_mode & 0o777), "0o700")
self.assertEqual(security.keychains, [self.login, str(self.keychain)])
def test_setup_preserves_the_record_when_the_keychain_is_missing(self):
security = self.configure()
record = self.directory / "identity.json"
before = record.read_bytes()
self.keychain.unlink()
with patch.object(signing, "create_certificate") as create:
with self.assertRaisesRegex(RuntimeError, "keychain is missing: .*; run .*remove --directory .*, then .*setup --directory "):
signing.setup(self.directory)
create.assert_not_called()
self.assertEqual(record.read_bytes(), before)
self.assertFalse(self.keychain.exists())
self.assertEqual(security.commands, [])
def test_setup_cli_preserves_a_recorded_identity_missing_its_keychain(self):
directory = self.root / "keys/dev"
directory.mkdir(parents=True)
(directory / signing.OWNER_MARKER).write_text(signing.OWNER_VERSION)
record = directory / "identity.json"
before = json.dumps({"sha1": "ABC123", "password": "secret-password"}).encode()
record.write_bytes(before)
result = subprocess.run([sys.executable, str(Path(signing.__file__)), "setup", "--directory", str(directory)],
capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 1)
self.assertEqual(len(result.stderr.splitlines()), 1)
self.assertIn("keychain is missing", result.stderr)
self.assertIn(f"run {signing.REMOVE_COMMAND} --directory {directory}, then {signing.SETUP_COMMAND} --directory {directory}", result.stderr)
self.assertNotIn("Traceback", result.stderr)
self.assertNotIn("secret-password", result.stderr)
self.assertEqual(record.read_bytes(), before)
self.assertFalse(signing.keychain_path(directory).exists())
def test_remove_restores_the_other_search_list_entries_and_deletes_the_password(self):
security = self.configure()
signing.remove(self.directory)
self.assertEqual(security.keychains, [self.login])
self.assertFalse(self.directory.exists())
signing.remove(self.directory)
self.assertEqual(security.keychains, [self.login])
def test_missing_certificate_requires_explicit_removal_instead_of_changing_identity(self):
self.configure()
(self.directory / "identity.json").write_text(json.dumps({"sha1": "MISSING", "password": "secret"}))
with self.assertRaisesRegex(RuntimeError, "certificate is missing; run .*remove --directory .*, then .*setup --directory "):
signing.setup(self.directory)
self.assertTrue(self.keychain.is_file())
def test_invalid_identity_record_reports_recovery_without_its_contents(self):
self.configure()
(self.directory / "identity.json").write_text("secret invalid json")
with self.assertRaisesRegex(RuntimeError, "record is invalid; run .*remove") as error:
signing.setup(self.directory)
self.assertNotIn("secret", str(error.exception))
def test_private_command_failures_never_echo_arguments_or_output(self):
for tool, action in ((signing.SECURITY, "unlock-keychain"), (signing.OPENSSL, "pkcs12")):
command = [tool, action, "-p", "secret-password"]
for failure in (subprocess.TimeoutExpired(command, 60, stderr="secret-password"),
subprocess.CalledProcessError(1, command, stderr="secret-password"),
OSError(2, "secret-password")):
with self.subTest(tool=tool, failure=type(failure).__name__), \
patch.object(signing.subprocess, "run", side_effect=failure):
with self.assertRaises(RuntimeError) as error:
signing.private_command(command)
self.assertNotIn("secret-password", str(error.exception))
self.assertTrue(error.exception.__suppress_context__)
def test_setup_and_remove_hold_the_same_cross_process_lock(self):
self.configure()
probe = """import fcntl, os, sys
with open(sys.argv[1], 'w') as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
sys.exit(0)
sys.exit(1)
"""
setup_locked, remove_locked = signing.setup_locked, signing.remove_locked
def check_lock(operation):
def run(directory):
result = subprocess.run([sys.executable, "-c", probe, str(directory.parent / f"{directory.name}.lock")],
capture_output=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stderr)
return operation(directory)
return run
with patch.object(signing, "setup_locked", side_effect=check_lock(setup_locked)), \
patch.object(signing, "remove_locked", side_effect=check_lock(remove_locked)):
signing.setup(self.directory)
signing.remove(self.directory)
with signing.identity_lock(self.directory):
pass
def test_setup_cli_reports_signing_timeout_without_traceback_or_password(self):
script = """import runpy, sys, subprocess
from unittest.mock import patch
from pathlib import Path
test_home = Path(sys.argv[2])
Path.home = lambda: test_home
sys.argv = [sys.argv[1], 'setup', '--directory', sys.argv[2]]
with patch('subprocess.run', side_effect=subprocess.TimeoutExpired(['security', 'unlock-keychain', '-p', 'secret-password'], 60)):
runpy.run_path(sys.argv[0], run_name='__main__')
"""
# Fail at the first security command, before setup can modify any keychain.
result = subprocess.run([sys.executable, "-c", script, str(Path(signing.__file__)), str(self.root / "home")],
capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 1)
self.assertEqual(len(result.stderr.splitlines()), 1)
self.assertIn("timed out", result.stderr)
self.assertNotIn("secret-password", result.stderr)
self.assertNotIn("Traceback", result.stderr)
if __name__ == "__main__":
unittest.main()
+17
View File
@@ -127,6 +127,23 @@ jobs:
args=()
if [[ "$PACKAGE_SKIP_NOTARIZATION" = true ]]; then args+=(--skip-notarization); fi
pnpm run package:desktop:mac:x64 --check --build-version "$PACKAGE_VERSION" "${args[@]}"
- name: Build and stage notarized Computer Use helpers
# A source whose dsh ships the Computer Use bundle packs the workspace provider into the Desktop runtime,
# which therefore needs the same notarized helper npm publication stages.
run: |
if ! node -e "process.exit(require('./apps/cli/package.json').dependencies?.['@deepseek-ai/dsh-cua-bundle'] ? 0 : 1)"; then
echo 'This source does not ship Computer Use in Desktop; no helper is staged.'
exit 0
fi
if [[ ! -f scripts/cua-helper/package.ts ]]; then
echo '::warning::This source ships Computer Use but predates helper packaging; Computer Use cannot prepare its helper in this package.'
exit 0
fi
mkdir -p dist
pnpm exec tsx scripts/cua-helper/package.ts --out dist/cua-helper
mkdir dist/cua-helper/extracted
tar -xzf dist/cua-helper/cua-helper.tgz -C dist/cua-helper/extracted
pnpm exec tsx scripts/cua-helper/stage.ts --from dist/cua-helper/extracted
- name: Build signed installers
env:
PACKAGE_VERSION: ${{ steps.settings.outputs.version }}
+17
View File
@@ -124,6 +124,23 @@ jobs:
args=()
if [[ "$PACKAGE_SKIP_NOTARIZATION" = true ]]; then args+=(--skip-notarization); fi
pnpm run package:desktop:mac:arm64 --check --build-version "$PACKAGE_VERSION" "${args[@]}"
- name: Build and stage notarized Computer Use helpers
# A source whose dsh ships the Computer Use bundle packs the workspace provider into the Desktop runtime,
# which therefore needs the same notarized helper npm publication stages.
run: |
if ! node -e "process.exit(require('./apps/cli/package.json').dependencies?.['@deepseek-ai/dsh-cua-bundle'] ? 0 : 1)"; then
echo 'This source does not ship Computer Use in Desktop; no helper is staged.'
exit 0
fi
if [[ ! -f scripts/cua-helper/package.ts ]]; then
echo '::warning::This source ships Computer Use but predates helper packaging; Computer Use cannot prepare its helper in this package.'
exit 0
fi
mkdir -p dist
pnpm exec tsx scripts/cua-helper/package.ts --out dist/cua-helper
mkdir dist/cua-helper/extracted
tar -xzf dist/cua-helper/cua-helper.tgz -C dist/cua-helper/extracted
pnpm exec tsx scripts/cua-helper/stage.ts --from dist/cua-helper/extracted
- name: Build signed installers
env:
PACKAGE_VERSION: ${{ steps.settings.outputs.version }}
+1
View File
@@ -106,6 +106,7 @@
"@deepseek-ai/dsh-experimental-liveshare": "workspace:*",
"@deepseek-ai/dsh-experimental-session-search": "workspace:*",
"@deepseek-ai/dsh-experimental-tool-worktree": "workspace:*",
"@deepseek-ai/dsh-cua-bundle": "workspace:*",
"@deepseek-ai/dsh-experimental-plugin-market-bundle": "workspace:*",
"@deepseek-ai/dsh-personalized-recommendations": "workspace:*",
"@deepseek-ai/dsh-experimental-forge-bundle": "workspace:*"
+2 -2
View File
@@ -15,8 +15,8 @@
en: 127ea90553cb6af7
zh: 7b1c5aec8558c684
/deepseek-harness-desktop/application-overview:
en: 1667e3d6ffddea4a
zh: 4661a42b9ef4f673
en: d4afa46403997884
zh: 9b9fe126afda70f0
/deepseek-harness-desktop/terminal-command:
en: 5f2d25a1d8472647
zh: 2acb5c5d7d1917e2
+1 -1
View File
@@ -35,7 +35,7 @@ Electron caches the last confirmed UI language in `userData/desktop/locale-cache
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.
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. Native Host requests send the current Host's authentication cookie explicitly, and no Electron session stores it; each Host start removes `dsh-auth-*` cookies that earlier releases left in the default session, because cookies ignore ports and would otherwise accompany every request to `127.0.0.1`.
Desktop binds `127.0.0.1`, the address Electron dials for the ready URL and the WebSocket credential filter. WebSocket streams use `ws:` or `wss:` according to the Host listener; credentials require matching authority and scheme.
+1 -1
View File
@@ -35,7 +35,7 @@ Electron 在 `userData/desktop/locale-cache` 缓存最近确认的界面语言
桌面埋点遵循[产品采集策略](../../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 覆盖。
桌面应用是完整 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 覆盖。原生 Host 请求会显式发送当前 Host 的认证 Cookie,任何 Electron session 都不保存该 Cookie;每次启动 Host 时都会移除早期版本遗留在默认 session 中的 `dsh-auth-*` Cookie,因为 Cookie 不区分端口,否则这些 Cookie 会随每个发往 `127.0.0.1` 的请求一并发送。
Desktop 绑定 `127.0.0.1`,即 Electron 为就绪 URL 与 WebSocket 凭据过滤器拨号的地址。WebSocket 流按 Host 监听器使用 `ws:` 或 `wss:`;附加凭据要求 authority 与 scheme 均匹配。
+10 -10
View File
@@ -27,17 +27,17 @@
en: 253e17998951931c
zh: b582b377391d2ec2
/desktop-packaging/macos-self-hosted-packaging:
en: f4cc5209bdaeefba
zh: 1db959d1ed345fcc
en: b7e03e2e9807a62c
zh: e5b0c43910e085d8
/desktop-packaging/unsigned-windows-test-installer:
en: f429bc0c280e2dfa
zh: 4adbcc9e906bdf80
/desktop-packaging/local-macos-dmg-without-release-signing:
en: 2feaa0412247d81f
zh: 461dde8e13fd4734
en: 1146bbc11be43960
zh: 7c13543a0513c059
/desktop-packaging/macos-release-signing-and-diagnostics:
en: 29fa6bd8919f3ec0
zh: 9e31e037fa3d9378
en: a0b4aa1080ecf6fb
zh: 37d4b8934f89bee8
/desktop-packaging/directory-builds-and-preparation:
en: 5860c306375ddd63
zh: a76e3cdbbe25c79e
@@ -45,11 +45,11 @@
en: b42f103358d0dfd7
zh: a534164ad9eb00da
/desktop-packaging/runtime-file-selection-and-installation-checks:
en: 83e1075417039410
zh: 3088a7ae0a2cc3c5
en: 44044a5c14b75533
zh: 39d91a369c4ec2fa
/desktop-packaging/desktop-runtime-preparation:
en: ab73b67d899e611d
zh: d77b0525c6b81e91
en: 84be38ab3136fff7
zh: bb4ed12ee0e1dfa0
/desktop-packaging/installation-and-release-verification:
en: eb35eb973b796643
zh: c1c52311632b7296
+8 -6
View File
@@ -125,7 +125,7 @@ Installer uploads store the already-compressed release files without ZIP recompr
## macOS self-hosted packaging
The [Apple Silicon workflow](../../../.github/workflows/macos-package.yml) and [Intel workflow](../../../.github/workflows/macos-intel-package.yml) produce separate arm64 and x64 packages on the Apple Silicon runner labeled `dsh-mac-package-trial`. Both share one concurrency group. The Intel workflow checks Rosetta execution before dependency installation; its selected source must include the target-aware macOS CI adapter. Both select `test` or `production` and use the existing signing, notarization and packaged-runtime checks. Successful DMG/ZIP files and diagnostic logs are retained for 14 days without publishing a release. Installer uploads disable redundant ZIP compression. The operator must verify a complete Actions run and installation on the target architecture before release qualification. The `compression_level` dropdown defaults to `3` and also offers `7`; it overrides the machine preset for this run and affects only ZIP and automatic-update downloads, not DMG.
The [Apple Silicon workflow](../../../.github/workflows/macos-package.yml) and [Intel workflow](../../../.github/workflows/macos-intel-package.yml) produce separate arm64 and x64 packages on the Apple Silicon runner labeled `dsh-mac-package-trial`. Both share one concurrency group. The Intel workflow checks Rosetta execution before dependency installation; its selected source must include the target-aware macOS CI adapter. Both select `test` or `production` and use the existing signing, notarization and packaged-runtime checks. When the selected source's dsh ships the Computer Use bundle, each workflow builds, notarizes and stages the helper for both architectures with `scripts/cua-helper/package.ts` and `stage.ts` after the configuration check, the steps npm publication uses; `skip_notarization` does not skip the helper's notarization. A source that predates helper packaging only emits a warning, and Computer Use cannot prepare its helper in that package. Successful DMG/ZIP files and diagnostic logs are retained for 14 days without publishing a release. Installer uploads disable redundant ZIP compression. The operator must verify a complete Actions run and installation on the target architecture before release qualification. The `compression_level` dropdown defaults to `3` and also offers `7`; it overrides the machine preset for this run and affects only ZIP and automatic-update downloads, not DMG.
All three platform forms put source, environment, update channel, version mode, manual version, test release ID and compression level first, with matching defaults. macOS notarization and Windows signing and cache measurement options follow these common fields.
@@ -172,19 +172,21 @@ pnpm run package:desktop:mac:x64:unsigned
Add `--check` to validate local configuration and tools without building, or `--dir` to stop at the unpacked application. The DMG is `apps/desktop/.desktop-build/targets/<target>/unsigned-artifacts/deepseek-harness-<version>-mac-<arch>-unsigned.dmg`. After all checks pass, the command prints `DMG:` followed by its absolute path. Open it and copy the application to a local test directory.
These commands ignore `.env.macos` and inherited release settings, use `com.deepseek.harness` as the app ID, and omit automatic-update and mandatory-update configuration. Build tools, standard network proxies, and `DSH_DESKTOP_NPM_REGISTRY` remain available from the shell. They skip Developer ID signing, Apple notarization, temporary signing keychains, and notarization proxy changes. Electron receives a local ad-hoc signature without certificates so the modified executable can run; the DMG is unsigned. Both preparation and the assembled application still run runtime integrity and smoke checks. Local builds omit update feeds, ZIPs, and release completion records, and the upload commands cannot publish them. macOS may require approval in System Settings → Privacy & Security to open an unnotarized application.
These commands ignore `.env.macos` and inherited release settings, use `com.deepseek.harness` as the app ID, and omit automatic-update and mandatory-update configuration. Build tools, standard network proxies, and `DSH_DESKTOP_NPM_REGISTRY` remain available from the shell. They skip Developer ID signing, Apple notarization, temporary signing keychains, and notarization proxy changes. Electron receives a local ad-hoc signature without certificates so the modified executable can run; the DMG is unsigned. Both preparation and the assembled application still run runtime integrity and smoke checks. Local builds omit update feeds, ZIPs, and release completion records, and the upload commands cannot publish them. macOS may require approval in System Settings → Privacy & Security to open an unnotarized application. These builds stage no Computer Use helper, so Computer Use reports the missing helper when it prepares.
<a id="macos-release-signing"></a>
## macOS release signing and diagnostics
The signed macOS configuration uses the required release environment instead of accepting whichever certificate appears first in a keychain. It rejects empty values, a malformed Team ID, a signing identity that includes electron-builder's unsupported `Developer ID Application:` prefix, and incomplete notarization credentials. Signed macOS packaging requires the configured identity and its private key. Runtime preparation applies that identity, a secure timestamp, and hardened runtime to every embedded Mach-O file; after signing the application, a deep strict check rejects any other leaf authority or Team ID before artifact creation. The signed fixed-target macOS installer commands create separate copies of the signed application and run two artifact lanes concurrently. One lane notarizes and staples the App before generating the ZIP and its update metadata. The other encloses its signed App copy in a signed DMG, then notarizes, staples, and verifies the DMG; its inner App has no individually stapled ticket. Both lanes must finish successfully before their artifacts reach the final directory and the release completion record is written. Signed directory-only commands also require notarization credentials and wait for Apple notarization and App stapling. The [parallel notarization decision](../../../.agents/notes/implemented/process/2026-09-09-parallel-macos-notarization.md) owns copy isolation and container ticket semantics. `CSC_LINK` must name a local p12 containing the Developer ID Application certificate and private key; URLs and Base64 inputs are not supported. `CSC_KEY_PASSWORD` is its export password, not an Apple account or login password; an explicitly empty value supports an unencrypted p12. Before building, packaging creates and unlocks a private temporary keychain, imports the p12, authorizes signing, and signs a small probe. Runtime and App signing use this keychain explicitly; existing login keychains require no setup or manual unlocking. Child processes receive its path without the p12 password. The keychain is deleted after success or ordinary failure; CI must clean temporary credentials after forced termination. Ephemeral CI writes the certificate and `.env.macos` from its secret store, restricts file access, and deletes both after the job; self-hosted machine presets retain private files outside the checkout. Ambient `CSC_NAME` and certificate discovery order do not select the release owner. Notary credentials may instead use electron-builder's complete Apple ID or keychain-profile strategy. The two macOS identity variables are also required when repeating the application check manually with `pnpm --dir apps/desktop run verify:mac-signature -- <path-to-app>`.
The signed macOS configuration uses the required release environment instead of accepting whichever certificate appears first in a keychain. It rejects empty values, a malformed Team ID, a signing identity that includes electron-builder's unsupported `Developer ID Application:` prefix, and incomplete notarization credentials. Signed macOS packaging requires the configured identity and its private key. Runtime preparation applies that identity, a secure timestamp, and hardened runtime to every embedded Mach-O file outside the notarized Computer Use helper bundles; for those bundles it verifies the deep signature, release identity, stapled ticket, and Gatekeeper acceptance without re-signing their files. A signed local build of a source that ships Computer Use therefore needs the notarized helper staged first with `scripts/cua-helper/package.ts` and `stage.ts`; an ad-hoc `build:native` output under `native/bin` fails this verification; after signing the application, a deep strict check rejects any other leaf authority or Team ID before artifact creation. The signed fixed-target macOS installer commands create separate copies of the signed application and run two artifact lanes concurrently. One lane notarizes and staples the App before generating the ZIP and its update metadata. The other encloses its signed App copy in a signed DMG, then notarizes, staples, and verifies the DMG; its inner App has no individually stapled ticket. Both lanes must finish successfully before their artifacts reach the final directory and the release completion record is written. Signed directory-only commands also require notarization credentials and wait for Apple notarization and App stapling. The [parallel notarization decision](../../../.agents/notes/implemented/process/2026-09-09-parallel-macos-notarization.md) owns copy isolation and container ticket semantics. `CSC_LINK` must name a local p12 containing the Developer ID Application certificate and private key; URLs and Base64 inputs are not supported. `CSC_KEY_PASSWORD` is its export password, not an Apple account or login password; an explicitly empty value supports an unencrypted p12. Before building, packaging creates and unlocks a private temporary keychain, imports the p12, authorizes signing, and signs a small probe. Runtime and App signing use this keychain explicitly; existing login keychains require no setup or manual unlocking. Child processes receive its path without the p12 password. The keychain is deleted after success or ordinary failure; CI must clean temporary credentials after forced termination. Ephemeral CI writes the certificate and `.env.macos` from its secret store, restricts file access, and deletes both after the job; self-hosted machine presets retain private files outside the checkout. Ambient `CSC_NAME` and certificate discovery order do not select the release owner. Notary credentials may instead use electron-builder's complete Apple ID or keychain-profile strategy. The two macOS identity variables are also required when repeating the application check manually with `pnpm --dir apps/desktop run verify:mac-signature -- <path-to-app>`.
macOS signing visits real files without following Framework symlink aliases. PAK resources retain all shipped languages and are sealed by the enclosing Framework or application signature instead of receiving individual signatures. The [release policy](../../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md) owns the dependency patch and verification requirements.
macOS runtime preparation caches verified single-architecture Mach-O signatures in `.desktop-build/targets/<target>/signature-cache` unless `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` selects external storage. An explicit path must be absolute and already exist, contain no linked ancestors, and be owned by the current account with mode `0700` and read/write/search access; invalid or empty settings fail preflight without fallback. Omit the field to retain target-local storage. Keys include input bytes and permissions, the signing probe’s actual leaf certificate, identifier, entitlement bytes, macOS version, and signing tools and policy. Git commits do not determine reuse: uncommitted byte changes invalidate the affected file. Every hit verifies cached bytes, the strict signature, certificate, identifier, entitlements, secure timestamp and hardened runtime before replacing an unchanged input. Universal binaries are signed each time. Runtime integrity and smoke checks, App signing, and Apple notarization still run. The cache requires trusted local build storage. Cache corruption or unsafe links fail the build; stop packaging before deleting the affected cache directory and retrying. Successful signing stages prune complete entries to a one-GiB payload budget; interrupted temporary entries require manual removal. Concurrent eviction can fail a reader safely. Logs report hit, miss and uncached counts.
Mac package commands print `DESKTOP_PACKAGING_RECORD` with a unique directory under `apps/desktop/.desktop-build/packaging-runs/`. After reading local configuration, each run retains `run.json` (published version, product version, Git commit, dirty-worktree flag, target and Node version), `events.jsonl` (timestamped phases, durations, parallel output attribution and proxy restoration), redacted child `stdout.log` / `stderr.log`, and `result.json` (overall outcome, stage results and artifact directory). Events also record pack concurrency and whether each proxy is configured. Logs survive failures and later builds; no automatic deletion runs. Missing `result.json` means completion is unconfirmed. Known credential values are redacted; environments and notarytool authentication arguments are not recorded. Runtime preparation records package staging, installation, materialization, signing, manifests, smoke checks, descriptor verification and cleanup separately. Nested phase durations overlap and must not be added together.
Mac package commands print `DESKTOP_PACKAGING_RECORD` with a unique directory under `apps/desktop/.desktop-build/packaging-runs/`. After reading local configuration, each run retains `run.json` (published version, product version, Git commit, dirty-worktree flag, target and Node version), `events.jsonl` (timestamped phases, durations, parallel output attribution and proxy restoration), redacted child `stdout.log` / `stderr.log`, and `result.json` (overall outcome, stage results and artifact directory). Events also record pack concurrency and whether each proxy is configured. Logs survive failures and later builds; no automatic deletion runs. Missing `result.json` means completion is unconfirmed. Known credential values are redacted, and environments are not recorded. Apple command failures retain their exit code, signal, stdout and stderr in redacted form; the adapter also writes these details to stderr when no journal is available. Runtime preparation records package staging, installation, materialization, signing, manifests, smoke checks, descriptor verification and cleanup separately. Nested phase durations overlap and must not be added together.
CUA helper packaging prints `CUA_PACKAGING_RECORD` and creates its own record in the same directory before desktop installer startup. Its `run.json` identifies the helper target, product version and source commit; `events.jsonl` retains command and notarization phases, submission IDs and Apple results. `result.json` records success or failure. These records survive temporary payload cleanup, and the Desktop Actions diagnostic upload includes them even when helper preparation fails.
App and DMG notarization each record a submission ID and separate `notarytool:upload:*` and `notarytool:wait:*` durations. Upload uses `submit --no-wait` and includes authentication, local validation, transfer and server acceptance; it is not pure transfer time. Waiting starts after that command returns and includes polling and remaining Apple processing; Apple can start processing before upload submission returns. Apple status and diagnostic logs are retained, including rejection; signature checks, acceptance checks and stapling remain owned by `@electron/notarize`. Directory-only package commands use this same measured App notarization path. Individual subprocess output remains live in the terminal, while phase failures and nested errors are retained in the journal. Both platforms record parent-process packaging failures and print redacted diagnostics, including proxy recovery instructions, to the terminal. The configuration-only `check:package` command creates no run log.
@@ -246,7 +248,7 @@ Desktop packs workspace packages locally and installs external dependencies thro
The [Electron shell file list](../scripts/electron-builder-config.mjs) excludes recognized JavaScript/CSS/TypeScript source maps and TypeScript build caches from the separate `resources/app.asar/node_modules` dependency collection. These exclusions preserve runtime code, native modules, WASM, data files (including ordinary `.map` assets), licenses, and notices; [shell archive tests](../tests/shell-file-selection.spec.ts) check retained bytes and exclusions.
The [Office conversion provider](../../../packages/document/office-to-pdf/README.md) carries the target’s declared native engine, or WASM when the kit declares no matching native target. Preparation rejects a missing target engine before packaging. The complete Office dependencies, including CLI, JavaScript libraries, and the selected engine’s executables, data, licenses, and notices, are unpacked under `resources/app.asar.unpacked/dsh/node_modules/`. The Desktop Host resolves engine manifests to these physical directories and supplies loaded skills with absolute standalone Node and unpacked CLI paths. Node lives in `resources/runtime/primary-runtime/dependencies/node/bin/`; the CLI is the unpacked `@deepseek-ai/libreoffice-kit/lib/cli.js`. On macOS, the native helper receives the JIT entitlement required by [LibreOffice’s UNO bridge](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in).
The [Office conversion provider](../../../packages/document/office-to-pdf/README.md) carries the target’s declared native engine, or WASM when the kit declares no matching native target. Preparation rejects a missing target engine before packaging. The complete Office dependencies, including CLI, JavaScript libraries, and the selected engine’s executables, data, licenses, and notices, are unpacked under `resources/app.asar.unpacked/dsh/node_modules/`. The Desktop Host resolves engine manifests to these physical directories and supplies loaded skills with absolute standalone Node and unpacked CLI paths. Node lives in `resources/runtime/primary-runtime/dependencies/node/bin/`; the CLI is the unpacked `@deepseek-ai/libreoffice-kit/lib/cli.js`. On macOS, the native helper receives the JIT entitlement required by [LibreOffice’s UNO bridge](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in). The Computer Use helper applications under `@deepseek-ai/dsh-experimental-cua-macos/native/bin` are also unpacked whole under `resources/app.asar.unpacked/dsh/node_modules/`, and the provider opens that copy.
The packaged application runs compiled JavaScript and pre-generated Typert metadata; it does not compile TypeScript plugins. Source-level debugger navigation and editor declarations remain available in development packages. [Copy-policy tests](../tests/runtime-file-policy.spec.ts) cover exclusions and retained assets; The [payload smoke](../tests/fixtures/runtime-payload-smoke.mjs) runs under Electron RunAsNode before the Host smoke and final inventory verification. The payload smoke resolves the search tool’s ripgrep executable and verifies text search and file enumeration. Signed Windows builds run these checks after dependency signing; other builds run them during `prepare:dsh`. The [Host smoke](../scripts/smoke-runtime.ts) creates DOCX, XLSX, and PPTX inputs with bundled Python, converts each through the real Office provider, and checks PDF output. Every assembled application, including directory and unsigned builds, repeats the payload and Host checks against ASAR. Archive integrity checks compare the complete archived descriptor with preparation, file bytes and membership in both archive and unpacked trees, recorded executable flags for archived files, and physical permissions for unpacked files. The Host smoke also obtains CLI paths from the loaded skill and runs capabilities and DOCX conversion with an empty PATH. Conversion failures stop packaging before a release record is written; macOS DMG/ZIP builds run these checks before notarization.
@@ -280,7 +282,7 @@ Desktop [patch policy](../scripts/runtime-patch-policy.ts) explicitly classifies
Desktop dependency overrides are declared separately in the patch-policy module, not inferred from patch versions. The pi-ai constraint keeps its runtime version at the version qualified by the shared patch. Desktop still resolves a fresh runtime lockfile for each build, then installs with `--frozen-lockfile`; dependency resolution across separate builds is not yet reproducible. CLI packed-installation tests and other distribution flows retain their own configuration.
Every package command builds the repository, packs the first-party production closures rooted at dsh and the private Desktop Host, and prepares the target Electron distribution plus primary-runtime with its shared pnpm CLI. `prepare:dsh` installs the production graph once at build time, prepares materialized packages for electron-builder to archive under `app.asar/dsh`, removes package-manager metadata, and writes `desktop-runtime.json` with shared package versions and final file hashes. Signed macOS builds sign and verify native files before inventory generation; electron-builder excludes this already-signed tree from nested re-signing. Resource mappings explicitly include `dsh/node_modules`, which the default root-directory filter omits; the prepared runtime inventory is checked after native signing. Native executables and libraries are unpacked beside ASAR; Python, standalone Node and pnpm remain in external runtime resources. Windows packaging checks every prepared PE against its ASAR unpacked entry and byte-identical disk copy, including unsigned builds. Builder glob rules match braces in PE filenames as single-character wildcards, so a matching neighboring file may also be unpacked. Prepared runtime smoke uses the verified target descriptor rather than the build host architecture. Signed installer, notarization, installed upgrade, and target-specific native-module qualification require the release environment.
Every package command builds the repository, packs the first-party production closures rooted at dsh and the private Desktop Host, and prepares the target Electron distribution plus primary-runtime with its shared pnpm CLI. `prepare:dsh` installs the production graph once at build time, prepares materialized packages for electron-builder to archive under `app.asar/dsh`, removes package-manager metadata, and writes `desktop-runtime.json` with shared package versions and final file hashes. Signed macOS builds sign and verify native files, and verify the notarized Computer Use helper bundles without re-signing them, before inventory generation; electron-builder excludes this already-signed tree from nested re-signing. Resource mappings explicitly include `dsh/node_modules`, which the default root-directory filter omits; the prepared runtime inventory is checked after native signing. Native executables and libraries are unpacked beside ASAR; Python, standalone Node and pnpm remain in external runtime resources. Windows packaging checks every prepared PE against its ASAR unpacked entry and byte-identical disk copy, including unsigned builds. Builder glob rules match braces in PE filenames as single-character wildcards, so a matching neighboring file may also be unpacked. Prepared runtime smoke uses the verified target descriptor rather than the build host architecture. Signed installer, notarization, installed upgrade, and target-specific native-module qualification require the release environment.
Windows runtime sealing reads at most eight files concurrently, before and after native signing. A read failure drains outstanding reads without replacing the descriptor; successful sealing still requires the subsequent complete integrity and smoke checks.
+8 -6
View File
@@ -125,7 +125,7 @@ runner 的受监督启动和恢复见 [Windows runner 机器准备](../windows-s
## macOS 自托管打包
[Apple Silicon 工作流](../../../.github/workflows/macos-package.yml)与 [Intel 工作流](../../../.github/workflows/macos-intel-package.yml)在带有 `dsh-mac-package-trial` 标签的 Apple Silicon runner 上分别生成 arm64 和 x64 安装包,两者共用一个并发组。Intel 工作流在安装依赖前检查 Rosetta 能否执行;所选源码必须包含按目标架构校验的 macOS CI 适配脚本。两者均选择 `test` 或 `production`,并复用现有签名、公证和打包运行时检查。成功的 DMG/ZIP 与诊断日志保留 14 天,不发布 release;安装包上传关闭重复 ZIP 压缩。操作人员须验收完整 Actions 运行及目标架构上的安装,才能确认可交付。`compression_level` 下拉选项默认为 `3`,也可选择 `7`;本次运行以该选项覆盖机器预设,只影响 ZIP 和自动升级下载,不影响 DMG。
[Apple Silicon 工作流](../../../.github/workflows/macos-package.yml)与 [Intel 工作流](../../../.github/workflows/macos-intel-package.yml)在带有 `dsh-mac-package-trial` 标签的 Apple Silicon runner 上分别生成 arm64 和 x64 安装包,两者共用一个并发组。Intel 工作流在安装依赖前检查 Rosetta 能否执行;所选源码必须包含按目标架构校验的 macOS CI 适配脚本。两者均选择 `test` 或 `production`,并复用现有签名、公证和打包运行时检查。所选源码的 dsh 随附 Computer Use 组合包时,两者都在配置检查之后用 `scripts/cua-helper/package.ts` 和 `stage.ts` 构建、公证并放入两种架构的 helper,与 npm 发布的步骤相同;`skip_notarization` 不会跳过 helper 的公证。源码早于 helper 打包支持时只输出警告,该安装包中的 Computer Use 无法准备 helper。成功的 DMG/ZIP 与诊断日志保留 14 天,不发布 release;安装包上传关闭重复 ZIP 压缩。操作人员须验收完整 Actions 运行及目标架构上的安装,才能确认可交付。`compression_level` 下拉选项默认为 `3`,也可选择 `7`;本次运行以该选项覆盖机器预设,只影响 ZIP 和自动升级下载,不影响 DMG。
三个平台的表单均依次展示源码、环境、升级通道、版本模式、手动版本号、测试 release ID 和压缩等级,默认值一致。macOS 公证选项和 Windows 签名、缓存测量选项位于公共字段之后。
@@ -172,19 +172,21 @@ pnpm run package:desktop:mac:x64:unsigned
添加 `--check` 仅验证本地配置和工具而不构建,或添加 `--dir` 只生成解包应用。DMG 路径为 `apps/desktop/.desktop-build/targets/<target>/unsigned-artifacts/deepseek-harness-<version>-mac-<arch>-unsigned.dmg`。所有检查通过后,命令打印 `DMG:` 及其绝对路径。打开后将应用复制到本地测试目录。
这些命令忽略 `.env.macos` 和继承的发布配置,使用 `com.deepseek.harness` 作为应用 ID,并省略自动更新和强制更新配置。构建工具、标准网络代理与 `DSH_DESKTOP_NPM_REGISTRY` 仍可从 shell 提供。它们跳过 Developer ID 签名、Apple 公证、临时签名钥匙串和公证代理修改。Electron 使用无需证书的本地 ad-hoc 签名,以便修改后的可执行文件能够运行;DMG 不签名。准备阶段和组装后的应用仍执行运行时完整性与冒烟检查。本地构建不生成更新源、ZIP 或发布完成记录,上传命令无法发布这些产物。macOS 可能要求在“系统设置 → 隐私与安全性”中批准打开未经公证的应用。
这些命令忽略 `.env.macos` 和继承的发布配置,使用 `com.deepseek.harness` 作为应用 ID,并省略自动更新和强制更新配置。构建工具、标准网络代理与 `DSH_DESKTOP_NPM_REGISTRY` 仍可从 shell 提供。它们跳过 Developer ID 签名、Apple 公证、临时签名钥匙串和公证代理修改。Electron 使用无需证书的本地 ad-hoc 签名,以便修改后的可执行文件能够运行;DMG 不签名。准备阶段和组装后的应用仍执行运行时完整性与冒烟检查。本地构建不生成更新源、ZIP 或发布完成记录,上传命令无法发布这些产物。macOS 可能要求在“系统设置 → 隐私与安全性”中批准打开未经公证的应用。这类构建不放入 Computer Use helper,Computer Use 准备时会报告 helper 缺失。
<a id="macos-release-signing"></a>
## macOS 发布签名与诊断
macOS 签名配置使用必填发布环境,不会接受钥匙串中最先发现的证书。空值、格式错误的 Team ID、包含 electron-builder 不支持的 `Developer ID Application:` 前缀的签名身份,以及不完整的公证凭据都会被拒绝。macOS 签名打包要求已配置的身份及其私钥可用。运行时准备会把该身份、安全时间戳与 hardened runtime 应用到每个内嵌 Mach-O 文件;应用签名完成后,深度严格检查会拒绝其他叶证书 Authority 或 Team ID,验证通过才生成发布产物。macOS 签名固定目标安装包命令为已签名应用创建独立副本,并发执行两条产物流。一路先公证 App 并钉票,再生成 ZIP 及其更新元数据。另一路把已签名 App 副本封装进签名 DMG,再公证 DMG、钉票并验证;其中的 App 不单独附加票据。只有两路均成功结束,产物才会移入最终目录并写入发布完成记录。签名的仅目录命令同样需要公证凭据,并等待 Apple 公证和 App 钉票完成。[并行公证决策](../../../.agents/notes/implemented/process/2026-09-09-parallel-macos-notarization.zh.md)负责副本隔离与容器票据语义。`CSC_LINK` 必须指向包含 Developer ID Application 证书及私钥的本地 p12,不支持 URL 或 Base64 输入。`CSC_KEY_PASSWORD` 是其导出密码,不是 Apple 账号或登录密码;未加密的 p12 可显式填写空值。构建前,打包流程自动创建并解锁私有临时钥匙串、导入 p12、授权签名并签署小型探针。运行时与 App 签名显式使用该钥匙串,无需预先配置或手动解锁登录钥匙串。子进程只接收钥匙串路径,不接收 p12 密码。成功或普通失败后删除临时钥匙串;强制终止后由 CI 清理临时凭据。临时 CI 从密钥存储生成证书文件和 `.env.macos`,限制文件访问权限,并在作业结束后删除二者;自托管机器 preset 在 checkout 外保留私有文件。环境中的 `CSC_NAME` 与证书发现顺序都不能选择发布所有者。公证凭据也可以使用 electron-builder 支持的完整 Apple ID 或钥匙串 profile 方式。手动执行 `pnpm --dir apps/desktop run verify:mac-signature -- <path-to-app>` 重复应用检查时,也必须提供两个 macOS 身份变量。
macOS 签名配置使用必填发布环境,不会接受钥匙串中最先发现的证书。空值、格式错误的 Team ID、包含 electron-builder 不支持的 `Developer ID Application:` 前缀的签名身份,以及不完整的公证凭据都会被拒绝。macOS 签名打包要求已配置的身份及其私钥可用。运行时准备会把该身份、安全时间戳与 hardened runtime 应用到已公证 Computer Use helper 应用包之外的每个内嵌 Mach-O 文件;对这些应用包,则校验深度签名、发布身份、钉票和 Gatekeeper 评估结果,不重签其中的文件。因此,打包会随附 Computer Use 的源码时,本地签名构建需要先用 `scripts/cua-helper/package.ts` 和 `stage.ts` 放入已公证的 helper;`native/bin` 下由 `build:native` 生成的临时签名产物无法通过此校验;应用签名完成后,深度严格检查会拒绝其他叶证书 Authority 或 Team ID,验证通过才生成发布产物。macOS 签名固定目标安装包命令为已签名应用创建独立副本,并发执行两条产物流。一路先公证 App 并钉票,再生成 ZIP 及其更新元数据。另一路把已签名 App 副本封装进签名 DMG,再公证 DMG、钉票并验证;其中的 App 不单独附加票据。只有两路均成功结束,产物才会移入最终目录并写入发布完成记录。签名的仅目录命令同样需要公证凭据,并等待 Apple 公证和 App 钉票完成。[并行公证决策](../../../.agents/notes/implemented/process/2026-09-09-parallel-macos-notarization.zh.md)负责副本隔离与容器票据语义。`CSC_LINK` 必须指向包含 Developer ID Application 证书及私钥的本地 p12,不支持 URL 或 Base64 输入。`CSC_KEY_PASSWORD` 是其导出密码,不是 Apple 账号或登录密码;未加密的 p12 可显式填写空值。构建前,打包流程自动创建并解锁私有临时钥匙串、导入 p12、授权签名并签署小型探针。运行时与 App 签名显式使用该钥匙串,无需预先配置或手动解锁登录钥匙串。子进程只接收钥匙串路径,不接收 p12 密码。成功或普通失败后删除临时钥匙串;强制终止后由 CI 清理临时凭据。临时 CI 从密钥存储生成证书文件和 `.env.macos`,限制文件访问权限,并在作业结束后删除二者;自托管机器 preset 在 checkout 外保留私有文件。环境中的 `CSC_NAME` 与证书发现顺序都不能选择发布所有者。公证凭据也可以使用 electron-builder 支持的完整 Apple ID 或钥匙串 profile 方式。手动执行 `pnpm --dir apps/desktop run verify:mac-signature -- <path-to-app>` 重复应用检查时,也必须提供两个 macOS 身份变量。
macOS 签名遍历真实文件,不跟随 Framework 的软链接别名。PAK 资源保留全部随附语言,由外层 Framework 或应用签名记录完整性,不逐个签名。[发布策略](../../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)负责依赖补丁和验证要求。
macOS 运行时准备将已验证的单架构 Mach-O 签名缓存在 `.desktop-build/targets/<target>/signature-cache`,除非通过 `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` 选择外置存储。显式路径必须是已存在的绝对目录,祖先路径不能包含链接,目录须归当前账户所有、权限为 `0700` 且可读写及遍历;非法或空配置在预检时失败,不回退。省略该字段保留目标本地缓存。缓存键包含输入字节与权限、签名探针实际使用的叶证书、签名标识、entitlement 字节、macOS 版本,以及签名工具与策略。复用不取决于 Git 提交:未提交的字节变更会使对应文件失效。每次命中都验证缓存字节、严格签名、证书、标识、entitlements、安全时间戳和 hardened runtime,再替换未被并发修改的输入。通用二进制每次重新签名。运行时完整性与 smoke 检查、App 签名和 Apple 公证仍会执行。缓存要求受信任的本地构建存储。缓存损坏或不安全链接会令构建失败;停止打包后删除对应缓存目录再重试。成功的签名阶段会将完整缓存条目的内容总量裁剪至一 GiB;中断留下的临时条目需手动清理。并发淘汰可能使读取方安全失败。日志记录命中、未命中及未缓存数量。
Mac 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `apps/desktop/.desktop-build/packaging-runs/` 下的唯一目录。读取本地配置后,每次运行保留 `run.json`(发布版本、产品版本、Git 提交、工作区是否有改动、目标及 Node 版本)、`events.jsonl`(带时间戳的阶段、耗时、并行输出归属及代理恢复状态)、脱敏后的子进程 `stdout.log` / `stderr.log`,以及 `result.json`(整体结果、阶段结果和产物目录)。事件还记录打包并发数及各代理是否配置。失败和后续打包不会清除日志;没有自动删除流程。缺少 `result.json` 表示完成状态未经确认。已知凭据值会被遮盖;不记录环境变量全集或 notarytool 认证参数。运行时准备分别记录包暂存、安装、依赖树复制、签名、清单生成、smoke 检查、描述文件校验和清理。嵌套阶段的耗时存在重叠,不能直接相加。
Mac 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `apps/desktop/.desktop-build/packaging-runs/` 下的唯一目录。读取本地配置后,每次运行保留 `run.json`(发布版本、产品版本、Git 提交、工作区是否有改动、目标及 Node 版本)、`events.jsonl`(带时间戳的阶段、耗时、并行输出归属及代理恢复状态)、脱敏后的子进程 `stdout.log` / `stderr.log`,以及 `result.json`(整体结果、阶段结果和产物目录)。事件还记录打包并发数及各代理是否配置。失败和后续打包不会清除日志;没有自动删除流程。缺少 `result.json` 表示完成状态未经确认。已知凭据值会被遮盖,不记录环境变量全集。Apple 命令失败时保留脱敏后的退出码、信号、stdout 和 stderr;没有日志目录时,适配器也会将这些详情写入 stderr。运行时准备分别记录包暂存、安装、依赖树复制、签名、清单生成、smoke 检查、描述文件校验和清理。嵌套阶段的耗时存在重叠,不能直接相加。
CUA helper 打包通过 `CUA_PACKAGING_RECORD` 输出同一目录下的独立记录路径,在桌面安装包开始构建前创建。其 `run.json` 记录 helper 目标、产品版本和源码提交,`events.jsonl` 保留命令与公证阶段、已返回的提交 ID 和 Apple 处理结果,`result.json` 记录成功或失败。这些记录不会随临时 payload 清理而删除;即使 helper 准备失败,Desktop Actions 的诊断上传步骤也会收集它们。
App 和 DMG 公证分别记录 submission ID,以及独立的 `notarytool:upload:*` 和 `notarytool:wait:*` 耗时。上传使用 `submit --no-wait`,包含认证、本地校验、传输和服务端受理,并非纯传输时间。等待从该命令返回后开始,包含轮询及剩余的 Apple 处理时间;Apple 可能在上传提交命令返回前已开始处理。日志保留 Apple 状态与诊断信息,包括拒绝结果;签名检查、接受状态校验和 stapling 仍由 `@electron/notarize` 负责。仅生成目录的打包命令也使用同一条可计时的 App 公证路径。各子进程输出仍实时显示在终端,阶段失败及嵌套错误保留在事件日志中。两个平台均记录父进程打包失败,并在终端显示脱敏诊断,包括代理恢复操作指引。仅检查配置的 `check:package` 命令不创建运行日志。
@@ -246,7 +248,7 @@ Desktop 在本地打包工作区包,并通过目标捆绑的 Node 和 pnpm 安
[Electron 外壳文件清单](../scripts/electron-builder-config.mjs)从单独收集的 `resources/app.asar/node_modules` 依赖中排除已识别的 JavaScript/CSS/TypeScript source map 和 TypeScript 构建缓存。这些排除规则保留运行时代码、原生模块、WASM、数据文件(包括普通 `.map` 资源)、许可证和 notices;[外壳归档测试](../tests/shell-file-selection.spec.ts)检查保留文件的字节和排除项。
[Office 转换提供方](../../../packages/document/office-to-pdf/README.zh.md)携带目标已声明的原生引擎;kit 未声明匹配原生目标时携带 WASM 引擎。准备阶段在打包前拒绝缺少目标引擎的情况。完整 Office 依赖(CLI、JavaScript 库和选定引擎的可执行文件、数据、许可证及 notices)解包到 `resources/app.asar.unpacked/dsh/node_modules/` 下。Desktop Host 将引擎清单解析到这些物理目录,并向加载的技能提供独立 Node 和解包后 CLI 的绝对路径。Node 位于 `resources/runtime/primary-runtime/dependencies/node/bin/`;CLI 位于解包后的 `@deepseek-ai/libreoffice-kit/lib/cli.js`。macOS 上的原生辅助程序获得 [LibreOffice UNO 桥](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in)所需的 JIT entitlement。
[Office 转换提供方](../../../packages/document/office-to-pdf/README.zh.md)携带目标已声明的原生引擎;kit 未声明匹配原生目标时携带 WASM 引擎。准备阶段在打包前拒绝缺少目标引擎的情况。完整 Office 依赖(CLI、JavaScript 库和选定引擎的可执行文件、数据、许可证及 notices)解包到 `resources/app.asar.unpacked/dsh/node_modules/` 下。Desktop Host 将引擎清单解析到这些物理目录,并向加载的技能提供独立 Node 和解包后 CLI 的绝对路径。Node 位于 `resources/runtime/primary-runtime/dependencies/node/bin/`;CLI 位于解包后的 `@deepseek-ai/libreoffice-kit/lib/cli.js`。macOS 上的原生辅助程序获得 [LibreOffice UNO 桥](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in)所需的 JIT entitlement。`@deepseek-ai/dsh-experimental-cua-macos/native/bin` 下的 Computer Use helper 应用也整体解包到 `resources/app.asar.unpacked/dsh/node_modules/` 下,提供方打开该副本。
打包应用运行编译后的 JavaScript 和预生成的 Typert 元数据,不编译 TypeScript 插件。源码级调试导航和编辑器声明仍可从开发包中获取。[复制规则测试](../tests/runtime-file-policy.spec.ts)覆盖排除项和保留资源;[产物 smoke](../tests/fixtures/runtime-payload-smoke.mjs) 在 Host smoke 和最终清单验证之前,使用 Electron RunAsNode 执行。产物 smoke 解析搜索工具使用的 ripgrep 可执行文件,并验证文本搜索和文件枚举。Windows 签名构建在依赖签名后运行这些检查;其他构建在 `prepare:dsh` 中运行。[Host smoke](../scripts/smoke-runtime.ts) 使用捆绑的 Python 创建 DOCX、XLSX 和 PPTX 输入,通过真实 Office 提供方逐一转换并检查 PDF 输出。每个组装后的应用(包括目录包和未签名构建)都会针对 ASAR 重复产物和 Host 检查。归档完整性检查将归档内完整描述符与准备结果比对,并核对归档和解包目录中的文件内容与清单、归档内文件记录的执行标志,以及解包文件的物理权限。转换失败会在写入发布记录前终止打包;macOS DMG/ZIP 构建在公证前执行这些检查。
@@ -280,7 +282,7 @@ Desktop [补丁策略](../scripts/runtime-patch-policy.ts) 将每份工作区补
Desktop 依赖 overrides 在补丁策略模块中单独声明,不从补丁版本推导。pi-ai 约束使运行时版本保持在共享补丁已验证的版本。Desktop 仍会在每次构建时重新解析运行时锁文件,再通过 `--frozen-lockfile` 安装;不同构建之间的依赖解析尚不保证可复现。CLI 打包安装测试及其他交付流程保留各自的配置。
每条打包命令都会构建仓库,打包以 dsh 和私有 Desktop Host 为根的第一方生产依赖闭包,并准备目标专用的 Electron 分发包和包含共享 pnpm CLI 的 primary-runtime。`prepare:dsh` 在构建时安装一次生产依赖图,准备物化包供 electron-builder 归档到 `app.asar/dsh`,移除包管理器元数据,并生成包含共享包版本和最终文件哈希的 `desktop-runtime.json`。macOS 签名构建先签名并验证原生文件,再生成清单;electron-builder 不对已签名的此目录重复进行嵌套签名。资源映射明确包含默认根目录过滤器会忽略的 `dsh/node_modules`;准备完成的运行时清单在原生签名后检查。原生可执行文件及库解包到 ASAR 旁;Python、独立 Node 和 pnpm 保留在外部 runtime 资源中。Windows 打包逐项检查准备好的 PE,确认其 ASAR 条目已标记为解包,且磁盘副本字节一致;未签名构建也执行此检查。Builder glob 规则用单字符通配符匹配 PE 文件名中的花括号,因此同目录中名称匹配的文件也可能被解包。准备好的运行时 smoke 沿用已验证的目标描述符,不使用构建宿主的架构。签名安装包、公证、已安装应用升级和各目标原生模块的验收需要发布环境。
每条打包命令都会构建仓库,打包以 dsh 和私有 Desktop Host 为根的第一方生产依赖闭包,并准备目标专用的 Electron 分发包和包含共享 pnpm CLI 的 primary-runtime。`prepare:dsh` 在构建时安装一次生产依赖图,准备物化包供 electron-builder 归档到 `app.asar/dsh`,移除包管理器元数据,并生成包含共享包版本和最终文件哈希的 `desktop-runtime.json`。macOS 签名构建先签名并验证原生文件,并在不重签的前提下校验已公证的 Computer Use helper 应用包,再生成清单;electron-builder 不对已签名的此目录重复进行嵌套签名。资源映射明确包含默认根目录过滤器会忽略的 `dsh/node_modules`;准备完成的运行时清单在原生签名后检查。原生可执行文件及库解包到 ASAR 旁;Python、独立 Node 和 pnpm 保留在外部 runtime 资源中。Windows 打包逐项检查准备好的 PE,确认其 ASAR 条目已标记为解包,且磁盘副本字节一致;未签名构建也执行此检查。Builder glob 规则用单字符通配符匹配 PE 文件名中的花括号,因此同目录中名称匹配的文件也可能被解包。准备好的运行时 smoke 沿用已验证的目标描述符,不使用构建宿主的架构。签名安装包、公证、已安装应用升级和各目标原生模块的验收需要发布环境。
Windows 运行时在原生签名前后封存文件清单,每次最多并发读取八个文件。读取失败时会等待未完成的读取结束,不替换描述符;封存成功后仍须完成后续的完整性与 smoke 检查。
@@ -76,7 +76,10 @@ export function createElectronBuilderConfig(
let dshDestination
let windowsCode = []
const unpack = ['**/*.{node,dylib,dll,so,exe}', '**/*.so.*', '**/spawn-helper', '**/@vscode/ripgrep-*/bin/rg',
`**/node_modules/@deepseek-ai/libreoffice-kit-${resolvedPlatform}-${resolvedArch}/**/*`]
`**/node_modules/@deepseek-ai/libreoffice-kit-${resolvedPlatform}-${resolvedArch}/**/*`,
// LaunchServices opens the Computer Use helper as an application, so every file of its bundles stays on disk.
// Both architectures ship: they form one notarized payload whose manifest staging verifies as a whole.
'**/node_modules/@deepseek-ai/dsh-experimental-cua-macos/native/bin/**/*']
const windowsSigner = packagesWindows && !unsigned
? createWindowsTokenSigner({
certificateFile: env.DSH_DESKTOP_WINDOWS_CER_FILE,
+10 -6
View File
@@ -5,7 +5,7 @@ import { basename, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { promisify } from 'node:util'
import { recordPackagingEvent, packagingOutputRedactor } from './packaging-run.mjs'
import { packagingStep } from './packaging-step.mjs'
import { packagingErrorDetails, packagingStep } from './packaging-step.mjs'
const exec = promisify(execFile)
const AUTH_FLAGS = new Set(['--apple-id', '--password', '--team-id', '--key', '--key-id', '--issuer', '--keychain', '--keychain-profile'])
@@ -17,7 +17,8 @@ async function execute(args) {
} catch (error) {
// Apple can report rejection with a nonzero exit; electron-notarize needs its JSON ID to retrieve diagnostics.
if (args[0] === 'wait' && typeof error.code === 'number' && typeof error.stdout === 'string' && error.stdout.trim()) return error.stdout
throw error
throw new Error(`notarytool ${args[0]} failed (code: ${String(error.code ?? 'unknown')}, signal: ${String(error.signal ?? 'none')})\n`
+ `stdout: ${error.stdout ?? ''}\nstderr: ${error.stderr ?? ''}`, { cause: error })
}
}
@@ -74,10 +75,13 @@ export async function runLoggedNotarytool(args, directory, invoke = execute) {
}
if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
try { process.stdout.write(await runLoggedNotarytool(process.argv.slice(2), process.env.DSH_DESKTOP_PACKAGING_RUN_DIR)) }
catch {
// execFile errors include credential-bearing argv; detailed failures are redacted in the journal.
process.stderr.write('desktop notarization: Apple command failed; see packaging events.jsonl\n')
const args = process.argv.slice(2)
const directory = process.env.DSH_DESKTOP_PACKAGING_RUN_DIR
try { process.stdout.write(await runLoggedNotarytool(args, directory)) }
catch (error) {
const credentials = args.filter((_, index) => AUTH_FLAGS.has(args[index - 1]))
process.stderr.write(`desktop notarization: Apple command failed${directory ? `; see ${directory}/events.jsonl` : ''}\n`
+ `${packagingErrorDetails(error, credentials)}\n`)
process.exitCode = 1
}
}
+21 -4
View File
@@ -8,9 +8,15 @@ import { inventoryDesktopRuntime } from '../src/runtime-tree.ts'
import type { MacOSSigningEnvironment } from './desktop-release-environment.mjs'
import { cachedMacOSSignature, pruneMacOSSignatureCache } from './macos-signature-cache.ts'
import { macOSCachePolicy } from './macos-cache-policy.ts'
import { signMacOSRuntimeCode, verifyMacOSRuntimeCode } from './verify-macos-signature.mjs'
import { signMacOSRuntimeCode, verifyMacOSNotarizedApplication, verifyMacOSRuntimeCode } from './verify-macos-signature.mjs'
const MACH_O_MAGICS = new Set(['cafebabe', 'cafebabf', 'cefaedfe', 'cffaedfe', 'feedface', 'feedfacf', 'bebafeca', 'bfbafeca'])
/**
* The notarized Computer Use helper bundle containing a runtime path, as staged by `scripts/cua-helper/stage.ts`:
* `native/bin/darwin-<arch>/<generation>/<name>.app`. Other bundles, such as LibreOffice's unsigned application,
* are not matched and keep per-file runtime signing.
*/
const CUA_HELPER_BUNDLE = /^(node_modules\/@deepseek-ai\/dsh-experimental-cua-macos\/native\/bin\/darwin-[^/]+\/[^/]+\/[^/]+\.app)\//u
function magic(path: string): string {
const descriptor = openSync(path, 'r')
@@ -33,21 +39,32 @@ async function primaryRuntimeFiles(root: string): Promise<string[]> {
}
/**
* Sign and verify every materialized Mach-O file, awaiting all signers on failure.
* Sign and verify every materialized Mach-O file, awaiting all signers on failure. Files inside the notarized Computer
* Use helper bundles are not re-signed, because signing them breaks the bundle seal and changes the identity macOS
* grants permissions to; each such bundle's deep signature, release identity, stapled ticket, and Gatekeeper
* acceptance are verified before any file is signed.
* @param root - Self-contained production runtime.
* @param appId - Release application identifier.
* @param expected - Required signing identity.
* @param arch - Target runtime architecture, independent of the signing host.
* @param cacheDirectory - Optional content-addressed cache; requires the keychain-owned signing probe.
* @param kind - Primary payloads admit validated Python aliases; Desktop application runtimes reject every link.
* @returns Number of signed native files.
* @returns Number of signed native files, excluding files inside verified Computer Use helper bundles.
* @throws When a helper bundle fails verification, or when any signer fails.
*/
export async function signMacOSRuntime(
root: string, appId: string, expected: MacOSSigningEnvironment, arch: 'arm64' | 'x64', cacheDirectory?: string,
kind: 'desktop' | 'primary' = 'desktop',
): Promise<number> {
const inventory = kind === 'primary' ? await primaryRuntimeFiles(root) : inventoryDesktopRuntime(root).map(file => file.path)
const files = inventory.filter(path => MACH_O_MAGICS.has(magic(join(root, path))))
const bundles = new Set<string>()
const files: string[] = []
for (const path of inventory) {
const bundle = CUA_HELPER_BUNDLE.exec(path)?.[1]
if (bundle !== undefined) bundles.add(bundle)
else if (MACH_O_MAGICS.has(magic(join(root, path)))) files.push(path)
}
for (const bundle of [...bundles].sort()) verifyMacOSNotarizedApplication(join(root, bundle), expected)
const policy = cacheDirectory === undefined ? undefined : macOSCachePolicy(process.env.DSH_DESKTOP_MACOS_SIGNING_PROBE ?? '')
let hits = 0
let misses = 0
+27 -30
View File
@@ -80,10 +80,10 @@ export interface DesktopAccountBackend {
* Connect native account operations to the standard authenticated Web backend.
* @param origin - Host Web origin.
* @param invoke - validated unary RPC caller.
* @param cookies - Electron session cookie reader.
* @param cookie - Host authentication Cookie header for the account WebSocket.
* @returns account operations; watch callers own their subscriptions.
*/
export function desktopAccountBackend(origin: string, invoke: AccountInvoke, cookies: () => Promise<string>): DesktopAccountBackend {
export function desktopAccountBackend(origin: string, invoke: AccountInvoke, cookie: string): DesktopAccountBackend {
const call = async (method: string, args: Record<string, unknown> = {}): Promise<AccountView> =>
accountView(await invoke({ namespace: 'account', method, args }))
return {
@@ -98,34 +98,31 @@ export function desktopAccountBackend(origin: string, invoke: AccountInvoke, coo
const streamId = randomUUID()
const expiryStreamId = randomUUID()
const analyticsPolicyStreamId = randomUUID()
void cookies().then((cookie) => {
if (closed) return
const url = new URL(REMOTE_STREAM_MUX_PATH, origin)
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
socket = new WebSocket(url, { headers: { cookie, origin }, maxPayload: 65_536 })
socket.on('open', () => {
if (onAnalyticsEnabledChanged !== undefined) socket?.send(JSON.stringify({ type: 'open', streamId: analyticsPolicyStreamId, endpoint: 'productAnalytics/watchPolicy', payload: { args: {} } }))
socket?.send(JSON.stringify({ type: 'open', streamId: expiryStreamId, endpoint: 'account/watchExpiry', payload: { args: {} } }))
socket?.send(JSON.stringify({ type: 'open', streamId, endpoint: 'account/watch', payload: { args: {} } }))
})
socket.on('message', (data) => {
try {
const bytes = Array.isArray(data) ? Buffer.concat(data) : Buffer.isBuffer(data) ? data : Buffer.from(data)
const frame = parseRemoteStreamServerMessage(bytes.toString('utf8'))
if (frame.streamId === analyticsPolicyStreamId) {
if (frame.type === 'item' && typeof frame.value === 'boolean') onAnalyticsEnabledChanged?.(frame.value)
else onAnalyticsEnabledChanged?.(false)
return
}
if (frame.streamId === expiryStreamId && frame.type === 'item' && frame.value === 'session-expired') { expired(); return }
if (frame.streamId !== streamId) throw new Error('desktop account: unexpected stream')
if (frame.type === 'item') listener(accountView(frame.value))
else socket?.close()
} catch { socket?.close() }
})
socket.on('error', () => { socket?.close() })
socket.on('close', () => { if (!closed) { onAnalyticsEnabledChanged?.(false); failed(); retry = setTimeout(connect, 1000) } })
}).catch(() => { if (!closed) { onAnalyticsEnabledChanged?.(false); failed(); retry = setTimeout(connect, 1000) } })
const url = new URL(REMOTE_STREAM_MUX_PATH, origin)
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
socket = new WebSocket(url, { headers: { cookie, origin }, maxPayload: 65_536 })
socket.on('open', () => {
if (onAnalyticsEnabledChanged !== undefined) socket?.send(JSON.stringify({ type: 'open', streamId: analyticsPolicyStreamId, endpoint: 'productAnalytics/watchPolicy', payload: { args: {} } }))
socket?.send(JSON.stringify({ type: 'open', streamId: expiryStreamId, endpoint: 'account/watchExpiry', payload: { args: {} } }))
socket?.send(JSON.stringify({ type: 'open', streamId, endpoint: 'account/watch', payload: { args: {} } }))
})
socket.on('message', (data) => {
try {
const bytes = Array.isArray(data) ? Buffer.concat(data) : Buffer.isBuffer(data) ? data : Buffer.from(data)
const frame = parseRemoteStreamServerMessage(bytes.toString('utf8'))
if (frame.streamId === analyticsPolicyStreamId) {
if (frame.type === 'item' && typeof frame.value === 'boolean') onAnalyticsEnabledChanged?.(frame.value)
else onAnalyticsEnabledChanged?.(false)
return
}
if (frame.streamId === expiryStreamId && frame.type === 'item' && frame.value === 'session-expired') { expired(); return }
if (frame.streamId !== streamId) throw new Error('desktop account: unexpected stream')
if (frame.type === 'item') listener(accountView(frame.value))
else socket?.close()
} catch { socket?.close() }
})
socket.on('error', () => { socket?.close() })
socket.on('close', () => { if (!closed) { onAnalyticsEnabledChanged?.(false); failed(); retry = setTimeout(connect, 1000) } })
}
connect()
return () => { closed = true; onAnalyticsEnabledChanged?.(false); clearTimeout(retry); socket?.close() }
+6 -4
View File
@@ -16,7 +16,6 @@ import {
powerMonitor,
nativeImage,
nativeTheme,
net,
protocol,
session,
shell,
@@ -39,7 +38,7 @@ import { desktopUpdateChannel } from './update-channel.ts'
import { DesktopUpdateCoordinator } from './update-coordinator.ts'
import { prepareDesktopUpdateWindow } from './update-window.ts'
import { DesktopCommandManager } from './command-management.ts'
import { serveWebDocument, authenticateWebHost, forwardWebRequest } from './web-document.ts'
import { serveWebDocument, authenticateWebHost, forwardWebRequest, removeLegacyHostCookies } 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'
@@ -529,11 +528,14 @@ async function main(): Promise<void> {
return {
start: async () => {
const ready = await host.start()
hostCookie = await authenticateWebHost(ready.url)
const cookie = await authenticateWebHost(ready.url)
hostCookie = cookie
hostUrl = ready.url
void removeLegacyHostCookies(session.defaultSession.cookies, ready.url)
.catch((error: unknown) => { console.error('desktop: legacy Host cookie cleanup failed', error) })
if (ready.injections === undefined) throw new Error('Desktop Host did not provide boot injections')
injections = ready.injections
welcomeBackend = await connectDesktopWelcome(ready.url, (input, init) => net.fetch(input, init), async () => (await session.defaultSession.cookies.get({ url: ready.url })).map(cookie => `${cookie.name}=${cookie.value}`).join('; '))
welcomeBackend = connectDesktopWelcome(ready.url, cookie)
analyticsEnabled = await welcomeBackend.analyticsEnabled().catch(() => false)
if (!reportedLaunch) { reportedLaunch = true; void track('desktop_app_launch', {}) }
stopAccount?.()
+20
View File
@@ -49,6 +49,26 @@ export async function authenticateWebHost(url: string): Promise<string> {
return end < 0 ? cookie : cookie.slice(0, end)
}
/** Cookie store operations used to remove legacy Host authentication cookies. */
export interface HostCookieStore {
get(filter: { url: string }): Promise<readonly { readonly name: string }[]>
remove(url: string, name: string): Promise<void>
}
/**
* Remove every `dsh-auth-*` cookie that earlier releases left in a cookie store for the Host's hostname.
* Cookies ignore ports, so cookies from earlier random-port Hosts would otherwise travel with every
* request to that hostname until they expire.
* @param cookies - Electron session cookie store.
* @param url - Host URL; cookies for its hostname on every port are removed.
*/
export async function removeLegacyHostCookies(cookies: HostCookieStore, url: string): Promise<void> {
const origin = new URL(url).origin
for (const { name } of await cookies.get({ url: origin })) {
if (name.startsWith('dsh-auth-')) await cookies.remove(origin, name)
}
}
/**
* Response headers not relayed to the renderer. `set-cookie` would hand the
* Host's authentication cookie to the page's cookie jar, which the shell owns
+13 -15
View File
@@ -35,20 +35,18 @@ function record(value: unknown): value is Record<string, unknown> {
}
/**
* Authenticate the native HTTP client through the Web application's launch URL.
* @param authenticatedUrl - URL supplied by the running Desktop Host.
* @param send - Electron session fetch, retaining the Web authentication cookie.
* Connect the native HTTP client to the Desktop Host; every request sends `cookie` explicitly and uses no cookie jar.
* @param hostUrl - URL of the running Desktop Host; only its origin is used.
* @param cookie - Cookie header returned by `authenticateWebHost` for this Host.
* @param send - HTTP client for Host requests.
* @returns metadata reads and write-only credential operations over standard RPC.
*/
export async function connectDesktopWelcome(
authenticatedUrl: string,
send: (input: string, init?: RequestInit) => Promise<Response>,
cookies: () => Promise<string> = () => Promise.resolve(''),
): Promise<DesktopWelcomeBackend> {
const origin = new URL(authenticatedUrl).origin
const authenticated = await send(authenticatedUrl, { credentials: 'include' })
await authenticated.body?.cancel()
if (!authenticated.ok) throw new Error('desktop welcome: Web authentication failed')
export function connectDesktopWelcome(
hostUrl: string,
cookie: string,
send: (input: string, init?: RequestInit) => Promise<Response> = fetch,
): DesktopWelcomeBackend {
const origin = new URL(hostUrl).origin
const invoke = async (
request: { namespace: string; method: string; args: Record<string, unknown> },
signal?: AbortSignal,
@@ -56,8 +54,8 @@ export async function connectDesktopWelcome(
const rpcId = randomUUID()
const method = `${request.namespace}/${request.method}`
const response = await send(new URL(`/api/${method}`, origin).href, {
method: 'POST', credentials: 'include', redirect: 'error', ...(signal === undefined ? {} : { signal }),
headers: { 'content-type': 'application/json' },
method: 'POST', redirect: 'error', ...(signal === undefined ? {} : { signal }),
headers: { 'content-type': 'application/json', cookie },
body: JSON.stringify({ type: 'client-request', rpcId, method, payload: { args: request.args } }),
})
if (!response.ok) throw new Error('desktop welcome: Web request failed')
@@ -68,7 +66,7 @@ export async function connectDesktopWelcome(
}
return envelope.result.value
}
const account = desktopAccountBackend(origin, invoke, cookies)
const account = desktopAccountBackend(origin, invoke, cookie)
const settingsAndReference = async () => {
const settings = await invoke({ namespace: 'settings', method: 'describe', args: {} })
if (!record(settings) || !Array.isArray(settings.namespaces)) throw new Error('desktop welcome: missing settings namespaces')
+5 -3
View File
@@ -1,4 +1,5 @@
import { once } from 'node:events'
import type { IncomingMessage } from 'node:http'
import { WebSocketServer } from 'ws'
import { expect, it, onTestFinished, vi } from 'vitest'
import { accountView, desktopAccountBackend } from '../src/account-backend.ts'
@@ -28,7 +29,7 @@ it('uses account Remote commands without returning additional wire fields', asyn
const backend = desktopAccountBackend('http://127.0.0.1:1234', (request) => {
requests.push(request)
return Promise.resolve({ links: { usageUrl: 'http://localhost/usage', topUpUrl: 'http://localhost/top_up' }, status: 'signed-out', attempt: null, token: 'private' })
}, () => Promise.resolve(''))
}, '')
const client = { version: '1.2.3', locale: 'en', timezoneOffsetSeconds: 28_800 }
expect(await backend.start(client)).toEqual({ links: { usageUrl: 'http://localhost/usage', topUpUrl: 'http://localhost/top_up' }, status: 'signed-out', attempt: null })
expect(await backend.signOut(client)).toMatchObject({ status: 'signed-out' })
@@ -59,12 +60,13 @@ it('receives live expiry separately from account snapshots', async () => {
const snapshot = { status: 'signed-out', attempt: null,
links: { usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up' } }
const received = Promise.withResolvers<undefined>()
const backend = desktopAccountBackend(`http://127.0.0.1:${address.port}`, () => Promise.resolve(snapshot), () => Promise.resolve(''))
const backend = desktopAccountBackend(`http://127.0.0.1:${address.port}`, () => Promise.resolve(snapshot), 'dsh-auth-fixture=signed')
const stop = backend.watch(
(value) => { expect(value).toEqual(snapshot); received.resolve(undefined) }, vi.fn(), expired, onAnalyticsEnabledChanged,
)
onTestFinished(stop)
await connected
const [, upgrade] = await connected as [unknown, IncomingMessage]
expect(upgrade.headers.cookie).toBe('dsh-auth-fixture=signed')
// Logical streams share the socket; observe their opening frames before sending data.
const streams = new Map<string, string>()
const opened = Promise.withResolvers<undefined>()
@@ -1,4 +1,4 @@
/** Cold pnpm requests exercise on-demand CUA dependency/platform metadata with inert package contents. */
/** Cold pnpm requests exercise shipped CUA dependency/platform metadata with inert package contents. */
import { createHash } from 'node:crypto'
import { createServer } from 'node:http'
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
@@ -37,14 +37,14 @@ it('fetches the macOS optional tarball only for Darwin, with an empty cache for
const cli = await readManifest('apps/cli')
const bundle = await readManifest('packages/experimental/cua-bundle')
const native = await readManifest('packages/experimental/cua-macos')
expect(cli.dependencies).not.toHaveProperty(bundleName)
expect(cli.dependencies).toHaveProperty(bundleName)
expect(bundle.dependencies).not.toHaveProperty(providerName)
expect(bundle.optionalDependencies).toEqual({ [providerName]: 'workspace:*' })
expect(native.os).toEqual(['darwin'])
const version = '1.0.0'
const bundleDependencies = Object.fromEntries(Object.keys(bundle.dependencies as Record<string, string>).map(name => [name, version]))
const manifests = [
{ name: cli.name, version },
{ name: cli.name, version, dependencies: { [bundleName]: version } },
{ name: bundleName, version, dependencies: bundleDependencies, optionalDependencies: { [providerName]: version } },
...Object.keys(bundleDependencies).map(name => ({ name, version })),
{ name: providerName, version, os: native.os, files: native.files },
@@ -102,13 +102,13 @@ it('fetches the macOS optional tarball only for Darwin, with an empty cache for
await new Promise<void>((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) })
const address = server.address()
if (!address || typeof address === 'string') throw new Error('fixture registry has no TCP address')
for (const target of ['darwin-base', 'darwin', 'win32', 'linux', 'linux-unrestricted']) {
for (const target of ['darwin', 'win32', 'linux', 'linux-unrestricted']) {
unrestricted = target === 'linux-unrestricted'
const project = join(root, target)
await mkdir(project)
await writeFile(join(project, 'package.json'), JSON.stringify({ private: true, dependencies: { [target === 'darwin-base' ? String(cli.name) : bundleName]: version } }))
await writeFile(join(project, 'package.json'), JSON.stringify({ private: true, dependencies: { [String(cli.name)]: version } }))
await writeFile(join(project, 'pnpm-workspace.yaml'), [
'autoInstallPeers: false', 'supportedArchitectures:', ` os: [${unrestricted ? 'linux' : target === 'darwin-base' ? 'darwin' : target}]`,
'autoInstallPeers: false', 'supportedArchitectures:', ` os: [${unrestricted ? 'linux' : target}]`,
' cpu: [arm64]', 'minimumReleaseAge: 0', '',
].join('\n'))
requests.length = 0
@@ -117,8 +117,8 @@ it('fetches the macOS optional tarball only for Darwin, with an empty cache for
`--config.registry=http://127.0.0.1:${address.port}/`, `--config.store-dir=${join(project, 'store')}`,
`--config.cache-dir=${join(project, 'cache')}`, `--config.state-dir=${join(project, 'state')}`,
], project)
expect(requests.includes(`/${bundleName}.tgz`)).toBe(target !== 'darwin-base')
expect(requests.includes('/@deepseek-ai/dsh-cua.tgz')).toBe(target !== 'darwin-base')
expect(requests).toContain(`/${bundleName}.tgz`)
expect(requests).toContain('/@deepseek-ai/dsh-cua.tgz')
expect(requests.includes(`/${providerName}.tgz`), `${target}: ${JSON.stringify(requests)}\n${output}`)
.toBe(target === 'darwin' || unrestricted)
}
@@ -1,5 +1,10 @@
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { expect, it, vi } from 'vitest'
import { runLoggedNotarytool } from '../scripts/logged-notarytool.mjs'
import { createPackagingRun } from '../scripts/packaging-run.mjs'
const command = vi.hoisted(() => vi.fn<(...args: unknown[]) => Promise<{ stdout: string; stderr: string }>>())
vi.mock('node:child_process', async (importOriginal) => {
@@ -28,6 +33,52 @@ it('does not treat failed upload output as a completed submission', async () =>
command.mockRejectedValueOnce(Object.assign(new Error('upload failed'), {
code: 1, stdout: JSON.stringify({ id }), stderr: '',
}))
await expect(runLoggedNotarytool(args)).rejects.toThrow('upload failed')
const work = runLoggedNotarytool(args)
await expect(work).rejects.toThrow('notarytool submit failed (code: 1')
await expect(work).rejects.toHaveProperty('cause.message', 'upload failed')
expect(command).toHaveBeenCalledOnce()
})
it.each([false, true])('prints the redacted Apple failure with a journal=%s and leaves stdout for protocol replies', async (recorded) => {
const root = await mkdtemp(join(tmpdir(), 'notary-cli-'))
const directory = recorded ? createPackagingRun(root, {}).directory : undefined
const savedArgv = process.argv
const savedExit = process.exitCode
const savedDirectory = process.env.DSH_DESKTOP_PACKAGING_RUN_DIR
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true)
const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(() => true)
try {
if (directory === undefined) delete process.env.DSH_DESKTOP_PACKAGING_RUN_DIR
else process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = directory
process.argv = [process.execPath, fileURLToPath(new URL('../scripts/logged-notarytool.mjs', import.meta.url)),
'submit', '/fixture/app.zip', '--apple-id', '[email protected]', '--password', 'secret-sentinel',
'--team-id', 'private-team', '--wait', '--output-format', 'json']
command.mockReset()
command.mockRejectedValueOnce(Object.assign(new Error('connection closed: [email protected] secret-sentinel private-team'), {
code: 69, signal: null, stdout: 'Apple response: secret-sentinel', stderr: 'HTTP 503 Service Unavailable',
}))
vi.resetModules()
await import('../scripts/logged-notarytool.mjs')
expect(command).toHaveBeenCalledOnce()
expect(process.exitCode).toBe(1)
expect(stdout).not.toHaveBeenCalled()
const output = stderr.mock.calls.map(([chunk]) => String(chunk)).join('')
const diagnostics = [output, ...directory === undefined ? [] : [await readFile(join(directory, 'events.jsonl'), 'utf8')]]
for (const diagnostic of diagnostics) {
expect(diagnostic).toContain('code: 69')
expect(diagnostic).toContain('Apple response: [REDACTED]')
expect(diagnostic).toContain('HTTP 503 Service Unavailable')
expect(diagnostic).toContain('connection closed')
for (const secret of ['[email protected]', 'secret-sentinel', 'private-team']) expect(diagnostic).not.toContain(secret)
}
expect(output.includes('events.jsonl')).toBe(recorded)
} finally {
process.argv = savedArgv
process.exitCode = savedExit
if (savedDirectory === undefined) delete process.env.DSH_DESKTOP_PACKAGING_RUN_DIR
else process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = savedDirectory
stderr.mockRestore()
stdout.mockRestore()
await rm(root, { recursive: true, force: true })
}
})
+32 -2
View File
@@ -3,9 +3,11 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
import { signMacOSRuntime } from '../scripts/macos-runtime.ts'
import { signMacOSRuntimeCode, verifyMacOSRuntimeCode } from '../scripts/verify-macos-signature.mjs'
import { signMacOSRuntimeCode, verifyMacOSNotarizedApplication, verifyMacOSRuntimeCode } from '../scripts/verify-macos-signature.mjs'
vi.mock('../scripts/verify-macos-signature.mjs', () => ({ signMacOSRuntimeCode: vi.fn(), verifyMacOSRuntimeCode: vi.fn() }))
vi.mock('../scripts/verify-macos-signature.mjs', () => ({
signMacOSRuntimeCode: vi.fn(), verifyMacOSNotarizedApplication: vi.fn(), verifyMacOSRuntimeCode: vi.fn(),
}))
const roots: string[] = []
function root(): string {
const path = mkdtempSync(join(tmpdir(), 'desktop-signing-'))
@@ -26,6 +28,34 @@ it('signs Mach-O files in their final locations and verifies each signature', as
expect(verifyMacOSRuntimeCode).toHaveBeenCalledWith(join(path, 'addon.node'), identity)
})
const helperBundle = 'node_modules/@deepseek-ai/dsh-experimental-cua-macos/native/bin/darwin-arm64/generation/DSH Computer Use.app'
function machO(path: string): void {
mkdirSync(join(path, '..'), { recursive: true })
writeFileSync(path, Buffer.from('cffaedfe00000000', 'hex'))
}
it('verifies the notarized Computer Use helper as a bundle and signs other bundles per file', async () => {
const path = root()
machO(join(path, helperBundle, 'Contents/MacOS/dsh-cua-native'))
writeFileSync(join(path, helperBundle, 'Contents/Info.plist'), '<plist/>')
// LibreOffice ships an unsigned application bundle whose executables are signed in place.
const office = join(path, 'node_modules/@deepseek-ai/libreoffice-kit-darwin-arm64/program/LibreOfficeDev.app/Contents/MacOS/soffice')
machO(office)
machO(join(path, 'addon.node'))
await expect(signMacOSRuntime(path, 'com.example.app', identity, 'arm64')).resolves.toBe(2)
expect(verifyMacOSNotarizedApplication).toHaveBeenCalledExactlyOnceWith(join(path, helperBundle), identity)
expect(vi.mocked(signMacOSRuntimeCode).mock.calls.map(([file]) => file).sort()).toEqual([join(path, 'addon.node'), office].sort())
})
it('rejects a helper bundle that fails notarized-application verification before signing any file', async () => {
const path = root()
machO(join(path, helperBundle, 'Contents/MacOS/dsh-cua-native'))
machO(join(path, 'addon.node'))
vi.mocked(verifyMacOSNotarizedApplication).mockImplementationOnce(() => { throw new Error('stapler validate exited with 65') })
await expect(signMacOSRuntime(path, 'com.example.app', identity, 'arm64')).rejects.toThrow('stapler validate')
expect(signMacOSRuntimeCode).not.toHaveBeenCalled()
})
// File symlinks in these macOS fixtures require privileges unavailable to ordinary Windows processes.
it.skipIf(process.platform === 'win32')('signs a shared Python interpreter once and retains both executable aliases', async () => {
const path = root()
@@ -73,6 +73,7 @@ describe('desktop macOS release signature', () => {
expect(config.asarUnpack).toEqual(expect.arrayContaining([
'**/*.{node,dylib,dll,so,exe}',
'**/@vscode/ripgrep-*/bin/rg',
'**/node_modules/@deepseek-ai/dsh-experimental-cua-macos/native/bin/**/*',
]))
expect(config).toMatchObject({
appId: RELEASE_ENVIRONMENT.DSH_DESKTOP_APP_ID,
+34 -13
View File
@@ -22,7 +22,10 @@ type InvokeHandler = (event: InvokeEvent, ...args: unknown[]) => unknown
const fileDrag = vi.hoisted(() => ({ dispose: vi.fn<() => Promise<void>>(), install: vi.fn() }))
vi.mock('../src/file-drag.ts', () => ({ installDesktopFileDrag: () => { fileDrag.install(); return fileDrag.dispose } }))
vi.mock('../src/web-document.ts', () => ({ authenticateWebHost: async () => 'test-cookie', serveWebDocument: vi.fn(), forwardWebRequest: vi.fn() }))
vi.mock('../src/web-document.ts', () => ({
authenticateWebHost: async () => 'test-cookie', serveWebDocument: vi.fn(), forwardWebRequest: vi.fn(),
removeLegacyHostCookies: harness.removeLegacyHostCookies,
}))
vi.mock('../src/operation-report-job.ts', () => ({ runOperationReportJob: vi.fn(async () => ({ appended: false, timedOut: false, cancelled: false })) }))
// Report persistence has its own unit tests; here it resolves within microtasks so the fatal
// dialog never outlives the test that triggered it.
@@ -215,7 +218,8 @@ const harness = await vi.hoisted(async () => {
failWindow(error: Error) { windowFailure = error },
windows, views, hosts, handlers, app, FakeWindow, FakeView, FakeHost, powerMonitor, nativeTheme, analytics,
trays, FakeTray, backgroundNotice, shellDialog,
menu, popup, socketHeaders: vi.fn(), loginShell, readLoginShell, updateCheck, updateDownload, updateInstall,
menu, popup, socketHeaders: vi.fn(), connectWelcome: vi.fn(), removeLegacyHostCookies: vi.fn(async () => {}), hostCookies: {},
loginShell, readLoginShell, updateCheck, updateDownload, updateInstall,
platformDispose,
platformCloseAndWait,
@@ -306,7 +310,6 @@ vi.mock('electron', () => ({
dialog: harness.dialog,
shell: { openExternal: harness.openExternal },
nativeTheme: harness.nativeTheme,
net: { fetch: vi.fn() },
ipcMain: {
on: harness.ipcOn,
handle: (channel: string, handler: InvokeHandler) => {
@@ -317,7 +320,7 @@ vi.mock('electron', () => ({
},
Menu: { setApplicationMenu: harness.menu.setApplicationMenu, buildFromTemplate: harness.menu },
session: { defaultSession: {
on: vi.fn(),
on: vi.fn(), cookies: harness.hostCookies,
setPermissionCheckHandler: vi.fn(), setPermissionRequestHandler: vi.fn(), webRequest: { onBeforeSendHeaders: harness.socketHeaders },
} },
protocol: { registerSchemesAsPrivileged: vi.fn(), handle: harness.protocolHandle },
@@ -389,14 +392,17 @@ vi.mock('../src/platform-view.ts', async importOriginal => ({
},
}))
vi.mock('../src/welcome-backend.ts', () => ({
connectDesktopWelcome: async () => ({
analyticsEnabled: async () => harness.analyticsEnabled,
report: harness.analytics,
readLocalePreference: async () => null,
read: async (): Promise<unknown> => (await harness.hosts.at(-1)!.fetch()).json() as Promise<unknown>,
save: async () => ({ ok: true }),
account: { watch: harness.watchAccount, state: async () => ({ status: 'signed-out', attempt: null }) },
}),
connectDesktopWelcome: (...args: unknown[]) => {
harness.connectWelcome(...args)
return {
analyticsEnabled: async () => harness.analyticsEnabled,
report: harness.analytics,
readLocalePreference: async () => null,
read: async (): Promise<unknown> => (await harness.hosts.at(-1)!.fetch()).json() as Promise<unknown>,
save: async () => ({ ok: true }),
account: { watch: harness.watchAccount, state: async () => ({ status: 'signed-out', attempt: null }) },
}
},
}))
function configureTestAuthPopup(allow: boolean): void {
@@ -1126,7 +1132,7 @@ describe('desktop main startup', () => {
} finally { harness.app.name = originalName }
})
it.each(['http:', 'https:'] as const)('attaches %s Host socket credentials only to the owned application origin and window', async (protocol) => {
it.each(['http:', 'https:'] as const)('passes the %s Host cookie explicitly and attaches socket credentials only to the owned application origin and window', async (protocol) => {
await import('../src/main.ts')
await harness.preparing.promise
harness.prepared.resolve()
@@ -1134,6 +1140,8 @@ describe('desktop main startup', () => {
harness.hosts[0]!.url = `${protocol}//127.0.0.1:3080/?token=test`
harness.hosts[0]!.ready.resolve()
await Promise.resolve(invoke(DESKTOP_IPC.boot))
expect(harness.connectWelcome).toHaveBeenCalledWith(`${protocol}//127.0.0.1:3080/?token=test`, 'test-cookie')
expect(harness.removeLegacyHostCookies).toHaveBeenCalledWith(harness.hostCookies, `${protocol}//127.0.0.1:3080/?token=test`)
const handler = harness.socketHeaders.mock.calls[0]![1] as (
details: { url: string; webContentsId: number; requestHeaders: Record<string, string> },
callback: (result: unknown) => void,
@@ -1155,6 +1163,19 @@ describe('desktop main startup', () => {
expect(callback).toHaveBeenLastCalledWith({})
})
it('logs a legacy Host cookie cleanup failure without blocking boot', async () => {
const failure = new Error('cookie store unavailable')
harness.removeLegacyHostCookies.mockRejectedValueOnce(failure)
await import('../src/main.ts')
await harness.preparing.promise
harness.prepared.resolve()
await harness.hostStarted.promise
harness.hosts[0]!.ready.resolve()
await Promise.resolve(invoke(DESKTOP_IPC.boot))
await vi.waitFor(() => { expect(console.error).toHaveBeenCalledWith('desktop: legacy Host cookie cleanup failed', failure) })
expect(harness.connectWelcome).toHaveBeenCalled()
})
it('shares login key discovery with onboarding and rejects foreign renderers', async () => {
await readyForUpdate()
const window = harness.windows[0]!
+12 -1
View File
@@ -2,7 +2,7 @@ import { afterEach, expect, it, vi } from 'vitest'
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { authenticateWebHost, forwardWebRequest, serveWebDocument } from '../src/web-document.ts'
import { authenticateWebHost, forwardWebRequest, removeLegacyHostCookies, serveWebDocument } from '../src/web-document.ts'
const roots: string[] = []
afterEach(async () => {
@@ -86,3 +86,14 @@ it('refuses another page origin without forwarding its request', async () => {
expect(response.status).toBe(403)
expect(fetch).not.toHaveBeenCalled()
})
it('removes only legacy Host authentication cookies for the Host hostname', async () => {
const removed: [string, string][] = []
const cookies = {
get: vi.fn(async () => [{ name: 'dsh-auth-old' }, { name: 'other-app' }, { name: 'dsh-auth-older' }]),
remove: vi.fn(async (url: string, name: string) => { removed.push([url, name]) }),
}
await removeLegacyHostCookies(cookies, 'http://127.0.0.1:1234/?token=secret')
expect(cookies.get).toHaveBeenCalledExactlyOnceWith({ url: 'http://127.0.0.1:1234' })
expect(removed).toEqual([['http://127.0.0.1:1234', 'dsh-auth-old'], ['http://127.0.0.1:1234', 'dsh-auth-older']])
})
+2 -11
View File
@@ -12,6 +12,7 @@ import { DesktopProjectManager } from '../src/project-manager.ts'
import { resolveDesktopPaths } from '../src/paths.ts'
import { desktopClientMetadata } from '../src/client-metadata.ts'
import { connectDesktopWelcome, type DesktopWelcomeBackend } from '../src/welcome-backend.ts'
import { authenticateWebHost } from '../src/web-document.ts'
import { DESKTOP_HOST_PROTOCOL_VERSION } from '../src/host-protocol.ts'
import { prepareDevelopmentProject } from '../scripts/development-project.ts'
@@ -129,17 +130,7 @@ describe.skipIf(!existsSync(builtHost))('built Desktop welcome flow', () => {
host = new DesktopHostProcess(process.execPath, project, paths.profile)
const { url } = await host.start()
hostOrigin = new URL(url).origin
let cookie = ''
const send: typeof fetch = async (input, init) => {
const headers = new Headers(init?.headers)
if (cookie !== '') headers.set('cookie', cookie)
const response = await fetch(input, { ...init, headers, redirect: 'manual' })
if (response.status !== 303) return response
cookie = response.headers.getSetCookie().map(value => value.split(';')[0]).join('; ')
await response.body?.cancel()
return fetch(new URL(response.headers.get('location')!, url), { headers: { cookie } })
}
backend = await connectDesktopWelcome(url, send, () => Promise.resolve(cookie))
backend = connectDesktopWelcome(url, await authenticateWebHost(url))
}
const status = async () => backend.read()
const fingerprint = (): string => createHash('sha256')
+16 -22
View File
@@ -9,9 +9,8 @@ function transport(preference?: string) {
{ ns: 'llm-pi-ai', value: { profiles: { example: { apiKeyEnv: 'EXAMPLE_API_KEY' } } } },
{ ns: 'locale', value: preference === undefined ? {} : { preference } },
]
const send = vi.fn<Parameters<typeof connectDesktopWelcome>[1]>(async (_input, init) => {
if (init?.method !== 'POST') return new Response('index')
const { rpcId, method, payload } = JSON.parse(init.body as string) as {
const send = vi.fn<NonNullable<Parameters<typeof connectDesktopWelcome>[2]>>(async (_input, init) => {
const { rpcId, method, payload } = JSON.parse(init!.body as string) as {
rpcId: string
method: string
payload: { args: { ref: string; value: string; refs: string[] } }
@@ -29,27 +28,28 @@ function transport(preference?: string) {
return { send, keys, namespaces }
}
const url = 'http://127.0.0.1:19387/?token=fixture'
const url = 'http://127.0.0.1:19387/'
const cookie = 'dsh-auth-fixture=signed'
describe('desktop welcome Web operations', () => {
it('authenticates through Web and stores only through the configured credential reference', async () => {
it('authenticates with the explicit Host cookie and stores only through the configured credential reference', async () => {
const host = transport()
const backend = await connectDesktopWelcome(url, host.send)
expect(host.send).toHaveBeenCalledExactlyOnceWith(url, { credentials: 'include' })
const backend = connectDesktopWelcome(url, cookie, host.send)
expect(await backend.analyticsEnabled()).toBe(true)
expect(await backend.save('sk-example')).toEqual({ ok: true })
expect(host.keys.get('CUSTOM_DEEPSEEK_KEY')).toBe('sk-example')
expect(await backend.read()).toEqual({ loggedIn: false, hasApiKey: true, writable: true, localePreference: null })
for (const [input, init] of host.send.mock.calls.slice(1)) {
for (const [input, init] of host.send.mock.calls) {
expect(input).toMatch(/^http:\/\/127\.0\.0\.1:19387\/api\//u)
expect(init).toMatchObject({ credentials: 'include', redirect: 'error' })
expect(init).toMatchObject({ redirect: 'error', headers: { cookie } })
expect(init).not.toHaveProperty('credentials')
}
})
it('reads the explicit language preference and recognizes another provider key', async () => {
const host = transport('zh')
host.keys.set('EXAMPLE_API_KEY', 'sk-other')
const backend = await connectDesktopWelcome(url, host.send)
const backend = connectDesktopWelcome(url, cookie, host.send)
expect(await backend.read()).toMatchObject({ localePreference: 'zh', hasApiKey: true })
host.keys.clear()
expect(await backend.read()).toMatchObject({ hasApiKey: false })
@@ -58,7 +58,7 @@ describe('desktop welcome Web operations', () => {
it('reads language without querying account or model providers', async () => {
const host = transport('zh')
const backend = await connectDesktopWelcome(url, host.send)
const backend = connectDesktopWelcome(url, cookie, host.send)
host.send.mockClear()
expect(await backend.readLocalePreference()).toBe('zh')
expect(host.send).toHaveBeenCalledOnce()
@@ -68,7 +68,7 @@ describe('desktop welcome Web operations', () => {
it('allows profiles without the official provider and retains custom key detection', async () => {
const host = transport()
host.namespaces.splice(0, 1)
const backend = await connectDesktopWelcome(url, host.send)
const backend = connectDesktopWelcome(url, cookie, host.send)
expect(await backend.read()).toMatchObject({ hasApiKey: false, writable: false })
host.keys.set('EXAMPLE_API_KEY', 'custom-key')
expect(await backend.read()).toMatchObject({ hasApiKey: true, writable: false })
@@ -78,7 +78,7 @@ describe('desktop welcome Web operations', () => {
it.each(['', 'bad key', 'key\n'])('rejects malformed keys without contacting a provider: %s', async (value) => {
const host = transport()
const backend = await connectDesktopWelcome(url, host.send)
const backend = connectDesktopWelcome(url, cookie, host.send)
host.send.mockClear()
expect(await backend.save(value)).toEqual({ ok: false })
expect(host.send).not.toHaveBeenCalled()
@@ -86,28 +86,22 @@ describe('desktop welcome Web operations', () => {
it('keeps provider diagnostics out of failures and rejects unmatched RPC envelopes', async () => {
const host = transport()
const backend = await connectDesktopWelcome(url, host.send)
const backend = connectDesktopWelcome(url, cookie, host.send)
host.send.mockRejectedValueOnce(new Error('private credential sk-must-not-leak'))
expect(await backend.save('sk-example')).toEqual({ ok: false })
host.send.mockResolvedValueOnce(Response.json({ type: 'server-response', rpcId: 'other', result: { ok: true } }))
await expect(backend.read()).rejects.toThrow('Web RPC failed')
})
it('submits native analytics through authenticated RPC with a bounded request', async () => {
const host = transport()
const backend = await connectDesktopWelcome(url, host.send)
const backend = connectDesktopWelcome(url, cookie, host.send)
const event = { eventName: 'desktop_app_launch' as const, timestamp: 100, attributes: {} }
await backend.report(event)
const [input, init] = host.send.mock.calls.at(-1)!
expect(input).toBe('http://127.0.0.1:19387/api/productAnalytics/report')
expect(init?.credentials).toBe('include')
expect(init?.headers).toMatchObject({ cookie })
expect(init?.signal).toBeInstanceOf(AbortSignal)
expect(JSON.parse(init!.body as string)).toMatchObject({ payload: { args: { event } } })
})
it('refuses an unauthenticated Web launch', async () => {
const send = vi.fn<Parameters<typeof connectDesktopWelcome>[1]>(async () => new Response(null, { status: 401 }))
await expect(connectDesktopWelcome(url, send)).rejects.toThrow('Web authentication failed')
})
})
+5 -4
View File
@@ -1,4 +1,6 @@
vi.mock('../src/web-document.ts', () => ({ authenticateWebHost: async () => 'test-cookie', serveWebDocument: vi.fn(), forwardWebRequest: vi.fn() }))
vi.mock('../src/web-document.ts', () => ({
authenticateWebHost: async () => 'test-cookie', serveWebDocument: vi.fn(), forwardWebRequest: vi.fn(), removeLegacyHostCookies: async () => {},
}))
/** Welcome startup uses the Host before transitioning to the workspace. */
import { afterEach, expect, it, vi } from 'vitest'
@@ -84,10 +86,9 @@ vi.mock('electron', () => ({
showInactive = state.showInactiveWorkspace
async loadURL(url: string) { state.contents = this.webContents; await state.loadWorkspace(url); this.ready?.() }
},
net: { fetch: vi.fn() },
nativeTheme: state.nativeTheme,
session: { defaultSession: {
on: vi.fn(),
on: vi.fn(), cookies: {},
setPermissionCheckHandler: vi.fn(), setPermissionRequestHandler: vi.fn(), webRequest: { onBeforeSendHeaders: vi.fn() },
} },
protocol: { registerSchemesAsPrivileged: vi.fn(), handle: vi.fn() },
@@ -124,7 +125,7 @@ vi.mock('../src/host-process.ts', () => ({
},
}))
vi.mock('../src/welcome-backend.ts', () => ({
connectDesktopWelcome: async () => ({
connectDesktopWelcome: () => ({
analyticsEnabled: async () => false,
readLocalePreference: async () => state.preference,
read: async () => {
+1 -1
View File
@@ -44,7 +44,7 @@ it('disables unsupported bundles, shows the Host restriction, and refuses direct
const names = [name]
await page.locator('[data-plugin-panel]').getByRole('button', { name: '更多', exact: true }).click()
const cua = page.locator('[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]')
expect(await cua.count()).toBe(0)
expect(await cua.count()).toBe(process.platform === 'darwin' ? 1 : 0)
if (process.platform !== 'darwin') {
expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle'))
.toMatchObject({ listedByDefault: false, enabled: false, error: { code: 'unsupported-platform' } })
+235
View File
@@ -0,0 +1,235 @@
/** Saved credentials and endpoints reach the assembled editor and provider requests. */
import { once } from 'node:events'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { createServer } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium } from 'playwright'
import { expect, it, onTestFinished } from 'vitest'
import { BlockAssembler } from '@deepseek-ai/dsh-llm'
import { credentialRef } from '@deepseek-ai/dsh-credentials'
import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, webSnapshotMode } from './scaffold.ts'
import { openSettings, ZH_BROWSER_LOCALE } from './support.ts'
it.each([false, true])('edits saved DeepSeek keys and restores environment detection (environment present: %s)', async (hasEnvironment) => {
const scaffold = await launchWebScaffold({
deepSeekMissingCredential: true,
extraOverlayPath: fileURLToPath(new URL('./fixtures/credential-editor.patch.yml', import.meta.url)),
openInAppEnvironment: createLaunchEnvironmentSnapshot([{
source: 'process', values: hasEnvironment ? { DEEPSEEK_API_KEY: 'fixture-environment-key' } : {},
}]),
})
try {
const browser = await chromium.launch()
try {
const page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: ZH_BROWSER_LOCALE })
const ref = credentialRef('DEEPSEEK_API_KEY')
await scaffold.ctx.credentials.set(ref, 'fixture-saved-deepseek-key')
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await openSettings(page, 'zh')
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '模型', exact: true }).click()
const edit = dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true })
await edit.click()
const key = dialog.getByLabel('API 密钥', { exact: true })
await expect.poll(() => key.inputValue()).toBe('fixture-saved-deepseek-key')
expect(await key.getAttribute('type')).toBe('password')
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/credential-editor/saved-key.expected.md', import.meta.url)),
await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode(),
)
await dialog.getByRole('button', { name: '显示密钥', exact: true }).click()
expect(await key.getAttribute('type')).toBe('text')
await key.fill('fixture-cancelled-key')
await dialog.getByRole('button', { name: '取消', exact: true }).click()
expect(await scaffold.ctx.credentials.readStored(ref)).toBe('fixture-saved-deepseek-key')
await edit.click()
await expect.poll(() => key.inputValue()).toBe('fixture-saved-deepseek-key')
expect(await key.getAttribute('type')).toBe('password')
await key.fill('fixture-replacement-key')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor()
expect(await scaffold.ctx.credentials.readStored(ref)).toBe('fixture-replacement-key')
await page.reload({ waitUntil: 'load' })
await openSettings(page, 'zh')
await dialog.getByRole('button', { name: '模型', exact: true }).click()
await edit.click()
await expect.poll(() => key.inputValue()).toBe('fixture-replacement-key')
await key.fill('')
expect(await key.getAttribute('placeholder')).toBe('留空使用环境认证(DEEPSEEK_API_KEY)')
await dialog.getByText('环境凭据状态尚未确认', { exact: true }).waitFor()
expect(await scaffold.ctx.credentials.readStored(ref)).toBe('fixture-replacement-key')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor()
expect(await scaffold.ctx.credentials.readStored(ref)).toBeUndefined()
// A missing credential opens the first-run settings card automatically;
// an environment credential keeps an ordinary row whose editor is closed.
if (hasEnvironment) await edit.click()
await expect.poll(() => key.inputValue()).toBe('')
expect(await key.getAttribute('placeholder')).toBe('留空使用环境认证(DEEPSEEK_API_KEY)')
const hint = hasEnvironment
? '已检测到环境变量(DEEPSEEK_API_KEY)'
: '未检测到环境变量。请填写 API 密钥,或设置环境变量 DEEPSEEK_API_KEY。'
const detection = dialog.getByText(hint, { exact: true })
await detection.waitFor()
const colors = await detection.evaluate((element, present) => {
const label = element as HTMLElement
const actual = getComputedStyle(label).color
const previous = label.style.color
label.style.color = present ? 'var(--dsw-alias-state-success-primary)' : 'var(--dsw-alias-state-warn-label)'
const expected = getComputedStyle(label).color
label.style.color = previous
return { actual, expected }
}, hasEnvironment)
expect(colors.actual).toBe(colors.expected)
expect(await dialog.getByRole('button', { name: '显示密钥', exact: true }).count()).toBe(0)
expect((await scaffold.ctx.credentials.resolve(ref))?.source).toBe(hasEnvironment ? 'env' : undefined)
await compareOrRefreshGolden(
fileURLToPath(new URL(`./expected/credential-editor/${hasEnvironment ? 'detected' : 'missing'}-environment.expected.md`, import.meta.url)),
await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode(),
)
} finally { await browser.close() }
} finally { await scaffold.close() }
})
/** Local provider endpoint recording the destination path and authentication actually received. */
async function connectionProbe(messages: boolean) {
const calls: { path: string; key: string | undefined }[] = []
const server = createServer((request, response) => {
request.on('end', () => {
const key = messages ? request.headers['x-api-key'] : request.headers.authorization
calls.push({ path: request.url ?? '', key: typeof key === 'string' ? key : undefined })
const events = messages ? [
{ type: 'message_start', message: { id: 'probe', type: 'message', role: 'assistant', model: 'credential-editor-model', content: [], usage: { input_tokens: 1, output_tokens: 0 } } },
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'connection-ok' } },
{ type: 'content_block_stop', index: 0 },
{ type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 1 } },
{ type: 'message_stop' },
] : [
{ choices: [{ delta: { role: 'assistant', content: 'connection-ok' }, index: 0, finish_reason: null }] },
{ choices: [{ delta: {}, index: 0, finish_reason: 'stop' }], usage: { prompt_tokens: 1, completion_tokens: 1 } },
]
response.writeHead(200, { 'content-type': 'text/event-stream' })
response.end(events.map(event => `${'type' in event ? `event: ${event.type}\n` : ''}data: ${JSON.stringify(event)}\n\n`).join('')
+ (messages ? '' : 'data: [DONE]\n\n'))
})
request.resume()
})
onTestFinished(async () => {
await new Promise<void>((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() })
})
server.listen(0, '127.0.0.1')
await once(server, 'listening')
const address = server.address()
if (address === null || typeof address === 'string') throw new Error('connection probe did not bind TCP')
return { url: `http://127.0.0.1:${String(address.port)}`, calls }
}
it.each([
{ provider: 'deepseek-official', ref: 'DEEPSEEK_API_KEY', messages: true },
{ provider: 'openai', ref: 'OPENAI_API_KEY', messages: false },
{ provider: 'anthropic', ref: 'ANTHROPIC_API_KEY', messages: true },
{ provider: 'credential-fixture', ref: 'CREDENTIAL_FIXTURE_API_KEY', messages: false },
])('uses the saved endpoint and key on the wire for $provider, then restores fallbacks', async ({ provider, ref, messages }) => {
const ambient = await connectionProbe(messages)
const saved = await connectionProbe(messages)
const root = await mkdtemp(join(tmpdir(), 'dsh-credential-routing-'))
onTestFinished(() => rm(root, { recursive: true, force: true }))
const overlay = join(root, 'connection.patch.yml')
const models = [{ id: 'credential-editor-model' }]
const baseSuffix = provider === 'anthropic' ? '' : '/v1'
const operation = provider === 'anthropic' ? '/v1/messages?beta=true' : messages ? '/messages' : '/chat/completions'
const ambientURL = `${ambient.url}/ambient${baseSuffix}`
await writeFile(overlay, JSON.stringify([
{ id: 'llm-deepseek', config: { models } },
...provider === 'deepseek-official' ? [] : [{
id: 'llm-pi-ai', config: { providers: { [provider]: {
api: messages ? 'anthropic-messages' : 'openai-completions',
baseURL: ambientURL, models,
...provider === 'credential-fixture' ? {} : { apiKeyEnv: ref },
} } },
}],
]))
const scaffold = await launchWebScaffold({
deepSeekMissingCredential: true,
extraOverlayPath: overlay,
openInAppEnvironment: createLaunchEnvironmentSnapshot([{
source: 'process', values: {
[ref]: 'fixture-environment-key',
DEEPSEEK_BASE_URL: ambientURL,
OPENAI_BASE_URL: ambientURL,
ANTHROPIC_BASE_URL: ambientURL,
},
}]),
})
try {
const browser = await chromium.launch()
try {
const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await openSettings(page, 'zh')
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '模型', exact: true }).click()
const edit = dialog.getByRole('button', {
name: `编辑 ${provider === 'deepseek-official' ? 'DeepSeek (deepseek-official)' : provider}`, exact: true,
})
const key = dialog.getByLabel('API 密钥', { exact: true })
const endpoint = dialog.getByLabel('API 地址', { exact: true })
const savedURL = `${saved.url}/configured${baseSuffix}`
const generate = async (): Promise<void> => {
const assembler = new BlockAssembler()
for await (const chunk of scaffold.ctx.llm.stream({ provider, model: 'credential-editor-model', messages: [] })) assembler.push(chunk)
expect(assembler.message({ provider, model: 'credential-editor-model' }).content).toContainEqual({ type: 'text', text: 'connection-ok' })
}
await edit.click()
await key.fill('fixture-saved-key')
await dialog.getByText('自定义设置', { exact: true }).click()
await endpoint.fill(savedURL)
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await expect.poll(() => key.count()).toBe(0)
await generate()
expect(saved.calls).toEqual([{ path: `/configured${baseSuffix}${operation}`, key: messages ? 'fixture-saved-key' : 'Bearer fixture-saved-key' }])
expect(ambient.calls).toEqual([])
await page.reload({ waitUntil: 'load' })
await openSettings(page, 'zh')
await dialog.getByRole('button', { name: '模型', exact: true }).click()
await edit.click()
expect(await key.inputValue()).toBe('fixture-saved-key')
expect(await key.getAttribute('type')).toBe('password')
await dialog.getByText('自定义设置', { exact: true }).click()
expect(await endpoint.inputValue()).toBe(savedURL)
await generate()
expect(saved.calls).toHaveLength(2)
expect(saved.calls[1]).toEqual(saved.calls[0])
expect(ambient.calls).toEqual([])
await key.fill('')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await expect.poll(() => key.count()).toBe(0)
await generate()
expect(saved.calls).toHaveLength(3)
expect(saved.calls[2]).toEqual({ path: `/configured${baseSuffix}${operation}`, key: messages ? 'fixture-environment-key' : 'Bearer fixture-environment-key' })
expect(ambient.calls).toEqual([])
await edit.click()
await key.fill('fixture-saved-key')
await dialog.getByText('自定义设置', { exact: true }).click()
await endpoint.fill('')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await expect.poll(() => key.count()).toBe(0)
await generate()
expect(saved.calls).toHaveLength(3)
expect(ambient.calls).toEqual([{ path: `/ambient${baseSuffix}${operation}`, key: messages ? 'fixture-saved-key' : 'Bearer fixture-saved-key' }])
await edit.click()
await key.fill('')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await expect.poll(() => key.count()).toBe(0)
await generate()
expect(saved.calls).toHaveLength(3)
expect(ambient.calls[1]).toEqual({ path: `/ambient${baseSuffix}${operation}`, key: messages ? 'fixture-environment-key' : 'Bearer fixture-environment-key' })
expect(ambient.calls).toHaveLength(2)
expect(await scaffold.ctx.credentials.readStored(credentialRef(ref))).toBeUndefined()
} finally { await browser.close() }
} finally { await scaffold.close() }
})
+8 -20
View File
@@ -53,22 +53,12 @@ it.skipIf(process.platform !== 'darwin').each([
await plugins.getByRole('button', { name: '更多', exact: true }).waitFor()
expect(await page.locator('[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]').count()).toBe(0)
await plugins.getByRole('button', { name: '更多', exact: true }).click()
// The installation ships the bundle off; the Experimental plugins list offers it without an installation step.
const card = page.locator('[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]')
expect(await card.count()).toBe(0)
expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle'))
.toMatchObject({ listedByDefault: false, enabled: false, installed: false })
await plugins.getByRole('button', { name: '返回插件', exact: true }).click()
const offerCua = async () => {
await plugins.getByRole('button', { name: '添加插件', exact: true }).click()
const dialog = page.getByRole('dialog', { name: '添加插件', exact: true })
await dialog.getByRole('textbox', { name: '包名或地址', exact: true }).fill('@deepseek-ai/dsh-cua-bundle')
await dialog.getByRole('button', { name: '安装', exact: true }).click()
const ready = page.getByRole('dialog', { name: '已安装', exact: true })
await ready.waitFor()
expect(await ready.getByText('无需下载,启用即可使用', { exact: true }).count()).toBe(0)
return ready.getByRole('button', { name: '立即启用', exact: true })
}
const enableNow = await offerCua()
await plugins.locator('[data-plugin-group="more"] [data-plugin-package="@deepseek-ai/dsh-cua-bundle"]').waitFor()
const listed = (await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle')
expect(listed).toMatchObject({ availability: 'installation', optional: true, enabled: false, installed: false })
expect(listed).not.toHaveProperty('listedByDefault')
let toggle = card.getByRole('switch', { name: '启用 Computer Use', exact: true })
const originalAgent = scaffold.ctx.agents.list()[0]!
const ptcAgent = (await scaffold.ctx.agents.create({
@@ -97,12 +87,10 @@ it.skipIf(process.platform !== 'darwin').each([
return applying
})
try {
await enableNow.click()
await expect.poll(() => enableNow.isEnabled()).toBe(false)
expect(await enableNow.getAttribute('aria-busy')).toBe('true')
expect(await card.count()).toBe(0)
await toggle.click()
await card.getByRole('status').getByText('正在应用 Computer Use 的更改', { exact: true }).waitFor()
await compareOrRefreshGolden(fileURLToPath(new URL('./expected/cua-permissions/enabling.expected.md', import.meta.url)),
await captureStableAria(page, '[data-install-phase="done"] button[aria-busy]', scaffold.workspaceCwd), webSnapshotMode())
await captureStableAria(page, '[data-plugin-package="@deepseek-ai/dsh-cua-bundle"] [role="status"]', scaffold.workspaceCwd), webSnapshotMode())
} finally {
enabling.resolve(undefined)
enableCall.mockRestore()
+1 -1
View File
@@ -42,7 +42,7 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr
})
resources.scaffold = scaffold
expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle'))
.toMatchObject({ listedByDefault: false, enabled: true, installed: true })
.toMatchObject({ availability: 'installation', enabled: true, installed: true })
const browser = await chromium.launch()
resources.browser = browser
const page = await newEnglishPage(browser), tripwire = watchConsole(page)
+2 -1
View File
@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { connectDesktopWelcome } from '../../desktop/src/welcome-backend.ts'
import { authenticateWebHost } from '../../desktop/src/web-document.ts'
import { chromium, type Browser, type Page } from 'playwright'
import { afterEach, beforeEach, describe, expect, it, onTestFailed } from 'vitest'
import { credentialKey, credentialRef } from '@deepseek-ai/dsh-credentials'
@@ -107,7 +108,7 @@ describe.skipIf(MODE === 'record')('web e2e: App-only desktop onboarding', () =>
async function desktopPage(locale = ZH_BROWSER_LOCALE): Promise<Page> {
const opened = await browser.newPage({ viewport: { width: 1280, height: 840 }, locale, reducedMotion: 'reduce' })
const welcome = await connectDesktopWelcome(scaffold.authenticatedUrl, (input, init) => scaffold.hostFetch(input, init))
const welcome = connectDesktopWelcome(scaffold.baseUrl, await authenticateWebHost(scaffold.authenticatedUrl))
await opened.exposeFunction('__onboardingHasApiKey', async () => (await welcome.read()).hasApiKey)
await opened.addInitScript(() => {
Object.defineProperty(globalThis, 'dshOnboarding', { value: {
@@ -0,0 +1,25 @@
- dialog "设置":
- text: 设置
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
- list:
- listitem:
- text: DeepSeek
- img "API 密钥已配置"
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY)
- paragraph: 已检测到环境变量(DEEPSEEK_API_KEY)
- group: 自定义设置
- button "取消"
- button "保存"
- button "添加模型提供商"
@@ -0,0 +1,23 @@
- dialog "设置":
- text: 设置
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
- status: 已保存 DeepSeek (deepseek-official)。
- list:
- listitem:
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY)
- paragraph: 未检测到环境变量。请填写 API 密钥,或设置环境变量 DEEPSEEK_API_KEY。
- group: 自定义设置
- button "取消"
- button "保存"
- button "添加模型提供商"
@@ -0,0 +1,26 @@
- dialog "设置":
- text: 设置
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
- list:
- listitem:
- text: DeepSeek
- img "API 密钥已配置"
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY)
- text: fixture-saved-deepseek-key
- button "显示密钥"
- group: 自定义设置
- button "取消"
- button "保存"
- button "添加模型提供商"
@@ -1 +1 @@
- button "立即启用" [disabled]
- status: 正在应用 Computer Use 的更改
@@ -17,7 +17,9 @@
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 留空使用已保存凭据
- /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY)
- text: sk-messages-onboarding
- button "显示密钥"
- group:
- text: 自定义设置 API 地址
- textbox "API 地址":
@@ -17,7 +17,9 @@
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 留空使用已保存凭据
- /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY)
- text: dsh_onboarding_fixture_key
- button "显示密钥"
- group:
- text: 自定义设置 API 地址
- textbox "API 地址":
@@ -17,7 +17,9 @@
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 留空使用已保存凭据
- /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY)
- text: dsh_onboarding_fixture_key
- button "显示密钥"
- group:
- text: 自定义设置 API 地址
- textbox "API 地址":
+5
View File
@@ -0,0 +1,5 @@
- id: llm-deepseek
config:
baseURL: http://127.0.0.1
models:
- id: credential-editor-model
+30 -8
View File
@@ -102,6 +102,13 @@ describe('web e2e: settled Markdown math rendering', () => {
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
const groupRow = page.locator('[role="treeitem"]').first()
await groupRow.waitFor({ timeout: 15_000 })
await groupRow.click()
const sessionRow = page.locator('[role="treeitem"]').nth(1)
await sessionRow.waitFor({ timeout: 10_000 })
await sessionRow.click()
await page.getByText(DONE, { exact: true }).waitFor({ timeout: 15_000 })
}, 120_000)
afterAll(async () => {
@@ -111,14 +118,6 @@ describe('web e2e: settled Markdown math rendering', () => {
it.skipIf(MODE === 'record')('renders the settled reply without KaTeX errors', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-math-rendering'))
const groupRow = page.locator('[role="treeitem"]').first()
await groupRow.waitFor({ timeout: 15_000 })
await groupRow.click()
const sessionRow = page.locator('[role="treeitem"]').nth(1)
await sessionRow.waitFor({ timeout: 10_000 })
await sessionRow.click()
await expect.poll(() => page.getByText(DONE, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
await expect.poll(() => page.locator('.katex').count(), { timeout: 10_000 }).toBe(6)
await expect.poll(() => page.locator('.katex-display').count(), { timeout: 10_000 }).toBe(2)
expect(await page.locator('.katex-error').count()).toBe(0)
@@ -141,4 +140,27 @@ describe('web e2e: settled Markdown math rendering', () => {
expect(tripwire.warnings).toEqual([])
await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md'])
}, 60_000)
it.skipIf(MODE === 'record')('copies a selection with formulas as TeX source', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-math-copy'))
await page.context().grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(page.url()).origin })
const sentinel = 'clipboard-before-copy'
await page.evaluate(value => navigator.clipboard.writeText(value), sentinel)
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(sentinel)
await page.evaluate(() => {
const paragraph = [...document.querySelectorAll('p')].find(item => item.textContent.startsWith('Inline dollar'))!
const visual = paragraph.parentElement!.querySelector('.katex-display .katex-html')!
const range = document.createRange()
range.setStart(paragraph.firstChild!, 0)
range.setEnd(visual.firstChild!, 1)
document.getSelection()!.removeAllRanges()
document.getSelection()!.addRange(range)
})
await page.keyboard.press('ControlOrMeta+C')
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(
'Inline dollar $\\theta$ and backslash $\\frac{1}{5}$.\n\n$$\\frac{\\pi}{4} < \\theta < \\frac{\\pi}{2}$$',
)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
}, 30_000)
})
+5 -4
View File
@@ -2,7 +2,7 @@
// wire — the one add card offers the dormant pi-ai catalog on its third-party
// mode and the create form on its custom-API mode, a blank key saves a
// reference-free profile for provider-native auth, and typing an API key later
// stores it write-only under the derived reference (`MINIMAX_CN_API_KEY`)
// stores it under the derived reference (`MINIMAX_CN_API_KEY`)
// while the settings document records only that reference. Each saved row
// appears after route topology invalidation without presenting liveness as
// provider status. The customized-settings fold writes its curated fields —
@@ -154,8 +154,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
await dialog.getByText('该 API 密钥格式错误,请检查。').waitFor({ timeout: 10_000 })
await expect.poll(async () => save.isEnabled(), { timeout: 10_000 }).toBe(false)
// Clearing it restores submit: an empty field means "keep what is stored",
// never a refusal, or editing any other setting would demand the key.
// An empty field leaves this new profile on native authentication.
await key.fill('')
await expect.poll(async () => save.isEnabled(), { timeout: 10_000 }).toBe(true)
expect(await dialog.getByText('该 API 密钥格式错误,请检查。').count()).toBe(0)
@@ -221,7 +220,9 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-models-customized'))
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click()
await dialog.getByPlaceholder('留空使用已保存凭据', { exact: true }).waitFor({ timeout: 10_000 })
const savedKey = dialog.getByLabel('API 密钥', { exact: true })
await expect.poll(() => savedKey.inputValue(), { timeout: 10_000 }).toBe('sk-e2e-minimax')
expect(await savedKey.getAttribute('type')).toBe('password')
expect(await dialog.textContent()).not.toContain('API 密钥来源:')
expect(await dialog.textContent()).not.toMatch(/oauth/i)
await dialog.getByText('自定义设置').click()
@@ -2,7 +2,6 @@
// credential is absent, both ordered steps share the shipped modal chrome,
// and the inline key write lands in an isolated harness home without a reload
// or model call.
import { randomBytes } from 'node:crypto'
import { assertModelInputLayout } from './model-input-layout.ts'
import { readFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
@@ -33,6 +32,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
let page: Page
let tripwire: ReturnType<typeof watchConsole>
const browserConsole: string[] = []
const secret = 'dsh_onboarding_fixture_key'
beforeAll(async () => {
scaffold = await launchWebScaffold({ deepSeekMissingCredential: true, welcomeNoticePending: true })
@@ -50,7 +50,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
await scaffold?.close()
})
it('stores a key write-only and observes configured state without restarting', async () => {
it('stores a key and loads it masked only in an explicitly opened editor', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-onboarding-deepseek-config'))
const welcome = page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title })
await welcome.waitFor({ timeout: 15_000 })
@@ -86,7 +86,6 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
const initial = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
await compareOrRefreshGolden(MISSING_EXPECTED, initial, MODE)
const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}`
await keyInput.fill(secret)
await credentialStep.getByRole('button', { name: '保存并继续' }).click()
await credentialStep.waitFor({ state: 'detached', timeout: 15_000 })
@@ -101,8 +100,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
const acknowledgedSettings = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(acknowledgedSettings).toContain(`${WELCOME_NOTICE_ACK_FIELD}: ${WELCOME_NOTICE_VERSION}`)
// The ordinary Models surface reuses the refreshed join and exposes the
// configured write-only placeholder without a reload.
// Opening the ordinary Models editor loads the saved key masked.
await openSettings(page, 'zh')
const settings = page.getByRole('dialog', { name: '设置' })
await settings.waitFor({ timeout: 10_000 })
@@ -113,9 +111,10 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
const configuredInput = settings.getByLabel('API 密钥', { exact: true })
await configuredInput.waitFor({ timeout: 10_000 })
await expect.poll(
() => configuredInput.getAttribute('placeholder'),
() => configuredInput.inputValue(),
{ timeout: 10_000 },
).toBe('留空使用已保存凭据')
).toBe(secret)
expect(await configuredInput.getAttribute('type')).toBe('password')
const secondReloadWarnings = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
@@ -255,9 +254,9 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
await settings.getByRole('group', { name: '输入类型 1' }).getByRole('checkbox', { name: '图片' }).check()
await expect.poll(
() => settings.getByLabel('API 密钥', { exact: true }).getAttribute('placeholder'),
() => settings.getByLabel('API 密钥', { exact: true }).inputValue(),
{ timeout: 10_000 },
).toBe('留空使用已保存凭据')
).toBe(secret)
const modelEditor = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
await compareOrRefreshGolden(MODELS_EXPECTED, modelEditor, MODE)
await settings.getByRole('button', { name: '保存', exact: true }).click()
+6 -2
View File
@@ -855,9 +855,12 @@ describe('web e2e: plugin manager', () => {
.toBe(bundles.filter(bundle => bundle.name !== '@deepseek-ai/dsh-experimental-terminal-bundle'
&& bundle.name !== '@deepseek-ai/dsh-experimental-liveshare'
&& bundle.official && (bundle.listedByDefault !== false || bundle.enabled || bundle.installed)).length)
// Computer Use ships with the installation and is listed only on the macOS Hosts it supports.
const cuaSupported = process.platform === 'darwin'
expect(bundles.find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle'))
.toMatchObject({ enabled: false, optional: false, availability: 'missing', listedByDefault: false })
expect(await panel.locator('[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]').count()).toBe(0)
.toMatchObject({ enabled: false, optional: true, availability: 'installation', ...cuaSupported ? {} : { listedByDefault: false } })
expect(await panel.locator('[data-plugin-group="more"] [data-plugin-package="@deepseek-ai/dsh-cua-bundle"]').count())
.toBe(cuaSupported ? 1 : 0)
for (const name of ['@deepseek-ai/dsh-experimental-session-search', '@deepseek-ai/dsh-experimental-ralph-bundle']) {
expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === name))
.toMatchObject({ enabled: false, optional: true, availability: 'installation', listedByDefault: false })
@@ -874,6 +877,7 @@ describe('web e2e: plugin manager', () => {
['@deepseek-ai/dsh-experimental-forge-bundle', 1],
['@deepseek-ai/dsh-personalized-recommendations', 1],
['@deepseek-ai/dsh-experimental-inspector-profile', 1],
...cuaSupported ? [['@deepseek-ai/dsh-cua-bundle', 1]] : [],
['@deepseek-ai/dsh-experimental-tool-worktree', 1],
['@deepseek-ai/dsh-experimental-cot-translation-bundle', 1],
['@deepseek-ai/dsh-experimental-session-titles-bundle', 1],
+9 -7
View File
@@ -694,7 +694,6 @@ async function toggleOptionalBundles(page: Page): Promise<void> {
})
}
return {
cua: bundles.filter(entry => entry.name === '@deepseek-ai/dsh-cua-bundle'),
optional: bundles.filter(entry => entry.optional).map(entry => ({
name: entry.name, enabled: entry.enabled, availability: entry.availability, error: entry.error ?? null,
title: typeof entry.meta?.title, icon: typeof entry.meta?.icon, metaError: entry.meta?.error ?? null,
@@ -706,16 +705,19 @@ async function toggleOptionalBundles(page: Page): Promise<void> {
})
expect(result.optional.map(entry => entry.name).sort()).toEqual([...OPTIONAL_BUNDLES].sort())
expect(result.optional.filter(entry => entry.enabled || entry.availability !== 'installation')).toEqual([])
expect(result.optional.filter(entry => entry.error !== null)).toEqual([])
expect(result.cua).toHaveLength(1)
expect(result.cua[0]).toMatchObject({ name: '@deepseek-ai/dsh-cua-bundle', optional: false,
availability: 'missing', error: { code: 'unsupported-platform' } })
expect(result.optional.filter(entry => entry.error !== null)).toEqual([
expect.objectContaining({ name: '@deepseek-ai/dsh-cua-bundle', error: { code: 'unsupported-platform' } }),
])
// Metadata resolves through the Worker's Node internal modules: every optional bundle shows its title and icon.
expect(result.optional.filter(entry => entry.metaError !== null || entry.title !== 'object' || entry.icon !== 'string')).toEqual([])
expect(result.inventoryErrors).toEqual([])
console.info(`preview boot: optional bundle toggles ${JSON.stringify(result.toggles.map(({ name, enable, disable, error }) => ({ name, enable, disable, error })))}`)
expect(result.toggles.find(toggle => toggle.name === '@deepseek-ai/dsh-cua-bundle')).toBeUndefined()
const supported = result.toggles
expect(result.toggles.find(toggle => toggle.name === '@deepseek-ai/dsh-cua-bundle')).toMatchObject({
enable: 'failed', disable: 'applied', error: { code: 'unsupported-platform' },
changed: 0, inactive: [], restored: true,
})
// Computer Use refuses enablement on this non-macOS worker Host, as asserted above, so the generic check omits it.
const supported = result.toggles.filter(toggle => toggle.name !== '@deepseek-ai/dsh-cua-bundle')
expect(supported.filter(toggle => toggle.enable !== 'applied' || toggle.disable !== 'applied')
.map(({ name, enable, disable }) => ({ name, enable, disable }))).toEqual([])
// Each bundle changes Loader rows, every enabled row it changes runs, and switching it off restores the prior rows.
+15 -2
View File
@@ -606,6 +606,7 @@ describe('dsh web keyless CLI smoke', () => {
it.each(['native', 'ptc'] as const)('selects the %s executor through profile overlays and ignores the retired environment selector', async (mode) => {
requireDist()
const workspace = mkdtempSync(join(tmpdir(), 'dsh-web-ptc-'))
const promptMarker = `WEB_EXECUTOR_${mode}_${randomUUID()}`
interface PtcModeProviderRequest {
system?: string
@@ -621,7 +622,11 @@ describe('dsh web keyless CLI smoke', () => {
request.setEncoding('utf8')
request.on('data', (chunk: string) => { body += chunk })
request.on('end', () => {
resolveProviderRequest(JSON.parse(body) as PtcModeProviderRequest)
const parsed = JSON.parse(body) as PtcModeProviderRequest
const messages = JSON.stringify(parsed.messages ?? [])
if (messages.includes(promptMarker) && !messages.includes(TITLE_PROMPT_MARKER)) {
resolveProviderRequest(parsed)
}
response.writeHead(200, { 'content-type': 'text/event-stream' })
response.end(messagesResponse('done'))
})
@@ -653,11 +658,19 @@ describe('dsh web keyless CLI smoke', () => {
try {
const baseUrl = await waitForReadyLine(child)
const created = await remoteRpc<{ sessionId: string }>(baseUrl, 'session/create', { request: {} })
// Title requests share the provider; exercise auxiliary-first arrival explicitly.
await fetch(`http://127.0.0.1:${address.port}`, {
method: 'POST',
body: JSON.stringify({ messages: [{
role: 'user',
content: [{ type: 'text', text: `${TITLE_PROMPT_MARKER}\n${JSON.stringify([promptMarker])}` }],
}] }),
}).then(response => response.text())
await remoteRpc<{ accepted: true }>(baseUrl, 'session/prompt', { request: {
requestId: randomUUID(),
sessionId: created.sessionId,
mode: 'queue',
content: [{ type: 'text', text: 'go' }],
content: [{ type: 'text', text: promptMarker }],
} })
const captured = await Promise.race([
providerRequest,
+1
View File
@@ -23,6 +23,7 @@
// this client-registered project must not also hold them (one program
// cannot see both sides of the cordis Context merges).
"exclude": [
"tests/credential-editor.e2e.ts",
"tests/sidebar-drawer.e2e.ts",
"tests/creation-recommendations.e2e.ts",
"tests/plugin-recommendations.e2e.ts",
+2 -2
View File
@@ -6,5 +6,5 @@
en: 41d772192075e133
zh: 5ef3da69b4de1d8a
/capability-seams-and-core-services:
en: 127bf10f09f4f2bc
zh: 0e3e9dfdd9b9a74e
en: 26b1c59e0bdb025a
zh: 009b62cf5399f43a
+4 -4
View File
@@ -211,7 +211,7 @@ flowchart LR
pkg_base["base"]
pkg_sdk_minimal["sdk-minimal"]
pkg_mcp_manager["mcp-manager"]
svc_mcpServers["ctx.mcpServers<br/>Settings-driven MCP server fleet"]
svc_mcpManager["ctx.mcpManager<br/>Settings-driven MCP server fleet"]
pkg_client_ui_mcp_account["client-ui-mcp-account"]
svc_mcpAccounts["ctx.mcpAccounts<br/>MCP connector accounts on the Plugins page"]
pkg_schedule["schedule"]
@@ -407,7 +407,7 @@ flowchart LR
pkg_lsp --> svc_lsp
pkg_lsp_stdio --> svc_lsp
pkg_mcp_client --> svc_mcpResources
pkg_mcp_manager --> svc_mcpServers
pkg_mcp_manager --> svc_mcpManager
pkg_mcp_resources --> svc_mcpResources
pkg_message_feedback --> svc_messageFeedback
pkg_office_to_pdf --> svc_officeToPdf
@@ -704,7 +704,7 @@ flowchart LR
| `ctx.configEditor` | `core` | [`config-editor`](../packages/boot/config-editor) | - | [`settings`](../packages/settings/settings), [`agent-default-model`](../packages/core/agent-default-model) | - | Persists profile config patches under the application file lock and HMR queue, then reconciles Loader entries. |
| `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. |
| `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | Owns the default-off settings namespace that Agent-scoped delegation tools sample when composing a new top-level Session. |
| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage. |
| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free metadata, writes, and owner-only reads of stored keys. |
| `ctx.deepseekAccount` | `seam` | [`deepseek-account`](../packages/credentials/deepseek-account) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | [`api-account-controller`](../packages/api/account-controller), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The Host owns browser authorization and local credentials; UI consumers receive state without tokens. |
| `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Flows are registered by the plugin that knows how to obtain one credential and keyed by the record they write; the seam owns the conversation and the one-attempt-per-key lifecycle, never the protocol. |
| `ctx.productAnalytics` | `service` | [`client-product-analytics`](../packages/client/product-analytics) | - | - | - | Accepts selected Desktop events, enriches available login identity, and observes live compaction under the live Host collection policy. |
@@ -732,7 +732,7 @@ flowchart LR
| `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/acp/acp), [`subagent`](../packages/subagent/subagent) | - | Owns live Agent handles, the create/resume factory seam, and process-local initiator propagation. |
| `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | Reads the default ModelSelection from volatile Config and saves selections through the profile editor. |
| `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`base`](../packages/bundle/base), [`sdk-minimal`](../packages/bundle/sdk-minimal) | - | The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package. |
| `ctx.mcpServers` | `core` | [`mcp-manager`](../packages/mcp/mcp-manager) | - | - | - | Reconciles mcp-client instances against its volatile servers configuration, aggregates their connection statuses, and serves restart and probe to management surfaces. |
| `ctx.mcpManager` | `core` | [`mcp-manager`](../packages/mcp/mcp-manager) | - | - | - | Reconciles mcp-client instances against its volatile servers configuration, aggregates their connection statuses, and serves restart and probe to management surfaces. |
| `ctx.mcpAccounts` | `service` | [`client-ui-mcp-account`](../packages/client/ui-mcp-account) | - | - | - | Holds the accounts MCP connector plugins register and serves them, with the manager's view of each server, to the Plugins page through one Remote; authorization runs through the manager. |
| `ctx.schedule` | `core` | [`schedule`](../packages/schedule/schedule) | - | - | - | Stores tasks independently of Session activation and queues due messages in each task's target Session. |
| `ctx.goals` | `core` | [`goal`](../packages/goal/goal) | - | - | - | Folds revisioned objective state from the session log and keeps live continuation activation process-local. |
+4 -4
View File
@@ -213,7 +213,7 @@ flowchart LR
pkg_base["base"]
pkg_sdk_minimal["sdk-minimal"]
pkg_mcp_manager["mcp-manager"]
svc_mcpServers["ctx.mcpServers<br/>Settings-driven MCP server fleet"]
svc_mcpManager["ctx.mcpManager<br/>Settings-driven MCP server fleet"]
pkg_client_ui_mcp_account["client-ui-mcp-account"]
svc_mcpAccounts["ctx.mcpAccounts<br/>MCP connector accounts on the Plugins page"]
pkg_schedule["schedule"]
@@ -409,7 +409,7 @@ flowchart LR
pkg_lsp --> svc_lsp
pkg_lsp_stdio --> svc_lsp
pkg_mcp_client --> svc_mcpResources
pkg_mcp_manager --> svc_mcpServers
pkg_mcp_manager --> svc_mcpManager
pkg_mcp_resources --> svc_mcpResources
pkg_message_feedback --> svc_messageFeedback
pkg_office_to_pdf --> svc_officeToPdf
@@ -706,7 +706,7 @@ flowchart LR
| `ctx.configEditor` | `core` | [`config-editor`](../packages/boot/config-editor) | - | [`settings`](../packages/settings/settings), [`agent-default-model`](../packages/core/agent-default-model) | - | Persists profile config patches under the application file lock and HMR queue, then reconciles Loader entries. |
| `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. |
| `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | 拥有默认关闭的设置命名空间;Agent 作用域的委派工具会在组合新顶层 Session 时读取它。 |
| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | 配置携带对机密信息的引用;提供方拥有实际值。消费方按操作解析,因此轮换后的凭据会在紧接着的下一次请求中生效;settings controller 提供不含实际值的视图和只写存储。 |
| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | 配置携带对机密信息的引用;提供方拥有实际值。消费方按操作解析,因此轮换后的凭据会在紧接着的下一次请求中生效;settings controller 提供不含实际值的元数据和写入操作,并仅向所有者读取已保存密钥。 |
| `ctx.deepseekAccount` | `seam` | [`deepseek-account`](../packages/credentials/deepseek-account) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | [`api-account-controller`](../packages/api/account-controller), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | Host 负责浏览器授权和本地凭证;UI 使用方只接收不含 token 的状态。 |
| `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | flow 由知道如何取得某份凭据的插件注册,并以其写入的记录为键;seam 拥有这段对话与"每个键同时只跑一次尝试"的生命周期,而非协议本身。 |
| `ctx.productAnalytics` | `service` | [`client-product-analytics`](../packages/client/product-analytics) | - | - | - | 根据 Host 动态采集策略接收指定桌面事件、补充可用登录身份并监听实时压缩。 |
@@ -734,7 +734,7 @@ flowchart LR
| `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/acp/acp), [`subagent`](../packages/subagent/subagent) | - | 拥有实时 Agent 句柄、创建/恢复工厂 seam,以及进程本地的发起方传播。 |
| `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | Reads the default ModelSelection from volatile Config and saves selections through the profile editor. |
| `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`base`](../packages/bundle/base), [`sdk-minimal`](../packages/bundle/sdk-minimal) | - | 唯一的具体循环插件;扩展包依赖 dsh-agent 的事件和服务,而不依赖此包。 |
| `ctx.mcpServers` | `core` | [`mcp-manager`](../packages/mcp/mcp-manager) | - | - | - | 依据自身 volatile servers 配置对账 mcp-client 实例,聚合它们的连接状态,并向管理界面提供 restart 与 probe。 |
| `ctx.mcpManager` | `core` | [`mcp-manager`](../packages/mcp/mcp-manager) | - | - | - | 依据自身 volatile servers 配置对账 mcp-client 实例,聚合它们的连接状态,并向管理界面提供 restart 与 probe。 |
| `ctx.mcpAccounts` | `service` | [`client-ui-mcp-account`](../packages/client/ui-mcp-account) | - | - | - | 保存 MCP 连接器插件注册的账号,并通过一个 Remote 把账号连同管理器对各服务器的视图提供给插件页;授权经由管理器完成。 |
| `ctx.schedule` | `core` | [`schedule`](../packages/schedule/schedule) | - | - | - | 独立于 Session 的加载状态存储任务,并将到期消息排入每个任务的目标 Session。 |
| `ctx.goals` | `core` | [`goal`](../packages/goal/goal) | - | - | - | 从会话日志折叠带修订版本的目标状态,并将实时延续激活保留在进程本地。 |
+17 -3
View File
@@ -1110,10 +1110,24 @@ export interface Config {
- `source`: [`packages/experimental/cua-macos/src/index.ts:18`](../packages/experimental/cua-macos/src/index.ts)
```ts config-catalog
/** Native preparation, operation bounds, and profile-local application grants. */
/** Native preparation, source-build signing, operation bounds, and profile-local application grants. */
export interface Config extends CuaConfig {
/** Interval in milliseconds between permission and position checks while the native guide is open. */
permissionPollIntervalMs: number
/**
* Source-build signing: `ad-hoc` (default) binds grants to the code hash;
* an object selects an existing certificate in an explicitly configured keychain.
* Installed packages and `helperPath` keep their own signature.
*/
sourceSigning: SourceSigning
}
/** Signature selected for source builds; certificates are created and unlocked by the developer. */
export type SourceSigning = 'ad-hoc' | {
/** Existing codesign certificate name or SHA-1 fingerprint, without a leading dash or whitespace. */
identity: string
/** Absolute keychain path. */
keychain: string
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-cua-macos -->
@@ -4400,7 +4414,7 @@ export interface Config {
- `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections`
- `refs`: [`AgentOptions`](subsystems/core.md)
- `source`: [`packages/subagent/tool-subagent/src/index.ts:46`](../packages/subagent/tool-subagent/src/index.ts)
- `source`: [`packages/subagent/tool-subagent/src/index.ts:45`](../packages/subagent/tool-subagent/src/index.ts)
```ts config-catalog
/** Config: which registered provider this tool delegates to, plus child defaults. */
@@ -4964,7 +4978,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
| `@deepseek-ai/dsh-client-ui-input-trigger` | — | [`packages/client/ui-input-trigger/src/index.ts`](../packages/client/ui-input-trigger/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-jobs` | — | [`packages/client/ui-jobs/src/index.ts`](../packages/client/ui-jobs/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-layout` | — | [`packages/client/ui-layout/src/index.ts`](../packages/client/ui-layout/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-mcp-account` | `mcpServers` | [`packages/client/ui-mcp-account/src/index.ts`](../packages/client/ui-mcp-account/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-mcp-account` | `mcpManager` | [`packages/client/ui-mcp-account/src/index.ts`](../packages/client/ui-mcp-account/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-message-feedback` | — | [`packages/client/ui-message-feedback/src/index.ts`](../packages/client/ui-message-feedback/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-model-selection` | — | [`packages/client/ui-model-selection/src/index.ts`](../packages/client/ui-model-selection/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-open-in-app` | — | [`packages/client/ui-open-in-app/src/index.ts`](../packages/client/ui-open-in-app/src/index.ts) |
+17 -3
View File
@@ -1112,10 +1112,24 @@ export interface Config {
- `source`: [`packages/experimental/cua-macos/src/index.ts:18`](../packages/experimental/cua-macos/src/index.ts)
```ts config-catalog
/** Native preparation, operation bounds, and profile-local application grants. */
/** Native preparation, source-build signing, operation bounds, and profile-local application grants. */
export interface Config extends CuaConfig {
/** Interval in milliseconds between permission and position checks while the native guide is open. */
permissionPollIntervalMs: number
/**
* Source-build signing: `ad-hoc` (default) binds grants to the code hash;
* an object selects an existing certificate in an explicitly configured keychain.
* Installed packages and `helperPath` keep their own signature.
*/
sourceSigning: SourceSigning
}
/** Signature selected for source builds; certificates are created and unlocked by the developer. */
export type SourceSigning = 'ad-hoc' | {
/** Existing codesign certificate name or SHA-1 fingerprint, without a leading dash or whitespace. */
identity: string
/** Absolute keychain path. */
keychain: string
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-cua-macos -->
@@ -4402,7 +4416,7 @@ export interface Config {
- `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections`
- `refs`: [`AgentOptions`](subsystems/core.zh.md)
- `source`: [`packages/subagent/tool-subagent/src/index.ts:46`](../packages/subagent/tool-subagent/src/index.ts)
- `source`: [`packages/subagent/tool-subagent/src/index.ts:45`](../packages/subagent/tool-subagent/src/index.ts)
```ts config-catalog
/** Config: which registered provider this tool delegates to, plus child defaults. */
@@ -4966,7 +4980,7 @@ export interface Config {
| `@deepseek-ai/dsh-client-ui-input-trigger` | — | [`packages/client/ui-input-trigger/src/index.ts`](../packages/client/ui-input-trigger/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-jobs` | — | [`packages/client/ui-jobs/src/index.ts`](../packages/client/ui-jobs/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-layout` | — | [`packages/client/ui-layout/src/index.ts`](../packages/client/ui-layout/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-mcp-account` | `mcpServers` | [`packages/client/ui-mcp-account/src/index.ts`](../packages/client/ui-mcp-account/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-mcp-account` | `mcpManager` | [`packages/client/ui-mcp-account/src/index.ts`](../packages/client/ui-mcp-account/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-message-feedback` | — | [`packages/client/ui-message-feedback/src/index.ts`](../packages/client/ui-message-feedback/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-model-selection` | — | [`packages/client/ui-model-selection/src/index.ts`](../packages/client/ui-model-selection/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-open-in-app` | — | [`packages/client/ui-open-in-app/src/index.ts`](../packages/client/ui-open-in-app/src/index.ts) |
+2 -2
View File
@@ -9,8 +9,8 @@
en: 0083032b9d19467d
zh: 15d7a7520bac094e
/user-credentials/resolution:
en: baaab4bca76bea6b
zh: 54ccdc03ffd44f63
en: 0583aeab49d80a4b
zh: 1ffd60d7e79f67cf
/user-credentials/description:
en: f7b09588c0f34952
zh: 1b93d673c5bf6a80
+19 -3
View File
@@ -20,6 +20,8 @@ type CredentialRef = Branded<'CredentialRef'>
`resolve(ref)` returns the value with the provider-defined source layer that supplied it, or `undefined` while unconfigured. Consumers re-resolve at each operation and never cache across operations — that per-operation read is the hot-update mechanism.
`readStored(ref)` returns only the provider-managed value for editing, or `undefined` when none is stored. It never reads environment fallbacks. The Remote editor operation restricts this read to the owner.
```ts type-equiv
/** One resolved credential value and the source layer that supplied it. */
interface ResolvedCredential {
@@ -152,6 +154,13 @@ A CredentialKey answers "what credential does this plugin hold for this id". Not
*/
abstract resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined>
/**
* Read the provider-managed value without consulting environment fallbacks.
* @param ref - the reference to read.
* @returns the stored secret, or undefined when no non-empty value is stored.
*/
abstract readStored(ref: CredentialRef): Promise<string | undefined>
/**
* Describe one reference for configuration surfaces without exposing the
* value.
@@ -228,7 +237,7 @@ Source: [`packages/credentials/credentials/src/index.ts`](../../packages/credent
### `ctx.credentialsController` — `CredentialsController`
Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Secret values cross in one direction only — no method here returns one.
Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Metadata reads exclude secrets; readStored returns only a provider-managed value for an explicitly opened editor.
```ts cordis-catalog
/**
@@ -243,8 +252,15 @@ Host service backing the generated `ctx.remote.credentials` namespace. It carrie
@Remote async describe(refs: string[]): Promise<Record<string, CredentialInfo>>
/**
* Store one value from a configuration surface. The value crosses the wire in
* this direction only: no read path returns it.
* Read one stored value for a credential editor, excluding environment fallbacks.
* @param ref - reference name to read.
* @returns the stored secret, or undefined when the provider stores none.
* @throws RemoteError for a non-owner Remote caller, an invalid reference, or an absent provider.
*/
@Remote async readStored(ref: string): Promise<string | undefined>
/**
* Store one value from a configuration surface.
* @param ref - reference name to store under.
* @param value - the non-empty secret value.
* @throws RemoteError when the request is invalid, no provider is mounted, or the provider refuses the write.
+19 -3
View File
@@ -20,6 +20,8 @@ type CredentialRef = Branded<'CredentialRef'>
`resolve(ref)` 返回值及提供该值的来源层(由提供方定义);未配置期间返回 `undefined`。消费方在每个操作中重新解析,绝不跨操作缓存——这种按操作进行的读取正是热更新机制。
`readStored(ref)` 仅返回用于编辑的提供方托管值;未存储时返回 `undefined`。它不读取环境后备值。编辑器的 Remote 操作仅允许所有者执行此读取。
```ts type-equiv
/** One resolved credential value and the source layer that supplied it. */
interface ResolvedCredential {
@@ -152,6 +154,13 @@ A CredentialKey answers "what credential does this plugin hold for this id". Not
*/
abstract resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined>
/**
* Read the provider-managed value without consulting environment fallbacks.
* @param ref - the reference to read.
* @returns the stored secret, or undefined when no non-empty value is stored.
*/
abstract readStored(ref: CredentialRef): Promise<string | undefined>
/**
* Describe one reference for configuration surfaces without exposing the
* value.
@@ -228,7 +237,7 @@ Source: [`packages/credentials/credentials/src/index.ts`](../../packages/credent
### `ctx.credentialsController` — `CredentialsController`
Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Secret values cross in one direction only — no method here returns one.
Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Metadata reads exclude secrets; readStored returns only a provider-managed value for an explicitly opened editor.
```ts cordis-catalog
/**
@@ -243,8 +252,15 @@ Host service backing the generated `ctx.remote.credentials` namespace. It carrie
@Remote async describe(refs: string[]): Promise<Record<string, CredentialInfo>>
/**
* Store one value from a configuration surface. The value crosses the wire in
* this direction only: no read path returns it.
* Read one stored value for a credential editor, excluding environment fallbacks.
* @param ref - reference name to read.
* @returns the stored secret, or undefined when the provider stores none.
* @throws RemoteError for a non-owner Remote caller, an invalid reference, or an absent provider.
*/
@Remote async readStored(ref: string): Promise<string | undefined>
/**
* Store one value from a configuration surface.
* @param ref - reference name to store under.
* @param value - the non-empty secret value.
* @throws RemoteError when the request is invalid, no provider is mounted, or the provider refuses the write.
+2 -2
View File
@@ -15,8 +15,8 @@
en: 4a164aa382a55d28
zh: de7794f817f2cf32
/mcp/responsibilities-and-scope:
en: 1cd19cd40c8b010c
zh: 37c9cdbc9e3edba0
en: 9aa0df86a35e1a0e
zh: 58f5382ef3f11f06
/mcp/protocol-and-results:
en: 46e9b914f016b636
zh: e1e9ee92a22f2562
+21 -21
View File
@@ -40,7 +40,7 @@ Protocol negotiation follows the SDK's supported revisions; there is no product
<a id="responsibilities-and-scope"></a>
## Responsibilities and scope
The client is a per-server connection plugin and a consumer of the harness tool registry. It does not publish a shared `ctx.mcp` service; the manager publishes `ctx.mcpServers` for the Host-global servers it mounts. The external server implements MCP operations; the SDK owns protocol exchange; the client adapts discovered tools to harness execution.
The client is a per-server connection plugin and a consumer of the harness tool registry. It does not publish a shared `ctx.mcp` service; the manager publishes `ctx.mcpManager` for the Host-global servers it mounts. The external server implements MCP operations; the SDK owns protocol exchange; the client adapts discovered tools to harness execution.
`mcp-resources` owns the shared resource tools and selects providers in the caller's scope. Each MCP client supplies resource operations through its own connection. The first provider in a scope enables the local shared tools, and removing the last removes them; inherited providers remain visible. The service owns these tool registrations independently of any one client. Connection failures do not remove shared resource tools while a visible client entry remains active.
@@ -122,27 +122,9 @@ MCP prompt templates, human-input elicitation, task-based execution, and resourc
Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md).
<a id="ctxmcpresources--mcpresourceruntime"></a>
<a id="ctxmcpmanager--mcpservermanager"></a>
### `ctx.mcpResources` — `McpResourceRuntime`
Scoped resource access plus three tools shared by configured MCP servers.
```ts cordis-catalog
/**
* Register one server and expose resource tools while that scope has providers.
* @param server - configured server name, unique in this scope.
* @param provider - connection-owned resource operations.
* @returns the effect disposer for this exact registration.
*/
register(server: string, provider: McpResourceProvider): () => void
```
Source: [`packages/mcp/mcp-resources/src/index.ts`](../../packages/mcp/mcp-resources/src/index.ts)
<a id="ctxmcpservers--mcpservermanager"></a>
### `ctx.mcpServers` — `McpServerManager`
### `ctx.mcpManager` — `McpServerManager`
The manager service. Reconciliation and `restart` serialize instance replacement. Probes run independently and are cancelled before replacement or disposal waits for their cleanup.
@@ -226,6 +208,24 @@ async probe(name: string, options?: McpProbeOptions): Promise<McpProbeResult>
Source: [`packages/mcp/mcp-manager/src/index.ts`](../../packages/mcp/mcp-manager/src/index.ts)
<a id="ctxmcpresources--mcpresourceruntime"></a>
### `ctx.mcpResources` — `McpResourceRuntime`
Scoped resource access plus three tools shared by configured MCP servers.
```ts cordis-catalog
/**
* Register one server and expose resource tools while that scope has providers.
* @param server - configured server name, unique in this scope.
* @param provider - connection-owned resource operations.
* @returns the effect disposer for this exact registration.
*/
register(server: string, provider: McpResourceProvider): () => void
```
Source: [`packages/mcp/mcp-resources/src/index.ts`](../../packages/mcp/mcp-resources/src/index.ts)
<a id="mcp-manager-events"></a>
### `mcp-manager/*` events
+21 -21
View File
@@ -40,7 +40,7 @@ Web 与 Desktop profile 还统一挂载一次 [MCP 服务器管理器](../../pac
<a id="responsibilities-and-scope"></a>
## 职责与作用域
客户端是每服务器一个的连接插件,也是 Harness 工具注册表的消费者。它不发布共享的 `ctx.mcp` 服务;管理器为其挂载的宿主全局服务器发布 `ctx.mcpServers`。外部服务器实现 MCP 操作;SDK 拥有协议交换;客户端将发现的工具适配到 Harness 执行过程。
客户端是每服务器一个的连接插件,也是 Harness 工具注册表的消费者。它不发布共享的 `ctx.mcp` 服务;管理器为其挂载的宿主全局服务器发布 `ctx.mcpManager`。外部服务器实现 MCP 操作;SDK 拥有协议交换;客户端将发现的工具适配到 Harness 执行过程。
`mcp-resources` 拥有共享资源工具,并在调用方作用域中选择提供方。每个 MCP 客户端通过自己的连接提供资源操作。作用域中的首个提供方启用本地共享工具,移除最后一个提供方时移除这些工具;继承的提供方仍然可见。服务独立于任何单一客户端拥有这些工具注册。只要可见的客户端条目保持激活,连接失败就不会移除共享资源工具。
@@ -122,27 +122,9 @@ interface McpResourceProvider {
Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.zh.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md).
<a id="ctxmcpresources--mcpresourceruntime"></a>
<a id="ctxmcpmanager--mcpservermanager"></a>
### `ctx.mcpResources` — `McpResourceRuntime`
Scoped resource access plus three tools shared by configured MCP servers.
```ts cordis-catalog
/**
* Register one server and expose resource tools while that scope has providers.
* @param server - configured server name, unique in this scope.
* @param provider - connection-owned resource operations.
* @returns the effect disposer for this exact registration.
*/
register(server: string, provider: McpResourceProvider): () => void
```
Source: [`packages/mcp/mcp-resources/src/index.ts`](../../packages/mcp/mcp-resources/src/index.ts)
<a id="ctxmcpservers--mcpservermanager"></a>
### `ctx.mcpServers` — `McpServerManager`
### `ctx.mcpManager` — `McpServerManager`
The manager service. Reconciliation and `restart` serialize instance replacement. Probes run independently and are cancelled before replacement or disposal waits for their cleanup.
@@ -226,6 +208,24 @@ async probe(name: string, options?: McpProbeOptions): Promise<McpProbeResult>
Source: [`packages/mcp/mcp-manager/src/index.ts`](../../packages/mcp/mcp-manager/src/index.ts)
<a id="ctxmcpresources--mcpresourceruntime"></a>
### `ctx.mcpResources` — `McpResourceRuntime`
Scoped resource access plus three tools shared by configured MCP servers.
```ts cordis-catalog
/**
* Register one server and expose resource tools while that scope has providers.
* @param server - configured server name, unique in this scope.
* @param provider - connection-owned resource operations.
* @returns the effect disposer for this exact registration.
*/
register(server: string, provider: McpResourceProvider): () => void
```
Source: [`packages/mcp/mcp-resources/src/index.ts`](../../packages/mcp/mcp-resources/src/index.ts)
<a id="mcp-manager-events"></a>
### `mcp-manager/*` events
+2 -2
View File
@@ -246,8 +246,8 @@
en: 841abe0dd5913ea7
zh: 841abe0dd5913ea7
/tool-schema-catalog/deepseek-ai-dsh-tool-subagent/list-subagent-models:
en: 207228068bc61885
zh: 36e9344ee1af8869
en: 0e21650bbe8c71c7
zh: fe4033efb38d51a3
/tool-schema-catalog/deepseek-ai-dsh-tool-subagent/subagent:
en: 430672da3c1a6ca6
zh: bd3a9ab4089f9dbb
+1 -1
View File
@@ -2039,7 +2039,7 @@ The subagent_oar tool selects among configured aliases for external providers. T
### `list_subagent_models`
Inspect subagent models without changing the current Agent. No arguments: providers; `provider`: allowed models; `provider` + `model`: that model and its reasoning efforts. Inspect options here before selecting a child provider and model; use returned ids for delegation.
Inspect the routes available for explicit subagent model selection. No arguments: authorized providers. `provider`: that provider's authorized models. `provider` + `model`: that model and its reasoning efforts. Query when choosing an explicit child route or reasoning effort. Omit optional fields rather than sending empty strings.
```json
{
+1 -1
View File
@@ -2045,7 +2045,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录
### `list_subagent_models`
查询 subagent 可用的模型,不更改当前 Agent。无参数:提供方;`provider`:允许的模型;`provider` + `model`:该模型及其推理强度。选择子级提供方和模型前先在此查询选项,再将返回的 id 用于委派。
查询允许为 subagent 显式选择的路由。无参数:提供方;`provider`:允许的模型;`provider` + `model`:该模型及其推理强度。选择子级提供方和模型前先在此查询选项,再将返回的 id 用于委派。
```json
{
@@ -12,5 +12,5 @@
en: 1552866718133b10
zh: 1c760c5c2d5cfc0b
/authorize-the-computer-use-helper/migration:
en: a79e5995415ff456
zh: 6f818a092e53af2c
en: 2a28385e24468734
zh: 725c1856a604bc0c
@@ -13,7 +13,7 @@ macOS Computer Use runs as `DSH Computer Use.app`, launched through LaunchServic
## Migration
1. Computer Use now installs on demand. In **Plugins → Add plugin**, install `@deepseek-ai/dsh-cua-bundle` and enable it; profiles that previously selected the shipped copy need this installation. Restart DSH if requested. In the Computer Use plugin page, grant Accessibility and Screen Recording access to `DSH Computer Use.app` when macOS requests it.
1. Restart DSH after upgrading the Computer Use package. In the Computer Use plugin page, grant Accessibility and Screen Recording access to `DSH Computer Use.app` when macOS requests it.
2. Remove an obsolete `helperPath` override or `DSH_CUA_HELPER` value to use automatic preparation. For a custom build, point it to the executable at `DSH Computer Use.app/Contents/MacOS/dsh-cua-native` inside the complete application bundle.
3. Confirm that the permission page identifies `DSH Computer Use.app` and both permissions are allowed before resuming native application tasks. Target-application consent remains required.
4. If a terminal or Desktop launcher was granted these permissions only for Computer Use, revoke those obsolete grants in System Settings. Authorizing the helper does not revoke other applications’ existing permissions; programs the model runs still follow their launcher’s system permissions and the DSH sandbox policy.
@@ -13,7 +13,7 @@ macOS Computer Use 通过 LaunchServices 以 `DSH Computer Use.app` 运行。终
## 迁移
1. Computer Use 改为按需安装。在“插件 → 添加插件”中安装 `@deepseek-ai/dsh-cua-bundle` 并启用;此前选中过内置副本的 profile 也需完成这次安装。按提示重启 DSH。在 Computer Use 插件页按 macOS 提示,给 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。
1. 升级 Computer Use 包后重启 DSH。在 Computer Use 插件页按 macOS 提示,给 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。
2. 删除过时的 `helperPath` 覆盖配置或 `DSH_CUA_HELPER` 值,使用自动准备。使用自定义构建时,将其指向完整应用包内的 `DSH Computer Use.app/Contents/MacOS/dsh-cua-native` 可执行文件。
3. 恢复原生应用任务前,确认权限页显示 `DSH Computer Use.app`,且两项权限均已允许。具体目标应用仍需另行许可。
4. 若终端或 Desktop 启动器的这两项权限只用于 Computer Use,可在系统设置中撤销这些旧授权。给 helper 授权不会撤销其他应用已有的权限;模型运行的程序仍遵循启动器的系统权限和 DSH 沙箱策略。
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.md
/:
en: 2f1907963c732ea8
zh: e25494c07150f6b9
/saved-api-keys-in-provider-editors:
en: 63376a595a0e6dae
zh: 2709df13410087e2
/saved-api-keys-in-provider-editors/change:
en: 463718dbe83f900d
zh: d2e55dfebf8a4b9e
/saved-api-keys-in-provider-editors/migration:
en: 19c94ae9626773b1
zh: 1098744f47162c43
@@ -0,0 +1,19 @@
---
kind: upgrade-guide
description: "Saved API keys appear in masked editor fields, and clearing a saved key removes its override."
---
# Saved API keys in provider editors
English | [中文](guide.zh.md)
## Change
Provider editors show stored API keys as masked values instead of empty fields. Applying an empty field removes a previously loaded key and restores environment authentication. Cancel preserves the stored key. Environment values are never loaded into the editor.
Credential providers implement `readStored(ref): Promise<string | undefined>` to return only the managed value, without environment fallbacks. The owner-only `credentials.readStored` Remote method supplies this value to an opened editor; general metadata reads remain redacted.
## Migration
1. Keep the loaded value to retain a saved key, replace it to rotate the key, or clear it and apply to use environment authentication.
2. Implement `readStored` in custom `CredentialProvider` subclasses; return `undefined` when no non-empty value is stored.
3. Reopen the DeepSeek editor to confirm the saved key appears masked. After clearing and applying, confirm the field is empty and offers environment authentication.
@@ -0,0 +1,19 @@
---
kind: upgrade-guide
description: "已保存的 API 密钥显示为编辑器中的掩码值,清空已保存密钥会删除其覆盖。"
---
# 提供商编辑器中的已保存 API 密钥
[English](guide.md) | 中文
## 变更
提供商编辑器以掩码值显示已保存的 API 密钥,不再显示空字段。应用空字段会删除之前加载的密钥并恢复环境认证。「取消」保留已保存密钥。环境变量值从不加载到编辑器。
凭据提供方实现 `readStored(ref): Promise<string | undefined>`,仅返回托管值,不使用环境后备。仅允许所有者调用的 `credentials.readStored` Remote 方法向已打开的编辑器提供此值;普通元数据读取仍保持脱敏。
## 迁移
1. 保留加载的值即可保留已保存密钥,替换它可轮换密钥,清空并应用则使用环境认证。
2. 为自定义 `CredentialProvider` 子类实现 `readStored`;未存储非空值时返回 `undefined`。
3. 重新打开 DeepSeek 编辑器,确认已保存密钥显示为掩码。清空并应用后,确认字段为空且提示使用环境认证。
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md
/:
en: 2f745e146345238c
zh: 9b41a7625ae45170
/source-built-computer-use-helper-identity:
en: 72a8ea364f7427fa
zh: 9e7ed2e00425bddb
/source-built-computer-use-helper-identity/change:
en: c1aa84364896b994
zh: a4559c563d995b2b
/source-built-computer-use-helper-identity/migration:
en: a86e330ab60ef800
zh: ce32e1959ca707fc
@@ -0,0 +1,19 @@
---
kind: upgrade-guide
description: "Source-built Computer Use helpers use a separate development bundle identifier and need one new macOS permission grant."
---
# Source-built Computer Use helper identity
English | [中文](guide.zh.md)
## Change
Source checkouts previously built `DSH Computer Use.app` with the release bundle identifier `com.deepseek.harness.computer-use` and an ad-hoc signature. They now build `DSH Computer Use Dev.app` with bundle identifier `com.deepseek.harness.computer-use.dev`. Accessibility and Screen Recording grants for the old entry do not apply to it. Desktop and npm installations are unchanged. Source builds still default to ad-hoc signing; developers generate and maintain fixed identities outside DSH home and select them through configuration.
## Migration
1. Keep the default `sourceSigning: ad-hoc` for temporary signatures. To reduce repeated grants after rebuilds and across worktrees, follow the [developer signing skill](../../../../.agents/skills/dsh-cua-macos-signing/SKILL.md) to generate or reuse a certificate, then write `sourceSigning: { identity, keychain }` into the DSH home’s `cordis.patch.yml`; `keychain` must be an absolute path.
2. Start DSH from the source checkout, call Computer Use, and grant Accessibility and Screen Recording to `DSH Computer Use Dev` in System Settings.
3. Confirm that `getCapabilities` reports both permissions as `true`. With a fixed signature, check again after changing and rebuilding Swift code and from another worktree. Remove an old `DSH Computer Use` entry only when no installed DSH uses it.
4. After the keychain locks, rerun setup as described in the skill to unlock and reuse the identity. To stop using it, select `ad-hoc` or remove the configuration, then remove the identity through the skill; deleting DSH home does not delete the developer keychain.
@@ -0,0 +1,19 @@
---
kind: upgrade-guide
description: "源码构建的 Computer Use helper 使用独立的开发版 Bundle ID,需要重新授予一次 macOS 权限。"
---
# 源码构建的 Computer Use helper 身份
[English](guide.md) | 中文
## 变更
源码检出原先以临时签名构建 `DSH Computer Use.app`,使用正式版 Bundle ID `com.deepseek.harness.computer-use`。现在构建 `DSH Computer Use Dev.app`,使用 `com.deepseek.harness.computer-use.dev`。旧条目的辅助功能和屏幕录制授权不能沿用。Desktop 和 npm 安装版不变。源码构建默认仍为临时签名;固定身份由开发者在 DSH home 之外生成和维护,再通过配置指定。
## 迁移
1. 保持默认 `sourceSigning: ad-hoc` 即可使用临时签名。需要减少重新编译和跨 worktree 的授权次数时,按[开发者签名 skill](../../../../.agents/skills/dsh-cua-macos-signing/SKILL.md)生成或复用证书,并将 `sourceSigning: { identity, keychain }` 写入 DSH home 的 `cordis.patch.yml`;`keychain` 必须为绝对路径。
2. 从源码检出启动 DSH,调用 Computer Use,在系统设置中给 `DSH Computer Use Dev` 授予辅助功能和屏幕录制权限。
3. 确认 `getCapabilities` 的两项权限均为 `true`。使用固定签名时,在修改 Swift 源码重建和另一个 worktree 中分别复查。只有确认没有安装版 DSH 使用旧条目时,才移除旧 `DSH Computer Use` 条目。
4. 钥匙串锁定后,按 skill 重新运行 setup 解锁并复用现有身份。停止使用时改回 `ad-hoc` 或移除该配置,再按 skill 删除身份;删除 DSH home 不会删除开发者钥匙串。
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.2/subagent-explicit-reasoning/guide.md
/:
en: 74a51bb421eb125c
zh: 2fccbfa5bcafb2af
/subagent-reasoning-overrides-require-an-explicit-route:
en: f6bc10b254fe4420
zh: 9ac48f0264d1bd69
/subagent-reasoning-overrides-require-an-explicit-route/change:
en: e31a906fc29dd5a6
zh: 2fa39b8bcbdfdb38
/subagent-reasoning-overrides-require-an-explicit-route/migration:
en: 9ebfdab054389c89
zh: 7c50e28db91781e4
@@ -0,0 +1,20 @@
---
kind: upgrade-guide
description: "Subagent reasoning overrides require an explicit provider and model, and explicit routes use model-default reasoning when effort is omitted."
---
# Subagent reasoning overrides require an explicit route
English | [中文](guide.zh.md)
## Change
Delegation tools with model selection enabled reject `reasoning_effort` unless the same call supplies both `provider` and `model`. Previously, an effort-only call could use a configured or inherited route. The rejection occurs before child creation.
An explicit provider/model pair without `reasoning_effort` uses the selected model's default effort, including when the pair matches the parent or configured child route. Previously, the unchanged route could retain a configured or parent effort. Omitting all three tool fields preserves the configured child defaults and existing fallback behavior.
## Migration
1. Update prompts, skills, and tool-call producers that send only `reasoning_effort`: include the authorized `provider` and `model`, or omit all three fields to use the default child selection. Query `list_subagent_models` for authorized routes and supported effort ids.
2. To preserve a specific effort while selecting a route, pass it explicitly as `reasoning_effort`.
3. Confirm an effort-only call returns a missing-route error without starting a child. For a complete route, check the child's logged `request/header` configuration: an omitted effort follows that model's default rather than the parent's selected effort.
@@ -0,0 +1,20 @@
---
kind: upgrade-guide
description: "subagent 推理强度覆盖要求显式指定提供方和模型,显式路由省略强度时使用模型默认值。"
---
# subagent 推理强度覆盖要求显式路由
[English](guide.md) | 中文
## 变更
启用模型选择的委派工具要求同一次调用同时提供 `provider` 和 `model`,否则拒绝 `reasoning_effort`。此前,仅指定强度的调用可以使用配置或继承的路由。拒绝发生在创建子级之前。
显式提供提供方/模型组合但省略 `reasoning_effort` 时,使用所选模型的默认强度,即使该组合与父级或配置的子级路由相同。此前,路由不变时可能保留配置或父级强度。省略全部三个工具字段时,仍保留配置的子级默认值与现有回退行为。
## 迁移
1. 更新仅发送 `reasoning_effort` 的提示、skill 和工具调用生成方:补齐已授权的 `provider` 和 `model`,或省略全部三个字段以使用默认子级选择。通过 `list_subagent_models` 查询已授权路由与支持的强度 ID。
2. 选择路由时若要保留某个强度,显式传入 `reasoning_effort`。
3. 确认仅指定强度的调用返回缺少路由的错误,且没有启动子级。对于完整路由,检查子级日志中的 `request/header` 配置:省略强度时应采用该模型的默认值,而不是父级选择的强度。
+4 -4
View File
@@ -6,11 +6,11 @@
en: b1631dcf25e805a1
zh: 8ded02e2ae87f00b
/configure-models/configure-deepseek:
en: 44852da64a6a39ec
zh: 4c280e428f0fec08
en: 5cf396eb7f22b0f6
zh: d70688c6cd826f3a
/configure-models/add-a-third-party-provider:
en: f6fb44a85dc5e4dd
zh: 2b86ea4492c32ed7
en: c8fd933006c3830c
zh: 386f8f7d302e98c3
/configure-models/add-a-custom-model-api:
en: 17867305a3e1b52a
zh: 876fedf1f6f563e4
+4 -4
View File
@@ -10,7 +10,7 @@ Open **Settings → Models**. The DeepSeek card exposes one API-key field; enter
![The Models page: the DeepSeek card, with Add model provider below it](providers-models-page.png)
Keys are write-only. The page receives a redacted descriptor after saving, never the literal secret. The key is stored in `$DSH_HOME/.credentials.yaml`, while settings retain only its credential reference.
Opening a provider editor loads its saved key into a masked input. Environment values are never loaded into this input. The key is stored in `$DSH_HOME/.credentials.yaml`, while settings retain only its credential reference. Credential metadata remains redacted.
With a key saved and the default endpoint, DeepSeek's models follow the list the DeepSeek API publishes. The list loads when the models are first needed, refreshes in the background about every ten minutes while they are in use, and falls back to the built-in models when it cannot load. Editing **Models** under **Customized settings** keeps your own list instead and stops following the published one; **Restore defaults** follows it again and reloads it. While the published list is in use, the card shows the built-in models, so a newly published model appears only in the model picker. The [API-key provider reference](../../../packages/llm/llm-deepseek-api-key/README.md) owns the listing, fallback, and gating rules.
@@ -18,11 +18,11 @@ With a key saved and the default endpoint, DeepSeek's models follow the list the
Choose **Add model provider**. The card opens on **Third-party model provider**: pick a provider dsh ships with — the list shows provider ids such as `anthropic`, `openai`, `moonshotai` for Kimi, or `zai` for GLM — enter its API key, and save. The installed catalog supplies the endpoint, protocol, and model list.
The authentication **?** explains saved-credential priority and environment fallbacks. Leave the key blank to use a saved credential or try the listed environment variables. A green hint identifies a detected environment variable. A yellow hint means no credential variable was detected; enter an API key or configure the listed variable. An unconfirmed hint means the status read failed. Detection does not validate the credential or test the connection. Provider-managed credential files, including AWS profiles and Google application-default credentials, are outside this check. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference.
The authentication **?** explains saved-credential priority and environment fallbacks. With no saved key, leave the input blank to try the listed environment variables. A green hint identifies a detected environment variable. A yellow hint means no credential variable was detected; enter an API key or configure the listed variable. An unconfirmed hint means the status read failed or a saved key still covers the environment lookup. Clearing a saved key shows an unconfirmed hint until you save its removal and the page refreshes the environment check. Detection does not validate the credential or test the connection. Provider-managed credential files, including AWS profiles and Google application-default credentials, are outside this check. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference.
A saved credential uses the placeholder **Leave blank to use saved credentials**, with no status text below the input. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials.
A saved key appears masked, with no status text below the input. An empty input uses **Leave blank to use env as auth** and one detection hint. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials.
A nonempty key input has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Stored credentials remain write-only.
A nonempty key input has an eye button. Select **Show secret** to check the loaded or newly entered key, and **Hide secret** to mask it again. Changing the input masks it again. Saving an unchanged key preserves its exact stored value. Clearing it and saving removes the saved key. Cancelling preserves the saved key.
## Add a custom model API
+4 -4
View File
@@ -10,7 +10,7 @@
![模型页:DeepSeek 卡片,及其下方的添加模型提供商入口](providers-models-page.zh.png)
密钥是只写的。保存后,页面只会收到脱敏描述符,永远不会收到明文密钥。密钥存储在 `$DSH_HOME/.credentials.yaml` 中,settings 只保留它的凭据引用。
打开提供商编辑器时,已保存密钥会载入遮罩输入框。环境变量的值不会载入此输入框。密钥存储在 `$DSH_HOME/.credentials.yaml` 中,settings 只保留它的凭据引用。凭据元数据仍保持脱敏。
保存了密钥且使用默认端点时,DeepSeek 的模型跟随 DeepSeek API 发布的列表。第一次需要模型时加载列表,使用期间约每十分钟在后台刷新一次,无法加载时退回内置模型。在**自定义设置**里编辑**模型目录**会改用你自己的列表,不再跟随发布的列表;点**恢复默认模型**会重新跟随并重新加载。使用发布的列表时,卡片上显示的是内置模型,因此新发布的模型只出现在模型选择器中。列表、兜底和门控规则见 [API key 提供方参考](../../../packages/llm/llm-deepseek-api-key/README.zh.md)。
@@ -18,11 +18,11 @@
选择**添加模型提供商**。卡片默认打开在**第三方模型提供商**:选取 dsh 自带的提供商——列表显示的是提供商 id,例如 `anthropic`、`openai`、Kimi 对应的 `moonshotai`、GLM 对应的 `zai`——输入其 API 密钥并保存。已安装目录会提供端点、协议和模型列表。
认证 **?** 说明已保存凭据的优先级和环境后备。密钥留空时,使用已保存凭据,或尝试读取列出的环境变量。绿色提示标明已检测到环境变量。黄色提示表示未检测到凭据变量;请输入 API 密钥或配置列出的变量。状态未确认表示读取失败。检测不验证凭据,也不测试连接。AWS profile 和 Google 应用默认凭据等提供商管理的凭据文件不在检查范围内。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。
认证 **?** 说明已保存凭据的优先级和环境后备。没有已保存密钥时,输入留空会尝试读取列出的环境变量。绿色提示标明已检测到环境变量。黄色提示表示未检测到凭据变量;请输入 API 密钥或配置列出的变量。状态未确认表示读取失败,或已保存密钥仍覆盖环境读取。清空已保存密钥后,提示会保持未确认,直到保存删除操作并刷新环境检测。检测不验证凭据,也不测试连接。AWS profile 和 Google 应用默认凭据等提供商管理的凭据文件不在检查范围内。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。
已保存凭据使用**留空使用已保存凭据**占位文字,输入框下方不显示状态文字。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。
已保存密钥以遮罩显示,输入框下方不显示状态文字。输入留空时,显示**留空使用环境认证**占位文字和一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。
密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。已保存凭据仍保持只写。
密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查已载入或新输入的密钥,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。保存未修改的密钥会保留原值。清空并保存会删除已保存密钥。取消编辑会保留已保存密钥。
## 添加自定义模型 API
+2 -2
View File
@@ -16,7 +16,7 @@ import scheduleRemote from '@deepseek-ai/dsh-schedule/remote'
import llmRemote from '@deepseek-ai/dsh-llm/remote'
import dynamicRemote from '@deepseek-ai/dsh-cordis-host-runner/remote'
import pluginManagerRemote from '@deepseek-ai/dsh-plugin-manager/remote'
import mcpServersRemote from '@deepseek-ai/dsh-mcp-manager/remote'
import mcpManagerRemote from '@deepseek-ai/dsh-mcp-manager/remote'
import toolResultsRemote from '@deepseek-ai/dsh-client-ui-trajectory/remote'
import pluginRegistryProbeRemote from '@deepseek-ai/dsh-client-ui-plugin-manager/remote'
import pluginMarketRemote from '@deepseek-ai/dsh-plugin-market/remote'
@@ -196,7 +196,7 @@ export async function apply(ctx: Context): Promise<() => Promise<void>> {
for (const contribution of [
productAnalyticsRemote, agentPresetsRemote, commandsRemote, agentTeamsRemote, settingsControllerRemote, accountRemote,
goalsRemote, llmRemote, dynamicRemote, scheduleRemote,
pluginInventoryRemote, pluginManagerRemote, mcpServersRemote, pluginMarketRemote, pluginRegistryProbeRemote,
pluginInventoryRemote, pluginManagerRemote, mcpManagerRemote, pluginMarketRemote, pluginRegistryProbeRemote,
toolResultsRemote,
messageFeedbackRemote, sessionFeedbackRemote,
fileUploadsRemote, sessionReferencesRemote,
@@ -9,14 +9,14 @@
en: 7fecb4d8800e8f97
zh: 3e2c3fdb29b73cd0
/settings-controller/summary:
en: e5068267079e62d0
zh: 9e2d663a6ca02c58
en: 94a995854f855609
zh: 7165eecdd85a5632
/settings-controller/table-of-contents:
en: 3a654e12f423946b
zh: 4e3a19aaee58f8a7
/settings-controller/use-this-package:
en: cf2f4de5bee8be55
zh: b2630dcba4be5ae8
en: d6fbd0324044be6b
zh: 5e86d8c95e51b421
/settings-controller/configuration:
en: e0297f144b649af7
zh: e70ed56edffd97f0
+2 -2
View File
@@ -8,7 +8,7 @@ English | [中文](README.zh.md)
## Summary
`@deepseek-ai/dsh-api-settings-controller` exposes generated `ctx.remote.settings` and `ctx.remote.credentials` namespaces for browser configuration surfaces. It returns redacted settings and credential metadata, supports settings and credential writes without returning secret values, and opens provider-owned settings or Agent preset locations on the Host desktop. When a provider is absent, the namespace remains registered and returns an actionable configuration error.
`@deepseek-ai/dsh-api-settings-controller` exposes generated `ctx.remote.settings` and `ctx.remote.credentials` namespaces for browser configuration surfaces. It returns redacted settings and credential metadata and supports settings and credential writes. It reads stored keys for owner-opened editors. It also opens provider-owned settings or Agent preset locations on the Host desktop. When a provider is absent, the namespace remains registered and returns an actionable configuration error.
## Table of Contents
@@ -25,7 +25,7 @@ English | [中文](README.zh.md)
Mount this package as a Loader entry in a profile that serves browser configuration. The entry registers both namespaces independently of their providers so a missing provider produces a named configuration error at invocation. Its generated descriptors enter the strict Typert registry, while the settings and credential Definitions remain plain Cordis Services with no wire obligations of their own.
`describe(refs)` answers one map keyed by the requested names, so a settings page describing every reference its rows carry settles those rows together. It accepts at most 64 names per call, reports an invalid name or empty write value as `bad-request`, and copies each answer field by field — a provider returning more than `CredentialInfo` declares cannot widen what crosses. Valid `set(ref, value)` and `unset(ref)` calls report a provider refusal as `credential-rejected`, carrying the provider's message with only the reference in its details. Secret values cross in this direction only: no method here returns one.
`describe(refs)` answers one map keyed by the requested names, so a settings page describing every reference its rows carry settles those rows together. It accepts at most 64 names per call, reports an invalid name or empty write value as `bad-request`, and copies each answer field by field — a provider returning more than `CredentialInfo` declares cannot widen what crosses. Valid `set(ref, value)` and `unset(ref)` calls report a provider refusal as `credential-rejected`, carrying the provider's message with only the reference in its details. `readStored(ref)` returns a provider-managed key only for the owner or trusted in-process code; it returns no environment fallback. A non-owner read returns `credential/rejected` before consulting the provider. Metadata reads remain secret-free.
`settings.describe()` returns deployment facts and every namespace under `redactSecrets: true`. `settings.update`, `settings.replace`, and `settings.mutate` expose the settings service's three write operations and return the namespace's new redacted view; stale writes use `settings-conflict` and other provider refusals use `settings-rejected`.
@@ -8,7 +8,7 @@ kind: "package-reference"
## 概述
`@deepseek-ai/dsh-api-settings-controller` 为浏览器配置界面提供生成的 `ctx.remote.settings` 与 `ctx.remote.credentials` namespace。它返回脱敏的 settings 与凭据元数据,支持 settings 与凭据写入而不返回机密值,并在 Host 桌面打开由提供方持有的 settings 或 Agent preset 位置。提供方缺失时,namespace 仍会注册,并返回可操作的配置错误。
`@deepseek-ai/dsh-api-settings-controller` 为浏览器配置界面提供生成的 `ctx.remote.settings` 与 `ctx.remote.credentials` namespace。它返回脱敏的 settings 与凭据元数据,支持 settings 与凭据写入。它为所有者打开的编辑器读取已保存密钥。它还在 Host 桌面打开由提供方持有的 settings 或 Agent preset 位置。提供方缺失时,namespace 仍会注册,并返回可操作的配置错误。
## 目录
@@ -25,7 +25,7 @@ kind: "package-reference"
请把本包作为 Loader entry 挂载到提供浏览器配置的 profile 中。本 entry 不依赖提供方是否存在而注册两个 namespace,因此缺少提供方会在调用时产生具名配置错误。它生成的 descriptor 进入严格 Typert 注册表,而 settings 与凭据 Definition 仍是普通 Cordis 服务,自身不承担任何 wire 义务。
`describe(refs)` 以请求的名字为键返回一份 map,因此设置页描述其各行携带的全部引用时,这些行会一起落定。单次调用最多接受 64 个名字,无效名字或空写入值报告为 `bad-request`,并逐字段复制每个答案——提供方返回超出 `CredentialInfo` 声明的内容也无法扩大跨越 wire 的字段。有效的 `set(ref, value)` 与 `unset(ref)` 调用把提供方拒绝报告为 `credential-rejected`,携带提供方的消息,details 中只有该引用。机密值只在这个方向跨越 wire:这里没有任何方法会返回它。
`describe(refs)` 以请求的名字为键返回一份 map,因此设置页描述其各行携带的全部引用时,这些行会一起落定。单次调用最多接受 64 个名字,无效名字或空写入值报告为 `bad-request`,并逐字段复制每个答案——提供方返回超出 `CredentialInfo` 声明的内容也无法扩大跨越 wire 的字段。有效的 `set(ref, value)` 与 `unset(ref)` 调用把提供方拒绝报告为 `credential-rejected`,携带提供方的消息,details 中只有该引用。`readStored(ref)` 仅向所有者或可信进程内代码返回提供方管理的密钥,不返回环境后备值。非所有者读取会在访问提供方之前返回 `credential/rejected`。元数据读取仍不包含机密。
`settings.describe()` 返回部署信息,以及在 `redactSecrets: true` 下读取的所有 namespace。`settings.update`、`settings.replace` 与 `settings.mutate` 暴露 settings 服务的三种写入操作,并返回该 namespace 的新脱敏视图;陈旧写入使用 `settings-conflict`,其他提供方拒绝使用 `settings-rejected`。
@@ -9,7 +9,7 @@ import { Context } from '@deepseek-ai/cordis'
import { credentialRef } from '@deepseek-ai/dsh-credentials'
import type { CredentialProvider } from '@deepseek-ai/dsh-credentials'
import type { CredentialInfo } from '@deepseek-ai/dsh-credentials/types'
import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
import { principalOf, Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
import { z } from 'zod'
/**
@@ -61,8 +61,8 @@ declare module '@deepseek-ai/cordis' {
* Host service backing the generated `ctx.remote.credentials` namespace. It
* carries every wire obligation the credential seam itself does not: the batch
* fan-out bound, the field-by-field view projection, the reference-grammar
* guard, and the refusal mapping. Secret values cross in one direction only —
* no method here returns one.
* guard, and the refusal mapping. Metadata reads exclude secrets; readStored
* returns only a provider-managed value for an explicitly opened editor.
*/
export class CredentialsController extends TypertRemoteService {
/** @param ctx - Host context where a credential provider may be mounted. */
@@ -90,8 +90,22 @@ export class CredentialsController extends TypertRemoteService {
}
/**
* Store one value from a configuration surface. The value crosses the wire in
* this direction only: no read path returns it.
* Read one stored value for a credential editor, excluding environment fallbacks.
* @param ref - reference name to read.
* @returns the stored secret, or undefined when the provider stores none.
* @throws RemoteError for a non-owner Remote caller, an invalid reference, or an absent provider.
*/
@Remote
async readStored(ref: string): Promise<string | undefined> {
const request = parseRequest('credentials.readStored', unsetRequestSchema, { ref })
if (principalOf(this.ctx.invocation) !== undefined) {
throw new RemoteError('credential/rejected', 'Only the owner can read stored credentials.', { ref: request.ref })
}
return this.provider().readStored(credentialRef(request.ref))
}
/**
* Store one value from a configuration surface.
* @param ref - reference name to store under.
* @param value - the non-empty secret value.
* @throws RemoteError when the request is invalid, no provider is mounted, or the provider refuses the write.
@@ -20,9 +20,9 @@ declare module '@deepseek-ai/dsh-typert-protocol' {
*/
'settings/conflict': { readonly ns: string; readonly expected: number; readonly actual: number }
/**
* The provider refused a valid credential write, for example because the
* stored document no longer parses. The details name only the reference,
* never the value.
* A non-owner requested a stored secret, or the provider refused a valid
* credential write, for example because the stored document no longer
* parses. The details name only the reference, never the value.
*/
'credential/rejected': { readonly ref: string }
}
Loaded 100 of 326 files, more files were not shown because too many files have changed in this diff. Show more