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): focus exact target for native menus (#2788)
Francesco Bonacci2269fa352a80
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_appkit_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_appkit_test.rsindex 65fe2c6e27..95f6eefe32 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_appkit_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_appkit_test.rs@@ -377,6 +377,11 @@ fn harness_appkit_invoke_menu_live_path() {.tree_text().contains("menu_action=none"));+ // A second native process deliberately steals AppKit activation+ // and key-window status. The target menu item validates against+ // both, so an AXFocused-only implementation cannot pass this cell.+ let _distractor = Harness::launch();+let invoked = driver.call("invoke_menu",serde_json::json!({diff --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 4fcd051231..b8e88edc62 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@@ -445,6 +445,51 @@ pub fn set_front_process_persistently(target_pid: libc::pid_t, target_wid: u32)unsafe { set_front(target_psn.as_ptr() as *const c_void, target_wid, 0x400) == 0 }}+fn make_key_window_record(window_id: u32, event_kind: u8) -> [u8; 0xF8] {+ let mut record = [0u8; 0xF8];+ record[0x04] = 0xF8;+ record[0x08] = event_kind;+ record[0x3A] = 0x10;+ record[0x3C..0x40].copy_from_slice(&window_id.to_le_bytes());+ record[0x20..0x30].fill(0xFF);+ record+}++/// Make one exact application window native-key and frontmost.+///+/// Accessibility's `AXFocusedWindow` can change without AppKit making the+/// corresponding `NSWindow` key. Native menu validation observes the latter,+/// so focus-sensitive commands remain disabled in that split state. This is+/// the bounded exact-window sequence used by established macOS window tools:+/// mark the front-process request as user generated, synthesize the paired+/// make-key records for the requested WindowServer id, then let the caller+/// raise the matching AX window. No other application window is addressed.+pub fn make_exact_window_key(target_pid: libc::pid_t, target_wid: u32) -> bool {+ let Some(set_front) = set_front_process_fn() else {+ return false;+ };+ let Some(post) = post_event_record_to_fn() else {+ return false;+ };+ let mut target_psn = [0u8; 8];+ if !get_process_psn_for_window(target_wid, target_pid, &mut target_psn) {+ return false;+ }++ // kCPSUserGenerated = 0x200. Unlike kCPSNoWindows, this permits AppKit to+ // establish the requested native key window before it validates NSMenu.+ if unsafe { set_front(target_psn.as_ptr() as *const c_void, target_wid, 0x200) } != 0 {+ return false;+ }+ for event_kind in [0x01, 0x02] {+ let record = make_key_window_record(target_wid, event_kind);+ if unsafe { post(target_psn.as_ptr() as *const c_void, record.as_ptr()) } != 0 {+ return false;+ }+ }+ true+}+/// Tool-agnostic foreground-assist: briefly front `window_id`, run `body` (which/// posts the synthetic input), then restore the prior frontmost process.///@@ -582,7 +627,20 @@ pub fn with_menu_shortcut_activation(#[cfg(test)]mod tests {- use super::preserves_exact_existing_focus;+ use super::{make_key_window_record, preserves_exact_existing_focus};++ #[test]+ fn make_key_records_address_only_the_exact_window() {+ let press = make_key_window_record(0x7856_3412, 0x01);+ let release = make_key_window_record(0x7856_3412, 0x02);+ assert_eq!(press.len(), 0xF8);+ assert_eq!(press[0x04], 0xF8);+ assert_eq!(press[0x08], 0x01);+ assert_eq!(release[0x08], 0x02);+ assert_eq!(&press[0x3C..0x40], &[0x12, 0x34, 0x56, 0x78]);+ assert_eq!(press[0x3A], 0x10);+ assert!(press[0x20..0x30].iter().all(|byte| *byte == 0xFF));+ }#[test]fn exact_existing_focus_avoids_reactivation() {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.rsindex c41b738ecb..ed6f812713 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,9 +13,9 @@ use serde_json::Value;use std::time::Duration;use crate::ax::bindings::{- copy_action_names, copy_bool_attr, copy_children, copy_element_attr, copy_string_attr,- kAXErrorSuccess, perform_action, AXUIElementCreateApplication, AXUIElementRef,- AXUIElementSetMessagingTimeout,+ ax_get_window_id, copy_action_names, copy_ax_windows, copy_bool_attr, copy_children,+ copy_element_attr, copy_string_attr, kAXErrorSuccess, perform_action, set_bool_attr_true,+ AXUIElementCreateApplication, AXUIElementRef, AXUIElementSetMessagingTimeout,};pub struct InvokeMenuTool;@@ -184,6 +184,81 @@ unsafe fn invoke_path(pid: i32, path: &[String]) -> Result<(), String> {result}+/// Make one exact application window key before resolving focus-sensitive+/// native menu state.+///+/// `SLPSSetFrontProcessWithOptions(..., kCPSNoWindows)` makes the application+/// active without broadly raising its windows. That is the right default for+/// input delivery, but it can leave the requested window non-key. macOS then+/// exposes contextual Window-menu commands (including Move & Resize) as+/// disabled even though the application itself is frontmost. Raise and mark+/// only the requested AX window, then require an exact focused-window readback+/// before menu resolution proceeds.+fn focus_exact_window(pid: i32, window_id: u32) -> Result<(), String> {+ let native_key_requested = crate::input::skylight::make_exact_window_key(pid, window_id);+ if !native_key_requested+ && crate::apps::frontmost_pid() != Some(pid)+ && !crate::apps::activate_pid(pid)+ {+ return Err("invoke_menu: target application could not be activated".into());+ }+ if !native_key_requested {+ std::thread::sleep(Duration::from_millis(120));+ }++ unsafe {+ let app = AXUIElementCreateApplication(pid);+ if app.is_null() {+ return Err("invoke_menu: target application is unavailable".into());+ }+ set_messaging_timeout(app);++ let mut target = None;+ for window in copy_ax_windows(app) {+ if target.is_none() && ax_get_window_id(window) == Some(window_id) {+ target = Some(window);+ } else {+ CFRelease(window as CFTypeRef);+ }+ }+ CFRelease(app as CFTypeRef);++ let Some(target) = target else {+ return Err("invoke_menu: target accessibility window is unavailable".into());+ };+ set_messaging_timeout(target);++ // SkyLight has requested native key status for this exact window. AX+ // raise/main/focus completes the corresponding visible and semantic+ // state; these writes remain best-effort for applications that expose+ // only a subset of the attributes.+ let _ = perform_action(target, "AXRaise");+ let _ = set_bool_attr_true(target, "AXMain");+ let _ = set_bool_attr_true(target, "AXFocused");+ CFRelease(target as CFTypeRef);+ }++ let deadline = std::time::Instant::now() + Duration::from_millis(600);+ loop {+ if exact_window_is_focused(+ crate::ax::bindings::focused_window_id_of_pid(pid),+ window_id,+ ) {+ return Ok(());+ }+ if std::time::Instant::now() >= deadline {+ return Err(format!(+ "invoke_menu: target window {window_id} did not become the focused window"+ ));+ }+ std::thread::sleep(Duration::from_millis(20));+ }+}++fn exact_window_is_focused(focused_window_id: Option<u32>, target_window_id: u32) -> bool {+ focused_window_id == Some(target_window_id)+}+fn refusal(message: String) -> ToolResult {ToolResult::error(message.clone()).with_structured(serde_json::json!({"status": "refused",@@ -224,20 +299,26 @@ impl Tool for InvokeMenuTool {let outcome = tokio::task::spawn_blocking(move || {let prior_frontmost = crate::apps::frontmost_pid();+ let prior_frontmost_window =+ prior_frontmost.and_then(crate::ax::bindings::focused_window_id_of_pid);let needs_activation = prior_frontmost != Some(pid);- if needs_activation- && !crate::input::skylight::set_front_process_persistently(pid, window_id)- && !crate::apps::activate_pid(pid)- {- return Err("invoke_menu: target application could not be activated".into());- }- if needs_activation {- std::thread::sleep(Duration::from_millis(120));- }- let result = unsafe { invoke_path(pid, &path) };- if needs_activation {- if let Some(prior_pid) = prior_frontmost {- let _ = crate::apps::activate_pid(prior_pid);++ let result = focus_exact_window(pid, window_id)+ .and_then(|()| unsafe { invoke_path(pid, &path) });++ // Restore the exact prior key window when one was observable,+ // including across applications. Falling back to app activation+ // preserves the previous behavior for apps without an AX window.+ if let Some(prior_pid) = prior_frontmost {+ let already_restored =+ prior_pid == pid && prior_frontmost_window == Some(window_id);+ if !already_restored {+ let restored_exact = prior_frontmost_window.is_some_and(|prior_window_id| {+ focus_exact_window(prior_pid, prior_window_id).is_ok()+ });+ if needs_activation && !restored_exact {+ let _ = crate::apps::activate_pid(prior_pid);+ }}}result@@ -288,4 +369,11 @@ mod tests {assert_eq!(choose_action(&actions, true), Some("AXPress"));assert_eq!(choose_action(&["AXShowMenu".into()], true), None);}++ #[test]+ fn menu_focus_requires_the_exact_requested_window() {+ assert!(exact_window_is_focused(Some(42), 42));+ assert!(!exact_window_is_focused(Some(41), 42));+ assert!(!exact_window_is_focused(None, 42));+ }}diff --git a/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift b/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swiftindex ced302f9d8..71852fefb1 100644--- a/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift+++ b/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift@@ -51,7 +51,7 @@ let kMenuItemTitle = "Harness Test Item"// MARK: - Controller-final class HarnessWindowController: NSObject, NSTextFieldDelegate {+final class HarnessWindowController: NSObject, NSTextFieldDelegate, NSMenuItemValidation {let window: NSWindowlet counterLabel = NSTextField(labelWithString: "counter=0")var counterValue = 0@@ -367,6 +367,17 @@ final class HarnessWindowController: NSObject, NSTextFieldDelegate {menuActionLabel.stringValue = "menu_action=window_arrange_left"}+ func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {+ if menuItem.action == #selector(onArrangeLeft(_:)) {+ // Real macOS Window-menu commands are contextual: the application+ // being active is insufficient when the requested window is not+ // key. Keep this fixture honest so invoke_menu must establish the+ // exact window context before resolving the final item.+ return NSApp.isActive && window.isKeyWindow+ }+ return true+ }+func controlTextDidChange(_ obj: Notification) {guard let field = obj.object as? NSTextField else { return }if field === textInput {