From 15c9e6006be2ad3c75bf084eef62bf9f634b6a22 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Mon, 26 Oct 2026 11:26:05 +0800 Subject: [PATCH 01/55] fix(prompt): name line ranges and shell readers in the read guidance Restore the 2026-10-13 wording removed together with a later prompt revert: sed, head, and tail join cat as shell commands the read tool replaces, and offset/limit now describes reading a line range. The unit expectation for the rendered guidance follows. --- packages/fs/tool-fs/src/read.ts | 2 +- packages/fs/tool-fs/tests/tools.spec.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/fs/tool-fs/src/read.ts b/packages/fs/tool-fs/src/read.ts index a5a747c776..22c2dc52c9 100644 --- a/packages/fs/tool-fs/src/read.ts +++ b/packages/fs/tool-fs/src/read.ts @@ -71,7 +71,7 @@ export function applyReadTool(ctx: Context, caps: ReadToolCaps): void { order: ctx.systemPrompt.getSectionOrder('TOOL_READ'), text: ({ scope }) => ctx.tools.get('read', scope) === undefined ? '' - : 'Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files.', + : '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.', }) ctx.tools.register(defineTool({ diff --git a/packages/fs/tool-fs/tests/tools.spec.ts b/packages/fs/tool-fs/tests/tools.spec.ts index 1f2c83d951..1d28251bd8 100644 --- a/packages/fs/tool-fs/tests/tools.spec.ts +++ b/packages/fs/tool-fs/tests/tools.spec.ts @@ -1077,7 +1077,7 @@ async function guidanceScope(ctx: Context) { } const originalGuidance = { - read: 'Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files.', + read: '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.', write: 'Read an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes.', edit: 'Read a file before editing it (the default fs-observation-policy requires it), unless you just created or edited it in this session.', } From c74015c81e35bc2d87e57e7af3e07b0f48554eee Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Mon, 26 Oct 2026 11:26:43 +0800 Subject: [PATCH 02/55] test(snapshot): re-render expected prompts and the read guidance fence 89 recorded system prompts carry the restored sentence; the two pinned historical sidecars keep their recorded text. The package README fence is updated in both languages. --- packages/fs/tool-fs/README.md | 2 +- packages/fs/tool-fs/README.zh.md | 2 +- .../sdk/background-wait-steer/system-prompt.expected.md | 2 +- snapshots/sdk/bash-tool/system-prompt.expected.md | 2 +- snapshots/sdk/desktop-context/system-prompt.expected.md | 2 +- snapshots/sdk/desktop-ptc-context/system-prompt.expected.md | 2 +- snapshots/sdk/session-resume/system-prompt.expected.md | 4 ++-- .../subagent-activation-limit/system-prompt.1.expected.md | 2 +- .../system-prompt.1.expected.md | 2 +- .../sdk/subagent-continuable/system-prompt.1.expected.md | 2 +- .../subagent-dsh-sdk-diagnostic/system-prompt.expected.md | 2 +- .../system-prompt.1.expected.md | 2 +- .../system-prompt.expected.md | 2 +- .../sdk/subagent-list-agents/system-prompt.1.expected.md | 2 +- .../sdk/subagent-send-message/system-prompt.1.expected.md | 2 +- snapshots/sdk/text-turn/system-prompt.expected.md | 2 +- snapshots/sdk/tool-error-details/system-prompt.expected.md | 4 ++-- .../session/advanced-toolchain/system-prompt.1.expected.md | 2 +- .../session/advanced-toolchain/system-prompt.2.expected.md | 2 +- .../session/advanced-toolchain/system-prompt.expected.md | 6 +++--- .../session/agent-instructions/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 +- snapshots/session/both-mode-turn/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 +- .../browser-use-playwright-mcp/system-prompt.expected.md | 2 +- .../browser-use-stagehand-native/system-prompt.expected.md | 2 +- .../session/claude-code-mods/system-prompt.expected.md | 2 +- .../session/compaction-recovery/system-prompt.expected.md | 2 +- .../computer-use-cua-driver-mcp/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 +- .../session/cordis-inspect-jsdoc/system-prompt.expected.md | 2 +- snapshots/session/cua-native/system-prompt.expected.md | 2 +- snapshots/session/cua-ptc/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 4 ++-- .../system-prompt.expected.md | 4 ++-- .../dynamic-tool-prompt-updates/system-prompt.expected.md | 4 ++-- .../session/dynamic-tool-updates/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 +- .../session/fs-glob-sampling/system-prompt.expected.md | 2 +- .../in-history-series-start/system-prompt.expected.md | 4 ++-- snapshots/session/lsp-definition/system-prompt.expected.md | 2 +- .../session/mcp-resources-ptc/system-prompt.expected.md | 2 +- snapshots/session/mcp-resources/system-prompt.expected.md | 2 +- .../model-switch-compaction/system-prompt.expected.md | 4 ++-- .../session/model-switch-notice/system-prompt.expected.md | 4 ++-- .../session/multimodal-spill-ends/system-prompt.expected.md | 2 +- .../office-authoring-checker/system-prompt.expected.md | 2 +- .../office-progressive-native/system-prompt.expected.md | 2 +- .../office-progressive-ptc/system-prompt.expected.md | 2 +- .../office-sidecar-instructions/system-prompt.expected.md | 2 +- snapshots/session/office-skills/system-prompt.expected.md | 2 +- .../persistent-pwsh-tool-turn/system-prompt.expected.md | 2 +- .../pi-ai-conversation-updates/system-prompt.expected.md | 4 ++-- .../session/plugin-manager-mcp/system-prompt.expected.md | 4 ++-- snapshots/session/plugin-manager/system-prompt.expected.md | 2 +- .../session/product-subagent-both/system-prompt.expected.md | 2 +- .../product-subagent-codex/system-prompt.expected.md | 2 +- .../session/product-subagent-oar/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 +- snapshots/session/provider-cwd/system-prompt.expected.md | 2 +- .../session/ptc-node-read-only/system-prompt.expected.md | 2 +- .../session/ptc-node-workspace/system-prompt.expected.md | 2 +- snapshots/session/ptc-persistent/system-prompt.expected.md | 2 +- .../session/ptc-policy-change/system-prompt.expected.md | 2 +- snapshots/session/ptc-python-turn/system-prompt.expected.md | 2 +- snapshots/session/ptc-read-image/system-prompt.expected.md | 2 +- snapshots/session/ptc-turn/system-prompt.expected.md | 2 +- .../pty-tools-sandbox-backend/system-prompt.expected.md | 2 +- snapshots/session/pwsh-tool-turn/system-prompt.expected.md | 2 +- snapshots/session/ralph-loop/system-prompt.1.expected.md | 2 +- snapshots/session/ralph-loop/system-prompt.2.expected.md | 2 +- snapshots/session/ralph-loop/system-prompt.expected.md | 2 +- snapshots/session/read-image/system-prompt.expected.md | 2 +- .../session/session-query-spill/system-prompt.expected.md | 2 +- .../subagent-acp-diagnostic/system-prompt.expected.md | 2 +- .../subagent-agent-preset/system-prompt.1.expected.md | 2 +- .../subagent-structured-parent/system-prompt.1.expected.md | 2 +- .../system-prompt-in-history/system-prompt.expected.md | 4 ++-- snapshots/session/team-targets/system-prompt.expected.md | 2 +- snapshots/session/text-turn/system-prompt.expected.md | 2 +- snapshots/session/web-fetch/system-prompt.expected.md | 2 +- .../web-search-unconfigured/system-prompt.expected.md | 2 +- .../session/workflow-confinement/system-prompt.expected.md | 2 +- .../workspace-dependencies/system-prompt.expected.md | 2 +- snapshots/session/worktree/system-prompt.expected.md | 2 +- .../web/creation-recommendations/system-prompt.expected.md | 2 +- snapshots/web/fresh-round-trip/system-prompt.expected.md | 2 +- .../web/official-subagent-bundle/system-prompt.expected.md | 2 +- .../web/optional-string-editor/system-prompt.expected.md | 2 +- .../web/plugin-recommendations/system-prompt.expected.md | 2 +- snapshots/web/ptc-round/system-prompt.expected.md | 2 +- 91 files changed, 104 insertions(+), 104 deletions(-) diff --git a/packages/fs/tool-fs/README.md b/packages/fs/tool-fs/README.md index e6e2d27144..5e8ba11ffe 100644 --- a/packages/fs/tool-fs/README.md +++ b/packages/fs/tool-fs/README.md @@ -147,7 +147,7 @@ At assembly time, each guidance section checks `ctx.tools.get(name, scope)` and ##### Read guidance ```markdown -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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. ``` ##### Write guidance diff --git a/packages/fs/tool-fs/README.zh.md b/packages/fs/tool-fs/README.zh.md index 82b68d2fe0..d7b3eab61f 100644 --- a/packages/fs/tool-fs/README.zh.md +++ b/packages/fs/tool-fs/README.zh.md @@ -147,7 +147,7 @@ kind: "package-reference" ##### Read 指导 ```markdown -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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. ``` ##### Write 指导 diff --git a/snapshots/sdk/background-wait-steer/system-prompt.expected.md b/snapshots/sdk/background-wait-steer/system-prompt.expected.md index 86a2cff4e4..c2439536ef 100644 --- a/snapshots/sdk/background-wait-steer/system-prompt.expected.md +++ b/snapshots/sdk/background-wait-steer/system-prompt.expected.md @@ -6,7 +6,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/bash-tool/system-prompt.expected.md b/snapshots/sdk/bash-tool/system-prompt.expected.md index 6288c22387..9d6dac39d5 100644 --- a/snapshots/sdk/bash-tool/system-prompt.expected.md +++ b/snapshots/sdk/bash-tool/system-prompt.expected.md @@ -4,7 +4,7 @@ You are a coding agent powered by the deepseek-v4-flash model. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/desktop-context/system-prompt.expected.md b/snapshots/sdk/desktop-context/system-prompt.expected.md index 86a2cff4e4..c2439536ef 100644 --- a/snapshots/sdk/desktop-context/system-prompt.expected.md +++ b/snapshots/sdk/desktop-context/system-prompt.expected.md @@ -6,7 +6,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md b/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md index 69ace6433c..6a6ded0f71 100644 --- a/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md +++ b/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md @@ -8,7 +8,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/session-resume/system-prompt.expected.md b/snapshots/sdk/session-resume/system-prompt.expected.md index edee628694..ebfa6ae4cb 100644 --- a/snapshots/sdk/session-resume/system-prompt.expected.md +++ b/snapshots/sdk/session-resume/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -40,7 +40,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/subagent-activation-limit/system-prompt.1.expected.md b/snapshots/sdk/subagent-activation-limit/system-prompt.1.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/sdk/subagent-activation-limit/system-prompt.1.expected.md +++ b/snapshots/sdk/subagent-activation-limit/system-prompt.1.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/subagent-continuable-inheritance/system-prompt.1.expected.md b/snapshots/sdk/subagent-continuable-inheritance/system-prompt.1.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/sdk/subagent-continuable-inheritance/system-prompt.1.expected.md +++ b/snapshots/sdk/subagent-continuable-inheritance/system-prompt.1.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/subagent-continuable/system-prompt.1.expected.md b/snapshots/sdk/subagent-continuable/system-prompt.1.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/sdk/subagent-continuable/system-prompt.1.expected.md +++ b/snapshots/sdk/subagent-continuable/system-prompt.1.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/subagent-dsh-sdk-diagnostic/system-prompt.expected.md b/snapshots/sdk/subagent-dsh-sdk-diagnostic/system-prompt.expected.md index 557223b560..19327b18a7 100644 --- a/snapshots/sdk/subagent-dsh-sdk-diagnostic/system-prompt.expected.md +++ b/snapshots/sdk/subagent-dsh-sdk-diagnostic/system-prompt.expected.md @@ -4,7 +4,7 @@ You are a coding agent powered by the deepseek-v4-flash model. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/subagent-dsh-sdk-dynamic-route/system-prompt.1.expected.md b/snapshots/sdk/subagent-dsh-sdk-dynamic-route/system-prompt.1.expected.md index 88216ca091..30fc27f25e 100644 --- a/snapshots/sdk/subagent-dsh-sdk-dynamic-route/system-prompt.1.expected.md +++ b/snapshots/sdk/subagent-dsh-sdk-dynamic-route/system-prompt.1.expected.md @@ -4,7 +4,7 @@ Echo where you run. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/subagent-dsh-sdk-dynamic-route/system-prompt.expected.md b/snapshots/sdk/subagent-dsh-sdk-dynamic-route/system-prompt.expected.md index 312d216243..19ed1747e3 100644 --- a/snapshots/sdk/subagent-dsh-sdk-dynamic-route/system-prompt.expected.md +++ b/snapshots/sdk/subagent-dsh-sdk-dynamic-route/system-prompt.expected.md @@ -4,7 +4,7 @@ You are a coding agent powered by the mock-delegate model. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/subagent-list-agents/system-prompt.1.expected.md b/snapshots/sdk/subagent-list-agents/system-prompt.1.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/sdk/subagent-list-agents/system-prompt.1.expected.md +++ b/snapshots/sdk/subagent-list-agents/system-prompt.1.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/subagent-send-message/system-prompt.1.expected.md b/snapshots/sdk/subagent-send-message/system-prompt.1.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/sdk/subagent-send-message/system-prompt.1.expected.md +++ b/snapshots/sdk/subagent-send-message/system-prompt.1.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/text-turn/system-prompt.expected.md b/snapshots/sdk/text-turn/system-prompt.expected.md index 6288c22387..9d6dac39d5 100644 --- a/snapshots/sdk/text-turn/system-prompt.expected.md +++ b/snapshots/sdk/text-turn/system-prompt.expected.md @@ -4,7 +4,7 @@ You are a coding agent powered by the deepseek-v4-flash model. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/tool-error-details/system-prompt.expected.md b/snapshots/sdk/tool-error-details/system-prompt.expected.md index aca0bd51a7..de964eee33 100644 --- a/snapshots/sdk/tool-error-details/system-prompt.expected.md +++ b/snapshots/sdk/tool-error-details/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -42,7 +42,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/advanced-toolchain/system-prompt.1.expected.md b/snapshots/session/advanced-toolchain/system-prompt.1.expected.md index c776c30451..96c21c3c36 100644 --- a/snapshots/session/advanced-toolchain/system-prompt.1.expected.md +++ b/snapshots/session/advanced-toolchain/system-prompt.1.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/advanced-toolchain/system-prompt.2.expected.md b/snapshots/session/advanced-toolchain/system-prompt.2.expected.md index c776c30451..96c21c3c36 100644 --- a/snapshots/session/advanced-toolchain/system-prompt.2.expected.md +++ b/snapshots/session/advanced-toolchain/system-prompt.2.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/advanced-toolchain/system-prompt.expected.md b/snapshots/session/advanced-toolchain/system-prompt.expected.md index 46dd5fe0a4..16c4ac1b27 100644 --- a/snapshots/session/advanced-toolchain/system-prompt.expected.md +++ b/snapshots/session/advanced-toolchain/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -42,7 +42,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -596,7 +596,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/agent-instructions/system-prompt.expected.md b/snapshots/session/agent-instructions/system-prompt.expected.md index c776c30451..96c21c3c36 100644 --- a/snapshots/session/agent-instructions/system-prompt.expected.md +++ b/snapshots/session/agent-instructions/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/background-confinement-failure/system-prompt.expected.md b/snapshots/session/background-confinement-failure/system-prompt.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/session/background-confinement-failure/system-prompt.expected.md +++ b/snapshots/session/background-confinement-failure/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/both-mode-turn/system-prompt.expected.md b/snapshots/session/both-mode-turn/system-prompt.expected.md index ed5922ee4f..fd99e781df 100644 --- a/snapshots/session/both-mode-turn/system-prompt.expected.md +++ b/snapshots/session/both-mode-turn/system-prompt.expected.md @@ -9,7 +9,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/browser-use-chrome-devtools-mcp/system-prompt.expected.md b/snapshots/session/browser-use-chrome-devtools-mcp/system-prompt.expected.md index c07f1a39fe..8fe493e37d 100644 --- a/snapshots/session/browser-use-chrome-devtools-mcp/system-prompt.expected.md +++ b/snapshots/session/browser-use-chrome-devtools-mcp/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/browser-use-playwright-mcp/system-prompt.expected.md b/snapshots/session/browser-use-playwright-mcp/system-prompt.expected.md index 63b5fb94fa..43813d6a9a 100644 --- a/snapshots/session/browser-use-playwright-mcp/system-prompt.expected.md +++ b/snapshots/session/browser-use-playwright-mcp/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/browser-use-stagehand-native/system-prompt.expected.md b/snapshots/session/browser-use-stagehand-native/system-prompt.expected.md index 2958e580fc..0eb0d56504 100644 --- a/snapshots/session/browser-use-stagehand-native/system-prompt.expected.md +++ b/snapshots/session/browser-use-stagehand-native/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/claude-code-mods/system-prompt.expected.md b/snapshots/session/claude-code-mods/system-prompt.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/session/claude-code-mods/system-prompt.expected.md +++ b/snapshots/session/claude-code-mods/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/compaction-recovery/system-prompt.expected.md b/snapshots/session/compaction-recovery/system-prompt.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/session/compaction-recovery/system-prompt.expected.md +++ b/snapshots/session/compaction-recovery/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/computer-use-cua-driver-mcp/system-prompt.expected.md b/snapshots/session/computer-use-cua-driver-mcp/system-prompt.expected.md index ec0feaa6d1..7c5cb56d21 100644 --- a/snapshots/session/computer-use-cua-driver-mcp/system-prompt.expected.md +++ b/snapshots/session/computer-use-cua-driver-mcp/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/computer-use-cua-driver-native/system-prompt.expected.md b/snapshots/session/computer-use-cua-driver-native/system-prompt.expected.md index b80574dac4..9da550bd3e 100644 --- a/snapshots/session/computer-use-cua-driver-native/system-prompt.expected.md +++ b/snapshots/session/computer-use-cua-driver-native/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/cordis-inspect-jsdoc/system-prompt.expected.md b/snapshots/session/cordis-inspect-jsdoc/system-prompt.expected.md index c776c30451..96c21c3c36 100644 --- a/snapshots/session/cordis-inspect-jsdoc/system-prompt.expected.md +++ b/snapshots/session/cordis-inspect-jsdoc/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index c842954b3b..b08a00dc92 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 55611ceb34..f0677e6786 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -9,7 +9,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/deepseek-messages-system-prompt/system-prompt.expected.md b/snapshots/session/deepseek-messages-system-prompt/system-prompt.expected.md index 0296cb556a..866544439b 100644 --- a/snapshots/session/deepseek-messages-system-prompt/system-prompt.expected.md +++ b/snapshots/session/deepseek-messages-system-prompt/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -42,7 +42,7 @@ Snapshot guidance added after the first read: reply with the single word DONE. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/deepseek-protocol-system-prompt/system-prompt.expected.md b/snapshots/session/deepseek-protocol-system-prompt/system-prompt.expected.md index 0296cb556a..866544439b 100644 --- a/snapshots/session/deepseek-protocol-system-prompt/system-prompt.expected.md +++ b/snapshots/session/deepseek-protocol-system-prompt/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -42,7 +42,7 @@ Snapshot guidance added after the first read: reply with the single word DONE. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/dynamic-tool-prompt-updates/system-prompt.expected.md b/snapshots/session/dynamic-tool-prompt-updates/system-prompt.expected.md index 86d12ea329..a05793a859 100644 --- a/snapshots/session/dynamic-tool-prompt-updates/system-prompt.expected.md +++ b/snapshots/session/dynamic-tool-prompt-updates/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -42,7 +42,7 @@ Dynamic tool guidance: call snapshot_ping once, then reply with the single word Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/dynamic-tool-updates/system-prompt.expected.md b/snapshots/session/dynamic-tool-updates/system-prompt.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/session/dynamic-tool-updates/system-prompt.expected.md +++ b/snapshots/session/dynamic-tool-updates/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/foreground-confinement-timeout/system-prompt.expected.md b/snapshots/session/foreground-confinement-timeout/system-prompt.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/session/foreground-confinement-timeout/system-prompt.expected.md +++ b/snapshots/session/foreground-confinement-timeout/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/fs-glob-sampling/system-prompt.expected.md b/snapshots/session/fs-glob-sampling/system-prompt.expected.md index 1b805eaf0c..d2353b3564 100644 --- a/snapshots/session/fs-glob-sampling/system-prompt.expected.md +++ b/snapshots/session/fs-glob-sampling/system-prompt.expected.md @@ -4,7 +4,7 @@ You are a concise snapshot agent. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/in-history-series-start/system-prompt.expected.md b/snapshots/session/in-history-series-start/system-prompt.expected.md index 560982974b..f1e2396301 100644 --- a/snapshots/session/in-history-series-start/system-prompt.expected.md +++ b/snapshots/session/in-history-series-start/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -42,7 +42,7 @@ Snapshot guidance added after the first read: call snapshot_ping once, then repl Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/lsp-definition/system-prompt.expected.md b/snapshots/session/lsp-definition/system-prompt.expected.md index 0283ccaab4..1f3292c0de 100644 --- a/snapshots/session/lsp-definition/system-prompt.expected.md +++ b/snapshots/session/lsp-definition/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/mcp-resources-ptc/system-prompt.expected.md b/snapshots/session/mcp-resources-ptc/system-prompt.expected.md index 47af8cdc91..6935afcb13 100644 --- a/snapshots/session/mcp-resources-ptc/system-prompt.expected.md +++ b/snapshots/session/mcp-resources-ptc/system-prompt.expected.md @@ -9,7 +9,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/mcp-resources/system-prompt.expected.md b/snapshots/session/mcp-resources/system-prompt.expected.md index 275f98c89b..27a0d010fa 100644 --- a/snapshots/session/mcp-resources/system-prompt.expected.md +++ b/snapshots/session/mcp-resources/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/model-switch-compaction/system-prompt.expected.md b/snapshots/session/model-switch-compaction/system-prompt.expected.md index edee628694..ebfa6ae4cb 100644 --- a/snapshots/session/model-switch-compaction/system-prompt.expected.md +++ b/snapshots/session/model-switch-compaction/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -40,7 +40,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/model-switch-notice/system-prompt.expected.md b/snapshots/session/model-switch-notice/system-prompt.expected.md index edee628694..ebfa6ae4cb 100644 --- a/snapshots/session/model-switch-notice/system-prompt.expected.md +++ b/snapshots/session/model-switch-notice/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -40,7 +40,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/multimodal-spill-ends/system-prompt.expected.md b/snapshots/session/multimodal-spill-ends/system-prompt.expected.md index 4956076bc6..203482bcf8 100644 --- a/snapshots/session/multimodal-spill-ends/system-prompt.expected.md +++ b/snapshots/session/multimodal-spill-ends/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/office-authoring-checker/system-prompt.expected.md b/snapshots/session/office-authoring-checker/system-prompt.expected.md index fb8a26b762..99835b05a4 100644 --- a/snapshots/session/office-authoring-checker/system-prompt.expected.md +++ b/snapshots/session/office-authoring-checker/system-prompt.expected.md @@ -5,7 +5,7 @@ You are a coding assistant powered by the deepseek-v4-flash model. Your bash too Verify your work by running the code or tests. Keep answers brief and factual. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/office-progressive-native/system-prompt.expected.md b/snapshots/session/office-progressive-native/system-prompt.expected.md index fb8a26b762..99835b05a4 100644 --- a/snapshots/session/office-progressive-native/system-prompt.expected.md +++ b/snapshots/session/office-progressive-native/system-prompt.expected.md @@ -5,7 +5,7 @@ You are a coding assistant powered by the deepseek-v4-flash model. Your bash too Verify your work by running the code or tests. Keep answers brief and factual. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/office-progressive-ptc/system-prompt.expected.md b/snapshots/session/office-progressive-ptc/system-prompt.expected.md index 5a735d0ba4..7b8827164b 100644 --- a/snapshots/session/office-progressive-ptc/system-prompt.expected.md +++ b/snapshots/session/office-progressive-ptc/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. `run_code` is the only tool you can call directly — a tool call naming any other tool fails. Reach every tool the SDK declares below from inside the program. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/office-sidecar-instructions/system-prompt.expected.md b/snapshots/session/office-sidecar-instructions/system-prompt.expected.md index fb8a26b762..99835b05a4 100644 --- a/snapshots/session/office-sidecar-instructions/system-prompt.expected.md +++ b/snapshots/session/office-sidecar-instructions/system-prompt.expected.md @@ -5,7 +5,7 @@ You are a coding assistant powered by the deepseek-v4-flash model. Your bash too Verify your work by running the code or tests. Keep answers brief and factual. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/office-skills/system-prompt.expected.md b/snapshots/session/office-skills/system-prompt.expected.md index fb8a26b762..99835b05a4 100644 --- a/snapshots/session/office-skills/system-prompt.expected.md +++ b/snapshots/session/office-skills/system-prompt.expected.md @@ -5,7 +5,7 @@ You are a coding assistant powered by the deepseek-v4-flash model. Your bash too Verify your work by running the code or tests. Keep answers brief and factual. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/persistent-pwsh-tool-turn/system-prompt.expected.md b/snapshots/session/persistent-pwsh-tool-turn/system-prompt.expected.md index 842c2d65fe..87e4851cef 100644 --- a/snapshots/session/persistent-pwsh-tool-turn/system-prompt.expected.md +++ b/snapshots/session/persistent-pwsh-tool-turn/system-prompt.expected.md @@ -2,7 +2,7 @@ You are an AI agent powered by DeepSeek Harness. You are a concise snapshot agent. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/pi-ai-conversation-updates/system-prompt.expected.md b/snapshots/session/pi-ai-conversation-updates/system-prompt.expected.md index ae076cd46e..98e9aa7f18 100644 --- a/snapshots/session/pi-ai-conversation-updates/system-prompt.expected.md +++ b/snapshots/session/pi-ai-conversation-updates/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -42,7 +42,7 @@ Dynamic tool guidance: call snapshot_ping once, then reply with the single word Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/plugin-manager-mcp/system-prompt.expected.md b/snapshots/session/plugin-manager-mcp/system-prompt.expected.md index 738714e849..0100efe4af 100644 --- a/snapshots/session/plugin-manager-mcp/system-prompt.expected.md +++ b/snapshots/session/plugin-manager-mcp/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -40,7 +40,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/plugin-manager/system-prompt.expected.md b/snapshots/session/plugin-manager/system-prompt.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/session/plugin-manager/system-prompt.expected.md +++ b/snapshots/session/plugin-manager/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/product-subagent-both/system-prompt.expected.md b/snapshots/session/product-subagent-both/system-prompt.expected.md index c56d93da7d..6d4a844eb5 100644 --- a/snapshots/session/product-subagent-both/system-prompt.expected.md +++ b/snapshots/session/product-subagent-both/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/product-subagent-codex/system-prompt.expected.md b/snapshots/session/product-subagent-codex/system-prompt.expected.md index 1d102aa047..821579815c 100644 --- a/snapshots/session/product-subagent-codex/system-prompt.expected.md +++ b/snapshots/session/product-subagent-codex/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/product-subagent-oar/system-prompt.expected.md b/snapshots/session/product-subagent-oar/system-prompt.expected.md index 1602145e6e..a968d842ef 100644 --- a/snapshots/session/product-subagent-oar/system-prompt.expected.md +++ b/snapshots/session/product-subagent-oar/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/product-subagent-result-diagnostic/system-prompt.expected.md b/snapshots/session/product-subagent-result-diagnostic/system-prompt.expected.md index f99fb3e50f..476ed70b23 100644 --- a/snapshots/session/product-subagent-result-diagnostic/system-prompt.expected.md +++ b/snapshots/session/product-subagent-result-diagnostic/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/provider-cwd/system-prompt.expected.md b/snapshots/session/provider-cwd/system-prompt.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/session/provider-cwd/system-prompt.expected.md +++ b/snapshots/session/provider-cwd/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/ptc-node-read-only/system-prompt.expected.md b/snapshots/session/ptc-node-read-only/system-prompt.expected.md index 792433868b..9be58967e7 100644 --- a/snapshots/session/ptc-node-read-only/system-prompt.expected.md +++ b/snapshots/session/ptc-node-read-only/system-prompt.expected.md @@ -9,7 +9,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/ptc-node-workspace/system-prompt.expected.md b/snapshots/session/ptc-node-workspace/system-prompt.expected.md index 792433868b..9be58967e7 100644 --- a/snapshots/session/ptc-node-workspace/system-prompt.expected.md +++ b/snapshots/session/ptc-node-workspace/system-prompt.expected.md @@ -9,7 +9,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/ptc-persistent/system-prompt.expected.md b/snapshots/session/ptc-persistent/system-prompt.expected.md index cee1d38ca1..f78d20535d 100644 --- a/snapshots/session/ptc-persistent/system-prompt.expected.md +++ b/snapshots/session/ptc-persistent/system-prompt.expected.md @@ -9,7 +9,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/ptc-policy-change/system-prompt.expected.md b/snapshots/session/ptc-policy-change/system-prompt.expected.md index 0299ece58d..980e98ffa4 100644 --- a/snapshots/session/ptc-policy-change/system-prompt.expected.md +++ b/snapshots/session/ptc-policy-change/system-prompt.expected.md @@ -9,7 +9,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/ptc-python-turn/system-prompt.expected.md b/snapshots/session/ptc-python-turn/system-prompt.expected.md index 30de551e71..89537e68ab 100644 --- a/snapshots/session/ptc-python-turn/system-prompt.expected.md +++ b/snapshots/session/ptc-python-turn/system-prompt.expected.md @@ -9,7 +9,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/ptc-read-image/system-prompt.expected.md b/snapshots/session/ptc-read-image/system-prompt.expected.md index 24a8c6d038..b2d28e5d8b 100644 --- a/snapshots/session/ptc-read-image/system-prompt.expected.md +++ b/snapshots/session/ptc-read-image/system-prompt.expected.md @@ -9,7 +9,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/ptc-turn/system-prompt.expected.md b/snapshots/session/ptc-turn/system-prompt.expected.md index 792433868b..9be58967e7 100644 --- a/snapshots/session/ptc-turn/system-prompt.expected.md +++ b/snapshots/session/ptc-turn/system-prompt.expected.md @@ -9,7 +9,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/pty-tools-sandbox-backend/system-prompt.expected.md b/snapshots/session/pty-tools-sandbox-backend/system-prompt.expected.md index 20152fd0c0..be57207fc0 100644 --- a/snapshots/session/pty-tools-sandbox-backend/system-prompt.expected.md +++ b/snapshots/session/pty-tools-sandbox-backend/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/pwsh-tool-turn/system-prompt.expected.md b/snapshots/session/pwsh-tool-turn/system-prompt.expected.md index d8b177d881..a80f28bb0b 100644 --- a/snapshots/session/pwsh-tool-turn/system-prompt.expected.md +++ b/snapshots/session/pwsh-tool-turn/system-prompt.expected.md @@ -4,7 +4,7 @@ You are a concise snapshot agent. Non-zero exits are reported as `[exit code: N]` markers; investigate failures before moving on. On Windows a killed process settles as `[exit code: 1]` without a signal marker; treat a bare exit 1 after an interruption as a termination, not a command failure. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/ralph-loop/system-prompt.1.expected.md b/snapshots/session/ralph-loop/system-prompt.1.expected.md index 5fbb332b1a..e6e23d12d1 100644 --- a/snapshots/session/ralph-loop/system-prompt.1.expected.md +++ b/snapshots/session/ralph-loop/system-prompt.1.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/ralph-loop/system-prompt.2.expected.md b/snapshots/session/ralph-loop/system-prompt.2.expected.md index 5fbb332b1a..e6e23d12d1 100644 --- a/snapshots/session/ralph-loop/system-prompt.2.expected.md +++ b/snapshots/session/ralph-loop/system-prompt.2.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/ralph-loop/system-prompt.expected.md b/snapshots/session/ralph-loop/system-prompt.expected.md index c660db009c..89df21339c 100644 --- a/snapshots/session/ralph-loop/system-prompt.expected.md +++ b/snapshots/session/ralph-loop/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/read-image/system-prompt.expected.md b/snapshots/session/read-image/system-prompt.expected.md index 4956076bc6..203482bcf8 100644 --- a/snapshots/session/read-image/system-prompt.expected.md +++ b/snapshots/session/read-image/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/session-query-spill/system-prompt.expected.md b/snapshots/session/session-query-spill/system-prompt.expected.md index 11134b52b8..57b51b4d63 100644 --- a/snapshots/session/session-query-spill/system-prompt.expected.md +++ b/snapshots/session/session-query-spill/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/subagent-acp-diagnostic/system-prompt.expected.md b/snapshots/session/subagent-acp-diagnostic/system-prompt.expected.md index e4447fa937..d6c0fe5ce3 100644 --- a/snapshots/session/subagent-acp-diagnostic/system-prompt.expected.md +++ b/snapshots/session/subagent-acp-diagnostic/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/subagent-agent-preset/system-prompt.1.expected.md b/snapshots/session/subagent-agent-preset/system-prompt.1.expected.md index 21ed8bf9ad..0871e4b88e 100644 --- a/snapshots/session/subagent-agent-preset/system-prompt.1.expected.md +++ b/snapshots/session/subagent-agent-preset/system-prompt.1.expected.md @@ -4,7 +4,7 @@ You are a file reviewer. Inspect the requested files and report your findings. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/subagent-structured-parent/system-prompt.1.expected.md b/snapshots/session/subagent-structured-parent/system-prompt.1.expected.md index 7cbbfb55ef..11e71560b8 100644 --- a/snapshots/session/subagent-structured-parent/system-prompt.1.expected.md +++ b/snapshots/session/subagent-structured-parent/system-prompt.1.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/system-prompt-in-history/system-prompt.expected.md b/snapshots/session/system-prompt-in-history/system-prompt.expected.md index 95c410e8ec..52bd312c90 100644 --- a/snapshots/session/system-prompt-in-history/system-prompt.expected.md +++ b/snapshots/session/system-prompt-in-history/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -42,7 +42,7 @@ Snapshot guidance added after the first read: reply with the single word DONE. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/team-targets/system-prompt.expected.md b/snapshots/session/team-targets/system-prompt.expected.md index ff7929a66a..6cebee7943 100644 --- a/snapshots/session/team-targets/system-prompt.expected.md +++ b/snapshots/session/team-targets/system-prompt.expected.md @@ -15,7 +15,7 @@ Use the target returned by spawn_teammate or list_agents for send_message and in Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/text-turn/system-prompt.expected.md b/snapshots/session/text-turn/system-prompt.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/session/text-turn/system-prompt.expected.md +++ b/snapshots/session/text-turn/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/web-fetch/system-prompt.expected.md b/snapshots/session/web-fetch/system-prompt.expected.md index f8ff1ad2b1..ec6c26f5ef 100644 --- a/snapshots/session/web-fetch/system-prompt.expected.md +++ b/snapshots/session/web-fetch/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/web-search-unconfigured/system-prompt.expected.md b/snapshots/session/web-search-unconfigured/system-prompt.expected.md index a839f0d76d..7ada3f9ff7 100644 --- a/snapshots/session/web-search-unconfigured/system-prompt.expected.md +++ b/snapshots/session/web-search-unconfigured/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/workflow-confinement/system-prompt.expected.md b/snapshots/session/workflow-confinement/system-prompt.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/session/workflow-confinement/system-prompt.expected.md +++ b/snapshots/session/workflow-confinement/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/workspace-dependencies/system-prompt.expected.md b/snapshots/session/workspace-dependencies/system-prompt.expected.md index fb8a26b762..99835b05a4 100644 --- a/snapshots/session/workspace-dependencies/system-prompt.expected.md +++ b/snapshots/session/workspace-dependencies/system-prompt.expected.md @@ -5,7 +5,7 @@ You are a coding assistant powered by the deepseek-v4-flash model. Your bash too Verify your work by running the code or tests. Keep answers brief and factual. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/worktree/system-prompt.expected.md b/snapshots/session/worktree/system-prompt.expected.md index 4129b103da..cfc9e19da9 100644 --- a/snapshots/session/worktree/system-prompt.expected.md +++ b/snapshots/session/worktree/system-prompt.expected.md @@ -7,7 +7,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/web/creation-recommendations/system-prompt.expected.md b/snapshots/web/creation-recommendations/system-prompt.expected.md index 5ee4be0c03..069e0c706f 100644 --- a/snapshots/web/creation-recommendations/system-prompt.expected.md +++ b/snapshots/web/creation-recommendations/system-prompt.expected.md @@ -6,7 +6,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/web/fresh-round-trip/system-prompt.expected.md b/snapshots/web/fresh-round-trip/system-prompt.expected.md index 5ee4be0c03..069e0c706f 100644 --- a/snapshots/web/fresh-round-trip/system-prompt.expected.md +++ b/snapshots/web/fresh-round-trip/system-prompt.expected.md @@ -6,7 +6,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/web/official-subagent-bundle/system-prompt.expected.md b/snapshots/web/official-subagent-bundle/system-prompt.expected.md index c8dd24b7af..5e9e80e632 100644 --- a/snapshots/web/official-subagent-bundle/system-prompt.expected.md +++ b/snapshots/web/official-subagent-bundle/system-prompt.expected.md @@ -8,7 +8,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/web/optional-string-editor/system-prompt.expected.md b/snapshots/web/optional-string-editor/system-prompt.expected.md index 8ecaade15e..0807f9f05e 100644 --- a/snapshots/web/optional-string-editor/system-prompt.expected.md +++ b/snapshots/web/optional-string-editor/system-prompt.expected.md @@ -8,7 +8,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/web/plugin-recommendations/system-prompt.expected.md b/snapshots/web/plugin-recommendations/system-prompt.expected.md index 5ee4be0c03..069e0c706f 100644 --- a/snapshots/web/plugin-recommendations/system-prompt.expected.md +++ b/snapshots/web/plugin-recommendations/system-prompt.expected.md @@ -6,7 +6,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/web/ptc-round/system-prompt.expected.md b/snapshots/web/ptc-round/system-prompt.expected.md index 68df54fc35..0d5612f486 100644 --- a/snapshots/web/ptc-round/system-prompt.expected.md +++ b/snapshots/web/ptc-round/system-prompt.expected.md @@ -8,7 +8,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. From 5b25f04e6f3b4f260b803e1cc7c164366015cade Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Mon, 26 Oct 2026 11:26:43 +0800 Subject: [PATCH 03/55] docs(notes): record the read guidance evidence The note keeps the #6057 observation and the 2026-10-23 evaluation of the single sentence so a later prompt trim does not remove it again. --- ...-10-26-read-guidance-line-ranges.i18n.yaml | 22 ++++++++++++ .../2026-10-26-read-guidance-line-ranges.md | 34 +++++++++++++++++++ ...2026-10-26-read-guidance-line-ranges.zh.md | 34 +++++++++++++++++++ 3 files changed, 90 insertions(+) create mode 100644 .agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml create mode 100644 .agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md create mode 100644 .agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.zh.md diff --git a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml new file mode 100644 index 0000000000..c50e4ba604 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml @@ -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: 0b8dc80eb5a32bfb + zh: e3a5588a330af784 +/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: a18ff1df8c97931c + zh: fd071b1b02755285 +/agent-note-read-guidance-names-shell-readers-and-line-ranges/verification: + en: 08557f13c54f2912 + zh: a0ae60861df1aea8 +/agent-note-read-guidance-names-shell-readers-and-line-ranges/consequences: + en: d92130932f757899 + zh: 011b8b66de41cf06 diff --git a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md new file mode 100644 index 0000000000..66e1a6396d --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md @@ -0,0 +1,34 @@ +# 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 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, 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. +- 89 `snapshots/**/system-prompt*.expected.md` sidecars carry the restored sentence and replay through the shipped profiles in `test:snapshot`; 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`. diff --git a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.zh.md b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.zh.md new file mode 100644 index 0000000000..747827cbf0 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.zh.md @@ -0,0 +1,34 @@ +# 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,步数与 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 是各自独立的决定;第一项已经恢复,其余各有自己的证据。 + +**只说“行区间”,不点名 shell 命令。** 观测到的失败就是模型选择 shell 命令,所以这句点名它们。 + +## 验证 + +- `packages/fs/tool-fs/tests/tools.spec.ts` 断言渲染出的指导文本。 +- 89 个 `snapshots/**/system-prompt*.expected.md` sidecar 带有恢复后的句子,由 `test:snapshot` 通过随附 profile 回放;两个显式 pin 的历史 sidecar(`web/cordis-tool-round`、`web/schedule-catalog`)保留录制文本。 +- 上面的评测在 native SDK profile 上只改了这一句进行测量。 + +## 影响 + +- 只要 read 工具存在,每个请求多三个命令名和一句行区间说明,约 10 token。 +- 模型读行区间时被引导到 read 工具,而不是 `cat`、`sed`、`head`、`tail`。 From 613722557646d3450c1ed4c7bb21b6f3162ea538 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 12:56:32 +0800 Subject: [PATCH 04/55] fix(desktop): ship the notarized Computer Use helper in macOS packages Build and stage the helper before packaging, keep its bundle unpacked outside app.asar, verify it instead of re-signing its files, and let the provider open the unpacked copy. Refs #7514 --- .github/workflows/macos-intel-package.yml | 8 ++++++ .github/workflows/macos-package.yml | 8 ++++++ apps/desktop/packaging/README.i18n.yaml | 8 +++--- apps/desktop/packaging/README.md | 4 +-- apps/desktop/packaging/README.zh.md | 4 +-- .../scripts/electron-builder-config.mjs | 4 ++- apps/desktop/scripts/macos-runtime.ts | 18 ++++++++++--- apps/desktop/tests/macos-runtime.spec.ts | 25 +++++++++++++++++++ apps/desktop/tests/macos-signature.spec.ts | 1 + .../experimental/cua-macos/README.i18n.yaml | 4 +-- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../cua-macos/src/native-build.ts | 5 +++- .../cua-macos/tests/native-build.spec.ts | 8 ++++++ scripts/macos-package-workflow.spec.ts | 9 +++++++ 15 files changed, 93 insertions(+), 17 deletions(-) diff --git a/.github/workflows/macos-intel-package.yml b/.github/workflows/macos-intel-package.yml index cc835b8933..1a1ede0c47 100644 --- a/.github/workflows/macos-intel-package.yml +++ b/.github/workflows/macos-intel-package.yml @@ -120,6 +120,14 @@ jobs: env: PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} run: node apps/desktop/scripts/prepare-macos-ci.mjs + - name: Build and stage notarized Computer Use helpers + # The Desktop runtime packs the workspace provider, so it carries the same helper npm publication stages. + run: | + 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: Check packaging configuration and toolchain env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} diff --git a/.github/workflows/macos-package.yml b/.github/workflows/macos-package.yml index 073f1e9541..cb62ac790d 100644 --- a/.github/workflows/macos-package.yml +++ b/.github/workflows/macos-package.yml @@ -117,6 +117,14 @@ jobs: env: PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} run: node apps/desktop/scripts/prepare-macos-ci.mjs + - name: Build and stage notarized Computer Use helpers + # The Desktop runtime packs the workspace provider, so it carries the same helper npm publication stages. + run: | + 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: Check packaging configuration and toolchain env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} diff --git a/apps/desktop/packaging/README.i18n.yaml b/apps/desktop/packaging/README.i18n.yaml index c39bb71bc3..41091f05b1 100644 --- a/apps/desktop/packaging/README.i18n.yaml +++ b/apps/desktop/packaging/README.i18n.yaml @@ -27,8 +27,8 @@ en: 253e17998951931c zh: b582b377391d2ec2 /desktop-packaging/macos-self-hosted-packaging: - en: f4cc5209bdaeefba - zh: 1db959d1ed345fcc + en: ed13421b5a0096c1 + zh: 641290b966d83916 /desktop-packaging/unsigned-windows-test-installer: en: f429bc0c280e2dfa zh: 4adbcc9e906bdf80 @@ -45,8 +45,8 @@ en: b42f103358d0dfd7 zh: a534164ad9eb00da /desktop-packaging/runtime-file-selection-and-installation-checks: - en: 83e1075417039410 - zh: 3088a7ae0a2cc3c5 + en: 5e6b38afd9b59207 + zh: d68f7cb18a4118ea /desktop-packaging/desktop-runtime-preparation: en: ab73b67d899e611d zh: d77b0525c6b81e91 diff --git a/apps/desktop/packaging/README.md b/apps/desktop/packaging/README.md index 28aa9ff9c7..cb476e7513 100644 --- a/apps/desktop/packaging/README.md +++ b/apps/desktop/packaging/README.md @@ -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. Before packaging, each builds, notarizes and stages the Computer Use helper for both architectures with `scripts/cua-helper/package.ts` and `stage.ts`, the steps npm publication uses; `skip_notarization` does not skip the helper's notarization. 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. @@ -246,7 +246,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 unpacked whole beside it. Runtime signing verifies each application bundle against the release identity and does not re-sign its files, and the provider opens the unpacked 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. diff --git a/apps/desktop/packaging/README.zh.md b/apps/desktop/packaging/README.zh.md index 2e87933826..148ea2ce50 100644 --- a/apps/desktop/packaging/README.zh.md +++ b/apps/desktop/packaging/README.zh.md @@ -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`,并复用现有签名、公证和打包运行时检查。打包前,两者都用 `scripts/cua-helper/package.ts` 和 `stage.ts` 构建、公证并放入两种架构的 Computer Use helper,与 npm 发布的步骤相同;`skip_notarization` 不会跳过 helper 的公证。成功的 DMG/ZIP 与诊断日志保留 14 天,不发布 release;安装包上传关闭重复 ZIP 压缩。操作人员须验收完整 Actions 运行及目标架构上的安装,才能确认可交付。`compression_level` 下拉选项默认为 `3`,也可选择 `7`;本次运行以该选项覆盖机器预设,只影响 ZIP 和自动升级下载,不影响 DMG。 三个平台的表单均依次展示源码、环境、升级通道、版本模式、手动版本号、测试 release ID 和压缩等级,默认值一致。macOS 公证选项和 Windows 签名、缓存测量选项位于公共字段之后。 @@ -246,7 +246,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 应用同样整体解包。运行时签名按发布身份校验每个应用包,不重签其中的文件,提供方打开解包后的副本。 打包应用运行编译后的 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 构建在公证前执行这些检查。 diff --git a/apps/desktop/scripts/electron-builder-config.mjs b/apps/desktop/scripts/electron-builder-config.mjs index cf0c19e895..50bd457098 100644 --- a/apps/desktop/scripts/electron-builder-config.mjs +++ b/apps/desktop/scripts/electron-builder-config.mjs @@ -75,8 +75,10 @@ export function createElectronBuilderConfig( let primaryRuntimeDestination let dshDestination let windowsCode = [] + // LaunchServices opens the Computer Use helper as an application, so every file of its bundle stays on disk. 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}/**/*`, + '**/node_modules/@deepseek-ai/dsh-experimental-cua-macos/native/bin/**/*'] const windowsSigner = packagesWindows && !unsigned ? createWindowsTokenSigner({ certificateFile: env.DSH_DESKTOP_WINDOWS_CER_FILE, diff --git a/apps/desktop/scripts/macos-runtime.ts b/apps/desktop/scripts/macos-runtime.ts index 1d4c27c0d5..5916694fa7 100644 --- a/apps/desktop/scripts/macos-runtime.ts +++ b/apps/desktop/scripts/macos-runtime.ts @@ -11,6 +11,8 @@ import { macOSCachePolicy } from './macos-cache-policy.ts' import { signMacOSRuntimeCode, verifyMacOSRuntimeCode } from './verify-macos-signature.mjs' const MACH_O_MAGICS = new Set(['cafebabe', 'cafebabf', 'cefaedfe', 'cffaedfe', 'feedface', 'feedfacf', 'bebafeca', 'bfbafeca']) +/** The outermost application bundle containing a runtime path; its own signature seals every file inside it. */ +const APPLICATION_BUNDLE = /^((?:[^/]+\/)*?[^/]+\.app)\//u function magic(path: string): string { const descriptor = openSync(path, 'r') @@ -33,21 +35,31 @@ async function primaryRuntimeFiles(root: string): Promise { } /** - * Sign and verify every materialized Mach-O file, awaiting all signers on failure. + * Sign and verify every materialized Mach-O file outside application bundles, awaiting all signers on failure. + * A bundle, such as the notarized Computer Use helper, keeps its own seal: it is verified against the release + * identity before any file is signed and is never re-signed, because signing a file inside it breaks the seal. * @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 application bundles. + * @throws When a bundle signature does not verify against the release identity, 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 { 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() + const files: string[] = [] + for (const path of inventory) { + const bundle = APPLICATION_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()) verifyMacOSRuntimeCode(join(root, bundle), expected) const policy = cacheDirectory === undefined ? undefined : macOSCachePolicy(process.env.DSH_DESKTOP_MACOS_SIGNING_PROBE ?? '') let hits = 0 let misses = 0 diff --git a/apps/desktop/tests/macos-runtime.spec.ts b/apps/desktop/tests/macos-runtime.spec.ts index 4ad63e41fd..644fe74eab 100644 --- a/apps/desktop/tests/macos-runtime.spec.ts +++ b/apps/desktop/tests/macos-runtime.spec.ts @@ -26,6 +26,31 @@ it('signs Mach-O files in their final locations and verifies each signature', as expect(verifyMacOSRuntimeCode).toHaveBeenCalledWith(join(path, 'addon.node'), identity) }) +it('verifies an embedded application bundle as a whole and leaves its files unsigned', async () => { + const path = root() + const bundle = 'node_modules/@deepseek-ai/dsh-experimental-cua-macos/native/bin/darwin-arm64/generation/DSH Computer Use.app' + for (const nested of ['Contents/MacOS/dsh-cua-native', 'Contents/Frameworks/Inner.app/Contents/MacOS/inner']) { + mkdirSync(join(path, bundle, nested, '..'), { recursive: true }) + writeFileSync(join(path, bundle, nested), Buffer.from('cffaedfe00000000', 'hex')) + } + writeFileSync(join(path, bundle, 'Contents/Info.plist'), '') + writeFileSync(join(path, 'addon.node'), Buffer.from('cffaedfe00000000', 'hex')) + await expect(signMacOSRuntime(path, 'com.example.app', identity, 'arm64')).resolves.toBe(1) + expect(signMacOSRuntimeCode).toHaveBeenCalledExactlyOnceWith(join(path, 'addon.node'), expect.any(String), identity, undefined) + expect(vi.mocked(verifyMacOSRuntimeCode).mock.calls).toEqual([[join(path, bundle), identity], [join(path, 'addon.node'), identity]]) +}) + +it('rejects an application bundle without the release signature before signing any file', async () => { + const path = root() + const bundle = join(path, 'Helper.app/Contents/MacOS') + mkdirSync(bundle, { recursive: true }) + writeFileSync(join(bundle, 'helper'), Buffer.from('cffaedfe00000000', 'hex')) + writeFileSync(join(path, 'addon.node'), Buffer.from('cffaedfe00000000', 'hex')) + vi.mocked(verifyMacOSRuntimeCode).mockImplementationOnce(() => { throw new Error('signature does not match the release identity') }) + await expect(signMacOSRuntime(path, 'com.example.app', identity, 'arm64')).rejects.toThrow('release identity') + 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() diff --git a/apps/desktop/tests/macos-signature.spec.ts b/apps/desktop/tests/macos-signature.spec.ts index 2e6a2bd48e..861521546d 100644 --- a/apps/desktop/tests/macos-signature.spec.ts +++ b/apps/desktop/tests/macos-signature.spec.ts @@ -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, diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index c9ff605b3b..bec4c6ae91 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 395f2a62b2ce6b4a zh: 67912bb946c78837 /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: 86f0d93baf627b8a - zh: df27e9c87893f97c + en: 5db02186dde77aa0 + zh: 48768d6277df4c65 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: 786b8fd630b11e5f zh: 55143f15486afce8 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index da51cf0e80..94d6dc2a72 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -29,7 +29,7 @@ The helper runs through LaunchServices as the independent background application ## Use this package -This package is an optional macOS dependency. For local development, run `pnpm --dir packages/experimental/cua-macos run build:native` to generate an ad-hoc-signed application and `current.json` under `native/bin`. Release packaging requires `--identity "Developer ID Application: ()"` and notarization; see [native build and service](native/README.md#build-and-service). Installed packages preserve the distributed signature. Source preparation requires Swift and Python 3 from Apple Command Line Tools. +This package is an optional macOS dependency. For local development, run `pnpm --dir packages/experimental/cua-macos run build:native` to generate an ad-hoc-signed application and `current.json` under `native/bin`. Release packaging requires `--identity "Developer ID Application: ()"` and notarization; see [native build and service](native/README.md#build-and-service). Installed packages preserve the distributed signature. A package inside an Electron `app.asar` archive reads its application from the matching `app.asar.unpacked` directory. Source preparation requires Swift and Python 3 from Apple Command Line Tools. For repository Web use, enable [Computer Use](../cua-bundle/README.md) in Plugins. This prepares the local executable on macOS 14 or later; Windows support is in development. Subsequent builds check it while the existing Web profile keeps the bundle selected. Disabled profiles do not prepare native components. Explicit source composition is also available: diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 3fdd1ed5f6..098de18274 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -29,7 +29,7 @@ helper 通过 LaunchServices 以独立的 `DSH Computer Use.app` 后台运行, ## 使用本包 -本包是仅限 macOS 的可选依赖。本地开发时运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin` 下生成临时签名应用及 `current.json`。正式打包需要指定 `--identity "Developer ID Application: ()"` 并完成公证,参见[原生构建与服务](native/README.zh.md#build-and-service)。安装版保留分发时的签名。源码准备需要 Apple Command Line Tools 提供的 Swift 和 Python 3。 +本包是仅限 macOS 的可选依赖。本地开发时运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin` 下生成临时签名应用及 `current.json`。正式打包需要指定 `--identity "Developer ID Application: ()"` 并完成公证,参见[原生构建与服务](native/README.zh.md#build-and-service)。安装版保留分发时的签名。位于 Electron `app.asar` 归档内的包从对应的 `app.asar.unpacked` 目录读取应用。源码准备需要 Apple Command Line Tools 提供的 Swift 和 Python 3。 从仓库运行 Web 时,在插件页开启 [Computer Use](../cua-bundle/README.zh.md)。首次启用会在 macOS 14 及以上准备本机组件,Windows 支持正在开发中。现有 Web profile 保持选中时,后续构建继续检查更新。未开启的 profile 不准备原生组件。也可以显式加载源码覆盖层: diff --git a/packages/experimental/cua-macos/src/native-build.ts b/packages/experimental/cua-macos/src/native-build.ts index 8fc603a61e..304e337b86 100644 --- a/packages/experimental/cua-macos/src/native-build.ts +++ b/packages/experimental/cua-macos/src/native-build.ts @@ -100,12 +100,15 @@ export async function buildNativeExecutable(spec: NativeBuildSpec): Promise { if (await isSourcePackage(spec.packageRoot)) return buildNativeExecutable(spec) - const executable = await nativeExecutablePath(join(spec.packageRoot, 'native', 'bin', `darwin-${spec.architecture}`)) + const packageRoot = spec.packageRoot.replace(/\.asar(?=[\\/])/u, '.asar.unpacked') + const executable = await nativeExecutablePath(join(packageRoot, 'native', 'bin', `darwin-${spec.architecture}`)) spec.signal.throwIfAborted() return executable } diff --git a/packages/experimental/cua-macos/tests/native-build.spec.ts b/packages/experimental/cua-macos/tests/native-build.spec.ts index a57ba604ad..324f82ea05 100644 --- a/packages/experimental/cua-macos/tests/native-build.spec.ts +++ b/packages/experimental/cua-macos/tests/native-build.spec.ts @@ -100,6 +100,14 @@ it('uses an installed application without compiling or re-signing it', async () await expect(prepareNativeExecutable(f.spec)).rejects.toThrow() }) +it('reads an application that an Electron archive installation keeps beside app.asar', async () => { + const f = await fixture() + const archived = join(f.root, 'Resources/app.asar/dsh/node_modules/@deepseek-ai/dsh-experimental-cua-macos') + const path = await publish(join(f.root, 'Resources/app.asar.unpacked/dsh/node_modules/@deepseek-ai/dsh-experimental-cua-macos/native/bin/darwin-arm64'), f.output) + expect(await prepareNativeExecutable({ ...f.spec, packageRoot: archived })).toBe(path) + expect(f.spawn).not.toHaveBeenCalled() +}) + it.each(['../outside', '/absolute', '', 'a'.repeat(63), 'A'.repeat(64)])('rejects an invalid installed generation %s', async (bundle) => { const f = await fixture() await mkdir(f.directory, { recursive: true }) diff --git a/scripts/macos-package-workflow.spec.ts b/scripts/macos-package-workflow.spec.ts index a0bb2cb027..f88cb6fe84 100644 --- a/scripts/macos-package-workflow.spec.ts +++ b/scripts/macos-package-workflow.spec.ts @@ -71,6 +71,15 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => { expect(workflow.jobs.package!.env.PACKAGE_MACOS_ZIP_COMPRESSION_LEVEL).toBe('${{ inputs.compression_level }}') }) + it('stages the notarized Computer Use helpers before packing the runtime', () => { + const steps = workflow.jobs.package!.steps + const staging = steps.findIndex(step => step.name === 'Build and stage notarized Computer Use helpers') + expect(staging).toBeGreaterThan(steps.findIndex(step => step.name === 'Install locked dependencies')) + expect(staging).toBeLessThan(steps.findIndex(step => step.run?.includes('pnpm run package:desktop:mac:') === true)) + expect(steps[staging]?.run).toContain('pnpm exec tsx scripts/cua-helper/package.ts --out dist/cua-helper') + expect(steps[staging]?.run).toContain('pnpm exec tsx scripts/cua-helper/stage.ts --from dist/cua-helper/extracted') + }) + it('passes the same target to preparation, packaging and retention', () => { const job = workflow.jobs.package! expect(job.env.DSH_DESKTOP_TARGET_PLATFORM).toBe('darwin') From fc1ed8c1cd10c990122857e3593b500a80d447a0 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 13:27:42 +0800 Subject: [PATCH 05/55] fix(desktop): verify only the Computer Use helper bundle and stage it only when shipped Limit the no-resign exemption to the staged helper so LibreOffice's unsigned bundle keeps per-file signing, verify the helper's ticket and Gatekeeper acceptance, stage it after the configuration check only for sources that ship the bundle, and report a missing helper by path. Refs #7514 --- .github/workflows/macos-intel-package.yml | 25 +++++++---- .github/workflows/macos-package.yml | 25 +++++++---- apps/desktop/packaging/README.i18n.yaml | 20 ++++----- apps/desktop/packaging/README.md | 10 ++--- apps/desktop/packaging/README.zh.md | 10 ++--- .../scripts/electron-builder-config.mjs | 3 +- apps/desktop/scripts/macos-runtime.ts | 25 ++++++----- apps/desktop/tests/macos-runtime.spec.ts | 45 ++++++++++--------- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../cua-macos/src/native-build.ts | 14 ++++-- .../cua-macos/tests/native-build.spec.ts | 11 +++++ scripts/macos-package-workflow.spec.ts | 14 +++--- 14 files changed, 130 insertions(+), 80 deletions(-) diff --git a/.github/workflows/macos-intel-package.yml b/.github/workflows/macos-intel-package.yml index 1a1ede0c47..4f60c1b2a7 100644 --- a/.github/workflows/macos-intel-package.yml +++ b/.github/workflows/macos-intel-package.yml @@ -120,14 +120,6 @@ jobs: env: PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} run: node apps/desktop/scripts/prepare-macos-ci.mjs - - name: Build and stage notarized Computer Use helpers - # The Desktop runtime packs the workspace provider, so it carries the same helper npm publication stages. - run: | - 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: Check packaging configuration and toolchain env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} @@ -135,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 }} diff --git a/.github/workflows/macos-package.yml b/.github/workflows/macos-package.yml index cb62ac790d..eff4ebe10d 100644 --- a/.github/workflows/macos-package.yml +++ b/.github/workflows/macos-package.yml @@ -117,14 +117,6 @@ jobs: env: PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} run: node apps/desktop/scripts/prepare-macos-ci.mjs - - name: Build and stage notarized Computer Use helpers - # The Desktop runtime packs the workspace provider, so it carries the same helper npm publication stages. - run: | - 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: Check packaging configuration and toolchain env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} @@ -132,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 }} diff --git a/apps/desktop/packaging/README.i18n.yaml b/apps/desktop/packaging/README.i18n.yaml index 41091f05b1..4a4de81f97 100644 --- a/apps/desktop/packaging/README.i18n.yaml +++ b/apps/desktop/packaging/README.i18n.yaml @@ -27,17 +27,17 @@ en: 253e17998951931c zh: b582b377391d2ec2 /desktop-packaging/macos-self-hosted-packaging: - en: ed13421b5a0096c1 - zh: 641290b966d83916 + 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: 015e91c6e0f72bfb + zh: 975fd70ee5bdc520 /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: 5e6b38afd9b59207 - zh: d68f7cb18a4118ea + 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 diff --git a/apps/desktop/packaging/README.md b/apps/desktop/packaging/README.md index cb476e7513..b2898a1a74 100644 --- a/apps/desktop/packaging/README.md +++ b/apps/desktop/packaging/README.md @@ -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. Before packaging, each builds, notarizes and stages the Computer Use helper for both architectures with `scripts/cua-helper/package.ts` and `stage.ts`, the steps npm publication uses; `skip_notarization` does not skip the helper's notarization. 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,13 +172,13 @@ pnpm run package:desktop:mac:x64:unsigned Add `--check` to validate local configuration and tools without building, or `--dir` to stop at the unpacked application. The DMG is `apps/desktop/.desktop-build/targets//unsigned-artifacts/deepseek-harness--mac--unsigned.dmg`. After all checks pass, the command prints `DMG:` followed by its absolute path. Open it and copy the application to a local test directory. -These commands ignore `.env.macos` and inherited release settings, use `com.deepseek.harness` as the app ID, and omit automatic-update and mandatory-update configuration. Build tools, standard network proxies, and `DSH_DESKTOP_NPM_REGISTRY` remain available from the shell. They skip Developer ID signing, Apple notarization, temporary signing keychains, and notarization proxy changes. Electron receives a local ad-hoc signature without certificates so the modified executable can run; the DMG is unsigned. Both preparation and the assembled application still run runtime integrity and smoke checks. Local builds omit update feeds, ZIPs, and release completion records, and the upload commands cannot publish them. macOS may require approval in System Settings → Privacy & Security to open an unnotarized application. +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. ## 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 -- `. +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 -- `. 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. @@ -246,7 +246,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 Computer Use helper applications under `@deepseek-ai/dsh-experimental-cua-macos/native/bin` are unpacked whole beside it. Runtime signing verifies each application bundle against the release identity and does not re-sign its files, and the provider opens the unpacked copy. +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 +280,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. diff --git a/apps/desktop/packaging/README.zh.md b/apps/desktop/packaging/README.zh.md index 148ea2ce50..ccb96d4aa5 100644 --- a/apps/desktop/packaging/README.zh.md +++ b/apps/desktop/packaging/README.zh.md @@ -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`,并复用现有签名、公证和打包运行时检查。打包前,两者都用 `scripts/cua-helper/package.ts` 和 `stage.ts` 构建、公证并放入两种架构的 Computer Use helper,与 npm 发布的步骤相同;`skip_notarization` 不会跳过 helper 的公证。成功的 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,13 +172,13 @@ pnpm run package:desktop:mac:x64:unsigned 添加 `--check` 仅验证本地配置和工具而不构建,或添加 `--dir` 只生成解包应用。DMG 路径为 `apps/desktop/.desktop-build/targets//unsigned-artifacts/deepseek-harness--mac--unsigned.dmg`。所有检查通过后,命令打印 `DMG:` 及其绝对路径。打开后将应用复制到本地测试目录。 -这些命令忽略 `.env.macos` 和继承的发布配置,使用 `com.deepseek.harness` 作为应用 ID,并省略自动更新和强制更新配置。构建工具、标准网络代理与 `DSH_DESKTOP_NPM_REGISTRY` 仍可从 shell 提供。它们跳过 Developer ID 签名、Apple 公证、临时签名钥匙串和公证代理修改。Electron 使用无需证书的本地 ad-hoc 签名,以便修改后的可执行文件能够运行;DMG 不签名。准备阶段和组装后的应用仍执行运行时完整性与冒烟检查。本地构建不生成更新源、ZIP 或发布完成记录,上传命令无法发布这些产物。macOS 可能要求在“系统设置 → 隐私与安全性”中批准打开未经公证的应用。 +这些命令忽略 `.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 缺失。 ## macOS 发布签名与诊断 -macOS 签名配置使用必填发布环境,不会接受钥匙串中最先发现的证书。空值、格式错误的 Team ID、包含 electron-builder 不支持的 `Developer ID Application:` 前缀的签名身份,以及不完整的公证凭据都会被拒绝。macOS 签名打包要求已配置的身份及其私钥可用。运行时准备会把该身份、安全时间戳与 hardened runtime 应用到每个内嵌 Mach-O 文件;应用签名完成后,深度严格检查会拒绝其他叶证书 Authority 或 Team ID,验证通过才生成发布产物。macOS 签名固定目标安装包命令为已签名应用创建独立副本,并发执行两条产物流。一路先公证 App 并钉票,再生成 ZIP 及其更新元数据。另一路把已签名 App 副本封装进签名 DMG,再公证 DMG、钉票并验证;其中的 App 不单独附加票据。只有两路均成功结束,产物才会移入最终目录并写入发布完成记录。签名的仅目录命令同样需要公证凭据,并等待 Apple 公证和 App 钉票完成。[并行公证决策](../../../.agents/notes/implemented/process/2026-09-09-parallel-macos-notarization.zh.md)负责副本隔离与容器票据语义。`CSC_LINK` 必须指向包含 Developer ID Application 证书及私钥的本地 p12,不支持 URL 或 Base64 输入。`CSC_KEY_PASSWORD` 是其导出密码,不是 Apple 账号或登录密码;未加密的 p12 可显式填写空值。构建前,打包流程自动创建并解锁私有临时钥匙串、导入 p12、授权签名并签署小型探针。运行时与 App 签名显式使用该钥匙串,无需预先配置或手动解锁登录钥匙串。子进程只接收钥匙串路径,不接收 p12 密码。成功或普通失败后删除临时钥匙串;强制终止后由 CI 清理临时凭据。临时 CI 从密钥存储生成证书文件和 `.env.macos`,限制文件访问权限,并在作业结束后删除二者;自托管机器 preset 在 checkout 外保留私有文件。环境中的 `CSC_NAME` 与证书发现顺序都不能选择发布所有者。公证凭据也可以使用 electron-builder 支持的完整 Apple ID 或钥匙串 profile 方式。手动执行 `pnpm --dir apps/desktop run verify:mac-signature -- ` 重复应用检查时,也必须提供两个 macOS 身份变量。 +macOS 签名配置使用必填发布环境,不会接受钥匙串中最先发现的证书。空值、格式错误的 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 -- ` 重复应用检查时,也必须提供两个 macOS 身份变量。 macOS 签名遍历真实文件,不跟随 Framework 的软链接别名。PAK 资源保留全部随附语言,由外层 Framework 或应用签名记录完整性,不逐个签名。[发布策略](../../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)负责依赖补丁和验证要求。 @@ -246,7 +246,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。`@deepseek-ai/dsh-experimental-cua-macos/native/bin` 下的 Computer Use helper 应用同样整体解包。运行时签名按发布身份校验每个应用包,不重签其中的文件,提供方打开解包后的副本。 +[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 +280,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 检查。 diff --git a/apps/desktop/scripts/electron-builder-config.mjs b/apps/desktop/scripts/electron-builder-config.mjs index 50bd457098..0e12399d89 100644 --- a/apps/desktop/scripts/electron-builder-config.mjs +++ b/apps/desktop/scripts/electron-builder-config.mjs @@ -75,9 +75,10 @@ export function createElectronBuilderConfig( let primaryRuntimeDestination let dshDestination let windowsCode = [] - // LaunchServices opens the Computer Use helper as an application, so every file of its bundle stays on disk. const unpack = ['**/*.{node,dylib,dll,so,exe}', '**/*.so.*', '**/spawn-helper', '**/@vscode/ripgrep-*/bin/rg', `**/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({ diff --git a/apps/desktop/scripts/macos-runtime.ts b/apps/desktop/scripts/macos-runtime.ts index 5916694fa7..16b8fe2a27 100644 --- a/apps/desktop/scripts/macos-runtime.ts +++ b/apps/desktop/scripts/macos-runtime.ts @@ -8,11 +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 outermost application bundle containing a runtime path; its own signature seals every file inside it. */ -const APPLICATION_BUNDLE = /^((?:[^/]+\/)*?[^/]+\.app)\//u +/** + * The notarized Computer Use helper bundle containing a runtime path, as staged by `scripts/cua-helper/stage.ts`: + * `native/bin/darwin-//.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') @@ -35,17 +39,18 @@ async function primaryRuntimeFiles(root: string): Promise { } /** - * Sign and verify every materialized Mach-O file outside application bundles, awaiting all signers on failure. - * A bundle, such as the notarized Computer Use helper, keeps its own seal: it is verified against the release - * identity before any file is signed and is never re-signed, because signing a file inside it breaks the seal. + * 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, excluding files inside verified application bundles. - * @throws When a bundle signature does not verify against the release identity, or when any signer fails. + * @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, @@ -55,11 +60,11 @@ export async function signMacOSRuntime( const bundles = new Set() const files: string[] = [] for (const path of inventory) { - const bundle = APPLICATION_BUNDLE.exec(path)?.[1] + 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()) verifyMacOSRuntimeCode(join(root, bundle), expected) + 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 diff --git a/apps/desktop/tests/macos-runtime.spec.ts b/apps/desktop/tests/macos-runtime.spec.ts index 644fe74eab..b5ac451827 100644 --- a/apps/desktop/tests/macos-runtime.spec.ts +++ b/apps/desktop/tests/macos-runtime.spec.ts @@ -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,28 +28,31 @@ it('signs Mach-O files in their final locations and verifies each signature', as expect(verifyMacOSRuntimeCode).toHaveBeenCalledWith(join(path, 'addon.node'), identity) }) -it('verifies an embedded application bundle as a whole and leaves its files unsigned', async () => { +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() - const bundle = 'node_modules/@deepseek-ai/dsh-experimental-cua-macos/native/bin/darwin-arm64/generation/DSH Computer Use.app' - for (const nested of ['Contents/MacOS/dsh-cua-native', 'Contents/Frameworks/Inner.app/Contents/MacOS/inner']) { - mkdirSync(join(path, bundle, nested, '..'), { recursive: true }) - writeFileSync(join(path, bundle, nested), Buffer.from('cffaedfe00000000', 'hex')) - } - writeFileSync(join(path, bundle, 'Contents/Info.plist'), '') - writeFileSync(join(path, 'addon.node'), Buffer.from('cffaedfe00000000', 'hex')) - await expect(signMacOSRuntime(path, 'com.example.app', identity, 'arm64')).resolves.toBe(1) - expect(signMacOSRuntimeCode).toHaveBeenCalledExactlyOnceWith(join(path, 'addon.node'), expect.any(String), identity, undefined) - expect(vi.mocked(verifyMacOSRuntimeCode).mock.calls).toEqual([[join(path, bundle), identity], [join(path, 'addon.node'), identity]]) + machO(join(path, helperBundle, 'Contents/MacOS/dsh-cua-native')) + writeFileSync(join(path, helperBundle, 'Contents/Info.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 an application bundle without the release signature before signing any file', async () => { +it('rejects a helper bundle that fails notarized-application verification before signing any file', async () => { const path = root() - const bundle = join(path, 'Helper.app/Contents/MacOS') - mkdirSync(bundle, { recursive: true }) - writeFileSync(join(bundle, 'helper'), Buffer.from('cffaedfe00000000', 'hex')) - writeFileSync(join(path, 'addon.node'), Buffer.from('cffaedfe00000000', 'hex')) - vi.mocked(verifyMacOSRuntimeCode).mockImplementationOnce(() => { throw new Error('signature does not match the release identity') }) - await expect(signMacOSRuntime(path, 'com.example.app', identity, 'arm64')).rejects.toThrow('release identity') + 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() }) diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index bec4c6ae91..e8b7a196c7 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 395f2a62b2ce6b4a zh: 67912bb946c78837 /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: 5db02186dde77aa0 - zh: 48768d6277df4c65 + en: d7e50cc9e3ad4137 + zh: a65cfb7e4688d159 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: 786b8fd630b11e5f zh: 55143f15486afce8 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 94d6dc2a72..79d19e7747 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -29,7 +29,7 @@ The helper runs through LaunchServices as the independent background application ## Use this package -This package is an optional macOS dependency. For local development, run `pnpm --dir packages/experimental/cua-macos run build:native` to generate an ad-hoc-signed application and `current.json` under `native/bin`. Release packaging requires `--identity "Developer ID Application: ()"` and notarization; see [native build and service](native/README.md#build-and-service). Installed packages preserve the distributed signature. A package inside an Electron `app.asar` archive reads its application from the matching `app.asar.unpacked` directory. Source preparation requires Swift and Python 3 from Apple Command Line Tools. +This package is an optional macOS dependency. For local development, run `pnpm --dir packages/experimental/cua-macos run build:native` to generate an ad-hoc-signed application and `current.json` under `native/bin`. Release packaging requires `--identity "Developer ID Application: ()"` and notarization; see [native build and service](native/README.md#build-and-service). Installed packages preserve the distributed signature. A package inside an Electron `app.asar` archive reads its application from the sibling `app.asar.unpacked` directory, which the Desktop installer populates; an installed package without the application fails preparation with an error naming the expected directory. Source preparation requires Swift and Python 3 from Apple Command Line Tools. For repository Web use, enable [Computer Use](../cua-bundle/README.md) in Plugins. This prepares the local executable on macOS 14 or later; Windows support is in development. Subsequent builds check it while the existing Web profile keeps the bundle selected. Disabled profiles do not prepare native components. Explicit source composition is also available: diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 098de18274..dc4fb75832 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -29,7 +29,7 @@ helper 通过 LaunchServices 以独立的 `DSH Computer Use.app` 后台运行, ## 使用本包 -本包是仅限 macOS 的可选依赖。本地开发时运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin` 下生成临时签名应用及 `current.json`。正式打包需要指定 `--identity "Developer ID Application: ()"` 并完成公证,参见[原生构建与服务](native/README.zh.md#build-and-service)。安装版保留分发时的签名。位于 Electron `app.asar` 归档内的包从对应的 `app.asar.unpacked` 目录读取应用。源码准备需要 Apple Command Line Tools 提供的 Swift 和 Python 3。 +本包是仅限 macOS 的可选依赖。本地开发时运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin` 下生成临时签名应用及 `current.json`。正式打包需要指定 `--identity "Developer ID Application: ()"` 并完成公证,参见[原生构建与服务](native/README.zh.md#build-and-service)。安装版保留分发时的签名。位于 Electron `app.asar` 归档内的包从同级的 `app.asar.unpacked` 目录读取应用,该目录由 Desktop 安装包提供;已安装包缺少应用时,准备阶段报错并给出预期目录。源码准备需要 Apple Command Line Tools 提供的 Swift 和 Python 3。 从仓库运行 Web 时,在插件页开启 [Computer Use](../cua-bundle/README.zh.md)。首次启用会在 macOS 14 及以上准备本机组件,Windows 支持正在开发中。现有 Web profile 保持选中时,后续构建继续检查更新。未开启的 profile 不准备原生组件。也可以显式加载源码覆盖层: diff --git a/packages/experimental/cua-macos/src/native-build.ts b/packages/experimental/cua-macos/src/native-build.ts index 304e337b86..7f1eff1d15 100644 --- a/packages/experimental/cua-macos/src/native-build.ts +++ b/packages/experimental/cua-macos/src/native-build.ts @@ -100,15 +100,21 @@ export async function buildNativeExecutable(spec: NativeBuildSpec): Promise { if (await isSourcePackage(spec.packageRoot)) return buildNativeExecutable(spec) - const packageRoot = spec.packageRoot.replace(/\.asar(?=[\\/])/u, '.asar.unpacked') - const executable = await nativeExecutablePath(join(packageRoot, 'native', 'bin', `darwin-${spec.architecture}`)) + const directory = join(spec.packageRoot.replace('/app.asar/', '/app.asar.unpacked/'), 'native', 'bin', `darwin-${spec.architecture}`) + let executable: string + try { executable = await nativeExecutablePath(directory) } + catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || (error as NodeJS.ErrnoException).path !== join(directory, 'current.json')) throw error + throw new Error(`Computer use helper application is missing from ${directory}; this installation does not include the signed helper`, { cause: error }) + } spec.signal.throwIfAborted() return executable } diff --git a/packages/experimental/cua-macos/tests/native-build.spec.ts b/packages/experimental/cua-macos/tests/native-build.spec.ts index 324f82ea05..3208e1968a 100644 --- a/packages/experimental/cua-macos/tests/native-build.spec.ts +++ b/packages/experimental/cua-macos/tests/native-build.spec.ts @@ -108,6 +108,17 @@ it('reads an application that an Electron archive installation keeps beside app. expect(f.spawn).not.toHaveBeenCalled() }) +it('names the expected directory when an installed package carries no helper application', async () => { + const f = await fixture() + const installed = join(f.root, 'node_modules/@deepseek-ai/dsh-experimental-cua-macos.asar/package') + const directory = join(installed, 'native/bin/darwin-arm64') + await expect(prepareNativeExecutable({ ...f.spec, packageRoot: installed })).rejects.toThrow( + `Computer use helper application is missing from ${directory}; this installation does not include the signed helper`) + await mkdir(directory, { recursive: true }) + await writeFile(join(directory, 'current.json'), '{') + await expect(prepareNativeExecutable({ ...f.spec, packageRoot: installed })).rejects.toThrow(SyntaxError) +}) + it.each(['../outside', '/absolute', '', 'a'.repeat(63), 'A'.repeat(64)])('rejects an invalid installed generation %s', async (bundle) => { const f = await fixture() await mkdir(f.directory, { recursive: true }) diff --git a/scripts/macos-package-workflow.spec.ts b/scripts/macos-package-workflow.spec.ts index f88cb6fe84..cb2f07cd39 100644 --- a/scripts/macos-package-workflow.spec.ts +++ b/scripts/macos-package-workflow.spec.ts @@ -71,13 +71,17 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => { expect(workflow.jobs.package!.env.PACKAGE_MACOS_ZIP_COMPRESSION_LEVEL).toBe('${{ inputs.compression_level }}') }) - it('stages the notarized Computer Use helpers before packing the runtime', () => { + it('stages the notarized Computer Use helpers after the configuration check and before packing the runtime', () => { const steps = workflow.jobs.package!.steps const staging = steps.findIndex(step => step.name === 'Build and stage notarized Computer Use helpers') - expect(staging).toBeGreaterThan(steps.findIndex(step => step.name === 'Install locked dependencies')) - expect(staging).toBeLessThan(steps.findIndex(step => step.run?.includes('pnpm run package:desktop:mac:') === true)) - expect(steps[staging]?.run).toContain('pnpm exec tsx scripts/cua-helper/package.ts --out dist/cua-helper') - expect(steps[staging]?.run).toContain('pnpm exec tsx scripts/cua-helper/stage.ts --from dist/cua-helper/extracted') + expect(staging).toBeGreaterThan(steps.findIndex(step => step.name === 'Check packaging configuration and toolchain')) + expect(staging).toBeLessThan(steps.findIndex(step => step.name === 'Build signed installers')) + const run = steps[staging]?.run ?? '' + // Sources whose dsh does not ship the bundle, or that predate helper packaging, skip staging. + expect(run.indexOf("dependencies?.['@deepseek-ai/dsh-cua-bundle']")).toBeLessThan(run.indexOf('scripts/cua-helper/package.ts --out')) + expect(run.indexOf('[[ ! -f scripts/cua-helper/package.ts ]]')).toBeLessThan(run.indexOf('scripts/cua-helper/package.ts --out')) + expect(run).toContain('pnpm exec tsx scripts/cua-helper/package.ts --out dist/cua-helper') + expect(run).toContain('pnpm exec tsx scripts/cua-helper/stage.ts --from dist/cua-helper/extracted') }) it('passes the same target to preparation, packaging and retention', () => { From 2b1368f317b86e326f2853a3d725631bf041e737 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 13:40:39 +0800 Subject: [PATCH 06/55] fix(cua): match the app.asar segment with either path separator The archive mapping missed Windows-joined paths in the cross-platform test run; anchor on the whole app.asar segment instead of a literal forward-slash string. Refs #7514 --- packages/experimental/cua-macos/src/native-build.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/experimental/cua-macos/src/native-build.ts b/packages/experimental/cua-macos/src/native-build.ts index 7f1eff1d15..9cc3e3bc2a 100644 --- a/packages/experimental/cua-macos/src/native-build.ts +++ b/packages/experimental/cua-macos/src/native-build.ts @@ -108,7 +108,7 @@ export async function buildNativeExecutable(spec: NativeBuildSpec): Promise { if (await isSourcePackage(spec.packageRoot)) return buildNativeExecutable(spec) - const directory = join(spec.packageRoot.replace('/app.asar/', '/app.asar.unpacked/'), 'native', 'bin', `darwin-${spec.architecture}`) + const directory = join(spec.packageRoot.replace(/([\\/])app\.asar(?=[\\/])/u, '$1app.asar.unpacked'), 'native', 'bin', `darwin-${spec.architecture}`) let executable: string try { executable = await nativeExecutablePath(directory) } catch (error) { From 3b544b041688967fd0f7c97c1fd1e4f52a0ee554 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 12:07:01 +0800 Subject: [PATCH 07/55] feat(cua): ship Computer Use as an optional bundle in the Experimental plugins list Refs #7514 --- apps/cli/package.json | 1 + .../tests/cua-optional-package.spec.ts | 16 +++++------ apps/web/tests/bundle-platform.e2e.ts | 2 +- apps/web/tests/cua-optin.e2e.ts | 28 ++++++------------- apps/web/tests/cua-permissions.e2e.ts | 2 +- apps/web/tests/plugin-manager.e2e.ts | 8 ++++-- apps/web/tests/preview-boot.e2e.ts | 17 ++++++----- .../guide.i18n.yaml | 4 +-- .../computer-use-helper-permissions/guide.md | 2 +- .../guide.zh.md | 2 +- .../tests/components.client.spec.tsx | 1 - .../experimental/cua-bundle/README.i18n.yaml | 12 ++++---- packages/experimental/cua-bundle/README.md | 11 ++++---- packages/experimental/cua-bundle/README.zh.md | 11 ++++---- packages/experimental/cua-bundle/package.json | 1 - packages/util/official-bundles/src/bundles.ts | 2 +- .../official-bundles/src/catalog.generated.ts | 10 ------- .../tests/official-bundles.spec.ts | 6 ++-- pnpm-lock.yaml | 3 ++ scripts/local-bundle-registry.spec.ts | 3 +- .../creation-recommendations/session.v4.jsonl | 2 +- 21 files changed, 66 insertions(+), 78 deletions(-) diff --git a/apps/cli/package.json b/apps/cli/package.json index 463f4f1b9e..a77b89b9f2 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -107,6 +107,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:*" diff --git a/apps/desktop/tests/cua-optional-package.spec.ts b/apps/desktop/tests/cua-optional-package.spec.ts index 85ef15f0ee..a6b42cdcfd 100644 --- a/apps/desktop/tests/cua-optional-package.spec.ts +++ b/apps/desktop/tests/cua-optional-package.spec.ts @@ -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).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((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) } diff --git a/apps/web/tests/bundle-platform.e2e.ts b/apps/web/tests/bundle-platform.e2e.ts index 55d22be94d..2f3c673a3c 100644 --- a/apps/web/tests/bundle-platform.e2e.ts +++ b/apps/web/tests/bundle-platform.e2e.ts @@ -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' } }) diff --git a/apps/web/tests/cua-optin.e2e.ts b/apps/web/tests/cua-optin.e2e.ts index c5900519c6..767af7ff10 100644 --- a/apps/web/tests/cua-optin.e2e.ts +++ b/apps/web/tests/cua-optin.e2e.ts @@ -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() diff --git a/apps/web/tests/cua-permissions.e2e.ts b/apps/web/tests/cua-permissions.e2e.ts index 72afb6648d..0404db7403 100644 --- a/apps/web/tests/cua-permissions.e2e.ts +++ b/apps/web/tests/cua-permissions.e2e.ts @@ -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) diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index 7963b22779..f8b01f726c 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -856,9 +856,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 }) @@ -876,6 +879,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], diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index 3cf7695139..13d03475ff 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -694,7 +694,6 @@ async function toggleOptionalBundles(page: Page): Promise { }) } 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,20 @@ async function toggleOptionalBundles(page: Page): Promise { }) 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, + }) + // The packed worker composition excludes LiveShare from its generic toggles; plugin-manager.e2e.ts + // covers that bundle's enable/disable path in the ordinary Web scaffold. + 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. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.i18n.yaml index f8584a6842..7e4e4247a2 100644 --- a/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.i18n.yaml @@ -12,5 +12,5 @@ en: 1552866718133b10 zh: 1c760c5c2d5cfc0b /authorize-the-computer-use-helper/migration: - en: a79e5995415ff456 - zh: 6f818a092e53af2c + en: 2a28385e24468734 + zh: 725c1856a604bc0c diff --git a/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.md b/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.md index c913488785..9e57c7c569 100644 --- a/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.md +++ b/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.md @@ -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. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.zh.md index f25a4b805d..a6c3a2f634 100644 --- a/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.zh.md @@ -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 沙箱策略。 diff --git a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx index adacb15d71..6b541f65a6 100644 --- a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx +++ b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx @@ -1256,7 +1256,6 @@ describe('PluginManagerPage', () => { }) it.each([ - '@deepseek-ai/dsh-cua-bundle', '@deepseek-ai/dsh-experimental-session-search', '@deepseek-ai/dsh-experimental-ralph-bundle', '@acme/shipped-exploration', diff --git a/packages/experimental/cua-bundle/README.i18n.yaml b/packages/experimental/cua-bundle/README.i18n.yaml index b8f7ced3c7..b3b770c7a9 100644 --- a/packages/experimental/cua-bundle/README.i18n.yaml +++ b/packages/experimental/cua-bundle/README.i18n.yaml @@ -9,14 +9,14 @@ en: 9084fb48d0f6489c zh: ce692972d91cf663 /deepseek-ai-dsh-cua-bundle/summary: - en: 5f213491dd724c91 - zh: 228439436d3b339c + en: 0d93f44a8ce7404c + zh: 6a73ed42d0efc9ea /deepseek-ai-dsh-cua-bundle/table-of-contents: en: b563e4ec4727d0de zh: d0228da978238e05 /deepseek-ai-dsh-cua-bundle/use-this-package: - en: 92b549c20b7b8e63 - zh: 90df835c4e9bac75 + en: 1c54bec900429732 + zh: c062f2515dc3e41a /deepseek-ai-dsh-cua-bundle/understand-the-implementation: en: b1011db52cfc17cd zh: 6fa8798fedc5c0b6 @@ -39,8 +39,8 @@ en: 417c40acd93df532 zh: 69cc5cf7140c75a9 /deepseek-ai-dsh-cua-bundle/known-limitations-and-deferred-work: - en: 7d91694e2f6b111e - zh: 54bcc0cef9496ed6 + en: f2362542e43a1946 + zh: c45ca90c66ce6a48 /deepseek-ai-dsh-cua-bundle/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: ce96645b3e75874e diff --git a/packages/experimental/cua-bundle/README.md b/packages/experimental/cua-bundle/README.md index 63bdd67b27..6f4bba076a 100644 --- a/packages/experimental/cua-bundle/README.md +++ b/packages/experimental/cua-bundle/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Enable macOS Computer Use from Plugins for existing and new PTC sessions. Windows support is in development. This bundle remains in `experimental` until that support is complete, then moves to the `computer-use` group. It is off by default and hidden from the default plugin lists until enabled or separately installed; disabled profiles prepare no native components and register neither CUA tools nor their model guidance. +Enable macOS Computer Use from Plugins for existing and new PTC sessions. Windows support is in development. This bundle remains in `experimental` until that support is complete, then moves to the `computer-use` group. It ships with DSH switched off and appears in the Experimental plugins list on macOS Hosts; disabled profiles prepare no native components and register neither CUA tools nor their model guidance. ## Table of Contents @@ -24,7 +24,7 @@ Enable macOS Computer Use from Plugins for existing and new PTC sessions. Window ## Use this package -In macOS Desktop, open **Plugins → Add plugin**, enter `@deepseek-ai/dsh-cua-bundle`, choose **Install**, then **Enable now**. DSH installs the official version matching its runtime into the profile. Published packages contain the signed and notarized helper; users need no compiler. Source Web and development Desktop link the workspace bundle and prepare an ad-hoc helper when enabled. Open Computer Use details, choose PTC if needed, and grant Accessibility and Screen Recording to `DSH Computer Use.app`. Disabled installed bundles remain available for management. For source Web, run these commands from the repository root: +On macOS, open **Plugins → More** and switch on Computer use in the Experimental plugins list. The bundle ships with DSH and updates with it, so enabling it downloads nothing. Published packages contain the signed and notarized helper; users need no compiler. Source Web and development Desktop prepare an ad-hoc helper when enabled. Open Computer Use details, choose PTC if needed, and grant Accessibility and Screen Recording to `DSH Computer Use.app`. An enabled bundle also appears in the main plugin list; switching it off returns it to the Experimental plugins list only. For source Web, run these commands from the repository root: ```sh pnpm run build @@ -33,11 +33,11 @@ pnpm dsh web For the source Desktop launcher and its separate development profile, follow [Desktop development](../../../apps/desktop/README.md). Enable Computer Use in each profile that needs it. -The switch saves bundle selection in the profile’s `package.json`. Computer Use is installed only in PTC sessions. Enabling through Add plugin, a visible card, or its detail page offers setup guidance when system permissions need attention. The detail page offers **Set to PTC** for the new-session default; existing sessions keep their preset. The switch leaves PTC execution mode and other settings unchanged. The detail page’s **Use persistent mode** action separately enables in-memory state across PTC calls; its effects and reload behavior are described in the [permission page](../cua/README.md). Native preparation runs when the provider loads and reuses the source-hashed executable when available. +The switch saves bundle selection in the profile’s `package.json`. Computer Use is installed only in PTC sessions. Enabling through its card or detail page offers setup guidance when system permissions need attention. The detail page offers **Set to PTC** for the new-session default; existing sessions keep their preset. The switch leaves PTC execution mode and other settings unchanged. The detail page’s **Use persistent mode** action separately enables in-memory state across PTC calls; its effects and reload behavior are described in the [permission page](../cua/README.md). Native preparation runs when the provider loads and reuses the source-hashed executable when available. Disabling unloads the provider and withdraws CUA tools from its Agent scopes. Runtime configuration, the new-session default and saved grants remain. -Computer Use is available only on a macOS DSH Host. The native provider is an optional dependency installed only on macOS; the bundle and its shared libraries install on demand. Other Hosts hide the bundle from default plugin lists and model recommendations and refuse enablement before saving settings. Explicit profile dependencies and saved selections remain visible for management. An already selected bundle is skipped at startup with a diagnostic and remains available for deselection; saved user settings remain. A browser on another operating system can connect to a supported Mac Host. +Computer Use is available only on a macOS DSH Host. The native provider is an optional dependency installed only on macOS; shared CUA and Client packages remain in the installation. Other Hosts hide the bundle from default plugin lists and model recommendations and refuse enablement before saving settings. Explicit profile dependencies and saved selections remain visible for management. An already selected bundle is skipped at startup with a diagnostic and remains available for deselection; saved user settings remain. A browser on another operating system can connect to a supported Mac Host. If preparation fails, the saved selection remains and CUA operations stay unavailable. Refresh or reopen the plugin page to read the component diagnostic, correct its cause, then restart DSH. @@ -85,7 +85,8 @@ CUA activation and removal change the PTC SDK and system guidance; subsequent re -- First installation requires a reachable registry carrying the matching DSH version. System permissions require the user’s approval in macOS; installation does not grant them. +- System permissions require the user’s approval in macOS; enabling the bundle does not grant them. +- A profile that installed the bundle from a registry keeps that dependency. The installation’s copy loads instead, and the plugin page offers no removal for the redundant dependency. - PTC execution is shared by the profile and is configured independently. A Host without HMR applies saved changes at restart. diff --git a/packages/experimental/cua-bundle/README.zh.md b/packages/experimental/cua-bundle/README.zh.md index e537ab287e..5d6cb63eb2 100644 --- a/packages/experimental/cua-bundle/README.zh.md +++ b/packages/experimental/cua-bundle/README.zh.md @@ -9,7 +9,7 @@ kind: "package-bundle" ## 概述 -从插件页为已有和新建 PTC 会话开启 macOS Computer Use。Windows 支持正在开发中。本组合包暂放在 `experimental`,待 Windows 支持完成后迁回 `computer-use` 组。默认关闭,启用或单独安装前不在默认插件列表中显示;关闭时不准备本机组件、不注册 CUA 工具或添加其模型指引。 +从插件页为已有和新建 PTC 会话开启 macOS Computer Use。Windows 支持正在开发中。本组合包暂放在 `experimental`,待 Windows 支持完成后迁回 `computer-use` 组。随 DSH 提供且默认关闭,在 macOS Host 的实验性插件列表中显示;关闭时不准备本机组件、不注册 CUA 工具或添加其模型指引。 ## 目录 @@ -24,7 +24,7 @@ kind: "package-bundle" ## 使用本包 -在 macOS Desktop 的“插件 → 添加插件”中输入 `@deepseek-ai/dsh-cua-bundle`,点击“安装”,再点击“立即启用”。DSH 将与当前运行时版本匹配的官方插件安装到 profile。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 链接工作区组合包,启用时准备临时签名的 helper。打开 Computer Use 详情,按需设置 PTC,并为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。已安装的组合包关闭后仍可管理。源码 Web 在仓库根目录运行以下命令: +在 macOS 上打开“插件 → 更多”,在实验性插件列表中开启 Computer Use。组合包随 DSH 提供并随之升级,开启时无需下载。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 在开启时准备临时签名的 helper。打开 Computer Use 详情,按需设置 PTC,并为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。源码 Web 在仓库根目录运行以下命令: ```sh pnpm run build @@ -33,11 +33,11 @@ pnpm dsh web 源码 Desktop 的启动方式和独立开发配置档见[桌面开发说明](../../../apps/desktop/README.zh.md)。需要使用 Computer Use 的配置档分别开启该功能。 -开关将组合包选择保存到 profile 的 `package.json`。Computer Use 仅安装在 PTC 会话中。通过「添加插件」、可见卡片或详情页启用时,系统权限未就绪会显示设置引导。详情页提供“设为 PTC”按钮来修改新会话默认模式,已有会话保留原 preset。开关保持 PTC 执行方式和其他设置不变。详情页的“设为持久化”按钮单独开启 PTC 跨调用的内存状态保留,作用范围和重载行为见[权限页面](../cua/README.zh.md)。提供方加载时准备本机组件,已有与源码摘要匹配的可执行文件时直接复用。 +开关将组合包选择保存到 profile 的 `package.json`。Computer Use 仅安装在 PTC 会话中。通过卡片或详情页启用时,系统权限未就绪会显示设置引导。详情页提供“设为 PTC”按钮来修改新会话默认模式,已有会话保留原 preset。开关保持 PTC 执行方式和其他设置不变。详情页的“设为持久化”按钮单独开启 PTC 跨调用的内存状态保留,作用范围和重载行为见[权限页面](../cua/README.zh.md)。提供方加载时准备本机组件,已有与源码摘要匹配的可执行文件时直接复用。 关闭会卸载提供方,并从其 Agent 作用域中撤回 CUA 工具。执行器配置、新会话默认值和已保存的授权保留。 -Computer Use 仅支持 macOS DSH Host。原生提供方是仅在 macOS 安装的可选依赖,组合包和共享库均按需安装。其他 Host 默认不在插件列表和模型推荐中展示此组合包,并在保存设置前拒绝启用。profile 显式安装的依赖和已保存的选择仍保留管理入口。已选中的组合包会在启动时跳过并报告原因,仍可取消选择;已保存的用户设置保留。其他操作系统上的浏览器可以连接受支持的 Mac Host。 +Computer Use 仅支持 macOS DSH Host。原生提供方是仅在 macOS 安装的可选依赖,共享 CUA 和 Client 包仍随安装提供。其他 Host 默认不在插件列表和模型推荐中展示此组合包,并在保存设置前拒绝启用。profile 显式安装的依赖和已保存的选择仍保留管理入口。已选中的组合包会在启动时跳过并报告原因,仍可取消选择;已保存的用户设置保留。其他操作系统上的浏览器可以连接受支持的 Mac Host。 准备失败时,已保存的选择保留,CUA 操作不可用。刷新或重新打开插件页查看组件诊断,修复后重启 DSH。 @@ -85,7 +85,8 @@ CUA 生效和卸载会改变 PTC SDK 与系统指引,后续请求使用更新 -- 首次安装需要能访问提供匹配 DSH 版本的注册表。系统权限需用户在 macOS 中确认,安装插件不会自动授予权限。 +- 系统权限需用户在 macOS 中确认,开启组合包不会自动授予权限。 +- 从注册表安装过组合包的 profile 会保留该依赖。加载的是安装目录中的副本,插件页不提供移除这条多余依赖的操作。 - PTC 执行方式由 profile 共享,需单独配置。未启用 HMR 的 Host 在重启时应用已保存的变更。 diff --git a/packages/experimental/cua-bundle/package.json b/packages/experimental/cua-bundle/package.json index 604a02ea63..93612c3ffc 100644 --- a/packages/experimental/cua-bundle/package.json +++ b/packages/experimental/cua-bundle/package.json @@ -35,7 +35,6 @@ "license": "MIT", "dsh": { "bundle": { - "listedByDefault": false, "patch": "./cordis.patch.yml", "platforms": [ "darwin" diff --git a/packages/util/official-bundles/src/bundles.ts b/packages/util/official-bundles/src/bundles.ts index 0ba7f23235..c3521b66d7 100644 --- a/packages/util/official-bundles/src/bundles.ts +++ b/packages/util/official-bundles/src/bundles.ts @@ -54,6 +54,7 @@ export const DEFAULT_PROFILE_BUNDLES: readonly string[] = ['@deepseek-ai/dsh-bas */ export const OPTIONAL_BUNDLES: readonly string[] = [ '@deepseek-ai/dsh-personalized-recommendations', + '@deepseek-ai/dsh-cua-bundle', '@deepseek-ai/dsh-experimental-session-search', '@deepseek-ai/dsh-experimental-ralph-bundle', '@deepseek-ai/dsh-experimental-terminal-bundle', @@ -74,5 +75,4 @@ export const OPTIONAL_BUNDLES: readonly string[] = [ export const ON_DEMAND_BUNDLES: readonly string[] = [ '@deepseek-ai/dsh-subagent-claude-code', '@deepseek-ai/dsh-subagent-codex', - '@deepseek-ai/dsh-cua-bundle', ] diff --git a/packages/util/official-bundles/src/catalog.generated.ts b/packages/util/official-bundles/src/catalog.generated.ts index 3a494f90e6..8a0cfb7579 100644 --- a/packages/util/official-bundles/src/catalog.generated.ts +++ b/packages/util/official-bundles/src/catalog.generated.ts @@ -20,14 +20,4 @@ export const OFFICIAL_ON_DEMAND_CATALOG: readonly OfficialBundleCatalogEntry[] = icon: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzYiIGhlaWdodD0iMzYiIHZpZXdCb3g9IjAgMCAzNiAzNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB4PSIxNC45ODkzIiB5PSIxNS4xODc3IiB3aWR0aD0iMTIuMjM2NSIgaGVpZ2h0PSIxMi4yMzY1IiByeD0iMiIgZmlsbD0idXJsKCNkc2hfcGx1Z2luX2FydF9SMGEpIiBmaWxsLW9wYWNpdHk9IjAuOCI+PC9yZWN0PjxyZWN0IHg9IjguODcxMDkiIHk9IjkuMDY5NyIgd2lkdGg9IjEyLjIzNjUiIGhlaWdodD0iMTIuMjM2NSIgcng9IjIiIGZpbGw9InVybCgjZHNoX3BsdWdpbl9hcnRfUjBiKSIgZmlsbC1vcGFjaXR5PSIwLjgiPjwvcmVjdD48ZGVmcz48bGluZWFyR3JhZGllbnQgaWQ9ImRzaF9wbHVnaW5fYXJ0X1IwYSIgeDE9IjIxLjEwNzUiIHkxPSIxNS4xODc3IiB4Mj0iMjEuMTA3NSIgeTI9IjI3LjQyNDMiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj48c3RvcCBzdG9wLWNvbG9yPSIjNDVFN0E0Ij48L3N0b3A+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjMDU5MDlEIj48L3N0b3A+PC9saW5lYXJHcmFkaWVudD48bGluZWFyR3JhZGllbnQgaWQ9ImRzaF9wbHVnaW5fYXJ0X1IwYiIgeDE9IjE0Ljk4OTQiIHkxPSI5LjA2OTciIHgyPSIxNC45ODk0IiB5Mj0iMjEuMzA2MyIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPjxzdG9wIHN0b3AtY29sb3I9IiM2OUI5RkYiPjwvc3RvcD48c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiMzMjRERTIiPjwvc3RvcD48L2xpbmVhckdyYWRpZW50PjwvZGVmcz48L3N2Zz4K', }, }, - { - packageName: '@deepseek-ai/dsh-cua-bundle', - platforms: ['darwin'], - listedByDefault: false, - meta: { - title: { 'de': 'Computernutzung', 'en': 'Computer use', 'es': 'Uso de la computadora', 'fr': 'Utilisation de l\'ordinateur', 'ja': 'Computer Use', 'pt': 'Uso do computador', 'ru': '\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u043A\u043E\u043C\u043F\u044C\u044E\u0442\u0435\u0440\u0430', 'zh': 'Computer Use' }, - description: { 'de': 'Unterst\u00FCtzt derzeit macOS; Die Windows-Unterst\u00FCtzung befindet sich in der Entwicklung. L\u00E4dt die Computernutzung f\u00FCr bestehende und neue PTC-Sitzungen. Wechseln Sie in den PTC-Modus und erteilen Sie die Berechtigungen f\u00FCr Barrierefreiheit und Bildschirmaufzeichnung, um ihn zu verwenden.', 'en': 'Currently supports macOS; Windows support is in development. Loads computer use for existing and new PTC sessions. Switch to PTC mode and grant Accessibility and Screen Recording permissions to use it.', 'es': 'Actualmente es compatible con macOS; El soporte para Windows est\u00E1 en desarrollo. Carga el uso de la computadora para sesiones PTC nuevas y existentes. Cambie al modo PTC y otorgue permisos de Accesibilidad y Grabaci\u00F3n de pantalla para usarlo.', 'fr': 'Prend actuellement en charge macOS\u00A0; La prise en charge de Windows est en cours de d\u00E9veloppement. Charge l\'utilisation de l\'ordinateur pour les sessions PTC existantes et nouvelles. Passez en mode PTC et accordez les autorisations d\u2019accessibilit\u00E9 et d\u2019enregistrement d\u2019\u00E9cran pour l\u2019utiliser.', 'ja': '\u73FE\u5728\u306F macOS \u306E\u307F\u5BFE\u5FDC\u3057\u3001Windows \u5BFE\u5FDC\u306F\u958B\u767A\u4E2D\u3067\u3059\u3002\u65E2\u5B58\u304A\u3088\u3073\u65B0\u898F\u306E PTC \u30BB\u30C3\u30B7\u30E7\u30F3\u306B Computer Use \u3092\u8AAD\u307F\u8FBC\u307F\u307E\u3059\u3002PTC \u30E2\u30FC\u30C9\u306B\u5207\u308A\u66FF\u3048\u3001\u30A2\u30AF\u30BB\u30B7\u30D3\u30EA\u30C6\u30A3\u3068\u753B\u9762\u53CE\u9332\u306E\u6A29\u9650\u3092\u8A31\u53EF\u3057\u3066\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044\u3002', 'pt': 'Atualmente suporta macOS; O suporte Windows est\u00E1 em desenvolvimento. Carrega o uso do computador para sess\u00F5es PTC novas e existentes. Mude para o modo PTC e conceda permiss\u00F5es de acessibilidade e grava\u00E7\u00E3o de tela para us\u00E1-lo.', 'ru': '\u0412 \u043D\u0430\u0441\u0442\u043E\u044F\u0449\u0435\u0435 \u0432\u0440\u0435\u043C\u044F \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F macOS; \u041F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u0430 Windows \u043D\u0430\u0445\u043E\u0434\u0438\u0442\u0441\u044F \u0432 \u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u043A\u0435. \u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u0442 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u043A\u043E\u043C\u043F\u044C\u044E\u0442\u0435\u0440\u0430 \u0434\u043B\u044F \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0445 \u0438 \u043D\u043E\u0432\u044B\u0445 \u0441\u0435\u0430\u043D\u0441\u043E\u0432 PTC. \u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u0435\u0441\u044C \u0432 \u0440\u0435\u0436\u0438\u043C PTC \u0438 \u043F\u0440\u0435\u0434\u043E\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u044F \u043D\u0430 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E\u0441\u0442\u044C \u0438 \u0437\u0430\u043F\u0438\u0441\u044C \u044D\u043A\u0440\u0430\u043D\u0430 \u0434\u043B\u044F \u0435\u0433\u043E \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F.', 'zh': '\u76EE\u524D\u4EC5\u652F\u6301 macOS\uFF0CWindows \u652F\u6301\u6B63\u5728\u5F00\u53D1\u4E2D\u3002\u4E3A\u5DF2\u6709\u53CA\u65B0\u5EFA PTC \u4F1A\u8BDD\u52A0\u8F7D Computer Use\u3002\u8BF7\u5207\u6362\u5230 PTC \u6A21\u5F0F\u6765\u4F7F\u7528\uFF0C\u5E76\u6388\u4E88\u8F85\u52A9\u529F\u80FD\u548C\u5C4F\u5E55\u5F55\u5236\u6743\u9650\u3002' }, - icon: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzYiIGhlaWdodD0iMzYiIHZpZXdCb3g9IjAgMCAzNiAzNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8IS0tCiAgICBDb21wdXRlciBVc2UgcGx1Z2luIGljb24uCiAgICBBZGFwdGVkIGZyb20gTHVjaWRlICJtb3VzZS1wb2ludGVyLWNsaWNrIiAoaHR0cHM6Ly9sdWNpZGUuZGV2L2ljb25zL21vdXNlLXBvaW50ZXItY2xpY2spLgogICAgQ2hhbmdlczogc29saWQtZmlsbGVkIHBvaW50ZXIsIHByb2plY3QgcGFsZXR0ZSwgMzZ4MzYgY2FudmFzLgoKICAgIElTQyBMaWNlbnNlCiAgICBDb3B5cmlnaHQgKGMpIDIwMjYgTHVjaWRlIEljb25zIGFuZCBDb250cmlidXRvcnMKICAgIGh0dHBzOi8vZ2l0aHViLmNvbS9sdWNpZGUtaWNvbnMvbHVjaWRlL2Jsb2IvbWFpbi9MSUNFTlNFCgogICAgUGVybWlzc2lvbiB0byB1c2UsIGNvcHksIG1vZGlmeSwgYW5kL29yIGRpc3RyaWJ1dGUgdGhpcyBzb2Z0d2FyZSBmb3IgYW55CiAgICBwdXJwb3NlIHdpdGggb3Igd2l0aG91dCBmZWUgaXMgaGVyZWJ5IGdyYW50ZWQsIHByb3ZpZGVkIHRoYXQgdGhlIGFib3ZlCiAgICBjb3B5cmlnaHQgbm90aWNlIGFuZCB0aGlzIHBlcm1pc3Npb24gbm90aWNlIGFwcGVhciBpbiBhbGwgY29waWVzLgogICAgVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEICJBUyBJUyIgQU5EIFRIRSBBVVRIT1IgRElTQ0xBSU1TIEFMTCBXQVJSQU5USUVTCiAgICBXSVRIIFJFR0FSRCBUTyBUSElTIFNPRlRXQVJFIElOQ0xVRElORyBBTEwgSU1QTElFRCBXQVJSQU5USUVTIE9GCiAgICBNRVJDSEFOVEFCSUxJVFkgQU5EIEZJVE5FU1MuIElOIE5PIEVWRU5UIFNIQUxMIFRIRSBBVVRIT1IgQkUgTElBQkxFIEZPUgogICAgQU5ZIFNQRUNJQUwsIERJUkVDVCwgSU5ESVJFQ1QsIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyBPUiBBTlkgREFNQUdFUwogICAgV0hBVFNPRVZFUiBSRVNVTFRJTkcgRlJPTSBMT1NTIE9GIFVTRSwgREFUQSBPUiBQUk9GSVRTLCBXSEVUSEVSIElOIEFOCiAgICBBQ1RJT04gT0YgQ09OVFJBQ1QsIE5FR0xJR0VOQ0UgT1IgT1RIRVIgVE9SVElPVVMgQUNUSU9OLCBBUklTSU5HIE9VVCBPRgogICAgT1IgSU4gQ09OTkVDVElPTiBXSVRIIFRIRSBVU0UgT1IgUEVSRk9STUFOQ0UgT0YgVEhJUyBTT0ZUV0FSRS4KICAtLT4KICA8ZyB0cmFuc2Zvcm09InRyYW5zbGF0ZSg0LjAzNiA0LjAzNikgc2NhbGUoMS4yMjAxKSI+CiAgICA8cGF0aCBkPSJNOS4wMzcgOS42OWEuNDk4LjQ5OCAwIDAgMSAuNjUzLS42NTNsMTEgNC41YS41LjUgMCAwIDEtLjA3NC45NDlsLTQuMzQ5IDEuMDQxYTEgMSAwIDAgMC0uNzQuNzM5bC0xLjA0IDQuMzVhLjUuNSAwIDAgMS0uOTUuMDc0eiIgZmlsbD0idXJsKCNnKSIgc3Ryb2tlPSJ1cmwoI2cpIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIC8+CiAgICA8cGF0aCBkPSJNMTQgNC4xIDEyIDYiIHN0cm9rZT0iIzUxQ0ZEQiIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIC8+CiAgICA8cGF0aCBkPSJtNS4xIDgtMi45LS44IiBzdHJva2U9IiM1MUNGREIiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiAvPgogICAgPHBhdGggZD0ibTYgMTItMS45IDIiIHN0cm9rZT0iIzUxQ0ZEQiIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIC8+CiAgICA8cGF0aCBkPSJNNy4yIDIuMiA4IDUuMSIgc3Ryb2tlPSIjNTFDRkRCIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgLz4KICA8L2c+CiAgPGRlZnM+CiAgICA8bGluZWFyR3JhZGllbnQgaWQ9ImciIHgxPSI5IiB5MT0iOSIgeDI9IjIxIiB5Mj0iMjEiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KICAgICAgPHN0b3Agc3RvcC1jb2xvcj0iIzg2QjhGNSIgLz4KICAgICAgPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjNTI2OUUxIiAvPgogICAgPC9saW5lYXJHcmFkaWVudD4KICA8L2RlZnM+Cjwvc3ZnPgo=', - }, - }, ] diff --git a/packages/util/official-bundles/tests/official-bundles.spec.ts b/packages/util/official-bundles/tests/official-bundles.spec.ts index bffbafcaed..716355ffe6 100644 --- a/packages/util/official-bundles/tests/official-bundles.spec.ts +++ b/packages/util/official-bundles/tests/official-bundles.spec.ts @@ -4,10 +4,8 @@ import { describe, expect, it } from 'vitest' import { OFFICIAL_ON_DEMAND_CATALOG, ON_DEMAND_BUNDLES, PROFILE_TEMPLATES } from '../src/index.ts' describe('Official on-demand catalog', () => { - it('offers native subagents and default-hidden Computer Use with offline metadata', () => { - expect(ON_DEMAND_BUNDLES).toEqual(['@deepseek-ai/dsh-subagent-claude-code', '@deepseek-ai/dsh-subagent-codex', '@deepseek-ai/dsh-cua-bundle']) - expect(OFFICIAL_ON_DEMAND_CATALOG.find(entry => entry.packageName === '@deepseek-ai/dsh-cua-bundle')) - .toMatchObject({ platforms: ['darwin'], listedByDefault: false }) + it('offers exactly the two native subagent integrations with offline localized metadata', () => { + expect(ON_DEMAND_BUNDLES).toEqual(['@deepseek-ai/dsh-subagent-claude-code', '@deepseek-ai/dsh-subagent-codex']) expect(OFFICIAL_ON_DEMAND_CATALOG.map(entry => entry.packageName)).toEqual(ON_DEMAND_BUNDLES) for (const entry of OFFICIAL_ON_DEMAND_CATALOG) { expect(entry.meta.icon).toMatch(/^data:image\/svg\+xml;base64,/) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index afc4a7eac6..2a5b1e9295 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -336,6 +336,9 @@ importers: '@deepseek-ai/dsh-cordis-client-runner': specifier: workspace:* version: link:../../packages/extensions/cordis-client-runner + '@deepseek-ai/dsh-cua-bundle': + specifier: workspace:* + version: link:../../packages/experimental/cua-bundle '@deepseek-ai/dsh-experimental-agent-team-profile': specifier: workspace:* version: link:../../packages/experimental/agent-team-profile diff --git a/scripts/local-bundle-registry.spec.ts b/scripts/local-bundle-registry.spec.ts index ea047d8aa6..fb2f9fc1e5 100644 --- a/scripts/local-bundle-registry.spec.ts +++ b/scripts/local-bundle-registry.spec.ts @@ -133,7 +133,8 @@ describe('catalog and local closure', () => { // A vendor package keeps its own version line, so a run must not assume one shared version. expect(packages.get('@deepseek-ai/cordis')?.manifest.version) .not.toBe(packages.get('@deepseek-ai/dsh-brand')?.manifest.version) - expect(selection.foreignTargets).toEqual(process.platform === 'darwin' ? [] : ['@deepseek-ai/dsh-experimental-cua-macos']) + // Nothing in this closure is built for another platform, on any host. + expect(selection.foreignTargets).toEqual([]) }) it('follows install, optional, and required peer edges but not optional peers', () => { diff --git a/snapshots/web/creation-recommendations/session.v4.jsonl b/snapshots/web/creation-recommendations/session.v4.jsonl index 9cfead0a39..d3c479a6d3 100644 --- a/snapshots/web/creation-recommendations/session.v4.jsonl +++ b/snapshots/web/creation-recommendations/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"session/title","data":{"title":"I wish I had a","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_creation_skill","name":"skill","arguments":"{\"name\":\"personalized-pages\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1792674450282,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792674450282,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_creation_skill","name":"skill","arguments":"{\"name\":\"personalized-pages\"}"}}},{"type":"chunk","time":1792674450283,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_creation_skill","name":"skill","arguments":"{\"name\":\"personalized-pages\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_creation_skill"},"toolCallId":"call_creation_skill","content":[{"type":"text","text":"\n\nResources for this skill are managed by provider \"dsh-personalized-pages\".\nLoad referenced resources only as needed.\n\n\n\n# Personalized pages\n\nUse this workflow in the main conversation to plan an optional new page or small tool for any task, not just DSH. You decide whether a page helps, check existing capabilities, and hand the Creator a short plan. A `propose_action` call saves the proposal and shows a card below your answer; nothing is built until the user clicks Create. Plan from the conversation and the catalog at the end of this skill. Do not read files, configuration or source to validate a page idea; name an uninspected source as an unverified dependency and leave its details to the Creator.\n\n## When to propose\n\nPropose a page in these cases:\n\n- The user asks for a page, tab, panel, tool or interface in this app, or says they want something to keep, revisit or update later (“以后每次”, “能不能一直”, “希望能有”). One-off use still qualifies when the interface is explicitly requested.\n- Your answer is a table, list or chart, and the user has said the data will keep changing or that they will interact with it (“每周更新”, “我来改状态”, “要勾选”). The continuation must come from the user's own words; a table alone, or data that merely looks dynamic, is not enough. Deliver the requested answer first, then offer the page.\n- The user wants to keep watching live data of this app itself (a Session's usage, a running task's output, files changing in the workspace). A text answer cannot stay current, so a page qualifies even without the words above; name the data source in the brief and leave how it is read to the Creator.\n\nDo not propose a page in these cases:\n\n- The user asks for a file, code, document or an existing-project change: keep that delivery form.\n- The wish appears inside quoted text, pasted content, a web page or a tool result rather than the user's own request.\n- The user only wants to discuss, asks how an existing feature works, or has declined recommendations or asked for text only: stay silent on pages for the rest of this conversation.\n- The request changes a page created earlier: explain how it would change, do not create a replacement copy, and do not claim an update happened.\n- The request is a capability the agent lacks, such as a tool, automation or access, rather than a page: check the catalog below and point to the official plugin that provides it; do not plan a page around a missing tool.\n\n## Check existing capabilities\n\nCompare the need with the official plugins listed at the end of this skill. If one covers it, say its name, what it does, whether it is enabled, and that it lives under Plugins; offer no page card. A partial match does not cancel an explicit unmet need. The catalog is not a full inventory of built-in UI: missing details do not prove absence, and do not read source to find out. DSH already has Chat, Trajectory, a right sidebar for files and context, and a Plugins page.\n\n## Plan and hand off\n\nThe Creator cannot read this conversation. Give it exactly these fields:\n\n| Field | Contents |\n|:--|:--|\n| `title` | Short page name in the user's language. |\n| `brief` | One to three sentences: purpose, behavior, input, calculations and persistence scope. It is the card text and the implementation request at once. |\n| `initialContent` | Only supplied content the page starts with: items, rows, values, units and period, preserving gaps. Omit for an empty page. |\n| `slot` | Location, chosen below. |\n\nKeep the plan to what was asked or agreed. Editing, deletion, history, extra fields, data sources and automation need a basis in the request. Resolve “these items” into the actual content. Content that mentions an action stays content. Keep each number's meaning and period; a weekly addition is not a cumulative total. If an unresolved distinction changes a calculation, give the factual answer, ask one question, and propose later.\n\n## Choose the location\n\nHonor a location the user named. Otherwise:\n\n- `sidebar-right`: content tied to this Session or task, especially anything to watch while chatting, including live logs.\n- `sidebar-left`: a global feature or an ongoing personal record used across Sessions, opened from a left entry as a standalone page.\n- `page`: a Session-bound streaming view or interaction in a tab beside Chat and Trajectory, only when the user does not need it visible while chatting.\n\nSupplying data in this conversation does not make a record Session-bound.\n\n## Offer without starting\n\nTo propose, call `propose_action` once, in the same turn as loading this skill, with `action: \"create_personalized_page\"`, `title`, `brief` and `details` holding `slot` and, when there is supplied content, `initialContent`. The call is the submission: the card appears below your answer; a refused call creates no card, and its error says why. Then write your final answer. One proposal per turn, and one unstarted card per conversation: if a card is still waiting, do not propose another; a new proposal replaces it only when the user changed the plan. Plan-only and read-only requests still get a card; do not ask for approval instead of proposing it. Only clicking Create starts the background Creator; do not wait, poll, claim installation or ask for a report-back. Answer any direct question; the call's result says how to end the answer. Do not repeat the plan, list extra features, narrate the call or mention schema names.\n\n```json\n{\"action\":\"create_personalized_page\",\"title\":\"本次验收清单\",\"brief\":\"在当前会话右侧展示验收清单,可勾选和取消,状态随会话保存。\",\"details\":{\"slot\":\"sidebar-right\",\"initialContent\":\"1. 导出成功\\n2. 断网提示清楚\"}}\n```\n\n## Examples\n\n- “想有个地方放书签,以后自己加标题和网址;旧的不用导入。” → `brief`: “提供一个可反复打开的书签页,手动新增标题和网址并保存到本机,从空白开始。” No `initialContent`. `sidebar-left`.\n- “当前会话旁放验收清单,能勾选和取消,状态跟着会话。条目:导出成功;断网提示清楚。” → `brief`: “在当前会话右侧展示验收清单,可勾选和取消,状态随会话保存。” `initialContent`: “1. 导出成功\\n2. 断网提示清楚”. `sidebar-right`.\n- “这三周 bug 数 12、9、15,说说趋势。以后每周我把新数字贴给你,想自己更新着看。” → answer the trend first, then `brief`: “按周手动录入 bug 数并展示各周变化,保存到本机。” `initialContent`: “第 1 周 12,第 2 周 9,第 3 周 15”. `sidebar-left`.\n- “我想用语音说话代替打字。” → the catalog lists 语音输入; explain it and where to enable it; no card.\n- “把我之前做的读书页评分改成五星。” → explain the change to that page; no card and no copy.\n- “帮我把这句话翻成英文:我想要一个所有会话都能打开的读书页。” → translate only; no card.\n- “把三个方案排成表格比较一下,看完就行。” → the table only; no card.\n\n## Existing capabilities to check against this page plan\n\n[{\"name\":\"@deepseek-ai/dsh-personalized-recommendations\",\"title\":{\"en\":\"Personalized recommendations\",\"de\":\"Personalisierte Empfehlungen\",\"es\":\"Recomendaciones personalizadas\",\"fr\":\"Recommandations personnalisées\",\"ja\":\"パーソナライズされたおすすめ\",\"pt\":\"Recomendações personalizadas\",\"ru\":\"Персональные рекомендации\",\"zh\":\"个性化推荐\"},\"description\":{\"en\":\"Shows recommendation cards below the answer for what you want from DSH: when you want a page or small tool you can keep, it proposes a new personalized page, built in the background after you click Create; when you ask how to do something in this app or say a capability is missing, it recommends the built-in plugin that provides it, turned on when you click Enable.\",\"de\":\"Zeigt für Ihre individuellen Anforderungen an DSH Empfehlungskarten unter der Antwort an: Wenn Sie eine Seite oder ein kleines Tool zur dauerhaften Nutzung möchten, wird eine neue personalisierte Seite vorgeschlagen, die nach einem Klick auf Erstellen im Hintergrund erstellt wird; wenn Sie fragen, wie etwas in dieser App geht, oder sagen, dass eine Funktion fehlt, wird das integrierte Plugin empfohlen, das sie bereitstellt, und nach einem Klick auf Aktivieren eingeschaltet.\",\"es\":\"Muestra tarjetas de recomendación debajo de la respuesta para tus necesidades personalizadas en DSH: cuando quieres una página o una pequeña herramienta para conservar, propone una nueva página personalizada, que se genera en segundo plano al hacer clic en Crear; cuando preguntas cómo hacer algo en esta aplicación o dices que falta una función, recomienda el complemento integrado que la ofrece, que se activa al hacer clic en Habilitar.\",\"fr\":\"Affiche des cartes de recommandation sous la réponse pour vos besoins personnalisés dans DSH : lorsque vous voulez une page ou un petit outil à conserver, propose une nouvelle page personnalisée, générée en arrière-plan après un clic sur Créer ; lorsque vous demandez comment faire quelque chose dans cette application ou signalez qu’une fonctionnalité manque, recommande le plugin intégré qui la fournit, activé lorsque vous cliquez sur Activer.\",\"ja\":\"DSH に対するあなた個人のニーズに合わせて、回答の下におすすめカードを表示します。長く使えるページや小さなツールが欲しいときは新しいパーソナルページを提案し、「作成」をクリックするとバックグラウンドで生成します。このアプリで何かをする方法を尋ねたときや機能が足りないと言ったときは、それを提供する内蔵プラグインを推薦し、「有効にする」をクリックすると有効になります。\",\"pt\":\"Mostra cartões de recomendação abaixo da resposta para suas necessidades personalizadas no DSH: quando você quer uma página ou uma pequena ferramenta para manter, propõe uma nova página personalizada, gerada em segundo plano depois que você clica em Criar; quando você pergunta como fazer algo neste aplicativo ou diz que falta um recurso, recomenda o plug-in integrado que o oferece, ativado quando você clica em Ativar.\",\"ru\":\"Показывает карточки рекомендаций под ответом с учетом ваших индивидуальных потребностей в DSH: когда вам нужна страница или небольшой инструмент для постоянного использования, предлагает новую персональную страницу, которая создается в фоне после нажатия «Создать»; когда вы спрашиваете, как что-то сделать в этом приложении, или говорите, что не хватает какой-то возможности, рекомендует встроенный плагин, который ее предоставляет, и включает его после нажатия «Включить».\",\"zh\":\"针对你对 DSH 的个性化需求,在回答下方展示推荐卡片:想要能长期使用的页面或小工具时,提议新增个性化页面,点击创建后在后台生成;问到本应用怎么做某件事或缺少某项能力时,推荐对应的内置插件,点击启用后开启。\"},\"enabled\":true},{\"name\":\"@deepseek-ai/dsh-experimental-agent-team-profile\",\"title\":{\"en\":\"Agent teams\",\"de\":\"Agententeams\",\"es\":\"Equipos de agentes\",\"fr\":\"Équipes d'agents\",\"ja\":\"エージェントチーム\",\"pt\":\"Equipes de agentes\",\"ru\":\"Команды агентов\",\"zh\":\"智能体团队\"},\"description\":{\"en\":\"Lets the agent you talk to split a job among named teammates, track it on a shared task board, and report back with their results.\",\"de\":\"Ermöglicht dem Agenten, mit dem Sie sprechen, eine Aufgabe auf benannte Teammitglieder aufzuteilen, sie auf einem gemeinsamen Aufgabenboard zu verfolgen und Ihnen mit deren Ergebnissen zu berichten.\",\"es\":\"Permite que el agente con el que habla reparta un trabajo entre compañeros con nombre, lo siga en un tablero de tareas compartido y le informe con sus resultados.\",\"fr\":\"Permet à l'agent avec lequel vous parlez de répartir un travail entre des coéquipiers nommés, de le suivre sur un tableau de tâches partagé et de vous rendre compte de leurs résultats.\",\"ja\":\"対話しているエージェントが、仕事を名前付きのチームメイトに分担させ、共有タスクボードで進捗を追跡し、チームメイトの結果をまとめて報告します。\",\"pt\":\"Permite que o agente com quem você conversa divida um trabalho entre colegas de equipe nomeados, acompanhe-o em um quadro de tarefas compartilhado e informe você com os resultados deles.\",\"ru\":\"Позволяет агенту, с которым вы общаетесь, распределить работу между именованными участниками команды, отслеживать её на общей доске задач и отчитываться перед вами об их результатах.\",\"zh\":\"让与你对话的智能体把工作分给有名字的队友,在共享任务看板上跟踪进度,并汇总队友的结果向你汇报。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-inspector-profile\",\"title\":{\"en\":\"Developer tools\",\"de\":\"Entwicklertools\",\"es\":\"Herramientas de desarrollador\",\"fr\":\"Outils de développement\",\"ja\":\"開発者ツール\",\"pt\":\"Ferramentas de desenvolvedor\",\"ru\":\"Инструменты разработчика\",\"zh\":\"开发者工具\"},\"description\":{\"en\":\"For troubleshooting: view what DSH recorded for a session in Session log, inspect per-turn and per-step statistics in the Statistics tab, and debug the DSH backend in Chrome DevTools.\",\"de\":\"Zur Fehlersuche: Sehen Sie in „Sitzungsprotokoll“, was DSH für eine Sitzung aufgezeichnet hat, prüfen Sie im Tab „Statistik“ Kontext, Dauer, Cache und Werkzeugkosten pro Runde und Schritt und debuggen Sie das DSH-Backend in Chrome DevTools.\",\"es\":\"Para solucionar problemas: vea en «Registro de sesión» lo que DSH registró de una sesión, consulte el contexto, los tiempos, la caché y el coste de herramientas por turno y paso en la pestaña «Estadísticas», y depure el backend de DSH en Chrome DevTools.\",\"fr\":\"Pour le dépannage : consultez dans « Journal de session » ce que DSH a enregistré pour une session, examinez le contexte, les durées, le cache et le coût des outils par tour et étape dans l’onglet « Statistiques », et déboguez le backend de DSH dans Chrome DevTools.\",\"ja\":\"トラブルシューティング用です。「セッションログ」で DSH がセッションについて記録した内容を確認し、「統計」タブでターン/ステップごとのコンテキスト、時間、キャッシュ、ツールコストを確認し、Chrome DevTools で DSH バックエンドをデバッグできます。\",\"pt\":\"Para solução de problemas: veja em «Registro da sessão» o que o DSH registrou de uma sessão, consulte contexto, tempos, cache e custo de ferramentas por turno e etapa na aba «Estatísticas» e depure o backend do DSH no Chrome DevTools.\",\"ru\":\"Для диагностики: просматривайте в «Журнале сеанса», что DSH записал для сеанса, смотрите контекст, время, кэш и стоимость инструментов по ходам и шагам на вкладке «Статистика» и отлаживайте бэкенд DSH в Chrome DevTools.\",\"zh\":\"用于排查问题:在「会话数据诊断」中查看 DSH 为会话记录的内容,在「统计」页签查看每轮/每步的上下文、耗时、缓存和工具成本,并在 Chrome DevTools 中调试 DSH 后端。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-voice-input-bundle\",\"title\":{\"en\":\"Voice input\",\"de\":\"Spracheingabe\",\"es\":\"Entrada de voz\",\"fr\":\"Saisie vocale\",\"ja\":\"音声入力\",\"pt\":\"Entrada de voz\",\"ru\":\"Голосовой ввод\",\"zh\":\"语音输入\"},\"description\":{\"en\":\"Transcribe recordings locally with SenseVoice; first use requires installing dependencies.\",\"de\":\"Transkribieren Sie Aufnahmen lokal mit SenseVoice; Für die erste Verwendung müssen Abhängigkeiten installiert werden.\",\"es\":\"Transcribe grabaciones localmente con SenseVoice; El primer uso requiere instalar dependencias.\",\"fr\":\"Transcrivez les enregistrements localement avec SenseVoice ; la première utilisation nécessite l'installation de dépendances.\",\"ja\":\"ローカルの SenseVoice で録音を文字に起こします。初回利用時には依存関係のインストールが必要です。\",\"pt\":\"Transcreva gravações localmente com SenseVoice; o primeiro uso requer a instalação de dependências.\",\"ru\":\"Транскрибируйте записи локально с помощью SenseVoice; при первом использовании требуется установка зависимостей.\",\"zh\":\"在本机使用 SenseVoice 转写录音,首次使用需安装依赖。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-auto-review\",\"title\":{\"en\":\"Auto authorization review\",\"de\":\"Automatische Autorisierungsüberprüfung\",\"es\":\"Revisión de autorización automática\",\"fr\":\"Examen des autorisations automatiques\",\"ja\":\"自動認可レビュー\",\"pt\":\"Revisão de autorização automática\",\"ru\":\"Проверка автоматической авторизации\",\"zh\":\"自动授权审查\"},\"description\":{\"en\":\"Adds an Auto review access mode: before each tool call, a model checks it against what you asked for, runs allowed calls at once, and holds denied calls for your approval.\",\"de\":\"Fügt den Zugriffsmodus „Auto review“ hinzu: Vor jedem Tool-Aufruf prüft ein Modell den Aufruf anhand Ihrer Anforderung; zugelassene Aufrufe laufen sofort, abgelehnte Aufrufe warten auf Ihre Genehmigung.\",\"es\":\"Añade el modo de acceso “Auto review”: antes de cada llamada a una herramienta, un modelo comprueba la llamada frente a lo que usted pidió; las llamadas permitidas se ejecutan de inmediato y las denegadas esperan su aprobación.\",\"fr\":\"Ajoute le mode d'accès « Auto review » : avant chaque appel d'outil, un modèle vérifie l'appel par rapport à ce que vous avez demandé ; les appels autorisés s'exécutent immédiatement et les appels refusés attendent votre approbation.\",\"ja\":\"「自動認可レビュー」アクセスモードを追加します。各ツール呼び出しの前に、モデルがその呼び出しをあなたの依頼内容と照らし合わせて確認し、許可された呼び出しは即座に実行され、拒否された呼び出しはあなたの承認を待ちます。\",\"pt\":\"Adiciona o modo de acesso “Auto review”: antes de cada chamada de ferramenta, um modelo verifica a chamada em relação ao que você pediu; as chamadas permitidas são executadas imediatamente e as negadas aguardam sua aprovação.\",\"ru\":\"Добавляет режим доступа «Auto review»: перед каждым вызовом инструмента модель сверяет вызов с вашей просьбой; разрешённые вызовы выполняются сразу, а отклонённые ждут вашего одобрения.\",\"zh\":\"提供“自动审查”访问模式:每次工具调用前,由模型对照你的要求检查,获准的调用立即运行,被拒绝的调用等你审批。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-cot-translation-bundle\",\"title\":{\"en\":\"Machine translation of reasoning\",\"de\":\"Maschinelle Übersetzung der Argumentation\",\"es\":\"Traducción automática de razonamiento\",\"fr\":\"Traduction automatique du raisonnement\",\"ja\":\"思考内容の機械翻訳\",\"pt\":\"Tradução automática de raciocínio\",\"ru\":\"Машинный перевод рассуждений\",\"zh\":\"思考过程机器翻译\"},\"description\":{\"en\":\"Translates expanded Think rows into your chosen language as the agent writes them, and View original switches back.\",\"de\":\"Übersetzt aufgeklappte „Denken Sie nach“-Zeilen, während der Agent sie schreibt, in die von Ihnen gewählte Sprache, und „Original ansehen“ wechselt zurück.\",\"es\":\"Traduce las filas “pensar” expandidas al idioma que elija mientras el agente las escribe, y “Ver original” vuelve al texto original.\",\"fr\":\"Traduit les lignes « Pensez » développées dans la langue de votre choix pendant que l'agent les écrit, et « Voir l'original » permet de revenir au texte d'origine.\",\"ja\":\"エージェントが書き出すのと同時に、展開された「思考」行を選択した言語に翻訳します。「原文を表示」で原文に戻せます。\",\"pt\":\"Traduz as linhas “Pense” expandidas para o idioma que você escolher enquanto o agente as escreve, e “Ver original” volta ao texto original.\",\"ru\":\"Переводит развёрнутые строки «Подумайте» на выбранный вами язык по мере того, как агент их пишет, а «Посмотреть оригинал» возвращает исходный текст.\",\"zh\":\"智能体输出时,把展开的“思考”行翻译成你选择的语言,点击“查看原文”可切换回原文。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-badge-skill-bundle\",\"title\":{\"en\":\"DSH badge skill\",\"de\":\"DSH-Abzeichen-Fertigkeit\",\"es\":\"Habilidad de insignia DSH\",\"fr\":\"Compétence du badge DSH\",\"ja\":\"DSH バッジスキル\",\"pt\":\"DSH habilidade de distintivo\",\"ru\":\"DSH значок навыка\",\"zh\":\"DSH 徽章技能\"},\"description\":{\"en\":\"Let agents add a “powered by dsh” badge to documents, pull requests, and other outputs.\",\"de\":\"Lassen Sie Agenten Dokumente, Pull-Requests und andere Ausgaben mit einem „powered by dsh“-Badge versehen.\",\"es\":\"Permita que los agentes agreguen una insignia \\\"con tecnología de dsh\\\" a documentos, solicitudes de extracción y otros resultados.\",\"fr\":\"Laissez les agents ajouter un badge « propulsé par dsh » aux documents, demandes d'extraction et autres sorties.\",\"ja\":\"エージェントが文書や PR などの成果物に「powered by dsh」バッジを追加できます。\",\"pt\":\"Permita que os agentes adicionem um selo “powered by dsh” a documentos, pull requests e outros resultados.\",\"ru\":\"Позвольте агентам добавлять значок «Powered by dsh» к документам, запросам на включение и другим результатам.\",\"zh\":\"让 Agent 为文档、PR 等产出添加「powered by dsh」徽章。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-ralph-bundle\",\"title\":{\"en\":\"Ralph loops\",\"de\":\"Ralph-Loops\",\"es\":\"Bucles de Ralph\",\"fr\":\"Boucles Ralph\",\"ja\":\"Ralph ループ\",\"pt\":\"Loops de Ralph\",\"ru\":\"Ральф петли\",\"zh\":\"Ralph 循环\"},\"description\":{\"en\":\"Ask for a Ralph loop with a goal, and the agent starts a fresh agent on it round after round until the goal is met, a blocker is reported, or the round limit is reached.\",\"de\":\"Bitten Sie um eine Ralph-Schleife mit einem Ziel, und der Agent startet Runde um Runde einen neuen Agenten darauf, bis das Ziel erreicht ist, ein Hindernis gemeldet wird oder das Rundenlimit erreicht ist.\",\"es\":\"Pida un bucle Ralph con un objetivo, y el agente inicia un agente nuevo sobre él ronda tras ronda hasta que se cumpla el objetivo, se informe de un bloqueo o se alcance el límite de rondas.\",\"fr\":\"Demandez une boucle Ralph avec un objectif, et l'agent lance un nouvel agent dessus, tour après tour, jusqu'à ce que l'objectif soit atteint, qu'un blocage soit signalé ou que la limite de tours soit atteinte.\",\"ja\":\"目標を指定して Ralph ループを依頼すると、エージェントは、目標が達成されるか、阻害要因が報告されるか、ラウンド数の上限に達するまで、ラウンドごとに新しいエージェントを起動してその目標に取り組ませます。\",\"pt\":\"Peça um loop Ralph com um objetivo, e o agente inicia um novo agente nele rodada após rodada até que o objetivo seja atingido, um bloqueio seja informado ou o limite de rodadas seja alcançado.\",\"ru\":\"Попросите запустить цикл Ralph с целью, и агент будет раунд за раундом запускать для неё нового агента, пока цель не будет достигнута, не будет сообщено о препятствии или не будет достигнут лимит раундов.\",\"zh\":\"要求用 Ralph 循环完成一个目标后,智能体会一轮接一轮地启动新的智能体处理它,直到目标达成、报告受阻或达到轮次上限。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-session-titles-bundle\",\"title\":{\"en\":\"Conversation-following titles\",\"de\":\"Konversationsfolgende Titel\",\"es\":\"Títulos que siguen la conversación\",\"fr\":\"Titres de suivi de conversation\",\"ja\":\"会話に追従するタイトル\",\"pt\":\"Títulos que acompanham conversas\",\"ru\":\"Заголовки, следующие за разговором\",\"zh\":\"随对话更新的标题\"},\"description\":{\"en\":\"Writes a session's title from all of your messages and updates it when the main task changes, instead of only from the first message.\",\"de\":\"Erstellt den Titel einer Sitzung aus all Ihren Nachrichten und aktualisiert ihn, wenn sich die Hauptaufgabe ändert, statt ihn nur aus der ersten Nachricht zu bilden.\",\"es\":\"Escribe el título de una sesión a partir de todos sus mensajes y lo actualiza cuando cambia la tarea principal, en lugar de basarse solo en el primer mensaje.\",\"fr\":\"Rédige le titre d'une session à partir de tous vos messages et le met à jour lorsque la tâche principale change, au lieu de se baser uniquement sur le premier message.\",\"ja\":\"最初のメッセージだけでなく、あなたのすべてのメッセージからセッションのタイトルを作成し、主なタスクが変わったときに更新します。\",\"pt\":\"Escreve o título de uma sessão a partir de todas as suas mensagens e o atualiza quando a tarefa principal muda, em vez de usar apenas a primeira mensagem.\",\"ru\":\"Составляет заголовок сеанса по всем вашим сообщениям и обновляет его при смене основной задачи, а не только по первому сообщению.\",\"zh\":\"根据你的所有消息生成会话标题,并在主要任务变化时更新,而不是只根据第一条消息生成。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-terminal-bundle\",\"title\":{\"en\":\"Persistent terminals\",\"de\":\"Persistente Terminals\",\"es\":\"Terminales persistentes\",\"fr\":\"Terminaux persistants\",\"ja\":\"永続ターミナル\",\"pt\":\"Terminais persistentes\",\"ru\":\"Постоянные терминалы\",\"zh\":\"持久终端\"},\"description\":{\"en\":\"Gives the agent terminals whose processes keep running in the background between tool calls, so it can start a dev server or REPL and come back later to read output or type input.\",\"de\":\"Stellt dem Agenten Terminals bereit, deren Prozesse zwischen Tool-Aufrufen im Hintergrund weiterlaufen, sodass er einen Entwicklungsserver oder eine REPL starten und später zurückkehren kann, um Ausgaben zu lesen oder Eingaben zu tippen.\",\"es\":\"Proporciona al agente terminales cuyos procesos siguen ejecutándose en segundo plano entre llamadas a herramientas, de modo que puede iniciar un servidor de desarrollo o un REPL y volver más tarde para leer la salida o escribir entradas.\",\"fr\":\"Fournit à l'agent des terminaux dont les processus continuent de s'exécuter en arrière-plan d'un appel d'outil à l'autre, afin qu'il puisse lancer un serveur de développement ou un REPL et revenir plus tard lire la sortie ou saisir des entrées.\",\"ja\":\"エージェントにターミナルを提供します。プロセスはツール呼び出し間もバックグラウンドで実行され続けるため、エージェントは開発サーバーや REPL を起動し、後から出力を読んだり入力したりできます。\",\"pt\":\"Fornece ao agente terminais cujos processos continuam em execução em segundo plano entre chamadas de ferramentas, para que ele possa iniciar um servidor de desenvolvimento ou um REPL e voltar depois para ler a saída ou digitar entradas.\",\"ru\":\"Предоставляет агенту терминалы, процессы которых продолжают работать в фоне между вызовами инструментов, поэтому агент может запустить сервер разработки или REPL и позже вернуться, чтобы прочитать вывод или ввести данные.\",\"zh\":\"为智能体提供终端,进程在多次工具调用之间持续在后台运行,因此它可以启动开发服务器或 REPL,稍后再读取输出或继续输入。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-liveshare\",\"title\":{\"en\":\"LiveShare Session Sharing\",\"de\":\"LiveShare-Sitzungsfreigabe\",\"es\":\"Compartir sesión de LiveShare\",\"fr\":\"Partage de session LiveShare\",\"ja\":\"LiveShare セッション共有\",\"pt\":\"Compartilhamento de sessão do LiveShare\",\"ru\":\"Совместный доступ к сеансу LiveShare\",\"zh\":\"LiveShare 会话分享\"},\"description\":{\"en\":\"Share the current Session with a colleague, who can drive it in a browser, edit files inside the granted workspace when the share allows writes, or branch their own Session from the completed history.\",\"de\":\"Teilt die aktuelle Sitzung mit einer Kollegin oder einem Kollegen, die oder der sie im Browser bedienen, bei erlaubten Schreibzugriffen Dateien im freigegebenen Arbeitsbereich bearbeiten oder aus der abgeschlossenen Historie eine eigene Sitzung abzweigen kann.\",\"es\":\"Comparte la sesión actual con un compañero, que puede dirigirla en un navegador, editar archivos dentro del espacio de trabajo concedido cuando el recurso compartido permite escritura, o crear su propia sesión a partir del historial completado.\",\"fr\":\"Partagez la session en cours avec un collègue, qui peut la piloter dans un navigateur, modifier des fichiers dans l'espace de travail accordé lorsque le partage autorise l'écriture, ou créer sa propre session à partir de l'historique terminé.\",\"ja\":\"現在のセッションを同僚と共有し、ブラウザから操作してもらう、共有が書き込みを許可する場合は付与されたワークスペース内のファイルを編集してもらう、または完了した履歴から自分のセッションを分岐してもらえます。\",\"pt\":\"Compartilhe a sessão atual com um colega, que pode conduzi-la no navegador, editar arquivos dentro do espaço de trabalho concedido quando o compartilhamento permite escrita, ou ramificar a própria sessão a partir do histórico concluído.\",\"ru\":\"Поделитесь текущим сеансом с коллегой: он сможет управлять им в браузере, редактировать файлы в предоставленном рабочем пространстве, если общий доступ разрешает запись, или ответвить собственный сеанс из завершённой истории.\",\"zh\":\"把当前会话分享给同事,对方可在浏览器中驱动该会话、在分享允许写入时修改授权工作区内的文件,或从已完成历史分支出自己的会话。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-session-search\",\"title\":{\"en\":\"Session search\",\"de\":\"Sitzungssuche\",\"es\":\"búsqueda de sesión\",\"fr\":\"Recherche de sessions\",\"ja\":\"セッション検索\",\"pt\":\"Pesquisa de sessão\",\"ru\":\"Поиск сеанса\",\"zh\":\"会话搜索\"},\"description\":{\"en\":\"Ask about earlier work, such as “How did we fix the pool leak last week?”, and the agent searches your earlier sessions in the same workspace to answer.\",\"de\":\"Fragen Sie nach früherer Arbeit, etwa „Wie haben wir letzte Woche das Pool-Leck behoben?“, und der Agent durchsucht Ihre früheren Sitzungen aus demselben Arbeitsverzeichnis, um zu antworten.\",\"es\":\"Pregunte por trabajo anterior, como “¿Cómo arreglamos la fuga del pool la semana pasada?”, y el agente busca en sus sesiones anteriores del mismo directorio de trabajo para responder.\",\"fr\":\"Posez une question sur un travail antérieur, par exemple « Comment avons-nous corrigé la fuite du pool la semaine dernière ? », et l'agent recherche dans vos sessions antérieures du même répertoire de travail pour répondre.\",\"ja\":\"「先週プールのリークをどう直した?」のように以前の作業について尋ねると、エージェントは同じ作業ディレクトリの過去のセッションを検索して回答します。\",\"pt\":\"Pergunte sobre trabalhos anteriores, como “Como corrigimos o vazamento do pool na semana passada?”, e o agente pesquisa suas sessões anteriores do mesmo diretório de trabalho para responder.\",\"ru\":\"Спросите о прошлой работе, например «Как мы исправили утечку в пуле на прошлой неделе?», и агент выполнит поиск по вашим прошлым сеансам из того же рабочего каталога, чтобы ответить.\",\"zh\":\"询问以往的工作,例如“上周我们是怎么修好连接池泄漏的?”,智能体会搜索同一工作区的历史会话来回答。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-tool-worktree\",\"title\":{\"en\":\"Git worktrees\",\"de\":\"Git-Arbeitsbäume\",\"es\":\"árboles de trabajo de git\",\"fr\":\"Arbres de travail Git\",\"ja\":\"Git ワークツリー\",\"pt\":\"Árvores de trabalho Git\",\"ru\":\"Рабочие деревья Git\",\"zh\":\"Git 工作树\"},\"description\":{\"en\":\"Ask for work on a new branch, and the agent creates a separate Git worktree and continues there, leaving your current checkout as it is.\",\"de\":\"Bitten Sie um Arbeit auf einem neuen Branch, und der Agent erstellt einen separaten Git-Worktree und arbeitet dort weiter, während Ihr aktueller Checkout unverändert bleibt.\",\"es\":\"Pida trabajar en una rama nueva, y el agente crea un worktree de Git independiente y continúa allí, dejando su checkout actual tal como está.\",\"fr\":\"Demandez à travailler sur une nouvelle branche, et l'agent crée un worktree Git distinct et y poursuit le travail, en laissant votre copie de travail actuelle telle quelle.\",\"ja\":\"新しいブランチでの作業を依頼すると、エージェントは別の Git ワークツリーを作成してそこで作業を続け、現在のチェックアウトはそのまま残します。\",\"pt\":\"Peça para trabalhar em um novo branch, e o agente cria um worktree do Git separado e continua lá, deixando seu checkout atual como está.\",\"ru\":\"Попросите поработать в новой ветке, и агент создаст отдельное рабочее дерево Git и продолжит работу там, оставив вашу текущую рабочую копию как есть.\",\"zh\":\"要求在新分支上工作时,智能体会创建单独的 Git 工作树并在其中继续,你当前的工作树保持原样。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-plugin-market-bundle\",\"title\":{\"en\":\"Custom plugin indexes\",\"de\":\"Benutzerdefinierte Plugin-Indizes\",\"es\":\"Índices de complementos personalizados\",\"fr\":\"Index de plugins personnalisés\",\"ja\":\"カスタムプラグインインデックス\",\"pt\":\"Índices de plug-ins personalizados\",\"ru\":\"Пользовательские индексы плагинов\",\"zh\":\"自定义插件索引\"},\"description\":{\"en\":\"Adds a Discover tab to Plugins, where you browse and install plugins from plugin indexes you add.\",\"de\":\"Fügt unter „Plugins“ den Tab „Entdecken“ hinzu, in dem Sie Plugins aus von Ihnen hinzugefügten Plugin-Indizes durchsuchen und installieren.\",\"es\":\"Añade la pestaña “Descubrir” a “Complementos”, donde puede explorar e instalar complementos de los índices de complementos que agregue.\",\"fr\":\"Ajoute à « Plugins » un onglet « Découvrez » où vous parcourez et installez des plugins provenant des index de plugins que vous ajoutez.\",\"ja\":\"「プラグイン」に「見つける」タブを追加し、追加したプラグインインデックスからプラグインを閲覧・インストールできるようにします。\",\"pt\":\"Adiciona a guia “Descubra” a “Plug-ins”, onde você navega e instala plug-ins dos índices de plug-ins que adiciona.\",\"ru\":\"Добавляет в «Плагины» вкладку «Откройте для себя», где можно просматривать и устанавливать плагины из добавленных вами индексов плагинов.\",\"zh\":\"在插件页添加“发现”标签页,从你添加的插件索引中浏览和安装插件。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-forge-bundle\",\"title\":{\"en\":\"Change requests & worktrees\",\"de\":\"Änderungsanfragen und Arbeitsbäume\",\"es\":\"Solicitudes de cambio y árboles de trabajo\",\"fr\":\"Demandes de modification et arbres de travail\",\"ja\":\"変更リクエストとワークツリー\",\"pt\":\"Solicitações de alteração e árvores de trabalho\",\"ru\":\"Запросы на изменение и рабочие деревья\",\"zh\":\"变更请求与工作树\"},\"description\":{\"en\":\"Track each Session's change requests with their checks and reviews, and start new Sessions in a Git worktree; uses the gh CLI for GitHub.\",\"de\":\"Verfolgen Sie die Änderungsanfragen jeder Sitzung mit ihren Prüfungen und Reviews und starten Sie neue Sitzungen in einem Git-Arbeitsbaum; nutzt die gh CLI für GitHub.\",\"es\":\"Siga las solicitudes de cambio de cada sesión con sus comprobaciones y revisiones, e inicie nuevas sesiones en un árbol de trabajo de Git; usa la CLI gh para GitHub.\",\"fr\":\"Suivez les demandes de modification de chaque session avec leurs vérifications et revues, et démarrez de nouvelles sessions dans un arbre de travail Git ; utilise la CLI gh pour GitHub.\",\"ja\":\"各セッションの変更リクエストとそのチェックやレビューを追跡し、新しいセッションを Git ワークツリーで開始できます。GitHub には gh CLI を使用します。\",\"pt\":\"Acompanhe as solicitações de alteração de cada sessão com suas verificações e revisões e inicie novas sessões em uma árvore de trabalho Git; usa a CLI gh para o GitHub.\",\"ru\":\"Отслеживайте запросы на изменение каждого сеанса вместе с их проверками и ревью и начинайте новые сеансы в рабочем дереве Git; для GitHub используется gh CLI.\",\"zh\":\"跟踪每个会话的变更请求及其检查与评审,新会话也可以在 Git 工作树中开始;GitHub 通过 gh 命令行访问。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-subagent-claude-code\",\"title\":{\"de\":\"Claude Code-Subagent\",\"en\":\"Claude Code subagent\",\"es\":\"Subagente Claude Code\",\"fr\":\"Sous-agent Claude Code\",\"ja\":\"Claude Code サブエージェント\",\"pt\":\"Claude Code subagente\",\"ru\":\"Субагент Claude Code\",\"zh\":\"Claude Code 子智能体\"},\"description\":{\"de\":\"Delegieren Sie eine Aufgabe an Claude Code, indem Sie dessen native Authentifizierung und Einstellungen verwenden.\",\"en\":\"Delegate one task to Claude Code using its native authentication and settings.\",\"es\":\"Delegue una tarea a Claude Code utilizando su autenticación y configuración nativas.\",\"fr\":\"Déléguez une tâche à Claude Code à l’aide de son authentification et de ses paramètres natifs.\",\"ja\":\"Claude Code のネイティブの認証と設定を使用して、単独のタスクを委派します。\",\"pt\":\"Delegue uma tarefa a Claude Code usando sua autenticação e configurações nativas.\",\"ru\":\"Делегируйте одну задачу Claude Code, используя его встроенную аутентификацию и настройки.\",\"zh\":\"使用 Claude Code 原生认证和设置委派单个任务。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-subagent-codex\",\"title\":{\"de\":\"Codex-Subagent\",\"en\":\"Codex subagent\",\"es\":\"Subagente Codex\",\"fr\":\"Sous-agent Codex\",\"ja\":\"Codex サブエージェント\",\"pt\":\"Codex subagente\",\"ru\":\"Субагент Codex\",\"zh\":\"Codex 子智能体\"},\"description\":{\"de\":\"Delegieren Sie eine Aufgabe an Codex, indem Sie dessen native Authentifizierung und Einstellungen verwenden.\",\"en\":\"Delegate one task to Codex using its native authentication and settings.\",\"es\":\"Delegue una tarea a Codex utilizando su autenticación y configuración nativas.\",\"fr\":\"Déléguez une tâche à Codex à l’aide de son authentification et de ses paramètres natifs.\",\"ja\":\"Codex のネイティブの認証と設定を使用して、単独のタスクを委派します。\",\"pt\":\"Delegue uma tarefa a Codex usando sua autenticação e configurações nativas.\",\"ru\":\"Делегируйте одну задачу Codex, используя его встроенную аутентификацию и настройки.\",\"zh\":\"使用 Codex 原生认证和设置委派单个任务。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-cua-bundle\",\"title\":{\"de\":\"Computernutzung\",\"en\":\"Computer use\",\"es\":\"Uso de la computadora\",\"fr\":\"Utilisation de l'ordinateur\",\"ja\":\"Computer Use\",\"pt\":\"Uso do computador\",\"ru\":\"Использование компьютера\",\"zh\":\"Computer Use\"},\"description\":{\"de\":\"Unterstützt derzeit macOS; Die Windows-Unterstützung befindet sich in der Entwicklung. Lädt die Computernutzung für bestehende und neue PTC-Sitzungen. Wechseln Sie in den PTC-Modus und erteilen Sie die Berechtigungen für Barrierefreiheit und Bildschirmaufzeichnung, um ihn zu verwenden.\",\"en\":\"Currently supports macOS; Windows support is in development. Loads computer use for existing and new PTC sessions. Switch to PTC mode and grant Accessibility and Screen Recording permissions to use it.\",\"es\":\"Actualmente es compatible con macOS; El soporte para Windows está en desarrollo. Carga el uso de la computadora para sesiones PTC nuevas y existentes. Cambie al modo PTC y otorgue permisos de Accesibilidad y Grabación de pantalla para usarlo.\",\"fr\":\"Prend actuellement en charge macOS ; La prise en charge de Windows est en cours de développement. Charge l'utilisation de l'ordinateur pour les sessions PTC existantes et nouvelles. Passez en mode PTC et accordez les autorisations d’accessibilité et d’enregistrement d’écran pour l’utiliser.\",\"ja\":\"現在は macOS のみ対応し、Windows 対応は開発中です。既存および新規の PTC セッションに Computer Use を読み込みます。PTC モードに切り替え、アクセシビリティと画面収録の権限を許可して使用してください。\",\"pt\":\"Atualmente suporta macOS; O suporte Windows está em desenvolvimento. Carrega o uso do computador para sessões PTC novas e existentes. Mude para o modo PTC e conceda permissões de acessibilidade e gravação de tela para usá-lo.\",\"ru\":\"В настоящее время поддерживается macOS; Поддержка Windows находится в разработке. Загружает использование компьютера для существующих и новых сеансов PTC. Переключитесь в режим PTC и предоставьте разрешения на доступность и запись экрана для его использования.\",\"zh\":\"目前仅支持 macOS,Windows 支持正在开发中。为已有及新建 PTC 会话加载 Computer Use。请切换到 PTC 模式来使用,并授予辅助功能和屏幕录制权限。\"},\"enabled\":false}]\n\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[16],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_creation_skill"},"toolCallId":"call_creation_skill","content":[{"type":"text","text":"\n\nResources for this skill are managed by provider \"dsh-personalized-pages\".\nLoad referenced resources only as needed.\n\n\n\n# Personalized pages\n\nUse this workflow in the main conversation to plan an optional new page or small tool for any task, not just DSH. You decide whether a page helps, check existing capabilities, and hand the Creator a short plan. A `propose_action` call saves the proposal and shows a card below your answer; nothing is built until the user clicks Create. Plan from the conversation and the catalog at the end of this skill. Do not read files, configuration or source to validate a page idea; name an uninspected source as an unverified dependency and leave its details to the Creator.\n\n## When to propose\n\nPropose a page in these cases:\n\n- The user asks for a page, tab, panel, tool or interface in this app, or says they want something to keep, revisit or update later (“以后每次”, “能不能一直”, “希望能有”). One-off use still qualifies when the interface is explicitly requested.\n- Your answer is a table, list or chart, and the user has said the data will keep changing or that they will interact with it (“每周更新”, “我来改状态”, “要勾选”). The continuation must come from the user's own words; a table alone, or data that merely looks dynamic, is not enough. Deliver the requested answer first, then offer the page.\n- The user wants to keep watching live data of this app itself (a Session's usage, a running task's output, files changing in the workspace). A text answer cannot stay current, so a page qualifies even without the words above; name the data source in the brief and leave how it is read to the Creator.\n\nDo not propose a page in these cases:\n\n- The user asks for a file, code, document or an existing-project change: keep that delivery form.\n- The wish appears inside quoted text, pasted content, a web page or a tool result rather than the user's own request.\n- The user only wants to discuss, asks how an existing feature works, or has declined recommendations or asked for text only: stay silent on pages for the rest of this conversation.\n- The request changes a page created earlier: explain how it would change, do not create a replacement copy, and do not claim an update happened.\n- The request is a capability the agent lacks, such as a tool, automation or access, rather than a page: check the catalog below and point to the official plugin that provides it; do not plan a page around a missing tool.\n\n## Check existing capabilities\n\nCompare the need with the official plugins listed at the end of this skill. If one covers it, say its name, what it does, whether it is enabled, and that it lives under Plugins; offer no page card. A partial match does not cancel an explicit unmet need. The catalog is not a full inventory of built-in UI: missing details do not prove absence, and do not read source to find out. DSH already has Chat, Trajectory, a right sidebar for files and context, and a Plugins page.\n\n## Plan and hand off\n\nThe Creator cannot read this conversation. Give it exactly these fields:\n\n| Field | Contents |\n|:--|:--|\n| `title` | Short page name in the user's language. |\n| `brief` | One to three sentences: purpose, behavior, input, calculations and persistence scope. It is the card text and the implementation request at once. |\n| `initialContent` | Only supplied content the page starts with: items, rows, values, units and period, preserving gaps. Omit for an empty page. |\n| `slot` | Location, chosen below. |\n\nKeep the plan to what was asked or agreed. Editing, deletion, history, extra fields, data sources and automation need a basis in the request. Resolve “these items” into the actual content. Content that mentions an action stays content. Keep each number's meaning and period; a weekly addition is not a cumulative total. If an unresolved distinction changes a calculation, give the factual answer, ask one question, and propose later.\n\n## Choose the location\n\nHonor a location the user named. Otherwise:\n\n- `sidebar-right`: content tied to this Session or task, especially anything to watch while chatting, including live logs.\n- `sidebar-left`: a global feature or an ongoing personal record used across Sessions, opened from a left entry as a standalone page.\n- `page`: a Session-bound streaming view or interaction in a tab beside Chat and Trajectory, only when the user does not need it visible while chatting.\n\nSupplying data in this conversation does not make a record Session-bound.\n\n## Offer without starting\n\nTo propose, call `propose_action` once, in the same turn as loading this skill, with `action: \"create_personalized_page\"`, `title`, `brief` and `details` holding `slot` and, when there is supplied content, `initialContent`. The call is the submission: the card appears below your answer; a refused call creates no card, and its error says why. Then write your final answer. One proposal per turn, and one unstarted card per conversation: if a card is still waiting, do not propose another; a new proposal replaces it only when the user changed the plan. Plan-only and read-only requests still get a card; do not ask for approval instead of proposing it. Only clicking Create starts the background Creator; do not wait, poll, claim installation or ask for a report-back. Answer any direct question; the call's result says how to end the answer. Do not repeat the plan, list extra features, narrate the call or mention schema names.\n\n```json\n{\"action\":\"create_personalized_page\",\"title\":\"本次验收清单\",\"brief\":\"在当前会话右侧展示验收清单,可勾选和取消,状态随会话保存。\",\"details\":{\"slot\":\"sidebar-right\",\"initialContent\":\"1. 导出成功\\n2. 断网提示清楚\"}}\n```\n\n## Examples\n\n- “想有个地方放书签,以后自己加标题和网址;旧的不用导入。” → `brief`: “提供一个可反复打开的书签页,手动新增标题和网址并保存到本机,从空白开始。” No `initialContent`. `sidebar-left`.\n- “当前会话旁放验收清单,能勾选和取消,状态跟着会话。条目:导出成功;断网提示清楚。” → `brief`: “在当前会话右侧展示验收清单,可勾选和取消,状态随会话保存。” `initialContent`: “1. 导出成功\\n2. 断网提示清楚”. `sidebar-right`.\n- “这三周 bug 数 12、9、15,说说趋势。以后每周我把新数字贴给你,想自己更新着看。” → answer the trend first, then `brief`: “按周手动录入 bug 数并展示各周变化,保存到本机。” `initialContent`: “第 1 周 12,第 2 周 9,第 3 周 15”. `sidebar-left`.\n- “我想用语音说话代替打字。” → the catalog lists 语音输入; explain it and where to enable it; no card.\n- “把我之前做的读书页评分改成五星。” → explain the change to that page; no card and no copy.\n- “帮我把这句话翻成英文:我想要一个所有会话都能打开的读书页。” → translate only; no card.\n- “把三个方案排成表格比较一下,看完就行。” → the table only; no card.\n\n## Existing capabilities to check against this page plan\n\n[{\"name\":\"@deepseek-ai/dsh-personalized-recommendations\",\"title\":{\"en\":\"Personalized recommendations\",\"de\":\"Personalisierte Empfehlungen\",\"es\":\"Recomendaciones personalizadas\",\"fr\":\"Recommandations personnalisées\",\"ja\":\"パーソナライズされたおすすめ\",\"pt\":\"Recomendações personalizadas\",\"ru\":\"Персональные рекомендации\",\"zh\":\"个性化推荐\"},\"description\":{\"en\":\"Shows recommendation cards below the answer for what you want from DSH: when you want a page or small tool you can keep, it proposes a new personalized page, built in the background after you click Create; when you ask how to do something in this app or say a capability is missing, it recommends the built-in plugin that provides it, turned on when you click Enable.\",\"de\":\"Zeigt für Ihre individuellen Anforderungen an DSH Empfehlungskarten unter der Antwort an: Wenn Sie eine Seite oder ein kleines Tool zur dauerhaften Nutzung möchten, wird eine neue personalisierte Seite vorgeschlagen, die nach einem Klick auf Erstellen im Hintergrund erstellt wird; wenn Sie fragen, wie etwas in dieser App geht, oder sagen, dass eine Funktion fehlt, wird das integrierte Plugin empfohlen, das sie bereitstellt, und nach einem Klick auf Aktivieren eingeschaltet.\",\"es\":\"Muestra tarjetas de recomendación debajo de la respuesta para tus necesidades personalizadas en DSH: cuando quieres una página o una pequeña herramienta para conservar, propone una nueva página personalizada, que se genera en segundo plano al hacer clic en Crear; cuando preguntas cómo hacer algo en esta aplicación o dices que falta una función, recomienda el complemento integrado que la ofrece, que se activa al hacer clic en Habilitar.\",\"fr\":\"Affiche des cartes de recommandation sous la réponse pour vos besoins personnalisés dans DSH : lorsque vous voulez une page ou un petit outil à conserver, propose une nouvelle page personnalisée, générée en arrière-plan après un clic sur Créer ; lorsque vous demandez comment faire quelque chose dans cette application ou signalez qu’une fonctionnalité manque, recommande le plugin intégré qui la fournit, activé lorsque vous cliquez sur Activer.\",\"ja\":\"DSH に対するあなた個人のニーズに合わせて、回答の下におすすめカードを表示します。長く使えるページや小さなツールが欲しいときは新しいパーソナルページを提案し、「作成」をクリックするとバックグラウンドで生成します。このアプリで何かをする方法を尋ねたときや機能が足りないと言ったときは、それを提供する内蔵プラグインを推薦し、「有効にする」をクリックすると有効になります。\",\"pt\":\"Mostra cartões de recomendação abaixo da resposta para suas necessidades personalizadas no DSH: quando você quer uma página ou uma pequena ferramenta para manter, propõe uma nova página personalizada, gerada em segundo plano depois que você clica em Criar; quando você pergunta como fazer algo neste aplicativo ou diz que falta um recurso, recomenda o plug-in integrado que o oferece, ativado quando você clica em Ativar.\",\"ru\":\"Показывает карточки рекомендаций под ответом с учетом ваших индивидуальных потребностей в DSH: когда вам нужна страница или небольшой инструмент для постоянного использования, предлагает новую персональную страницу, которая создается в фоне после нажатия «Создать»; когда вы спрашиваете, как что-то сделать в этом приложении, или говорите, что не хватает какой-то возможности, рекомендует встроенный плагин, который ее предоставляет, и включает его после нажатия «Включить».\",\"zh\":\"针对你对 DSH 的个性化需求,在回答下方展示推荐卡片:想要能长期使用的页面或小工具时,提议新增个性化页面,点击创建后在后台生成;问到本应用怎么做某件事或缺少某项能力时,推荐对应的内置插件,点击启用后开启。\"},\"enabled\":true},{\"name\":\"@deepseek-ai/dsh-experimental-agent-team-profile\",\"title\":{\"en\":\"Agent teams\",\"de\":\"Agententeams\",\"es\":\"Equipos de agentes\",\"fr\":\"Équipes d'agents\",\"ja\":\"エージェントチーム\",\"pt\":\"Equipes de agentes\",\"ru\":\"Команды агентов\",\"zh\":\"智能体团队\"},\"description\":{\"en\":\"Lets the agent you talk to split a job among named teammates, track it on a shared task board, and report back with their results.\",\"de\":\"Ermöglicht dem Agenten, mit dem Sie sprechen, eine Aufgabe auf benannte Teammitglieder aufzuteilen, sie auf einem gemeinsamen Aufgabenboard zu verfolgen und Ihnen mit deren Ergebnissen zu berichten.\",\"es\":\"Permite que el agente con el que habla reparta un trabajo entre compañeros con nombre, lo siga en un tablero de tareas compartido y le informe con sus resultados.\",\"fr\":\"Permet à l'agent avec lequel vous parlez de répartir un travail entre des coéquipiers nommés, de le suivre sur un tableau de tâches partagé et de vous rendre compte de leurs résultats.\",\"ja\":\"対話しているエージェントが、仕事を名前付きのチームメイトに分担させ、共有タスクボードで進捗を追跡し、チームメイトの結果をまとめて報告します。\",\"pt\":\"Permite que o agente com quem você conversa divida um trabalho entre colegas de equipe nomeados, acompanhe-o em um quadro de tarefas compartilhado e informe você com os resultados deles.\",\"ru\":\"Позволяет агенту, с которым вы общаетесь, распределить работу между именованными участниками команды, отслеживать её на общей доске задач и отчитываться перед вами об их результатах.\",\"zh\":\"让与你对话的智能体把工作分给有名字的队友,在共享任务看板上跟踪进度,并汇总队友的结果向你汇报。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-inspector-profile\",\"title\":{\"en\":\"Developer tools\",\"de\":\"Entwicklertools\",\"es\":\"Herramientas de desarrollador\",\"fr\":\"Outils de développement\",\"ja\":\"開発者ツール\",\"pt\":\"Ferramentas de desenvolvedor\",\"ru\":\"Инструменты разработчика\",\"zh\":\"开发者工具\"},\"description\":{\"en\":\"For troubleshooting: view what DSH recorded for a session in Session log, inspect per-turn and per-step statistics in the Statistics tab, and debug the DSH backend in Chrome DevTools.\",\"de\":\"Zur Fehlersuche: Sehen Sie in „Sitzungsprotokoll“, was DSH für eine Sitzung aufgezeichnet hat, prüfen Sie im Tab „Statistik“ Kontext, Dauer, Cache und Werkzeugkosten pro Runde und Schritt und debuggen Sie das DSH-Backend in Chrome DevTools.\",\"es\":\"Para solucionar problemas: vea en «Registro de sesión» lo que DSH registró de una sesión, consulte el contexto, los tiempos, la caché y el coste de herramientas por turno y paso en la pestaña «Estadísticas», y depure el backend de DSH en Chrome DevTools.\",\"fr\":\"Pour le dépannage : consultez dans « Journal de session » ce que DSH a enregistré pour une session, examinez le contexte, les durées, le cache et le coût des outils par tour et étape dans l’onglet « Statistiques », et déboguez le backend de DSH dans Chrome DevTools.\",\"ja\":\"トラブルシューティング用です。「セッションログ」で DSH がセッションについて記録した内容を確認し、「統計」タブでターン/ステップごとのコンテキスト、時間、キャッシュ、ツールコストを確認し、Chrome DevTools で DSH バックエンドをデバッグできます。\",\"pt\":\"Para solução de problemas: veja em «Registro da sessão» o que o DSH registrou de uma sessão, consulte contexto, tempos, cache e custo de ferramentas por turno e etapa na aba «Estatísticas» e depure o backend do DSH no Chrome DevTools.\",\"ru\":\"Для диагностики: просматривайте в «Журнале сеанса», что DSH записал для сеанса, смотрите контекст, время, кэш и стоимость инструментов по ходам и шагам на вкладке «Статистика» и отлаживайте бэкенд DSH в Chrome DevTools.\",\"zh\":\"用于排查问题:在「会话数据诊断」中查看 DSH 为会话记录的内容,在「统计」页签查看每轮/每步的上下文、耗时、缓存和工具成本,并在 Chrome DevTools 中调试 DSH 后端。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-voice-input-bundle\",\"title\":{\"en\":\"Voice input\",\"de\":\"Spracheingabe\",\"es\":\"Entrada de voz\",\"fr\":\"Saisie vocale\",\"ja\":\"音声入力\",\"pt\":\"Entrada de voz\",\"ru\":\"Голосовой ввод\",\"zh\":\"语音输入\"},\"description\":{\"en\":\"Transcribe recordings locally with SenseVoice; first use requires installing dependencies.\",\"de\":\"Transkribieren Sie Aufnahmen lokal mit SenseVoice; Für die erste Verwendung müssen Abhängigkeiten installiert werden.\",\"es\":\"Transcribe grabaciones localmente con SenseVoice; El primer uso requiere instalar dependencias.\",\"fr\":\"Transcrivez les enregistrements localement avec SenseVoice ; la première utilisation nécessite l'installation de dépendances.\",\"ja\":\"ローカルの SenseVoice で録音を文字に起こします。初回利用時には依存関係のインストールが必要です。\",\"pt\":\"Transcreva gravações localmente com SenseVoice; o primeiro uso requer a instalação de dependências.\",\"ru\":\"Транскрибируйте записи локально с помощью SenseVoice; при первом использовании требуется установка зависимостей.\",\"zh\":\"在本机使用 SenseVoice 转写录音,首次使用需安装依赖。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-auto-review\",\"title\":{\"en\":\"Auto authorization review\",\"de\":\"Automatische Autorisierungsüberprüfung\",\"es\":\"Revisión de autorización automática\",\"fr\":\"Examen des autorisations automatiques\",\"ja\":\"自動認可レビュー\",\"pt\":\"Revisão de autorização automática\",\"ru\":\"Проверка автоматической авторизации\",\"zh\":\"自动授权审查\"},\"description\":{\"en\":\"Adds an Auto review access mode: before each tool call, a model checks it against what you asked for, runs allowed calls at once, and holds denied calls for your approval.\",\"de\":\"Fügt den Zugriffsmodus „Auto review“ hinzu: Vor jedem Tool-Aufruf prüft ein Modell den Aufruf anhand Ihrer Anforderung; zugelassene Aufrufe laufen sofort, abgelehnte Aufrufe warten auf Ihre Genehmigung.\",\"es\":\"Añade el modo de acceso “Auto review”: antes de cada llamada a una herramienta, un modelo comprueba la llamada frente a lo que usted pidió; las llamadas permitidas se ejecutan de inmediato y las denegadas esperan su aprobación.\",\"fr\":\"Ajoute le mode d'accès « Auto review » : avant chaque appel d'outil, un modèle vérifie l'appel par rapport à ce que vous avez demandé ; les appels autorisés s'exécutent immédiatement et les appels refusés attendent votre approbation.\",\"ja\":\"「自動認可レビュー」アクセスモードを追加します。各ツール呼び出しの前に、モデルがその呼び出しをあなたの依頼内容と照らし合わせて確認し、許可された呼び出しは即座に実行され、拒否された呼び出しはあなたの承認を待ちます。\",\"pt\":\"Adiciona o modo de acesso “Auto review”: antes de cada chamada de ferramenta, um modelo verifica a chamada em relação ao que você pediu; as chamadas permitidas são executadas imediatamente e as negadas aguardam sua aprovação.\",\"ru\":\"Добавляет режим доступа «Auto review»: перед каждым вызовом инструмента модель сверяет вызов с вашей просьбой; разрешённые вызовы выполняются сразу, а отклонённые ждут вашего одобрения.\",\"zh\":\"提供“自动审查”访问模式:每次工具调用前,由模型对照你的要求检查,获准的调用立即运行,被拒绝的调用等你审批。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-cot-translation-bundle\",\"title\":{\"en\":\"Machine translation of reasoning\",\"de\":\"Maschinelle Übersetzung der Argumentation\",\"es\":\"Traducción automática de razonamiento\",\"fr\":\"Traduction automatique du raisonnement\",\"ja\":\"思考内容の機械翻訳\",\"pt\":\"Tradução automática de raciocínio\",\"ru\":\"Машинный перевод рассуждений\",\"zh\":\"思考过程机器翻译\"},\"description\":{\"en\":\"Translates expanded Think rows into your chosen language as the agent writes them, and View original switches back.\",\"de\":\"Übersetzt aufgeklappte „Denken Sie nach“-Zeilen, während der Agent sie schreibt, in die von Ihnen gewählte Sprache, und „Original ansehen“ wechselt zurück.\",\"es\":\"Traduce las filas “pensar” expandidas al idioma que elija mientras el agente las escribe, y “Ver original” vuelve al texto original.\",\"fr\":\"Traduit les lignes « Pensez » développées dans la langue de votre choix pendant que l'agent les écrit, et « Voir l'original » permet de revenir au texte d'origine.\",\"ja\":\"エージェントが書き出すのと同時に、展開された「思考」行を選択した言語に翻訳します。「原文を表示」で原文に戻せます。\",\"pt\":\"Traduz as linhas “Pense” expandidas para o idioma que você escolher enquanto o agente as escreve, e “Ver original” volta ao texto original.\",\"ru\":\"Переводит развёрнутые строки «Подумайте» на выбранный вами язык по мере того, как агент их пишет, а «Посмотреть оригинал» возвращает исходный текст.\",\"zh\":\"智能体输出时,把展开的“思考”行翻译成你选择的语言,点击“查看原文”可切换回原文。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-badge-skill-bundle\",\"title\":{\"en\":\"DSH badge skill\",\"de\":\"DSH-Abzeichen-Fertigkeit\",\"es\":\"Habilidad de insignia DSH\",\"fr\":\"Compétence du badge DSH\",\"ja\":\"DSH バッジスキル\",\"pt\":\"DSH habilidade de distintivo\",\"ru\":\"DSH значок навыка\",\"zh\":\"DSH 徽章技能\"},\"description\":{\"en\":\"Let agents add a “powered by dsh” badge to documents, pull requests, and other outputs.\",\"de\":\"Lassen Sie Agenten Dokumente, Pull-Requests und andere Ausgaben mit einem „powered by dsh“-Badge versehen.\",\"es\":\"Permita que los agentes agreguen una insignia \\\"con tecnología de dsh\\\" a documentos, solicitudes de extracción y otros resultados.\",\"fr\":\"Laissez les agents ajouter un badge « propulsé par dsh » aux documents, demandes d'extraction et autres sorties.\",\"ja\":\"エージェントが文書や PR などの成果物に「powered by dsh」バッジを追加できます。\",\"pt\":\"Permita que os agentes adicionem um selo “powered by dsh” a documentos, pull requests e outros resultados.\",\"ru\":\"Позвольте агентам добавлять значок «Powered by dsh» к документам, запросам на включение и другим результатам.\",\"zh\":\"让 Agent 为文档、PR 等产出添加「powered by dsh」徽章。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-ralph-bundle\",\"title\":{\"en\":\"Ralph loops\",\"de\":\"Ralph-Loops\",\"es\":\"Bucles de Ralph\",\"fr\":\"Boucles Ralph\",\"ja\":\"Ralph ループ\",\"pt\":\"Loops de Ralph\",\"ru\":\"Ральф петли\",\"zh\":\"Ralph 循环\"},\"description\":{\"en\":\"Ask for a Ralph loop with a goal, and the agent starts a fresh agent on it round after round until the goal is met, a blocker is reported, or the round limit is reached.\",\"de\":\"Bitten Sie um eine Ralph-Schleife mit einem Ziel, und der Agent startet Runde um Runde einen neuen Agenten darauf, bis das Ziel erreicht ist, ein Hindernis gemeldet wird oder das Rundenlimit erreicht ist.\",\"es\":\"Pida un bucle Ralph con un objetivo, y el agente inicia un agente nuevo sobre él ronda tras ronda hasta que se cumpla el objetivo, se informe de un bloqueo o se alcance el límite de rondas.\",\"fr\":\"Demandez une boucle Ralph avec un objectif, et l'agent lance un nouvel agent dessus, tour après tour, jusqu'à ce que l'objectif soit atteint, qu'un blocage soit signalé ou que la limite de tours soit atteinte.\",\"ja\":\"目標を指定して Ralph ループを依頼すると、エージェントは、目標が達成されるか、阻害要因が報告されるか、ラウンド数の上限に達するまで、ラウンドごとに新しいエージェントを起動してその目標に取り組ませます。\",\"pt\":\"Peça um loop Ralph com um objetivo, e o agente inicia um novo agente nele rodada após rodada até que o objetivo seja atingido, um bloqueio seja informado ou o limite de rodadas seja alcançado.\",\"ru\":\"Попросите запустить цикл Ralph с целью, и агент будет раунд за раундом запускать для неё нового агента, пока цель не будет достигнута, не будет сообщено о препятствии или не будет достигнут лимит раундов.\",\"zh\":\"要求用 Ralph 循环完成一个目标后,智能体会一轮接一轮地启动新的智能体处理它,直到目标达成、报告受阻或达到轮次上限。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-session-titles-bundle\",\"title\":{\"en\":\"Conversation-following titles\",\"de\":\"Konversationsfolgende Titel\",\"es\":\"Títulos que siguen la conversación\",\"fr\":\"Titres de suivi de conversation\",\"ja\":\"会話に追従するタイトル\",\"pt\":\"Títulos que acompanham conversas\",\"ru\":\"Заголовки, следующие за разговором\",\"zh\":\"随对话更新的标题\"},\"description\":{\"en\":\"Writes a session's title from all of your messages and updates it when the main task changes, instead of only from the first message.\",\"de\":\"Erstellt den Titel einer Sitzung aus all Ihren Nachrichten und aktualisiert ihn, wenn sich die Hauptaufgabe ändert, statt ihn nur aus der ersten Nachricht zu bilden.\",\"es\":\"Escribe el título de una sesión a partir de todos sus mensajes y lo actualiza cuando cambia la tarea principal, en lugar de basarse solo en el primer mensaje.\",\"fr\":\"Rédige le titre d'une session à partir de tous vos messages et le met à jour lorsque la tâche principale change, au lieu de se baser uniquement sur le premier message.\",\"ja\":\"最初のメッセージだけでなく、あなたのすべてのメッセージからセッションのタイトルを作成し、主なタスクが変わったときに更新します。\",\"pt\":\"Escreve o título de uma sessão a partir de todas as suas mensagens e o atualiza quando a tarefa principal muda, em vez de usar apenas a primeira mensagem.\",\"ru\":\"Составляет заголовок сеанса по всем вашим сообщениям и обновляет его при смене основной задачи, а не только по первому сообщению.\",\"zh\":\"根据你的所有消息生成会话标题,并在主要任务变化时更新,而不是只根据第一条消息生成。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-terminal-bundle\",\"title\":{\"en\":\"Persistent terminals\",\"de\":\"Persistente Terminals\",\"es\":\"Terminales persistentes\",\"fr\":\"Terminaux persistants\",\"ja\":\"永続ターミナル\",\"pt\":\"Terminais persistentes\",\"ru\":\"Постоянные терминалы\",\"zh\":\"持久终端\"},\"description\":{\"en\":\"Gives the agent terminals whose processes keep running in the background between tool calls, so it can start a dev server or REPL and come back later to read output or type input.\",\"de\":\"Stellt dem Agenten Terminals bereit, deren Prozesse zwischen Tool-Aufrufen im Hintergrund weiterlaufen, sodass er einen Entwicklungsserver oder eine REPL starten und später zurückkehren kann, um Ausgaben zu lesen oder Eingaben zu tippen.\",\"es\":\"Proporciona al agente terminales cuyos procesos siguen ejecutándose en segundo plano entre llamadas a herramientas, de modo que puede iniciar un servidor de desarrollo o un REPL y volver más tarde para leer la salida o escribir entradas.\",\"fr\":\"Fournit à l'agent des terminaux dont les processus continuent de s'exécuter en arrière-plan d'un appel d'outil à l'autre, afin qu'il puisse lancer un serveur de développement ou un REPL et revenir plus tard lire la sortie ou saisir des entrées.\",\"ja\":\"エージェントにターミナルを提供します。プロセスはツール呼び出し間もバックグラウンドで実行され続けるため、エージェントは開発サーバーや REPL を起動し、後から出力を読んだり入力したりできます。\",\"pt\":\"Fornece ao agente terminais cujos processos continuam em execução em segundo plano entre chamadas de ferramentas, para que ele possa iniciar um servidor de desenvolvimento ou um REPL e voltar depois para ler a saída ou digitar entradas.\",\"ru\":\"Предоставляет агенту терминалы, процессы которых продолжают работать в фоне между вызовами инструментов, поэтому агент может запустить сервер разработки или REPL и позже вернуться, чтобы прочитать вывод или ввести данные.\",\"zh\":\"为智能体提供终端,进程在多次工具调用之间持续在后台运行,因此它可以启动开发服务器或 REPL,稍后再读取输出或继续输入。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-liveshare\",\"title\":{\"en\":\"LiveShare Session Sharing\",\"de\":\"LiveShare-Sitzungsfreigabe\",\"es\":\"Compartir sesión de LiveShare\",\"fr\":\"Partage de session LiveShare\",\"ja\":\"LiveShare セッション共有\",\"pt\":\"Compartilhamento de sessão do LiveShare\",\"ru\":\"Совместный доступ к сеансу LiveShare\",\"zh\":\"LiveShare 会话分享\"},\"description\":{\"en\":\"Share the current Session with a colleague, who can drive it in a browser, edit files inside the granted workspace when the share allows writes, or branch their own Session from the completed history.\",\"de\":\"Teilt die aktuelle Sitzung mit einer Kollegin oder einem Kollegen, die oder der sie im Browser bedienen, bei erlaubten Schreibzugriffen Dateien im freigegebenen Arbeitsbereich bearbeiten oder aus der abgeschlossenen Historie eine eigene Sitzung abzweigen kann.\",\"es\":\"Comparte la sesión actual con un compañero, que puede dirigirla en un navegador, editar archivos dentro del espacio de trabajo concedido cuando el recurso compartido permite escritura, o crear su propia sesión a partir del historial completado.\",\"fr\":\"Partagez la session en cours avec un collègue, qui peut la piloter dans un navigateur, modifier des fichiers dans l'espace de travail accordé lorsque le partage autorise l'écriture, ou créer sa propre session à partir de l'historique terminé.\",\"ja\":\"現在のセッションを同僚と共有し、ブラウザから操作してもらう、共有が書き込みを許可する場合は付与されたワークスペース内のファイルを編集してもらう、または完了した履歴から自分のセッションを分岐してもらえます。\",\"pt\":\"Compartilhe a sessão atual com um colega, que pode conduzi-la no navegador, editar arquivos dentro do espaço de trabalho concedido quando o compartilhamento permite escrita, ou ramificar a própria sessão a partir do histórico concluído.\",\"ru\":\"Поделитесь текущим сеансом с коллегой: он сможет управлять им в браузере, редактировать файлы в предоставленном рабочем пространстве, если общий доступ разрешает запись, или ответвить собственный сеанс из завершённой истории.\",\"zh\":\"把当前会话分享给同事,对方可在浏览器中驱动该会话、在分享允许写入时修改授权工作区内的文件,或从已完成历史分支出自己的会话。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-session-search\",\"title\":{\"en\":\"Session search\",\"de\":\"Sitzungssuche\",\"es\":\"búsqueda de sesión\",\"fr\":\"Recherche de sessions\",\"ja\":\"セッション検索\",\"pt\":\"Pesquisa de sessão\",\"ru\":\"Поиск сеанса\",\"zh\":\"会话搜索\"},\"description\":{\"en\":\"Ask about earlier work, such as “How did we fix the pool leak last week?”, and the agent searches your earlier sessions in the same workspace to answer.\",\"de\":\"Fragen Sie nach früherer Arbeit, etwa „Wie haben wir letzte Woche das Pool-Leck behoben?“, und der Agent durchsucht Ihre früheren Sitzungen aus demselben Arbeitsverzeichnis, um zu antworten.\",\"es\":\"Pregunte por trabajo anterior, como “¿Cómo arreglamos la fuga del pool la semana pasada?”, y el agente busca en sus sesiones anteriores del mismo directorio de trabajo para responder.\",\"fr\":\"Posez une question sur un travail antérieur, par exemple « Comment avons-nous corrigé la fuite du pool la semaine dernière ? », et l'agent recherche dans vos sessions antérieures du même répertoire de travail pour répondre.\",\"ja\":\"「先週プールのリークをどう直した?」のように以前の作業について尋ねると、エージェントは同じ作業ディレクトリの過去のセッションを検索して回答します。\",\"pt\":\"Pergunte sobre trabalhos anteriores, como “Como corrigimos o vazamento do pool na semana passada?”, e o agente pesquisa suas sessões anteriores do mesmo diretório de trabalho para responder.\",\"ru\":\"Спросите о прошлой работе, например «Как мы исправили утечку в пуле на прошлой неделе?», и агент выполнит поиск по вашим прошлым сеансам из того же рабочего каталога, чтобы ответить.\",\"zh\":\"询问以往的工作,例如“上周我们是怎么修好连接池泄漏的?”,智能体会搜索同一工作区的历史会话来回答。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-tool-worktree\",\"title\":{\"en\":\"Git worktrees\",\"de\":\"Git-Arbeitsbäume\",\"es\":\"árboles de trabajo de git\",\"fr\":\"Arbres de travail Git\",\"ja\":\"Git ワークツリー\",\"pt\":\"Árvores de trabalho Git\",\"ru\":\"Рабочие деревья Git\",\"zh\":\"Git 工作树\"},\"description\":{\"en\":\"Ask for work on a new branch, and the agent creates a separate Git worktree and continues there, leaving your current checkout as it is.\",\"de\":\"Bitten Sie um Arbeit auf einem neuen Branch, und der Agent erstellt einen separaten Git-Worktree und arbeitet dort weiter, während Ihr aktueller Checkout unverändert bleibt.\",\"es\":\"Pida trabajar en una rama nueva, y el agente crea un worktree de Git independiente y continúa allí, dejando su checkout actual tal como está.\",\"fr\":\"Demandez à travailler sur une nouvelle branche, et l'agent crée un worktree Git distinct et y poursuit le travail, en laissant votre copie de travail actuelle telle quelle.\",\"ja\":\"新しいブランチでの作業を依頼すると、エージェントは別の Git ワークツリーを作成してそこで作業を続け、現在のチェックアウトはそのまま残します。\",\"pt\":\"Peça para trabalhar em um novo branch, e o agente cria um worktree do Git separado e continua lá, deixando seu checkout atual como está.\",\"ru\":\"Попросите поработать в новой ветке, и агент создаст отдельное рабочее дерево Git и продолжит работу там, оставив вашу текущую рабочую копию как есть.\",\"zh\":\"要求在新分支上工作时,智能体会创建单独的 Git 工作树并在其中继续,你当前的工作树保持原样。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-cua-bundle\",\"title\":{\"en\":\"Computer use\",\"de\":\"Computernutzung\",\"es\":\"Uso de la computadora\",\"fr\":\"Utilisation de l'ordinateur\",\"ja\":\"Computer Use\",\"pt\":\"Uso do computador\",\"ru\":\"Использование компьютера\",\"zh\":\"Computer Use\"},\"description\":{\"en\":\"Currently supports macOS; Windows support is in development. Loads computer use for existing and new PTC sessions. Switch to PTC mode and grant Accessibility and Screen Recording permissions to use it.\",\"de\":\"Unterstützt derzeit macOS; Die Windows-Unterstützung befindet sich in der Entwicklung. Lädt die Computernutzung für bestehende und neue PTC-Sitzungen. Wechseln Sie in den PTC-Modus und erteilen Sie die Berechtigungen für Barrierefreiheit und Bildschirmaufzeichnung, um ihn zu verwenden.\",\"es\":\"Actualmente es compatible con macOS; El soporte para Windows está en desarrollo. Carga el uso de la computadora para sesiones PTC nuevas y existentes. Cambie al modo PTC y otorgue permisos de Accesibilidad y Grabación de pantalla para usarlo.\",\"fr\":\"Prend actuellement en charge macOS ; La prise en charge de Windows est en cours de développement. Charge l'utilisation de l'ordinateur pour les sessions PTC existantes et nouvelles. Passez en mode PTC et accordez les autorisations d’accessibilité et d’enregistrement d’écran pour l’utiliser.\",\"ja\":\"現在は macOS のみ対応し、Windows 対応は開発中です。既存および新規の PTC セッションに Computer Use を読み込みます。PTC モードに切り替え、アクセシビリティと画面収録の権限を許可して使用してください。\",\"pt\":\"Atualmente suporta macOS; O suporte Windows está em desenvolvimento. Carrega o uso do computador para sessões PTC novas e existentes. Mude para o modo PTC e conceda permissões de acessibilidade e gravação de tela para usá-lo.\",\"ru\":\"В настоящее время поддерживается macOS; Поддержка Windows находится в разработке. Загружает использование компьютера для существующих и новых сеансов PTC. Переключитесь в режим PTC и предоставьте разрешения на доступность и запись экрана для его использования.\",\"zh\":\"目前仅支持 macOS,Windows 支持正在开发中。为已有及新建 PTC 会话加载 Computer Use。请切换到 PTC 模式来使用,并授予辅助功能和屏幕录制权限。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-plugin-market-bundle\",\"title\":{\"en\":\"Custom plugin indexes\",\"de\":\"Benutzerdefinierte Plugin-Indizes\",\"es\":\"Índices de complementos personalizados\",\"fr\":\"Index de plugins personnalisés\",\"ja\":\"カスタムプラグインインデックス\",\"pt\":\"Índices de plug-ins personalizados\",\"ru\":\"Пользовательские индексы плагинов\",\"zh\":\"自定义插件索引\"},\"description\":{\"en\":\"Adds a Discover tab to Plugins, where you browse and install plugins from plugin indexes you add.\",\"de\":\"Fügt unter „Plugins“ den Tab „Entdecken“ hinzu, in dem Sie Plugins aus von Ihnen hinzugefügten Plugin-Indizes durchsuchen und installieren.\",\"es\":\"Añade la pestaña “Descubrir” a “Complementos”, donde puede explorar e instalar complementos de los índices de complementos que agregue.\",\"fr\":\"Ajoute à « Plugins » un onglet « Découvrez » où vous parcourez et installez des plugins provenant des index de plugins que vous ajoutez.\",\"ja\":\"「プラグイン」に「見つける」タブを追加し、追加したプラグインインデックスからプラグインを閲覧・インストールできるようにします。\",\"pt\":\"Adiciona a guia “Descubra” a “Plug-ins”, onde você navega e instala plug-ins dos índices de plug-ins que adiciona.\",\"ru\":\"Добавляет в «Плагины» вкладку «Откройте для себя», где можно просматривать и устанавливать плагины из добавленных вами индексов плагинов.\",\"zh\":\"在插件页添加“发现”标签页,从你添加的插件索引中浏览和安装插件。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-forge-bundle\",\"title\":{\"en\":\"Change requests & worktrees\",\"de\":\"Änderungsanfragen und Arbeitsbäume\",\"es\":\"Solicitudes de cambio y árboles de trabajo\",\"fr\":\"Demandes de modification et arbres de travail\",\"ja\":\"変更リクエストとワークツリー\",\"pt\":\"Solicitações de alteração e árvores de trabalho\",\"ru\":\"Запросы на изменение и рабочие деревья\",\"zh\":\"变更请求与工作树\"},\"description\":{\"en\":\"Track each Session's change requests with their checks and reviews, and start new Sessions in a Git worktree; uses the gh CLI for GitHub.\",\"de\":\"Verfolgen Sie die Änderungsanfragen jeder Sitzung mit ihren Prüfungen und Reviews und starten Sie neue Sitzungen in einem Git-Arbeitsbaum; nutzt die gh CLI für GitHub.\",\"es\":\"Siga las solicitudes de cambio de cada sesión con sus comprobaciones y revisiones, e inicie nuevas sesiones en un árbol de trabajo de Git; usa la CLI gh para GitHub.\",\"fr\":\"Suivez les demandes de modification de chaque session avec leurs vérifications et revues, et démarrez de nouvelles sessions dans un arbre de travail Git ; utilise la CLI gh pour GitHub.\",\"ja\":\"各セッションの変更リクエストとそのチェックやレビューを追跡し、新しいセッションを Git ワークツリーで開始できます。GitHub には gh CLI を使用します。\",\"pt\":\"Acompanhe as solicitações de alteração de cada sessão com suas verificações e revisões e inicie novas sessões em uma árvore de trabalho Git; usa a CLI gh para o GitHub.\",\"ru\":\"Отслеживайте запросы на изменение каждого сеанса вместе с их проверками и ревью и начинайте новые сеансы в рабочем дереве Git; для GitHub используется gh CLI.\",\"zh\":\"跟踪每个会话的变更请求及其检查与评审,新会话也可以在 Git 工作树中开始;GitHub 通过 gh 命令行访问。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-subagent-claude-code\",\"title\":{\"de\":\"Claude Code-Subagent\",\"en\":\"Claude Code subagent\",\"es\":\"Subagente Claude Code\",\"fr\":\"Sous-agent Claude Code\",\"ja\":\"Claude Code サブエージェント\",\"pt\":\"Claude Code subagente\",\"ru\":\"Субагент Claude Code\",\"zh\":\"Claude Code 子智能体\"},\"description\":{\"de\":\"Delegieren Sie eine Aufgabe an Claude Code, indem Sie dessen native Authentifizierung und Einstellungen verwenden.\",\"en\":\"Delegate one task to Claude Code using its native authentication and settings.\",\"es\":\"Delegue una tarea a Claude Code utilizando su autenticación y configuración nativas.\",\"fr\":\"Déléguez une tâche à Claude Code à l’aide de son authentification et de ses paramètres natifs.\",\"ja\":\"Claude Code のネイティブの認証と設定を使用して、単独のタスクを委派します。\",\"pt\":\"Delegue uma tarefa a Claude Code usando sua autenticação e configurações nativas.\",\"ru\":\"Делегируйте одну задачу Claude Code, используя его встроенную аутентификацию и настройки.\",\"zh\":\"使用 Claude Code 原生认证和设置委派单个任务。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-subagent-codex\",\"title\":{\"de\":\"Codex-Subagent\",\"en\":\"Codex subagent\",\"es\":\"Subagente Codex\",\"fr\":\"Sous-agent Codex\",\"ja\":\"Codex サブエージェント\",\"pt\":\"Codex subagente\",\"ru\":\"Субагент Codex\",\"zh\":\"Codex 子智能体\"},\"description\":{\"de\":\"Delegieren Sie eine Aufgabe an Codex, indem Sie dessen native Authentifizierung und Einstellungen verwenden.\",\"en\":\"Delegate one task to Codex using its native authentication and settings.\",\"es\":\"Delegue una tarea a Codex utilizando su autenticación y configuración nativas.\",\"fr\":\"Déléguez une tâche à Codex à l’aide de son authentification et de ses paramètres natifs.\",\"ja\":\"Codex のネイティブの認証と設定を使用して、単独のタスクを委派します。\",\"pt\":\"Delegue uma tarefa a Codex usando sua autenticação e configurações nativas.\",\"ru\":\"Делегируйте одну задачу Codex, используя его встроенную аутентификацию и настройки.\",\"zh\":\"使用 Codex 原生认证和设置委派单个任务。\"},\"enabled\":false}]\n\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[16],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["ask_user_question","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","list_subagent_models","plugin_manager","present","propose_action","read","read_image","schedule_create","schedule_delete","schedule_list","schedule_update","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} From a40d1f4c36c0583aba55f0bfc63f90c18365dda7 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 12:12:21 +0800 Subject: [PATCH 08/55] test(cua): capture the card status while Computer Use enables --- apps/web/tests/expected/cua-permissions/enabling.expected.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/tests/expected/cua-permissions/enabling.expected.md b/apps/web/tests/expected/cua-permissions/enabling.expected.md index b9d6557e3e..44fc57e3e3 100644 --- a/apps/web/tests/expected/cua-permissions/enabling.expected.md +++ b/apps/web/tests/expected/cua-permissions/enabling.expected.md @@ -1 +1 @@ -- button "立即启用" [disabled] +- status: 正在应用 Computer Use 的更改 From 4247226074c5d4bebd95608bd1901934f32f8f85 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 13:29:15 +0800 Subject: [PATCH 09/55] refactor(plugins): drop catalog listedByDefault after Computer Use leaves the on-demand catalog No on-demand catalog entry declares listedByDefault once Computer Use ships with the installation, so the generator field, catalog type, and plugin-manager propagation lose their only consumer. Also correct the packed-worker comment and the Computer Use README wording. Refs #7514 --- apps/web/tests/preview-boot.e2e.ts | 3 +-- packages/boot/plugin-manager/src/index.ts | 1 - packages/boot/plugin-manager/tests/manager.spec.ts | 1 - packages/client/ui-plugin-manager/README.i18n.yaml | 4 ++-- packages/client/ui-plugin-manager/README.md | 2 +- packages/client/ui-plugin-manager/README.zh.md | 2 +- .../tests/manager-store.client.spec.ts | 8 ++++---- packages/experimental/cua-bundle/README.i18n.yaml | 8 ++++---- packages/experimental/cua-bundle/README.md | 3 +-- packages/experimental/cua-bundle/README.zh.md | 3 +-- packages/util/official-bundles/README.i18n.yaml | 4 ++-- packages/util/official-bundles/README.md | 2 +- packages/util/official-bundles/README.zh.md | 2 +- packages/util/official-bundles/src/index.ts | 2 -- scripts/gen-official-bundle-catalog.spec.ts | 11 ----------- scripts/gen-official-bundle-catalog.ts | 12 +++--------- 16 files changed, 22 insertions(+), 46 deletions(-) diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index 13d03475ff..f1ea40b25c 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -716,8 +716,7 @@ async function toggleOptionalBundles(page: Page): Promise { enable: 'failed', disable: 'applied', error: { code: 'unsupported-platform' }, changed: 0, inactive: [], restored: true, }) - // The packed worker composition excludes LiveShare from its generic toggles; plugin-manager.e2e.ts - // covers that bundle's enable/disable path in the ordinary Web scaffold. + // 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([]) diff --git a/packages/boot/plugin-manager/src/index.ts b/packages/boot/plugin-manager/src/index.ts index ceb82aac47..b1d696ad74 100644 --- a/packages/boot/plugin-manager/src/index.ts +++ b/packages/boot/plugin-manager/src/index.ts @@ -522,7 +522,6 @@ export class PluginManager extends TypertRemoteService { catch (error) { platformError = managementError(error) } const error = platformError ?? targetError ?? (enabled ? { code: 'not-bundle' as const } : undefined) bundles.push({ name, official, availability: 'missing', ...catalogMeta, ...target, enabled, installed, optional, - ...offered.listedByDefault === undefined ? {} : { listedByDefault: offered.listedByDefault }, ...platformError?.code === 'unsupported-platform' ? { listedByDefault: false } : {}, removable: enabled, rows: [], overrides: [], ...error === undefined ? {} : { error } }) diff --git a/packages/boot/plugin-manager/tests/manager.spec.ts b/packages/boot/plugin-manager/tests/manager.spec.ts index 207f34291f..8187c45a9b 100644 --- a/packages/boot/plugin-manager/tests/manager.spec.ts +++ b/packages/boot/plugin-manager/tests/manager.spec.ts @@ -1811,7 +1811,6 @@ it('lists absent Official entries offline without resolving their packages or co expect(bundles.filter(bundle => bundle.name === entry.packageName)).toMatchObject([{ name: entry.packageName, official: true, availability: 'missing', enabled: false, installed: false, optional: false, removable: false, updatable: false, rows: [], overrides: [], meta: entry.meta, - ...entry.listedByDefault === undefined ? {} : { listedByDefault: entry.listedByDefault }, ...entry.platforms !== undefined && !entry.platforms.includes(process.platform) ? { listedByDefault: false, error: { code: 'unsupported-platform' } } : {}, installTarget: { spec: `${entry.packageName}@${getDshRuntimeVersion()}`, version: getDshRuntimeVersion() }, diff --git a/packages/client/ui-plugin-manager/README.i18n.yaml b/packages/client/ui-plugin-manager/README.i18n.yaml index f9d7f07f73..a28974991b 100644 --- a/packages/client/ui-plugin-manager/README.i18n.yaml +++ b/packages/client/ui-plugin-manager/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package: - en: 07da57fb0a0cb10e - zh: c743fd96317bec22 + en: 5a06147f2a79eccf + zh: 6ca5899680e3cc6f /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/installing-a-bundle: en: 45f62bdddae3f8c0 zh: 4be303f322a5553a diff --git a/packages/client/ui-plugin-manager/README.md b/packages/client/ui-plugin-manager/README.md index 66a9a11321..dce39d6932 100644 --- a/packages/client/ui-plugin-manager/README.md +++ b/packages/client/ui-plugin-manager/README.md @@ -39,7 +39,7 @@ Installed bundles and their plugin rows display their own title and description A bundle's page shows the bundle's detail document first among its sections, without a heading of its own: the bundle's long description in the current UI language, as Markdown with images. It is the Markdown file that `meta.detail` in the bundle's `locale/.json` names, otherwise the bundle's README, read by [`pluginManager.readBundleDetail`](../../boot/plugin-manager/README.md#bundle-detail-documents) in the [document order of `dsh-plugin-detail`](../../util/plugin-detail/README.md#document-order); the repository a bundle declares is not read. An installed bundle's document comes from its own files without network access, and an on-demand Official bundle's from the npm file CDNs at its offered version. While the document loads the section shows three skeleton lines; a bundle without a document shows no section; a failed read names its reason with **Retry**. Raw HTML is omitted, relative images load from the Host beside the document, relative links stay text, and a document taller than the section's height limit scrolls inside it. A bundle whose files are not installed, such as an on-demand Official bundle, is read from the npm file CDNs: its read first asks the Host's registry comparison and, when npmmirror answered fastest, reads it and its images from npmmirror first. An installed bundle's read does not wait for the comparison. Any profile change and a connection reset read shown documents again. -On-demand Official cards follow package discovery visibility and are available offline before installation. In Add plugin, a bare Official package name uses the Host’s matching-version or source-checkout target, retains the selected registry, and offers Enable now after installation. Turning one On opens the existing install progress dialog, installs the [target offered by the running Host](../../boot/plugin-manager/README.md#use-this-package), and selects its layer. The same registry fallback, cancellation, and script-approval controls apply. Turning Off keeps the dependency installed; Remove is separate. A different version or development link source offers **Update**; details show current and offered sources and versions. An update removes the installed package and installs the offered one with the same selection, reporting whether a restart is required; when the installation fails after the removal, the package stays uninstalled. Missing or unreadable packages keep their recorded dependency source alongside the diagnostic. An enabled bundle can still be switched Off when its checkout target is unavailable. +On-demand Official cards are visible offline before installation. In Add plugin, a bare Official package name uses the Host’s matching-version or source-checkout target, retains the selected registry, and offers Enable now after installation. Turning one On opens the existing install progress dialog, installs the [target offered by the running Host](../../boot/plugin-manager/README.md#use-this-package), and selects its layer. The same registry fallback, cancellation, and script-approval controls apply. Turning Off keeps the dependency installed; Remove is separate. A different version or development link source offers **Update**; details show current and offered sources and versions. An update removes the installed package and installs the offered one with the same selection, reporting whether a restart is required; when the installation fails after the removal, the package stays uninstalled. Missing or unreadable packages keep their recorded dependency source alongside the diagnostic. An enabled bundle can still be switched Off when its checkout target is unavailable. The first list read shows a short group-heading placeholder and four skeleton cards, using the real cards' row, icon, and text-line spacing, with the action area left blank. They use the same opacity pulse as Session search and remain static with reduced motion. The accessible loading label and read timing are unchanged; refreshes retain the existing list, and installation and component-loading indicators keep their own states. diff --git a/packages/client/ui-plugin-manager/README.zh.md b/packages/client/ui-plugin-manager/README.zh.md index bfffd1fe09..5466effc6c 100644 --- a/packages/client/ui-plugin-manager/README.zh.md +++ b/packages/client/ui-plugin-manager/README.zh.md @@ -39,7 +39,7 @@ kind: "package-reference" 组合包页面在其各部分中首先显示该组合包的详细介绍文档,不带单独的标题:以当前界面语言、带图片的 Markdown 显示该组合包的详细介绍。该文档是组合包 `locale/.json` 中 `meta.detail` 指定的 Markdown 文件,没有时为组合包的 README,由 [`pluginManager.readBundleDetail`](../../boot/plugin-manager/README.zh.md#bundle-detail-documents) 按 [`dsh-plugin-detail` 的文档顺序](../../util/plugin-detail/README.zh.md#document-order)读取;不读取组合包声明的仓库。已安装组合包的文档来自其自身文件,不访问网络;按需官方组合包的文档按其提供的版本从 npm 文件 CDN 读取。文档加载期间,该部分显示三行骨架屏;没有文档的组合包不显示该部分;读取失败时说明原因,并提供**重试**。原始 HTML 会被省略,相对路径的图片从 Host 上该文档旁的位置加载,相对链接保持为文本,文档高度超过该部分的高度上限时在该部分内滚动。文件未安装的组合包(例如按需官方组合包)从 npm 文件 CDN 读取:读取前先询问 Host 的注册表比较,npmmirror 响应最快时,先从 npmmirror 读取该文档及其图片。已安装组合包的读取不等待该比较。任何 profile 变化和连接重置都会重新读取已显示的文档。 -官方按需卡片遵循包的显示声明,在安装前即可离线读取。在“添加插件”中输入不带版本的官方包名时,使用 Host 提供的匹配版本或源码 checkout 目标,保留用户选择的安装源,并在安装后提供“立即启用”。开启会打开已有的安装进度对话框,安装[当前 Host 提供的目标](../../boot/plugin-manager/README.zh.md#use-this-package)并选择配置层。安装源回退、取消和脚本审批继续使用同一组控件。关闭保留依赖;移除是独立操作。版本或开发链接来源不同会提供**更新**;详情显示当前及所提供的来源和版本。更新先删除已安装的包,再以相同的选择状态安装所提供的包,并报告是否需要重启;删除之后安装失败时,该包保持未安装。文件缺失或不可读的包在诊断旁保留记录的依赖来源。已启用的 bundle 在 checkout 目标不可用时仍可关闭。 +官方按需卡片在安装前即可离线显示。在“添加插件”中输入不带版本的官方包名时,使用 Host 提供的匹配版本或源码 checkout 目标,保留用户选择的安装源,并在安装后提供“立即启用”。开启会打开已有的安装进度对话框,安装[当前 Host 提供的目标](../../boot/plugin-manager/README.zh.md#use-this-package)并选择配置层。安装源回退、取消和脚本审批继续使用同一组控件。关闭保留依赖;移除是独立操作。版本或开发链接来源不同会提供**更新**;详情显示当前及所提供的来源和版本。更新先删除已安装的包,再以相同的选择状态安装所提供的包,并报告是否需要重启;删除之后安装失败时,该包保持未安装。文件缺失或不可读的包在诊断旁保留记录的依赖来源。已启用的 bundle 在 checkout 目标不可用时仍可关闭。 首次读取列表时,页面显示一条较短的分组标题占位和四行骨架卡片,沿用真实卡片的行、图标和文字间距,操作区域留白。骨架使用与 Session 搜索相同的透明度呼吸动效,在减少动态效果模式下保持静止。无障碍加载文案和读取时机不变;刷新时保留已有列表,安装及组件加载仍使用各自的状态提示。 diff --git a/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts b/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts index 67b95bded7..dd8cb347e7 100644 --- a/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts +++ b/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts @@ -1979,10 +1979,10 @@ const CATALOG: BundleInfo = { installTarget: { spec: '@deepseek-ai/dsh-subagent-codex@2.0.0', version: '2.0.0' }, } -it.each(['registry', 'source'] as const)('installs a typed default-hidden Official name using its %s target', async (mode) => { - const name = '@deepseek-ai/dsh-cua-bundle' - const spec = mode === 'source' ? 'link:/workspace/cua-bundle' : `${name}@2.0.0` - const entry = { ...CATALOG, name, listedByDefault: false, installTarget: { spec, version: '2.0.0' } } +it.each(['registry', 'source'] as const)('installs a typed Official catalog name using its %s target', async (mode) => { + const name = CATALOG.name + const spec = mode === 'source' ? 'link:/workspace/subagent-codex' : `${name}@2.0.0` + const entry = { ...CATALOG, installTarget: { spec, version: '2.0.0' } } const { controller, plugins, face, state } = bench({ listBundles: vi.fn().mockResolvedValue(ok([entry])) }) await controller.load() face.openInstall() diff --git a/packages/experimental/cua-bundle/README.i18n.yaml b/packages/experimental/cua-bundle/README.i18n.yaml index b3b770c7a9..b561f27e44 100644 --- a/packages/experimental/cua-bundle/README.i18n.yaml +++ b/packages/experimental/cua-bundle/README.i18n.yaml @@ -15,8 +15,8 @@ en: b563e4ec4727d0de zh: d0228da978238e05 /deepseek-ai-dsh-cua-bundle/use-this-package: - en: 1c54bec900429732 - zh: c062f2515dc3e41a + en: 5c025a58990bb2eb + zh: c3d1280ccbdfe214 /deepseek-ai-dsh-cua-bundle/understand-the-implementation: en: b1011db52cfc17cd zh: 6fa8798fedc5c0b6 @@ -39,8 +39,8 @@ en: 417c40acd93df532 zh: 69cc5cf7140c75a9 /deepseek-ai-dsh-cua-bundle/known-limitations-and-deferred-work: - en: f2362542e43a1946 - zh: c45ca90c66ce6a48 + en: 559776e398bb7c47 + zh: 27adfd2cacad1ee6 /deepseek-ai-dsh-cua-bundle/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: ce96645b3e75874e diff --git a/packages/experimental/cua-bundle/README.md b/packages/experimental/cua-bundle/README.md index 6f4bba076a..50109f1066 100644 --- a/packages/experimental/cua-bundle/README.md +++ b/packages/experimental/cua-bundle/README.md @@ -24,7 +24,7 @@ Enable macOS Computer Use from Plugins for existing and new PTC sessions. Window ## Use this package -On macOS, open **Plugins → More** and switch on Computer use in the Experimental plugins list. The bundle ships with DSH and updates with it, so enabling it downloads nothing. Published packages contain the signed and notarized helper; users need no compiler. Source Web and development Desktop prepare an ad-hoc helper when enabled. Open Computer Use details, choose PTC if needed, and grant Accessibility and Screen Recording to `DSH Computer Use.app`. An enabled bundle also appears in the main plugin list; switching it off returns it to the Experimental plugins list only. For source Web, run these commands from the repository root: +On macOS, open **Plugins → More** and switch on **Computer use** in the Experimental plugins list. The bundle ships with DSH and updates with it, so enabling it downloads nothing. Published packages contain the signed and notarized helper; users need no compiler. Source Web and development Desktop prepare an ad-hoc helper when enabled. Open its details, choose PTC if needed, and grant Accessibility and Screen Recording to `DSH Computer Use.app`. An enabled bundle also appears in the main plugin list; switching it off returns it to the Experimental plugins list only. For source Web, run these commands from the repository root: ```sh pnpm run build @@ -86,7 +86,6 @@ CUA activation and removal change the PTC SDK and system guidance; subsequent re - System permissions require the user’s approval in macOS; enabling the bundle does not grant them. -- A profile that installed the bundle from a registry keeps that dependency. The installation’s copy loads instead, and the plugin page offers no removal for the redundant dependency. - PTC execution is shared by the profile and is configured independently. A Host without HMR applies saved changes at restart. diff --git a/packages/experimental/cua-bundle/README.zh.md b/packages/experimental/cua-bundle/README.zh.md index 5d6cb63eb2..b7d8804e91 100644 --- a/packages/experimental/cua-bundle/README.zh.md +++ b/packages/experimental/cua-bundle/README.zh.md @@ -24,7 +24,7 @@ kind: "package-bundle" ## 使用本包 -在 macOS 上打开“插件 → 更多”,在实验性插件列表中开启 Computer Use。组合包随 DSH 提供并随之升级,开启时无需下载。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 在开启时准备临时签名的 helper。打开 Computer Use 详情,按需设置 PTC,并为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。源码 Web 在仓库根目录运行以下命令: +在 macOS 上打开“插件 → 更多”,在实验性插件列表中开启 Computer Use。组合包随 DSH 提供并随之升级,开启时无需下载。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 在开启时准备临时签名的 helper。打开它的详情,按需设置 PTC,并为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。源码 Web 在仓库根目录运行以下命令: ```sh pnpm run build @@ -86,7 +86,6 @@ CUA 生效和卸载会改变 PTC SDK 与系统指引,后续请求使用更新 - 系统权限需用户在 macOS 中确认,开启组合包不会自动授予权限。 -- 从注册表安装过组合包的 profile 会保留该依赖。加载的是安装目录中的副本,插件页不提供移除这条多余依赖的操作。 - PTC 执行方式由 profile 共享,需单独配置。未启用 HMR 的 Host 在重启时应用已保存的变更。 diff --git a/packages/util/official-bundles/README.i18n.yaml b/packages/util/official-bundles/README.i18n.yaml index e843d9aadd..b58cb9c8e7 100644 --- a/packages/util/official-bundles/README.i18n.yaml +++ b/packages/util/official-bundles/README.i18n.yaml @@ -27,8 +27,8 @@ en: 27c22abdfff69a41 zh: e60d828cdb75c263 /deepseek-ai-dsh-official-bundles/use-this-package/on-demand-bundles: - en: ba4f412474854ba1 - zh: 17dae8155c013367 + en: 6ba39ba5bfefec79 + zh: 788a71b5b6f75404 /deepseek-ai-dsh-official-bundles/understand-the-implementation: en: 3fb2b58db529d8be zh: 46064459a23d458d diff --git a/packages/util/official-bundles/README.md b/packages/util/official-bundles/README.md index f1e0d1224b..9af85af79f 100644 --- a/packages/util/official-bundles/README.md +++ b/packages/util/official-bundles/README.md @@ -41,7 +41,7 @@ Edit this package when the installation's bundle selection or the plugin manager ### On-demand bundles -`ON_DEMAND_BUNDLES` names the public Official packages installed only on request. `OFFICIAL_ON_DEMAND_CATALOG` embeds their package-owned localized metadata, icons, and optional `dsh.bundle.platforms` declarations for offline discovery and Host platform checks before installation; `pnpm gen-official-bundle-catalog` explicitly updates generated content, and `verify-official-bundle-catalog` checks resource completeness and freshness; builds consume the committed catalog without importing provider code. The catalog contains no install target: the plugin manager derives it from the running version and installation and uses the ordinary bundle installer. The [product-use check](../../../scripts/verify-product-use.ts) composes shipped and on-demand selections against Web without executing providers. The catalog also preserves `listedByDefault` so a default-hidden bundle stays hidden until explicitly installed or enabled. +`ON_DEMAND_BUNDLES` names the public Official packages installed only on request. `OFFICIAL_ON_DEMAND_CATALOG` embeds their package-owned localized metadata, icons, and optional `dsh.bundle.platforms` declarations for offline discovery and Host platform checks before installation; `pnpm gen-official-bundle-catalog` explicitly updates generated content, and `verify-official-bundle-catalog` checks resource completeness and freshness; builds consume the committed catalog without importing provider code. The catalog contains no install target: the plugin manager derives it from the running version and installation and uses the ordinary bundle installer. The [product-use check](../../../scripts/verify-product-use.ts) composes shipped and on-demand selections against Web without executing providers. ----- diff --git a/packages/util/official-bundles/README.zh.md b/packages/util/official-bundles/README.zh.md index 2ce46257d2..91c0722cf7 100644 --- a/packages/util/official-bundles/README.zh.md +++ b/packages/util/official-bundles/README.zh.md @@ -41,7 +41,7 @@ kind: "package-library" ### 按需组合包 -`ON_DEMAND_BUNDLES` 列出只在请求时安装的官方公开包。`OFFICIAL_ON_DEMAND_CATALOG` 内嵌这些包自己持有的本地化元信息、图标和可选的 `dsh.bundle.platforms` 声明,用于离线发现与安装前的 Host 平台检查;`pnpm gen-official-bundle-catalog` 显式更新生成内容,`verify-official-bundle-catalog` 检查资源完整性与时效;构建使用已提交的目录,不导入提供方代码。目录不包含安装目标:插件管理器根据运行中的版本和安装推导目标,并使用普通的组合包安装器。[产品使用检查](../../../scripts/verify-product-use.ts)针对 Web 组合随附选择和按需选择,不执行提供方。 目录也保留 `listedByDefault`,使默认隐藏的组合包在用户显式安装或启用前保持隐藏。 +`ON_DEMAND_BUNDLES` 列出只在请求时安装的官方公开包。`OFFICIAL_ON_DEMAND_CATALOG` 内嵌这些包自己持有的本地化元信息、图标和可选的 `dsh.bundle.platforms` 声明,用于离线发现与安装前的 Host 平台检查;`pnpm gen-official-bundle-catalog` 显式更新生成内容,`verify-official-bundle-catalog` 检查资源完整性与时效;构建使用已提交的目录,不导入提供方代码。目录不包含安装目标:插件管理器根据运行中的版本和安装推导目标,并使用普通的组合包安装器。[产品使用检查](../../../scripts/verify-product-use.ts)针对 Web 组合随附选择和按需选择,不执行提供方。 ----- diff --git a/packages/util/official-bundles/src/index.ts b/packages/util/official-bundles/src/index.ts index e84033d6f0..433ff321a4 100644 --- a/packages/util/official-bundles/src/index.ts +++ b/packages/util/official-bundles/src/index.ts @@ -17,8 +17,6 @@ export interface OfficialBundleCatalogEntry { readonly packageName: string /** Package-owned Host platform declaration, available before installation. */ readonly platforms?: DshBundleManifest['platforms'] - /** Package-owned discovery visibility before installation. */ - readonly listedByDefault?: boolean /** Package-owned localized text and a self-contained icon, embedded without provider code. */ readonly meta: Required> } diff --git a/scripts/gen-official-bundle-catalog.spec.ts b/scripts/gen-official-bundle-catalog.spec.ts index 8ca4381dce..316f4ea800 100644 --- a/scripts/gen-official-bundle-catalog.spec.ts +++ b/scripts/gen-official-bundle-catalog.spec.ts @@ -81,17 +81,6 @@ describe('Official bundle catalog generation', () => { expect(() => { syncOfficialBundleCatalog(root, true) }).toThrow('is stale') }) - it('preserves default-hidden discovery before installation', () => { - const root = fixture() - const name = ON_DEMAND_BUNDLES[0]! - updateManifest(root, name, { dsh: { bundle: { patch: './cordis.patch.yml', listedByDefault: false } } }) - expect(generateOfficialBundleCatalog(root)[0]?.listedByDefault).toBe(false) - syncOfficialBundleCatalog(root, false) - expect(readFileSync(join(root, output), 'utf8')).toContain('listedByDefault: false') - updateManifest(root, name, { dsh: { bundle: { patch: './cordis.patch.yml', listedByDefault: 'hidden' } } }) - expect(() => generateOfficialBundleCatalog(root)).toThrow('listedByDefault must be a boolean') - }) - it.each([[], ['macos'], 'darwin'].map(platforms => ({ platforms })))('rejects invalid package platform metadata $platforms', ({ platforms }) => { const root = fixture() updateManifest(root, ON_DEMAND_BUNDLES[0]!, { dsh: { bundle: { patch: './cordis.patch.yml', platforms } } }) diff --git a/scripts/gen-official-bundle-catalog.ts b/scripts/gen-official-bundle-catalog.ts index b9f703b927..4336e998c2 100644 --- a/scripts/gen-official-bundle-catalog.ts +++ b/scripts/gen-official-bundle-catalog.ts @@ -22,7 +22,7 @@ const OUTPUT = 'packages/util/official-bundles/src/catalog.generated.ts' */ export function generateOfficialBundleCatalog(root: string, names: readonly string[] = ON_DEMAND_BUNDLES): OfficialBundleCatalogEntry[] { if (names.length === 0 || new Set(names).size !== names.length) throw new Error('Official on-demand catalog must contain distinct package names') - const manifests = new Map() + const manifests = new Map() for (const path of globSync(['packages/*/*/package.json', 'apps/*/package.json', 'vendor/*/package.json'], { cwd: root }).map(path => path.replaceAll('\\', '/')).sort()) { const manifest = JSON.parse(readFileSync(resolve(root, path), 'utf8')) as { name: string @@ -30,15 +30,12 @@ export function generateOfficialBundleCatalog(root: string, names: readonly stri dependencies?: Record optionalDependencies?: Record peerDependencies?: Record - dsh?: { bundle?: { patch?: unknown; platforms?: DshBundleManifest['platforms']; listedByDefault?: boolean } } + dsh?: { bundle?: { patch?: unknown; platforms?: DshBundleManifest['platforms'] } } } if (manifests.has(manifest.name)) throw new Error(`duplicate workspace package ${manifest.name}`) - const listedByDefault = manifest.dsh?.bundle?.listedByDefault - if (listedByDefault !== undefined && typeof listedByDefault !== 'boolean') throw new Error(`${manifest.name}: dsh.bundle.listedByDefault must be a boolean`) const runtime = ['dependencies', 'optionalDependencies', 'peerDependencies'] as const manifests.set(manifest.name, { path, private: manifest.private === true, bundle: manifest.dsh?.bundle?.patch !== undefined, ...manifest.dsh?.bundle?.platforms === undefined ? {} : { platforms: manifest.dsh.bundle.platforms }, - ...listedByDefault === undefined ? {} : { listedByDefault }, runtime: runtime.flatMap(section => Object.keys(manifest[section] ?? {})) }) } const visited = new Set() @@ -80,9 +77,7 @@ export function generateOfficialBundleCatalog(root: string, names: readonly stri } } } - return { packageName, - ...entry.listedByDefault === undefined ? {} : { listedByDefault: entry.listedByDefault }, - ...entry.platforms === undefined ? {} : { platforms: entry.platforms }, + return { packageName, ...entry.platforms === undefined ? {} : { platforms: entry.platforms }, meta: { title: meta.title, description: meta.description, icon: meta.icon } } }) } @@ -100,7 +95,6 @@ export function renderOfficialBundleCatalog(entries: readonly OfficialBundleCata + entries.map(entry => ' {\n' + ` packageName: ${quote(entry.packageName)},\n` + (entry.platforms === undefined ? '' : ` platforms: [${entry.platforms.map(quote).join(', ')}],\n`) - + (entry.listedByDefault === undefined ? '' : ` listedByDefault: ${entry.listedByDefault},\n`) + ' meta: {\n' + ` title: ${localized(entry.meta.title)},\n` + ` description: ${localized(entry.meta.description)},\n` From 64394008850d97926058aeb162a6a5ef49af3e49 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 15:12:23 +0800 Subject: [PATCH 10/55] feat(cua): sign source-built helpers with a shared development identity Source checkouts build DSH Computer Use Dev with its own bundle identifier. An explicit per-user setup creates a self-signed identity in a dedicated keychain; every development build signs with it, so one macOS grant covers rebuilds and other worktrees. Unchanged sources reuse their signed generation. Fixes #7536 --- ...6-10-09-cua-shared-native-helper.i18n.yaml | 4 +- .../2026-10-09-cua-shared-native-helper.md | 2 +- .../2026-10-09-cua-shared-native-helper.zh.md | 2 +- ...6-10-29-cua-dev-signing-identity.i18n.yaml | 19 ++ .../2026-10-29-cua-dev-signing-identity.md | 33 ++++ .../2026-10-29-cua-dev-signing-identity.zh.md | 33 ++++ .../cua-source-dev-helper/guide.i18n.yaml | 16 ++ .../cua-source-dev-helper/guide.md | 19 ++ .../cua-source-dev-helper/guide.zh.md | 19 ++ .../experimental/cua-macos/README.i18n.yaml | 8 +- packages/experimental/cua-macos/README.md | 4 +- packages/experimental/cua-macos/README.zh.md | 4 +- .../cua-macos/native/README.i18n.yaml | 8 +- .../experimental/cua-macos/native/README.md | 4 +- .../cua-macos/native/README.zh.md | 4 +- .../cua-macos/native/build_app.py | 100 ++++++++-- .../cua-macos/native/dev_signing.py | 182 ++++++++++++++++++ .../cua-macos/native/tests/dev_signing_e2e.py | 60 ++++++ .../cua-macos/native/tests/test_build_app.py | 96 ++++++++- .../native/tests/test_dev_signing.py | 109 +++++++++++ packages/experimental/cua-macos/package.json | 3 + .../cua-macos/src/native-build.ts | 5 +- .../cua-macos/tests/native-build.spec.ts | 4 +- .../tests/native-publication.spec.ts | 7 + scripts/check-workspace-constraints.ts | 2 +- 25 files changed, 708 insertions(+), 39 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md create mode 100644 .agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md create mode 100644 docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md create mode 100644 packages/experimental/cua-macos/native/dev_signing.py create mode 100644 packages/experimental/cua-macos/native/tests/dev_signing_e2e.py create mode 100644 packages/experimental/cua-macos/native/tests/test_dev_signing.py diff --git a/.agents/notes/implemented/architecture/2026-10-09-cua-shared-native-helper.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-09-cua-shared-native-helper.i18n.yaml index dc596b4fae..5494e130cf 100644 --- a/.agents/notes/implemented/architecture/2026-10-09-cua-shared-native-helper.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-09-cua-shared-native-helper.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-10-09-cua-shared-native-helper.md b/.agents/notes/implemented/architecture/2026-10-09-cua-shared-native-helper.md index 8e986aaa2f..ff06f52dc1 100644 --- a/.agents/notes/implemented/architecture/2026-10-09-cua-shared-native-helper.md +++ b/.agents/notes/implemented/architecture/2026-10-09-cua-shared-native-helper.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-10-09-cua-shared-native-helper.zh.md b/.agents/notes/implemented/architecture/2026-10-09-cua-shared-native-helper.zh.md index 371ae5cc3a..2fa2f9b07f 100644 --- a/.agents/notes/implemented/architecture/2026-10-09-cua-shared-native-helper.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-09-cua-shared-native-helper.zh.md @@ -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)继续负责应用许可。 diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml new file mode 100644 index 0000000000..7f11476e9f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml @@ -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: 733d0bc8a9669023 + zh: c556b726531c9c77 +/agent-note-development-signing-identity-for-source-built-cua-helpers/alternatives-considered: + en: 4796d5f7a085b365 + zh: 7096a9623f1a1bde +/agent-note-development-signing-identity-for-source-built-cua-helpers/consequences: + en: 9e60502bcfb035aa + zh: 161556d1556db574 diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md new file mode 100644 index 0000000000..f558e5be56 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md @@ -0,0 +1,33 @@ +# 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`. 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. + +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. + +## 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. + +**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 + +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. diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md new file mode 100644 index 0000000000..8164bbb9a8 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md @@ -0,0 +1,33 @@ +# 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`。正式版及其打包流程不变。按[共享 helper 决策](2026-10-09-cua-shared-native-helper.zh.md)的要求,授权仍归经 LaunchServices 启动的 helper 应用。 + +一条显式运行的单用户初始化命令在专用钥匙串中创建自签名代码签名证书,把随机钥匙串密码保存在旁边仅所有者可读的文件中,通过密钥分区列表允许 `codesign` 使用私钥,并把该钥匙串加入用户钥匙串搜索列表。`codesign` 只从这个列表查找签名身份。开发构建每次签名前都用保存的密码解锁钥匙串,因此初始化和签名都不会弹出密码或密钥访问窗口。签名得到的指定要求只包含 Bundle ID 和证书,同一台机器上签出的所有构建都相同,与代码哈希和路径无关。 + +即使不使用时间戳服务器,证书签名也会写入签名时间。开发版发布时记录每个未签名应用与签名身份对应的目录,再次构建时直接选中该目录,不重新签名,因此相同源码保持同一个可执行文件摘要和同一个共享服务。未初始化时,开发构建使用临时签名并输出初始化命令。显式传入 `--identity` 时覆盖本机身份。 + +## 考虑过的替代方案 + +**把权限交给启动终端。** 直接启动服务时,macOS 把权限归属到启动 DSH 的终端或编辑器。该应用运行的所有程序,包括模型执行的命令,都会带上这些权限。 + +**单独的 Bundle ID 加临时签名。** 这样能把开发版与正式版的授权分开,但每次构建内容变化后代码哈希仍会改变,仍需重新授权。 + +**把自签名身份放进登录钥匙串。** 登录钥匙串已解锁且在搜索列表中,但要让 `codesign` 不弹窗地使用其中的新私钥,需要用户的登录密码。 + +**只在签名期间把钥匙串加入搜索列表。** 正式打包脚本对单次调用这样处理。多个 worktree 并发构建时会互相覆盖读取和恢复的列表,构建被中断时条目也会残留。 + +**用固定的启动器运行各 worktree 的 helper。** 授权会跟随启动器,但任何本机进程都能让它带着这些授权运行任意可执行文件,暴露面与保存的私钥相同,还少了签名检查。 + +## 后果 + +同一 macOS 用户的所有源码检出和重新编译共用一次授权。该用户的任何进程都能读取钥匙串密码,并签出获得开发版授权的代码;正式 helper 的授权不受影响,而且同一用户本来就能修改下一次构建会签名的 Swift 源码。初始化会改变用户钥匙串搜索列表,直到运行移除命令。系统设置中已有的授权在移除后仍然保留。原有的临时签名源码授权不会沿用,开发者需要给 `DSH Computer Use Dev` 授权一次。`dev_signing_e2e.py` 检查两个不同构建共用同一个指定要求,并确认移除后搜索列表已恢复。 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml new file mode 100644 index 0000000000..d93fa3eed2 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.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: 29be2dd047eba853 + zh: a2025097f7a0f37d +/source-built-computer-use-helper-identity/migration: + en: f4456b96cc84bda8 + zh: 2d941040267d7f61 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md new file mode 100644 index 0000000000..1ea3033a8b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md @@ -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` 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. + +## 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. +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. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md new file mode 100644 index 0000000000..02aaa31c24 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md @@ -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`,Bundle ID 为 `com.deepseek.harness.computer-use.dev`。旧条目上的辅助功能和屏幕录制授权不适用于它。桌面端和 npm 安装版不变。 + +## 迁移 + +1. 每个 macOS 用户运行一次 `pnpm --dir packages/experimental/cua-macos run dev-signing:setup`,之后的构建和其他 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` 条目。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index c9ff605b3b..4f2a327711 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 395f2a62b2ce6b4a zh: 67912bb946c78837 /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: 86f0d93baf627b8a - zh: df27e9c87893f97c + en: 530cd1ddd6f4cdcf + zh: 51c74c4f71e0d552 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: 786b8fd630b11e5f zh: 55143f15486afce8 @@ -45,8 +45,8 @@ en: a2c9acb5a4320dda zh: e8d1586af60215c4 /deepseek-ai-dsh-experimental-cua-macos/known-limitations-and-deferred-work: - en: d57dbc7f973d6104 - zh: dae87bc6ee99a2a2 + en: a900c335ed926dcf + zh: 4eb9537ca51ad905 /deepseek-ai-dsh-experimental-cua-macos/known-limitations-and-deferred-work/dev-note: en: b836f01bd0bceb4a zh: 8122fa08b2aa95fa diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index da51cf0e80..ab922a5bd4 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -37,7 +37,7 @@ 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. `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 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. | Field | Default | Meaning | | --- | --- | --- | @@ -215,7 +215,7 @@ The queue orders individual native requests. Holding an app object does not rese - macOS Stage Manager can reduce background window bounds and screenshots to thumbnails. Full-window observation and coordinate input in this state are not guaranteed; model guidance requires explaining foreground needs and avoiding repeated focus reclamation. - Background input depends on private SkyLight symbols; macOS updates can make them unavailable. Validate each target OS version. - Observed failures include dispatched Unicode text not appearing in Blender and background Command+A not selecting all text in AppKit. Inspect application state after input; a successful tool result confirms dispatch only. -- Source builds use ad-hoc signatures and may require authorization again after source changes. Release distribution needs a stable Developer ID signature and notarization; the build command accepts `--identity`, and installed packages preserve the distributed signature. The [permission page](../cua/README.md) offers helper authorization and target-application revocation. +- Source builds without the [development signing identity](native/README.md#build-and-service) use ad-hoc signatures and require authorization again after source changes. Release distribution needs a stable Developer ID signature and notarization; the build command accepts `--identity`, and installed packages preserve the distributed signature. The [permission page](../cua/README.md) offers helper authorization and target-application revocation. - Release packaging does not automatically verify GUI startup, helper identity or exit cleanup. Release maintainers can run the [distribution smoke](native/README.md#build-and-service) on a logged-in Mac before publication; a successful package build does not establish those runtime results. - Saved permission rows show the name, path and icon of one approved copy, not an inventory of every installation sharing its identity. Removing that copy can leave its icon unavailable. Revocation still applies to every copy with the same identity. - If macOS does not expose a running application’s bundle identifier, the helper checks its reported bundle only when its executable matches the observed process path, then falls back to that path. Consent identity creation fails only when both the bundle identifier and actual executable path are unavailable; process-instance verification can still fail independently. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 3fdd1ed5f6..73bdd2f66b 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -37,7 +37,7 @@ 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 授权。`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 授权。源码检出的 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` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。 | 字段 | 默认值 | 含义 | | --- | --- | --- | @@ -215,7 +215,7 @@ Use selectText only on controls advertising selectionWritable. It selects a uniq - macOS 台前调度可能将后台窗口的尺寸与截图变为缩略图,当前无法保证这种状态下的完整画面与坐标输入;模型指引要求说明前台需求并避免反复抢回焦点。 - 后台输入依赖私有 SkyLight 符号,macOS 升级可能使其不可用,需在目标系统版本验证。 - 实测 Blender Unicode 输入曾出现分派成功但界面未显示文本,后台 AppKit 的 Command+A 曾未选中全文。输入后必须检查应用状态;工具返回成功只表示已分派。 -- 源码构建使用临时签名,源码变化后可能需要重新授权。正式分发应以固定 Developer ID 签名并完成公证;构建命令支持 `--identity` 指定签名身份,安装版保留分发时的签名。[权限页面](../cua/README.zh.md)提供 helper 授权入口和目标应用许可撤销。 +- 未配置[开发签名身份](native/README.zh.md#build-and-service)时,源码构建使用临时签名,源码变化后需要重新授权。正式分发应以固定 Developer ID 签名并完成公证;构建命令支持 `--identity` 指定签名身份,安装版保留分发时的签名。[权限页面](../cua/README.zh.md)提供 helper 授权入口和目标应用许可撤销。 - 发布打包不自动验证 GUI 启动、helper 身份或退出清理。发布维护者可在发布前,在已登录桌面的 Mac 上执行[分发 smoke](native/README.zh.md#build-and-service);打包成功不能证明这些运行行为已通过验收。 - 已保存许可的条目显示一个已批准副本的名称、路径和图标,不枚举共享身份的所有安装副本。删除该副本后图标可能不可用,撤销仍作用于同一身份的所有副本。 - macOS 无法提供运行中应用的 Bundle ID 时,helper 仅在其报告的 bundle 可执行路径与实际进程路径相同时读取该 bundle,仍无标识则使用路径。只有 Bundle ID 和实际可执行路径均不可用时才拒绝生成授权身份;进程实例验证仍可能独立失败。 diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 83bbf0b697..291fd98c0c 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -15,8 +15,8 @@ en: e8cbc43d38786c40 zh: 52b3ba85d98011b9 /dsh-cua-native-helper/build-and-service: - en: 7619d37566e773ef - zh: c8f6e37f19ad9763 + en: 405120fe2ade9d33 + zh: 8981a10cb38ccd2f /dsh-cua-native-helper/request-protocol: en: fc8043c425322cdd zh: cf1edb9a78fda301 @@ -24,8 +24,8 @@ en: caeccd866da14a36 zh: 6a82e3a16a03813e /dsh-cua-native-helper/verification: - en: 706d3434799530b3 - zh: e327c5fc7330c2b9 + en: 2cddaae20fc5e39e + zh: 69ffdf436e5083f1 /dsh-cua-native-helper/further-exploration: en: 265e1927952ce6d7 zh: 7c35d9fd98b6e6c8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index ae932f0a97..d6405657be 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -25,6 +25,8 @@ 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-`. 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. + Generations in `native/.build/prepared/` and `native/bin/darwin-` 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. The manual **Package CUA helper · macOS** [workflow](../../../../.github/workflows/cua-helper-package.yml) builds both architectures on `dsh-mac-package-trial`. Select a trusted `source_ref` and machine `preset`; credentials use the existing [macOS packaging configuration](../../../../apps/desktop/packaging/README.md#macos-actions). Packaging does not require a macOS desktop login or Rosetta. `pnpm exec tsx scripts/cua-helper/package.ts --out ` runs the same preparation from the repository root. It signs, notarizes and staples each complete application before selecting its final content digest, then verifies architectures, signatures, tickets, Gatekeeper and file integrity from the extracted `cua-helper.tgz`. Packaging does not launch the helper. Run `python3 scripts/cua-helper/smoke.py ` separately in a logged-in desktop session to check capabilities, helper identity and cleanup; x64 execution on Apple Silicon requires Rosetta. The smoke does not request permissions or inspect applications. Failed or timed-out commands and unreadable startup replies report captured stdout and stderr; invalid encoding is replaced only in diagnostic text, while protocol parsing remains strict. A successful package build does not certify runtime behavior. @@ -119,7 +121,7 @@ Desktop checks require grants for `DSH Computer Use.app`; source rebuilds with a 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, signing failure and corrupted-generation rejection. +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. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index d7473d91b0..6ff48be6c4 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -25,6 +25,8 @@ kind: "package-reference" 运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-` 下生成带签名的 `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 证书。 + `native/.build/prepared/` 和 `native/bin/darwin-` 中的各代应用不会自动清理。正式打包时使用全新的 `--output-directory`,或确认没有客户端使用后清理打包输出再构建,避免旧应用进入 tarball。安全签名时间戳可能让相同源码生成不同代应用。 手动工作流 **Package CUA helper · macOS** 的[配置](../../../../.github/workflows/cua-helper-package.yml)在 `dsh-mac-package-trial` 构建两种架构。选择可信的 `source_ref` 和机器 `preset`;凭据沿用[macOS 打包配置](../../../../apps/desktop/packaging/README.zh.md#macos-actions)。打包无需 macOS 桌面登录或 Rosetta。在仓库根目录运行 `pnpm exec tsx scripts/cua-helper/package.ts --out ` 可执行相同准备。完整应用签名、公证和贴票后才确定最终内容摘要,再从解包后的 `cua-helper.tgz` 验证架构、签名、票据、Gatekeeper 和文件完整性。打包不启动 helper。在已登录的桌面会话中单独运行 `python3 scripts/cua-helper/smoke.py ` 检查能力、helper 身份和退出清理;Apple Silicon 上执行 x64 版本需要 Rosetta。该检查不申请权限或观察应用。命令失败、超时或启动回复无法解析时,会输出捕获的 stdout 和 stderr;无效编码只在诊断文本中替换,协议解析仍严格校验。打包成功不代表运行验收通过。 @@ -119,7 +121,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 运行 `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_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` 将检查限定为协议与进程生命期。 diff --git a/packages/experimental/cua-macos/native/build_app.py b/packages/experimental/cua-macos/native/build_app.py index cd27ce2d88..9d1924b735 100644 --- a/packages/experimental/cua-macos/native/build_app.py +++ b/packages/experimental/cua-macos/native/build_app.py @@ -1,14 +1,20 @@ """Build, sign and publish immutable Computer Use application generations.""" import argparse import hashlib +import importlib.util import json import os from pathlib import Path import platform +import plistlib import shutil import subprocess +import sys import tempfile +DEV_BUNDLE_SUFFIX = ".dev" +DEV_DISPLAY_NAME = "DSH Computer Use Dev" + def bundle_digest(application): """Hash bundle membership and bytes; generated bundles contain only regular files.""" @@ -27,29 +33,66 @@ def bundle_digest(application): return digest.hexdigest() -def publish(binary, output, identity, plist): - """Publish a complete signed bundle before atomically selecting its generation.""" +def application_info(plist, variant): + """Render Info.plist; development builds get their own bundle identifier and permission entry.""" + if variant == "release": + return plist.read_bytes() + info = plistlib.loads(plist.read_bytes()) + info["CFBundleIdentifier"] += DEV_BUNDLE_SUFFIX + info["CFBundleName"] = info["CFBundleDisplayName"] = DEV_DISPLAY_NAME + return plistlib.dumps(info) + + +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: + raise ValueError(f"Retained helper application does not match its content digest: {application}") + return application if application.exists() else None + + +def select(output, temporary, key): + receipt = Path(temporary) / "current.json" + receipt.write_text(json.dumps({"bundle": key}) + "\n") + os.replace(receipt, output / "current.json") + return output / key / "DSH Computer Use.app/Contents/MacOS/dsh-cua-native" + + +def publish(binary, output, identity, plist, variant="release", keychain=None): + """Publish a complete signed bundle before atomically selecting its generation. + + Certificate signatures embed a signing time, so development builds record which generation + each unsigned bundle and identity produced and select it again instead of re-signing. + """ output.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix=".prepare-", dir=output) as temporary: staged = Path(temporary) / "DSH Computer Use.app" executable = staged / "Contents/MacOS/dsh-cua-native" executable.parent.mkdir(parents=True) shutil.copy2(binary, executable) - shutil.copy2(plist, staged / "Contents/Info.plist") + (staged / "Contents/Info.plist").write_bytes(application_info(plist, variant)) 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) - subprocess.run(["/usr/bin/codesign", "--force", "--sign", identity, "--options", "runtime", - "--timestamp=none" if identity == "-" else "--timestamp", str(staged)], check=True) + index = None + if variant == "dev": + source = hashlib.sha256(f"{bundle_digest(staged)}\0{identity}".encode()).hexdigest() + index = output / "sources" / source + if index.is_file(): + key = index.read_text().strip() + if retained(output, key) is not None: + return select(output, temporary, key) + command = ["/usr/bin/codesign", "--force", "--sign", identity, "--options", "runtime", + "--timestamp=none" if identity == "-" or variant == "dev" else "--timestamp"] + if keychain is not None: + command += ["--keychain", str(keychain)] + subprocess.run([*command, str(staged)], check=True) subprocess.run(["/usr/bin/codesign", "--verify", "--strict", str(staged)], check=True) key = bundle_digest(staged) generation = output / key application = generation / staged.name - if application.exists(): - if bundle_digest(application) != key: - raise ValueError(f"Retained helper application does not match its content digest: {application}") - else: + if retained(output, key) is None: generation.mkdir(exist_ok=True) try: staged.rename(application) @@ -57,10 +100,34 @@ def publish(binary, output, identity, plist): # Independent packagers can publish the same immutable generation. if not application.is_dir() or bundle_digest(application) != key: raise - receipt = Path(temporary) / "current.json" - receipt.write_text(json.dumps({"bundle": key}) + "\n") - os.replace(receipt, output / "current.json") - return application / "Contents/MacOS/dsh-cua-native" + if index is not None: + index.parent.mkdir(exist_ok=True) + entry = Path(temporary) / "source" + entry.write_text(key + "\n") + os.replace(entry, index) + return select(output, temporary, key) + + +def load_dev_signing(): + """Load the sibling module whether this file runs as a script or is imported by path.""" + location = Path(__file__).resolve().with_name("dev_signing.py") + spec = importlib.util.spec_from_file_location("dev_signing", location) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + 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": + 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 + return local.sha1, local.keychain def main(): @@ -69,15 +136,18 @@ def main(): parser.add_argument("--arch", choices=["arm64", "x86_64"], default=platform.machine()) parser.add_argument("--scratch-path", type=Path) parser.add_argument("--output-directory", type=Path) - parser.add_argument("--identity", default="-", help="codesign identity; '-' produces a local ad-hoc build") + 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") 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) 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) - executable = publish(scratch / "release/dsh-cua-native", output, args.identity, root / "Info.plist") + executable = publish(scratch / "release/dsh-cua-native", output, identity, root / "Info.plist", args.variant, keychain) print(executable) diff --git a/packages/experimental/cua-macos/native/dev_signing.py b/packages/experimental/cua-macos/native/dev_signing.py new file mode 100644 index 0000000000..74d0cff401 --- /dev/null +++ b/packages/experimental/cua-macos/native/dev_signing.py @@ -0,0 +1,182 @@ +"""Own the per-user signing identity that keeps source-built Computer Use permissions across rebuilds. + +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. + +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 +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 dataclasses import dataclass +import json +import os +from pathlib import Path +import re +import secrets +import shutil +import subprocess +import sys +import tempfile + +DEFAULT_DIRECTORY = Path.home() / "Library/Application Support/DeepSeek Harness/computer-use-dev-signing" +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" +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 security(*args): + """Run security without echoing arguments, which can contain keychain passwords.""" + try: + return subprocess.run([SECURITY, *args], check=True, capture_output=True, text=True, timeout=60).stdout + except subprocess.CalledProcessError as error: + raise RuntimeError(f"security {args[0]} failed: {error.stderr.strip()}") from None + + +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 load(directory=DEFAULT_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. + """ + record = record_path(directory) + if not record.exists(): + return None + fields = json.loads(record.read_text()) + keychain = keychain_path(directory) + if not keychain.is_file(): + raise RuntimeError(f"Computer Use development signing keychain is missing: {keychain}; run {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)) + 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}"], + ): + 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 + 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=DEFAULT_DIRECTORY): + """Create the identity once and keep its keychain on the user search list.""" + 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) + directory.mkdir(mode=0o700, parents=True) + 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=DEFAULT_DIRECTORY): + """Delete the keychain, its search-list entry and the stored password.""" + 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)) + if directory.exists(): + shutil.rmtree(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) + 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") + else: + identity = load(args.directory) + print("not configured" if identity is None else f"{identity.sha1} {identity.keychain}") + + +if __name__ == "__main__": + try: + main() + except RuntimeError as error: + print(error, file=sys.stderr) + sys.exit(1) diff --git a/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py b/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py new file mode 100644 index 0000000000..232ea9953b --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py @@ -0,0 +1,60 @@ +"""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 tempfile + +NATIVE = Path(__file__).resolve().parents[1] + + +def module(name): + spec = importlib.util.spec_from_file_location(name, NATIVE / f"{name}.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 / "signing" + try: + identity = signing.setup(directory) + 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) + application = executable.parents[2] + 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 / "output/current.json").read_text())["bundle"] + assert second.parent.name == selected + print(f"PASS: changed development builds share {first_requirement}") + finally: + signing.remove(directory) + assert signing.user_keychains() == before, "the user keychain search list was not restored" + + +if __name__ == "__main__": + main() diff --git a/packages/experimental/cua-macos/native/tests/test_build_app.py b/packages/experimental/cua-macos/native/tests/test_build_app.py index e8578c434f..7486076931 100644 --- a/packages/experimental/cua-macos/native/tests/test_build_app.py +++ b/packages/experimental/cua-macos/native/tests/test_build_app.py @@ -1,7 +1,11 @@ """Application publication preserves complete immutable bundles and previous receipts.""" +import contextlib import importlib.util +import io import json from pathlib import Path +import plistlib +import secrets import tempfile import unittest from unittest.mock import patch @@ -11,7 +15,8 @@ builder = importlib.util.module_from_spec(spec) spec.loader.exec_module(builder) -class PublicationTests(unittest.TestCase): +class PublicationCases: + """Publication behavior shared by release and development variants.""" def setUp(self): temporary = tempfile.TemporaryDirectory(prefix="cua-bundle-") self.addCleanup(temporary.cleanup) @@ -81,11 +86,100 @@ class PublicationTests(unittest.TestCase): with self.assertRaisesRegex(ValueError, "not a real directory"): builder.bundle_digest(linked) + +class ReleasePublicationTests(PublicationCases, unittest.TestCase): def test_release_identity_uses_a_secure_timestamp(self): builder.publish(self.binary, self.output, "Developer ID Application: Example", self.plist) self.assertIn("--timestamp", self.commands.call_args_list[0].args[0]) self.assertNotIn("--timestamp=none", self.commands.call_args_list[0].args[0]) + def test_release_publication_keeps_info_plist_bytes_and_records_no_sources(self): + first = self.publish() + self.assertEqual((first.parents[1] / "Info.plist").read_text(), "application identity") + self.assertEqual(sorted(path.name for path in self.output.iterdir()), sorted([first.parents[3].name, "current.json"])) + + +class DevelopmentPublicationTests(PublicationCases, unittest.TestCase): + def setUp(self): + super().setUp() + self.plist.write_bytes(plistlib.dumps({"CFBundleIdentifier": "com.example.helper", "CFBundleName": "Helper", + "CFBundleDisplayName": "Helper", "CFBundleExecutable": "dsh-cua-native"})) + # Certificate signatures embed a signing time, so each signing pass produces different bytes. + def sign(command, check): + if command[1] == "--force": + signature = Path(command[-1]) / "Contents/_CodeSignature/CodeResources" + signature.parent.mkdir(exist_ok=True) + signature.write_bytes(secrets.token_bytes(16)) + self.commands.side_effect = sign + + def publish(self, identity="0123456789ABCDEF0123456789ABCDEF01234567"): + return builder.publish(self.binary, self.output, identity, self.plist, "dev", Path("/keychains/dev.keychain-db")) + + def signings(self): + return [call.args[0] for call in self.commands.call_args_list if call.args[0][1] == "--force"] + + def test_signing_failure_keeps_the_previous_selected_application(self): + self.publish() + previous = (self.output / "current.json").read_bytes() + self.binary.write_bytes(b"changed executable") + self.commands.side_effect = RuntimeError("signer unavailable") + with self.assertRaisesRegex(RuntimeError, "signer unavailable"): + self.publish() + self.assertEqual((self.output / "current.json").read_bytes(), previous) + self.assertEqual(list(self.output.glob(".prepare-*")), []) + + def test_development_bundle_has_its_own_identifier_and_display_name(self): + info = plistlib.loads((self.publish().parents[1] / "Info.plist").read_bytes()) + self.assertEqual(info["CFBundleIdentifier"], "com.example.helper.dev") + self.assertEqual((info["CFBundleName"], info["CFBundleDisplayName"]), ("DSH Computer Use Dev", "DSH Computer Use Dev")) + self.assertEqual(info["CFBundleExecutable"], "dsh-cua-native") + + def test_development_signing_uses_the_local_keychain_without_a_timestamp_server(self): + self.publish() + command = self.signings()[0] + self.assertIn("--timestamp=none", command) + self.assertEqual(command[command.index("--keychain") + 1], "/keychains/dev.keychain-db") + + def test_unchanged_content_selects_the_signed_generation_without_signing_again(self): + first = self.publish() + self.binary.write_bytes(b"second executable") + second = self.publish() + self.binary.write_bytes(b"first executable") + self.assertEqual(self.publish(), first) + self.assertEqual(len(self.signings()), 2) + self.assertEqual(json.loads((self.output / "current.json").read_text())["bundle"], first.parents[3].name) + self.assertNotEqual(second, first) + + def test_another_identity_signs_the_same_content_again(self): + first = self.publish() + other = self.publish("FEDCBA9876543210FEDCBA9876543210FEDCBA98") + self.assertNotEqual(other, first) + self.assertEqual(len(self.signings()), 2) + + +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_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): + local = type("Identity", (), {"sha1": "ABC", "keychain": Path("/keychains/dev.keychain-db")}) + self.assertEqual(self.resolve("dev", None, local), (("ABC", Path("/keychains/dev.keychain-db")), "")) + + 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_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) + if __name__ == "__main__": unittest.main() diff --git a/packages/experimental/cua-macos/native/tests/test_dev_signing.py b/packages/experimental/cua-macos/native/tests/test_dev_signing.py new file mode 100644 index 0000000000..373b6e75f3 --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/test_dev_signing.py @@ -0,0 +1,109 @@ +"""Development signing setup keeps one unlocked identity on the user keychain search list.""" +import importlib.util +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location("dev_signing", Path(__file__).resolve().parents[1] / "dev_signing.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() + return "" + + +class DevelopmentSigningTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory(prefix="cua-dev-signing-") + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + 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() + 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_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 pnpm"): + 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_an_incomplete_directory(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_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]) + + +if __name__ == "__main__": + unittest.main() diff --git a/packages/experimental/cua-macos/package.json b/packages/experimental/cua-macos/package.json index 13a7c2fd2b..e52d26722a 100644 --- a/packages/experimental/cua-macos/package.json +++ b/packages/experimental/cua-macos/package.json @@ -31,6 +31,7 @@ "native/Info.plist", "native/DSHComputerUse.icns", "native/build_app.py", + "native/dev_signing.py", "native/Sources", "native/tests/swift", "native/tests/test_swift.py", @@ -97,6 +98,8 @@ }, "scripts": { "build:native": "xcrun python3 native/build_app.py", + "dev-signing:setup": "xcrun python3 native/dev_signing.py setup", + "dev-signing:remove": "xcrun python3 native/dev_signing.py remove", "build:icon": "node native/generate_icon.mjs" }, "os": [ diff --git a/packages/experimental/cua-macos/src/native-build.ts b/packages/experimental/cua-macos/src/native-build.ts index 8fc603a61e..c67fe8ecab 100644 --- a/packages/experimental/cua-macos/src/native-build.ts +++ b/packages/experimental/cua-macos/src/native-build.ts @@ -64,7 +64,8 @@ export async function isSourcePackage(packageRoot: string): Promise { } /** - * Build and sign an immutable helper application with the selected Apple developer tools. + * 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. * @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. @@ -79,7 +80,7 @@ export async function buildNativeExecutable(spec: NativeBuildSpec): Promise nativeHostArchitecture(platform, architecture)).toThrow('requires macOS') }) -it('returns a bundled executable only after the managed builder exits', async () => { +it('builds the development variant and returns its executable only after the managed builder exits', async () => { const f = await fixture() const path = await buildNativeExecutable(f.spec) expect(await readFile(path)).toEqual(f.output) @@ -77,7 +77,7 @@ it('returns a bundled executable only after the managed builder exits', async () 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', + '--output-directory', f.directory, '--arch', 'arm64', '--variant', 'dev', ]) expect(f.terminate).toHaveBeenCalledTimes(1) expect(f.waitForExit).toHaveBeenCalledTimes(1) diff --git a/packages/experimental/cua-macos/tests/native-publication.spec.ts b/packages/experimental/cua-macos/tests/native-publication.spec.ts index 0b80ab04f5..1013f06072 100644 --- a/packages/experimental/cua-macos/tests/native-publication.spec.ts +++ b/packages/experimental/cua-macos/tests/native-publication.spec.ts @@ -10,6 +10,13 @@ it.skipIf(process.platform === 'win32')('preserves signed generations and reject expect(output).toBe('') }) +it.skipIf(process.platform === 'win32')('keeps one unlocked development signing identity on the user keychain search list', () => { + const output = execFileSync('python3', [fileURLToPath(new URL('../native/tests/test_dev_signing.py', import.meta.url))], { + encoding: 'utf8', timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'], + }) + expect(output).toBe('') +}) + it.skipIf(process.platform === 'win32')('accepts shallow bare reference paths in native test helpers', () => { const output = execFileSync('python3', [fileURLToPath(new URL('../native/tests/test_native_test_support.py', import.meta.url))], { encoding: 'utf8', timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'], diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index c3bcaf5a1a..98fbaf81ec 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -191,7 +191,7 @@ const packageFileExtras: Readonly> = { '@deepseek-ai/dsh-experimental-subagent-oar': ['LICENSE-OAR'], // CUA publishes its client API and attributed native source for local macOS builds. '@deepseek-ai/dsh-cua': ['lib/remote-types.js', 'lib/api.js', 'lib/bridge.js', 'lib/native-client.js', 'lib/protocol.js'], - '@deepseek-ai/dsh-experimental-cua-macos': ['native/bin', 'cua-helper.json', 'native/Package.swift', 'native/Info.plist', 'native/DSHComputerUse.icns', 'native/build_app.py', 'native/Sources', 'native/tests/swift', 'native/tests/test_swift.py', 'native/LICENSE.cua-driver', 'native/LICENSE.computer-use-icon', 'native/upstream.json', 'native/README.md', 'native/README.zh.md', 'native/protocol.schema.json'], + '@deepseek-ai/dsh-experimental-cua-macos': ['native/bin', 'cua-helper.json', 'native/Package.swift', 'native/Info.plist', 'native/DSHComputerUse.icns', 'native/build_app.py', 'native/dev_signing.py', 'native/Sources', 'native/tests/swift', 'native/tests/test_swift.py', 'native/LICENSE.cua-driver', 'native/LICENSE.computer-use-icon', 'native/upstream.json', 'native/README.md', 'native/README.zh.md', 'native/protocol.schema.json'], '@deepseek-ai/dsh-webhook-github': ['examples/github-review/cordis.yml', 'examples/github-review/github-ready-review-rule.mjs'], // Liveshare publishes its built Relay gateway entry and the shared runtime // chunk that entry imports, plus the declaration-plane entry and its chunk. From e57fe7969681e3ffbc98013c08e807d0f034a325 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 15:35:59 +0800 Subject: [PATCH 11/55] feat(cua): make local development signing opt in --- ...6-10-29-cua-dev-signing-identity.i18n.yaml | 12 +-- .../2026-10-29-cua-dev-signing-identity.md | 8 +- .../2026-10-29-cua-dev-signing-identity.zh.md | 8 +- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- .../cua-source-dev-helper/guide.i18n.yaml | 4 +- .../cua-source-dev-helper/guide.md | 4 +- .../cua-source-dev-helper/guide.zh.md | 4 +- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 13 +++- packages/experimental/cua-macos/README.zh.md | 13 +++- .../cua-macos/native/README.i18n.yaml | 8 +- .../experimental/cua-macos/native/README.md | 12 ++- .../cua-macos/native/README.zh.md | 12 ++- .../cua-macos/native/build_app.py | 38 ++++++---- .../cua-macos/native/dev_signing.py | 72 +++++++++++++----- .../cua-macos/native/tests/dev_signing_e2e.py | 13 +++- .../cua-macos/native/tests/test_build_app.py | 64 +++++++++++----- .../native/tests/test_dev_signing.py | 75 +++++++++++++++++++ packages/experimental/cua-macos/src/index.ts | 4 +- .../cua-macos/src/native-build.ts | 7 +- .../cua-macos/tests/native-build.spec.ts | 11 +-- .../tests/provider-lifecycle.spec.ts | 9 ++- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 + packages/experimental/cua/README.zh.md | 2 + packages/experimental/cua/src/index.ts | 7 ++ 27 files changed, 310 insertions(+), 104 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml index 7f11476e9f..609751ecf8 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md index f558e5be56..304ae4ac5f 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md index 8164bbb9a8..82762767d9 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md @@ -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` 检查两个不同构建共用同一个指定要求,并确认移除后搜索列表已恢复。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index a0a770bb22..22a80e5041 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -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 ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 7e9c6f3506..5619c331bb 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -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 ``` diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml index d93fa3eed2..a96bc3a49c 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml @@ -12,5 +12,5 @@ en: 29be2dd047eba853 zh: a2025097f7a0f37d /source-built-computer-use-helper-identity/migration: - en: f4456b96cc84bda8 - zh: 2d941040267d7f61 + en: 318184f2a11cbcea + zh: c320de5acc4ee165 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md index 1ea3033a8b..851c406650 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md @@ -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. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md index 02aaa31c24..c92d67c868 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md @@ -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`,并在系统设置中删除开发版授权。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 4f2a327711..1782d61fce 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -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 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index ab922a5bd4..e75e3e0a80 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -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. | diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 73bdd2f66b..55a8418d83 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -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 的截止时间。 | diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 291fd98c0c..1277d7c7be 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -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 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index d6405657be..9b7ba380b1 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -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-`. 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/` and `native/bin/darwin-` 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 ## 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. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 6ff48be6c4..374cbaaa47 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -25,7 +25,13 @@ kind: "package-reference" 运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-` 下生成带签名的 `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/` 和 `native/bin/darwin-` 中的各代应用不会自动清理。正式打包时使用全新的 `--output-directory`,或确认没有客户端使用后清理打包输出再构建,避免旧应用进入 tarball。安全签名时间戳可能让相同源码生成不同代应用。 @@ -117,13 +123,13 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 ## 验证 -桌面检查要求给 `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 按钮点击,截取窗口,并记录删除可执行文件后的观察结果;此模式要求已有两项系统权限。 diff --git a/packages/experimental/cua-macos/native/build_app.py b/packages/experimental/cua-macos/native/build_app.py index 9d1924b735..87262c46da 100644 --- a/packages/experimental/cua-macos/native/build_app.py +++ b/packages/experimental/cua-macos/native/build_app.py @@ -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) diff --git a/packages/experimental/cua-macos/native/dev_signing.py b/packages/experimental/cua-macos/native/dev_signing.py index 74d0cff401..438c7b54b1 100644 --- a/packages/experimental/cua-macos/native/dev_signing.py +++ b/packages/experimental/cua-macos/native/dev_signing.py @@ -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__": diff --git a/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py b/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py index 232ea9953b..f31f8884ae 100644 --- a/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py +++ b/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py @@ -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: diff --git a/packages/experimental/cua-macos/native/tests/test_build_app.py b/packages/experimental/cua-macos/native/tests/test_build_app.py index 7486076931..f4627ff0cd 100644 --- a/packages/experimental/cua-macos/native/tests/test_build_app.py +++ b/packages/experimental/cua-macos/native/tests/test_build_app.py @@ -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__": diff --git a/packages/experimental/cua-macos/native/tests/test_dev_signing.py b/packages/experimental/cua-macos/native/tests/test_dev_signing.py index 373b6e75f3..510e5ce005 100644 --- a/packages/experimental/cua-macos/native/tests/test_dev_signing.py +++ b/packages/experimental/cua-macos/native/tests/test_dev_signing.py @@ -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() diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index b351d8be8f..cfbcae615f 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -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 { 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 () => { diff --git a/packages/experimental/cua-macos/src/native-build.ts b/packages/experimental/cua-macos/src/native-build.ts index c67fe8ecab..a81c7e6922 100644 --- a/packages/experimental/cua-macos/src/native-build.ts +++ b/packages/experimental/cua-macos/src/native-build.ts @@ -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 signal: AbortSignal timeoutMs: number @@ -65,7 +68,7 @@ export async function isSourcePackage(packageRoot: string): Promise { /** * 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 { 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() diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 77195e0dd8..1e9ab1efc3 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -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 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) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index cc1d8c7a73..0ef85a1bc4 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -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 diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index ea4b8e2b24..3c64f08c09 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -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. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 043817a53f..e5802c472d 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -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 重载规则。权限检查和执行方式状态独立返回。设置仍在加载、只读或不可用时不能提交;写入失败时在设置旁显示错误,供用户重试。 diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index e9fee3a268..a770f3b6b3 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -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), From b5197dd07d4012f9c5fb7435b13981c7a486d987 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 15:39:02 +0800 Subject: [PATCH 12/55] test(cua): type invalid signing configuration explicitly --- .../experimental/cua-macos/tests/provider-lifecycle.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 1e9ab1efc3..ac132d8bbb 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -69,7 +69,7 @@ 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() + expect(() => NativeProvider.Config({ sourceSigning: 'developer-id' } as never)).toThrow() }) it('defaults the explicit click hold limit to five seconds and accepts a configured zero or larger limit', () => { From ce988594eef95a0e05edda8313bcd40d76f7d479 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 29 Oct 2026 16:14:35 +0800 Subject: [PATCH 13/55] docs(notes): correct the read guidance evidence and cross-links Split the sidecar coverage into 83 test:snapshot sidecars and 6 web snapshots run by test:web:ci, state the Pass@3 denominator, record that the benchmark is neutral for this sentence, and link the read and subagent notes to each other in both languages. --- ...26-10-21-subagent-end-turn-guidance.i18n.yaml | 4 ++-- .../2026-10-21-subagent-end-turn-guidance.md | 2 +- .../2026-10-21-subagent-end-turn-guidance.zh.md | 2 +- ...026-10-26-read-guidance-line-ranges.i18n.yaml | 16 ++++++++-------- .../2026-10-26-read-guidance-line-ranges.md | 7 ++++--- .../2026-10-26-read-guidance-line-ranges.zh.md | 7 ++++--- 6 files changed, 20 insertions(+), 18 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.i18n.yaml index 8b8bba1309..bbc63b3c3b 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.md b/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.md index cd800e94fe..8a25a23102 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.md +++ b/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.md @@ -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 diff --git a/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.zh.md b/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.zh.md index b11656473a..ba1c5cbc6a 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-10-21-subagent-end-turn-guidance.zh.md @@ -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` 参数顺序是各自有证据的独立决定;本记录只覆盖委派段。 ## 验证 diff --git a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml index c50e4ba604..c682d07e6b 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml @@ -6,17 +6,17 @@ en: 1926710614598539 zh: b0106d4a6a2d648d /agent-note-read-guidance-names-shell-readers-and-line-ranges/problem: - en: 0b8dc80eb5a32bfb - zh: e3a5588a330af784 + 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: a18ff1df8c97931c - zh: fd071b1b02755285 + en: aea7ffb1159ab81a + zh: 4842ca79dc30654d /agent-note-read-guidance-names-shell-readers-and-line-ranges/verification: - en: 08557f13c54f2912 - zh: a0ae60861df1aea8 + en: 7d7a46a6e98087da + zh: 80339994cbd09b1f /agent-note-read-guidance-names-shell-readers-and-line-ranges/consequences: - en: d92130932f757899 - zh: 011b8b66de41cf06 + en: cf55161ea197a7a9 + zh: fa10ca413f8fd726 diff --git a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md index 66e1a6396d..447aaca9aa 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md +++ b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md @@ -8,7 +8,7 @@ English | [中文](2026-10-26-read-guidance-line-ranges.zh.md) 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 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. +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 @@ -18,17 +18,18 @@ Restore the #6054 wording, byte-identical: `Use the read tool — not shell comm **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, and the others carry their own evidence. +**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. -- 89 `snapshots/**/system-prompt*.expected.md` sidecars carry the restored sentence and replay through the shipped profiles in `test:snapshot`; two pinned historical sidecars (`web/cordis-tool-round`, `web/schedule-catalog`) retain their recorded text. +- 83 `snapshots/**/system-prompt*.expected.md` sidecars and 6 `snapshots/web/*` sidecars carry the restored sentence; `test:snapshot` replays the 83 session and SDK sidecars, and `pnpm run test:web:ci` replays the 6 web sidecars (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. diff --git a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.zh.md b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.zh.md index 747827cbf0..c1168bb1b7 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.zh.md @@ -8,7 +8,7 @@ Status: implemented 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,步数与 token 变化方向不一(ProgramBench-New −15.5 步、Terminal-Bench-v4 +13.5 步)。PTC 模式的运行没有包含这个变体;只要 `read` 可见,这段就会进入每个请求。 +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` 可见,这段就会进入每个请求。 ## 决策 @@ -18,17 +18,18 @@ read 指导只把 `cat` 点名为 read 工具替代的 shell 命令,并把 `of **只依赖 read 工具 schema。** schema 已经写明 `offset` 与 `limit`,但 #6057 显示在那个 schema 存在时模型仍选择 `sed`;指导是唯一点名 `sed`、`head`、`tail` 的模型可见位置。 -**把与这句一起被回退的所有提示词都恢复。** subagent 结束本轮句、`run_code` 参数顺序、PTC 语法归属、SDK persona 是各自独立的决定;第一项已经恢复,其余各有自己的证据。 +**把与这句一起被回退的所有提示词都恢复。** 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` 断言渲染出的指导文本。 -- 89 个 `snapshots/**/system-prompt*.expected.md` sidecar 带有恢复后的句子,由 `test:snapshot` 通过随附 profile 回放;两个显式 pin 的历史 sidecar(`web/cordis-tool-round`、`web/schedule-catalog`)保留录制文本。 +- 83 个 `snapshots/**/system-prompt*.expected.md` sidecar 和 6 个 `snapshots/web/*` sidecar 带有恢复后的句子;`test:snapshot` 回放 83 个 session/SDK sidecar,`pnpm run test:web:ci` 回放 6 个 web sidecar(`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 的生产观测,而不是测到的质量收益。 From 91474bb32ef78a84e62c2904cbfed916fa11a7d5 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 16:17:26 +0800 Subject: [PATCH 14/55] fix(cua): distinguish the development helper application name --- ...6-10-29-cua-dev-signing-identity.i18n.yaml | 4 ++-- .../2026-10-29-cua-dev-signing-identity.md | 2 +- .../2026-10-29-cua-dev-signing-identity.zh.md | 2 +- .../cua-source-dev-helper/guide.i18n.yaml | 4 ++-- .../cua-source-dev-helper/guide.md | 2 +- .../cua-source-dev-helper/guide.zh.md | 2 +- .../experimental/cua-macos/README.i18n.yaml | 8 +++---- packages/experimental/cua-macos/README.md | 4 ++-- packages/experimental/cua-macos/README.zh.md | 4 ++-- .../cua-macos/native/README.i18n.yaml | 8 +++---- .../experimental/cua-macos/native/README.md | 4 ++-- .../cua-macos/native/README.zh.md | 4 ++-- .../cua-macos/native/build_app.py | 19 ++++++++------- .../cua-macos/native/tests/dev_signing_e2e.py | 1 + .../cua-macos/native/tests/test_build_app.py | 15 +++++++++++- .../cua-macos/src/native-build.ts | 10 ++++---- .../cua-macos/tests/native-build.spec.ts | 24 ++++++++++++------- scripts/cua-helper/smoke.py | 2 +- 18 files changed, 71 insertions(+), 48 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml index 609751ecf8..30c3149c44 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml @@ -9,8 +9,8 @@ en: a24857a312482724 zh: dbac75d363670e86 /agent-note-development-signing-identity-for-source-built-cua-helpers/decision: - en: b11d0338edfa56f6 - zh: ec93519fb3acc99d + en: 1063fd73edaf7c56 + zh: 9b491cba43f26d32 /agent-note-development-signing-identity-for-source-built-cua-helpers/alternatives-considered: en: 713bcd3484cf3594 zh: ae45617289117b7e diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md index 304ae4ac5f..411f9bc0b3 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md @@ -10,7 +10,7 @@ Source checkouts compile `DSH Computer Use.app` with an ad-hoc signature. macOS ## 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`. 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. +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` 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. diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md index 82762767d9..1ada9cb3c1 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md @@ -10,7 +10,7 @@ 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 应用。 +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` 默认为 `ad-hoc`,不读取已有身份或修改钥匙串。显式选择 `local-identity` 后,构建自动初始化或复用本机身份。初始化在专用钥匙串中创建自签名代码签名证书,把随机钥匙串密码保存在旁边仅所有者可读的文件中,通过密钥分区列表允许 `codesign` 使用私钥,并把该钥匙串加入用户钥匙串搜索列表。`codesign` 只从这个列表查找签名身份。固定身份构建每次签名前都用保存的密码解锁钥匙串,避免密码或密钥访问窗口。跨进程文件锁串行化不同 worktree 的初始化和移除,防止并发创建不同证书。签名得到的指定要求只包含 Bundle ID 和证书,同一台机器上签出的所有构建都相同,与代码哈希和路径无关。 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml index a96bc3a49c..a71c90c16f 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 72a8ea364f7427fa zh: 9e7ed2e00425bddb /source-built-computer-use-helper-identity/change: - en: 29be2dd047eba853 - zh: a2025097f7a0f37d + en: c0bb4349a8bb975c + zh: 7e13fa29c2b8e7c4 /source-built-computer-use-helper-identity/migration: en: 318184f2a11cbcea zh: c320de5acc4ee165 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md index 851c406650..74ac04269a 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md @@ -9,7 +9,7 @@ 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` 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 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. ## Migration diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md index c92d67c868..2fd3f1cbbc 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md @@ -9,7 +9,7 @@ description: "源码构建的 Computer Use helper 使用独立的开发版 Bundl ## 变更 -此前源码检出构建的 `DSH Computer Use.app` 使用正式版 Bundle ID `com.deepseek.harness.computer-use` 和临时签名。现在构建的是 `DSH Computer Use Dev`,Bundle ID 为 `com.deepseek.harness.computer-use.dev`。旧条目上的辅助功能和屏幕录制授权不适用于它。桌面端和 npm 安装版不变。 +此前源码检出构建的 `DSH Computer Use.app` 使用正式版 Bundle ID `com.deepseek.harness.computer-use` 和临时签名。现在构建的是 `DSH Computer Use Dev.app`,Bundle ID 为 `com.deepseek.harness.computer-use.dev`。旧条目上的辅助功能和屏幕录制授权不适用于它。桌面端和 npm 安装版不变。 ## 迁移 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 1782d61fce..e65da96194 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -12,11 +12,11 @@ en: 4549f02fc53854a5 zh: 6f74f1130b6623a8 /deepseek-ai-dsh-experimental-cua-macos/table-of-contents: - en: 395f2a62b2ce6b4a - zh: 67912bb946c78837 + en: 6390cd271bbb64fe + zh: 342f4f6aa617809f /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: 8877abe53e4b2ed8 - zh: e85dd36f64041855 + en: c94d759b5b80b8a5 + zh: cb8178d8f76f8770 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: 786b8fd630b11e5f zh: 55143f15486afce8 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index e75e3e0a80..9f93eaaa69 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -22,7 +22,7 @@ Inspect macOS permissions, select running applications and windows, read accessi The helper supplies bounded 64-pixel PNG application icons for permission prompts and saved-application lists. Icon reads do not launch an application or inspect its windows; icons do not determine reusable consent. -The helper runs through LaunchServices as the independent background application `DSH Computer Use.app`. Accessibility and Screen Recording permissions belong to this application. The permission page uses its system-reported name and icon; when attribution is unavailable, the system prompt identifies the application. +The helper runs through LaunchServices as an independent background application: `DSH Computer Use.app` for release builds and `DSH Computer Use Dev.app` for source development builds. Accessibility and Screen Recording permissions belong to this application. The permission page uses its system-reported name and icon; when attribution is unavailable, the system prompt identifies the application. ----- @@ -37,7 +37,7 @@ 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 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. +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. The helper needs Accessibility permission for AX/input and Screen Recording permission for capture; grant these permissions to the helper when prompted. Source builds use the bundle filename `DSH Computer Use Dev.app` and declare `DSH Computer Use Dev` in Info.plist; select the development entry 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`: diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 55a8418d83..f5ced6c088 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -22,7 +22,7 @@ kind: "package-reference" helper 为授权提示和已授权应用列表提供 64 像素 PNG 图标。读取图标不会启动应用或检查窗口,图标不决定可复用授权。 -helper 通过 LaunchServices 以独立的 `DSH Computer Use.app` 后台运行,辅助功能和屏幕录制权限归属于这个应用。权限页使用系统返回的应用名称和图标;无法查询归属时,以系统授权提示为准。 +helper 通过 LaunchServices 以独立应用后台运行,正式版为 `DSH Computer Use.app`,源码开发版为 `DSH Computer Use Dev.app`,辅助功能和屏幕录制权限归属于这个应用。权限页使用系统返回的应用名称和图标;无法查询归属时,以系统授权提示为准。 ----- @@ -37,7 +37,7 @@ 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 授权。源码构建在 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` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。 +配置输出命令不发起模型请求。执行真实任务时,将 `--dump-config` 替换为任务提示,并配置该 profile 的模型凭据。配置挂载 computer-use 注册表和本 provider;使用前需移除已有的竞争 provider。helper 需要辅助功能权限来读取 AX 和输入,需要屏幕录制权限来截图;按系统提示给 helper 授权。源码构建的应用包名为 `DSH Computer Use Dev.app`,Info.plist 声明名称 `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` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。 源码构建默认使用临时签名,即使本机已有开发证书也不会读取或修改钥匙串。需要在重新编译或切换 worktree 后保留签名身份时,在 profile 的 `cordis.patch.yml` 中为已加载的 `cua` 节点配置: diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 1277d7c7be..a58b538ab7 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -15,14 +15,14 @@ en: e8cbc43d38786c40 zh: 52b3ba85d98011b9 /dsh-cua-native-helper/build-and-service: - en: 488fe3adbc838de3 - zh: 768bf452370a0f36 + en: 2bc0fe6a9b96897c + zh: c43c5ab96eb3ec4b /dsh-cua-native-helper/request-protocol: en: fc8043c425322cdd zh: cf1edb9a78fda301 /dsh-cua-native-helper/observation-and-input: - en: caeccd866da14a36 - zh: 6a82e3a16a03813e + en: 27f23e6f3b77ee64 + zh: 9cd1fdc76e9f041e /dsh-cua-native-helper/verification: en: c2ad240e2ce1962f zh: 4a0cb0b30df98b71 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 9b7ba380b1..bd6f6b48c3 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -25,7 +25,7 @@ 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-`. 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 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. +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 is `DSH Computer Use Dev.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. @@ -99,7 +99,7 @@ Capture and pointer delivery read CG bounds before and after an exact-window AX `typeText` and `pressKey` target the selected process's current focused control, not an exact window. Key chords send PID-targeted modifier transitions before the base key and release modifiers in reverse order; these events do not use the global HID queue. Background pointer actions may change that keyboard focus. Keypad names such as KP_0 and KP_Enter preserve their physical key codes. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each down/up event is followed by the configured text interval; dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. -`DSH Computer Use.app` needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. +The selected helper application needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. Host-only permission controls are `permissionStatus {}`, `requestPermission {permission}`, and `openPermissionSettings {permission}`, where permission is `accessibility` or `screenRecording`. They are excluded from model tools and from `getCapabilities.methods`. Permission status includes observed helper/parent process paths; these paths do not identify the TCC responsible application. The operating-system prompt names the application and asks for the user’s decision. The helper identifies the responsible process with the optional libSystem SPI `responsibility_get_pid_responsible_for_pid`, then captures its application name and icon before publishing readiness. The function is resolved dynamically, following the same signature used by [Chromium](https://chromium.googlesource.com/chromium/src/+/refs/tags/134.0.6998.28/base/process/process_info_mac.mm). If the symbol, process, or application metadata is unavailable, attribution stays unknown; it is not inferred from the nearest GUI ancestor. Permission checks remain independent of this metadata. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 374cbaaa47..fc7de78795 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" 运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-` 下生成带签名的 `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`,应用包文件名仍为 `DSH Computer Use.app`。默认的 `--signing ad-hoc` 不访问开发钥匙串。临时签名的指定要求包含代码哈希,因此二进制变化时可能需要重新授权,干净重建也可能产生这种变化。 +源码检出以 `--variant dev` 构建:应用声明的 Bundle ID 为 `com.deepseek.harness.computer-use.dev`,名称为 `DSH Computer Use Dev`,应用包文件名为 `DSH Computer Use Dev.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 上手动授权验证。 @@ -99,7 +99,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。组合键先向 PID 发送修饰键变化,再发送主键,并逆序释放修饰键,不使用全局 HID 队列。后台鼠标操作可能改变键盘焦点。KP_0 和 KP_Enter 等数字键盘名称保留物理键码。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。每次按下和抬起后等待配置的文本事件间隔,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 -`DSH Computer Use.app` 需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 +所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 仅供 Host 使用的权限操作为 `permissionStatus {}`、`requestPermission {permission}` 和 `openPermissionSettings {permission}`,其中 permission 为 `accessibility` 或 `screenRecording`。这些操作不出现在模型工具及 `getCapabilities.methods` 中。权限状态包含观察到的 helper 和父进程路径,这些路径不能确定 TCC 归属的应用。系统授权提示负责指出应用并询问用户决定。helper 使用可选的 libSystem 内部接口 `responsibility_get_pid_responsible_for_pid` 查询责任进程,在报告就绪前记录对应应用的名称和图标。接口通过动态加载解析,函数签名与 [Chromium](https://chromium.googlesource.com/chromium/src/+/refs/tags/134.0.6998.28/base/process/process_info_mac.mm) 使用的一致。符号、进程或应用信息不可用时,归属保持未知,不根据最近的 GUI 祖先推断。权限检查独立于这些信息。 diff --git a/packages/experimental/cua-macos/native/build_app.py b/packages/experimental/cua-macos/native/build_app.py index 87262c46da..a27a41626f 100644 --- a/packages/experimental/cua-macos/native/build_app.py +++ b/packages/experimental/cua-macos/native/build_app.py @@ -44,9 +44,9 @@ def application_info(plist, variant): return plistlib.dumps(info) -def retained(output, key): +def retained(output, key, name): """Return a published generation after checking that its bytes still match its name.""" - application = output / key / "DSH Computer Use.app" + application = output / key / name if not application.exists(): return None if bundle_digest(application) != key: @@ -54,11 +54,11 @@ def retained(output, key): return application -def select(output, temporary, key): +def select(output, temporary, key, name): receipt = Path(temporary) / "current.json" receipt.write_text(json.dumps({"bundle": key}) + "\n") os.replace(receipt, output / "current.json") - return output / key / "DSH Computer Use.app/Contents/MacOS/dsh-cua-native" + return output / key / name / "Contents/MacOS/dsh-cua-native" def publish(binary, output, identity, plist, variant="release", keychain=None): @@ -69,7 +69,8 @@ def publish(binary, output, identity, plist, variant="release", keychain=None): """ output.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix=".prepare-", dir=output) as temporary: - staged = Path(temporary) / "DSH Computer Use.app" + name = f"{DEV_DISPLAY_NAME}.app" if variant == "dev" else "DSH Computer Use.app" + staged = Path(temporary) / name executable = staged / "Contents/MacOS/dsh-cua-native" executable.parent.mkdir(parents=True) shutil.copy2(binary, executable) @@ -86,8 +87,8 @@ def publish(binary, output, identity, plist, variant="release", keychain=None): index = output / "sources" / source if index.is_file(): key = index.read_text().strip() - if retained(output, key) is not None: - return select(output, temporary, key) + if retained(output, key, name) is not None: + return select(output, temporary, key, name) command = ["/usr/bin/codesign", "--force", "--sign", identity, "--options", "runtime", "--timestamp=none" if identity == "-" or variant == "dev" else "--timestamp"] if keychain is not None: @@ -97,7 +98,7 @@ def publish(binary, output, identity, plist, variant="release", keychain=None): key = bundle_digest(staged) generation = output / key application = generation / staged.name - if retained(output, key) is None: + if retained(output, key, name) is None: generation.mkdir(exist_ok=True) try: staged.rename(application) @@ -110,7 +111,7 @@ def publish(binary, output, identity, plist, variant="release", keychain=None): entry = Path(temporary) / "source" entry.write_text(key + "\n") os.replace(entry, index) - return select(output, temporary, key) + return select(output, temporary, key, name) def load_dev_signing(): diff --git a/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py b/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py index f31f8884ae..7eab63af18 100644 --- a/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py +++ b/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py @@ -46,6 +46,7 @@ def main(): 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 diff --git a/packages/experimental/cua-macos/native/tests/test_build_app.py b/packages/experimental/cua-macos/native/tests/test_build_app.py index f4627ff0cd..eeda633c5b 100644 --- a/packages/experimental/cua-macos/native/tests/test_build_app.py +++ b/packages/experimental/cua-macos/native/tests/test_build_app.py @@ -95,6 +95,7 @@ class ReleasePublicationTests(PublicationCases, unittest.TestCase): def test_release_publication_keeps_info_plist_bytes_and_records_no_sources(self): first = self.publish() + self.assertEqual(first.parents[2].name, "DSH Computer Use.app") self.assertEqual((first.parents[1] / "Info.plist").read_text(), "application identity") self.assertEqual(sorted(path.name for path in self.output.iterdir()), sorted([first.parents[3].name, "current.json"])) @@ -129,11 +130,23 @@ class DevelopmentPublicationTests(PublicationCases, unittest.TestCase): self.assertEqual(list(self.output.glob(".prepare-*")), []) def test_development_bundle_has_its_own_identifier_and_display_name(self): - info = plistlib.loads((self.publish().parents[1] / "Info.plist").read_bytes()) + executable = self.publish() + self.assertEqual(executable.parents[2].name, "DSH Computer Use Dev.app") + info = plistlib.loads((executable.parents[1] / "Info.plist").read_bytes()) self.assertEqual(info["CFBundleIdentifier"], "com.example.helper.dev") self.assertEqual((info["CFBundleName"], info["CFBundleDisplayName"]), ("DSH Computer Use Dev", "DSH Computer Use Dev")) self.assertEqual(info["CFBundleExecutable"], "dsh-cua-native") + def test_old_bundle_filename_is_republished_without_deleting_the_running_generation(self): + first = self.publish() + legacy = first.parents[2].with_name("DSH Computer Use.app") + first.parents[2].rename(legacy) + second = self.publish() + self.assertEqual(second.parents[2].name, "DSH Computer Use Dev.app") + self.assertTrue(second.is_file()) + self.assertTrue((legacy / "Contents/MacOS/dsh-cua-native").is_file()) + self.assertEqual(len(self.signings()), 2) + def test_development_signing_uses_the_local_keychain_without_a_timestamp_server(self): self.publish() command = self.signings()[0] diff --git a/packages/experimental/cua-macos/src/native-build.ts b/packages/experimental/cua-macos/src/native-build.ts index a81c7e6922..24a6932ee7 100644 --- a/packages/experimental/cua-macos/src/native-build.ts +++ b/packages/experimental/cua-macos/src/native-build.ts @@ -39,12 +39,14 @@ export interface NativeBuildSpec { /** * Resolve the immutable application selected by a packaged or source-build receipt. * @param directory - Architecture-specific directory containing current.json and application generations. + * @param variant - Development or release application filename selected by the build or installation. * @returns Executable inside the selected application bundle. * @throws When the receipt is invalid or the application executable is missing. */ -export async function nativeExecutablePath(directory: string): Promise { +export async function nativeExecutablePath(directory: string, variant: 'release' | 'dev'): Promise { const receipt = NativeApplication.parse(JSON.parse(await readFile(join(directory, 'current.json'), 'utf8'))) - const executable = join(directory, receipt.bundle, 'DSH Computer Use.app', 'Contents', 'MacOS', 'dsh-cua-native') + const application = variant === 'dev' ? 'DSH Computer Use Dev.app' : 'DSH Computer Use.app' + const executable = join(directory, receipt.bundle, application, 'Contents', 'MacOS', 'dsh-cua-native') await access(executable, constants.X_OK) return executable } @@ -98,7 +100,7 @@ export async function buildNativeExecutable(spec: NativeBuildSpec): Promise { if (await isSourcePackage(spec.packageRoot)) return buildNativeExecutable(spec) - const executable = await nativeExecutablePath(join(spec.packageRoot, 'native', 'bin', `darwin-${spec.architecture}`)) + const executable = await nativeExecutablePath(join(spec.packageRoot, 'native', 'bin', `darwin-${spec.architecture}`), 'release') spec.signal.throwIfAborted() return executable } diff --git a/packages/experimental/cua-macos/tests/native-build.spec.ts b/packages/experimental/cua-macos/tests/native-build.spec.ts index 95eb756b4d..a01f6749de 100644 --- a/packages/experimental/cua-macos/tests/native-build.spec.ts +++ b/packages/experimental/cua-macos/tests/native-build.spec.ts @@ -7,9 +7,9 @@ import { expect, it, onTestFinished, vi } from 'vitest' import type { SubprocessHandle, SubprocessOutcome, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' import { buildNativeExecutable, isSourcePackage, nativeExecutablePath, nativeHostArchitecture, prepareNativeExecutable } from '../src/native-build.ts' -async function publish(directory: string, bytes: Buffer): Promise { +async function publish(directory: string, bytes: Buffer, variant: 'release' | 'dev'): Promise { const bundle = createHash('sha256').update(bytes).digest('hex') - const executable = join(directory, bundle, 'DSH Computer Use.app', 'Contents/MacOS/dsh-cua-native') + const executable = join(directory, bundle, variant === 'dev' ? 'DSH Computer Use Dev.app' : 'DSH Computer Use.app', 'Contents/MacOS/dsh-cua-native') await mkdir(dirname(executable), { recursive: true }) await writeFile(executable, bytes, { mode: 0o755 }) await writeFile(join(directory, 'current.json'), JSON.stringify({ bundle })) @@ -36,7 +36,7 @@ async function fixture(diagnostics = true) { done: (async () => { await beforeExit() if (outcome.exitCode === 0 && !request.signal?.aborted) { - await publish(request.argv[request.argv.indexOf('--output-directory') + 1]!, output) + await publish(request.argv[request.argv.indexOf('--output-directory') + 1]!, output, 'dev') } return outcome })(), terminate, waitForExit, @@ -73,7 +73,7 @@ it('builds the development variant and returns its executable only after the man const f = await fixture() const path = await buildNativeExecutable(f.spec) expect(await readFile(path)).toEqual(f.output) - expect(path).toContain(join('DSH Computer Use.app', 'Contents', 'MacOS')) + expect(path).toContain(join('DSH Computer Use Dev.app', 'Contents', 'MacOS')) 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'), @@ -94,7 +94,7 @@ it('checks source builds on activation and maps Intel architecture to the compil 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) + const path = await publish(join(f.spec.packageRoot, 'native/bin/darwin-arm64'), f.output, 'release') expect(await prepareNativeExecutable({ ...f.spec, sourceSigning: 'local-identity' })).toBe(path) expect(f.spawn).not.toHaveBeenCalled() f.controller.abort() @@ -105,14 +105,20 @@ it.each(['../outside', '/absolute', '', 'a'.repeat(63), 'A'.repeat(64)])('reject const f = await fixture() await mkdir(f.directory, { recursive: true }) await writeFile(join(f.directory, 'current.json'), JSON.stringify({ bundle })) - await expect(nativeExecutablePath(f.directory)).rejects.toThrow() + await expect(nativeExecutablePath(f.directory, 'dev')).rejects.toThrow() }) it('refuses a missing executable selected by an otherwise valid receipt', async () => { const f = await fixture() - const path = await publish(f.directory, f.output) + const path = await publish(f.directory, f.output, 'dev') await rm(path) - await expect(nativeExecutablePath(f.directory)).rejects.toMatchObject({ code: 'ENOENT' }) + await expect(nativeExecutablePath(f.directory, 'dev')).rejects.toMatchObject({ code: 'ENOENT' }) +}) + +it('refuses a release-named application selected by a development receipt', async () => { + const f = await fixture() + await publish(f.directory, f.output, 'release') + await expect(nativeExecutablePath(f.directory, 'dev')).rejects.toMatchObject({ code: 'ENOENT' }) }) it('preserves the previous generation when preparation fails and reports diagnostics', async () => { @@ -120,7 +126,7 @@ it('preserves the previous generation when preparation fails and reports diagnos const path = await buildNativeExecutable(f.spec) f.setOutcome({ exitCode: 1, signal: null }) await expect(buildNativeExecutable(f.spec)).rejects.toThrow('compiler diagnostic') - expect(await nativeExecutablePath(f.directory)).toBe(path) + expect(await nativeExecutablePath(f.directory, 'dev')).toBe(path) f.setOutcome({ exitCode: null, signal: 'SIGTERM' }) await expect(buildNativeExecutable(f.spec)).rejects.toThrow('SIGTERM') }) diff --git a/scripts/cua-helper/smoke.py b/scripts/cua-helper/smoke.py index 513f133958..62de2606cf 100644 --- a/scripts/cua-helper/smoke.py +++ b/scripts/cua-helper/smoke.py @@ -80,7 +80,7 @@ def main(): if method == "getCapabilities": assert result["platform"] == "macos", result else: - assert result["launchApplication"]["name"] == "DSH Computer Use.app", result.get("launchApplication", {}).get("name") + assert result["launchApplication"]["name"] == executable.parents[2].name, result.get("launchApplication", {}).get("name") assert isinstance(result["accessibility"], bool) and isinstance(result["screenRecording"], bool) connection.shutdown(socket.SHUT_WR) assert stream.read() == b"", "helper did not acknowledge connection cleanup" From 09bc71f831627d968c6b9577bd95be17741dd92a Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 29 Oct 2026 16:50:16 +0800 Subject: [PATCH 15/55] test(snapshot): carry the read guidance into scenarios merged from master The merge from master adds four scenarios recorded before the restore (ptc-script-fresh, ptc-script-retained, command-attachments, plan-review); their system-prompt sidecars still show the old sentence. --- .../sdk/command-attachments/system-prompt.expected.md | 2 +- snapshots/sdk/plan-review/system-prompt.expected.md | 10 +++++----- .../session/ptc-script-fresh/system-prompt.expected.md | 2 +- .../ptc-script-retained/system-prompt.expected.md | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/snapshots/sdk/command-attachments/system-prompt.expected.md b/snapshots/sdk/command-attachments/system-prompt.expected.md index 87c8754913..7b66cec998 100644 --- a/snapshots/sdk/command-attachments/system-prompt.expected.md +++ b/snapshots/sdk/command-attachments/system-prompt.expected.md @@ -19,7 +19,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/sdk/plan-review/system-prompt.expected.md b/snapshots/sdk/plan-review/system-prompt.expected.md index d76bb0ad7b..4590ecdd88 100644 --- a/snapshots/sdk/plan-review/system-prompt.expected.md +++ b/snapshots/sdk/plan-review/system-prompt.expected.md @@ -6,7 +6,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -53,7 +53,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -87,7 +87,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -134,7 +134,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. @@ -168,7 +168,7 @@ Tokens prefixed with @ are paths the user explicitly referenced. Relative paths Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/ptc-script-fresh/system-prompt.expected.md b/snapshots/session/ptc-script-fresh/system-prompt.expected.md index cee1d38ca1..f78d20535d 100644 --- a/snapshots/session/ptc-script-fresh/system-prompt.expected.md +++ b/snapshots/session/ptc-script-fresh/system-prompt.expected.md @@ -9,7 +9,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 8b1fb247db..3dc763d9ea 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -9,7 +9,7 @@ Verify your work by running the code or tests. Keep answers brief and factual. Check the [exit code: N] marker on every bash result; investigate failures before moving on. -Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files. +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 an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes. From 58c375d8a5676753ae024aeb9891f73a2c5609d9 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 29 Oct 2026 16:51:48 +0800 Subject: [PATCH 16/55] docs(notes): avoid fixed sidecar counts in the read note --- .../bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml | 4 ++-- .../bug-fix/2026-10-26-read-guidance-line-ranges.md | 2 +- .../bug-fix/2026-10-26-read-guidance-line-ranges.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml index c682d07e6b..86e21bee13 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.i18n.yaml @@ -15,8 +15,8 @@ en: aea7ffb1159ab81a zh: 4842ca79dc30654d /agent-note-read-guidance-names-shell-readers-and-line-ranges/verification: - en: 7d7a46a6e98087da - zh: 80339994cbd09b1f + en: cbc16bfba4abe862 + zh: 9a71e6c020c01f69 /agent-note-read-guidance-names-shell-readers-and-line-ranges/consequences: en: cf55161ea197a7a9 zh: fa10ca413f8fd726 diff --git a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md index 447aaca9aa..60ad77abee 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md +++ b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.md @@ -25,7 +25,7 @@ Restore the #6054 wording, byte-identical: `Use the read tool — not shell comm ## Verification - `packages/fs/tool-fs/tests/tools.spec.ts` asserts the rendered guidance text. -- 83 `snapshots/**/system-prompt*.expected.md` sidecars and 6 `snapshots/web/*` sidecars carry the restored sentence; `test:snapshot` replays the 83 session and SDK sidecars, and `pnpm run test:web:ci` replays the 6 web sidecars (the `node 24 / snapshots and artifacts` lane runs both). Two pinned historical sidecars (`web/cordis-tool-round`, `web/schedule-catalog`) retain their recorded 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 diff --git a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.zh.md b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.zh.md index c1168bb1b7..25487ea733 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-10-26-read-guidance-line-ranges.zh.md @@ -25,7 +25,7 @@ read 指导只把 `cat` 点名为 read 工具替代的 shell 命令,并把 `of ## 验证 - `packages/fs/tool-fs/tests/tools.spec.ts` 断言渲染出的指导文本。 -- 83 个 `snapshots/**/system-prompt*.expected.md` sidecar 和 6 个 `snapshots/web/*` sidecar 带有恢复后的句子;`test:snapshot` 回放 83 个 session/SDK sidecar,`pnpm run test:web:ci` 回放 6 个 web sidecar(`node 24 / snapshots and artifacts` lane 两条都跑)。两个显式 pin 的历史 sidecar(`web/cordis-tool-round`、`web/schedule-catalog`)保留录制文本。 +- 所有渲染 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 上只改了这一句进行测量。 ## 影响 From a93b1ecdf16e4679461525e03716996e49121bd8 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 17:26:27 +0800 Subject: [PATCH 17/55] fix(cua): launch nested helpers with independent macOS permissions --- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../cua-macos/native/README.i18n.yaml | 12 +- .../experimental/cua-macos/native/README.md | 6 +- .../cua-macos/native/README.zh.md | 6 +- .../Sources/CuaNative/Permissions.swift | 14 +- .../CuaNative/SharedHelperRuntime.swift | 7 +- .../CuaNative/StandaloneApplication.swift | 80 ++++++++++ .../native/tests/nested_application_e2e.py | 79 ++++++++++ .../swift/StandaloneApplicationTests.swift | 140 ++++++++++++++++++ 11 files changed, 329 insertions(+), 23 deletions(-) create mode 100644 packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift create mode 100644 packages/experimental/cua-macos/native/tests/nested_application_e2e.py create mode 100644 packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index e8b7a196c7..cab5247eff 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -12,8 +12,8 @@ en: 4549f02fc53854a5 zh: 6f74f1130b6623a8 /deepseek-ai-dsh-experimental-cua-macos/table-of-contents: - en: 395f2a62b2ce6b4a - zh: 67912bb946c78837 + en: d473fa94a4488852 + zh: 43f0265a97820f64 /deepseek-ai-dsh-experimental-cua-macos/use-this-package: en: d7e50cc9e3ad4137 zh: a65cfb7e4688d159 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 79d19e7747..d84fdb7732 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -22,7 +22,7 @@ Inspect macOS permissions, select running applications and windows, read accessi The helper supplies bounded 64-pixel PNG application icons for permission prompts and saved-application lists. Icon reads do not launch an application or inspect its windows; icons do not determine reusable consent. -The helper runs through LaunchServices as the independent background application `DSH Computer Use.app`. Accessibility and Screen Recording permissions belong to this application. The permission page uses its system-reported name and icon; when attribution is unavailable, the system prompt identifies the application. +The helper runs through LaunchServices as the independent background application `DSH Computer Use.app`. Accessibility and Screen Recording permissions belong to this application. The permission page uses its system-reported name and icon; when attribution is unavailable, the system prompt identifies the application. When the helper is nested inside another `.app`, its launcher copies the complete signed bundle to `~/Library/Application Support/DeepSeek Harness/Computer Use//` before starting it. Each immutable generation is verified against the executable hash and application signature; earlier generations remain available for running installations. This keeps both macOS permission services attributed to the helper. A failed verification stops startup; remove the named cached generation before retrying. ----- diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index dc4fb75832..8ab08e0433 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -22,7 +22,7 @@ kind: "package-reference" helper 为授权提示和已授权应用列表提供 64 像素 PNG 图标。读取图标不会启动应用或检查窗口,图标不决定可复用授权。 -helper 通过 LaunchServices 以独立的 `DSH Computer Use.app` 后台运行,辅助功能和屏幕录制权限归属于这个应用。权限页使用系统返回的应用名称和图标;无法查询归属时,以系统授权提示为准。 +helper 通过 LaunchServices 以独立的 `DSH Computer Use.app` 后台运行,辅助功能和屏幕录制权限归属于这个应用。权限页使用系统返回的应用名称和图标;无法查询归属时,以系统授权提示为准。 helper 嵌套在另一个 `.app` 内时,启动器先把完整的已签名应用复制到 `~/Library/Application Support/DeepSeek Harness/Computer Use//`,再启动它。每个不可变目录都校验可执行文件哈希和应用签名,旧目录保留给仍在运行的安装版本使用,使两项 macOS 权限都归属于 helper。校验失败会中止启动;删除报错中指定的缓存目录后再重试。 ----- diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 83bbf0b697..3f7591dd58 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -15,17 +15,17 @@ en: e8cbc43d38786c40 zh: 52b3ba85d98011b9 /dsh-cua-native-helper/build-and-service: - en: 7619d37566e773ef - zh: c8f6e37f19ad9763 + en: ab8fe195c70dd31c + zh: b05bc116dc173c9c /dsh-cua-native-helper/request-protocol: en: fc8043c425322cdd zh: cf1edb9a78fda301 /dsh-cua-native-helper/observation-and-input: - en: caeccd866da14a36 - zh: 6a82e3a16a03813e + en: c7d6f3fec3470f3a + zh: 998b7478369d5517 /dsh-cua-native-helper/verification: - en: 706d3434799530b3 - zh: e327c5fc7330c2b9 + en: d7d27c97fff638cd + zh: 7f52556496a304d2 /dsh-cua-native-helper/further-exploration: en: 265e1927952ce6d7 zh: 7c35d9fd98b6e6c8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index ae932f0a97..1cc5243b9b 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -23,7 +23,7 @@ This macOS 14+ JSON-lines helper uses Swift 6, AppKit, Accessibility, CoreGraphi ## Build and service -Run `pnpm --dir packages/experimental/cua-macos run build:native` to publish a signed `DSH Computer Use.app` under `native/bin/darwin-`. 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. +Run `pnpm --dir packages/experimental/cua-macos run build:native` to publish a signed `DSH Computer Use.app` under `native/bin/darwin-`. 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. When the helper is nested inside another `.app`, its launcher copies the complete signed bundle to `~/Library/Application Support/DeepSeek Harness/Computer Use//` before starting it. Each immutable generation is verified against the executable hash and application signature; earlier generations remain available for running installations. This keeps both macOS permission services attributed to the helper. A failed verification stops startup; remove the named cached generation before retrying. Generations in `native/.build/prepared/` and `native/bin/darwin-` 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. @@ -93,7 +93,7 @@ Capture and pointer delivery read CG bounds before and after an exact-window AX `DSH Computer Use.app` needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. -Host-only permission controls are `permissionStatus {}`, `requestPermission {permission}`, and `openPermissionSettings {permission}`, where permission is `accessibility` or `screenRecording`. They are excluded from model tools and from `getCapabilities.methods`. Permission status includes observed helper/parent process paths; these paths do not identify the TCC responsible application. The operating-system prompt names the application and asks for the user’s decision. The helper identifies the responsible process with the optional libSystem SPI `responsibility_get_pid_responsible_for_pid`, then captures its application name and icon before publishing readiness. The function is resolved dynamically, following the same signature used by [Chromium](https://chromium.googlesource.com/chromium/src/+/refs/tags/134.0.6998.28/base/process/process_info_mac.mm). If the symbol, process, or application metadata is unavailable, attribution stays unknown; it is not inferred from the nearest GUI ancestor. Permission checks remain independent of this metadata. +Host-only permission controls are `permissionStatus {}`, `requestPermission {permission}`, and `openPermissionSettings {permission}`, where permission is `accessibility` or `screenRecording`. They are excluded from model tools and from `getCapabilities.methods`. Permission status includes observed helper/parent process paths; these paths do not identify the TCC responsible application. The operating-system prompt names the application and asks for the user’s decision. The helper identifies the responsible process with the optional libSystem SPI `responsibility_get_pid_responsible_for_pid`, then captures its application name and icon before publishing readiness. The function is resolved dynamically, following the same signature used by [Chromium](https://chromium.googlesource.com/chromium/src/+/refs/tags/134.0.6998.28/base/process/process_info_mac.mm). If the symbol, process, or application metadata is unavailable, attribution stays unknown; it is not inferred from the nearest GUI ancestor. Permission checks remain independent of this metadata. If a user-requested permission remains ungranted after the native request, the same action opens its System Settings pane, including when macOS suppresses another prompt. Observation reads each non-layout node’s descriptive properties and children through `AXUIElementCopyMultipleAttributeValues`. Per-attribute errors retain the individual-read rules; unsupported batch APIs use individual reads. Values are retained only during that observation, and input reads live attributes. Application state can change between nodes; a batch does not make the whole tree atomic. @@ -125,7 +125,7 @@ Run `python3 packages/experimental/cua-macos/native/tests/shared_helper_e2e.py - 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. -Run `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py` in a GUI login session to verify that the helper owns its permission identity even when started through two nested GUI launchers. Concurrent connections report the same helper name and icon. The check owns its applications, cleans up LaunchServices registrations, and requests no Accessibility or Screen Recording access. +Run `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py` in a GUI login session to verify that the helper owns its permission identity even when started through two nested GUI launchers. Concurrent connections report the same helper name and icon. The check owns its applications, cleans up LaunchServices registrations, and requests no Accessibility or Screen Recording access. Run `python3 packages/experimental/cua-macos/native/tests/nested_application_e2e.py` to verify signature-preserving extraction outside an enclosing `.app`, concurrent publication, and service teardown with uniquely signed fixtures. Run `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py` after building and unlocking the Mac to verify an owned window whose application removes and later restores its AX roots. The check requires existing Accessibility/Screen Recording grants, rejects stale element indices, captures the AXless window, verifies a coordinate click in the fixture state file, and checks restoration. It never changes system permission settings. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index d7473d91b0..02b1c7aa29 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -23,7 +23,7 @@ kind: "package-reference" ## 构建与服务 -运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-` 下生成带签名的 `DSH Computer Use.app`,`current.json` 选择完整的内容摘要目录。默认使用临时签名;正式打包可传入 `--identity` 指定 Developer ID,并由发布流程完成公证。Host 运行应用内的 `--ensure-shared` 入口,经 LaunchServices 后台启动服务。最后一条连接完成清理后,服务退出。 +运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-` 下生成带签名的 `DSH Computer Use.app`,`current.json` 选择完整的内容摘要目录。默认使用临时签名;正式打包可传入 `--identity` 指定 Developer ID,并由发布流程完成公证。Host 运行应用内的 `--ensure-shared` 入口,经 LaunchServices 后台启动服务。最后一条连接完成清理后,服务退出。 helper 嵌套在另一个 `.app` 内时,启动器先把完整的已签名应用复制到 `~/Library/Application Support/DeepSeek Harness/Computer Use//`,再启动它。每个不可变目录都校验可执行文件哈希和应用签名,旧目录保留给仍在运行的安装版本使用,使两项 macOS 权限都归属于 helper。校验失败会中止启动;删除报错中指定的缓存目录后再重试。 `native/.build/prepared/` 和 `native/bin/darwin-` 中的各代应用不会自动清理。正式打包时使用全新的 `--output-directory`,或确认没有客户端使用后清理打包输出再构建,避免旧应用进入 tarball。安全签名时间戳可能让相同源码生成不同代应用。 @@ -93,7 +93,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `DSH Computer Use.app` 需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 -仅供 Host 使用的权限操作为 `permissionStatus {}`、`requestPermission {permission}` 和 `openPermissionSettings {permission}`,其中 permission 为 `accessibility` 或 `screenRecording`。这些操作不出现在模型工具及 `getCapabilities.methods` 中。权限状态包含观察到的 helper 和父进程路径,这些路径不能确定 TCC 归属的应用。系统授权提示负责指出应用并询问用户决定。helper 使用可选的 libSystem 内部接口 `responsibility_get_pid_responsible_for_pid` 查询责任进程,在报告就绪前记录对应应用的名称和图标。接口通过动态加载解析,函数签名与 [Chromium](https://chromium.googlesource.com/chromium/src/+/refs/tags/134.0.6998.28/base/process/process_info_mac.mm) 使用的一致。符号、进程或应用信息不可用时,归属保持未知,不根据最近的 GUI 祖先推断。权限检查独立于这些信息。 +仅供 Host 使用的权限操作为 `permissionStatus {}`、`requestPermission {permission}` 和 `openPermissionSettings {permission}`,其中 permission 为 `accessibility` 或 `screenRecording`。这些操作不出现在模型工具及 `getCapabilities.methods` 中。权限状态包含观察到的 helper 和父进程路径,这些路径不能确定 TCC 归属的应用。系统授权提示负责指出应用并询问用户决定。helper 使用可选的 libSystem 内部接口 `responsibility_get_pid_responsible_for_pid` 查询责任进程,在报告就绪前记录对应应用的名称和图标。接口通过动态加载解析,函数签名与 [Chromium](https://chromium.googlesource.com/chromium/src/+/refs/tags/134.0.6998.28/base/process/process_info_mac.mm) 使用的一致。符号、进程或应用信息不可用时,归属保持未知,不根据最近的 GUI 祖先推断。权限检查独立于这些信息。 用户申请权限后若仍未授权,同一操作会打开对应的系统设置页,包括 macOS 不再弹出提示的情况。 观察通过 `AXUIElementCopyMultipleAttributeValues` 读取每个非布局节点的描述属性和子节点。逐属性错误保留单独读取的规则;不支持批量 API 时使用单独读取。值只在本次观察期间保留,输入读取即时属性。应用状态可能在节点之间变化,批量读取不使整棵树具备原子性。 @@ -125,7 +125,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 在已解锁的 macOS GUI 会话中运行 `python3 packages/experimental/cua-macos/native/tests/application_consent_e2e.py --helper /absolute/helper`,需要可用的 Apple Swift 编译器。它创建并清理自己的 AppKit 应用和独立 GUI 进程,检查元数据替换、冷启动与直接启动、共用 Bundle ID、独立程序重启后的持久路径身份,以及删除运行中可执行文件后的选择行为。默认身份检查不需要辅助功能或屏幕录制权限。添加 `--desktop` 可读取完整测试应用的控件,通过状态文件验证 AX 按钮点击,截取窗口,并记录删除可执行文件后的观察结果;此模式要求已有两项系统权限。 -在 GUI 登录会话中运行 `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py`,验证两个嵌套 GUI 启动器启动 helper 后,授权归属仍为 helper 自己,多条连接得到相同名称和图标。检查自行创建应用并清理 LaunchServices 注册,不申请辅助功能或屏幕录制权限。 +在 GUI 登录会话中运行 `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py`,验证两个嵌套 GUI 启动器启动 helper 后,授权归属仍为 helper 自己,多条连接得到相同名称和图标。检查自行创建应用并清理 LaunchServices 注册,不申请辅助功能或屏幕录制权限。 运行 `python3 packages/experimental/cua-macos/native/tests/nested_application_e2e.py`,用独立签名的测试应用验证 helper 在外层 `.app` 之外保留签名发布、并发发布和服务退出。 构建并解锁 Mac 后运行 `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py`,验证应用移除并恢复 AX 根节点的窗口。检查需要已有辅助功能/屏幕录制权限,会拒绝过期元素索引,捕获无 AX 窗口,通过 fixture 状态文件核实坐标点击,并检查恢复。不会修改系统权限设置。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/Permissions.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/Permissions.swift index b4a9dcc587..c2a2c8771a 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/Permissions.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/Permissions.swift @@ -24,17 +24,23 @@ import Foundation func request(_ permission: String) throws -> JSONValue { switch permission { case "accessibility": - if !AXIsProcessTrusted() { + try Self.requestConsent(granted: AXIsProcessTrusted(), request: { let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary - _ = AXIsProcessTrustedWithOptions(options) - } + return AXIsProcessTrustedWithOptions(options) + }, openSettings: { _ = try openSettings(permission) }) case "screenRecording": - if !CGPreflightScreenCaptureAccess() { _ = CGRequestScreenCaptureAccess() } + try Self.requestConsent(granted: CGPreflightScreenCaptureAccess(), request: CGRequestScreenCaptureAccess, + openSettings: { _ = try openSettings(permission) }) default: throw RequestParameters.invalid("permission must be accessibility or screenRecording") } return status() } + // macOS may suppress a repeated consent prompt; the existing request action still reaches its settings pane. + static func requestConsent(granted: Bool, request: () -> Bool, openSettings: () throws -> Void) throws { + if !granted && !request() { try openSettings() } + } + func openSettings(_ permission: String) throws -> JSONValue { let pane: String switch permission { diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperRuntime.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperRuntime.swift index 42c1853870..c468d95032 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperRuntime.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperRuntime.swift @@ -296,6 +296,7 @@ final class SharedSocket: @unchecked Sendable { throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED", message: "Computer Use requires its signed application bundle; set helperPath to DSH Computer Use.app/Contents/MacOS/dsh-cua-native") } + let applicationURL = try StandaloneApplication.prepare(bundle.bundleURL, runtimeKey: options.runtimeKey, deadline: deadline) let configuration = NSWorkspace.OpenConfiguration() configuration.activates = false configuration.addsToRecentItems = false @@ -310,12 +311,12 @@ final class SharedSocket: @unchecked Sendable { guard DispatchTime.now().uptimeNanoseconds < deadline else { throw NativeFailure(code: "NATIVE_STARTUP_TIMEOUT", message: "Computer Use launch lock exhausted the startup deadline") } - // LaunchServices gives the application its own TCC identity; direct spawning inherits the terminal's. + // LaunchServices and a standalone bundle keep both permission services attributed to this helper. let application: NSRunningApplication - do { application = try await NSWorkspace.shared.openApplication(at: bundle.bundleURL, configuration: configuration) } + do { application = try await NSWorkspace.shared.openApplication(at: applicationURL, configuration: configuration) } catch { if let failure = try SharedHelperOptions.startupFailure(at: failurePath) { throw failure } - throw NativeFailure(code: "NATIVE_STARTUP", message: "macOS could not launch Computer Use at \(bundle.bundleURL.path): \(error.localizedDescription)") + throw NativeFailure(code: "NATIVE_STARTUP", message: "macOS could not launch Computer Use at \(applicationURL.path): \(error.localizedDescription)") } let pid = application.processIdentifier guard pid > 0 else { diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift new file mode 100644 index 0000000000..eee40085e9 --- /dev/null +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift @@ -0,0 +1,80 @@ +// Nested applications share their enclosing app's Screen Recording identity in TCC. +import CryptoKit +import Darwin +import Foundation +import Security + +enum StandaloneApplication { + static func hasApplicationAncestor(_ application: URL) -> Bool { + var parent = application.deletingLastPathComponent() + while parent.path != "/" { + if parent.pathExtension.lowercased() == "app" { return true } + parent.deleteLastPathComponent() + } + return false + } + + static func prepare(_ application: URL, runtimeKey: String, deadline: UInt64) throws -> URL { + let source = application.resolvingSymlinksInPath() + guard hasApplicationAncestor(source) else { return source } + let support = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, + appropriateFor: nil, create: true) + return try install(source, runtimeKey: runtimeKey, + root: support.appendingPathComponent("DeepSeek Harness/Computer Use"), deadline: deadline) + } + + // Published generations remain immutable while any installed DSH version may still run them. + static func install(_ source: URL, runtimeKey: String, root: URL, deadline: UInt64) throws -> URL { + let files = FileManager.default + try files.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + let root = root.resolvingSymlinksInPath() + let generation = root.appendingPathComponent(runtimeKey) + let application = generation.appendingPathComponent(source.lastPathComponent) + guard !hasApplicationAncestor(application) else { + throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED", message: "Computer Use application storage must be outside another .app: \(root.path)") + } + var lock: SharedHelperLock? + repeat { + lock = try SharedHelperLock(path: root.appendingPathComponent("\(runtimeKey).lock").path) + if lock != nil { break } + usleep(10_000) + } while DispatchTime.now().uptimeNanoseconds < deadline + guard let lock else { + throw NativeFailure(code: "NATIVE_STARTUP_TIMEOUT", message: "Computer Use application installation is still in progress") + } + defer { withExtendedLifetime(lock) {} } + if files.fileExists(atPath: generation.path) { + try validate(application, runtimeKey: runtimeKey) + return application + } + let staging = root.appendingPathComponent(".staging-\(UUID().uuidString)") + try files.createDirectory(at: staging, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + do { + let stagedApplication = staging.appendingPathComponent(source.lastPathComponent) + try files.copyItem(at: source, to: stagedApplication) + try validate(stagedApplication, runtimeKey: runtimeKey) + try files.moveItem(at: staging, to: generation) + } catch { + let failure = error + do { try files.removeItem(at: staging) } + catch { + throw NativeFailure(code: "NATIVE_IO", message: "Computer Use installation failed: \(failure.localizedDescription); could not remove \(staging.path): \(error.localizedDescription)") + } + throw failure + } + return application + } + + private static func validate(_ application: URL, runtimeKey: String) throws { + let executable = application.appendingPathComponent("Contents/MacOS/dsh-cua-native") + let bytes = try Data(contentsOf: executable, options: .mappedIfSafe) + let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() + var code: SecStaticCode? + let flags = SecCSFlags(rawValue: kSecCSStrictValidate | kSecCSCheckAllArchitectures | kSecCSCheckNestedCode) + guard digest == runtimeKey, + SecStaticCodeCreateWithPath(application as CFURL, [], &code) == errSecSuccess, + let code, SecStaticCodeCheckValidity(code, flags, nil) == errSecSuccess else { + throw NativeFailure(code: "NATIVE_APPLICATION_INVALID", message: "Computer Use application failed signature or executable verification at \(application.path); remove this cached generation and retry") + } + } +} diff --git a/packages/experimental/cua-macos/native/tests/nested_application_e2e.py b/packages/experimental/cua-macos/native/tests/nested_application_e2e.py new file mode 100644 index 0000000000..b8b3b3d994 --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/nested_application_e2e.py @@ -0,0 +1,79 @@ +"""Verify nested helper extraction and concurrent launchers without granting macOS permissions.""" +import argparse +import concurrent.futures +from contextlib import ExitStack +import hashlib +import json +import os +from pathlib import Path +import plistlib +import shutil +import signal +import subprocess +import tempfile +import uuid + +from native_test_support import copy_helper, default_binary, unregister_helper +from shared_helper_e2e import Connection, wait_released + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--helper', type=Path, default=None) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix='cua-nest-', dir='/tmp') as temporary, ExitStack() as cleanup: + root = Path(temporary) + parent = root / 'Desktop.app' / 'Contents' / 'Resources' + parent.mkdir(parents=True) + helper = copy_helper(args.helper or default_binary(), parent) + application = helper.parents[2] + manifest = application / 'Contents/Info.plist' + info = plistlib.loads(manifest.read_bytes()) + info['CFBundleIdentifier'] = 'dev.dsh.cua.nested-test.' + uuid.uuid4().hex + manifest.write_bytes(plistlib.dumps(info)) + subprocess.run(['codesign', '--force', '--sign', '-', '--timestamp=none', str(application)], + check=True, capture_output=True, timeout=30) + key = hashlib.sha256(helper.read_bytes()).hexdigest() + cache = Path.home() / 'Library/Application Support/DeepSeek Harness/Computer Use' + generation = cache / key + assert not generation.exists(), 'The unique signed fixture unexpectedly shares an existing generation' + cleanup.callback(lambda: (cache / (key + '.lock')).unlink(missing_ok=True)) + cleanup.callback(lambda: shutil.rmtree(generation) if generation.exists() else None) + copied_helper = generation / application.name / 'Contents/MacOS/dsh-cua-native' + cleanup.callback(unregister_helper, copied_helper) + runtime = [root / 'a', root / 'b'] + + def stop_owned(directory, pid): + try: + os.kill(pid, signal.SIGTERM) + except ProcessLookupError: + pass + wait_released(directory / (key + '.lock'), pid) + + def launch(directory): + result = subprocess.run([str(helper), '--ensure-shared', '--runtime-key', key, + '--runtime-directory', str(directory), '--startup-timeout-ms', '15000'], + check=True, capture_output=True, text=True, timeout=25) + ready = json.loads(result.stdout) + cleanup.callback(stop_owned, directory, ready['pid']) + client = Connection(directory / (key + '.sock'), key) + cleanup.callback(client.close) + return client + + # Separate launcher processes share the installation lock while retaining independent service sockets. + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as workers: + clients = list(workers.map(launch, runtime)) + for client in clients: + state = client.call('permissionStatus', {}) + assert Path(state['helper']['path']).resolve() == copied_helper.resolve(), state + assert Path(state['launchApplication']['path']).resolve() == copied_helper.parents[2].resolve(), state + assert not any(part.endswith('.app') for part in copied_helper.parents[3].parts), state + assert clients[0].ready['pid'] != clients[1].ready['pid'] + assert copied_helper.read_bytes() == helper.read_bytes() + subprocess.run(['codesign', '--verify', '--deep', '--strict', str(copied_helper.parents[2])], + check=True, capture_output=True, timeout=30) + print('PASS: concurrent launchers use the same signature-preserving standalone application and drain both helpers') + + +if __name__ == '__main__': + main() diff --git a/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift b/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift new file mode 100644 index 0000000000..7983c84284 --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift @@ -0,0 +1,140 @@ +// Real signed fixtures exercise cache publication, reuse, integrity and isolated permission ownership. +import CryptoKit +import Darwin +import Foundation +import Testing +@testable import CuaNative + +private struct ApplicationFixture { + let root: URL + let application: URL + let cache: URL + var executable: URL { application.appendingPathComponent("Contents/MacOS/dsh-cua-native") } + var resource: URL { application.appendingPathComponent("Contents/Resources/value.txt") } + var key: String { get throws { SHA256.hash(data: try Data(contentsOf: executable)).map { String(format: "%02x", $0) }.joined() } } + var deadline: UInt64 { DispatchTime.now().uptimeNanoseconds + 30_000_000_000 } + + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("cua-application-\(UUID().uuidString)") + application = root.appendingPathComponent("Desktop.app/Contents/Resources/DSH Computer Use.app") + cache = root.appendingPathComponent("support") + try FileManager.default.createDirectory(at: executable.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: resource.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.copyItem(at: URL(fileURLWithPath: "/usr/bin/true"), to: executable) + try Data("original resource".utf8).write(to: resource) + let plist = try PropertyListSerialization.data(fromPropertyList: [ + "CFBundleIdentifier": "dev.dsh.cua.cache-test.\(UUID().uuidString)", + "CFBundleExecutable": "dsh-cua-native", "CFBundleName": "DSH Computer Use", "CFBundlePackageType": "APPL", + ], format: .xml, options: 0) + try plist.write(to: application.appendingPathComponent("Contents/Info.plist")) + try sign() + } + + func sign() throws { + let process = Process(), finished = DispatchSemaphore(value: 0) + process.executableURL = URL(fileURLWithPath: "/usr/bin/codesign") + process.arguments = ["--force", "--sign", "-", "--timestamp=none", application.path] + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + process.terminationHandler = { _ in finished.signal() } + try process.run() + if finished.wait(timeout: .now() + 30) == .timedOut { + kill(process.processIdentifier, SIGKILL) + process.waitUntilExit() + throw NativeFailure(code: "FIXTURE_TIMEOUT", message: "Ad-hoc fixture signing did not exit") + } + #expect(process.terminationReason == .exit) + try #require(process.terminationStatus == 0) + } + + func close() { + do { try FileManager.default.removeItem(at: root) } + catch { Issue.record("Could not remove owned application fixture: \(error)") } + } +} + +@Test func onlyNestedApplicationsNeedAnIndependentInstallation() throws { + #expect(StandaloneApplication.hasApplicationAncestor(URL(fileURLWithPath: "/Applications/Desktop.app/Contents/Helper.app"))) + #expect(StandaloneApplication.hasApplicationAncestor(URL(fileURLWithPath: "/Applications/Desktop.APP/Helper.app"))) + let standalone = URL(fileURLWithPath: "/Users/example/Helper.app") + #expect(!StandaloneApplication.hasApplicationAncestor(standalone)) + #expect(try StandaloneApplication.prepare(standalone, runtimeKey: "unused", deadline: 0) == standalone) +} + +@Test func aSignedHelperIsPublishedOutsideItsEnclosingApplicationAndReused() throws { + let f = try ApplicationFixture(); defer { f.close() } + let key = try f.key + let installed = try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) + #expect(!StandaloneApplication.hasApplicationAncestor(installed)) + #expect(try Data(contentsOf: installed.appendingPathComponent("Contents/MacOS/dsh-cua-native")) == Data(contentsOf: f.executable)) + #expect(try Data(contentsOf: installed.appendingPathComponent("Contents/Resources/value.txt")) == Data(contentsOf: f.resource)) + #expect(try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) == installed) +} + +@Test func changingTheSignedApplicationRetainsTheEarlierGeneration() throws { + let f = try ApplicationFixture(); defer { f.close() } + let old = try StandaloneApplication.install(f.application, runtimeKey: f.key, root: f.cache, deadline: f.deadline) + try Data("new resource".utf8).write(to: f.resource) + try f.sign() + let new = try StandaloneApplication.install(f.application, runtimeKey: f.key, root: f.cache, deadline: f.deadline) + #expect(old != new) + #expect(try String(contentsOf: old.appendingPathComponent("Contents/Resources/value.txt"), encoding: .utf8) == "original resource") + #expect(try String(contentsOf: new.appendingPathComponent("Contents/Resources/value.txt"), encoding: .utf8) == "new resource") +} + +@Test(arguments: ["Contents/Resources/value.txt", "Contents/MacOS/dsh-cua-native"]) +func aChangedCachedApplicationIsRejected(file: String) throws { + let f = try ApplicationFixture(); defer { f.close() } + let key = try f.key + let installed = try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) + try Data("changed".utf8).write(to: installed.appendingPathComponent(file)) + #expect(throws: (any Error).self) { + try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) + } +} + +@Test func anInvalidSourceLeavesNoPartialPublishedApplication() throws { + let f = try ApplicationFixture(); defer { f.close() } + let key = try f.key + try Data("unsigned change".utf8).write(to: f.resource) + #expect(throws: (any Error).self) { + try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: f.cache.path) == ["\(key).lock"]) +} + +@Test func applicationStorageCannotItselfBeNestedInAnotherApplication() throws { + let f = try ApplicationFixture(); defer { f.close() } + #expect(throws: (any Error).self) { + try StandaloneApplication.install(f.application, runtimeKey: f.key, + root: f.root.appendingPathComponent("Other.app/cache"), deadline: f.deadline) + } +} + +@Test func aCompetingInstallerDoesNotUseAPartialGeneration() throws { + let f = try ApplicationFixture(); defer { f.close() } + let key = try f.key + try FileManager.default.createDirectory(at: f.cache, withIntermediateDirectories: true) + let lock = try #require(SharedHelperLock(path: f.cache.appendingPathComponent("\(key).lock").path)) + defer { withExtendedLifetime(lock) {} } + #expect(throws: (any Error).self) { + try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, + deadline: DispatchTime.now().uptimeNanoseconds) + } + #expect(!FileManager.default.fileExists(atPath: f.cache.appendingPathComponent(key).path)) +} + +@MainActor @Test func permissionRequestsReachSettingsWhenTheSystemDoesNotGrantAccess() throws { + var requests = 0, settings = 0 + try SystemPermissions.requestConsent(granted: false, request: { requests += 1; return false }, openSettings: { settings += 1 }) + #expect(requests == 1 && settings == 1) + try SystemPermissions.requestConsent(granted: true, request: { requests += 1; return false }, openSettings: { settings += 1 }) + #expect(requests == 1 && settings == 1) + try SystemPermissions.requestConsent(granted: false, request: { requests += 1; return true }, openSettings: { settings += 1 }) + #expect(requests == 2 && settings == 1) + #expect(throws: (any Error).self) { + try SystemPermissions.requestConsent(granted: false, request: { false }, openSettings: { + throw NativeFailure(code: "SETTINGS_UNAVAILABLE", message: "Settings unavailable") + }) + } +} From 1c9d95a77836f888f1fb29918b560feebeb6cb21 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 17:34:35 +0800 Subject: [PATCH 18/55] fix(cua): keep this change scoped to standalone helper identity --- .../cua-macos/native/README.i18n.yaml | 4 ++-- .../experimental/cua-macos/native/README.md | 2 +- .../experimental/cua-macos/native/README.zh.md | 2 +- .../native/Sources/CuaNative/Permissions.swift | 14 ++++---------- .../CuaNative/StandaloneApplication.swift | 10 ++++++++-- .../swift/StandaloneApplicationTests.swift | 17 +---------------- 6 files changed, 17 insertions(+), 32 deletions(-) diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 3f7591dd58..c5068ecfae 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: fc8043c425322cdd zh: cf1edb9a78fda301 /dsh-cua-native-helper/observation-and-input: - en: c7d6f3fec3470f3a - zh: 998b7478369d5517 + en: caeccd866da14a36 + zh: 6a82e3a16a03813e /dsh-cua-native-helper/verification: en: d7d27c97fff638cd zh: 7f52556496a304d2 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 1cc5243b9b..7ef1a645e0 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -93,7 +93,7 @@ Capture and pointer delivery read CG bounds before and after an exact-window AX `DSH Computer Use.app` needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. -Host-only permission controls are `permissionStatus {}`, `requestPermission {permission}`, and `openPermissionSettings {permission}`, where permission is `accessibility` or `screenRecording`. They are excluded from model tools and from `getCapabilities.methods`. Permission status includes observed helper/parent process paths; these paths do not identify the TCC responsible application. The operating-system prompt names the application and asks for the user’s decision. The helper identifies the responsible process with the optional libSystem SPI `responsibility_get_pid_responsible_for_pid`, then captures its application name and icon before publishing readiness. The function is resolved dynamically, following the same signature used by [Chromium](https://chromium.googlesource.com/chromium/src/+/refs/tags/134.0.6998.28/base/process/process_info_mac.mm). If the symbol, process, or application metadata is unavailable, attribution stays unknown; it is not inferred from the nearest GUI ancestor. Permission checks remain independent of this metadata. If a user-requested permission remains ungranted after the native request, the same action opens its System Settings pane, including when macOS suppresses another prompt. +Host-only permission controls are `permissionStatus {}`, `requestPermission {permission}`, and `openPermissionSettings {permission}`, where permission is `accessibility` or `screenRecording`. They are excluded from model tools and from `getCapabilities.methods`. Permission status includes observed helper/parent process paths; these paths do not identify the TCC responsible application. The operating-system prompt names the application and asks for the user’s decision. The helper identifies the responsible process with the optional libSystem SPI `responsibility_get_pid_responsible_for_pid`, then captures its application name and icon before publishing readiness. The function is resolved dynamically, following the same signature used by [Chromium](https://chromium.googlesource.com/chromium/src/+/refs/tags/134.0.6998.28/base/process/process_info_mac.mm). If the symbol, process, or application metadata is unavailable, attribution stays unknown; it is not inferred from the nearest GUI ancestor. Permission checks remain independent of this metadata. Observation reads each non-layout node’s descriptive properties and children through `AXUIElementCopyMultipleAttributeValues`. Per-attribute errors retain the individual-read rules; unsupported batch APIs use individual reads. Values are retained only during that observation, and input reads live attributes. Application state can change between nodes; a batch does not make the whole tree atomic. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 02b1c7aa29..158edda05d 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -93,7 +93,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `DSH Computer Use.app` 需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 -仅供 Host 使用的权限操作为 `permissionStatus {}`、`requestPermission {permission}` 和 `openPermissionSettings {permission}`,其中 permission 为 `accessibility` 或 `screenRecording`。这些操作不出现在模型工具及 `getCapabilities.methods` 中。权限状态包含观察到的 helper 和父进程路径,这些路径不能确定 TCC 归属的应用。系统授权提示负责指出应用并询问用户决定。helper 使用可选的 libSystem 内部接口 `responsibility_get_pid_responsible_for_pid` 查询责任进程,在报告就绪前记录对应应用的名称和图标。接口通过动态加载解析,函数签名与 [Chromium](https://chromium.googlesource.com/chromium/src/+/refs/tags/134.0.6998.28/base/process/process_info_mac.mm) 使用的一致。符号、进程或应用信息不可用时,归属保持未知,不根据最近的 GUI 祖先推断。权限检查独立于这些信息。 用户申请权限后若仍未授权,同一操作会打开对应的系统设置页,包括 macOS 不再弹出提示的情况。 +仅供 Host 使用的权限操作为 `permissionStatus {}`、`requestPermission {permission}` 和 `openPermissionSettings {permission}`,其中 permission 为 `accessibility` 或 `screenRecording`。这些操作不出现在模型工具及 `getCapabilities.methods` 中。权限状态包含观察到的 helper 和父进程路径,这些路径不能确定 TCC 归属的应用。系统授权提示负责指出应用并询问用户决定。helper 使用可选的 libSystem 内部接口 `responsibility_get_pid_responsible_for_pid` 查询责任进程,在报告就绪前记录对应应用的名称和图标。接口通过动态加载解析,函数签名与 [Chromium](https://chromium.googlesource.com/chromium/src/+/refs/tags/134.0.6998.28/base/process/process_info_mac.mm) 使用的一致。符号、进程或应用信息不可用时,归属保持未知,不根据最近的 GUI 祖先推断。权限检查独立于这些信息。 观察通过 `AXUIElementCopyMultipleAttributeValues` 读取每个非布局节点的描述属性和子节点。逐属性错误保留单独读取的规则;不支持批量 API 时使用单独读取。值只在本次观察期间保留,输入读取即时属性。应用状态可能在节点之间变化,批量读取不使整棵树具备原子性。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/Permissions.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/Permissions.swift index c2a2c8771a..b4a9dcc587 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/Permissions.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/Permissions.swift @@ -24,23 +24,17 @@ import Foundation func request(_ permission: String) throws -> JSONValue { switch permission { case "accessibility": - try Self.requestConsent(granted: AXIsProcessTrusted(), request: { + if !AXIsProcessTrusted() { let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary - return AXIsProcessTrustedWithOptions(options) - }, openSettings: { _ = try openSettings(permission) }) + _ = AXIsProcessTrustedWithOptions(options) + } case "screenRecording": - try Self.requestConsent(granted: CGPreflightScreenCaptureAccess(), request: CGRequestScreenCaptureAccess, - openSettings: { _ = try openSettings(permission) }) + if !CGPreflightScreenCaptureAccess() { _ = CGRequestScreenCaptureAccess() } default: throw RequestParameters.invalid("permission must be accessibility or screenRecording") } return status() } - // macOS may suppress a repeated consent prompt; the existing request action still reaches its settings pane. - static func requestConsent(granted: Bool, request: () -> Bool, openSettings: () throws -> Void) throws { - if !granted && !request() { try openSettings() } - } - func openSettings(_ permission: String) throws -> JSONValue { let pane: String switch permission { diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift index eee40085e9..ea0b357454 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift @@ -44,7 +44,10 @@ enum StandaloneApplication { } defer { withExtendedLifetime(lock) {} } if files.fileExists(atPath: generation.path) { - try validate(application, runtimeKey: runtimeKey) + do { try validate(application, runtimeKey: runtimeKey) } + catch { + throw NativeFailure(code: "NATIVE_APPLICATION_INVALID", message: "Computer Use cached application is invalid: \(error.localizedDescription); remove \(generation.path) and retry") + } return application } let staging = root.appendingPathComponent(".staging-\(UUID().uuidString)") @@ -66,6 +69,9 @@ enum StandaloneApplication { } private static func validate(_ application: URL, runtimeKey: String) throws { + guard !hasApplicationAncestor(application.resolvingSymlinksInPath()) else { + throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED", message: "Computer Use application resolves inside another .app: \(application.path)") + } let executable = application.appendingPathComponent("Contents/MacOS/dsh-cua-native") let bytes = try Data(contentsOf: executable, options: .mappedIfSafe) let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() @@ -74,7 +80,7 @@ enum StandaloneApplication { guard digest == runtimeKey, SecStaticCodeCreateWithPath(application as CFURL, [], &code) == errSecSuccess, let code, SecStaticCodeCheckValidity(code, flags, nil) == errSecSuccess else { - throw NativeFailure(code: "NATIVE_APPLICATION_INVALID", message: "Computer Use application failed signature or executable verification at \(application.path); remove this cached generation and retry") + throw NativeFailure(code: "NATIVE_APPLICATION_INVALID", message: "Computer Use application failed signature or executable verification at \(application.path)") } } } diff --git a/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift b/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift index 7983c84284..5db54bcd3c 100644 --- a/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift @@ -115,7 +115,7 @@ func aChangedCachedApplicationIsRejected(file: String) throws { let f = try ApplicationFixture(); defer { f.close() } let key = try f.key try FileManager.default.createDirectory(at: f.cache, withIntermediateDirectories: true) - let lock = try #require(SharedHelperLock(path: f.cache.appendingPathComponent("\(key).lock").path)) + let lock = try #require(try SharedHelperLock(path: f.cache.appendingPathComponent("\(key).lock").path)) defer { withExtendedLifetime(lock) {} } #expect(throws: (any Error).self) { try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, @@ -123,18 +123,3 @@ func aChangedCachedApplicationIsRejected(file: String) throws { } #expect(!FileManager.default.fileExists(atPath: f.cache.appendingPathComponent(key).path)) } - -@MainActor @Test func permissionRequestsReachSettingsWhenTheSystemDoesNotGrantAccess() throws { - var requests = 0, settings = 0 - try SystemPermissions.requestConsent(granted: false, request: { requests += 1; return false }, openSettings: { settings += 1 }) - #expect(requests == 1 && settings == 1) - try SystemPermissions.requestConsent(granted: true, request: { requests += 1; return false }, openSettings: { settings += 1 }) - #expect(requests == 1 && settings == 1) - try SystemPermissions.requestConsent(granted: false, request: { requests += 1; return true }, openSettings: { settings += 1 }) - #expect(requests == 2 && settings == 1) - #expect(throws: (any Error).self) { - try SystemPermissions.requestConsent(granted: false, request: { false }, openSettings: { - throw NativeFailure(code: "SETTINGS_UNAVAILABLE", message: "Settings unavailable") - }) - } -} From e87a535d57fc09e6a8a8749e6ba93d4ce04b61fa Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 17:37:31 +0800 Subject: [PATCH 19/55] fix(cua): keep standalone application URLs stable across reuse --- .../Sources/CuaNative/StandaloneApplication.swift | 8 ++++---- .../tests/swift/StandaloneApplicationTests.swift | 11 +++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift index ea0b357454..15bd509639 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift @@ -28,8 +28,8 @@ enum StandaloneApplication { let files = FileManager.default try files.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) let root = root.resolvingSymlinksInPath() - let generation = root.appendingPathComponent(runtimeKey) - let application = generation.appendingPathComponent(source.lastPathComponent) + let generation = root.appendingPathComponent(runtimeKey, isDirectory: true) + let application = generation.appendingPathComponent(source.lastPathComponent, isDirectory: true) guard !hasApplicationAncestor(application) else { throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED", message: "Computer Use application storage must be outside another .app: \(root.path)") } @@ -50,10 +50,10 @@ enum StandaloneApplication { } return application } - let staging = root.appendingPathComponent(".staging-\(UUID().uuidString)") + let staging = root.appendingPathComponent(".staging-\(UUID().uuidString)", isDirectory: true) try files.createDirectory(at: staging, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) do { - let stagedApplication = staging.appendingPathComponent(source.lastPathComponent) + let stagedApplication = staging.appendingPathComponent(source.lastPathComponent, isDirectory: true) try files.copyItem(at: source, to: stagedApplication) try validate(stagedApplication, runtimeKey: runtimeKey) try files.moveItem(at: staging, to: generation) diff --git a/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift b/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift index 5db54bcd3c..a73dda8516 100644 --- a/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift @@ -111,6 +111,17 @@ func aChangedCachedApplicationIsRejected(file: String) throws { } } +@Test func aCachedSymlinkCannotRedirectTheHelperIntoAnEnclosingApplication() throws { + let f = try ApplicationFixture(); defer { f.close() } + let key = try f.key + try FileManager.default.createDirectory(at: f.cache, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: f.cache.appendingPathComponent(key), + withDestinationURL: f.application.deletingLastPathComponent()) + #expect(throws: (any Error).self) { + try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) + } +} + @Test func aCompetingInstallerDoesNotUseAPartialGeneration() throws { let f = try ApplicationFixture(); defer { f.close() } let key = try f.key From 84b26858d39825a8f4e386c4d905825e7577c984 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 18:32:47 +0800 Subject: [PATCH 20/55] refactor(cua): keep source signing configuration in the macOS provider --- docs/config-catalog.md | 11 +++++++++-- docs/config-catalog.zh.md | 11 +++++++++-- .../experimental/cua-macos/README.i18n.yaml | 4 ++-- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- packages/experimental/cua-macos/package.json | 1 + packages/experimental/cua-macos/src/index.ts | 19 ++++++++++++++++--- .../cua-macos/src/native-build.ts | 4 ++-- packages/experimental/cua-macos/tsconfig.json | 3 +++ packages/experimental/cua/README.i18n.yaml | 4 ++-- packages/experimental/cua/README.md | 2 -- packages/experimental/cua/README.zh.md | 2 -- packages/experimental/cua/src/index.ts | 7 ------- pnpm-lock.yaml | 3 +++ 14 files changed, 49 insertions(+), 26 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 22a80e5041..d39644b538 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1113,11 +1113,18 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:16`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:17`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ -export type Config = CuaConfig +export interface Config extends CuaConfig { + /** + * 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' +} ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 5619c331bb..4ed5e2241c 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1115,11 +1115,18 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:16`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:17`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ -export type Config = CuaConfig +export interface Config extends CuaConfig { + /** + * 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' +} ``` diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index e65da96194..9ec10f9015 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 6390cd271bbb64fe zh: 342f4f6aa617809f /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: c94d759b5b80b8a5 - zh: cb8178d8f76f8770 + en: e405b2ed1f6f82b3 + zh: 42b2d73810f95e80 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: 786b8fd630b11e5f zh: 55143f15486afce8 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 9f93eaaa69..d029c7c91b 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -39,7 +39,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. 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. The helper needs Accessibility permission for AX/input and Screen Recording permission for capture; grant these permissions to the helper when prompted. Source builds use the bundle filename `DSH Computer Use Dev.app` and declare `DSH Computer Use Dev` in Info.plist; select the development entry 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`: +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`. This entry loads `@deepseek-ai/dsh-experimental-cua-macos`; `cua` is its profile ID: ```yaml - id: cua diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index f5ced6c088..7033d88671 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -39,7 +39,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. 配置输出命令不发起模型请求。执行真实任务时,将 `--dump-config` 替换为任务提示,并配置该 profile 的模型凭据。配置挂载 computer-use 注册表和本 provider;使用前需移除已有的竞争 provider。helper 需要辅助功能权限来读取 AX 和输入,需要屏幕录制权限来截图;按系统提示给 helper 授权。源码构建的应用包名为 `DSH Computer Use Dev.app`,Info.plist 声明名称 `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` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。 -源码构建默认使用临时签名,即使本机已有开发证书也不会读取或修改钥匙串。需要在重新编译或切换 worktree 后保留签名身份时,在 profile 的 `cordis.patch.yml` 中为已加载的 `cua` 节点配置: +源码构建默认使用临时签名,即使本机已有开发证书也不会读取或修改钥匙串。需要在重新编译或切换 worktree 后保留签名身份时,在 profile 的 `cordis.patch.yml` 中为已加载的 `cua` 节点配置;该节点加载 `@deepseek-ai/dsh-experimental-cua-macos`,`cua` 是节点 ID: ```yaml - id: cua diff --git a/packages/experimental/cua-macos/package.json b/packages/experimental/cua-macos/package.json index e52d26722a..7178a1a138 100644 --- a/packages/experimental/cua-macos/package.json +++ b/packages/experimental/cua-macos/package.json @@ -54,6 +54,7 @@ "@deepseek-ai/dsh-user-questions": "workspace:*" }, "dependencies": { + "@deepseek-ai/schemastery": "workspace:~", "zod": "^4.4.3", "@deepseek-ai/dsh-atomic-write": "workspace:*", "@deepseek-ai/dsh-cua": "workspace:*" diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index cfbcae615f..4722e5803c 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -2,6 +2,7 @@ import { isAbsolute, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import type { Context } from '@deepseek-ai/cordis' +import Schema from '@deepseek-ai/schemastery' import { CuaConfig, installCua } from '@deepseek-ai/dsh-cua' import { nativeHostArchitecture, prepareNativeExecutable } from './native-build.ts' import { createSharedNativeChannel } from './shared-native.ts' @@ -13,9 +14,21 @@ 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, 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 +export interface Config extends CuaConfig { + /** + * 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' +} +/** Validate shared operation bounds and macOS source signing before preparing the helper. */ +export const Config = Schema.intersect([ + CuaConfig, + Schema.object({ + sourceSigning: Schema.union([Schema.const('ad-hoc'), Schema.const('local-identity')]).default('ad-hoc'), + }), +]) satisfies Schema, Config> const description = 'Inspect macOS permissions, select an application and window, read AX state, capture screenshots or dispatch input. Use appHandle from getApp; verify actions by reading fresh state.' diff --git a/packages/experimental/cua-macos/src/native-build.ts b/packages/experimental/cua-macos/src/native-build.ts index 24a6932ee7..7b303ce8e0 100644 --- a/packages/experimental/cua-macos/src/native-build.ts +++ b/packages/experimental/cua-macos/src/native-build.ts @@ -3,9 +3,9 @@ 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' +import type { Config } from './index.ts' const NativeApplication = z.object({ bundle: z.string().regex(/^[a-f0-9]{64}$/) }).strict() @@ -29,7 +29,7 @@ export interface NativeBuildSpec { packageRoot: string architecture: NativeArchitecture /** Signature of a source-checkout build; installed packages ignore it. */ - sourceSigning: CuaConfig['sourceSigning'] + sourceSigning: Config['sourceSigning'] subprocess: Pick signal: AbortSignal timeoutMs: number diff --git a/packages/experimental/cua-macos/tsconfig.json b/packages/experimental/cua-macos/tsconfig.json index 986873b01b..3d23cff1bf 100644 --- a/packages/experimental/cua-macos/tsconfig.json +++ b/packages/experimental/cua-macos/tsconfig.json @@ -8,6 +8,9 @@ "src" ], "references": [ + { + "path": "../../../vendor/schemastery" + }, { "path": "../../../vendor/cordis" }, diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 0ef85a1bc4..cc1d8c7a73 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: deb4ec91b186399e zh: 7febe3b08dbb185e /deepseek-ai-dsh-cua/understand-the-implementation: - en: a8caacb0d3347ce0 - zh: b1a392d54599fe95 + en: 951d9a3b925de34a + zh: f3444e127953a63f /deepseek-ai-dsh-cua/further-exploration: en: 166e3c1f9a67f753 zh: 698c5136c5350052 diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index 3c64f08c09..ea4b8e2b24 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -80,8 +80,6 @@ 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. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index e5802c472d..043817a53f 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -80,8 +80,6 @@ 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 重载规则。权限检查和执行方式状态独立返回。设置仍在加载、只读或不可用时不能提交;写入失败时在设置旁显示错误,供用户重试。 diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index a770f3b6b3..e9fee3a268 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -41,12 +41,6 @@ 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. */ @@ -91,7 +85,6 @@ 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), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5354f26ac5..7f362b99c7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9861,6 +9861,9 @@ importers: '@deepseek-ai/dsh-cua': specifier: workspace:* version: link:../cua + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery zod: specifier: ^4.4.3 version: 4.4.3 From c9d2c5f9082b0c20c1d7dc947bf680460bdd03cc Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 19:23:03 +0800 Subject: [PATCH 21/55] fix(cua): preserve object schema fields when extending macOS configuration --- packages/experimental/cua-macos/src/index.ts | 11 +++--- .../tests/provider-lifecycle.spec.ts | 16 ++++++++ scripts/gen-config-catalog.spec.ts | 39 +++++++++++++++++++ scripts/gen-config-catalog.ts | 18 ++++++++- 4 files changed, 77 insertions(+), 7 deletions(-) diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index 4722e5803c..841412eb3c 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -23,12 +23,11 @@ export interface Config extends CuaConfig { sourceSigning: 'ad-hoc' | 'local-identity' } /** Validate shared operation bounds and macOS source signing before preparing the helper. */ -export const Config = Schema.intersect([ - CuaConfig, - Schema.object({ - sourceSigning: Schema.union([Schema.const('ad-hoc'), Schema.const('local-identity')]).default('ad-hoc'), - }), -]) satisfies Schema, Config> +export const Config = Schema.object({ + // Schemastery erases object field types on dict; the shared Config declares their output types. + ...CuaConfig.dict as { [Key in keyof CuaConfig]: Schema }, + sourceSigning: Schema.union([Schema.const('ad-hoc'), Schema.const('local-identity')]).default('ad-hoc'), +}) satisfies Schema, Config> const description = 'Inspect macOS permissions, select an application and window, read AX state, capture screenshots or dispatch input. Use appHandle from getApp; verify actions by reading fresh state.' diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index ac132d8bbb..b637ad2b10 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -17,6 +17,8 @@ import * as StorageDomain from '@deepseek-ai/dsh-storage-domain' import Hmr from '@deepseek-ai/dsh-hmr' import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' import ComputerUseRegistry from '@deepseek-ai/dsh-computer-use' +import { CuaConfig } from '@deepseek-ai/dsh-cua' +import { createConfigProjector } from '@deepseek-ai/dsh-app-boot/src/config-schema/projector.ts' import LocalAttachmentStore from '@deepseek-ai/dsh-attachment-local' import FileSystem from '@deepseek-ai/dsh-fs-local' import UserQuestions from '@deepseek-ai/dsh-user-questions' @@ -72,6 +74,20 @@ it('defaults source builds to ad-hoc signatures and accepts only the two signing expect(() => NativeProvider.Config({ sourceSigning: 'developer-id' } as never)).toThrow() }) +it('projects shared controls and macOS signing without adding signing to the shared schema', async () => { + const project = await createConfigProjector() + const projected = project(NativeProvider.Config, 'cua-macos') + expect(projected.schema).toMatchObject({ anyOf: [ + { properties: { sourceSigning: expect.any(Object), agentPreset: expect.any(Object), helperPath: expect.any(Object) } }, + expect.any(Object), + ] }) + expect(CuaConfig({})).not.toHaveProperty('sourceSigning') + expect(CuaConfig.dict).not.toHaveProperty('sourceSigning') + expect(NativeProvider.Config({ sourceSigning: 'local-identity', timeoutMs: 1234 })).toMatchObject({ + agentPreset: 'ptc', sourceSigning: 'local-identity', timeoutMs: 1234, + }) +}) + 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) diff --git a/scripts/gen-config-catalog.spec.ts b/scripts/gen-config-catalog.spec.ts index 4aed5f9782..f7f4ac2377 100644 --- a/scripts/gen-config-catalog.spec.ts +++ b/scripts/gen-config-catalog.spec.ts @@ -86,6 +86,45 @@ export function apply(ctx: unknown, config: Config): void {} .toEqual(new Set(['mode', 'headless', 'endpoint'])) }) + it.each([false, true])('checks fields spread from an imported object schema (undeclared field: %s)', (invalid) => { + const { root, write } = fixture(` +import Schema from '@deepseek-ai/schemastery' +export interface SharedOptions { limit: number } +export const Shared = Schema.object({ limit: Schema.number(), ${invalid ? 'hidden: Schema.string(),' : ''} }) +`) + write('packages/test/provider/src/index.ts', ` +import Schema from '@deepseek-ai/schemastery' +import { Shared as SharedConfig, type SharedOptions } from '@test/runtime/config' +export interface Config extends SharedOptions { sourceSigning: string } +export const Config = Schema.object({ ...SharedConfig.dict, sourceSigning: Schema.string() }) +export function apply(ctx: unknown, config: Config): void {} +`) + if (invalid) expect(() => collectConfigCatalog(root)).toThrow("schema validates key 'hidden'") + else expect(new Set(collectConfigCatalog(root).find(entry => entry.pkg === '@test/provider')?.schemaKeys)) + .toEqual(new Set(['limit', 'sourceSigning'])) + }) + + it.each(['SharedConfig.dict', 'unknownFields'])('rejects a spread without an object schema: %s', (spread) => { + const { root, write } = fixture() + write('packages/test/provider/src/index.ts', ` +import Schema from '@deepseek-ai/schemastery' +import { Shared as SharedConfig, type BrowserConfig } from '@test/runtime/config' +export type Config = BrowserConfig +export const Config = Schema.object({ ...${spread} }) +export function apply(ctx: unknown, config: Config): void {} +`) + expect(() => collectConfigCatalog(root)).toThrow('object schema') + }) + + it('rejects a recursive object-schema dict spread', () => { + const { root } = fixture(` +import Schema from '@deepseek-ai/schemastery' +export interface BrowserConfig { mode: string } +export const Shared = Schema.object({ ...Shared.dict, mode: Schema.string() }) +`) + expect(() => collectConfigCatalog(root)).toThrow('cyclic schema alias') + }) + it('rejects a schema field absent from the shared config type', () => { const { root } = fixture(sharedSchema.replace('headless: Schema.boolean()', 'headless: Schema.boolean(), hidden: Schema.string()')) expect(() => collectConfigCatalog(root)).toThrow("schema validates key 'hidden' but config type 'Config' declares no such member") diff --git a/scripts/gen-config-catalog.ts b/scripts/gen-config-catalog.ts index 60a31c9fdb..610d3063a9 100644 --- a/scripts/gen-config-catalog.ts +++ b/scripts/gen-config-catalog.ts @@ -504,7 +504,7 @@ function unwrapExpr(expr: ts.Expression): ts.Expression { * packages whose schemas an intersect composes. A key path is the top-level * key or a nested path through object/array compositions (`agents[].id`). * Handles object/union calls, chained refinements, named const schema imports - * through public workspace source paths, and `z.intersect([X.Config, …])`; errors on + * through public workspace source paths, object-schema dict spreads, and `z.intersect([X.Config, …])`; errors on * anything else, so a schema the walk cannot see fails the gate instead of * silently thinning it. Nested values that are neither `object` nor `array` * compositions (primitives, unions, dynamic-key dicts) contribute no paths. @@ -570,6 +570,22 @@ function walkSchemaExpr( const key = ts.isStringLiteral(prop.name) ? prop.name.text : prop.name.getText(ctx.sf) keys.push(key) if (ts.isPropertyAssignment(prop)) collectValuePaths(prop.initializer, key) + } else if (ts.isSpreadAssignment(prop)) { + const spread = unwrapExpr(prop.expression) + if (!ts.isPropertyAccessExpression(spread) || spread.name.text !== 'dict' || !ts.isIdentifier(spread.expression)) { + violations.push(`${where}: schema spread '${prop.getText(ctx.sf)}' must name a const object schema's dict.`) + continue + } + try { + const target = schemaAlias(world, ctx, spread.expression.text) + const object = unwrapExpr(target.expr) + if (!ts.isCallExpression(object) || !ts.isPropertyAccessExpression(object.expression) || object.expression.name.text !== 'object') { + throw new Error(`schema spread '${spread.getText(ctx.sf)}' must refer directly to an object schema`) + } + visit(spread.expression) + } catch (error) { + violations.push(`${where}: ${error instanceof Error ? error.message : String(error)}.`) + } } else { violations.push(`${where}: schema object property '${prop.getText(ctx.sf)}' is not a plain key.`) } From 159c91868015334d31a0e2a990c5c8f987ee7144 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 19:25:27 +0800 Subject: [PATCH 22/55] test(config): document fields in object schema spread fixtures --- scripts/gen-config-catalog.spec.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/scripts/gen-config-catalog.spec.ts b/scripts/gen-config-catalog.spec.ts index f7f4ac2377..90a1144d14 100644 --- a/scripts/gen-config-catalog.spec.ts +++ b/scripts/gen-config-catalog.spec.ts @@ -89,13 +89,19 @@ export function apply(ctx: unknown, config: Config): void {} it.each([false, true])('checks fields spread from an imported object schema (undeclared field: %s)', (invalid) => { const { root, write } = fixture(` import Schema from '@deepseek-ai/schemastery' -export interface SharedOptions { limit: number } +export interface SharedOptions { + /** Maximum result count. */ + limit: number +} export const Shared = Schema.object({ limit: Schema.number(), ${invalid ? 'hidden: Schema.string(),' : ''} }) `) write('packages/test/provider/src/index.ts', ` import Schema from '@deepseek-ai/schemastery' import { Shared as SharedConfig, type SharedOptions } from '@test/runtime/config' -export interface Config extends SharedOptions { sourceSigning: string } +export interface Config extends SharedOptions { + /** Signature selected for a source build. */ + sourceSigning: string +} export const Config = Schema.object({ ...SharedConfig.dict, sourceSigning: Schema.string() }) export function apply(ctx: unknown, config: Config): void {} `) From 887356ba1ad582fba41029fdb7ab06d2b8eb12e6 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 19:26:28 +0800 Subject: [PATCH 23/55] test(cua): inspect projected configuration fields without unsafe matchers --- .../cua-macos/tests/provider-lifecycle.spec.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index b637ad2b10..ff296b5186 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -77,10 +77,9 @@ it('defaults source builds to ad-hoc signatures and accepts only the two signing it('projects shared controls and macOS signing without adding signing to the shared schema', async () => { const project = await createConfigProjector() const projected = project(NativeProvider.Config, 'cua-macos') - expect(projected.schema).toMatchObject({ anyOf: [ - { properties: { sourceSigning: expect.any(Object), agentPreset: expect.any(Object), helperPath: expect.any(Object) } }, - expect.any(Object), - ] }) + for (const field of ['sourceSigning', 'agentPreset', 'helperPath']) { + expect(projected.schema.anyOf?.[0]).toHaveProperty(`properties.${field}`) + } expect(CuaConfig({})).not.toHaveProperty('sourceSigning') expect(CuaConfig.dict).not.toHaveProperty('sourceSigning') expect(NativeProvider.Config({ sourceSigning: 'local-identity', timeoutMs: 1234 })).toMatchObject({ From 2e4fddec5d7aa61addfeb2bb261f82fe0e606b69 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 29 Oct 2026 19:41:19 +0800 Subject: [PATCH 24/55] fix(cua): preserve recorded signing identities when the keychain is missing --- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 2 +- .../cua-macos/native/dev_signing.py | 13 +++--- .../native/tests/test_dev_signing.py | 42 +++++++++++++++++++ 5 files changed, 53 insertions(+), 10 deletions(-) diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index a58b538ab7..58edd3f789 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -15,8 +15,8 @@ en: e8cbc43d38786c40 zh: 52b3ba85d98011b9 /dsh-cua-native-helper/build-and-service: - en: 2bc0fe6a9b96897c - zh: c43c5ab96eb3ec4b + en: 98b752544721cd1b + zh: 0148b4b08310246b /dsh-cua-native-helper/request-protocol: en: fc8043c425322cdd zh: cf1edb9a78fda301 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index bd6f6b48c3..ca1743475a 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -29,7 +29,7 @@ Source checkouts build with `--variant dev`: the application declares bundle ide 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. +`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. When an identity record exists but its keychain or certificate is missing, the build preserves the record and fails. Invalid records also fail. Recovery requires explicit removal and setup; 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. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index fc7de78795..bacb528a94 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" 在 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`,沿用原有签名行为。 +`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/` 中记录每个未签名应用与证书指纹对应的目录,内容不变时复用该目录。临时签名使用独立记录。显式传入证书名称时会重新签名,因为续期可能改变名称对应的证书。 diff --git a/packages/experimental/cua-macos/native/dev_signing.py b/packages/experimental/cua-macos/native/dev_signing.py index 438c7b54b1..668a2b5372 100644 --- a/packages/experimental/cua-macos/native/dev_signing.py +++ b/packages/experimental/cua-macos/native/dev_signing.py @@ -112,7 +112,7 @@ def load(directory=DEFAULT_DIRECTORY): 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}") + 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. @@ -154,17 +154,18 @@ def create_certificate(directory, password): def setup(directory=DEFAULT_DIRECTORY): - """Create the identity once and keep its keychain on the user search list.""" + """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): 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)) + 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) remove_locked(directory) directory.mkdir(mode=0o700, parents=True) diff --git a/packages/experimental/cua-macos/native/tests/test_dev_signing.py b/packages/experimental/cua-macos/native/tests/test_dev_signing.py index 510e5ce005..bc554e2b6a 100644 --- a/packages/experimental/cua-macos/native/tests/test_dev_signing.py +++ b/packages/experimental/cua-macos/native/tests/test_dev_signing.py @@ -100,6 +100,48 @@ class DevelopmentSigningTests(unittest.TestCase): 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, then .*setup"): + 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_build_cli_stops_without_replacing_a_recorded_identity_missing_its_keychain(self): + home = self.root / "home" + directory = home / "Library/Application Support/DeepSeek Harness/computer-use-dev-signing" + directory.mkdir(parents=True) + record = directory / "identity.json" + before = json.dumps({"sha1": "ABC123", "password": "secret-password"}).encode() + record.write_bytes(before) + output = self.root / "applications" + script = """import runpy, sys +from pathlib import Path +from unittest.mock import patch +test_home = Path(sys.argv[2]) +Path.home = lambda: test_home +sys.argv = [sys.argv[1], '--variant', 'dev', '--signing', 'local-identity', '--output-directory', sys.argv[3]] +with patch('subprocess.run', side_effect=AssertionError('unexpected native build or signing command')): + runpy.run_path(sys.argv[0], run_name='__main__') +""" + result = subprocess.run([sys.executable, "-c", script, str(Path(signing.__file__).with_name("build_app.py")), str(home), str(output)], + 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}, then {signing.SETUP_COMMAND}", 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()) + self.assertFalse(output.exists()) + def test_remove_restores_the_other_search_list_entries_and_deletes_the_password(self): security = self.configure() signing.remove(self.directory) From 4d4a7e58590aa6763caed4c47d2d9ff46e953ebf Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 30 Oct 2026 10:47:29 +0800 Subject: [PATCH 25/55] fix(cua): remove the standalone helper copy --- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../cua-macos/native/README.i18n.yaml | 8 +- .../experimental/cua-macos/native/README.md | 4 +- .../cua-macos/native/README.zh.md | 4 +- .../CuaNative/SharedHelperRuntime.swift | 7 +- .../CuaNative/StandaloneApplication.swift | 86 ----------- .../native/tests/nested_application_e2e.py | 79 ---------- .../swift/StandaloneApplicationTests.swift | 136 ------------------ 10 files changed, 15 insertions(+), 317 deletions(-) delete mode 100644 packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift delete mode 100644 packages/experimental/cua-macos/native/tests/nested_application_e2e.py delete mode 100644 packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index cab5247eff..e8b7a196c7 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -12,8 +12,8 @@ en: 4549f02fc53854a5 zh: 6f74f1130b6623a8 /deepseek-ai-dsh-experimental-cua-macos/table-of-contents: - en: d473fa94a4488852 - zh: 43f0265a97820f64 + en: 395f2a62b2ce6b4a + zh: 67912bb946c78837 /deepseek-ai-dsh-experimental-cua-macos/use-this-package: en: d7e50cc9e3ad4137 zh: a65cfb7e4688d159 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index d84fdb7732..79d19e7747 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -22,7 +22,7 @@ Inspect macOS permissions, select running applications and windows, read accessi The helper supplies bounded 64-pixel PNG application icons for permission prompts and saved-application lists. Icon reads do not launch an application or inspect its windows; icons do not determine reusable consent. -The helper runs through LaunchServices as the independent background application `DSH Computer Use.app`. Accessibility and Screen Recording permissions belong to this application. The permission page uses its system-reported name and icon; when attribution is unavailable, the system prompt identifies the application. When the helper is nested inside another `.app`, its launcher copies the complete signed bundle to `~/Library/Application Support/DeepSeek Harness/Computer Use//` before starting it. Each immutable generation is verified against the executable hash and application signature; earlier generations remain available for running installations. This keeps both macOS permission services attributed to the helper. A failed verification stops startup; remove the named cached generation before retrying. +The helper runs through LaunchServices as the independent background application `DSH Computer Use.app`. Accessibility and Screen Recording permissions belong to this application. The permission page uses its system-reported name and icon; when attribution is unavailable, the system prompt identifies the application. ----- diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 8ab08e0433..dc4fb75832 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -22,7 +22,7 @@ kind: "package-reference" helper 为授权提示和已授权应用列表提供 64 像素 PNG 图标。读取图标不会启动应用或检查窗口,图标不决定可复用授权。 -helper 通过 LaunchServices 以独立的 `DSH Computer Use.app` 后台运行,辅助功能和屏幕录制权限归属于这个应用。权限页使用系统返回的应用名称和图标;无法查询归属时,以系统授权提示为准。 helper 嵌套在另一个 `.app` 内时,启动器先把完整的已签名应用复制到 `~/Library/Application Support/DeepSeek Harness/Computer Use//`,再启动它。每个不可变目录都校验可执行文件哈希和应用签名,旧目录保留给仍在运行的安装版本使用,使两项 macOS 权限都归属于 helper。校验失败会中止启动;删除报错中指定的缓存目录后再重试。 +helper 通过 LaunchServices 以独立的 `DSH Computer Use.app` 后台运行,辅助功能和屏幕录制权限归属于这个应用。权限页使用系统返回的应用名称和图标;无法查询归属时,以系统授权提示为准。 ----- diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index c5068ecfae..83bbf0b697 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -15,8 +15,8 @@ en: e8cbc43d38786c40 zh: 52b3ba85d98011b9 /dsh-cua-native-helper/build-and-service: - en: ab8fe195c70dd31c - zh: b05bc116dc173c9c + en: 7619d37566e773ef + zh: c8f6e37f19ad9763 /dsh-cua-native-helper/request-protocol: en: fc8043c425322cdd zh: cf1edb9a78fda301 @@ -24,8 +24,8 @@ en: caeccd866da14a36 zh: 6a82e3a16a03813e /dsh-cua-native-helper/verification: - en: d7d27c97fff638cd - zh: 7f52556496a304d2 + en: 706d3434799530b3 + zh: e327c5fc7330c2b9 /dsh-cua-native-helper/further-exploration: en: 265e1927952ce6d7 zh: 7c35d9fd98b6e6c8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 7ef1a645e0..ae932f0a97 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -23,7 +23,7 @@ This macOS 14+ JSON-lines helper uses Swift 6, AppKit, Accessibility, CoreGraphi ## Build and service -Run `pnpm --dir packages/experimental/cua-macos run build:native` to publish a signed `DSH Computer Use.app` under `native/bin/darwin-`. 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. When the helper is nested inside another `.app`, its launcher copies the complete signed bundle to `~/Library/Application Support/DeepSeek Harness/Computer Use//` before starting it. Each immutable generation is verified against the executable hash and application signature; earlier generations remain available for running installations. This keeps both macOS permission services attributed to the helper. A failed verification stops startup; remove the named cached generation before retrying. +Run `pnpm --dir packages/experimental/cua-macos run build:native` to publish a signed `DSH Computer Use.app` under `native/bin/darwin-`. 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. Generations in `native/.build/prepared/` and `native/bin/darwin-` 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. @@ -125,7 +125,7 @@ Run `python3 packages/experimental/cua-macos/native/tests/shared_helper_e2e.py - 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. -Run `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py` in a GUI login session to verify that the helper owns its permission identity even when started through two nested GUI launchers. Concurrent connections report the same helper name and icon. The check owns its applications, cleans up LaunchServices registrations, and requests no Accessibility or Screen Recording access. Run `python3 packages/experimental/cua-macos/native/tests/nested_application_e2e.py` to verify signature-preserving extraction outside an enclosing `.app`, concurrent publication, and service teardown with uniquely signed fixtures. +Run `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py` in a GUI login session to verify that the helper owns its permission identity even when started through two nested GUI launchers. Concurrent connections report the same helper name and icon. The check owns its applications, cleans up LaunchServices registrations, and requests no Accessibility or Screen Recording access. Run `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py` after building and unlocking the Mac to verify an owned window whose application removes and later restores its AX roots. The check requires existing Accessibility/Screen Recording grants, rejects stale element indices, captures the AXless window, verifies a coordinate click in the fixture state file, and checks restoration. It never changes system permission settings. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 158edda05d..d7473d91b0 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -23,7 +23,7 @@ kind: "package-reference" ## 构建与服务 -运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-` 下生成带签名的 `DSH Computer Use.app`,`current.json` 选择完整的内容摘要目录。默认使用临时签名;正式打包可传入 `--identity` 指定 Developer ID,并由发布流程完成公证。Host 运行应用内的 `--ensure-shared` 入口,经 LaunchServices 后台启动服务。最后一条连接完成清理后,服务退出。 helper 嵌套在另一个 `.app` 内时,启动器先把完整的已签名应用复制到 `~/Library/Application Support/DeepSeek Harness/Computer Use//`,再启动它。每个不可变目录都校验可执行文件哈希和应用签名,旧目录保留给仍在运行的安装版本使用,使两项 macOS 权限都归属于 helper。校验失败会中止启动;删除报错中指定的缓存目录后再重试。 +运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-` 下生成带签名的 `DSH Computer Use.app`,`current.json` 选择完整的内容摘要目录。默认使用临时签名;正式打包可传入 `--identity` 指定 Developer ID,并由发布流程完成公证。Host 运行应用内的 `--ensure-shared` 入口,经 LaunchServices 后台启动服务。最后一条连接完成清理后,服务退出。 `native/.build/prepared/` 和 `native/bin/darwin-` 中的各代应用不会自动清理。正式打包时使用全新的 `--output-directory`,或确认没有客户端使用后清理打包输出再构建,避免旧应用进入 tarball。安全签名时间戳可能让相同源码生成不同代应用。 @@ -125,7 +125,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 在已解锁的 macOS GUI 会话中运行 `python3 packages/experimental/cua-macos/native/tests/application_consent_e2e.py --helper /absolute/helper`,需要可用的 Apple Swift 编译器。它创建并清理自己的 AppKit 应用和独立 GUI 进程,检查元数据替换、冷启动与直接启动、共用 Bundle ID、独立程序重启后的持久路径身份,以及删除运行中可执行文件后的选择行为。默认身份检查不需要辅助功能或屏幕录制权限。添加 `--desktop` 可读取完整测试应用的控件,通过状态文件验证 AX 按钮点击,截取窗口,并记录删除可执行文件后的观察结果;此模式要求已有两项系统权限。 -在 GUI 登录会话中运行 `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py`,验证两个嵌套 GUI 启动器启动 helper 后,授权归属仍为 helper 自己,多条连接得到相同名称和图标。检查自行创建应用并清理 LaunchServices 注册,不申请辅助功能或屏幕录制权限。 运行 `python3 packages/experimental/cua-macos/native/tests/nested_application_e2e.py`,用独立签名的测试应用验证 helper 在外层 `.app` 之外保留签名发布、并发发布和服务退出。 +在 GUI 登录会话中运行 `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py`,验证两个嵌套 GUI 启动器启动 helper 后,授权归属仍为 helper 自己,多条连接得到相同名称和图标。检查自行创建应用并清理 LaunchServices 注册,不申请辅助功能或屏幕录制权限。 构建并解锁 Mac 后运行 `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py`,验证应用移除并恢复 AX 根节点的窗口。检查需要已有辅助功能/屏幕录制权限,会拒绝过期元素索引,捕获无 AX 窗口,通过 fixture 状态文件核实坐标点击,并检查恢复。不会修改系统权限设置。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperRuntime.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperRuntime.swift index c468d95032..42c1853870 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperRuntime.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperRuntime.swift @@ -296,7 +296,6 @@ final class SharedSocket: @unchecked Sendable { throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED", message: "Computer Use requires its signed application bundle; set helperPath to DSH Computer Use.app/Contents/MacOS/dsh-cua-native") } - let applicationURL = try StandaloneApplication.prepare(bundle.bundleURL, runtimeKey: options.runtimeKey, deadline: deadline) let configuration = NSWorkspace.OpenConfiguration() configuration.activates = false configuration.addsToRecentItems = false @@ -311,12 +310,12 @@ final class SharedSocket: @unchecked Sendable { guard DispatchTime.now().uptimeNanoseconds < deadline else { throw NativeFailure(code: "NATIVE_STARTUP_TIMEOUT", message: "Computer Use launch lock exhausted the startup deadline") } - // LaunchServices and a standalone bundle keep both permission services attributed to this helper. + // LaunchServices gives the application its own TCC identity; direct spawning inherits the terminal's. let application: NSRunningApplication - do { application = try await NSWorkspace.shared.openApplication(at: applicationURL, configuration: configuration) } + do { application = try await NSWorkspace.shared.openApplication(at: bundle.bundleURL, configuration: configuration) } catch { if let failure = try SharedHelperOptions.startupFailure(at: failurePath) { throw failure } - throw NativeFailure(code: "NATIVE_STARTUP", message: "macOS could not launch Computer Use at \(applicationURL.path): \(error.localizedDescription)") + throw NativeFailure(code: "NATIVE_STARTUP", message: "macOS could not launch Computer Use at \(bundle.bundleURL.path): \(error.localizedDescription)") } let pid = application.processIdentifier guard pid > 0 else { diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift deleted file mode 100644 index 15bd509639..0000000000 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift +++ /dev/null @@ -1,86 +0,0 @@ -// Nested applications share their enclosing app's Screen Recording identity in TCC. -import CryptoKit -import Darwin -import Foundation -import Security - -enum StandaloneApplication { - static func hasApplicationAncestor(_ application: URL) -> Bool { - var parent = application.deletingLastPathComponent() - while parent.path != "/" { - if parent.pathExtension.lowercased() == "app" { return true } - parent.deleteLastPathComponent() - } - return false - } - - static func prepare(_ application: URL, runtimeKey: String, deadline: UInt64) throws -> URL { - let source = application.resolvingSymlinksInPath() - guard hasApplicationAncestor(source) else { return source } - let support = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, - appropriateFor: nil, create: true) - return try install(source, runtimeKey: runtimeKey, - root: support.appendingPathComponent("DeepSeek Harness/Computer Use"), deadline: deadline) - } - - // Published generations remain immutable while any installed DSH version may still run them. - static func install(_ source: URL, runtimeKey: String, root: URL, deadline: UInt64) throws -> URL { - let files = FileManager.default - try files.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) - let root = root.resolvingSymlinksInPath() - let generation = root.appendingPathComponent(runtimeKey, isDirectory: true) - let application = generation.appendingPathComponent(source.lastPathComponent, isDirectory: true) - guard !hasApplicationAncestor(application) else { - throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED", message: "Computer Use application storage must be outside another .app: \(root.path)") - } - var lock: SharedHelperLock? - repeat { - lock = try SharedHelperLock(path: root.appendingPathComponent("\(runtimeKey).lock").path) - if lock != nil { break } - usleep(10_000) - } while DispatchTime.now().uptimeNanoseconds < deadline - guard let lock else { - throw NativeFailure(code: "NATIVE_STARTUP_TIMEOUT", message: "Computer Use application installation is still in progress") - } - defer { withExtendedLifetime(lock) {} } - if files.fileExists(atPath: generation.path) { - do { try validate(application, runtimeKey: runtimeKey) } - catch { - throw NativeFailure(code: "NATIVE_APPLICATION_INVALID", message: "Computer Use cached application is invalid: \(error.localizedDescription); remove \(generation.path) and retry") - } - return application - } - let staging = root.appendingPathComponent(".staging-\(UUID().uuidString)", isDirectory: true) - try files.createDirectory(at: staging, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) - do { - let stagedApplication = staging.appendingPathComponent(source.lastPathComponent, isDirectory: true) - try files.copyItem(at: source, to: stagedApplication) - try validate(stagedApplication, runtimeKey: runtimeKey) - try files.moveItem(at: staging, to: generation) - } catch { - let failure = error - do { try files.removeItem(at: staging) } - catch { - throw NativeFailure(code: "NATIVE_IO", message: "Computer Use installation failed: \(failure.localizedDescription); could not remove \(staging.path): \(error.localizedDescription)") - } - throw failure - } - return application - } - - private static func validate(_ application: URL, runtimeKey: String) throws { - guard !hasApplicationAncestor(application.resolvingSymlinksInPath()) else { - throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED", message: "Computer Use application resolves inside another .app: \(application.path)") - } - let executable = application.appendingPathComponent("Contents/MacOS/dsh-cua-native") - let bytes = try Data(contentsOf: executable, options: .mappedIfSafe) - let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() - var code: SecStaticCode? - let flags = SecCSFlags(rawValue: kSecCSStrictValidate | kSecCSCheckAllArchitectures | kSecCSCheckNestedCode) - guard digest == runtimeKey, - SecStaticCodeCreateWithPath(application as CFURL, [], &code) == errSecSuccess, - let code, SecStaticCodeCheckValidity(code, flags, nil) == errSecSuccess else { - throw NativeFailure(code: "NATIVE_APPLICATION_INVALID", message: "Computer Use application failed signature or executable verification at \(application.path)") - } - } -} diff --git a/packages/experimental/cua-macos/native/tests/nested_application_e2e.py b/packages/experimental/cua-macos/native/tests/nested_application_e2e.py deleted file mode 100644 index b8b3b3d994..0000000000 --- a/packages/experimental/cua-macos/native/tests/nested_application_e2e.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Verify nested helper extraction and concurrent launchers without granting macOS permissions.""" -import argparse -import concurrent.futures -from contextlib import ExitStack -import hashlib -import json -import os -from pathlib import Path -import plistlib -import shutil -import signal -import subprocess -import tempfile -import uuid - -from native_test_support import copy_helper, default_binary, unregister_helper -from shared_helper_e2e import Connection, wait_released - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--helper', type=Path, default=None) - args = parser.parse_args() - with tempfile.TemporaryDirectory(prefix='cua-nest-', dir='/tmp') as temporary, ExitStack() as cleanup: - root = Path(temporary) - parent = root / 'Desktop.app' / 'Contents' / 'Resources' - parent.mkdir(parents=True) - helper = copy_helper(args.helper or default_binary(), parent) - application = helper.parents[2] - manifest = application / 'Contents/Info.plist' - info = plistlib.loads(manifest.read_bytes()) - info['CFBundleIdentifier'] = 'dev.dsh.cua.nested-test.' + uuid.uuid4().hex - manifest.write_bytes(plistlib.dumps(info)) - subprocess.run(['codesign', '--force', '--sign', '-', '--timestamp=none', str(application)], - check=True, capture_output=True, timeout=30) - key = hashlib.sha256(helper.read_bytes()).hexdigest() - cache = Path.home() / 'Library/Application Support/DeepSeek Harness/Computer Use' - generation = cache / key - assert not generation.exists(), 'The unique signed fixture unexpectedly shares an existing generation' - cleanup.callback(lambda: (cache / (key + '.lock')).unlink(missing_ok=True)) - cleanup.callback(lambda: shutil.rmtree(generation) if generation.exists() else None) - copied_helper = generation / application.name / 'Contents/MacOS/dsh-cua-native' - cleanup.callback(unregister_helper, copied_helper) - runtime = [root / 'a', root / 'b'] - - def stop_owned(directory, pid): - try: - os.kill(pid, signal.SIGTERM) - except ProcessLookupError: - pass - wait_released(directory / (key + '.lock'), pid) - - def launch(directory): - result = subprocess.run([str(helper), '--ensure-shared', '--runtime-key', key, - '--runtime-directory', str(directory), '--startup-timeout-ms', '15000'], - check=True, capture_output=True, text=True, timeout=25) - ready = json.loads(result.stdout) - cleanup.callback(stop_owned, directory, ready['pid']) - client = Connection(directory / (key + '.sock'), key) - cleanup.callback(client.close) - return client - - # Separate launcher processes share the installation lock while retaining independent service sockets. - with concurrent.futures.ThreadPoolExecutor(max_workers=2) as workers: - clients = list(workers.map(launch, runtime)) - for client in clients: - state = client.call('permissionStatus', {}) - assert Path(state['helper']['path']).resolve() == copied_helper.resolve(), state - assert Path(state['launchApplication']['path']).resolve() == copied_helper.parents[2].resolve(), state - assert not any(part.endswith('.app') for part in copied_helper.parents[3].parts), state - assert clients[0].ready['pid'] != clients[1].ready['pid'] - assert copied_helper.read_bytes() == helper.read_bytes() - subprocess.run(['codesign', '--verify', '--deep', '--strict', str(copied_helper.parents[2])], - check=True, capture_output=True, timeout=30) - print('PASS: concurrent launchers use the same signature-preserving standalone application and drain both helpers') - - -if __name__ == '__main__': - main() diff --git a/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift b/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift deleted file mode 100644 index a73dda8516..0000000000 --- a/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift +++ /dev/null @@ -1,136 +0,0 @@ -// Real signed fixtures exercise cache publication, reuse, integrity and isolated permission ownership. -import CryptoKit -import Darwin -import Foundation -import Testing -@testable import CuaNative - -private struct ApplicationFixture { - let root: URL - let application: URL - let cache: URL - var executable: URL { application.appendingPathComponent("Contents/MacOS/dsh-cua-native") } - var resource: URL { application.appendingPathComponent("Contents/Resources/value.txt") } - var key: String { get throws { SHA256.hash(data: try Data(contentsOf: executable)).map { String(format: "%02x", $0) }.joined() } } - var deadline: UInt64 { DispatchTime.now().uptimeNanoseconds + 30_000_000_000 } - - init() throws { - root = FileManager.default.temporaryDirectory.appendingPathComponent("cua-application-\(UUID().uuidString)") - application = root.appendingPathComponent("Desktop.app/Contents/Resources/DSH Computer Use.app") - cache = root.appendingPathComponent("support") - try FileManager.default.createDirectory(at: executable.deletingLastPathComponent(), withIntermediateDirectories: true) - try FileManager.default.createDirectory(at: resource.deletingLastPathComponent(), withIntermediateDirectories: true) - try FileManager.default.copyItem(at: URL(fileURLWithPath: "/usr/bin/true"), to: executable) - try Data("original resource".utf8).write(to: resource) - let plist = try PropertyListSerialization.data(fromPropertyList: [ - "CFBundleIdentifier": "dev.dsh.cua.cache-test.\(UUID().uuidString)", - "CFBundleExecutable": "dsh-cua-native", "CFBundleName": "DSH Computer Use", "CFBundlePackageType": "APPL", - ], format: .xml, options: 0) - try plist.write(to: application.appendingPathComponent("Contents/Info.plist")) - try sign() - } - - func sign() throws { - let process = Process(), finished = DispatchSemaphore(value: 0) - process.executableURL = URL(fileURLWithPath: "/usr/bin/codesign") - process.arguments = ["--force", "--sign", "-", "--timestamp=none", application.path] - process.standardOutput = FileHandle.nullDevice - process.standardError = FileHandle.nullDevice - process.terminationHandler = { _ in finished.signal() } - try process.run() - if finished.wait(timeout: .now() + 30) == .timedOut { - kill(process.processIdentifier, SIGKILL) - process.waitUntilExit() - throw NativeFailure(code: "FIXTURE_TIMEOUT", message: "Ad-hoc fixture signing did not exit") - } - #expect(process.terminationReason == .exit) - try #require(process.terminationStatus == 0) - } - - func close() { - do { try FileManager.default.removeItem(at: root) } - catch { Issue.record("Could not remove owned application fixture: \(error)") } - } -} - -@Test func onlyNestedApplicationsNeedAnIndependentInstallation() throws { - #expect(StandaloneApplication.hasApplicationAncestor(URL(fileURLWithPath: "/Applications/Desktop.app/Contents/Helper.app"))) - #expect(StandaloneApplication.hasApplicationAncestor(URL(fileURLWithPath: "/Applications/Desktop.APP/Helper.app"))) - let standalone = URL(fileURLWithPath: "/Users/example/Helper.app") - #expect(!StandaloneApplication.hasApplicationAncestor(standalone)) - #expect(try StandaloneApplication.prepare(standalone, runtimeKey: "unused", deadline: 0) == standalone) -} - -@Test func aSignedHelperIsPublishedOutsideItsEnclosingApplicationAndReused() throws { - let f = try ApplicationFixture(); defer { f.close() } - let key = try f.key - let installed = try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) - #expect(!StandaloneApplication.hasApplicationAncestor(installed)) - #expect(try Data(contentsOf: installed.appendingPathComponent("Contents/MacOS/dsh-cua-native")) == Data(contentsOf: f.executable)) - #expect(try Data(contentsOf: installed.appendingPathComponent("Contents/Resources/value.txt")) == Data(contentsOf: f.resource)) - #expect(try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) == installed) -} - -@Test func changingTheSignedApplicationRetainsTheEarlierGeneration() throws { - let f = try ApplicationFixture(); defer { f.close() } - let old = try StandaloneApplication.install(f.application, runtimeKey: f.key, root: f.cache, deadline: f.deadline) - try Data("new resource".utf8).write(to: f.resource) - try f.sign() - let new = try StandaloneApplication.install(f.application, runtimeKey: f.key, root: f.cache, deadline: f.deadline) - #expect(old != new) - #expect(try String(contentsOf: old.appendingPathComponent("Contents/Resources/value.txt"), encoding: .utf8) == "original resource") - #expect(try String(contentsOf: new.appendingPathComponent("Contents/Resources/value.txt"), encoding: .utf8) == "new resource") -} - -@Test(arguments: ["Contents/Resources/value.txt", "Contents/MacOS/dsh-cua-native"]) -func aChangedCachedApplicationIsRejected(file: String) throws { - let f = try ApplicationFixture(); defer { f.close() } - let key = try f.key - let installed = try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) - try Data("changed".utf8).write(to: installed.appendingPathComponent(file)) - #expect(throws: (any Error).self) { - try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) - } -} - -@Test func anInvalidSourceLeavesNoPartialPublishedApplication() throws { - let f = try ApplicationFixture(); defer { f.close() } - let key = try f.key - try Data("unsigned change".utf8).write(to: f.resource) - #expect(throws: (any Error).self) { - try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) - } - #expect(try FileManager.default.contentsOfDirectory(atPath: f.cache.path) == ["\(key).lock"]) -} - -@Test func applicationStorageCannotItselfBeNestedInAnotherApplication() throws { - let f = try ApplicationFixture(); defer { f.close() } - #expect(throws: (any Error).self) { - try StandaloneApplication.install(f.application, runtimeKey: f.key, - root: f.root.appendingPathComponent("Other.app/cache"), deadline: f.deadline) - } -} - -@Test func aCachedSymlinkCannotRedirectTheHelperIntoAnEnclosingApplication() throws { - let f = try ApplicationFixture(); defer { f.close() } - let key = try f.key - try FileManager.default.createDirectory(at: f.cache, withIntermediateDirectories: true) - try FileManager.default.createSymbolicLink(at: f.cache.appendingPathComponent(key), - withDestinationURL: f.application.deletingLastPathComponent()) - #expect(throws: (any Error).self) { - try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) - } -} - -@Test func aCompetingInstallerDoesNotUseAPartialGeneration() throws { - let f = try ApplicationFixture(); defer { f.close() } - let key = try f.key - try FileManager.default.createDirectory(at: f.cache, withIntermediateDirectories: true) - let lock = try #require(try SharedHelperLock(path: f.cache.appendingPathComponent("\(key).lock").path)) - defer { withExtendedLifetime(lock) {} } - #expect(throws: (any Error).self) { - try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, - deadline: DispatchTime.now().uptimeNanoseconds) - } - #expect(!FileManager.default.fileExists(atPath: f.cache.appendingPathComponent(key).path)) -} From aa5fde3700affc28530408d081159625e8362d64 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 30 Oct 2026 10:49:44 +0800 Subject: [PATCH 26/55] feat(cua): default to a DSH-home identity and allow user certificates --- ...6-10-29-cua-dev-signing-identity.i18n.yaml | 12 ++--- .../2026-10-29-cua-dev-signing-identity.md | 10 ++-- .../2026-10-29-cua-dev-signing-identity.zh.md | 10 ++-- docs/config-catalog.md | 15 ++++-- docs/config-catalog.zh.md | 15 ++++-- .../cua-source-dev-helper/guide.i18n.yaml | 8 ++-- .../cua-source-dev-helper/guide.md | 6 +-- .../cua-source-dev-helper/guide.zh.md | 6 +-- .../experimental/cua-macos/README.i18n.yaml | 8 ++-- packages/experimental/cua-macos/README.md | 11 +++-- packages/experimental/cua-macos/README.zh.md | 11 +++-- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 8 ++-- .../cua-macos/native/README.zh.md | 8 ++-- .../cua-macos/native/build_app.py | 29 +++++++---- .../cua-macos/native/dev_signing.py | 44 ++++++++++++----- .../cua-macos/native/tests/dev_signing_e2e.py | 20 +++++--- .../cua-macos/native/tests/test_build_app.py | 48 +++++++++++++++---- .../native/tests/test_dev_signing.py | 33 +++++++++++-- packages/experimental/cua-macos/package.json | 3 +- packages/experimental/cua-macos/src/index.ts | 24 +++++++--- .../cua-macos/src/native-build.ts | 8 +++- .../cua-macos/tests/native-build.spec.ts | 19 ++++++-- .../tests/provider-lifecycle.spec.ts | 12 +++-- packages/experimental/cua-macos/tsconfig.json | 3 ++ pnpm-lock.yaml | 3 ++ 26 files changed, 264 insertions(+), 114 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml index 30c3149c44..4a7241cbd7 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml @@ -9,11 +9,11 @@ en: a24857a312482724 zh: dbac75d363670e86 /agent-note-development-signing-identity-for-source-built-cua-helpers/decision: - en: 1063fd73edaf7c56 - zh: 9b491cba43f26d32 + en: f83e1ec19e7b8783 + zh: 843c911c6531cb17 /agent-note-development-signing-identity-for-source-built-cua-helpers/alternatives-considered: - en: 713bcd3484cf3594 - zh: ae45617289117b7e + en: 88dc1b86ce9aa018 + zh: 4f940dbc16331f3e /agent-note-development-signing-identity-for-source-built-cua-helpers/consequences: - en: 540579c5459e9e7a - zh: b7530006e681b618 + en: e2950b9e0698a0b0 + zh: c9c304ef59086784 diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md index 411f9bc0b3..66a5748de2 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md @@ -12,15 +12,17 @@ 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`, 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` 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. +`sourceSigning` belongs to the macOS provider and accepts `ad-hoc`, default `local-identity`, or `{ identity, keychain? }` for an existing certificate. The generated identity and password live under `$DSH_HOME/computer-use-dev-signing`, using `~/.dsh` when no home is configured. The first build creates the certificate and later builds using that home reuse it. The Host uses the shared home-path resolver and passes the result to Python. Ad-hoc and user-certificate modes do not read or create the generated identity; users own unlocking and maintaining their certificates. -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. +Setup creates a self-signed certificate in a dedicated keychain, stores a random password in a `0600` file, permits codesign through the key partition list, and adds the keychain to the user search list. Automatic builds unlock it before signing to avoid password or key-access dialogs. A file lock serializes setup and removal within the same home. A recorded identity with a missing keychain is preserved and rejected until the user explicitly removes it. The signing requirement contains the bundle identifier and certificate, independent of code hash or path for builds using that certificate. + +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. `--identity` selects user-certificate signing and is mutually exclusive with `--signing`. ## 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. -**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. +**Ad-hoc signing by default.** This avoids storing a private key but can require new grants when binaries change. Automatic fixed signing removes manual certificate setup from ordinary source builds; ad-hoc signing remains an explicit option. **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 +32,4 @@ Certificate signatures embed a signing time even without a timestamp server. Dev ## Consequences -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. +Automatic builds using the same DSH home share a signing requirement; actual permission retention across rebuilds and worktrees still needs manual verification. Other processes of the same user can read the password and sign with the development identity; the release helper uses a different bundle identifier. Deleting DSH home removes the generated identity, so the next build creates another certificate and needs new grants; home reset therefore clears signing state too. System permission entries and the keychain search entry survive directory deletion; subsequent setup removes a stale search entry at the same path. Select ad-hoc or user-certificate signing before explicit removal to prevent regeneration. The real signing e2e checks requirements across output directories, user-selected certificates, and search-list restoration after removal. diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md index 1ada9cb3c1..370175a7ad 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md @@ -12,15 +12,17 @@ Status: implemented 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` 默认为 `ad-hoc`,不读取已有身份或修改钥匙串。显式选择 `local-identity` 后,构建自动初始化或复用本机身份。初始化在专用钥匙串中创建自签名代码签名证书,把随机钥匙串密码保存在旁边仅所有者可读的文件中,通过密钥分区列表允许 `codesign` 使用私钥,并把该钥匙串加入用户钥匙串搜索列表。`codesign` 只从这个列表查找签名身份。固定身份构建每次签名前都用保存的密码解锁钥匙串,避免密码或密钥访问窗口。跨进程文件锁串行化不同 worktree 的初始化和移除,防止并发创建不同证书。签名得到的指定要求只包含 Bundle ID 和证书,同一台机器上签出的所有构建都相同,与代码哈希和路径无关。 +`sourceSigning` 由 macOS provider 定义,支持 `ad-hoc`、默认的 `local-identity`,以及指定已有证书的 `{ identity, keychain? }`。自动身份及密码存放在 `$DSH_HOME/computer-use-dev-signing`,未配置 home 时使用 `~/.dsh`;首次构建创建证书,此后同一 home 的构建都复用它。Host 使用公共 home 路径解析器并把结果传给 Python。临时签名和用户证书模式不读取或创建自动身份。用户证书的解锁和维护由用户负责。 -即使不使用时间戳服务器,证书签名也会写入签名时间。开发版发布时记录每个未签名应用与签名身份对应的目录,再次构建时直接选中该目录,不重新签名,因此相同源码保持同一个可执行文件摘要和同一个共享服务。缓存使用证书指纹;显式证书名称可能对应续期后的证书,因此不复用缓存。签名初始化失败会中止构建;异常信息不包含密码或完整命令参数。显式传入 `--identity` 时覆盖配置的签名方式。 +初始化在专用钥匙串中创建自签名证书,将随机密码存入权限为 `0600` 的文件,通过密钥分区列表允许 `codesign` 访问,并把钥匙串加入用户搜索列表。自动构建每次签名前用保存的密码解锁,避免密码或密钥访问窗口。同一 home 的初始化和移除使用文件锁串行执行。已有身份记录但钥匙串缺失时保留记录并报错,只有用户显式移除后才允许重新生成。签名要求包含 Bundle ID 和证书,使用同一证书的构建不依赖代码哈希或路径。 + +即使不使用时间戳服务器,证书签名也会写入签名时间。开发版发布时记录每个未签名应用与签名身份对应的目录,再次构建时直接选中该目录,不重新签名,因此相同源码保持同一个可执行文件摘要和同一个共享服务。缓存使用证书指纹;显式证书名称可能对应续期后的证书,因此不复用缓存。签名初始化失败会中止构建;异常信息不包含密码或完整命令参数。`--identity` 选择用户证书签名,与 `--signing` 互斥。 ## 考虑过的替代方案 **把权限交给启动终端。** 直接启动服务时,macOS 把权限归属到启动 DSH 的终端或编辑器。该应用运行的所有程序,包括模型执行的命令,都会带上这些权限。 -**默认固定签名。** 固定身份可以保持签名要求,但会保存私钥并修改钥匙串搜索列表。默认临时签名让用户自行选择是否接受这些改动,代价是二进制变化后可能需要重新授权。 +**默认临时签名。** 可以避免保存私钥,但二进制变化后可能需要重新授权。默认自动生成固定身份,让普通源码构建无需手动准备证书;临时签名仍可显式选择。 **把自签名身份放进登录钥匙串。** 登录钥匙串已解锁且在搜索列表中,但要让 `codesign` 不弹窗地使用其中的新私钥,需要用户的登录密码。 @@ -30,4 +32,4 @@ Host 以开发版构建源码检出,Bundle ID 为 `com.deepseek.harness.comput ## 后果 -启用固定签名的检出和重新编译共用签名要求。真实授权在重新编译和跨 worktree 后是否保留,仍需手动验证。该用户的任何进程都能读取钥匙串密码,并签出获得开发版授权的代码;正式 helper 的授权不受影响,而且同一用户本来就能修改下一次构建会签名的 Swift 源码。初始化会改变用户钥匙串搜索列表,直到运行移除命令。移除前需切回 `ad-hoc`,否则下次构建会重新创建身份;切换签名方式或更换身份可能需要重新授权。系统设置中已有的授权在移除后仍然保留。原有的临时签名源码授权不会沿用,开发者需要给 `DSH Computer Use Dev` 授权一次。`dev_signing_e2e.py` 检查两个不同构建共用同一个指定要求,并确认移除后搜索列表已恢复。 +使用同一 DSH home 的自动签名构建共用签名要求,实际授权在重建和跨 worktree 后是否保留仍需手动验证。同一用户的进程能读取密码并使用开发身份签名,正式 helper 使用不同的 Bundle ID。删除 DSH home 会删除自动身份,下次构建生成新证书并需要重新授权;这也让 home 重置能清除签名状态。系统设置中的授权和钥匙串搜索条目不随目录删除而消失;后续初始化会清理同路径的失效搜索条目。主动移除身份前需选择临时签名或用户证书,以免下次构建重新生成。真实签名 e2e 核对不同输出目录的构建共用要求、用户指定证书可用,以及移除后搜索列表恢复。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index d39644b538..908d10aaf2 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1113,17 +1113,22 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:17`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:18`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ export interface Config extends CuaConfig { /** - * 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. + * Source-build signing: `local-identity` (default) creates or reuses an identity in DSH home; + * `ad-hoc` binds grants to the code hash; an object selects an existing user-managed certificate. + * Installed packages and `helperPath` keep their own signature. */ - sourceSigning: 'ad-hoc' | 'local-identity' + sourceSigning: 'ad-hoc' | 'local-identity' | { + /** Existing codesign certificate name or SHA-1 fingerprint. */ + identity: string + /** Absolute keychain path; omission uses the user's keychain search list. The user owns unlocking it. */ + keychain?: string + } } ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 4ed5e2241c..a5e928ecce 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1115,17 +1115,22 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:17`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:18`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ export interface Config extends CuaConfig { /** - * 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. + * Source-build signing: `local-identity` (default) creates or reuses an identity in DSH home; + * `ad-hoc` binds grants to the code hash; an object selects an existing user-managed certificate. + * Installed packages and `helperPath` keep their own signature. */ - sourceSigning: 'ad-hoc' | 'local-identity' + sourceSigning: 'ad-hoc' | 'local-identity' | { + /** Existing codesign certificate name or SHA-1 fingerprint. */ + identity: string + /** Absolute keychain path; omission uses the user's keychain search list. The user owns unlocking it. */ + keychain?: string + } } ``` diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml index a71c90c16f..2021a137ed 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 72a8ea364f7427fa zh: 9e7ed2e00425bddb /source-built-computer-use-helper-identity/change: - en: c0bb4349a8bb975c - zh: 7e13fa29c2b8e7c4 + en: 14b5363428db53fe + zh: 58f7ba480871197e /source-built-computer-use-helper-identity/migration: - en: 318184f2a11cbcea - zh: c320de5acc4ee165 + en: e5dd3a1a5825fc8c + zh: 494ef3db1feb9a18 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md index 74ac04269a..3d6bacc71d 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md @@ -9,11 +9,11 @@ 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 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 now generate a fixed signing identity under `$DSH_HOME/computer-use-dev-signing` by default and reuse it; an unset `DSH_HOME` uses `~/.dsh`. ## Migration -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. +1. Default `sourceSigning: local-identity` needs no manual setup; use the same DSH home across worktrees to share the identity. For ad-hoc signing, set `config.sourceSigning: ad-hoc` on `id: cua` in `cordis.patch.yml`. For an existing certificate, use the [user-signing configuration](../../../../packages/experimental/cua-macos/README.md#use-this-package). 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 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. +4. To stop using the generated identity, select ad-hoc or user-certificate signing, then run `pnpm --dir packages/experimental/cua-macos run dev-signing:remove`. Select a custom home with the same `DSH_HOME` or `--dsh-home `. Deleting DSH home causes a new certificate on the next build and requires new grants. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md index 2fd3f1cbbc..dd79e7fab8 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md @@ -9,11 +9,11 @@ description: "源码构建的 Computer Use helper 使用独立的开发版 Bundl ## 变更 -此前源码检出构建的 `DSH Computer Use.app` 使用正式版 Bundle ID `com.deepseek.harness.computer-use` 和临时签名。现在构建的是 `DSH Computer Use Dev.app`,Bundle ID 为 `com.deepseek.harness.computer-use.dev`。旧条目上的辅助功能和屏幕录制授权不适用于它。桌面端和 npm 安装版不变。 +此前源码检出构建的 `DSH Computer Use.app` 使用正式版 Bundle ID `com.deepseek.harness.computer-use` 和临时签名。现在构建的是 `DSH Computer Use Dev.app`,Bundle ID 为 `com.deepseek.harness.computer-use.dev`。旧条目上的辅助功能和屏幕录制授权不适用于它。桌面端和 npm 安装版不变。 源码构建现在默认在 `$DSH_HOME/computer-use-dev-signing` 中生成并复用固定签名身份,未设置 `DSH_HOME` 时使用 `~/.dsh`。 ## 迁移 -1. 源码构建默认使用临时签名,二进制变化后可能需要重新授权。如需固定身份,在 profile 的 `cordis.patch.yml` 中为 `id: cua` 设置 `config.sourceSigning: local-identity`,首次构建会自动创建或复用本机身份。各 worktree 需使用相同配置。 +1. 默认的 `sourceSigning: local-identity` 无需手动 setup;各 worktree 使用同一 DSH home 即可复用身份。如需临时签名,在 `cordis.patch.yml` 的 `id: cua` 节点设置 `config.sourceSigning: ad-hoc`;如需已有证书,使用[用户签名配置](../../../../packages/experimental/cua-macos/README.zh.md#use-this-package)。 2. 从源码检出启动 DSH 并调用 Computer Use,在系统设置中给 `DSH Computer Use Dev` 授予辅助功能和屏幕录制权限。 3. 确认 `getCapabilities` 报告两项权限均为 `true`。只有在没有已安装的 DSH 使用旧的 `DSH Computer Use` 条目时才移除它。 -4. 撤销固定签名时,先切回 `sourceSigning: ad-hoc`,再运行 `pnpm --dir packages/experimental/cua-macos run dev-signing:remove`,并在系统设置中删除开发版授权。 +4. 停用自动身份时,先改用临时签名或用户证书,再运行 `pnpm --dir packages/experimental/cua-macos run dev-signing:remove`。自定义 home 通过同一个 `DSH_HOME` 或 `--dsh-home <路径>` 指定。删除 DSH home 后会重新生成证书,届时需要重新授权。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 9ec10f9015..fa9cd3f06b 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 6390cd271bbb64fe zh: 342f4f6aa617809f /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: e405b2ed1f6f82b3 - zh: 42b2d73810f95e80 + en: 7e29c174a0712fa2 + zh: 086cb1d75b6d2d08 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: 786b8fd630b11e5f zh: 55143f15486afce8 @@ -45,8 +45,8 @@ en: a2c9acb5a4320dda zh: e8d1586af60215c4 /deepseek-ai-dsh-experimental-cua-macos/known-limitations-and-deferred-work: - en: a900c335ed926dcf - zh: 4eb9537ca51ad905 + en: a38284cd2b90a4a4 + zh: 5f8b67f1ca765e9d /deepseek-ai-dsh-experimental-cua-macos/known-limitations-and-deferred-work/dev-note: en: b836f01bd0bceb4a zh: 8122fa08b2aa95fa diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index d029c7c91b..1b5fe9dabb 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -39,22 +39,23 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. 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. The helper needs Accessibility permission for AX/input and Screen Recording permission for capture; grant these permissions to the helper when prompted. Source builds use the bundle filename `DSH Computer Use Dev.app` and declare `DSH Computer Use Dev` in Info.plist; select the development entry 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`. This entry loads `@deepseek-ai/dsh-experimental-cua-macos`; `cua` is its profile ID: +Source builds default to `sourceSigning: local-identity`: the first build generates an identity under `$DSH_HOME/computer-use-dev-signing`, and later builds and worktrees using that home reuse it. An unset `DSH_HOME` uses `~/.dsh`. Select `sourceSigning: ad-hoc` for temporary signatures, or choose an existing certificate in the profile’s `cordis.patch.yml` as below; `cua` is the entry ID loading `@deepseek-ai/dsh-experimental-cua-macos`: ```yaml - id: cua config: - sourceSigning: local-identity + sourceSigning: + identity: "Apple Development: Your name (TEAMID)" ``` -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. +Replace `identity` with an existing certificate name or SHA-1 fingerprint. Optional `keychain` selects an absolute keychain path; omission uses the user search list, and the user owns unlocking it. Custom signing does not create, unlock or modify the generated identity. Automatic signing stores a private key and password accessible to other processes of the same user; see [development signing](native/README.md#build-and-service). | 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`. | +| `sourceSigning` | `local-identity` | Source signing: a generated identity, `ad-hoc`, or `{ identity, keychain? }` for an existing certificate. 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. | @@ -226,7 +227,7 @@ The queue orders individual native requests. Holding an app object does not rese - macOS Stage Manager can reduce background window bounds and screenshots to thumbnails. Full-window observation and coordinate input in this state are not guaranteed; model guidance requires explaining foreground needs and avoiding repeated focus reclamation. - Background input depends on private SkyLight symbols; macOS updates can make them unavailable. Validate each target OS version. - Observed failures include dispatched Unicode text not appearing in Blender and background Command+A not selecting all text in AppKit. Inspect application state after input; a successful tool result confirms dispatch only. -- Source builds without the [development signing identity](native/README.md#build-and-service) use ad-hoc signatures and require authorization again after source changes. Release distribution needs a stable Developer ID signature and notarization; the build command accepts `--identity`, and installed packages preserve the distributed signature. The [permission page](../cua/README.md) offers helper authorization and target-application revocation. +- Source builds explicitly selecting `ad-hoc` can require new grants after binary changes. Deleting DSH home removes its [generated identity](native/README.md#build-and-service), so the next automatic build creates a new certificate and needs new grants. Release distribution needs a stable Developer ID signature and notarization; the build command accepts `--identity`, and installed packages preserve the distributed signature. The [permission page](../cua/README.md) offers helper authorization and target-application revocation. - Release packaging does not automatically verify GUI startup, helper identity or exit cleanup. Release maintainers can run the [distribution smoke](native/README.md#build-and-service) on a logged-in Mac before publication; a successful package build does not establish those runtime results. - Saved permission rows show the name, path and icon of one approved copy, not an inventory of every installation sharing its identity. Removing that copy can leave its icon unavailable. Revocation still applies to every copy with the same identity. - If macOS does not expose a running application’s bundle identifier, the helper checks its reported bundle only when its executable matches the observed process path, then falls back to that path. Consent identity creation fails only when both the bundle identifier and actual executable path are unavailable; process-instance verification can still fail independently. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 7033d88671..3d53491649 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -39,22 +39,23 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. 配置输出命令不发起模型请求。执行真实任务时,将 `--dump-config` 替换为任务提示,并配置该 profile 的模型凭据。配置挂载 computer-use 注册表和本 provider;使用前需移除已有的竞争 provider。helper 需要辅助功能权限来读取 AX 和输入,需要屏幕录制权限来截图;按系统提示给 helper 授权。源码构建的应用包名为 `DSH Computer Use Dev.app`,Info.plist 声明名称 `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` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。 -源码构建默认使用临时签名,即使本机已有开发证书也不会读取或修改钥匙串。需要在重新编译或切换 worktree 后保留签名身份时,在 profile 的 `cordis.patch.yml` 中为已加载的 `cua` 节点配置;该节点加载 `@deepseek-ai/dsh-experimental-cua-macos`,`cua` 是节点 ID: +源码构建默认使用 `sourceSigning: local-identity`:首次构建在 `$DSH_HOME/computer-use-dev-signing` 中生成固定身份,后续构建和使用同一 DSH home 的 worktree 复用它。未设置 `DSH_HOME` 时使用 `~/.dsh`。临时签名可配置为 `sourceSigning: ad-hoc`;已有签名证书可在 profile 的 `cordis.patch.yml` 中这样选择,`cua` 是加载 `@deepseek-ai/dsh-experimental-cua-macos` 的节点 ID: ```yaml - id: cua config: - sourceSigning: local-identity + sourceSigning: + identity: "Apple Development: Your name (TEAMID)" ``` -首次启用会创建本机签名身份。不同 worktree 都需选择 `local-identity`;共享 profile 可复用这项配置。钥匙串访问范围、撤销方法和授权限制见[开发签名](native/README.zh.md#build-and-service)。 +将 `identity` 替换为已有证书的名称或 SHA-1 指纹。可选的 `keychain` 指定钥匙串绝对路径;省略时使用用户钥匙串搜索列表,解锁由用户负责。自定义证书模式不会创建、解锁或修改自动生成的身份。自动模式会保存私钥和密码,同一用户的进程可以读取并使用它们;详见[开发签名](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` 忽略此项。 | +| `sourceSigning` | `local-identity` | 源码签名:自动生成固定身份、`ad-hoc` 临时签名,或 `{ identity, keychain? }` 指定已有证书。安装版和 `helperPath` 忽略此项。 | | `buildTimeoutMs` | `300000` | 原生组件准备的最长时间。 | | `timeoutMs` | `30000` | 单次操作截止时间,取消后可能已发生部分输入。 | | `connectTimeoutMs` | `5000` | 连接或启动共享 helper 的截止时间。 | @@ -226,7 +227,7 @@ Use selectText only on controls advertising selectionWritable. It selects a uniq - macOS 台前调度可能将后台窗口的尺寸与截图变为缩略图,当前无法保证这种状态下的完整画面与坐标输入;模型指引要求说明前台需求并避免反复抢回焦点。 - 后台输入依赖私有 SkyLight 符号,macOS 升级可能使其不可用,需在目标系统版本验证。 - 实测 Blender Unicode 输入曾出现分派成功但界面未显示文本,后台 AppKit 的 Command+A 曾未选中全文。输入后必须检查应用状态;工具返回成功只表示已分派。 -- 未配置[开发签名身份](native/README.zh.md#build-and-service)时,源码构建使用临时签名,源码变化后需要重新授权。正式分发应以固定 Developer ID 签名并完成公证;构建命令支持 `--identity` 指定签名身份,安装版保留分发时的签名。[权限页面](../cua/README.zh.md)提供 helper 授权入口和目标应用许可撤销。 +- 显式选择 `ad-hoc` 的源码构建在二进制变化后可能需要重新授权。删除 DSH home 会删除其中的[自动签名身份](native/README.zh.md#build-and-service),下次自动构建会生成新证书并需要重新授权。正式分发应以固定 Developer ID 签名并完成公证;构建命令支持 `--identity` 指定签名身份,安装版保留分发时的签名。[权限页面](../cua/README.zh.md)提供 helper 授权入口和目标应用许可撤销。 - 发布打包不自动验证 GUI 启动、helper 身份或退出清理。发布维护者可在发布前,在已登录桌面的 Mac 上执行[分发 smoke](native/README.zh.md#build-and-service);打包成功不能证明这些运行行为已通过验收。 - 已保存许可的条目显示一个已批准副本的名称、路径和图标,不枚举共享身份的所有安装副本。删除该副本后图标可能不可用,撤销仍作用于同一身份的所有副本。 - macOS 无法提供运行中应用的 Bundle ID 时,helper 仅在其报告的 bundle 可执行路径与实际进程路径相同时读取该 bundle,仍无标识则使用路径。只有 Bundle ID 和实际可执行路径均不可用时才拒绝生成授权身份;进程实例验证仍可能独立失败。 diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 58edd3f789..5187c56956 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -15,8 +15,8 @@ en: e8cbc43d38786c40 zh: 52b3ba85d98011b9 /dsh-cua-native-helper/build-and-service: - en: 98b752544721cd1b - zh: 0148b4b08310246b + en: e673418383f64b0c + zh: f27e4ac4b868da16 /dsh-cua-native-helper/request-protocol: en: fc8043c425322cdd zh: cf1edb9a78fda301 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index ca1743475a..531da35f16 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -25,11 +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-`. 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 declares bundle identifier `com.deepseek.harness.computer-use.dev` and name `DSH Computer Use Dev`; its bundle filename is `DSH Computer Use Dev.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. +Source checkouts build with `--variant dev`, producing `DSH Computer Use Dev.app` with bundle identifier `com.deepseek.harness.computer-use.dev`. Development builds default to `local-identity`, generating a fixed identity on first use. Explicit `--signing ad-hoc` uses a temporary signature without accessing the generated identity. Ad-hoc requirements contain the code hash, so changed binaries can require new grants. -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. +Automatic mode creates or reuses the `DSH Computer Use Dev (local)` certificate in a dedicated keychain under `$DSH_HOME/computer-use-dev-signing` and adds the keychain to the user search list. The Host passes `--dsh-home` from the shared home-path resolver; standalone Python commands use `--dsh-home`, a nonblank `DSH_HOME`, then `~/.dsh`. The identity, password and lock file stay inside that home, with setup and removal serialized per home. Each build unlocks the keychain using the adjacent `0600` identity record. Other processes of the same user can read the password and sign code. The designated requirement contains the bundle identifier and certificate; actual grant retention after rebuilds and across worktrees still needs manual verification. -`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. When an identity record exists but its keychain or certificate is missing, the build preserves the record and fails. Invalid records also fail. Recovery requires explicit removal and setup; identity replacement requires new grants. `--identity` overrides `--signing`; release builds ignore `--signing` and keep their existing signing behavior. +User-certificate mode uses `sourceSigning: { identity, keychain? }`, or CLI `--identity `. Optional `--keychain ` selects a keychain; otherwise the user search list applies. The build does not create certificates, read the generated identity or unlock user keychains. `--identity` and `--signing` are mutually exclusive. Release builds retain their ad-hoc default and support explicit certificates. + +`pnpm --dir packages/experimental/cua-macos run dev-signing:setup` can generate the automatic identity in advance. `dev-signing:remove` deletes that home’s identity, password and keychain search entry, retaining the empty lock file. Both commands accept `--dsh-home `. Select ad-hoc or user-certificate signing before removal to prevent regeneration. Deleting DSH home also deletes its identity; a new certificate needs new grants. An existing record with a missing keychain or certificate is preserved and fails with commands to explicitly remove and initialize that home again. Remove system permission entries separately in System Settings. 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. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index bacb528a94..e5eaf92180 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -25,11 +25,13 @@ kind: "package-reference" 运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-` 下生成带签名的 `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`,应用包文件名为 `DSH Computer Use Dev.app`。默认的 `--signing ad-hoc` 不访问开发钥匙串。临时签名的指定要求包含代码哈希,因此二进制变化时可能需要重新授权,干净重建也可能产生这种变化。 +源码检出以 `--variant dev` 构建,应用包为 `DSH Computer Use Dev.app`,Bundle ID 为 `com.deepseek.harness.computer-use.dev`。开发版默认使用 `local-identity`,首次构建自动生成固定身份;显式 `--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 上手动授权验证。 +自动模式在 `$DSH_HOME/computer-use-dev-signing` 下的专用钥匙串中创建或复用 `DSH Computer Use Dev (local)` 证书,并把钥匙串加入用户搜索列表。Host 通过公共 home 路径解析器传入 `--dsh-home`;独立 Python 命令依次使用 `--dsh-home`、非空 `DSH_HOME`、`~/.dsh`。身份、密码和锁文件都在该 home 内,文件锁让同一 home 的初始化与移除串行执行。每次构建使用旁边权限为 `0600` 的身份记录解锁钥匙串。同一用户的进程可以读取密码并签名。指定要求包含 Bundle ID 和证书,重新编译和跨 worktree 后实际保留授权的效果仍需手动验证。 -`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`,沿用原有签名行为。 +用户证书模式使用 `sourceSigning: { identity, keychain? }`,或命令行 `--identity <证书名称或 SHA-1 指纹>`。可选的 `--keychain <绝对路径>` 指定钥匙串,否则使用用户搜索列表。构建不创建证书,不读取自动身份,也不解锁用户钥匙串。`--identity` 与 `--signing` 不能同时指定;正式构建仍默认临时签名,并支持指定证书。 + +`pnpm --dir packages/experimental/cua-macos run dev-signing:setup` 可提前生成自动身份;`dev-signing:remove` 删除当前 DSH home 中的身份、密码和钥匙串搜索条目,保留空锁文件。两条命令均接受 `--dsh-home <路径>`。停止使用自动身份时,先选择临时签名或用户证书,否则下次构建会重新生成身份。删除 DSH home 也会删除身份,新证书需要重新授权。已有记录但钥匙串或证书缺失时,构建保留记录并报错,提示使用该 home 明确移除后重新初始化;系统设置中的授权需单独移除。 证书签名包含签名时间。开发构建在 `sources/` 中记录每个未签名应用与证书指纹对应的目录,内容不变时复用该目录。临时签名使用独立记录。显式传入证书名称时会重新签名,因为续期可能改变名称对应的证书。 diff --git a/packages/experimental/cua-macos/native/build_app.py b/packages/experimental/cua-macos/native/build_app.py index a27a41626f..45f1510061 100644 --- a/packages/experimental/cua-macos/native/build_app.py +++ b/packages/experimental/cua-macos/native/build_app.py @@ -123,11 +123,14 @@ def load_dev_signing(): return module -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 - local = load_dev_signing().setup() +def signing_identity(variant, identity, signing, dsh_home=None, keychain=None): + """Select a user certificate, an ad-hoc signature, or an identity retained in DSH home.""" + if identity is not None: + return identity, keychain + if variant == "release" or signing == "ad-hoc": + return "-", None + signing_module = load_dev_signing() + local = signing_module.setup(signing_module.default_directory(dsh_home)) return local.sha1, local.keychain @@ -139,14 +142,22 @@ def main(): parser.add_argument("--output-directory", type=Path) parser.add_argument("--variant", choices=["release", "dev"], default="release", 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") + signing_options = parser.add_mutually_exclusive_group() + signing_options.add_argument("--signing", choices=["ad-hoc", "local-identity"], + help="defaults to local-identity for dev and ad-hoc for release") + signing_options.add_argument("--identity", help="existing codesign certificate name or SHA-1 fingerprint") + parser.add_argument("--keychain", type=Path, help="absolute keychain path for --identity; the user owns unlocking it") + parser.add_argument("--dsh-home", type=Path, help="home for local-identity; defaults to DSH_HOME or ~/.dsh") args = parser.parse_args() + if args.identity is not None and not args.identity.strip(): + parser.error("--identity must name an existing certificate") + if args.keychain is not None and (args.identity is None or not args.keychain.is_absolute()): + parser.error("--keychain requires --identity and an absolute path") 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, args.signing) + signing = args.signing or ("local-identity" if args.variant == "dev" else "ad-hoc") + identity, keychain = signing_identity(args.variant, args.identity, signing, args.dsh_home, args.keychain) 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) diff --git a/packages/experimental/cua-macos/native/dev_signing.py b/packages/experimental/cua-macos/native/dev_signing.py index 668a2b5372..695e5f59b0 100644 --- a/packages/experimental/cua-macos/native/dev_signing.py +++ b/packages/experimental/cua-macos/native/dev_signing.py @@ -1,4 +1,4 @@ -"""Own the per-user signing identity that keeps source-built Computer Use permissions across rebuilds. +"""Own the signing identity retained in DSH home for source-built Computer Use applications. 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 @@ -19,12 +19,12 @@ import os from pathlib import Path import re import secrets +import shlex import shutil import subprocess import sys import tempfile -DEFAULT_DIRECTORY = Path.home() / "Library/Application Support/DeepSeek Harness/computer-use-dev-signing" COMMON_NAME = "DSH Computer Use Dev (local)" SECURITY = "/usr/bin/security" OPENSSL = "/usr/bin/openssl" @@ -94,12 +94,28 @@ def keychain_path(directory): return directory / "signing.keychain-db" -def load(directory=DEFAULT_DIRECTORY): +def default_directory(dsh_home=None): + """Use the Host-resolved home, or DSH_HOME / ~/.dsh for standalone Python commands.""" + selected = dsh_home if dsh_home is not None else os.environ.get("DSH_HOME", "") + selected = str(selected) + if not selected.strip(): + home = Path.home() / ".dsh" + elif selected == "~" or selected.startswith(("~/", "~\\")): + home = Path.home() / selected[2:] + else: + home = Path(selected) + return Path(os.path.abspath(home)) / "computer-use-dev-signing" + + +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. """ + home_argument = shlex.quote(str(directory.parent)) + setup_command = f"{SETUP_COMMAND} --dsh-home {home_argument}" + remove_command = f"{REMOVE_COMMAND} --dsh-home {home_argument}" record = record_path(directory) if not record.exists(): return None @@ -109,16 +125,16 @@ def load(directory=DEFAULT_DIRECTORY): except (ValueError, OSError): valid = False if not valid: - raise RuntimeError(f"Computer Use development signing record is invalid; run {REMOVE_COMMAND}, then {SETUP_COMMAND}") + 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}") + 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}") + 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}") + raise RuntimeError(f"Computer Use development signing certificate is missing; run {remove_command}, then {setup_command}") return SigningIdentity(sha1=fields["sha1"], keychain=keychain) @@ -153,7 +169,7 @@ def create_certificate(directory, password): return sha1 -def setup(directory=DEFAULT_DIRECTORY): +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) @@ -180,7 +196,7 @@ def setup_locked(directory): return load(directory) -def remove(directory=DEFAULT_DIRECTORY): +def remove(directory): """Delete the keychain, its search-list entry and the stored password.""" with identity_lock(directory): remove_locked(directory) @@ -200,13 +216,15 @@ def remove_locked(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"]) + parser.add_argument("--dsh-home", type=Path, help="DSH home; defaults to DSH_HOME or ~/.dsh") args = parser.parse_args() + directory = default_directory(args.dsh_home) if args.action == "setup": - identity = setup() - print(f"Prepared \"{COMMON_NAME}\" ({identity.sha1}); source builds use it when sourceSigning is local-identity") + identity = setup(directory) + print(f"Prepared \"{COMMON_NAME}\" ({identity.sha1}) in {directory}") else: - remove() - print("Removed the development signing identity; select sourceSigning: ad-hoc to prevent recreation") + remove(directory) + print("Removed the development signing identity; select ad-hoc or a user certificate to prevent recreation") if __name__ == "__main__": diff --git a/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py b/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py index 7eab63af18..0357846e06 100644 --- a/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py +++ b/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py @@ -9,7 +9,6 @@ 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 +31,14 @@ def main(): before = signing.user_keychains() with tempfile.TemporaryDirectory(prefix="cua-dev-signing-e2e-") as temporary: root = Path(temporary) - directory = root / "signing" + home = root / "home" + directory = signing.default_directory(home) try: - 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", return_value=signing): + sha1, keychain = builder.signing_identity("dev", None, "local-identity", home) + assert builder.signing_identity("dev", None, "local-identity", home) == (sha1, keychain) + assert keychain == home / "computer-use-dev-signing/signing.keychain-db" + assert (directory / "identity.json").stat().st_mode & 0o777 == 0o600 with patch.object(builder, "load_dev_signing", side_effect=AssertionError("ad-hoc accessed keychain")): assert builder.signing_identity("dev", None, "ad-hoc") == ("-", None) requirements = [] @@ -58,7 +59,12 @@ def main(): 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 - print(f"PASS: changed development builds share {first_requirement}") + with patch.object(builder, "load_dev_signing", side_effect=AssertionError("custom signing accessed managed identity")): + for index, (certificate, selected_keychain) in enumerate(((sha1, None), (signing.COMMON_NAME, keychain))): + custom_identity, custom_keychain = builder.signing_identity("dev", certificate, None, keychain=selected_keychain) + custom = builder.publish(root / "helper", root / f"custom-{index}", custom_identity, NATIVE / "Info.plist", "dev", custom_keychain) + assert requirement(custom.parents[2]) == first_requirement + print(f"PASS: DSH-home identity is reused across changed builds; user-supplied signatures share {first_requirement}") finally: signing.remove(directory) assert signing.user_keychains() == before, "the user keychain search list was not restored" diff --git a/packages/experimental/cua-macos/native/tests/test_build_app.py b/packages/experimental/cua-macos/native/tests/test_build_app.py index eeda633c5b..91a700fbb2 100644 --- a/packages/experimental/cua-macos/native/tests/test_build_app.py +++ b/packages/experimental/cua-macos/native/tests/test_build_app.py @@ -184,7 +184,7 @@ class DevelopmentPublicationTests(PublicationCases, unittest.TestCase): class SigningIdentityTests(unittest.TestCase): - def test_default_and_release_builds_never_load_a_local_identity(self): + def test_ad_hoc_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)) @@ -194,15 +194,17 @@ class SigningIdentityTests(unittest.TestCase): local = type("Identity", (), {"sha1": "ABC", "keychain": Path("/keychains/dev.keychain-db")}) signing = Mock() signing.setup.return_value = local + signing.default_directory.return_value = Path("/dsh/computer-use-dev-signing") 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() + self.assertEqual(builder.signing_identity("dev", None, "local-identity", Path("/dsh")), ("ABC", local.keychain)) + signing.default_directory.assert_called_once_with(Path("/dsh")) + signing.setup.assert_called_once_with(Path("/dsh/computer-use-dev-signing")) - def test_an_explicit_identity_overrides_either_signing_mode(self): + def test_user_certificates_do_not_load_or_modify_generated_identities(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)) + for keychain in (None, Path("/keychains/custom.keychain-db")): + self.assertEqual(builder.signing_identity("dev", "Apple Development: Example", None, keychain=keychain), + ("Apple Development: Example", keychain)) load.assert_not_called() def test_local_identity_failure_does_not_fall_back_to_ad_hoc(self): @@ -212,14 +214,40 @@ class SigningIdentityTests(unittest.TestCase): 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")): + def test_command_line_defaults_to_local_identity_and_passes_the_selected_mode(self): + for flags, mode in (([], "local-identity"), (["--signing", "ad-hoc"], "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) + identity.assert_called_once_with("dev", None, mode, None, None) + + def test_command_line_passes_a_custom_identity_and_keychain(self): + with patch.object(builder.sys, "argv", ["build_app.py", "--variant", "dev", "--identity", "Example", "--keychain", "/keychains/user.keychain-db"]), \ + patch.object(builder, "signing_identity", return_value=("Example", Path("/keychains/user.keychain-db"))) 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", "Example", "local-identity", None, Path("/keychains/user.keychain-db")) + + def test_release_command_line_keeps_ad_hoc_signing_by_default(self): + with patch.object(builder.sys, "argv", ["build_app.py"]), \ + 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("release", None, "ad-hoc", None, None) + + def test_invalid_user_signing_options_fail_before_building(self): + for flags in (["--identity", "Example", "--signing", "ad-hoc"], ["--keychain", "/keychains/user"], + ["--identity", "Example", "--keychain", "relative"], ["--identity", " "]): + with self.subTest(flags=flags), patch.object(builder.sys, "argv", ["build_app.py", *flags]), \ + patch.object(builder.subprocess, "run") as run, contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(SystemExit) as error: + builder.main() + self.assertEqual(error.exception.code, 2) + run.assert_not_called() if __name__ == "__main__": diff --git a/packages/experimental/cua-macos/native/tests/test_dev_signing.py b/packages/experimental/cua-macos/native/tests/test_dev_signing.py index bc554e2b6a..759323ed3c 100644 --- a/packages/experimental/cua-macos/native/tests/test_dev_signing.py +++ b/packages/experimental/cua-macos/native/tests/test_dev_signing.py @@ -1,4 +1,6 @@ """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 @@ -54,6 +56,29 @@ class DevelopmentSigningTests(unittest.TestCase): self.addCleanup(patcher.stop) return security + def test_signing_directory_follows_dsh_home_and_explicit_overrides(self): + home = self.root / "user" + with patch.object(Path, "home", return_value=home): + for value in ("", " "): + with patch.dict(signing.os.environ, {"DSH_HOME": value}): + self.assertEqual(signing.default_directory(), home / ".dsh/computer-use-dev-signing") + for value, expected in ((str(self.root / "custom"), self.root / "custom"), + ("~/custom", home / "custom"), ("~", home), + ("relative-home", Path(signing.os.path.abspath("relative-home")))): + with patch.dict(signing.os.environ, {"DSH_HOME": value}): + self.assertEqual(signing.default_directory(), expected / "computer-use-dev-signing") + self.assertEqual(signing.default_directory(self.root / "explicit"), + self.root / "explicit/computer-use-dev-signing") + + def test_setup_and_remove_commands_target_the_selected_dsh_home(self): + directory = self.root / "home/computer-use-dev-signing" + identity = signing.SigningIdentity("ABC123", directory / "signing.keychain-db") + for action in ("setup", "remove"): + with patch.object(signing.sys, "argv", ["dev_signing.py", action, "--dsh-home", str(directory.parent)]), \ + patch.object(signing, action, return_value=identity) as operation, contextlib.redirect_stdout(io.StringIO()): + signing.main() + operation.assert_called_once_with(directory) + def test_missing_setup_leaves_builds_unconfigured(self): self.fake([self.login]) self.assertIsNone(signing.load(self.directory)) @@ -115,7 +140,7 @@ class DevelopmentSigningTests(unittest.TestCase): def test_build_cli_stops_without_replacing_a_recorded_identity_missing_its_keychain(self): home = self.root / "home" - directory = home / "Library/Application Support/DeepSeek Harness/computer-use-dev-signing" + directory = home / "computer-use-dev-signing" directory.mkdir(parents=True) record = directory / "identity.json" before = json.dumps({"sha1": "ABC123", "password": "secret-password"}).encode() @@ -126,7 +151,7 @@ from pathlib import Path from unittest.mock import patch test_home = Path(sys.argv[2]) Path.home = lambda: test_home -sys.argv = [sys.argv[1], '--variant', 'dev', '--signing', 'local-identity', '--output-directory', sys.argv[3]] +sys.argv = [sys.argv[1], '--variant', 'dev', '--dsh-home', sys.argv[2], '--output-directory', sys.argv[3]] with patch('subprocess.run', side_effect=AssertionError('unexpected native build or signing command')): runpy.run_path(sys.argv[0], run_name='__main__') """ @@ -135,7 +160,7 @@ with patch('subprocess.run', side_effect=AssertionError('unexpected native build 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}, then {signing.SETUP_COMMAND}", result.stderr) + self.assertIn(f"run {signing.REMOVE_COMMAND} --dsh-home {home}, then {signing.SETUP_COMMAND} --dsh-home {home}", result.stderr) self.assertNotIn("Traceback", result.stderr) self.assertNotIn("secret-password", result.stderr) self.assertEqual(record.read_bytes(), before) @@ -208,7 +233,7 @@ 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'] +sys.argv = [sys.argv[1], '--variant', 'dev', '--dsh-home', 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__') """ diff --git a/packages/experimental/cua-macos/package.json b/packages/experimental/cua-macos/package.json index 7178a1a138..79397708ab 100644 --- a/packages/experimental/cua-macos/package.json +++ b/packages/experimental/cua-macos/package.json @@ -57,7 +57,8 @@ "@deepseek-ai/schemastery": "workspace:~", "zod": "^4.4.3", "@deepseek-ai/dsh-atomic-write": "workspace:*", - "@deepseek-ai/dsh-cua": "workspace:*" + "@deepseek-ai/dsh-cua": "workspace:*", + "@deepseek-ai/dsh-home-paths": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-working-directory": "workspace:*", diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index 841412eb3c..b1d3703fef 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -4,6 +4,7 @@ import { fileURLToPath } from 'node:url' import type { Context } from '@deepseek-ai/cordis' import Schema from '@deepseek-ai/schemastery' import { CuaConfig, installCua } from '@deepseek-ai/dsh-cua' +import { resolveDshHome } from '@deepseek-ai/dsh-home-paths' import { nativeHostArchitecture, prepareNativeExecutable } from './native-build.ts' import { createSharedNativeChannel } from './shared-native.ts' import { GUIDANCE } from './guidance.ts' @@ -16,17 +17,28 @@ export const inject = ['computerUse', 'tools', 'systemPrompt', 'subprocess', 'ag /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ export interface Config extends CuaConfig { /** - * 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. + * Source-build signing: `local-identity` (default) creates or reuses an identity in DSH home; + * `ad-hoc` binds grants to the code hash; an object selects an existing user-managed certificate. + * Installed packages and `helperPath` keep their own signature. */ - sourceSigning: 'ad-hoc' | 'local-identity' + sourceSigning: 'ad-hoc' | 'local-identity' | { + /** Existing codesign certificate name or SHA-1 fingerprint. */ + identity: string + /** Absolute keychain path; omission uses the user's keychain search list. The user owns unlocking it. */ + keychain?: string + } } /** Validate shared operation bounds and macOS source signing before preparing the helper. */ export const Config = Schema.object({ // Schemastery erases object field types on dict; the shared Config declares their output types. ...CuaConfig.dict as { [Key in keyof CuaConfig]: Schema }, - sourceSigning: Schema.union([Schema.const('ad-hoc'), Schema.const('local-identity')]).default('ad-hoc'), + sourceSigning: Schema.union([ + Schema.const('ad-hoc'), Schema.const('local-identity'), + Schema.object({ + identity: Schema.string().pattern(/\S/).required(), + keychain: Schema.string().pattern(/^\/.+/), + }), + ]).default('local-identity'), }) satisfies Schema, Config> const description = 'Inspect macOS permissions, select an application and window, read AX state, capture screenshots or dispatch input. Use appHandle from getApp; verify actions by reading fresh state.' @@ -47,7 +59,7 @@ export async function apply(ctx: Context, config: Config): Promise { const controller = new AbortController() const prepared = prepareNativeExecutable({ packageRoot: resolve(fileURLToPath(new URL('..', import.meta.url))), - architecture, sourceSigning: config.sourceSigning, subprocess: ctx.subprocess, + architecture, sourceSigning: config.sourceSigning, dshHome: resolveDshHome(), subprocess: ctx.subprocess, timeoutMs: config.buildTimeoutMs, graceMs: config.graceMs, signal: controller.signal, }) ctx.effect(() => async () => { diff --git a/packages/experimental/cua-macos/src/native-build.ts b/packages/experimental/cua-macos/src/native-build.ts index 7b303ce8e0..22eff6fa47 100644 --- a/packages/experimental/cua-macos/src/native-build.ts +++ b/packages/experimental/cua-macos/src/native-build.ts @@ -30,6 +30,8 @@ export interface NativeBuildSpec { architecture: NativeArchitecture /** Signature of a source-checkout build; installed packages ignore it. */ sourceSigning: Config['sourceSigning'] + /** Resolved DSH home for the automatically generated signing identity. */ + dshHome: string subprocess: Pick signal: AbortSignal timeoutMs: number @@ -82,10 +84,14 @@ export async function buildNativeExecutable(spec: NativeBuildSpec): Promise { + const signing = spec.sourceSigning + const signingArgs = typeof signing === 'string' + ? ['--signing', signing, ...(signing === 'local-identity' ? ['--dsh-home', spec.dshHome] : [])] + : ['--identity', signing.identity, ...(signing.keychain === undefined ? [] : ['--keychain', signing.keychain])] 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', '--signing', spec.sourceSigning], + '--output-directory', directory, '--arch', spec.architecture === 'x64' ? 'x86_64' : 'arm64', '--variant', 'dev', ...signingArgs], cwd: spec.packageRoot, signal, graceMs: spec.graceMs, stdio: { stdin: 'ignore', stdout: { maxBytes: 65_536 }, stderr: { maxBytes: 65_536 } }, }) diff --git a/packages/experimental/cua-macos/tests/native-build.spec.ts b/packages/experimental/cua-macos/tests/native-build.spec.ts index a01f6749de..7f195359d5 100644 --- a/packages/experimental/cua-macos/tests/native-build.spec.ts +++ b/packages/experimental/cua-macos/tests/native-build.spec.ts @@ -41,7 +41,7 @@ async function fixture(diagnostics = true) { return outcome })(), terminate, waitForExit, })) - const spec = { packageRoot, architecture: 'arm64' as const, sourceSigning: 'ad-hoc' as const, subprocess: { spawn }, signal: controller.signal, timeoutMs: 60_000, graceMs: 100 } + const spec = { packageRoot, architecture: 'arm64' as const, sourceSigning: 'ad-hoc' as const, dshHome: join(root, 'dsh-home'), 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 }, @@ -88,14 +88,25 @@ it('checks source builds on activation and maps Intel architecture to the compil await writeFile(join(f.root, 'package.json'), '{"name":"@deepseek-ai/dsh-root"}') 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(f.spawn.mock.calls[0]![0].argv.slice(-4)).toEqual(['--signing', 'local-identity', '--dsh-home', f.spec.dshHome]) expect(path).toContain(join('native', '.build', 'prepared', 'x64')) }) -it('ignores local-identity for an installed application without compiling or re-signing it', async () => { +it.each([undefined, '/keychains/custom.keychain-db'])('uses a configured certificate with keychain %s', async (keychain) => { + const f = await fixture() + await buildNativeExecutable({ ...f.spec, sourceSigning: { identity: 'Apple Development: Example', keychain } }) + const argv = f.spawn.mock.calls[0]![0].argv + expect(argv.slice(argv.indexOf('--identity'))).toEqual([ + '--identity', 'Apple Development: Example', ...(keychain === undefined ? [] : ['--keychain', keychain]), + ]) + expect(argv).not.toContain('--dsh-home') + expect(argv).not.toContain('--signing') +}) + +it.each(['local-identity', { identity: 'Apple Development: Example' }] as const)('ignores signing choice %j for an installed application', async (sourceSigning) => { const f = await fixture() const path = await publish(join(f.spec.packageRoot, 'native/bin/darwin-arm64'), f.output, 'release') - expect(await prepareNativeExecutable({ ...f.spec, sourceSigning: 'local-identity' })).toBe(path) + expect(await prepareNativeExecutable({ ...f.spec, sourceSigning })).toBe(path) expect(f.spawn).not.toHaveBeenCalled() f.controller.abort() await expect(prepareNativeExecutable(f.spec)).rejects.toThrow() diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index ff296b5186..7001a4d4cc 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -68,10 +68,16 @@ const config = { 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') +it('defaults to a generated identity and validates all three signing choices', () => { + expect(NativeProvider.Config({}).sourceSigning).toBe('local-identity') + expect(NativeProvider.Config({ sourceSigning: 'ad-hoc' }).sourceSigning).toBe('ad-hoc') expect(NativeProvider.Config({ sourceSigning: 'local-identity' }).sourceSigning).toBe('local-identity') - expect(() => NativeProvider.Config({ sourceSigning: 'developer-id' } as never)).toThrow() + for (const sourceSigning of [{ identity: 'Apple Development: Example' }, { identity: 'ABC123', keychain: '/keychains/custom.keychain-db' }]) { + expect(NativeProvider.Config({ sourceSigning }).sourceSigning).toEqual(sourceSigning) + } + for (const sourceSigning of ['developer-id', {}, { identity: '' }, { identity: ' ' }, { identity: 'Example', keychain: 'relative' }]) { + expect(() => NativeProvider.Config({ sourceSigning } as never)).toThrow() + } }) it('projects shared controls and macOS signing without adding signing to the shared schema', async () => { diff --git a/packages/experimental/cua-macos/tsconfig.json b/packages/experimental/cua-macos/tsconfig.json index 3d23cff1bf..19c545454c 100644 --- a/packages/experimental/cua-macos/tsconfig.json +++ b/packages/experimental/cua-macos/tsconfig.json @@ -22,6 +22,9 @@ }, { "path": "../../util/atomic-write" + }, + { + "path": "../../util/home-paths" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7f362b99c7..d2e16cbdf0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9861,6 +9861,9 @@ importers: '@deepseek-ai/dsh-cua': specifier: workspace:* version: link:../cua + '@deepseek-ai/dsh-home-paths': + specifier: workspace:* + version: link:../../util/home-paths '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery From 4301596be1f18d436d1301952d9a68bab02c00e4 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 30 Oct 2026 10:56:27 +0800 Subject: [PATCH 27/55] test(cua): align signing fixtures with home-aware recovery and optional keychains --- .../experimental/cua-macos/native/tests/test_dev_signing.py | 4 ++-- packages/experimental/cua-macos/tests/native-build.spec.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/experimental/cua-macos/native/tests/test_dev_signing.py b/packages/experimental/cua-macos/native/tests/test_dev_signing.py index 759323ed3c..e24d4d3c86 100644 --- a/packages/experimental/cua-macos/native/tests/test_dev_signing.py +++ b/packages/experimental/cua-macos/native/tests/test_dev_signing.py @@ -131,7 +131,7 @@ class DevelopmentSigningTests(unittest.TestCase): before = record.read_bytes() self.keychain.unlink() with patch.object(signing, "create_certificate") as create: - with self.assertRaisesRegex(RuntimeError, "keychain is missing: .*; run .*remove, then .*setup"): + with self.assertRaisesRegex(RuntimeError, "keychain is missing: .*; run .*remove --dsh-home .*, then .*setup --dsh-home "): signing.setup(self.directory) create.assert_not_called() self.assertEqual(record.read_bytes(), before) @@ -178,7 +178,7 @@ with patch('subprocess.run', side_effect=AssertionError('unexpected native build 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"): + with self.assertRaisesRegex(RuntimeError, "certificate is missing; run .*remove --dsh-home .*, then .*setup --dsh-home "): signing.setup(self.directory) self.assertTrue(self.keychain.is_file()) diff --git a/packages/experimental/cua-macos/tests/native-build.spec.ts b/packages/experimental/cua-macos/tests/native-build.spec.ts index 7f195359d5..7ce4ab0916 100644 --- a/packages/experimental/cua-macos/tests/native-build.spec.ts +++ b/packages/experimental/cua-macos/tests/native-build.spec.ts @@ -94,7 +94,7 @@ it('checks source builds on activation and maps Intel architecture to the compil it.each([undefined, '/keychains/custom.keychain-db'])('uses a configured certificate with keychain %s', async (keychain) => { const f = await fixture() - await buildNativeExecutable({ ...f.spec, sourceSigning: { identity: 'Apple Development: Example', keychain } }) + await buildNativeExecutable({ ...f.spec, sourceSigning: { identity: 'Apple Development: Example', ...(keychain === undefined ? {} : { keychain }) } }) const argv = f.spawn.mock.calls[0]![0].argv expect(argv.slice(argv.indexOf('--identity'))).toEqual([ '--identity', 'Apple Development: Example', ...(keychain === undefined ? [] : ['--keychain', keychain]), From 8cce23db442273a1b0b9d327479fc23b717a934f Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 30 Oct 2026 12:04:58 +0800 Subject: [PATCH 28/55] fix(plugin-market): retry detail clone fetches over SSH after https is refused Refs #7598 --- packages/boot/plugin-market/README.i18n.yaml | 4 +- packages/boot/plugin-market/README.md | 2 +- packages/boot/plugin-market/README.zh.md | 2 +- .../plugin-market/src/repository-cache.ts | 44 ++++++++++++++++--- .../tests/repository-cache.spec.ts | 29 ++++++++++++ 5 files changed, 70 insertions(+), 11 deletions(-) diff --git a/packages/boot/plugin-market/README.i18n.yaml b/packages/boot/plugin-market/README.i18n.yaml index fb47f93c88..162778f052 100644 --- a/packages/boot/plugin-market/README.i18n.yaml +++ b/packages/boot/plugin-market/README.i18n.yaml @@ -18,8 +18,8 @@ en: fef9850d643e327f zh: c6e8cab773cf93b9 /deepseek-ai-dsh-plugin-market/use-this-package/plugin-detail-documents: - en: 0e15de273c9acaae - zh: 4fd93c92b71d4398 + en: 6a469ad74ed69d7e + zh: f7d3f8aaed1daf88 /deepseek-ai-dsh-plugin-market/understand-the-implementation: en: 678705f57d986377 zh: 68d090edfe04acde diff --git a/packages/boot/plugin-market/README.md b/packages/boot/plugin-market/README.md index b93adc2bf9..e6af0f5e3a 100644 --- a/packages/boot/plugin-market/README.md +++ b/packages/boot/plugin-market/README.md @@ -72,7 +72,7 @@ Text matches the package name, author, keywords, and every language of the title Without any, the result is `{ status: 'none' }`. A found document carries its `origin` (`locale`, `readme`, or `repository`), its Markdown without a leading YAML front matter block, and a `document` id. Results, and the `too-large`, `denied`, and `invalid` failures that reading again would repeat, are cached for `cacheTtlMs`; `refresh` reads again instead, and concurrent reads share one read. A `document` id stays valid while a read returns it or an image request names it at least once every `cacheTtlMs`; an unused id is forgotten, and its images answer 404 until the document is read again. -Repository files are read through GitHub's raw file host for `github.com` and the GitLab repository files API for `detailGitlabHosts`. API requests follow redirects within their origin. When an API answers 401, 403, or 404, a request to the repository's smart HTTP endpoint without any credentials decides whether the repository is public; a public repository's miss means the file does not exist. A repository that needs credentials, and a repository on a host without such an API, is read from a partial clone over https, http, or ssh. Git uses the user's configuration, credential helpers, and `url..insteadOf` rules without prompting, so an https URL can be routed to ssh; ssh runs in batch mode unless `GIT_SSH` or `GIT_SSH_COMMAND` is set. +Repository files are read through GitHub's raw file host for `github.com` and the GitLab repository files API for `detailGitlabHosts`. API requests follow redirects within their origin. When an API answers 401, 403, or 404, a request to the repository's smart HTTP endpoint without any credentials decides whether the repository is public; a public repository's miss means the file does not exist. A repository that needs credentials, and a repository on a host without such an API, is read from a partial clone over https, http, or ssh. Git uses the user's configuration, credential helpers, and `url..insteadOf` rules without prompting, so an https URL can be routed to ssh. When Git refuses an http(s) URL, the clone fetches again from `ssh://git@/`, as plugin installation does, and keeps that remote; a retry that fails for any reason but the size limit reports `denied` with both diagnostics. ssh runs in batch mode unless `GIT_SSH` or `GIT_SSH_COMMAND` is set. `GET /api/plugin-market/detail-file?document=&path=` serves an image beside a read document to authenticated owner connections. The destination is relative to the document, or to the package or repository root when it starts with `/`; its query and fragment are ignored. Only PNG, JPEG, GIF, WebP, AVIF, and SVG files inside that root are served, with `Content-Security-Policy: sandbox`, `X-Content-Type-Options: nosniff`, and a private cache for `cacheTtlMs`. A missing file, unknown document, or other path answers 404; the failures below answer 413, 502, 403, 503, and 400; failure responses are not cached. diff --git a/packages/boot/plugin-market/README.zh.md b/packages/boot/plugin-market/README.zh.md index 5d82b46c77..c2972489b9 100644 --- a/packages/boot/plugin-market/README.zh.md +++ b/packages/boot/plugin-market/README.zh.md @@ -73,7 +73,7 @@ Remote 方法如下: 三者都没有时,结果为 `{ status: 'none' }`。找到的文档携带其 `origin`(`locale`、`readme` 或 `repository`)、去掉开头 YAML front matter 块后的 Markdown 内容和 `document` id。结果,以及再次读取也会重复出现的 `too-large`、`denied` 和 `invalid` 失败,缓存 `cacheTtlMs`;传入 `refresh` 时改为重新读取;并发读取共享一次读取。只要每个 `cacheTtlMs` 内至少有一次读取返回某个 `document` id 或有一次图片请求引用它,该 id 就保持有效;未使用的 id 会被遗忘,在再次读取该文档之前,其图片请求返回 404。 -`github.com` 上的仓库文件通过 GitHub 的原始文件主机读取,`detailGitlabHosts` 中主机上的仓库文件通过 GitLab 仓库文件 API 读取。API 请求跟随同一 origin 内的重定向。API 返回 401、403 或 404 时,由一次不带任何凭据、发往该仓库 smart HTTP 端点的请求判断仓库是否公开;公开仓库中未找到文件即表示该文件不存在。需要凭据的仓库,以及所在主机没有此类 API 的仓库,通过 https、http 或 ssh 从部分克隆中读取。Git 使用用户的配置、凭据助手和 `url..insteadOf` 规则,且不提示输入,因此 https URL 可能被改为通过 ssh 访问;除非设置了 `GIT_SSH` 或 `GIT_SSH_COMMAND`,ssh 以批处理模式运行。 +`github.com` 上的仓库文件通过 GitHub 的原始文件主机读取,`detailGitlabHosts` 中主机上的仓库文件通过 GitLab 仓库文件 API 读取。API 请求跟随同一 origin 内的重定向。API 返回 401、403 或 404 时,由一次不带任何凭据、发往该仓库 smart HTTP 端点的请求判断仓库是否公开;公开仓库中未找到文件即表示该文件不存在。需要凭据的仓库,以及所在主机没有此类 API 的仓库,通过 https、http 或 ssh 从部分克隆中读取。Git 使用用户的配置、凭据助手和 `url..insteadOf` 规则,且不提示输入,因此 https URL 可能被改为通过 ssh 访问。Git 拒绝 http(s) URL 时,部分克隆会像插件安装一样改从 `ssh://git@/` 再次获取,并保留该远程地址;重试因大小限制以外的原因失败时报告 `denied`,附两次的诊断。除非设置了 `GIT_SSH` 或 `GIT_SSH_COMMAND`,ssh 以批处理模式运行。 `GET /api/plugin-market/detail-file?document=&path=` 向已通过认证的 owner 连接提供已读取文档旁的图片。目标路径相对于该文档;以 `/` 开头时相对于包或仓库的根目录;路径中的查询和片段被忽略。只提供该根目录内的 PNG、JPEG、GIF、WebP、AVIF 和 SVG 文件,响应带有 `Content-Security-Policy: sandbox`、`X-Content-Type-Options: nosniff` 和时长为 `cacheTtlMs` 的私有缓存。文件不存在、文档未知或其他路径返回 404;下文所列的失败依次返回 413、502、403、503 和 400;失败响应不被缓存。 diff --git a/packages/boot/plugin-market/src/repository-cache.ts b/packages/boot/plugin-market/src/repository-cache.ts index 87a9b51b15..7ff276abd1 100644 --- a/packages/boot/plugin-market/src/repository-cache.ts +++ b/packages/boot/plugin-market/src/repository-cache.ts @@ -15,10 +15,10 @@ import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess' import { DetailFailure, readmeName, type FoundFile } from '@deepseek-ai/dsh-plugin-detail' /** - * Git deadlines one operation's lock waits for: an operation runs at most a fetch and a file read that contact the - * remote, each bounded by the deadline, plus short local commands. + * Git deadlines one operation's lock waits for: an operation runs at most a fetch, its SSH retry, and a file read that + * contact the remote, each bounded by the deadline, plus short local commands. */ -const OPERATION_COMMANDS = 4 +const OPERATION_COMMANDS = 5 /** Limits, location, and transports of the clone cache. */ export interface RepositoryCacheOptions { @@ -68,6 +68,18 @@ function remoteFailureOf(result: GitResult, label: string): DetailFailure { return new DetailFailure(NETWORK_FAILURE.test(result.diagnostic) ? 'network' : 'denied', `${label}: ${result.diagnostic}`) } +/** + * The SSH form of an http(s) repository URL: `ssh://git@/` on SSH's default port, the form plugin + * installation also falls back to. + * @returns undefined for another scheme, or a URL with credentials or a query. + */ +function sshUrlOf(url: string): string | undefined { + if (!/^https?:/iu.test(url)) return undefined + const parsed = new URL(url) + if (parsed.username !== '' || parsed.password !== '' || parsed.search !== '') return undefined + return `ssh://git@${parsed.hostname}${parsed.pathname}` +} + /** A value reused until it expires. */ interface Expiring { readonly value: T @@ -259,17 +271,35 @@ export class RepositoryCache { const head = this.heads.get(url) const known = commit ?? (head !== undefined && head.expiresAt > Date.now() ? head.value : undefined) if (known !== undefined && !(await this.git(['show-ref', '--verify', '--quiet', `refs/dsh/${known}`], repository, signal)).failed) return known - await this.fetch(repository, url, commit ?? 'HEAD', signal) + await this.fetch(repository, commit ?? 'HEAD', signal) const fetched = commit ?? (await this.run(repository, ['rev-parse', 'FETCH_HEAD'], signal)).toString('utf8').trim() await this.run(repository, ['update-ref', `refs/dsh/${fetched}`, fetched], signal) if (commit === undefined) this.heads.set(url, { value: fetched, expiresAt: Date.now() + this.options.ttlMs }) return fetched } - /** Fetch one commit without file contents. */ - private async fetch(repository: string, url: string, target: string, signal: AbortSignal): Promise { + /** + * Fetch one commit without file contents. When Git refuses an http(s) URL, the clone's remote switches to the SSH form + * of that URL and the fetch runs again, so a user with only SSH credentials for the host can read it; later reads of + * the clone keep that remote. An SSH fetch that fails for any reason but the size limit reports `denied` with both + * diagnostics. + */ + private async fetch(repository: string, target: string, signal: AbortSignal): Promise { const args = ['fetch', '--quiet', '--depth', '1', '--filter=blob:none', '--no-tags', 'origin', target] - await this.watched(repository, url, args, signal, `${url}: git fetch`) + // The remote is the URL this cache wrote, or its SSH form; neither approaches the buffer. + const remote = (await this.run(repository, ['config', 'remote.origin.url'], signal, 64 * 1024)).toString('utf8').trim() + try { + await this.watched(repository, remote, args, signal, `${remote}: git fetch`) + } catch (error) { + const ssh = sshUrlOf(remote) + if (ssh === undefined || !(error instanceof DetailFailure) || error.reason !== 'denied') throw error + await this.run(repository, ['config', 'remote.origin.url', ssh], signal) + await this.watched(repository, ssh, args, signal, `${ssh}: git fetch`).catch((sshError: unknown) => { + throw sshError instanceof DetailFailure && sshError.reason !== 'too-large' + ? new DetailFailure('denied', `${error.message}\n${sshError.message}`, { cause: sshError }) + : sshError + }) + } await this.evict(repository) } diff --git a/packages/boot/plugin-market/tests/repository-cache.spec.ts b/packages/boot/plugin-market/tests/repository-cache.spec.ts index bb57767bc3..0ecc2c338d 100644 --- a/packages/boot/plugin-market/tests/repository-cache.spec.ts +++ b/packages/boot/plugin-market/tests/repository-cache.spec.ts @@ -170,6 +170,35 @@ it('reports a repository Git cannot fetch as denied', async () => { await expect(repositories.read(source.url, source.commit, 'README.md', 100, signal)).resolves.toBeDefined() }) +it('fetches over SSH when Git refuses the https URL, and reports the https refusal when SSH also fails', async () => { + const source = repository('ssh', { 'README.md': 'over ssh', 'a.png': 'png' }) + // The cache allows no https transport, so Git refuses every https URL; the SSH form, without the https port, reaches the source. + writeFileSync(join(root, 'home', '.gitconfig'), [ + `[url "${source.url}"]`, ' insteadOf = ssh://git@git.example/team/plugin.git', + `[url "${pathToFileURL(join(root, 'missing')).href}"]`, ' insteadOf = ssh://git@git.example/team/other.git', '', + ].join('\n')) + const repositories = cache() + expect(text(await repositories.read('https://git.example:8443/team/plugin.git', undefined, 'README.md', 100, signal))).toBe('over ssh') + // The clone keeps the SSH remote for file contents it downloads later. + expect(text(await repositories.read('https://git.example:8443/team/plugin.git', source.commit, 'a.png', 100, signal))).toBe('png') + // A refused SSH fetch reports both refusals. + const refused = repositories.read('https://git.example/team/other.git', undefined, 'README.md', 100, signal) + await expectRejection(refused, { reason: 'denied' }, 'https://git.example/team/other.git: git fetch') + await expect(refused).rejects.toThrow('ssh://git@git.example/team/other.git: git fetch') + // A missing commit on a clone that already fetches over SSH is not retried. + const missing = await repositories.read('https://git.example:8443/team/plugin.git', 'f'.repeat(40), 'README.md', 100, signal).catch((error: unknown) => error) + expect(missing).toMatchObject({ reason: 'denied' }) + expect((missing as Error).message.match(/git fetch/gu)).toEqual(['git fetch']) + expect((missing as Error).message).toContain('ssh://git@git.example/team/plugin.git: git fetch') + // The SSH fetch keeps the repository limit. + const small = cache({ dir: join(root, 'small'), maxRepositoryBytes: 1, sizePollMs: 3_600_000 }) + await expect(small.read('https://git.example/team/plugin.git', undefined, 'README.md', 100, signal)).rejects.toMatchObject({ reason: 'too-large' }) + // A URL with credentials or a query has no SSH form. + for (const url of ['https://user@git.example/team/plugin.git', 'https://git.example/team/plugin.git?x=1']) { + await expectRejection(repositories.read(url, undefined, 'README.md', 100, signal), { reason: 'denied' }, `${url}: git fetch`) + } +}) + it('stops a fetch once the repository grows past its limit, and deletes the repository', async () => { const source = repository('e', { 'README.md': 'x' }) // The empty repository already exceeds one byte, so the first size check stops Git. From 51856c3f4f244bb97dadb690e909d0c502dc9b2f Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 30 Oct 2026 12:17:35 +0800 Subject: [PATCH 29/55] fix(plugin-market): keep network failures of the SSH retry retryable Refs #7598 --- packages/boot/plugin-market/README.i18n.yaml | 4 ++-- packages/boot/plugin-market/README.md | 2 +- packages/boot/plugin-market/README.zh.md | 2 +- packages/boot/plugin-market/src/index.ts | 2 +- .../boot/plugin-market/src/repository-cache.ts | 12 ++++++------ .../tests/repository-cache.spec.ts | 17 +++++++++++++++++ 6 files changed, 28 insertions(+), 11 deletions(-) diff --git a/packages/boot/plugin-market/README.i18n.yaml b/packages/boot/plugin-market/README.i18n.yaml index 162778f052..e8352139a5 100644 --- a/packages/boot/plugin-market/README.i18n.yaml +++ b/packages/boot/plugin-market/README.i18n.yaml @@ -18,8 +18,8 @@ en: fef9850d643e327f zh: c6e8cab773cf93b9 /deepseek-ai-dsh-plugin-market/use-this-package/plugin-detail-documents: - en: 6a469ad74ed69d7e - zh: f7d3f8aaed1daf88 + en: b5d96ca29cf76f31 + zh: e5099b4f694cf4c9 /deepseek-ai-dsh-plugin-market/understand-the-implementation: en: 678705f57d986377 zh: 68d090edfe04acde diff --git a/packages/boot/plugin-market/README.md b/packages/boot/plugin-market/README.md index e6af0f5e3a..cdd9b211c2 100644 --- a/packages/boot/plugin-market/README.md +++ b/packages/boot/plugin-market/README.md @@ -72,7 +72,7 @@ Text matches the package name, author, keywords, and every language of the title Without any, the result is `{ status: 'none' }`. A found document carries its `origin` (`locale`, `readme`, or `repository`), its Markdown without a leading YAML front matter block, and a `document` id. Results, and the `too-large`, `denied`, and `invalid` failures that reading again would repeat, are cached for `cacheTtlMs`; `refresh` reads again instead, and concurrent reads share one read. A `document` id stays valid while a read returns it or an image request names it at least once every `cacheTtlMs`; an unused id is forgotten, and its images answer 404 until the document is read again. -Repository files are read through GitHub's raw file host for `github.com` and the GitLab repository files API for `detailGitlabHosts`. API requests follow redirects within their origin. When an API answers 401, 403, or 404, a request to the repository's smart HTTP endpoint without any credentials decides whether the repository is public; a public repository's miss means the file does not exist. A repository that needs credentials, and a repository on a host without such an API, is read from a partial clone over https, http, or ssh. Git uses the user's configuration, credential helpers, and `url..insteadOf` rules without prompting, so an https URL can be routed to ssh. When Git refuses an http(s) URL, the clone fetches again from `ssh://git@/`, as plugin installation does, and keeps that remote; a retry that fails for any reason but the size limit reports `denied` with both diagnostics. ssh runs in batch mode unless `GIT_SSH` or `GIT_SSH_COMMAND` is set. +Repository files are read through GitHub's raw file host for `github.com` and the GitLab repository files API for `detailGitlabHosts`. API requests follow redirects within their origin. When an API answers 401, 403, or 404, a request to the repository's smart HTTP endpoint without any credentials decides whether the repository is public; a public repository's miss means the file does not exist. A repository that needs credentials, and a repository on a host without such an API, is read from a partial clone over https, http, or ssh. Git uses the user's configuration, credential helpers, and `url..insteadOf` rules without prompting, so an https URL can be routed to ssh. When Git refuses an http(s) URL, the clone fetches again from `ssh://git@/`, the SSH form plugin installation also uses, and keeps that remote; a failed retry reports both diagnostics, as `network` or `too-large` for those causes and `denied` otherwise. Opening a detail page can therefore connect over ssh to the host an index entry names; with batch mode and the default host key checking, ssh authenticates only to hosts in the user's known hosts. ssh runs in batch mode unless `GIT_SSH` or `GIT_SSH_COMMAND` is set. `GET /api/plugin-market/detail-file?document=&path=` serves an image beside a read document to authenticated owner connections. The destination is relative to the document, or to the package or repository root when it starts with `/`; its query and fragment are ignored. Only PNG, JPEG, GIF, WebP, AVIF, and SVG files inside that root are served, with `Content-Security-Policy: sandbox`, `X-Content-Type-Options: nosniff`, and a private cache for `cacheTtlMs`. A missing file, unknown document, or other path answers 404; the failures below answer 413, 502, 403, 503, and 400; failure responses are not cached. diff --git a/packages/boot/plugin-market/README.zh.md b/packages/boot/plugin-market/README.zh.md index c2972489b9..ca213854bd 100644 --- a/packages/boot/plugin-market/README.zh.md +++ b/packages/boot/plugin-market/README.zh.md @@ -73,7 +73,7 @@ Remote 方法如下: 三者都没有时,结果为 `{ status: 'none' }`。找到的文档携带其 `origin`(`locale`、`readme` 或 `repository`)、去掉开头 YAML front matter 块后的 Markdown 内容和 `document` id。结果,以及再次读取也会重复出现的 `too-large`、`denied` 和 `invalid` 失败,缓存 `cacheTtlMs`;传入 `refresh` 时改为重新读取;并发读取共享一次读取。只要每个 `cacheTtlMs` 内至少有一次读取返回某个 `document` id 或有一次图片请求引用它,该 id 就保持有效;未使用的 id 会被遗忘,在再次读取该文档之前,其图片请求返回 404。 -`github.com` 上的仓库文件通过 GitHub 的原始文件主机读取,`detailGitlabHosts` 中主机上的仓库文件通过 GitLab 仓库文件 API 读取。API 请求跟随同一 origin 内的重定向。API 返回 401、403 或 404 时,由一次不带任何凭据、发往该仓库 smart HTTP 端点的请求判断仓库是否公开;公开仓库中未找到文件即表示该文件不存在。需要凭据的仓库,以及所在主机没有此类 API 的仓库,通过 https、http 或 ssh 从部分克隆中读取。Git 使用用户的配置、凭据助手和 `url..insteadOf` 规则,且不提示输入,因此 https URL 可能被改为通过 ssh 访问。Git 拒绝 http(s) URL 时,部分克隆会像插件安装一样改从 `ssh://git@/` 再次获取,并保留该远程地址;重试因大小限制以外的原因失败时报告 `denied`,附两次的诊断。除非设置了 `GIT_SSH` 或 `GIT_SSH_COMMAND`,ssh 以批处理模式运行。 +`github.com` 上的仓库文件通过 GitHub 的原始文件主机读取,`detailGitlabHosts` 中主机上的仓库文件通过 GitLab 仓库文件 API 读取。API 请求跟随同一 origin 内的重定向。API 返回 401、403 或 404 时,由一次不带任何凭据、发往该仓库 smart HTTP 端点的请求判断仓库是否公开;公开仓库中未找到文件即表示该文件不存在。需要凭据的仓库,以及所在主机没有此类 API 的仓库,通过 https、http 或 ssh 从部分克隆中读取。Git 使用用户的配置、凭据助手和 `url..insteadOf` 规则,且不提示输入,因此 https URL 可能被改为通过 ssh 访问。Git 拒绝 http(s) URL 时,部分克隆改从 `ssh://git@/`(插件安装也使用的 SSH 形式)再次获取,并保留该远程地址;重试失败时报告两次的诊断,原因是网络或大小限制时分别报告 `network` 或 `too-large`,否则报告 `denied`。因此打开详情页可能通过 ssh 连接索引条目指定的主机;在批处理模式和默认的主机密钥检查下,ssh 只向用户 known hosts 中的主机认证。除非设置了 `GIT_SSH` 或 `GIT_SSH_COMMAND`,ssh 以批处理模式运行。 `GET /api/plugin-market/detail-file?document=&path=` 向已通过认证的 owner 连接提供已读取文档旁的图片。目标路径相对于该文档;以 `/` 开头时相对于包或仓库的根目录;路径中的查询和片段被忽略。只提供该根目录内的 PNG、JPEG、GIF、WebP、AVIF 和 SVG 文件,响应带有 `Content-Security-Policy: sandbox`、`X-Content-Type-Options: nosniff` 和时长为 `cacheTtlMs` 的私有缓存。文件不存在、文档未知或其他路径返回 404;下文所列的失败依次返回 413、502、403、503 和 400;失败响应不被缓存。 diff --git a/packages/boot/plugin-market/src/index.ts b/packages/boot/plugin-market/src/index.ts index f4f2a26c95..b64d36e702 100644 --- a/packages/boot/plugin-market/src/index.ts +++ b/packages/boot/plugin-market/src/index.ts @@ -142,7 +142,7 @@ export default class PluginMarket extends TypertRemoteService { const lifetime = this.lifetime.signal this.repositories = new RepositoryCache({ dir: cacheDir, maxRepositoryBytes: config.detailRepositoryMaxBytes, maxCacheBytes: config.detailCacheMaxBytes, - // The URL forms repositories are read from, and ssh, which `url..insteadOf` may route them to. + // The URL forms repositories are read from, and ssh, which `url..insteadOf` or the retry after a refused http(s) fetch uses. timeoutMs: config.detailGitTimeoutMs, ttlMs: config.cacheTtlMs, transports: ['https', 'http', 'ssh'], lifetime, // Bounds how far a fetch overshoots `detailRepositoryMaxBytes`; directory walks cost little at this rate. sizePollMs: 200, diff --git a/packages/boot/plugin-market/src/repository-cache.ts b/packages/boot/plugin-market/src/repository-cache.ts index 7ff276abd1..944e79fbd0 100644 --- a/packages/boot/plugin-market/src/repository-cache.ts +++ b/packages/boot/plugin-market/src/repository-cache.ts @@ -69,8 +69,8 @@ function remoteFailureOf(result: GitResult, label: string): DetailFailure { } /** - * The SSH form of an http(s) repository URL: `ssh://git@/` on SSH's default port, the form plugin - * installation also falls back to. + * The SSH form of an http(s) repository URL: `ssh://git@/` on SSH's default port, the form that + * `sshGitSpec` in `@deepseek-ai/dsh-plugin-manager` gives installation. * @returns undefined for another scheme, or a URL with credentials or a query. */ function sshUrlOf(url: string): string | undefined { @@ -281,12 +281,12 @@ export class RepositoryCache { /** * Fetch one commit without file contents. When Git refuses an http(s) URL, the clone's remote switches to the SSH form * of that URL and the fetch runs again, so a user with only SSH credentials for the host can read it; later reads of - * the clone keep that remote. An SSH fetch that fails for any reason but the size limit reports `denied` with both - * diagnostics. + * the clone keep that remote. A failed SSH fetch reports both diagnostics, as `network` or `too-large` when it failed + * for that reason and as `denied` otherwise. */ private async fetch(repository: string, target: string, signal: AbortSignal): Promise { const args = ['fetch', '--quiet', '--depth', '1', '--filter=blob:none', '--no-tags', 'origin', target] - // The remote is the URL this cache wrote, or its SSH form; neither approaches the buffer. + // The remote is the URL this cache wrote or its SSH form; 64 KiB holds any such URL. const remote = (await this.run(repository, ['config', 'remote.origin.url'], signal, 64 * 1024)).toString('utf8').trim() try { await this.watched(repository, remote, args, signal, `${remote}: git fetch`) @@ -296,7 +296,7 @@ export class RepositoryCache { await this.run(repository, ['config', 'remote.origin.url', ssh], signal) await this.watched(repository, ssh, args, signal, `${ssh}: git fetch`).catch((sshError: unknown) => { throw sshError instanceof DetailFailure && sshError.reason !== 'too-large' - ? new DetailFailure('denied', `${error.message}\n${sshError.message}`, { cause: sshError }) + ? new DetailFailure(sshError.reason === 'network' ? 'network' : 'denied', `${error.message}\n${sshError.message}`, { cause: sshError }) : sshError }) } diff --git a/packages/boot/plugin-market/tests/repository-cache.spec.ts b/packages/boot/plugin-market/tests/repository-cache.spec.ts index 0ecc2c338d..176591baaf 100644 --- a/packages/boot/plugin-market/tests/repository-cache.spec.ts +++ b/packages/boot/plugin-market/tests/repository-cache.spec.ts @@ -199,6 +199,23 @@ it('fetches over SSH when Git refuses the https URL, and reports the https refus } }) +it('reports an SSH retry that cannot connect as a network failure, and does not retry an https URL that cannot connect', async () => { + vi.stubEnv('GIT_SSH_COMMAND', 'ssh -F /dev/null -o BatchMode=yes -o ConnectTimeout=5') + for (const name of ['http_proxy', 'https_proxy', 'HTTP_PROXY', 'HTTPS_PROXY', 'all_proxy', 'ALL_PROXY']) vi.stubEnv(name, '') + writeFileSync(join(root, 'home', '.gitconfig'), [ + '[url "ssh://127.0.0.1:1/down.git"]', ' insteadOf = ssh://git@git.example/team/down.git', + '[url "http://127.0.0.1:1/offline.git"]', ' insteadOf = https://git.example/team/offline.git', + '[http]', ' proxy =', '', + ].join('\n')) + const refused = cache().read('https://git.example/team/down.git', undefined, 'README.md', 100, signal) + await expectRejection(refused, { reason: 'network' }, 'https://git.example/team/down.git: git fetch') + await expect(refused).rejects.toThrow('ssh://git@git.example/team/down.git: git fetch') + const offline = await cache({ transports: ['http', 'ssh'] }).read('https://git.example/team/offline.git', undefined, 'README.md', 100, signal) + .catch((error: unknown) => error) + expect(offline).toMatchObject({ reason: 'network' }) + expect((offline as Error).message).not.toContain('ssh://') +}) + it('stops a fetch once the repository grows past its limit, and deletes the repository', async () => { const source = repository('e', { 'README.md': 'x' }) // The empty repository already exceeds one byte, so the first size check stops Git. From 6d33eb56ca48e2add4477ec65f284ca94fad50c5 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 30 Oct 2026 13:41:02 +0800 Subject: [PATCH 30/55] refactor(cua): move fixed signing setup into a developer skill --- ...6-10-29-cua-dev-signing-identity.i18n.yaml | 12 +-- .../2026-10-29-cua-dev-signing-identity.md | 10 +-- .../2026-10-29-cua-dev-signing-identity.zh.md | 10 +-- .agents/skills/dsh-cua-macos-signing/SKILL.md | 64 +++++++++++++++ .../scripts/signing_e2e.py | 29 +++---- .../scripts/signing_identity.py | 34 +++----- .../scripts/test_signing_identity.py | 58 +++++--------- docs/config-catalog.md | 12 +-- docs/config-catalog.zh.md | 12 +-- .../cua-source-dev-helper/guide.i18n.yaml | 8 +- .../cua-source-dev-helper/guide.md | 8 +- .../cua-source-dev-helper/guide.zh.md | 10 +-- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 9 ++- packages/experimental/cua-macos/README.zh.md | 9 ++- .../cua-macos/native/README.i18n.yaml | 8 +- .../experimental/cua-macos/native/README.md | 10 +-- .../cua-macos/native/README.zh.md | 10 +-- .../cua-macos/native/build_app.py | 35 +------- .../cua-macos/native/tests/test_build_app.py | 79 ++++++------------- packages/experimental/cua-macos/package.json | 6 +- packages/experimental/cua-macos/src/index.ts | 19 +++-- .../cua-macos/src/native-build.ts | 6 +- .../cua-macos/tests/native-build.spec.ts | 17 ++-- .../tests/native-publication.spec.ts | 7 -- .../tests/provider-lifecycle.spec.ts | 17 ++-- packages/experimental/cua-macos/tsconfig.json | 3 - pnpm-lock.yaml | 3 - scripts/cua-macos-signing.spec.ts | 11 +++ 29 files changed, 243 insertions(+), 277 deletions(-) create mode 100644 .agents/skills/dsh-cua-macos-signing/SKILL.md rename packages/experimental/cua-macos/native/tests/dev_signing_e2e.py => .agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py (66%) rename packages/experimental/cua-macos/native/dev_signing.py => .agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py (87%) rename packages/experimental/cua-macos/native/tests/test_dev_signing.py => .agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py (80%) create mode 100644 scripts/cua-macos-signing.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml index 4a7241cbd7..210d7f2be5 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml @@ -9,11 +9,11 @@ en: a24857a312482724 zh: dbac75d363670e86 /agent-note-development-signing-identity-for-source-built-cua-helpers/decision: - en: f83e1ec19e7b8783 - zh: 843c911c6531cb17 + en: 6e34d4c1e4816a7c + zh: 1f00b046832e19be /agent-note-development-signing-identity-for-source-built-cua-helpers/alternatives-considered: - en: 88dc1b86ce9aa018 - zh: 4f940dbc16331f3e + en: e30db5bc9c7aab43 + zh: fa84883b5527334e /agent-note-development-signing-identity-for-source-built-cua-helpers/consequences: - en: e2950b9e0698a0b0 - zh: c9c304ef59086784 + en: fb0e8fe44890bdf9 + zh: d9e9ace1a4c10060 diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md index 66a5748de2..93dcdf2451 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md @@ -12,17 +12,17 @@ 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`, 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 `ad-hoc`, default `local-identity`, or `{ identity, keychain? }` for an existing certificate. The generated identity and password live under `$DSH_HOME/computer-use-dev-signing`, using `~/.dsh` when no home is configured. The first build creates the certificate and later builds using that home reuse it. The Host uses the shared home-path resolver and passes the result to Python. Ad-hoc and user-certificate modes do not read or create the generated identity; users own unlocking and maintaining their certificates. +`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. -Setup creates a self-signed certificate in a dedicated keychain, stores a random password in a `0600` file, permits codesign through the key partition list, and adds the keychain to the user search list. Automatic builds unlock it before signing to avoid password or key-access dialogs. A file lock serializes setup and removal within the same home. A recorded identity with a missing keychain is preserved and rejected until the user explicitly removes it. The signing requirement contains the bundle identifier and certificate, independent of code hash or path for builds using that certificate. +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. -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. `--identity` selects user-certificate signing and is mutually exclusive with `--signing`. +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. -**Ad-hoc signing by default.** This avoids storing a private key but can require new grants when binaries change. Automatic fixed signing removes manual certificate setup from ordinary source builds; ad-hoc signing remains an explicit option. +**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. @@ -32,4 +32,4 @@ Certificate signatures embed a signing time even without a timestamp server. Dev ## Consequences -Automatic builds using the same DSH home share a signing requirement; actual permission retention across rebuilds and worktrees still needs manual verification. Other processes of the same user can read the password and sign with the development identity; the release helper uses a different bundle identifier. Deleting DSH home removes the generated identity, so the next build creates another certificate and needs new grants; home reset therefore clears signing state too. System permission entries and the keychain search entry survive directory deletion; subsequent setup removes a stale search entry at the same path. Select ad-hoc or user-certificate signing before explicit removal to prevent regeneration. The real signing e2e checks requirements across output directories, user-selected certificates, and search-list restoration after removal. +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. diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md index 370175a7ad..02d107c56d 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md @@ -12,17 +12,17 @@ Status: implemented 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`、默认的 `local-identity`,以及指定已有证书的 `{ identity, keychain? }`。自动身份及密码存放在 `$DSH_HOME/computer-use-dev-signing`,未配置 home 时使用 `~/.dsh`;首次构建创建证书,此后同一 home 的构建都复用它。Host 使用公共 home 路径解析器并把结果传给 Python。临时签名和用户证书模式不读取或创建自动身份。用户证书的解锁和维护由用户负责。 +`sourceSigning` 由 macOS provider 定义,只接受默认的 `ad-hoc` 和指定已有证书及钥匙串绝对路径的 `{ identity, keychain }`。构建不创建、解锁或移除身份。开发者凭据与面向用户的 DSH home 分开,后者只保存选择证书的配置;共享 `cua` 包不持有 macOS 签名配置。 -初始化在专用钥匙串中创建自签名证书,将随机密码存入权限为 `0600` 的文件,通过密钥分区列表允许 `codesign` 访问,并把钥匙串加入用户搜索列表。自动构建每次签名前用保存的密码解锁,避免密码或密钥访问窗口。同一 home 的初始化和移除使用文件锁串行执行。已有身份记录但钥匙串缺失时保留记录并报错,只有用户显式移除后才允许重新生成。签名要求包含 Bundle ID 和证书,使用同一证书的构建不依赖代码哈希或路径。 +[开发者签名 skill](../../../skills/dsh-cua-macos-signing/SKILL.md)指导 Agent 在 `~/.cua-macos-keys/` 创建、复用和解锁独立身份,将证书指纹和钥匙串路径写入用户配置。工具把随机密码存入 `0600` 文件,允许 codesign 访问私钥,并把专用钥匙串加入用户搜索列表。文件锁让同一目录的初始化和移除串行执行;已有记录但钥匙串缺失时保留记录并报错。 -即使不使用时间戳服务器,证书签名也会写入签名时间。开发版发布时记录每个未签名应用与签名身份对应的目录,再次构建时直接选中该目录,不重新签名,因此相同源码保持同一个可执行文件摘要和同一个共享服务。缓存使用证书指纹;显式证书名称可能对应续期后的证书,因此不复用缓存。签名初始化失败会中止构建;异常信息不包含密码或完整命令参数。`--identity` 选择用户证书签名,与 `--signing` 互斥。 +即使不使用时间戳服务器,证书签名也包含签名时间。开发构建记录每份未签名内容与身份对应的已签名目录,再次构建相同内容时复用该目录,保持可执行文件摘要和共享服务一致。缓存使用证书指纹;按证书名称选择时每次签名,避免续期后复用旧证书。签名失败会中止发布。开发者工具的诊断不包含密码或完整命令参数;构建 CLI 默认 `--identity -`,支持指定证书,正式打包也可省略 `--keychain`。 ## 考虑过的替代方案 **把权限交给启动终端。** 直接启动服务时,macOS 把权限归属到启动 DSH 的终端或编辑器。该应用运行的所有程序,包括模型执行的命令,都会带上这些权限。 -**默认临时签名。** 可以避免保存私钥,但二进制变化后可能需要重新授权。默认自动生成固定身份,让普通源码构建无需手动准备证书;临时签名仍可显式选择。 +**源码构建自动创建固定身份。** 这会让普通启动生成开发者私钥,并把身份生命周期绑定到用户数据目录。显式开发者操作保留了减少重新授权的选择,也让证书的创建、移除和使用范围由开发者决定。 **把自签名身份放进登录钥匙串。** 登录钥匙串已解锁且在搜索列表中,但要让 `codesign` 不弹窗地使用其中的新私钥,需要用户的登录密码。 @@ -32,4 +32,4 @@ Host 以开发版构建源码检出,Bundle ID 为 `com.deepseek.harness.comput ## 后果 -使用同一 DSH home 的自动签名构建共用签名要求,实际授权在重建和跨 worktree 后是否保留仍需手动验证。同一用户的进程能读取密码并使用开发身份签名,正式 helper 使用不同的 Bundle ID。删除 DSH home 会删除自动身份,下次构建生成新证书并需要重新授权;这也让 home 重置能清除签名状态。系统设置中的授权和钥匙串搜索条目不随目录删除而消失;后续初始化会清理同路径的失效搜索条目。主动移除身份前需选择临时签名或用户证书,以免下次构建重新生成。真实签名 e2e 核对不同输出目录的构建共用要求、用户指定证书可用,以及移除后搜索列表恢复。 +同一证书签出的开发构建共用签名要求;授权后重建和跨 worktree 的实际权限保持仍需验证。同一用户的进程可读取保存的密码并使用该身份签名,正式 helper 使用不同的 Bundle ID。删除 DSH home 只移除配置,不删除开发者身份;删除该身份后应清理所有引用它的配置。真实签名 e2e 验证复用、解锁、不同输出目录的签名要求和移除后的搜索列表恢复。 diff --git a/.agents/skills/dsh-cua-macos-signing/SKILL.md b/.agents/skills/dsh-cua-macos-signing/SKILL.md new file mode 100644 index 0000000000..1c2233cafe --- /dev/null +++ b/.agents/skills/dsh-cua-macos-signing/SKILL.md @@ -0,0 +1,64 @@ +--- +name: dsh-cua-macos-signing +description: Set up, reuse, unlock, or remove a local macOS Computer Use development signing identity and configure source builds to use it across worktrees. Use when developing the CUA helper or reducing repeated macOS permission grants; release signing and notarization use their packaging workflow. +--- + +# macOS CUA development signing + +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. Supply `--directory ` when the developer chose another location outside DSH home and the checkout. + +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: "" + keychain: "/Users//.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- ` 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 the dedicated keychain, its search-list entry, and password record; 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. diff --git a/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py b/.agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py similarity index 66% rename from packages/experimental/cua-macos/native/tests/dev_signing_e2e.py rename to .agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py index 0357846e06..81aa85b7f4 100644 --- a/packages/experimental/cua-macos/native/tests/dev_signing_e2e.py +++ b/.agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py @@ -9,13 +9,12 @@ from pathlib import Path import plistlib import subprocess import tempfile -from unittest.mock import patch -NATIVE = Path(__file__).resolve().parents[1] +NATIVE = Path(__file__).resolve().parents[4] / "packages/experimental/cua-macos/native" def module(name): - spec = importlib.util.spec_from_file_location(name, NATIVE / f"{name}.py") + 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 @@ -31,16 +30,14 @@ def main(): before = signing.user_keychains() with tempfile.TemporaryDirectory(prefix="cua-dev-signing-e2e-") as temporary: root = Path(temporary) - home = root / "home" - directory = signing.default_directory(home) + directory = root / "keys/dev" try: - with patch.object(builder, "load_dev_signing", return_value=signing): - sha1, keychain = builder.signing_identity("dev", None, "local-identity", home) - assert builder.signing_identity("dev", None, "local-identity", home) == (sha1, keychain) - assert keychain == home / "computer-use-dev-signing/signing.keychain-db" + identity = signing.setup(directory) + assert signing.setup(directory) == identity + sha1, keychain = identity.sha1, identity.keychain assert (directory / "identity.json").stat().st_mode & 0o777 == 0o600 - with patch.object(builder, "load_dev_signing", side_effect=AssertionError("ad-hoc accessed keychain")): - assert builder.signing_identity("dev", None, "ad-hoc") == ("-", None) + 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") @@ -59,12 +56,10 @@ def main(): 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 - with patch.object(builder, "load_dev_signing", side_effect=AssertionError("custom signing accessed managed identity")): - for index, (certificate, selected_keychain) in enumerate(((sha1, None), (signing.COMMON_NAME, keychain))): - custom_identity, custom_keychain = builder.signing_identity("dev", certificate, None, keychain=selected_keychain) - custom = builder.publish(root / "helper", root / f"custom-{index}", custom_identity, NATIVE / "Info.plist", "dev", custom_keychain) - assert requirement(custom.parents[2]) == first_requirement - print(f"PASS: DSH-home identity is reused across changed builds; user-supplied signatures share {first_requirement}") + 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: signing.remove(directory) assert signing.user_keychains() == before, "the user keychain search list was not restored" diff --git a/packages/experimental/cua-macos/native/dev_signing.py b/.agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py similarity index 87% rename from packages/experimental/cua-macos/native/dev_signing.py rename to .agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py index 695e5f59b0..e57dbecef3 100644 --- a/packages/experimental/cua-macos/native/dev_signing.py +++ b/.agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py @@ -1,4 +1,4 @@ -"""Own the signing identity retained in DSH home for source-built Computer Use applications. +"""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 @@ -28,8 +28,8 @@ import tempfile 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" +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 @@ -94,17 +94,9 @@ def keychain_path(directory): return directory / "signing.keychain-db" -def default_directory(dsh_home=None): - """Use the Host-resolved home, or DSH_HOME / ~/.dsh for standalone Python commands.""" - selected = dsh_home if dsh_home is not None else os.environ.get("DSH_HOME", "") - selected = str(selected) - if not selected.strip(): - home = Path.home() / ".dsh" - elif selected == "~" or selected.startswith(("~/", "~\\")): - home = Path.home() / selected[2:] - else: - home = Path(selected) - return Path(os.path.abspath(home)) / "computer-use-dev-signing" +def default_directory(): + """Keep developer credentials independent of DSH profiles, homes, and worktrees.""" + return Path.home() / ".cua-macos-keys" / "dev" def load(directory): @@ -113,9 +105,9 @@ def load(directory): 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. """ - home_argument = shlex.quote(str(directory.parent)) - setup_command = f"{SETUP_COMMAND} --dsh-home {home_argument}" - remove_command = f"{REMOVE_COMMAND} --dsh-home {home_argument}" + 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 @@ -216,15 +208,15 @@ def remove_locked(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"]) - parser.add_argument("--dsh-home", type=Path, help="DSH home; defaults to DSH_HOME or ~/.dsh") + parser.add_argument("--directory", type=Path, default=default_directory(), help="identity directory; defaults to ~/.cua-macos-keys/dev") args = parser.parse_args() - directory = default_directory(args.dsh_home) + directory = args.directory.expanduser().resolve() if args.action == "setup": identity = setup(directory) - print(f"Prepared \"{COMMON_NAME}\" ({identity.sha1}) in {directory}") + print(json.dumps({"identity": identity.sha1, "keychain": str(identity.keychain)}, indent=2)) else: remove(directory) - print("Removed the development signing identity; select ad-hoc or a user certificate to prevent recreation") + print("Removed the development signing identity; remove its sourceSigning configuration before the next build") if __name__ == "__main__": diff --git a/packages/experimental/cua-macos/native/tests/test_dev_signing.py b/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py similarity index 80% rename from packages/experimental/cua-macos/native/tests/test_dev_signing.py rename to .agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py index e24d4d3c86..054d935981 100644 --- a/packages/experimental/cua-macos/native/tests/test_dev_signing.py +++ b/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py @@ -10,7 +10,7 @@ import tempfile import unittest from unittest.mock import patch -spec = importlib.util.spec_from_file_location("dev_signing", Path(__file__).resolve().parents[1] / "dev_signing.py") +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) @@ -56,28 +56,24 @@ class DevelopmentSigningTests(unittest.TestCase): self.addCleanup(patcher.stop) return security - def test_signing_directory_follows_dsh_home_and_explicit_overrides(self): + def test_default_identity_is_outside_dsh_home(self): home = self.root / "user" with patch.object(Path, "home", return_value=home): - for value in ("", " "): + for value in ("", str(self.root / "custom-dsh-home")): with patch.dict(signing.os.environ, {"DSH_HOME": value}): - self.assertEqual(signing.default_directory(), home / ".dsh/computer-use-dev-signing") - for value, expected in ((str(self.root / "custom"), self.root / "custom"), - ("~/custom", home / "custom"), ("~", home), - ("relative-home", Path(signing.os.path.abspath("relative-home")))): - with patch.dict(signing.os.environ, {"DSH_HOME": value}): - self.assertEqual(signing.default_directory(), expected / "computer-use-dev-signing") - self.assertEqual(signing.default_directory(self.root / "explicit"), - self.root / "explicit/computer-use-dev-signing") + self.assertEqual(signing.default_directory(), home / ".cua-macos-keys/dev") + self.assertFalse(home.exists()) - def test_setup_and_remove_commands_target_the_selected_dsh_home(self): - directory = self.root / "home/computer-use-dev-signing" + 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", ["dev_signing.py", action, "--dsh-home", str(directory.parent)]), \ - patch.object(signing, action, return_value=identity) as operation, contextlib.redirect_stdout(io.StringIO()): + 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]) @@ -97,7 +93,7 @@ class DevelopmentSigningTests(unittest.TestCase): def test_unlisted_or_missing_keychains_fail_with_the_setup_command(self): security = self.configure(listed=False) - with self.assertRaisesRegex(RuntimeError, "search list; run pnpm"): + with self.assertRaisesRegex(RuntimeError, "search list; run python3"): signing.load(self.directory) self.keychain.unlink() with self.assertRaisesRegex(RuntimeError, "keychain is missing"): @@ -131,41 +127,29 @@ class DevelopmentSigningTests(unittest.TestCase): before = record.read_bytes() self.keychain.unlink() with patch.object(signing, "create_certificate") as create: - with self.assertRaisesRegex(RuntimeError, "keychain is missing: .*; run .*remove --dsh-home .*, then .*setup --dsh-home "): + 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_build_cli_stops_without_replacing_a_recorded_identity_missing_its_keychain(self): - home = self.root / "home" - directory = home / "computer-use-dev-signing" + def test_setup_cli_preserves_a_recorded_identity_missing_its_keychain(self): + directory = self.root / "keys/dev" directory.mkdir(parents=True) record = directory / "identity.json" before = json.dumps({"sha1": "ABC123", "password": "secret-password"}).encode() record.write_bytes(before) - output = self.root / "applications" - script = """import runpy, sys -from pathlib import Path -from unittest.mock import patch -test_home = Path(sys.argv[2]) -Path.home = lambda: test_home -sys.argv = [sys.argv[1], '--variant', 'dev', '--dsh-home', sys.argv[2], '--output-directory', sys.argv[3]] -with patch('subprocess.run', side_effect=AssertionError('unexpected native build or signing command')): - runpy.run_path(sys.argv[0], run_name='__main__') -""" - result = subprocess.run([sys.executable, "-c", script, str(Path(signing.__file__).with_name("build_app.py")), str(home), str(output)], + 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} --dsh-home {home}, then {signing.SETUP_COMMAND} --dsh-home {home}", 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()) - self.assertFalse(output.exists()) def test_remove_restores_the_other_search_list_entries_and_deletes_the_password(self): security = self.configure() @@ -178,7 +162,7 @@ with patch('subprocess.run', side_effect=AssertionError('unexpected native build 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 --dsh-home .*, then .*setup --dsh-home "): + with self.assertRaisesRegex(RuntimeError, "certificate is missing; run .*remove --directory .*, then .*setup --directory "): signing.setup(self.directory) self.assertTrue(self.keychain.is_file()) @@ -227,18 +211,18 @@ with open(sys.argv[1], 'w') as lock: with signing.identity_lock(self.directory): pass - def test_build_cli_reports_signing_timeout_without_traceback_or_password(self): + 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], '--variant', 'dev', '--dsh-home', sys.argv[2]] +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__).with_name("build_app.py")), str(self.root / "home")], + 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) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 1376532b60..898f56086f 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1113,21 +1113,21 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:18`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:17`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ export interface Config extends CuaConfig { /** - * Source-build signing: `local-identity` (default) creates or reuses an identity in DSH home; - * `ad-hoc` binds grants to the code hash; an object selects an existing user-managed certificate. + * 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: 'ad-hoc' | 'local-identity' | { + sourceSigning: 'ad-hoc' | { /** Existing codesign certificate name or SHA-1 fingerprint. */ identity: string - /** Absolute keychain path; omission uses the user's keychain search list. The user owns unlocking it. */ - keychain?: string + /** Absolute keychain path. The developer owns creating and unlocking it. */ + keychain: string } } ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 4ca609fc14..0d26019979 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1115,21 +1115,21 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:18`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:17`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ export interface Config extends CuaConfig { /** - * Source-build signing: `local-identity` (default) creates or reuses an identity in DSH home; - * `ad-hoc` binds grants to the code hash; an object selects an existing user-managed certificate. + * 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: 'ad-hoc' | 'local-identity' | { + sourceSigning: 'ad-hoc' | { /** Existing codesign certificate name or SHA-1 fingerprint. */ identity: string - /** Absolute keychain path; omission uses the user's keychain search list. The user owns unlocking it. */ - keychain?: string + /** Absolute keychain path. The developer owns creating and unlocking it. */ + keychain: string } } ``` diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml index 2021a137ed..1e9d8c17c2 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 72a8ea364f7427fa zh: 9e7ed2e00425bddb /source-built-computer-use-helper-identity/change: - en: 14b5363428db53fe - zh: 58f7ba480871197e + en: c1aa84364896b994 + zh: a4559c563d995b2b /source-built-computer-use-helper-identity/migration: - en: e5dd3a1a5825fc8c - zh: 494ef3db1feb9a18 + en: a86e330ab60ef800 + zh: ce32e1959ca707fc diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md index 3d6bacc71d..92d0339b4e 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.md @@ -9,11 +9,11 @@ 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 now generate a fixed signing identity under `$DSH_HOME/computer-use-dev-signing` by default and reuse it; an unset `DSH_HOME` uses `~/.dsh`. +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. Default `sourceSigning: local-identity` needs no manual setup; use the same DSH home across worktrees to share the identity. For ad-hoc signing, set `config.sourceSigning: ad-hoc` on `id: cua` in `cordis.patch.yml`. For an existing certificate, use the [user-signing configuration](../../../../packages/experimental/cua-macos/README.md#use-this-package). +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`. Remove an old `DSH Computer Use` entry only when no installed DSH uses it. -4. To stop using the generated identity, select ad-hoc or user-certificate signing, then run `pnpm --dir packages/experimental/cua-macos run dev-signing:remove`. Select a custom home with the same `DSH_HOME` or `--dsh-home `. Deleting DSH home causes a new certificate on the next build and requires new grants. +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. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md index dd79e7fab8..64552b7524 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-alpha.2/cua-source-dev-helper/guide.zh.md @@ -9,11 +9,11 @@ description: "源码构建的 Computer Use helper 使用独立的开发版 Bundl ## 变更 -此前源码检出构建的 `DSH Computer Use.app` 使用正式版 Bundle ID `com.deepseek.harness.computer-use` 和临时签名。现在构建的是 `DSH Computer Use Dev.app`,Bundle ID 为 `com.deepseek.harness.computer-use.dev`。旧条目上的辅助功能和屏幕录制授权不适用于它。桌面端和 npm 安装版不变。 源码构建现在默认在 `$DSH_HOME/computer-use-dev-signing` 中生成并复用固定签名身份,未设置 `DSH_HOME` 时使用 `~/.dsh`。 +源码检出原先以临时签名构建 `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: local-identity` 无需手动 setup;各 worktree 使用同一 DSH home 即可复用身份。如需临时签名,在 `cordis.patch.yml` 的 `id: cua` 节点设置 `config.sourceSigning: ad-hoc`;如需已有证书,使用[用户签名配置](../../../../packages/experimental/cua-macos/README.zh.md#use-this-package)。 -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`。自定义 home 通过同一个 `DSH_HOME` 或 `--dsh-home <路径>` 指定。删除 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 不会删除开发者钥匙串。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index fa9cd3f06b..0f7875235b 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 6390cd271bbb64fe zh: 342f4f6aa617809f /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: 7e29c174a0712fa2 - zh: 086cb1d75b6d2d08 + en: ceb982af46176a87 + zh: de39943183dad724 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: 786b8fd630b11e5f zh: 55143f15486afce8 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 1b5fe9dabb..f23091005e 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -39,23 +39,24 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. 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. The helper needs Accessibility permission for AX/input and Screen Recording permission for capture; grant these permissions to the helper when prompted. Source builds use the bundle filename `DSH Computer Use Dev.app` and declare `DSH Computer Use Dev` in Info.plist; select the development entry 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 `sourceSigning: local-identity`: the first build generates an identity under `$DSH_HOME/computer-use-dev-signing`, and later builds and worktrees using that home reuse it. An unset `DSH_HOME` uses `~/.dsh`. Select `sourceSigning: ad-hoc` for temporary signatures, or choose an existing certificate in the profile’s `cordis.patch.yml` as below; `cua` is the entry ID loading `@deepseek-ai/dsh-experimental-cua-macos`: +Source builds default to `sourceSigning: ad-hoc`, without creating certificates or keychains. Changed binaries can require new permission grants. To reduce repeated grants during rebuilds and across worktrees, select an existing certificate and its absolute keychain path in the DSH home’s `cordis.patch.yml`; `cua` is the entry ID loading `@deepseek-ai/dsh-experimental-cua-macos`: ```yaml - id: cua config: sourceSigning: - identity: "Apple Development: Your name (TEAMID)" + identity: "" + keychain: "/Users//.cua-macos-keys/dev/signing.keychain-db" ``` -Replace `identity` with an existing certificate name or SHA-1 fingerprint. Optional `keychain` selects an absolute keychain path; omission uses the user search list, and the user owns unlocking it. Custom signing does not create, unlock or modify the generated identity. Automatic signing stores a private key and password accessible to other processes of the same user; see [development signing](native/README.md#build-and-service). +`identity` is an existing certificate name or SHA-1 fingerprint; `keychain` is a required absolute path. Developers own creating and unlocking the keychain; builds only use the selected certificate. Preserve the entry’s other configuration fields when merging this patch. The repository’s [developer signing skill](../../../.agents/skills/dsh-cua-macos-signing/SKILL.md) guides Agents through creating, reusing, and removing identities under `~/.cua-macos-keys/`, with only their selection stored in DSH home. | 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` | `local-identity` | Source signing: a generated identity, `ad-hoc`, or `{ identity, keychain? }` for an existing certificate. Ignored for installed packages and `helperPath`. | +| `sourceSigning` | `ad-hoc` | Source signing: `ad-hoc`, or `{ identity, keychain }` for an existing certificate and keychain path. 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. | diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 3d53491649..da07676e46 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -39,23 +39,24 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. 配置输出命令不发起模型请求。执行真实任务时,将 `--dump-config` 替换为任务提示,并配置该 profile 的模型凭据。配置挂载 computer-use 注册表和本 provider;使用前需移除已有的竞争 provider。helper 需要辅助功能权限来读取 AX 和输入,需要屏幕录制权限来截图;按系统提示给 helper 授权。源码构建的应用包名为 `DSH Computer Use Dev.app`,Info.plist 声明名称 `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` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。 -源码构建默认使用 `sourceSigning: local-identity`:首次构建在 `$DSH_HOME/computer-use-dev-signing` 中生成固定身份,后续构建和使用同一 DSH home 的 worktree 复用它。未设置 `DSH_HOME` 时使用 `~/.dsh`。临时签名可配置为 `sourceSigning: ad-hoc`;已有签名证书可在 profile 的 `cordis.patch.yml` 中这样选择,`cua` 是加载 `@deepseek-ai/dsh-experimental-cua-macos` 的节点 ID: +源码构建默认使用 `sourceSigning: ad-hoc` 临时签名,不创建证书或钥匙串。二进制变化后可能需要重新授权。需要减少开发重建和跨 worktree 的授权次数时,在 DSH home 的 `cordis.patch.yml` 中选择已有证书及其钥匙串绝对路径;`cua` 是加载 `@deepseek-ai/dsh-experimental-cua-macos` 的节点 ID: ```yaml - id: cua config: sourceSigning: - identity: "Apple Development: Your name (TEAMID)" + identity: "" + keychain: "/Users//.cua-macos-keys/dev/signing.keychain-db" ``` -将 `identity` 替换为已有证书的名称或 SHA-1 指纹。可选的 `keychain` 指定钥匙串绝对路径;省略时使用用户钥匙串搜索列表,解锁由用户负责。自定义证书模式不会创建、解锁或修改自动生成的身份。自动模式会保存私钥和密码,同一用户的进程可以读取并使用它们;详见[开发签名](native/README.zh.md#build-and-service)。 +`identity` 是已有证书名称或 SHA-1 指纹,`keychain` 是必填的绝对路径。开发者负责生成和解锁钥匙串;构建只使用所选证书。合并配置时保留该节点已有的其他字段。仓库的[开发者签名 skill](../../../.agents/skills/dsh-cua-macos-signing/SKILL.md)指导 Agent 在 `~/.cua-macos-keys/` 中生成、复用和移除身份,并只将选择身份的配置写入 DSH home。 | 字段 | 默认值 | 含义 | | --- | --- | --- | | `agentPreset` | `ptc` | 仅为绑定该 preset 的 Agent 注册工具和指引;`false` 表示全局注册。 | | `allowedApps` | `[]` | 旧路径和签名许可,只导入 profile 存储一次供撤销,不授予新 Bundle ID 身份访问权限。 | | `helperPath` | 包内可执行文件 | 已签名 helper `.app` 内可执行文件的绝对路径;裸二进制会触发 `NATIVE_APPLICATION_REQUIRED`。 | -| `sourceSigning` | `local-identity` | 源码签名:自动生成固定身份、`ad-hoc` 临时签名,或 `{ identity, keychain? }` 指定已有证书。安装版和 `helperPath` 忽略此项。 | +| `sourceSigning` | `ad-hoc` | 源码签名:`ad-hoc` 临时签名,或 `{ identity, keychain }` 指定已有证书及钥匙串路径。安装版和 `helperPath` 忽略此项。 | | `buildTimeoutMs` | `300000` | 原生组件准备的最长时间。 | | `timeoutMs` | `30000` | 单次操作截止时间,取消后可能已发生部分输入。 | | `connectTimeoutMs` | `5000` | 连接或启动共享 helper 的截止时间。 | diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 5187c56956..70cb779505 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -15,8 +15,8 @@ en: e8cbc43d38786c40 zh: 52b3ba85d98011b9 /dsh-cua-native-helper/build-and-service: - en: e673418383f64b0c - zh: f27e4ac4b868da16 + en: 1dca32fdeba46e0f + zh: c82d4c92ccdde367 /dsh-cua-native-helper/request-protocol: en: fc8043c425322cdd zh: cf1edb9a78fda301 @@ -24,8 +24,8 @@ en: 27f23e6f3b77ee64 zh: 9cd1fdc76e9f041e /dsh-cua-native-helper/verification: - en: c2ad240e2ce1962f - zh: 4a0cb0b30df98b71 + en: 32d832fd7a9a60a7 + zh: e80b5e47fd60cc8f /dsh-cua-native-helper/further-exploration: en: 265e1927952ce6d7 zh: 7c35d9fd98b6e6c8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 531da35f16..fcdf6f5c54 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -25,13 +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-`. 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`, producing `DSH Computer Use Dev.app` with bundle identifier `com.deepseek.harness.computer-use.dev`. Development builds default to `local-identity`, generating a fixed identity on first use. Explicit `--signing ad-hoc` uses a temporary signature without accessing the generated identity. Ad-hoc requirements contain the code hash, so changed binaries can require new grants. +Source checkouts build with `--variant dev`, producing `DSH Computer Use Dev.app` with bundle identifier `com.deepseek.harness.computer-use.dev`. Development and release builds default to ad-hoc signing. Ad-hoc requirements contain the code hash, so changed binaries can require new grants. -Automatic mode creates or reuses the `DSH Computer Use Dev (local)` certificate in a dedicated keychain under `$DSH_HOME/computer-use-dev-signing` and adds the keychain to the user search list. The Host passes `--dsh-home` from the shared home-path resolver; standalone Python commands use `--dsh-home`, a nonblank `DSH_HOME`, then `~/.dsh`. The identity, password and lock file stay inside that home, with setup and removal serialized per home. Each build unlocks the keychain using the adjacent `0600` identity record. Other processes of the same user can read the password and sign code. The designated requirement contains the bundle identifier and certificate; actual grant retention after rebuilds and across worktrees still needs manual verification. +The source provider’s `sourceSigning: { identity, keychain }` selects an existing certificate and its absolute keychain path. The build CLI accepts `--identity ` and `--keychain `; release packaging may also omit `--keychain` to use the user search list. Builds do not create, unlock or remove identities; signing fails when the selected certificate is unavailable. -User-certificate mode uses `sourceSigning: { identity, keychain? }`, or CLI `--identity `. Optional `--keychain ` selects a keychain; otherwise the user search list applies. The build does not create certificates, read the generated identity or unlock user keychains. `--identity` and `--signing` are mutually exclusive. Release builds retain their ad-hoc default and support explicit certificates. +The repository’s [developer signing skill](../../../../.agents/skills/dsh-cua-macos-signing/SKILL.md) owns the Agent workflow: generate an isolated identity under `~/.cua-macos-keys/`, write its selection into DSH home, and unlock or remove it when requested. Developers maintain the private key and password separately; deleting DSH home does not delete them. Other processes of the same user can read the stored password and sign with that identity. -`pnpm --dir packages/experimental/cua-macos run dev-signing:setup` can generate the automatic identity in advance. `dev-signing:remove` deletes that home’s identity, password and keychain search entry, retaining the empty lock file. Both commands accept `--dsh-home `. Select ad-hoc or user-certificate signing before removal to prevent regeneration. Deleting DSH home also deletes its identity; a new certificate needs new grants. An existing record with a missing keychain or certificate is preserved and fails with commands to explicitly remove and initialize that home again. Remove system permission entries separately in System Settings. +Builds using the same certificate share a designated requirement containing the bundle identifier and certificate. The first permission grant remains manual in System Settings; equal requirements do not replace actual permission checks after rebuilds and across worktrees. 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. @@ -129,7 +129,7 @@ Desktop checks require grants for the selected helper: release builds declare `D 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. +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. Developer signing unit tests run through `scripts/cua-macos-signing.spec.ts`; the [developer signing skill](../../../../.agents/skills/dsh-cua-macos-signing/SKILL.md) owns the real-signing verification command. 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. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index e5eaf92180..e55cceb4ee 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -25,13 +25,13 @@ kind: "package-reference" 运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-` 下生成带签名的 `DSH Computer Use.app`,`current.json` 选择完整的内容摘要目录。默认使用临时签名;正式打包可传入 `--identity` 指定 Developer ID,并由发布流程完成公证。Host 运行应用内的 `--ensure-shared` 入口,经 LaunchServices 后台启动服务。最后一条连接完成清理后,服务退出。 -源码检出以 `--variant dev` 构建,应用包为 `DSH Computer Use Dev.app`,Bundle ID 为 `com.deepseek.harness.computer-use.dev`。开发版默认使用 `local-identity`,首次构建自动生成固定身份;显式 `--signing ad-hoc` 使用临时签名,不访问自动身份。临时签名的指定要求包含代码哈希,二进制变化后可能需要重新授权。 +源码检出以 `--variant dev` 构建,应用包为 `DSH Computer Use Dev.app`,Bundle ID 为 `com.deepseek.harness.computer-use.dev`。开发版和正式版默认临时签名。临时签名的指定要求包含代码哈希,二进制变化后可能需要重新授权。 -自动模式在 `$DSH_HOME/computer-use-dev-signing` 下的专用钥匙串中创建或复用 `DSH Computer Use Dev (local)` 证书,并把钥匙串加入用户搜索列表。Host 通过公共 home 路径解析器传入 `--dsh-home`;独立 Python 命令依次使用 `--dsh-home`、非空 `DSH_HOME`、`~/.dsh`。身份、密码和锁文件都在该 home 内,文件锁让同一 home 的初始化与移除串行执行。每次构建使用旁边权限为 `0600` 的身份记录解锁钥匙串。同一用户的进程可以读取密码并签名。指定要求包含 Bundle ID 和证书,重新编译和跨 worktree 后实际保留授权的效果仍需手动验证。 +源码 provider 的 `sourceSigning: { identity, keychain }` 选择已有证书及其钥匙串绝对路径。构建 CLI 使用 `--identity <证书名称或 SHA-1 指纹>` 和 `--keychain <绝对路径>`;正式打包也可省略 `--keychain`,使用用户搜索列表。构建不生成、解锁或移除签名身份;所选证书不可用时签名失败。 -用户证书模式使用 `sourceSigning: { identity, keychain? }`,或命令行 `--identity <证书名称或 SHA-1 指纹>`。可选的 `--keychain <绝对路径>` 指定钥匙串,否则使用用户搜索列表。构建不创建证书,不读取自动身份,也不解锁用户钥匙串。`--identity` 与 `--signing` 不能同时指定;正式构建仍默认临时签名,并支持指定证书。 +仓库的[开发者签名 skill](../../../../.agents/skills/dsh-cua-macos-signing/SKILL.md)负责 Agent 操作流程:在 `~/.cua-macos-keys/` 生成独立身份,将指向它的配置写入 DSH home,并按需解锁或移除。私钥和密码由开发者单独维护,删除 DSH home 不会删除它们。同一用户的进程可以读取保存的密码并使用该身份签名。 -`pnpm --dir packages/experimental/cua-macos run dev-signing:setup` 可提前生成自动身份;`dev-signing:remove` 删除当前 DSH home 中的身份、密码和钥匙串搜索条目,保留空锁文件。两条命令均接受 `--dsh-home <路径>`。停止使用自动身份时,先选择临时签名或用户证书,否则下次构建会重新生成身份。删除 DSH home 也会删除身份,新证书需要重新授权。已有记录但钥匙串或证书缺失时,构建保留记录并报错,提示使用该 home 明确移除后重新初始化;系统设置中的授权需单独移除。 +使用相同证书的构建共用包含 Bundle ID 和证书的指定要求。首次授权仍需在系统设置中完成;签名要求相同不代替授权后重建、跨 worktree 的实际权限验证。 证书签名包含签名时间。开发构建在 `sources/` 中记录每个未签名应用与证书指纹对应的目录,内容不变时复用该目录。临时签名使用独立记录。显式传入证书名称时会重新签名,因为续期可能改变名称对应的证书。 @@ -129,7 +129,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 运行 `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/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` 验证应用发布、开发版构建、已签名目录复用、签名失败和损坏副本拒绝。开发者签名工具的单测由 `scripts/cua-macos-signing.spec.ts` 执行;真实签名验证命令见[开发者签名 skill](../../../../.agents/skills/dsh-cua-macos-signing/SKILL.md)。 运行 `python3 packages/experimental/cua-macos/native/tests/shared_helper_e2e.py --helper /absolute/helper`,通过测试自建的 AppKit fixture 核实并发启动、共享服务 PID、独立句柄、同一应用交接、请求级截图期限、连接清理和信号退出。需要已经给所选的正式版或开发版 helper 授予辅助功能和屏幕录制权限。`--without-desktop` 将检查限定为协议与进程生命期。 diff --git a/packages/experimental/cua-macos/native/build_app.py b/packages/experimental/cua-macos/native/build_app.py index 45f1510061..e4e2393d9c 100644 --- a/packages/experimental/cua-macos/native/build_app.py +++ b/packages/experimental/cua-macos/native/build_app.py @@ -1,7 +1,6 @@ """Build, sign and publish immutable Computer Use application generations.""" import argparse import hashlib -import importlib.util import json import os from pathlib import Path @@ -114,26 +113,6 @@ def publish(binary, output, identity, plist, variant="release", keychain=None): return select(output, temporary, key, name) -def load_dev_signing(): - """Load the sibling module whether this file runs as a script or is imported by path.""" - location = Path(__file__).resolve().with_name("dev_signing.py") - spec = importlib.util.spec_from_file_location("dev_signing", location) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def signing_identity(variant, identity, signing, dsh_home=None, keychain=None): - """Select a user certificate, an ad-hoc signature, or an identity retained in DSH home.""" - if identity is not None: - return identity, keychain - if variant == "release" or signing == "ad-hoc": - return "-", None - signing_module = load_dev_signing() - local = signing_module.setup(signing_module.default_directory(dsh_home)) - return local.sha1, local.keychain - - def main(): root = Path(__file__).resolve().parent parser = argparse.ArgumentParser(description=__doc__) @@ -142,26 +121,20 @@ def main(): parser.add_argument("--output-directory", type=Path) parser.add_argument("--variant", choices=["release", "dev"], default="release", help="dev uses a separate bundle identifier") - signing_options = parser.add_mutually_exclusive_group() - signing_options.add_argument("--signing", choices=["ad-hoc", "local-identity"], - help="defaults to local-identity for dev and ad-hoc for release") - signing_options.add_argument("--identity", help="existing codesign certificate name or SHA-1 fingerprint") + parser.add_argument("--identity", default="-", help="existing codesign certificate name or SHA-1 fingerprint; defaults to ad-hoc (-)") parser.add_argument("--keychain", type=Path, help="absolute keychain path for --identity; the user owns unlocking it") - parser.add_argument("--dsh-home", type=Path, help="home for local-identity; defaults to DSH_HOME or ~/.dsh") args = parser.parse_args() - if args.identity is not None and not args.identity.strip(): + if not args.identity.strip(): parser.error("--identity must name an existing certificate") - if args.keychain is not None and (args.identity is None or not args.keychain.is_absolute()): + if args.keychain is not None and (args.identity == "-" or not args.keychain.is_absolute()): parser.error("--keychain requires --identity and an absolute path") 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}" - signing = args.signing or ("local-identity" if args.variant == "dev" else "ad-hoc") - identity, keychain = signing_identity(args.variant, args.identity, signing, args.dsh_home, args.keychain) 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) - executable = publish(scratch / "release/dsh-cua-native", output, identity, root / "Info.plist", args.variant, keychain) + executable = publish(scratch / "release/dsh-cua-native", output, args.identity, root / "Info.plist", args.variant, args.keychain) print(executable) diff --git a/packages/experimental/cua-macos/native/tests/test_build_app.py b/packages/experimental/cua-macos/native/tests/test_build_app.py index 91a700fbb2..61408164ed 100644 --- a/packages/experimental/cua-macos/native/tests/test_build_app.py +++ b/packages/experimental/cua-macos/native/tests/test_build_app.py @@ -8,7 +8,7 @@ import plistlib import secrets import tempfile import unittest -from unittest.mock import Mock, patch +from unittest.mock import 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) @@ -168,7 +168,7 @@ class DevelopmentPublicationTests(PublicationCases, unittest.TestCase): 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): + def test_switching_between_ad_hoc_and_configured_identity_selects_the_matching_generation(self): ad_hoc = self.publish("-") local = self.publish() self.assertNotEqual(local, ad_hoc) @@ -183,65 +183,30 @@ class DevelopmentPublicationTests(PublicationCases, unittest.TestCase): self.assertEqual(len(self.signings()), 2) -class SigningIdentityTests(unittest.TestCase): - def test_ad_hoc_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_local_identity_builds_create_or_reuse_the_identity(self): - local = type("Identity", (), {"sha1": "ABC", "keychain": Path("/keychains/dev.keychain-db")}) - signing = Mock() - signing.setup.return_value = local - signing.default_directory.return_value = Path("/dsh/computer-use-dev-signing") - with patch.object(builder, "load_dev_signing", return_value=signing): - self.assertEqual(builder.signing_identity("dev", None, "local-identity", Path("/dsh")), ("ABC", local.keychain)) - signing.default_directory.assert_called_once_with(Path("/dsh")) - signing.setup.assert_called_once_with(Path("/dsh/computer-use-dev-signing")) - - def test_user_certificates_do_not_load_or_modify_generated_identities(self): - with patch.object(builder, "load_dev_signing") as load: - for keychain in (None, Path("/keychains/custom.keychain-db")): - self.assertEqual(builder.signing_identity("dev", "Apple Development: Example", None, keychain=keychain), - ("Apple Development: Example", keychain)) - load.assert_not_called() - - 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_local_identity_and_passes_the_selected_mode(self): - for flags, mode in (([], "local-identity"), (["--signing", "ad-hoc"], "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"), \ +class SigningOptionsTests(unittest.TestCase): + def test_default_dev_and_release_builds_use_ad_hoc_without_keychain_commands(self): + for variant in ("dev", "release"): + with self.subTest(variant=variant), patch.object(builder.sys, "argv", ["build_app.py", "--variant", variant]), \ + patch.object(builder.subprocess, "run") as run, patch.object(builder, "publish", return_value="helper") as publish, \ contextlib.redirect_stdout(io.StringIO()): builder.main() - identity.assert_called_once_with("dev", None, mode, None, None) + self.assertEqual(len(run.call_args_list), 1) + self.assertEqual(run.call_args.args[0][:3], ["/usr/bin/xcrun", "swift", "build"]) + self.assertEqual(publish.call_args.args[2], "-") + self.assertEqual(publish.call_args.args[4:], (variant, None)) - def test_command_line_passes_a_custom_identity_and_keychain(self): - with patch.object(builder.sys, "argv", ["build_app.py", "--variant", "dev", "--identity", "Example", "--keychain", "/keychains/user.keychain-db"]), \ - patch.object(builder, "signing_identity", return_value=("Example", Path("/keychains/user.keychain-db"))) 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", "Example", "local-identity", None, Path("/keychains/user.keychain-db")) + def test_custom_certificate_and_keychain_reach_the_signer(self): + for flags, keychain in (([], None), (["--keychain", "/keychains/user.keychain-db"], Path("/keychains/user.keychain-db"))): + with patch.object(builder.sys, "argv", ["build_app.py", "--variant", "dev", "--identity", "Example", *flags]), \ + patch.object(builder.subprocess, "run"), patch.object(builder, "publish", return_value="helper") as publish, \ + contextlib.redirect_stdout(io.StringIO()): + builder.main() + self.assertEqual(publish.call_args.args[2], "Example") + self.assertEqual(publish.call_args.args[4:], ("dev", keychain)) - def test_release_command_line_keeps_ad_hoc_signing_by_default(self): - with patch.object(builder.sys, "argv", ["build_app.py"]), \ - 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("release", None, "ad-hoc", None, None) - - def test_invalid_user_signing_options_fail_before_building(self): - for flags in (["--identity", "Example", "--signing", "ad-hoc"], ["--keychain", "/keychains/user"], - ["--identity", "Example", "--keychain", "relative"], ["--identity", " "]): + def test_invalid_or_retired_signing_options_fail_before_building(self): + for flags in (["--signing", "local-identity"], ["--dsh-home", "/home/example"], + ["--keychain", "/keychains/user"], ["--identity", "Example", "--keychain", "relative"], ["--identity", " "]): with self.subTest(flags=flags), patch.object(builder.sys, "argv", ["build_app.py", *flags]), \ patch.object(builder.subprocess, "run") as run, contextlib.redirect_stderr(io.StringIO()): with self.assertRaises(SystemExit) as error: diff --git a/packages/experimental/cua-macos/package.json b/packages/experimental/cua-macos/package.json index 79397708ab..fab269c217 100644 --- a/packages/experimental/cua-macos/package.json +++ b/packages/experimental/cua-macos/package.json @@ -31,7 +31,6 @@ "native/Info.plist", "native/DSHComputerUse.icns", "native/build_app.py", - "native/dev_signing.py", "native/Sources", "native/tests/swift", "native/tests/test_swift.py", @@ -57,8 +56,7 @@ "@deepseek-ai/schemastery": "workspace:~", "zod": "^4.4.3", "@deepseek-ai/dsh-atomic-write": "workspace:*", - "@deepseek-ai/dsh-cua": "workspace:*", - "@deepseek-ai/dsh-home-paths": "workspace:*" + "@deepseek-ai/dsh-cua": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-working-directory": "workspace:*", @@ -100,8 +98,6 @@ }, "scripts": { "build:native": "xcrun python3 native/build_app.py", - "dev-signing:setup": "xcrun python3 native/dev_signing.py setup", - "dev-signing:remove": "xcrun python3 native/dev_signing.py remove", "build:icon": "node native/generate_icon.mjs" }, "os": [ diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index b1d3703fef..9c366d5084 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -4,7 +4,6 @@ import { fileURLToPath } from 'node:url' import type { Context } from '@deepseek-ai/cordis' import Schema from '@deepseek-ai/schemastery' import { CuaConfig, installCua } from '@deepseek-ai/dsh-cua' -import { resolveDshHome } from '@deepseek-ai/dsh-home-paths' import { nativeHostArchitecture, prepareNativeExecutable } from './native-build.ts' import { createSharedNativeChannel } from './shared-native.ts' import { GUIDANCE } from './guidance.ts' @@ -17,15 +16,15 @@ export const inject = ['computerUse', 'tools', 'systemPrompt', 'subprocess', 'ag /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ export interface Config extends CuaConfig { /** - * Source-build signing: `local-identity` (default) creates or reuses an identity in DSH home; - * `ad-hoc` binds grants to the code hash; an object selects an existing user-managed certificate. + * 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: 'ad-hoc' | 'local-identity' | { + sourceSigning: 'ad-hoc' | { /** Existing codesign certificate name or SHA-1 fingerprint. */ identity: string - /** Absolute keychain path; omission uses the user's keychain search list. The user owns unlocking it. */ - keychain?: string + /** Absolute keychain path. The developer owns creating and unlocking it. */ + keychain: string } } /** Validate shared operation bounds and macOS source signing before preparing the helper. */ @@ -33,12 +32,12 @@ export const Config = Schema.object({ // Schemastery erases object field types on dict; the shared Config declares their output types. ...CuaConfig.dict as { [Key in keyof CuaConfig]: Schema }, sourceSigning: Schema.union([ - Schema.const('ad-hoc'), Schema.const('local-identity'), + Schema.const('ad-hoc'), Schema.object({ identity: Schema.string().pattern(/\S/).required(), - keychain: Schema.string().pattern(/^\/.+/), + keychain: Schema.string().pattern(/^\/.+/).required(), }), - ]).default('local-identity'), + ]).default('ad-hoc'), }) satisfies Schema, Config> const description = 'Inspect macOS permissions, select an application and window, read AX state, capture screenshots or dispatch input. Use appHandle from getApp; verify actions by reading fresh state.' @@ -59,7 +58,7 @@ export async function apply(ctx: Context, config: Config): Promise { const controller = new AbortController() const prepared = prepareNativeExecutable({ packageRoot: resolve(fileURLToPath(new URL('..', import.meta.url))), - architecture, sourceSigning: config.sourceSigning, dshHome: resolveDshHome(), subprocess: ctx.subprocess, + architecture, sourceSigning: config.sourceSigning, subprocess: ctx.subprocess, timeoutMs: config.buildTimeoutMs, graceMs: config.graceMs, signal: controller.signal, }) ctx.effect(() => async () => { diff --git a/packages/experimental/cua-macos/src/native-build.ts b/packages/experimental/cua-macos/src/native-build.ts index 22eff6fa47..b12db84a0f 100644 --- a/packages/experimental/cua-macos/src/native-build.ts +++ b/packages/experimental/cua-macos/src/native-build.ts @@ -30,8 +30,6 @@ export interface NativeBuildSpec { architecture: NativeArchitecture /** Signature of a source-checkout build; installed packages ignore it. */ sourceSigning: Config['sourceSigning'] - /** Resolved DSH home for the automatically generated signing identity. */ - dshHome: string subprocess: Pick signal: AbortSignal timeoutMs: number @@ -86,8 +84,8 @@ export async function buildNativeExecutable(spec: NativeBuildSpec): Promise { const signing = spec.sourceSigning const signingArgs = typeof signing === 'string' - ? ['--signing', signing, ...(signing === 'local-identity' ? ['--dsh-home', spec.dshHome] : [])] - : ['--identity', signing.identity, ...(signing.keychain === undefined ? [] : ['--keychain', signing.keychain])] + ? ['--identity', '-'] + : ['--identity', signing.identity, '--keychain', signing.keychain] const handle = spec.subprocess.spawn({ argv: ['/usr/bin/xcrun', 'python3', join(nativeRoot, 'build_app.py'), '--scratch-path', join(nativeRoot, '.build', `runtime-${spec.architecture}`), diff --git a/packages/experimental/cua-macos/tests/native-build.spec.ts b/packages/experimental/cua-macos/tests/native-build.spec.ts index 7ce4ab0916..2d657374d6 100644 --- a/packages/experimental/cua-macos/tests/native-build.spec.ts +++ b/packages/experimental/cua-macos/tests/native-build.spec.ts @@ -41,7 +41,7 @@ async function fixture(diagnostics = true) { return outcome })(), terminate, waitForExit, })) - const spec = { packageRoot, architecture: 'arm64' as const, sourceSigning: 'ad-hoc' as const, dshHome: join(root, 'dsh-home'), 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', '--signing', 'ad-hoc', + '--output-directory', f.directory, '--arch', 'arm64', '--variant', 'dev', '--identity', '-', ]) expect(f.terminate).toHaveBeenCalledTimes(1) expect(f.waitForExit).toHaveBeenCalledTimes(1) @@ -86,24 +86,25 @@ 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', sourceSigning: 'local-identity' }) + const path = await prepareNativeExecutable({ ...f.spec, architecture: 'x64' }) expect(f.spawn.mock.calls[0]![0].argv).toContain('x86_64') - expect(f.spawn.mock.calls[0]![0].argv.slice(-4)).toEqual(['--signing', 'local-identity', '--dsh-home', f.spec.dshHome]) + expect(f.spawn.mock.calls[0]![0].argv.slice(-2)).toEqual(['--identity', '-']) expect(path).toContain(join('native', '.build', 'prepared', 'x64')) }) -it.each([undefined, '/keychains/custom.keychain-db'])('uses a configured certificate with keychain %s', async (keychain) => { +it('uses a configured certificate in the specified keychain', async () => { + const keychain = '/keychains/custom.keychain-db' const f = await fixture() - await buildNativeExecutable({ ...f.spec, sourceSigning: { identity: 'Apple Development: Example', ...(keychain === undefined ? {} : { keychain }) } }) + await buildNativeExecutable({ ...f.spec, sourceSigning: { identity: 'Apple Development: Example', keychain } }) const argv = f.spawn.mock.calls[0]![0].argv expect(argv.slice(argv.indexOf('--identity'))).toEqual([ - '--identity', 'Apple Development: Example', ...(keychain === undefined ? [] : ['--keychain', keychain]), + '--identity', 'Apple Development: Example', '--keychain', keychain, ]) expect(argv).not.toContain('--dsh-home') expect(argv).not.toContain('--signing') }) -it.each(['local-identity', { identity: 'Apple Development: Example' }] as const)('ignores signing choice %j for an installed application', async (sourceSigning) => { +it.each(['ad-hoc', { identity: 'Apple Development: Example', keychain: '/keychains/custom.keychain-db' }] as const)('ignores signing choice %j for an installed application', async (sourceSigning) => { const f = await fixture() const path = await publish(join(f.spec.packageRoot, 'native/bin/darwin-arm64'), f.output, 'release') expect(await prepareNativeExecutable({ ...f.spec, sourceSigning })).toBe(path) diff --git a/packages/experimental/cua-macos/tests/native-publication.spec.ts b/packages/experimental/cua-macos/tests/native-publication.spec.ts index 1013f06072..0b80ab04f5 100644 --- a/packages/experimental/cua-macos/tests/native-publication.spec.ts +++ b/packages/experimental/cua-macos/tests/native-publication.spec.ts @@ -10,13 +10,6 @@ it.skipIf(process.platform === 'win32')('preserves signed generations and reject expect(output).toBe('') }) -it.skipIf(process.platform === 'win32')('keeps one unlocked development signing identity on the user keychain search list', () => { - const output = execFileSync('python3', [fileURLToPath(new URL('../native/tests/test_dev_signing.py', import.meta.url))], { - encoding: 'utf8', timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'], - }) - expect(output).toBe('') -}) - it.skipIf(process.platform === 'win32')('accepts shallow bare reference paths in native test helpers', () => { const output = execFileSync('python3', [fileURLToPath(new URL('../native/tests/test_native_test_support.py', import.meta.url))], { encoding: 'utf8', timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'], diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 7001a4d4cc..89a99c5de3 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -62,20 +62,19 @@ vi.mock('@deepseek-ai/dsh-cua/native-client', async importOriginal => ({ const config = { agentPreset: false, - 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, + helperPath: resolve('fixture-helper'), sourceSigning: 'ad-hoc', 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 const { helperPath: _helperPath, ...automaticConfig } = config -it('defaults to a generated identity and validates all three signing choices', () => { - expect(NativeProvider.Config({}).sourceSigning).toBe('local-identity') +it('defaults to ad-hoc signing and requires a keychain path for certificate signing', () => { + expect(NativeProvider.Config({}).sourceSigning).toBe('ad-hoc') expect(NativeProvider.Config({ sourceSigning: 'ad-hoc' }).sourceSigning).toBe('ad-hoc') - expect(NativeProvider.Config({ sourceSigning: 'local-identity' }).sourceSigning).toBe('local-identity') - for (const sourceSigning of [{ identity: 'Apple Development: Example' }, { identity: 'ABC123', keychain: '/keychains/custom.keychain-db' }]) { + for (const sourceSigning of [{ identity: 'Apple Development: Example', keychain: '/keychains/custom.keychain-db' }, { identity: 'ABC123', keychain: '/keychains/custom.keychain-db' }]) { expect(NativeProvider.Config({ sourceSigning }).sourceSigning).toEqual(sourceSigning) } - for (const sourceSigning of ['developer-id', {}, { identity: '' }, { identity: ' ' }, { identity: 'Example', keychain: 'relative' }]) { + for (const sourceSigning of ['local-identity', 'developer-id', {}, { identity: 'Example' }, { identity: '' }, { identity: ' ' }, { identity: 'Example', keychain: 'relative' }]) { expect(() => NativeProvider.Config({ sourceSigning } as never)).toThrow() } }) @@ -88,8 +87,8 @@ it('projects shared controls and macOS signing without adding signing to the sha } expect(CuaConfig({})).not.toHaveProperty('sourceSigning') expect(CuaConfig.dict).not.toHaveProperty('sourceSigning') - expect(NativeProvider.Config({ sourceSigning: 'local-identity', timeoutMs: 1234 })).toMatchObject({ - agentPreset: 'ptc', sourceSigning: 'local-identity', timeoutMs: 1234, + expect(NativeProvider.Config({ sourceSigning: 'ad-hoc', timeoutMs: 1234 })).toMatchObject({ + agentPreset: 'ptc', sourceSigning: 'ad-hoc', timeoutMs: 1234, }) }) @@ -609,7 +608,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.prepare.mock.calls[0]![0].sourceSigning).toBe('ad-hoc') expect(native.instances).toHaveLength(0) await f.execute() expect(native.instances).toHaveLength(1) diff --git a/packages/experimental/cua-macos/tsconfig.json b/packages/experimental/cua-macos/tsconfig.json index 19c545454c..3d23cff1bf 100644 --- a/packages/experimental/cua-macos/tsconfig.json +++ b/packages/experimental/cua-macos/tsconfig.json @@ -22,9 +22,6 @@ }, { "path": "../../util/atomic-write" - }, - { - "path": "../../util/home-paths" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 859dbbcb1a..af6fb24532 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9879,9 +9879,6 @@ importers: '@deepseek-ai/dsh-cua': specifier: workspace:* version: link:../cua - '@deepseek-ai/dsh-home-paths': - specifier: workspace:* - version: link:../../util/home-paths '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery diff --git a/scripts/cua-macos-signing.spec.ts b/scripts/cua-macos-signing.spec.ts new file mode 100644 index 0000000000..02725c7efc --- /dev/null +++ b/scripts/cua-macos-signing.spec.ts @@ -0,0 +1,11 @@ +/** Exercise developer signing tooling without reading or mutating real keychains. */ +import { execFileSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { expect, it } from 'vitest' + +it.skipIf(process.platform === 'win32')('creates, reuses, and removes developer identities outside DSH home', () => { + const output = execFileSync('python3', [fileURLToPath(new URL('../.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py', import.meta.url))], { + encoding: 'utf8', timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'], + }) + expect(output).toBe('') +}) From 850c035fd145db33f640528cef9dc5821dba4236 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 30 Oct 2026 13:42:46 +0800 Subject: [PATCH 31/55] test(cua): verify developer signing CLI with canonical paths --- .agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py | 4 ++++ .../dsh-cua-macos-signing/scripts/test_signing_identity.py | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py b/.agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py index 81aa85b7f4..29a6c0a2ce 100644 --- a/.agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py +++ b/.agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py @@ -8,6 +8,7 @@ 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" @@ -32,7 +33,10 @@ def main(): 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 diff --git a/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py b/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py index 054d935981..11a476011e 100644 --- a/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py +++ b/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py @@ -38,7 +38,7 @@ class DevelopmentSigningTests(unittest.TestCase): def setUp(self): temporary = tempfile.TemporaryDirectory(prefix="cua-dev-signing-") self.addCleanup(temporary.cleanup) - self.root = Path(temporary.name) + 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" From f2ad80451d1809684f137f2c13f45d263a4b01ca Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 30 Oct 2026 13:45:29 +0800 Subject: [PATCH 32/55] build(cua): exclude developer signing tools from package files --- scripts/check-workspace-constraints.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index 98fbaf81ec..c3bcaf5a1a 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -191,7 +191,7 @@ const packageFileExtras: Readonly> = { '@deepseek-ai/dsh-experimental-subagent-oar': ['LICENSE-OAR'], // CUA publishes its client API and attributed native source for local macOS builds. '@deepseek-ai/dsh-cua': ['lib/remote-types.js', 'lib/api.js', 'lib/bridge.js', 'lib/native-client.js', 'lib/protocol.js'], - '@deepseek-ai/dsh-experimental-cua-macos': ['native/bin', 'cua-helper.json', 'native/Package.swift', 'native/Info.plist', 'native/DSHComputerUse.icns', 'native/build_app.py', 'native/dev_signing.py', 'native/Sources', 'native/tests/swift', 'native/tests/test_swift.py', 'native/LICENSE.cua-driver', 'native/LICENSE.computer-use-icon', 'native/upstream.json', 'native/README.md', 'native/README.zh.md', 'native/protocol.schema.json'], + '@deepseek-ai/dsh-experimental-cua-macos': ['native/bin', 'cua-helper.json', 'native/Package.swift', 'native/Info.plist', 'native/DSHComputerUse.icns', 'native/build_app.py', 'native/Sources', 'native/tests/swift', 'native/tests/test_swift.py', 'native/LICENSE.cua-driver', 'native/LICENSE.computer-use-icon', 'native/upstream.json', 'native/README.md', 'native/README.zh.md', 'native/protocol.schema.json'], '@deepseek-ai/dsh-webhook-github': ['examples/github-review/cordis.yml', 'examples/github-review/github-ready-review-rule.mjs'], // Liveshare publishes its built Relay gateway entry and the shared runtime // chunk that entry imports, plus the declaration-plane entry and its chunk. From dec3a642dfd62e11e77bb5b81a117fe5bd004e86 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 30 Oct 2026 13:57:21 +0800 Subject: [PATCH 33/55] test(plugin-market): make Git probe timeout classification deterministic --- .../tests/repository-cache.spec.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/boot/plugin-market/tests/repository-cache.spec.ts b/packages/boot/plugin-market/tests/repository-cache.spec.ts index bb57767bc3..501ce07d51 100644 --- a/packages/boot/plugin-market/tests/repository-cache.spec.ts +++ b/packages/boot/plugin-market/tests/repository-cache.spec.ts @@ -5,10 +5,16 @@ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync, sym import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { pathToFileURL } from 'node:url' +import * as subprocess from 'execa' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { DetailFailure } from '@deepseek-ai/dsh-plugin-detail' import { RepositoryCache, type RepositoryCacheOptions } from '../src/repository-cache.ts' +vi.mock('execa', async (original) => { + const module = await original() + return { ...module, execa: vi.fn(module.execa) } +}) + /** Await a rejection that matches `fields` and whose message contains `message`. */ async function expectRejection(promise: Promise, fields: object, message: string): Promise { await expect(promise).rejects.toMatchObject(fields) @@ -149,9 +155,18 @@ it('reports an unreachable host as a network failure, a failed local command as await expect(broken).rejects.toThrow('git update-ref') await expect(broken).rejects.not.toBeInstanceOf(DetailFailure) expect(readdirSync(join(root, 'cache'))).toEqual([]) - // Git that cannot answer `git --version` within the deadline cannot run. const other = repository('t2', { 'README.md': 'x' }) - await expectRejection(cache({ timeoutMs: 1 }).read(other.url, other.commit, 'README.md', 100, signal), { reason: 'git-unavailable' }, 'timed out') + // A real 1 ms deadline can expire during either the version probe or a later Git command. + const probe = vi.spyOn(subprocess, 'execa').mockResolvedValueOnce({ + failed: true, shortMessage: 'Command timed out: git --version', stdout: '', stderr: '', isMaxBuffer: false, + } as Awaited>) + try { + await expectRejection(cache().read(other.url, other.commit, 'README.md', 100, signal), { reason: 'git-unavailable' }, 'timed out') + expect(probe).toHaveBeenCalledTimes(1) + expect(probe).toHaveBeenCalledWith('git', expect.arrayContaining(['--version']), expect.anything()) + } finally { + probe.mockRestore() + } vi.stubEnv('PATH', join(root, 'no-git')) const missing = cache().read(other.url, other.commit, 'README.md', 100, signal) await expectRejection(missing, { reason: 'git-unavailable' }, 'git --version') From 2361eaebec28e0e55a5d232fdaa3e19c9ff53dac Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 30 Oct 2026 13:58:35 +0800 Subject: [PATCH 34/55] test(plugin-market): isolate Git probe call assertions --- packages/boot/plugin-market/tests/repository-cache.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/boot/plugin-market/tests/repository-cache.spec.ts b/packages/boot/plugin-market/tests/repository-cache.spec.ts index 501ce07d51..e01172bd7e 100644 --- a/packages/boot/plugin-market/tests/repository-cache.spec.ts +++ b/packages/boot/plugin-market/tests/repository-cache.spec.ts @@ -157,7 +157,7 @@ it('reports an unreachable host as a network failure, a failed local command as expect(readdirSync(join(root, 'cache'))).toEqual([]) const other = repository('t2', { 'README.md': 'x' }) // A real 1 ms deadline can expire during either the version probe or a later Git command. - const probe = vi.spyOn(subprocess, 'execa').mockResolvedValueOnce({ + const probe = vi.spyOn(subprocess, 'execa').mockClear().mockResolvedValueOnce({ failed: true, shortMessage: 'Command timed out: git --version', stdout: '', stderr: '', isMaxBuffer: false, } as Awaited>) try { From e8f79f135d932d4fa540c17b05f7e49f56b8ee09 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 30 Oct 2026 14:40:36 +0800 Subject: [PATCH 35/55] fix(cua): restore standalone helper launch --- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../cua-macos/native/README.i18n.yaml | 8 +- .../experimental/cua-macos/native/README.md | 4 +- .../cua-macos/native/README.zh.md | 4 +- .../CuaNative/SharedHelperRuntime.swift | 7 +- .../CuaNative/StandaloneApplication.swift | 86 +++++++++++ .../native/tests/nested_application_e2e.py | 79 ++++++++++ .../swift/StandaloneApplicationTests.swift | 136 ++++++++++++++++++ 10 files changed, 317 insertions(+), 15 deletions(-) create mode 100644 packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift create mode 100644 packages/experimental/cua-macos/native/tests/nested_application_e2e.py create mode 100644 packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 4da34368fa..1ac1c88107 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -12,8 +12,8 @@ en: 4549f02fc53854a5 zh: 6f74f1130b6623a8 /deepseek-ai-dsh-experimental-cua-macos/table-of-contents: - en: 1c91307fdaebba7a - zh: 910fba0aa793f47f + en: 7d49f2f1c75e76ad + zh: b2e7f4146dd043ee /deepseek-ai-dsh-experimental-cua-macos/use-this-package: en: d714239a7ae8e72f zh: c08e9bcc3d644a01 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 3112379726..2799499386 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -22,7 +22,7 @@ Inspect macOS permissions, select running applications and windows, read accessi The helper supplies bounded 64-pixel PNG application icons for permission prompts and saved-application lists. Icon reads do not launch an application or inspect its windows; icons do not determine reusable consent. -The helper runs through LaunchServices as the independent application `DSH Computer Use.app`. Accessibility and Screen Recording permissions belong to this application. Permission guidance uses the responsible application’s bundle URL, identifier, filename, and system icon captured at startup; unavailable system attribution falls back to the independent helper’s own bundle. Dragging and Finder selection read the current on-disk bundle identifier and executable through the application-discovery reader. The page and guide both display the application’s `.app` filename. Existing connections retain their running application generation when another build updates `current.json`. +The helper runs through LaunchServices as the independent application `DSH Computer Use.app`. Accessibility and Screen Recording permissions belong to this application. Permission guidance uses the responsible application’s bundle URL, identifier, filename, and system icon captured at startup; unavailable system attribution falls back to the independent helper’s own bundle. Dragging and Finder selection read the current on-disk bundle identifier and executable through the application-discovery reader. The page and guide both display the application’s `.app` filename. Existing connections retain their running application generation when another build updates `current.json`. When bundled inside another `.app`, it starts from a verified standalone copy; see [application storage](native/README.md#build-and-service). Permission requests open the selected privacy pane and a native floating guide. The guide selects the largest settings window once and follows that window by ID. It uses the normal window level, ordered immediately above the selected window so authentication dialogs remain above it. Placement reads window bounds without requesting Accessibility access. The guide stays hidden until the settings window is identified; a failed settings-open request displays manual navigation instructions independently. A material alpha mask gives the panel and its shadow rounded corners. The latest request replaces the shared guide, and only its owning connection can close it during cleanup. Navigation is attempted even when the application is unavailable, and the page reports that failure. Already-granted permissions open settings without a guide; explicit settings navigation dismisses previous guidance. A rejected settings-open request reports `SETTINGS_UNAVAILABLE`; missing or replaced application targets report `APPLICATION_UNAVAILABLE`. System Settings owns drag acceptance and any relaunch requirement. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 23b6539f7f..11617d1e0d 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -22,7 +22,7 @@ kind: "package-reference" helper 为授权提示和已授权应用列表提供 64 像素 PNG 图标。读取图标不会启动应用或检查窗口,图标不决定可复用授权。 -helper 通过 LaunchServices 作为独立应用 `DSH Computer Use.app` 运行。辅助功能和屏幕录制权限属于此应用。授权引导使用启动时记录的责任应用 bundle URL、标识、文件名和系统图标;系统归属信息不可用时使用独立 helper 自身的 bundle。拖动和 Finder 选择通过应用发现模块读取磁盘上当前的 bundle 标识及可执行文件。页面和引导框统一显示应用的 `.app` 文件名。其他构建更新 `current.json` 后,已有连接仍指向正在运行的应用版本。 +helper 通过 LaunchServices 作为独立应用 `DSH Computer Use.app` 运行。辅助功能和屏幕录制权限属于此应用。授权引导使用启动时记录的责任应用 bundle URL、标识、文件名和系统图标;系统归属信息不可用时使用独立 helper 自身的 bundle。拖动和 Finder 选择通过应用发现模块读取磁盘上当前的 bundle 标识及可执行文件。页面和引导框统一显示应用的 `.app` 文件名。其他构建更新 `current.json` 后,已有连接仍指向正在运行的应用版本。 helper 嵌套在其他 `.app` 中时,会从经过校验的独立副本启动,存放与校验规则见[原生构建与服务](native/README.zh.md#build-and-service)。 权限请求打开对应隐私设置页和原生悬浮引导框。引导框首次选择面积最大的设置窗口,随后按窗口 ID 跟随。它使用普通窗口层级,紧邻所选窗口上方排列,使认证弹窗保持在其上方。定位读取窗口边界,不申请辅助功能权限。引导框等到识别出设置窗口后才显示;打开设置失败时独立显示手动导航说明。材质的透明度遮罩为面板和阴影提供圆角。最新请求替换共享引导,连接清理只关闭自身创建的引导。应用不可用时仍尝试打开设置,并在页面报告失败原因。权限已授予时只打开设置;显式进入设置会关闭原有引导。系统拒绝打开设置时报告 `SETTINGS_UNAVAILABLE`;应用目标缺失或被替换时报告 `APPLICATION_UNAVAILABLE`。系统设置决定是否接收拖入的应用,以及是否要求重新启动。 diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index d5488053dd..eb73f7355b 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -15,8 +15,8 @@ en: e8cbc43d38786c40 zh: 52b3ba85d98011b9 /dsh-cua-native-helper/build-and-service: - en: 7619d37566e773ef - zh: c8f6e37f19ad9763 + en: ab8fe195c70dd31c + zh: b05bc116dc173c9c /dsh-cua-native-helper/request-protocol: en: fc8043c425322cdd zh: cf1edb9a78fda301 @@ -24,8 +24,8 @@ en: 8fb132761a24c73f zh: 2ebb04c235328178 /dsh-cua-native-helper/verification: - en: 706d3434799530b3 - zh: e327c5fc7330c2b9 + en: d7d27c97fff638cd + zh: 7f52556496a304d2 /dsh-cua-native-helper/further-exploration: en: 265e1927952ce6d7 zh: 7c35d9fd98b6e6c8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 4b0a81eacf..770689cea3 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -23,7 +23,7 @@ This macOS 14+ JSON-lines helper uses Swift 6, AppKit, Accessibility, CoreGraphi ## Build and service -Run `pnpm --dir packages/experimental/cua-macos run build:native` to publish a signed `DSH Computer Use.app` under `native/bin/darwin-`. 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. +Run `pnpm --dir packages/experimental/cua-macos run build:native` to publish a signed `DSH Computer Use.app` under `native/bin/darwin-`. 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. When the helper is nested inside another `.app`, its launcher copies the complete signed bundle to `~/Library/Application Support/DeepSeek Harness/Computer Use//` before starting it. Each immutable generation is verified against the executable hash and application signature; earlier generations remain available for running installations. This keeps both macOS permission services attributed to the helper. A failed verification stops startup; remove the named cached generation before retrying. Generations in `native/.build/prepared/` and `native/bin/darwin-` 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. @@ -125,7 +125,7 @@ Run `python3 packages/experimental/cua-macos/native/tests/shared_helper_e2e.py - 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. -Run `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py` in a GUI login session to verify that the helper owns its permission identity even when started through two nested GUI launchers. Concurrent connections report the same helper name and icon. The check owns its applications, cleans up LaunchServices registrations, and requests no Accessibility or Screen Recording access. +Run `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py` in a GUI login session to verify that the helper owns its permission identity even when started through two nested GUI launchers. Concurrent connections report the same helper name and icon. The check owns its applications, cleans up LaunchServices registrations, and requests no Accessibility or Screen Recording access. Run `python3 packages/experimental/cua-macos/native/tests/nested_application_e2e.py` to verify signature-preserving extraction outside an enclosing `.app`, concurrent publication, and service teardown with uniquely signed fixtures. Run `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py` after building and unlocking the Mac to verify an owned window whose application removes and later restores its AX roots. The check requires existing Accessibility/Screen Recording grants, rejects stale element indices, captures the AXless window, verifies a coordinate click in the fixture state file, and checks restoration. It never changes system permission settings. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index f2734c0240..b4ff72e8ec 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -23,7 +23,7 @@ kind: "package-reference" ## 构建与服务 -运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-` 下生成带签名的 `DSH Computer Use.app`,`current.json` 选择完整的内容摘要目录。默认使用临时签名;正式打包可传入 `--identity` 指定 Developer ID,并由发布流程完成公证。Host 运行应用内的 `--ensure-shared` 入口,经 LaunchServices 后台启动服务。最后一条连接完成清理后,服务退出。 +运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-` 下生成带签名的 `DSH Computer Use.app`,`current.json` 选择完整的内容摘要目录。默认使用临时签名;正式打包可传入 `--identity` 指定 Developer ID,并由发布流程完成公证。Host 运行应用内的 `--ensure-shared` 入口,经 LaunchServices 后台启动服务。最后一条连接完成清理后,服务退出。 helper 嵌套在另一个 `.app` 内时,启动器先把完整的已签名应用复制到 `~/Library/Application Support/DeepSeek Harness/Computer Use//`,再启动它。每个不可变目录都校验可执行文件哈希和应用签名,旧目录保留给仍在运行的安装版本使用,使两项 macOS 权限都归属于 helper。校验失败会中止启动;删除报错中指定的缓存目录后再重试。 `native/.build/prepared/` 和 `native/bin/darwin-` 中的各代应用不会自动清理。正式打包时使用全新的 `--output-directory`,或确认没有客户端使用后清理打包输出再构建,避免旧应用进入 tarball。安全签名时间戳可能让相同源码生成不同代应用。 @@ -125,7 +125,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 在已解锁的 macOS GUI 会话中运行 `python3 packages/experimental/cua-macos/native/tests/application_consent_e2e.py --helper /absolute/helper`,需要可用的 Apple Swift 编译器。它创建并清理自己的 AppKit 应用和独立 GUI 进程,检查元数据替换、冷启动与直接启动、共用 Bundle ID、独立程序重启后的持久路径身份,以及删除运行中可执行文件后的选择行为。默认身份检查不需要辅助功能或屏幕录制权限。添加 `--desktop` 可读取完整测试应用的控件,通过状态文件验证 AX 按钮点击,截取窗口,并记录删除可执行文件后的观察结果;此模式要求已有两项系统权限。 -在 GUI 登录会话中运行 `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py`,验证两个嵌套 GUI 启动器启动 helper 后,授权归属仍为 helper 自己,多条连接得到相同名称和图标。检查自行创建应用并清理 LaunchServices 注册,不申请辅助功能或屏幕录制权限。 +在 GUI 登录会话中运行 `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py`,验证两个嵌套 GUI 启动器启动 helper 后,授权归属仍为 helper 自己,多条连接得到相同名称和图标。检查自行创建应用并清理 LaunchServices 注册,不申请辅助功能或屏幕录制权限。 运行 `python3 packages/experimental/cua-macos/native/tests/nested_application_e2e.py`,用独立签名的测试应用验证 helper 在外层 `.app` 之外保留签名发布、并发发布和服务退出。 构建并解锁 Mac 后运行 `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py`,验证应用移除并恢复 AX 根节点的窗口。检查需要已有辅助功能/屏幕录制权限,会拒绝过期元素索引,捕获无 AX 窗口,通过 fixture 状态文件核实坐标点击,并检查恢复。不会修改系统权限设置。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperRuntime.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperRuntime.swift index 42c1853870..c468d95032 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperRuntime.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperRuntime.swift @@ -296,6 +296,7 @@ final class SharedSocket: @unchecked Sendable { throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED", message: "Computer Use requires its signed application bundle; set helperPath to DSH Computer Use.app/Contents/MacOS/dsh-cua-native") } + let applicationURL = try StandaloneApplication.prepare(bundle.bundleURL, runtimeKey: options.runtimeKey, deadline: deadline) let configuration = NSWorkspace.OpenConfiguration() configuration.activates = false configuration.addsToRecentItems = false @@ -310,12 +311,12 @@ final class SharedSocket: @unchecked Sendable { guard DispatchTime.now().uptimeNanoseconds < deadline else { throw NativeFailure(code: "NATIVE_STARTUP_TIMEOUT", message: "Computer Use launch lock exhausted the startup deadline") } - // LaunchServices gives the application its own TCC identity; direct spawning inherits the terminal's. + // LaunchServices and a standalone bundle keep both permission services attributed to this helper. let application: NSRunningApplication - do { application = try await NSWorkspace.shared.openApplication(at: bundle.bundleURL, configuration: configuration) } + do { application = try await NSWorkspace.shared.openApplication(at: applicationURL, configuration: configuration) } catch { if let failure = try SharedHelperOptions.startupFailure(at: failurePath) { throw failure } - throw NativeFailure(code: "NATIVE_STARTUP", message: "macOS could not launch Computer Use at \(bundle.bundleURL.path): \(error.localizedDescription)") + throw NativeFailure(code: "NATIVE_STARTUP", message: "macOS could not launch Computer Use at \(applicationURL.path): \(error.localizedDescription)") } let pid = application.processIdentifier guard pid > 0 else { diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift new file mode 100644 index 0000000000..15bd509639 --- /dev/null +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/StandaloneApplication.swift @@ -0,0 +1,86 @@ +// Nested applications share their enclosing app's Screen Recording identity in TCC. +import CryptoKit +import Darwin +import Foundation +import Security + +enum StandaloneApplication { + static func hasApplicationAncestor(_ application: URL) -> Bool { + var parent = application.deletingLastPathComponent() + while parent.path != "/" { + if parent.pathExtension.lowercased() == "app" { return true } + parent.deleteLastPathComponent() + } + return false + } + + static func prepare(_ application: URL, runtimeKey: String, deadline: UInt64) throws -> URL { + let source = application.resolvingSymlinksInPath() + guard hasApplicationAncestor(source) else { return source } + let support = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, + appropriateFor: nil, create: true) + return try install(source, runtimeKey: runtimeKey, + root: support.appendingPathComponent("DeepSeek Harness/Computer Use"), deadline: deadline) + } + + // Published generations remain immutable while any installed DSH version may still run them. + static func install(_ source: URL, runtimeKey: String, root: URL, deadline: UInt64) throws -> URL { + let files = FileManager.default + try files.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + let root = root.resolvingSymlinksInPath() + let generation = root.appendingPathComponent(runtimeKey, isDirectory: true) + let application = generation.appendingPathComponent(source.lastPathComponent, isDirectory: true) + guard !hasApplicationAncestor(application) else { + throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED", message: "Computer Use application storage must be outside another .app: \(root.path)") + } + var lock: SharedHelperLock? + repeat { + lock = try SharedHelperLock(path: root.appendingPathComponent("\(runtimeKey).lock").path) + if lock != nil { break } + usleep(10_000) + } while DispatchTime.now().uptimeNanoseconds < deadline + guard let lock else { + throw NativeFailure(code: "NATIVE_STARTUP_TIMEOUT", message: "Computer Use application installation is still in progress") + } + defer { withExtendedLifetime(lock) {} } + if files.fileExists(atPath: generation.path) { + do { try validate(application, runtimeKey: runtimeKey) } + catch { + throw NativeFailure(code: "NATIVE_APPLICATION_INVALID", message: "Computer Use cached application is invalid: \(error.localizedDescription); remove \(generation.path) and retry") + } + return application + } + let staging = root.appendingPathComponent(".staging-\(UUID().uuidString)", isDirectory: true) + try files.createDirectory(at: staging, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + do { + let stagedApplication = staging.appendingPathComponent(source.lastPathComponent, isDirectory: true) + try files.copyItem(at: source, to: stagedApplication) + try validate(stagedApplication, runtimeKey: runtimeKey) + try files.moveItem(at: staging, to: generation) + } catch { + let failure = error + do { try files.removeItem(at: staging) } + catch { + throw NativeFailure(code: "NATIVE_IO", message: "Computer Use installation failed: \(failure.localizedDescription); could not remove \(staging.path): \(error.localizedDescription)") + } + throw failure + } + return application + } + + private static func validate(_ application: URL, runtimeKey: String) throws { + guard !hasApplicationAncestor(application.resolvingSymlinksInPath()) else { + throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED", message: "Computer Use application resolves inside another .app: \(application.path)") + } + let executable = application.appendingPathComponent("Contents/MacOS/dsh-cua-native") + let bytes = try Data(contentsOf: executable, options: .mappedIfSafe) + let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() + var code: SecStaticCode? + let flags = SecCSFlags(rawValue: kSecCSStrictValidate | kSecCSCheckAllArchitectures | kSecCSCheckNestedCode) + guard digest == runtimeKey, + SecStaticCodeCreateWithPath(application as CFURL, [], &code) == errSecSuccess, + let code, SecStaticCodeCheckValidity(code, flags, nil) == errSecSuccess else { + throw NativeFailure(code: "NATIVE_APPLICATION_INVALID", message: "Computer Use application failed signature or executable verification at \(application.path)") + } + } +} diff --git a/packages/experimental/cua-macos/native/tests/nested_application_e2e.py b/packages/experimental/cua-macos/native/tests/nested_application_e2e.py new file mode 100644 index 0000000000..b8b3b3d994 --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/nested_application_e2e.py @@ -0,0 +1,79 @@ +"""Verify nested helper extraction and concurrent launchers without granting macOS permissions.""" +import argparse +import concurrent.futures +from contextlib import ExitStack +import hashlib +import json +import os +from pathlib import Path +import plistlib +import shutil +import signal +import subprocess +import tempfile +import uuid + +from native_test_support import copy_helper, default_binary, unregister_helper +from shared_helper_e2e import Connection, wait_released + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--helper', type=Path, default=None) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix='cua-nest-', dir='/tmp') as temporary, ExitStack() as cleanup: + root = Path(temporary) + parent = root / 'Desktop.app' / 'Contents' / 'Resources' + parent.mkdir(parents=True) + helper = copy_helper(args.helper or default_binary(), parent) + application = helper.parents[2] + manifest = application / 'Contents/Info.plist' + info = plistlib.loads(manifest.read_bytes()) + info['CFBundleIdentifier'] = 'dev.dsh.cua.nested-test.' + uuid.uuid4().hex + manifest.write_bytes(plistlib.dumps(info)) + subprocess.run(['codesign', '--force', '--sign', '-', '--timestamp=none', str(application)], + check=True, capture_output=True, timeout=30) + key = hashlib.sha256(helper.read_bytes()).hexdigest() + cache = Path.home() / 'Library/Application Support/DeepSeek Harness/Computer Use' + generation = cache / key + assert not generation.exists(), 'The unique signed fixture unexpectedly shares an existing generation' + cleanup.callback(lambda: (cache / (key + '.lock')).unlink(missing_ok=True)) + cleanup.callback(lambda: shutil.rmtree(generation) if generation.exists() else None) + copied_helper = generation / application.name / 'Contents/MacOS/dsh-cua-native' + cleanup.callback(unregister_helper, copied_helper) + runtime = [root / 'a', root / 'b'] + + def stop_owned(directory, pid): + try: + os.kill(pid, signal.SIGTERM) + except ProcessLookupError: + pass + wait_released(directory / (key + '.lock'), pid) + + def launch(directory): + result = subprocess.run([str(helper), '--ensure-shared', '--runtime-key', key, + '--runtime-directory', str(directory), '--startup-timeout-ms', '15000'], + check=True, capture_output=True, text=True, timeout=25) + ready = json.loads(result.stdout) + cleanup.callback(stop_owned, directory, ready['pid']) + client = Connection(directory / (key + '.sock'), key) + cleanup.callback(client.close) + return client + + # Separate launcher processes share the installation lock while retaining independent service sockets. + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as workers: + clients = list(workers.map(launch, runtime)) + for client in clients: + state = client.call('permissionStatus', {}) + assert Path(state['helper']['path']).resolve() == copied_helper.resolve(), state + assert Path(state['launchApplication']['path']).resolve() == copied_helper.parents[2].resolve(), state + assert not any(part.endswith('.app') for part in copied_helper.parents[3].parts), state + assert clients[0].ready['pid'] != clients[1].ready['pid'] + assert copied_helper.read_bytes() == helper.read_bytes() + subprocess.run(['codesign', '--verify', '--deep', '--strict', str(copied_helper.parents[2])], + check=True, capture_output=True, timeout=30) + print('PASS: concurrent launchers use the same signature-preserving standalone application and drain both helpers') + + +if __name__ == '__main__': + main() diff --git a/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift b/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift new file mode 100644 index 0000000000..a73dda8516 --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/swift/StandaloneApplicationTests.swift @@ -0,0 +1,136 @@ +// Real signed fixtures exercise cache publication, reuse, integrity and isolated permission ownership. +import CryptoKit +import Darwin +import Foundation +import Testing +@testable import CuaNative + +private struct ApplicationFixture { + let root: URL + let application: URL + let cache: URL + var executable: URL { application.appendingPathComponent("Contents/MacOS/dsh-cua-native") } + var resource: URL { application.appendingPathComponent("Contents/Resources/value.txt") } + var key: String { get throws { SHA256.hash(data: try Data(contentsOf: executable)).map { String(format: "%02x", $0) }.joined() } } + var deadline: UInt64 { DispatchTime.now().uptimeNanoseconds + 30_000_000_000 } + + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("cua-application-\(UUID().uuidString)") + application = root.appendingPathComponent("Desktop.app/Contents/Resources/DSH Computer Use.app") + cache = root.appendingPathComponent("support") + try FileManager.default.createDirectory(at: executable.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: resource.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.copyItem(at: URL(fileURLWithPath: "/usr/bin/true"), to: executable) + try Data("original resource".utf8).write(to: resource) + let plist = try PropertyListSerialization.data(fromPropertyList: [ + "CFBundleIdentifier": "dev.dsh.cua.cache-test.\(UUID().uuidString)", + "CFBundleExecutable": "dsh-cua-native", "CFBundleName": "DSH Computer Use", "CFBundlePackageType": "APPL", + ], format: .xml, options: 0) + try plist.write(to: application.appendingPathComponent("Contents/Info.plist")) + try sign() + } + + func sign() throws { + let process = Process(), finished = DispatchSemaphore(value: 0) + process.executableURL = URL(fileURLWithPath: "/usr/bin/codesign") + process.arguments = ["--force", "--sign", "-", "--timestamp=none", application.path] + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + process.terminationHandler = { _ in finished.signal() } + try process.run() + if finished.wait(timeout: .now() + 30) == .timedOut { + kill(process.processIdentifier, SIGKILL) + process.waitUntilExit() + throw NativeFailure(code: "FIXTURE_TIMEOUT", message: "Ad-hoc fixture signing did not exit") + } + #expect(process.terminationReason == .exit) + try #require(process.terminationStatus == 0) + } + + func close() { + do { try FileManager.default.removeItem(at: root) } + catch { Issue.record("Could not remove owned application fixture: \(error)") } + } +} + +@Test func onlyNestedApplicationsNeedAnIndependentInstallation() throws { + #expect(StandaloneApplication.hasApplicationAncestor(URL(fileURLWithPath: "/Applications/Desktop.app/Contents/Helper.app"))) + #expect(StandaloneApplication.hasApplicationAncestor(URL(fileURLWithPath: "/Applications/Desktop.APP/Helper.app"))) + let standalone = URL(fileURLWithPath: "/Users/example/Helper.app") + #expect(!StandaloneApplication.hasApplicationAncestor(standalone)) + #expect(try StandaloneApplication.prepare(standalone, runtimeKey: "unused", deadline: 0) == standalone) +} + +@Test func aSignedHelperIsPublishedOutsideItsEnclosingApplicationAndReused() throws { + let f = try ApplicationFixture(); defer { f.close() } + let key = try f.key + let installed = try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) + #expect(!StandaloneApplication.hasApplicationAncestor(installed)) + #expect(try Data(contentsOf: installed.appendingPathComponent("Contents/MacOS/dsh-cua-native")) == Data(contentsOf: f.executable)) + #expect(try Data(contentsOf: installed.appendingPathComponent("Contents/Resources/value.txt")) == Data(contentsOf: f.resource)) + #expect(try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) == installed) +} + +@Test func changingTheSignedApplicationRetainsTheEarlierGeneration() throws { + let f = try ApplicationFixture(); defer { f.close() } + let old = try StandaloneApplication.install(f.application, runtimeKey: f.key, root: f.cache, deadline: f.deadline) + try Data("new resource".utf8).write(to: f.resource) + try f.sign() + let new = try StandaloneApplication.install(f.application, runtimeKey: f.key, root: f.cache, deadline: f.deadline) + #expect(old != new) + #expect(try String(contentsOf: old.appendingPathComponent("Contents/Resources/value.txt"), encoding: .utf8) == "original resource") + #expect(try String(contentsOf: new.appendingPathComponent("Contents/Resources/value.txt"), encoding: .utf8) == "new resource") +} + +@Test(arguments: ["Contents/Resources/value.txt", "Contents/MacOS/dsh-cua-native"]) +func aChangedCachedApplicationIsRejected(file: String) throws { + let f = try ApplicationFixture(); defer { f.close() } + let key = try f.key + let installed = try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) + try Data("changed".utf8).write(to: installed.appendingPathComponent(file)) + #expect(throws: (any Error).self) { + try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) + } +} + +@Test func anInvalidSourceLeavesNoPartialPublishedApplication() throws { + let f = try ApplicationFixture(); defer { f.close() } + let key = try f.key + try Data("unsigned change".utf8).write(to: f.resource) + #expect(throws: (any Error).self) { + try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: f.cache.path) == ["\(key).lock"]) +} + +@Test func applicationStorageCannotItselfBeNestedInAnotherApplication() throws { + let f = try ApplicationFixture(); defer { f.close() } + #expect(throws: (any Error).self) { + try StandaloneApplication.install(f.application, runtimeKey: f.key, + root: f.root.appendingPathComponent("Other.app/cache"), deadline: f.deadline) + } +} + +@Test func aCachedSymlinkCannotRedirectTheHelperIntoAnEnclosingApplication() throws { + let f = try ApplicationFixture(); defer { f.close() } + let key = try f.key + try FileManager.default.createDirectory(at: f.cache, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: f.cache.appendingPathComponent(key), + withDestinationURL: f.application.deletingLastPathComponent()) + #expect(throws: (any Error).self) { + try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) + } +} + +@Test func aCompetingInstallerDoesNotUseAPartialGeneration() throws { + let f = try ApplicationFixture(); defer { f.close() } + let key = try f.key + try FileManager.default.createDirectory(at: f.cache, withIntermediateDirectories: true) + let lock = try #require(try SharedHelperLock(path: f.cache.appendingPathComponent("\(key).lock").path)) + defer { withExtendedLifetime(lock) {} } + #expect(throws: (any Error).self) { + try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, + deadline: DispatchTime.now().uptimeNanoseconds) + } + #expect(!FileManager.default.fileExists(atPath: f.cache.appendingPathComponent(key).path)) +} From d9e89b3b37ec46eefc5d26c9b841fd7cd72d16f3 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 30 Oct 2026 16:47:49 +0800 Subject: [PATCH 36/55] fix(cua): retain redacted notarization failure diagnostics --- apps/desktop/packaging/README.i18n.yaml | 4 +- apps/desktop/packaging/README.md | 4 +- apps/desktop/packaging/README.zh.md | 4 +- apps/desktop/scripts/logged-notarytool.mjs | 16 ++- .../tests/logged-notarytool-exit.spec.ts | 53 ++++++++- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 2 +- scripts/cua-helper/package.spec.ts | 110 ++++++++++++++++++ scripts/cua-helper/package.ts | 22 +++- 10 files changed, 203 insertions(+), 18 deletions(-) create mode 100644 scripts/cua-helper/package.spec.ts diff --git a/apps/desktop/packaging/README.i18n.yaml b/apps/desktop/packaging/README.i18n.yaml index 4a4de81f97..49412773f7 100644 --- a/apps/desktop/packaging/README.i18n.yaml +++ b/apps/desktop/packaging/README.i18n.yaml @@ -36,8 +36,8 @@ en: 1146bbc11be43960 zh: 7c13543a0513c059 /desktop-packaging/macos-release-signing-and-diagnostics: - en: 015e91c6e0f72bfb - zh: 975fd70ee5bdc520 + en: a0b4aa1080ecf6fb + zh: 37d4b8934f89bee8 /desktop-packaging/directory-builds-and-preparation: en: 5860c306375ddd63 zh: a76e3cdbbe25c79e diff --git a/apps/desktop/packaging/README.md b/apps/desktop/packaging/README.md index b2898a1a74..502a95e2be 100644 --- a/apps/desktop/packaging/README.md +++ b/apps/desktop/packaging/README.md @@ -184,7 +184,9 @@ macOS signing visits real files without following Framework symlink aliases. PAK macOS runtime preparation caches verified single-architecture Mach-O signatures in `.desktop-build/targets//signature-cache` unless `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` selects external storage. An explicit path must be absolute and already exist, contain no linked ancestors, and be owned by the current account with mode `0700` and read/write/search access; invalid or empty settings fail preflight without fallback. Omit the field to retain target-local storage. Keys include input bytes and permissions, the signing probe’s actual leaf certificate, identifier, entitlement bytes, macOS version, and signing tools and policy. Git commits do not determine reuse: uncommitted byte changes invalidate the affected file. Every hit verifies cached bytes, the strict signature, certificate, identifier, entitlements, secure timestamp and hardened runtime before replacing an unchanged input. Universal binaries are signed each time. Runtime integrity and smoke checks, App signing, and Apple notarization still run. The cache requires trusted local build storage. Cache corruption or unsafe links fail the build; stop packaging before deleting the affected cache directory and retrying. Successful signing stages prune complete entries to a one-GiB payload budget; interrupted temporary entries require manual removal. Concurrent eviction can fail a reader safely. Logs report hit, miss and uncached counts. -Mac package commands print `DESKTOP_PACKAGING_RECORD` with a unique directory under `apps/desktop/.desktop-build/packaging-runs/`. After reading local configuration, each run retains `run.json` (published version, product version, Git commit, dirty-worktree flag, target and Node version), `events.jsonl` (timestamped phases, durations, parallel output attribution and proxy restoration), redacted child `stdout.log` / `stderr.log`, and `result.json` (overall outcome, stage results and artifact directory). Events also record pack concurrency and whether each proxy is configured. Logs survive failures and later builds; no automatic deletion runs. Missing `result.json` means completion is unconfirmed. Known credential values are redacted; environments and notarytool authentication arguments are not recorded. Runtime preparation records package staging, installation, materialization, signing, manifests, smoke checks, descriptor verification and cleanup separately. Nested phase durations overlap and must not be added together. +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. diff --git a/apps/desktop/packaging/README.zh.md b/apps/desktop/packaging/README.zh.md index ccb96d4aa5..7f43a0c2e5 100644 --- a/apps/desktop/packaging/README.zh.md +++ b/apps/desktop/packaging/README.zh.md @@ -184,7 +184,9 @@ macOS 签名遍历真实文件,不跟随 Framework 的软链接别名。PAK macOS 运行时准备将已验证的单架构 Mach-O 签名缓存在 `.desktop-build/targets//signature-cache`,除非通过 `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` 选择外置存储。显式路径必须是已存在的绝对目录,祖先路径不能包含链接,目录须归当前账户所有、权限为 `0700` 且可读写及遍历;非法或空配置在预检时失败,不回退。省略该字段保留目标本地缓存。缓存键包含输入字节与权限、签名探针实际使用的叶证书、签名标识、entitlement 字节、macOS 版本,以及签名工具与策略。复用不取决于 Git 提交:未提交的字节变更会使对应文件失效。每次命中都验证缓存字节、严格签名、证书、标识、entitlements、安全时间戳和 hardened runtime,再替换未被并发修改的输入。通用二进制每次重新签名。运行时完整性与 smoke 检查、App 签名和 Apple 公证仍会执行。缓存要求受信任的本地构建存储。缓存损坏或不安全链接会令构建失败;停止打包后删除对应缓存目录再重试。成功的签名阶段会将完整缓存条目的内容总量裁剪至一 GiB;中断留下的临时条目需手动清理。并发淘汰可能使读取方安全失败。日志记录命中、未命中及未缓存数量。 -Mac 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `apps/desktop/.desktop-build/packaging-runs/` 下的唯一目录。读取本地配置后,每次运行保留 `run.json`(发布版本、产品版本、Git 提交、工作区是否有改动、目标及 Node 版本)、`events.jsonl`(带时间戳的阶段、耗时、并行输出归属及代理恢复状态)、脱敏后的子进程 `stdout.log` / `stderr.log`,以及 `result.json`(整体结果、阶段结果和产物目录)。事件还记录打包并发数及各代理是否配置。失败和后续打包不会清除日志;没有自动删除流程。缺少 `result.json` 表示完成状态未经确认。已知凭据值会被遮盖;不记录环境变量全集或 notarytool 认证参数。运行时准备分别记录包暂存、安装、依赖树复制、签名、清单生成、smoke 检查、描述文件校验和清理。嵌套阶段的耗时存在重叠,不能直接相加。 +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` 命令不创建运行日志。 diff --git a/apps/desktop/scripts/logged-notarytool.mjs b/apps/desktop/scripts/logged-notarytool.mjs index ae2a9bf055..a9ed964b3c 100755 --- a/apps/desktop/scripts/logged-notarytool.mjs +++ b/apps/desktop/scripts/logged-notarytool.mjs @@ -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 } } diff --git a/apps/desktop/tests/logged-notarytool-exit.spec.ts b/apps/desktop/tests/logged-notarytool-exit.spec.ts index 8deaf4ece4..3e8e222d84 100644 --- a/apps/desktop/tests/logged-notarytool-exit.spec.ts +++ b/apps/desktop/tests/logged-notarytool-exit.spec.ts @@ -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') + await expect(runLoggedNotarytool(args)).rejects.toMatchObject({ + message: expect.stringContaining('notarytool submit failed (code: 1'), cause: expect.objectContaining({ 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', 'private@example.test', '--password', 'secret-sentinel', + '--team-id', 'private-team', '--wait', '--output-format', 'json'] + command.mockReset() + command.mockRejectedValueOnce(Object.assign(new Error('connection closed: private@example.test 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 ['private@example.test', '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 }) + } +}) diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index dcce02fa45..fdb14959cf 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -15,8 +15,8 @@ en: e8cbc43d38786c40 zh: 52b3ba85d98011b9 /dsh-cua-native-helper/build-and-service: - en: b5dbcee0ffd40a1a - zh: fab3abcd56a5248f + en: 7d431d98f362db74 + zh: 29104e6215bb9ade /dsh-cua-native-helper/request-protocol: en: fc8043c425322cdd zh: cf1edb9a78fda301 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 165126eb4c..d6a8d54e21 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -27,7 +27,7 @@ Run `pnpm --dir packages/experimental/cua-macos run build:native` to publish a s Generations in `native/.build/prepared/` and `native/bin/darwin-` 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. -The manual **Package CUA helper · macOS** [workflow](../../../../.github/workflows/cua-helper-package.yml) builds both architectures on `dsh-mac-package-trial`. Select a trusted `source_ref` and machine `preset`; credentials use the existing [macOS packaging configuration](../../../../apps/desktop/packaging/README.md#macos-actions). Packaging does not require a macOS desktop login or Rosetta. `pnpm exec tsx scripts/cua-helper/package.ts --out ` runs the same preparation from the repository root. It signs, notarizes and staples each complete application before selecting its final content digest, then verifies architectures, signatures, tickets, Gatekeeper and file integrity from the extracted `cua-helper.tgz`. Packaging does not launch the helper. Run `python3 scripts/cua-helper/smoke.py ` separately in a logged-in desktop session to check capabilities, helper identity and cleanup; x64 execution on Apple Silicon requires Rosetta. The smoke does not request permissions or inspect applications. Failed or timed-out commands and unreadable startup replies report captured stdout and stderr; invalid encoding is replaced only in diagnostic text, while protocol parsing remains strict. A successful package build does not certify runtime behavior. +The manual **Package CUA helper · macOS** [workflow](../../../../.github/workflows/cua-helper-package.yml) builds both architectures on `dsh-mac-package-trial`. Select a trusted `source_ref` and machine `preset`; credentials use the existing [macOS packaging configuration](../../../../apps/desktop/packaging/README.md#macos-actions). Packaging does not require a macOS desktop login or Rosetta. `pnpm exec tsx scripts/cua-helper/package.ts --out ` runs the same preparation from the repository root. It signs, notarizes and staples each complete application before selecting its final content digest, then verifies architectures, signatures, tickets, Gatekeeper and file integrity from the extracted `cua-helper.tgz`. Packaging does not launch the helper. Run `python3 scripts/cua-helper/smoke.py ` separately in a logged-in desktop session to check capabilities, helper identity and cleanup; x64 execution on Apple Silicon requires Rosetta. The smoke does not request permissions or inspect applications. Failed or timed-out commands and unreadable startup replies report captured stdout and stderr; invalid encoding is replaced only in diagnostic text, while protocol parsing remains strict. A successful package build does not certify runtime behavior. Helper packaging retains its own [diagnostic record](../../../../apps/desktop/packaging/README.md#macos-release-signing), including failures before desktop installer startup. The workflow retains `cua-helper.tgz` and `cua-helper.json`, which binds the product version, source commit, Team ID and both application digests. [Release publish](../../../../.github/workflows/release-publish.yml) consumes this artifact before packing the provider for npm; ordinary PR release rehearsals have no signing credentials. Staging rejects a source/version mismatch, incomplete architectures, stale generations, links, changed bytes and missing executable permissions. npm publication rechecks the exact provider tarball before any registry write. A re-signed release has different bytes; preserve the retained artifact when retrying a partially published version. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index bc4a41c0a3..88b9ad6db0 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -27,7 +27,7 @@ kind: "package-reference" `native/.build/prepared/` 和 `native/bin/darwin-` 中的各代应用不会自动清理。正式打包时使用全新的 `--output-directory`,或确认没有客户端使用后清理打包输出再构建,避免旧应用进入 tarball。安全签名时间戳可能让相同源码生成不同代应用。 -手动工作流 **Package CUA helper · macOS** 的[配置](../../../../.github/workflows/cua-helper-package.yml)在 `dsh-mac-package-trial` 构建两种架构。选择可信的 `source_ref` 和机器 `preset`;凭据沿用[macOS 打包配置](../../../../apps/desktop/packaging/README.zh.md#macos-actions)。打包无需 macOS 桌面登录或 Rosetta。在仓库根目录运行 `pnpm exec tsx scripts/cua-helper/package.ts --out ` 可执行相同准备。完整应用签名、公证和贴票后才确定最终内容摘要,再从解包后的 `cua-helper.tgz` 验证架构、签名、票据、Gatekeeper 和文件完整性。打包不启动 helper。在已登录的桌面会话中单独运行 `python3 scripts/cua-helper/smoke.py ` 检查能力、helper 身份和退出清理;Apple Silicon 上执行 x64 版本需要 Rosetta。该检查不申请权限或观察应用。命令失败、超时或启动回复无法解析时,会输出捕获的 stdout 和 stderr;无效编码只在诊断文本中替换,协议解析仍严格校验。打包成功不代表运行验收通过。 +手动工作流 **Package CUA helper · macOS** 的[配置](../../../../.github/workflows/cua-helper-package.yml)在 `dsh-mac-package-trial` 构建两种架构。选择可信的 `source_ref` 和机器 `preset`;凭据沿用[macOS 打包配置](../../../../apps/desktop/packaging/README.zh.md#macos-actions)。打包无需 macOS 桌面登录或 Rosetta。在仓库根目录运行 `pnpm exec tsx scripts/cua-helper/package.ts --out ` 可执行相同准备。完整应用签名、公证和贴票后才确定最终内容摘要,再从解包后的 `cua-helper.tgz` 验证架构、签名、票据、Gatekeeper 和文件完整性。打包不启动 helper。在已登录的桌面会话中单独运行 `python3 scripts/cua-helper/smoke.py ` 检查能力、helper 身份和退出清理;Apple Silicon 上执行 x64 版本需要 Rosetta。该检查不申请权限或观察应用。命令失败、超时或启动回复无法解析时,会输出捕获的 stdout 和 stderr;无效编码只在诊断文本中替换,协议解析仍严格校验。打包成功不代表运行验收通过。 helper 打包保留独立的[诊断记录](../../../../apps/desktop/packaging/README.zh.md#macos-release-signing),包括桌面安装包开始构建前发生的失败。 工作流保留 `cua-helper.tgz` 和 `cua-helper.json`,后者记录产品版本、源码 commit、Team ID 和两份应用摘要。[Release publish](../../../../.github/workflows/release-publish.yml)在生成 provider 的 npm 包前接入该产物;普通 PR 发布检查不使用签名凭据。准备步骤拒绝源码或版本不匹配、架构不全、旧应用目录、链接、字节变化和执行权限缺失。npm 发布在写入注册表前重新检查实际 provider tarball。重新签名会改变产物字节,重试部分发布的版本时需保留原产物。 diff --git a/scripts/cua-helper/package.spec.ts b/scripts/cua-helper/package.spec.ts new file mode 100644 index 0000000000..4df793d010 --- /dev/null +++ b/scripts/cua-helper/package.spec.ts @@ -0,0 +1,110 @@ +/** Helper packaging retains redacted Apple failures independently of desktop installer startup. */ +import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { expect, it, vi } from 'vitest' + +const state = vi.hoisted(() => ({ root: '', directory: '', requestedRoot: '', reject: false })) +vi.mock('../../apps/desktop/scripts/desktop-package-environment.mjs', () => ({ + loadDesktopPackageEnvironment: () => ({ APPLE_ID: 'private@example.test', APPLE_PASSWORD: 'secret-sentinel' }), +})) +vi.mock('../../apps/desktop/scripts/desktop-release-environment.mjs', () => ({ + resolveMacOSSigningEnvironment: () => ({ signingIdentity: 'Fixture (ABCDEFGHIJ)', teamId: 'ABCDEFGHIJ' }), + resolveMacOSNotarizationEnvironment: () => ({ appleId: 'private@example.test', appleIdPassword: 'secret-sentinel', appleTeamId: 'ABCDEFGHIJ' }), +})) +vi.mock('../../apps/desktop/scripts/macos-package-settings.mjs', () => ({ resolveMacOSPackageSettings: () => ({}) })) +vi.mock('../../apps/desktop/scripts/macos-signing-keychain.mjs', () => ({ + withMacOSSigningKeychain: async (environment: object, action: (environment: object) => Promise) => action(environment), +})) +vi.mock('../../apps/desktop/scripts/macos-notarization-proxy.ts', () => ({ + withMacOSNotarizationProxy: async (_settings: object, action: () => Promise) => action(), +})) +vi.mock('../../apps/desktop/scripts/verify-macos-signature.mjs', () => ({ verifyMacOSRuntimeCode: () => {} })) +vi.mock('../../apps/desktop/scripts/packaging-run.mjs', async (importOriginal) => { + const original = await importOriginal() + return { ...original, createPackagingRun: (...args: Parameters) => { + state.requestedRoot = args[0] + const run = original.createPackagingRun(join(state.root, 'records'), args[1], args[2]) + state.directory = run.directory + return run + } } +}) +vi.mock('../../apps/desktop/scripts/notarize-macos.mjs', () => ({ + notarizeMacOS: async () => { + const { runLoggedNotarytool } = await import('../../apps/desktop/scripts/logged-notarytool.mjs') + const id = '11111111-2222-3333-4444-555555555555' + await runLoggedNotarytool(['submit', '/fixture/helper.zip', '--apple-id', 'private@example.test', + '--password', 'secret-sentinel', '--wait', '--output-format', 'json'], process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, async (args) => { + if (state.reject) throw new Error('Apple transport failed: private@example.test secret-sentinel') + return JSON.stringify(args[0] === 'submit' ? { id } : { id, status: 'Accepted' }) + }) + }, +})) +vi.mock('execa', () => ({ execa: async (_command: string, args: string[]) => { + const output = args.indexOf('--output-directory') + if (output !== -1) await mkdir(args[output + 1]!, { recursive: true }) +} })) +vi.mock('tar', () => ({ + create: async ({ file }: { file: string }) => writeFile(file, 'fixture archive'), + extract: async ({ cwd }: { cwd: string }) => mkdir(cwd), +})) +vi.mock('./payload.ts', async importOriginal => ({ + ...await importOriginal(), + readCuaApplication: (directory: string) => ({ application: join(directory, 'fixture/DSH Computer Use.app') }), + sealCuaApplication: () => 'fixture', + verifyCuaHelperPayload: () => {}, +})) + +it.each([false, true])('retains helper packaging outcome and restores the inherited journal when Apple rejects=%s', async (reject) => { + state.root = await mkdtemp(join(tmpdir(), 'cua-package-log-')) + state.directory = '' + state.reject = reject + const output = join(state.root, 'output') + const savedPlatform = Object.getOwnPropertyDescriptor(process, 'platform')! + const savedArgv = process.argv + const savedDirectory = process.env.DSH_DESKTOP_PACKAGING_RUN_DIR + const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true) + const consoleLog = vi.spyOn(console, 'log').mockImplementation(() => {}) + const inherited = reject ? join(state.root, 'outer-record') : undefined + const listeners = ['SIGINT', 'SIGTERM'].map(signal => process.listenerCount(signal)) + try { + Object.defineProperty(process, 'platform', { ...savedPlatform, value: 'darwin' }) + process.argv = [process.execPath, resolve('scripts/cua-helper/package.ts'), '--out', output] + if (inherited === undefined) delete process.env.DSH_DESKTOP_PACKAGING_RUN_DIR + else process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = inherited + vi.resetModules() + const work = import('./package.ts') + if (reject) await expect(work).rejects.toThrow('CUA helper packaging failed; see') + else await work + expect(state.requestedRoot).toBe(resolve('apps/desktop/.desktop-build/packaging-runs')) + expect(state.directory).not.toBe('') + const events = await readFile(join(state.directory, 'events.jsonl'), 'utf8') + const result = await readFile(join(state.directory, 'result.json'), 'utf8') + const terminal = stderr.mock.calls.map(([chunk]) => String(chunk)).join('') + expect(JSON.parse(result)).toMatchObject({ success: !reject }) + expect(events).toContain('notarytool:upload:helper.zip') + for (const diagnostic of [events, result, terminal]) { + expect(diagnostic).not.toContain('private@example.test') + expect(diagnostic).not.toContain('secret-sentinel') + } + if (reject) { + expect(events).toContain('Apple transport failed: [REDACTED] [REDACTED]') + expect(terminal).toContain('Apple transport failed: [REDACTED] [REDACTED]') + expect(events).not.toContain('notarytool:wait') + await expect(stat(join(output, 'cua-helper.tgz'))).rejects.toMatchObject({ code: 'ENOENT' }) + } else { + expect(events).toContain('"status":"Accepted"') + expect(await readFile(join(output, 'cua-helper.tgz'), 'utf8')).toBe('fixture archive') + } + expect(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR).toBe(inherited) + expect(['SIGINT', 'SIGTERM'].map(signal => process.listenerCount(signal))).toEqual(listeners) + } finally { + Object.defineProperty(process, 'platform', savedPlatform) + process.argv = savedArgv + if (savedDirectory === undefined) delete process.env.DSH_DESKTOP_PACKAGING_RUN_DIR + else process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = savedDirectory + stderr.mockRestore() + consoleLog.mockRestore() + await rm(state.root, { recursive: true, force: true }) + } +}) diff --git a/scripts/cua-helper/package.ts b/scripts/cua-helper/package.ts index 408503691c..c2f6170178 100644 --- a/scripts/cua-helper/package.ts +++ b/scripts/cua-helper/package.ts @@ -2,7 +2,7 @@ import { execFileSync } from 'node:child_process' import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join, resolve } from 'node:path' +import { basename, join, resolve } from 'node:path' import { parseArgs } from 'node:util' import { execa } from 'execa' import { create, extract } from 'tar' @@ -12,6 +12,8 @@ import { withMacOSSigningKeychain } from '../../apps/desktop/scripts/macos-signi import { withMacOSNotarizationProxy } from '../../apps/desktop/scripts/macos-notarization-proxy.ts' import { resolveMacOSPackageSettings } from '../../apps/desktop/scripts/macos-package-settings.mjs' import { notarizeMacOS } from '../../apps/desktop/scripts/notarize-macos.mjs' +import { createPackagingRun } from '../../apps/desktop/scripts/packaging-run.mjs' +import { packagingErrorDetails, packagingStep } from '../../apps/desktop/scripts/packaging-step.mjs' import { verifyMacOSRuntimeCode } from '../../apps/desktop/scripts/verify-macos-signature.mjs' import { CUA_APPLICATION, CUA_ARCHITECTURES, CUA_MANIFEST, readCuaApplication, sealCuaApplication, verifyCuaHelperPayload, type CuaHelperManifest } from './payload.ts' @@ -27,13 +29,22 @@ async function main(): Promise { const { version } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version: string } const commit = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim() mkdirSync(output, { recursive: false }) + const secrets = Object.entries(environment).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD|APPLE_ID/iu.test(name)).map(([, value]) => value ?? '') + const journal = createPackagingRun(join(root, 'apps/desktop/.desktop-build/packaging-runs'), { + target: 'cua-helper', version, commit, + }) + console.log(`CUA_PACKAGING_RECORD ${journal.directory}`) const scratch = mkdtempSync(join(tmpdir(), 'dsh-cua-package-')) + const previousDirectory = process.env.DSH_DESKTOP_PACKAGING_RUN_DIR + process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = journal.directory const controller = new AbortController() const stop = (): void => { controller.abort() } process.once('SIGINT', stop) process.once('SIGTERM', stop) const run = async (command: string, args: string[], env = environment): Promise => { - await execa(command, args, { cwd: root, env, extendEnv: false, stdio: 'inherit', cancelSignal: controller.signal, killDescendants: true }) + await packagingStep(journal.directory, basename(command), async () => { + await execa(command, args, { cwd: root, env, extendEnv: false, stdio: 'inherit', cancelSignal: controller.signal, killDescendants: true }) + }, secrets) } const verify = async (application: string, architecture: 'arm64' | 'x64'): Promise => { verifyMacOSRuntimeCode(application, signing) @@ -73,13 +84,18 @@ async function main(): Promise { writeFileSync(join(output, CUA_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`) console.log(`CUA helper artifact: ${archive}`) } catch (error) { + process.stderr.write(`${packagingErrorDetails(error, secrets)}\n`) + journal.finish(false) rmSync(join(output, 'cua-helper.tgz'), { force: true }) - throw error + throw new Error(`CUA helper packaging failed; see ${journal.directory}/events.jsonl`) } finally { process.off('SIGINT', stop) process.off('SIGTERM', stop) + if (previousDirectory === undefined) delete process.env.DSH_DESKTOP_PACKAGING_RUN_DIR + else process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = previousDirectory rmSync(scratch, { recursive: true, force: true }) } + journal.finish(true) } await main() From ee9ae56599b8508db0a6019e87bfb03d73175e1b Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 30 Oct 2026 16:50:55 +0800 Subject: [PATCH 37/55] test(cua): reuse the prepared extraction directory --- scripts/cua-helper/package.spec.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/scripts/cua-helper/package.spec.ts b/scripts/cua-helper/package.spec.ts index 4df793d010..a4c5b85202 100644 --- a/scripts/cua-helper/package.spec.ts +++ b/scripts/cua-helper/package.spec.ts @@ -46,7 +46,7 @@ vi.mock('execa', () => ({ execa: async (_command: string, args: string[]) => { } })) vi.mock('tar', () => ({ create: async ({ file }: { file: string }) => writeFile(file, 'fixture archive'), - extract: async ({ cwd }: { cwd: string }) => mkdir(cwd), + extract: async () => {}, })) vi.mock('./payload.ts', async importOriginal => ({ ...await importOriginal(), @@ -75,7 +75,11 @@ it.each([false, true])('retains helper packaging outcome and restores the inheri vi.resetModules() const work = import('./package.ts') if (reject) await expect(work).rejects.toThrow('CUA helper packaging failed; see') - else await work + else { + try { await work } catch (error) { + throw new Error(stderr.mock.calls.map(([chunk]) => String(chunk)).join(''), { cause: error }) + } + } expect(state.requestedRoot).toBe(resolve('apps/desktop/.desktop-build/packaging-runs')) expect(state.directory).not.toBe('') const events = await readFile(join(state.directory, 'events.jsonl'), 'utf8') From 1a294f7f79d3ada1c39900660a2e39af9f149b15 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 30 Oct 2026 17:01:29 +0800 Subject: [PATCH 38/55] test(desktop): keep notarization assertions type-safe --- apps/desktop/tests/logged-notarytool-exit.spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/desktop/tests/logged-notarytool-exit.spec.ts b/apps/desktop/tests/logged-notarytool-exit.spec.ts index 3e8e222d84..82e14f232d 100644 --- a/apps/desktop/tests/logged-notarytool-exit.spec.ts +++ b/apps/desktop/tests/logged-notarytool-exit.spec.ts @@ -33,9 +33,9 @@ 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.toMatchObject({ - message: expect.stringContaining('notarytool submit failed (code: 1'), cause: expect.objectContaining({ message: '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() }) From 5868dbc35772e10573e55e9df0249f7ab9eafc1d Mon Sep 17 00:00:00 2001 From: Turtle Date: Sat, 31 Oct 2026 19:46:38 +0800 Subject: [PATCH 39/55] fix(desktop): stop storing Host auth cookies in the Electron session Each Desktop launch picks a random Host port and the native welcome client authenticated through net.fetch with credentials: 'include', so the default Electron session kept one port-named 30-day dsh-auth cookie per launch. Cookies ignore ports, so every request carried all of them; after about 70 launches the Cookie header exceeded Node's 16 KiB limit, the Host answered 431, and startup failed with 'Web authentication failed'. The welcome RPC client and the account WebSocket now send the Cookie header returned by authenticateWebHost explicitly and use no cookie jar. Co-authored-by: lsdsjy <1356263+lsdsjy@users.noreply.github.com> --- apps/desktop/src/account-backend.ts | 57 ++++++++++------------ apps/desktop/src/main.ts | 6 +-- apps/desktop/src/welcome-backend.ts | 29 ++++++----- apps/desktop/tests/account-backend.spec.ts | 8 +-- apps/desktop/tests/main-startup.spec.ts | 3 +- apps/desktop/tests/welcome-flow.e2e.ts | 13 +---- apps/desktop/tests/welcome-host.spec.ts | 38 ++++++--------- apps/desktop/tests/welcome-startup.spec.ts | 3 +- apps/web/tests/desktop-onboarding.e2e.ts | 3 +- 9 files changed, 71 insertions(+), 89 deletions(-) diff --git a/apps/desktop/src/account-backend.ts b/apps/desktop/src/account-backend.ts index 862b8f81ed..19ae3fe796 100644 --- a/apps/desktop/src/account-backend.ts +++ b/apps/desktop/src/account-backend.ts @@ -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): DesktopAccountBackend { +export function desktopAccountBackend(origin: string, invoke: AccountInvoke, cookie: string): DesktopAccountBackend { const call = async (method: string, args: Record = {}): Promise => 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() } diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index d8d0e30c4c..f3f89cd5c1 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -16,7 +16,6 @@ import { powerMonitor, nativeImage, nativeTheme, - net, protocol, session, shell, @@ -529,11 +528,12 @@ async function main(): Promise { return { start: async () => { const ready = await host.start() - hostCookie = await authenticateWebHost(ready.url) + const cookie = await authenticateWebHost(ready.url) + hostCookie = cookie hostUrl = ready.url 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?.() diff --git a/apps/desktop/src/welcome-backend.ts b/apps/desktop/src/welcome-backend.ts index 54ab46d85e..41c706896a 100644 --- a/apps/desktop/src/welcome-backend.ts +++ b/apps/desktop/src/welcome-backend.ts @@ -35,20 +35,19 @@ function record(value: unknown): value is Record { } /** - * 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 with its explicit authentication cookie. + * No cookie jar retains the Host cookie, so launches on new ports do not accumulate cookies. + * @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, - cookies: () => Promise = () => Promise.resolve(''), -): Promise { - 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 = fetch, +): DesktopWelcomeBackend { + const origin = new URL(hostUrl).origin const invoke = async ( request: { namespace: string; method: string; args: Record }, signal?: AbortSignal, @@ -56,8 +55,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 +67,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') diff --git a/apps/desktop/tests/account-backend.spec.ts b/apps/desktop/tests/account-backend.spec.ts index c239336b22..ffdc59d340 100644 --- a/apps/desktop/tests/account-backend.spec.ts +++ b/apps/desktop/tests/account-backend.spec.ts @@ -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() - 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() const opened = Promise.withResolvers() diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index 3b1e63e00c..1a36e58e7d 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -306,7 +306,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) => { @@ -389,7 +388,7 @@ vi.mock('../src/platform-view.ts', async importOriginal => ({ }, })) vi.mock('../src/welcome-backend.ts', () => ({ - connectDesktopWelcome: async () => ({ + connectDesktopWelcome: () => ({ analyticsEnabled: async () => harness.analyticsEnabled, report: harness.analytics, readLocalePreference: async () => null, diff --git a/apps/desktop/tests/welcome-flow.e2e.ts b/apps/desktop/tests/welcome-flow.e2e.ts index ce1dc896b2..08347912ec 100644 --- a/apps/desktop/tests/welcome-flow.e2e.ts +++ b/apps/desktop/tests/welcome-flow.e2e.ts @@ -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') diff --git a/apps/desktop/tests/welcome-host.spec.ts b/apps/desktop/tests/welcome-host.spec.ts index dea2905583..d5dfb480a2 100644 --- a/apps/desktop/tests/welcome-host.spec.ts +++ b/apps/desktop/tests/welcome-host.spec.ts @@ -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[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[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[1]>(async () => new Response(null, { status: 401 })) - await expect(connectDesktopWelcome(url, send)).rejects.toThrow('Web authentication failed') - }) }) diff --git a/apps/desktop/tests/welcome-startup.spec.ts b/apps/desktop/tests/welcome-startup.spec.ts index 4ae8743e2e..0977d1032e 100644 --- a/apps/desktop/tests/welcome-startup.spec.ts +++ b/apps/desktop/tests/welcome-startup.spec.ts @@ -84,7 +84,6 @@ 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(), @@ -124,7 +123,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 () => { diff --git a/apps/web/tests/desktop-onboarding.e2e.ts b/apps/web/tests/desktop-onboarding.e2e.ts index 24c3ada01e..dd19a13252 100644 --- a/apps/web/tests/desktop-onboarding.e2e.ts +++ b/apps/web/tests/desktop-onboarding.e2e.ts @@ -107,7 +107,8 @@ describe.skipIf(MODE === 'record')('web e2e: App-only desktop onboarding', () => async function desktopPage(locale = ZH_BROWSER_LOCALE): Promise { 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)) + // hostFetch replaces the Cookie header with the scaffold's authenticated cookie. + const welcome = connectDesktopWelcome(scaffold.baseUrl, '', (input, init) => scaffold.hostFetch(input, init)) await opened.exposeFunction('__onboardingHasApiKey', async () => (await welcome.read()).hasApiKey) await opened.addInitScript(() => { Object.defineProperty(globalThis, 'dshOnboarding', { value: { From 93bef27ec7bc16524f4fc396f02164549dc0eae9 Mon Sep 17 00:00:00 2001 From: Turtle Date: Sat, 31 Oct 2026 19:55:51 +0800 Subject: [PATCH 40/55] fix(desktop): remove legacy Host auth cookies from the default session Earlier releases left one dsh-auth-* cookie per launch in the default Electron session. Each Host start now removes them so other requests to 127.0.0.1 stop carrying them. Co-authored-by: lsdsjy <1356263+lsdsjy@users.noreply.github.com> --- apps/desktop/README.i18n.yaml | 4 +-- apps/desktop/README.md | 2 +- apps/desktop/README.zh.md | 2 +- apps/desktop/src/main.ts | 4 ++- apps/desktop/src/web-document.ts | 20 ++++++++++++++ apps/desktop/src/welcome-backend.ts | 3 +-- apps/desktop/tests/main-startup.spec.ts | 31 ++++++++++++++-------- apps/desktop/tests/web-document.spec.ts | 13 ++++++++- apps/desktop/tests/welcome-startup.spec.ts | 6 +++-- apps/web/tests/desktop-onboarding.e2e.ts | 4 +-- 10 files changed, 66 insertions(+), 23 deletions(-) diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 3dfceaccd1..899796c03a 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -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 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index fe24b24568..bf36a7b9fe 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -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. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 933e329ce1..6241072116 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -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 均匹配。 diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index f3f89cd5c1..4c223c3c09 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -38,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' @@ -531,6 +531,8 @@ async function main(): Promise { 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 = connectDesktopWelcome(ready.url, cookie) diff --git a/apps/desktop/src/web-document.ts b/apps/desktop/src/web-document.ts index a74ea7c7ef..15f289e14b 100644 --- a/apps/desktop/src/web-document.ts +++ b/apps/desktop/src/web-document.ts @@ -49,6 +49,26 @@ export async function authenticateWebHost(url: string): Promise { 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 + remove(url: string, name: string): Promise +} + +/** + * 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 { + 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 diff --git a/apps/desktop/src/welcome-backend.ts b/apps/desktop/src/welcome-backend.ts index 41c706896a..15b0932cb2 100644 --- a/apps/desktop/src/welcome-backend.ts +++ b/apps/desktop/src/welcome-backend.ts @@ -35,8 +35,7 @@ function record(value: unknown): value is Record { } /** - * Connect the native HTTP client to the Desktop Host with its explicit authentication cookie. - * No cookie jar retains the Host cookie, so launches on new ports do not accumulate cookies. + * 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. diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index 1a36e58e7d..1c93867978 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -22,7 +22,10 @@ type InvokeHandler = (event: InvokeEvent, ...args: unknown[]) => unknown const fileDrag = vi.hoisted(() => ({ dispose: vi.fn<() => Promise>(), 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, @@ -316,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 }, @@ -388,14 +392,17 @@ vi.mock('../src/platform-view.ts', async importOriginal => ({ }, })) vi.mock('../src/welcome-backend.ts', () => ({ - connectDesktopWelcome: () => ({ - analyticsEnabled: async () => harness.analyticsEnabled, - report: harness.analytics, - readLocalePreference: async () => null, - read: async (): Promise => (await harness.hosts.at(-1)!.fetch()).json() as Promise, - 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 => (await harness.hosts.at(-1)!.fetch()).json() as Promise, + save: async () => ({ ok: true }), + account: { watch: harness.watchAccount, state: async () => ({ status: 'signed-out', attempt: null }) }, + } + }, })) function configureTestAuthPopup(allow: boolean): void { @@ -1133,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 }, callback: (result: unknown) => void, diff --git a/apps/desktop/tests/web-document.spec.ts b/apps/desktop/tests/web-document.spec.ts index 0fd9b591b1..6507712ef6 100644 --- a/apps/desktop/tests/web-document.spec.ts +++ b/apps/desktop/tests/web-document.spec.ts @@ -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']]) +}) diff --git a/apps/desktop/tests/welcome-startup.spec.ts b/apps/desktop/tests/welcome-startup.spec.ts index 0977d1032e..e578c8a655 100644 --- a/apps/desktop/tests/welcome-startup.spec.ts +++ b/apps/desktop/tests/welcome-startup.spec.ts @@ -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' @@ -86,7 +88,7 @@ vi.mock('electron', () => ({ }, 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() }, diff --git a/apps/web/tests/desktop-onboarding.e2e.ts b/apps/web/tests/desktop-onboarding.e2e.ts index dd19a13252..417edf8bba 100644 --- a/apps/web/tests/desktop-onboarding.e2e.ts +++ b/apps/web/tests/desktop-onboarding.e2e.ts @@ -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,8 +108,7 @@ describe.skipIf(MODE === 'record')('web e2e: App-only desktop onboarding', () => async function desktopPage(locale = ZH_BROWSER_LOCALE): Promise { const opened = await browser.newPage({ viewport: { width: 1280, height: 840 }, locale, reducedMotion: 'reduce' }) - // hostFetch replaces the Cookie header with the scaffold's authenticated cookie. - const welcome = connectDesktopWelcome(scaffold.baseUrl, '', (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: { From 8394c706fc888b9189f37eb40046d68716aab02a Mon Sep 17 00:00:00 2001 From: Turtle Date: Sat, 31 Oct 2026 20:22:50 +0800 Subject: [PATCH 41/55] test(desktop): cover legacy Host cookie cleanup failure Co-authored-by: lsdsjy <1356263+lsdsjy@users.noreply.github.com> --- apps/desktop/tests/main-startup.spec.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index 1c93867978..924808eb0d 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -1132,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() @@ -1163,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]! From 898b2875b357d3030546df5117f028fc1a6f3c29 Mon Sep 17 00:00:00 2001 From: Turtle Date: Sun, 1 Nov 2026 21:47:19 +0800 Subject: [PATCH 42/55] fix(client): copy selected KaTeX math as TeX source Refs #7690 --- apps/web/tests/math-rendering.e2e.ts | 20 ++++ .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- .../src/markdown/MarkdownText.tsx | 7 +- .../ui-primitives/src/markdown/copy-tex.ts | 50 ++++++++ .../tests/markdown-copy-tex.client.spec.tsx | 107 ++++++++++++++++++ 7 files changed, 186 insertions(+), 6 deletions(-) create mode 100644 packages/client/ui-primitives/src/markdown/copy-tex.ts create mode 100644 packages/client/ui-primitives/tests/markdown-copy-tex.client.spec.tsx diff --git a/apps/web/tests/math-rendering.e2e.ts b/apps/web/tests/math-rendering.e2e.ts index d7fa2b8873..c3395b02a4 100644 --- a/apps/web/tests/math-rendering.e2e.ts +++ b/apps/web/tests/math-rendering.e2e.ts @@ -141,4 +141,24 @@ 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.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) + window.addEventListener('copy', (event) => { + document.documentElement.dataset['copied'] = event.clipboardData!.getData('text/plain') + }, { once: true }) + }) + await page.keyboard.press('ControlOrMeta+c') + expect(await page.locator('html').getAttribute('data-copied')).toBe( + 'Inline dollar $\\theta$ and backslash $\\frac{1}{5}$.\n\n$$\\frac{\\pi}{4} < \\theta < \\frac{\\pi}{2}$$', + ) + }, 30_000) }) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index d04786950e..41fe9cecfc 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -24,8 +24,8 @@ en: 0d756c1e8207181d zh: 921ce997c6b14823 /deepseek-ai-dsh-client-ui-primitives/use-this-package/rendering-agent-output: - en: 3271871a42bd52c8 - zh: 89b7a9f03018454d + en: 429c8563ef56a86c + zh: adc3123f738c3db2 /deepseek-ai-dsh-client-ui-primitives/use-this-package/localizing-copy: en: 81e58c7b342baf3c zh: 6cd47b16124b215c diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 299c78633c..1810407349 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -115,7 +115,7 @@ The nearest `MarkdownDelegateProvider` supplies optional `openExternalLink` and Explicit `./`, `../`, slash/backslash-rooted paths (including UNC), and Windows drive paths such as `C:/work/file.ts` take precedence over URL parsing. Otherwise, destinations accepted by the absolute URL parser remain URLs: `index.ts:24`, `Makefile:12`, and `localhost:3000` are links, without adding a protocol or testing whether they can open. Use `./index.ts:24` for a file reference. Other destinations are paths. Authored links reject `javascript:`, `vbscript:`, `data:`, and `blob:`; other parseable protocols retain native navigation. HTTP(S) links retain delegated navigation and modified-click behavior. No click-time failure notice is added. -`MarkdownText` renders untrusted GFM and TeX math, blocks unsafe links and images, and can turn resolved file mentions into explicit controls. Strikethrough requires `~~`; a single `~`, as in `10~20`, stays literal. A bare URL ends before non-ASCII punctuation or symbols, such as `。` or `,`, so CJK prose that follows it stays outside the link. A surrounding `MarkdownDelegateProvider` receives sanitized HTTP(S) URLs from ordinary clicks; modified clicks and links outside a provider retain native external-anchor behavior. `omitHtml` renders raw HTML as nothing instead of literal text, for documents written for HTML renderers. When the owner passes a `pathImages` vocabulary, image destinations that are local media paths rewrite to displayable URLs on settled renders only (the same streaming gate as file mentions); without a vocabulary, local destinations remain inert alt text. Rewritten images accept HTTP(S), data, blob, and the Desktop `dsh-app://app/api/file`, `dsh-app://app/api/plugin-market/detail-file`, and `dsh-app://app/api/plugin-manager/detail-file` routes; authored Desktop URLs remain inert. A load or decode failure replaces the image with its authored alt text, or the original destination when alt is empty; `fileImages` additionally supplies a localized failure prefix. Changing the image source permits a fresh load. Each mounted image appends a `load` query parameter to a resolved Host `api/file` URL, because browsers reuse a same-URL image within one document despite `no-store`; a newly rendered image of an overwritten file therefore loads its current bytes, and every remount requests the file again; the Host file route redirects that request to a cacheable URL for the current file version. While a reply streams, it freezes completed blocks, advances a top-level open fence by completed lines, and highlights that fence from saved Shiki grammar state. Completed token lines enter fixed-size React groups, so later chunks reconcile only the growing group; an unchanged fence retains that DOM when the final full parse resolves cross-document syntax. `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, and `WebBlock` render the matching tool-result intent with copy controls, overflow handling, and ANSI processing where applicable. `JsonTree` and `JsonBlock` inspect JSON values read-only, while `UserTextRun` renders uninterpreted text and `ReferenceChip` renders business-resolved labels. An explicit `onActivate` makes a chip a keyboard-accessible button; repeated pointer clicks and an existing text selection do not activate it, while keyboard activation remains available. Labels inherit their host’s wrapping policy. Recognition and JSON transforms belong to [ui-conversation](../ui-conversation/README.md#sent-user-text). +`MarkdownText` renders untrusted GFM and TeX math, blocks unsafe links and images, and can turn resolved file mentions into explicit controls. Copying a selection that includes rendered math puts each whole formula on the clipboard as TeX source in both plain text and HTML, delimited as `$…$` inline and `$$…$$` for display math. Strikethrough requires `~~`; a single `~`, as in `10~20`, stays literal. A bare URL ends before non-ASCII punctuation or symbols, such as `。` or `,`, so CJK prose that follows it stays outside the link. A surrounding `MarkdownDelegateProvider` receives sanitized HTTP(S) URLs from ordinary clicks; modified clicks and links outside a provider retain native external-anchor behavior. `omitHtml` renders raw HTML as nothing instead of literal text, for documents written for HTML renderers. When the owner passes a `pathImages` vocabulary, image destinations that are local media paths rewrite to displayable URLs on settled renders only (the same streaming gate as file mentions); without a vocabulary, local destinations remain inert alt text. Rewritten images accept HTTP(S), data, blob, and the Desktop `dsh-app://app/api/file`, `dsh-app://app/api/plugin-market/detail-file`, and `dsh-app://app/api/plugin-manager/detail-file` routes; authored Desktop URLs remain inert. A load or decode failure replaces the image with its authored alt text, or the original destination when alt is empty; `fileImages` additionally supplies a localized failure prefix. Changing the image source permits a fresh load. Each mounted image appends a `load` query parameter to a resolved Host `api/file` URL, because browsers reuse a same-URL image within one document despite `no-store`; a newly rendered image of an overwritten file therefore loads its current bytes, and every remount requests the file again; the Host file route redirects that request to a cacheable URL for the current file version. While a reply streams, it freezes completed blocks, advances a top-level open fence by completed lines, and highlights that fence from saved Shiki grammar state. Completed token lines enter fixed-size React groups, so later chunks reconcile only the growing group; an unchanged fence retains that DOM when the final full parse resolves cross-document syntax. `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, and `WebBlock` render the matching tool-result intent with copy controls, overflow handling, and ANSI processing where applicable. `JsonTree` and `JsonBlock` inspect JSON values read-only, while `UserTextRun` renders uninterpreted text and `ReferenceChip` renders business-resolved labels. An explicit `onActivate` makes a chip a keyboard-accessible button; repeated pointer clicks and an existing text selection do not activate it, while keyboard activation remains available. Labels inherit their host’s wrapping policy. Recognition and JSON transforms belong to [ui-conversation](../ui-conversation/README.md#sent-user-text). `MarkdownText` defaults to `variant="body"`. Use `variant="compact"` for secondary content: its 13px text and 20px line height follow the content-size setting, all heading levels use the same size with weight 600, and paragraphs and lists use tighter spacing. Text, links, and code keep the tertiary color; dotted underlines distinguish links. Code headers scroll with their blocks. Tables and math stay enabled at the surrounding text size and scroll horizontally within the available width. Both variants share the parser and streaming cache. `textInteractionSource` marks its existing root as a source for text selection interactions. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 29fd963e29..81a8fe8006 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -115,7 +115,7 @@ kind: "package-library" 明确的 `./`、`../`、斜杠或反斜杠开头的路径(包括 UNC),以及 `C:/work/file.ts` 这样的 Windows 盘符路径优先于 URL 解析。其余目标若能被绝对 URL 解析器接受,就保留为 URL:`index.ts:24`、`Makefile:12` 和 `localhost:3000` 均为链接,不补协议,也不预先检查能否打开。文件引用使用 `./index.ts:24`。其他目标视为路径。正文链接禁止 `javascript:`、`vbscript:`、`data:` 和 `blob:`;其余可解析的协议保留原生导航。HTTP(S) 链接保留委托导航和修饰键点击行为。不添加点击后的失败提示。 -`MarkdownText` 渲染不可信的 GFM 与 TeX 公式、阻止不安全的链接与图片,并可把已解析的文件提及转换为显式控件。删除线需要 `~~`;单个 `~`(如 `10~20`)保持字面文本。裸 URL 在非 ASCII 标点或符号(如 `。`、`,`)前结束,紧随其后的中文正文不会并入链接。外层 `MarkdownDelegateProvider` 会接收普通点击产生的已净化 HTTP(S) URL;带修饰键的点击和 Provider 外的链接保留原生外部 anchor 行为。`omitHtml` 不渲染原始 HTML,而不是将其显示为原样文本,用于为 HTML 渲染器编写的文档。当 owner 传入 `pathImages` 词表时,本地媒体路径的图片目标只在落定渲染阶段重写为可展示 URL(与 file mentions 相同的流式门);不传词表时本地目标保持惰性 alt 文本。重写后的图片支持 HTTP(S)、data、blob 及桌面端 `dsh-app://app/api/file`、`dsh-app://app/api/plugin-market/detail-file` 与 `dsh-app://app/api/plugin-manager/detail-file` 路由;正文直接书写的桌面端 URL 仍保持惰性。加载或解码失败后,图片替换为作者的 alt 文本;alt 为空时显示原始目标路径;`fileImages` 还提供本地化的失败提示前缀。图片源变化后可重新加载。每个挂载的图片会为解析得到的 Host `api/file` 地址追加 `load` 查询参数,因为浏览器在同一文档内会无视 `no-store` 复用相同 URL 的图片;因此覆盖后的文件在新渲染的图片中会加载当前内容,每次重新挂载都会重新请求该文件;Host 文件路由会把该请求重定向到当前文件版本的可缓存地址。回复流式输出时,它冻结已完成的块、按已完成行推进顶层未闭合 fence,并从保存的 Shiki grammar state 为该 fence 增量高亮。已完成的 token 行进入固定大小的 React 分组,后续分片只 reconcile 正在增长的分组;最终全量解析解决跨文档语法时,未变化的 fence 会保留该 DOM。`TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock` 与 `WebBlock` 把对应的工具结果意图渲染为带复制控件、溢出处理及适用时 ANSI 处理的卡片。`JsonTree` 与 `JsonBlock` 以只读方式检查 JSON 值;`UserTextRun` 渲染不做解析的文本,`ReferenceChip` 渲染业务已解析的标签。显式传入 `onActivate` 后,胶囊成为可由键盘操作的按钮;重复指针点击和已有文本选区不触发激活,键盘激活仍然可用。标签继承所属容器的换行规则。识别和 JSON 变换由 [ui-conversation](../ui-conversation/README.zh.md#sent-user-text) 负责。 +`MarkdownText` 渲染不可信的 GFM 与 TeX 公式、阻止不安全的链接与图片,并可把已解析的文件提及转换为显式控件。复制包含已渲染公式的选区时,每个完整公式会以 TeX 源码同时写入剪贴板的纯文本和 HTML 格式,行内公式用 `$…$` 包裹,展示公式用 `$$…$$` 包裹。删除线需要 `~~`;单个 `~`(如 `10~20`)保持字面文本。裸 URL 在非 ASCII 标点或符号(如 `。`、`,`)前结束,紧随其后的中文正文不会并入链接。外层 `MarkdownDelegateProvider` 会接收普通点击产生的已净化 HTTP(S) URL;带修饰键的点击和 Provider 外的链接保留原生外部 anchor 行为。`omitHtml` 不渲染原始 HTML,而不是将其显示为原样文本,用于为 HTML 渲染器编写的文档。当 owner 传入 `pathImages` 词表时,本地媒体路径的图片目标只在落定渲染阶段重写为可展示 URL(与 file mentions 相同的流式门);不传词表时本地目标保持惰性 alt 文本。重写后的图片支持 HTTP(S)、data、blob 及桌面端 `dsh-app://app/api/file`、`dsh-app://app/api/plugin-market/detail-file` 与 `dsh-app://app/api/plugin-manager/detail-file` 路由;正文直接书写的桌面端 URL 仍保持惰性。加载或解码失败后,图片替换为作者的 alt 文本;alt 为空时显示原始目标路径;`fileImages` 还提供本地化的失败提示前缀。图片源变化后可重新加载。每个挂载的图片会为解析得到的 Host `api/file` 地址追加 `load` 查询参数,因为浏览器在同一文档内会无视 `no-store` 复用相同 URL 的图片;因此覆盖后的文件在新渲染的图片中会加载当前内容,每次重新挂载都会重新请求该文件;Host 文件路由会把该请求重定向到当前文件版本的可缓存地址。回复流式输出时,它冻结已完成的块、按已完成行推进顶层未闭合 fence,并从保存的 Shiki grammar state 为该 fence 增量高亮。已完成的 token 行进入固定大小的 React 分组,后续分片只 reconcile 正在增长的分组;最终全量解析解决跨文档语法时,未变化的 fence 会保留该 DOM。`TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock` 与 `WebBlock` 把对应的工具结果意图渲染为带复制控件、溢出处理及适用时 ANSI 处理的卡片。`JsonTree` 与 `JsonBlock` 以只读方式检查 JSON 值;`UserTextRun` 渲染不做解析的文本,`ReferenceChip` 渲染业务已解析的标签。显式传入 `onActivate` 后,胶囊成为可由键盘操作的按钮;重复指针点击和已有文本选区不触发激活,键盘激活仍然可用。标签继承所属容器的换行规则。识别和 JSON 变换由 [ui-conversation](../ui-conversation/README.zh.md#sent-user-text) 负责。 `MarkdownText` 默认为 `variant="body"`。次级内容使用 `variant="compact"`:其 13px 字号与 20px 行高跟随内容字号设置,各级标题保持同一字号并使用 600 字重,段落与列表采用更紧凑的间距。正文、链接和代码均保持 tertiary 颜色,以点状下划线区分链接。代码标题栏随代码块滚动。表格和公式仍然启用,使用周围文字的字号,并在可用宽度内横向滚动。两个变体共享解析器与流式缓存。 `textInteractionSource` 将已有根元素标记为文本选区交互的来源。 diff --git a/packages/client/ui-primitives/src/markdown/MarkdownText.tsx b/packages/client/ui-primitives/src/markdown/MarkdownText.tsx index 004c962963..43751d1991 100644 --- a/packages/client/ui-primitives/src/markdown/MarkdownText.tsx +++ b/packages/client/ui-primitives/src/markdown/MarkdownText.tsx @@ -14,6 +14,7 @@ import { memo, useMemo, useRef } from 'react' import type { ReactNode } from 'react' import clsx from 'clsx' +import { copyKatexAsTex } from './copy-tex.ts' import { IncrementalMarkdownParser } from './incremental.ts' import { parseGfm, parseGfmWithMath } from './parse.ts' import { @@ -179,7 +180,8 @@ class StreamingRenderer { * including `#L24` / `#L24-L30` fragments and `:24` / `:24-30` / `:24:5` suffixes * (ranges open at their first line, columns are ignored, and invalid locations * open only the file; see the README for URL/path classification). - * @returns A GFM document with TeX math rendered through KaTeX; raw HTML never + * @returns A GFM document with TeX math rendered through KaTeX, whose + * selected formulas copy as `$…$` / `$$…$$` TeX source; raw HTML never * renders as markup, and unsafe protocols are disabled. Local links without an opener remain text; * absolute HTTP(S) images render directly. */ @@ -210,5 +212,6 @@ export const MarkdownText = memo(function MarkdownText({ }, [text, streaming, labels, fileMentions, pathImages, omitHtml]) return
{children}
+ data-markdown-variant={variant === 'compact' ? variant : undefined} + onCopy={(event) => { copyKatexAsTex(event.nativeEvent, event.currentTarget.ownerDocument) }}>{children} }) diff --git a/packages/client/ui-primitives/src/markdown/copy-tex.ts b/packages/client/ui-primitives/src/markdown/copy-tex.ts new file mode 100644 index 0000000000..527d5618c6 --- /dev/null +++ b/packages/client/ui-primitives/src/markdown/copy-tex.ts @@ -0,0 +1,50 @@ +/** Clipboard projection that copies rendered KaTeX formulas as their TeX source. */ + +/** The whole formula around a node, including the display wrapper that marks display math. */ +function closestFormula(node: Node): Element | null { + const element = node instanceof Element ? node : node.parentElement + return element?.closest('.katex-display') ?? element?.closest('.katex') ?? null +} + +/** + * Rewrite a copy whose document selection includes rendered math so each + * formula becomes its TeX source, delimited as `$…$` inline and `$$…$$` for + * display math, in both the plain-text and HTML clipboard data. A selection + * endpoint inside a formula extends to the whole formula in the clipboard only; + * the visible selection is unchanged. Copies without math, or already handled + * by an inner listener, keep their data. + * @param event - Native copy event. + * @param document - Document whose selection is copied. + */ +export function copyKatexAsTex(event: ClipboardEvent, document: Document): void { + const selection = document.getSelection() + if (event.defaultPrevented || event.clipboardData === null || selection === null + || selection.rangeCount !== 1 || selection.isCollapsed) return + const range = selection.getRangeAt(0).cloneRange() + const startFormula = closestFormula(range.startContainer) + if (startFormula !== null) range.setStartBefore(startFormula) + const endFormula = closestFormula(range.endContainer) + if (endFormula !== null) range.setEndAfter(endFormula) + const fragment = range.cloneContents() + const formulas = [...fragment.querySelectorAll('.katex')] + if (formulas.length === 0) return + for (const formula of formulas) { + const tex = formula.querySelector('annotation[encoding="application/x-tex"]')?.textContent + if (tex === undefined) continue + const delimiter = formula.closest('.katex-display') === null ? '$' : '$$' + formula.replaceWith(`${delimiter}${tex}${delimiter}`) + } + // innerText applies the browser's own block and line-break serialization, + // which needs a rendered element; an off-screen one keeps it invisible. + const container = document.createElement('div') + container.style.cssText = 'position:fixed;top:0;left:-100000px;white-space:normal;pointer-events:none' + container.append(fragment) + document.body.append(container) + try { + event.clipboardData.setData('text/plain', container.innerText) + event.clipboardData.setData('text/html', container.innerHTML) + } finally { + container.remove() + } + event.preventDefault() +} diff --git a/packages/client/ui-primitives/tests/markdown-copy-tex.client.spec.tsx b/packages/client/ui-primitives/tests/markdown-copy-tex.client.spec.tsx new file mode 100644 index 0000000000..d73f217a5f --- /dev/null +++ b/packages/client/ui-primitives/tests/markdown-copy-tex.client.spec.tsx @@ -0,0 +1,107 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render } from '@testing-library/react' +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest' +import { MarkdownText } from './markdown-test-components.tsx' +import { copyKatexAsTex } from '../src/markdown/copy-tex.ts' + +// jsdom implements no layout, so innerText falls back to textContent here; +// math-rendering.e2e.ts covers the browser's line breaks. +beforeAll(() => { + Object.defineProperty(HTMLElement.prototype, 'innerText', { + configurable: true, + get(this: HTMLElement) { return this.textContent }, + }) +}) +afterAll(() => { Reflect.deleteProperty(HTMLElement.prototype, 'innerText') }) +afterEach(() => { + document.getSelection()?.removeAllRanges() + cleanup() +}) + +function select(start: Node, startOffset: number, end: Node, endOffset: number): void { + const range = document.createRange() + range.setStart(start, startOffset) + range.setEnd(end, endOffset) + document.getSelection()!.removeAllRanges() + document.getSelection()!.addRange(range) +} + +function copy(target: Element): { data: Map; prevented: boolean } { + const data = new Map() + const clipboardData = { setData: (type: string, value: string) => { data.set(type, value) } } + const prevented = !fireEvent.copy(target, { clipboardData }) + return { data, prevented } +} + +describe('MarkdownText math copy', () => { + it('copies selected formulas as delimited TeX source', () => { + const view = render() + const paragraphs = view.container.querySelectorAll('p') + const inlineVisual = view.container.querySelector('.katex-html')! + const lastText = paragraphs[paragraphs.length - 1]!.firstChild! + select(inlineVisual.firstChild!, 0, lastText, 3) + const { data, prevented } = copy(inlineVisual) + expect(prevented).toBe(true) + const plain = data.get('text/plain')! + expect(plain).toBe('$E=mc^2$ and\n$$\\frac{a}{b}$$\nend') + expect(data.get('text/html')).toContain('$E=mc^2$') + expect(document.body.textContent).not.toContain('$E=mc^2$') + expect(document.getSelection()!.getRangeAt(0).startContainer).toBe(inlineVisual.firstChild) + }) + + it('extends a selection ending inside a formula to the whole formula', () => { + const view = render() + const paragraph = view.container.querySelector('p')! + const visualText = view.container.querySelector('.katex-html .mord')!.firstChild! + select(paragraph.firstChild!, 0, visualText, 1) + expect(copy(paragraph).data.get('text/plain')).toBe('Energy $E=mc^2$') + }) + + it('marks a selection entirely inside display math as display TeX', () => { + const view = render() + const glyph = view.container.querySelector('.katex-display .katex-html .mord')! + select(glyph, 0, glyph, 1) + expect(copy(glyph).data.get('text/plain')).toBe('$$\\frac{a}{b}$$') + }) + + it('keeps native copy without math or with a collapsed selection', () => { + const view = render() + const text = view.container.querySelector('p')!.firstChild! + select(text, 0, text, 5) + expect(copy(text.parentElement!)).toEqual({ data: new Map(), prevented: false }) + select(text, 0, text, 0) + expect(copy(text.parentElement!).prevented).toBe(false) + }) + + it('leaves a copy that an inner listener already handled', () => { + const view = render() + const paragraph = view.container.querySelector('p')! + paragraph.addEventListener('copy', (event) => { + event.clipboardData!.setData('text/plain', 'inner') + event.preventDefault() + }) + select(paragraph, 0, paragraph, paragraph.childNodes.length) + expect(copy(paragraph).data).toEqual(new Map([['text/plain', 'inner']])) + }) + + it('ignores a copy without clipboard data', () => { + render() + const paragraph = document.querySelector('p')! + select(paragraph, 0, paragraph, paragraph.childNodes.length) + const event = new Event('copy', { cancelable: true }) as ClipboardEvent + Object.defineProperty(event, 'clipboardData', { value: null }) + copyKatexAsTex(event, document) + expect(event.defaultPrevented).toBe(false) + }) + + it('leaves a formula without TeX annotation as rendered text', () => { + const root = document.createElement('div') + root.innerHTML = '

a visual b

' + document.body.append(root) + root.addEventListener('copy', (event) => { copyKatexAsTex(event, document) }) + select(root, 0, root, 1) + const { data } = copy(root) + expect(data.get('text/plain')).toBe('a visual b') + root.remove() + }) +}) From 0039a8879a77962fb841fbff3e78b80968a66508 Mon Sep 17 00:00:00 2001 From: Turtle Date: Sun, 1 Nov 2026 22:00:57 +0800 Subject: [PATCH 43/55] fix(client): scope math copy to one Markdown document Refs #7690 --- apps/web/tests/math-rendering.e2e.ts | 28 ++++----- .../client/ui-primitives/README.i18n.yaml | 8 +-- packages/client/ui-primitives/README.md | 3 +- packages/client/ui-primitives/README.zh.md | 3 +- .../src/markdown/MarkdownText.tsx | 7 ++- .../ui-primitives/src/markdown/copy-tex.ts | 31 +++++----- .../tests/markdown-copy-tex.client.spec.tsx | 58 +++++++++++++------ 7 files changed, 85 insertions(+), 53 deletions(-) diff --git a/apps/web/tests/math-rendering.e2e.ts b/apps/web/tests/math-rendering.e2e.ts index c3395b02a4..7f31d0a3fe 100644 --- a/apps/web/tests/math-rendering.e2e.ts +++ b/apps/web/tests/math-rendering.e2e.ts @@ -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) @@ -144,6 +143,10 @@ describe('web e2e: settled Markdown math rendering', () => { 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')! @@ -152,13 +155,12 @@ describe('web e2e: settled Markdown math rendering', () => { range.setEnd(visual.firstChild!, 1) document.getSelection()!.removeAllRanges() document.getSelection()!.addRange(range) - window.addEventListener('copy', (event) => { - document.documentElement.dataset['copied'] = event.clipboardData!.getData('text/plain') - }, { once: true }) }) - await page.keyboard.press('ControlOrMeta+c') - expect(await page.locator('html').getAttribute('data-copied')).toBe( + 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) }) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 41fe9cecfc..75b0d5e942 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -24,8 +24,8 @@ en: 0d756c1e8207181d zh: 921ce997c6b14823 /deepseek-ai-dsh-client-ui-primitives/use-this-package/rendering-agent-output: - en: 429c8563ef56a86c - zh: adc3123f738c3db2 + en: e2649937f077d4e0 + zh: 6ad604cb5adfc16b /deepseek-ai-dsh-client-ui-primitives/use-this-package/localizing-copy: en: 81e58c7b342baf3c zh: 6cd47b16124b215c @@ -54,8 +54,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-client-ui-primitives/known-limitations-and-deferred-work: - en: 6b4d21406db53e7c - zh: aa130102a8f7cd13 + en: 433ff539bd3d16b3 + zh: fcb37c1fbe503620 /deepseek-ai-dsh-client-ui-primitives/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 1810407349..13c8e21341 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -115,7 +115,7 @@ The nearest `MarkdownDelegateProvider` supplies optional `openExternalLink` and Explicit `./`, `../`, slash/backslash-rooted paths (including UNC), and Windows drive paths such as `C:/work/file.ts` take precedence over URL parsing. Otherwise, destinations accepted by the absolute URL parser remain URLs: `index.ts:24`, `Makefile:12`, and `localhost:3000` are links, without adding a protocol or testing whether they can open. Use `./index.ts:24` for a file reference. Other destinations are paths. Authored links reject `javascript:`, `vbscript:`, `data:`, and `blob:`; other parseable protocols retain native navigation. HTTP(S) links retain delegated navigation and modified-click behavior. No click-time failure notice is added. -`MarkdownText` renders untrusted GFM and TeX math, blocks unsafe links and images, and can turn resolved file mentions into explicit controls. Copying a selection that includes rendered math puts each whole formula on the clipboard as TeX source in both plain text and HTML, delimited as `$…$` inline and `$$…$$` for display math. Strikethrough requires `~~`; a single `~`, as in `10~20`, stays literal. A bare URL ends before non-ASCII punctuation or symbols, such as `。` or `,`, so CJK prose that follows it stays outside the link. A surrounding `MarkdownDelegateProvider` receives sanitized HTTP(S) URLs from ordinary clicks; modified clicks and links outside a provider retain native external-anchor behavior. `omitHtml` renders raw HTML as nothing instead of literal text, for documents written for HTML renderers. When the owner passes a `pathImages` vocabulary, image destinations that are local media paths rewrite to displayable URLs on settled renders only (the same streaming gate as file mentions); without a vocabulary, local destinations remain inert alt text. Rewritten images accept HTTP(S), data, blob, and the Desktop `dsh-app://app/api/file`, `dsh-app://app/api/plugin-market/detail-file`, and `dsh-app://app/api/plugin-manager/detail-file` routes; authored Desktop URLs remain inert. A load or decode failure replaces the image with its authored alt text, or the original destination when alt is empty; `fileImages` additionally supplies a localized failure prefix. Changing the image source permits a fresh load. Each mounted image appends a `load` query parameter to a resolved Host `api/file` URL, because browsers reuse a same-URL image within one document despite `no-store`; a newly rendered image of an overwritten file therefore loads its current bytes, and every remount requests the file again; the Host file route redirects that request to a cacheable URL for the current file version. While a reply streams, it freezes completed blocks, advances a top-level open fence by completed lines, and highlights that fence from saved Shiki grammar state. Completed token lines enter fixed-size React groups, so later chunks reconcile only the growing group; an unchanged fence retains that DOM when the final full parse resolves cross-document syntax. `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, and `WebBlock` render the matching tool-result intent with copy controls, overflow handling, and ANSI processing where applicable. `JsonTree` and `JsonBlock` inspect JSON values read-only, while `UserTextRun` renders uninterpreted text and `ReferenceChip` renders business-resolved labels. An explicit `onActivate` makes a chip a keyboard-accessible button; repeated pointer clicks and an existing text selection do not activate it, while keyboard activation remains available. Labels inherit their host’s wrapping policy. Recognition and JSON transforms belong to [ui-conversation](../ui-conversation/README.md#sent-user-text). +`MarkdownText` renders untrusted GFM and TeX math, blocks unsafe links and images, and can turn resolved file mentions into explicit controls. Copying a selection that lies inside one `MarkdownText` document and includes rendered math puts each whole formula on the clipboard as TeX source in both plain text and HTML, delimited as `$…$` inline and `$$…$$` for display math. Strikethrough requires `~~`; a single `~`, as in `10~20`, stays literal. A bare URL ends before non-ASCII punctuation or symbols, such as `。` or `,`, so CJK prose that follows it stays outside the link. A surrounding `MarkdownDelegateProvider` receives sanitized HTTP(S) URLs from ordinary clicks; modified clicks and links outside a provider retain native external-anchor behavior. `omitHtml` renders raw HTML as nothing instead of literal text, for documents written for HTML renderers. When the owner passes a `pathImages` vocabulary, image destinations that are local media paths rewrite to displayable URLs on settled renders only (the same streaming gate as file mentions); without a vocabulary, local destinations remain inert alt text. Rewritten images accept HTTP(S), data, blob, and the Desktop `dsh-app://app/api/file`, `dsh-app://app/api/plugin-market/detail-file`, and `dsh-app://app/api/plugin-manager/detail-file` routes; authored Desktop URLs remain inert. A load or decode failure replaces the image with its authored alt text, or the original destination when alt is empty; `fileImages` additionally supplies a localized failure prefix. Changing the image source permits a fresh load. Each mounted image appends a `load` query parameter to a resolved Host `api/file` URL, because browsers reuse a same-URL image within one document despite `no-store`; a newly rendered image of an overwritten file therefore loads its current bytes, and every remount requests the file again; the Host file route redirects that request to a cacheable URL for the current file version. While a reply streams, it freezes completed blocks, advances a top-level open fence by completed lines, and highlights that fence from saved Shiki grammar state. Completed token lines enter fixed-size React groups, so later chunks reconcile only the growing group; an unchanged fence retains that DOM when the final full parse resolves cross-document syntax. `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, and `WebBlock` render the matching tool-result intent with copy controls, overflow handling, and ANSI processing where applicable. `JsonTree` and `JsonBlock` inspect JSON values read-only, while `UserTextRun` renders uninterpreted text and `ReferenceChip` renders business-resolved labels. An explicit `onActivate` makes a chip a keyboard-accessible button; repeated pointer clicks and an existing text selection do not activate it, while keyboard activation remains available. Labels inherit their host’s wrapping policy. Recognition and JSON transforms belong to [ui-conversation](../ui-conversation/README.md#sent-user-text). `MarkdownText` defaults to `variant="body"`. Use `variant="compact"` for secondary content: its 13px text and 20px line height follow the content-size setting, all heading levels use the same size with weight 600, and paragraphs and lists use tighter spacing. Text, links, and code keep the tertiary color; dotted underlines distinguish links. Code headers scroll with their blocks. Tables and math stay enabled at the surrounding text size and scroll horizontally within the available width. Both variants share the parser and streaming cache. `textInteractionSource` marks its existing root as a source for text selection interactions. @@ -230,6 +230,7 @@ These limits define how the atoms behave at the edges; they are current package - **Known-site marks are a fixed list** — only the named hosts resolve to their own mark, and every other external host keeps the globe; recognizing an arbitrary site would require fetching its icon over the network. - **Streaming defers cross-boundary reference resolution** — a reference-style link or footnote whose definition sits on the other side of the incremental freeze boundary renders as literal text while the reply streams; the settled full parse at finalize resolves it. - **A long highlighted fence retains its complete token DOM** — streaming avoids re-parsing, re-tokenizing, and reconciling the completed prefix, but it does not discard old colors or virtualize token spans. Final DOM cardinality therefore still follows the fence's token count; nested/container fences and a pathological single long line remain on the general tail path. +- **Math copies as TeX only within one Markdown document** — a selection that reaches outside its `MarkdownText` root, such as from a user message into a reply, keeps the browser's native copy, which joins KaTeX's hidden MathML text with the visible glyphs. Inside one document, the plain text of non-math content comes from `innerText`, so code-block language labels and copy-button text are included, as in native copy. - **Overlong lines stay uncolored** — a source line of 1,000 or more UTF-16 units renders as one plain run in every highlighted surface, because TextMate scanning cost grows superlinearly with line length and a single generated line can otherwise block the page for seconds. The grammar state skips that line, so a comment or template literal that opens or closes on it mis-colors the following lines. Highlighting still runs synchronously during render, so a file with thousands of ordinary lines costs proportionally more. - **Bare URLs end before non-ASCII punctuation** — the [tokenizer patch](../../../patches/micromark-extension-gfm-autolink-literal@2.1.0.patch) and the [transform patch](../../../patches/mdast-util-gfm-autolink-literal@2.0.1.patch) end a GFM autolink literal at non-ASCII punctuation, symbols, or whitespace, so a URL with an unencoded character such as `(` or `・` in its path links only up to it; write such a URL as `<…>` or `[…](…)`. A URL followed directly by CJK letters still links them, because paths such as `/wiki/中文` are valid. Both patches are keyed to exact versions: an upgrade of either package must re-apply or retire its patch, otherwise the boundary rule silently disappears. - **The Go struct-field rule is patched locally** — when the Go grammar loads, its repeated one-line struct-field rule is replaced with the rule [worlpaker/go-syntax#25](https://github.com/worlpaker/go-syntax/pull/25) merged, because the vendored rule backtracks exponentially on lines such as a brace-bearing comment after `struct {`. If a dependency upgrade removes that rule, loading the grammar throws and Go code renders as plain text; delete the patch once `@shikijs/langs` ships the upstream rule. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 81a8fe8006..77bf13ebc9 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -115,7 +115,7 @@ kind: "package-library" 明确的 `./`、`../`、斜杠或反斜杠开头的路径(包括 UNC),以及 `C:/work/file.ts` 这样的 Windows 盘符路径优先于 URL 解析。其余目标若能被绝对 URL 解析器接受,就保留为 URL:`index.ts:24`、`Makefile:12` 和 `localhost:3000` 均为链接,不补协议,也不预先检查能否打开。文件引用使用 `./index.ts:24`。其他目标视为路径。正文链接禁止 `javascript:`、`vbscript:`、`data:` 和 `blob:`;其余可解析的协议保留原生导航。HTTP(S) 链接保留委托导航和修饰键点击行为。不添加点击后的失败提示。 -`MarkdownText` 渲染不可信的 GFM 与 TeX 公式、阻止不安全的链接与图片,并可把已解析的文件提及转换为显式控件。复制包含已渲染公式的选区时,每个完整公式会以 TeX 源码同时写入剪贴板的纯文本和 HTML 格式,行内公式用 `$…$` 包裹,展示公式用 `$$…$$` 包裹。删除线需要 `~~`;单个 `~`(如 `10~20`)保持字面文本。裸 URL 在非 ASCII 标点或符号(如 `。`、`,`)前结束,紧随其后的中文正文不会并入链接。外层 `MarkdownDelegateProvider` 会接收普通点击产生的已净化 HTTP(S) URL;带修饰键的点击和 Provider 外的链接保留原生外部 anchor 行为。`omitHtml` 不渲染原始 HTML,而不是将其显示为原样文本,用于为 HTML 渲染器编写的文档。当 owner 传入 `pathImages` 词表时,本地媒体路径的图片目标只在落定渲染阶段重写为可展示 URL(与 file mentions 相同的流式门);不传词表时本地目标保持惰性 alt 文本。重写后的图片支持 HTTP(S)、data、blob 及桌面端 `dsh-app://app/api/file`、`dsh-app://app/api/plugin-market/detail-file` 与 `dsh-app://app/api/plugin-manager/detail-file` 路由;正文直接书写的桌面端 URL 仍保持惰性。加载或解码失败后,图片替换为作者的 alt 文本;alt 为空时显示原始目标路径;`fileImages` 还提供本地化的失败提示前缀。图片源变化后可重新加载。每个挂载的图片会为解析得到的 Host `api/file` 地址追加 `load` 查询参数,因为浏览器在同一文档内会无视 `no-store` 复用相同 URL 的图片;因此覆盖后的文件在新渲染的图片中会加载当前内容,每次重新挂载都会重新请求该文件;Host 文件路由会把该请求重定向到当前文件版本的可缓存地址。回复流式输出时,它冻结已完成的块、按已完成行推进顶层未闭合 fence,并从保存的 Shiki grammar state 为该 fence 增量高亮。已完成的 token 行进入固定大小的 React 分组,后续分片只 reconcile 正在增长的分组;最终全量解析解决跨文档语法时,未变化的 fence 会保留该 DOM。`TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock` 与 `WebBlock` 把对应的工具结果意图渲染为带复制控件、溢出处理及适用时 ANSI 处理的卡片。`JsonTree` 与 `JsonBlock` 以只读方式检查 JSON 值;`UserTextRun` 渲染不做解析的文本,`ReferenceChip` 渲染业务已解析的标签。显式传入 `onActivate` 后,胶囊成为可由键盘操作的按钮;重复指针点击和已有文本选区不触发激活,键盘激活仍然可用。标签继承所属容器的换行规则。识别和 JSON 变换由 [ui-conversation](../ui-conversation/README.zh.md#sent-user-text) 负责。 +`MarkdownText` 渲染不可信的 GFM 与 TeX 公式、阻止不安全的链接与图片,并可把已解析的文件提及转换为显式控件。复制位于同一个 `MarkdownText` 文档内且包含已渲染公式的选区时,每个完整公式会以 TeX 源码同时写入剪贴板的纯文本和 HTML 格式,行内公式用 `$…$` 包裹,展示公式用 `$$…$$` 包裹。删除线需要 `~~`;单个 `~`(如 `10~20`)保持字面文本。裸 URL 在非 ASCII 标点或符号(如 `。`、`,`)前结束,紧随其后的中文正文不会并入链接。外层 `MarkdownDelegateProvider` 会接收普通点击产生的已净化 HTTP(S) URL;带修饰键的点击和 Provider 外的链接保留原生外部 anchor 行为。`omitHtml` 不渲染原始 HTML,而不是将其显示为原样文本,用于为 HTML 渲染器编写的文档。当 owner 传入 `pathImages` 词表时,本地媒体路径的图片目标只在落定渲染阶段重写为可展示 URL(与 file mentions 相同的流式门);不传词表时本地目标保持惰性 alt 文本。重写后的图片支持 HTTP(S)、data、blob 及桌面端 `dsh-app://app/api/file`、`dsh-app://app/api/plugin-market/detail-file` 与 `dsh-app://app/api/plugin-manager/detail-file` 路由;正文直接书写的桌面端 URL 仍保持惰性。加载或解码失败后,图片替换为作者的 alt 文本;alt 为空时显示原始目标路径;`fileImages` 还提供本地化的失败提示前缀。图片源变化后可重新加载。每个挂载的图片会为解析得到的 Host `api/file` 地址追加 `load` 查询参数,因为浏览器在同一文档内会无视 `no-store` 复用相同 URL 的图片;因此覆盖后的文件在新渲染的图片中会加载当前内容,每次重新挂载都会重新请求该文件;Host 文件路由会把该请求重定向到当前文件版本的可缓存地址。回复流式输出时,它冻结已完成的块、按已完成行推进顶层未闭合 fence,并从保存的 Shiki grammar state 为该 fence 增量高亮。已完成的 token 行进入固定大小的 React 分组,后续分片只 reconcile 正在增长的分组;最终全量解析解决跨文档语法时,未变化的 fence 会保留该 DOM。`TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock` 与 `WebBlock` 把对应的工具结果意图渲染为带复制控件、溢出处理及适用时 ANSI 处理的卡片。`JsonTree` 与 `JsonBlock` 以只读方式检查 JSON 值;`UserTextRun` 渲染不做解析的文本,`ReferenceChip` 渲染业务已解析的标签。显式传入 `onActivate` 后,胶囊成为可由键盘操作的按钮;重复指针点击和已有文本选区不触发激活,键盘激活仍然可用。标签继承所属容器的换行规则。识别和 JSON 变换由 [ui-conversation](../ui-conversation/README.zh.md#sent-user-text) 负责。 `MarkdownText` 默认为 `variant="body"`。次级内容使用 `variant="compact"`:其 13px 字号与 20px 行高跟随内容字号设置,各级标题保持同一字号并使用 600 字重,段落与列表采用更紧凑的间距。正文、链接和代码均保持 tertiary 颜色,以点状下划线区分链接。代码标题栏随代码块滚动。表格和公式仍然启用,使用周围文字的字号,并在可用宽度内横向滚动。两个变体共享解析器与流式缓存。 `textInteractionSource` 将已有根元素标记为文本选区交互的来源。 @@ -230,6 +230,7 @@ kind: "package-library" - **已知站点标记是固定列表**:只有列名的主机解析为自己的标记,其余外部主机仍使用地球;要识别任意站点需要通过网络抓取它的图标。 - **流式期间跨边界引用解析被推迟**:定义落在增量冻结边界另一侧的引用式链接或脚注,在回复流式输出期间渲染为字面文本;定稿时的全量解析会将其解析。 - **长高亮 fence 会保留完整 token DOM**:流式路径避免重新解析、重新 tokenize 和 reconcile 已完成前缀,但不会丢弃旧颜色或虚拟化 token span。因此最终 DOM 数量仍随 fence 的 token 数增长;嵌套/容器内 fence 与病态的单个超长行仍走通用尾部路径。 +- **公式仅在单个 Markdown 文档内复制为 TeX**:超出其 `MarkdownText` 根节点的选区(例如从用户消息延伸到回复)沿用浏览器原生复制,会将 KaTeX 隐藏的 MathML 文本与可见字形拼接在一起。在单个文档内,非公式内容的纯文本取自 `innerText`,因此与原生复制一样,会包含代码块语言标签和复制按钮文本。 - **超长行不着色**:所有高亮界面中,长度达到 1,000 个 UTF-16 单元的源码行渲染为一段纯文本,因为 TextMate 扫描成本随行长超线性增长,单个生成行否则会阻塞页面数秒。语法状态会跳过该行,因此在该行开始或结束的注释、模板字符串会使后续行着色错误。高亮仍在渲染期间同步执行,因此数千个普通行的文件仍按比例增加开销。 - **裸 URL 在非 ASCII 标点前结束**:[tokenizer 补丁](../../../patches/micromark-extension-gfm-autolink-literal@2.1.0.patch)和[转换补丁](../../../patches/mdast-util-gfm-autolink-literal@2.0.1.patch)让 GFM 自动链接在非 ASCII 标点、符号或空白处结束,因此路径中含未编码 `(`、`・` 等字符的 URL 只链接到该字符之前;这类 URL 请写成 `<…>` 或 `[…](…)`。URL 后直接跟中日韩文字时仍会并入链接,因为 `/wiki/中文` 这类路径是合法的。两个补丁都绑定精确版本:升级任一依赖时必须重新应用或撤销对应补丁,否则该边界规则会悄然失效。 - **Go 结构体字段规则在本地打了补丁**:Go 语法加载时,重复匹配单行结构体字段的规则会替换为 [worlpaker/go-syntax#25](https://github.com/worlpaker/go-syntax/pull/25) 合入的规则,因为内置规则在 `struct {` 之后含花括号注释等行上会指数级回溯。若依赖升级后该规则消失,加载语法会抛错,Go 代码以纯文本显示;`@shikijs/langs` 发布上游规则后删除此补丁。 diff --git a/packages/client/ui-primitives/src/markdown/MarkdownText.tsx b/packages/client/ui-primitives/src/markdown/MarkdownText.tsx index 43751d1991..8f1c4c7d29 100644 --- a/packages/client/ui-primitives/src/markdown/MarkdownText.tsx +++ b/packages/client/ui-primitives/src/markdown/MarkdownText.tsx @@ -180,8 +180,9 @@ class StreamingRenderer { * including `#L24` / `#L24-L30` fragments and `:24` / `:24-30` / `:24:5` suffixes * (ranges open at their first line, columns are ignored, and invalid locations * open only the file; see the README for URL/path classification). - * @returns A GFM document with TeX math rendered through KaTeX, whose - * selected formulas copy as `$…$` / `$$…$$` TeX source; raw HTML never + * Copying a selection inside the document writes selected formulas as + * `$…$` / `$$…$$` TeX source. + * @returns A GFM document with TeX math rendered through KaTeX; raw HTML never * renders as markup, and unsafe protocols are disabled. Local links without an opener remain text; * absolute HTTP(S) images render directly. */ @@ -213,5 +214,5 @@ export const MarkdownText = memo(function MarkdownText({ return
{ copyKatexAsTex(event.nativeEvent, event.currentTarget.ownerDocument) }}>{children}
+ onCopy={(event) => { copyKatexAsTex(event.nativeEvent, event.currentTarget) }}>{children} }) diff --git a/packages/client/ui-primitives/src/markdown/copy-tex.ts b/packages/client/ui-primitives/src/markdown/copy-tex.ts index 527d5618c6..0b600281ec 100644 --- a/packages/client/ui-primitives/src/markdown/copy-tex.ts +++ b/packages/client/ui-primitives/src/markdown/copy-tex.ts @@ -7,20 +7,22 @@ function closestFormula(node: Node): Element | null { } /** - * Rewrite a copy whose document selection includes rendered math so each - * formula becomes its TeX source, delimited as `$…$` inline and `$$…$$` for - * display math, in both the plain-text and HTML clipboard data. A selection - * endpoint inside a formula extends to the whole formula in the clipboard only; - * the visible selection is unchanged. Copies without math, or already handled - * by an inner listener, keep their data. + * Rewrite a copy whose selection lies inside one rendered Markdown document and + * includes rendered math, so each formula becomes its trimmed TeX source, + * delimited as `$…$` inline and `$$…$$` for display math, in both the + * plain-text and HTML clipboard data. A selection endpoint inside a formula + * extends to the whole formula in the clipboard only; the visible selection is + * unchanged. A copy without math, a selection reaching outside `root`, and a + * copy whose default an inner listener already prevented keep their data. * @param event - Native copy event. - * @param document - Document whose selection is copied. + * @param root - The rendered Markdown document root. */ -export function copyKatexAsTex(event: ClipboardEvent, document: Document): void { - const selection = document.getSelection() +export function copyKatexAsTex(event: ClipboardEvent, root: HTMLElement): void { + const selection = root.ownerDocument.getSelection() if (event.defaultPrevented || event.clipboardData === null || selection === null || selection.rangeCount !== 1 || selection.isCollapsed) return const range = selection.getRangeAt(0).cloneRange() + if (!root.contains(range.commonAncestorContainer)) return const startFormula = closestFormula(range.startContainer) if (startFormula !== null) range.setStartBefore(startFormula) const endFormula = closestFormula(range.endContainer) @@ -29,17 +31,18 @@ export function copyKatexAsTex(event: ClipboardEvent, document: Document): void const formulas = [...fragment.querySelectorAll('.katex')] if (formulas.length === 0) return for (const formula of formulas) { - const tex = formula.querySelector('annotation[encoding="application/x-tex"]')?.textContent + const tex = formula.querySelector('annotation[encoding="application/x-tex"]')?.textContent.trim() if (tex === undefined) continue const delimiter = formula.closest('.katex-display') === null ? '$' : '$$' formula.replaceWith(`${delimiter}${tex}${delimiter}`) } // innerText applies the browser's own block and line-break serialization, - // which needs a rendered element; an off-screen one keeps it invisible. - const container = document.createElement('div') - container.style.cssText = 'position:fixed;top:0;left:-100000px;white-space:normal;pointer-events:none' + // which needs a rendered element; an off-screen child of the root keeps the + // Markdown styles that decide block layout while staying invisible. + const container = root.ownerDocument.createElement('div') + container.style.cssText = 'position:fixed;top:0;left:-100000px;pointer-events:none' container.append(fragment) - document.body.append(container) + root.append(container) try { event.clipboardData.setData('text/plain', container.innerText) event.clipboardData.setData('text/html', container.innerHTML) diff --git a/packages/client/ui-primitives/tests/markdown-copy-tex.client.spec.tsx b/packages/client/ui-primitives/tests/markdown-copy-tex.client.spec.tsx index d73f217a5f..abe9353102 100644 --- a/packages/client/ui-primitives/tests/markdown-copy-tex.client.spec.tsx +++ b/packages/client/ui-primitives/tests/markdown-copy-tex.client.spec.tsx @@ -4,15 +4,20 @@ import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest' import { MarkdownText } from './markdown-test-components.tsx' import { copyKatexAsTex } from '../src/markdown/copy-tex.ts' -// jsdom implements no layout, so innerText falls back to textContent here; -// math-rendering.e2e.ts covers the browser's line breaks. +// jsdom implements no layout or innerText, so textContent stands in for it here +// and these specs assert only the TeX fragments; math-rendering.e2e.ts covers +// the browser's line breaks. +const nativeInnerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText') beforeAll(() => { Object.defineProperty(HTMLElement.prototype, 'innerText', { configurable: true, get(this: HTMLElement) { return this.textContent }, }) }) -afterAll(() => { Reflect.deleteProperty(HTMLElement.prototype, 'innerText') }) +afterAll(() => { + if (nativeInnerText === undefined) Reflect.deleteProperty(HTMLElement.prototype, 'innerText') + else Object.defineProperty(HTMLElement.prototype, 'innerText', nativeInnerText) +}) afterEach(() => { document.getSelection()?.removeAllRanges() cleanup() @@ -34,7 +39,7 @@ function copy(target: Element): { data: Map; prevented: boolean } describe('MarkdownText math copy', () => { - it('copies selected formulas as delimited TeX source', () => { + it('copies selected inline and display formulas as delimited TeX source', () => { const view = render() const paragraphs = view.container.querySelectorAll('p') const inlineVisual = view.container.querySelector('.katex-html')! @@ -42,19 +47,24 @@ describe('MarkdownText math copy', () => { select(inlineVisual.firstChild!, 0, lastText, 3) const { data, prevented } = copy(inlineVisual) expect(prevented).toBe(true) - const plain = data.get('text/plain')! - expect(plain).toBe('$E=mc^2$ and\n$$\\frac{a}{b}$$\nend') - expect(data.get('text/html')).toContain('$E=mc^2$') - expect(document.body.textContent).not.toContain('$E=mc^2$') + for (const type of ['text/plain', 'text/html']) { + expect(data.get(type)).toContain('$E=mc^2$ and') + expect(data.get(type)).toContain('$$\\frac{a}{b}$$') + expect(data.get(type)).toContain('end') + } + expect(data.get('text/html')).not.toMatch(/katex-(?:html|mathml)/u) + expect(view.container.textContent).not.toContain('$E=mc^2$') expect(document.getSelection()!.getRangeAt(0).startContainer).toBe(inlineVisual.firstChild) }) - it('extends a selection ending inside a formula to the whole formula', () => { + it('extends a selection starting or ending inside a formula to the whole formula', () => { const view = render() const paragraph = view.container.querySelector('p')! const visualText = view.container.querySelector('.katex-html .mord')!.firstChild! select(paragraph.firstChild!, 0, visualText, 1) expect(copy(paragraph).data.get('text/plain')).toBe('Energy $E=mc^2$') + select(visualText, 0, paragraph.lastChild!, 3) + expect(copy(paragraph).data.get('text/plain')).toBe('$E=mc^2$ ta') }) it('marks a selection entirely inside display math as display TeX', () => { @@ -64,6 +74,13 @@ describe('MarkdownText math copy', () => { expect(copy(glyph).data.get('text/plain')).toBe('$$\\frac{a}{b}$$') }) + it('trims the trailing newline of a fenced math block', () => { + const view = render() + const glyph = view.container.querySelector('.katex-display .katex-html .mord')! + select(glyph, 0, glyph, 1) + expect(copy(glyph).data.get('text/plain')).toBe('$$\\frac{a}{b}$$') + }) + it('keeps native copy without math or with a collapsed selection', () => { const view = render() const text = view.container.querySelector('p')!.firstChild! @@ -73,7 +90,15 @@ describe('MarkdownText math copy', () => { expect(copy(text.parentElement!).prevented).toBe(false) }) - it('leaves a copy that an inner listener already handled', () => { + it('keeps native copy for a selection reaching outside the Markdown document', () => { + const view = render(<>

outside

) + const formula = view.container.querySelector('.katex-html')! + const outside = view.container.lastElementChild!.firstChild! + select(formula, 0, outside, 3) + expect(copy(formula)).toEqual({ data: new Map(), prevented: false }) + }) + + it('keeps data from an inner listener that prevented the default', () => { const view = render() const paragraph = view.container.querySelector('p')! paragraph.addEventListener('copy', (event) => { @@ -85,12 +110,12 @@ describe('MarkdownText math copy', () => { }) it('ignores a copy without clipboard data', () => { - render() - const paragraph = document.querySelector('p')! - select(paragraph, 0, paragraph, paragraph.childNodes.length) + const view = render() + const root = view.container.firstElementChild as HTMLElement + select(root, 0, root, root.childNodes.length) const event = new Event('copy', { cancelable: true }) as ClipboardEvent Object.defineProperty(event, 'clipboardData', { value: null }) - copyKatexAsTex(event, document) + copyKatexAsTex(event, root) expect(event.defaultPrevented).toBe(false) }) @@ -98,10 +123,9 @@ describe('MarkdownText math copy', () => { const root = document.createElement('div') root.innerHTML = '

a visual b

' document.body.append(root) - root.addEventListener('copy', (event) => { copyKatexAsTex(event, document) }) + root.addEventListener('copy', (event) => { copyKatexAsTex(event, root) }) select(root, 0, root, 1) - const { data } = copy(root) - expect(data.get('text/plain')).toBe('a visual b') + expect(copy(root).data.get('text/plain')).toBe('a visual b') root.remove() }) }) From d052805f9659150d30485213324b51db17442af0 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Mon, 2 Nov 2026 11:37:23 +0800 Subject: [PATCH 44/55] fix(cua): preserve unowned files during developer signing setup --- ...6-10-29-cua-dev-signing-identity.i18n.yaml | 4 +- .../2026-10-29-cua-dev-signing-identity.md | 2 +- .../2026-10-29-cua-dev-signing-identity.zh.md | 2 +- .agents/skills/dsh-cua-macos-signing/SKILL.md | 6 +- .../scripts/signing_identity.py | 43 ++++++++-- .../scripts/test_signing_identity.py | 83 ++++++++++++++++++- docs/config-catalog.md | 15 ++-- docs/config-catalog.zh.md | 15 ++-- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../cua-macos/native/build_app.py | 7 +- .../cua-macos/native/tests/test_build_app.py | 7 +- packages/experimental/cua-macos/src/index.ts | 11 +-- .../cua-macos/src/native-build.ts | 11 ++- .../tests/provider-lifecycle.spec.ts | 2 +- 16 files changed, 164 insertions(+), 52 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml index 210d7f2be5..de5a17b10d 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.i18n.yaml @@ -9,8 +9,8 @@ en: a24857a312482724 zh: dbac75d363670e86 /agent-note-development-signing-identity-for-source-built-cua-helpers/decision: - en: 6e34d4c1e4816a7c - zh: 1f00b046832e19be + en: d2265f9ec5fb7a79 + zh: 05da2479b024a4bb /agent-note-development-signing-identity-for-source-built-cua-helpers/alternatives-considered: en: e30db5bc9c7aab43 zh: fa84883b5527334e diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md index 93dcdf2451..5f721474fc 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.md @@ -14,7 +14,7 @@ The Host builds source checkouts as a development variant with bundle identifier `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. +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. diff --git a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md index 02d107c56d..9491738cad 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-29-cua-dev-signing-identity.zh.md @@ -14,7 +14,7 @@ Host 以开发版构建源码检出,Bundle ID 为 `com.deepseek.harness.comput `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 访问私钥,并把专用钥匙串加入用户搜索列表。文件锁让同一目录的初始化和移除串行执行;已有记录但钥匙串缺失时保留记录并报错。 +[开发者签名 skill](../../../skills/dsh-cua-macos-signing/SKILL.md)指导 Agent 在 `~/.cua-macos-keys/` 创建、复用和解锁独立身份,将证书指纹和钥匙串路径写入用户配置。工具把随机密码存入 `0600` 文件,允许 codesign 访问私钥,并把专用钥匙串加入用户搜索列表。文件锁让同一目录的初始化和移除串行执行;已有记录但钥匙串缺失时保留记录并报错。目录标记将身份管理限制在明确占用的初始空目录中。发现无关文件或身份文件软链接时,初始化和移除都会在修改前停止,避免开发者指定的路径导致无关内容被删除。 即使不使用时间戳服务器,证书签名也包含签名时间。开发构建记录每份未签名内容与身份对应的已签名目录,再次构建相同内容时复用该目录,保持可执行文件摘要和共享服务一致。缓存使用证书指纹;按证书名称选择时每次签名,避免续期后复用旧证书。签名失败会中止发布。开发者工具的诊断不包含密码或完整命令参数;构建 CLI 默认 `--identity -`,支持指定证书,正式打包也可省略 `--keychain`。 diff --git a/.agents/skills/dsh-cua-macos-signing/SKILL.md b/.agents/skills/dsh-cua-macos-signing/SKILL.md index 1c2233cafe..c6bd8f4580 100644 --- a/.agents/skills/dsh-cua-macos-signing/SKILL.md +++ b/.agents/skills/dsh-cua-macos-signing/SKILL.md @@ -17,7 +17,9 @@ Run from a repository checkout on macOS with the selected Apple command-line too 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. Supply `--directory ` when the developer chose another location outside DSH home and the checkout. +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 ` 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. @@ -61,4 +63,4 @@ First remove the selecting configuration or set `sourceSigning: ad-hoc` in each python3 .agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py remove ``` -Use the same `--directory` for a custom location. Removal deletes the dedicated keychain, its search-list entry, and password record; 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. +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. diff --git a/.agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py b/.agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py index e57dbecef3..f9dcc9a0e3 100644 --- a/.agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py +++ b/.agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py @@ -6,7 +6,7 @@ code hash, so every changed build loses the grant. A certificate signature's req 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 +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. """ @@ -20,12 +20,13 @@ from pathlib import Path import re import secrets import shlex -import shutil 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" @@ -71,7 +72,7 @@ def security(*args): 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: + 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 @@ -99,6 +100,25 @@ def default_directory(): 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(): + if entry.name not in allowed 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. @@ -168,6 +188,7 @@ def setup(directory): def setup_locked(directory): + owned_directory(directory, create=True) keychain = keychain_path(directory) if record_path(directory).exists(): if keychain.is_file(): @@ -175,8 +196,7 @@ def setup_locked(directory): if not listed(keychain, keychains): security("list-keychains", "-d", "user", "-s", *keychains, str(keychain)) return load(directory) - remove_locked(directory) - directory.mkdir(mode=0o700, parents=True) + clear_identity(directory) password = secrets.token_hex(32) sha1 = create_certificate(directory, password) security("list-keychains", "-d", "user", "-s", *user_keychains(), str(keychain)) @@ -195,14 +215,23 @@ def remove(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)) - if directory.exists(): - shutil.rmtree(directory) + record_path(directory).unlink(missing_ok=True) + record_path(directory).with_suffix(".tmp").unlink(missing_ok=True) def main(): diff --git a/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py b/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py index 11a476011e..3e79daff7c 100644 --- a/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py +++ b/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py @@ -44,7 +44,8 @@ class DevelopmentSigningTests(unittest.TestCase): self.login = "/Users/example/Library/Keychains/login.keychain-db" def configure(self, listed=True): - self.directory.mkdir() + 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]) @@ -56,6 +57,81 @@ class DevelopmentSigningTests(unittest.TestCase): 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_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): @@ -107,7 +183,7 @@ class DevelopmentSigningTests(unittest.TestCase): create.assert_not_called() self.assertEqual(security.keychains, [self.login, str(self.keychain)]) - def test_setup_replaces_an_incomplete_directory(self): + def test_setup_replaces_only_an_incomplete_owned_identity(self): security = self.configure() (self.directory / "identity.json").unlink() def create(directory, password): @@ -137,6 +213,7 @@ class DevelopmentSigningTests(unittest.TestCase): 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) @@ -199,7 +276,7 @@ with open(sys.argv[1], 'w') as lock: 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"))], + 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) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 02e7d240ae..57e8f5bccb 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1119,12 +1119,15 @@ export interface Config extends CuaConfig { * an object selects an existing certificate in an explicitly configured keychain. * Installed packages and `helperPath` keep their own signature. */ - sourceSigning: 'ad-hoc' | { - /** Existing codesign certificate name or SHA-1 fingerprint. */ - identity: string - /** Absolute keychain path. The developer owns creating and unlocking it. */ - keychain: string - } + 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 } ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 9b289675e0..bc03ae4b7a 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1121,12 +1121,15 @@ export interface Config extends CuaConfig { * an object selects an existing certificate in an explicitly configured keychain. * Installed packages and `helperPath` keep their own signature. */ - sourceSigning: 'ad-hoc' | { - /** Existing codesign certificate name or SHA-1 fingerprint. */ - identity: string - /** Absolute keychain path. The developer owns creating and unlocking it. */ - keychain: string - } + 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 } ``` diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index e290711cd6..0ed84d6b08 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -45,8 +45,8 @@ en: a2c9acb5a4320dda zh: e8d1586af60215c4 /deepseek-ai-dsh-experimental-cua-macos/known-limitations-and-deferred-work: - en: 8041acf481133585 - zh: 0864d0d837439b7c + en: 3e4be6170edfa131 + zh: 27ce8561860d1b66 /deepseek-ai-dsh-experimental-cua-macos/known-limitations-and-deferred-work/dev-note: en: b836f01bd0bceb4a zh: 8122fa08b2aa95fa diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index a02969a126..0bc24469b8 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -235,7 +235,7 @@ The queue orders individual native requests. Holding an app object does not rese - macOS Stage Manager can reduce background window bounds and screenshots to thumbnails. Full-window observation and coordinate input in this state are not guaranteed; model guidance requires explaining foreground needs and avoiding repeated focus reclamation. - Background input depends on private SkyLight symbols; macOS updates can make them unavailable. Validate each target OS version. - Observed failures include dispatched Unicode text not appearing in Blender and background Command+A not selecting all text in AppKit. Inspect application state after input; a successful tool result confirms dispatch only. -- Source builds explicitly selecting `ad-hoc` can require new grants after binary changes. Deleting DSH home removes its [generated identity](native/README.md#build-and-service), so the next automatic build creates a new certificate and needs new grants. Release distribution needs a stable Developer ID signature and notarization; the build command accepts `--identity`, and installed packages preserve the distributed signature. The [permission page](../cua/README.md) offers helper authorization and target-application revocation. +- Source builds default to `ad-hoc` and can require new grants after binary changes. The [developer’s fixed identity](../../../.agents/skills/dsh-cua-macos-signing/SKILL.md) lives outside DSH home; deleting DSH home removes its selection, not the certificate or private key. Release distribution needs a stable Developer ID signature and notarization; the build command accepts `--identity`, and installed packages preserve the distributed signature. The [permission page](../cua/README.md) offers helper authorization and target-application revocation. - Release packaging does not automatically verify GUI startup, helper identity or exit cleanup. Release maintainers can run the [distribution smoke](native/README.md#build-and-service) on a logged-in Mac before publication; a successful package build does not establish those runtime results. - Saved permission rows show the name, path and icon of one approved copy, not an inventory of every installation sharing its identity. Removing that copy can leave its icon unavailable. Revocation still applies to every copy with the same identity. - If macOS does not expose a running application’s bundle identifier, the helper checks its reported bundle only when its executable matches the observed process path, then falls back to that path. Consent identity creation fails only when both the bundle identifier and actual executable path are unavailable; process-instance verification can still fail independently. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index a5505d4139..7bce161fc3 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -235,7 +235,7 @@ Use selectText only on controls advertising selectionWritable. It selects a uniq - macOS 台前调度可能将后台窗口的尺寸与截图变为缩略图,当前无法保证这种状态下的完整画面与坐标输入;模型指引要求说明前台需求并避免反复抢回焦点。 - 后台输入依赖私有 SkyLight 符号,macOS 升级可能使其不可用,需在目标系统版本验证。 - 实测 Blender Unicode 输入曾出现分派成功但界面未显示文本,后台 AppKit 的 Command+A 曾未选中全文。输入后必须检查应用状态;工具返回成功只表示已分派。 -- 显式选择 `ad-hoc` 的源码构建在二进制变化后可能需要重新授权。删除 DSH home 会删除其中的[自动签名身份](native/README.zh.md#build-and-service),下次自动构建会生成新证书并需要重新授权。正式分发应以固定 Developer ID 签名并完成公证;构建命令支持 `--identity` 指定签名身份,安装版保留分发时的签名。[权限页面](../cua/README.zh.md)提供 helper 授权入口和目标应用许可撤销。 +- 源码构建默认使用 `ad-hoc`,二进制变化后可能需要重新授权。[开发者固定身份](../../../.agents/skills/dsh-cua-macos-signing/SKILL.md)保存在 DSH home 之外;删除 DSH home 只删除选择它的配置,不删除证书和私钥。正式分发应以固定 Developer ID 签名并完成公证;构建命令支持 `--identity` 指定签名身份,安装版保留分发时的签名。[权限页面](../cua/README.zh.md)提供 helper 授权入口和目标应用许可撤销。 - 发布打包不自动验证 GUI 启动、helper 身份或退出清理。发布维护者可在发布前,在已登录桌面的 Mac 上执行[分发 smoke](native/README.zh.md#build-and-service);打包成功不能证明这些运行行为已通过验收。 - 已保存许可的条目显示一个已批准副本的名称、路径和图标,不枚举共享身份的所有安装副本。删除该副本后图标可能不可用,撤销仍作用于同一身份的所有副本。 - macOS 无法提供运行中应用的 Bundle ID 时,helper 仅在其报告的 bundle 可执行路径与实际进程路径相同时读取该 bundle,仍无标识则使用路径。只有 Bundle ID 和实际可执行路径均不可用时才拒绝生成授权身份;进程实例验证仍可能独立失败。 diff --git a/packages/experimental/cua-macos/native/build_app.py b/packages/experimental/cua-macos/native/build_app.py index e4e2393d9c..75e3c4ad11 100644 --- a/packages/experimental/cua-macos/native/build_app.py +++ b/packages/experimental/cua-macos/native/build_app.py @@ -9,7 +9,6 @@ import plistlib import re import shutil import subprocess -import sys import tempfile DEV_BUNDLE_SUFFIX = ".dev" @@ -139,8 +138,4 @@ def main(): if __name__ == "__main__": - try: - main() - except RuntimeError as error: - print(error, file=sys.stderr) - sys.exit(1) + main() diff --git a/packages/experimental/cua-macos/native/tests/test_build_app.py b/packages/experimental/cua-macos/native/tests/test_build_app.py index 61408164ed..5ab1802e38 100644 --- a/packages/experimental/cua-macos/native/tests/test_build_app.py +++ b/packages/experimental/cua-macos/native/tests/test_build_app.py @@ -6,6 +6,7 @@ import json from pathlib import Path import plistlib import secrets +import sys import tempfile import unittest from unittest.mock import patch @@ -186,7 +187,7 @@ class DevelopmentPublicationTests(PublicationCases, unittest.TestCase): class SigningOptionsTests(unittest.TestCase): def test_default_dev_and_release_builds_use_ad_hoc_without_keychain_commands(self): for variant in ("dev", "release"): - with self.subTest(variant=variant), patch.object(builder.sys, "argv", ["build_app.py", "--variant", variant]), \ + with self.subTest(variant=variant), patch.object(sys, "argv", ["build_app.py", "--variant", variant]), \ patch.object(builder.subprocess, "run") as run, patch.object(builder, "publish", return_value="helper") as publish, \ contextlib.redirect_stdout(io.StringIO()): builder.main() @@ -197,7 +198,7 @@ class SigningOptionsTests(unittest.TestCase): def test_custom_certificate_and_keychain_reach_the_signer(self): for flags, keychain in (([], None), (["--keychain", "/keychains/user.keychain-db"], Path("/keychains/user.keychain-db"))): - with patch.object(builder.sys, "argv", ["build_app.py", "--variant", "dev", "--identity", "Example", *flags]), \ + with patch.object(sys, "argv", ["build_app.py", "--variant", "dev", "--identity", "Example", *flags]), \ patch.object(builder.subprocess, "run"), patch.object(builder, "publish", return_value="helper") as publish, \ contextlib.redirect_stdout(io.StringIO()): builder.main() @@ -207,7 +208,7 @@ class SigningOptionsTests(unittest.TestCase): def test_invalid_or_retired_signing_options_fail_before_building(self): for flags in (["--signing", "local-identity"], ["--dsh-home", "/home/example"], ["--keychain", "/keychains/user"], ["--identity", "Example", "--keychain", "relative"], ["--identity", " "]): - with self.subTest(flags=flags), patch.object(builder.sys, "argv", ["build_app.py", *flags]), \ + with self.subTest(flags=flags), patch.object(sys, "argv", ["build_app.py", *flags]), \ patch.object(builder.subprocess, "run") as run, contextlib.redirect_stderr(io.StringIO()): with self.assertRaises(SystemExit) as error: builder.main() diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index d4ba56843c..5dd647a963 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -5,7 +5,7 @@ import type { Context } from '@deepseek-ai/cordis' import Schema from '@deepseek-ai/schemastery' import { CuaConfig, installCua } from '@deepseek-ai/dsh-cua' import { createPermissionParameters } from './permission-guide.ts' -import { nativeHostArchitecture, prepareNativeExecutable } from './native-build.ts' +import { nativeHostArchitecture, prepareNativeExecutable, type SourceSigning } from './native-build.ts' import { createSharedNativeChannel } from './shared-native.ts' import { GUIDANCE } from './guidance.ts' export { GUIDANCE } from './guidance.ts' @@ -23,12 +23,7 @@ export interface Config extends CuaConfig { * an object selects an existing certificate in an explicitly configured keychain. * Installed packages and `helperPath` keep their own signature. */ - sourceSigning: 'ad-hoc' | { - /** Existing codesign certificate name or SHA-1 fingerprint. */ - identity: string - /** Absolute keychain path. The developer owns creating and unlocking it. */ - keychain: string - } + sourceSigning: SourceSigning } /** Validate shared operation bounds and macOS source signing before preparing the helper. */ export const Config = Schema.object({ @@ -38,7 +33,7 @@ export const Config = Schema.object({ sourceSigning: Schema.union([ Schema.const('ad-hoc'), Schema.object({ - identity: Schema.string().pattern(/\S/).required(), + identity: Schema.string().pattern(/^[^-\s]/).required(), keychain: Schema.string().pattern(/^\/.+/).required(), }), ]).default('ad-hoc'), diff --git a/packages/experimental/cua-macos/src/native-build.ts b/packages/experimental/cua-macos/src/native-build.ts index b12db84a0f..8c288bbdc3 100644 --- a/packages/experimental/cua-macos/src/native-build.ts +++ b/packages/experimental/cua-macos/src/native-build.ts @@ -5,13 +5,20 @@ import { join, resolve } from 'node:path' import { withFileLock } from '@deepseek-ai/dsh-atomic-write' import type { SubprocessOutcome, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' import { z } from 'zod' -import type { Config } from './index.ts' const NativeApplication = z.object({ bundle: z.string().regex(/^[a-f0-9]{64}$/) }).strict() /** Architecture names used by the platform-specific native payload. */ export type NativeArchitecture = 'arm64' | 'x64' +/** 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 +} + /** * Validate the host before preparing a platform-specific application. * @param platform - Node host platform. @@ -29,7 +36,7 @@ export interface NativeBuildSpec { packageRoot: string architecture: NativeArchitecture /** Signature of a source-checkout build; installed packages ignore it. */ - sourceSigning: Config['sourceSigning'] + sourceSigning: SourceSigning subprocess: Pick signal: AbortSignal timeoutMs: number diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 111aed6bc1..bb45e394c9 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -75,7 +75,7 @@ it('defaults to ad-hoc signing and requires a keychain path for certificate sign for (const sourceSigning of [{ identity: 'Apple Development: Example', keychain: '/keychains/custom.keychain-db' }, { identity: 'ABC123', keychain: '/keychains/custom.keychain-db' }]) { expect(NativeProvider.Config({ sourceSigning }).sourceSigning).toEqual(sourceSigning) } - for (const sourceSigning of ['local-identity', 'developer-id', {}, { identity: 'Example' }, { identity: '' }, { identity: ' ' }, { identity: 'Example', keychain: 'relative' }]) { + for (const sourceSigning of ['local-identity', 'developer-id', {}, { identity: 'Example' }, { identity: '' }, { identity: ' ' }, { identity: 'Example', keychain: 'relative' }, ...['-', '--help', '-Example', ' Example'].map(identity => ({ identity, keychain: '/keychains/custom.keychain-db' }))]) { expect(() => NativeProvider.Config({ sourceSigning } as never)).toThrow() } }) From 2bd4226dc955503506478a1d95165b769235b685 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Mon, 2 Nov 2026 11:41:57 +0800 Subject: [PATCH 45/55] fix(cua): preserve system keychain lock lifecycle --- .../scripts/signing_e2e.py | 6 ++++- .../scripts/signing_identity.py | 4 +++- .../scripts/test_signing_identity.py | 23 +++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/.agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py b/.agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py index 29a6c0a2ce..71c36752d5 100644 --- a/.agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py +++ b/.agents/skills/dsh-cua-macos-signing/scripts/signing_e2e.py @@ -65,7 +65,11 @@ def main(): 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: - signing.remove(directory) + 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" diff --git a/.agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py b/.agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py index f9dcc9a0e3..69ab639a9d 100644 --- a/.agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py +++ b/.agents/skills/dsh-cua-macos-signing/scripts/signing_identity.py @@ -115,7 +115,9 @@ def owned_directory(directory, create=False): 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(): - if entry.name not in allowed or entry.is_symlink() or not entry.is_file(): + # 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") diff --git a/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py b/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py index 3e79daff7c..949926f98c 100644 --- a/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py +++ b/.agents/skills/dsh-cua-macos-signing/scripts/test_signing_identity.py @@ -82,6 +82,29 @@ class DevelopmentSigningTests(unittest.TestCase): 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 From a313ff916b5f8638f17e34aa8ddb4b98b0b12d3a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Mon, 2 Nov 2026 14:31:28 +0800 Subject: [PATCH 46/55] docs(cua): proactively recommend developer signing identities --- .agents/skills/dsh-cua-macos-signing/SKILL.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/.agents/skills/dsh-cua-macos-signing/SKILL.md b/.agents/skills/dsh-cua-macos-signing/SKILL.md index c6bd8f4580..6d28147f29 100644 --- a/.agents/skills/dsh-cua-macos-signing/SKILL.md +++ b/.agents/skills/dsh-cua-macos-signing/SKILL.md @@ -1,10 +1,22 @@ --- name: dsh-cua-macos-signing -description: Set up, reuse, unlock, or remove a local macOS Computer Use development signing identity and configure source builds to use it across worktrees. Use when developing the CUA helper or reducing repeated macOS permission grants; release signing and notarization use their packaging workflow. +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. From 8d0c3b46333707778d9cab6667522ba5d18ee481 Mon Sep 17 00:00:00 2001 From: Magolor Date: Mon, 2 Nov 2026 15:00:19 +0800 Subject: [PATCH 47/55] fix(settings): show saved API keys and preserve environment detection (#7695) * fix(settings): show saved API keys in provider editors * test(settings): retain DeepSeek environment detection states * fix(settings): classify saved-key reads and align browser expectations * test(settings): cover saved keys under derived references * test(settings): verify saved endpoints and keys on provider requests * fix(settings): preserve credential drafts without changing authentication --- apps/web/tests/credential-editor.e2e.ts | 235 ++++++++++++++++++ .../detected-environment.expected.md | 25 ++ .../missing-environment.expected.md | 23 ++ .../credential-editor/saved-key.expected.md | 26 ++ .../cards.expected.md | 4 +- .../default-models.expected.md | 4 +- .../models.expected.md | 4 +- .../fixtures/credential-editor.patch.yml | 5 + apps/web/tests/models-settings.e2e.ts | 9 +- .../tests/onboarding-deepseek-config.e2e.ts | 17 +- apps/web/tsconfig.json | 1 + docs/capability-seams.i18n.yaml | 4 +- docs/capability-seams.md | 2 +- docs/capability-seams.zh.md | 2 +- docs/subsystems/credentials.i18n.yaml | 4 +- docs/subsystems/credentials.md | 22 +- docs/subsystems/credentials.zh.md | 22 +- .../credential-editor/guide.i18n.yaml | 16 ++ .../v0.2.2-alpha.2/credential-editor/guide.md | 19 ++ .../credential-editor/guide.zh.md | 19 ++ docs/user/guide/providers.i18n.yaml | 8 +- docs/user/guide/providers.md | 8 +- docs/user/guide/providers.zh.md | 8 +- .../api/settings-controller/README.i18n.yaml | 8 +- packages/api/settings-controller/README.md | 4 +- packages/api/settings-controller/README.zh.md | 4 +- .../settings-controller/src/credentials.ts | 24 +- packages/api/settings-controller/src/types.ts | 6 +- .../tests/credentials-controller.host.spec.ts | 40 +++ .../ui-settings-models/README.i18n.yaml | 12 +- packages/client/ui-settings-models/README.md | 10 +- .../client/ui-settings-models/README.zh.md | 10 +- .../src/client/ApiKeyInput.tsx | 4 +- .../src/client/ModelListEditor.tsx | 2 +- .../src/client/ModelsSection.tsx | 49 +++- .../src/client/ProviderEditor.tsx | 36 +-- .../ui-settings-models/src/client/apiKey.ts | 9 +- .../ui-settings-models/src/client/locales.ts | 8 - .../src/client/operations.ts | 15 ++ .../tests/components.client.spec.tsx | 178 ++++++++++++- .../tests/model-list-catalog.client.spec.tsx | 2 +- .../tests/model-order.client.spec.tsx | 4 +- .../model-reasoning-efforts.client.spec.tsx | 2 +- .../tests/provider-form.client.spec.tsx | 1 + .../credentials/authorization/tests/memory.ts | 4 + .../credentials-local/README.i18n.yaml | 4 +- .../credentials/credentials-local/README.md | 2 +- .../credentials-local/README.zh.md | 2 +- .../credentials-local/src/index.ts | 4 + .../credentials-local/tests/local.spec.ts | 12 + .../credentials/credentials/README.i18n.yaml | 12 +- packages/credentials/credentials/README.md | 6 +- packages/credentials/credentials/README.zh.md | 6 +- packages/credentials/credentials/src/index.ts | 7 + .../credentials/credentials/tests/memory.ts | 5 + .../liveshare/src/endpoint-classification.ts | 1 + .../endpoint-classification.client.spec.ts | 1 + .../extensions/tool-cordis/src/api-catalog.ts | 17 +- scripts/gen-doc-graphs.ts | 2 +- tsconfig.host.json | 1 + 60 files changed, 853 insertions(+), 148 deletions(-) create mode 100644 apps/web/tests/credential-editor.e2e.ts create mode 100644 apps/web/tests/expected/credential-editor/detected-environment.expected.md create mode 100644 apps/web/tests/expected/credential-editor/missing-environment.expected.md create mode 100644 apps/web/tests/expected/credential-editor/saved-key.expected.md create mode 100644 apps/web/tests/fixtures/credential-editor.patch.yml create mode 100644 docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.zh.md diff --git a/apps/web/tests/credential-editor.e2e.ts b/apps/web/tests/credential-editor.e2e.ts new file mode 100644 index 0000000000..b9ee283aa4 --- /dev/null +++ b/apps/web/tests/credential-editor.e2e.ts @@ -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((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 => { + 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() } +}) diff --git a/apps/web/tests/expected/credential-editor/detected-environment.expected.md b/apps/web/tests/expected/credential-editor/detected-environment.expected.md new file mode 100644 index 0000000000..829eeedd37 --- /dev/null +++ b/apps/web/tests/expected/credential-editor/detected-environment.expected.md @@ -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 "添加模型提供商" diff --git a/apps/web/tests/expected/credential-editor/missing-environment.expected.md b/apps/web/tests/expected/credential-editor/missing-environment.expected.md new file mode 100644 index 0000000000..609ac50d0e --- /dev/null +++ b/apps/web/tests/expected/credential-editor/missing-environment.expected.md @@ -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 "添加模型提供商" diff --git a/apps/web/tests/expected/credential-editor/saved-key.expected.md b/apps/web/tests/expected/credential-editor/saved-key.expected.md new file mode 100644 index 0000000000..2d4dde4639 --- /dev/null +++ b/apps/web/tests/expected/credential-editor/saved-key.expected.md @@ -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 "添加模型提供商" diff --git a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md index 08a0750772..d4fa1c31fb 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md @@ -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 地址": diff --git a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md index 03900f109b..018ea8a13c 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md @@ -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 地址": diff --git a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md index 27ba737236..a5811b5d66 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md @@ -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 地址": diff --git a/apps/web/tests/fixtures/credential-editor.patch.yml b/apps/web/tests/fixtures/credential-editor.patch.yml new file mode 100644 index 0000000000..911f60db22 --- /dev/null +++ b/apps/web/tests/fixtures/credential-editor.patch.yml @@ -0,0 +1,5 @@ +- id: llm-deepseek + config: + baseURL: http://127.0.0.1 + models: + - id: credential-editor-model diff --git a/apps/web/tests/models-settings.e2e.ts b/apps/web/tests/models-settings.e2e.ts index d36008959d..1b5a5dcbed 100644 --- a/apps/web/tests/models-settings.e2e.ts +++ b/apps/web/tests/models-settings.e2e.ts @@ -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() diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index 8706a7a4de..06e451032d 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -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 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() diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 9b3977d4ee..938c0dae3c 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -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", diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 1083094774..4dc23c45e6 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: 3c972fccec17a890 - zh: 94c82847a3c8b83c + en: 6215d15e0e273fa4 + zh: dec5c7779e0a42f5 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index e333a79f71..334e3757bc 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -698,7 +698,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. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index cf3f2e67fc..d0f0bdffb0 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -700,7 +700,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 动态采集策略接收指定桌面事件、补充可用登录身份并监听实时压缩。 | diff --git a/docs/subsystems/credentials.i18n.yaml b/docs/subsystems/credentials.i18n.yaml index bad9827407..06c51858d4 100644 --- a/docs/subsystems/credentials.i18n.yaml +++ b/docs/subsystems/credentials.i18n.yaml @@ -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 diff --git a/docs/subsystems/credentials.md b/docs/subsystems/credentials.md index 2a084fb29f..b4ffca123b 100644 --- a/docs/subsystems/credentials.md +++ b/docs/subsystems/credentials.md @@ -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 +/** + * 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 + /** * 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> /** - * 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 + +/** + * 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. diff --git a/docs/subsystems/credentials.zh.md b/docs/subsystems/credentials.zh.md index 1e9221699a..d4784832ca 100644 --- a/docs/subsystems/credentials.zh.md +++ b/docs/subsystems/credentials.zh.md @@ -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 +/** + * 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 + /** * 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> /** - * 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 + +/** + * 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. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.i18n.yaml new file mode 100644 index 0000000000..3acec7569f --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.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 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.md new file mode 100644 index 0000000000..8e721ad800 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.md @@ -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` 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. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.zh.md new file mode 100644 index 0000000000..75efbcc4d7 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/credential-editor/guide.zh.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "已保存的 API 密钥显示为编辑器中的掩码值,清空已保存密钥会删除其覆盖。" +--- +# 提供商编辑器中的已保存 API 密钥 + +[English](guide.md) | 中文 + +## 变更 + +提供商编辑器以掩码值显示已保存的 API 密钥,不再显示空字段。应用空字段会删除之前加载的密钥并恢复环境认证。「取消」保留已保存密钥。环境变量值从不加载到编辑器。 + +凭据提供方实现 `readStored(ref): Promise`,仅返回托管值,不使用环境后备。仅允许所有者调用的 `credentials.readStored` Remote 方法向已打开的编辑器提供此值;普通元数据读取仍保持脱敏。 + +## 迁移 + +1. 保留加载的值即可保留已保存密钥,替换它可轮换密钥,清空并应用则使用环境认证。 +2. 为自定义 `CredentialProvider` 子类实现 `readStored`;未存储非空值时返回 `undefined`。 +3. 重新打开 DeepSeek 编辑器,确认已保存密钥显示为掩码。清空并应用后,确认字段为空且提示使用环境认证。 diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index b04aada43b..62801fa60d 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -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 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index fe831bcaf9..1ab90f440e 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -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 diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index bb518c42b9..ddb44f1814 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -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 diff --git a/packages/api/settings-controller/README.i18n.yaml b/packages/api/settings-controller/README.i18n.yaml index 4b3f0d24d3..979d0867fb 100644 --- a/packages/api/settings-controller/README.i18n.yaml +++ b/packages/api/settings-controller/README.i18n.yaml @@ -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 diff --git a/packages/api/settings-controller/README.md b/packages/api/settings-controller/README.md index b38072546d..17357971ed 100644 --- a/packages/api/settings-controller/README.md +++ b/packages/api/settings-controller/README.md @@ -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`. diff --git a/packages/api/settings-controller/README.zh.md b/packages/api/settings-controller/README.zh.md index 3c9e876740..2c4f4a2b29 100644 --- a/packages/api/settings-controller/README.zh.md +++ b/packages/api/settings-controller/README.zh.md @@ -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`。 diff --git a/packages/api/settings-controller/src/credentials.ts b/packages/api/settings-controller/src/credentials.ts index 3889669048..f9172f8f9e 100644 --- a/packages/api/settings-controller/src/credentials.ts +++ b/packages/api/settings-controller/src/credentials.ts @@ -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 { + 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. diff --git a/packages/api/settings-controller/src/types.ts b/packages/api/settings-controller/src/types.ts index 3d11c6ab0c..d1dadc1e16 100644 --- a/packages/api/settings-controller/src/types.ts +++ b/packages/api/settings-controller/src/types.ts @@ -20,9 +20,9 @@ declare module '@deepseek-ai/dsh-typert-protocol' { */ 'settings/conflict': { readonly ns: string; readonly expected: number; readonly actual: number } /** - * The provider refused a valid credential write, for example because 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 } } diff --git a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts index 5eeb190385..552baa7b5d 100644 --- a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts +++ b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts @@ -2,9 +2,17 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import type { CredentialInfo } from '@deepseek-ai/dsh-credentials/types' import { remoteErrorOf, remoteMethods } from '@deepseek-ai/dsh-typert-protocol' +import type { PeerId, RemoteInvocation } from '@deepseek-ai/dsh-typert-protocol' import CredentialsController from '../src/credentials.ts' import { MemoryCredentials } from '../../../credentials/credentials/tests/memory.ts' +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + /** Non-owner used to verify stored-key read denial. */ + 'credential-viewer': { readonly kind: 'credential-viewer' } + } +} + /** A store whose `describe` carries more than the view declares, as a foreign provider might. */ class LeakyCredentials extends MemoryCredentials { override describe(): Promise { @@ -46,6 +54,7 @@ describe('the credentials Remote namespace a configuration surface calls', () => expect(binding.namespace).toBe('credentials') expect(remoteMethods(controller)).toEqual([ { method: 'describe', invocation: { kind: 'direct' } }, + { method: 'readStored', invocation: { kind: 'direct' } }, { method: 'set', invocation: { kind: 'direct' } }, { method: 'unset', invocation: { kind: 'direct' } }, ]) @@ -56,6 +65,7 @@ describe('the credentials Remote namespace a configuration surface calls', () => await ctx.plugin(CredentialsController) for (const call of [ () => ctx.credentialsController.describe(['DEEPSEEK_API_KEY']), + () => ctx.credentialsController.readStored('DEEPSEEK_API_KEY'), () => ctx.credentialsController.set('DEEPSEEK_API_KEY', 'sk-live'), () => ctx.credentialsController.unset('DEEPSEEK_API_KEY'), ]) { @@ -82,6 +92,7 @@ describe('the credentials Remote namespace a configuration surface calls', () => const controller = await boot() for (const call of [ () => controller.describe(['DEEPSEEK_API_KEY', 'not a var']), + () => controller.readStored('not a var'), () => controller.set('not a var', 'sk-live'), () => controller.unset('not a var'), ]) { @@ -115,6 +126,35 @@ describe('the credentials Remote namespace a configuration surface calls', () => .toEqual({ DEEPSEEK_API_KEY: { configured: false, writable: true } }) }) + it('reads stored secrets only through the explicit editor read', async () => { + const controller = await boot({ DEEPSEEK_API_KEY: 'fixture-saved-key' }) + expect(await controller.readStored('DEEPSEEK_API_KEY')).toBe('fixture-saved-key') + expect(await controller.readStored('OPENAI_API_KEY')).toBeUndefined() + expect(JSON.stringify(await controller.describe(['DEEPSEEK_API_KEY']))).not.toContain('fixture-saved-key') + await controller.unset('DEEPSEEK_API_KEY') + expect(await controller.readStored('DEEPSEEK_API_KEY')).toBeUndefined() + }) + + it('denies non-owner stored-key reads before consulting the provider', async () => { + const ctx = new Context() + await ctx.plugin(MemoryCredentials, { DEEPSEEK_API_KEY: 'fixture-saved-key' }) + await ctx.plugin(CredentialsController) + const signal = new AbortController().signal + const invocation: RemoteInvocation = { + request: { namespace: 'credentials', method: 'readStored', args: { ref: 'DEEPSEEK_API_KEY' } }, + service: 'credentialsController', signal, + peer: { + id: 'credential-viewer' as PeerId, ctx, signal, principal: { kind: 'credential-viewer' }, + interactions: 'none', dispose: () => Promise.resolve(), + }, + uplink: async function* (): AsyncGenerator {}, + } + const caller = ctx.extend({ invocation }) + const failure = await caller.credentialsController.readStored('DEEPSEEK_API_KEY').catch((error: unknown) => error) + expect(remoteErrorOf(failure)).toMatchObject({ code: 'credential/rejected', details: { ref: 'DEEPSEEK_API_KEY' } }) + expect(JSON.stringify(remoteErrorOf(failure))).not.toContain('fixture-saved-key') + }) + it('reports a refused write as credential/rejected naming only the reference', async () => { const controller = await boot({}, RejectingCredentials) const failure = await controller.set('DEEPSEEK_API_KEY', 'sk-live').catch((error: unknown) => error) diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index 02b3bd6729..3c28ce7528 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -9,8 +9,8 @@ en: 0db6fa836e1ff511 zh: 0e2968763e1fb7a5 /deepseek-ai-dsh-client-ui-settings-models/summary: - en: 51252c1e9fa6da0a - zh: 227b54d7898417fa + en: 2d39061747367414 + zh: 35edfca13c457deb /deepseek-ai-dsh-client-ui-settings-models/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb @@ -18,11 +18,11 @@ en: db5aaf7f702e1f0c zh: 409a78c14fb2b6e3 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/api-keys: - en: f4817eb2e3537ed9 - zh: e589c193fa85473f + en: d771da09da774692 + zh: 9566b3c0e95da8a6 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: ce52da7e6065ccc4 - zh: c63690cb5de5ea85 + en: 23c8e60086660111 + zh: f277b69a202f207c /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: c0b04b2b11af60d3 zh: d195eec281e445cb diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index 8db24c5170..3e579642fe 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -11,7 +11,7 @@ Desktop product events use the optional [product analytics service](../product-a ## Summary -`dsh-client-ui-settings-models` is the Models settings page of the dsh web client: users configure API keys (stored write-only under the profile's credential reference), edit each provider's model list, and hand-declare custom pi-ai routes, with provider rows and one editor card at a time. The page joins the provider directory, the settings document, and the credential descriptions into one shared snapshot, so a row's state stays consistent across all three. It also walks first-run users through two ordered dialogs — a versioned preview notice and the conditional official-DeepSeek credential step. +`dsh-client-ui-settings-models` is the Models settings page of the dsh web client: users configure API keys (stored under the profile's credential reference), edit each provider's model list, and hand-declare custom pi-ai routes, with provider rows and one editor card at a time. The page joins the provider directory, the settings document, and the credential descriptions into one shared snapshot, so a row's state stays consistent across all three. It also walks first-run users through two ordered dialogs — a versioned preview notice and the conditional official-DeepSeek credential step. ## Table of Contents @@ -41,15 +41,15 @@ Host configuration `credentialOnboarding` defaults to `true`. The Electron prelo ### API keys -API-key inputs start empty and use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Stored credentials are never read into the input. +The API key input shows a saved key masked and uses `autocomplete="new-password"` to avoid filling login passwords. Its eye button reveals the current value; editing or clearing the value masks it again. Environment values are never loaded into the input. -The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores write-only through `credentials.set` under the profile's reference, deriving `_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). The field's placeholder and help tooltip use the profile's `apiKeyEnv` when it has one; otherwise they use the credential variables of the route's `nativeAuth`, excluding `baseURLEnv` address variables, in lookup order, as the configurable-provider directory reports them. These display hints omit references containing `oauth` (case-insensitively), and describe saved credentials followed by the displayed environment fallbacks. This presentation filter does not change the [credential resolution order](../../../docs/subsystems/credentials.md#resolution), the adapter's complete environment list, or an explicit reference. A filtered explicit reference still has a usable key input with the plain placeholder and no tooltip. A native route that has no key authentication omits the key field and authentication help entirely; an explicit reference still enables the field. A profile without a reference on a route without `nativeAuth`, such as a hand-declared route, shows the plain key placeholder and no tooltip. A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material. +The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores through `credentials.set` under the profile's reference, deriving `_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). The field's placeholder and help tooltip use the profile's `apiKeyEnv` when it has one; otherwise they use the credential variables of the route's `nativeAuth`, excluding `baseURLEnv` address variables, in lookup order, as the configurable-provider directory reports them. These display hints omit references containing `oauth` (case-insensitively), and describe saved credentials followed by the displayed environment fallbacks. This presentation filter does not change the [credential resolution order](../../../docs/subsystems/credentials.md#resolution), the adapter's complete environment list, or an explicit reference. A filtered explicit reference still has a usable key input with the plain placeholder and no tooltip. A native route that has no key authentication omits the key field and authentication help entirely; an explicit reference still enables the field. A profile without a reference on a route without `nativeAuth`, such as a hand-declared route, shows the plain key placeholder and no tooltip. A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material. -The editor uses redacted `CredentialInfo` to choose the saved-credential placeholder or environment detection, without displaying a credential-source label. Refreshing the snapshot updates an open editor without a separate probe. The hint never receives a credential value or changes field writability. +Opening an existing provider editor reads its stored key through the owner-only `credentials.readStored` operation and shows it as a password input. The reveal button shows the loaded value. The key stays in that editor's local state; provider-directory and settings snapshots contain only redacted metadata. A failed read shows an error instead of an empty editor. Cancel discards edits, and Apply preserves an unchanged key, replaces an edited key, or removes a cleared key so environment authentication can apply. ### Editing a provider -A blank key field offers a saved credential when one is detected, with no status text below the input; otherwise it offers environment authentication. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A nonempty input shows no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. +An empty key field offers environment authentication; a saved key appears as a masked value. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A nonempty input shows no authentication status text. The page describes native variable names and named references in batches of at most 64. Editor reads return only provider-managed values, never environment values. An endpoint without a fixed catalog default shows the provider's `baseURLEnv` configuration names below the input. A profile endpoint remains the first placeholder choice. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 23763f168c..f96f6d9d2b 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" ## 概述 -`dsh-client-ui-settings-models` 是 dsh Web 客户端的 Models 设置页面:用户可以配置 API 密钥(以只写方式存入 profile 的凭据引用之下)、编辑每个提供商的模型列表,并手工声明自定义 pi-ai 路由;页面以提供商行展示,一次只展开一张编辑卡片。该页面把提供商目录、设置文档与凭据描述合并为一个共享快照,因此行的状态在三个方面始终一致。它还会带首次运行的用户走两个有序弹窗——版本化预览版说明,以及按条件显示的官方 DeepSeek 凭据步骤。 +`dsh-client-ui-settings-models` 是 dsh Web 客户端的 Models 设置页面:用户可以配置 API 密钥(存入 profile 的凭据引用之下)、编辑每个提供商的模型列表,并手工声明自定义 pi-ai 路由;页面以提供商行展示,一次只展开一张编辑卡片。该页面把提供商目录、设置文档与凭据描述合并为一个共享快照,因此行的状态在三个方面始终一致。它还会带首次运行的用户走两个有序弹窗——版本化预览版说明,以及按条件显示的官方 DeepSeek 凭据步骤。 ## 目录 @@ -41,15 +41,15 @@ Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会 ### API 密钥 -API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存凭据从不读入输入框。 +API 密钥输入框以掩码显示已保存的密钥,并通过 `autocomplete="new-password"` 避免填入登录密码。眼睛按钮显示当前值;修改或清空输入后重新遮住密钥。环境变量值从不加载到输入框。 -编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。profile 有 `apiKeyEnv` 时,字段的占位文字与帮助提示采用该引用;否则按查找顺序采用可配置提供商目录为该路由报告的 `nativeAuth` 凭据变量,并排除 `baseURLEnv` 地址变量。这些显示提示会忽略包含 `oauth` 的引用(不区分大小写),并说明优先使用已保存凭据,其后为显示的环境后备。这项显示过滤不改变[凭据解析顺序](../../../docs/subsystems/credentials.zh.md#resolution)、适配器的完整环境变量列表或显式引用。被过滤的显式引用仍有可用的密钥输入框,使用普通占位文字且不显示帮助提示。没有密钥认证的原生路由不显示密钥字段及认证帮助;显式引用仍会启用该字段。路由没有 `nativeAuth`(例如手动声明的路由)且 profile 没有引用时,显示普通的密钥占位文字,且不显示帮助提示。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。 +编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 存入 profile 的引用之下,profile 没有引用时便派生 `_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。profile 有 `apiKeyEnv` 时,字段的占位文字与帮助提示采用该引用;否则按查找顺序采用可配置提供商目录为该路由报告的 `nativeAuth` 凭据变量,并排除 `baseURLEnv` 地址变量。这些显示提示会忽略包含 `oauth` 的引用(不区分大小写),并说明优先使用已保存凭据,其后为显示的环境后备。这项显示过滤不改变[凭据解析顺序](../../../docs/subsystems/credentials.zh.md#resolution)、适配器的完整环境变量列表或显式引用。被过滤的显式引用仍有可用的密钥输入框,使用普通占位文字且不显示帮助提示。没有密钥认证的原生路由不显示密钥字段及认证帮助;显式引用仍会启用该字段。路由没有 `nativeAuth`(例如手动声明的路由)且 profile 没有引用时,显示普通的密钥占位文字,且不显示帮助提示。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。 -编辑器使用脱敏 `CredentialInfo` 选择已保存凭据的占位文字或环境检测,不显示凭据来源标签。快照刷新会更新打开的编辑器,无需单独探测。提示从不接收凭据值,也不改变字段的可写性。 +打开已有提供商的编辑器时,通过仅允许所有者调用的 `credentials.readStored` 操作读取已保存密钥,并以密码输入框显示。显示按钮可以展示已加载的值。密钥只保存在该编辑器的本地状态中;提供商目录与设置快照只包含脱敏元数据。读取失败时显示错误,不打开空白编辑器。「取消」丢弃编辑;「保存」保留未修改的密钥、替换已编辑的密钥,或删除已清空的密钥,从而允许使用环境认证。 ### 编辑提供商 -密钥字段留空时,已检测到已保存凭据则提示使用该凭据,输入框下方不显示状态文字;否则提示使用环境认证。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。输入非空时,不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。 +空密钥字段提示使用环境认证;已保存的密钥显示为掩码值。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。输入非空时,不显示认证状态文字。页面按每批最多 64 项描述原生变量名和具名引用。编辑器读取只返回提供方管理的值,不返回环境变量值。 目录未提供固定默认端点时,输入框下方显示提供方的 `baseURLEnv` 配置变量名。Profile 中的端点仍是占位符的首选。 diff --git a/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx b/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx index e983a40303..3727000fc1 100644 --- a/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx +++ b/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx @@ -1,4 +1,4 @@ -/** Write-only credential input with the same reveal behavior as masked conversation text. */ +/** Credential input with the same reveal behavior as masked conversation text. */ import { useState } from 'react' import type { InputHTMLAttributes, ReactNode } from 'react' import type { en } from './locales.ts' @@ -10,7 +10,7 @@ const EYE_OFF_PATH = `${EYE_CONTOUR}M2.5 2.5L13.5 13.5` /** Input attributes and section copy for the current credential draft. */ interface ApiKeyInputProps extends Omit, 'value' | 'type' | 'className' | 'autoComplete'> { - /** Unsaved input; stored credentials are never read into this field. */ + /** Stored credential or the user's current edit; initially masked. */ readonly value: string /** Section copy, including the same reveal labels as SecretText. */ readonly t: (key: keyof typeof en) => string diff --git a/packages/client/ui-settings-models/src/client/ModelListEditor.tsx b/packages/client/ui-settings-models/src/client/ModelListEditor.tsx index 05c2b3e1ab..37a2ae989f 100644 --- a/packages/client/ui-settings-models/src/client/ModelListEditor.tsx +++ b/packages/client/ui-settings-models/src/client/ModelListEditor.tsx @@ -63,7 +63,7 @@ export interface ProbeTarget { baseURL?: string /** Wire protocol the form names, when it names one. */ api?: string - /** Key typed into the form and not yet stored, when there is one. */ + /** Loaded or newly entered key currently shown in the form, when there is one. */ apiKey?: string } diff --git a/packages/client/ui-settings-models/src/client/ModelsSection.tsx b/packages/client/ui-settings-models/src/client/ModelsSection.tsx index 461ab37aad..adff556795 100644 --- a/packages/client/ui-settings-models/src/client/ModelsSection.tsx +++ b/packages/client/ui-settings-models/src/client/ModelsSection.tsx @@ -86,6 +86,8 @@ export interface ProviderIdentity { /** One existing row or dormant directory entry addressed by an editor action. */ interface EditorTarget extends ProviderIdentity { + /** Stored secret retained only while this editor is open. */ + initialCredential?: string settingsNs: string settingsPath: readonly string[] /** Writable credential identified under this page's conventional reference. */ @@ -123,16 +125,18 @@ interface ProviderEditorRenderProps extends Pick< /** Render an editor for either the setup posture or an expanded provider row. */ function renderProviderEditor({ target, row, ...props }: ProviderEditorRenderProps): ReactNode { + const credential = row.apiKeyEnv === undefined ? row.derivedCredential : row.credential return ( @@ -254,6 +258,10 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS if (state.status === 'ready' && !hasReadySnapshot) setHasReadySnapshot(true) if (state.status === 'error' && hasReadySnapshot) setHasReadySnapshot(false) const [editing, setEditing] = useState(undefined) + const [credentialRead, setCredentialRead] = useState< + { provider: string; status: 'loading' } | { provider: string; status: 'failed'; message: string } + >() + const editorLoading = credentialRead?.status === 'loading' const [addOpen, setAddOpen] = useState(false) const [addMode, setAddMode] = useState('catalog') /** The modes shown since the add card opened; each keeps its panel mounted. */ @@ -269,6 +277,26 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS const [savedTarget, setSavedTarget] = useState(undefined) const [dismissedSetup, setDismissedSetup] = useState>(() => new Set()) + const openEditor = async (row: ProviderRow, target: EditorTarget): Promise => { + setSavedTarget(undefined) + setAddOpen(false) + setEditing(undefined) + setCredentialRead(undefined) + const info = row.apiKeyEnv === undefined ? row.derivedCredential : row.credential + if (info?.configured === false) { + setEditing(target) + return + } + setCredentialRead({ provider: target.provider, status: 'loading' }) + const loaded = await operations.readCredential(row.apiKeyEnv ?? deriveKeyRef(target.provider)) + if (loaded.kind === 'refused') { + setCredentialRead({ provider: target.provider, status: 'failed', message: loaded.message }) + return + } + setCredentialRead(undefined) + setEditing({ ...target, ...loaded.value === undefined ? {} : { initialCredential: loaded.value } }) + } + const announceSaved = (target: ProviderIdentity): void => { // Announced only once the refreshed directory is in the snapshot the // notice reads its name from: an apply can rename the route, and the @@ -509,15 +537,12 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS type="button" className={styles['secondaryButton']} aria-label={providerCopy(t('editProvider'), target)} - disabled={!open && state.status !== 'ready'} + disabled={editorLoading || (!open && state.status !== 'ready')} + aria-busy={credentialRead?.provider === target.provider && editorLoading} onClick={() => { if (!open && controller.store.getSnapshot().status !== 'ready') return - setSavedTarget(undefined) - // One card at a time: the add card closes with whatever - // it held, since closing either card would otherwise - // discard the other's draft. - setAddOpen(false) - setEditing(open ? undefined : target) + if (open) setEditing(undefined) + else void openEditor(row, target) }} > {t('edit')} @@ -529,7 +554,7 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS type="button" className={styles['dangerButton']} aria-label={providerCopy(t('removeProvider'), target)} - disabled={!state.writable || state.status !== 'ready'} + disabled={editorLoading || !state.writable || state.status !== 'ready'} onClick={() => { if (controller.store.getSnapshot().status !== 'ready') return setSavedTarget(undefined) @@ -544,6 +569,8 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS {error} + {credentialRead?.provider === target.provider && credentialRead.status === 'failed' + ?

{credentialRead.message}

: null} {renderSlot( 'settings.models.provider-card', { provider: row.entry, configured: row.configured, keyConfigured: keyConfiguredOf(row) }, @@ -551,7 +578,7 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS )} {open ? renderProviderEditor({ - target, + target: { ...target, ...editing.initialCredential === undefined ? {} : { initialCredential: editing.initialCredential } }, row, namespace, schema, @@ -698,7 +725,7 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS