forked from cflmy/deepseek-harness
Scope native CUA input holds to the issuing connection
This commit is contained in:
1 parent
ad535742cb
commit
b39c243f4d
49 files changed
+230
-302
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: fd10784f6cea2da6
|
||||
zh: f31891b0179334f8
|
||||
en: c6def9831c503e1f
|
||||
zh: c4c2ac5cca9f0e07
|
||||
@@ -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 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 and Windows both implement this lifecycle. Custom helpers must support the matching task-scoped query and release operations. 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. Each Agent owns an input connection, and the helper tracks holds by that 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 and Windows both implement this lifecycle. Custom helpers must support the matching connection-scoped query and release operations. 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 和 MCP 程序成功结束时报告剩余持有输入,不自动释放。客户端在两次 MCP 调用之间暂停时不会通知服务端,输入可能继续按住;原生所有权仍支持显式释放和连接清理。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 和 Windows 都实现了这套生命周期。自定义 helper 必须支持对应的任务级状态查询和释放操作。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
|
||||
键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。每个 Agent 使用独立的输入连接,helper 按连接记录持有输入。DSH 和 MCP 程序成功结束时报告剩余持有输入,不自动释放。客户端在两次 MCP 调用之间暂停时不会通知服务端,输入可能继续按住;原生所有权仍支持显式释放和连接清理。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 和 Windows 都实现了这套生命周期。自定义 helper 必须支持按连接查询和释放持有输入。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
|
||||
|
||||
Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。
|
||||
@@ -12,5 +12,5 @@
|
||||
en: cf9c1397e07dffa5
|
||||
zh: f1cce9fadf321d43
|
||||
/cua-reports-held-input-after-programs/migration:
|
||||
en: 1bd7668cac0efe0d
|
||||
zh: 2122c9d5135283f7
|
||||
en: c26899347e7a24c9
|
||||
zh: ae78a24c58d6f80f
|
||||
@@ -13,5 +13,5 @@ On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')`
|
||||
## Migration
|
||||
|
||||
1. Pair explicit downs with ups when input should stop. Read the reminder before continuing; no reminder is added when no input remains held.
|
||||
2. Upgrade the platform package and helper together. A custom `helperPath` must implement the task-owned `getHeldInputs` and `releaseHeldInputs` private operations.
|
||||
2. Upgrade the platform package and helper together. A custom `helperPath` must accept `getHeldInputs({})` and `releaseHeldInputs({})` on the same connection that dispatched the input.
|
||||
3. Verify that one successful program can hold a key, receive its reminder, and release it in a later program. When a program fails or is cancelled during execution, it waits for cleanup. If the program succeeds but a post-execute policy rejects the output, the tool returns the policy error and CUA finishes cleanup independently. If the model is thinking when DSH stops or fails, the Agent can finish before native release is confirmed. Subsequent CUA calls wait for the outcome. If cleanup cannot be confirmed, CUA disables further operations for that task; inspect the desktop manually before starting another task.
|
||||
@@ -13,5 +13,5 @@ macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨
|
||||
## 迁移
|
||||
|
||||
1. 输入不再需要保持时,将显式 down 与 up 配对。继续操作前阅读提醒;没有持有输入时不添加提醒。
|
||||
2. 同步升级平台包和 helper。自定义 `helperPath` 必须实现按任务区分的 `getHeldInputs` 和 `releaseHeldInputs` 私有操作。
|
||||
2. 同步升级平台包和 helper。自定义 `helperPath` 必须在派发输入的同一条连接上接受 `getHeldInputs({})` 和 `releaseHeldInputs({})`。
|
||||
3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序执行中失败或取消时,会等待自身的清理。如果程序执行成功,但后置策略拒绝结果,工具返回策略错误,CUA 单独等待原生释放确认。模型思考期间停止或报错,Agent 可以先结束,原生释放随后确认。后续 CUA 调用会等待清理结果。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 4764629c9d31b705
|
||||
zh: 107fa3b77bce0734
|
||||
/deepseek-ai-dsh-cua-macos/understand-the-implementation:
|
||||
en: ee655e273363bb7b
|
||||
zh: 7c2d60b4a6f7343f
|
||||
en: 812aa05e9fc15883
|
||||
zh: bacb60868d67bd1d
|
||||
/deepseek-ai-dsh-cua-macos/further-exploration:
|
||||
en: ff9fac614001a98f
|
||||
zh: 329678941154aaea
|
||||
|
||||
@@ -155,7 +155,7 @@ Element clicks use opaque element IDs from the current snapshot. Left clicks sup
|
||||
<a id="understand-the-implementation"></a>
|
||||
## Understand the implementation
|
||||
|
||||
The shared helper's `HeldInputs` records task, connection, process generation, application/window and actual input route before dispatch. One lock orders posts, state queries and releases. Program middleware queries native state after successful execution and defers a logged reminder to the outer tool result. Failure and cancellation close input admission and await `releaseHeldInputs` using an independent bounded request. Native connection shutdown cancels and joins in-flight work before fallback release. A killed host relies on that disconnect path; host callbacks cannot be guaranteed.
|
||||
The shared helper's `HeldInputs` records connection, process generation, application/window and actual input route before dispatch. One lock orders posts, state queries and releases. Program middleware queries native state after successful execution and defers a logged reminder to the outer tool result. Failure and cancellation close input admission and await `releaseHeldInputs` using an independent bounded request. Native connection shutdown cancels and joins in-flight work before fallback release. A killed host relies on that disconnect path; host callbacks cannot be guaranteed.
|
||||
|
||||
<details>
|
||||
<summary>Dispatch and resource ownership</summary>
|
||||
|
||||
@@ -155,7 +155,7 @@ AppKit 的 sheet 可以出现在文档窗口的树里,并有独立的窗口 ID
|
||||
<a id="understand-the-implementation"></a>
|
||||
## 理解实现
|
||||
|
||||
共享 helper 的 `HeldInputs` 在派发前记录任务、连接、进程代次、应用或窗口和实际输入方式。同一把锁维护派发、状态查询和释放。程序中间件在成功执行后查询原生状态,并把已记录的提醒附加到外层工具结果。失败和取消会关闭输入准入,通过独立且有超时限制的请求等待 `releaseHeldInputs`。原生连接关闭会先取消并等待在途操作,再做兜底释放。宿主被强杀时依赖断连清理,无法保证宿主回调执行。
|
||||
共享 helper 的 `HeldInputs` 在派发前记录连接、进程代次、应用或窗口和实际输入方式。同一把锁维护派发、状态查询和释放。程序中间件在成功执行后查询原生状态,并把已记录的提醒附加到外层工具结果。失败和取消会关闭输入准入,通过独立且有超时限制的请求等待 `releaseHeldInputs`。原生连接关闭会先取消并等待在途操作,再做兜底释放。宿主被强杀时依赖断连清理,无法保证宿主回调执行。
|
||||
|
||||
<details>
|
||||
<summary>操作分派与资源归属</summary>
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: da316afc1edbe50e
|
||||
zh: a150c1dacc689f4b
|
||||
/dsh-cua-native-helper/observation-and-input:
|
||||
en: fdbabf0b85e16486
|
||||
zh: 62c598d8b330ffdf
|
||||
en: d52f2d056703e787
|
||||
zh: 70993f7d024d831d
|
||||
/dsh-cua-native-helper/verification:
|
||||
en: 40bb7339f914bb9a
|
||||
zh: 272a3aae64f55d87
|
||||
|
||||
@@ -114,7 +114,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. `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.
|
||||
`HeldInputs` records the requesting connection, 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’s holds, 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.
|
||||
|
||||
|
||||
@@ -114,7 +114,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` 按派发顺序的反序统一释放键盘和鼠标记录。正常程序结束和回合结束不释放输入。`releaseHeldInputs` 返回已派发 up 的记录,用于确认后的清理提醒。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。
|
||||
`HeldInputs` 在派发前记录请求所属的连接、应用、原进程身份、键码或按钮、释放事件和实际输入方式。重复按键只保留一条记录。显式 up 使用保存的目标和输入方式;进程退出或 PID 身份变化后跳过定向释放。`getHeldInputs` 只报告当前连接的记录,不读取用户物理按键状态。成功结束的程序用该快照生成提醒。程序失败、取消或销毁时,`releaseHeldInputs` 按派发顺序的反序统一释放键盘和鼠标记录。正常程序结束和回合结束不释放输入。`releaseHeldInputs` 返回已派发 up 的记录,用于确认后的清理提醒。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。
|
||||
|
||||
所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。
|
||||
|
||||
|
||||
@@ -218,7 +218,7 @@ actor AXWorker {
|
||||
var recovery = AXChildRecoveryBudget(maxElements: NativeProtocol.elementRange.upperBound, timeout: axTimeout)
|
||||
if method == "sendKeyEvent", try params.string("direction") == "up" {
|
||||
let handle = try params.string("appHandle")
|
||||
let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, task: params.string("taskId"), useSystemInput: params.optionalBoolean("useSystemInput") ?? false) {
|
||||
let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, useSystemInput: params.optionalBoolean("useSystemInput") ?? false) {
|
||||
try NativePlatform.requireUnlocked(observeSession())
|
||||
try NativePlatform.requireAccessibility()
|
||||
return try ax().keyboardRecipient(validateIdentity(handle), catalog: catalog, budget: &recovery)
|
||||
@@ -361,7 +361,7 @@ actor AXWorker {
|
||||
maxElements: try params.integer("maxElements", in: NativeProtocol.elementRange), maxDepth: try params.integer("maxDepth", in: NativeProtocol.depthRange)))
|
||||
case "sendKeyEvent":
|
||||
let system = try params.optionalBoolean("useSystemInput") ?? false
|
||||
try inputs().0.keyDown(params.string("key"), app: handle, task: params.string("taskId"), useSystemInput: system) {
|
||||
try inputs().0.keyDown(params.string("key"), app: handle, useSystemInput: system) {
|
||||
if system { return identity }
|
||||
return try ax().keyboardRecipient(identity, catalog: catalog, budget: &recovery)
|
||||
}
|
||||
@@ -395,7 +395,7 @@ actor AXWorker {
|
||||
if try params.optionalBoolean("useSystemInput") == true {
|
||||
return .systemButtonDown(route, try WindowPointerInput.button(params.string("mouseButton")))
|
||||
}
|
||||
try await inputs().1.mouseDown(owner: .init(connection: connectionID, task: params.string("taskId"), app: handle),
|
||||
try await inputs().1.mouseDown(owner: .init(connection: connectionID, app: handle),
|
||||
in: route, button: params.string("mouseButton"))
|
||||
case "click", "mouseMove":
|
||||
let useSystemInput = try params.optionalBoolean("useSystemInput") ?? false
|
||||
|
||||
@@ -6,7 +6,6 @@ import Foundation
|
||||
final class HeldInputs: @unchecked Sendable {
|
||||
struct Owner: Equatable {
|
||||
let connection: UUID
|
||||
let task: String
|
||||
let app: String
|
||||
}
|
||||
enum Mode: Equatable {
|
||||
@@ -42,10 +41,7 @@ final class HeldInputs: @unchecked Sendable {
|
||||
}
|
||||
|
||||
private func conflict(_ name: String, holder: Owner, caller: Owner) -> NativeFailure {
|
||||
let source: String
|
||||
if holder.connection != caller.connection { source = "another session" }
|
||||
else if holder.task != caller.task { source = "another task" }
|
||||
else { source = "a different application handle" }
|
||||
let source = holder.connection != caller.connection ? "another session" : "a different application handle"
|
||||
return RequestParameters.invalid("Key '\(name)' is held for this target by \(source). No event was sent. Wait for the holder to release it before using it.")
|
||||
}
|
||||
|
||||
@@ -152,14 +148,14 @@ final class HeldInputs: @unchecked Sendable {
|
||||
func pointerUp(owner: Owner, window: UInt32, button: CGMouseButton) throws -> Bool {
|
||||
try lock.withLock {
|
||||
guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.mode.pointer == button && $0.mode.window == window }) else {
|
||||
throw RequestParameters.invalid("Release the mouse button through the same task, application and window that pressed it")
|
||||
throw RequestParameters.invalid("Release the mouse button through the same connection, application and window that pressed it")
|
||||
}
|
||||
return try release(at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// Create and post movement under the same lock as ownership and the saved release point.
|
||||
func moveSystem(owner: Owner?, route: WindowRoute, screen: CGPoint, checkCancellation: () throws -> Void) throws {
|
||||
func moveSystem(owner: Owner, route: WindowRoute, screen: CGPoint, checkCancellation: () throws -> Void) throws {
|
||||
try lock.withLock {
|
||||
let press = pressed.first { if case .systemPointer = $0.mode { return true }; return false }
|
||||
let event: CGEvent
|
||||
@@ -198,32 +194,31 @@ final class HeldInputs: @unchecked Sendable {
|
||||
}
|
||||
|
||||
/// Only the caller's registered input is disclosed; physical user input is never inferred.
|
||||
func held(connection: UUID, task: String) throws -> JSONValue {
|
||||
func held(connection: UUID) throws -> JSONValue {
|
||||
try lock.withLock {
|
||||
for index in pressed.indices.reversed() {
|
||||
let press = pressed[index]
|
||||
guard press.owner.connection == connection, press.owner.task == task else { continue }
|
||||
guard press.owner.connection == connection else { continue }
|
||||
if press.mode.isSystem { continue }
|
||||
do { try NativePlatform.verify(press.recipient) }
|
||||
catch let error as NativeFailure where error.code == "STALE_APP" || error.code == "APP_UNAVAILABLE" {
|
||||
pressed.remove(at: index)
|
||||
}
|
||||
}
|
||||
return .array(pressed.filter { $0.owner.connection == connection && $0.owner.task == task }.map { press in
|
||||
return .array(pressed.filter { $0.owner.connection == connection }.map { press in
|
||||
record(press)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func release(connection: UUID, task: String? = nil) throws -> [JSONValue] {
|
||||
func release(connection: UUID) throws -> [JSONValue] {
|
||||
try lock.withLock {
|
||||
var failures: [String] = []
|
||||
var released: [JSONValue] = []
|
||||
for index in pressed.indices.reversed() {
|
||||
let press = pressed[index]
|
||||
let owner = press.owner
|
||||
guard owner.connection == connection, task == nil || owner.task == task else { continue }
|
||||
guard press.owner.connection == connection else { continue }
|
||||
do { if try release(at: index) { released.append(record(press)) } }
|
||||
catch { failures.append(String(describing: error)) }
|
||||
}
|
||||
|
||||
@@ -30,8 +30,8 @@ final class KeyboardInput {
|
||||
else { postProcess(event, pid) }
|
||||
}
|
||||
|
||||
func keyDown(_ name: String, app: String, task: String, useSystemInput: Bool = false, recipient: () throws -> ProcessIdentity) throws {
|
||||
let owner = HeldInputs.Owner(connection: connection, task: task, app: app)
|
||||
func keyDown(_ name: String, app: String, useSystemInput: Bool = false, recipient: () throws -> ProcessIdentity) throws {
|
||||
let owner = HeldInputs.Owner(connection: connection, app: app)
|
||||
let code = try Self.keyCode(name)
|
||||
let source = try Self.source(system: useSystemInput)
|
||||
let down = try Self.keyEvent(source: source, code: code, down: true, flags: [])
|
||||
@@ -49,8 +49,8 @@ final class KeyboardInput {
|
||||
})
|
||||
}
|
||||
|
||||
func keyUp(_ name: String, app: String, task: String, useSystemInput: Bool = false, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool {
|
||||
try held.keyUp(owner: .init(connection: connection, task: task, app: app), name: name, code: Self.keyCode(name), system: useSystemInput,
|
||||
func keyUp(_ name: String, app: String, useSystemInput: Bool = false, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool {
|
||||
try held.keyUp(owner: .init(connection: connection, app: app), name: name, code: Self.keyCode(name), system: useSystemInput,
|
||||
recipientIfUnheld: recipientIfUnheld)
|
||||
}
|
||||
|
||||
|
||||
+5
-5
@@ -12,29 +12,29 @@ enum NativeProtocol {
|
||||
"getActionSchema": ["action"],
|
||||
"getApp": ["selector"],
|
||||
"getCapabilities": [],
|
||||
"getHeldInputs": ["taskId"],
|
||||
"getHeldInputs": [],
|
||||
"getState": ["appHandle", "details", "includeMenus", "maxDepth", "maxElements", "windowId"],
|
||||
"invoke": ["appHandle", "elementId", "snapshotId", "windowId"],
|
||||
"launchApp": ["appHandle"],
|
||||
"listActions": ["appHandle", "elementId", "snapshotId", "windowId"],
|
||||
"listApps": [],
|
||||
"listWindows": ["appHandle"],
|
||||
"mouseMove": ["appHandle", "elementId", "snapshotId", "taskId", "useSystemInput", "windowId", "x", "y"],
|
||||
"mouseMove": ["appHandle", "elementId", "snapshotId", "useSystemInput", "windowId", "x", "y"],
|
||||
"openPermissionSettings": ["permission", "settingsMessage"],
|
||||
"paste": ["appHandle", "format", "maxClipboardBytes", "maxDepth", "maxElements", "pasteReadTimeoutMs", "text", "windowId"],
|
||||
"performAction": ["action", "appHandle", "argument", "elementId", "snapshotId", "windowId"],
|
||||
"permissionStatus": [],
|
||||
"pressKey": ["appHandle", "key", "modifiers", "useSystemInput", "windowId"],
|
||||
"releaseHeldInputs": ["taskId"],
|
||||
"releaseHeldInputs": [],
|
||||
"requestPermission": ["backLabel", "finderLabel", "instruction", "permission", "pollIntervalMs", "settingsMessage", "unavailableMessage"],
|
||||
"screenshot": ["appHandle", "windowId"],
|
||||
"scroll": ["appHandle", "deltaLinesX", "deltaLinesY", "snapshotId", "windowId", "x", "y"],
|
||||
"selectText": ["appHandle", "elementId", "prefix", "selectionType", "snapshotId", "suffix", "text", "windowId"],
|
||||
"sendKeyEvent": ["appHandle", "direction", "key", "taskId", "useSystemInput", "windowId"],
|
||||
"sendKeyEvent": ["appHandle", "direction", "key", "useSystemInput", "windowId"],
|
||||
"setValue": ["appHandle", "elementId", "snapshotId", "value", "windowId"],
|
||||
"show": ["appHandle", "windowId"],
|
||||
"takeWindowActivity": ["appHandle", "observations"],
|
||||
"toggleMouse": ["appHandle", "direction", "mouseButton", "taskId", "useSystemInput", "windowId"],
|
||||
"toggleMouse": ["appHandle", "direction", "mouseButton", "useSystemInput", "windowId"],
|
||||
"typeText": ["appHandle", "text", "windowId"],
|
||||
]
|
||||
static let stringEnums: [String: [String: Set<String>]] = [
|
||||
|
||||
@@ -190,10 +190,10 @@ import Darwin
|
||||
let params = try RequestParameters(request)
|
||||
try cancellation.check()
|
||||
if request.method == "getHeldInputs" {
|
||||
return try scheduler.heldInputs.held(connection: connectionID, task: params.string("taskId"))
|
||||
return try scheduler.heldInputs.held(connection: connectionID)
|
||||
}
|
||||
if request.method == "releaseHeldInputs" {
|
||||
return .array(try scheduler.heldInputs.release(connection: connectionID, task: params.string("taskId")))
|
||||
return .array(try scheduler.heldInputs.release(connection: connectionID))
|
||||
}
|
||||
if request.method == "screenshot" { try capture.requireAvailable() }
|
||||
// A dispatched action can invalidate the snapshot that identifies its window.
|
||||
@@ -218,7 +218,7 @@ import Darwin
|
||||
let catalog = requiresCatalog ? ApplicationCatalog.snapshot() : ApplicationCatalogSnapshot(applications: [], frontPID: nil)
|
||||
let result: JSONValue
|
||||
if request.method == "toggleMouse", try params.string("direction") == "up" {
|
||||
let dispatched = try scheduler.heldInputs.pointerUp(owner: .init(connection: connectionID, task: params.string("taskId"),
|
||||
let dispatched = try scheduler.heldInputs.pointerUp(owner: .init(connection: connectionID,
|
||||
app: params.string("appHandle")), window: params.windowID(), button: WindowPointerInput.button(params.string("mouseButton")))
|
||||
return .object(["dispatched": .bool(dispatched)])
|
||||
}
|
||||
@@ -267,12 +267,11 @@ import Darwin
|
||||
case .foreground(let plan): result = try await performForeground(plan, requestID: request.id)
|
||||
case .mouseMove(let route, let point):
|
||||
let latch = cancellation
|
||||
let owner: HeldInputs.Owner? = try params.contains("taskId")
|
||||
? .init(connection: connectionID, task: params.string("taskId"), app: params.string("appHandle")) : nil
|
||||
let owner = HeldInputs.Owner(connection: connectionID, app: try params.string("appHandle"))
|
||||
try scheduler.systemPointer.move(owner: owner, in: route, at: point, checkCancellation: { try latch.check() })
|
||||
result = AXWorker.mouseMoveResult(route: "system-pointer", pointerMoved: true)
|
||||
case .systemButtonDown(let route, let button):
|
||||
try scheduler.systemPointer.down(owner: .init(connection: connectionID, task: params.string("taskId"), app: params.string("appHandle")), in: route, button: button,
|
||||
try scheduler.systemPointer.down(owner: .init(connection: connectionID, app: params.string("appHandle")), in: route, button: button,
|
||||
checkCancellation: { try cancellation.check() })
|
||||
result = AXWorker.actionResult
|
||||
case .paste(let plan):
|
||||
|
||||
@@ -38,7 +38,7 @@ import Foundation
|
||||
try held.pointerDown(owner: owner, route: route, button: button, system: true, down: down, up: up, post: Self.post)
|
||||
}
|
||||
|
||||
func move(owner: HeldInputs.Owner?, in route: WindowRoute, at point: WindowPoint, checkCancellation: () throws -> Void) throws {
|
||||
func move(owner: HeldInputs.Owner, in route: WindowRoute, at point: WindowPoint, checkCancellation: () throws -> Void) throws {
|
||||
try WindowPointerInput.validate(point, in: route)
|
||||
try WindowPointerInput.validateWindow(route)
|
||||
let screen = WindowPointerInput.screenPoint(point, in: route)
|
||||
|
||||
@@ -15,22 +15,18 @@ export function renderNativeProtocol(): { json: string; swift: string } {
|
||||
maxElements: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxElements),
|
||||
maxDepth: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxDepth),
|
||||
}
|
||||
const owner = { taskId: z.string().min(1) }
|
||||
const systemInput = { useSystemInput: z.boolean().optional() }
|
||||
const { fields, enums, json } = nativeProtocol({
|
||||
getState: NativeResourceParameters.getState.extend(traversal),
|
||||
paste: NativeResourceParameters.paste.extend(traversal),
|
||||
sendKeyEvent: z.object({ ...owner, ...systemInput }),
|
||||
sendKeyEvent: z.object(systemInput),
|
||||
pressKey: z.object(systemInput),
|
||||
click: z.object(systemInput),
|
||||
mouseMove: z.object({ ...systemInput, taskId: owner.taskId.optional() }),
|
||||
toggleMouse: z.object({ ...systemInput, ...owner }),
|
||||
mouseMove: z.object(systemInput),
|
||||
toggleMouse: z.object(systemInput),
|
||||
drag: NativeResourceParameters.drag.extend(systemInput),
|
||||
requestPermission: PermissionGuideParameters, openPermissionSettings: PermissionSettingsParameters,
|
||||
}, [
|
||||
...['getHeldInputs', 'releaseHeldInputs'].map(method => z.object({
|
||||
method: z.literal(method), params: z.object(owner).strict(),
|
||||
}).strict()),
|
||||
z.object({ method: z.literal('takeWindowActivity'), params: z.object({ appHandle: z.string(),
|
||||
observations: z.record(z.string(), z.string().regex(/^[0-9]{1,20}$/)) }).strict() }).strict(),
|
||||
z.object({ method: z.literal('clearWindowActivity'), params: z.object({}).strict() }).strict(),
|
||||
|
||||
@@ -520,18 +520,13 @@
|
||||
},
|
||||
"useSystemInput": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"appHandle",
|
||||
"windowId",
|
||||
"mouseButton",
|
||||
"direction",
|
||||
"taskId"
|
||||
"direction"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -577,10 +572,6 @@
|
||||
},
|
||||
"useSystemInput": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -615,10 +606,6 @@
|
||||
},
|
||||
"useSystemInput": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -1150,10 +1137,6 @@
|
||||
"up"
|
||||
]
|
||||
},
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"useSystemInput": {
|
||||
"type": "boolean"
|
||||
}
|
||||
@@ -1161,8 +1144,7 @@
|
||||
"required": [
|
||||
"appHandle",
|
||||
"key",
|
||||
"direction",
|
||||
"taskId"
|
||||
"direction"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -1575,15 +1557,7 @@
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"taskId"
|
||||
],
|
||||
"properties": {},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
@@ -1606,15 +1580,7 @@
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"taskId"
|
||||
],
|
||||
"properties": {},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
|
||||
@@ -392,7 +392,7 @@ def check_system_input(helper, owner, state_file, executable):
|
||||
events = wait_for_state(state_file, lambda value: any(event["type"] == 11 for event in value["events"][count:]))["events"][count:]
|
||||
assert [(event["type"], event.get("keyCode")) for event in events] == [(10, 2), (11, 2)], events
|
||||
assert all(event["shift"] for event in events) and not any(keys().values()), events
|
||||
held = {**owner, "key": "w", "taskId": "system-input-e2e", "useSystemInput": True}
|
||||
held = {**owner, "key": "w", "useSystemInput": True}
|
||||
for cleanup in (False, True):
|
||||
count = len(json.loads(state_file.read_text())["events"])
|
||||
call("sendKeyEvent", {**held, "direction": "down"})
|
||||
@@ -403,7 +403,7 @@ def check_system_input(helper, owner, state_file, executable):
|
||||
assert down["systemW"], down
|
||||
finally:
|
||||
if cleanup:
|
||||
call("releaseHeldInputs", {"taskId": held["taskId"]})
|
||||
call("releaseHeldInputs", {})
|
||||
else:
|
||||
call("sendKeyEvent", {**held, "direction": "up"})
|
||||
state = wait_for_state(state_file, lambda value: any(
|
||||
|
||||
@@ -109,8 +109,6 @@ class NativeHelper:
|
||||
self.transcript = transcript
|
||||
|
||||
def call(self, method, params, error_code=None):
|
||||
if method in ("sendKeyEvent", "toggleMouse", "getHeldInputs", "releaseHeldInputs") or (method == "mouseMove" and params.get("useSystemInput")):
|
||||
params = {**params, "taskId": "native-fixture"}
|
||||
self.sequence += 1
|
||||
request = {"id": str(self.sequence), "method": method, "params": params}
|
||||
self.process.stdin.write(json.dumps(request) + "\n")
|
||||
|
||||
@@ -55,8 +55,6 @@ class Connection:
|
||||
return value
|
||||
|
||||
def call(self, method, params, error=None):
|
||||
if method in ("sendKeyEvent", "toggleMouse", "getHeldInputs", "releaseHeldInputs") or (method == "mouseMove" and params.get("useSystemInput")):
|
||||
params = {**params, "taskId": "native-fixture"}
|
||||
self.sequence += 1
|
||||
identifier = str(self.sequence)
|
||||
self.send({"id": identifier, "method": method, "params": params})
|
||||
@@ -301,6 +299,12 @@ def main():
|
||||
assert b.call("listWindows", {"appHandle": app_b})
|
||||
timed.close()
|
||||
clients.remove(timed)
|
||||
a.call("sendKeyEvent", {"appHandle": app_a, "key": "w", "direction": "down"})
|
||||
assert b.call("getHeldInputs", {}) == []
|
||||
b.call("sendKeyEvent", {"appHandle": app_b, "key": "w", "direction": "up"}, error="INVALID_ARGUMENT")
|
||||
assert b.call("releaseHeldInputs", {}) == []
|
||||
assert [entry["key"] for entry in a.call("getHeldInputs", {})] == ["w"]
|
||||
b.call("sendKeyEvent", {"appHandle": app_b, "key": "d", "direction": "down"})
|
||||
a.close()
|
||||
clients.remove(a)
|
||||
b.call("protocol-still-open", {}, error="UNSUPPORTED")
|
||||
@@ -308,6 +312,9 @@ def main():
|
||||
if not args.without_desktop:
|
||||
assert b.call("listWindows", {"appHandle": app_b})
|
||||
capture((b, app_b))
|
||||
assert [entry["key"] for entry in b.call("getHeldInputs", {})] == ["d"]
|
||||
b.call("sendKeyEvent", {"appHandle": app_b, "key": "w", "direction": "down"})
|
||||
assert [entry["key"] for entry in b.call("releaseHeldInputs", {})] == ["w", "d"]
|
||||
b.close()
|
||||
clients.remove(b)
|
||||
if not args.without_desktop:
|
||||
|
||||
@@ -5,7 +5,6 @@ import Foundation
|
||||
import Testing
|
||||
@testable import CuaNative
|
||||
|
||||
private let task = "task"
|
||||
|
||||
private func pointer(_ type: CGEventType) throws -> CGEvent {
|
||||
let event = try #require(CGEvent(mouseEventSource: nil, mouseType: type, mouseCursorPosition: .zero, mouseButton: .left))
|
||||
@@ -18,7 +17,7 @@ func mixedInputsReleaseInDispatchOrder(_ system: Bool, _ systemKey: Bool) throws
|
||||
let held = HeldInputs()
|
||||
let connection = UUID()
|
||||
let target = try NativePlatform.identity(getpid())
|
||||
let owner = HeldInputs.Owner(connection: connection, task: task, app: "editor")
|
||||
let owner = HeldInputs.Owner(connection: connection, app: "editor")
|
||||
let route = WindowRoute(owner: target, windowID: 7, bounds: .init(x: 0, y: 0, width: 100, height: 100))
|
||||
var events: [String] = []
|
||||
let keyboard = SystemKeyboardInput(post: { event in
|
||||
@@ -28,20 +27,20 @@ func mixedInputsReleaseInDispatchOrder(_ system: Bool, _ systemKey: Bool) throws
|
||||
#expect(pid == target.pid)
|
||||
events.append("key:\(event.getIntegerValueField(.keyboardEventKeycode)):\(event.type.rawValue)")
|
||||
}, textEventInterval: 0, held: held, connection: connection, system: keyboard)
|
||||
try input.keyDown("shift", app: "editor", task: task, recipient: { target })
|
||||
try input.keyDown("shift", app: "editor", recipient: { target })
|
||||
try held.pointerDown(owner: owner, route: route, button: .left, system: system,
|
||||
down: pointer(.leftMouseDown), up: pointer(.leftMouseUp), post: { events.append("mouse:\($0.type.rawValue)") })
|
||||
try input.keyDown("w", app: "editor", task: task, useSystemInput: systemKey, recipient: { target })
|
||||
let state = try held.held(connection: connection, task: task)
|
||||
try input.keyDown("w", app: "editor", useSystemInput: systemKey, recipient: { target })
|
||||
let state = try held.held(connection: connection)
|
||||
#expect(state == .array([
|
||||
.object(["kind": .string("key"), "key": .string("shift"), "appHandle": .string("editor"), "mode": .string("application")]),
|
||||
.object(["kind": .string("mouse"), "button": .string("left"), "appHandle": .string("editor"), "windowId": .string("7"), "mode": .string(system ? "system" : "window")]),
|
||||
.object(["kind": .string("key"), "key": .string("w"), "appHandle": .string("editor"), "mode": .string(systemKey ? "system" : "application")]),
|
||||
]))
|
||||
#expect(try held.held(connection: UUID(), task: task) == .array([]))
|
||||
try held.release(connection: connection, task: task)
|
||||
#expect(try held.held(connection: connection, task: task) == .array([]))
|
||||
try held.release(connection: connection, task: task)
|
||||
#expect(try held.held(connection: UUID()) == .array([]))
|
||||
try held.release(connection: connection)
|
||||
#expect(try held.held(connection: connection) == .array([]))
|
||||
try held.release(connection: connection)
|
||||
let wRoute = systemKey ? "hid" : "key"
|
||||
#expect(events == ["key:56:12", "mouse:1", "\(wRoute):13:10", "\(wRoute):13:11", "mouse:2", "key:56:12"])
|
||||
}
|
||||
@@ -53,35 +52,34 @@ func mixedInputsReleaseInDispatchOrder(_ system: Bool, _ systemKey: Bool) throws
|
||||
var events: [CGEvent] = []
|
||||
let input = KeyboardInput(post: { event, _ in events.append(event) }, textEventInterval: 0, held: held, connection: connection)
|
||||
func changedFocus() throws -> ProcessIdentity { throw RequestParameters.invalid("Unexpected focus lookup") }
|
||||
try input.keyDown("w", app: "editor", task: task, recipient: { target })
|
||||
try input.keyDown("w", app: "editor", task: task, recipient: changedFocus)
|
||||
#expect(try input.keyUp("w", app: "editor", task: task, recipientIfUnheld: changedFocus))
|
||||
try input.keyDown("d", app: "editor", task: task, recipient: { target })
|
||||
try input.keyDown("w", app: "editor", task: task, recipient: { target })
|
||||
try held.release(connection: connection, task: task)
|
||||
try input.keyDown("w", app: "editor", recipient: { target })
|
||||
try input.keyDown("w", app: "editor", recipient: changedFocus)
|
||||
#expect(try input.keyUp("w", app: "editor", recipientIfUnheld: changedFocus))
|
||||
try input.keyDown("d", app: "editor", recipient: { target })
|
||||
try input.keyDown("w", app: "editor", recipient: { target })
|
||||
try held.release(connection: connection)
|
||||
#expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [13, 13, 13, 2, 13, 13, 2])
|
||||
#expect(events.map(\.type) == [.keyDown, .keyDown, .keyUp, .keyDown, .keyDown, .keyUp, .keyUp])
|
||||
#expect(events.map { $0.getIntegerValueField(.keyboardEventAutorepeat) } == [0, 1, 0, 0, 0, 0, 0])
|
||||
}
|
||||
|
||||
@Test func connectionsAndTasksCannotReleaseEachOthersInput() throws {
|
||||
@Test func connectionsReleaseOnlyTheirOwnInput() throws {
|
||||
let held = HeldInputs()
|
||||
let a = UUID(), b = UUID()
|
||||
let target = try NativePlatform.identity(getpid())
|
||||
var events: [CGEventType] = []
|
||||
let input = KeyboardInput(post: { event, _ in events.append(event.type) }, textEventInterval: 0, held: held, connection: a)
|
||||
let peer = KeyboardInput(post: { _, _ in Issue.record("Foreign connection posted input") }, textEventInterval: 0, held: held, connection: b)
|
||||
try input.keyDown("w", app: "editor", task: task, recipient: { target })
|
||||
#expect(throws: NativeFailure.self) { try peer.keyDown("w", app: "editor", task: task, recipient: { target }) }
|
||||
#expect(throws: NativeFailure.self) { try peer.keyUp("w", app: "editor", task: task, recipientIfUnheld: { target }) }
|
||||
try held.release(connection: b)
|
||||
#expect(events == [.keyDown])
|
||||
try held.release(connection: a, task: task)
|
||||
try input.keyDown("w", app: "editor", task: "another-task", recipient: { target })
|
||||
try held.release(connection: a, task: task)
|
||||
#expect(events == [.keyDown, .keyUp, .keyDown])
|
||||
var eventsA: [CGEventType] = [], eventsB: [CGEventType] = []
|
||||
let input = KeyboardInput(post: { event, _ in eventsA.append(event.type) }, textEventInterval: 0, held: held, connection: a)
|
||||
let peer = KeyboardInput(post: { event, _ in eventsB.append(event.type) }, textEventInterval: 0, held: held, connection: b)
|
||||
try input.keyDown("w", app: "editor", recipient: { target })
|
||||
#expect(try held.held(connection: b) == .array([]))
|
||||
#expect(throws: NativeFailure.self) { try peer.keyDown("w", app: "editor", recipient: { target }) }
|
||||
#expect(throws: NativeFailure.self) { try peer.keyUp("w", app: "editor", recipientIfUnheld: { target }) }
|
||||
try peer.keyDown("d", app: "editor", recipient: { target })
|
||||
try held.release(connection: a)
|
||||
#expect(events == [.keyDown, .keyUp, .keyDown, .keyUp])
|
||||
#expect(eventsA == [.keyDown, .keyUp])
|
||||
#expect(eventsB == [.keyDown])
|
||||
#expect(try peer.keyUp("d", app: "editor", recipientIfUnheld: { target }))
|
||||
#expect(eventsB == [.keyDown, .keyUp])
|
||||
}
|
||||
|
||||
@Test(arguments: [false, true])
|
||||
@@ -90,7 +88,7 @@ func pointerReleaseUsesSavedRouteAfterWindowAndProcessChanges(_ system: Bool) th
|
||||
let target = try NativePlatform.identity(getpid())
|
||||
// The current PID with a different start identity models a reused process identifier.
|
||||
let stale = ProcessIdentity(pid: target.pid, startedSeconds: target.startedSeconds + 1, startedMicroseconds: target.startedMicroseconds)
|
||||
let owner = HeldInputs.Owner(connection: UUID(), task: task, app: "old-window")
|
||||
let owner = HeldInputs.Owner(connection: UUID(), app: "old-window")
|
||||
let route = WindowRoute(owner: stale, windowID: 987654, bounds: .init(x: 0, y: 0, width: 100, height: 100))
|
||||
var events: [CGEventType] = []
|
||||
try held.pointerDown(owner: owner, route: route, button: .left, system: system,
|
||||
@@ -104,7 +102,7 @@ func pointerReleaseUsesSavedRouteAfterWindowAndProcessChanges(_ system: Bool) th
|
||||
let held = HeldInputs()
|
||||
let target = try NativePlatform.identity(getpid())
|
||||
let route = WindowRoute(owner: target, windowID: 7, bounds: .init(x: 0, y: 0, width: 100, height: 100))
|
||||
let owner = HeldInputs.Owner(connection: UUID(), task: task, app: "editor")
|
||||
let owner = HeldInputs.Owner(connection: UUID(), app: "editor")
|
||||
try held.pointerDown(owner: owner, route: route, button: .left, system: false,
|
||||
down: pointer(.leftMouseDown), up: pointer(.leftMouseUp), post: { _ in })
|
||||
#expect(throws: NativeFailure.self) { try held.requirePointerAvailable(route: route, button: .left, system: false) }
|
||||
|
||||
@@ -71,14 +71,14 @@ import Testing
|
||||
let held = HeldInputs()
|
||||
let connection = UUID()
|
||||
let keyboard = KeyboardInput(post: { _, _ in Issue.record("System key used process delivery") }, textEventInterval: 0, held: held, connection: connection, system: system)
|
||||
try keyboard.keyDown("shift", app: "app", task: "task", useSystemInput: true, recipient: { target })
|
||||
#expect(throws: NativeFailure.self) { try keyboard.keyUp("shift", app: "app", task: "task", recipientIfUnheld: { target }) }
|
||||
try keyboard.keyDown("shift", app: "app", useSystemInput: true, recipient: { target })
|
||||
#expect(throws: NativeFailure.self) { try keyboard.keyUp("shift", app: "app", recipientIfUnheld: { target }) }
|
||||
foreground = 99
|
||||
#expect(try keyboard.keyUp("shift", app: "app", task: "task", useSystemInput: true, recipientIfUnheld: { target }))
|
||||
#expect(try keyboard.keyUp("shift", app: "app", useSystemInput: true, recipientIfUnheld: { target }))
|
||||
foreground = target.pid
|
||||
try keyboard.keyDown("w", app: "app", task: "task", useSystemInput: true, recipient: { target })
|
||||
try keyboard.keyDown("w", app: "app", useSystemInput: true, recipient: { target })
|
||||
foreground = 99
|
||||
try held.release(connection: connection, task: "task")
|
||||
try held.release(connection: connection)
|
||||
#expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [56, 56, 13, 13])
|
||||
}
|
||||
|
||||
@@ -97,12 +97,12 @@ import Testing
|
||||
var events: [CGEvent] = []
|
||||
let system = SystemKeyboardInput(post: { events.append($0) }, keyState: { _ in false }, currentFlags: { ambient }, foreground: { target.pid })
|
||||
let keyboard = KeyboardInput(post: { _, _ in Issue.record("System key used process delivery") }, textEventInterval: 0, held: held, connection: connection, system: system)
|
||||
try keyboard.keyDown("w", app: "app", task: "task", useSystemInput: true, recipient: { target })
|
||||
try keyboard.keyDown("w", app: "app", task: "task", useSystemInput: true, recipient: { target })
|
||||
#expect(try keyboard.keyUp("w", app: "app", task: "task", useSystemInput: true, recipientIfUnheld: { target }))
|
||||
try keyboard.keyDown("w", app: "app", useSystemInput: true, recipient: { target })
|
||||
try keyboard.keyDown("w", app: "app", useSystemInput: true, recipient: { target })
|
||||
#expect(try keyboard.keyUp("w", app: "app", useSystemInput: true, recipientIfUnheld: { target }))
|
||||
#expect(events.allSatisfy { $0.flags.contains(.maskAlternate) })
|
||||
try keyboard.keyDown("command", app: "app", task: "task", useSystemInput: true, recipient: { target })
|
||||
try keyboard.keyDown("command", app: "app", useSystemInput: true, recipient: { target })
|
||||
ambient.formUnion(.maskCommand)
|
||||
try held.release(connection: connection, task: "task")
|
||||
try held.release(connection: connection)
|
||||
#expect(events.last?.flags == .maskAlternate)
|
||||
}
|
||||
@@ -49,7 +49,7 @@ def check_input(executable, helper_path, root):
|
||||
("click", {**scoped, "x": 20, "y": 40}),
|
||||
("typeText", {**owner, "text": "a"}),
|
||||
("pressKey", {**owner, "key": "a"}),
|
||||
("sendKeyEvent", {**owner, "key": "a", "direction": "down", "taskId": "fixture"})]:
|
||||
("sendKeyEvent", {**owner, "key": "a", "direction": "down"})]:
|
||||
failure = helper.call(method, params, "PANEL_NOT_READY")
|
||||
assert failure["message"] == "File panel recipient discovery is incomplete. No input was dispatched. Read fresh state before retrying.", failure
|
||||
assert json.loads(log.read_text()) == expected
|
||||
|
||||
@@ -12,6 +12,14 @@ describe('native protocol generation', () => {
|
||||
expect(await readFile(new URL('../native/Sources/CuaNative/NativeProtocol.generated.swift', import.meta.url), 'utf8')).toBe(generated.swift)
|
||||
})
|
||||
|
||||
it('uses the requesting connection for held-input queries and cleanup', () => {
|
||||
const validate = new Ajv2020().compile(JSON.parse(renderNativeProtocol().json))
|
||||
for (const method of ['getHeldInputs', 'releaseHeldInputs']) {
|
||||
expect(validate({ id: 'held', method, params: {} })).toBe(true)
|
||||
expect(validate({ id: 'foreign', method, params: { taskId: 'other' } })).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('resolves recursive JSON arguments in the complete native request schema', () => {
|
||||
const validate = new Ajv2020().compile(JSON.parse(renderNativeProtocol().json))
|
||||
const target = { appHandle: 'app', snapshotId: 'snapshot', elementId: '0' }
|
||||
@@ -74,7 +82,8 @@ describe('native protocol generation', () => {
|
||||
{ method: 'paste', params: { appHandle: 'app', text: 'text', pasteReadTimeoutMs: 1000 } },
|
||||
{ method: 'mouseMove', params: { appHandle: 'app', windowId: '1', x: 0, y: 0, allowSystemPointer: true } },
|
||||
{ method: 'findApps', params: { query: 'Editor', maxAppMatches: 1 } },
|
||||
{ method: 'releaseHeldInputs', params: { taskId: 'task', turn: 1 } },
|
||||
{ method: 'getHeldInputs', params: {} },
|
||||
{ method: 'releaseHeldInputs', params: {} },
|
||||
{ method: 'takeWindowActivity', params: { appHandle: 'app', observations: { '7': '123' } } },
|
||||
{ method: 'clearWindowActivity', params: {} },
|
||||
{ method: 'launchApp', params: { appHandle: 'pending' } },
|
||||
|
||||
@@ -274,13 +274,13 @@ it('delivers window activity at the next accepted step and clears it at turn end
|
||||
expect(native.request).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('accepts task-owned directional input outside a turn', async () => {
|
||||
it('accepts directional input on the Agent connection outside a turn', async () => {
|
||||
const f = await setup()
|
||||
await selectApplication(f)
|
||||
native.request.mockResolvedValueOnce({ dispatched: true })
|
||||
const result = await f.execute('sendKeyEvent', { appHandle: 'app-one', key: 'w', direction: 'down' })
|
||||
expect(result.isError).toBe(false)
|
||||
expect(native.request).toHaveBeenLastCalledWith('sendKeyEvent', { appHandle: 'app-one', key: 'w', direction: 'down', taskId: f.handle.agent.id }, expect.any(AbortSignal), expect.any(String))
|
||||
expect(native.request).toHaveBeenLastCalledWith('sendKeyEvent', { appHandle: 'app-one', key: 'w', direction: 'down' }, expect.any(AbortSignal), expect.any(String))
|
||||
})
|
||||
|
||||
it.each(PTC_MODES)('holds a key across $mode programs in the same turn', async (mode) => {
|
||||
@@ -291,7 +291,6 @@ it.each(PTC_MODES)('holds a key across $mode programs in the same turn', async (
|
||||
native.request.mockClear().mockImplementation(async (method, params) => {
|
||||
if (method === 'getHeldInputs') return [...held].map(key => ({ kind: 'key', key, appHandle: 'app-one', mode: 'application' }))
|
||||
expect(method).toBe('sendKeyEvent')
|
||||
expect(params).toMatchObject({ taskId: f.handle.agent.id })
|
||||
const key = params.key
|
||||
if (typeof key !== 'string') throw new Error('The native fixture requires a key name')
|
||||
if (params.direction === 'down') held.add(key)
|
||||
@@ -1214,9 +1213,9 @@ it('requires an explicit system-pointer request on every move and asks only once
|
||||
[hoverTarget, false], [{ ...hoverTarget, useSystemInput: false }, false], [physicalHover, true],
|
||||
] as const) {
|
||||
expect((await f.execute('mouseMove', params)).isError).toBe(false)
|
||||
expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: physical, ...physical ? { taskId: f.handle.agent.id } : {} }, expect.any(AbortSignal), expect.any(String))
|
||||
expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: physical }, expect.any(AbortSignal), expect.any(String))
|
||||
}
|
||||
expect(native.request.mock.calls[1]?.[1]).toEqual({ ...physicalHover, taskId: f.handle.agent.id })
|
||||
expect(native.request.mock.calls[1]?.[1]).toEqual(physicalHover)
|
||||
expect(f.ask).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
@@ -1225,7 +1224,7 @@ it.each([true, false])('shares the system input decision for a system button wit
|
||||
const target = { appHandle: 'app-one', windowId: '7', mouseButton: 'left', direction: 'down' }
|
||||
for (const params of [target, { ...target, useSystemInput: false }]) {
|
||||
expect((await f.execute('toggleMouse', params)).isError).toBe(false)
|
||||
expect(native.request.mock.lastCall?.[1]).toEqual({ ...target, taskId: f.handle.agent.id })
|
||||
expect(native.request.mock.lastCall?.[1]).toEqual(target)
|
||||
}
|
||||
expect(f.ask).not.toHaveBeenCalled()
|
||||
const answer = Promise.withResolvers<typeof f.approved>()
|
||||
@@ -1246,7 +1245,7 @@ it.each([true, false])('shares the system input decision for a system button wit
|
||||
.toEqual([['toggleMouse', true], ['mouseMove', true], ['toggleMouse', undefined]])
|
||||
f.handle.agent.cancel({ kind: 'user' })
|
||||
await f.handle.agent.whenIdle()
|
||||
expect(native.cleanup).toHaveBeenCalledWith('releaseHeldInputs', { taskId: f.handle.agent.id })
|
||||
expect(native.cleanup).toHaveBeenCalledWith('releaseHeldInputs', {})
|
||||
} else {
|
||||
for (const result of results.slice(0, 2)) expect(JSON.stringify(result.content)).toContain('SYSTEM_INPUT_DENIED')
|
||||
expect(results[2]?.isError).toBe(false)
|
||||
@@ -1294,7 +1293,7 @@ it('keeps refusals and grants separate and forgets a closed session on reopen',
|
||||
expect((await f.call(agent, 'mouseMove', hoverTarget)).isError).toBe(false)
|
||||
expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: false }, expect.any(AbortSignal), expect.any(String))
|
||||
expect((await f.execute('mouseMove', physicalHover)).isError).toBe(false)
|
||||
expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...physicalHover, taskId: f.handle.agent.id }, expect.any(AbortSignal), expect.any(String))
|
||||
expect(native.request).toHaveBeenLastCalledWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String))
|
||||
const sessionId = f.handle.agent.id
|
||||
await f.handle.dispose()
|
||||
const reopened = await f.ctx.agents.create({ sessionId })
|
||||
@@ -1354,7 +1353,7 @@ it('allows only the explicitly requested physical move when approval is disabled
|
||||
const f = await hoverFixture(false)
|
||||
for (const [target, expected] of [[hoverTarget, false], [physicalHover, true], [hoverTarget, false]] as const) {
|
||||
expect((await f.execute('mouseMove', target)).isError).toBe(false)
|
||||
expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: expected, ...expected ? { taskId: f.handle.agent.id } : {} }, expect.any(AbortSignal), expect.any(String))
|
||||
expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: expected }, expect.any(AbortSignal), expect.any(String))
|
||||
}
|
||||
expect(f.ask).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -1423,7 +1422,7 @@ it('keeps complete system moves available outside a turn without registering a p
|
||||
await selectApplication(f)
|
||||
native.request.mockClear()
|
||||
expect((await f.execute('mouseMove', physicalHover)).isError).toBe(false)
|
||||
expect(native.request).toHaveBeenCalledExactlyOnceWith('mouseMove', { ...physicalHover, taskId: f.handle.agent.id }, expect.any(AbortSignal), expect.any(String))
|
||||
expect(native.request).toHaveBeenCalledExactlyOnceWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String))
|
||||
await f.handle.dispose()
|
||||
expect(native.cleanup).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -36,8 +36,8 @@
|
||||
en: 38b3250d6ae0f3d6
|
||||
zh: 33d056c416e11d75
|
||||
/deepseek-ai-dsh-cua-windows/model-experience/explicit-application-and-window-operations/what-the-model-sees:
|
||||
en: 81af5b1e782d3290
|
||||
zh: db72fcd496fd44e4
|
||||
en: bf6f99c4c1fafe72
|
||||
zh: 791930be8c5f80f4
|
||||
/deepseek-ai-dsh-cua-windows/model-experience/explicit-application-and-window-operations/token-effect:
|
||||
en: 39eebd53ee226af7
|
||||
zh: ba7b352cf1e23c3c
|
||||
|
||||
@@ -65,7 +65,7 @@ Each result contains `id`, `displayName`, and `isRunning`. The ID is an AUMID, i
|
||||
|
||||
#### What the model sees
|
||||
|
||||
The program receives application and window identifiers, observations, and action results. Selection alone does not provide an accessibility tree. After a successful program, a reminder lists any held keys and buttons with their window and desktop input mode. Program failure, cancellation, reset and disconnect release owned input in reverse order.
|
||||
The program receives application and window identifiers, observations, and action results. Selection alone does not provide an accessibility tree. After a successful program, a reminder lists any held keys and buttons with their window and desktop input mode. Program failure, cancellation, reset and disconnect release the input held by that connection in reverse dispatch order.
|
||||
|
||||
#### Token effect
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ kind: "package-reference"
|
||||
|
||||
#### 模型看到什么
|
||||
|
||||
程序可以读取应用和窗口标识、观察结果及动作结果。仅执行选择操作不会提供辅助功能树。程序成功后,提醒会列出仍按住的键和鼠标按钮、所属窗口和桌面输入方式。程序异常、取消、重置和断连时,按派发顺序反序释放任务持有的输入。
|
||||
程序可以读取应用和窗口标识、观察结果及动作结果。仅执行选择操作不会提供辅助功能树。程序成功后,提醒会列出仍按住的键和鼠标按钮、所属窗口和桌面输入方式。程序异常、取消、重置和断连时,按派发顺序的反序释放这条连接持有的输入。
|
||||
|
||||
#### Token 影响
|
||||
|
||||
|
||||
@@ -86,20 +86,19 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA
|
||||
if (request.Method == "getActionSchema") return PatternActions.Schema(String(parameters, "action"));
|
||||
if (request.Method is "requestPermission" or "openPermissionSettings")
|
||||
throw new NativeFailure("UNSUPPORTED", "Windows desktop access has no macOS permission switches; inspect the Windows session status");
|
||||
if (request.Method == "getHeldInputs") return inputs.Get(state.Connection, String(parameters, "taskId"));
|
||||
if (request.Method == "getHeldInputs") return inputs.Get(state.Connection);
|
||||
if (request.Method == "releaseHeldInputs")
|
||||
return inputs.Release(state.Connection, String(parameters, "taskId"), cancellation);
|
||||
return inputs.Release(state.Connection, cancellation);
|
||||
|
||||
if (request.Method is "sendKeyEvent" or "toggleMouse" && String(parameters, "direction") == "up")
|
||||
{
|
||||
var window = WindowId(parameters) ?? throw new NativeFailure("INVALID_ARGUMENT", "Release through the original window");
|
||||
var task = String(parameters, "taskId");
|
||||
var recipient = String(parameters, "appHandle");
|
||||
var before = Win32.GetForegroundWindow();
|
||||
if (request.Method == "sendKeyEvent")
|
||||
Input.ReleaseKey(state.Connection, task, recipient, window, String(parameters, "key"), context);
|
||||
Input.ReleaseKey(state.Connection, recipient, window, String(parameters, "key"), context);
|
||||
else
|
||||
Input.ReleaseButton(state.Connection, task, recipient, window, String(parameters, "mouseButton"), context);
|
||||
Input.ReleaseButton(state.Connection, recipient, window, String(parameters, "mouseButton"), context);
|
||||
return ActionResult(before);
|
||||
}
|
||||
DesktopSession.RequireInteractive();
|
||||
@@ -116,7 +115,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA
|
||||
var app = state.App(String(parameters, "appHandle"));
|
||||
var foreground = Win32.GetForegroundWindow();
|
||||
if (request.Method is "sendKeyEvent" or "toggleMouse" or "pressKey" or "typeText" or "paste" or "mouseMove" or "scroll" or "drag" or "click")
|
||||
inputs.RequireOwner(state.Connection, OptionalString(parameters, "taskId"), app.Handle, WindowId(parameters) ?? 0);
|
||||
inputs.RequireOwner(state.Connection, app.Handle, WindowId(parameters) ?? 0);
|
||||
switch (request.Method)
|
||||
{
|
||||
case "launchApp":
|
||||
@@ -163,7 +162,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA
|
||||
case "sendKeyEvent":
|
||||
{
|
||||
var target = Selected(app, parameters, context);
|
||||
var dispatched = Input.KeyDown(state.Connection, String(parameters, "taskId"), app, target, String(parameters, "key"), context);
|
||||
var dispatched = Input.KeyDown(state.Connection, app, target, String(parameters, "key"), context);
|
||||
return ActionResult(foreground, dispatched);
|
||||
}
|
||||
case "paste":
|
||||
@@ -194,7 +193,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA
|
||||
case "toggleMouse":
|
||||
{
|
||||
var target = Selected(app, parameters, context);
|
||||
var dispatched = Input.ButtonDown(state.Connection, String(parameters, "taskId"), app, target, String(parameters, "mouseButton"), context);
|
||||
var dispatched = Input.ButtonDown(state.Connection, app, target, String(parameters, "mouseButton"), context);
|
||||
return ActionResult(foreground, dispatched);
|
||||
}
|
||||
case "scroll":
|
||||
@@ -304,7 +303,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA
|
||||
if (!inputs.HasConnection(state.Connection)) return;
|
||||
using var deadline = new CancellationTokenSource(graceMs);
|
||||
await queue.WaitAsync(deadline.Token);
|
||||
try { inputs.Release(state.Connection, null, deadline.Token); }
|
||||
try { inputs.Release(state.Connection, deadline.Token); }
|
||||
finally { queue.Release(); }
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace DeepSeek.Cua.Windows;
|
||||
internal sealed class HeldInputs(Action<Win32.Input> send, Action requireInteractive)
|
||||
{
|
||||
internal readonly record struct Target(string AppHandle, nint Window, int ProcessId, long ProcessStarted);
|
||||
private sealed record Press(Guid Connection, string Task, Target Target, ushort Control, string Name, Win32.Input Up)
|
||||
private sealed record Press(Guid Connection, Target Target, ushort Control, string Name, Win32.Input Up)
|
||||
{
|
||||
internal object Describe() => new
|
||||
{
|
||||
@@ -20,13 +20,12 @@ internal sealed class HeldInputs(Action<Win32.Input> send, Action requireInterac
|
||||
private readonly object gate = new();
|
||||
private readonly List<Press> pressed = [];
|
||||
|
||||
internal void RequireOwner(Guid connection, string? task, string app, nint window)
|
||||
internal void RequireOwner(Guid connection, string app, nint window)
|
||||
{
|
||||
lock (gate)
|
||||
if (pressed.Any(press => press.Connection != connection
|
||||
|| (task is not null && press.Task != task)
|
||||
|| press.Target.AppHandle != app || press.Target.Window != window))
|
||||
throw new NativeFailure("INPUT_BUSY", "Another task or window owns held desktop input; release it before sending input to this window");
|
||||
throw new NativeFailure("INPUT_BUSY", "Another connection or window owns held desktop input; release it before sending input to this window");
|
||||
}
|
||||
|
||||
internal void RequireAvailable(ushort control)
|
||||
@@ -36,7 +35,7 @@ internal sealed class HeldInputs(Action<Win32.Input> send, Action requireInterac
|
||||
throw new NativeFailure("INPUT_BUSY", "This key or button is already held; release it before a complete action uses it");
|
||||
}
|
||||
|
||||
internal bool Down(Guid connection, string task, Target target, ushort control, string name, Win32.Input down,
|
||||
internal bool Down(Guid connection, Target target, ushort control, string name, Win32.Input down,
|
||||
Win32.Input up, CancellationToken cancellation)
|
||||
{
|
||||
lock (gate)
|
||||
@@ -45,12 +44,12 @@ internal sealed class HeldInputs(Action<Win32.Input> send, Action requireInterac
|
||||
var existing = pressed.Find(press => press.Control == control);
|
||||
if (existing is not null)
|
||||
{
|
||||
if (existing.Connection == connection && existing.Task == task && existing.Target == target && existing.Name == name)
|
||||
if (existing.Connection == connection && existing.Target == target && existing.Name == name)
|
||||
return false;
|
||||
throw new NativeFailure("INPUT_BUSY", "This key or button is already held by another input target");
|
||||
}
|
||||
|
||||
var press = new Press(connection, task, target, control, name, up);
|
||||
var press = new Press(connection, target, control, name, up);
|
||||
pressed.Add(press);
|
||||
try { send(down); }
|
||||
catch (NativeFailure error) when (error.Code == "INPUT_BLOCKED")
|
||||
@@ -63,21 +62,21 @@ internal sealed class HeldInputs(Action<Win32.Input> send, Action requireInterac
|
||||
}
|
||||
}
|
||||
|
||||
internal void Up(Guid connection, string task, string app, nint window, string name, bool keyboard)
|
||||
internal void Up(Guid connection, string app, nint window, string name, bool keyboard)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var index = pressed.FindIndex(press => press.Connection == connection && press.Task == task && press.Target.AppHandle == app
|
||||
var index = pressed.FindIndex(press => press.Connection == connection && press.Target.AppHandle == app
|
||||
&& press.Target.Window == window && press.Name == name && (press.Up.Type == 1) == keyboard);
|
||||
if (index < 0) throw new NativeFailure("INPUT_NOT_HELD", "This task did not hold that input on the selected window");
|
||||
if (index < 0) throw new NativeFailure("INPUT_NOT_HELD", "This connection did not hold that input on the selected window");
|
||||
ReleaseAt(index);
|
||||
}
|
||||
}
|
||||
|
||||
internal object[] Get(Guid connection, string task)
|
||||
internal object[] Get(Guid connection)
|
||||
{
|
||||
lock (gate)
|
||||
return pressed.Where(press => press.Connection == connection && press.Task == task).Select(press => press.Describe()).ToArray();
|
||||
return pressed.Where(press => press.Connection == connection).Select(press => press.Describe()).ToArray();
|
||||
}
|
||||
|
||||
internal bool HasConnection(Guid connection)
|
||||
@@ -85,7 +84,7 @@ internal sealed class HeldInputs(Action<Win32.Input> send, Action requireInterac
|
||||
lock (gate) return pressed.Exists(press => press.Connection == connection);
|
||||
}
|
||||
|
||||
internal object[] Release(Guid connection, string? task, CancellationToken cancellation)
|
||||
internal object[] Release(Guid connection, CancellationToken cancellation)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
@@ -94,7 +93,7 @@ internal sealed class HeldInputs(Action<Win32.Input> send, Action requireInterac
|
||||
for (var index = pressed.Count - 1; index >= 0; index--)
|
||||
{
|
||||
var press = pressed[index];
|
||||
if (press.Connection != connection || (task is not null && press.Task != task)) continue;
|
||||
if (press.Connection != connection) continue;
|
||||
cancellation.ThrowIfCancellationRequested();
|
||||
try { ReleaseAt(index); released.Add(press.Describe()); }
|
||||
catch (NativeFailure error) { failures.Add(error.Message); }
|
||||
|
||||
@@ -104,10 +104,10 @@ internal static class Input
|
||||
var key => key,
|
||||
};
|
||||
|
||||
internal static void ReleaseKey(Guid connection, string task, string app, nint window, string name, RequestContext context)
|
||||
=> context.HeldInputs.Up(connection, task, app, window, HoldKeyName(name), true);
|
||||
internal static void ReleaseKey(Guid connection, string app, nint window, string name, RequestContext context)
|
||||
=> context.HeldInputs.Up(connection, app, window, HoldKeyName(name), true);
|
||||
|
||||
internal static bool KeyDown(Guid connection, string task, AppState app, WindowState window, string name, RequestContext context)
|
||||
internal static bool KeyDown(Guid connection, AppState app, WindowState window, string name, RequestContext context)
|
||||
{
|
||||
Windows.RequireForeground(app, window, context);
|
||||
name = HoldKeyName(name);
|
||||
@@ -115,7 +115,7 @@ internal static class Input
|
||||
if (key.Modifiers.Length != 0)
|
||||
throw new NativeFailure("UNSUPPORTED", "This key requires modifiers in the target keyboard layout; send each modifier and the base key separately");
|
||||
var flags = key.Extended ? 1u : 0;
|
||||
return context.HeldInputs.Down(connection, task, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted),
|
||||
return context.HeldInputs.Down(connection, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted),
|
||||
key.Key, name, Keyboard(key.Key, flags: flags), Keyboard(key.Key, flags: flags | 2), context.Cancellation);
|
||||
}
|
||||
|
||||
@@ -187,15 +187,15 @@ internal static class Input
|
||||
return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y };
|
||||
}
|
||||
|
||||
internal static void ReleaseButton(Guid connection, string task, string app, nint window, string button, RequestContext context)
|
||||
=> context.HeldInputs.Up(connection, task, app, window, button, false);
|
||||
internal static void ReleaseButton(Guid connection, string app, nint window, string button, RequestContext context)
|
||||
=> context.HeldInputs.Up(connection, app, window, button, false);
|
||||
|
||||
internal static bool ButtonDown(Guid connection, string task, AppState app, WindowState window, string button, RequestContext context)
|
||||
internal static bool ButtonDown(Guid connection, AppState app, WindowState window, string button, RequestContext context)
|
||||
{
|
||||
var flags = Button(button);
|
||||
if (!Win32.GetCursorPos(out var point)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable");
|
||||
Hit(app, window, point, context);
|
||||
return context.HeldInputs.Down(connection, task, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted),
|
||||
return context.HeldInputs.Down(connection, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted),
|
||||
flags.Control, button, Mouse(flags.Down), Mouse(flags.Up), context.Cancellation);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,9 @@
|
||||
/** Generate Windows native admission from the shared CUA operation definitions. */
|
||||
import { readFile, writeFile } from 'node:fs/promises'
|
||||
import { nativeProtocol } from '@deepseek-ai/dsh-cua/native-schema'
|
||||
import { z } from 'zod'
|
||||
|
||||
const path = new URL('protocol.schema.json', import.meta.url)
|
||||
const owner = z.object({ taskId: z.string().min(1) }).strict()
|
||||
const content = nativeProtocol({
|
||||
sendKeyEvent: owner,
|
||||
toggleMouse: owner,
|
||||
}, ['getHeldInputs', 'releaseHeldInputs'].map(method => z.object({
|
||||
method: z.literal(method), params: owner,
|
||||
}).strict())).json
|
||||
const content = nativeProtocol().json
|
||||
if (process.argv.includes('--check')) {
|
||||
if (await readFile(path, 'utf8') !== content) throw new Error('Stale Windows CUA native request schema')
|
||||
} else await writeFile(path, content)
|
||||
@@ -517,18 +517,13 @@
|
||||
"down",
|
||||
"up"
|
||||
]
|
||||
},
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"appHandle",
|
||||
"windowId",
|
||||
"mouseButton",
|
||||
"direction",
|
||||
"taskId"
|
||||
"direction"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -1123,17 +1118,12 @@
|
||||
"down",
|
||||
"up"
|
||||
]
|
||||
},
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"appHandle",
|
||||
"key",
|
||||
"direction",
|
||||
"taskId"
|
||||
"direction"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -1507,15 +1497,7 @@
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"taskId"
|
||||
],
|
||||
"properties": {},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
@@ -1538,15 +1520,7 @@
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"taskId"
|
||||
],
|
||||
"properties": {},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
|
||||
@@ -26,61 +26,61 @@ internal static class HeldInputChecks
|
||||
if (!interactive) throw new NativeFailure("SESSION_LOCKED", "The interactive desktop is unavailable");
|
||||
});
|
||||
|
||||
bool Key(Guid connection, string task, ushort key, string name, CancellationToken cancellation = default)
|
||||
=> inputs.Down(connection, task, target, key, name,
|
||||
bool Key(Guid connection, ushort key, string name, CancellationToken cancellation = default)
|
||||
=> inputs.Down(connection, target, key, name,
|
||||
new() { Type = 1, Data = new() { Keyboard = new() { Key = key } } },
|
||||
new() { Type = 1, Data = new() { Keyboard = new() { Key = key, Flags = 2 } } },
|
||||
cancellation);
|
||||
|
||||
refuses(() => inputs.Up(a, "task", "app", 72, "shift", true), "INPUT_NOT_HELD");
|
||||
refuses(() => inputs.Up(a, "app", 72, "shift", true), "INPUT_NOT_HELD");
|
||||
check(events.Count == 0, "No up is sent for a key the helper never pressed");
|
||||
blocked = true;
|
||||
refuses(() => Key(a, "task", 16, "shift"), "INPUT_BLOCKED");
|
||||
check(inputs.Get(a, "task").Length == 0, "A refused down does not cause an up");
|
||||
refuses(() => Key(a, 16, "shift"), "INPUT_BLOCKED");
|
||||
check(inputs.Get(a).Length == 0, "A refused down does not cause an up");
|
||||
blocked = false;
|
||||
check(Key(a, "task", 16, "shift"), "Record the accepted keyboard down");
|
||||
check(inputs.Down(a, "task", target, 1, "left",
|
||||
check(Key(a, 16, "shift"), "Record the accepted keyboard down");
|
||||
check(inputs.Down(a, target, 1, "left",
|
||||
new() { Data = new() { Mouse = new() { Flags = 2 } } },
|
||||
new() { Data = new() { Mouse = new() { Flags = 4 } } }, default), "Record the accepted mouse down");
|
||||
check(Key(a, "task", 87, "w") && !Key(a, "task", 87, "w"), "A repeated key does not duplicate a hold");
|
||||
refuses(() => inputs.RequireOwner(b, "task", "app", 72), "INPUT_BUSY");
|
||||
refuses(() => inputs.RequireOwner(a, "other", "app", 72), "INPUT_BUSY");
|
||||
check(Key(a, 87, "w") && !Key(a, 87, "w"), "A repeated key does not duplicate a hold");
|
||||
refuses(() => inputs.RequireOwner(b, "app", 72), "INPUT_BUSY");
|
||||
refuses(() => inputs.RequireOwner(a, "app", 73), "INPUT_BUSY");
|
||||
refuses(() => inputs.RequireAvailable(1), "INPUT_BUSY");
|
||||
refuses(() => inputs.Up(a, "other", "app", 72, "w", true), "INPUT_NOT_HELD");
|
||||
refuses(() => inputs.Up(a, "task", "app", 73, "w", true), "INPUT_NOT_HELD");
|
||||
check(inputs.Release(b, null, default).Length == 0, "Another connection releases nothing");
|
||||
check(inputs.Get(a, "other").Length == 0 && inputs.Get(a, "task").Length == 3, "State query is task-scoped");
|
||||
var described = JsonSerializer.SerializeToElement(inputs.Get(a, "task"), WireJson.Options);
|
||||
refuses(() => inputs.Up(b, "app", 72, "w", true), "INPUT_NOT_HELD");
|
||||
refuses(() => inputs.Up(a, "app", 73, "w", true), "INPUT_NOT_HELD");
|
||||
check(inputs.Release(b, default).Length == 0, "Another connection releases nothing");
|
||||
check(inputs.Get(b).Length == 0 && inputs.Get(a).Length == 3, "State query is connection-scoped");
|
||||
var described = JsonSerializer.SerializeToElement(inputs.Get(a), WireJson.Options);
|
||||
check(described[0].GetProperty("windowId").GetString() == "72" && described[0].GetProperty("mode").GetString() == "system",
|
||||
"Keyboard reminders identify the window and actual desktop mode");
|
||||
inputs.Up(a, "task", "app", 72, "shift", true);
|
||||
check(Key(a, "task", 16, "shift"), "Explicit up and repress update the dispatch order");
|
||||
check(inputs.Release(a, "task", default).Length == 3
|
||||
inputs.Up(a, "app", 72, "shift", true);
|
||||
check(Key(a, 16, "shift"), "Explicit up and repress update the dispatch order");
|
||||
check(inputs.Release(a, default).Length == 3
|
||||
&& events.TakeLast(3).SequenceEqual(["16:up", "87:up", "1:up"]), "Release in mixed reverse order, including repress");
|
||||
check(inputs.Release(a, null, default).Length == 0, "Duplicate connection cleanup sends no up");
|
||||
check(inputs.Release(a, default).Length == 0, "Duplicate connection cleanup sends no up");
|
||||
using (var cancelled = new CancellationTokenSource())
|
||||
{
|
||||
cancelled.Cancel();
|
||||
try { Key(a, "task", 87, "w", cancelled.Token); throw new Exception("Expected cancelled down"); }
|
||||
catch (OperationCanceledException) { check(inputs.Get(a, "task").Length == 0, "Cancelled down never dispatches"); }
|
||||
try { Key(a, 87, "w", cancelled.Token); throw new Exception("Expected cancelled down"); }
|
||||
catch (OperationCanceledException) { check(inputs.Get(a).Length == 0, "Cancelled down never dispatches"); }
|
||||
}
|
||||
Key(a, "task", 87, "w");
|
||||
Key(a, 87, "w");
|
||||
interactive = false;
|
||||
refuses(() => inputs.Release(a, null, default), "INPUT_CLEANUP_FAILED");
|
||||
check(inputs.Get(a, "task").Length == 1, "A locked desktop leaves the failed release recorded");
|
||||
refuses(() => inputs.Release(a, default), "INPUT_CLEANUP_FAILED");
|
||||
check(inputs.Get(a).Length == 1, "A locked desktop leaves the failed release recorded");
|
||||
interactive = true;
|
||||
blocked = true;
|
||||
refuses(() => inputs.Release(a, null, default), "INPUT_CLEANUP_FAILED");
|
||||
check(inputs.Get(a, "task").Length == 1, "A refused release stays recorded for disconnect fallback");
|
||||
refuses(() => inputs.Release(a, default), "INPUT_CLEANUP_FAILED");
|
||||
check(inputs.Get(a).Length == 1, "A refused release stays recorded for disconnect fallback");
|
||||
blocked = false;
|
||||
// Another source releases W and presses D at the same receiver.
|
||||
Receive(new() { Type = 1, Data = new() { Keyboard = new() { Key = 87, Flags = 2 } } });
|
||||
Receive(new() { Type = 1, Data = new() { Keyboard = new() { Key = 68 } } });
|
||||
described = JsonSerializer.SerializeToElement(inputs.Get(a, "task"), WireJson.Options);
|
||||
described = JsonSerializer.SerializeToElement(inputs.Get(a), WireJson.Options);
|
||||
check(described.GetArrayLength() == 1 && described[0].GetProperty("key").GetString() == "w",
|
||||
"The reminder still reports only the helper's W down");
|
||||
var count = events.Count;
|
||||
check(inputs.Release(a, null, default).Length == 1 && events.Skip(count).SequenceEqual(["87:up"]),
|
||||
check(inputs.Release(a, default).Length == 1 && events.Skip(count).SequenceEqual(["87:up"]),
|
||||
"Disconnect retries the helper's W release and leaves D alone");
|
||||
check(!inputs.HasConnection(a), "Accepted release removes the connection's last hold");
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ foreach (var direction in new[] { "down", "up" })
|
||||
{
|
||||
var toggle = NativeRequest.Parse(WireJson.Parse(System.Text.Json.JsonSerializer.Serialize(new
|
||||
{
|
||||
id = "mouse", method = "toggleMouse", @params = new { appHandle = "app", windowId = "1", taskId = "task", mouseButton, direction },
|
||||
id = "mouse", method = "toggleMouse", @params = new { appHandle = "app", windowId = "1", mouseButton, direction },
|
||||
})));
|
||||
Check(toggle.Params.GetProperty("mouseButton").GetString() == mouseButton
|
||||
&& toggle.Params.GetProperty("direction").GetString() == direction,
|
||||
@@ -75,22 +75,20 @@ foreach (var direction in new[] { "down", "up" })
|
||||
foreach (var invalid in new[]
|
||||
{
|
||||
"""{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down"}""",
|
||||
"""{"appHandle":"app","taskId":"task","windowId":"1","mouseButton":"left"}""",
|
||||
"""{"appHandle":"app","taskId":"task","windowId":"1","direction":"down"}""",
|
||||
"""{"appHandle":"app","taskId":"task","mouseButton":"left","direction":"down"}""",
|
||||
"""{"appHandle":"app","taskId":"task","windowId":"1","mouseButton":"back","direction":"down"}""",
|
||||
"""{"appHandle":"app","taskId":"task","windowId":"1","mouseButton":"left","direction":"press"}""",
|
||||
"""{"appHandle":"app","taskId":"task","windowId":"1","mouseButton":"left","direction":"down","x":1,"y":2}""",
|
||||
"""{"appHandle":"app","windowId":"1","mouseButton":"left"}""",
|
||||
"""{"appHandle":"app","windowId":"1","direction":"down"}""",
|
||||
"""{"appHandle":"app","mouseButton":"left","direction":"down"}""",
|
||||
"""{"appHandle":"app","windowId":"1","mouseButton":"back","direction":"down"}""",
|
||||
"""{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"press"}""",
|
||||
"""{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down","x":1,"y":2}""",
|
||||
})
|
||||
Refuses(() => NativeRequest.Parse(WireJson.Parse("{\"id\":\"mouse\",\"method\":\"toggleMouse\",\"params\":" + invalid + "}")), "INVALID_ARGUMENT");
|
||||
|
||||
foreach (var method in new[] { "getHeldInputs", "releaseHeldInputs" })
|
||||
{
|
||||
var query = $$$"""{"id":"holds","method":"{{{method}}}","params":{"taskId":"a"}}""";
|
||||
Check(NativeRequest.Parse(WireJson.Parse(query)).Params.GetProperty("taskId").GetString() == "a",
|
||||
"Private held-input operations accept only the task owner");
|
||||
Refuses(() => NativeRequest.Parse(WireJson.Parse($$$"""{"id":"holds","method":"{{{method}}}","params":{}}""")), "INVALID_ARGUMENT");
|
||||
Refuses(() => NativeRequest.Parse(WireJson.Parse($$$"""{"id":"holds","method":"{{{method}}}","params":{"taskId":"a","appHandle":"app"}}""")), "INVALID_ARGUMENT");
|
||||
var query = $$$"""{"id":"holds","method":"{{{method}}}","params":{}}""";
|
||||
Check(NativeRequest.Parse(WireJson.Parse(query)).Method == method, "Held-input operations use the requesting connection");
|
||||
Refuses(() => NativeRequest.Parse(WireJson.Parse($$$"""{"id":"holds","method":"{{{method}}}","params":{"taskId":"other"}}""")), "INVALID_ARGUMENT");
|
||||
}
|
||||
HeldInputChecks.Run(Check, Refuses);
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)(
|
||||
const windowId = initial.state.window
|
||||
expect(windows.some(window => window.windowId === windowId)).toBe(true)
|
||||
const toggle = async (mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') =>
|
||||
ToggleResult.parse(await native.request('toggleMouse', { appHandle: app.appHandle, windowId, taskId: 'desktop-test', mouseButton, direction }, signal))
|
||||
ToggleResult.parse(await native.request('toggleMouse', { appHandle: app.appHandle, windowId, mouseButton, direction }, signal))
|
||||
|
||||
const { cursor } = await fixture.command('pointer', FixtureState)
|
||||
for (const mouseButton of ['left', 'right', 'middle'] as const) {
|
||||
@@ -144,10 +144,9 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)(
|
||||
expect((await toggle('left', 'up')).dispatched).toBe(true)
|
||||
await observed({ buttons: 'None', cursor: outside.cursor, ups: { left: pressed.ups.left + 1 }, clicks: pressed.clicks })
|
||||
|
||||
const taskId = 'desktop-test'
|
||||
const target = { appHandle: app.appHandle, windowId, taskId }
|
||||
const target = { appHandle: app.appHandle, windowId }
|
||||
const key = (key: string, direction: 'down' | 'up') => native.request('sendKeyEvent', { ...target, key, direction }, signal)
|
||||
const holds = () => native.request('getHeldInputs', { taskId }, signal)
|
||||
const holds = () => native.request('getHeldInputs', {}, signal)
|
||||
const released = z.array(z.object({ kind: z.string(), key: z.string().nullable(), button: z.string().nullable(), mode: z.literal('system') }))
|
||||
await fixture.command('pointer', FixtureState)
|
||||
const offset = (await inspect()).inputEvents.length
|
||||
@@ -162,10 +161,11 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)(
|
||||
(_owner, config) => nativeRuntime.connect(config))
|
||||
cleanups.push(() => other.dispose())
|
||||
const otherApp = App.parse(await other.request('getApp', { selector: fixturePath! }, signal))
|
||||
expect(await other.request('getHeldInputs', { taskId }, signal)).toEqual([])
|
||||
expect(await other.request('getHeldInputs', {}, signal)).toEqual([])
|
||||
expect(await other.requestCleanup('releaseHeldInputs', {})).toEqual([])
|
||||
await expect(other.request('sendKeyEvent', { ...target, appHandle: otherApp.appHandle, key: 'w', direction: 'up' }, signal))
|
||||
.rejects.toMatchObject({ code: 'INPUT_NOT_HELD' })
|
||||
const release = await native.requestCleanup('releaseHeldInputs', { taskId })
|
||||
const release = await native.requestCleanup('releaseHeldInputs', {})
|
||||
expect(released.parse(release).map(input => input.key ?? input.button)).toEqual(['w', 'left', 'shift'])
|
||||
await expect.poll(async () => (await inspect()).inputEvents.slice(offset)).toEqual(
|
||||
['ShiftKey:down', 'Left:down', 'W:down', 'W:up', 'Left:up', 'ShiftKey:up'])
|
||||
@@ -176,7 +176,7 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)(
|
||||
await fixture.command('left-up', FixtureState)
|
||||
await observed({ ups: { left: beforeExternal.ups.left + 1 } })
|
||||
expect(released.parse(await holds()).map(input => input.button)).toEqual(['left'])
|
||||
const afterExternal = await native.requestCleanup('releaseHeldInputs', { taskId })
|
||||
const afterExternal = await native.requestCleanup('releaseHeldInputs', {})
|
||||
expect(released.parse(afterExternal).map(input => input.button)).toEqual(['left'])
|
||||
expect(await holds()).toEqual([])
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 3f638a4a76023fc5
|
||||
zh: 515aeb5de6ae5b33
|
||||
/deepseek-ai-dsh-cua/understand-the-implementation:
|
||||
en: 60892f557adb5d01
|
||||
zh: 2e8483610017484a
|
||||
en: 7754a370ed7e54ff
|
||||
zh: a3fa369e265746ad
|
||||
/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 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. macOS and Windows both implement this protocol. Capability methods remain static.
|
||||
Providers implementing `CuaBackend.heldInputState` return the requesting connection’s holds through `getHeldInputs({})` and acknowledge their release through `releaseHeldInputs({})`. 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. macOS and Windows both implement this protocol. Capability methods remain static.
|
||||
|
||||
Held input belongs to the task and native connection, outside program processes. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. A final tool error after successful dispatch starts cleanup of that invocation’s input owner. The original tool error can return while native release is pending. Any cleanup failure is reported separately. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup.
|
||||
Each Agent uses its own native input connection across programs and turns. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. A final tool error after successful dispatch starts cleanup of that invocation’s input owner. The original tool error can return while native release is pending. Any cleanup failure is reported separately. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup.
|
||||
|
||||
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 })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。
|
||||
实现 `CuaBackend.heldInputState` 的提供方通过 `getHeldInputs({})` 返回当前连接的持有记录,通过 `releaseHeldInputs({})` 释放这些输入并返回结果。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。
|
||||
|
||||
持有输入属于任务和原生连接,保存在程序进程之外。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。程序执行成功后,如果最终工具结果失败,CUA 立即清理这次调用所属的输入。原工具错误可以先返回,清理失败会另行报告。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。
|
||||
每个 Agent 使用独立的原生输入连接,多个程序和回合可以复用这条连接。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。程序执行成功后,如果最终工具结果失败,CUA 立即清理这次调用所属的输入。原工具错误可以先返回,清理失败会另行报告。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。
|
||||
|
||||
[授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_<sha256>.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ class InputOwner {
|
||||
private notifySessionOnRelease = false
|
||||
closing: Promise<z.infer<typeof heldInputs>> | undefined
|
||||
|
||||
constructor(readonly agent: Agent, private readonly failed: (error: unknown) => void,
|
||||
constructor(private readonly failed: (error: unknown) => void,
|
||||
private readonly released: (inputs: z.infer<typeof heldInputs>) => void) {}
|
||||
|
||||
track(client: NativeClient, inTurn: boolean): void {
|
||||
@@ -44,7 +44,7 @@ class InputOwner {
|
||||
|
||||
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))
|
||||
const inputs = heldInputs.parse(await this.client.request('getHeldInputs', {}, this.controller.signal))
|
||||
if (inputs.length === 0) {
|
||||
this.removeCleanup?.()
|
||||
this.removeCleanup = undefined
|
||||
@@ -61,7 +61,7 @@ class InputOwner {
|
||||
try {
|
||||
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')
|
||||
const released = heldInputs.parse(await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id }))
|
||||
const released = heldInputs.parse(await this.client.requestCleanup('releaseHeldInputs', {}))
|
||||
if (this.notifySessionOnRelease) this.released(released)
|
||||
return released
|
||||
} catch (error) {
|
||||
@@ -103,7 +103,7 @@ export class CuaHeldInputs {
|
||||
'CUA cleanup was not confirmed. All CUA operations are disabled for this task; inspect the desktop manually before starting a new task', { cause: this.failures.get(agent) })
|
||||
const current = this.owners.get(agent)
|
||||
if (current && !current.closing) return current
|
||||
const owner = new InputOwner(agent, (error) => {
|
||||
const owner = new InputOwner((error) => {
|
||||
this.failures.set(agent, error)
|
||||
this.ctx.logger.error('CUA cleanup was not confirmed; all CUA operations are disabled for task %s: %s', agent.id, error)
|
||||
emitAgentEvent(this.ctx, agent, 'agent/error', { turn: this.ctx.agents.turnBoundaryOf(agent.session).lastTurn, step: 0, error })
|
||||
|
||||
@@ -200,7 +200,7 @@ export interface CuaBackend {
|
||||
capabilities: CuaStartupCapabilities
|
||||
/** Preserve discovery PIDs when getApp accepts a decimal PID as an exact process selector. */
|
||||
acceptsPidSelector?: boolean
|
||||
/** Opt in to task-owned getHeldInputs and releaseHeldInputs; omission preserves the provider's existing protocol. */
|
||||
/** Opt in to connection-scoped getHeldInputs and releaseHeldInputs; omission preserves the provider's existing protocol. */
|
||||
heldInputState?: boolean
|
||||
/** Registers a window read. The returned receipt handler sees the native reply only after Host decoding succeeds. */
|
||||
windowRead?: (read: CuaWindowRead) => (reply: JsonValue) => void
|
||||
@@ -304,12 +304,9 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend)
|
||||
// Earlier helpers accept an explicit false only for mouseMove.
|
||||
if (method !== 'mouseMove' && !useSystemInput) delete params.useSystemInput
|
||||
else if (useSystemInput !== undefined) params.useSystemInput = useSystemInput
|
||||
if (heldInputs && (method === 'sendKeyEvent' || method === 'toggleMouse' || (method === 'mouseMove' && useSystemInput))) {
|
||||
if (heldInputs && (method === 'sendKeyEvent' || method === 'toggleMouse') && params.direction === 'down') {
|
||||
const owner = await heldInputs.ready(agent)
|
||||
if (method !== 'mouseMove' && params.direction === 'down') {
|
||||
owner.track(client, ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null)
|
||||
}
|
||||
params.taskId = agent.id
|
||||
owner.track(client, ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null)
|
||||
}
|
||||
const nativeParams = method === 'findApps'
|
||||
? { ...params, maxAppMatches: config.maxAppMatches }
|
||||
|
||||
@@ -116,12 +116,13 @@ export const NativeResourceParameters = {
|
||||
}).strict(),
|
||||
findApps: z.object({ maxAppMatches: z.number().int().min(1).max(1000) }).strict(),
|
||||
}
|
||||
/** Host-only launch continuation and user-facing system permission controls; absent from model arguments. */
|
||||
/** Host-only launch, permission, and held-input operations; absent from model arguments. */
|
||||
export const NativeOnlyOperations = [
|
||||
operation('launchApp', app), operation('permissionStatus', {}),
|
||||
operation('applicationIcons', { paths: z.array(z.string().min(1)) }),
|
||||
operation('requestPermission', { permission: z.enum(['accessibility', 'screenRecording']) }),
|
||||
operation('openPermissionSettings', { permission: z.enum(['accessibility', 'screenRecording']) }),
|
||||
operation('getHeldInputs', {}), operation('releaseHeldInputs', {}),
|
||||
] as const
|
||||
|
||||
/** Application selection returned only after a successful app selection. */
|
||||
|
||||
@@ -495,6 +495,7 @@ it('a late policy refusal closes only the owner captured by that execution', asy
|
||||
})
|
||||
const running = f.run()
|
||||
await entered.promise
|
||||
const openedChannels = f.native.state.openedChannels
|
||||
const execute = (id: string, code: string) => f.ctx.agents.withInitiator(f.agent, () => f.ctx.tools.execute({
|
||||
agent: f.agent, signal: new AbortController().signal,
|
||||
calls: [{ type: 'tool-call', id: brandString<ToolCallId>(id), name: 'cua_run_code', arguments: JSON.stringify({ code, description: id }) }],
|
||||
@@ -508,6 +509,7 @@ it('a late policy refusal closes only the owner captured by that execution', asy
|
||||
} finally { finish.resolve(); await running }
|
||||
expect((await execute('release-d', 'await app.sendKeyEvent("d", "up")')).results[0]?.result.isError).toBe(false)
|
||||
expect(f.native.events).toEqual(['w:down', 'w:up', 'd:down', 'd:up'])
|
||||
expect(f.native.state.openedChannels).toBe(openedChannels)
|
||||
expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs')).toHaveLength(1)
|
||||
})
|
||||
|
||||
|
||||
@@ -135,10 +135,10 @@ function createApplicationState(socket, record, application, captureBroker, conn
|
||||
function refuse(code, message) { throw Object.assign(new Error(message), { code }) }
|
||||
function call(requestId, method, params) {
|
||||
record('call', { requestId, method, params })
|
||||
if (method === 'getHeldInputs') return [...heldInputs.get(params.taskId)?.values() ?? []]
|
||||
if (method === 'getHeldInputs') return [...heldInputs.values()]
|
||||
if (method === 'releaseHeldInputs') {
|
||||
const released = [...heldInputs.get(params.taskId)?.values() ?? []].reverse()
|
||||
heldInputs.delete(params.taskId)
|
||||
const released = [...heldInputs.values()].reverse()
|
||||
heldInputs.clear()
|
||||
return released
|
||||
}
|
||||
if (method === 'applicationIcons') return Object.fromEntries(params.paths.map(path => [path, `data:image/png;base64,${png}`]))
|
||||
@@ -289,14 +289,12 @@ function createApplicationState(socket, record, application, captureBroker, conn
|
||||
return { dispatched: true }
|
||||
}
|
||||
if (method === 'sendKeyEvent' || method === 'toggleMouse') {
|
||||
const held = heldInputs.get(params.taskId) ?? new Map()
|
||||
const input = method === 'sendKeyEvent'
|
||||
? { kind: 'key', key: params.key, appHandle: params.appHandle, mode: params.useSystemInput ? 'system' : 'application' }
|
||||
: { kind: 'mouse', button: params.mouseButton, appHandle: params.appHandle, windowId: params.windowId, mode: params.useSystemInput ? 'system' : 'window' }
|
||||
const id = JSON.stringify([params.appHandle, params.windowId, method, params.key ?? params.mouseButton])
|
||||
if (params.direction === 'down') held.set(id, input)
|
||||
else if (!held.delete(id)) refuse('INVALID_ARGUMENT', 'Input was not held by this task')
|
||||
heldInputs.set(params.taskId, held)
|
||||
if (params.direction === 'down') heldInputs.set(id, input)
|
||||
else if (!heldInputs.delete(id)) refuse('INVALID_ARGUMENT', 'Input was not held by this connection')
|
||||
return { dispatched: true }
|
||||
}
|
||||
if (method === 'typeText') application.value += params.text
|
||||
|
||||
@@ -12,7 +12,7 @@ export function createNativeFixture(selectorPid?: number): {
|
||||
createChannel: NativeChannelFactory
|
||||
calls: Array<{ id: string; method: string; params: Record<string, JsonValue> }>
|
||||
events: string[]
|
||||
held: Array<{ connection: number; taskId: string; key: string }>
|
||||
held: Array<{ connection: number; key: string }>
|
||||
/** Control one native reply or cancellation acknowledgement at a deterministic barrier. */
|
||||
controlNext(method: string, options?: { afterDispatch?: boolean; waitForCancellation?: boolean }): {
|
||||
entered: Promise<void>
|
||||
|
||||
@@ -27,7 +27,7 @@ export function createNativeFixture(selectorPid) {
|
||||
let blocked
|
||||
let heldCallId
|
||||
function dispatch(method, params) {
|
||||
if (method === 'getHeldInputs') return held.filter(press => press.connection === connection && press.taskId === params.taskId).map(press => press.kind === 'key'
|
||||
if (method === 'getHeldInputs') return held.filter(press => press.connection === connection).map(press => press.kind === 'key'
|
||||
? { kind: 'key', key: press.key, appHandle: press.appHandle, ...press.windowId === undefined
|
||||
? { mode: 'application' } : { windowId: press.windowId, mode: 'system' } }
|
||||
: { kind: 'mouse', button: press.key, appHandle: press.appHandle, windowId: press.windowId, mode: press.mode })
|
||||
@@ -35,7 +35,7 @@ export function createNativeFixture(selectorPid) {
|
||||
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) {
|
||||
if (press.connection === connection) {
|
||||
events.push(`${press.key}:up`)
|
||||
held.splice(index, 1)
|
||||
}
|
||||
@@ -55,11 +55,11 @@ export function createNativeFixture(selectorPid) {
|
||||
if (!acquired || params.appHandle !== 'fixture-app') throw new Error('Acquire the application before using its handle')
|
||||
if (method === 'sendKeyEvent' || method === 'toggleMouse') {
|
||||
const key = params.key ?? params.mouseButton
|
||||
const index = held.findIndex(press => press.connection === connection && press.taskId === params.taskId && press.key === key)
|
||||
if (params.direction === 'down' && index < 0) held.push({ connection, taskId: params.taskId, key, appHandle: params.appHandle,
|
||||
const index = held.findIndex(press => press.connection === connection && press.key === key)
|
||||
if (params.direction === 'down' && index < 0) held.push({ connection, key, appHandle: params.appHandle,
|
||||
kind: method === 'sendKeyEvent' ? 'key' : 'mouse', windowId: params.windowId, mode: params.useSystemInput ? 'system' : 'window' })
|
||||
if (params.direction === 'up') {
|
||||
if (index < 0) throw new Error('Input was not held by this task')
|
||||
if (index < 0) throw new Error('Input was not held by this connection')
|
||||
held.splice(index, 1)
|
||||
}
|
||||
events.push(`${key}:${params.direction}`)
|
||||
|
||||
Reference in new issue
Block a user