Skip to content

Commit 6cb5bfc

Browse files
authored
fix(computer-use): click an editor into focus when Accessibility cannot focus it (#10004)
* fix(computer-use): click an editor into focus when Accessibility cannot focus it SwiftUI sheets such as Clock's city search ignore an Accessibility focus request, so type_text refused with 'the exact editor is no longer focused'. In a foreground app the helper now clicks the editor's center, only when that point hit-tests to the editor inside its observed window, then applies the usual focus checks. * docs(computer-use): describe the click-to-focus fallback * fix(computer-use): click only onto the editor or a text control inside it, and cover click-to-focus in the live fixture * test(computer-use): move focus away before checking the background click-to-focus refusal * fix(computer-use): check for Stop before the click-to-focus mouse-down * fix(computer-use): never click a secure field into focus
1 parent 0f9009c commit 6cb5bfc

4 files changed

Lines changed: 50 additions & 4 deletions

File tree

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -590,6 +590,25 @@ func postMouse(pid: pid_t, type: CGEventType, point: CGPoint, button: CGMouseBut
590590
event.post(tap: .cghidEventTap)
591591
}
592592

593+
/// Clicks the center of an observed text control so it takes keyboard focus, only when that point lands on
594+
/// the control (or a text control inside it) within its observed window; otherwise nothing is sent and the focus check decides.
595+
@MainActor
596+
func focusByClicking(_ element: AXUIElement, pid: pid_t, snapshot: Snapshot) async throws {
597+
guard let rect = elementRect(element), let windowID = snapshot.windowId(holding: element),
598+
let frame = snapshot.windowFrames[windowID], let window = snapshot.windowElements[windowID] else { return }
599+
let center = CGPoint(x: rect.midX, y: rect.midY)
600+
// The point must land on the editor or a text control inside it, never a button or row nested in a container.
601+
guard takesText(element), frame.contains(center), let hit = elementAtPoint(center) else { return }
602+
let insideEditor = takesText(hit) ? try ancestorPath(hit, to: element) != nil : false
603+
// Secure inputs stay untargetable, so a password field is never clicked into focus either.
604+
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)
609+
}
610+
try await Task.sleep(for: .milliseconds(100))
611+
}
593612
func discoverApps() throws -> [[String: Any]] {
594613
var entries: [String: [String: Any]] = [:]
595614
let roots = [URL(fileURLWithPath: "/Applications"), URL(fileURLWithPath: "/System/Applications"), FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Applications")]
@@ -814,6 +833,11 @@ final class Driver {
814833
if attribute(root, kAXFocusedUIElementAttribute).map({ holdsFocus($0, element) }) != true {
815834
try axCheck(AXUIElementSetAttributeValue(element, kAXFocusedAttribute as CFString, kCFBooleanTrue))
816835
try await Task.sleep(for: .milliseconds(50))
836+
// Some apps (SwiftUI sheets such as Clock's city search) ignore an Accessibility focus
837+
// request; in a foreground app the field is focused the way a user would, by clicking it.
838+
if app.isActive, attribute(root, kAXFocusedUIElementAttribute).map({ holdsFocus($0, element) }) != true {
839+
try await focusByClicking(element, pid: pid, snapshot: snapshot)
840+
}
817841
}
818842
let observedWindows = snapshot.observedWindows()
819843
// The first editor found holding focus receives the whole input, so text never follows focus elsewhere.

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ 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. `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, 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.
1818

1919
## Cancellation
2020

‎apps/desktop/native/computer-use/tests/Fixture.swift‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ final class MarkerView: NSView {
88
}
99
}
1010

11+
/// A field that ignores Accessibility focus requests but takes focus from a click, as SwiftUI sheets do.
12+
final class ClickFocusField: NSTextField {
13+
override func setAccessibilityFocused(_ accessibilityFocused: Bool) {}
14+
}
1115
final class FixtureDelegate: NSObject, NSApplicationDelegate {
1216
var window: NSWindow!
1317
var count = 0
@@ -31,6 +35,7 @@ final class FixtureDelegate: NSObject, NSApplicationDelegate {
3135
let field = NSTextField(string: "Fixture text"); field.setAccessibilityIdentifier("fixture-text"); field.setAccessibilityLabel("Fixture editable text")
3236
let secure = NSSecureTextField(string: "fixture-only-secret"); secure.setAccessibilityIdentifier("fixture-password"); secure.setAccessibilityLabel("Fixture password")
3337
let button = NSButton(title: "Increment", target: self, action: #selector(increment)); button.setAccessibilityIdentifier("fixture-increment")
38+
let clickField = ClickFocusField(string: ""); clickField.setAccessibilityLabel("Fixture click-focus field")
3439
let sheetButton = NSButton(title: "Show sheet", target: self, action: #selector(showSheet)); sheetButton.setAccessibilityIdentifier("fixture-show-sheet")
3540
let slider = NSSlider(value: 25, minValue: 0, maxValue: 100, target: nil, action: nil); slider.setAccessibilityLabel("Fixture slider")
3641
let time = NSDatePicker(); time.datePickerStyle = .textField; time.datePickerElements = .hourMinute; time.setAccessibilityLabel("Fixture time")
@@ -44,9 +49,9 @@ final class FixtureDelegate: NSObject, NSApplicationDelegate {
4449
scroll.documentView = document
4550
scroll.contentView.postsBoundsChangedNotifications = true
4651
NotificationCenter.default.addObserver(self, selector: #selector(scrolled(_:)), name: NSView.boundsDidChangeNotification, object: scroll.contentView)
47-
for view in [field, secure, button, counter, sheetButton, slider, time, timeLabel, marker, scrollCounter, scroll] { stack.addArrangedSubview(view) }
52+
for view in [field, secure, button, counter, clickField, sheetButton, slider, time, timeLabel, marker, scrollCounter, scroll] { stack.addArrangedSubview(view) }
4853
window.contentView!.addSubview(stack)
49-
NSLayoutConstraint.activate([stack.leadingAnchor.constraint(equalTo: window.contentView!.leadingAnchor, constant: 30), stack.trailingAnchor.constraint(equalTo: window.contentView!.trailingAnchor, constant: -30), stack.topAnchor.constraint(equalTo: window.contentView!.topAnchor, constant: 30), field.widthAnchor.constraint(equalTo: stack.widthAnchor), secure.widthAnchor.constraint(equalTo: stack.widthAnchor), slider.widthAnchor.constraint(equalTo: stack.widthAnchor), scroll.widthAnchor.constraint(equalTo: stack.widthAnchor), scroll.heightAnchor.constraint(equalToConstant: 230), marker.widthAnchor.constraint(equalToConstant: 100), marker.heightAnchor.constraint(equalToConstant: 70)])
54+
NSLayoutConstraint.activate([stack.leadingAnchor.constraint(equalTo: window.contentView!.leadingAnchor, constant: 30), stack.trailingAnchor.constraint(equalTo: window.contentView!.trailingAnchor, constant: -30), stack.topAnchor.constraint(equalTo: window.contentView!.topAnchor, constant: 30), field.widthAnchor.constraint(equalTo: stack.widthAnchor), secure.widthAnchor.constraint(equalTo: stack.widthAnchor), clickField.widthAnchor.constraint(equalTo: stack.widthAnchor), slider.widthAnchor.constraint(equalTo: stack.widthAnchor), scroll.widthAnchor.constraint(equalTo: stack.widthAnchor), scroll.heightAnchor.constraint(equalToConstant: 230), marker.widthAnchor.constraint(equalToConstant: 100), marker.heightAnchor.constraint(equalToConstant: 70)])
5055
window.makeKeyAndOrderFront(nil)
5156
window.makeFirstResponder(field)
5257
NSApplication.shared.activate()

‎apps/desktop/native/computer-use/tests/live.py‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,24 @@ def batch(snapshot, steps):
170170
# While the sheet is open only the sheet is observed; the step after it must not have run.
171171
snapshot = mutate('click', snapshot, elementId=find(snapshot, role='AXButton', label='Dismiss')['elementId'])
172172
assert count(snapshot) == before + 3, 'A batch step ran after a sheet opened'
173-
print('PASS: real fixture state, secure suppression, AX click/set/action, Unicode typing, keyboard chord, coordinate drag and scrolling, text refused by a slider, typing into a date picker, a window target typing into its focused editor, a title-bar click, a batch that applies, stops at a failing step, refuses before dispatch and stops when a sheet opens; every mutation verified in fresh state; screenshot=' + ('verified' if permissions['screenRecording'] else 'BLOCKED'))
173+
# An editor that ignores Accessibility focus takes focus from a click in a foreground app only.
174+
call('activate_app', bundleId=bundle)
175+
snapshot = state()
176+
click_field = find(snapshot, role='AXTextField', label='Fixture click-focus field')
177+
result = call('type_text', bundleId=bundle, snapshotId=snapshot['snapshotId'], elementId=click_field['elementId'], text='clicked')
178+
assert result['dispatched'], result
179+
assert find(state(), role='AXTextField', label='Fixture click-focus field').get('value') == 'clicked', 'Click-to-focus did not reach the editor'
180+
# Move focus to the other editor, then put another app in front: the click-only editor cannot take focus.
181+
snapshot = state()
182+
mutate('click', snapshot, **coordinate(snapshot, find(snapshot, role='AXTextField', label='Fixture editable text')))
183+
call('activate_app', bundleId='com.apple.finder')
184+
time.sleep(0.5)
185+
snapshot = state()
186+
error = refused('type_text', snapshot, elementId=find(snapshot, role='AXTextField', label='Fixture click-focus field')['elementId'], text='x')
187+
assert error['dispatchState'] == 'not_started', error
188+
assert find(state(), role='AXTextField', label='Fixture click-focus field').get('value') == 'clicked', 'A background app was clicked or typed into'
189+
call('activate_app', bundleId=bundle)
190+
print('PASS: real fixture state, secure suppression, AX click/set/action, Unicode typing, keyboard chord, coordinate drag and scrolling, text refused by a slider, typing into a date picker, a window target typing into its focused editor, a title-bar click, a batch that applies, stops at a failing step, refuses before dispatch and stops when a sheet opens, click-to-focus for an editor that ignores Accessibility focus (and none in the background); every mutation verified in fresh state; screenshot=' + ('verified' if permissions['screenRecording'] else 'BLOCKED'))
174191
finally:
175192
if fixture:
176193
fixture.terminate()

0 commit comments

Comments
 (0)