Skip to content

Commit debdd0e

Browse files
authored
fix(desktop): accept common computer calls and let input reach attached sheets (#9093)
* fix(desktop): accept coordinate input without a window, one-axis scrolls and targeted keys Mirrors the worker contract. Coordinate clicks, scrolls and drags without a windowId target the window the snapshot selected; scroll deltas default to 0; press_key with an elementId focuses that element first. Each shape was rejected before reaching the app in benchmark runs (about one call per task). * fix(desktop): let input reach sheets attached to the observed window Go to Folder and out-of-process open and save panels are sheets: the app reports them as its focused window, and a panel's contents report no window at all. Input checks now treat a sheet as the window it is attached to, and a click on windowless panel content is allowed only inside the app's focused sheet. * fix(desktop): keep coordinate input on the selected window and confirm targeted focus - Coordinate clicks and scrolls without a windowId use the snapshot's selected window through every input check; element targets keep their own window - press_key with an elementId sends the key only once that element holds focus - The service observes the selected window after a call without one - A scroll needs at least one delta, matching the worker contract * fix(desktop): observe the focused window after an untargeted key
1 parent 455c2bd commit debdd0e

5 files changed

Lines changed: 109 additions & 35 deletions

File tree

‎apps/desktop/native/computer-use/ComputerUse.swift‎

Lines changed: 58 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,18 @@ func requireNonSecure(_ element: AXUIElement) throws {
106106
func rectJSON(_ rect: CGRect) -> [String: Double] {
107107
["x": rect.minX, "y": rect.minY, "width": rect.width, "height": rect.height]
108108
}
109+
/// Whether keyboard focus is on `element` or an editor inside it, such as a combo box's field.
110+
func holdsFocus(_ focused: CFTypeRef, _ element: AXUIElement) -> Bool {
111+
guard CFGetTypeID(focused) == AXUIElementGetTypeID() else { return false }
112+
var current: AXUIElement? = unsafeBitCast(focused, to: AXUIElement.self)
113+
for _ in 0..<8 {
114+
guard let candidate = current else { return false }
115+
if CFEqual(candidate, element) { return true }
116+
guard let parent = attribute(candidate, kAXParentAttribute), CFGetTypeID(parent) == AXUIElementGetTypeID() else { return false }
117+
current = unsafeBitCast(parent, to: AXUIElement.self)
118+
}
119+
return false
120+
}
109121
func axActions(_ element: AXUIElement) -> [String] {
110122
var names: CFArray?
111123
return AXUIElementCopyActionNames(element, &names) == .success ? names as? [String] ?? [] : []
@@ -224,6 +236,8 @@ final class Snapshot {
224236
/// The Accessibility window behind each observed windowId, so input checks compare identity, not
225237
/// just bounds that two windows can share.
226238
var windowElements: [String: AXUIElement] = [:]
239+
/// The window this observation selected; coordinate input without a windowId targets it.
240+
var selectedWindowId: String?
227241
var nodes: [[String: Any]] = []
228242
var truncated = false
229243
init(app: NSRunningApplication) { pid = app.processIdentifier; launchDate = app.launchDate }
@@ -423,14 +437,34 @@ func requireForegroundTarget(pid: pid_t, windowID: String, window: AXUIElement,
423437
throw ComputerError("window_occluded", "Another of this app's windows covers the target point; observe that window and target it instead.")
424438
}
425439
} else if ![kAXMenuRole, kAXMenuItemRole, kAXMenuBarRole, kAXMenuBarItemRole].contains(attribute(hit, kAXRoleAttribute) as? String ?? "") {
426-
throw ComputerError("window_occluded", "Cannot confirm which window receives this point; observe again before retrying.")
440+
// Out-of-process panels (open and save) expose their contents without a window; they are
441+
// reachable only inside the app's focused sheet, which must belong to the observed window.
442+
let root = AXUIElementCreateApplication(pid)
443+
guard let rawSheet = attribute(root, kAXFocusedWindowAttribute), CFGetTypeID(rawSheet) == AXUIElementGetTypeID(),
444+
case let sheet = unsafeBitCast(rawSheet, to: AXUIElement.self), attribute(sheet, kAXRoleAttribute) as? String == kAXSheetRole,
445+
elementRect(sheet)?.contains(point) == true, acceptsInput(sheet, observed: [(window, frame)]) else {
446+
throw ComputerError("window_occluded", "Cannot confirm which window receives this point; observe again before retrying.")
447+
}
427448
}
428449
}
450+
/// The window a sheet is attached to: its parent, or for an out-of-process panel that reports no
451+
/// parent, the window it reports as its own.
452+
func sheetOwner(_ sheet: AXUIElement) -> AXUIElement? {
453+
for name in [kAXParentAttribute, kAXWindowAttribute] {
454+
if let raw = attribute(sheet, name), CFGetTypeID(raw) == AXUIElementGetTypeID() {
455+
let owner = unsafeBitCast(raw, to: AXUIElement.self)
456+
if attribute(owner, kAXRoleAttribute) as? String == kAXWindowRole { return owner }
457+
}
458+
}
459+
return nil
460+
}
429461
/// Whether input aimed at an observed window may go to `window`: the observed window itself, or one of
430462
/// the app's dialogs or floating panels above it. Another document window, or one whose kind cannot be
431463
/// read, is refused.
432464
func acceptsInput(_ window: AXUIElement, observed: [(element: AXUIElement, frame: CGRect)]) -> Bool {
433465
if observed.contains(where: { CFEqual($0.element, window) && elementRect(window) == $0.frame }) { return true }
466+
// A sheet (Go to Folder, an open or save panel) belongs to the window it is attached to.
467+
if attribute(window, kAXRoleAttribute) as? String == kAXSheetRole { return sheetOwner(window).map { acceptsInput($0, observed: observed) } ?? false }
434468
let auxiliary: Set<String> = [kAXDialogSubrole, kAXSystemDialogSubrole, kAXFloatingWindowSubrole, kAXSystemFloatingWindowSubrole]
435469
return (attribute(window, kAXSubroleAttribute) as? String).map(auxiliary.contains) ?? false
436470
}
@@ -502,7 +536,7 @@ final class Driver {
502536
guard let frame = elementRect(try snapshot.element(elementId)) else { throw ComputerError("element_unavailable", "Element has no usable frame.") }
503537
return CGPoint(x: frame.midX, y: frame.midY)
504538
}
505-
let windowId = try required(p.windowId, "windowId")
539+
let windowId = try required(p.windowId ?? snapshot.selectedWindowId, "windowId")
506540
let frame = try windowRect(windowId, pid: app.processIdentifier)
507541
guard snapshot.windowFrames[windowId] == frame else { throw ComputerError("stale_window", "Window moved or changed; observe it again.") }
508542
let x = try required(end ? p.toX : p.x, end ? "toX" : "x"); let y = try required(end ? p.toY : p.y, end ? "toY" : "y")
@@ -579,6 +613,7 @@ final class Driver {
579613
}
580614
guard let selectedWindowId = p.windowId ?? focusedID ?? windows.first?["windowId"] as? String else { throw ComputerError("app_window_unavailable", "No accessible app window is available. Open a window, then observe the app again.") }
581615
guard snapshot.windowFrames[selectedWindowId] != nil else { throw ComputerError("window_unavailable", "Selected window does not belong to the app.") }
616+
snapshot.selectedWindowId = selectedWindowId
582617
var result: [String: Any] = ["kind": "state", "windowId": selectedWindowId, "snapshotId": snapshot.id, "bundleId": app.bundleIdentifier!, "nodes": snapshot.nodes, "windows": windows, "truncated": snapshot.truncated]
583618
if p.includeScreenshot == true {
584619
do {
@@ -633,7 +668,8 @@ final class Driver {
633668
} else {
634669
try await coordinateAction { dispatch in
635670
let position = try point(p, app: app, snapshot: snapshot); let mouse: CGMouseButton = button == "right" ? .right : .left
636-
let windowID = try required(p.windowId ?? snapshot.windowFrames.first(where: { $0.value.contains(position) })?.key, "windowId")
671+
// Coordinates are window-local to the requested (or selected) window; an element target uses its own.
672+
let windowID = try required(p.windowId ?? (p.elementId == nil ? snapshot.selectedWindowId : snapshot.windowFrames.first(where: { $0.value.contains(position) })?.key), "windowId")
637673
let frame = try required(snapshot.windowFrames[windowID], "window frame")
638674
for click in 1...count {
639675
try checkCancellation()
@@ -660,18 +696,6 @@ final class Driver {
660696
try axCheck(AXUIElementSetAttributeValue(element, kAXFocusedAttribute as CFString, kCFBooleanTrue))
661697
try await Task.sleep(for: .milliseconds(50))
662698
}
663-
/// Focus may land on the element itself or on an editor inside it, such as a combo box's field.
664-
func holdsFocus(_ focused: CFTypeRef) -> Bool {
665-
guard CFGetTypeID(focused) == AXUIElementGetTypeID() else { return false }
666-
var current: AXUIElement? = unsafeBitCast(focused, to: AXUIElement.self)
667-
for _ in 0..<8 {
668-
guard let candidate = current else { return false }
669-
if CFEqual(candidate, element) { return true }
670-
guard let parent = attribute(candidate, kAXParentAttribute), CFGetTypeID(parent) == AXUIElementGetTypeID() else { return false }
671-
current = unsafeBitCast(parent, to: AXUIElement.self)
672-
}
673-
return false
674-
}
675699
let observedWindows = snapshot.observedWindows()
676700
func validateFocus() throws {
677701
try checkCancellation(); try requireNonSecure(element)
@@ -680,7 +704,7 @@ final class Driver {
680704
acceptsInput(unsafeBitCast(rawWindow, to: AXUIElement.self), observed: observedWindows) else {
681705
throw ComputerError("stale_window", "The editor's window moved or is not an observed window; observe again.")
682706
}
683-
guard let current = attribute(root, kAXFocusedUIElementAttribute), holdsFocus(current) else { throw ComputerError("focus_changed", "The exact editor is no longer focused; remaining input was not dispatched. Observe again.") }
707+
guard let current = attribute(root, kAXFocusedUIElementAttribute), holdsFocus(current, element) else { throw ComputerError("focus_changed", "The exact editor is no longer focused; remaining input was not dispatched. Observe again.") }
684708
if let focused = attribute(root, kAXFocusedUIElementAttribute), CFGetTypeID(focused) == AXUIElementGetTypeID() { try requireNonSecure(unsafeBitCast(focused, to: AXUIElement.self)) }
685709
}
686710
// AX focus requests and app activation may settle asynchronously. Wait without
@@ -730,6 +754,21 @@ final class Driver {
730754
return frame
731755
}
732756
let root = AXUIElementCreateApplication(pid)
757+
// A targeted key first moves keyboard focus to that element, as clicking into it would.
758+
if let elementId = p.elementId {
759+
let element = try snapshot.element(elementId)
760+
if attribute(root, kAXFocusedUIElementAttribute).map({ holdsFocus($0, element) }) != true {
761+
try axCheck(AXUIElementSetAttributeValue(element, kAXFocusedAttribute as CFString, kCFBooleanTrue))
762+
}
763+
// Focus can settle asynchronously; the key is sent only once this element holds it.
764+
var focused = false
765+
for _ in 0..<10 {
766+
try checkCancellation()
767+
if attribute(root, kAXFocusedUIElementAttribute).map({ holdsFocus($0, element) }) == true { focused = true; break }
768+
try await Task.sleep(for: .milliseconds(50))
769+
}
770+
guard focused else { throw ComputerError("focus_changed", "The element did not take keyboard focus; no key was sent. Observe again.") }
771+
}
733772
// Keys go to the app's key window: the observed window, or a dialog, panel or popover above it,
734773
// but never another document window the snapshot did not observe.
735774
guard let rawWindow = attribute(root, kAXFocusedWindowAttribute), CFGetTypeID(rawWindow) == AXUIElementGetTypeID() else { throw ComputerError("focus_failed", "The app has no focused window to receive keys; click a window or call activate_app, then observe again.") }
@@ -755,15 +794,16 @@ final class Driver {
755794
let position = try point(p, app: app, snapshot: snapshot); let dx = p.deltaX ?? 0; let dy = p.deltaY ?? 0
756795
guard dx.isFinite, dy.isFinite, abs(dx) <= 10000, abs(dy) <= 10000 else { throw ComputerError("invalid_arguments", "Scroll deltas exceed bounds.") }
757796
guard let event = CGEvent(scrollWheelEvent2Source: CGEventSource(stateID: .privateState), units: .pixel, wheelCount: 2, wheel1: Int32(-dy), wheel2: Int32(-dx), wheel3: 0) else { throw ComputerError("input_failed", "Could not create scroll event.") }
758-
let windowID = try required(p.windowId ?? snapshot.windowFrames.first(where: { $0.value.contains(position) })?.key, "windowId")
797+
// Coordinates are window-local to the requested (or selected) window; an element target uses its own.
798+
let windowID = try required(p.windowId ?? (p.elementId == nil ? snapshot.selectedWindowId : snapshot.windowFrames.first(where: { $0.value.contains(position) })?.key), "windowId")
759799
let frame = try required(snapshot.windowFrames[windowID], "window frame")
760800
try requireForegroundTarget(pid: pid, windowID: windowID, window: try required(snapshot.windowElements[windowID], "observed window"), point: position, frame: frame)
761801
event.location = position; dispatch.willDispatch(); event.post(tap: .cghidEventTap)
762802
}
763803
case "drag":
764804
try await coordinateAction { dispatch in
765805
let start = try point(p, app: app, snapshot: snapshot); let end = try point(p, app: app, snapshot: snapshot, end: true)
766-
let windowID = try required(p.windowId, "windowId"); let frame = try required(snapshot.windowFrames[windowID], "window frame")
806+
let windowID = try required(p.windowId ?? snapshot.selectedWindowId, "windowId"); let frame = try required(snapshot.windowFrames[windowID], "window frame")
767807
try postMouse(pid: pid, type: .leftMouseDown, point: start, button: .left, windowID: windowID, window: snapshot.windowElements[windowID], frame: frame, dispatch: dispatch)
768808
var lastPoint = start
769809
defer { try? postMouse(pid: pid, type: .leftMouseUp, point: lastPoint, button: .left, windowID: windowID, window: snapshot.windowElements[windowID], frame: frame, release: true, dispatch: dispatch) }

‎apps/desktop/native/computer-use/README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ Persistent newline-delimited JSON over stdin/stdout: `{id,method,params}` return
1010

1111
The helper observes up to 2000 accessibility nodes (depth 64, queue 4000, traversal deadline 8 seconds, each AX call timeout 250ms). Selected-window and focused-element ancestry are prioritized; menu traversal is deferred and capped at 80 nodes. Electron accessibility is enabled using its documented `AXManualAccessibility` attribute. The helper observes 100 windows and 1000 apps. Requests are bounded to 128 KiB during ingestion. Text/value input is capped at 32000 UTF-16 units. State references are per-process, per-app, expire after 60 seconds, and are consumed by every action that reaches the app; a request that fails before sending anything reports `dispatchState: "not_started"` and keeps them valid. Restarts invalidate all references. Screen captures exclude window shadows, preserve the selected window’s coordinate geometry, and are capped to 1600 pixels on the longest side and 8 MiB encoded. Complete JSON replies are capped at 16 MiB: oversized observations omit screenshots first, then truncate accessibility nodes, while preserving action outcomes. Screenshots are optional and failure is reported in `screenshotError` without discarding accessibility state. macOS 26 uses the screenshot-specific capture API; the macOS 14/15 API path includes only the selected window in a display filter and crops its exact frame. That older path requires the window to fit within one display and reports `capture_geometry_unavailable` otherwise.
1212

13-
Coordinates in action inputs are window-local points; node frames are global screen points. Window bounds must still match the observed snapshot. App PID and launch time must match. Secure fields and descendants are unavailable as action targets; secure values and labels are suppressed. Sim's own apps and System Settings are protected targets. `get_app_state` can open an installed bundle ID without activating it. `list_apps` discovers installed apps under `/Applications`, `/System/Applications`, and `~/Applications` (bounded to 5000 filesystem entries and depth 3), merging running regular apps; installed apps omit `pid`.
13+
Coordinates in action inputs are window-local points; node frames are global screen points. Coordinate input without a `windowId` targets the window the snapshot selected; `press_key` with an `elementId` focuses that element first. Window bounds must still match the observed snapshot. App PID and launch time must match. Secure fields and descendants are unavailable as action targets; secure values and labels are suppressed. Sim's own apps and System Settings are protected targets. `get_app_state` can open an installed bundle ID without activating it. `list_apps` discovers installed apps under `/Applications`, `/System/Applications`, and `~/Applications` (bounded to 5000 filesystem entries and depth 3), merging running regular apps; installed apps omit `pid`.
1414

15-
AXPress and AXSetValue are direct semantic operations. Keyboard events target the app PID. Cmd+A uses the focused editor's writable accessibility selection range where supported. Coordinate mouse input requires the target app in front; `activate_app` makes that focus change explicit and confirms it. Click/drag/scroll validate the foreground process, unchanged window geometry and the app that receives the point; the topmost window-list entry is not the click target because Notification Center and the Dock keep full-screen click-through windows. A press that times out while the app opens a sheet or modal (`cannotComplete`) counts as dispatched. A menu-item press that leaves its menu open with the item highlighted (Calendar on macOS 26) is completed with Return. Open menus and their submenus are observed first, and menu item labels carry their shortcuts (for example ⇧⌘N). Some apps ignore background keyboard events. `dispatched:true,verified:false` means only dispatch succeeded; the agent must observe again to establish the outcome. No foreground activation fallback is hidden inside the helper. Native key codes currently assume the US layout for shortcuts; literal text uses Unicode events. Unsupported shortcuts fail explicitly.
15+
AXPress and AXSetValue are direct semantic operations. Keyboard events target the app PID. Cmd+A uses the focused editor's writable accessibility selection range where supported. Coordinate mouse input requires the target app in front; `activate_app` makes that focus change explicit and confirms it. Click/drag/scroll validate the foreground process, unchanged window geometry and the app that receives the point; the topmost window-list entry is not the click target because Notification Center and the Dock keep full-screen click-through windows. A press that times out while the app opens a sheet or modal (`cannotComplete`) counts as dispatched. A menu-item press that leaves its menu open with the item highlighted (Calendar on macOS 26) is completed with Return. Sheets, including Go to Folder and out-of-process open and save panels whose contents report no window, count as the window they are attached to. Open menus and their submenus are observed first, and menu item labels carry their shortcuts (for example ⇧⌘N). Some apps ignore background keyboard events. `dispatched:true,verified:false` means only dispatch succeeded; the agent must observe again to establish the outcome. No foreground activation fallback is hidden inside the helper. Native key codes currently assume the US layout for shortcuts; literal text uses Unicode events. Unsupported shortcuts fail explicitly.
1616

1717
`type_text` and `input_sequence` target any observed element that can take keyboard focus (text fields, terminals, combo boxes, web editors). `input_sequence` executes 1–32 key/text steps against one such element. It validates every step before dispatch and checks the same editor, window, and secure-input ancestry between steps. Enter can continue into another step when the same editor and window retain focus. Actual focus loss, Tab, or navigation shortcuts end the sequence before later input. Explicit `activateFirst: true` activates the target app inside the batch before input; it never enables automatic refocusing between steps. Partial execution reports completed steps and an error; callers must observe before retrying. Every mutation is followed by fresh state under the same authorization and queue entry; `observeAfter` optionally requests a screenshot. Observation failure is reported separately so the mutation is never replayed. The model receives a compact, bounded projection of the native snapshot; omitted nodes are reported explicitly.
1818

0 commit comments

Comments
 (0)