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): revert a background target's self-activation on macOS and route pixel double_click through click (#4976)
Francesco Bonacci5458c77b04a6
diff --git a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md b/libs/cua-driver/rust/Skills/cua-driver/MACOS.mdindex 6e74564702..21427423ab 100644--- a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md+++ b/libs/cua-driver/rust/Skills/cua-driver/MACOS.md@@ -310,6 +310,18 @@ chosen with `click` on the `AXMenuItem` (or in one call with`set_value` on the popup). Keyboard navigation of such a menu with`press_key` is not the route; pick the item by element.+### Apps that activate themselves++Some apps activate themselves in answer to input, even in the background:+Chrome when `cmd+L` focuses its address bar, GnuCash on a double-click in+its account tree. No client can stop that. After a background+action Cua Driver checks WindowServer's front process and, if the target+made itself frontmost, re-activates the user's app and hands its window+key focus back within a few tens of milliseconds. Prefer routes that do+not ask the app to come forward: `set_value` on the address field or+`browser_navigate` instead of `cmd+L`, and `AXOpen` through+`double_click` on an element instead of a pixel double-click.+### `delivery_mode` on the pointer family (macOS)`click`, `double_click`, `right_click`, `drag`, and `scroll` acceptdiff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rsindex 4d8b7636ab..ae4e0be489 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs@@ -548,6 +548,24 @@ pub fn key_focus_pid() -> Option<pid_t> {Some(pid)}+/// The pid of the process WindowServer has frontmost now. Unlike+/// `NSWorkspace.frontmostApplication`, this does not wait for the caller's+/// AppKit run loop to process an activation notice, so it sees a background+/// app's self-activation at once.+pub fn front_process_pid() -> Option<pid_t> {+ let get_front = get_front_process_fn()?;+ let to_pid = get_process_pid_fn()?;+ let mut psn = [0u8; 8];+ if unsafe { get_front(psn.as_mut_ptr() as *mut c_void) } != 0 || psn == [0u8; 8] {+ return None;+ }+ let mut pid: pid_t = 0;+ if unsafe { to_pid(psn.as_ptr() as *const c_void, &mut pid) } != 0 || pid <= 0 {+ return None;+ }+ Some(pid)+}+/// Whether the key-focus theft SPIs resolve on this system.pub fn key_focus_theft_available() -> bool {steal_key_focus_fn().is_some()@@ -781,6 +799,7 @@ pub fn front_process_matches(target_pid: libc::pid_t, target_wid: u32) -> Option/// Returns `true` only when the target PSN resolved and WindowServer accepted/// `SLPSSetFrontProcessWithOptions`.pub fn set_front_process_persistently(target_pid: libc::pid_t, target_wid: u32) -> bool {+ crate::window_change_detector::note_intentional_activation();let Some(set_front) = set_front_process_fn() else {return false;};@@ -869,6 +888,7 @@ fn foreground_turn() -> ForegroundTurn {// An intentional activation ends the previous action's detached window// watch, whose wildcard lease would otherwise revert it.crate::window_change_detector::end_tail();+ crate::window_change_detector::note_intentional_activation();if HOLDS_FOREGROUND_LOCK.with(std::cell::Cell::get) {return ForegroundTurn { _guard: None };}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/key_focus_guard.rs b/libs/cua-driver/rust/crates/platform-macos/src/key_focus_guard.rsindex 10082d8f2d..9096e6b4a5 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/key_focus_guard.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/key_focus_guard.rs@@ -98,6 +98,80 @@ fn restore_front_if_raised(target: i32, front: i32) -> bool {true}+/// Whether WindowServer's front process is the background target: it+/// activated itself (`activateIgnoringOtherApps:`) in answer to the action,+/// such as Chrome focusing its omnibox on cmd+L or GnuCash opening a register+/// on a double-click. No client can stop an app from activating itself.+fn target_self_activated(front_process: Option<i32>, target: i32, front: i32) -> bool {+ target != front && front_process == Some(target)+}++/// Undo a background target's self-activation: re-activate the user's app+/// and hand key focus back to its window. Reads WindowServer's front process+/// directly; `NSWorkspace` only learns of the activation once the daemon's run+/// loop processes the notice, which took about a second in Bench v2 CDB-G04.+fn revert_self_activation(target: i32, front: i32) -> bool {+ if !target_self_activated(skylight::front_process_pid(), target, front) {+ return false;+ }+ // The user may have switched to the target themselves (a click on its+ // window, or Cmd-Tab). Leave that alone.+ if user_switched_recently() {+ return false;+ }+ let started = Instant::now();+ // Make the user's key window frontmost and key again, the way the+ // foreground tools front an exact window (a user-generated front request+ // plus the make-key records). `NSRunningApplication.activate` from the+ // daemon is only a request under cooperative activation and can be+ // ignored, so it is the fallback.+ let restored = skylight::key_window_of_pid(front)+ .is_some_and(|wid| skylight::make_exact_window_key(front, wid))+ && skylight::front_process_pid() == Some(front);+ if !restored {+ use objc2_app_kit::{NSApplicationActivationOptions, NSRunningApplication};+ unsafe {+ if let Some(app) = NSRunningApplication::runningApplicationWithProcessIdentifier(front)+ {+ app.activateWithOptions(NSApplicationActivationOptions(0));+ }+ }+ }+ REVERTED.fetch_add(1, Ordering::Relaxed);+ tracing::debug!(+ target,+ front,+ restored,+ elapsed_ms = started.elapsed().as_millis() as u64,+ "reverted a background target's self-activation"+ );+ true+}++/// A hardware mouse-down or modifier change within this long before an+/// activation means the user may have caused it.+const USER_SWITCH_WINDOW_S: f64 = 1.0;++#[link(name = "ApplicationServices", kind = "framework")]+extern "C" {+ fn CGEventSourceSecondsSinceLastEventType(state: i32, event_type: u32) -> f64;+}++/// Whether the user pressed a mouse button or a modifier key on the real+/// hardware just now. Events the driver posts to a pid do not count.+fn user_switched_recently() -> bool {+ const HID_SYSTEM_STATE: i32 = 1;+ const LEFT_MOUSE_DOWN: u32 = 1;+ const RIGHT_MOUSE_DOWN: u32 = 3;+ const FLAGS_CHANGED: u32 = 12;+ [LEFT_MOUSE_DOWN, RIGHT_MOUSE_DOWN, FLAGS_CHANGED]+ .into_iter()+ .any(|kind| {+ let since = unsafe { CGEventSourceSecondsSinceLastEventType(HID_SYSTEM_STATE, kind) };+ since.is_finite() && since < USER_SWITCH_WINDOW_S+ })+}+/// How long the order stays watched after a guarded action ends. A target/// can raise a window a moment after the call that caused it returns (a/// banner, a sheet, or a menu that a renderer process opens later).@@ -105,18 +179,36 @@ const ORDER_WATCH: Duration = Duration::from_millis(2500);const ORDER_POLL: Duration = Duration::from_millis(20);const MAX_RESTORES_PER_WATCH: u32 = 3;-/// Keep restoring the user's window above `target` for a short while after-/// the action. One watcher per target; a later action extends it.-fn watch_order_after_action(target: i32, front: i32) {- static WATCHING: OnceLock<Mutex<HashMap<i32, Instant>>> = OnceLock::new();+/// One target's watch after a guarded action.+#[derive(Clone, Copy)]+struct Watch {+ until: Instant,+ front: i32,+ /// Also restore the window order (off when the user had put the target+ /// above their window before the action).+ order: bool,+ /// [`crate::window_change_detector::intentional_epoch`] when armed.+ epoch: u64,+}++/// Keep restoring the user's window above `target`, and undoing the target's+/// self-activation, for a short while after the action. One watcher per+/// target; a later action extends it.+fn watch_order_after_action(target: i32, front: i32, order: bool, epoch: u64) {+ static WATCHING: OnceLock<Mutex<HashMap<i32, Watch>>> = OnceLock::new();let watching = WATCHING.get_or_init(|| Mutex::new(HashMap::new()));- let until = Instant::now() + ORDER_WATCH;+ let watch = Watch {+ until: Instant::now() + ORDER_WATCH,+ front,+ order,+ epoch,+ };{let mut map = watching.lock().unwrap_or_else(std::sync::PoisonError::into_inner);let running = map.contains_key(&target);- map.insert(target, until);+ map.insert(target, watch);if running {return;}@@ -128,9 +220,27 @@ fn watch_order_after_action(target: i32, front: i32) {// that stays open); cap the restores so the user's app is not// re-activated in a loop.let mut restores = 0;+ let mut reverts = 0;loop {std::thread::sleep(ORDER_POLL);- if restores < MAX_RESTORES_PER_WATCH && restore_front_if_raised(target, front) {+ let current = watching+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .get(&target)+ .copied();+ let Some(current) = current else { return };+ // An activation the driver asked for since (bring_to_front,+ // foreground delivery) is not reverted.+ if reverts < MAX_RESTORES_PER_WATCH+ && current.epoch == crate::window_change_detector::intentional_epoch()+ && revert_self_activation(target, current.front)+ {+ reverts += 1;+ }+ if current.order+ && restores < MAX_RESTORES_PER_WATCH+ && restore_front_if_raised(target, current.front)+ {restores += 1;}let mut map = watching@@ -138,7 +248,7 @@ fn watch_order_after_action(target: i32, front: i32) {.unwrap_or_else(std::sync::PoisonError::into_inner);if map.get(&target)- .is_none_or(|until| Instant::now() >= *until)+ .is_none_or(|watch| Instant::now() >= watch.until){map.remove(&target);return;@@ -252,6 +362,7 @@ static UNVERIFIED_FRONT: AtomicI32 = AtomicI32::new(0);static RELEASED: AtomicU64 = AtomicU64::new(0);static MISSED: AtomicU64 = AtomicU64::new(0);static RESTORED: AtomicU64 = AtomicU64::new(0);+static REVERTED: AtomicU64 = AtomicU64::new(0);/// Counters since the daemon started.pub fn stats() -> Stats {@@ -269,14 +380,21 @@ pub struct Lease {/// A target window already sat above the user's window when the action/// started (the user arranged it so); then nothing is restored.above_before: bool,+ /// [`crate::window_change_detector::intentional_epoch`] when armed. If+ /// the driver activated an app itself since, the target's activation is+ /// not reverted.+ epoch: u64,}impl Drop for Lease {fn drop(&mut self) {+ if self.epoch == crate::window_change_detector::intentional_epoch() {+ revert_self_activation(self.pid, self.front);+ }if !self.above_before {restore_front_if_raised(self.pid, self.front);- watch_order_after_action(self.pid, self.front);}+ watch_order_after_action(self.pid, self.front, !self.above_before, self.epoch);let mut st = lock();if let Some((leases, until)) = st.guarded.get_mut(&self.pid) {*leases = leases.saturating_sub(1);@@ -323,6 +441,7 @@ pub fn protect(target_pid: i32) -> Option<Lease> {pid: target_pid,front,above_before: target_above_front(target_pid, front),+ epoch: crate::window_change_detector::intentional_epoch(),};if !ensure_tap(front) {return None;@@ -603,6 +722,19 @@ mod tests {}}+ #[test]+ fn only_the_targets_own_activation_is_reverted() {+ // The target is WindowServer's front process: it activated itself.+ assert!(super::target_self_activated(Some(7), 7, OWN));+ // The user's app is still in front, or a third app took it (not ours+ // to undo), or nothing is known.+ assert!(!super::target_self_activated(Some(OWN), 7, OWN));+ assert!(!super::target_self_activated(Some(9), 7, OWN));+ assert!(!super::target_self_activated(None, 7, OWN));+ // A target that is the user's app is never reverted.+ assert!(!super::target_self_activated(Some(7), 7, 7));+ }+#[test]fn a_target_window_above_the_users_window_is_detected() {// z_index: higher is closer to the front.diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rsindex b1ad983a95..222de0c88d 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs@@ -366,6 +366,7 @@ impl Tool for BringToFrontTool {async fn invoke(&self, args: Value) -> ToolResult {crate::window_change_detector::end_tail();+ crate::window_change_detector::note_intentional_activation();let pid = match args.get("pid").and_then(Value::as_i64) {Some(p) => match libc::pid_t::try_from(p) {Ok(pid) => pid,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 7acd80675e..a0a79e18a9 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@@ -1363,9 +1363,10 @@ impl Tool for ClickTool {let changes = super::finish_window_observation(snapshot).await;- let button_label = match button_str.as_str() {- "right" => "right-click",- "middle" => "middle-click",+ let button_label = match (button_str.as_str(), count) {+ ("right", _) => "right-click",+ ("middle", _) => "middle-click",+ (_, 2) => "double-click",_ => "click",};match result {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rsindex 90a4e89d9a..fd8d3273b9 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs@@ -126,178 +126,68 @@ impl Tool for DoubleClickTool {// Thread the resolved session cursor key into the blocking AX path// so its ClickPulse lands on THIS session's cursor, not "default".let ck = cursor_key.clone();- let result = tokio::task::spawn_blocking(move || {- ax_double_click(- pid,- wid,- element_guard.as_ptr(),- idx,- &ck,- has_ax_open,- delivery_mode.is_foreground(),+ let foreground = delivery_mode.is_foreground();+ // AXOpen or the routed double-click can make the app activate+ // itself (opening a document or a register). In the background,+ // revert that and keep the user's key window, as `click` does.+ let prior_front = crate::apps::frontmost_pid();+ let snapshot = if foreground {+ crate::window_change_detector::WindowChangeDetector::snapshot_without_suppression(+ prior_front,)- })+ } else {+ crate::window_change_detector::WindowChangeDetector::snapshot(prior_front)+ };+ let result = crate::focus_guard::with_focus_suppressed(+ (!foreground).then_some(pid),+ prior_front,+ "double_click.ax",+ || async move {+ tokio::task::spawn_blocking(move || {+ ax_double_click(+ pid,+ wid,+ element_guard.as_ptr(),+ idx,+ &ck,+ has_ax_open,+ foreground,+ )+ })+ .await+ },+ ).await;+ let changes = super::finish_window_observation(snapshot).await;return match result {- Ok(Ok(msg)) => ToolResult::text(msg),+ Ok(Ok(msg)) => ToolResult::text(format!("{msg}{}", changes.result_suffix())),Ok(Err(e)) => ToolResult::error(format!("double_click failed: {e}")),Err(e) => ToolResult::error(format!("Task error: {e}")),};}// ── Pixel path ───────────────────────────────────────────────────────- let mut cx = match args.get("x").and_then(|v| v.as_f64()) {- Some(v) => v,- None => return ToolResult::error("Either element_token or x + y must be provided."),- };- let mut cy = match args.get("y").and_then(|v| v.as_f64()) {- Some(v) => v,- None => return ToolResult::error("Missing required parameter: y"),- };-- // Scale back from downscaled-image space to native pixels when needed.- let ratio = match super::screenshot_scale(&self.state, &args, pid, window_id) {- Ok(ratio) => ratio,- Err(refusal) => return refusal,- };- cx *= ratio;- cy *= ratio;-- // Window-local → screen coordinate translation + win-local logical coords- // for CGEventSetWindowLocation (shared with click.rs via px_frame, which- // refuses a window with no live frame instead of silently treating the- // local point as screen-absolute).- let (screen_x, screen_y, win_local_x, win_local_y) = if let Some(wid) = window_id {- match super::px_frame::resolve_or_refuse(wid).await {- Ok(frame) => {- let translated = frame.to_screen(cx, cy);- if !delivery_mode.is_foreground()- && (translated.2 < 0.0- || translated.3 < 0.0- || translated.2 > frame.bounds.width- || translated.3 > frame.bounds.height)- {- return ToolResult::error(format!(- "double_click: window-local point ({:.1}, {:.1}) pt lies outside \- window {wid}'s {:.0}×{:.0} pt frame; background delivery refused",- translated.2, translated.3, frame.bounds.width, frame.bounds.height- ));- }- translated- }- Err(refusal) => return refusal,- }- } else {- (cx, cy, cx, cy)- };-- let _mutation_lease = if !delivery_mode.is_foreground() {- if let Some(wid) = window_id {- match super::gate_background_window_action(- pid,- wid,- None,- cua_driver_core::background_input::BackgroundAction::WindowPointer,- )- .await- {- Ok(lease) => Some(lease),- Err(refusal_result) => return refusal_result,- }- } else {- None- }- } else {- None- };-- // Pin overlay above the target window before animating.- if let Some(wid) = window_id {- crate::cursor::overlay::send_command(- cursor_key.clone(),- cursor_overlay::OverlayCommand::PinAbove(wid as u64),- );+ // A pixel double-click is a click with count 2. Route it through+ // `click` so it gets the same coordinate mapping, exact-window gate,+ // window-change observation, key-focus guard and focus-steal restore.+ // Some apps activate themselves when a double-click opens something+ // (GnuCash opening an account register); before this, the pixel+ // double-click had none of those and the activation stayed (Bench v2+ // CDB-G03, CUA-1341).+ if args.get("x").and_then(|v| v.as_f64()).is_none() {+ return ToolResult::error("Either element_token or x + y must be provided.");}- // Animate cursor to the click point; wait for arrival before firing.- crate::cursor::overlay::animate_cursor_to(cursor_key.clone(), screen_x, screen_y).await;- crate::cursor::overlay::send_command(- cursor_key.clone(),- cursor_overlay::OverlayCommand::ClickPulse {- x: screen_x,- y: screen_y,- },- );-- let fg = delivery_mode.is_foreground() && window_id.is_some();- let route =- match super::pixel_route::resolve(pid, fg, window_id, "mouse_double_click").await {- Ok(route) => route,- Err(refusal) => return refusal,- };- let result = tokio::task::spawn_blocking(move || -> anyhow::Result<()> {- let do_click = move || -> anyhow::Result<()> {- if route == super::pixel_route::PixelClickRoute::ForegroundHid {- // Warp the hardware pointer and post at the HID tap; see- // `pixel_route` for the cross-platform foreground contract.- return crate::input::mouse::click_at_xy_desktop_with_modifiers(- screen_x,- screen_y,- 2,- "left",- &[],- );- }- if let Some(wid) = window_id {- crate::input::mouse::click_at_xy_with_window_local(- pid,- screen_x,- screen_y,- win_local_x,- win_local_y,- wid,- 2,- &[],- crate::input::mouse::WindowClickDelivery::from_foreground(fg),- )- } else {- crate::input::mouse::click_at_xy(pid, screen_x, screen_y, 2, &[])- }- };- // Foreground rung: front the exact window → HID double-click →- // restore the prior frontmost. No input is sent unless the exact- // window is proven focused.- match (route, window_id) {- (super::pixel_route::PixelClickRoute::ForegroundHid, Some(wid)) => {- crate::input::skylight::with_foreground_hid_activation(- pid as libc::pid_t,- wid,- do_click,- )- }- _ => do_click(),- }- })- .await;-- match result {- Ok(Ok(())) => ToolResult::text(format!(- "✅ Double-clicked at ({screen_x:.1}, {screen_y:.1}) ({}).",- super::pixel_route::delivery_note(route)- ))- .with_structured(serde_json::json!({- "path": super::pixel_route::path_label(route), "verified": false, "effect": "unverifiable"- })),- Ok(Err(e)) if route == super::pixel_route::PixelClickRoute::ForegroundHid => {- super::pixel_route::foreground_unavailable(- "Double-click",- window_id.unwrap_or_default(),- &e.to_string(),- )- }- Ok(Err(e)) => ToolResult::error(format!("Double-click failed: {e}")),- Err(e) => ToolResult::error(format!("Task error: {e}")),+ if args.get("y").and_then(|v| v.as_f64()).is_none() {+ return ToolResult::error("Missing required parameter: y");}+ let mut click_args = args;+ if let Some(map) = click_args.as_object_mut() {+ map.insert("count".into(), serde_json::json!(2));+ }+ super::click::ClickTool::new(self.state.clone())+ .invoke(click_args)+ .await}}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rsindex 0f0574ce30..648a0adb05 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs@@ -88,6 +88,7 @@ impl Tool for LaunchAppTool {async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;crate::window_change_detector::end_tail();+ crate::window_change_detector::note_intentional_activation();let bundle_id = args.opt_str("bundle_id");let name = args.opt_str("name");let mut response_bundle_id = bundle_id.clone();diff --git a/libs/cua-driver/rust/crates/platform-macos/src/window_change_detector.rs b/libs/cua-driver/rust/crates/platform-macos/src/window_change_detector.rsindex 4ecaed91cf..82d073f3d8 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/window_change_detector.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/window_change_detector.rs@@ -244,6 +244,22 @@ pub fn end_tail() {drop(tail);}+/// Advanced whenever the driver itself makes an app frontmost (bring_to_front,+/// launch_app, any foreground delivery). The key-focus guard reverts a+/// background target's self-activation only while this has not moved since+/// the guard was armed, so it never undoes an activation the driver asked for.+static INTENTIONAL_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);++/// Record an activation the driver asked for.+pub fn note_intentional_activation() {+ INTENTIONAL_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+}++/// The current intentional-activation epoch.+pub fn intentional_epoch() -> u64 {+ INTENTIONAL_EPOCH.load(std::sync::atomic::Ordering::SeqCst)+}+/// Take a late change recorded by a detached tail, if it is recent.fn take_late() -> Option<Late> {lock(&LATE)