diff --git a/packages/computer-use/cua/README.i18n.yaml b/packages/computer-use/cua/README.i18n.yaml index 660daba2b5..1fb3f595ee 100644 --- a/packages/computer-use/cua/README.i18n.yaml +++ b/packages/computer-use/cua/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 7b30b973a849247d /deepseek-ai-dsh-cua/use-this-package: - en: 7cb6848d7ccd7132 - zh: 48900d1231f97bb6 + en: 494643109e1ede83 + zh: 39e603abb26ed601 /deepseek-ai-dsh-cua/use-this-package/connect-an-external-execution-environment: - en: 2cdaaca90c5c78f7 - zh: bcdbf54da0353d9a + en: d4636ec68878d60a + zh: f37e82c5194f4c0d /deepseek-ai-dsh-cua/understand-the-implementation: en: ee9fd0ddf93d496d zh: 38d8d5f8b58e6f50 diff --git a/packages/computer-use/cua/README.md b/packages/computer-use/cua/README.md index 93ee40e208..d166af32b6 100644 --- a/packages/computer-use/cua/README.md +++ b/packages/computer-use/cua/README.md @@ -50,7 +50,7 @@ The dump command checks profile composition without a model request. For a real The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-cua) lists all fields. Native tool calls use `{method, params}`; the complete method-specific schema is exposed to the model. For example, `getApp` returns the `appHandle` needed by `listWindows`, `getState` and input operations. -Key chords use `+` between modifiers and the key. Use `+` for the plus key, `cmd++` for Command-plus, or the key name `plus`; an unfinished chord such as `cmd+` is rejected. +Keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. Key chords use `+` between modifiers and the key. Use `+` for the plus key, `cmd++` for Command-plus, or the key name `plus`; an unfinished chord such as `cmd+` is rejected. Agent disposal and plugin unload cancel and await the complete tool call, including image admission and attachment storage. An image write already in progress must settle before disposal returns; a canceled call cannot return a successful screenshot. @@ -83,7 +83,7 @@ Retained objects resolve the current tool binding on every call. The external ru AppKit sheets are selectable by their window IDs and remain visible in their document window’s tree. Keyboard input follows a system Open/Save panel only when the application’s focused sheet identifies one Apple panel-service window and that service still focuses the same panel. Unrelated or ambiguous remote recipients fail before dispatch. -Indexed clicks support a single right click or a single/double left click. The helper uses an advertised accessibility action when available; pointer delivery resolves the element’s current bounds and verifies its owning window. Actions report dispatch, not application success. A visual pointer or click marker can be rendered independently of input; AX actions do not require moving the system cursor. Window-directed mouse input can still change application focus, selection or dialogs. Read state after input. `STALE_APP` requires acquiring the application again; `STALE_SNAPSHOT` requires a fresh AX read. Transport timeout/cancellation terminates that Agent’s helper and invalidates its handles. Never retry uncertain input automatically. Closing an Agent releases its helper and AX references, without undoing changes to applications. +Indexed clicks support a single right/middle click or a single/double left click. Click and drag options accept a button and modifier keys; a modified click uses pointer input. Drags hold that button and carry its modifiers through every movement and release. AX text marks disabled controls, `valueWritable=true`, and available `selected` state. The helper uses an advertised accessibility action for unmodified clicks when available; pointer delivery resolves the element’s current bounds and verifies its owning window. Actions report dispatch, not application success. A visual pointer or click marker can be rendered independently of input; AX actions do not require moving the system cursor. Window-directed mouse input can still change application focus, selection or dialogs. Read state after input. `STALE_APP` requires acquiring the application again; `STALE_SNAPSHOT` requires a fresh AX read. Transport timeout/cancellation terminates that Agent’s helper and invalidates its handles. Never retry uncertain input automatically. Closing an Agent releases its helper and AX references, without undoing changes to applications. ----- @@ -126,7 +126,7 @@ The plugin contributes one `cua` operation tool with method-specific parameters. ```markdown Use cua with method getCapabilities and params {} to inspect permissions and sessionLocked. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI attempts and ask the user to unlock macOS. A null sessionLocked means no usable console session was verified. After unlocking, read fresh state; screenshots from a locked desktop are not current observations. Use listApps and getApp to select an already running application. getApp requests user consent before application observations or input. If access is denied or revoked, stop using that application until the user explicitly grants access again. Never switch tools to bypass a refusal. Keep the returned appHandle; every app operation requires it. listWindows returns window IDs and point bounds. getState returns a complete AX tree and snapshotId. Use its element indices only with that snapshotId. Raw screenshot and coordinate operations require a windowId. Coordinates are window-local macOS points, which may differ from screenshot pixels. A verified window can expose no AX elements. Its empty snapshot permits screenshots and coordinate input; element-index actions require an element from a fresh AX observation. -Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. +Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text marks disabled controls, writable values and available selection state. Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. @@ -146,17 +146,17 @@ App and Window methods: - getAXState(options?: { emit?: boolean, disableDiffing?: boolean }) -> string - getScreenshot(options?: { emit?: boolean }) -> Uint8Array - getAXStateAndScreenshot(options?) -> { state: string, screenshot: Uint8Array } -- click(target: number | [x, y], options?: { mouseButton?: "left" | "right", clickCount?: 1 | 2 }) -> action result +- click(target: number | [x, y], options?: { mouseButton?: "left" | "right" | "middle", clickCount?: 1 | 2, modifiers?: Array<"command" | "control" | "option" | "shift" | "fn"> }) -> action result - setValue(elementIndex: number, value: string) -> action result - performSecondaryAction(elementIndex: number, action: string) -> action result - scroll({ x, y, deltaLinesX, deltaLinesY }) -> action result -- drag(from: [x, y], to: [x, y]) -> action result +- drag(from: [x, y], to: [x, y], options?: { mouseButton?: "left" | "right" | "middle", modifiers?: Array<"command" | "control" | "option" | "shift" | "fn"> }) -> action result Raw operation tools use { method, params }, including params: {} for parameterless methods. getApp selects without activating the app. Keep applications in the background for observation and routine input. Do not activate or raise an app during initialization, before each action, or merely because another app is foreground. Prefer advertised AX actions. If a hidden window, another Space or Stage Manager prevents usable observation, explain the foreground-dependent step before app.activate() or an advertised raise action, then read fresh state. Avoid repeated activation when the user switches away; continue background-capable steps and report what requires foreground access. Applications may still change focus in response to input. Await operations sequentially. After input, read fresh state to verify the effect. A successful action means dispatched, not verified completion. Cancellation may leave partial effects; never retry uncertain input without observing. STALE_APP requires getApp again; STALE_SNAPSHOT requires getState again. WINDOW_CHANGED requires fresh state before any retry; use an advertised AX action or explicitly restore the window before screenshot or coordinate input, then observe again. PERMISSION_DENIED requires the user to grant macOS Accessibility or Screen Recording access in System Settings. After granting access, observe fresh state before continuing; do not automatically replay prior input. -Window objects expose observation and pointer/AX actions; keyboard input remains app-scoped and follows current focus. Scroll deltas are integer lines from -10 to 10; positive values reveal content above or left. Paste inserts plain text using native Unicode input without changing the clipboard; rich-text formats are unavailable. Browser applications can be controlled with getApp like other native apps; browser tabs and app launching are unavailable. The execution host must install the object API and own variable persistence; this plugin does not preload a cua global. In persistent PTC, use the host-provided initialization snippet below once. Its installation-owned file URL works independently of the project directory. Retain app objects between calls. End screenshot calls with void await app.getScreenshot() or void await app.getAXStateAndScreenshot() so image bytes are not serialized as the program completion value. +Left clicks support single/double clicks; right and middle clicks support single clicks. Modified clicks use pointer input. Keypad names such as KP_0 and KP_Enter retain their physical key identity. Window objects expose observation and pointer/AX actions; keyboard input remains app-scoped and follows current focus. Scroll deltas are integer lines from -10 to 10; positive values reveal content above or left. Paste inserts plain text using native Unicode input without changing the clipboard; rich-text formats are unavailable. Browser applications can be controlled with getApp like other native apps; browser tabs and app launching are unavailable. The execution host must install the object API and own variable persistence; this plugin does not preload a cua global. In persistent PTC, use the host-provided initialization snippet below once. Its installation-owned file URL works independently of the project directory. Retain app objects between calls. End screenshot calls with void await app.getScreenshot() or void await app.getAXStateAndScreenshot() so image bytes are not serialized as the program completion value. ``` #### Token effect diff --git a/packages/computer-use/cua/README.zh.md b/packages/computer-use/cua/README.zh.md index ad2bf51c22..7ce116e24c 100644 --- a/packages/computer-use/cua/README.zh.md +++ b/packages/computer-use/cua/README.zh.md @@ -50,7 +50,7 @@ pnpm dsh headless --patch packages/computer-use/cua/examples/macos.cordis.yml -- [配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-cua)列出全部字段。原生工具调用使用 `{method, params}`,模型可以看到每个方法的完整参数定义。例如,`getApp` 返回 `listWindows`、`getState` 和输入操作所需的 `appHandle`。 -组合键用 `+` 分隔修饰键与按键。加号键写作 `+`,Command 加号写作 `cmd++`,也可以使用键名 `plus`;`cmd+` 这类缺少按键的输入会被拒绝。 +数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。组合键用 `+` 分隔修饰键与按键。加号键写作 `+`,Command 加号写作 `cmd++`,也可以使用键名 `plus`;`cmd+` 这类缺少按键的输入会被拒绝。 Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。 @@ -83,7 +83,7 @@ void await app.getScreenshot() AppKit sheet 可以通过其窗口 ID 单独选择,也会出现在所属文档窗口的控件树中。只有应用当前获得焦点的 sheet 指向唯一的 Apple 面板服务窗口,且该服务仍聚焦于同一面板时,键盘输入才转交系统打开或保存面板。无法确认或存在歧义的远端接收方会在输入前报错。 -元素索引支持右键单击以及左键单击、双击。辅助进程优先使用元素声明的辅助功能动作;需要发送鼠标事件时,会重新读取元素位置并核实所属窗口。动作返回只表示输入已分派。可视指针或点击标记可以独立绘制;AX 动作无需移动系统指针。窗口定向鼠标输入仍可能改变应用焦点、选区或对话框。输入后需要读取状态确认结果。`STALE_APP` 需要重新获取应用,`STALE_SNAPSHOT` 需要重新读取 AX。通信超时或取消会终止该 Agent 的辅助进程,使已有句柄失效。不能自动重试结果不确定的输入。关闭 Agent 会释放辅助进程和 AX 引用,但不会撤销应用中的修改。 +元素索引支持右键或中键单击以及左键单击、双击。点击和拖动选项可指定按键与修饰键;带修饰键的点击使用指针输入。拖动期间保持指定按键,并在移动和释放事件中携带修饰键。AX 文本标明禁用控件、`valueWritable=true` 和可读取的 `selected` 状态。不带修饰键的点击优先使用元素声明的辅助功能动作;需要发送鼠标事件时,会重新读取元素位置并核实所属窗口。动作返回只表示输入已分派。可视指针或点击标记可以独立绘制;AX 动作无需移动系统指针。窗口定向鼠标输入仍可能改变应用焦点、选区或对话框。输入后需要读取状态确认结果。`STALE_APP` 需要重新获取应用,`STALE_SNAPSHOT` 需要重新读取 AX。通信超时或取消会终止该 Agent 的辅助进程,使已有句柄失效。不能自动重试结果不确定的输入。关闭 Agent 会释放辅助进程和 AX 引用,但不会撤销应用中的修改。 ----- @@ -126,7 +126,7 @@ AppKit sheet 可以通过其窗口 ID 单独选择,也会出现在所属文档 ```markdown Use cua with method getCapabilities and params {} to inspect permissions and sessionLocked. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI attempts and ask the user to unlock macOS. A null sessionLocked means no usable console session was verified. After unlocking, read fresh state; screenshots from a locked desktop are not current observations. Use listApps and getApp to select an already running application. getApp requests user consent before application observations or input. If access is denied or revoked, stop using that application until the user explicitly grants access again. Never switch tools to bypass a refusal. Keep the returned appHandle; every app operation requires it. listWindows returns window IDs and point bounds. getState returns a complete AX tree and snapshotId. Use its element indices only with that snapshotId. Raw screenshot and coordinate operations require a windowId. Coordinates are window-local macOS points, which may differ from screenshot pixels. A verified window can expose no AX elements. Its empty snapshot permits screenshots and coordinate input; element-index actions require an element from a fresh AX observation. -Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. +Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text marks disabled controls, writable values and available selection state. Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. @@ -146,17 +146,17 @@ App and Window methods: - getAXState(options?: { emit?: boolean, disableDiffing?: boolean }) -> string - getScreenshot(options?: { emit?: boolean }) -> Uint8Array - getAXStateAndScreenshot(options?) -> { state: string, screenshot: Uint8Array } -- click(target: number | [x, y], options?: { mouseButton?: "left" | "right", clickCount?: 1 | 2 }) -> action result +- click(target: number | [x, y], options?: { mouseButton?: "left" | "right" | "middle", clickCount?: 1 | 2, modifiers?: Array<"command" | "control" | "option" | "shift" | "fn"> }) -> action result - setValue(elementIndex: number, value: string) -> action result - performSecondaryAction(elementIndex: number, action: string) -> action result - scroll({ x, y, deltaLinesX, deltaLinesY }) -> action result -- drag(from: [x, y], to: [x, y]) -> action result +- drag(from: [x, y], to: [x, y], options?: { mouseButton?: "left" | "right" | "middle", modifiers?: Array<"command" | "control" | "option" | "shift" | "fn"> }) -> action result Raw operation tools use { method, params }, including params: {} for parameterless methods. getApp selects without activating the app. Keep applications in the background for observation and routine input. Do not activate or raise an app during initialization, before each action, or merely because another app is foreground. Prefer advertised AX actions. If a hidden window, another Space or Stage Manager prevents usable observation, explain the foreground-dependent step before app.activate() or an advertised raise action, then read fresh state. Avoid repeated activation when the user switches away; continue background-capable steps and report what requires foreground access. Applications may still change focus in response to input. Await operations sequentially. After input, read fresh state to verify the effect. A successful action means dispatched, not verified completion. Cancellation may leave partial effects; never retry uncertain input without observing. STALE_APP requires getApp again; STALE_SNAPSHOT requires getState again. WINDOW_CHANGED requires fresh state before any retry; use an advertised AX action or explicitly restore the window before screenshot or coordinate input, then observe again. PERMISSION_DENIED requires the user to grant macOS Accessibility or Screen Recording access in System Settings. After granting access, observe fresh state before continuing; do not automatically replay prior input. -Window objects expose observation and pointer/AX actions; keyboard input remains app-scoped and follows current focus. Scroll deltas are integer lines from -10 to 10; positive values reveal content above or left. Paste inserts plain text using native Unicode input without changing the clipboard; rich-text formats are unavailable. Browser applications can be controlled with getApp like other native apps; browser tabs and app launching are unavailable. The execution host must install the object API and own variable persistence; this plugin does not preload a cua global. In persistent PTC, use the host-provided initialization snippet below once. Its installation-owned file URL works independently of the project directory. Retain app objects between calls. End screenshot calls with void await app.getScreenshot() or void await app.getAXStateAndScreenshot() so image bytes are not serialized as the program completion value. +Left clicks support single/double clicks; right and middle clicks support single clicks. Modified clicks use pointer input. Keypad names such as KP_0 and KP_Enter retain their physical key identity. Window objects expose observation and pointer/AX actions; keyboard input remains app-scoped and follows current focus. Scroll deltas are integer lines from -10 to 10; positive values reveal content above or left. Paste inserts plain text using native Unicode input without changing the clipboard; rich-text formats are unavailable. Browser applications can be controlled with getApp like other native apps; browser tabs and app launching are unavailable. The execution host must install the object API and own variable persistence; this plugin does not preload a cua global. In persistent PTC, use the host-provided initialization snippet below once. Its installation-owned file URL works independently of the project directory. Retain app objects between calls. End screenshot calls with void await app.getScreenshot() or void await app.getAXStateAndScreenshot() so image bytes are not serialized as the program completion value. ``` #### Token 影响 diff --git a/packages/computer-use/cua/native/Sources/CuaNative/AXAccess.swift b/packages/computer-use/cua/native/Sources/CuaNative/AXAccess.swift index 4091d2f754..6bb7bb3f1b 100644 --- a/packages/computer-use/cua/native/Sources/CuaNative/AXAccess.swift +++ b/packages/computer-use/cua/native/Sources/CuaNative/AXAccess.swift @@ -50,7 +50,7 @@ final class AXAccess { // and accessibility children remain readable. guard error == .failure else { return false } let optional: Set = ["AXValue", "AXTitle", "AXDescription", "AXIdentifier", "AXPlaceholderValue", - "AXSubrole", "AXEnabled", "AXPosition", "AXSize", "AXMain", "AXMinimized"] + "AXSubrole", "AXEnabled", "AXSelected", "AXPosition", "AXSize", "AXMain", "AXMinimized"] return optional.contains(attribute) } static func actionsUnavailable(_ error: AXError) -> Bool { @@ -189,7 +189,7 @@ final class AXAccess { private func metadata(_ element: AXUIElement) throws -> [String: CFTypeRef]? { try prepare(element) let names = ["AXRole", "AXTitle", "AXValue", "AXPlaceholderValue", "AXDescription", "AXEnabled", - "AXIdentifier", "AXPosition", "AXSize", "AXChildren"] + "AXIdentifier", "AXPosition", "AXSize", "AXChildren", "AXSelected"] var output: CFArray? let error = AXUIElementCopyMultipleAttributeValues(element, names as CFArray, [], &output) if error == .notImplemented || error == .attributeUnsupported { return nil } @@ -328,6 +328,7 @@ final class AXAccess { if valueRoles.contains(role) { valueWritable = try writable(element, "AXValue") } else { valueWritable = false } let enabled = try booleanValue(observed("AXEnabled"), attribute: "AXEnabled") + let selected = try booleanValue(observed("AXSelected"), attribute: "AXSelected") let addressable = enabled != false && (!actionNames.isEmpty || valueWritable) let meaningful = [title, value, description].contains { !($0?.isEmpty ?? true) } if !addressable && !meaningful && role != "AXWindow" && role != "AXSheet" { @@ -338,6 +339,9 @@ final class AXAccess { var line = String(repeating: " ", count: level) + "- " if let index { indexed[index] = element; line += "[\(index)] " } line += role + if enabled == false { line += " disabled" } + if valueWritable { line += " valueWritable=true" } + if let selected { line += " selected=\(selected)" } if let title, !title.isEmpty { line += " \(String(reflecting: title))" } if let value, !value.isEmpty { line += " = \(String(reflecting: value))" } if let description, !description.isEmpty { line += " (\(description))" } @@ -353,6 +357,7 @@ final class AXAccess { "value": value.map(JSONValue.string) ?? .null, "description": description.map(JSONValue.string) ?? .null, "identifier": try stringValue(observed("AXIdentifier"), attribute: "AXIdentifier").map(JSONValue.string) ?? .null, "bounds": frameJSON, "actions": .array(actionNames.map(JSONValue.string)), "enabled": enabled.map(JSONValue.bool) ?? .null, + "valueWritable": .bool(valueWritable), "selected": selected.map(JSONValue.bool) ?? .null, ])) } for child in try childValues(observed("AXChildren"), attribute: "AXChildren") { try walk(child, level: level + 1, depth: depth + 1) } diff --git a/packages/computer-use/cua/native/Sources/CuaNative/AXWorker.swift b/packages/computer-use/cua/native/Sources/CuaNative/AXWorker.swift index cec897f5f2..b25985c421 100644 --- a/packages/computer-use/cua/native/Sources/CuaNative/AXWorker.swift +++ b/packages/computer-use/cua/native/Sources/CuaNative/AXWorker.swift @@ -246,12 +246,13 @@ actor AXWorker { case "click": let button = try params.optionalString("mouseButton") ?? "left" let count = params.contains("clickCount") ? try params.integer("clickCount", in: 1...2) : 1 - guard button == "left" || (button == "right" && count == 1) else { throw RequestParameters.invalid("Unsupported mouse button or click count") } + guard button == "left" || (["right", "middle"].contains(button) && count == 1) else { throw RequestParameters.invalid("Unsupported mouse button or click count") } + let modifiers = try params.modifiers() if params.contains("elementIndex") { guard !params.contains("x"), !params.contains("y"), !params.contains("windowId") else { throw RequestParameters.invalid("Element and coordinate targets cannot be combined") } let selected = try element(handle, params) let names = try ax().actions(selected) - let action: String? = button == "right" && names.contains("AXShowMenu") ? "AXShowMenu" + let action: String? = !modifiers.isEmpty ? nil : button == "right" && names.contains("AXShowMenu") ? "AXShowMenu" : (button == "left" && count == 1 ? (names.contains("AXPress") ? "AXPress" : names.contains("AXPick") ? "AXPick" : nil) : nil) if let action { try ax().perform(selected, action) } else { @@ -259,13 +260,13 @@ actor AXWorker { guard let bounds = try ax().bounds(selected), bounds.width > 0, bounds.height > 0 else { throw NativeFailure(code: "NATIVE_ERROR", message: "Element has no pointer bounds") } let window = try ax().enclosingWindow(selected, owner: identity) let point = WindowPoint(x: bounds.x + bounds.width / 2 - window.bounds.x, y: bounds.y + bounds.height / 2 - window.bounds.y) - try inputs().1.click(in: WindowRoute(owner: identity, windowID: window.windowID, bounds: window.bounds), at: point, button: button, count: count) + try inputs().1.click(in: WindowRoute(owner: identity, windowID: window.windowID, bounds: window.bounds), at: point, button: button, count: count, modifiers: modifiers) } } else { let id = try params.windowID() try coordinateSnapshot(handle, params, id) let window = try coordinateWindow(identity, id) - try inputs().1.click(in: WindowRoute(owner: identity, windowID: id, bounds: window.bounds), at: params.point(), button: button, count: count) + try inputs().1.click(in: WindowRoute(owner: identity, windowID: id, bounds: window.bounds), at: params.point(), button: button, count: count, modifiers: modifiers) } case "scroll", "drag": let id = try params.windowID() @@ -278,7 +279,8 @@ actor AXWorker { try inputs().1.scroll(in: route, at: params.point(), deltaLinesX: Int32(dx), deltaLinesY: Int32(dy)) } else { try inputs().1.drag(in: route, from: params.point("fromX", "fromY"), to: params.point("toX", "toY"), - durationMs: params.integer("durationMs", in: 1...5000), steps: params.integer("steps", in: 1...240)) + durationMs: params.integer("durationMs", in: 1...5000), steps: params.integer("steps", in: 1...240), + button: params.optionalString("mouseButton") ?? "left", modifiers: params.modifiers()) } default: throw NativeFailure(code: "UNSUPPORTED", message: method) } diff --git a/packages/computer-use/cua/native/Sources/CuaNative/KeyboardInput.swift b/packages/computer-use/cua/native/Sources/CuaNative/KeyboardInput.swift index a4715c0859..be75257f1c 100644 --- a/packages/computer-use/cua/native/Sources/CuaNative/KeyboardInput.swift +++ b/packages/computer-use/cua/native/Sources/CuaNative/KeyboardInput.swift @@ -150,8 +150,31 @@ final class KeyboardInput { } } - private static func keyCode(_ key: String) throws -> CGKeyCode { + static func modifierFlags(_ names: [String]) throws -> CGEventFlags { + try names.reduce(into: CGEventFlags()) { flags, name in flags.formUnion(try modifier(name).flag) } + } + + static func keyCode(_ key: String) throws -> CGKeyCode { switch key.lowercased() { + case "kp_0": return 82 + case "kp_1": return 83 + case "kp_2": return 84 + case "kp_3": return 85 + case "kp_4": return 86 + case "kp_5": return 87 + case "kp_6": return 88 + case "kp_7": return 89 + case "kp_8": return 91 + case "kp_9": return 92 + case "kp_decimal": return 65 + case "kp_separator": return 95 + case "kp_multiply": return 67 + case "kp_add": return 69 + case "kp_clear": return 71 + case "kp_divide": return 75 + case "kp_enter": return 76 + case "kp_subtract": return 78 + case "kp_equal": return 81 case "return", "enter": return 36 case "tab": return 48 case "space": return 49 diff --git a/packages/computer-use/cua/native/Sources/CuaNative/RequestAdmission.swift b/packages/computer-use/cua/native/Sources/CuaNative/RequestAdmission.swift index 95caf85985..eafccec007 100644 --- a/packages/computer-use/cua/native/Sources/CuaNative/RequestAdmission.swift +++ b/packages/computer-use/cua/native/Sources/CuaNative/RequestAdmission.swift @@ -6,12 +6,12 @@ struct RequestParameters: Sendable { "getCapabilities": [], "listApps": [], "getApp": ["selector"], "listWindows": ["appHandle"], "activate": ["appHandle"], "getState": ["appHandle", "windowId", "maxElements", "maxDepth"], - "click": ["appHandle", "snapshotId", "elementIndex", "windowId", "x", "y", "mouseButton", "clickCount"], + "click": ["appHandle", "snapshotId", "elementIndex", "windowId", "x", "y", "mouseButton", "clickCount", "modifiers"], "setValue": ["appHandle", "snapshotId", "elementIndex", "value"], "performSecondaryAction": ["appHandle", "snapshotId", "elementIndex", "action"], "typeText": ["appHandle", "text"], "pressKey": ["appHandle", "key", "modifiers"], "scroll": ["appHandle", "windowId", "snapshotId", "x", "y", "deltaLinesX", "deltaLinesY"], - "drag": ["appHandle", "windowId", "snapshotId", "fromX", "fromY", "toX", "toY", "durationMs", "steps"], + "drag": ["appHandle", "windowId", "snapshotId", "fromX", "fromY", "toX", "toY", "durationMs", "steps", "mouseButton", "modifiers"], "screenshot": ["appHandle", "windowId"], ] let values: [String: JSONValue] diff --git a/packages/computer-use/cua/native/Sources/CuaNative/WindowPointerInput.swift b/packages/computer-use/cua/native/Sources/CuaNative/WindowPointerInput.swift index c410a70eef..af3231fda6 100644 --- a/packages/computer-use/cua/native/Sources/CuaNative/WindowPointerInput.swift +++ b/packages/computer-use/cua/native/Sources/CuaNative/WindowPointerInput.swift @@ -28,32 +28,34 @@ final class WindowPointerInput { Double(durationMs) / Double(steps) / 1000 } - /// Post one or two left clicks, or one right click, with a shared window-routing group. - func click(in route: WindowRoute, at point: WindowPoint, button: String, count: Int) throws { + /// Post one or two left clicks, or one right/middle click, with a shared window-routing group. + func click(in route: WindowRoute, at point: WindowPoint, button: String, count: Int, modifiers: [String] = []) throws { try checkCancellation() try Self.validate(point, in: route) - guard (button == "left" && (count == 1 || count == 2)) || (button == "right" && count == 1) else { + guard (button == "left" && (count == 1 || count == 2)) || (["right", "middle"].contains(button) && count == 1) else { throw NativeFailure(code: "INVALID_ARGUMENT", message: "Unsupported mouse button or click count") } let source = try Self.source() + let selectedButton = try Self.button(button) + let flags = try KeyboardInput.modifierFlags(modifiers) let group = Self.clickGroup() let screen = Self.screenPoint(point, in: route) let move = try mouseEvent( source: source, route: route, screen: screen, local: point, type: .mouseMoved, button: .left, clickState: 0, subtype: 3, - group: group, number: button == "left" ? 2 : nil + group: group, number: button == "left" ? 2 : nil, flags: flags ) if button == "left" { let outside = WindowPoint(x: -1, y: -1) let primer = try mousePair( source: source, route: route, screen: CGPoint(x: -1, y: -1), local: outside, - button: .left, clickState: 1, group: group, downNumber: 1, upNumber: 2 + button: .left, clickState: 1, group: group, downNumber: 1, upNumber: 2, flags: flags ) var pairs: [MousePair] = [] for index in 1...count { pairs.append(try mousePair( source: source, route: route, screen: screen, local: point, - button: .left, clickState: Int64(index), group: group, downNumber: 3, upNumber: 3 + button: .left, clickState: Int64(index), group: group, downNumber: 3, upNumber: 3, flags: flags )) } try checkCancellation() @@ -69,7 +71,7 @@ final class WindowPointerInput { } else { let pair = try mousePair( source: source, route: route, screen: screen, local: point, - button: .right, clickState: 1, group: group + button: selectedButton, clickState: 1, group: group, flags: flags ) try checkCancellation() poster.post(move, to: route.owner.pid) @@ -113,9 +115,10 @@ final class WindowPointerInput { try checkCancellation() } - /// Drag the left button along an interpolated path, releasing at the last posted point on cancellation. + /// Drag the selected button along an interpolated path, releasing at the last posted point on cancellation. func drag( - in route: WindowRoute, from start: WindowPoint, to end: WindowPoint, durationMs: Int, steps: Int + in route: WindowRoute, from start: WindowPoint, to end: WindowPoint, durationMs: Int, steps: Int, + button: String = "left", modifiers: [String] = [] ) throws { try checkCancellation() try Self.validate(start, in: route) @@ -124,14 +127,16 @@ final class WindowPointerInput { throw NativeFailure(code: "INVALID_ARGUMENT", message: "Drag durationMs must be 1...5000 and steps 1...240") } let source = try Self.source() + let selectedButton = try Self.button(button) + let flags = try KeyboardInput.modifierFlags(modifiers) let group = Self.clickGroup() let down = try mouseEvent( source: source, route: route, screen: Self.screenPoint(start, in: route), local: start, - type: .leftMouseDown, button: .left, clickState: 1, subtype: 0, group: group + type: Self.down(selectedButton), button: selectedButton, clickState: 1, subtype: 0, group: group, flags: flags ) let initialRelease = try mouseEvent( source: source, route: route, screen: Self.screenPoint(start, in: route), local: start, - type: .leftMouseUp, button: .left, clickState: 1, subtype: 0, group: group + type: Self.up(selectedButton), button: selectedButton, clickState: 1, subtype: 0, group: group, flags: flags ) var path: [DragStep] = [] for index in 1...steps { @@ -144,11 +149,11 @@ final class WindowPointerInput { path.append(DragStep( movement: try mouseEvent( source: source, route: route, screen: screen, local: local, - type: .leftMouseDragged, button: .left, clickState: 1, subtype: 0, group: group + type: Self.dragged(selectedButton), button: selectedButton, clickState: 1, subtype: 0, group: group, flags: flags ), release: try mouseEvent( source: source, route: route, screen: screen, local: local, - type: .leftMouseUp, button: .left, clickState: 1, subtype: 0, group: group + type: Self.up(selectedButton), button: selectedButton, clickState: 1, subtype: 0, group: group, flags: flags ) )) } @@ -197,18 +202,18 @@ final class WindowPointerInput { private func mousePair( source: CGEventSource, route: WindowRoute, screen: CGPoint, local: WindowPoint, button: CGMouseButton, clickState: Int64, group: Int64, - downNumber: Int64? = nil, upNumber: Int64? = nil + downNumber: Int64? = nil, upNumber: Int64? = nil, flags: CGEventFlags = [] ) throws -> MousePair { try MousePair( down: mouseEvent( source: source, route: route, screen: screen, local: local, - type: button == .right ? .rightMouseDown : .leftMouseDown, - button: button, clickState: clickState, subtype: 3, group: group, number: downNumber + type: Self.down(button), + button: button, clickState: clickState, subtype: 3, group: group, number: downNumber, flags: flags ), up: mouseEvent( source: source, route: route, screen: screen, local: local, - type: button == .right ? .rightMouseUp : .leftMouseUp, - button: button, clickState: clickState, subtype: 3, group: group, number: upNumber + type: Self.up(button), + button: button, clickState: clickState, subtype: 3, group: group, number: upNumber, flags: flags ) ) } @@ -216,14 +221,14 @@ final class WindowPointerInput { private func mouseEvent( source: CGEventSource, route: WindowRoute, screen: CGPoint, local: WindowPoint, type: CGEventType, button: CGMouseButton, clickState: Int64, subtype: Int64, - group: Int64, number: Int64? = nil + group: Int64, number: Int64? = nil, flags: CGEventFlags = [] ) throws -> CGEvent { guard let event = CGEvent( mouseEventSource: source, mouseType: type, mouseCursorPosition: screen, mouseButton: button ) else { throw NativeFailure(code: "NATIVE_ERROR", message: "Could not create pointer event") } - event.flags = [] + event.flags = flags try poster.stampWindow(event, pid: route.owner.pid, windowID: route.windowID, point: local) let fields: [(UInt32, Int64)] = [(1, clickState), (3, Int64(button.rawValue)), (7, subtype), (58, group)] for (field, value) in fields { try poster.stamp(event, field: field, value: value) } @@ -231,6 +236,24 @@ final class WindowPointerInput { return event } + static func button(_ name: String) throws -> CGMouseButton { + switch name { + case "left": return .left + case "right": return .right + case "middle": return .center + default: throw NativeFailure(code: "INVALID_ARGUMENT", message: "Unsupported mouse button") + } + } + static func down(_ button: CGMouseButton) -> CGEventType { + button == .left ? .leftMouseDown : button == .right ? .rightMouseDown : .otherMouseDown + } + static func up(_ button: CGMouseButton) -> CGEventType { + button == .left ? .leftMouseUp : button == .right ? .rightMouseUp : .otherMouseUp + } + static func dragged(_ button: CGMouseButton) -> CGEventType { + button == .left ? .leftMouseDragged : button == .right ? .rightMouseDragged : .otherMouseDragged + } + private static func validate(_ point: WindowPoint, in route: WindowRoute) throws { guard point.x.isFinite, point.y.isFinite, point.x >= 0, point.y >= 0, point.x < route.bounds.width, point.y < route.bounds.height, diff --git a/packages/computer-use/cua/native/protocol.schema.json b/packages/computer-use/cua/native/protocol.schema.json index 303f952baf..0390e12188 100644 --- a/packages/computer-use/cua/native/protocol.schema.json +++ b/packages/computer-use/cua/native/protocol.schema.json @@ -178,9 +178,11 @@ "minimum": 0 }, "mouseButton": { + "type": "string", "enum": [ "left", - "right" + "right", + "middle" ] }, "clickCount": { @@ -188,6 +190,19 @@ 1, 2 ] + }, + "modifiers": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "command", + "control", + "option", + "shift", + "fn" + ] + } } }, "required": [ @@ -235,9 +250,11 @@ "type": "number" }, "mouseButton": { + "type": "string", "enum": [ "left", - "right" + "right", + "middle" ] }, "clickCount": { @@ -245,6 +262,19 @@ 1, 2 ] + }, + "modifiers": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "command", + "control", + "option", + "shift", + "fn" + ] + } } }, "required": [ @@ -512,6 +542,27 @@ "type": "integer", "minimum": 1, "maximum": 240 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "modifiers": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "command", + "control", + "option", + "shift", + "fn" + ] + } } }, "required": [ diff --git a/packages/computer-use/cua/native/tests/swift/InputMappingTests.swift b/packages/computer-use/cua/native/tests/swift/InputMappingTests.swift new file mode 100644 index 0000000000..25ca984d5a --- /dev/null +++ b/packages/computer-use/cua/native/tests/swift/InputMappingTests.swift @@ -0,0 +1,27 @@ +// Native input identities retain keypad keys and button/modifier distinctions. +import CoreGraphics +import Testing +@testable import CuaNative + +@Test(arguments: [("KP_0", 82), ("KP_1", 83), ("KP_9", 92), ("KP_Enter", 76), + ("KP_Add", 69), ("KP_Subtract", 78), ("KP_Multiply", 67), ("KP_Divide", 75), + ("KP_Decimal", 65), ("KP_Separator", 95), ("KP_Equal", 81), ("KP_Clear", 71)]) +func keypadKeysRetainTheirPhysicalIdentity(_ key: String, _ code: UInt16) throws { + #expect(try KeyboardInput.keyCode(key) == code) +} + +@Test func keypadEnterDiffersFromReturnAndKeypadZeroDiffersFromZero() throws { + #expect(try KeyboardInput.keyCode("KP_Enter") != KeyboardInput.keyCode("Return")) + #expect(try KeyboardInput.keyCode("KP_0") != KeyboardInput.keyCode("0")) + #expect(try KeyboardInput.modifierFlags(["shift", "cmd"]) == [.maskShift, .maskCommand]) + #expect(throws: NativeFailure.self) { try KeyboardInput.modifierFlags(["unsupported"]) } +} + +@Test func middleGestureRetainsItsButtonAndEventFamily() throws { + let button = try WindowPointerInput.button("middle") + #expect(button == .center) + #expect(WindowPointerInput.down(button) == .otherMouseDown) + #expect(WindowPointerInput.dragged(button) == .otherMouseDragged) + #expect(WindowPointerInput.up(button) == .otherMouseUp) + #expect(throws: NativeFailure.self) { try WindowPointerInput.button("unsupported") } +} diff --git a/packages/computer-use/cua/native/upstream.json b/packages/computer-use/cua/native/upstream.json index 96bb51f492..65a65ff42f 100644 --- a/packages/computer-use/cua/native/upstream.json +++ b/packages/computer-use/cua/native/upstream.json @@ -8,12 +8,12 @@ { "local": "Sources/CuaNative/KeyboardInput.swift", "upstream": "libs/cua-driver/rust/crates/platform-macos/src/input/keyboard.rs", - "changes": "Reimplement the exposed PID keyboard path in Swift, including key aliases, explicit modifier transitions, reverse release and Unicode-scalar typing. Add preconstructed event pairs, cooperative cancellation and configurable Unicode event spacing, and Return/Tab delivery for text controls; omit unreachable global and Screen Sharing paths." + "changes": "Reimplement the exposed PID keyboard path in Swift, including key aliases, explicit modifier transitions, reverse release and Unicode-scalar typing. Add preconstructed event pairs, cooperative cancellation and configurable Unicode event spacing, and Return/Tab delivery for text controls; omit unreachable global and Screen Sharing paths. Preserve keypad key codes separately from ordinary digits and share modifier flags with pointer input." }, { "local": "Sources/CuaNative/WindowPointerInput.swift", "upstream": "libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs", - "changes": "Reimplement the exposed window-directed click, drag and line-scroll paths in Swift. Preserve routing fields and gesture timing, post each event once, and release this operation\u2019s held button on cooperative cancellation. Preserve fractional movement delays for short or unevenly divided drags." + "changes": "Reimplement the exposed window-directed click, drag and line-scroll paths in Swift. Preserve routing fields and gesture timing, post each event once, and release this operation’s held button on cooperative cancellation. Preserve fractional movement delays for short or unevenly divided drags. Support middle-button and modifier-bearing clicks and configurable-button drags." }, { "local": "Sources/CuaNative/PIDEventPoster.swift", @@ -28,7 +28,7 @@ { "local": "Sources/CuaNative/AXAccess.swift", "upstream": "libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs", - "changes": "Reimplement AX traversal, selected-window filtering and display projection in Swift. Retain CFEqual identity handling, scoped AX references, checked discovery failures, AX-less owned windows and DSH system-panel ownership validation. Batch per-node observation attributes while retaining per-attribute errors and individual reads for unsupported batch APIs. Resolve exact-window AX frames for DSH capture and pointer geometry checks." + "changes": "Reimplement AX traversal, selected-window filtering and display projection in Swift. Retain CFEqual identity handling, scoped AX references, checked discovery failures, AX-less owned windows and DSH system-panel ownership validation. Batch per-node observation attributes while retaining per-attribute errors and individual reads for unsupported batch APIs. Resolve exact-window AX frames for DSH capture and pointer geometry checks. Include value writability, disabled and selected state in the model-facing tree." }, { "local": "Sources/CuaNative/NativePlatform.swift", diff --git a/packages/computer-use/cua/src/api.ts b/packages/computer-use/cua/src/api.ts index beeaa53f80..a8edf3de06 100644 --- a/packages/computer-use/cua/src/api.ts +++ b/packages/computer-use/cua/src/api.ts @@ -90,14 +90,15 @@ export function createCuaApi(dispatch: CuaDispatch, sink?: CuaObservationSink): async click(target, options) { const mouseButton = options?.mouseButton ?? 'left' const clickCount = options?.clickCount ?? 1 - if (mouseButton === 'right' && clickCount !== 1) throw new Error('Right double-click is unsupported') + if (mouseButton !== 'left' && clickCount !== 1) throw new Error('Only left double-click is supported') + const modifiers = options?.modifiers === undefined ? {} : { modifiers: [...options.modifiers] } if (typeof target === 'number') { - return action('click', { ...snapshotParams(), elementIndex: target, + return action('click', { ...snapshotParams(), ...modifiers, elementIndex: target, ...mouseButton === 'left' ? {} : { mouseButton }, ...clickCount === 1 ? {} : { clickCount }, }) } const [x, y] = target - return action('click', { ...snapshotParams(), windowId: windowId(), x, y, mouseButton, clickCount }) + return action('click', { ...snapshotParams(), windowId: windowId(), x, y, mouseButton, clickCount, ...modifiers }) }, async setValue(index, value) { return action('setValue', { ...snapshotParams(), elementIndex: index, value }) }, async performSecondaryAction(index, name) { return action('performSecondaryAction', { ...snapshotParams(), elementIndex: index, action: name }) }, @@ -108,8 +109,11 @@ export function createCuaApi(dispatch: CuaDispatch, sink?: CuaObservationSink): x: options.x, y: options.y, deltaLinesX: options.deltaLinesX, deltaLinesY: options.deltaLinesY, }) }, - async drag(from, to) { - return action('drag', { ...snapshotParams(), windowId: windowId(), fromX: from[0], fromY: from[1], toX: to[0], toY: to[1] }) + async drag(from, to, options) { + return action('drag', { ...snapshotParams(), windowId: windowId(), fromX: from[0], fromY: from[1], toX: to[0], toY: to[1], + ...options?.mouseButton === undefined ? {} : { mouseButton: options.mouseButton }, + ...options?.modifiers === undefined ? {} : { modifiers: [...options.modifiers] }, + }) }, } return result diff --git a/packages/computer-use/cua/src/index.ts b/packages/computer-use/cua/src/index.ts index 2fd5374df3..aaa8b43b30 100644 --- a/packages/computer-use/cua/src/index.ts +++ b/packages/computer-use/cua/src/index.ts @@ -82,7 +82,7 @@ export const Config = Schema.object({ /** Instructions for raw operation calls and optional object-API bindings. */ export const GUIDANCE = `Use cua with method getCapabilities and params {} to inspect permissions and sessionLocked. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI attempts and ask the user to unlock macOS. A null sessionLocked means no usable console session was verified. After unlocking, read fresh state; screenshots from a locked desktop are not current observations. Use listApps and getApp to select an already running application. getApp requests user consent before application observations or input. If access is denied or revoked, stop using that application until the user explicitly grants access again. Never switch tools to bypass a refusal. Keep the returned appHandle; every app operation requires it. listWindows returns window IDs and point bounds. getState returns a complete AX tree and snapshotId. Use its element indices only with that snapshotId. Raw screenshot and coordinate operations require a windowId. Coordinates are window-local macOS points, which may differ from screenshot pixels. A verified window can expose no AX elements. Its empty snapshot permits screenshots and coordinate input; element-index actions require an element from a fresh AX observation. -Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. +Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text marks disabled controls, writable values and available selection state. Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. @@ -102,17 +102,17 @@ App and Window methods: - getAXState(options?: { emit?: boolean, disableDiffing?: boolean }) -> string - getScreenshot(options?: { emit?: boolean }) -> Uint8Array - getAXStateAndScreenshot(options?) -> { state: string, screenshot: Uint8Array } -- click(target: number | [x, y], options?: { mouseButton?: "left" | "right", clickCount?: 1 | 2 }) -> action result +- click(target: number | [x, y], options?: { mouseButton?: "left" | "right" | "middle", clickCount?: 1 | 2, modifiers?: Array<"command" | "control" | "option" | "shift" | "fn"> }) -> action result - setValue(elementIndex: number, value: string) -> action result - performSecondaryAction(elementIndex: number, action: string) -> action result - scroll({ x, y, deltaLinesX, deltaLinesY }) -> action result -- drag(from: [x, y], to: [x, y]) -> action result +- drag(from: [x, y], to: [x, y], options?: { mouseButton?: "left" | "right" | "middle", modifiers?: Array<"command" | "control" | "option" | "shift" | "fn"> }) -> action result Raw operation tools use { method, params }, including params: {} for parameterless methods. getApp selects without activating the app. Keep applications in the background for observation and routine input. Do not activate or raise an app during initialization, before each action, or merely because another app is foreground. Prefer advertised AX actions. If a hidden window, another Space or Stage Manager prevents usable observation, explain the foreground-dependent step before app.activate() or an advertised raise action, then read fresh state. Avoid repeated activation when the user switches away; continue background-capable steps and report what requires foreground access. Applications may still change focus in response to input. Await operations sequentially. After input, read fresh state to verify the effect. A successful action means dispatched, not verified completion. Cancellation may leave partial effects; never retry uncertain input without observing. STALE_APP requires getApp again; STALE_SNAPSHOT requires getState again. WINDOW_CHANGED requires fresh state before any retry; use an advertised AX action or explicitly restore the window before screenshot or coordinate input, then observe again. PERMISSION_DENIED requires the user to grant macOS Accessibility or Screen Recording access in System Settings. After granting access, observe fresh state before continuing; do not automatically replay prior input. -Window objects expose observation and pointer/AX actions; keyboard input remains app-scoped and follows current focus. Scroll deltas are integer lines from -10 to 10; positive values reveal content above or left. Paste inserts plain text using native Unicode input without changing the clipboard; rich-text formats are unavailable. Browser applications can be controlled with getApp like other native apps; browser tabs and app launching are unavailable. The execution host must install the object API and own variable persistence; this plugin does not preload a cua global. In persistent PTC, use the host-provided initialization snippet below once. Its installation-owned file URL works independently of the project directory. Retain app objects between calls. End screenshot calls with void await app.getScreenshot() or void await app.getAXStateAndScreenshot() so image bytes are not serialized as the program completion value.` +Left clicks support single/double clicks; right and middle clicks support single clicks. Modified clicks use pointer input. Keypad names such as KP_0 and KP_Enter retain their physical key identity. Window objects expose observation and pointer/AX actions; keyboard input remains app-scoped and follows current focus. Scroll deltas are integer lines from -10 to 10; positive values reveal content above or left. Paste inserts plain text using native Unicode input without changing the clipboard; rich-text formats are unavailable. Browser applications can be controlled with getApp like other native apps; browser tabs and app launching are unavailable. The execution host must install the object API and own variable persistence; this plugin does not preload a cua global. In persistent PTC, use the host-provided initialization snippet below once. Its installation-owned file URL works independently of the project directory. Retain app objects between calls. End screenshot calls with void await app.getScreenshot() or void await app.getAXStateAndScreenshot() so image bytes are not serialized as the program completion value.` function executionAgent(execution: Readonly): Agent { if (!execution.agent) throw new Error('dsh-cua requires an agent-owned execution') diff --git a/packages/computer-use/cua/src/protocol.ts b/packages/computer-use/cua/src/protocol.ts index ad44ba55e3..077bf72874 100644 --- a/packages/computer-use/cua/src/protocol.ts +++ b/packages/computer-use/cua/src/protocol.ts @@ -6,6 +6,8 @@ import type { CuaAppHandle, CuaSnapshotId } from './types.ts' const id = z.number().int().positive() const point = z.number().nonnegative() const app = { appHandle: z.string().min(1) } +const pointer = { mouseButton: z.enum(['left', 'right', 'middle']).optional(), + modifiers: z.array(z.enum(['command', 'control', 'option', 'shift', 'fn'])).optional() } const window = { ...app, windowId: id } const snapshot = { ...app, snapshotId: z.string().min(1), elementIndex: z.number().int().nonnegative() } const coordinate = { ...window, snapshotId: z.string().min(1).optional(), x: point, y: point } @@ -29,15 +31,15 @@ export const Request = z.discriminatedUnion('method', [ operation('listWindows', app), operation('getState', { ...app, windowId: id.optional() }), z.object({ method: z.literal('click'), params: z.union([ - z.object({ ...snapshot, mouseButton: z.enum(['left', 'right']).optional(), clickCount: z.union([z.literal(1), z.literal(2)]).optional() }).strict(), - z.object({ ...coordinate, mouseButton: z.enum(['left', 'right']).optional(), clickCount: z.union([z.literal(1), z.literal(2)]).optional() }).strict(), + z.object({ ...snapshot, ...pointer, clickCount: z.union([z.literal(1), z.literal(2)]).optional() }).strict(), + z.object({ ...coordinate, ...pointer, clickCount: z.union([z.literal(1), z.literal(2)]).optional() }).strict(), ]) }).strict(), operation('setValue', { ...snapshot, value: z.string() }), operation('performSecondaryAction', { ...snapshot, action: z.string().min(1) }), operation('typeText', { ...app, text: z.string() }), operation('pressKey', { ...app, key: z.string().min(1), modifiers: z.array(z.enum(['command', 'control', 'option', 'shift', 'fn'])).optional() }), operation('scroll', { ...coordinate, deltaLinesX: z.number().int().min(-10).max(10), deltaLinesY: z.number().int().min(-10).max(10) }), - operation('drag', { ...window, snapshotId: z.string().min(1).optional(), fromX: point, fromY: point, toX: point, toY: point }), + operation('drag', { ...window, ...pointer, snapshotId: z.string().min(1).optional(), fromX: point, fromY: point, toX: point, toY: point }), operation('screenshot', window), ]) diff --git a/packages/computer-use/cua/src/types.ts b/packages/computer-use/cua/src/types.ts index eef7e33690..ffbaccaef6 100644 --- a/packages/computer-use/cua/src/types.ts +++ b/packages/computer-use/cua/src/types.ts @@ -53,8 +53,14 @@ export interface CuaWindowInfo { } /** Successful input dispatch; application outcome still requires observation. */ export interface CuaActionResult { dispatched: true; verified: false } -/** Indexed and coordinate clicks support left single/double clicks and right single clicks. */ -export interface CuaClickOptions { mouseButton?: 'left' | 'right'; clickCount?: 1 | 2 } +/** Modifiers attached to a window-directed pointer gesture. */ +export type CuaPointerModifier = 'command' | 'control' | 'option' | 'shift' | 'fn' +/** Buttons supported by window-directed clicks and drags. */ +export type CuaMouseButton = 'left' | 'right' | 'middle' +/** Left clicks support one or two presses; right and middle clicks support one. */ +export interface CuaClickOptions { mouseButton?: CuaMouseButton; clickCount?: 1 | 2; modifiers?: readonly CuaPointerModifier[] } +/** One same-window drag; omitted button is left and omitted modifiers are empty. */ +export interface CuaDragOptions { mouseButton?: CuaMouseButton; modifiers?: readonly CuaPointerModifier[] } /** Positive deltas reveal content above/left; each axis is an integer from -10 to 10. */ export interface CuaScrollOptions { x: number; y: number; deltaLinesX: number; deltaLinesY: number } /** An observed AX tree and independently captured PNG; capture is not atomic. */ @@ -111,12 +117,13 @@ export interface CuaSurface { */ scroll(options: CuaScrollOptions): Promise /** - * Drag between points in one window. + * Drag between points in one window while holding the selected button and modifiers. * @param from - starting window point. * @param to - destination window point. + * @param options - Button and modifiers for the complete gesture. * @returns dispatch evidence. */ - drag(from: readonly [number, number], to: readonly [number, number]): Promise + drag(from: readonly [number, number], to: readonly [number, number], options?: CuaDragOptions): Promise } /** One explicit window; keyboard operations remain app-scoped because they follow focus. */ export interface CuaWindow extends CuaSurface { readonly windowId: number } diff --git a/packages/computer-use/cua/tests/api.spec.ts b/packages/computer-use/cua/tests/api.spec.ts index b924ab9fbf..ee7e90eef1 100644 --- a/packages/computer-use/cua/tests/api.spec.ts +++ b/packages/computer-use/cua/tests/api.spec.ts @@ -91,6 +91,30 @@ describe('application discovery', () => { }) }) +describe('pointer buttons and modifiers', () => { + it('retains middle-button and modifier intent through click and drag dispatch', async () => { + const f = fixture() + const app = await f.api.getApp('Editor') + await app.click(0, { mouseButton: 'middle', modifiers: ['shift'] }) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { + appHandle: 'app-17', snapshotId: 'snapshot-1', elementIndex: 0, mouseButton: 'middle', modifiers: ['shift'], + } }) + await app.click([10, 20], { modifiers: ['command'] }) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { + appHandle: 'app-17', snapshotId: 'snapshot-1', windowId: 23, x: 10, y: 20, + mouseButton: 'left', clickCount: 1, modifiers: ['command'], + } }) + await app.drag([10, 20], [30, 40], { mouseButton: 'middle', modifiers: ['shift', 'option'] }) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'drag', params: { + appHandle: 'app-17', snapshotId: 'snapshot-1', windowId: 23, fromX: 10, fromY: 20, toX: 30, toY: 40, + mouseButton: 'middle', modifiers: ['shift', 'option'], + } }) + const count = f.dispatch.mock.calls.length + await expect(app.click(0, { mouseButton: 'middle', clickCount: 2 })).rejects.toThrow('Only left double-click') + expect(f.dispatch).toHaveBeenCalledTimes(count) + }) +}) + describe('application and window observations', () => { it('keeps the latest AX index scope separate for an app and each selected window', async () => { const f = fixture()