Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): count an erroring macOS toggle press when its value moved (#4485)
Ed-Keyca59dc0f15ac
diff --git a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md b/libs/cua-driver/rust/Skills/cua-driver/MACOS.mdindex 3a2486cec4..332057df78 100644--- a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md+++ b/libs/cua-driver/rust/Skills/cua-driver/MACOS.md@@ -510,6 +510,7 @@ starting point for new browser workflows.| macOS system-alert beep on `press_key` with no visible change | Target window is minimized; Return / Space / Tab commits don't establish real renderer focus on minimized windows | AX-click a clickable equivalent (Go button, Submit button, checkbox) instead of pressing the key; see "Keyboard commits on minimized windows" under the Browser section || `Accessibility permission not granted` | TCC not granted | Stop; tell user to grant in System Settings || `Screen Recording permission not granted` | TCC not granted for capture | Screenshots and pixel actions are unavailable. If the task is AX-completable, use `get_window_state({include_screenshot:false})` and `element_token` actions; otherwise stop and ask the user to run `cua-driver permissions grant` |+| `AX action failed: ... returned -25200` (or -25205, -25206) | The app may have acted anyway: some AppKit controls return these after a press they performed | Re-read with `get_window_state` before retrying; a second press on a checkbox toggles it back. A radio button or checkbox whose AXValue settles on the pressed state is reported as performed, naming the error |## Example end-to-end task (macOS)diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rsindex b1bbf38958..756fa79270 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs@@ -81,17 +81,39 @@ impl Harness {pointer_oracle: Option<&Path>,keep_ordered_front: bool,) -> Self {- let harness = Self::spawn(command_oracle, pointer_oracle, keep_ordered_front, None);+ Self::spawn(+ command_oracle,+ pointer_oracle,+ keep_ordered_front,+ None,+ &[],+ )+ .presented()+ }++ /// Launch with the opt-in erroring toggles (`erroring_toggles` scenario).+ fn launch_with_erroring_toggles() -> Self {+ Self::spawn(+ None,+ None,+ false,+ None,+ &[("CUA_APPKIT_ERRORING_TOGGLES", "1")],+ )+ .presented()+ }++ fn presented(self) -> Self {// Settle for window creation + activation.std::thread::sleep(Duration::from_millis(800));- harness.await_presented();- harness+ self.await_presented();+ self}/// Launch a harness that holds off entering its run loop for `delay`/// after registering its window, without waiting for its launch posture.fn launch_slowly(delay: Duration) -> Self {- Self::spawn(None, None, false, Some(delay))+ Self::spawn(None, None, false, Some(delay), &[])}fn spawn(@@ -99,6 +121,7 @@ impl Harness {pointer_oracle: Option<&Path>,keep_ordered_front: bool,launch_delay: Option<Duration>,+ env: &[(&str, &str)],) -> Self {let exe = harness_exe();assert!(@@ -122,6 +145,7 @@ impl Harness {if let Some(delay) = launch_delay {command.env("CUA_APPKIT_LAUNCH_DELAY_MS", delay.as_millis().to_string());}+ command.envs(env.iter().copied());let app = command.spawn().unwrap_or_else(|error| panic!("launch AppKit harness {exe:?}: {error}"));@@ -1581,6 +1605,99 @@ fn harness_appkit_counter() {);}+/// AppKit answers an accessibility press whose handler raises with an AX+/// error, as Finder's toolbar view switcher does after switching (#3835). A+/// checkbox that toggled before raising is reported as performed and+/// confirmed; one that changed nothing keeps the error.+#[test]+#[ignore]+fn harness_appkit_erroring_toggle_press_counts_only_when_its_value_moved() {+ let case = native_background_case(+ "appkit",+ "toggle_press_error",+ Targeting::Ax,+ DriverRoute::MacosAxAction,+ );+ let cell_id = case.cell_id.clone();+ execute_case(case, |evidence| {+ let mut driver = McpDriver::spawn_macos_daemon_proxy_named(&cell_id)+ .expect("start installed macOS daemon proxy");+ *evidence = recording_evidence(driver.recording_dir());+ let harness = Harness::launch_with_erroring_toggles();+ let pid = harness.pid;+ let (wid, _) = driver+ .find_window(pid as i64, "CuaTestHarness AppKit")+ .expect("AppKit main window not found");++ let (_, passed) = run_with_background_oracles(+ &mut driver,+ TargetWindow {+ pid,+ native_id: wid,+ },+ |driver| {+ let press = |driver: &mut McpDriver, identifier: &str| {+ let snapshot = snapshot_elements(driver, pid, wid);+ driver.call(+ "click",+ serde_json::json!({+ "pid": pid as i64,+ "window_id": wid,+ "element_token": element_token_by_id(&snapshot, identifier),+ "action": "press",+ "delivery_mode": "background"+ }),+ )+ };+ let state = |driver: &mut McpDriver| {+ snapshot_elements(driver, pid, wid).tree_text().to_owned()+ };+ assert!(+ state(driver).contains("acts_then_errors=false errors_only=false"),+ "erroring toggles did not start off"+ );++ let acted = press(driver, "chk-acts-then-errors");+ assert!(+ !acted.is_error(),+ "a press whose value moved was reported as failed: {}",+ acted.raw+ );+ assert_eq!(acted.action_effect(), Some("confirmed"), "{}", acted.raw);+ assert!(+ acted.text().contains("although the app returned AX error"),+ "result does not name the AX error: {}",+ acted.raw+ );++ let refused = press(driver, "chk-errors-only");+ assert!(+ refused.is_error(),+ "a press that changed nothing was reported as performed: {}",+ refused.raw+ );+ assert!(+ refused+ .text()+ .contains("AXUIElementPerformAction(AXPress) returned"),+ "{}",+ refused.raw+ );++ std::thread::sleep(Duration::from_millis(200));+ let after = state(driver);+ assert!(+ after.contains("acts_then_errors=true errors_only=false"),+ "fixture state after the presses:\n{after}"+ );+ },+ )+ .unwrap_or_else(|error| panic!("background desktop contract failed: {error}"));++ Observation::delivered_with_fixture_state(passed)+ });+}+/// Resolve the native AppKit button from a screenshot-space PX target, then/// deliver through the background-safe AX hit-test bridge while another app/// remains fully foreground.diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/bindings.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/bindings.rsindex 598ec24a32..cca6190a59 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/bindings.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/bindings.rs@@ -30,6 +30,7 @@ pub const kAXErrorSuccess: AXError = 0;pub const kAXErrorFailure: AXError = -25200;pub const kAXErrorInvalidUIElement: AXError = -25202;pub const kAXErrorAttributeUnsupported: AXError = -25205;+pub const kAXErrorActionUnsupported: AXError = -25206;pub const kAXErrorNoValue: AXError = -25212;pub const kAXErrorAPIDisabled: AXError = -25211;diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rsindex ba6fa56b8d..ac1f9d8448 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs@@ -132,6 +132,59 @@ const SELECTION_READBACK_POLL: std::time::Duration = std::time::Duration::from_mconst SELECTION_READBACK_SETTLE: std::time::Duration = std::time::Duration::from_millis(200);const SELECTION_READBACK_STABILITY: std::time::Duration = std::time::Duration::from_millis(250);+/// AXPress on a radio button or checkbox that advertises it: a press whose+/// effect the control's own AXValue shows.+fn is_toggle_press(ax_action: &str, role: &str, advertised: &[String]) -> bool {+ ax_action == "AXPress"+ && matches!(role, "AXRadioButton" | "AXCheckBox")+ && advertised.iter().any(|action| action == "AXPress")+}++/// AX errors that AppKit apps return from a press they performed (#3835).+/// Errors that mean the request never reached the app (illegal argument,+/// invalid element, cannot complete, API disabled) are not among them.+fn press_error_may_have_acted(err: crate::ax::bindings::AXError) -> bool {+ use crate::ax::bindings::{+ kAXErrorActionUnsupported, kAXErrorAttributeUnsupported, kAXErrorFailure,+ };+ matches!(+ err,+ kAXErrorFailure | kAXErrorAttributeUnsupported | kAXErrorActionUnsupported+ )+}++/// Whether a toggle's value moving from `before` to `now` is what pressing it+/// does: a checkbox changes state; a radio button becomes selected (a radio+/// turning off was another radio's press).+fn toggle_press_shows(role: &str, before: &str, now: &str) -> bool {+ now != before && (role != "AXRadioButton" || now == "1")+}++/// The value `read` returns when, before `timeout`, it satisfies `shows` and+/// a second read `stability` later agrees on it. Some apps (Finder's toolbar+/// view switcher) apply a press and still return an AX error.+fn settled_value(+ shows: impl Fn(&str) -> bool,+ mut read: impl FnMut() -> Option<String>,+ timeout: std::time::Duration,+ poll: std::time::Duration,+ stability: std::time::Duration,+) -> Option<String> {+ let deadline = std::time::Instant::now() + timeout;+ loop {+ if let Some(now) = read().filter(|now| shows(now)) {+ std::thread::sleep(stability);+ if read().as_deref() == Some(now.as_str()) {+ return Some(now);+ }+ }+ if std::time::Instant::now() >= deadline {+ return None;+ }+ std::thread::sleep(poll);+ }+}+fn pixel_activation_policy(button: &str,effective_foreground: bool,@@ -1439,8 +1492,37 @@ fn perform_ax_click(}}+ let read_value = || unsafe {+ crate::ax::bindings::copy_stringish_attr(element, "AXValue").map(|value| value.state_value)+ };+ let toggle_before = is_toggle_press(ax_action, &role, &advertised)+ .then(read_value)+ .flatten();let err = unsafe { crate::ax::bindings::perform_action(element, ax_action) };if err != crate::ax::bindings::kAXErrorSuccess {+ // Checked before the row-selection fallback, which writes AXSelected+ // on an ancestor: a toggle whose press landed needs no other write.+ if let Some(before) = toggle_before.filter(|_| press_error_may_have_acted(err)) {+ if let Some(now) = settled_value(+ |now| toggle_press_shows(&role, &before, now),+ read_value,+ SELECTION_READBACK_TIMEOUT,+ SELECTION_READBACK_POLL,+ SELECTION_READBACK_STABILITY,+ ) {+ return Ok((+ format!(+ "✅ Performed {ax_action} on [{idx}] {role} \"{title}\"; AXValue is now \+ {now} (was {before}) on two reads, although the app returned AX error \+ {err}."+ ),+ false,+ false,+ true,+ false,+ ));+ }+ }// Some collection rows claim a click-like action but Finder returns// kAXErrorCannotComplete. Use the same verified selection fallback// before surfacing the dispatch error.@@ -1594,6 +1676,69 @@ fn map_action(action: &str) -> &'static str {mod tests {use super::*;+ /// #3835: Finder's toolbar view switcher applies an AXPress and returns+ /// -25205. Only a radio button or checkbox qualifies for the read-back.+ #[test]+ fn toggle_press_is_an_advertised_press_on_a_radio_or_checkbox() {+ let press = vec!["AXPress".to_owned()];+ assert!(is_toggle_press("AXPress", "AXRadioButton", &press));+ assert!(is_toggle_press("AXPress", "AXCheckBox", &press));+ assert!(+ !is_toggle_press("AXPress", "AXButton", &press),+ "a button has no value that shows the press"+ );+ assert!(!is_toggle_press("AXPick", "AXRadioButton", &press));+ assert!(+ !is_toggle_press("AXPress", "AXRadioButton", &[]),+ "AXPress not advertised"+ );+ }++ /// Only errors an app returns after acting qualify; errors that mean the+ /// request never reached the app keep failing (#3835).+ #[test]+ fn only_errors_an_app_returns_after_acting_qualify() {+ assert!(press_error_may_have_acted(-25200));+ assert!(press_error_may_have_acted(-25205));+ assert!(press_error_may_have_acted(-25206));+ for refused in [-25201, -25202, -25204, -25211] {+ assert!(!press_error_may_have_acted(refused), "{refused}");+ }+ }++ /// A checkbox press shows as any state change; a radio press only as the+ /// radio becoming selected.+ #[test]+ fn toggle_press_shows_as_the_value_the_press_produces() {+ assert!(toggle_press_shows("AXCheckBox", "0", "1"));+ assert!(toggle_press_shows("AXCheckBox", "1", "0"));+ assert!(toggle_press_shows("AXCheckBox", "2", "1"), "mixed state");+ assert!(!toggle_press_shows("AXCheckBox", "1", "1"));+ assert!(toggle_press_shows("AXRadioButton", "0", "1"));+ assert!(+ !toggle_press_shows("AXRadioButton", "1", "0"),+ "a radio turning off was another radio's press"+ );+ assert!(!toggle_press_shows("AXRadioButton", "1", "1"));+ }++ /// An erroring toggle press counts only when the value shows the press+ /// and a second read agrees on it.+ #[test]+ fn erroring_toggle_press_counts_only_when_its_value_settles() {+ let zero = std::time::Duration::ZERO;+ let settled = |reads: Vec<Option<&str>>| {+ let mut reads = reads.into_iter().map(|read| read.map(str::to_owned));+ let shows = |now: &str| toggle_press_shows("AXRadioButton", "0", now);+ settled_value(shows, || reads.next().flatten(), zero, zero, zero)+ };+ assert_eq!(settled(vec![Some("1"), Some("1")]), Some("1".to_owned()));+ assert_eq!(settled(vec![Some("1"), Some("0")]), None, "flickered back");+ assert_eq!(settled(vec![Some("1"), None]), None, "second read failed");+ assert_eq!(settled(vec![Some("0")]), None, "never moved");+ assert_eq!(settled(vec![None]), None, "unreadable");+ }+/// Surface 5: schema must advertise the new `button` field with the three/// canonical values and default to "left". Hermes / Codex / Claude Code/// consumers branch on this enum being present.diff --git a/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift b/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swiftindex 5e753e608f..ae665ee8c7 100644--- a/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift+++ b/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift@@ -15,6 +15,9 @@// click_target — NSButton (AX-addressable) records click/double_click/right_click// slider — NSSlider drives drag / set_value (slider_value=)// checkable_controls — NSButton checkbox (agreed=)+// erroring_toggles — opt-in (CUA_APPKIT_ERRORING_TOGGLES=1): two checkboxes+// whose accessibility press raises, so AppKit answers AXPress+// with an AX error; one toggles before raising (#3835)// context_menu — NSButton + NSMenu (Cut/Copy/Paste → menu_action=)// scroll_target — NSScrollView with a tall body and offset label// ns_menubar — main menu item with known title (Mac-specific)@@ -52,6 +55,10 @@ let kSliderAID = "sld-value"let kSliderValueAID = "lbl-slider-value"let kCheckboxAID = "chk-agree"let kCheckStateAID = "lbl-chk-state"+let kErroringTogglesEnv = "CUA_APPKIT_ERRORING_TOGGLES"+let kActsThenErrorsAID = "chk-acts-then-errors"+let kErrorsOnlyAID = "chk-errors-only"+let kErroringTogglesStateAID = "lbl-erroring-toggles"let kSelectionStateAID = "lbl-selection-state"let kContextButtonAID = "btn-context"let kMenuActionAID = "lbl-menu-action"@@ -126,6 +133,9 @@ final class HarnessWindowController: NSObject, NSTextFieldDelegate, NSTableViewDvar clicks = 0let sliderValueLabel = NSTextField(labelWithString: "slider_value=0")let checkStateLabel = NSTextField(labelWithString: "agreed=false")+ let actsThenErrors = RaisingCheckbox(checkboxWithTitle: "Acts then errors", target: nil, action: nil)+ let errorsOnly = RaisingCheckbox(checkboxWithTitle: "Errors only", target: nil, action: nil)+ let erroringTogglesLabel = NSTextField(labelWithString: "")let selectionItems = ["alpha", "beta", "gamma"]let selectionTable = NSTableView()let selectionStateLabel = NSTextField(labelWithString: "selection=none")@@ -390,6 +400,9 @@ final class HarnessWindowController: NSObject, NSTextFieldDelegate, NSTableViewDif taskStatePath != nil {addTaskControls(to: content)}+ if ProcessInfo.processInfo.environment[kErroringTogglesEnv] == "1" {+ addErroringToggles(to: content)+ }// No outer scroll-view wrap: the content is sized to fit the window// so the only scrollable surface is the inner scroll_target NSScrollView.@@ -456,6 +469,34 @@ final class HarnessWindowController: NSObject, NSTextFieldDelegate, NSTableViewDcontent.addArrangedSubview(sizeRow)}+ /// Opt-in erroring toggles (#3835), appended below Exit like the task+ /// controls so every ordinary control keeps its position. The label is the+ /// fixture's own record of both states.+ private func addErroringToggles(to content: NSStackView) {+ content.addArrangedSubview(sectionLabel("erroring_toggles"))+ actsThenErrors.setAccessibilityIdentifier(kActsThenErrorsAID)+ actsThenErrors.toggles = true+ errorsOnly.setAccessibilityIdentifier(kErrorsOnlyAID)+ erroringTogglesLabel.setAccessibilityIdentifier(kErroringTogglesStateAID)+ erroringTogglesLabel.font = NSFont.monospacedSystemFont(ofSize: 14, weight: .regular)+ let row = NSStackView()+ row.orientation = .horizontal+ row.spacing = 12+ for box in [actsThenErrors, errorsOnly] {+ box.state = .off+ box.onChange = { [weak self] in self?.recordErroringToggles() }+ row.addArrangedSubview(box)+ }+ row.addArrangedSubview(erroringTogglesLabel)+ content.addArrangedSubview(row)+ recordErroringToggles()+ }++ private func recordErroringToggles() {+ erroringTogglesLabel.stringValue =+ "acts_then_errors=\(actsThenErrors.state == .on) errors_only=\(errorsOnly.state == .on)"+ }+/// Benign distractor controls for density mode (#4312): a grid of buttons,/// labeled text fields, checkboxes, and radio groups. Each radio row is/// its own group (radio buttons group by superview and action).@@ -716,6 +757,24 @@ final class HarnessWindowController: NSObject, NSTextFieldDelegate, NSTableViewD// via AXPress) that additionally reports double-click and right-click. AXPress and// single mouse-up fire the target/action (→ click); a pixel double-click is caught// here before super so it reports double_click; right-click reports right_click.+/// A checkbox whose accessibility press raises after optionally toggling.+/// AppKit answers that AXPress with an AX error, as Finder's toolbar view+/// switcher does after it has switched the view (#3835).+final class RaisingCheckbox: NSButton {+ var toggles = false+ var onChange: (() -> Void)?++ override func accessibilityPerformPress() -> Bool {+ if toggles {+ state = state == .on ? .off : .on+ onChange?()+ }+ NSException(name: .genericException, reason: "harness press handler raised",+ userInfo: nil).raise()+ return false+ }+}+final class ClickTargetButton: NSButton {weak var harness: HarnessWindowController?diff --git a/libs/cua-driver/tests/fixtures/shared/scenarios.json b/libs/cua-driver/tests/fixtures/shared/scenarios.jsonindex 358ebc8e9d..38558fa773 100644--- a/libs/cua-driver/tests/fixtures/shared/scenarios.json+++ b/libs/cua-driver/tests/fixtures/shared/scenarios.json@@ -370,6 +370,16 @@"state_label_aid": "lbl-chk-state"}},+ {+ "id": "erroring_toggles",+ "kind": "toggle",+ "description": "Opt-in (CUA_APPKIT_ERRORING_TOGGLES=1): two NSButton checkboxes whose accessibility press raises, so AppKit answers AXPress with an AX error. The first toggles before raising (as Finder's toolbar view switcher does), the second changes nothing. Tests that click reports the first as performed and keeps the error for the second (#3835). acts_then_errors= errors_only= label.",+ "controls": {+ "acts_then_errors_aid": "chk-acts-then-errors",+ "errors_only_aid": "chk-errors-only",+ "state_label_aid": "lbl-erroring-toggles"+ }+ },{"id": "context_menu","kind": "context_menu",diff --git a/libs/cua/skills/cua-driver/MACOS.md b/libs/cua/skills/cua-driver/MACOS.mdindex 3a2486cec4..332057df78 100644--- a/libs/cua/skills/cua-driver/MACOS.md+++ b/libs/cua/skills/cua-driver/MACOS.md@@ -510,6 +510,7 @@ starting point for new browser workflows.| macOS system-alert beep on `press_key` with no visible change | Target window is minimized; Return / Space / Tab commits don't establish real renderer focus on minimized windows | AX-click a clickable equivalent (Go button, Submit button, checkbox) instead of pressing the key; see "Keyboard commits on minimized windows" under the Browser section || `Accessibility permission not granted` | TCC not granted | Stop; tell user to grant in System Settings || `Screen Recording permission not granted` | TCC not granted for capture | Screenshots and pixel actions are unavailable. If the task is AX-completable, use `get_window_state({include_screenshot:false})` and `element_token` actions; otherwise stop and ask the user to run `cua-driver permissions grant` |+| `AX action failed: ... returned -25200` (or -25205, -25206) | The app may have acted anyway: some AppKit controls return these after a press they performed | Re-read with `get_window_state` before retrying; a second press on a checkbox toggles it back. A radio button or checkbox whose AXValue settles on the pressed state is reported as performed, naming the error |## Example end-to-end task (macOS)diff --git a/scripts/ci/macos/run-rust-e2e.sh b/scripts/ci/macos/run-rust-e2e.shindex 1d975344c2..4a6a414099 100755--- a/scripts/ci/macos/run-rust-e2e.sh+++ b/scripts/ci/macos/run-rust-e2e.sh@@ -366,6 +366,7 @@ if [[ "${SUITE}" == native || "${SUITE}" == all ]]; thenharness_appkit_scroll_background \harness_appkit_counter \harness_appkit_counter_px_background \+ harness_appkit_erroring_toggle_press_counts_only_when_its_value_moved \harness_appkit_px_background_press_key_reports_honest_delivery_truth \harness_appkit_exact_activation_with_agent_cursor \harness_appkit_exact_activation_ignores_competing_application_window \