Release MCP held input before returning and report acknowledged releases
This commit is contained in:
1 parent
02df940e7b
commit
4795e0fc20
27 files changed
+110
-74
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: 7bb0a5c23044b09c
|
||||
zh: ca7c4b860660b5ce
|
||||
en: 7f4cb4b375fc8bdb
|
||||
zh: bf273fdc4940d988
|
||||
@@ -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 report remaining held input; normal program and turn endings do not release it. 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 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.
|
||||
|
||||
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` 的调用方控制按下与抬起的配对。原生输入所有权属于任务和连接。成功结束的程序报告剩余持有输入,正常程序结束和回合结束不释放。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 已实现这套生命周期,Windows 待实现。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
|
||||
键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。原生输入所有权属于任务和连接。DSH 回合中的程序成功结束时报告剩余持有输入,不自动释放。没有 DSH 回合的程序,包括 MCP,在返回前释放并报告确认结果,因为外部客户端不提供调用之间的暂停通知。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 已实现这套生命周期,Windows 待实现。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
|
||||
|
||||
Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 37252a5d19c7fe09
|
||||
zh: f1b33b7da3935155
|
||||
/cua-reports-held-input-after-programs/change:
|
||||
en: 5b321223d0dead45
|
||||
zh: d0d09bd63dd303c2
|
||||
en: e849a0f031b21621
|
||||
zh: ce75b936e290f185
|
||||
/cua-reports-held-input-after-programs/migration:
|
||||
en: ff2470e52eb67983
|
||||
zh: 8fd179145c4da20a
|
||||
@@ -8,7 +8,7 @@ English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
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 use the same behavior. Windows reporting and unified cleanup remain unimplemented.
|
||||
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.
|
||||
|
||||
## Migration
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ description: macOS CUA 的显式输入跨程序和回合保持,成功结束的
|
||||
|
||||
## 变更
|
||||
|
||||
macOS 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 使用相同行为。Windows 的状态报告和统一清理仍未实现。
|
||||
在 DSH 回合中,macOS 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。MCP 程序在返回前释放剩余输入并报告确认的自动释放,因为客户端在两次调用之间暂停时不会通知服务端。Windows 的状态报告和统一清理仍未实现。
|
||||
|
||||
## 迁移
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: 1777e7bf6785f986
|
||||
zh: e3daac1074ebb74d
|
||||
/deepseek-ai-dsh-cua-macos/use-this-package:
|
||||
en: ba5ff17d83e875cd
|
||||
zh: 3fc685617b240e00
|
||||
en: e6cc819a0e923ed9
|
||||
zh: 39c7ecd7d007d4a7
|
||||
/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')`. 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')`. 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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -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')`。显式键盘和鼠标按下会跨程序、跨回合保持,直到显式 up 按保存的目标释放。成功结束的程序通过 system reminder 报告剩余持有输入,包括目标和实际输入方式。程序失败、用户取消、断连、重置和销毁按实际派发顺序的反序统一释放所属键盘键和鼠标按钮。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内及时清理。
|
||||
长按时调用 `app.sendKeyEvent('w', 'down')`。在 DSH 中,显式键盘和鼠标按下会跨程序、跨回合保持,直到显式 up 按保存的目标释放。成功结束的程序通过 system reminder 报告剩余持有输入,包括目标和实际输入方式。程序失败、用户取消、断连、重置和销毁按实际派发顺序的反序统一释放所属键盘键和鼠标按钮。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内及时清理。
|
||||
|
||||
Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: dea4de90fb3dd169
|
||||
zh: 378ae657f5288807
|
||||
/dsh-cua-native-helper/observation-and-input:
|
||||
en: f242f4dbb1e46342
|
||||
zh: ff87afc313433636
|
||||
en: efbdd87d24ceb412
|
||||
zh: b9eb5d9d38dde450
|
||||
/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 program and turn endings do not release input. 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 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 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` 按派发顺序的反序统一释放键盘和鼠标记录。正常程序结束和回合结束不释放输入。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。
|
||||
宿主为显式输入附上 `taskId`。`HeldInputs` 在派发前记录连接、任务、应用、原进程身份、键码或按钮、释放事件和实际输入方式。重复按键只保留一条记录。显式 up 使用保存的目标和输入方式;进程退出或 PID 身份变化后跳过定向释放。`getHeldInputs` 只报告请求连接和任务的记录,不读取用户物理按键状态。成功结束的程序用该快照生成提醒。程序失败、取消或销毁时,`releaseHeldInputs` 按派发顺序的反序统一释放键盘和鼠标记录。正常 DSH 程序结束和回合结束不释放输入。MCP 程序结束会释放剩余输入,`releaseHeldInputs` 返回已派发 up 的记录。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。
|
||||
|
||||
所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。
|
||||
|
||||
|
||||
@@ -168,6 +168,23 @@ final class HeldInputs: @unchecked Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
private func record(_ press: Press) -> JSONValue {
|
||||
var record: [String: JSONValue] = ["appHandle": .string(press.owner.app)]
|
||||
switch press.mode {
|
||||
case .keyboard(_, _, let name):
|
||||
record["kind"] = .string("key")
|
||||
record["key"] = .string(name)
|
||||
record["mode"] = .string("application")
|
||||
case .windowPointer(let button, let window), .systemPointer(let button, let window):
|
||||
record["kind"] = .string("mouse")
|
||||
record["button"] = .string(button == .left ? "left" : button == .right ? "right" : "middle")
|
||||
record["windowId"] = .string(String(window))
|
||||
if case .systemPointer = press.mode { record["mode"] = .string("system") }
|
||||
else { record["mode"] = .string("window") }
|
||||
}
|
||||
return .object(record)
|
||||
}
|
||||
|
||||
/// Only the caller's registered input is disclosed; physical user input is never inferred.
|
||||
func held(connection: UUID, task: String) throws -> JSONValue {
|
||||
try lock.withLock {
|
||||
@@ -181,34 +198,25 @@ final class HeldInputs: @unchecked Sendable {
|
||||
}
|
||||
}
|
||||
return .array(pressed.filter { $0.owner.connection == connection && $0.owner.task == task }.map { press in
|
||||
var record: [String: JSONValue] = ["appHandle": .string(press.owner.app)]
|
||||
switch press.mode {
|
||||
case .keyboard(_, _, let name):
|
||||
record["kind"] = .string("key")
|
||||
record["key"] = .string(name)
|
||||
record["mode"] = .string("application")
|
||||
case .windowPointer(let button, let window), .systemPointer(let button, let window):
|
||||
record["kind"] = .string("mouse")
|
||||
record["button"] = .string(button == .left ? "left" : button == .right ? "right" : "middle")
|
||||
record["windowId"] = .string(String(window))
|
||||
if case .systemPointer = press.mode { record["mode"] = .string("system") }
|
||||
else { record["mode"] = .string("window") }
|
||||
}
|
||||
return .object(record)
|
||||
record(press)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func release(connection: UUID, task: String? = nil) throws {
|
||||
@discardableResult
|
||||
func release(connection: UUID, task: String? = nil) throws -> [JSONValue] {
|
||||
try lock.withLock {
|
||||
var failures: [String] = []
|
||||
var released: [JSONValue] = []
|
||||
for index in pressed.indices.reversed() {
|
||||
let owner = pressed[index].owner
|
||||
let press = pressed[index]
|
||||
let owner = press.owner
|
||||
guard owner.connection == connection, task == nil || owner.task == task else { continue }
|
||||
do { _ = try release(at: index) }
|
||||
do { if try release(at: index) { released.append(record(press)) } }
|
||||
catch { failures.append(String(describing: error)) }
|
||||
}
|
||||
if !failures.isEmpty { throw NativeFailure(code: "INPUT_CLEANUP_FAILED", message: failures.joined(separator: "; ")) }
|
||||
return released
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -169,8 +169,7 @@ import Darwin
|
||||
return try scheduler.heldInputs.held(connection: connectionID, task: params.string("taskId"))
|
||||
}
|
||||
if request.method == "releaseHeldInputs" {
|
||||
try scheduler.heldInputs.release(connection: connectionID, task: params.string("taskId"))
|
||||
return AXWorker.actionResult
|
||||
return .array(try scheduler.heldInputs.release(connection: connectionID, task: params.string("taskId")))
|
||||
}
|
||||
if request.method == "toggleMouse", try params.string("direction") == "up" {
|
||||
let dispatched = try scheduler.heldInputs.pointerUp(owner: .init(connection: connectionID, task: params.string("taskId"),
|
||||
|
||||
@@ -148,7 +148,7 @@ async function setup(
|
||||
model?: { provider: string; model: string }, ptc = false, overrides: Parameters<typeof NativeProvider.Config>[0] = {},
|
||||
) {
|
||||
native.connect.mockClear()
|
||||
native.cleanup.mockReset().mockResolvedValue({ dispatched: true })
|
||||
native.cleanup.mockReset().mockResolvedValue([])
|
||||
native.request.mockReset().mockResolvedValue([])
|
||||
native.dispose.mockReset()
|
||||
native.instances.length = 0
|
||||
|
||||
@@ -51,8 +51,8 @@
|
||||
en: 0b0c63281111993b
|
||||
zh: 45716a56b5a5ad12
|
||||
/deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work:
|
||||
en: 15a5daadd52dddd8
|
||||
zh: 5d4ddf2da4f31bba
|
||||
en: 27085bbaf0a24801
|
||||
zh: 4fefe3ddbf60fea2
|
||||
/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>
|
||||
|
||||
- Successful programs disclose remaining native-held keys and mouse buttons in a system reminder. Inputs persist across calls until explicit up. Program failure, cancellation, reset and connection closure release owned input; no client turn notification is required.
|
||||
- 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.
|
||||
- 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 报告原生仍按住的键盘键和鼠标按钮。输入跨调用保持,直到显式 up。程序失败、取消、重置和断连释放所属输入,不需要客户端发送回合通知。
|
||||
- 每个程序在返回前释放剩余的原生键盘键和鼠标按钮。原生确认后,通过 system reminder 列出自动释放的输入。输入不能跨 MCP 调用保持,不需要客户端提供暂停通知。程序失败、取消、重置和断连也会释放所属输入。
|
||||
- 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. '
|
||||
+ 'Explicit key and mouse downs can remain held across programs. A system reminder lists remaining held inputs after successful programs. Release them explicitly when finished; program failure, cancellation, reset, and connection closure release owned input.'
|
||||
+ '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.'
|
||||
|
||||
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.'
|
||||
|
||||
@@ -182,21 +182,35 @@ async function setup(options: SetupOptions = {}) {
|
||||
}
|
||||
|
||||
describe('Computer Use MCP composition', () => {
|
||||
it('retains input across MCP programs, reminds after success, and releases on error and reset', async () => {
|
||||
const { native, run, client } = await setup()
|
||||
expect((await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); await app.sendKeyEvent("w", "down")')).isError).not.toBe(true)
|
||||
expect(native.held.map(press => press.key)).toEqual(['w'])
|
||||
const continuing = await run('inspect("continue")')
|
||||
expect(texts(continuing).join('')).toContain('Key "w", appHandle "fixture-app"')
|
||||
const released = await run('await app.sendKeyEvent("w", "up")')
|
||||
expect(texts(released).join('')).not.toContain('<system-reminder>')
|
||||
it('releases MCP input before returning and reports only confirmed automatic releases', 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).toEqual([])
|
||||
expect((await run('await win.toggleMouse("left", "down"); throw Error("failed program")')).isError).toBe(true)
|
||||
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(texts(await run('await app.sendKeyEvent("d", "down")')).join('')).toContain('Key "d"')
|
||||
await client.callTool({ name: 'cua_reset', arguments: {} })
|
||||
expect(native.held).toEqual([])
|
||||
expect((await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); await win.click("0")')).isError).not.toBe(true)
|
||||
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 () => {
|
||||
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 })
|
||||
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('serves three tools, returns the API reference on request, and retains program state in the workspace', async () => {
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 3f638a4a76023fc5
|
||||
zh: 515aeb5de6ae5b33
|
||||
/deepseek-ai-dsh-cua/understand-the-implementation:
|
||||
en: 3b13747971967c17
|
||||
zh: 8ce73ad7615b5f05
|
||||
en: 78be79b4935a5a93
|
||||
zh: eb50cccc867fb1e9
|
||||
/deepseek-ai-dsh-cua/further-exploration:
|
||||
en: c174fb5a00ea3681
|
||||
zh: 039340042676881d
|
||||
|
||||
@@ -91,7 +91,7 @@ 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 query those records and append a system reminder only when input remains held; normal program and turn endings preserve input. The reminder travels 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 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.
|
||||
|
||||
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,7 +91,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
|
||||
<details>
|
||||
<summary>共享执行与平台职责</summary>
|
||||
|
||||
实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仅在仍有输入按住时添加 system reminder;正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。程序失败、取消、断连、环境重置和销毁会停止所属输入派发,并等待反序释放。清理失败会禁用该任务后续 CUA 操作并报告结果不确定。提供方卸载前保留监听器,直到程序和原生连接排空。能力方法列表保持静态。Windows 在 helper 实现报告和清理前不设置 `heldInputState`,不会收到新命令。
|
||||
实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。DSH 回合中成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;正常程序结束和回合结束均保持输入。没有 DSH 回合的程序,包括 MCP,在返回前等待释放,并只报告 helper 已确认释放的输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。程序失败、取消、断连、环境重置和销毁会停止所属输入派发,并等待反序释放。清理失败会禁用该任务后续 CUA 操作并报告结果不确定。提供方卸载前保留监听器,直到程序和原生连接排空。能力方法列表保持静态。Windows 在 helper 实现报告和清理前不设置 `heldInputState`,不会收到新命令。
|
||||
|
||||
[授权存储](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.
|
||||
|
||||
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 keys and mouse buttons still held, with their targets and input modes. No reminder is added when none remain. 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.
|
||||
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.
|
||||
|
||||
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,18 +12,29 @@ 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'): 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).`)
|
||||
return ['<system-reminder>', state === 'held' ? 'CUA inputs are still held:' : 'CUA inputs were automatically released at program end:', ...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."
|
||||
: 'These inputs are no longer held. In this environment, keep any required hold sequence within one program.',
|
||||
'</system-reminder>'].join('\n')
|
||||
}
|
||||
|
||||
class InputOwner {
|
||||
readonly controller = new AbortController()
|
||||
private client: NativeClient | undefined
|
||||
private removeCleanup: (() => void) | undefined
|
||||
closing: Promise<void> | undefined
|
||||
closing: Promise<z.infer<typeof heldInputs>> | undefined
|
||||
|
||||
constructor(readonly agent: Agent, private readonly failed: (error: unknown) => void) {}
|
||||
|
||||
track(client: NativeClient): void {
|
||||
this.controller.signal.throwIfAborted()
|
||||
if (this.client) return
|
||||
this.removeCleanup = client.registerCleanup(canRequest => this.close(canRequest))
|
||||
this.removeCleanup = client.registerCleanup(async (canRequest) => { await this.close(canRequest) })
|
||||
this.client = client
|
||||
}
|
||||
|
||||
@@ -36,21 +47,21 @@ class InputOwner {
|
||||
this.client = undefined
|
||||
return
|
||||
}
|
||||
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).`)
|
||||
return ['<system-reminder>', 'CUA inputs are still held:', ...rows,
|
||||
"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.",
|
||||
'</system-reminder>'].join('\n')
|
||||
return renderInputs(inputs, 'held')
|
||||
}
|
||||
|
||||
close(canRequest = true): Promise<void> {
|
||||
async releaseReminder(): Promise<string | undefined> {
|
||||
const released = await this.close()
|
||||
return released.length > 0 ? renderInputs(released, 'released') : undefined
|
||||
}
|
||||
|
||||
close(canRequest = true): Promise<z.infer<typeof heldInputs>> {
|
||||
this.controller.abort()
|
||||
return this.closing ??= Promise.resolve().then(async () => {
|
||||
try {
|
||||
if (!this.client) return
|
||||
if (!this.client) return []
|
||||
if (!canRequest) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'Native connection closed before held-input cleanup was confirmed. Inspect the desktop manually before starting a new task')
|
||||
await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id })
|
||||
return heldInputs.parse(await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id }))
|
||||
} catch (error) {
|
||||
this.failed(error)
|
||||
throw error
|
||||
@@ -127,10 +138,12 @@ export class CuaHeldInputs {
|
||||
catch (error) { throw new NativeError('INPUT_CLEANUP_UNCONFIRMED',
|
||||
`${result.isError ? result.error.message : 'Program cancelled'}. Held-input cleanup failed: ${String(error)}`, { cause: error }) }
|
||||
} else if (execution.parent === undefined) {
|
||||
const text = await this.owners.get(agent)?.reminder()
|
||||
const owner = this.owners.get(agent)
|
||||
const inTurn = ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null
|
||||
const text = inTurn ? await owner?.reminder() : await owner?.releaseReminder()
|
||||
if (text) return { ...result, additionalContexts: [...result.additionalContexts ?? [],
|
||||
createUserMessage({ content: [{ type: 'text', text }],
|
||||
source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }),
|
||||
source: { kind: 'cua-held-inputs', form: 'notice', summary: inTurn ? 'CUA inputs remain held' : 'CUA inputs released' } }),
|
||||
] }
|
||||
}
|
||||
return result
|
||||
|
||||
@@ -182,7 +182,8 @@ export interface CuaSurface {
|
||||
pressKey(key: string, modifiers?: string[]): Promise<CuaActionResult>
|
||||
/**
|
||||
* Send one key-down or key-up event at the current input focus.
|
||||
* Explicit downs persist across programs and turns. Successful programs disclose remaining holds in a system reminder.
|
||||
* 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.
|
||||
* 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.
|
||||
|
||||
@@ -31,6 +31,7 @@ export function createNativeFixture(selectorPid) {
|
||||
? { kind: 'key', key: press.key, appHandle: press.appHandle, mode: 'application' }
|
||||
: { kind: 'mouse', button: press.key, appHandle: press.appHandle, windowId: press.windowId, mode: press.mode })
|
||||
if (method === 'releaseHeldInputs') {
|
||||
const released = dispatch('getHeldInputs', params).reverse()
|
||||
for (let index = held.length - 1; index >= 0; index--) {
|
||||
const press = held[index]
|
||||
if (press.connection === connection && press.taskId === params.taskId) {
|
||||
@@ -38,7 +39,7 @@ export function createNativeFixture(selectorPid) {
|
||||
held.splice(index, 1)
|
||||
}
|
||||
}
|
||||
return { dispatched: true }
|
||||
return released
|
||||
}
|
||||
if (method === 'getCapabilities') return { sessionLocked: false, permissions: { accessibility: true, screenRecording: true } }
|
||||
if (method === 'listApps') return [{ id: 'test.fixture', name: 'Fixture', isRunning: true, pid: selectorPid ?? 4 }]
|
||||
|
||||
Reference in new issue
Block a user