Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(platform-macos): raise own-process windows on the AppKit main queue (CUA-3309) (#6559)

injaneity95b3b9bc9485
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.rs
index 04d55a4417..d0527f49b6 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
@@ -563,7 +563,20 @@ pub fn focused_window_id_of_pid(pid: i32) -> Option<u32> {
/// the alternative, is only a request under cooperative activation; Chromium
/// keeps its window above it, and when it is honoured the user's app gets a
/// fresh `didBecomeActive`.
+///
+/// When `pid` is this process, the raise runs on the AppKit main queue.
pub fn raise_focused_window_of_pid(pid: i32) -> bool {
+ super::main_thread::run_ax_mutation(pid, OWN_WINDOW_RAISE_TIMEOUT, move || {
+ raise_focused_window_of_pid_here(pid)
+ })
+ .unwrap_or(false)
+}
+
+/// Bound on waiting for the main queue to raise one of this process's own
+/// windows; a stalled main thread must not hang the calling worker.
+const OWN_WINDOW_RAISE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
+
+fn raise_focused_window_of_pid_here(pid: i32) -> bool {
unsafe {
let app = AXUIElementCreateApplication(pid);
if app.is_null() {
@@ -589,7 +602,16 @@ pub fn raise_focused_window_of_pid(pid: i32) -> bool {
/// is what moves the key window between siblings; a front-process change on
/// its own leaves AppKit's key window where it was. No other window of the
/// process is addressed.
+///
+/// When `pid` is this process, the raise runs on the AppKit main queue.
pub fn raise_exact_window_of_pid(pid: i32, window_id: u32) -> bool {
+ super::main_thread::run_ax_mutation(pid, OWN_WINDOW_RAISE_TIMEOUT, move || {
+ raise_exact_window_of_pid_here(pid, window_id)
+ })
+ .unwrap_or(false)
+}
+
+fn raise_exact_window_of_pid_here(pid: i32, window_id: u32) -> bool {
unsafe {
let app = AXUIElementCreateApplication(pid);
if app.is_null() {
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/main_thread.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/main_thread.rs
new file mode 100644
index 0000000000..4ce07500aa
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/main_thread.rs
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Thread affinity for AX mutations aimed at this process's own windows.
+//!
+//! An AX action against another process executes in that process. When an
+//! embedded driver targets its own window, AppKit services the action (for
+//! `AXRaise`, `NSWindow makeKeyAndOrderFront:`) in this process on the calling
+//! thread, and window ordering is main-thread-only. Off the main thread, such
+//! a call is queued onto AppKit's main queue and the caller waits for it.
+
+use std::{
+ ffi::c_void,
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ mpsc::{self, RecvTimeoutError, SyncSender},
+ Arc,
+ },
+ time::Duration,
+};
+
+#[link(name = "System", kind = "framework")]
+extern "C" {
+ static _dispatch_main_q: u8;
+ fn dispatch_async_f(
+ queue: *const c_void,
+ context: *mut c_void,
+ work: unsafe extern "C" fn(*mut c_void),
+ );
+}
+
+/// Whether an AX mutation against `pid` must run on the main thread before
+/// it may run on `on_main_thread`'s thread.
+pub(crate) fn needs_main_queue(pid: i32, on_main_thread: bool) -> bool {
+ pid == std::process::id() as i32 && !on_main_thread
+}
+
+struct Request<F, T> {
+ work: F,
+ tx: SyncSender<T>,
+ cancelled: Arc<AtomicBool>,
+}
+
+unsafe extern "C" fn run_request<F, T>(context: *mut c_void)
+where
+ F: FnOnce() -> T,
+{
+ let request = unsafe { Box::from_raw(context.cast::<Request<F, T>>()) };
+ if request.cancelled.load(Ordering::Acquire) {
+ return;
+ }
+ let _ = request.tx.send((request.work)());
+}
+
+/// Run the AX mutation `work` against `pid` with the thread affinity it
+/// needs: inline for another process or on the main thread, else on AppKit's
+/// main queue, waiting at most `timeout`. On timeout the queued work is
+/// cancelled so a stale window change cannot fire after the caller gave up.
+pub(crate) fn run_ax_mutation<F, T>(
+ pid: i32,
+ timeout: Duration,
+ work: F,
+) -> Result<T, RecvTimeoutError>
+where
+ F: FnOnce() -> T + Send + 'static,
+ T: Send + 'static,
+{
+ let on_main_thread = objc2_foundation::MainThreadMarker::new().is_some();
+ if !needs_main_queue(pid, on_main_thread) {
+ return Ok(work());
+ }
+ let (tx, rx) = mpsc::sync_channel(1);
+ let cancelled = Arc::new(AtomicBool::new(false));
+ let request = Box::new(Request {
+ work,
+ tx,
+ cancelled: Arc::clone(&cancelled),
+ });
+ unsafe {
+ let main_queue = &raw const _dispatch_main_q as *const c_void;
+ dispatch_async_f(
+ main_queue,
+ Box::into_raw(request).cast::<c_void>(),
+ run_request::<F, T>,
+ );
+ }
+ let result = rx.recv_timeout(timeout);
+ if result.is_err() {
+ cancelled.store(true, Ordering::Release);
+ }
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn only_own_process_off_main_thread_is_queued() {
+ let own = std::process::id() as i32;
+ assert!(needs_main_queue(own, false));
+ assert!(!needs_main_queue(own, true));
+ assert!(!needs_main_queue(own.wrapping_add(1), false));
+ assert!(!needs_main_queue(own.wrapping_add(1), true));
+ }
+
+ #[test]
+ fn other_process_runs_inline_on_the_calling_thread() {
+ let caller = std::thread::current().id();
+ let ran_on = run_ax_mutation(
+ (std::process::id() as i32).wrapping_add(1),
+ Duration::ZERO,
+ || std::thread::current().id(),
+ );
+ assert_eq!(ran_on, Ok(caller));
+ }
+
+ #[test]
+ fn own_process_waits_for_the_main_queue_and_cancels_on_timeout() {
+ // The cargo test harness never drains the main queue, so the
+ // own-process mutation must not run on this worker thread.
+ let ran = Arc::new(AtomicBool::new(false));
+ let flag = Arc::clone(&ran);
+ let result = std::thread::spawn(move || {
+ run_ax_mutation(
+ std::process::id() as i32,
+ Duration::from_millis(50),
+ move || flag.store(true, Ordering::Release),
+ )
+ })
+ .join()
+ .unwrap();
+ assert_eq!(result, Err(RecvTimeoutError::Timeout));
+ assert!(!ran.load(Ordering::Acquire));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs
index 8c252b0dbd..f41036ad40 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs
@@ -23,6 +23,7 @@ pub mod bindings;
pub mod enablement;
pub mod exact_target;
pub mod launch;
+pub(crate) mod main_thread;
pub mod reveal_scroll;
pub mod snapshot;
pub mod tree;
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/invoke_menu.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/invoke_menu.rs
index 49467e6af0..e37391b0b2 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/invoke_menu.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/invoke_menu.rs
@@ -13,15 +13,7 @@ use cua_driver_core::{
tool::{Tool, ToolDef},
};
use serde_json::Value;
-use std::{
- ffi::c_void,
- sync::{
- atomic::{AtomicBool, Ordering},
- mpsc::{self, SyncSender},
- Arc,
- },
- time::Duration,
-};
+use std::time::Duration;
use crate::ax::bindings::{
ax_get_window_id, copy_action_names, copy_ax_windows, copy_bool_attr, copy_children,
@@ -418,70 +410,18 @@ fn focus_ax_window(pid: i32, window_id: u32) -> Result<(), String> {
Ok(())
}
-struct AxWindowFocusRequest {
- pid: i32,
- window_id: u32,
- tx: SyncSender<Result<(), String>>,
- cancelled: Arc<AtomicBool>,
-}
-
-#[link(name = "System", kind = "framework")]
-extern "C" {
- static _dispatch_main_q: u8;
- fn dispatch_async_f(
- queue: *const c_void,
- context: *mut c_void,
- work: unsafe extern "C" fn(*mut c_void),
- );
-}
-
-unsafe extern "C" fn focus_ax_window_on_main(context: *mut c_void) {
- let request = unsafe { Box::from_raw(context.cast::<AxWindowFocusRequest>()) };
- if request.cancelled.load(Ordering::Acquire) {
- return;
- }
- let result = focus_ax_window(request.pid, request.window_id);
- let _ = request.tx.send(result);
-}
-
fn focus_ax_window_with_thread_affinity(pid: i32, window_id: u32) -> Result<(), String> {
- let is_main_thread = objc2_foundation::MainThreadMarker::new().is_some();
- if pid != std::process::id() as i32 || is_main_thread {
- return focus_ax_window(pid, window_id);
- }
-
- // AX actions against another process execute in that process. An embedded
- // driver targeting its own window is different: AppKit services AXRaise
- // in this process, and window ordering is main-thread-only. Queue just the
- // self-process AX mutation onto AppKit's main queue, then return to the
- // blocking worker for readiness polling and menu traversal.
- let (tx, rx) = mpsc::sync_channel(1);
- let cancelled = Arc::new(AtomicBool::new(false));
- let request = Box::new(AxWindowFocusRequest {
- pid,
- window_id,
- tx,
- cancelled: Arc::clone(&cancelled),
- });
- unsafe {
- let main_queue = &raw const _dispatch_main_q as *const c_void;
- dispatch_async_f(
- main_queue,
- Box::into_raw(request).cast::<c_void>(),
- focus_ax_window_on_main,
- );
- }
- match rx.recv_timeout(MAIN_QUEUE_TIMEOUT) {
- Ok(result) => result,
- Err(error) => {
- // If AppKit never serviced the request, prevent a stale focus
- // change from firing after this tool call has already failed.
- cancelled.store(true, Ordering::Release);
- Err(format!(
- "invoke_menu: failed waiting for the embedded host window on the AppKit main queue: {error}"
- ))
- }
- }
+ // An embedded driver targeting its own window must raise it on AppKit's
+ // main queue; see `ax::main_thread`. Only the AX mutation moves there; the
+ // blocking worker keeps readiness polling and menu traversal.
+ crate::ax::main_thread::run_ax_mutation(pid, MAIN_QUEUE_TIMEOUT, move || {
+ focus_ax_window(pid, window_id)
+ })
+ .unwrap_or_else(|error| {
+ Err(format!(
+ "invoke_menu: failed waiting for the embedded host window on the AppKit main queue: {error}"
+ ))
+ })
}
fn focus_exact_window(pid: i32, window_id: u32) -> Result<(), String> {