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 a macOS sheet's own id for focus and snapshot scope (#6758)
injaneityab1d654a953d
diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/bring_to_front_macos_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/bring_to_front_macos_test.rsindex 75ba4a0e1e..eac209f578 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/bring_to_front_macos_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/bring_to_front_macos_test.rs@@ -389,6 +389,134 @@ fn modal_sheet_never_yields_false_parent_success() {assert_ne!(focused_window_title(target.pid), MAIN_TITLE);}+/// The sheet's text field value, read through System Events. `Err` carries+/// the oracle's error while the sheet is not readable yet.+fn sheet_field_value(pid: u32) -> Result<String, String> {+ let script = format!(+ "tell application \"System Events\" to tell (first process whose unix id is {pid}) to get value of text field 1 of sheet 1 of window \"{MAIN_TITLE}\""+ );+ let output = Command::new("osascript")+ .args(["-e", &script])+ .output()+ .expect("query sheet field");+ if output.status.success() {+ Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())+ } else {+ Err(String::from_utf8_lossy(&output.stderr).trim().to_owned())+ }+}++fn wait_for_sheet_field(pid: u32, expected: &str, context: &str) {+ let deadline = Instant::now() + Duration::from_secs(5);+ loop {+ let value = sheet_field_value(pid);+ if value.as_deref() == Ok(expected) {+ return;+ }+ assert!(+ Instant::now() < deadline,+ "{context}: sheet field is {value:?}, expected {expected:?}"+ );+ std::thread::sleep(Duration::from_millis(100));+ }+}++/// Keys addressed to a sheet's own id and to its parent's id both reach the+/// sheet's focused field, and a snapshot of the sheet's id holds only the+/// sheet, while the parent's snapshot holds both (Finder's Go to Folder).+#[test]+#[ignore]+fn sheet_and_parent_ids_both_reach_the_sheet_and_the_sheet_snapshot_is_isolated() {+ let mut driver = McpDriver::spawn_macos_daemon_proxy_named("macos-sheet-input")+ .expect("start installed macOS daemon proxy");+ let target = launch(&mut driver, Some("sheet-input"));+ let windows = wait_for_window_ids(&target, &["main", "sheet"]);+ let (parent, sheet) = (windows["main"], windows["sheet"]);+ wait_for_sheet_field(target.pid, "", "sheet before input");++ let mut typed = String::new();+ for (window_id, text) in [(sheet, "sheet"), (parent, "parent")] {+ let result = driver.call(+ "type_text",+ serde_json::json!({+ "pid": target.pid, "window_id": window_id, "text": text,+ "delivery_mode": "background",+ }),+ );+ assert!(+ !result.is_error(),+ "keys to window {window_id}: {}",+ result.raw+ );+ typed.push_str(text);+ wait_for_sheet_field(target.pid, &typed, &format!("keys to window {window_id}"));+ }+ for window_id in [sheet, parent] {+ let result = driver.call(+ "press_key",+ serde_json::json!({"pid": target.pid, "window_id": window_id, "key": "delete"}),+ );+ assert!(+ !result.is_error(),+ "press_key to window {window_id}: {}",+ result.raw+ );+ typed.pop();+ wait_for_sheet_field(+ target.pid,+ &typed,+ &format!("press_key to window {window_id}"),+ );+ }++ let state = |window_id: u32, driver: &mut McpDriver| {+ let state = driver.call(+ "get_window_state",+ serde_json::json!({"pid": target.pid, "window_id": window_id, "tree_format": "both"}),+ );+ assert!(+ !state.is_error(),+ "get_window_state {window_id}: {}",+ state.raw+ );+ state.structured().clone()+ };+ let sheet_state = state(sheet, &mut driver);+ let sheet_tree = sheet_state["tree_markdown"]+ .as_str()+ .expect("tree_markdown");+ assert!(sheet_tree.contains("txt-sheet"), "{sheet_tree}");+ assert!(+ !sheet_tree.contains("btn-increment") && !sheet_tree.contains("AXMenuBar"),+ "sheet snapshot carries parent controls: {sheet_tree}"+ );+ let parent_state = state(parent, &mut driver);+ let parent_tree = parent_state["tree_markdown"]+ .as_str()+ .expect("tree_markdown");+ assert!(+ parent_tree.contains("btn-increment") && parent_tree.contains("txt-sheet"),+ "{parent_tree}"+ );++ // An element of the sheet's own snapshot passes the sheet-addressed+ // ancestry gate on real AX.+ let token = sheet_state["elements"]+ .as_array()+ .expect("elements")+ .iter()+ .find(|element| element["role"] == "AXTextField")+ .and_then(|element| element["element_token"].as_str())+ .unwrap_or_else(|| panic!("sheet field token: {sheet_state}"))+ .to_owned();+ let result = driver.call(+ "set_value",+ serde_json::json!({"element_token": token, "value": "token"}),+ );+ assert!(!result.is_error(), "set_value in the sheet: {}", result.raw);+ wait_for_sheet_field(target.pid, "token", "set_value in the sheet");+}+#[test]#[ignore]fn floating_panel_is_typed_nonordinary_without_focus_theft() {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/bindings.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/bindings.rsindex d0527f49b6..4fb93830ad 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@@ -534,12 +534,14 @@ pub unsafe fn focused_element_of_pid(pid: i32) -> Option<AXUIElementRef> {Some(value as AXUIElementRef)}-/// Return the CGWindowID of the application's focused AX window.+/// The application's focused AX window, as the ids it answers to: a focused+/// sheet (Finder's Go to Folder, a Save sheet) is both itself and the window+/// it is attached to, because keys addressed to that window go to the sheet.////// This is a narrow read-only proof used before global keyboard delivery: an/// already focused exact window must not be re-activated, because doing so can/// make a focus-proxy renderer drop its current key target.-pub fn focused_window_id_of_pid(pid: i32) -> Option<u32> {+pub fn focused_window_id_of_pid(pid: i32) -> Option<super::exact_target::AxWindowId> {unsafe {let app = AXUIElementCreateApplication(pid);if app.is_null() {@@ -548,7 +550,7 @@ pub fn focused_window_id_of_pid(pid: i32) -> Option<u32> {let window = copy_element_attr(app, "AXFocusedWindow");CFRelease(app as CFTypeRef);let window = window?;- let window_id = ax_get_window_id(window);+ let window_id = super::exact_target::owning_window_id(window);CFRelease(window as CFTypeRef);window_id}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/exact_target.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/exact_target.rsindex 362ea975b3..2391ac22fd 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/exact_target.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/exact_target.rs@@ -16,8 +16,9 @@ use cua_driver_core::background_input::{};use super::bindings::{- ax_get_window_id, copy_ax_windows_including, copy_bool_attr, copy_element_attr,- copy_string_attr, focused_element_of_pid, AXUIElementCreateApplication, AXUIElementRef,+ ax_get_window_id, copy_ax_windows, copy_ax_windows_including, copy_bool_attr, copy_children,+ copy_element_attr, copy_string_attr, focused_element_of_pid, AXUIElementCreateApplication,+ AXUIElementRef,};use super::snapshot::RetainedElement;use crate::windows::{all_windows_without_spaces, resolve_window_owner, WindowOwner};@@ -37,21 +38,48 @@ const MAX_SHEET_NESTING: usize = 8;/// A sheet is its own WindowServer window (and a remote Open/Save panel's/// content lives in yet another, service-owned one), but it is modal to the/// window it is attached to and is observed inside that window's snapshot.-/// An element under an `AXSheet` therefore resolves to the sheet's parent-/// window when AX proves that parent (issue #4392).+/// An element under an `AXSheet` therefore answers to the sheet and to the+/// sheet's parent window when AX proves that parent (issue #4392). AppKit+/// reports such an element's `AXWindow` as the parent window, so while that+/// window has a sheet the `AXParent` chain decides.////// # Safety////// `element` must be a valid `AXUIElementRef` for the duration of the call.-pub unsafe fn element_window_id(element: AXUIElementRef) -> Option<u32> {+pub unsafe fn element_window_id(element: AXUIElementRef) -> Option<AxWindowId> {if let Some(window) = copy_element_attr(element, "AXWindow") {- let window_id = owning_window_id(window);+ let mut window_id = owning_window_id(window);+ if has_sheet(window) {+ window_id = nearest_window_ancestor(element).or(window_id);+ }CFRelease(window as CFTypeRef);if window_id.is_some() {return window_id;}}- // Fallback: ascend AXParent until a window role, then map it.+ nearest_window_ancestor(element)+}++/// Whether one of `window`'s children is an `AXSheet`.+///+/// # Safety+///+/// `window` must be a valid `AXUIElementRef`.+unsafe fn has_sheet(window: AXUIElementRef) -> bool {+ let mut found = false;+ for child in copy_children(window) {+ found = found || copy_string_attr(child, "AXRole").as_deref() == Some("AXSheet");+ CFRelease(child as CFTypeRef);+ }+ found+}++/// Ascend `AXParent` from `element` to the nearest window or sheet and map it.+///+/// # Safety+///+/// `element` must be a valid `AXUIElementRef`.+unsafe fn nearest_window_ancestor(element: AXUIElementRef) -> Option<AxWindowId> {let mut current: AXUIElementRef = element;let mut owned = false;let mut resolved = None;@@ -81,9 +109,13 @@ pub unsafe fn element_window_id(element: AXUIElementRef) -> Option<u32> {}/// Decide an addressed element's ancestry from what was read about it.-fn element_ancestry(window: Option<u32>, in_app_menu_bar: bool, requested: u32) -> ElementAncestry {+fn element_ancestry(+ window: Option<AxWindowId>,+ in_app_menu_bar: bool,+ requested: u32,+) -> ElementAncestry {match window {- Some(id) if id == requested => ElementAncestry::ProvenDescendant,+ Some(id) if id.is(requested) => ElementAncestry::ProvenDescendant,Some(_) => ElementAncestry::OutsideTargetWindow,None if in_app_menu_bar => ElementAncestry::ProvenDescendant,None => ElementAncestry::Unproven,@@ -137,14 +169,36 @@ unsafe fn element_in_app_menu_bar(app: AXUIElementRef, element: AXUIElementRef)found}-/// Map a window-role AX element to the CGWindowID of the top-level window it-/// belongs to: an `AXWindow` maps to itself, an `AXSheet` to the window it is-/// attached to (see [`element_window_id`]).+/// The window ids an AX window or sheet answers to: its own CGWindowID and+/// the top-level window it is attached to. A window is both. A sheet is its+/// own WindowServer window but is modal to its parent, so input addressed to+/// the parent reaches it, while input addressed to the sheet must not reach+/// the parent (issue #4392).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct AxWindowId {+ pub own: u32,+ pub root: u32,+}++impl AxWindowId {+ pub fn window(id: u32) -> Self {+ Self { own: id, root: id }+ }++ /// Whether a request addressed to `window_id` covers this window.+ pub fn is(self, window_id: u32) -> bool {+ self.own == window_id || self.root == window_id+ }+}++/// Map a window-role AX element to the ids it answers to: an `AXWindow` to+/// itself, an `AXSheet` to itself and the window it is attached to (see+/// [`element_window_id`]).////// # Safety////// `window` must be a valid `AXUIElementRef` for the duration of the call.-unsafe fn owning_window_id(window: AXUIElementRef) -> Option<u32> {+pub(crate) unsafe fn owning_window_id(window: AXUIElementRef) -> Option<AxWindowId> {resolve_owning_window(RetainedElement::retain(window as usize),MAX_SHEET_NESTING,@@ -161,33 +215,105 @@ unsafe fn owning_window_id(window: AXUIElementRef) -> Option<u32> {)}+/// The sheets attached to `window`: its `AXSheet` children, and theirs, up+/// to [`MAX_SHEET_NESTING`] levels. Each is retained; the caller releases.+///+/// # Safety+///+/// `window` must be a valid `AXUIElementRef` for the duration of the call.+pub(crate) unsafe fn attached_sheets(window: AXUIElementRef) -> Vec<AXUIElementRef> {+ let mut sheets = Vec::new();+ let mut level = 0;+ for depth in 0..MAX_SHEET_NESTING {+ let parents = if depth == 0 {+ vec![window]+ } else {+ sheets[level..].to_vec()+ };+ level = sheets.len();+ for parent in parents {+ for child in copy_children(parent) {+ if copy_string_attr(child, "AXRole").as_deref() == Some("AXSheet") {+ sheets.push(child);+ } else {+ CFRelease(child as CFTypeRef);+ }+ }+ }+ if sheets.len() == level {+ break;+ }+ }+ sheets+}++/// The CGWindowIDs of the sheets attached to `window` (see [`attached_sheets`]).+///+/// # Safety+///+/// `window` must be a valid `AXUIElementRef` for the duration of the call.+unsafe fn attached_sheet_ids(window: AXUIElementRef) -> Vec<u32> {+ attached_sheets(window)+ .into_iter()+ .filter_map(|sheet| {+ let id = ax_get_window_id(sheet);+ CFRelease(sheet as CFTypeRef);+ id+ })+ .collect()+}++/// Each of the application's `AXWindows` with the sheets attached to it.+///+/// # Safety+///+/// `app` must be a valid application `AXUIElementRef`.+unsafe fn windows_with_sheets(app: AXUIElementRef) -> Vec<(u32, Vec<u32>)> {+ copy_ax_windows(app)+ .into_iter()+ .filter_map(|window| {+ let row = ax_get_window_id(window).map(|id| (id, attached_sheet_ids(window)));+ CFRelease(window as CFTypeRef);+ row+ })+ .collect()+}+/// Pure sheet-to-parent resolution behind [`owning_window_id`].////// A sheet whose parent is not a window (or a sheet attached to another/// sheet) is followed up to `max_nesting` levels. When no parent window is-/// proven, the sheet keeps its own window id: that never names a different-/// window than before, so it can only stay refused, never widen.+/// proven, the sheet is its own root: that never names a different window+/// than before, so it can only stay refused, never widen.fn resolve_owning_window<E>(start: E,max_nesting: usize,role: impl Fn(&E) -> Option<String>,parent: impl Fn(&E) -> Option<E>,window_id: impl Fn(&E) -> Option<u32>,-) -> Option<u32> {- let own_id = window_id(&start);+) -> Option<AxWindowId> {+ let own = window_id(&start);let mut current = start;+ let mut root = None;for _ in 0..=max_nesting {match role(¤t).as_deref() {Some("AXSheet") => {}- Some("AXWindow") => return window_id(¤t),- _ => return own_id,+ Some("AXWindow") => {+ root = window_id(¤t);+ break;+ }+ _ => break,}- current = match parent(¤t) {- Some(next) => next,- None => return own_id,- };+ match parent(¤t) {+ Some(next) => current = next,+ None => break,+ }+ }+ match (own, root) {+ (Some(own), Some(root)) => Some(AxWindowId { own, root }),+ (Some(id), None) | (None, Some(id)) => Some(AxWindowId::window(id)),+ (None, None) => None,}- own_id}/// The process's focused AX element, but only when it provably belongs to the@@ -202,7 +328,7 @@ fn resolve_owning_window<E>(/// Caller must `CFRelease` the returned element.pub unsafe fn focused_element_in_window(pid: i32, window_id: u32) -> Option<AXUIElementRef> {let element = focused_element_of_pid(pid)?;- if element_window_id(element) == Some(window_id) {+ if element_window_id(element).is_some_and(|window| window.is(window_id)) {Some(element)} else {CFRelease(element as CFTypeRef);@@ -236,6 +362,30 @@ unsafe fn ax_window_records(app: AXUIElementRef, pid: i32, window_id: u32) -> Ve.collect()}+/// The AX window the requested CGWindowID is judged as: itself when AX lists+/// it, else the window it is attached to as a sheet. A sheet's own id never+/// appears in `AXWindows`, and its elements resolve to that window. The sheet+/// rows are read only when the id is not a listed window.+fn ax_target_window(+ requested: u32,+ records: &[AxWindowRecord],+ windows_with_sheets: impl FnOnce() -> Vec<(u32, Vec<u32>)>,+) -> u32 {+ if records.iter().any(|record| record.window_id == requested) {+ return requested;+ }+ let windows = windows_with_sheets();+ let mut owners = windows+ .iter()+ .filter(|(_, sheets)| sheets.contains(&requested))+ .map(|(window, _)| *window);+ // Two windows claiming one sheet prove nothing.+ match (owners.next(), owners.next()) {+ (Some(owner), None) => owner,+ _ => requested,+ }+}+/// One same-session WindowServer row as the keyboard-ambiguity count sees it.struct WindowServerRow {pid: i32,@@ -304,11 +454,12 @@ pub fn gather_background_facts(// SAFETY: the application element is created and released here; window// elements are released inside ax_window_records; the caller guarantees// element_ptr stays retained.- let (records, app_hidden, element, focused_window_id) = unsafe {+ let (records, ax_target, app_hidden, element, focused_window_id) = unsafe {let app = AXUIElementCreateApplication(pid);if app.is_null() {(Vec::new(),+ window_id,None,element_ptr.map(|_| ElementAncestry::Unproven),None,@@ -318,6 +469,9 @@ pub fn gather_background_facts(// before their AX windows and subtrees are materialized.super::enablement::ensure_chromium_ax_enabled(pid, app);let records = ax_window_records(app, pid, window_id);+ // A sheet's own id stands for the window it is attached to: AX+ // lists only that window, and the sheet's elements resolve to it.+ let ax_target = ax_target_window(window_id, &records, || windows_with_sheets(app));let app_hidden = copy_bool_attr(app, "AXHidden");let element = element_ptr.map(|ptr| {let element = ptr as AXUIElementRef;@@ -328,19 +482,19 @@ pub fn gather_background_facts(element_ancestry(window, in_menu_bar, window_id)});let focused_window_id = copy_element_attr(app, "AXFocusedWindow").and_then(|window| {- let window_id = ax_get_window_id(window);+ let window_id = owning_window_id(window);CFRelease(window as CFTypeRef);window_id});CFRelease(app as CFTypeRef);- (records, app_hidden, element, focused_window_id)+ (records, ax_target, app_hidden, element, focused_window_id)}};- let target = records.iter().find(|record| record.window_id == window_id);+ let target = records.iter().find(|record| record.window_id == ax_target);let competing_keyboard_destinations = count_competing_keyboard_destinations(pid,- window_id,+ ax_target,all_windows_without_spaces().iter().map(|window| WindowServerRow {@@ -351,7 +505,7 @@ pub fn gather_background_facts(&& window.bounds.height >= 2.0,}),&records,- target.is_some() && focused_window_id == Some(window_id),+ target.is_some() && focused_window_id.is_some_and(|focused| focused.is(window_id)),);BackgroundTargetFacts {@@ -368,14 +522,14 @@ pub fn gather_background_facts(#[cfg(test)]mod tests {use super::{- count_competing_keyboard_destinations, resolve_owning_window, AxWindowRecord,+ count_competing_keyboard_destinations, resolve_owning_window, AxWindowId, AxWindowRecord,WindowServerRow,};/// A fake AX node: (role, AXParent index, CGWindowID).type FakeNode = (&'static str, Option<usize>, Option<u32>);- fn resolve(tree: &[FakeNode], start: usize) -> Option<u32> {+ fn ids(tree: &[FakeNode], start: usize) -> Option<AxWindowId> {resolve_owning_window(start,8,@@ -385,14 +539,71 @@ mod tests {)}+ fn resolve(tree: &[FakeNode], start: usize) -> Option<u32> {+ ids(tree, start).map(|window| window.root)+ }+#[test]fn menu_bar_item_is_proven_only_through_the_app_menu_bar() {use super::element_ancestry;use cua_driver_core::background_input::ElementAncestry::*;assert_eq!(element_ancestry(None, true, 7), ProvenDescendant);assert_eq!(element_ancestry(None, false, 7), Unproven);- assert_eq!(element_ancestry(Some(7), false, 7), ProvenDescendant);- assert_eq!(element_ancestry(Some(8), true, 7), OutsideTargetWindow);+ let window = |id| Some(AxWindowId::window(id));+ assert_eq!(element_ancestry(window(7), false, 7), ProvenDescendant);+ assert_eq!(element_ancestry(window(8), true, 7), OutsideTargetWindow);+ }++ #[test]+ fn a_sheets_own_id_is_judged_as_the_window_it_is_attached_to() {+ use super::ax_target_window;+ let records = [ax_window(167, Some(false)), ax_window(200, Some(false))];+ let sheets = || vec![(167, vec![15304]), (200, vec![])];+ // Finder's Go to Folder sheet 15304 on window 167.+ assert_eq!(ax_target_window(15304, &records, sheets), 167);+ // A listed window never reads sheets; an unknown id stays itself.+ assert_eq!(+ ax_target_window(200, &records, || panic!("no sheet read")),+ 200+ );+ assert_eq!(ax_target_window(999, &records, sheets), 999);+ // Two windows claiming one sheet prove nothing.+ let shared = || vec![(167, vec![15304]), (200, vec![15304])];+ assert_eq!(ax_target_window(15304, &records, shared), 15304);+ }++ #[test]+ fn a_sheet_request_proves_only_sheet_elements() {+ use super::element_ancestry;+ use cua_driver_core::background_input::ElementAncestry::*;+ // Window 167, its sheet 15304, and a button in each.+ let tree = [+ ("AXWindow", None, Some(167)),+ ("AXSheet", Some(0), Some(15304)),+ ];+ let in_sheet = ids(&tree, 1);+ let in_parent = ids(&tree, 0);+ assert_eq!(+ in_sheet,+ Some(AxWindowId {+ own: 15304,+ root: 167+ })+ );+ // Addressed to the sheet: its own controls only, never the parent's.+ assert_eq!(element_ancestry(in_sheet, false, 15304), ProvenDescendant);+ assert_eq!(+ element_ancestry(in_parent, false, 15304),+ OutsideTargetWindow+ );+ // Addressed to the parent: the sheet is modal to it and counts.+ assert_eq!(element_ancestry(in_sheet, false, 167), ProvenDescendant);+ assert_eq!(element_ancestry(in_parent, false, 167), ProvenDescendant);+ // Another window is outside both.+ assert_eq!(+ element_ancestry(Some(AxWindowId::window(200)), false, 15304),+ OutsideTargetWindow+ );}#[test]@@ -418,6 +629,7 @@ mod tests {("AXSheet", Some(1), Some(180)),];assert_eq!(resolve(&tree, 2), Some(167));+ assert_eq!(ids(&tree, 2).map(|window| window.own), Some(180));}#[test]diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rsindex bcc2772722..5b468c1000 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs@@ -283,7 +283,7 @@ fn walk_tree_with_web_content(let attempt_started = Instant::now();super::enablement::ensure_chromium_ax_enabled(pid, app_elem);- let top_level = copy_top_level(app_elem, pid, window_id);+ let mut top_level = copy_top_level(app_elem, pid, window_id);// Scope: keep non-window children (menu bar) + the target window —// but ONLY once the target window has actually been identified. When@@ -294,7 +294,7 @@ fn walk_tree_with_web_content(let walk = top_level.clone();break (top_level, walk);};- let decision = scope_top_level(&top_level, pid, wid);+ let decision = scope_top_level(&mut top_level, pid, wid);if matches!(decision.scope, WindowScope::AxUnresolved { .. }) {match launch_wait.step(attempt_started, Instant::now(), || is_still_launching(pid)){@@ -402,34 +402,70 @@ unsafe fn copy_top_level(}/// Decide which of `top_level` a walk scoped to `wid` covers.-unsafe fn scope_top_level(top_level: &[AXUIElementRef], pid: i32, wid: u32) -> ScopeDecision {- let candidates: Vec<TopLevelCandidate> = top_level+///+/// A sheet's own id is never a top-level window: the sheet hangs off the+/// window it is attached to. When no window claims `wid`, the matching+/// attached sheet is appended to `top_level`, so the walk covers that sheet+/// and not the parent window's own controls.+unsafe fn scope_top_level(+ top_level: &mut Vec<AXUIElementRef>,+ pid: i32,+ wid: u32,+) -> ScopeDecision {+ let mut candidates: Vec<TopLevelCandidate> = top_level.iter()- .map(|&child| {- set_messaging_timeout(child);- let role = copy_string_attr(child, "AXRole").unwrap_or_default();- let subrole = copy_string_attr(child, "AXSubrole");- let identifier = copy_string_attr(child, "AXIdentifier");- // Match AX window element → CGWindowID via private SPI.- // Only windows carry one, so skip the round-trip elsewhere.- let ax_window_id = if role == "AXWindow" {- ax_get_window_id(child)+ .map(|&child| top_level_candidate(child))+ .collect();+ if !candidates+ .iter()+ .any(|candidate| candidate.ax_window_id == Some(wid))+ {+ let windows: Vec<AXUIElementRef> = top_level+ .iter()+ .zip(&candidates)+ .filter(|(_, candidate)| candidate.role == "AXWindow")+ .map(|(&window, _)| window)+ .collect();+ for sheet in windows+ .into_iter()+ .flat_map(|window| super::exact_target::attached_sheets(window))+ {+ let candidate = top_level_candidate(sheet);+ if candidate.ax_window_id == Some(wid)+ && !candidates.iter().any(|c| c.ax_window_id == Some(wid))+ {+ top_level.push(sheet);+ candidates.push(candidate);} else {- None- };- TopLevelCandidate {- role,- subrole,- identifier,- ax_window_id,+ CFRelease(sheet as CFTypeRef);}- })- .collect();+ }+ }decide_window_scope(&candidates, wid, || {crate::windows::resolve_window_owner(pid, wid)})}+unsafe fn top_level_candidate(child: AXUIElementRef) -> TopLevelCandidate {+ set_messaging_timeout(child);+ let role = copy_string_attr(child, "AXRole").unwrap_or_default();+ let subrole = copy_string_attr(child, "AXSubrole");+ let identifier = copy_string_attr(child, "AXIdentifier");+ // Match AX window element → CGWindowID via private SPI. Only windows and+ // sheets carry one, so skip the round-trip elsewhere.+ let ax_window_id = if matches!(role.as_str(), "AXWindow" | "AXSheet") {+ ax_get_window_id(child)+ } else {+ None+ };+ TopLevelCandidate {+ role,+ subrole,+ identifier,+ ax_window_id,+ }+}+/// Release elements retained by [`copy_top_level`].unsafe fn release_all(elements: Vec<AXUIElementRef>) {for element in elements {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/window_scope.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/window_scope.rsindex db052bf130..bbea6cac0f 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/window_scope.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/window_scope.rs@@ -57,7 +57,7 @@ pub struct TopLevelCandidate {/// themselves as `open-panel` / `save-panel`.pub identifier: Option<String>,/// `_AXUIElementGetWindow` result, when the SPI resolved one. Only read- /// for `AXWindow` roles.+ /// for `AXWindow` and `AXSheet` roles.pub ax_window_id: Option<u32>,}@@ -136,7 +136,9 @@ wherelet matched: Vec<usize> = candidates.iter().enumerate()- .filter(|(_, c)| c.role == "AXWindow" && c.ax_window_id == Some(requested))+ .filter(|(_, c)| {+ matches!(c.role.as_str(), "AXWindow" | "AXSheet") && c.ax_window_id == Some(requested)+ }).map(|(i, _)| i).collect();@@ -163,6 +165,14 @@ where// menu navigation with no replacement path. Keeping other non-window// children is also what `browser/consent_ui.rs` relies on to reach a// top-level `AXSheet` consent prompt.+ // A sheet's own id walks the sheet alone: it hangs off its parent window,+ // and nothing else at the top level belongs to it.+ if matched.iter().any(|&i| candidates[i].role == "AXSheet") {+ return ScopeDecision {+ scope: WindowScope::Matched,+ walk: matched,+ };+ }let dialog_scope = matched.iter().any(|&i| candidates[i].is_dialog_like());let walk = candidates.iter()@@ -304,6 +314,31 @@ mod tests {assert_eq!(d.walk, vec![0, 1]);}+ /// A request for a sheet's own id walks the sheet, never the parent+ /// window's controls or the application menu bar (Finder's Go to Folder+ /// sheet 15304 on window 167; the sheet is appended by the tree walker).+ #[test]+ fn a_sheet_id_walks_only_the_sheet() {+ let candidates = [+ TopLevelCandidate::new("AXMenuBar", None),+ TopLevelCandidate::new("AXSheet", None),+ TopLevelCandidate::new("AXWindow", Some(11)),+ TopLevelCandidate::new("AXWindow", Some(167)),+ TopLevelCandidate::new("AXSheet", Some(15304)),+ ];+ let d = decide_window_scope(&candidates, 15304, never_called);+ assert_eq!(d.scope, WindowScope::Matched);+ assert_eq!(+ d.walk,+ vec![4],+ "not the menu bar or another top-level sheet"+ );+ // The parent's own request still walks the parent (its sheet is in+ // its subtree) and the menu bar.+ let d = decide_window_scope(&candidates[..4], 167, never_called);+ assert_eq!(d.walk, vec![0, 1, 3]);+ }+#[test]fn menu_bar_only_app_has_no_ax_windows() {let candidates = [TopLevelCandidate::new("AXMenuBar", None)];diff --git a/libs/cua-driver/rust/crates/platform-macos/src/document_edit.rs b/libs/cua-driver/rust/crates/platform-macos/src/document_edit.rsindex ecededb4ae..3b4574f7ac 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/document_edit.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/document_edit.rs@@ -95,7 +95,7 @@ unsafe fn keys_reach_element_window(pid: i32, element: AXUIElementRef) -> bool {};let own = crate::ax::bindings::ax_get_window_id(window);core_foundation::base::CFRelease(window as _);- own.is_some() && crate::ax::bindings::focused_window_id_of_pid(pid) == own+ own.is_some() && crate::ax::bindings::focused_window_id_of_pid(pid).map(|w| w.own) == own}/// After an AX text write on `element` (in `pid`) that changed its value, make@@ -141,7 +141,7 @@ pub unsafe fn ensure_marked_after_ax_write(None => return DocumentEdited::NotMarked,Some(false) => {}}- let previous = crate::ax::bindings::focused_window_id_of_pid(pid);+ let previous = crate::ax::bindings::focused_window_id_of_pid(pid).map(|w| w.own);if !crate::input::skylight::activate_without_raise_with(pid, own, false) {return DocumentEdited::NotMarked;}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 cab7e4412f..0630b2b50f 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@@ -69,7 +69,7 @@ pub enum KeyPrime {#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct KeyFocus {/// The app's `AXFocusedWindow`.- pub window: Option<u32>,+ pub window: Option<crate::ax::exact_target::AxWindowId>,/// The window holding the app's `AXFocusedUIElement`.pub element_window: Option<u32>,}@@ -82,7 +82,7 @@ impl KeyFocus {/// reporting a modeless dialog's field as focused after its document/// window has become key and is receiving the keys.fn routes_to(self, target: u32) -> bool {- self.window == Some(target)+ self.window.is_some_and(|window| window.is(target))}/// `target` is key with nothing left to prime. A focused window without@@ -127,7 +127,8 @@ pub fn prime_exact_window_key(window is {:?}, its focused element is in window {:?}), so no keys were sent: they \could have gone to another window of the same app. Close the other window, or use \delivery_mode:\"foreground\"",- now.window, now.element_window+ now.window.map(|window| window.own),+ now.element_window))}@@ -297,7 +298,7 @@ fn await_key_focus(pid: pid_t, target: u32, budget: std::time::Duration) {/// hands key back. `Err` when it cannot be confirmed.pub fn enter_exact_window_key(pid: pid_t, target_wid: u32) -> Result<WindowKeyScope, String> {let before = key_focus_of_pid(pid);- let previous = before.window;+ let previous = before.window.map(|window| window.own);let order_before = app_window_order(pid);let primed = prime_exact_window_key(target_wid,@@ -1368,7 +1369,7 @@ const ACTIVATION_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_fn await_window_focused(pid: libc::pid_t, window_id: u32) -> bool {let deadline = std::time::Instant::now() + ACTIVATION_WAIT_TIMEOUT;loop {- if crate::ax::bindings::focused_window_id_of_pid(pid) == Some(window_id) {+ if crate::ax::bindings::focused_window_id_of_pid(pid).is_some_and(|w| w.is(window_id)) {return true;}if std::time::Instant::now() >= deadline {@@ -1385,8 +1386,9 @@ fn await_window_focused(pid: libc::pid_t, window_id: u32) -> bool {/// is proven.fn focus_failure_hint(pid: libc::pid_t, target_wid: u32) -> String {let target = crate::windows::window_info_by_id(target_wid);- let focused =- crate::ax::bindings::focused_window_id_of_pid(pid).filter(|focused| *focused != target_wid);+ let focused = crate::ax::bindings::focused_window_id_of_pid(pid)+ .filter(|focused| !focused.is(target_wid))+ .map(|focused| focused.own);focus_failure_hint_from(target.as_ref().map(|window| {window.is_on_screen && window.bounds.width >= 2.0 && window.bounds.height >= 2.0@@ -1494,12 +1496,12 @@ fn preserves_exact_existing_focus(previous_process_known: bool,previous_psn: [u8; 8],target_psn: [u8; 8],- focused_window_id: Option<u32>,+ focused_window_id: Option<crate::ax::exact_target::AxWindowId>,target_window_id: u32,) -> bool {previous_process_known&& previous_psn == target_psn- && focused_window_id == Some(target_window_id)+ && focused_window_id.is_some_and(|focused| focused.is(target_window_id))}#[cfg(test)]@@ -1509,6 +1511,7 @@ mod tests {preserves_exact_existing_focus, reset_windowserver_connection_invalid_for_test,windowserver_connection_invalid, WINDOWSERVER_INVALID_CONNECTION,};+ use crate::ax::exact_target::AxWindowId;#[test]fn a_1002_post_status_is_remembered_and_other_failures_are_not() {@@ -1580,7 +1583,22 @@ mod tests {#[test]fn exact_existing_focus_avoids_reactivation() {let psn = [1, 2, 3, 4, 5, 6, 7, 8];- assert!(preserves_exact_existing_focus(true, psn, psn, Some(42), 42));+ assert!(preserves_exact_existing_focus(+ true,+ psn,+ psn,+ Some(AxWindowId::window(42)),+ 42+ ));+ }++ #[test]+ fn a_focused_sheet_avoids_reactivation_for_the_sheet_and_its_window() {+ let psn = [1, 2, 3, 4, 5, 6, 7, 8];+ let sheet = Some(AxWindowId { own: 43, root: 42 });+ assert!(preserves_exact_existing_focus(true, psn, psn, sheet, 42));+ assert!(preserves_exact_existing_focus(true, psn, psn, sheet, 43));+ assert!(!preserves_exact_existing_focus(true, psn, psn, sheet, 41));}#[test]@@ -1591,21 +1609,21 @@ mod tests {false,target,target,- Some(42),+ Some(AxWindowId::window(42)),42));assert!(!preserves_exact_existing_focus(true,other,target,- Some(42),+ Some(AxWindowId::window(42)),42));assert!(!preserves_exact_existing_focus(true,target,target,- Some(41),+ Some(AxWindowId::window(41)),42));assert!(!preserves_exact_existing_focus(@@ -1617,15 +1635,48 @@ mod tests {#[cfg(test)]mod key_prime_tests {use super::{prime_exact_window_key, restore_target, KeyFocus, KeyPrime};+ use crate::ax::exact_target::AxWindowId;use std::cell::Cell;fn at(window: Option<u32>, element_window: Option<u32>) -> KeyFocus {KeyFocus {- window,+ window: window.map(AxWindowId::window),element_window,}}+ /// Sheet 15304 attached to window 167 is the app's focused window.+ fn sheet_focused() -> KeyFocus {+ KeyFocus {+ window: Some(AxWindowId {+ own: 15304,+ root: 167,+ }),+ element_window: Some(15304),+ }+ }++ /// Keys addressed to the window go to its open sheet, and keys addressed+ /// to the sheet itself are confirmed by the same focus read.+ #[test]+ fn a_focused_sheet_is_key_for_the_sheet_and_its_window() {+ for target in [167, 15304] {+ let r =+ prime_exact_window_key(target, sheet_focused, || panic!("record"), || panic!("ax"));+ assert_eq!(r, Ok(KeyPrime::AlreadyKey), "target {target}");+ }+ // A sibling window of the app is still refused.+ let r = prime_exact_window_key(200, sheet_focused, || true, || true);+ assert!(r.unwrap_err().contains("no keys were sent"));+ }++ /// The parent window focused does not prove keys reach its sheet.+ #[test]+ fn a_focused_parent_does_not_confirm_its_sheet() {+ let r = prime_exact_window_key(15304, || at(Some(167), Some(167)), || true, || true);+ assert!(r.unwrap_err().contains("no keys were sent"));+ }+#[test]fn already_key_sends_nothing() {let r = prime_exact_window_key(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 88ff810d55..4a499af6db 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@@ -205,7 +205,8 @@ fn observe_exact_window(pid: i32, window_id: u32) -> ExactWindowObservation {ExactWindowObservation {workspace_frontmost_pid: crate::apps::frontmost_pid(),front_process_matches_target: crate::input::skylight::front_process_matches(pid, window_id),- focused_window_id: crate::ax::bindings::focused_window_id_of_pid(pid),+ focused_window_id: crate::ax::bindings::focused_window_id_of_pid(pid)+ .map(|window| window.own),frontmost_ordinary_window_id,process_front_window_on_display,target_visible_ordinary,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 85beac9149..eddeb4d720 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@@ -1224,7 +1224,7 @@ impl ClickTool {let refusal = tokio::task::spawn_blocking(move || unsafe {let element = element_at_screen_position(pid, screen_x, screen_y)?;let refusal = (crate::ax::exact_target::element_window_id(element)- == Some(select_wid)+ .is_some_and(|window| window.is(select_wid))&& super::set_value::is_chromium_web_select(pid, select_wid, element)).then(|| {super::set_value::chromium_select_open_refusal(@@ -1270,7 +1270,9 @@ impl ClickTool {// Require proven ancestry in the requested window before// acting; otherwise fall through to the routed pixel path// (already gated for this exact window).- if crate::ax::exact_target::element_window_id(element) != Some(hit_test_wid) {+ if !crate::ax::exact_target::element_window_id(element)+ .is_some_and(|window| window.is(hit_test_wid))+ {CFRelease(element as _);return Ok(false);}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 e37391b0b2..2bf5d89d84 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@@ -449,7 +449,7 @@ fn focus_exact_window(pid: i32, window_id: u32) -> Result<(), String> {if exact_window_is_ready(live_frontmost_pid(pid, window_id),pid,- crate::ax::bindings::focused_window_id_of_pid(pid),+ crate::ax::bindings::focused_window_id_of_pid(pid).map(|window| window.own),window_id,) {let since = stable_since.get_or_insert(now);@@ -926,8 +926,9 @@ impl Tool for InvokeMenuTool {let outcome = tokio::task::spawn_blocking(move || {let prior_frontmost = live_frontmost_app().or_else(crate::apps::frontmost_pid);- let prior_frontmost_window =- prior_frontmost.and_then(crate::ax::bindings::focused_window_id_of_pid);+ let prior_frontmost_window = prior_frontmost.and_then(|prior| {+ crate::ax::bindings::focused_window_id_of_pid(prior).map(|window| window.own)+ });let needs_activation = prior_frontmost != Some(pid);let result = focus_exact_window(pid, window_id)diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rsindex ce1a8062a4..3e6f338940 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs@@ -235,7 +235,7 @@ mod pid_window_target_tests {/// sends process-scoped key events anyway. `None` leaves the call refused.fn pid_focused_window(pid: i64) -> Option<u64> {let pid = i32::try_from(pid).ok()?;- crate::ax::bindings::focused_window_id_of_pid(pid).map(u64::from)+ crate::ax::bindings::focused_window_id_of_pid(pid).map(|window| u64::from(window.root))}fn pid_window_guarded<T: Tool + 'static>(@@ -442,7 +442,8 @@ pub(crate) fn default_window_for_pid(args: &mut serde_json::Value) {else {return;};- let window_id = crate::ax::bindings::focused_window_id_of_pid(pid).or_else(|| {+ let focused = crate::ax::bindings::focused_window_id_of_pid(pid).map(|window| window.root);+ let window_id = focused.or_else(|| {crate::windows::all_windows().into_iter().filter(|window| window.pid == pid && window.is_on_screen && window.layer == 0)@@ -760,16 +761,14 @@ async fn focused_element_holds_point(return false;};let rect = crate::ax::bindings::element_screen_rect(focused);- let focused_window = if require_window {- crate::ax::exact_target::element_window_id(focused)- } else {- Some(wid)- };+ let in_window = !require_window+ || crate::ax::exact_target::element_window_id(focused)+ .is_some_and(|window| window.is(wid));core_foundation::base::CFRelease(focused as core_foundation::base::CFTypeRef);let Some(rect) = rect else {return false;};- focused_window == Some(wid) && point_within_rect(rect, screen_x, screen_y)+ in_window && point_within_rect(rect, screen_x, screen_y)}}).awaitdiff --git a/libs/cua-driver/rust/crates/platform-macos/tests/embedded_menu_restore.rs b/libs/cua-driver/rust/crates/platform-macos/tests/embedded_menu_restore.rsindex 9c35f9de79..100a64e93b 100644--- a/libs/cua-driver/rust/crates/platform-macos/tests/embedded_menu_restore.rs+++ b/libs/cua-driver/rust/crates/platform-macos/tests/embedded_menu_restore.rs@@ -213,7 +213,9 @@ mod native {&& platform_macos::apps::frontmost_pid() == Some(std::process::id() as i32)&& platform_macos::ax::bindings::focused_window_id_of_pid(std::process::id() as i32- ) == Some(original_wid as u32);+ )+ .map(|window| window.own)+ == Some(original_wid as u32);if ready {if stable_since.get_or_insert_with(Instant::now).elapsed()>= Duration::from_millis(300)diff --git a/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift b/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swiftindex 39160da5c8..e419041e33 100644--- a/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift+++ b/libs/cua-driver/tests/fixtures/apps/macos/appkit/main.swift@@ -79,6 +79,7 @@ let kExitButtonAID = "btn-exit"let kMenuItemTitle = "Harness Test Item"let kSecondaryWindowTitle = "CuaTestHarness AppKit Secondary"let kSheetWindowTitle = "CuaTestHarness AppKit Sheet"+let kSheetInputAID = "txt-sheet"let kFloatingWindowTitle = "CuaTestHarness AppKit Floating"let kTaskStateEnv = "CUA_APPKIT_TASK_STATE"let kTaskStateSchema = "cua.appkit_task_state_v1"@@ -870,14 +871,28 @@ final class BringToFrontMatrixWindows {secondary.contentView = NSTextField(labelWithString: "bring_to_front secondary ordinary window")secondary.orderFront(nil)- if mode == "sheet" {+ if mode == "sheet" || mode == "sheet-input" {let candidate = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 360, height: 160),styleMask: [.titled], backing: .buffered, defer: false)candidate.title = kSheetWindowTitlecandidate.contentView = NSTextField(labelWithString: "modal sheet blocks parent key status")+ // An editable field, like Finder's Go to Folder path, for keys+ // addressed to the sheet or to its parent window.+ var field: NSTextField?+ if mode == "sheet-input" {+ let input = NSTextField(frame: NSRect(x: 20, y: 60, width: 320, height: 24))+ input.setAccessibilityIdentifier(kSheetInputAID)+ let content = NSView(frame: NSRect(x: 0, y: 0, width: 360, height: 160))+ content.addSubview(input)+ candidate.contentView = content+ field = input+ }sheet = candidateparent.beginSheet(candidate)+ if let field {+ candidate.makeFirstResponder(field)+ }} else if mode == "floating" {let candidate = NSPanel(contentRect: NSRect(x: 180, y: 180, width: 320, height: 140),