Skip to content

Commit 06f077d

Browse files
authored
fix(computer-use): tighten batch and click-to-focus edge cases from the staging audit (#10012)
* fix(computer-use): tighten batch and click-to-focus edge cases from the staging audit Validate every batch step before the first runs and name a refused first step; observe the window a batch targets; wait 250 ms for Accessibility focus before clicking, treat a refused click as no click and put the caret at the end; never report nothing-dispatched after a click; skip per-attribute fallback reads on a hung app; guard a self-parent in the projection; fix legend and README wording. Syncs the contract's activateFirst wording. * fix(computer-use): check Stop before every batch step, validate click and scroll targets up front, and keep the escaped-newline row cost * fix(computer-use): send no text when the caret cannot be moved to the end after a focus click
1 parent 17a38b3 commit 06f077d

10 files changed

Lines changed: 166 additions & 33 deletions

File tree

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

Lines changed: 63 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,11 @@ func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? {
9191
/// the element lacks or fails to return is omitted, as `attribute` would return nil for it.
9292
func attributes(_ element: AXUIElement, _ names: [String]) -> [String: CFTypeRef] {
9393
var raw: CFArray?
94-
guard AXUIElementCopyMultipleAttributeValues(element, names as CFArray, AXCopyMultipleAttributeOptions(rawValue: 0), &raw) == .success,
95-
let values = raw as [AnyObject]?, values.count == names.count else {
94+
let status = AXUIElementCopyMultipleAttributeValues(element, names as CFArray, AXCopyMultipleAttributeOptions(rawValue: 0), &raw)
95+
guard status == .success, let values = raw as [AnyObject]?, values.count == names.count else {
96+
// Only an element that cannot answer a batched read is asked one attribute at a time; a
97+
// timeout or failure would only repeat once per attribute.
98+
guard [.attributeUnsupported, .illegalArgument, .notImplemented].contains(status) else { return [:] }
9699
return names.reduce(into: [:]) { result, name in result[name] = attribute(element, name) }
97100
}
98101
var result: [String: CFTypeRef] = [:]
@@ -467,9 +470,23 @@ func validateBatchSteps(_ steps: [Parameters]) throws {
467470
guard (2...8).contains(steps.count) else { throw ComputerError("invalid_arguments", "A batch requires 2 to 8 steps.") }
468471
var units = 0
469472
for step in steps {
470-
guard let action = step.action, BATCH_ACTIONS.contains(action), step.bundleId == nil, step.snapshotId == nil, step.steps == nil else {
473+
guard let action = step.action, BATCH_ACTIONS.contains(action), step.bundleId == nil, step.snapshotId == nil else {
471474
throw ComputerError("invalid_arguments", "Batch steps are click, type_text, set_value, press_key, scroll or perform_action, without their own app or snapshot.")
472475
}
476+
// Malformed steps are refused before step 1 runs, so a typo never leaves a half-applied batch.
477+
switch action {
478+
case "type_text": _ = try required(step.elementId, "elementId"); _ = try required(step.text, "text")
479+
case "set_value": _ = try required(step.elementId, "elementId"); _ = try required(step.value, "value")
480+
case "perform_action": _ = try required(step.elementId, "elementId"); _ = try required(step.accessibilityAction, "accessibilityAction")
481+
case "press_key": _ = try parseKey(required(step.key, "key"))
482+
case "click":
483+
guard ["left", "right"].contains(step.button ?? "left"), (1...3).contains(step.clickCount ?? 1) else { throw ComputerError("invalid_arguments", "Invalid button or clickCount.") }
484+
guard step.elementId != nil || (step.x != nil && step.y != nil) else { throw ComputerError("invalid_arguments", "A click step needs an elementId or x and y.") }
485+
case "scroll":
486+
guard step.elementId != nil || (step.x != nil && step.y != nil) else { throw ComputerError("invalid_arguments", "A scroll step needs an elementId or x and y.") }
487+
guard step.deltaX != nil || step.deltaY != nil else { throw ComputerError("invalid_arguments", "A scroll step needs deltaX or deltaY.") }
488+
default: break
489+
}
473490
units += (step.text?.utf16.count ?? 0) + (step.value?.utf16.count ?? 0)
474491
}
475492
guard units <= 32000 else { throw ComputerError("invalid_arguments", "Combined batch text exceeds 32000 UTF-16 units.") }
@@ -599,15 +616,35 @@ func focusByClicking(_ element: AXUIElement, pid: pid_t, snapshot: Snapshot) asy
599616
let center = CGPoint(x: rect.midX, y: rect.midY)
600617
// The point must land on the editor or a text control inside it, never a button or row nested in a container.
601618
guard takesText(element), frame.contains(center), let hit = elementAtPoint(center) else { return }
602-
let insideEditor = takesText(hit) ? try ancestorPath(hit, to: element) != nil : false
619+
let insideEditor = try takesText(hit) && ancestorPath(hit, to: element) != nil
603620
// Secure inputs stay untargetable, so a password field is never clicked into focus either.
604621
guard CFEqual(hit, element) || insideEditor, (try? requireNonSecure(hit)) != nil else { return }
605-
try await coordinateAction { dispatch in
606-
try checkCancellation()
607-
try postMouse(pid: pid, type: .leftMouseDown, point: center, button: .left, windowID: windowID, window: window, frame: frame, dispatch: dispatch)
608-
try postMouse(pid: pid, type: .leftMouseUp, point: center, button: .left, windowID: windowID, window: window, frame: frame, release: true, dispatch: dispatch)
622+
do {
623+
try await coordinateAction { dispatch in
624+
try checkCancellation()
625+
try postMouse(pid: pid, type: .leftMouseDown, point: center, button: .left, windowID: windowID, window: window, frame: frame, dispatch: dispatch)
626+
try postMouse(pid: pid, type: .leftMouseUp, point: center, button: .left, windowID: windowID, window: window, frame: frame, release: true, dispatch: dispatch)
627+
}
628+
} catch let error as ComputerError where error.dispatchState == "not_started" {
629+
// A mouse guard refused the point before anything was sent; the focus check reports the outcome.
630+
return
631+
}
632+
// A click leaves the caret where it landed; typing inserts at the end, as after an Accessibility focus.
633+
let root = AXUIElementCreateApplication(pid)
634+
for _ in 0..<5 {
635+
try await Task.sleep(for: .milliseconds(50))
636+
guard let focused = attribute(root, kAXFocusedUIElementAttribute), holdsFocus(focused, element) else { continue }
637+
let editor = unsafeBitCast(focused, to: AXUIElement.self)
638+
var settable: DarwinBoolean = false
639+
if AXUIElementIsAttributeSettable(editor, kAXSelectedTextRangeAttribute as CFString, &settable) == .success, settable.boolValue,
640+
let value = attribute(editor, kAXValueAttribute) as? String {
641+
var range = CFRange(location: value.utf16.count, length: 0)
642+
guard let end = AXValueCreate(.cfRange, &range), AXUIElementSetAttributeValue(editor, kAXSelectedTextRangeAttribute as CFString, end) == .success else {
643+
throw ComputerError("caret_unconfirmed", "The editor was clicked into focus, but its caret could not be moved to the end, so no text was sent. Observe the app, then use set_value or move the caret with press_key.")
644+
}
645+
}
646+
return
609647
}
610-
try await Task.sleep(for: .milliseconds(100))
611648
}
612649
func discoverApps() throws -> [[String: Any]] {
613650
var entries: [String: [String: Any]] = [:]
@@ -767,14 +804,20 @@ final class Driver {
767804
"sequence": ["completedSteps": completed, "totalSteps": steps.count, "error": String((message + " The remaining steps were not run; observe the app before continuing, and do not retry the batch.").prefix(2000))]]
768805
}
769806
for (index, step) in steps.enumerated() {
770-
// Stop can arrive during the previous step's settle; no later step may start after it.
771-
do { try checkCancellation() } catch { if completed == 0 { throw error }; return stopped("Stopped before step \(index + 1).") }
772-
var params = step; params.bundleId = p.bundleId; params.snapshotId = p.snapshotId
807+
// Stop can arrive during the previous step's render wait; no later step may start after it.
808+
do { try checkCancellation() } catch {
809+
// Before any step ran nothing was sent, so Stop fails the batch as cancelled.
810+
if completed == 0 { throw error }
811+
return stopped("Stopped before step \(index + 1).")
812+
}
773813
let before = uiStructure(pid: pid)
774-
do { _ = try await act(Request(id: request.id, method: try required(step.action, "action"), params: params), app: app, bundle: bundle, snapshot: snapshot) }
814+
do { _ = try await act(Request(id: request.id, method: try required(step.action, "action"), params: step), app: app, bundle: bundle, snapshot: snapshot) }
775815
catch {
776816
// A first step that sent nothing fails like the single action, keeping the snapshot valid.
777-
if !inputDispatched { throw error }
817+
if completed == 0 && !inputDispatched {
818+
guard let error = error as? ComputerError else { throw error }
819+
throw ComputerError(error.code, "Batch step 1 failed: " + error.message, dispatchState: error.dispatchState)
820+
}
778821
return stopped("Step \(index + 1) failed: " + ((error as? ComputerError)?.message ?? "its outcome is unknown."))
779822
}
780823
completed += 1
@@ -832,7 +875,11 @@ final class Driver {
832875
// Activation can move focus, so whether the editor holds it is read after activating.
833876
if attribute(root, kAXFocusedUIElementAttribute).map({ holdsFocus($0, element) }) != true {
834877
try axCheck(AXUIElementSetAttributeValue(element, kAXFocusedAttribute as CFString, kCFBooleanTrue))
835-
try await Task.sleep(for: .milliseconds(50))
878+
// Focus can settle asynchronously; slow apps get 250 ms before any click is considered.
879+
for _ in 0..<5 {
880+
try await Task.sleep(for: .milliseconds(50))
881+
if attribute(root, kAXFocusedUIElementAttribute).map({ holdsFocus($0, element) }) == true { break }
882+
}
836883
// Some apps (SwiftUI sheets such as Clock's city search) ignore an Accessibility focus
837884
// request; in a foreground app the field is focused the way a user would, by clicking it.
838885
if app.isActive, attribute(root, kAXFocusedUIElementAttribute).map({ holdsFocus($0, element) }) != true {
@@ -861,7 +908,7 @@ final class Driver {
861908
do { try validateFocus(); break }
862909
catch let error as ComputerError where error.code == "focus_changed" {
863910
if attempt < 9 { try await Task.sleep(for: .milliseconds(50)) }
864-
else if !app.isActive { throw ComputerError("activation_required", "No input was dispatched. This background app does not expose the exact keyboard focus target. Call activate_app for this bundle, then get_app_state and retry using the fresh editor reference.", dispatchState: "not_started") }
911+
else if !app.isActive && !inputDispatched { throw ComputerError("activation_required", "No input was dispatched. This background app does not expose the exact keyboard focus target. Call activate_app for this bundle, then get_app_state and retry using the fresh editor reference.", dispatchState: "not_started") }
865912
else { throw error }
866913
}
867914
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,15 @@ Coordinates in action inputs are window-local points; node frames are global scr
1414

1515
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 hit on a window's own background counts as that window. Background tabs and minimized windows share bounds with the window in front, so they take no coordinate input. An action that opens UI (AXPress, AXPick, AXShowMenu) and times out while the app shows a sheet, modal or menu (`cannotComplete`) counts as dispatched; any other action that times out fails as uncertain. A menu-item press that leaves the item's own menu open with the app highlighting that item (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. 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

17-
`type_text` and `input_sequence` target a text control (text fields and areas, terminals, combo boxes, date and time pickers, or anything with an editable text selection), or a container whose focused editor already holds keyboard focus, such as a web composer; keystrokes are sent only while focus is in a text input. When an app ignores the Accessibility focus request (SwiftUI sheets such as Clock's city search), a foreground app's editor is clicked at its center to take focus, only if that point hit-tests to the editor inside its observed window; the usual focus checks then apply. `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. `batch` runs 2–8 click, type_text, set_value, press_key, scroll or perform_action steps planned from one snapshot, each through its own action's checks; it stops at the first step that fails and after any step that opens or closes a window, sheet, menu or popover, reports progress the same way, and a first step that sent nothing is refused with `dispatchState: "not_started"`. 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.
17+
`type_text` and `input_sequence` target a text control (text fields and areas, terminals, combo boxes, date and time pickers, or anything with an editable text selection), or a container whose focused editor already holds keyboard focus, such as a web composer; keystrokes are sent only while focus is in a text input. When an app ignores the Accessibility focus request (SwiftUI sheets such as Clock's city search), a foreground app's editor is clicked at its center to take focus after 250 ms without it, only if that point hit-tests to the editor (or a non-secure text control inside it) within its observed window; a click refused by the mouse guards sends nothing, the caret is moved to the end so typing inserts there, and the usual focus checks then apply. `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 sequence before input; it never enables automatic refocusing between steps. Partial execution reports completed steps and an error; callers must observe before retrying. `batch` runs 2–8 click, type_text, set_value, press_key, scroll or perform_action steps planned from one snapshot, each through its own action's checks; it stops at the first step that fails and after any step that changes the app's window structure (on-screen windows, which include sheets, menus and popovers, or the focused window's direct children), reports progress the same way, and a first step that sent nothing is refused with `dispatchState: "not_started"`. Every step is validated before the first one runs. The structure check is a heuristic: it misses modals inside web content and UI that appears after the step's render wait, and stops conservatively on tooltips and autocomplete popovers. 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

1919
## Cancellation
2020

2121
SIGTERM/SIGINT sets a cancellation flag. Traversal, typing and drag loops check it; mouse up is sent through a defer before returning from a cancelled drag. Keyboard down/up are paired in one function. The owner should close stdin and send SIGTERM, allowing a grace period before SIGKILL. Foreground drags also stop if the active app or window geometry changes; this does not detect every physical user input within the same app. Forced termination cannot guarantee a final release event; input routines deliberately avoid long waits with held buttons. Cancellation cannot undo an action already dispatched.
2222

2323
## Tests and limitations
2424

25-
Compile pure native tests with `swiftc -parse-as-library -D COMPUTER_USE_TEST ComputerUse.swift tests/NativeTests.swift -o native-tests`. They cover multi-display negative origins, coordinate bounds/nonfinite input, shortcut modifiers, invalid key handling and cooperative cancellation. Real status and app discovery outputs were validated against the generated worker Zod schema (156 apps, including 147 installed-only apps).
25+
Compile pure native tests with `swiftc -parse-as-library -D COMPUTER_USE_TEST ComputerUse.swift tests/NativeTests.swift -o native-tests`. They cover multi-display negative origins, coordinate bounds/nonfinite input, shortcut modifiers, invalid key handling, input-sequence and batch validation, protected apps and cooperative cancellation. The live fixture also covers batches and click-to-focus for an editor that ignores Accessibility focus. Real status and app discovery outputs were validated against the generated worker Zod schema (156 apps, including 147 installed-only apps).
2626

2727
`python3 tests/protocol.py <compiled-helper>` checks persistent framing, bounded-request recovery, Unicode decoding, no-prompt status, invalid methods/permissions, permission gates and clean EOF. `tests/Fixture.swift` compiles into a disposable AppKit app with a text field, secure field, increment button/counter, slider, scroll area and a visual-only marker. `python3 tests/live.py <helper>` requires both grants and verifies actual outcomes. `--allow-missing-screen` explicitly reports screenshots blocked rather than passing them; `--existing-fixture` leaves an existing fixture running for coordinated model trials. Give the fixture bundle ID `com.mothership.computer-use-fixture` when packaging it for integration tests.
2828

0 commit comments

Comments
 (0)