feat(cua): make local development signing opt in

This commit is contained in:
creatixchu committed 2026-10-29 15:35:59 +08:00
1 parent 6439400885
commit e57fe79696
27 files changed
+310 -104

No files matched your search

@@ -9,11 +9,11 @@
en: a24857a312482724
zh: dbac75d363670e86
/agent-note-development-signing-identity-for-source-built-cua-helpers/decision:
en: 733d0bc8a9669023
zh: c556b726531c9c77
en: b11d0338edfa56f6
zh: ec93519fb3acc99d
/agent-note-development-signing-identity-for-source-built-cua-helpers/alternatives-considered:
en: 4796d5f7a085b365
zh: 7096a9623f1a1bde
en: 713bcd3484cf3594
zh: ae45617289117b7e
/agent-note-development-signing-identity-for-source-built-cua-helpers/consequences:
en: 9e60502bcfb035aa
zh: 161556d1556db574
en: 540579c5459e9e7a
zh: b7530006e681b618
@@ -12,15 +12,15 @@ Source checkouts compile `DSH Computer Use.app` with an ad-hoc signature. macOS
The Host builds source checkouts as a development variant with bundle identifier `com.deepseek.harness.computer-use.dev` and name `DSH Computer Use 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.
An explicit per-user setup command creates a self-signed code-signing certificate in a dedicated keychain, stores the random keychain password in an owner-only file beside it, allows `codesign` through the key partition list, and adds the keychain to the user keychain search list. `codesign` resolves identities only from that list. Development builds unlock the keychain with the stored password before every signature, so neither setup nor signing shows a password or key-access dialog. The resulting designated requirement names the bundle identifier and the certificate, so it is identical for every build signed on that machine, independent of code hash and path.
`sourceSigning` defaults to `ad-hoc`, which does not read an existing identity or modify keychains. Selecting `local-identity` makes the build create or reuse the local identity. Setup creates a self-signed code-signing certificate in a dedicated keychain, stores the random keychain password in an owner-only file beside it, allows `codesign` through the key partition list, and adds the keychain to the user keychain search list. `codesign` resolves identities only from that list. Local-identity builds unlock the keychain with the stored password before signing to avoid password or key-access dialogs. A process lock serializes setup and removal across worktrees so concurrent initialization cannot create different certificates. The resulting designated requirement names the bundle identifier and the certificate, so it is identical for every build signed on that machine, independent of code hash and path.
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. Without setup, development builds use ad-hoc signatures and print the setup command. An explicit `--identity` overrides the local identity.
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. Setup failures stop the build, and diagnostics omit passwords and complete command arguments. An explicit `--identity` overrides the selected signing mode.
## 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.
**Separate bundle identifier with ad-hoc signatures.** This separates development grants from release grants, but every changed build still has a new code hash and needs new grants.
**Fixed signing by default.** A fixed identity preserves the designated requirement but stores a private key and changes the keychain search list. Ad-hoc defaults let users choose whether to accept those changes, at the cost of possible reauthorization when binaries change.
**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.
@@ -30,4 +30,4 @@ Certificate signatures embed a signing time even without a timestamp server. Dev
## Consequences
One grant covers all source checkouts and rebuilds of one macOS user. Any process of that user can read the keychain password and sign code that receives the development grants; the release helper's grants are unaffected, and the same user can already change the Swift sources that the next build signs. Setup changes the user keychain search list until the remove command runs. Grants already listed in System Settings stay there after removal. Existing ad-hoc source grants do not carry over; developers grant `DSH Computer Use Dev` once. `dev_signing_e2e.py` checks that two different builds share one designated requirement and that removal restores the search list.
Checkouts and rebuilds selecting local-identity share a designated requirement. Actual permission retention after rebuilds and across worktrees still requires manual verification. Any process of that user can read the keychain password and sign code that receives the development grants; the release helper's grants are unaffected, and the same user can already change the Swift sources that the next build signs. Setup changes the user keychain search list until the remove command runs. Select `ad-hoc` before removal or the next build creates another identity; changing signing modes or identities can require new grants. Grants already listed in System Settings stay there after removal. Existing ad-hoc source grants do not carry over; developers grant `DSH Computer Use Dev` once. `dev_signing_e2e.py` checks that two different builds share one designated requirement and that removal restores the search list.
@@ -12,15 +12,15 @@ Status: implemented
Host 以开发版构建源码检出,Bundle ID 为 `com.deepseek.harness.computer-use.dev`,名称为 `DSH Computer Use Dev`。正式版及其打包流程不变。按[共享 helper 决策](2026-10-09-cua-shared-native-helper.zh.md)的要求,授权仍归经 LaunchServices 启动的 helper 应用。
一条显式运行的单用户初始化命令在专用钥匙串中创建自签名代码签名证书,把随机钥匙串密码保存在旁边仅所有者可读的文件中,通过密钥分区列表允许 `codesign` 使用私钥,并把该钥匙串加入用户钥匙串搜索列表。`codesign` 只从这个列表查找签名身份。开发构建每次签名前都用保存的密码解锁钥匙串,因此初始化和签名都不会弹出密码或密钥访问窗口。签名得到的指定要求只包含 Bundle ID 和证书,同一台机器上签出的所有构建都相同,与代码哈希和路径无关。
`sourceSigning` 默认为 `ad-hoc`,不读取已有身份或修改钥匙串。显式选择 `local-identity` 后,构建自动初始化或复用本机身份。初始化在专用钥匙串中创建自签名代码签名证书,把随机钥匙串密码保存在旁边仅所有者可读的文件中,通过密钥分区列表允许 `codesign` 使用私钥,并把该钥匙串加入用户钥匙串搜索列表。`codesign` 只从这个列表查找签名身份。固定身份构建每次签名前都用保存的密码解锁钥匙串,避免密码或密钥访问窗口。跨进程文件锁串行化不同 worktree 的初始化和移除,防止并发创建不同证书。签名得到的指定要求只包含 Bundle ID 和证书,同一台机器上签出的所有构建都相同,与代码哈希和路径无关。
即使不使用时间戳服务器,证书签名也会写入签名时间。开发版发布时记录每个未签名应用与签名身份对应的目录,再次构建时直接选中该目录,不重新签名,因此相同源码保持同一个可执行文件摘要和同一个共享服务。未初始化时,开发构建使用临时签名并输出初始化命令。显式传入 `--identity` 时覆盖本机身份。
即使不使用时间戳服务器,证书签名也会写入签名时间。开发版发布时记录每个未签名应用与签名身份对应的目录,再次构建时直接选中该目录,不重新签名,因此相同源码保持同一个可执行文件摘要和同一个共享服务。缓存使用证书指纹;显式证书名称可能对应续期后的证书,因此不复用缓存。签名初始化失败会中止构建;异常信息不包含密码或完整命令参数。显式传入 `--identity` 时覆盖配置的签名方式。
## 考虑过的替代方案
**把权限交给启动终端。** 直接启动服务时,macOS 把权限归属到启动 DSH 的终端或编辑器。该应用运行的所有程序,包括模型执行的命令,都会带上这些权限。
**单独的 Bundle ID 加临时签名。** 这样能把开发版与正式版的授权分开,但每次构建内容变化后代码哈希仍会改变,仍需重新授权。
**默认固定签名。** 固定身份可以保持签名要求,但会保存私钥并修改钥匙串搜索列表。默认临时签名让用户自行选择是否接受这些改动,代价是二进制变化后可能需要重新授权。
**把自签名身份放进登录钥匙串。** 登录钥匙串已解锁且在搜索列表中,但要让 `codesign` 不弹窗地使用其中的新私钥,需要用户的登录密码。
@@ -30,4 +30,4 @@ Host 以开发版构建源码检出,Bundle ID 为 `com.deepseek.harness.comput
## 后果
同一 macOS 用户的所有源码检出和重新编译共用一次授权。该用户的任何进程都能读取钥匙串密码,并签出获得开发版授权的代码;正式 helper 的授权不受影响,而且同一用户本来就能修改下一次构建会签名的 Swift 源码。初始化会改变用户钥匙串搜索列表,直到运行移除命令。系统设置中已有的授权在移除后仍然保留。原有的临时签名源码授权不会沿用,开发者需要给 `DSH Computer Use Dev` 授权一次。`dev_signing_e2e.py` 检查两个不同构建共用同一个指定要求,并确认移除后搜索列表已恢复。
启用固定签名的检出和重新编译共用签名要求。真实授权在重新编译和跨 worktree 后是否保留,仍需手动验证。该用户的任何进程都能读取钥匙串密码,并签出获得开发版授权的代码;正式 helper 的授权不受影响,而且同一用户本来就能修改下一次构建会签名的 Swift 源码。初始化会改变用户钥匙串搜索列表,直到运行移除命令。移除前需切回 `ad-hoc`,否则下次构建会重新创建身份;切换签名方式或更换身份可能需要重新授权。系统设置中已有的授权在移除后仍然保留。原有的临时签名源码授权不会沿用,开发者需要给 `DSH Computer Use Dev` 授权一次。`dev_signing_e2e.py` 检查两个不同构建共用同一个指定要求,并确认移除后搜索列表已恢复。
+1 -1
View File
@@ -1116,7 +1116,7 @@ export interface Config {
- `source`: [`packages/experimental/cua-macos/src/index.ts:16`](../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 type Config = CuaConfig
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-cua-macos -->
+1 -1
View File
@@ -1118,7 +1118,7 @@ export interface Config {
- `source`: [`packages/experimental/cua-macos/src/index.ts:16`](../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 type Config = CuaConfig
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-cua-macos -->
@@ -12,5 +12,5 @@
en: 29be2dd047eba853
zh: a2025097f7a0f37d
/source-built-computer-use-helper-identity/migration:
en: f4456b96cc84bda8
zh: 2d941040267d7f61
en: 318184f2a11cbcea
zh: c320de5acc4ee165
@@ -13,7 +13,7 @@ Source checkouts previously built `DSH Computer Use.app` with the release bundle
## Migration
1. Run `pnpm --dir packages/experimental/cua-macos run dev-signing:setup` once per macOS user so later builds and other worktrees keep the grant. Without it, every changed build is ad-hoc signed and asks again.
1. Source builds default to ad-hoc signing; changed binaries can require new grants. For a fixed identity, set `config.sourceSigning: local-identity` on `id: cua` in the profile’s `cordis.patch.yml`. The first build creates or reuses the identity automatically. Use the same configuration in each worktree.
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`. Remove an old `DSH Computer Use` entry only when no installed DSH uses it.
4. To undo setup, run `pnpm --dir packages/experimental/cua-macos run dev-signing:remove` and remove the `DSH Computer Use Dev` entries in System Settings.
4. To remove fixed signing, first select `sourceSigning: ad-hoc`, then run `pnpm --dir packages/experimental/cua-macos run dev-signing:remove` and remove the development grants in System Settings.
@@ -13,7 +13,7 @@ description: "源码构建的 Computer Use helper 使用独立的开发版 Bundl
## 迁移
1. 每个 macOS 用户运行一次 `pnpm --dir packages/experimental/cua-macos run dev-signing:setup`,之后的构建和其他 worktree 都能沿用授权。未运行时,每次构建内容变化都使用临时签名并重新要求授权。
1. 源码构建默认使用临时签名,二进制变化后可能需要重新授权。如需固定身份,在 profile 的 `cordis.patch.yml` 中为 `id: cua` 设置 `config.sourceSigning: local-identity`,首次构建会自动创建或复用本机身份。各 worktree 需使用相同配置。
2. 从源码检出启动 DSH 并调用 Computer Use,在系统设置中给 `DSH Computer Use Dev` 授予辅助功能和屏幕录制权限。
3. 确认 `getCapabilities` 报告两项权限均为 `true`。只有在没有已安装的 DSH 使用旧的 `DSH Computer Use` 条目时才移除它。
4. 撤销初始化时运行 `pnpm --dir packages/experimental/cua-macos run dev-signing:remove`,并在系统设置中移除 `DSH Computer Use Dev` 条目。
4. 撤销固定签名时,先切回 `sourceSigning: ad-hoc`,再运行 `pnpm --dir packages/experimental/cua-macos run dev-signing:remove`,并在系统设置中删除开发版授权。
@@ -15,8 +15,8 @@
en: 395f2a62b2ce6b4a
zh: 67912bb946c78837
/deepseek-ai-dsh-experimental-cua-macos/use-this-package:
en: 530cd1ddd6f4cdcf
zh: 51c74c4f71e0d552
en: 8877abe53e4b2ed8
zh: e85dd36f64041855
/deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment:
en: 786b8fd630b11e5f
zh: 55143f15486afce8
+12 -1
View File
@@ -37,13 +37,24 @@ For repository Web use, enable [Computer Use](../cua-bundle/README.md) in Plugin
pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.yml --dump-config
```
The dump command checks profile composition without a model request. For a real task, replace `--dump-config` with a prompt and configure the profile’s model credentials. The overlay mounts the computer-use registry and this provider; remove an existing competing provider before using it. `DSH Computer Use.app` needs Accessibility permission for AX/input and Screen Recording permission for capture; grant these permissions to the helper when prompted. Source checkouts show the helper as `DSH Computer Use Dev`. `getCapabilities` reports permissions and session lock state without opening a system dialog. Locked or unavailable desktop sessions reject UI observations and input before dispatch; the user must unlock macOS before resuming. `listApps` and `cua.getState` list running applications. `findApps(query)` searches standard macOS application directories by name, bundle ID or absolute path. `getApp` selects a unique name, bundle ID, path or running PID, obtains application consent, and launches a stopped app in the background when needed. A stopped application’s bundle identifier and executable path are read from disk before approval and rechecked before and after launch; applications without a bundle identifier use their canonical executable path for reusable consent. Selecting a stopped installation requests a new instance of that copy. The helper waits for the launched application to finish launching before returning its PID. A post-launch verification failure expires the pending handle but can leave the process running; inspect running applications before selecting a fresh handle. The returned object reads initial AX without activating the app. Launch cancellation may leave the application running. Model guidance starts with background observation and input, without activation during initialization or before each action. For hidden or minimized windows, try `app.show()` or `window.show()` and read fresh state. This requests unhide and unminimize without activation, raising or switching Spaces; app-level restoration selects the focused, main or sole AX window. The result names the selected `windowId`, or null when no window was selected, and reports `foregroundChanged` by comparing the front app and top window before and after the request. Null means foreground evidence was unavailable; later focus changes remain possible. If restoration fails or the window remains unusable, explain the needed foreground step, call `app.activate()` or an observed window’s `raise` action, then observe again. Necessary foreground access takes priority over preserving focus. Applications may change focus after input; background delivery does not guarantee an undisturbed user session.
The dump command checks profile composition without a model request. For a real task, replace `--dump-config` with a prompt and configure the profile’s model credentials. The overlay mounts the computer-use registry and this provider; remove an existing competing provider before using it. `DSH Computer Use.app` needs Accessibility permission for AX/input and Screen Recording permission for capture; grant these permissions to the helper when prompted. Source builds declare `DSH Computer Use Dev` in Info.plist; the bundle filename remains `DSH Computer Use.app`. Follow the system prompt when granting access. `getCapabilities` reports permissions and session lock state without opening a system dialog. Locked or unavailable desktop sessions reject UI observations and input before dispatch; the user must unlock macOS before resuming. `listApps` and `cua.getState` list running applications. `findApps(query)` searches standard macOS application directories by name, bundle ID or absolute path. `getApp` selects a unique name, bundle ID, path or running PID, obtains application consent, and launches a stopped app in the background when needed. A stopped application’s bundle identifier and executable path are read from disk before approval and rechecked before and after launch; applications without a bundle identifier use their canonical executable path for reusable consent. Selecting a stopped installation requests a new instance of that copy. The helper waits for the launched application to finish launching before returning its PID. A post-launch verification failure expires the pending handle but can leave the process running; inspect running applications before selecting a fresh handle. The returned object reads initial AX without activating the app. Launch cancellation may leave the application running. Model guidance starts with background observation and input, without activation during initialization or before each action. For hidden or minimized windows, try `app.show()` or `window.show()` and read fresh state. This requests unhide and unminimize without activation, raising or switching Spaces; app-level restoration selects the focused, main or sole AX window. The result names the selected `windowId`, or null when no window was selected, and reports `foregroundChanged` by comparing the front app and top window before and after the request. Null means foreground evidence was unavailable; later focus changes remain possible. If restoration fails or the window remains unusable, explain the needed foreground step, call `app.activate()` or an observed window’s `raise` action, then observe again. Necessary foreground access takes priority over preserving focus. Applications may change focus after input; background delivery does not guarantee an undisturbed user session.
Source builds default to ad-hoc signing and do not read or modify keychains, even when a development certificate already exists. To keep a signing identity across rebuilds and worktrees, configure the loaded `cua` entry in the profile’s `cordis.patch.yml`:
```yaml
- id: cua
config:
sourceSigning: local-identity
```
The first activation creates the local identity. Each worktree must select `local-identity`; a shared profile reuses this configuration. See [development signing](native/README.md#build-and-service) for keychain access, removal and permission limits.
| Field | Default | Meaning |
| --- | --- | --- |
| `agentPreset` | `ptc` | Register tools and guidance only for Agents bound to this preset; `false` registers globally. |
| `allowedApps` | `[]` | Legacy path/signature grants, imported once for removal; they do not authorize new bundle-ID identities. |
| `helperPath` | package-owned executable | Absolute executable inside the signed helper `.app`; a bare binary fails with `NATIVE_APPLICATION_REQUIRED`. |
| `sourceSigning` | `ad-hoc` | Source-build signature; `local-identity` automatically creates or reuses a local identity. Ignored for installed packages and `helperPath`. |
| `buildTimeoutMs` | `300000` | Maximum native preparation time. |
| `timeoutMs` | `30000` | Per-operation deadline; cancellation can leave partial input. |
| `connectTimeoutMs` | `5000` | Deadline for connecting to or starting the shared helper. |
+12 -1
View File
@@ -37,13 +37,24 @@ helper 通过 LaunchServices 以独立的 `DSH Computer Use.app` 后台运行,
pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.yml --dump-config
```
配置输出命令不发起模型请求。执行真实任务时,将 `--dump-config` 替换为任务提示,并配置该 profile 的模型凭据。配置挂载 computer-use 注册表和本 provider;使用前需移除已有的竞争 provider。`DSH Computer Use.app` 需要辅助功能权限来读取 AX 和输入,需要屏幕录制权限来截图;按系统提示给 helper 授权。源码检出的 helper 显示为 `DSH Computer Use Dev`。`getCapabilities` 查询权限和锁屏状态,不弹出系统授权窗口。桌面会话锁定或不可用时,界面观察与输入会在分派前拒绝,需由用户解锁 macOS 后继续。`listApps` 和 `cua.getState` 列出运行中的应用。`findApps(query)` 按名称、bundle ID 或绝对路径搜索 macOS 标准应用目录。`getApp` 按唯一名称、bundle ID、路径或运行中的 PID 选择应用,取得应用许可后,在需要时后台启动尚未运行的应用。授权前从磁盘读取应用的 Bundle ID 和可执行路径,在启动前后重新读取并核对;没有 Bundle ID 的应用使用规范化的可执行路径复用授权。选择尚未运行的安装副本时,会请求为该副本创建新实例。helper 等待应用完成启动后才返回其 PID。启动后验证失败会使待启动句柄失效,但进程可能仍在运行;应先查看运行中的应用,再取得新句柄。返回的对象读取初始 AX,不自动激活应用。启动被取消时,应用可能已经运行。模型指引要求先在后台观察和输入,不在初始化或每次动作前激活应用。窗口隐藏或最小化时,先尝试 `app.show()` 或 `window.show()`,再重新观察。它请求取消隐藏和恢复最小化,不主动激活、抬起窗口或切换桌面空间;应用级恢复选择焦点窗口、主窗口或唯一 AX 窗口。结果通过 `windowId` 指明选中的窗口,未选中时为 null;`foregroundChanged` 比较操作前后的前台应用和最上层窗口,无法取得完整观察时为 null,返回后仍可能发生焦点变化。恢复失败或窗口仍不可用时,说明需要前台的步骤,再调用 `app.activate()` 或窗口的 `raise` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。
配置输出命令不发起模型请求。执行真实任务时,将 `--dump-config` 替换为任务提示,并配置该 profile 的模型凭据。配置挂载 computer-use 注册表和本 provider;使用前需移除已有的竞争 provider。`DSH Computer Use.app` 需要辅助功能权限来读取 AX 和输入,需要屏幕录制权限来截图;按系统提示给 helper 授权。源码构建在 Info.plist 中声明名称 `DSH Computer Use Dev`,应用包文件名仍为 `DSH Computer Use.app`;授权时以系统提示为准。`getCapabilities` 查询权限和锁屏状态,不弹出系统授权窗口。桌面会话锁定或不可用时,界面观察与输入会在分派前拒绝,需由用户解锁 macOS 后继续。`listApps` 和 `cua.getState` 列出运行中的应用。`findApps(query)` 按名称、bundle ID 或绝对路径搜索 macOS 标准应用目录。`getApp` 按唯一名称、bundle ID、路径或运行中的 PID 选择应用,取得应用许可后,在需要时后台启动尚未运行的应用。授权前从磁盘读取应用的 Bundle ID 和可执行路径,在启动前后重新读取并核对;没有 Bundle ID 的应用使用规范化的可执行路径复用授权。选择尚未运行的安装副本时,会请求为该副本创建新实例。helper 等待应用完成启动后才返回其 PID。启动后验证失败会使待启动句柄失效,但进程可能仍在运行;应先查看运行中的应用,再取得新句柄。返回的对象读取初始 AX,不自动激活应用。启动被取消时,应用可能已经运行。模型指引要求先在后台观察和输入,不在初始化或每次动作前激活应用。窗口隐藏或最小化时,先尝试 `app.show()` 或 `window.show()`,再重新观察。它请求取消隐藏和恢复最小化,不主动激活、抬起窗口或切换桌面空间;应用级恢复选择焦点窗口、主窗口或唯一 AX 窗口。结果通过 `windowId` 指明选中的窗口,未选中时为 null;`foregroundChanged` 比较操作前后的前台应用和最上层窗口,无法取得完整观察时为 null,返回后仍可能发生焦点变化。恢复失败或窗口仍不可用时,说明需要前台的步骤,再调用 `app.activate()` 或窗口的 `raise` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。
源码构建默认使用临时签名,即使本机已有开发证书也不会读取或修改钥匙串。需要在重新编译或切换 worktree 后保留签名身份时,在 profile 的 `cordis.patch.yml` 中为已加载的 `cua` 节点配置:
```yaml
- id: cua
config:
sourceSigning: local-identity
```
首次启用会创建本机签名身份。不同 worktree 都需选择 `local-identity`;共享 profile 可复用这项配置。钥匙串访问范围、撤销方法和授权限制见[开发签名](native/README.zh.md#build-and-service)。
| 字段 | 默认值 | 含义 |
| --- | --- | --- |
| `agentPreset` | `ptc` | 仅为绑定该 preset 的 Agent 注册工具和指引;`false` 表示全局注册。 |
| `allowedApps` | `[]` | 旧路径和签名许可,只导入 profile 存储一次供撤销,不授予新 Bundle ID 身份访问权限。 |
| `helperPath` | 包内可执行文件 | 已签名 helper `.app` 内可执行文件的绝对路径;裸二进制会触发 `NATIVE_APPLICATION_REQUIRED`。 |
| `sourceSigning` | `ad-hoc` | 源码构建的签名方式;`local-identity` 自动创建或复用本机固定身份。安装版和 `helperPath` 忽略此项。 |
| `buildTimeoutMs` | `300000` | 原生组件准备的最长时间。 |
| `timeoutMs` | `30000` | 单次操作截止时间,取消后可能已发生部分输入。 |
| `connectTimeoutMs` | `5000` | 连接或启动共享 helper 的截止时间。 |
@@ -15,8 +15,8 @@
en: e8cbc43d38786c40
zh: 52b3ba85d98011b9
/dsh-cua-native-helper/build-and-service:
en: 405120fe2ade9d33
zh: 8981a10cb38ccd2f
en: 488fe3adbc838de3
zh: 768bf452370a0f36
/dsh-cua-native-helper/request-protocol:
en: fc8043c425322cdd
zh: cf1edb9a78fda301
@@ -24,8 +24,8 @@
en: caeccd866da14a36
zh: 6a82e3a16a03813e
/dsh-cua-native-helper/verification:
en: 2cddaae20fc5e39e
zh: 69ffdf436e5083f1
en: c2ad240e2ce1962f
zh: 4a0cb0b30df98b71
/dsh-cua-native-helper/further-exploration:
en: 265e1927952ce6d7
zh: 7c35d9fd98b6e6c8
@@ -25,7 +25,13 @@ This macOS 14+ JSON-lines helper uses Swift 6, AppKit, Accessibility, CoreGraphi
Run `pnpm --dir packages/experimental/cua-macos run build:native` to publish a signed `DSH Computer Use.app` under `native/bin/darwin-<arch>`. The `current.json` receipt selects a complete content-addressed generation. Signing defaults to ad hoc; release packagers can pass `--identity` for Developer ID signing and must notarize the distribution. The Host runs the application executable with `--ensure-shared`, which launches the background service through LaunchServices. The service exits after its last connection finishes cleanup.
Source checkouts build with `--variant dev`: the application has bundle identifier `com.deepseek.harness.computer-use.dev` and name `DSH Computer Use Dev`, so its macOS permission entries are separate from the release helper. An ad-hoc signature’s designated requirement is its code hash, so macOS asks again for permissions after every changed build. Run `pnpm --dir packages/experimental/cua-macos run dev-signing:setup` once per macOS user to create the `DSH Computer Use Dev (local)` certificate in a dedicated keychain under `~/Library/Application Support/DeepSeek Harness/computer-use-dev-signing` and add that keychain to the user keychain search list. Development builds in every checkout then sign with this certificate; their designated requirement names only the bundle identifier and the certificate, so one grant covers changed builds and other worktrees. Each build unlocks the keychain with the password stored beside it, so neither setup nor builds show a password dialog. Any process of the same user can read that password and sign code that receives the development grants; release helper grants are unaffected. Certificate signatures include a signing time, so development builds record the generation produced by each unsigned bundle and identity under `sources/` and select it again instead of re-signing. `dev-signing:remove` deletes the keychain, its search-list entry and the password; grants already listed in System Settings remain until removed there. `--identity` overrides the local identity, for example with an Apple Development certificate.
Source checkouts build with `--variant dev`: the application declares bundle identifier `com.deepseek.harness.computer-use.dev` and name `DSH Computer Use Dev`; its bundle filename remains `DSH Computer Use.app`. The default `--signing ad-hoc` never accesses the development keychain. Ad-hoc requirements contain the code hash, so changed binaries, including clean rebuilds, can require authorization again.
Select `sourceSigning: local-identity` in the provider configuration, or pass `--variant dev --signing local-identity` to `build_app.py`, to create or reuse the `DSH Computer Use Dev (local)` certificate. Setup stores it in a dedicated keychain under `~/Library/Application Support/DeepSeek Harness/computer-use-dev-signing` and adds the keychain to the user search list. A file lock serializes setup and removal across worktrees. Each build unlocks the keychain with its adjacent owner-only password file. Any process of the same user can read that password and sign code with the development identity. The designated requirement contains the bundle identifier and certificate instead of the code hash; actual permission retention after rebuilds and across worktrees still requires a manual macOS grant check.
`pnpm --dir packages/experimental/cua-macos run dev-signing:setup` can prepare the identity in advance; it does not change the default signing mode. To remove it, first select `sourceSigning: ad-hoc`, then run `pnpm --dir packages/experimental/cua-macos run dev-signing:remove`. Removal deletes the keychain, its search-list entry and password; the empty lock file remains to serialize later setup. Remove grants separately in System Settings. A missing certificate or invalid identity record fails with instructions to remove and set up again; identity replacement requires new grants. `--identity` overrides `--signing`; release builds ignore `--signing` and keep their existing signing behavior.
Certificate signatures include a signing time. Development builds record the generation produced by each unsigned bundle and certificate fingerprint under `sources/` and reuse it for unchanged content. Ad-hoc builds use a separate record. Explicit certificate names are re-signed because renewal can change the certificate behind a name.
Generations in `native/.build/prepared/<arch>` and `native/bin/darwin-<arch>` are retained without automatic garbage collection. Use a fresh `--output-directory` for release staging, or clean the packaging output before building while no client uses it, so old generations do not enter the tarball. Secure signing timestamps can create distinct generations for identical sources.
@@ -117,13 +123,13 @@ Request modifier arrays accept command/control/option/shift/fn. The object API n
<a id="verification"></a>
## Verification
Desktop checks require grants for `DSH Computer Use.app`; source rebuilds with ad-hoc signatures can require authorization again. `--helper` names the executable inside that application. Bare executables are supported only as old-version comparison inputs, not as current helper overrides.
Desktop checks require grants for the selected helper: release builds declare `DSH Computer Use`, and development builds declare `DSH Computer Use Dev`. Follow the system prompt; ad-hoc rebuilds can require authorization again. `--helper` names the executable inside that application. Bare executables are supported only as old-version comparison inputs, not as current helper overrides.
Run `python3 packages/experimental/cua-macos/native/tests/startup_e2e.py` to check immediate exit, typed startup errors, stale readiness rejection and termination of stalled new instances through LaunchServices. It uses owned applications and requests no system permissions. Publication unit tests mock signing; `build:native` invokes real `codesign --verify --strict`, and `launcher_identity_e2e.py` verifies LaunchServices attribution.
Use `python3 packages/experimental/cua-macos/native/tests/test_swift.py` for offline unit checks with the selected Apple toolchain’s Swift Testing framework/runtime paths and `python3 packages/experimental/cua-macos/native/tests/protocol_e2e.py` for JSONL admission, ordered replies and EOF shutdown without desktop operations. Application and protocol e2e checks accept `--helper` to select a separately built comparison binary. `python3 packages/experimental/cua-macos/native/tests/test_build_app.py` covers application publication, the development variant, signed-generation reuse, signing failure and corrupted-generation rejection. `python3 packages/experimental/cua-macos/native/tests/test_dev_signing.py` covers identity setup, unlocking and removal with a simulated `security` command. `python3 packages/experimental/cua-macos/native/tests/dev_signing_e2e.py` creates a temporary identity, signs two different builds, checks that both have the same designated requirement, then removes the identity and verifies the restored keychain search list.
Run `python3 packages/experimental/cua-macos/native/tests/shared_helper_e2e.py --helper /absolute/helper` to verify concurrent startup, a shared service PID, independent handles, same-application handoff, request-local screenshot deadlines, connection cleanup and signal shutdown with an owned AppKit fixture. Existing Accessibility and Screen Recording grants for `DSH Computer Use.app` are required. `--without-desktop` limits the check to protocol and process lifetime.
Run `python3 packages/experimental/cua-macos/native/tests/shared_helper_e2e.py --helper /absolute/helper` to verify concurrent startup, a shared service PID, independent handles, same-application handoff, request-local screenshot deadlines, connection cleanup and signal shutdown with an owned AppKit fixture. Existing Accessibility and Screen Recording grants for the selected release or development helper are required. `--without-desktop` limits the check to protocol and process lifetime.
Run `python3 packages/experimental/cua-macos/native/tests/application_consent_e2e.py --helper /absolute/helper` in an unlocked macOS GUI session with the Apple Swift compiler available. It owns and cleans up its AppKit bundles and standalone GUI processes, checks metadata replacement, cold and direct launches, shared bundle IDs, persistent path identity across standalone restarts, and selection after a running executable is deleted. The default identity check requires no Accessibility or Screen Recording grants. Add `--desktop` to read intact fixtures’ controls, verify AX button presses in their state files, capture their windows, and record observation results after executable deletion; this requires existing grants for both permissions.
@@ -25,7 +25,13 @@ kind: "package-reference"
运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-<arch>` 下生成带签名的 `DSH Computer Use.app`,`current.json` 选择完整的内容摘要目录。默认使用临时签名;正式打包可传入 `--identity` 指定 Developer ID,并由发布流程完成公证。Host 运行应用内的 `--ensure-shared` 入口,经 LaunchServices 后台启动服务。最后一条连接完成清理后,服务退出。
源码检出以 `--variant dev` 构建:应用的 Bundle ID 为 `com.deepseek.harness.computer-use.dev`,名称为 `DSH Computer Use Dev`,系统权限条目与正式 helper 分开。临时签名的指定要求就是代码哈希,每次构建内容变化后,macOS 都会重新要求授权。每个 macOS 用户运行一次 `pnpm --dir packages/experimental/cua-macos run dev-signing:setup`,在 `~/Library/Application Support/DeepSeek Harness/computer-use-dev-signing` 下的专用钥匙串中创建 `DSH Computer Use Dev (local)` 证书,并把该钥匙串加入用户钥匙串搜索列表。此后所有检出的开发构建都用这张证书签名,指定要求只包含 Bundle ID 和证书,一次授权即可覆盖重新编译的构建和其他 worktree。每次构建都用存放在钥匙串旁边的密码解锁钥匙串,初始化和构建都不会弹出密码窗口。同一用户的任何进程都能读取该密码,并签出获得开发版授权的代码;正式 helper 的授权不受影响。证书签名包含签名时间,因此开发构建在 `sources/` 中记录每个未签名应用与签名身份对应的目录,再次构建时直接选中该目录,不重新签名。`dev-signing:remove` 删除钥匙串、它在搜索列表中的条目和密码;系统设置中已有的授权需要在系统设置中移除。`--identity` 可以覆盖本机身份,例如改用 Apple Development 证书。
源码检出以 `--variant dev` 构建:应用声明的 Bundle ID 为 `com.deepseek.harness.computer-use.dev`,名称为 `DSH Computer Use Dev`,应用包文件名仍为 `DSH Computer Use.app`。默认的 `--signing ad-hoc` 不访问开发钥匙串。临时签名的指定要求包含代码哈希,因此二进制变化时可能需要重新授权,干净重建也可能产生这种变化。
在 provider 配置中选择 `sourceSigning: local-identity`,或给 `build_app.py` 传入 `--variant dev --signing local-identity`,即可创建或复用 `DSH Computer Use Dev (local)` 证书。初始化会把证书存入 `~/Library/Application Support/DeepSeek Harness/computer-use-dev-signing` 下的专用钥匙串,并将该钥匙串加入用户搜索列表。文件锁让不同 worktree 的初始化和移除串行执行。每次构建都用旁边仅所有者可读的密码文件解锁钥匙串。同一用户的任何进程都能读取该密码并用开发身份签名。指定要求包含 Bundle ID 和证书,不包含代码哈希;重新编译和切换 worktree 后实际能否保留权限,仍需在 macOS 上手动授权验证。
`pnpm --dir packages/experimental/cua-macos run dev-signing:setup` 可以提前准备身份,但不会改变默认签名方式。移除时先选择 `sourceSigning: ad-hoc`,再运行 `pnpm --dir packages/experimental/cua-macos run dev-signing:remove`。移除命令删除钥匙串、搜索列表条目和密码,保留空锁文件以协调后续初始化。系统设置中的授权需单独删除。证书缺失或身份记录损坏会报错,并提示先移除再初始化;更换身份需要重新授权。`--identity` 覆盖 `--signing`;正式版忽略 `--signing`,沿用原有签名行为。
证书签名包含签名时间。开发构建在 `sources/` 中记录每个未签名应用与证书指纹对应的目录,内容不变时复用该目录。临时签名使用独立记录。显式传入证书名称时会重新签名,因为续期可能改变名称对应的证书。
`native/.build/prepared/<arch>` 和 `native/bin/darwin-<arch>` 中的各代应用不会自动清理。正式打包时使用全新的 `--output-directory`,或确认没有客户端使用后清理打包输出再构建,避免旧应用进入 tarball。安全签名时间戳可能让相同源码生成不同代应用。
@@ -117,13 +123,13 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后
<a id="verification"></a>
## 验证
桌面检查要求给 `DSH Computer Use.app` 授权;临时签名的源码构建变化后可能需要重新授权。`--helper` 指向该应用内的可执行文件。裸二进制仅用于旧版本对比,不支持作为当前 helper 的覆盖路径。
桌面检查要求给所选 helper 授权:正式版声明名称 `DSH Computer Use`,开发版声明名称 `DSH Computer Use Dev`。以系统提示为准,临时签名重建后可能需要重新授权。`--helper` 指向该应用内的可执行文件。裸二进制仅用于旧版本对比,不支持作为当前 helper 的覆盖路径。
运行 `python3 packages/experimental/cua-macos/native/tests/startup_e2e.py`,通过 LaunchServices 检查启动即退出、原始错误传递、过期就绪记录拒绝,以及卡住的新实例退出。检查使用自建应用,不申请系统权限。发布单元测试模拟签名;`build:native` 调用真实的 `codesign --verify --strict`,`launcher_identity_e2e.py` 验证 LaunchServices 授权归属。
使用 `python3 packages/experimental/cua-macos/native/tests/test_swift.py` 通过选定 Apple 工具链的 Swift Testing 框架和运行时路径执行离线单元检查;使用 `python3 packages/experimental/cua-macos/native/tests/protocol_e2e.py` 检查 JSONL 接纳、有序回复和 EOF 退出,不执行桌面操作。应用与协议端到端检查接受 `--helper` 以选择单独构建的对比二进制。 `python3 packages/experimental/cua-macos/native/tests/test_build_app.py` 验证应用发布、开发版构建、已签名目录复用、签名失败和损坏副本拒绝。`python3 packages/experimental/cua-macos/native/tests/test_dev_signing.py` 用模拟的 `security` 命令验证身份初始化、解锁和移除。`python3 packages/experimental/cua-macos/native/tests/dev_signing_e2e.py` 创建临时身份,签出两个不同的构建并检查二者的指定要求相同,随后移除身份并核对钥匙串搜索列表已恢复。
运行 `python3 packages/experimental/cua-macos/native/tests/shared_helper_e2e.py --helper /absolute/helper`,通过测试自建的 AppKit fixture 核实并发启动、共享服务 PID、独立句柄、同一应用交接、请求级截图期限、连接清理和信号退出。需要已经给 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。`--without-desktop` 将检查限定为协议与进程生命期。
运行 `python3 packages/experimental/cua-macos/native/tests/shared_helper_e2e.py --helper /absolute/helper`,通过测试自建的 AppKit fixture 核实并发启动、共享服务 PID、独立句柄、同一应用交接、请求级截图期限、连接清理和信号退出。需要已经给所选的正式版或开发版 helper 授予辅助功能和屏幕录制权限。`--without-desktop` 将检查限定为协议与进程生命期。
在已解锁的 macOS GUI 会话中运行 `python3 packages/experimental/cua-macos/native/tests/application_consent_e2e.py --helper /absolute/helper`,需要可用的 Apple Swift 编译器。它创建并清理自己的 AppKit 应用和独立 GUI 进程,检查元数据替换、冷启动与直接启动、共用 Bundle ID、独立程序重启后的持久路径身份,以及删除运行中可执行文件后的选择行为。默认身份检查不需要辅助功能或屏幕录制权限。添加 `--desktop` 可读取完整测试应用的控件,通过状态文件验证 AX 按钮点击,截取窗口,并记录删除可执行文件后的观察结果;此模式要求已有两项系统权限。
@@ -7,6 +7,7 @@ import os
from pathlib import Path
import platform
import plistlib
import re
import shutil
import subprocess
import sys
@@ -46,9 +47,11 @@ def application_info(plist, variant):
def retained(output, key):
"""Return a published generation after checking that its bytes still match its name."""
application = output / key / "DSH Computer Use.app"
if application.exists() and bundle_digest(application) != key:
if not application.exists():
return None
if bundle_digest(application) != key:
raise ValueError(f"Retained helper application does not match its content digest: {application}")
return application if application.exists() else None
return application
def select(output, temporary, key):
@@ -71,12 +74,14 @@ def publish(binary, output, identity, plist, variant="release", keychain=None):
executable.parent.mkdir(parents=True)
shutil.copy2(binary, executable)
(staged / "Contents/Info.plist").write_bytes(application_info(plist, variant))
shutil.copystat(plist, staged / "Contents/Info.plist")
resources = staged / "Contents/Resources"
resources.mkdir()
for filename in ["DSHComputerUse.icns", "LICENSE.computer-use-icon", "LICENSE.cua-driver"]:
shutil.copy2(plist.with_name(filename), resources / filename)
index = None
if variant == "dev":
# Names can resolve to a renewed certificate; only fingerprints identify a stable signing key.
if variant == "dev" and (identity == "-" or re.fullmatch(r"[0-9a-fA-F]{40}", identity)):
source = hashlib.sha256(f"{bundle_digest(staged)}\0{identity}".encode()).hexdigest()
index = output / "sources" / source
if index.is_file():
@@ -117,16 +122,11 @@ def load_dev_signing():
return module
def signing_identity(variant, identity):
"""Resolve the codesign identity and keychain; development builds prefer the local identity."""
if identity is not None or variant == "release":
def signing_identity(variant, identity, signing):
"""Resolve signing without accessing the keychain unless local-identity is explicitly selected."""
if identity is not None or variant == "release" or signing == "ad-hoc":
return identity or "-", None
signing = load_dev_signing()
local = signing.load()
if local is None:
print(f"Computer Use development build is ad-hoc signed; macOS asks for permissions again after each change. "
f"Run {signing.SETUP_COMMAND} once to keep them across rebuilds and checkouts.", file=sys.stderr)
return "-", None
local = load_dev_signing().setup()
return local.sha1, local.keychain
@@ -137,13 +137,15 @@ def main():
parser.add_argument("--scratch-path", type=Path)
parser.add_argument("--output-directory", type=Path)
parser.add_argument("--variant", choices=["release", "dev"], default="release",
help="dev uses a separate bundle identifier and the local development signing identity")
parser.add_argument("--identity", help="codesign identity; release defaults to '-', an ad-hoc build")
help="dev uses a separate bundle identifier")
parser.add_argument("--signing", choices=["ad-hoc", "local-identity"], default="ad-hoc",
help="dev signing mode; local-identity creates or reuses a per-user identity")
parser.add_argument("--identity", help="explicit codesign identity, overriding --signing")
args = parser.parse_args()
architecture = "x64" if args.arch == "x86_64" else "arm64"
scratch = args.scratch_path or root / ".build" / f"runtime-{architecture}"
output = args.output_directory or root / "bin" / f"darwin-{architecture}"
identity, keychain = signing_identity(args.variant, args.identity)
identity, keychain = signing_identity(args.variant, args.identity, args.signing)
subprocess.run(["/usr/bin/xcrun", "swift", "build", "--package-path", str(root),
"--scratch-path", str(scratch), "--configuration", "release",
"--product", "dsh-cua-native", "--arch", args.arch], check=True)
@@ -152,4 +154,8 @@ def main():
if __name__ == "__main__":
main()
try:
main()
except RuntimeError as error:
print(error, file=sys.stderr)
sys.exit(1)
@@ -3,7 +3,7 @@
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, so every build signed by the identity created here keeps it.
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 builds unlock it and sign without a system dialog. Any process running as the same
@@ -11,7 +11,9 @@ user can read that password and sign code that inherits the development grants;
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
@@ -27,6 +29,7 @@ COMMON_NAME = "DSH Computer Use Dev (local)"
SECURITY = "/usr/bin/security"
OPENSSL = "/usr/bin/openssl"
SETUP_COMMAND = "pnpm --dir packages/experimental/cua-macos run dev-signing:setup"
REMOVE_COMMAND = "pnpm --dir packages/experimental/cua-macos run dev-signing:remove"
CERTIFICATE_CONFIG = f"""[req]
distinguished_name = subject
x509_extensions = extensions
@@ -47,12 +50,30 @@ class SigningIdentity:
keychain: Path
def security(*args):
"""Run security without echoing arguments, which can contain keychain passwords."""
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([SECURITY, *args], check=True, capture_output=True, text=True, timeout=60).stdout
return subprocess.run(command, check=True, capture_output=True, text=True, timeout=60, **kwargs).stdout
except subprocess.CalledProcessError as error:
raise RuntimeError(f"security {args[0]} failed: {error.stderr.strip()}") from None
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.with_suffix(".lock"), os.O_WRONLY | os.O_CREAT, 0o600), "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
yield
def user_keychains():
@@ -82,7 +103,13 @@ def load(directory=DEFAULT_DIRECTORY):
record = record_path(directory)
if not record.exists():
return None
fields = json.loads(record.read_text())
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 {SETUP_COMMAND}")
@@ -90,6 +117,8 @@ def load(directory=DEFAULT_DIRECTORY):
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)
@@ -106,9 +135,8 @@ def create_certificate(directory, password):
["pkcs12", "-export", "-inkey", "key.pem", "-in", "certificate.pem", "-out", "identity.p12",
"-passout", f"pass:{export_password}"],
):
subprocess.run([OPENSSL, *command], cwd=work, check=True, capture_output=True, timeout=60)
fingerprint = subprocess.run([OPENSSL, "x509", "-in", "certificate.pem", "-noout", "-fingerprint", "-sha1"],
cwd=work, check=True, capture_output=True, text=True, timeout=60).stdout
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.
@@ -127,13 +155,18 @@ def create_certificate(directory, password):
def setup(directory=DEFAULT_DIRECTORY):
"""Create the identity once and keep its keychain on the user search list."""
with identity_lock(directory):
return setup_locked(directory)
def setup_locked(directory):
keychain = keychain_path(directory)
if record_path(directory).exists() and keychain.is_file():
keychains = user_keychains()
if not listed(keychain, keychains):
security("list-keychains", "-d", "user", "-s", *keychains, str(keychain))
return load(directory)
remove(directory)
remove_locked(directory)
directory.mkdir(mode=0o700, parents=True)
password = secrets.token_hex(32)
sha1 = create_certificate(directory, password)
@@ -148,6 +181,11 @@ def setup(directory=DEFAULT_DIRECTORY):
def remove(directory=DEFAULT_DIRECTORY):
"""Delete the keychain, its search-list entry and the stored password."""
with identity_lock(directory):
remove_locked(directory)
def remove_locked(directory):
keychain = keychain_path(directory)
keychains = user_keychains()
if listed(keychain, keychains):
@@ -160,18 +198,14 @@ def remove(directory=DEFAULT_DIRECTORY):
def main():
parser = argparse.ArgumentParser(description="Manage the local signing identity for source-built Computer Use applications.")
parser.add_argument("action", choices=["setup", "remove", "status"])
parser.add_argument("--directory", type=Path, default=DEFAULT_DIRECTORY, help=argparse.SUPPRESS)
parser.add_argument("action", choices=["setup", "remove"])
args = parser.parse_args()
if args.action == "setup":
identity = setup(args.directory)
print(f"Source builds sign as \"{COMMON_NAME}\" ({identity.sha1}) from {identity.keychain}")
elif args.action == "remove":
remove(args.directory)
print("Removed the development signing identity; source builds return to ad-hoc signatures")
identity = setup()
print(f"Prepared \"{COMMON_NAME}\" ({identity.sha1}); source builds use it when sourceSigning is local-identity")
else:
identity = load(args.directory)
print("not configured" if identity is None else f"{identity.sha1} {identity.keychain}")
remove()
print("Removed the development signing identity; select sourceSigning: ad-hoc to prevent recreation")
if __name__ == "__main__":
@@ -9,6 +9,8 @@ from pathlib import Path
import plistlib
import subprocess
import tempfile
from types import SimpleNamespace
from unittest.mock import patch
NATIVE = Path(__file__).resolve().parents[1]
@@ -32,12 +34,17 @@ def main():
root = Path(temporary)
directory = root / "signing"
try:
identity = signing.setup(directory)
local_signing = SimpleNamespace(setup=lambda: signing.setup(directory))
with patch.object(builder, "load_dev_signing", return_value=local_signing):
sha1, keychain = builder.signing_identity("dev", None, "local-identity")
assert builder.signing_identity("dev", None, "local-identity") == (sha1, keychain)
with patch.object(builder, "load_dev_signing", side_effect=AssertionError("ad-hoc accessed keychain")):
assert builder.signing_identity("dev", None, "ad-hoc") == ("-", None)
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 / "output", identity.sha1, NATIVE / "Info.plist", "dev", identity.keychain)
executable = builder.publish(root / "helper", root / f"checkout-{status}", sha1, NATIVE / "Info.plist", "dev", keychain)
application = executable.parents[2]
subprocess.run(["/usr/bin/codesign", "--verify", "--strict", str(application)], check=True)
info = plistlib.loads((application / "Contents/Info.plist").read_bytes())
@@ -48,7 +55,7 @@ def main():
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 / "output/current.json").read_text())["bundle"]
selected = json.loads((root / "checkout-1/current.json").read_text())["bundle"]
assert second.parent.name == selected
print(f"PASS: changed development builds share {first_requirement}")
finally:
@@ -8,7 +8,7 @@ import plistlib
import secrets
import tempfile
import unittest
from unittest.mock import patch
from unittest.mock import Mock, patch
spec = importlib.util.spec_from_file_location("build_app", Path(__file__).resolve().parents[1] / "build_app.py")
builder = importlib.util.module_from_spec(spec)
@@ -150,6 +150,19 @@ class DevelopmentPublicationTests(PublicationCases, unittest.TestCase):
self.assertEqual(json.loads((self.output / "current.json").read_text())["bundle"], first.parents[3].name)
self.assertNotEqual(second, first)
def test_named_identities_are_resigned_in_case_the_certificate_was_renewed(self):
first = self.publish("Apple Development: Example")
self.assertNotEqual(self.publish("Apple Development: Example"), first)
self.assertEqual(len(self.signings()), 2)
def test_switching_between_ad_hoc_and_local_identity_selects_the_matching_generation(self):
ad_hoc = self.publish("-")
local = self.publish()
self.assertNotEqual(local, ad_hoc)
self.assertEqual(self.publish("-"), ad_hoc)
self.assertEqual(self.publish(), local)
self.assertEqual(len(self.signings()), 2)
def test_another_identity_signs_the_same_content_again(self):
first = self.publish()
other = self.publish("FEDCBA9876543210FEDCBA9876543210FEDCBA98")
@@ -158,27 +171,42 @@ class DevelopmentPublicationTests(PublicationCases, unittest.TestCase):
class SigningIdentityTests(unittest.TestCase):
def resolve(self, variant, identity, local):
signing = type("Signing", (), {"SETUP_COMMAND": "setup-command", "load": staticmethod(lambda: local)})
errors = io.StringIO()
with patch.object(builder, "load_dev_signing", return_value=signing), contextlib.redirect_stderr(errors):
return builder.signing_identity(variant, identity), errors.getvalue()
def test_default_and_release_builds_never_load_a_local_identity(self):
with patch.object(builder, "load_dev_signing") as load:
for variant, mode in (("dev", "ad-hoc"), ("release", "ad-hoc"), ("release", "local-identity")):
self.assertEqual(builder.signing_identity(variant, None, mode), ("-", None))
load.assert_not_called()
def test_release_builds_stay_ad_hoc_unless_an_identity_is_named(self):
self.assertEqual(self.resolve("release", None, None), (("-", None), ""))
self.assertEqual(self.resolve("release", "Developer ID Application: Example", None)[0], ("Developer ID Application: Example", None))
def test_development_builds_use_the_configured_local_identity(self):
def test_local_identity_builds_create_or_reuse_the_identity(self):
local = type("Identity", (), {"sha1": "ABC", "keychain": Path("/keychains/dev.keychain-db")})
self.assertEqual(self.resolve("dev", None, local), (("ABC", Path("/keychains/dev.keychain-db")), ""))
signing = Mock()
signing.setup.return_value = local
with patch.object(builder, "load_dev_signing", return_value=signing):
self.assertEqual(builder.signing_identity("dev", None, "local-identity"), ("ABC", local.keychain))
signing.setup.assert_called_once_with()
def test_an_explicit_identity_overrides_the_local_development_identity(self):
self.assertEqual(self.resolve("dev", "Apple Development: Example", None), (("Apple Development: Example", None), ""))
def test_an_explicit_identity_overrides_either_signing_mode(self):
with patch.object(builder, "load_dev_signing") as load:
for mode in ("ad-hoc", "local-identity"):
self.assertEqual(builder.signing_identity("dev", "Apple Development: Example", mode),
("Apple Development: Example", None))
load.assert_not_called()
def test_unconfigured_development_builds_are_ad_hoc_and_name_the_setup_command(self):
(identity, errors) = self.resolve("dev", None, None)
self.assertEqual(identity, ("-", None))
self.assertIn("setup-command", errors)
def test_local_identity_failure_does_not_fall_back_to_ad_hoc(self):
signing = Mock()
signing.setup.side_effect = RuntimeError("identity unavailable")
with patch.object(builder, "load_dev_signing", return_value=signing):
with self.assertRaisesRegex(RuntimeError, "identity unavailable"):
builder.signing_identity("dev", None, "local-identity")
def test_command_line_defaults_to_ad_hoc_and_passes_the_selected_mode(self):
for flags, mode in (([], "ad-hoc"), (["--signing", "local-identity"], "local-identity")):
with patch.object(builder.sys, "argv", ["build_app.py", "--variant", "dev", *flags]), \
patch.object(builder, "signing_identity", return_value=("-", None)) as identity, \
patch.object(builder.subprocess, "run"), patch.object(builder, "publish", return_value="helper"), \
contextlib.redirect_stdout(io.StringIO()):
builder.main()
identity.assert_called_once_with("dev", None, mode)
if __name__ == "__main__":
@@ -2,6 +2,8 @@
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
@@ -25,6 +27,8 @@ class FakeSecurity:
self.keychains = list(args[4:])
if args[0] == "delete-keychain":
Path(args[1]).unlink()
if args[0] == "find-identity":
return "ABC123 NEW456"
return ""
@@ -104,6 +108,77 @@ class DevelopmentSigningTests(unittest.TestCase):
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, then .*setup"):
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.with_suffix(".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_build_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], '--variant', 'dev', '--signing', 'local-identity']
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__).with_name("build_app.py")), 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()
+2 -2
View File
@@ -12,7 +12,7 @@ export { GUIDANCE } from './guidance.ts'
export const name = 'experimental-cua-macos'
/** Services required by the shared CUA executor and the native launcher. */
export const inject = ['computerUse', 'tools', 'systemPrompt', 'subprocess', 'agents']
/** Native preparation, operation bounds, and profile-local application grants. */
/** Native preparation, source-build signing, operation bounds, and profile-local application grants. */
export type Config = CuaConfig
/** Validate the shared configuration before preparing the macOS helper. */
export const Config: typeof CuaConfig = CuaConfig
@@ -35,7 +35,7 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
const controller = new AbortController()
const prepared = prepareNativeExecutable({
packageRoot: resolve(fileURLToPath(new URL('..', import.meta.url))),
architecture, subprocess: ctx.subprocess,
architecture, sourceSigning: config.sourceSigning, subprocess: ctx.subprocess,
timeoutMs: config.buildTimeoutMs, graceMs: config.graceMs, signal: controller.signal,
})
ctx.effect(() => async () => {
@@ -3,6 +3,7 @@ import { constants } from 'node:fs'
import { access, mkdir, readFile } from 'node:fs/promises'
import { join, resolve } from 'node:path'
import { withFileLock } from '@deepseek-ai/dsh-atomic-write'
import type { CuaConfig } from '@deepseek-ai/dsh-cua'
import type { SubprocessOutcome, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess'
import { z } from 'zod'
@@ -27,6 +28,8 @@ export function nativeHostArchitecture(platform: string, architecture: string):
export interface NativeBuildSpec {
packageRoot: string
architecture: NativeArchitecture
/** Signature of a source-checkout build; installed packages ignore it. */
sourceSigning: CuaConfig['sourceSigning']
subprocess: Pick<SubprocessRuntime, 'spawn'>
signal: AbortSignal
timeoutMs: number
@@ -65,7 +68,7 @@ export async function isSourcePackage(packageRoot: string): Promise<boolean> {
/**
* Build and sign an immutable development helper application with the selected Apple developer tools.
* The development variant has its own bundle identifier and uses the local development signing identity when configured.
* The development variant has its own bundle identifier and the signature selected by `spec.sourceSigning`.
* @param spec - Checkout, target, managed process provider and cancellation/deadline limits.
* @returns Executable inside the prepared application, after complete compiler cleanup.
* @throws When preparation, cancellation, resource cleanup or receipt validation fails.
@@ -80,7 +83,7 @@ export async function buildNativeExecutable(spec: NativeBuildSpec): Promise<stri
const handle = spec.subprocess.spawn({
argv: ['/usr/bin/xcrun', 'python3', join(nativeRoot, 'build_app.py'),
'--scratch-path', join(nativeRoot, '.build', `runtime-${spec.architecture}`),
'--output-directory', directory, '--arch', spec.architecture === 'x64' ? 'x86_64' : 'arm64', '--variant', 'dev'],
'--output-directory', directory, '--arch', spec.architecture === 'x64' ? 'x86_64' : 'arm64', '--variant', 'dev', '--signing', spec.sourceSigning],
cwd: spec.packageRoot, signal, graceMs: spec.graceMs,
stdio: { stdin: 'ignore', stdout: { maxBytes: 65_536 }, stderr: { maxBytes: 65_536 } },
})
@@ -41,7 +41,7 @@ async function fixture(diagnostics = true) {
return outcome
})(), terminate, waitForExit,
}))
const spec = { packageRoot, architecture: 'arm64' as const, subprocess: { spawn }, signal: controller.signal, timeoutMs: 60_000, graceMs: 100 }
const spec = { packageRoot, architecture: 'arm64' as const, sourceSigning: 'ad-hoc' as const, subprocess: { spawn }, signal: controller.signal, timeoutMs: 60_000, graceMs: 100 }
const directory = join(packageRoot, 'native/.build/prepared/arm64')
return { root, spec, directory, spawn, output, controller, terminate, waitForExit,
setOutput: (value: Buffer) => { output = value },
@@ -77,7 +77,7 @@ it('builds the development variant and returns its executable only after the man
expect(f.spawn.mock.calls[0]![0].argv).toEqual([
'/usr/bin/xcrun', 'python3', join(f.spec.packageRoot, 'native/build_app.py'),
'--scratch-path', join(f.spec.packageRoot, 'native/.build/runtime-arm64'),
'--output-directory', f.directory, '--arch', 'arm64', '--variant', 'dev',
'--output-directory', f.directory, '--arch', 'arm64', '--variant', 'dev', '--signing', 'ad-hoc',
])
expect(f.terminate).toHaveBeenCalledTimes(1)
expect(f.waitForExit).toHaveBeenCalledTimes(1)
@@ -86,15 +86,16 @@ it('builds the development variant and returns its executable only after the man
it('checks source builds on activation and maps Intel architecture to the compiler target', async () => {
const f = await fixture()
await writeFile(join(f.root, 'package.json'), '{"name":"@deepseek-ai/dsh-root"}')
const path = await prepareNativeExecutable({ ...f.spec, architecture: 'x64' })
const path = await prepareNativeExecutable({ ...f.spec, architecture: 'x64', sourceSigning: 'local-identity' })
expect(f.spawn.mock.calls[0]![0].argv).toContain('x86_64')
expect(f.spawn.mock.calls[0]![0].argv.slice(-2)).toEqual(['--signing', 'local-identity'])
expect(path).toContain(join('native', '.build', 'prepared', 'x64'))
})
it('uses an installed application without compiling or re-signing it', async () => {
it('ignores local-identity for an installed application without compiling or re-signing it', async () => {
const f = await fixture()
const path = await publish(join(f.spec.packageRoot, 'native/bin/darwin-arm64'), f.output)
expect(await prepareNativeExecutable(f.spec)).toBe(path)
expect(await prepareNativeExecutable({ ...f.spec, sourceSigning: 'local-identity' })).toBe(path)
expect(f.spawn).not.toHaveBeenCalled()
f.controller.abort()
await expect(prepareNativeExecutable(f.spec)).rejects.toThrow()
@@ -60,12 +60,18 @@ vi.mock('@deepseek-ai/dsh-cua/native-client', async importOriginal => ({
const config = {
agentPreset: false,
helperPath: resolve('fixture-helper'), buildTimeoutMs: 300_000, timeoutMs: 10_000, connectTimeoutMs: 5000, screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 1024, maxResponseBytes: 4096, maxClipboardBytes: 8192, pasteReadTimeoutMs: 1000, maxAppMatches: 20,
helperPath: resolve('fixture-helper'), sourceSigning: 'local-identity', buildTimeoutMs: 300_000, timeoutMs: 10_000, connectTimeoutMs: 5000, screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 1024, maxResponseBytes: 4096, maxClipboardBytes: 8192, pasteReadTimeoutMs: 1000, maxAppMatches: 20,
graceMs: 10, textEventIntervalMs: 8, maxClickHoldMs: 7000, maxElements: 64, maxDepth: 8, dragDurationMs: 200, dragSteps: 10,
} satisfies Omit<NativeProvider.Config, 'allowedApps'>
const { helperPath: _helperPath, ...automaticConfig } = config
it('defaults source builds to ad-hoc signatures and accepts only the two signing choices', () => {
expect(NativeProvider.Config({}).sourceSigning).toBe('ad-hoc')
expect(NativeProvider.Config({ sourceSigning: 'local-identity' }).sourceSigning).toBe('local-identity')
expect(() => NativeProvider.Config(JSON.parse('{"sourceSigning":"developer-id"}'))).toThrow()
})
it('defaults the explicit click hold limit to five seconds and accepts a configured zero or larger limit', () => {
expect(NativeProvider.Config({}).maxClickHoldMs).toBe(5000)
for (const maxClickHoldMs of [0, 7000]) expect(NativeProvider.Config({ maxClickHoldMs }).maxClickHoldMs).toBe(maxClickHoldMs)
@@ -582,6 +588,7 @@ it('prepares the selected native component before registering CUA and creates no
native.prepare.mockReset().mockResolvedValue(resolve('prepared-helper'))
await NativeProvider.apply(f.ctx, { ...automaticConfig, allowedApps: [] })
expect(native.prepare).toHaveBeenCalledTimes(1)
expect(native.prepare.mock.calls[0]![0].sourceSigning).toBe('local-identity')
expect(native.instances).toHaveLength(0)
await f.execute()
expect(native.instances).toHaveLength(1)
+2 -2
View File
@@ -21,8 +21,8 @@
en: deb4ec91b186399e
zh: 7febe3b08dbb185e
/deepseek-ai-dsh-cua/understand-the-implementation:
en: 951d9a3b925de34a
zh: f3444e127953a63f
en: a8caacb0d3347ce0
zh: b1a392d54599fe95
/deepseek-ai-dsh-cua/further-exploration:
en: 166e3c1f9a67f753
zh: 698c5136c5350052
+2
View File
@@ -80,6 +80,8 @@ The provider calls [installCua](src/index.ts) with its prepared helper, connecti
The root Host entry exports `installCua`, `CuaConfig`, and the Typert-discovered `CuaAccess` service; its `apply()` only marks the optional Client contribution. `/client` loads the permission UI through the existing module loader. Separate Host and Client compiler projects keep React, CSS, and browser registrations out of headless imports. `/api` owns the app/window API and its types; `/bridge`, `/native-client`, and `/protocol` retain runtime and platform consumers. `/types` exports only the four named boundary types required by generated Remote declarations. The Client uses package-local types. `/typert` supplies Host reflection and `/remote` supplies generated browser descriptors and codecs; permission authority remains on the Host.
The [macOS provider](../cua-macos/README.md#use-this-package) interprets `CuaConfig.sourceSigning` to select ad-hoc or local-identity signing for source-built helpers.
The optional browser contribution mounts the native provider's permission Remote and reuses the Plugins activation and configuration slots. The four setup rows remain visible while unknown fields use placeholders; the same permission-management guidance remains visible while queries settle and after access is granted, including when the text wraps. The default-mode form, runtime configuration, system checks, application decisions, and application icons fill in as each query completes. Application names and actions do not wait for icons; icon positions retain their space. User actions run in order without waiting for pending observation queries. Disposal waits for both actions and queries to settle before releasing the separately owned Remote mount. Known query errors and read-only settings stay visible while management operations or retries run, with their actions disabled. Query errors stay with the affected section, and activation guidance depends only on system checks. The injection layer observes Plugin Manager operations independently of the page. Bundle and row changes pause all four queries and invalidate in-flight results; settlement refreshes observations even after the page closes. Last known errors remain until a successful read. Disposal discards late results. The controller consumes the generated `ctx.remote.cuaAccess` namespace directly and handles unsuccessful Remote results in its existing query and action paths. It projects queries into the page and setup dialog; reconnects refresh it. Page entry, focus and completed actions read the current permission store. Operation notices live in the shell overlay, so closing the page does not remove them. The provider owns permission checks, persisted decisions, and cancellation; the browser owns no authorization state.
The detail page reads the effective default (`selectedDefault ?? default`) from the existing `configForms` service. The default button writes only `selectedDefault` through the form's revision-checked settings path. The execution-mode row uses CUA's `ptcConfiguration()` and `enablePersistentPtc()` controls: persistence follows the loaded runtime's `retainsState`. Enabling persistence preserves an active Script evaluator and writes `executionMode` and `scriptPersistence` together through the configuration editor; other modes select the retained REPL with Script persistence disabled. The ordinary Loader reload lifecycle applies. Permission checks and runtime state settle independently. Loading, read-only and unavailable settings cannot submit a change; a failed write remains beside the setting for retry.
+2
View File
@@ -80,6 +80,8 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
根 Host 入口导出 `installCua`、`CuaConfig` 和供 Typert 发现的 `CuaAccess` 服务,`apply()` 只标记可选 Client 贡献。`/client` 通过现有模块加载器加载权限界面。Host 和 Client 使用独立编译项目,headless 导入不会加载 React、CSS 或浏览器注册。`/api` 提供应用、窗口 API 及其类型;`/bridge`、`/native-client` 和 `/protocol` 保留运行时和平台消费者。`/types` 仅导出生成 Remote 声明所需的四个命名类型,Client 使用包内类型。`/typert` 提供 Host 反射,`/remote` 提供浏览器描述和编解码,权限判断仍由 Host 执行。
`CuaConfig.sourceSigning` 由 [macOS provider](../cua-macos/README.zh.md#use-this-package) 解释,控制源码 helper 的临时签名或本机固定签名。
可选浏览器插件挂载原生 provider 的权限 Remote,复用插件页的启用引导和配置插槽。四排使用条件始终可见,未加载的字段保留占位;查询期间和权限已允许时显示相同的权限管理说明,换行也不会改变内容。默认模式、执行方式、系统权限、应用列表和应用图标分别查询,结果返回后各自显示。应用名称和操作按钮不等待图标,图标位置保留空位。用户操作按顺序执行,不等待尚未完成的查询;卸载时等待操作和查询全部结束,再释放独立持有的 Remote 挂载。已知查询错误和只读设置提示在管理操作或重试期间保持可见,操作按钮禁用。查询错误只显示在对应部分,启用引导只等待系统权限结果。注入层独立于页面观察插件管理操作。组合包和组件行变更会暂停四项查询,并使进行中的结果失效;操作结束后即使页面已关闭,也会重新查询。已知错误保留至读取成功;卸载后的迟到结果会被丢弃。控制器直接接收生成的 `ctx.remote.cuaAccess`,在现有查询和操作流程中处理失败响应,并把查询结果投影到页面和设置弹窗;重新连接时刷新状态。进入页面、窗口聚焦或操作完成后读取当前授权存储。操作提示挂载到 shell overlay,关闭页面后仍可显示。provider 负责权限检查、持久授权和取消;浏览器不保存授权决定。
详情页通过现有 `configForms` 服务读取实际默认值(`selectedDefault ?? default`)。默认模式按钮仅写入 `selectedDefault`,沿用表单带版本检查的设置写入流程。执行方式一行调用 CUA 的 `ptcConfiguration()` 和 `enablePersistentPtc()`,根据已加载运行时的 `retainsState` 判断状态保留。启用持久化时保留正在使用的 Script 求值器,并通过配置编辑器同时写入 `executionMode` 和 `scriptPersistence`;其他模式选择保留状态的 REPL,并关闭 Script 状态保留。操作沿用普通 Loader 重载规则。权限检查和执行方式状态独立返回。设置仍在加载、只读或不可用时不能提交;写入失败时在设置旁显示错误,供用户重试。
+7
View File
@@ -41,6 +41,12 @@ export interface CuaConfig {
}>
/** Absolute executable inside the signed macOS helper .app; omission prepares the package-owned application. */
helperPath?: string
/**
* Signature of a helper compiled from a DSH source checkout. `ad-hoc` binds macOS grants to the code hash, so changed or
* clean builds ask again. `local-identity` creates or reuses a per-user self-signed identity shared by
* builds that select it. Installed packages and `helperPath` keep their own signature.
*/
sourceSigning: 'ad-hoc' | 'local-identity'
/** Maximum time in milliseconds for native component preparation. */
buildTimeoutMs: number
/** Deadline for one native operation, including capture and AX traversal. */
@@ -85,6 +91,7 @@ export const CuaConfig = Schema.object({
name: Schema.string().required(), executablePath: Schema.string().min(1),
})).default([]),
helperPath: Schema.string(),
sourceSigning: Schema.union([Schema.const('ad-hoc'), Schema.const('local-identity')]).default('ad-hoc'),
buildTimeoutMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(300_000),
timeoutMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(30_000),
connectTimeoutMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(5000),