Keep successful MCP input held and clean only on observed cancellation
This commit is contained in:
1 parent
e9d19c9d35
commit
1100abfac4
28 files changed
+118
-80
No files matched your search
+2
-2
@@ -15,5 +15,5 @@
|
||||
en: 32c970ae153e0f6c
|
||||
zh: 8431be0a10ffed15
|
||||
/agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences:
|
||||
en: 7f4cb4b375fc8bdb
|
||||
zh: bf273fdc4940d988
|
||||
en: f1efc14ced052492
|
||||
zh: 9834bb2cf09c536e
|
||||
@@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps
|
||||
|
||||
Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first.
|
||||
|
||||
Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. Native input ownership follows the task and connection. Successful programs in DSH turns report remaining held input without releasing it. Programs outside DSH turns, including MCP, release before returning and report confirmed releases because external clients provide no between-call pause notification. Explicit up, program failure, user cancellation and resource disposal release owned input. macOS implements this lifecycle; Windows implementation is pending. Keyboard modifier names are provider-defined, so the same string may have different support across providers.
|
||||
Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. Native input ownership follows the task and connection. Successful DSH and MCP programs report remaining held input without releasing it. A client pause between completed MCP calls does not notify this server and can leave input held; native ownership still permits explicit release and connection cleanup. Explicit up, program failure, user cancellation and resource disposal release owned input. macOS implements this lifecycle; Windows implementation is pending. Keyboard modifier names are provider-defined, so the same string may have different support across providers.
|
||||
|
||||
Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock.
|
||||
+1
-1
@@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅
|
||||
|
||||
元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。
|
||||
|
||||
键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。原生输入所有权属于任务和连接。DSH 回合中的程序成功结束时报告剩余持有输入,不自动释放。没有 DSH 回合的程序,包括 MCP,在返回前释放并报告确认结果,因为外部客户端不提供调用之间的暂停通知。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 已实现这套生命周期,Windows 待实现。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
|
||||
键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。原生输入所有权属于任务和连接。DSH 和 MCP 程序成功结束时报告剩余持有输入,不自动释放。客户端在两次 MCP 调用之间暂停时不会通知服务端,输入可能继续按住;原生所有权仍支持显式释放和连接清理。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 已实现这套生命周期,Windows 待实现。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
|
||||
|
||||
Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。
|
||||
@@ -93,15 +93,15 @@ describe.skipIf(!existsSync(bin))('cua-mcp profile', { retry: 0 }, () => {
|
||||
|
||||
const held = await probe.request('tools/call', { name: 'cua_run_code', arguments: {
|
||||
code: 'await app.sendKeyEvent("shift", "down"); await win.toggleMouse("left", "down"); await app.sendKeyEvent("w", "down"); inspect("Input sequence finished.")',
|
||||
description: 'Hold mixed input within one MCP program',
|
||||
description: 'Hold mixed input across MCP programs',
|
||||
} }) as CallResult
|
||||
expect(held.isError).toBeUndefined()
|
||||
await expect(`${JSON.stringify(held, null, 2)}\n`).toMatchFileSnapshot('./expected/input-release.json')
|
||||
await expect(`${JSON.stringify(held, null, 2)}\n`).toMatchFileSnapshot('./expected/held-inputs.json')
|
||||
const up = await probe.request('tools/call', { name: 'cua_run_code', arguments: {
|
||||
code: 'await app.sendKeyEvent("w", "up")', description: 'Confirm W was released',
|
||||
code: 'await app.sendKeyEvent("w", "up"); await win.toggleMouse("left", "up"); await app.sendKeyEvent("shift", "up")', description: 'Release the held input',
|
||||
} }) as CallResult
|
||||
expect(up.isError).toBe(true)
|
||||
expect(up.content.some(block => block.type === 'text' && block.text.includes('not held'))).toBe(true)
|
||||
expect(up.isError).toBeUndefined()
|
||||
expect(up.content.some(block => block.type === 'text' && block.text.includes('<system-reminder>'))).toBe(false)
|
||||
const afterRelease = await probe.request('tools/call', { name: 'cua_run_code', arguments: {
|
||||
code: 'inspect("After release")', description: 'Continue without held input',
|
||||
} }) as CallResult
|
||||
|
||||
@@ -18,7 +18,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
|
||||
| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`), [`cua`](../packages/experimental/cua) (`emitAgentEvent`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) |
|
||||
| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
|
||||
| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
|
||||
| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) |
|
||||
| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
|
||||
| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) |
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`), [`cua`](../packages/experimental/cua) (`emitAgentEvent`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) |
|
||||
| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
|
||||
| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
|
||||
| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) |
|
||||
| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
|
||||
| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) |
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 37252a5d19c7fe09
|
||||
zh: f1b33b7da3935155
|
||||
/cua-reports-held-input-after-programs/change:
|
||||
en: e849a0f031b21621
|
||||
zh: ce75b936e290f185
|
||||
en: 4bd67513168d23c2
|
||||
zh: 62139119ecfdc51e
|
||||
/cua-reports-held-input-after-programs/migration:
|
||||
en: ff2470e52eb67983
|
||||
zh: 8fd179145c4da20a
|
||||
@@ -8,7 +8,7 @@ English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
Within DSH turns, macOS explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. MCP programs release remaining input before returning and report confirmed automatic releases, because clients do not notify the server when paused between calls. Windows reporting and unified cleanup remain unimplemented.
|
||||
macOS explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP both preserve input after successful programs. A client pause between completed MCP calls is not observable by the server and can leave input held. Windows reporting and unified cleanup remain unimplemented.
|
||||
|
||||
## Migration
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ description: macOS CUA 的显式输入跨程序和回合保持,成功结束的
|
||||
|
||||
## 变更
|
||||
|
||||
在 DSH 回合中,macOS 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。MCP 程序在返回前释放剩余输入并报告确认的自动释放,因为客户端在两次调用之间暂停时不会通知服务端。Windows 的状态报告和统一清理仍未实现。
|
||||
macOS 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 都在程序成功后保持输入。客户端在两次 MCP 调用之间暂停时,服务端无法观察到,输入可能继续按住。Windows 的状态报告和统一清理仍未实现。
|
||||
|
||||
## 迁移
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: 1777e7bf6785f986
|
||||
zh: e3daac1074ebb74d
|
||||
/deepseek-ai-dsh-cua-macos/use-this-package:
|
||||
en: e6cc819a0e923ed9
|
||||
zh: 39c7ecd7d007d4a7
|
||||
en: ba5ff17d83e875cd
|
||||
zh: 3fc685617b240e00
|
||||
/deepseek-ai-dsh-cua-macos/use-this-package/connect-an-external-execution-environment:
|
||||
en: 3bf05d9ce5eb7224
|
||||
zh: d8d0cd6429374860
|
||||
|
||||
@@ -83,7 +83,7 @@ The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-cua-m
|
||||
|
||||
`pressKey(key, modifiers?)` presses and releases one key. For shortcuts, pass held modifiers separately, as in `pressKey('a', ['command'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. For `pressKey`, `click`, and `drag`, use `command`, `shift`, `option`/`alt`, `control`/`ctrl`, or `fn`. Only `pressKey` accepts `cmd` as a modifier alias for `command`. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. Use the App object's `pressKey` for a short press.
|
||||
|
||||
For a long press, call `app.sendKeyEvent('w', 'down')`. In DSH, explicit key and mouse downs remain held across programs and turns until an explicit up releases them at their saved target. Successful programs report remaining holds in a system reminder, including the target and actual input mode. Program failure, user cancellation, connection closure, reset and disposal release owned keys and buttons together in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` operations retain their immediate cleanup.
|
||||
For a long press, call `app.sendKeyEvent('w', 'down')`. Explicit key and mouse downs remain held across programs and turns until an explicit up releases them at their saved target. Successful programs report remaining holds in a system reminder, including the target and actual input mode. Program failure, user cancellation, connection closure, reset and disposal release owned keys and buttons together in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` operations retain their immediate cleanup.
|
||||
|
||||
Agent disposal and plugin unload cancel and await the complete tool call, including image admission and attachment storage. An image write already in progress must settle before disposal returns; a canceled call cannot return a successful screenshot.
|
||||
|
||||
@@ -245,7 +245,7 @@ Available at app or window level depending on the platform.
|
||||
- pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string.
|
||||
- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold.
|
||||
|
||||
In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation.
|
||||
Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation.
|
||||
|
||||
click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform.
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.
|
||||
|
||||
`pressKey(key, modifiers?)` 按下并松开一个键。使用快捷键时单独传入修饰键,例如 `pressKey('a', ['command'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。`+` 和 `plus` 都会发送 Shift 和等号。`pressKey`、`click` 和 `drag` 都接受修饰键 `command`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`。只有 `pressKey` 的修饰键参数还接受 `command` 的别名 `cmd`。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。
|
||||
|
||||
长按时调用 `app.sendKeyEvent('w', 'down')`。在 DSH 中,显式键盘和鼠标按下会跨程序、跨回合保持,直到显式 up 按保存的目标释放。成功结束的程序通过 system reminder 报告剩余持有输入,包括目标和实际输入方式。程序失败、用户取消、断连、重置和销毁按实际派发顺序的反序统一释放所属键盘键和鼠标按钮。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内及时清理。
|
||||
长按时调用 `app.sendKeyEvent('w', 'down')`。显式键盘和鼠标按下会跨程序、跨回合保持,直到显式 up 按保存的目标释放。成功结束的程序通过 system reminder 报告剩余持有输入,包括目标和实际输入方式。程序失败、用户取消、断连、重置和销毁按实际派发顺序的反序统一释放所属键盘键和鼠标按钮。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内及时清理。
|
||||
|
||||
Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。
|
||||
|
||||
@@ -245,7 +245,7 @@ Available at app or window level depending on the platform.
|
||||
- pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string.
|
||||
- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold.
|
||||
|
||||
In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation.
|
||||
Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation.
|
||||
|
||||
click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform.
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: dea4de90fb3dd169
|
||||
zh: 378ae657f5288807
|
||||
/dsh-cua-native-helper/observation-and-input:
|
||||
en: 3ca2ccd0ee8d549c
|
||||
zh: 1ada0c7b7c38a1a8
|
||||
en: 968548e7bc74562d
|
||||
zh: 29ef183d9dd98734
|
||||
/dsh-cua-native-helper/verification:
|
||||
en: 11172b21e8ebf972
|
||||
zh: dac6787e1e75a88e
|
||||
|
||||
@@ -112,7 +112,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. `pressKey` presses the listed modifiers followed by one key, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. 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 `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and 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.
|
||||
|
||||
The Host attaches `taskId` to explicit input. `HeldInputs` records connection, task, application, original process identity, key code or button, release event and actual input mode before dispatch. Repeated key downs keep one record. Explicit up uses the saved target and input mode, skipping PID-directed releases after process exit or identity reuse. `getHeldInputs` reports only the requesting connection and task records, without reading physical user key state. Successful programs use this snapshot for their reminder. `releaseHeldInputs` releases keyboard and mouse records together in reverse dispatch order after program failure, cancellation or disposal. Normal DSH program and turn endings do not release input. MCP program completion releases remaining input, and `releaseHeldInputs` returns the records whose up events were dispatched. Connection shutdown joins native work before fallback release. Balanced key chords, text, clicks and drags keep their operation-local cleanup.
|
||||
The Host attaches `taskId` to explicit input. `HeldInputs` records connection, task, application, original process identity, key code or button, release event and actual input mode before dispatch. Repeated key downs keep one record. Explicit up uses the saved target and input mode, skipping PID-directed releases after process exit or identity reuse. `getHeldInputs` reports only the requesting connection and task records, without reading physical user key state. Successful programs use this snapshot for their reminder. `releaseHeldInputs` releases keyboard and mouse records together in reverse dispatch order after program failure, cancellation or disposal. Normal program and turn endings do not release input. `releaseHeldInputs` returns the records whose up events were dispatched, for confirmed cleanup notices. Connection shutdown joins native work before fallback release. Balanced key chords, text, clicks and drags keep their operation-local cleanup.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后
|
||||
|
||||
`typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和一个主键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。
|
||||
|
||||
宿主为显式输入附上 `taskId`。`HeldInputs` 在派发前记录连接、任务、应用、原进程身份、键码或按钮、释放事件和实际输入方式。重复按键只保留一条记录。显式 up 使用保存的目标和输入方式;进程退出或 PID 身份变化后跳过定向释放。`getHeldInputs` 只报告请求连接和任务的记录,不读取用户物理按键状态。成功结束的程序用该快照生成提醒。程序失败、取消或销毁时,`releaseHeldInputs` 按派发顺序的反序统一释放键盘和鼠标记录。正常 DSH 程序结束和回合结束不释放输入。MCP 程序结束会释放剩余输入,`releaseHeldInputs` 返回已派发 up 的记录。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。
|
||||
宿主为显式输入附上 `taskId`。`HeldInputs` 在派发前记录连接、任务、应用、原进程身份、键码或按钮、释放事件和实际输入方式。重复按键只保留一条记录。显式 up 使用保存的目标和输入方式;进程退出或 PID 身份变化后跳过定向释放。`getHeldInputs` 只报告请求连接和任务的记录,不读取用户物理按键状态。成功结束的程序用该快照生成提醒。程序失败、取消或销毁时,`releaseHeldInputs` 按派发顺序的反序统一释放键盘和鼠标记录。正常程序结束和回合结束不释放输入。`releaseHeldInputs` 返回已派发 up 的记录,用于确认后的清理提醒。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。
|
||||
|
||||
所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。
|
||||
|
||||
|
||||
@@ -51,8 +51,8 @@
|
||||
en: 0b0c63281111993b
|
||||
zh: 45716a56b5a5ad12
|
||||
/deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work:
|
||||
en: 27085bbaf0a24801
|
||||
zh: 4fefe3ddbf60fea2
|
||||
en: b1ce029c37a771af
|
||||
zh: 42390a45e6c440e4
|
||||
/deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 8ec3e73528ddb1a6
|
||||
@@ -167,7 +167,7 @@ The tool catalog and instructions are stable for one installation. The reference
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- Each program releases remaining native-held keys and mouse buttons before returning. A system reminder lists inputs automatically released after native acknowledgement. Input cannot remain held across MCP calls; no client pause notification is required. Program failure, cancellation, reset and connection closure also release owned input.
|
||||
- Successful programs retain held keys and mouse buttons across calls and report them in a system reminder. Program failure, a received cancellation of an active cua_run_code request, reset and connection closure release owned input. If a call sends down and returns, and the client pauses while its model is thinking, this server receives no cancellation: that input can remain pressed until explicit up or later cleanup.
|
||||
- macOS and native Windows Hosts have a provider. Other Hosts, WSL included, list `cua_get_api_reference` and `cua_reset`, which both name the missing provider; a `cua_run_code` call fails as `unknown tool`.
|
||||
- On Windows the [provider's limits](../cua-windows/README.md#known-limitations-and-deferred-work) apply through MCP: it does not launch applications, grants no `Always allow`, and an npm installation needs `helperPath`.
|
||||
- Elicitation uses the 2025 MCP request model; a client that negotiates the 2026-07-28 revision receives an error for consent requests and should use `DSH_CUA_CONSENT=allow`.
|
||||
|
||||
@@ -167,7 +167,7 @@ patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载该
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- 每个程序在返回前释放剩余的原生键盘键和鼠标按钮。原生确认后,通过 system reminder 列出自动释放的输入。输入不能跨 MCP 调用保持,不需要客户端提供暂停通知。程序失败、取消、重置和断连也会释放所属输入。
|
||||
- 成功结束的程序跨调用保持键盘键和鼠标按钮,并通过 system reminder 报告。程序失败、执行中的 cua_run_code 请求收到取消、重置和断连会释放所属输入。如果一次调用发送 down 后返回,客户端随后在模型思考期间暂停,服务端收不到取消:该输入可能持续按住,直到显式 up 或后续清理。
|
||||
- macOS 与原生 Windows Host 有提供方。其他 Host(包括 WSL)列出 `cua_get_api_reference` 与 `cua_reset`,二者都指出缺少提供方;调用 `cua_run_code` 以 `unknown tool` 失败。
|
||||
- 在 Windows 上,[提供方的限制](../cua-windows/README.zh.md#known-limitations-and-deferred-work)经 MCP 同样适用:它不启动应用,不提供 `Always allow` 授权,npm 安装需要配置 `helperPath`。
|
||||
- Elicitation 使用 2025 版 MCP 请求模型;协商到 2026-07-28 修订版的客户端在授权请求时收到错误,应改用 `DSH_CUA_CONSENT=allow`。
|
||||
|
||||
@@ -96,7 +96,7 @@ const INSTRUCTIONS = 'DeepSeek Harness Computer Use: observe and operate desktop
|
||||
+ 'written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua '
|
||||
+ 'object; program state persists across calls on this connection. A call may ask the user for application or pointer '
|
||||
+ 'consent before it proceeds. Call cua_reset to discard program state. '
|
||||
+ 'Remaining held keys and mouse buttons are released before each program returns. A system reminder lists inputs automatically released at program end. Explicit downs cannot stay held across MCP calls.'
|
||||
+ 'Explicit key and mouse downs remain held across successful programs; a system reminder lists remaining holds. Explicit up, program failure, request cancellation, reset, and connection closure release owned input. Client pause between completed calls is not observable by this server and does not release input.'
|
||||
|
||||
const NO_PROVIDER = 'Computer Use is not available on this Host: the cua-mcp profile has no active CUA provider. '
|
||||
+ 'Providers exist for macOS and native Windows; on those Hosts the server\'s stderr names why the provider did not start.'
|
||||
@@ -203,21 +203,34 @@ export async function createCuaMcpServer(ctx: Context, options: CuaMcpServerOpti
|
||||
}
|
||||
// The program runtime rejects a run while the Agent's previous process is still exiting.
|
||||
while (resetting !== undefined) await resetting
|
||||
// The call is the Agent's maintenance activity: Agent disposal cancels it and waits for it, with its nested
|
||||
// calls, to settle before the Agent's scope and Session close.
|
||||
const batch = await agent.runMaintenance(maintenance => ctx.agents.withInitiator(agent, () => ctx.tools.execute({
|
||||
calls: [{
|
||||
type: 'tool-call', id: brandString<ToolCallId>(`cua-mcp-${String(++calls)}`), name: PROGRAM_TOOL, arguments: JSON.stringify(args),
|
||||
}],
|
||||
agent, signal: AbortSignal.any([signal, maintenance]),
|
||||
})))
|
||||
const outcome = batch.results[0]
|
||||
if (outcome === undefined) throw new Error(`The tool executor settled without a ${PROGRAM_TOOL} result`)
|
||||
const programs = ctx.get('cuaPrograms')
|
||||
return projectToolResult(outcome.result, batch.additionalContexts, {
|
||||
attachments: ctx.attachments, target: image => programs?.screenshotRequestTarget(image),
|
||||
}, signal)
|
||||
let cleanup: Promise<void> | undefined
|
||||
const cancel = (): void => {
|
||||
cleanup ??= programs?.releaseInputs(agent) ?? Promise.resolve()
|
||||
void cleanup.catch(() => undefined) // The native owner reports failure; finally joins this same cleanup.
|
||||
}
|
||||
signal.addEventListener('abort', cancel, { once: true })
|
||||
if (signal.aborted) cancel()
|
||||
try {
|
||||
// The call is the Agent's maintenance activity: Agent disposal cancels it and waits for it, with its nested
|
||||
// calls, to settle before the Agent's scope and Session close.
|
||||
const batch = await agent.runMaintenance(maintenance => ctx.agents.withInitiator(agent, () => ctx.tools.execute({
|
||||
calls: [{
|
||||
type: 'tool-call', id: brandString<ToolCallId>(`cua-mcp-${String(++calls)}`), name: PROGRAM_TOOL, arguments: JSON.stringify(args),
|
||||
}],
|
||||
agent, signal: AbortSignal.any([signal, maintenance]),
|
||||
})))
|
||||
const outcome = batch.results[0]
|
||||
if (outcome === undefined) throw new Error(`The tool executor settled without a ${PROGRAM_TOOL} result`)
|
||||
return await projectToolResult(outcome.result, batch.additionalContexts, {
|
||||
attachments: ctx.attachments, target: image => programs?.screenshotRequestTarget(image),
|
||||
}, signal)
|
||||
} finally {
|
||||
signal.removeEventListener('abort', cancel)
|
||||
await cleanup
|
||||
}
|
||||
}
|
||||
|
||||
const resetEnvironment = (): CallToolResult | Promise<CallToolResult> => {
|
||||
const programs = ctx.get('cuaPrograms')
|
||||
if (programs === undefined) return failure(NO_PROVIDER)
|
||||
|
||||
@@ -182,35 +182,60 @@ async function setup(options: SetupOptions = {}) {
|
||||
}
|
||||
|
||||
describe('Computer Use MCP composition', () => {
|
||||
it('releases MCP input before returning and reports only confirmed automatic releases', async () => {
|
||||
it('retains input across successful MCP programs and reports remaining holds', async () => {
|
||||
const { native, run } = await setup()
|
||||
const held = await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); await app.sendKeyEvent("w", "down"); await win.toggleMouse("left", "down")')
|
||||
expect(held.isError).not.toBe(true)
|
||||
expect(native.held.map(press => press.key)).toEqual(['w', 'left'])
|
||||
expect(native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false)
|
||||
expect(texts(held).join('')).toContain('CUA inputs are still held')
|
||||
expect(texts(await run('inspect("next program")')).join('')).toContain('Key "w"')
|
||||
const released = await run('await win.toggleMouse("left", "up"); await app.sendKeyEvent("w", "up")')
|
||||
expect(texts(released).join('')).not.toContain('<system-reminder>')
|
||||
expect(native.held).toEqual([])
|
||||
expect(native.events).toEqual(['w:down', 'left:down', 'left:up', 'w:up'])
|
||||
expect(texts(held).join('')).toContain('CUA inputs were automatically released at program end')
|
||||
expect(texts(held).join('')).toContain('Mouse left')
|
||||
expect(texts(held).join('')).toContain('Key "w"')
|
||||
expect(texts(await run('inspect("next program")')).join('')).not.toContain('<system-reminder>')
|
||||
expect(texts(await run('await app.sendKeyEvent("d", "down"); await app.sendKeyEvent("d", "up")')).join('')).not.toContain('<system-reminder>')
|
||||
const failed = await run('await win.toggleMouse("left", "down"); throw Error("failed program")')
|
||||
expect(failed.isError).toBe(true)
|
||||
expect(native.held).toEqual([])
|
||||
expect((await run('await win.click("0")')).isError).not.toBe(true)
|
||||
})
|
||||
|
||||
it('waits for the native MCP cleanup reply and reports refusal without claiming release', async () => {
|
||||
it('waits for cleanup after a failed MCP program and reports native refusal', async () => {
|
||||
const { native, run } = await setup()
|
||||
const release = native.controlNext('releaseHeldInputs')
|
||||
let settled = false
|
||||
const running = run('var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")').then((value) => { settled = true; return value })
|
||||
const running = run('var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down"); throw Error("program failed")').then((value) => { settled = true; return value })
|
||||
await release.entered
|
||||
expect(settled).toBe(false)
|
||||
release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'MCP release refused' })
|
||||
const result = await running
|
||||
expect(result.isError).toBe(true)
|
||||
expect(texts(result).join('')).toContain('MCP release refused')
|
||||
expect(texts(result).join('')).not.toContain('inputs were automatically released')
|
||||
})
|
||||
|
||||
it('cleans up a cancelled MCP request even after its program has finished and image delivery is pending', async () => {
|
||||
const { ctx, native, run } = await setup()
|
||||
const entered: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const finish: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const original = ctx.attachments.readImageRequest.bind(ctx.attachments)
|
||||
const read = vi.spyOn(ctx.attachments, 'readImageRequest').mockImplementation(async (...args) => {
|
||||
if (native.calls.some(call => call.method === 'getHeldInputs')) { entered.resolve(); await finish.promise }
|
||||
return original(...args)
|
||||
})
|
||||
onTestFinished(() => { finish.resolve(); read.mockRestore() })
|
||||
const controller = new AbortController()
|
||||
const running = run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await app.sendKeyEvent("w", "down"); inspect(await win.getScreenshot())', {}, controller.signal)
|
||||
const cancelled = expect(running).rejects.toThrow(/abort/i)
|
||||
await entered.promise
|
||||
const release = native.controlNext('releaseHeldInputs')
|
||||
try {
|
||||
controller.abort()
|
||||
await release.entered
|
||||
expect(native.held.map(press => press.key)).toEqual(['w'])
|
||||
release.reply()
|
||||
} finally { finish.resolve() }
|
||||
await cancelled
|
||||
await run('inspect("after cancellation")')
|
||||
expect(native.held).toEqual([])
|
||||
})
|
||||
|
||||
it('serves three tools, returns the API reference on request, and retains program state in the workspace', async () => {
|
||||
|
||||
@@ -102,7 +102,7 @@ function fixture(options: SetupOptions = {}) {
|
||||
ctx.provide('tools', { execute, get } as never)
|
||||
ctx.provide('systemPrompt', { assemble } as never)
|
||||
ctx.provide('attachments', {} as never)
|
||||
if (options.programs !== false) ctx.provide('cuaPrograms', { release, screenshotRequestTarget: () => undefined, ...options.programs } as never)
|
||||
if (options.programs !== false) ctx.provide('cuaPrograms', { release, releaseInputs: vi.fn(async () => {}), screenshotRequestTarget: () => undefined, ...options.programs } as never)
|
||||
onTestFinished(async () => { await ctx.fiber.dispose() })
|
||||
return {
|
||||
ctx, agent, maintenance, runMaintenance, cancel, whenIdle, create, withInitiator, initiators, mount, execute, get, assemble,
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 3f638a4a76023fc5
|
||||
zh: 515aeb5de6ae5b33
|
||||
/deepseek-ai-dsh-cua/understand-the-implementation:
|
||||
en: 7e8694a4435a1186
|
||||
zh: 8070eb8cabf9fd83
|
||||
en: 7e40a3ed87af41a5
|
||||
zh: a0ad1cbf2c70c285
|
||||
/deepseek-ai-dsh-cua/further-exploration:
|
||||
en: c174fb5a00ea3681
|
||||
zh: 039340042676881d
|
||||
|
||||
@@ -91,9 +91,9 @@ Permission responses identify their platform and report only the state that plat
|
||||
<details>
|
||||
<summary>Shared execution and platform ownership</summary>
|
||||
|
||||
Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs in DSH turns query those records and append a system reminder when input remains held; normal program and turn endings preserve input. Programs outside a DSH turn, including MCP, instead await release before returning and report only inputs the helper confirmed it released. Reminders travel through logged additional context in DSH and through the tool response in MCP. Program failure, cancellation, connection closure, environment reset and disposal stop owned dispatch and await reverse-order release. Cleanup failure disables further CUA operations for the task and reports the uncertainty. Provider unload retains these listeners until programs and native connections drain. Capability methods remain static. Windows leaves `heldInputState` unset until its helper implements reporting and cleanup; it receives no new commands.
|
||||
Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. Program failure, cancellation, connection closure, environment reset and disposal stop owned dispatch and await reverse-order release. Cleanup failure disables further CUA operations for the task and reports the uncertainty. Provider unload retains these listeners until programs and native connections drain. Capability methods remain static. Windows leaves `heldInputState` unset until its helper implements reporting and cleanup; it receives no new commands.
|
||||
|
||||
Held input belongs to the task and native connection, outside program processes. DSH observes the turn cancellation signal while the model is thinking. Confirmed cleanup queues a release notice for the resumed model; held-state snapshots arriving after cleanup starts are discarded.
|
||||
Held input belongs to the task and native connection, outside program processes. DSH observes the turn cancellation signal while the model is thinking. DSH queues confirmed cleanup as a release notice for the resumed model; held-state snapshots arriving after cleanup starts are discarded.
|
||||
|
||||
The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_<sha256>.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock.
|
||||
|
||||
|
||||
@@ -91,9 +91,9 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
|
||||
<details>
|
||||
<summary>共享执行与平台职责</summary>
|
||||
|
||||
实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。DSH 回合中成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;正常程序结束和回合结束均保持输入。没有 DSH 回合的程序,包括 MCP,在返回前等待释放,并只报告 helper 已确认释放的输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。程序失败、取消、断连、环境重置和销毁会停止所属输入派发,并等待反序释放。清理失败会禁用该任务后续 CUA 操作并报告结果不确定。提供方卸载前保留监听器,直到程序和原生连接排空。能力方法列表保持静态。Windows 在 helper 实现报告和清理前不设置 `heldInputState`,不会收到新命令。
|
||||
实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。程序失败、取消、断连、环境重置和销毁会停止所属输入派发,并等待反序释放。清理失败会禁用该任务后续 CUA 操作并报告结果不确定。提供方卸载前保留监听器,直到程序和原生连接排空。能力方法列表保持静态。Windows 在 helper 实现报告和清理前不设置 `heldInputState`,不会收到新命令。
|
||||
|
||||
持有输入属于任务和原生连接,保存在程序进程之外。模型思考期间,DSH 仍监听回合取消信号。清理确认后,释放提醒进入会话队列,供恢复后的模型读取;清理开始后才到达的旧持有状态提醒会被丢弃。
|
||||
持有输入属于任务和原生连接,保存在程序进程之外。模型思考期间,DSH 仍监听回合取消信号。DSH 在清理确认后将释放提醒写入会话队列,供恢复后的模型读取;清理开始后才到达的旧持有状态提醒会被丢弃。
|
||||
|
||||
[授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_<sha256>.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ Available at app or window level depending on the platform.
|
||||
- pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string.
|
||||
- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier.
|
||||
|
||||
In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation.
|
||||
Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation.
|
||||
|
||||
click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform.
|
||||
|
||||
|
||||
@@ -12,17 +12,15 @@ const heldInputs = z.array(z.discriminatedUnion('kind', [
|
||||
z.object({ ...target, kind: z.literal('mouse'), button: z.enum(['left', 'right', 'middle']), windowId: z.string() }),
|
||||
]))
|
||||
|
||||
function renderInputs(inputs: z.infer<typeof heldInputs>, state: 'held' | 'released' | 'program-end'): string {
|
||||
function renderInputs(inputs: z.infer<typeof heldInputs>, state: 'held' | 'released'): string {
|
||||
const rows = inputs.map(input => input.kind === 'key'
|
||||
? `- Key ${JSON.stringify(input.key)}, appHandle ${JSON.stringify(input.appHandle)} (${input.mode} input).`
|
||||
: `- Mouse ${input.button}, appHandle ${JSON.stringify(input.appHandle)}, windowId ${JSON.stringify(input.windowId)} (${input.mode} input).`)
|
||||
const title = state === 'held' ? 'CUA inputs are still held:'
|
||||
: state === 'program-end' ? 'CUA inputs were automatically released at program end:' : 'CUA inputs were released during cleanup:'
|
||||
const title = state === 'held' ? 'CUA inputs are still held:' : 'CUA inputs were released during cleanup:'
|
||||
return ['<system-reminder>', title, ...rows,
|
||||
state === 'held'
|
||||
? "They remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed."
|
||||
: state === 'program-end' ? 'These inputs are no longer held. In this environment, keep any required hold sequence within one program.'
|
||||
: 'These inputs are no longer held.',
|
||||
: 'These inputs are no longer held.',
|
||||
'</system-reminder>'].join('\n')
|
||||
}
|
||||
|
||||
@@ -44,7 +42,7 @@ class InputOwner {
|
||||
this.client = client
|
||||
}
|
||||
|
||||
async reminder(): Promise<string | undefined> {
|
||||
async reminder(inTurn: boolean): Promise<string | undefined> {
|
||||
if (this.closing || !this.client) return
|
||||
const inputs = heldInputs.parse(await this.client.request('getHeldInputs', { taskId: this.agent.id }, this.controller.signal))
|
||||
if (inputs.length === 0) {
|
||||
@@ -53,15 +51,10 @@ class InputOwner {
|
||||
this.client = undefined
|
||||
return
|
||||
}
|
||||
this.notifySessionOnRelease = true
|
||||
this.notifySessionOnRelease ||= inTurn
|
||||
return renderInputs(inputs, 'held')
|
||||
}
|
||||
|
||||
async releaseReminder(): Promise<string | undefined> {
|
||||
if (this.closing) return
|
||||
const released = await this.close()
|
||||
return released.length > 0 ? renderInputs(released, 'program-end') : undefined
|
||||
}
|
||||
|
||||
close(canRequest = true): Promise<z.infer<typeof heldInputs>> {
|
||||
this.controller.abort()
|
||||
@@ -161,12 +154,11 @@ export class CuaHeldInputs {
|
||||
} else if (execution.parent === undefined) {
|
||||
const owner = this.owners.get(agent)
|
||||
const inTurn = ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null
|
||||
const text = inTurn ? await owner?.reminder() : await owner?.releaseReminder()
|
||||
const text = await owner?.reminder(inTurn)
|
||||
if (signal.aborted) { await this.release(agent); return result }
|
||||
if (text && (!inTurn || !owner?.closing)) return { ...result, additionalContexts: [...result.additionalContexts ?? [],
|
||||
if (text && !owner?.closing) return { ...result, additionalContexts: [...result.additionalContexts ?? [],
|
||||
createUserMessage({ content: [{ type: 'text', text }],
|
||||
source: { kind: inTurn ? 'cua-held-inputs' : 'cua-inputs-released',
|
||||
form: 'notice', summary: inTurn ? 'CUA inputs remain held' : 'CUA inputs released' } }),
|
||||
source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }),
|
||||
] }
|
||||
}
|
||||
return result
|
||||
|
||||
@@ -33,6 +33,13 @@ export interface CuaPrograms {
|
||||
* @throws When the process cleanup fails.
|
||||
*/
|
||||
release(agent: Agent): Promise<void>
|
||||
/**
|
||||
* Release the Agent's tracked input while retaining its program variables and application grants.
|
||||
* Providers without held-input state support retain their existing cancellation behavior.
|
||||
* @param agent - Owner of the input to release.
|
||||
* @returns Completion after native acknowledgement, or rejection when cleanup is unconfirmed.
|
||||
*/
|
||||
releaseInputs(agent: Agent): Promise<void>
|
||||
/**
|
||||
* Request-image target the provider delivered for a stored screenshot when `screenshotTarget` is configured.
|
||||
* A host that forwards screenshots outside a model request reads the same request version with it, so the
|
||||
@@ -68,7 +75,7 @@ export function fixedScreenshotTarget(configured: CuaScreenshotTargetConfig, ima
|
||||
* @param tool Internal native tool; Agents off the configured preset can reach it only through the program.
|
||||
* @param guidance Raw-tool operation instructions for the configured preset.
|
||||
* @param programGuidance Operation instructions available inside cua_run_code.
|
||||
* @param releaseInputs Release held input when resetting the program environment.
|
||||
* @param releaseInputs Release tracked input on cancellation or environment reset.
|
||||
* @returns Exact registration disposer, draining programs before native resources can close.
|
||||
*/
|
||||
export function installCuaTools(
|
||||
@@ -157,6 +164,7 @@ var cua = connectCua(() => tools.cua);
|
||||
release: async (agent: Agent) => {
|
||||
try { await consumer.ptcRuntime.release(agent) } finally { await releaseInputs(agent) }
|
||||
},
|
||||
releaseInputs,
|
||||
screenshotRequestTarget: image => config.screenshotTarget === undefined
|
||||
? undefined : fixedScreenshotTarget(config.screenshotTarget, image),
|
||||
} satisfies CuaPrograms)
|
||||
|
||||
@@ -183,8 +183,8 @@ export interface CuaSurface {
|
||||
pressKey(key: string, modifiers?: string[]): Promise<CuaActionResult>
|
||||
/**
|
||||
* Send one key-down or key-up event at the current input focus.
|
||||
* In DSH turns, explicit downs persist across programs and turns; successful programs remind about remaining holds.
|
||||
* Programs outside a DSH turn, including MCP, release remaining input before returning and report the release.
|
||||
* Explicit downs persist across programs and turns; successful programs remind about remaining holds.
|
||||
* MCP client pauses between completed calls do not notify the provider and leave held input unchanged.
|
||||
* Program failure, cancellation, connection closure and disposal release owned input. Windows support is pending.
|
||||
* Rejects when the provider does not support keyboard input at this scope.
|
||||
* @param key - Platform-defined key name; modifier keys may themselves be targets.
|
||||
|
||||
Reference in new issue
Block a user