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): keep the user's key window during background work on macOS (#4943)
Francesco Bonaccie32127764436
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/click.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/click.mdxindex 2c4aa08a9b..ed3b05916a 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools/click.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools/click.mdx@@ -26,7 +26,7 @@ Click a target pid. Prefer `element_token` (from get_window_state): it identifie- element_token: AX action path. Tokens are scoped to (pid, window_id) and stale once the window is snapshotted again.- x, y: window-local pixels of the get_window_state screenshot, sent as CGEvent mouse events. Needs a visible window. `modifier` takes cmd/shift/option/ctrl.-`button` defaults to left; on the AX path "right" maps to AXShowMenu and "middle" falls back to a pixel click at the element center. `action`: press (default), show_menu, pick, confirm, cancel, open. `from_zoom:true` translates zoom-image pixels after a `zoom` call. Pressing a popup button opens its menu and leaves it open (holding key focus) until dismissed; to choose an option use `set_value`.+`button` defaults to left; on the AX path "right" maps to AXShowMenu and "middle" falls back to a pixel click at the element center. `action`: press (default), show_menu, pick, confirm, cancel, open. `from_zoom:true` translates zoom-image pixels after a `zoom` call. Pressing a popup button opens its menu and leaves it open until an item is chosen or it is dismissed; in the background the user's front window keeps key focus meanwhile. To choose an option in one call use `set_value`.**macOS parameters**diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/values-and-clipboard.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/values-and-clipboard.mdxindex b14d297894..aaa7e9a5cc 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools/values-and-clipboard.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools/values-and-clipboard.mdx@@ -27,7 +27,7 @@ Effect: destructive, idempotent. Platforms: macOS, Linux, Windows.<Tabs items={['macOS', 'Linux', 'Windows']} groupId="platform" persist><Tab value="macOS">-Set an element's value by `element_token`. A popup button / select dropdown: selects the menu item whose title or value matches `value` (case-insensitive). Safari `<select>` is set through the DOM; AppKit and Chromium popups list items only while open, so the menu is opened, the item pressed and the menu closed again (the front window loses key focus for ~0.4 s). An unknown value lists the options. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).+Set an element's value by `element_token`. A popup button / select dropdown: selects the menu item whose title or value matches `value` (case-insensitive). Safari `<select>` is set through the DOM; AppKit and Chromium popups list items only while open, so the menu is opened, the item pressed and the menu closed again (in the background the user's front window keeps key focus). An unknown value lists the options. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).A Finder file name (list row or Get Info `Name` field, not being edited) is refused with `file_name_needs_rename`; the refusal names the keyboard route. For free-form text in web inputs use `type_text_chars`: WebKit ignores AXValue writes.diff --git a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md b/libs/cua-driver/rust/Skills/cua-driver/MACOS.mdindex 5784cf1ba8..d05c093611 100644--- a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md+++ b/libs/cua-driver/rust/Skills/cua-driver/MACOS.md@@ -288,14 +288,24 @@ permission prompt the agent loop shouldn't be burning on app launch.The pixel click is routed through SkyLight's per-pid event path(`SLEventPostToPid`), not the system HID stream. The dispatch recipe-is the backgrounded "noraise" sequence: focus-without-raise-SLPS event records followed by an off-screen user-activation primer-and the real click. The target app becomes AppKit-active for event-routing but its window does **not** rise to the front of the-z-stack, and macOS's "switch to Space with windows for app" follow-is suppressed. Full mechanics in-`Sources/CuaDriverCore/Input/MouseInput.swift` (`clickViaAuthSignedPost`)-and the companion `FocusWithoutRaise.swift`.+is the backgrounded "noraise" sequence: a focus-without-raise+SLPS event record to the target window, followed by an off-screen+user-activation primer and the real click. The target window becomes+AppKit-key for event routing, but it does **not** rise to the front of+the z-stack, macOS's "switch to Space with windows for app" follow is+suppressed, and the user's front window keeps key status, so their+typing keeps landing there.++### Menus opened in the background keep the user's keyboard++A popup button, a `<select>`, or a context menu opened in a background+app takes key focus from the user's front window for as long as the menu+is open (AppKit's menu tracking steals it). While a background action+runs, Cua Driver watches for that and hands key focus straight back, so+the user's window never loses it. The menu stays open and its items are+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.### `delivery_mode` on the pointer family (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 756fa79270..a836ead09c 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@@ -2093,3 +2093,149 @@ fn harness_appkit_slider_drag_px_background() {)});}++/// popup_select: a background AXPress opens the NSPopUpButton's menu. The menu+/// steals key focus from the front app, so the background oracles (the+/// foreground sentinel must not blur) check that the driver hands it back.+/// The menu stays open and its item is chosen through accessibility.+#[test]+#[ignore]+fn harness_appkit_popup_click_keeps_front_key_focus_background() {+ run_background_case(+ "popup_click",+ DriverRoute::MacosAxAction,+ |pid, wid, driver| {+ let pre = snapshot_elements(driver, pid, wid);+ assert!(+ pre.tree_text().contains("popup_value=Choose a team"),+ "popup fixture missing:\n{}",+ pre.tree_text()+ );+ let opened = driver.call(+ "click",+ serde_json::json!({+ "pid": pid as i64,+ "window_id": wid,+ "element_token": element_token_by_id(&pre, "pop-team"),+ "delivery_mode": "background"+ }),+ );+ assert!(!opened.is_error(), "popup click failed: {}", opened.text());++ let open = snapshot_elements(driver, pid, wid);+ let item = element_index_containing(open.tree_text(), "AXMenuItem \"Research\"")+ .unwrap_or_else(|| {+ panic!("open popup lists no Research item:\n{}", open.tree_text())+ });+ let chosen = driver.call(+ "click",+ serde_json::json!({+ "pid": pid as i64,+ "window_id": wid,+ "element_token": open.element_token(item),+ "delivery_mode": "background"+ }),+ );+ assert!(+ !chosen.is_error(),+ "menu item click failed: {}",+ chosen.text()+ );++ let deadline = Instant::now() + Duration::from_secs(2);+ loop {+ if snapshot_elements(driver, pid, wid)+ .tree_text()+ .contains("popup_value=Research")+ {+ break;+ }+ assert!(Instant::now() < deadline, "popup selection did not land");+ std::thread::sleep(Duration::from_millis(100));+ }+ },+ );+}++/// popup_select through set_value: the driver opens the menu, presses the+/// matching item and closes it, while the front window keeps key status.+#[test]+#[ignore]+fn harness_appkit_popup_set_value_keeps_front_key_focus_background() {+ run_background_case(+ "popup_set_value",+ DriverRoute::MacosAxValue,+ |pid, wid, driver| {+ let pre = snapshot_elements(driver, pid, wid);+ let set = driver.call(+ "set_value",+ serde_json::json!({+ "pid": pid as i64,+ "window_id": wid,+ "element_token": element_token_by_id(&pre, "pop-team"),+ "value": "Finance"+ }),+ );+ assert!(!set.is_error(), "popup set_value failed: {}", set.text());+ std::thread::sleep(Duration::from_millis(250));+ assert!(+ snapshot_elements(driver, pid, wid)+ .tree_text()+ .contains("popup_value=Finance"),+ "popup set_value did not land"+ );+ },+ );+}++/// context_menu through right_click (AXShowMenu) in the background: the menu+/// steals key focus like a popup does; the front window must keep it.+#[test]+#[ignore]+fn harness_appkit_context_menu_keeps_front_key_focus_background() {+ run_background_case(+ "context_menu",+ DriverRoute::MacosAxAction,+ |pid, wid, driver| {+ let pre = snapshot_elements(driver, pid, wid);+ let shown = driver.call(+ "right_click",+ serde_json::json!({+ "pid": pid as i64,+ "window_id": wid,+ "element_token": element_token_by_id(&pre, "btn-context")+ }),+ );+ assert!(!shown.is_error(), "context menu failed: {}", shown.text());+ let open = snapshot_elements(driver, pid, wid);+ let item = element_index_containing(open.tree_text(), "AXMenuItem \"Copy\"")+ .unwrap_or_else(|| {+ panic!(+ "open context menu lists no Copy item:\n{}",+ open.tree_text()+ )+ });+ let chosen = driver.call(+ "click",+ serde_json::json!({+ "pid": pid as i64,+ "window_id": wid,+ "element_token": open.element_token(item),+ "delivery_mode": "background"+ }),+ );+ assert!(+ !chosen.is_error(),+ "context item click failed: {}",+ chosen.text()+ );+ std::thread::sleep(Duration::from_millis(250));+ assert!(+ snapshot_elements(driver, pid, wid)+ .tree_text()+ .contains("menu_action=Copy"),+ "context menu item did not fire"+ );+ },+ );+}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/focus_guard.rs b/libs/cua-driver/rust/crates/platform-macos/src/focus_guard.rsindex a271397a30..7c859bc301 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/focus_guard.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/focus_guard.rs@@ -107,6 +107,18 @@ whereNone};+ // Hand key focus back to the user's app if the target opens a menu+ // (popup, select, context menu) while it is in the background.+ let _key_focus = match target_pid {+ Some(tp) if prior_frontmost != Some(tp) => {+ tokio::task::spawn_blocking(move || crate::key_focus_guard::protect(tp))+ .await+ .ok()+ .flatten()+ }+ _ => None,+ };+let result = f().await;// Post-action settle — give the reactive observer time to fire ondiff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rsindex b7aadfa970..31a72ffe51 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs@@ -499,8 +499,9 @@ fn click_at_xy_inner(})}-/// Prepare a raw background pixel click by making the target AppKit-active-/// without raising or restacking its window.+/// Prepare a raw background pixel click by making the target window AppKit-key+/// without raising or restacking it and without taking key status from the+/// user's window.////// The Swift implementation ran this immediately before the stamped event/// stream. The original Rust port retained the SkyLight primitive but omitted@@ -510,7 +511,12 @@ fn click_at_xy_inner(/// Returns whether the private focus-without-raise recipe succeeded. Event/// posting remains best-effort when the private APIs are unavailable.pub fn prepare_background_pixel_click(pid: i32, wid: u32) -> bool {- let activated = crate::input::skylight::activate_without_raise(pid as libc::pid_t, wid);+ // Post only the focus record to the target. The defocus record to the+ // current front process made the user's key window resign key, and+ // re-activating that process afterwards did not make the window key+ // again, so the user's typing was dropped until they clicked it.+ let activated =+ crate::input::skylight::activate_without_raise_with(pid as libc::pid_t, wid, false);// Match Swift's settle interval so AppKit updates its active/key-window// routing before the mouseMoved + primer + target stream arrives.std::thread::sleep(std::time::Duration::from_millis(50));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 452d8dc77e..4d8b7636ab 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@@ -488,6 +488,95 @@ impl SpaceQuery {}}+// ── Key-focus theft ───────────────────────────────────────────────────────────++/// `CGError SLPSStealKeyFocusReturningID(uint32_t cid, uint32_t options, int32_t *theft_id)`+type StealKeyFocusReturningIdFn = unsafe extern "C" fn(u32, u32, *mut i32) -> i32;++/// `CGError SLPSReleaseKeyFocusWithID(int32_t theft_id)`+type ReleaseKeyFocusWithIdFn = unsafe extern "C" fn(i32) -> i32;++fn steal_key_focus_fn() -> Option<StealKeyFocusReturningIdFn> {+ static SYM: OnceLock<Option<StealKeyFocusReturningIdFn>> = OnceLock::new();+ *SYM.get_or_init(|| find_sym(b"SLPSStealKeyFocusReturningID\0").map(|p| unsafe { as_fn(p) }))+}++fn release_key_focus_fn() -> Option<ReleaseKeyFocusWithIdFn> {+ static SYM: OnceLock<Option<ReleaseKeyFocusWithIdFn>> = OnceLock::new();+ *SYM.get_or_init(|| find_sym(b"SLPSReleaseKeyFocusWithID\0").map(|p| unsafe { as_fn(p) }))+}++/// `OSStatus SLPSGetKeyFocusProcess(ProcessSerialNumber *psn, uint32_t *connection)`.+/// Both are out-parameters; the second must be a valid pointer.+type GetKeyFocusProcessFn = unsafe extern "C" fn(*mut c_void, *mut c_void) -> i32;++/// `OSStatus GetProcessPID(const ProcessSerialNumber *psn, pid_t *pid)`+type GetProcessPidFn = unsafe extern "C" fn(*const c_void, *mut pid_t) -> i32;++fn get_key_focus_process_fn() -> Option<GetKeyFocusProcessFn> {+ static SYM: OnceLock<Option<GetKeyFocusProcessFn>> = OnceLock::new();+ *SYM.get_or_init(|| find_sym(b"SLPSGetKeyFocusProcess\0").map(|p| unsafe { as_fn(p) }))+}++fn get_process_pid_fn() -> Option<GetProcessPidFn> {+ static SYM: OnceLock<Option<GetProcessPidFn>> = OnceLock::new();+ *SYM.get_or_init(|| find_sym(b"GetProcessPID\0").map(|p| unsafe { as_fn(p) }))+}++/// The pid of the process WindowServer gives key focus to: normally the+/// frontmost app, or a non-activating panel (Spotlight-like launchers) or a+/// menu that took it.+pub fn key_focus_pid() -> Option<pid_t> {+ let get = get_key_focus_process_fn()?;+ let to_pid = get_process_pid_fn()?;+ let mut psn = [0u8; 8];+ // Room for whatever the second out-parameter holds (a connection id).+ let mut second = [0u64; 2];+ let err = unsafe {+ get(+ psn.as_mut_ptr() as *mut c_void,+ second.as_mut_ptr() as *mut c_void,+ )+ };+ if err != 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()+ && release_key_focus_fn().is_some()+ && main_connection_id().is_some()+}++/// Steal key focus for this process's own connection and return the theft id.+///+/// WindowServer numbers thefts from one session-wide counter, so the id tells+/// the caller which id the next theft will get. AppKit uses the same call,+/// with the same options, when it opens a menu in an app that is not active.+pub fn steal_key_focus() -> Option<i32> {+ let steal = steal_key_focus_fn()?;+ let cid = main_connection_id()?;+ let mut id = 0i32;+ let err = unsafe { steal(cid, 0xC80, &mut id) };+ (err == 0 && id != 0).then_some(id)+}++/// Release a key-focus theft by id, whichever connection made it.+/// Returns the CGError (0 on success; 1010 when no such theft is live).+pub fn release_key_focus(theft_id: i32) -> i32 {+ match release_key_focus_fn() {+ Some(release) => unsafe { release(theft_id) },+ None => -1,+ }+}+// ── Focus-without-raise ───────────────────────────────────────────────────────/// Activate `target_pid`'s window `target_wid` without raising any windows@@ -508,6 +597,16 @@ impl SpaceQuery {////// Returns `true` when all SPIs resolved and both posts succeeded.pub fn activate_without_raise(target_pid: pid_t, target_wid: u32) -> bool {+ activate_without_raise_with(target_pid, target_wid, true)+}++/// [`activate_without_raise`] with the defocus record to the current front+/// process made optional (`defocus_front`).+pub fn activate_without_raise_with(+ target_pid: pid_t,+ target_wid: u32,+ defocus_front: bool,+) -> bool {crate::window_change_detector::end_tail();let post_fn = match post_event_record_to_fn() {Some(f) => f,@@ -542,7 +641,8 @@ pub fn activate_without_raise(target_pid: pid_t, target_wid: u32) -> bool {// Step 3: defocus previous front.buf[0x8A] = 0x02;- let defocus_ok = unsafe { post_fn(prev_psn.as_ptr() as *const c_void, buf.as_ptr()) == 0 };+ let defocus_ok =+ !defocus_front || unsafe { post_fn(prev_psn.as_ptr() as *const c_void, buf.as_ptr()) == 0 };// Step 4: focus target.buf[0x8A] = 0x01;@@ -561,13 +661,14 @@ pub fn activate_without_raise(target_pid: pid_t, target_wid: u32) -> bool {/// succeeded.pub fn restore_focus_after_without_raise(previous_pid: pid_t,+ previous_key_wid: Option<u32>,target_pid: pid_t,target_wid: u32,) -> bool {let Some(post_fn) = post_event_record_to_fn() else {return false;};- let Some(previous_wid) = key_window_of_pid(previous_pid) else {+ let Some(previous_wid) = previous_key_wid.or_else(|| key_window_of_pid(previous_pid)) else {return false;};let mut previous_psn = [0u8; 8];@@ -601,7 +702,7 @@ fn focus_record(wid: u32) -> [u8; 0xF8] {/// The CGWindowID of `pid`'s key window: its `AXFocusedWindow`, else its/// frontmost on-screen layer-0 window.-fn key_window_of_pid(pid: pid_t) -> Option<u32> {+pub fn key_window_of_pid(pid: pid_t) -> Option<u32> {use crate::ax::bindings::{ax_get_window_id, copy_element_attr, AXUIElementCreateApplication};let focused = unsafe {let app = AXUIElementCreateApplication(pid);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.rsnew file mode 100644index 0000000000..15ef0df1e5--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-macos/src/key_focus_guard.rs@@ -0,0 +1,485 @@+//! Keep the user's key window while a background target opens a menu.+//!+//! When an app that is not active opens a menu (a popup button, a `<select>`,+//! a context menu), AppKit's menu tracking calls+//! `SLPSStealKeyFocusReturningID`. WindowServer then tells the app that holds+//! key focus, normally the user's frontmost app, that it lost key focus, and+//! routes the keyboard to the menu until it closes. The user's window resigns+//! key and their typing stops landing in it, even though no app was activated+//! and no window was raised.+//!+//! While the driver acts on a background target, this module holds a+//! per-process event tap on the user's frontmost app. When that app is told it+//! lost key focus to a guarded target (a type-21 event, subtype `0x4000`, whose+//! field 73 is the thief's pid), the tap releases the theft by id with+//! `SLPSReleaseKeyFocusWithID` and drops the event. The user's app never sees+//! the loss; the menu stays open and is still operable through accessibility.+//!+//! Theft ids come from one session-wide counter that only the thief learns.+//! [`protect`] therefore calibrates before each guarded action: it steals and+//! releases key focus on the driver's own connection (the tap drops that+//! notice too) and expects the target's theft to take the next id. If another+//! app steals in between, the tap tries the next few ids.++use std::collections::HashMap;+use std::ffi::c_void;+use std::sync::atomic::{AtomicI32, AtomicU64, Ordering};+use std::sync::{Mutex, OnceLock};+use std::time::{Duration, Instant};++use crate::input::skylight;++/// How long a target stays guarded after the action that armed it ends.+/// AppKit opens a pressed popup's menu from a delayed perform that runs just+/// after the accessibility call returns.+const TAIL: Duration = Duration::from_secs(3);+/// Ids tried after the expected one when another app stole in between.+const ID_SLACK: i32 = 3;+/// Longest wait for the thief's menu window before releasing the theft.+const MENU_WAIT: Duration = Duration::from_millis(150);+/// CGWindowLevel of popup menus (`kCGPopUpMenuWindowLevel`).+const POPUP_MENU_LAYER: i32 = 101;++/// Wait until `pid` shows a menu-level window, or `budget` runs out.+fn wait_for_menu_window(pid: i32, budget: Duration) {+ let deadline = Instant::now() + budget;+ while Instant::now() < deadline {+ if crate::windows::visible_windows()+ .iter()+ .any(|w| w.pid == pid && w.layer >= POPUP_MENU_LAYER && w.is_on_screen)+ {+ return;+ }+ std::thread::sleep(Duration::from_millis(3));+ }+}++/// CGEvent type of the WindowServer focus notices an app receives.+const FOCUS_NOTICE_TYPE: u32 = 21;+/// Field holding the notice subtype.+const FIELD_SUBTYPE: u32 = 64;+/// Field holding the pid of the process that took key focus.+const FIELD_THIEF_PID: u32 = 73;+/// Subtype: "you lost key focus".+const SUBTYPE_LOST_KEY_FOCUS: i64 = 0x4000;++const TAP_DISABLED_BY_TIMEOUT: u32 = 0xFFFF_FFFE;+const TAP_DISABLED_BY_USER_INPUT: u32 = 0xFFFF_FFFF;++#[link(name = "ApplicationServices", kind = "framework")]+extern "C" {+ fn CGEventTapCreateForPid(+ pid: i32,+ place: u32,+ options: u32,+ events_of_interest: u64,+ callback: extern "C" fn(*mut c_void, u32, *mut c_void, *mut c_void) -> *mut c_void,+ user_info: *mut c_void,+ ) -> *mut c_void;+ fn CGEventTapEnable(tap: *mut c_void, enable: bool);+ fn CGEventGetIntegerValueField(event: *mut c_void, field: u32) -> i64;+}++#[link(name = "CoreFoundation", kind = "framework")]+extern "C" {+ fn CFMachPortCreateRunLoopSource(+ allocator: *const c_void,+ port: *mut c_void,+ order: isize,+ ) -> *mut c_void;+ fn CFMachPortInvalidate(port: *mut c_void);+ fn CFRunLoopGetCurrent() -> *mut c_void;+ fn CFRunLoopAddSource(rl: *mut c_void, source: *mut c_void, mode: *const c_void);+ fn CFRunLoopRun();+ fn CFRunLoopStop(rl: *mut c_void);+ fn CFRelease(cf: *const c_void);+ static kCFRunLoopCommonModes: *const c_void;+}++/// What the guard did, for tool results and tests.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct Stats {+ /// Thefts by a guarded target that were released.+ pub released: u64,+ /// Thefts by a guarded target that could not be released.+ pub missed: u64,+}++struct Tap {+ front_pid: i32,+ port: usize,+ run_loop: usize,+}++#[derive(Default)]+struct State {+ tap: Option<Tap>,+ /// Guarded pid -> (live leases, end of the tail after the last lease).+ guarded: HashMap<i32, (usize, Instant)>,+}++fn state() -> &'static Mutex<State> {+ static STATE: OnceLock<Mutex<State>> = OnceLock::new();+ STATE.get_or_init(|| Mutex::new(State::default()))+}++fn lock() -> std::sync::MutexGuard<'static, State> {+ state()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+}++/// The id the next theft is expected to take (0 = unknown).+static NEXT_THEFT_ID: AtomicI32 = AtomicI32::new(0);+/// Calibration notices the tap has dropped.+static OWN_NOTICES: AtomicU64 = AtomicU64::new(0);+/// A front app whose tap missed a calibration notice (0 = none).+static UNVERIFIED_FRONT: AtomicI32 = AtomicI32::new(0);+static RELEASED: AtomicU64 = AtomicU64::new(0);+static MISSED: AtomicU64 = AtomicU64::new(0);++/// Counters since the daemon started.+pub fn stats() -> Stats {+ Stats {+ released: RELEASED.load(Ordering::Relaxed),+ missed: MISSED.load(Ordering::Relaxed),+ }+}++/// While alive, key-focus thefts by the guarded pid are handed back to the+/// user's frontmost app. Dropping it starts a short tail (see [`TAIL`]).+pub struct Lease {+ pid: i32,+}++impl Drop for Lease {+ fn drop(&mut self) {+ let mut st = lock();+ if let Some((leases, until)) = st.guarded.get_mut(&self.pid) {+ *leases = leases.saturating_sub(1);+ *until = Instant::now() + TAIL;+ }+ drop(st);+ schedule_idle_teardown();+ }+}++/// Guard the user's key focus while the driver acts on `target_pid` in the+/// background. Returns `None` (no guard) when the target is the frontmost app,+/// when there is no other frontmost app, or when the SPIs or the event tap are+/// unavailable; the action then runs exactly as before.+pub fn protect(target_pid: i32) -> Option<Lease> {+ if std::env::var_os("CUA_DRIVER_DISABLE_KEY_FOCUS_GUARD").is_some() {+ return None;+ }+ let own = std::process::id() as i32;+ if !skylight::key_focus_theft_available() {+ return None;+ }+ // Tap the process that holds key focus now. That is the one WindowServer+ // tells when a menu steals it, and it may be a non-activating panel+ // rather than the frontmost app. Only guard when it is the frontmost app:+ // otherwise a launcher-style panel would see the calibration theft.+ let front = crate::apps::frontmost_pid()?;+ let holder = skylight::key_focus_pid().unwrap_or(front);+ if holder != front || front == target_pid || front == own {+ return None;+ }+ if UNVERIFIED_FRONT.load(Ordering::SeqCst) == front {+ return None;+ }+ // Register first, so an idle teardown cannot remove the tap between+ // ensure_tap and the calibration below.+ {+ let mut st = lock();+ let entry = st.guarded.entry(target_pid).or_insert((0, Instant::now()));+ entry.0 += 1;+ entry.1 = Instant::now() + TAIL;+ }+ let lease = Lease { pid: target_pid };+ if !ensure_tap(front) {+ return None;+ }+ if !calibrate() {+ // The tap did not see the calibration notice, so it would not see a+ // menu's either. Stop calibrating against this app.+ UNVERIFIED_FRONT.store(front, Ordering::SeqCst);+ tracing::warn!(+ front,+ "key-focus guard: tap did not observe the calibration notice"+ );+ return None;+ }+ Some(lease)+}++/// Learn the id the next theft will take: steal and release key focus on the+/// driver's own connection. The tap drops the notice this sends to the user's+/// app, so it never sees the round trip. Returns whether the tap saw it.+fn calibrate() -> bool {+ let seen_before = OWN_NOTICES.load(Ordering::SeqCst);+ let Some(id) = skylight::steal_key_focus() else {+ return false;+ };+ skylight::release_key_focus(id);+ NEXT_THEFT_ID.store(id.wrapping_add(1), Ordering::SeqCst);+ let deadline = Instant::now() + Duration::from_millis(150);+ while OWN_NOTICES.load(Ordering::SeqCst) == seen_before {+ if Instant::now() >= deadline {+ return false;+ }+ std::thread::sleep(Duration::from_millis(2));+ }+ true+}++fn is_guarded(pid: i32) -> bool {+ let st = lock();+ st.guarded+ .get(&pid)+ .is_some_and(|(leases, until)| *leases > 0 || Instant::now() < *until)+}++/// Release the theft a guarded target just made. Tries the expected id first,+/// then a few later ones in case another app stole in between.+fn release_target_theft() -> bool {+ let expected = NEXT_THEFT_ID.load(Ordering::SeqCst);+ if expected == 0 {+ return false;+ }+ for id in expected..=expected.wrapping_add(ID_SLACK) {+ if skylight::release_key_focus(id) == 0 {+ NEXT_THEFT_ID.store(id.wrapping_add(1), Ordering::SeqCst);+ return true;+ }+ }+ false+}++/// What the tap does with one focus notice. Pure, for tests.+#[derive(Debug, PartialEq, Eq)]+enum NoticeAction {+ Pass,+ /// The driver's own calibration theft: swallow it.+ DropOwn,+ /// A guarded target stole key focus: release it, then swallow the notice.+ ReleaseAndDrop,+}++fn classify_notice(+ event_type: u32,+ subtype: i64,+ thief_pid: i64,+ own_pid: i32,+ guarded: impl Fn(i32) -> bool,+) -> NoticeAction {+ if event_type != FOCUS_NOTICE_TYPE || subtype != SUBTYPE_LOST_KEY_FOCUS {+ return NoticeAction::Pass;+ }+ let Ok(thief) = i32::try_from(thief_pid) else {+ return NoticeAction::Pass;+ };+ if thief == own_pid {+ NoticeAction::DropOwn+ } else if guarded(thief) {+ NoticeAction::ReleaseAndDrop+ } else {+ NoticeAction::Pass+ }+}++extern "C" fn tap_callback(+ _proxy: *mut c_void,+ event_type: u32,+ event: *mut c_void,+ _user_info: *mut c_void,+) -> *mut c_void {+ if event_type == TAP_DISABLED_BY_TIMEOUT || event_type == TAP_DISABLED_BY_USER_INPUT {+ if let Some(port) = lock().tap.as_ref().map(|tap| tap.port) {+ unsafe { CGEventTapEnable(port as *mut c_void, true) };+ }+ return event;+ }+ if event.is_null() {+ return event;+ }+ let (subtype, thief) = unsafe {+ (+ CGEventGetIntegerValueField(event, FIELD_SUBTYPE),+ CGEventGetIntegerValueField(event, FIELD_THIEF_PID),+ )+ };+ match classify_notice(+ event_type,+ subtype,+ thief,+ std::process::id() as i32,+ is_guarded,+ ) {+ NoticeAction::Pass => event,+ NoticeAction::DropOwn => {+ OWN_NOTICES.fetch_add(1, Ordering::SeqCst);+ std::ptr::null_mut()+ }+ NoticeAction::ReleaseAndDrop => {+ // Swallow the notice now, so the user's window never resigns key,+ // but release the theft only once the menu window is on screen.+ // Released earlier, AppKit orders the menu's window group to the+ // front, which raises the target's window over the user's.+ let thief_pid = thief as i32;+ let spawned = std::thread::Builder::new()+ .name("cua-key-focus-release".into())+ .spawn(move || {+ wait_for_menu_window(thief_pid, MENU_WAIT);+ if release_target_theft() {+ RELEASED.fetch_add(1, Ordering::Relaxed);+ tracing::debug!(thief_pid, "released a background key-focus theft");+ } else {+ MISSED.fetch_add(1, Ordering::Relaxed);+ tracing::warn!(thief_pid, "could not release a background key-focus theft");+ }+ });+ if spawned.is_ok() {+ std::ptr::null_mut()+ } else {+ event+ }+ }+ }+}++/// Make sure the tap sits on `front_pid`, the app that holds key focus.+fn ensure_tap(front_pid: i32) -> bool {+ {+ let mut st = lock();+ if st+ .tap+ .as_ref()+ .is_some_and(|tap| tap.front_pid == front_pid)+ {+ return true;+ }+ if let Some(old) = st.tap.take() {+ stop_tap(old);+ }+ }+ let (tx, rx) = std::sync::mpsc::channel::<Option<(usize, usize)>>();+ let spawned = std::thread::Builder::new()+ .name("cua-key-focus-guard".into())+ .spawn(move || unsafe {+ let mask = 1u64 << FOCUS_NOTICE_TYPE;+ // kCGHeadInsertEventTap = 0, kCGEventTapOptionDefault = 0.+ let port =+ CGEventTapCreateForPid(front_pid, 0, 0, mask, tap_callback, std::ptr::null_mut());+ if port.is_null() {+ let _ = tx.send(None);+ return;+ }+ let source = CFMachPortCreateRunLoopSource(std::ptr::null(), port, 0);+ if source.is_null() {+ CFMachPortInvalidate(port);+ CFRelease(port);+ let _ = tx.send(None);+ return;+ }+ let run_loop = CFRunLoopGetCurrent();+ CFRunLoopAddSource(run_loop, source, kCFRunLoopCommonModes);+ CGEventTapEnable(port, true);+ let _ = tx.send(Some((port as usize, run_loop as usize)));+ CFRunLoopRun();+ CFMachPortInvalidate(port);+ CFRelease(source);+ CFRelease(port);+ });+ if spawned.is_err() {+ return false;+ }+ match rx.recv_timeout(Duration::from_secs(2)) {+ Ok(Some((port, run_loop))) => {+ let mut st = lock();+ if let Some(old) = st.tap.replace(Tap {+ front_pid,+ port,+ run_loop,+ }) {+ stop_tap(old);+ }+ true+ }+ _ => {+ tracing::warn!(front_pid, "key-focus guard: event tap unavailable");+ false+ }+ }+}++fn stop_tap(tap: Tap) {+ unsafe {+ CGEventTapEnable(tap.port as *mut c_void, false);+ CFRunLoopStop(tap.run_loop as *mut c_void);+ }+}++/// Remove the tap once nothing has been guarded for a while, so the driver+/// does not keep a tap on the user's app between tasks.+fn schedule_idle_teardown() {+ let _ = std::thread::Builder::new()+ .name("cua-key-focus-guard-idle".into())+ .spawn(|| {+ std::thread::sleep(TAIL + Duration::from_secs(1));+ let mut st = lock();+ let now = Instant::now();+ st.guarded+ .retain(|_, (leases, until)| *leases > 0 || now < *until);+ if st.guarded.is_empty() {+ if let Some(tap) = st.tap.take() {+ stop_tap(tap);+ }+ }+ });+}++#[cfg(test)]+mod tests {+ use super::*;++ const OWN: i32 = 100;++ #[test]+ fn a_guarded_target_theft_is_released_and_swallowed() {+ let action = classify_notice(21, 0x4000, 42, OWN, |pid| pid == 42);+ assert_eq!(action, NoticeAction::ReleaseAndDrop);+ }++ #[test]+ fn the_drivers_own_calibration_theft_is_swallowed() {+ assert_eq!(+ classify_notice(21, 0x4000, OWN as i64, OWN, |_| false),+ NoticeAction::DropOwn+ );+ }++ #[test]+ fn other_apps_and_other_notices_pass_through() {+ // An app the driver is not acting on keeps normal macOS behaviour.+ assert_eq!(+ classify_notice(21, 0x4000, 7, OWN, |pid| pid == 42),+ NoticeAction::Pass+ );+ // "Key focus returned" and other subtypes are never touched.+ assert_eq!(+ classify_notice(21, 0x8000, 42, OWN, |_| true),+ NoticeAction::Pass+ );+ // Other event types are never touched.+ assert_eq!(+ classify_notice(13, 0x4000, 42, OWN, |_| true),+ NoticeAction::Pass+ );+ // A malformed pid passes.+ assert_eq!(+ classify_notice(21, 0x4000, i64::MAX, OWN, |_| true),+ NoticeAction::Pass+ );+ }+}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs b/libs/cua-driver/rust/crates/platform-macos/src/lib.rsindex 665ea93fcd..5d44298051 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs@@ -32,6 +32,8 @@ pub mod history;#[cfg(target_os = "macos")]pub mod input;#[cfg(target_os = "macos")]+pub mod key_focus_guard;+#[cfg(target_os = "macos")]mod permission_observation;#[cfg(target_os = "macos")]pub mod permissions;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 4bb7ab33f7..7acd80675e 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@@ -222,6 +222,20 @@ fn background_pixel_restore_pid(}}+/// Poll until `pid` is the frontmost application or `budget` runs out.+async fn wait_until_frontmost(pid: i32, budget: std::time::Duration) -> bool {+ let deadline = std::time::Instant::now() + budget;+ loop {+ if apps::frontmost_pid() == Some(pid) {+ return true;+ }+ if std::time::Instant::now() >= deadline {+ return false;+ }+ tokio::time::sleep(std::time::Duration::from_millis(15)).await;+ }+}+fn def() -> &'static ToolDef {DEF.get_or_init(|| ToolDef {name: "click".into(),@@ -230,7 +244,7 @@ fn def() -> &'static ToolDef {- element_token: AX action path. Tokens are scoped to (pid, window_id) and stale once the window is snapshotted again.\n\- x, y: window-local pixels of the get_window_state screenshot, sent as CGEvent mouse events. Needs a visible window. `modifier` takes cmd/shift/option/ctrl.\n\\n\- `button` defaults to left; on the AX path \"right\" maps to AXShowMenu and \"middle\" falls back to a pixel click at the element center. `action`: press (default), show_menu, pick, confirm, cancel, open. `from_zoom:true` translates zoom-image pixels after a `zoom` call. Pressing a popup button opens its menu and leaves it open (holding key focus) until dismissed; to choose an option use `set_value`.".into(),+ `button` defaults to left; on the AX path \"right\" maps to AXShowMenu and \"middle\" falls back to a pixel click at the element center. `action`: press (default), show_menu, pick, confirm, cancel, open. `from_zoom:true` translates zoom-image pixels after a `zoom` call. Pressing a popup button opens its menu and leaves it open until an item is chosen or it is dismissed; in the background the user's front window keeps key focus meanwhile. To choose an option in one call use `set_value`.".into(),input_schema: serde_json::json!({"type": "object",// `pid` is conditionally required — needed for window/element clicks@@ -1146,6 +1160,34 @@ impl Tool for ClickTool {}};+ // A raw click can open a menu (a popup drawn without AX, a canvas+ // context menu); keep the user's key focus if it does.+ let _key_focus = if fg {+ None+ } else {+ tokio::task::spawn_blocking(move || crate::key_focus_guard::protect(pid))+ .await+ .ok()+ .flatten()+ };++ // The user's key window, read before the click, so the restore+ // below hands key status back to exactly that window.+ let prior_key_wid = match prior_front {+ Some(prior)+ if activation_policy == PixelActivationPolicy::AllowTargetWithoutRaise+ && prior != pid =>+ {+ tokio::task::spawn_blocking(move || {+ crate::input::skylight::key_window_of_pid(prior)+ })+ .await+ .ok()+ .flatten()+ }+ _ => None,+ };+// Restore the Swift background-click prologue that was left// disconnected in the original Rust port. It makes an opaque// target AppKit-active without raising/restacking its window, which@@ -1285,21 +1327,31 @@ impl Tool for ClickTool {&& prior_front != Some(pid){tokio::time::sleep(std::time::Duration::from_millis(50)).await;- if let Some(previous_pid) = background_pixel_restore_pid(+ let reactivated = if let Some(previous_pid) = background_pixel_restore_pid(activation_policy,prior_front,pid,apps::frontmost_pid(),) {let _ = apps::activate_pid(previous_pid);- } else if let (Some(previous_pid), Some(wid)) = (prior_front, window_id) {- // The prior app is still frontmost, but the no-raise- // recipe posted it a defocus record: hand its key window- // focus back so the user's typing keeps landing there.- if focus_without_raise && apps::frontmost_pid() == Some(previous_pid) {+ wait_until_frontmost(previous_pid, std::time::Duration::from_millis(300)).await;+ true+ } else {+ false+ };+ // The prologue leaves the user's window key, but the click can+ // still make the target self-activate, and re-activating the+ // prior app does not by itself make its window key again.+ // Post the focus record to the user's window in both cases so+ // their typing keeps landing there.+ if let (Some(previous_pid), Some(wid)) = (prior_front, window_id) {+ if (focus_without_raise || reactivated)+ && apps::frontmost_pid() == Some(previous_pid)+ {let _ = tokio::task::spawn_blocking(move || {crate::input::skylight::restore_focus_after_without_raise(previous_pid,+ prior_key_wid,pid,wid,)@@ -1591,9 +1643,9 @@ fn perform_ax_click(if !options.is_empty() {let opt_list = options.join(", ");summary.push_str(- "\n\n⚠️ This is a popup/select button. The native macOS menu closes \- immediately when the window is in the background. Do NOT use click \- again — instead, use:\n set_value(pid, element_token, value)\n\+ "\n\nThis is a popup/select button; its menu is open. Choose an item \+ by clicking its AXMenuItem from a fresh get_window_state, or select \+ in one call with:\n set_value(pid, element_token, value)\n\Available options: [",);summary.push_str(&opt_list);diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rsindex a45e01c3a5..9f492f8d8c 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs@@ -139,7 +139,10 @@ impl Tool for RightClickTool {Err(refusal_result) => return refusal_result,};+ // The context menu steals key focus from the user's app when the+ // target is in the background; the guard hands it back.let result = tokio::task::spawn_blocking(move || {+ let _key_focus = crate::key_focus_guard::protect(pid);ax_show_menu(element_guard.as_ptr(), idx, pid, wid)}).await;@@ -238,6 +241,9 @@ impl Tool for RightClickTool {Err(refusal) => return refusal,};let result = tokio::task::spawn_blocking(move || -> anyhow::Result<()> {+ let _key_focus = (!fg)+ .then(|| crate::key_focus_guard::protect(pid))+ .flatten();let do_it = move || -> anyhow::Result<()> {let m: Vec<&str> = modifiers.iter().map(String::as_str).collect();if route == super::pixel_route::PixelClickRoute::ForegroundHid {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rsindex 58a8423456..2d9278cac2 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs@@ -46,7 +46,7 @@ static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();fn def() -> &'static ToolDef {DEF.get_or_init(|| ToolDef {name: "set_value".into(),- description: "Set an element's value by `element_token`. A popup button / select dropdown: selects the menu item whose title or value matches `value` (case-insensitive). Safari `<select>` is set through the DOM; AppKit and Chromium popups list items only while open, so the menu is opened, the item pressed and the menu closed again (the front window loses key focus for ~0.4 s). An unknown value lists the options. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).\n\+ description: "Set an element's value by `element_token`. A popup button / select dropdown: selects the menu item whose title or value matches `value` (case-insensitive). Safari `<select>` is set through the DOM; AppKit and Chromium popups list items only while open, so the menu is opened, the item pressed and the menu closed again (in the background the user's front window keeps key focus). An unknown value lists the options. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).\n\\n\A Finder file name (list row or Get Info `Name` field, not being edited) is refused with `file_name_needs_rename`; the refusal names the keyboard route. For free-form text in web inputs use `type_text_chars`: WebKit ignores AXValue writes.".into(),input_schema: serde_json::json!({@@ -689,9 +689,9 @@ fn select_popup_option(// AppKit NSPopUpButton and Chromium <select> publish their items only// while the menu is open (a closed Chromium popup lists just the// selected one). Open it, wait for the full list, press the match,- // and close the menu again whatever happens. While the menu is open- // the app's menu tracking holds key focus, so the window that was key- // loses it until the menu closes.+ // and close the menu again whatever happens. The menu's tracking+ // steals key focus; in the background the key-focus guard armed by+ // the caller hands it straight back to the user's front window.//// The AXPress returns only once the app's menu tracking lets it (or// the messaging timeout fires), so run it on its own thread and readdiff --git a/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift b/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swiftindex ae665ee8c7..316be76532 100644--- a/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift+++ b/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift@@ -19,6 +19,7 @@// 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=)+// popup_select — NSPopUpButton (Design/Research/Finance → popup_value=)// scroll_target — NSScrollView with a tall body and offset label// ns_menubar — main menu item with known title (Mac-specific)// exit — NSButton terminates the app@@ -62,6 +63,8 @@ let kErroringTogglesStateAID = "lbl-erroring-toggles"let kSelectionStateAID = "lbl-selection-state"let kContextButtonAID = "btn-context"let kMenuActionAID = "lbl-menu-action"+let kPopupAID = "pop-team"+let kPopupValueAID = "lbl-popup-value"let kScrollerAID = "scroll-tall"let kScrollOffsetAID = "lbl-scroll-offset"let kAccelCountAID = "lbl-accel-count"@@ -140,6 +143,7 @@ final class HarnessWindowController: NSObject, NSTextFieldDelegate, NSTableViewDlet selectionTable = NSTableView()let selectionStateLabel = NSTextField(labelWithString: "selection=none")let menuActionLabel = NSTextField(labelWithString: "menu_action=none")+ let popupValueLabel = NSTextField(labelWithString: "popup_value=Choose a team")let scrollOffsetLabel = NSTextField(labelWithString: "scroll_offset=0")let accelCountLabel = NSTextField(labelWithString: "accel_fired=0")var accelCount = 0@@ -352,6 +356,25 @@ final class HarnessWindowController: NSObject, NSTextFieldDelegate, NSTableViewDcontextRow.addArrangedSubview(menuActionLabel)content.addArrangedSubview(contextRow)+ // popup_select — an NSPopUpButton whose menu is opened by AXPress.+ // Background tests check the user's front window keeps key status+ // while the menu is open.+ content.addArrangedSubview(sectionLabel("popup_select"))+ let teamPopup = NSPopUpButton(frame: .zero, pullsDown: false)+ teamPopup.addItems(withTitles: ["Choose a team", "Design", "Research", "Finance"])+ teamPopup.target = self+ teamPopup.action = #selector(onTeamPopup(_:))+ teamPopup.setAccessibilityIdentifier(kPopupAID)+ teamPopup.setAccessibilityLabel("Team")+ popupValueLabel.setAccessibilityIdentifier(kPopupValueAID)+ popupValueLabel.font = NSFont.monospacedSystemFont(ofSize: 14, weight: .regular)+ let popupRow = NSStackView()+ popupRow.orientation = .horizontal+ popupRow.spacing = 12+ popupRow.addArrangedSubview(teamPopup)+ popupRow.addArrangedSubview(popupValueLabel)+ content.addArrangedSubview(popupRow)+// scroll_targetcontent.addArrangedSubview(sectionLabel("scroll_target"))let scrollWrap = NSStackView()@@ -687,6 +710,10 @@ final class HarnessWindowController: NSObject, NSTextFieldDelegate, NSTableViewDmenuActionLabel.stringValue = "menu_action=\(sender.title)"}+ @objc private func onTeamPopup(_ sender: NSPopUpButton) {+ popupValueLabel.stringValue = "popup_value=\(sender.titleOfSelectedItem ?? "")"+ }+@objc func onArrangeLeft(_ sender: NSMenuItem) {menuActionLabel.stringValue = "menu_action=window_arrange_left"}diff --git a/libs/cua-driver/tests/fixtures/shared/scenarios.json b/libs/cua-driver/tests/fixtures/shared/scenarios.jsonindex 38558fa773..09ccd0f220 100644--- a/libs/cua-driver/tests/fixtures/shared/scenarios.json+++ b/libs/cua-driver/tests/fixtures/shared/scenarios.json@@ -389,6 +389,15 @@"action_label_aid": "lbl-menu-action"}},+ {+ "id": "popup_select",+ "kind": "popup_select",+ "description": "NSPopUpButton (Choose a team/Design/Research/Finance). AXPress opens its menu; choosing an item sets popup_value=. Background tests check the front window keeps key status while the menu is open.",+ "controls": {+ "popup_aid": "pop-team",+ "value_label_aid": "lbl-popup-value"+ }+ },{"id": "scroll_target","kind": "scroll_viewer",diff --git a/scripts/ci/macos/run-rust-e2e.sh b/scripts/ci/macos/run-rust-e2e.shindex 4a6a414099..85bbd3b19e 100755--- a/scripts/ci/macos/run-rust-e2e.sh+++ b/scripts/ci/macos/run-rust-e2e.sh@@ -375,6 +375,9 @@ if [[ "${SUITE}" == native || "${SUITE}" == all ]]; thenharness_appkit_right_click_px_background \harness_appkit_double_click_px_foreground \harness_appkit_double_click_px_background \+ harness_appkit_popup_click_keeps_front_key_focus_background \+ harness_appkit_popup_set_value_keeps_front_key_focus_background \+ harness_appkit_context_menu_keeps_front_key_focus_background \harness_appkit_slider_drag_px_foreground \harness_appkit_slider_drag_px_background; dorun_test "appkit-${appkit_test}" cargo test -p cua-driver-e2e --test harness_appkit_test -- \diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.jsonindex 82cc94d3cf..4c32f612ba 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json@@ -509,7 +509,7 @@"read_only": false},{- "description": "Click a target pid. Prefer `element_token` (from get_window_state): it identifies one snapshot element, works on backgrounded, minimized or off-Space windows, and moves no cursor or focus. Use `x, y` only for canvas / video / WebGL / custom-drawn surfaces missing from the AX tree.\n\n- element_token: AX action path. Tokens are scoped to (pid, window_id) and stale once the window is snapshotted again.\n- x, y: window-local pixels of the get_window_state screenshot, sent as CGEvent mouse events. Needs a visible window. `modifier` takes cmd/shift/option/ctrl.\n\n`button` defaults to left; on the AX path \"right\" maps to AXShowMenu and \"middle\" falls back to a pixel click at the element center. `action`: press (default), show_menu, pick, confirm, cancel, open. `from_zoom:true` translates zoom-image pixels after a `zoom` call. Pressing a popup button opens its menu and leaves it open (holding key focus) until dismissed; to choose an option use `set_value`.",+ "description": "Click a target pid. Prefer `element_token` (from get_window_state): it identifies one snapshot element, works on backgrounded, minimized or off-Space windows, and moves no cursor or focus. Use `x, y` only for canvas / video / WebGL / custom-drawn surfaces missing from the AX tree.\n\n- element_token: AX action path. Tokens are scoped to (pid, window_id) and stale once the window is snapshotted again.\n- x, y: window-local pixels of the get_window_state screenshot, sent as CGEvent mouse events. Needs a visible window. `modifier` takes cmd/shift/option/ctrl.\n\n`button` defaults to left; on the AX path \"right\" maps to AXShowMenu and \"middle\" falls back to a pixel click at the element center. `action`: press (default), show_menu, pick, confirm, cancel, open. `from_zoom:true` translates zoom-image pixels after a `zoom` call. Pressing a popup button opens its menu and leaves it open until an item is chosen or it is dismissed; in the background the user's front window keeps key focus meanwhile. To choose an option in one call use `set_value`.","destructive": true,"idempotent": false,"input_schema": {@@ -1261,7 +1261,7 @@"read_only": false},{- "description": "Set an element's value by `element_token`. A popup button / select dropdown: selects the menu item whose title or value matches `value` (case-insensitive). Safari `<select>` is set through the DOM; AppKit and Chromium popups list items only while open, so the menu is opened, the item pressed and the menu closed again (the front window loses key focus for ~0.4 s). An unknown value lists the options. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).\n\nA Finder file name (list row or Get Info `Name` field, not being edited) is refused with `file_name_needs_rename`; the refusal names the keyboard route. For free-form text in web inputs use `type_text_chars`: WebKit ignores AXValue writes.",+ "description": "Set an element's value by `element_token`. A popup button / select dropdown: selects the menu item whose title or value matches `value` (case-insensitive). Safari `<select>` is set through the DOM; AppKit and Chromium popups list items only while open, so the menu is opened, the item pressed and the menu closed again (in the background the user's front window keeps key focus). An unknown value lists the options. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).\n\nA Finder file name (list row or Get Info `Name` field, not being edited) is refused with `file_name_needs_rename`; the refusal names the keyboard route. For free-form text in web inputs use `type_text_chars`: WebKit ignores AXValue writes.","destructive": true,"idempotent": true,"input_schema": {