From 37465542d48b785beeb943816d61808b53877e15 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Sun, 15 Nov 2026 23:17:40 -0800 Subject: [PATCH 01/19] fix(macos): bound the open-menu search like a skeleton and keep a raised popover when the inventory fails `list-surfaces`, `snapshot --surface menu` and the surface report after a click look for an open context menu. When none was open, the search walked every node of every window of the application. A Finder window in column view held 2,376 nodes and the walk took 5.8 s, so all three timed out on that app (at the base of this branch too), and the click on Finder's Share button took 4 to 7 s and reported no surface although its popover was open. A menu hangs directly below the element that shows it. The search still checks every child, but it no longer opens the items of a content container (more than 16 children: a list, a table, a column of a browser). On the same window `list-surfaces` now answers in 0.4 to 0.7 s and the Share click returns in 0.4 s. The surfaces below the clicked element are read before the inventory and are kept when the inventory fails, so a failed inventory no longer hides a popover the action raised. --- crates/macos/src/tree/adapter.rs | 9 ++- crates/macos/src/tree/app_menu.rs | 23 +++++-- crates/macos/src/tree/app_menu_tests.rs | 63 ++++++++++++++++--- crates/macos/src/tree/surface_inventory.rs | 22 ++++++- .../macos/src/tree/surface_inventory_tests.rs | 20 ++++++ 5 files changed, 117 insertions(+), 20 deletions(-) diff --git a/crates/macos/src/tree/adapter.rs b/crates/macos/src/tree/adapter.rs index f1636c81e3..a6094491ec 100644 --- a/crates/macos/src/tree/adapter.rs +++ b/crates/macos/src/tree/adapter.rs @@ -115,16 +115,19 @@ impl ObservationOps for MacOSAdapter { raised_by: &NativeHandle, deadline: Deadline, ) -> Result, AdapterError> { - let mut surfaces = self.list_surfaces(process, deadline)?; + let mut anchored = Vec::new(); #[cfg(target_os = "macos")] if let Ok(anchor) = ax_element(raised_by) { crate::tree::surface_inventory::collect_anchored_surfaces( anchor, deadline, - &mut surfaces, + &mut anchored, ); } - Ok(surfaces) + crate::tree::surface_inventory::with_anchored( + self.list_surfaces(process, deadline), + anchored, + ) } fn hit_test( diff --git a/crates/macos/src/tree/app_menu.rs b/crates/macos/src/tree/app_menu.rs index 19eb6637e1..72c297beaa 100644 --- a/crates/macos/src/tree/app_menu.rs +++ b/crates/macos/src/tree/app_menu.rs @@ -198,7 +198,7 @@ fn find_menu_descendant( source: String, deadline: Deadline, ) -> Result, AdapterError> { - find_menu_descendant_with(root, source, deadline, |element| { + find_menu_descendant_with(root, source, deadline, |element, expand| { let role = surface_read::string(element, "AXRole", deadline)?; if role.as_deref() == Some("AXMenuBar") { return Ok((false, Vec::new())); @@ -208,6 +208,9 @@ fn find_menu_descendant( { return Ok((true, Vec::new())); } + if !expand { + return Ok((false, Vec::new())); + } Ok(( false, surface_read::elements(element, "AXChildren", deadline)?, @@ -215,22 +218,29 @@ fn find_menu_descendant( }) } +/// Breadth-first search for an open menu below `root`. A menu hangs directly +/// below the element that shows it, so every child is checked, but the items +/// of a content container (more than `ANCHOR_CHILD_LIMIT` children: a list, +/// a table, a column of a browser) are not opened: what lies inside an item is +/// that item's content, and reading it made the search grow with the content +/// of every window. `inspect` gets whether it may return the element's +/// children. fn find_menu_descendant_with( root: T, source: String, deadline: Deadline, - mut inspect: impl FnMut(&T) -> Result<(bool, Vec), AdapterError>, + mut inspect: impl FnMut(&T, bool) -> Result<(bool, Vec), AdapterError>, ) -> Result, AdapterError> { - let mut pending = std::collections::VecDeque::from([(source, root)]); + let mut pending = std::collections::VecDeque::from([(source, root, true)]); let mut incomplete = None; let mut visited = 0_usize; - while let Some((path, element)) = pending.pop_front() { + while let Some((path, element, expand)) = pending.pop_front() { surface_read::ensure_before_deadline(deadline)?; visited += 1; if visited > MAX_SURFACE_NODES { return Err(surface_limit_error()); } - let (is_menu, children) = match inspect(&element) { + let (is_menu, children) = match inspect(&element, expand) { Ok(observed) => observed, Err(error) if error.code == ErrorCode::AppUnresponsive && !invalidated(&error) => { incomplete.get_or_insert(error); @@ -241,11 +251,12 @@ fn find_menu_descendant_with( if is_menu { return Ok(Some((path, element))); } + let expand_children = children.len() <= super::surface_inventory::ANCHOR_CHILD_LIMIT; pending.extend( children .into_iter() .enumerate() - .map(|(index, child)| (format!("{path}/children/{index}"), child)), + .map(|(index, child)| (format!("{path}/children/{index}"), child, expand_children)), ); } incomplete.map_or(Ok(None), Err) diff --git a/crates/macos/src/tree/app_menu_tests.rs b/crates/macos/src/tree/app_menu_tests.rs index bd8d807d9a..870d2aaa18 100644 --- a/crates/macos/src/tree/app_menu_tests.rs +++ b/crates/macos/src/tree/app_menu_tests.rs @@ -234,7 +234,7 @@ fn surface_node_limit_is_explicitly_incomplete() { fn menus_beyond_eight_wrappers_remain_discoverable() { let deadline = Deadline::after(5000).unwrap(); for target_depth in [9, 11, 30] { - let found = find_menu_descendant_with(0, "app".into(), deadline, |depth| { + let found = find_menu_descendant_with(0, "app".into(), deadline, |depth, _| { Ok((*depth == target_depth, vec![depth + 1])) }) .unwrap(); @@ -245,12 +245,16 @@ fn menus_beyond_eight_wrappers_remain_discoverable() { #[test] fn cyclic_menu_search_remains_bounded_and_explicitly_incomplete() { let mut reads = 0; - let error = - find_menu_descendant_with(0, "app".into(), Deadline::after(5000).unwrap(), |node| { + let error = find_menu_descendant_with( + 0, + "app".into(), + Deadline::after(5000).unwrap(), + |node, _| { reads += 1; Ok((false, vec![*node])) - }) - .unwrap_err(); + }, + ) + .unwrap_err(); assert_eq!(reads, MAX_SURFACE_NODES); assert_eq!(error.details.unwrap()["complete"], false); } @@ -258,7 +262,7 @@ fn cyclic_menu_search_remains_bounded_and_explicitly_incomplete() { #[test] fn expired_menu_search_never_reads_a_node() { let result = - find_menu_descendant_with::<()>((), "app".into(), Deadline::after(0).unwrap(), |_| { + find_menu_descendant_with::<()>((), "app".into(), Deadline::after(0).unwrap(), |_, _| { panic!("expired search must not call AX") }); assert_eq!(result.unwrap_err().code, ErrorCode::Timeout); @@ -270,7 +274,7 @@ fn incomplete_content_branch_does_not_hide_a_menu_in_a_sibling() { 0, "app".into(), Deadline::after(5000).unwrap(), - |node| match node { + |node, _| match node { 0 => Ok((false, vec![1, 2])), 1 => Err(surface_limit_error()), 2 => Ok((true, vec![])), @@ -286,7 +290,7 @@ fn an_incomplete_branch_cannot_prove_menu_absence() { 0, "app".into(), Deadline::after(5000).unwrap(), - |node| match node { + |node, _| match node { 0 => Ok((false, vec![1, 2])), 1 => Err(surface_limit_error()), _ => Ok((false, vec![])), @@ -298,13 +302,13 @@ fn an_incomplete_branch_cannot_prove_menu_absence() { #[test] fn shallow_menu_precedes_unbounded_content_and_permission_errors_stay_terminal() { let deadline = Deadline::after(5000).unwrap(); - let found = find_menu_descendant_with(0, "app".into(), deadline, |node| match node { + let found = find_menu_descendant_with(0, "app".into(), deadline, |node, _| match node { 0 => Ok((false, vec![1, 2])), 1 => Ok((false, vec![1])), _ => Ok((true, vec![])), }); assert_eq!(found.unwrap(), Some(("app/children/1".into(), 2))); - let denied = find_menu_descendant_with(0, "app".into(), deadline, |node| match node { + let denied = find_menu_descendant_with(0, "app".into(), deadline, |node, _| match node { 0 => Ok((false, vec![1, 2])), 1 => Err(AdapterError::new(ErrorCode::PermDenied, "denied")), _ => panic!("permission failure must stop all further AX reads"), @@ -349,3 +353,42 @@ fn invalidated_menu_roots_are_reacquired_once_and_permission_errors_are_terminal } } } + +#[test] +fn the_items_of_a_content_container_are_checked_but_not_opened() { + let deadline = Deadline::after(5000).unwrap(); + let wide = super::super::surface_inventory::ANCHOR_CHILD_LIMIT + 1; + let mut opened = Vec::new(); + let found = find_menu_descendant_with(0_usize, "app".into(), deadline, |node, expand| { + if expand { + opened.push(*node); + } + Ok(match *node { + 0 => (false, vec![1, 2]), + 1 => (false, (100..100 + wide).collect()), + 2 => (false, vec![3]), + 3 => (true, vec![]), + item if item >= 100 => (false, vec![item * 10]), + _ => (false, vec![]), + }) + }) + .unwrap(); + + assert_eq!(found.map(|(_, node)| node), Some(3)); + assert!(opened.iter().all(|node| *node < 100)); +} + +#[test] +fn a_menu_among_the_items_of_a_content_container_is_still_found() { + let deadline = Deadline::after(5000).unwrap(); + let wide = super::super::surface_inventory::ANCHOR_CHILD_LIMIT + 1; + let found = find_menu_descendant_with(0_usize, "app".into(), deadline, |node, _| { + Ok(match *node { + 0 => (false, (100..100 + wide).collect()), + node => (node == 100 + wide - 1, vec![]), + }) + }) + .unwrap(); + + assert_eq!(found.map(|(_, node)| node), Some(100 + wide - 1)); +} diff --git a/crates/macos/src/tree/surface_inventory.rs b/crates/macos/src/tree/surface_inventory.rs index 8f7efb5237..eb06d82848 100644 --- a/crates/macos/src/tree/surface_inventory.rs +++ b/crates/macos/src/tree/surface_inventory.rs @@ -1,7 +1,9 @@ use crate::tree::{AXElement, properties::element::element_for_pid}; use agent_desktop_core::{AdapterError, Deadline, SurfaceInfo}; -const ANCHOR_CHILD_LIMIT: usize = 16; +/// The most children an element that anchors a surface has. An element with +/// more is a content container: a list, a table or a column of a browser. +pub(crate) const ANCHOR_CHILD_LIMIT: usize = 16; pub(crate) fn list_surfaces_for_process( identity: crate::system::process::process_identity::ProcessIdentity, @@ -89,6 +91,24 @@ pub(crate) fn collect_anchored_surfaces( } } +/// The surfaces an action raised: the application's inventory, then the ones +/// hanging below the element the action targeted. Those are read first and +/// cost a few reads, so an inventory that fails does not hide them; the +/// failure is returned only when no anchored surface was found. +pub(crate) fn with_anchored( + inventory: Result, AdapterError>, + anchored: Vec, +) -> Result, AdapterError> { + match inventory { + Ok(mut surfaces) => { + surfaces.extend(anchored); + Ok(surfaces) + } + Err(error) if anchored.is_empty() => Err(error), + Err(_) => Ok(anchored), + } +} + fn anchors_few_children(count: Option) -> bool { count.is_some_and(|count| (1..=ANCHOR_CHILD_LIMIT).contains(&count)) } diff --git a/crates/macos/src/tree/surface_inventory_tests.rs b/crates/macos/src/tree/surface_inventory_tests.rs index 26c4f92a79..1311862266 100644 --- a/crates/macos/src/tree/surface_inventory_tests.rs +++ b/crates/macos/src/tree/surface_inventory_tests.rs @@ -84,3 +84,23 @@ fn only_a_control_with_few_children_is_read_for_an_anchored_surface() { assert!(!anchors_few_children(Some(ANCHOR_CHILD_LIMIT + 1))); assert!(!anchors_few_children(None)); } + +#[test] +fn a_failed_inventory_does_not_hide_the_surface_below_the_target() { + let failed = || Err(agent_desktop_core::AdapterError::timeout("inventory")); + + let kept = + super::with_anchored(failed(), vec![surface("target/children/0", "popover")]).unwrap(); + assert_eq!(kept.len(), 1); + assert!(super::with_anchored(failed(), Vec::new()).is_err()); + + let both = super::with_anchored( + Ok(vec![surface("menu", "menu")]), + vec![surface("target", "popover")], + ) + .unwrap(); + assert_eq!( + both.iter().map(|s| s.id.as_str()).collect::>(), + ["menu", "target"] + ); +} From 3a16e7c12c3485ef755d1b65cd5bb158b23735d1 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Sun, 15 Nov 2026 23:44:21 -0800 Subject: [PATCH 02/19] feat(macos): close an open menu or popover with Escape in the background `press escape --app` sent the key to the application's focus holder. When the focus holder did not take Escape and a popover was open, as after a headless click on Finder's Share button, the press failed for lack of a focused element or went to the window behind the popover, and the popover stayed on the user's screen. Escape now reaches, in this order: the focus holder that advertises the cancel action, as before; then, when no focus holder takes it, the menu or popover the application shows, through that surface's own cancel action, verified by reading that the surface is gone; then the key event route, as before. The surface is found in one pass by the bounded search that finds an open menu, which now also accepts a popover; the popover snapshot uses the same search in place of its own unbounded walk. On Finder the Share popover closes in 0.37 s with `delivered_verified` and the front application unchanged. With no surface open, the result is the same as before on Finder and Stickies; the search adds about 0.15 s on a Finder window of 2,376 elements. --- crates/macos/src/system/key_dispatch.rs | 108 ++++++++++++++++-- crates/macos/src/system/key_dispatch_tests.rs | 19 +++ crates/macos/src/tree/app_menu.rs | 63 +++++++--- crates/macos/src/tree/app_menu_tests.rs | 26 +++-- crates/macos/src/tree/surfaces.rs | 78 ++++++++----- skills/agent-desktop-macos/SKILL.md | 4 + 6 files changed, 235 insertions(+), 63 deletions(-) diff --git a/crates/macos/src/system/key_dispatch.rs b/crates/macos/src/system/key_dispatch.rs index 996516d34e..b6b7aff472 100644 --- a/crates/macos/src/system/key_dispatch.rs +++ b/crates/macos/src/system/key_dispatch.rs @@ -43,9 +43,9 @@ fn press_for_app( } } if let Some(action) = simple_key_action(combo) - && try_simple_key_action(&app, action, deadline)? + && let Some(step) = deliver_semantic_key(pid, &app, action, deadline)? { - return post_delivery_process_result(&process, semantic_step(action)); + return post_delivery_process_result(&process, step); } crate::input::keyboard::keyboard_map::key_name_to_code(&combo.key)?; @@ -77,34 +77,120 @@ fn post_delivery_process_result( ) -> Result { crate::system::process::process_identity::require_core(process) .map_err(|error| error.with_disposition(DeliverySemantics::delivered_unverified()))?; - Ok(ActionResult::delivered_unverified("press_key").with_steps(vec![step])) + let verified = step.verified == Some(true); + let result = ActionResult::delivered_unverified("press_key").with_steps(vec![step]); + Ok(if verified { + result.with_verified_delivery() + } else { + result + }) +} + +/// Where a key without modifiers lands as an accessibility action. +#[derive(Debug, PartialEq, Eq)] +enum SemanticKeyTarget { + /// The focus holder advertises the action the key stands for. + FocusHolder(T), + /// Escape while no focus holder takes it and the application shows a menu + /// or a popover: the surface the key would close. + OpenSurface(T), +} + +/// The states in the order they are tried: the focus holder, then, for +/// Escape only, the open surface. None leaves the key its event route. +fn choose_key_target( + focus_holder: Option, + action: &str, + open_surface: impl FnOnce() -> Option, +) -> Option> { + if let Some(holder) = focus_holder { + return Some(SemanticKeyTarget::FocusHolder(holder)); + } + (action == CANCEL) + .then(open_surface) + .flatten() + .map(SemanticKeyTarget::OpenSurface) } -fn try_simple_key_action( +fn semantic_key_target( + pid: i32, app: &AXElement, action: &str, deadline: Deadline, -) -> Result { - let Some(focused) = focused_element(app, deadline)? else { - return Ok(false); +) -> Result>, AdapterError> { + let focus_holder = focused_element(app, deadline)?.filter(|focused| { + crate::actions::ax_helpers::advertises_action(focused, action, deadline) == Some(true) + }); + Ok(choose_key_target(focus_holder, action, || { + open_transient_surface(pid, deadline) + })) +} + +/// The menu or popover the application shows. A read that cannot finish finds +/// none, and the key then takes the route it had before. +fn open_transient_surface(pid: i32, deadline: Deadline) -> Option { + crate::tree::surfaces::transient_surface_for_pid(pid, deadline) + .ok() + .flatten() +} + +/// Performs the action on the target the key reaches. A closed surface is +/// verified by reading that it is gone. +fn deliver_semantic_key( + pid: i32, + app: &AXElement, + action: &'static str, + deadline: Deadline, +) -> Result, AdapterError> { + let Some(target) = semantic_key_target(pid, app, action, deadline)? else { + return Ok(None); + }; + let (element, closes_surface) = match &target { + SemanticKeyTarget::FocusHolder(element) => (element, false), + SemanticKeyTarget::OpenSurface(element) => (element, true), }; - if crate::actions::ax_helpers::advertises_action(&focused, action, deadline) != Some(true) { - return Ok(false); + if !crate::actions::ax_helpers::try_ax_action_or_err(element, action, deadline)? { + return Ok(None); } - crate::actions::ax_helpers::try_ax_action_or_err(&focused, action, deadline) + let closed = closes_surface && surface_closed(element, deadline); + Ok(Some(semantic_step(action).with_verified(closed))) +} + +/// A closed surface leaves the tree: a popover's element becomes invalid, and +/// a menu's element stays readable but is no longer a child of its parent. +fn surface_closed(surface: &AXElement, deadline: Deadline) -> bool { + let gone = || match crate::tree::surface_read::element(surface, "AXParent", deadline) { + Err(error) => error.code == ErrorCode::StaleRef, + Ok(None) => true, + Ok(Some(parent)) => crate::tree::surface_read::elements(&parent, "AXChildren", deadline) + .is_ok_and(|children| { + !children + .iter() + .any(|child| crate::tree::same_element(child, surface)) + }), + }; + deadline.poll_until( + SURFACE_CLOSE_WAIT, + Duration::from_millis(10), + gone, + |gone| *gone, + ) } fn uses_menu_shortcut(combo: &KeyCombo, policy: InteractionPolicy) -> bool { policy.allow_focus_steal && !combo.modifiers.is_empty() } +const CANCEL: &str = "AXCancel"; +const SURFACE_CLOSE_WAIT: Duration = Duration::from_millis(500); + fn simple_key_action(combo: &KeyCombo) -> Option<&'static str> { if !combo.modifiers.is_empty() { return None; } match combo.key.as_str() { "return" | "enter" => Some("AXConfirm"), - "escape" | "esc" => Some("AXCancel"), + "escape" | "esc" => Some(CANCEL), _ => None, } } diff --git a/crates/macos/src/system/key_dispatch_tests.rs b/crates/macos/src/system/key_dispatch_tests.rs index 8ff26dd656..bbf1414087 100644 --- a/crates/macos/src/system/key_dispatch_tests.rs +++ b/crates/macos/src/system/key_dispatch_tests.rs @@ -114,3 +114,22 @@ fn an_unresolvable_key_fails_before_any_focus_change() { error.message ); } + +#[test] +fn escape_reaches_the_focus_holder_first_then_the_open_surface() { + use super::{SemanticKeyTarget, choose_key_target}; + + assert_eq!( + choose_key_target(Some(1), "AXCancel", || panic!("surface read")), + Some(SemanticKeyTarget::FocusHolder(1)) + ); + assert_eq!( + choose_key_target(None, "AXCancel", || Some(2)), + Some(SemanticKeyTarget::OpenSurface(2)) + ); + assert_eq!(choose_key_target::(None, "AXCancel", || None), None); + assert_eq!( + choose_key_target::(None, "AXConfirm", || panic!("surface read")), + None + ); +} diff --git a/crates/macos/src/tree/app_menu.rs b/crates/macos/src/tree/app_menu.rs index 72c297beaa..0741f36773 100644 --- a/crates/macos/src/tree/app_menu.rs +++ b/crates/macos/src/tree/app_menu.rs @@ -113,6 +113,14 @@ fn menu_element_for_pid(pid: i32, deadline: Deadline) -> Result Result, AdapterError> { + open_menus_for_pid_until(pid, Transient::Menu, deadline) +} + +fn open_menus_for_pid_until( + pid: i32, + accept: Transient, + deadline: Deadline, ) -> Result, AdapterError> { let mut menus = Vec::new(); if let Some(menubar) = menubar_for_pid(pid, deadline)? { @@ -131,13 +139,35 @@ pub(crate) fn open_menus_for_pid( ); } if menus.is_empty() - && let Some((id, menu)) = context_menu_from_app(pid, deadline)? + && let Some((id, menu)) = surface_from_app(pid, accept, deadline)? { menus.push(("context_menu", id, menu)); } Ok(menus) } +/// What a search below the application accepts as the open transient surface. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Transient { + Menu, + MenuOrPopover, +} + +/// The menu or popover the application shows, in one pass: an open menu bar +/// menu first, then the bounded search below the application. +#[cfg(target_os = "macos")] +pub(crate) fn open_transient_surface( + pid: i32, + deadline: Deadline, +) -> Result, AdapterError> { + Ok( + open_menus_for_pid_until(pid, Transient::MenuOrPopover, deadline)? + .into_iter() + .next() + .map(|(_, _, surface)| surface), + ) +} + fn open_menubar_menus_with( menubar: &T, mut children: impl FnMut(&T) -> Result, AdapterError>, @@ -162,8 +192,9 @@ fn open_menubar_menus_with( } #[cfg(target_os = "macos")] -fn context_menu_from_app( +fn surface_from_app( pid: i32, + accept: Transient, deadline: Deadline, ) -> Result, AdapterError> { let app = element_for_pid(pid); @@ -176,7 +207,8 @@ fn context_menu_from_app( } } if let Some(focused) = surface_read::element(&app, "AXFocusedUIElement", deadline)? - && let Some(menu) = find_menu_descendant(focused, "app/focused-element".into(), deadline)? + && let Some(menu) = + find_menu_descendant(focused, "app/focused-element".into(), accept, deadline)? { return Ok(Some(menu)); } @@ -184,7 +216,8 @@ fn context_menu_from_app( .into_iter() .enumerate() { - if let Some(menu) = find_menu_descendant(child, format!("app/children/{index}"), deadline)? + if let Some(menu) = + find_menu_descendant(child, format!("app/children/{index}"), accept, deadline)? { return Ok(Some(menu)); } @@ -196,13 +229,17 @@ fn context_menu_from_app( fn find_menu_descendant( root: AXElement, source: String, + accept: Transient, deadline: Deadline, ) -> Result, AdapterError> { - find_menu_descendant_with(root, source, deadline, |element, expand| { + find_surface_descendant_with(root, source, deadline, |element, expand| { let role = surface_read::string(element, "AXRole", deadline)?; if role.as_deref() == Some("AXMenuBar") { return Ok((false, Vec::new())); } + if accept == Transient::MenuOrPopover && role.as_deref() == Some("AXPopover") { + return Ok((true, Vec::new())); + } if role.as_deref() == Some("AXMenu") && surface_read::boolean(element, "AXVisible", deadline)? != Some(false) { @@ -218,14 +255,14 @@ fn find_menu_descendant( }) } -/// Breadth-first search for an open menu below `root`. A menu hangs directly -/// below the element that shows it, so every child is checked, but the items -/// of a content container (more than `ANCHOR_CHILD_LIMIT` children: a list, -/// a table, a column of a browser) are not opened: what lies inside an item is -/// that item's content, and reading it made the search grow with the content -/// of every window. `inspect` gets whether it may return the element's -/// children. -fn find_menu_descendant_with( +/// Breadth-first search below `root` for a transient surface: a menu, or a +/// popover. Such a surface hangs directly below the element that shows it, +/// so every child is checked, but the items of a content container (more than +/// `ANCHOR_CHILD_LIMIT` children: a list, a table, a column of a browser) are +/// not opened: what lies inside an item is that item's content, and reading it +/// made the search grow with the content of every window. `inspect` gets +/// whether it may return the element's children. +pub(super) fn find_surface_descendant_with( root: T, source: String, deadline: Deadline, diff --git a/crates/macos/src/tree/app_menu_tests.rs b/crates/macos/src/tree/app_menu_tests.rs index 870d2aaa18..6b32e3e5b5 100644 --- a/crates/macos/src/tree/app_menu_tests.rs +++ b/crates/macos/src/tree/app_menu_tests.rs @@ -234,7 +234,7 @@ fn surface_node_limit_is_explicitly_incomplete() { fn menus_beyond_eight_wrappers_remain_discoverable() { let deadline = Deadline::after(5000).unwrap(); for target_depth in [9, 11, 30] { - let found = find_menu_descendant_with(0, "app".into(), deadline, |depth, _| { + let found = find_surface_descendant_with(0, "app".into(), deadline, |depth, _| { Ok((*depth == target_depth, vec![depth + 1])) }) .unwrap(); @@ -245,7 +245,7 @@ fn menus_beyond_eight_wrappers_remain_discoverable() { #[test] fn cyclic_menu_search_remains_bounded_and_explicitly_incomplete() { let mut reads = 0; - let error = find_menu_descendant_with( + let error = find_surface_descendant_with( 0, "app".into(), Deadline::after(5000).unwrap(), @@ -261,16 +261,18 @@ fn cyclic_menu_search_remains_bounded_and_explicitly_incomplete() { #[test] fn expired_menu_search_never_reads_a_node() { - let result = - find_menu_descendant_with::<()>((), "app".into(), Deadline::after(0).unwrap(), |_, _| { - panic!("expired search must not call AX") - }); + let result = find_surface_descendant_with::<()>( + (), + "app".into(), + Deadline::after(0).unwrap(), + |_, _| panic!("expired search must not call AX"), + ); assert_eq!(result.unwrap_err().code, ErrorCode::Timeout); } #[test] fn incomplete_content_branch_does_not_hide_a_menu_in_a_sibling() { - let result = find_menu_descendant_with( + let result = find_surface_descendant_with( 0, "app".into(), Deadline::after(5000).unwrap(), @@ -286,7 +288,7 @@ fn incomplete_content_branch_does_not_hide_a_menu_in_a_sibling() { #[test] fn an_incomplete_branch_cannot_prove_menu_absence() { - let result = find_menu_descendant_with( + let result = find_surface_descendant_with( 0, "app".into(), Deadline::after(5000).unwrap(), @@ -302,13 +304,13 @@ fn an_incomplete_branch_cannot_prove_menu_absence() { #[test] fn shallow_menu_precedes_unbounded_content_and_permission_errors_stay_terminal() { let deadline = Deadline::after(5000).unwrap(); - let found = find_menu_descendant_with(0, "app".into(), deadline, |node, _| match node { + let found = find_surface_descendant_with(0, "app".into(), deadline, |node, _| match node { 0 => Ok((false, vec![1, 2])), 1 => Ok((false, vec![1])), _ => Ok((true, vec![])), }); assert_eq!(found.unwrap(), Some(("app/children/1".into(), 2))); - let denied = find_menu_descendant_with(0, "app".into(), deadline, |node, _| match node { + let denied = find_surface_descendant_with(0, "app".into(), deadline, |node, _| match node { 0 => Ok((false, vec![1, 2])), 1 => Err(AdapterError::new(ErrorCode::PermDenied, "denied")), _ => panic!("permission failure must stop all further AX reads"), @@ -359,7 +361,7 @@ fn the_items_of_a_content_container_are_checked_but_not_opened() { let deadline = Deadline::after(5000).unwrap(); let wide = super::super::surface_inventory::ANCHOR_CHILD_LIMIT + 1; let mut opened = Vec::new(); - let found = find_menu_descendant_with(0_usize, "app".into(), deadline, |node, expand| { + let found = find_surface_descendant_with(0_usize, "app".into(), deadline, |node, expand| { if expand { opened.push(*node); } @@ -382,7 +384,7 @@ fn the_items_of_a_content_container_are_checked_but_not_opened() { fn a_menu_among_the_items_of_a_content_container_is_still_found() { let deadline = Deadline::after(5000).unwrap(); let wide = super::super::surface_inventory::ANCHOR_CHILD_LIMIT + 1; - let found = find_menu_descendant_with(0_usize, "app".into(), deadline, |node, _| { + let found = find_surface_descendant_with(0_usize, "app".into(), deadline, |node, _| { Ok(match *node { 0 => (false, (100..100 + wide).collect()), node => (node == 100 + wide - 1, vec![]), diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rs index ba4f951c35..5827ccc0f4 100644 --- a/crates/macos/src/tree/surfaces.rs +++ b/crates/macos/src/tree/surfaces.rs @@ -1,9 +1,6 @@ use super::{AXElement, properties::element::element_for_pid, surface_read}; use agent_desktop_core::{AdapterError, Deadline, ErrorCode, SnapshotSurface}; -#[cfg(target_os = "macos")] -const POPOVER_SEARCH_LIMIT: usize = 4_096; - #[cfg(target_os = "macos")] pub(crate) fn focused_surface_for_pid( pid: i32, @@ -25,6 +22,19 @@ pub(crate) fn menu_element_for_pid( }) } +/// The menu or popover the application shows, read in one bounded pass. +#[cfg(target_os = "macos")] +pub(crate) fn transient_surface_for_pid( + pid: i32, + deadline: Deadline, +) -> Result, AdapterError> { + let identity = crate::system::process::process_identity::ProcessIdentity::capture(pid)? + .ok_or_else(|| AdapterError::stale_ref_because("Application exited"))?; + super::app_menu::observe(identity, deadline, || { + super::app_menu::open_transient_surface(pid, deadline) + }) +} + #[cfg(target_os = "macos")] fn first_child_with_role_or_subrole( pid: i32, @@ -60,38 +70,52 @@ pub(crate) fn surface_in_window( } } -/// The first popover in `window`, nearest the window first. None only when -/// every element was read: a search cut at `POPOVER_SEARCH_LIMIT` elements -/// fails as not found and says it is incomplete. +/// The first popover in `window`, nearest the window first, through the +/// bounded search that finds an open menu. None only when every element that +/// search reads was read: a search cut at its element limit fails as not found +/// and says it is incomplete. #[cfg(target_os = "macos")] fn popover_in_window( window: &AXElement, deadline: Deadline, ) -> Result, AdapterError> { - let mut level = vec![window.clone()]; - let mut searched = 0; - while !level.is_empty() { - let mut below = Vec::new(); - for element in level { - if role_or_subrole_matches(&element, "AXPopover", deadline)? { - return Ok(Some(element)); + super::app_menu::find_surface_descendant_with( + window.clone(), + "window".into(), + deadline, + |element, expand| { + if role_or_subrole_matches(element, "AXPopover", deadline)? { + return Ok((true, Vec::new())); } - searched += 1; - if searched >= POPOVER_SEARCH_LIMIT { - return Err(AdapterError::new( - ErrorCode::ElementNotFound, - format!("No popover among the first {searched} elements of the window; the rest was not searched"), - ) - .with_details(serde_json::json!({ - "kind": "popover_search_limit", - "complete": false, - }))); + if !expand { + return Ok((false, Vec::new())); } - below.extend(surface_read::elements(&element, "AXChildren", deadline)?); - } - level = below; + Ok(( + false, + surface_read::elements(element, "AXChildren", deadline)?, + )) + }, + ) + .map(|found| found.map(|(_, popover)| popover)) + .map_err(popover_search_error) +} + +fn popover_search_error(error: AdapterError) -> AdapterError { + let cut = error + .details + .as_ref() + .is_some_and(|details| details["kind"] == "surface_search_limit"); + if !cut { + return error; } - Ok(None) + AdapterError::new( + ErrorCode::ElementNotFound, + "No popover among the elements the search may read; the rest was not searched", + ) + .with_details(serde_json::json!({ + "kind": "popover_search_limit", + "complete": false, + })) } #[cfg(target_os = "macos")] diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.md index 07c349c939..9eda6ea58f 100644 --- a/skills/agent-desktop-macos/SKILL.md +++ b/skills/agent-desktop-macos/SKILL.md @@ -40,6 +40,10 @@ may report `unknown` when consent would require a prompt. - `menu` and `menubar` observations are application-owned and can omit `data.window`. An app without an ordinary window may still expose process-owned surfaces. Inspect `supported_surfaces` rather than assuming every surface exists. +- `agent-desktop press escape --app ` closes an open menu or popover with its + cancel action when no focused element takes Escape, and reads that it closed. A + popover can appear a moment after the click that opens it: read it with + `snapshot --app --surface popover`. - Headless menu-opening and dialog-opening actions can refuse before delivery. A label ending in an ellipsis predicts a dialog; it does not prove one exists. Stop on a headed-only refusal rather than changing mode. From beeb601d89c4ee12723fea0bacadcb5a198357cb Mon Sep 17 00:00:00 2001 From: Lahfir Date: Sun, 15 Nov 2026 23:45:53 -0800 Subject: [PATCH 03/19] fix: name a ref that carries its snapshot id twice and the zsh modifier trap A script that put the snapshot id in front of a printed ref_id sent `@sid:@sid:e4`; the error said "Invalid snapshot_id" with no suggestion. A zsh script that wrote `$SID:e4` sent a broken ref, because zsh reads `:e` as a modifier. Both now fail as an invalid ref_id with the one suggestion for ref syntax, which also says that ref_id already holds the snapshot id and that zsh needs `${SID}:e4`. --- apps/docs/content/docs/json-output.mdx | 2 +- apps/docs/content/docs/snapshots-and-refs.mdx | 2 +- crates/core/src/refs/ref_token.rs | 6 ++++-- crates/core/src/refs/ref_token_tests.rs | 17 +++++++++++++++++ 4 files changed, 23 insertions(+), 4 deletions(-) diff --git a/apps/docs/content/docs/json-output.mdx b/apps/docs/content/docs/json-output.mdx index 3f6a4216f3..8336440ca0 100644 --- a/apps/docs/content/docs/json-output.mdx +++ b/apps/docs/content/docs/json-output.mdx @@ -43,7 +43,7 @@ An error envelope has `error` and no `data`: "error": { "code": "INVALID_ARGS", "message": "Invalid ref_id '@e1': expected @:e", - "suggestion": "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted.", + "suggestion": "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted. Pass ref_id as printed: it already holds the snapshot id. In zsh write \"${SID}:e1\", because an unbraced $SID:e1 reads :e as a modifier.", "disposition": { "delivery": "not_delivered", "retry": "safe" } } } diff --git a/apps/docs/content/docs/snapshots-and-refs.mdx b/apps/docs/content/docs/snapshots-and-refs.mdx index 662ea6f1f1..e8ff08d9a8 100644 --- a/apps/docs/content/docs/snapshots-and-refs.mdx +++ b/apps/docs/content/docs/snapshots-and-refs.mdx @@ -112,7 +112,7 @@ Every command accepts only this qualified form. A bare `@e6` fails with `INVALID "error": { "code": "INVALID_ARGS", "message": "Invalid ref_id '@e1': expected @:e", - "suggestion": "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted.", + "suggestion": "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted. Pass ref_id as printed: it already holds the snapshot id. In zsh write \"${SID}:e1\", because an unbraced $SID:e1 reads :e as a modifier.", "disposition": { "delivery": "not_delivered", "retry": "safe" } } } diff --git a/crates/core/src/refs/ref_token.rs b/crates/core/src/refs/ref_token.rs index cdd7591435..98421634a0 100644 --- a/crates/core/src/refs/ref_token.rs +++ b/crates/core/src/refs/ref_token.rs @@ -23,7 +23,7 @@ pub(crate) fn resolve_ref_target(ref_id: &str) -> Result<(String, String), AppEr let Some((snapshot_id, element_number)) = without_at.rsplit_once(":e") else { return Err(invalid_ref(ref_id)); }; - validate_snapshot_id(snapshot_id)?; + validate_snapshot_id(snapshot_id).map_err(|_| invalid_ref(ref_id))?; let local_ref = format!("@e{element_number}"); if !is_local_ref(&local_ref) { return Err(invalid_ref(ref_id)); @@ -52,10 +52,12 @@ fn is_local_ref(ref_id: &str) -> bool { }) } +const REF_SUGGESTION: &str = "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted. Pass ref_id as printed: it already holds the snapshot id. In zsh write \"${SID}:e1\", because an unbraced $SID:e1 reads :e as a modifier."; + fn invalid_ref(ref_id: &str) -> AppError { AppError::invalid_input_with_suggestion( format!("Invalid ref_id '{ref_id}': expected @:e"), - "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted.", + REF_SUGGESTION, ) } diff --git a/crates/core/src/refs/ref_token_tests.rs b/crates/core/src/refs/ref_token_tests.rs index 98068617bc..321031cbc2 100644 --- a/crates/core/src/refs/ref_token_tests.rs +++ b/crates/core/src/refs/ref_token_tests.rs @@ -31,3 +31,20 @@ fn syntax_validation_accepts_only_the_qualified_form() { assert!(validate_ref_token("@sabc:e").is_err()); assert!(validate_ref_token("sabc:e1").is_err()); } + +#[test] +fn a_ref_prefixed_twice_is_named_as_a_ref_with_the_same_suggestion() { + let error = resolve_ref_target("@sabc:@sabc:e7").unwrap_err(); + + assert_eq!(error.code(), "INVALID_ARGS"); + assert!( + error + .to_string() + .contains("Invalid ref_id '@sabc:@sabc:e7'") + ); + assert!( + error + .suggestion() + .is_some_and(|s| s.contains("already holds")) + ); +} From 92e9d8724f6741842016f63e759bafbcec5c193b Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 00:05:57 -0800 Subject: [PATCH 04/19] fix(macos): list the floating and panel windows an app raises while they are on screen The window inventory kept only windows at the normal level (0). An accessory application often raises its own windows to a floating or panel level, so its window was missing from `list-windows` while it was on screen and readable, and an id from an earlier list no longer led to it. Raycast's panel (level 8) is such a window: `list-windows --app Raycast` returned [], while `snapshot --app Raycast` read 22 refs in it. The inventory now also lists a window between the normal level and the Dock level (20), but only while it is on screen: off screen such a window is a hidden helper. The Dock, the menu bar, status items, overlays and the desktop stay out. On this Mac the full list gained exactly the two windows that are on screen and readable; the Raycast panel resolves by its id and its snapshot is complete. `list-windows` takes the same time. --- crates/macos/src/system/window/cg_window.rs | 19 +++++++++++++++++-- .../src/system/window/cg_window_tests.rs | 13 +++++++++++++ skills/agent-desktop-macos/SKILL.md | 2 ++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/macos/src/system/window/cg_window.rs b/crates/macos/src/system/window/cg_window.rs index 97a3018306..777f5f9a6c 100644 --- a/crates/macos/src/system/window/cg_window.rs +++ b/crates/macos/src/system/window/cg_window.rs @@ -119,6 +119,20 @@ fn stabilize_records_until( } } +/// Whether the inventory lists a window. A normal-level window is listed on or +/// off screen. A floating, panel or utility window an application raises +/// itself (below the Dock level, 20), as accessory apps do, is listed while +/// on screen; off screen it is a hidden helper. System levels stay out. +fn lists_window(layer: i64, on_screen: bool) -> bool { + match layer { + 0 => true, + 1..DOCK_WINDOW_LEVEL => on_screen, + _ => false, + } +} + +const DOCK_WINDOW_LEVEL: i64 = 20; + pub(in crate::system) fn records_from_dictionaries( dictionaries: Vec, scope: WindowRecordScope<'_>, @@ -126,7 +140,8 @@ pub(in crate::system) fn records_from_dictionaries( let mut records = Vec::new(); for dictionary in dictionaries { let layer = required_int_field(&dictionary, "kCGWindowLayer")?; - if layer != 0 { + let visible = bool_field(&dictionary, "kCGWindowIsOnscreen")?; + if !lists_window(layer, visible) { continue; } let pid = i32::try_from(required_int_field(&dictionary, "kCGWindowOwnerPID")?) @@ -156,7 +171,7 @@ pub(in crate::system) fn records_from_dictionaries( title: string_field(&dictionary, "kCGWindowName").filter(|title| !title.is_empty()), window_number, bounds, - visible: bool_field(&dictionary, "kCGWindowIsOnscreen")?, + visible, process_instance: None, }); } diff --git a/crates/macos/src/system/window/cg_window_tests.rs b/crates/macos/src/system/window/cg_window_tests.rs index 84d5733c5f..b8881420c1 100644 --- a/crates/macos/src/system/window/cg_window_tests.rs +++ b/crates/macos/src/system/window/cg_window_tests.rs @@ -373,3 +373,16 @@ fn persistent_capture_failure_is_not_window_churn() { "core_graphics_windows" ); } + +#[test] +fn a_raised_app_window_is_listed_only_while_on_screen() { + assert!(lists_window(0, true)); + assert!(lists_window(0, false)); + for raised in [3, 5, 8, 19] { + assert!(lists_window(raised, true), "{raised}"); + assert!(!lists_window(raised, false), "{raised}"); + } + for system in [-2147483624, -1, 20, 24, 25, 101, 2147483630] { + assert!(!lists_window(system, true), "{system}"); + } +} diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.md index 9eda6ea58f..8eb62c8d42 100644 --- a/skills/agent-desktop-macos/SKILL.md +++ b/skills/agent-desktop-macos/SKILL.md @@ -37,6 +37,8 @@ may report `unknown` when consent would require a prompt. - Native AX element tokens identify individual controls, including twins. A stale token never falls back to a look-alike search. Elements without a token follow the uniqueness rule of the core skill. +- `list-windows` also lists a floating or panel window an app raises above the + normal level, as accessory apps do with settings and panels, while it is on screen. - `menu` and `menubar` observations are application-owned and can omit `data.window`. An app without an ordinary window may still expose process-owned surfaces. Inspect `supported_surfaces` rather than assuming every surface exists. From 0a80e01b453944f4a55d894e2ced62c8e88db962 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 00:14:37 -0800 Subject: [PATCH 05/19] feat(linux): close the open popup of a background window with Escape `press escape` sends the key only to the active window, so for a window in the background it was refused with STALE_REF, and a GTK3 combo box popup that the tool's own click had opened stayed open. An Escape without modifiers that the key route refuses for focus now looks in the target window for the deepest open popup owner: a combo box, or a button that has a popup, whose popup menu shows (GTK3 reports no EXPANDED state on the combo; its menu child gets SHOWING). Because the owner's action toggles the popup, the action is sent only after that read shows the popup open, and the result is `delivered_verified` only when a second read shows it gone. With no open owner, or on any error, the refusal is returned as it was. Every result the key route gave before is unchanged, and a tree row, an expander or a table cell is never an owner. Measured on real apps against the base of this branch: no surface open, the same results on GTK3 and Qt, active or in the back; a GTK3 combo popup in the back closes, read back raw, with the active window unchanged; an expanded GTK3 tree row stays expanded; a second Escape sends nothing. The refused path costs about 8 ms more. --- crates/linux/src/system/focus/escape_popup.rs | 220 ++++++++++++++++++ .../src/system/focus/escape_popup_tests.rs | 70 ++++++ crates/linux/src/system/focus/key_dispatch.rs | 39 +++- crates/linux/src/system/focus/mod.rs | 1 + skills/agent-desktop-linux/SKILL.md | 4 + 5 files changed, 330 insertions(+), 4 deletions(-) create mode 100644 crates/linux/src/system/focus/escape_popup.rs create mode 100644 crates/linux/src/system/focus/escape_popup_tests.rs diff --git a/crates/linux/src/system/focus/escape_popup.rs b/crates/linux/src/system/focus/escape_popup.rs new file mode 100644 index 0000000000..341547ddff --- /dev/null +++ b/crates/linux/src/system/focus/escape_popup.rs @@ -0,0 +1,220 @@ +//! Escape for an application that does not own the active window. +//! +//! The key route sends the key only to the active window, so a key for a +//! background application is refused. A popup that the application opened +//! stays open in the background on some toolkits, and the key cannot reach +//! it. The popup has an owner: a combo box, or a button that has a popup. The +//! owner's own action toggles the popup, so the action is sent only when a +//! read shows the popup open, and the result is verified by reading it gone. +//! +//! Three states, in this order: the key route is allowed and nothing here +//! runs; the key route is refused for focus and an open popup owner exists +//! in the target window, whose own action closes it; otherwise the refusal +//! stays as it was. + +use std::time::Duration; + +use agent_desktop_core::{ + Action, ActionResult, AdapterError, ChainRung, Deadline, DeliveryOutcome, KeyCombo, + StepMechanism, WindowInfo, +}; + +use crate::actions::action_call::resolve_verb; +use crate::actions::chain::run_semantic_chain; +use crate::system::window::window_id; +use crate::system::window::window_ops::windows_of_process; +use crate::system::{SharedBus, within}; +use crate::tree::capabilities::action_names::click_verbs; +use crate::tree::menu::observe_menu::{rooted, scan_walk_structure}; +use crate::tree::vocabulary::role_numbers::{ + COMBO_BOX, MENU, POPUP_MENU, PUSH_BUTTON, PUSH_BUTTON_MENU, TOGGLE_BUTTON, +}; +use crate::tree::vocabulary::state_bits::{EXPANDED, HAS_POPUP, SHOWING, StateBits}; +use crate::tree::{AtspiElement, ObservedRead, WalkedNode, call, get_live_actions}; + +const ACTION_INTERFACE: &str = "org.a11y.atspi.Action"; +const SCAN_NODES: usize = 600; +const OWNER_NODES: usize = 64; +const POPUP_CONTAINER_CHILDREN: usize = 16; +const CLOSE_SETTLE: Duration = Duration::from_millis(1000); +const CLOSE_STEP: Duration = Duration::from_millis(50); +const FOCUS_CHECKS: [&str; 2] = ["window_active", "exact_window_focus"]; +const SUGGESTION: &str = "Refresh the snapshot and check whether the popup is still open."; +const CLOSE_LABEL: &str = "Action.DoAction"; + +pub(super) fn is_plain_escape(combo: &KeyCombo) -> bool { + combo.modifiers.is_empty() && combo.key.eq_ignore_ascii_case("escape") +} + +pub(super) fn is_focus_refusal(error: &AdapterError) -> bool { + error + .details + .as_ref() + .and_then(|details| details.get("check")) + .and_then(|check| check.as_str()) + .is_some_and(|check| FOCUS_CHECKS.contains(&check)) +} + +fn bits(node: &WalkedNode) -> Option> { + node.payload + .node + .traits + .states + .present() + .map(|words| StateBits::new(words)) +} + +fn role(node: &WalkedNode) -> Option { + node.payload.node.traits.role.present().copied() +} + +fn showing_popup(node: &WalkedNode) -> bool { + matches!(role(node), Some(MENU | POPUP_MENU)) + && bits(node).is_some_and(|bits| bits.has(SHOWING)) +} + +/// Whether the node owns a popup and the popup is open now. The owner roles +/// are the ones whose expansion is a popup: a combo box, and a button that +/// has the popup state. An owner is open when it reports `EXPANDED` or when a +/// popup menu below it shows. A tree row, an expander or a table cell is +/// never an owner: Escape does not collapse a tree. +pub(super) fn is_open_owner(node: &WalkedNode) -> bool { + let Some(bits) = bits(node) else { + return false; + }; + let owner = match role(node) { + Some(COMBO_BOX) => true, + Some(PUSH_BUTTON | PUSH_BUTTON_MENU | TOGGLE_BUTTON) => bits.has(HAS_POPUP), + _ => false, + }; + owner && (bits.has(EXPANDED) || node.children.iter().any(showing_popup)) +} + +fn deepest_open_owner<'a>( + node: &'a WalkedNode, + depth: usize, + best: &mut Option<(usize, &'a WalkedNode)>, +) { + if is_open_owner(node) && best.is_none_or(|(deepest, _)| depth > deepest) { + *best = Some((depth, node)); + } + for child in &node.children { + deepest_open_owner(child, depth + 1, best); + } +} + +fn frames_of( + bus: &SharedBus, + pid: u32, + window: Option<&WindowInfo>, + deadline: Deadline, +) -> Result, AdapterError> { + let windows = match window { + Some(window) => vec![window.clone()], + None => windows_of_process(bus, pid, deadline)?.0, + }; + let mut frames = Vec::new(); + for window in windows { + let (name, path) = window_id::decode(&window.id)?; + frames.push(rooted(&AtspiElement::new(name, path, pid))); + } + Ok(frames) +} + +fn still_open(bus: &SharedBus, owner: &AtspiElement, deadline: Deadline) -> Option { + let walk = scan_walk_structure( + bus, + &rooted(owner), + OWNER_NODES, + Some(POPUP_CONTAINER_CHILDREN), + deadline, + ) + .ok()?; + Some(is_open_owner(&walk)) +} + +fn press_owner( + bus: &SharedBus, + owner: &AtspiElement, + role: Option, + deadline: Deadline, +) -> Result { + let handle = owner.clone().into_native_handle(); + let names = get_live_actions(bus, &handle, deadline)?.unwrap_or_default(); + let Some(index) = resolve_verb(&names, click_verbs(role)) else { + return Ok(false); + }; + let connection = bus.get(deadline)?; + within(deadline, async { + call( + connection.inner(), + owner, + ACTION_INTERFACE, + "DoAction", + &(index,), + ) + .await + .map(|_| true) + .map_err(|error| crate::system::classify(&error)) + }) +} + +/// The refused Escape of a background application, answered by closing the +/// open popup its target window shows. `None` leaves the refusal as it was. +pub(super) fn close_open_popup( + bus: &SharedBus, + pid: u32, + window: Option<&WindowInfo>, + combo: &KeyCombo, + deadline: Deadline, +) -> Result, AdapterError> { + let mut best: Option<(usize, AtspiElement, Option)> = None; + for frame in frames_of(bus, pid, window, deadline)? { + let walk = scan_walk_structure( + bus, + &frame, + SCAN_NODES, + Some(POPUP_CONTAINER_CHILDREN), + deadline, + )?; + let mut found = None; + deepest_open_owner(&walk, 0, &mut found); + if let Some((depth, node)) = found + && best.as_ref().is_none_or(|(deepest, _, _)| depth > *deepest) + { + best = Some((depth, node.payload.node.element.clone(), role(node))); + } + } + let Some((_, owner, owner_role)) = best else { + return Ok(None); + }; + let run = || { + if !press_owner(bus, &owner, owner_role, deadline)? { + return Ok(DeliveryOutcome::NotDelivered); + } + let closed = deadline.poll_until( + CLOSE_SETTLE, + CLOSE_STEP, + || still_open(bus, &owner, deadline).map(|open| !open), + |closed| *closed == Some(true), + ); + Ok(DeliveryOutcome::observed(closed)) + }; + let mut rungs = [ChainRung { + label: CLOSE_LABEL, + effects: &[], + mechanism: StepMechanism::SemanticApi, + run: Box::new(run), + }]; + run_semantic_chain( + &Action::PressKey(combo.clone()), + &mut rungs, + deadline, + SUGGESTION, + ) + .map(Some) +} + +#[cfg(test)] +#[path = "escape_popup_tests.rs"] +mod tests; diff --git a/crates/linux/src/system/focus/escape_popup_tests.rs b/crates/linux/src/system/focus/escape_popup_tests.rs new file mode 100644 index 0000000000..231acd4f5d --- /dev/null +++ b/crates/linux/src/system/focus/escape_popup_tests.rs @@ -0,0 +1,70 @@ +use agent_desktop_core::{AdapterError, ErrorCode, KeyCombo, Modifier}; +use serde_json::json; + +use super::{is_focus_refusal, is_open_owner, is_plain_escape}; +use crate::tree::test_support::helpers::{read_of, words}; +use crate::tree::vocabulary::role_numbers::{COMBO_BOX, MENU, PUSH_BUTTON, TABLE_CELL}; +use crate::tree::vocabulary::state_bits::{EXPANDED, HAS_POPUP, SHOWING}; +use crate::tree::{Field, ObservedRead, WalkedNode}; + +fn node( + role: u32, + states: &[u32], + children: Vec>, +) -> WalkedNode { + let mut read = read_of(role, "n", &[]); + read.node.traits.states = Field::Present(words(states)); + WalkedNode { + payload: read, + children, + truncated: false, + child_count: None, + source_index: 0, + in_web_document: false, + } +} + +fn combo(key: &str, modifiers: Vec) -> KeyCombo { + KeyCombo { + key: key.to_owned(), + modifiers, + } +} + +#[test] +fn only_a_plain_escape_is_an_escape() { + assert!(is_plain_escape(&combo("escape", Vec::new()))); + assert!(is_plain_escape(&combo("Escape", Vec::new()))); + assert!(!is_plain_escape(&combo("escape", vec![Modifier::Ctrl]))); + assert!(!is_plain_escape(&combo("return", Vec::new()))); +} + +#[test] +fn only_a_focus_refusal_is_answered_by_closing_a_popup() { + let refusal = |check: &str| { + AdapterError::new(ErrorCode::ActionFailed, "refused") + .with_details(json!({ "check": check })) + }; + assert!(is_focus_refusal(&refusal("window_active"))); + assert!(is_focus_refusal(&refusal("exact_window_focus"))); + assert!(!is_focus_refusal(&refusal("process_state"))); + assert!(!is_focus_refusal(&AdapterError::new( + ErrorCode::ActionFailed, + "no details" + ))); +} + +#[test] +fn only_a_combo_box_or_a_popup_button_with_an_open_popup_is_an_open_owner() { + let shown = || vec![node(MENU, &[SHOWING], Vec::new())]; + let hidden = || vec![node(MENU, &[], Vec::new())]; + assert!(is_open_owner(&node(COMBO_BOX, &[], shown()))); + assert!(!is_open_owner(&node(COMBO_BOX, &[], hidden()))); + assert!(is_open_owner(&node( + PUSH_BUTTON, + &[HAS_POPUP, EXPANDED], + Vec::new() + ))); + assert!(!is_open_owner(&node(PUSH_BUTTON, &[EXPANDED], Vec::new()))); + assert!(!is_open_owner(&node(TABLE_CELL, &[EXPANDED], shown()))); +} diff --git a/crates/linux/src/system/focus/key_dispatch.rs b/crates/linux/src/system/focus/key_dispatch.rs index 015c3fa449..13e730ded6 100644 --- a/crates/linux/src/system/focus/key_dispatch.rs +++ b/crates/linux/src/system/focus/key_dispatch.rs @@ -4,6 +4,7 @@ use agent_desktop_core::{ }; use serde_json::json; +use super::escape_popup::{close_open_popup, is_focus_refusal, is_plain_escape}; use crate::input::backend::Backend; use crate::input::physical::target_keyboard::press_for_process; use crate::input::physical::target_world::{LiveWorld, PhysicalWorld}; @@ -205,6 +206,27 @@ fn press_in( after_delivery(keys, process, result) } +/// An Escape that the key route refused for focus closes the open popup of +/// the target window through its owner; every other result is the key +/// route's own. +fn closing_popup_when_refused( + result: Result, + bus: &SharedBus, + target: (u32, Option<&WindowInfo>), + combo: &KeyCombo, + deadline: Deadline, +) -> Result { + match result { + Err(error) if is_plain_escape(combo) && is_focus_refusal(&error) => { + match close_open_popup(bus, target.0, target.1, combo, deadline) { + Ok(Some(closed)) => Ok(closed), + Ok(None) | Err(_) => Err(error), + } + } + other => other, + } +} + pub(crate) fn press_key_for_app( bus: &SharedBus, process: ProcessIdentity, @@ -214,7 +236,8 @@ pub(crate) fn press_key_for_app( ) -> Result { crate::system::display::display_server::require(lease.deadline()) .map_err(|error| error.with_disposition(DeliverySemantics::not_delivered()))?; - press_in(Press { + let pid = process.pid.get(); + let result = press_in(Press { physical: &LiveWorld { bus, lease }, keys: &LiveKeys { bus }, process: &process, @@ -222,7 +245,8 @@ pub(crate) fn press_key_for_app( combo, policy, deadline: lease.deadline(), - }) + }); + closing_popup_when_refused(result, bus, (pid, None), combo, lease.deadline()) } pub(crate) fn press_key_for_window( @@ -239,7 +263,7 @@ pub(crate) fn press_key_for_window( .as_deref() .filter(|instance| !instance.is_empty()) .ok_or_else(|| window_not_active(window))?; - press_in(Press { + let result = press_in(Press { physical: &LiveWorld { bus, lease }, keys: &LiveKeys { bus }, process: &ProcessIdentity::new(window.pid, instance), @@ -247,7 +271,14 @@ pub(crate) fn press_key_for_window( combo, policy, deadline: lease.deadline(), - }) + }); + closing_popup_when_refused( + result, + bus, + (window.pid.get(), Some(window)), + combo, + lease.deadline(), + ) } #[cfg(test)] diff --git a/crates/linux/src/system/focus/mod.rs b/crates/linux/src/system/focus/mod.rs index 18e6431d4f..3af5891e86 100644 --- a/crates/linux/src/system/focus/mod.rs +++ b/crates/linux/src/system/focus/mod.rs @@ -29,6 +29,7 @@ pub(crate) fn focus_is_indeterminate(candidates: &[usize], decided: Option --window-id ` on a background window that shows an + open combo box or popup button popup closes it through the owner's own action, and + reports `delivered_verified` after a read shows it gone; otherwise it is refused as + before. It never collapses a tree row. - Sandboxes are not available on Linux yet. To run agent-desktop in a container you manage yourself, see `agent-browser.dev/desktop/guides/docker-container`. ## Troubleshooting From e61f29f83bfbf3b0d89ede46981f8baa76b8db83 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 00:32:30 -0800 Subject: [PATCH 06/19] feat(windows): close the open popup of a window that is not in front with Escape `press escape` on Windows needs the target to hold the keyboard, so for a window in the background it was refused, and an open drop-down of that window stayed open: the column menu of an Explorer folder window, for one. An Escape without modifiers that the key route refuses for focus now looks in the target (the named window, or the process's top-level windows for `--app`) for the innermost expanded popup owner: a menu item, a combo box or a split button. It collapses it with `ExpandCollapsePattern.Collapse` and reports `delivered_verified` once the state reads collapsed. With no such owner the refusal is returned as it was. A tree item, a group or a data item is never an owner, and every result the key route gave before is unchanged. To add that route after the refusal without copying it, the core default for a key to a named window is now one public function, `press_key_in_focused_window`, which the default and the Windows override both call. Its behaviour is unchanged. Measured on real apps against the base of this branch: with no popup open, Notepad and Explorer, in front or in the back, give the same results; an open Explorer column menu in a folder window in the back closes in 0.29 s, read back raw, with the foreground unchanged; an expanded tree item in the navigation pane stays expanded; `press escape` with no popup takes the same time (51 against 52 ms). --- crates/core/src/adapter/focused_window_key.rs | 57 +++++++ crates/core/src/adapter/mod.rs | 1 + crates/core/src/adapter/system.rs | 45 +----- crates/core/src/lib.rs | 1 + crates/windows/src/system/adapter.rs | 23 ++- crates/windows/src/system/escape_popup.rs | 107 +++++++++++++ .../windows/src/system/escape_popup_tests.rs | 45 ++++++ crates/windows/src/system/escape_popup_uia.rs | 144 ++++++++++++++++++ crates/windows/src/system/mod.rs | 1 + skills/agent-desktop-windows/SKILL.md | 4 + 10 files changed, 379 insertions(+), 49 deletions(-) create mode 100644 crates/core/src/adapter/focused_window_key.rs create mode 100644 crates/windows/src/system/escape_popup.rs create mode 100644 crates/windows/src/system/escape_popup_tests.rs create mode 100644 crates/windows/src/system/escape_popup_uia.rs diff --git a/crates/core/src/adapter/focused_window_key.rs b/crates/core/src/adapter/focused_window_key.rs new file mode 100644 index 0000000000..019c4b5eb2 --- /dev/null +++ b/crates/core/src/adapter/focused_window_key.rs @@ -0,0 +1,57 @@ +//! Key delivery to a named window, gated on that window holding the focus. + +use crate::{ + ActionResult, AdapterError, InteractionLease, InteractionPolicy, KeyCombo, ProcessIdentity, + WindowInfo, adapter::SystemOps, +}; + +/// Sends `combo` to the process of `window` only when `window` is the exact +/// focused window, and refuses before anything is sent otherwise. This is the +/// default of `SystemOps::press_key_for_window`; an adapter that overrides +/// that method to add a route after the refusal calls it first. +pub fn press_key_in_focused_window( + adapter: &A, + window: &WindowInfo, + combo: &KeyCombo, + policy: InteractionPolicy, + lease: &InteractionLease, +) -> Result { + let refusal = || { + AdapterError::stale_ref_because( + "The named window's exact focus could not be confirmed, so no key was sent", + ) + .with_suggestion(if policy.is_headed() { + "Ensure the named window remains active before retrying; a sibling window or another application's menu can hold the keyboard".to_owned() + } else { + format!("{} Or name the already active window.", crate::headed_mode_suggestion("brings the named window to the foreground before sending keys")) + }) + .with_details(serde_json::json!({ + "check": "window_active", + "cause": "exact_window_focus_unconfirmed", + "physical_delivery_started": false, + "window_id": window.id, + })) + .with_disposition(crate::DeliverySemantics::not_delivered()) + }; + let instance = window + .process_instance + .as_deref() + .filter(|instance| !instance.is_empty()) + .ok_or_else(refusal)?; + let focused = adapter + .focused_window(lease.deadline()) + .map_err(AdapterError::unsent)?; + if !focused.is_some_and(|focused| { + focused.id == window.id + && focused.pid == window.pid + && focused.process_instance.as_deref() == Some(instance) + }) { + return Err(refusal()); + } + adapter.press_key_for_app( + ProcessIdentity::new(window.pid, instance), + combo, + policy, + lease, + ) +} diff --git a/crates/core/src/adapter/mod.rs b/crates/core/src/adapter/mod.rs index 4108ff43d8..7424b0d68a 100644 --- a/crates/core/src/adapter/mod.rs +++ b/crates/core/src/adapter/mod.rs @@ -1,5 +1,6 @@ pub(crate) mod actions; pub(crate) mod adapter_session; +pub(crate) mod focused_window_key; pub mod hit_test; pub(crate) mod input; pub mod live_element; diff --git a/crates/core/src/adapter/system.rs b/crates/core/src/adapter/system.rs index 8e5680fb62..9539498dc8 100644 --- a/crates/core/src/adapter/system.rs +++ b/crates/core/src/adapter/system.rs @@ -269,9 +269,9 @@ pub trait SystemOps: Send + Sync { Err(AdapterError::not_supported("press_key_for_app")) } - /// Checks the exact focused window before process-scoped key delivery. - /// Adapters can override this to retain the window identity through their - /// native delivery gates. + /// Checks the exact focused window before process-scoped key delivery + /// (`press_key_in_focused_window`). Adapters can override this to retain + /// the window identity through their native delivery gates. fn press_key_for_window( &self, window: &WindowInfo, @@ -279,44 +279,7 @@ pub trait SystemOps: Send + Sync { policy: InteractionPolicy, lease: &InteractionLease, ) -> Result { - let refusal = || { - AdapterError::stale_ref_because( - "The named window's exact focus could not be confirmed, so no key was sent", - ) - .with_suggestion(if policy.is_headed() { - "Ensure the named window remains active before retrying; a sibling window or another application's menu can hold the keyboard".to_owned() - } else { - format!("{} Or name the already active window.", crate::headed_mode_suggestion("brings the named window to the foreground before sending keys")) - }) - .with_details(serde_json::json!({ - "check": "window_active", - "cause": "exact_window_focus_unconfirmed", - "physical_delivery_started": false, - "window_id": window.id, - })) - .with_disposition(crate::DeliverySemantics::not_delivered()) - }; - let instance = window - .process_instance - .as_deref() - .filter(|instance| !instance.is_empty()) - .ok_or_else(refusal)?; - let focused = self - .focused_window(lease.deadline()) - .map_err(AdapterError::unsent)?; - if !focused.is_some_and(|focused| { - focused.id == window.id - && focused.pid == window.pid - && focused.process_instance.as_deref() == Some(instance) - }) { - return Err(refusal()); - } - self.press_key_for_app( - ProcessIdentity::new(window.pid, instance), - combo, - policy, - lease, - ) + super::focused_window_key::press_key_in_focused_window(self, window, combo, policy, lease) } fn wait_for_menu( diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 147da88200..a8bde82e8c 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -41,6 +41,7 @@ pub use actions::step_mechanism::StepMechanism; pub use adapter::PlatformAdapter; pub use adapter::actions::ActionOps; pub use adapter::adapter_session::AdapterSession; +pub use adapter::focused_window_key::press_key_in_focused_window; pub use adapter::hit_test::HitTestResult; pub use adapter::input::InputOps; pub use adapter::live_element::LiveElement; diff --git a/crates/windows/src/system/adapter.rs b/crates/windows/src/system/adapter.rs index 396cf4fc3e..9d2ed221c9 100644 --- a/crates/windows/src/system/adapter.rs +++ b/crates/windows/src/system/adapter.rs @@ -10,6 +10,7 @@ use agent_desktop_core::{ use crate::adapter::WindowsAdapter; use crate::system::close_outcome::CloseOutcome; +use crate::system::escape_popup; #[cfg(target_os = "windows")] #[path = "tcp_listener.rs"] @@ -145,10 +146,8 @@ impl SystemOps for WindowsAdapter { crate::system::shell::shell_surface_open::open_surface(surface, policy, lease.deadline()) } - /// The focused window is the focused-only filter's first result, composed - /// from `list_windows` rather than a second native path (mirroring - /// `focused_window` in `crates/macos/src/system/adapter.rs`). Whatever HWND-shape a - /// host presents, it maps to the same identity `list_windows` reports. + /// The focused-only filter's first result over `list_windows`, as on macOS, + /// so any HWND shape maps to the identity `list_windows` reports. fn focused_window(&self, deadline: Deadline) -> Result, AdapterError> { let filter = WindowFilter { focused_only: true, @@ -270,9 +269,7 @@ impl SystemOps for WindowsAdapter { crate::system::capture::screenshot::capture_window(window, deadline) } - /// Verify-only composition over the keyboard primitive. Core's headed - /// path already activated; this never raises (A9-3: SendInput has no - /// per-pid targeting). + /// Key delivery, then `escape_popup` for a refused Escape (A9-3). fn press_key_for_app( &self, process: ProcessIdentity, @@ -280,7 +277,17 @@ impl SystemOps for WindowsAdapter { policy: InteractionPolicy, lease: &InteractionLease, ) -> Result { - crate::system::key_dispatch::press_for_app_impl(process, combo, policy, lease.deadline()) + escape_popup::press_for_app(process, combo, policy, lease.deadline()) + } + + fn press_key_for_window( + &self, + window: &WindowInfo, + combo: &KeyCombo, + policy: InteractionPolicy, + lease: &InteractionLease, + ) -> Result { + escape_popup::press_for_window(self, window, combo, policy, lease) } /// The core default blocks nothing; Windows ships its own dangerous-combo diff --git a/crates/windows/src/system/escape_popup.rs b/crates/windows/src/system/escape_popup.rs new file mode 100644 index 0000000000..d5616eb806 --- /dev/null +++ b/crates/windows/src/system/escape_popup.rs @@ -0,0 +1,107 @@ +//! Escape for an open popup when the key route refused for focus. +//! +//! The key route needs the target to hold the keyboard. A popup a person +//! opened (a menu, a drop-down, a split-button list) can sit in a window that +//! is not the foreground window, and the key is then refused. The popup still +//! has a semantic close: `ExpandCollapsePattern.Collapse` on its owner. The +//! states, in this order: the key route delivers, unchanged; it refuses for +//! focus and the target shows an open popup, whose owner is collapsed and read +//! back; otherwise the refusal stays as it was. + +use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode, KeyCombo}; + +/// Key delivery to `process` (A9-3: SendInput has no per-pid targeting; +/// core's headed path already activated), then the popup close. +pub(crate) fn press_for_app( + process: agent_desktop_core::ProcessIdentity, + combo: &KeyCombo, + policy: agent_desktop_core::InteractionPolicy, + deadline: agent_desktop_core::Deadline, +) -> Result { + let result = + crate::system::key_dispatch::press_for_app_impl(process.clone(), combo, policy, deadline); + after_key_route( + result, + PopupScope::Process(&process), + combo, + policy, + deadline, + ) +} + +/// Core's focus-gated delivery to a named window, then the popup close. +pub(crate) fn press_for_window( + adapter: &A, + window: &agent_desktop_core::WindowInfo, + combo: &KeyCombo, + policy: agent_desktop_core::InteractionPolicy, + lease: &agent_desktop_core::InteractionLease, +) -> Result { + let result = + agent_desktop_core::press_key_in_focused_window(adapter, window, combo, policy, lease); + after_key_route( + result, + PopupScope::Window(window), + combo, + policy, + lease.deadline(), + ) +} + +/// Where a refused Escape looks for an open popup. +pub(crate) enum PopupScope<'a> { + Window(&'a agent_desktop_core::WindowInfo), + Process(&'a agent_desktop_core::ProcessIdentity), +} + +pub(crate) fn is_plain_escape(combo: &KeyCombo) -> bool { + combo.modifiers.is_empty() + && (combo.key.eq_ignore_ascii_case("escape") || combo.key.eq_ignore_ascii_case("esc")) +} + +/// The refusals after which the target's popup gets its close: core's refusal +/// of a window that is not the exact focus holder, and this adapter's refusal +/// of a process that does not hold the keyboard. Each scope answers only its +/// own refusal, so one refusal is searched once. +pub(crate) fn refused_for_focus(window_scope: bool, error: &AdapterError) -> bool { + let details = error.details.as_ref(); + let unsent = error.disposition == DeliverySemantics::not_delivered() + && details.and_then(|details| details["physical_delivery_started"].as_bool()) + == Some(false); + let check = details.and_then(|details| details["check"].as_str()); + unsent + && if window_scope { + check == Some("window_active") + } else { + error.code == ErrorCode::ActionFailed && check.is_none() + } +} + +/// The control types whose expansion is a popup: menu item (50011), combo box +/// (50003) and split button (50031). A tree item or a group is never one. +fn opens_a_popup(control_type: i32) -> bool { + [50011, 50003, 50031].contains(&control_type) +} + +#[cfg(target_os = "windows")] +#[path = "escape_popup_uia.rs"] +mod uia; + +#[cfg(target_os = "windows")] +pub(crate) use uia::after_key_route; + +/// Off Windows no popup can be open, so the key route's result stands. +#[cfg(not(target_os = "windows"))] +pub(crate) fn after_key_route( + result: Result, + _scope: PopupScope<'_>, + _combo: &KeyCombo, + _policy: agent_desktop_core::InteractionPolicy, + _deadline: agent_desktop_core::Deadline, +) -> Result { + result +} + +#[cfg(test)] +#[path = "escape_popup_tests.rs"] +mod tests; diff --git a/crates/windows/src/system/escape_popup_tests.rs b/crates/windows/src/system/escape_popup_tests.rs new file mode 100644 index 0000000000..c474e54a5e --- /dev/null +++ b/crates/windows/src/system/escape_popup_tests.rs @@ -0,0 +1,45 @@ +use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode, KeyCombo, Modifier}; + +use super::{is_plain_escape, opens_a_popup, refused_for_focus}; + +fn key(name: &str, modifiers: Vec) -> KeyCombo { + KeyCombo { + key: name.to_owned(), + modifiers, + } +} + +#[test] +fn only_a_plain_escape_may_close_a_popup() { + assert!(is_plain_escape(&key("escape", vec![]))); + assert!(is_plain_escape(&key("Esc", vec![]))); + assert!(!is_plain_escape(&key("escape", vec![Modifier::Shift]))); + assert!(!is_plain_escape(&key("return", vec![]))); +} + +#[test] +fn each_scope_answers_only_its_own_focus_refusal() { + let window = AdapterError::stale_ref_because("not focused") + .with_details( + serde_json::json!({ "check": "window_active", "physical_delivery_started": false }), + ) + .with_disposition(DeliverySemantics::not_delivered()); + let process = AdapterError::new(ErrorCode::ActionFailed, "not foreground") + .with_details(serde_json::json!({ "pid": 4, "physical_delivery_started": false })) + .with_disposition(DeliverySemantics::not_delivered()); + let sent = AdapterError::new(ErrorCode::ActionFailed, "sent") + .with_details(serde_json::json!({ "physical_delivery_started": true })) + .with_disposition(DeliverySemantics::delivered_unverified()); + + assert!(refused_for_focus(true, &window)); + assert!(!refused_for_focus(false, &window)); + assert!(refused_for_focus(false, &process)); + assert!(!refused_for_focus(true, &process)); + assert!(!refused_for_focus(false, &sent)); +} + +#[test] +fn a_tree_item_or_a_group_is_never_a_popup_owner() { + assert!(opens_a_popup(50011) && opens_a_popup(50003) && opens_a_popup(50031)); + assert!(!opens_a_popup(50024) && !opens_a_popup(50026) && !opens_a_popup(50029)); +} diff --git a/crates/windows/src/system/escape_popup_uia.rs b/crates/windows/src/system/escape_popup_uia.rs new file mode 100644 index 0000000000..30adcef736 --- /dev/null +++ b/crates/windows/src/system/escape_popup_uia.rs @@ -0,0 +1,144 @@ +//! The UI Automation half of `escape_popup`: the popup search, the collapse and the two entry points. + +use super::{PopupScope, is_plain_escape, opens_a_popup, refused_for_focus}; +use agent_desktop_core::{ + Action, ActionResult, AdapterError, Deadline, DeliveryOutcome, InteractionPolicy, KeyCombo, + ProcessIdentity, WindowInfo, +}; +use std::time::Duration; +use uiautomation::patterns::UIExpandCollapsePattern; +use uiautomation::types::{TreeScope, UIProperty}; +use uiautomation::variants::Variant; + +use crate::actions::chain::{offered, poll_until, rung}; +use crate::actions::mutation::{classify_success, classify_write}; +use crate::tree::element::UIAElement; +use crate::tree::properties::property_ids::TreeProperty; +use crate::tree::properties::read_one; + +const COLLAPSE_LABEL: &str = "ExpandCollapsePattern.Collapse"; +const COLLAPSE_SUGGESTION: &str = "Close the popup with the key while its window is in front."; +const VERIFY_TIMEOUT: Duration = Duration::from_millis(600); +const EXPANDED: i32 = 1; +const COLLAPSED: i32 = 0; + +/// The deepest expanded popup owner among the elements below `roots`: a +/// document-order search, so the last match is the innermost level. +fn deepest_popup_owner(roots: &[UIAElement]) -> Option { + let client = crate::tree::automation::automation_client().ok()?; + let expanded = client + .create_property_condition( + UIProperty::ExpandCollapseExpandCollapseState, + Variant::from(EXPANDED), + None, + ) + .ok()?; + let mut owner = None; + for root in roots { + let Ok(found) = root.0.find_all(TreeScope::Descendants, &expanded) else { + continue; + }; + for element in found { + let element = UIAElement::from(element); + if read_one(&element, TreeProperty::ControlType) + .number() + .is_some_and(opens_a_popup) + { + owner = Some(element); + } + } + } + owner +} + +fn window_roots(window: &WindowInfo, deadline: Deadline) -> Vec { + crate::tree::surfaces::surface_root( + agent_desktop_core::ObservationRoot::Window(window), + agent_desktop_core::SnapshotSurface::Window, + deadline, + ) + .into_iter() + .collect() +} + +fn process_roots(process: &ProcessIdentity) -> Vec { + let Ok(client) = crate::tree::automation::automation_client() else { + return Vec::new(); + }; + let Ok(root) = client.get_root_element() else { + return Vec::new(); + }; + let Ok(condition) = client.create_property_condition( + UIProperty::ProcessId, + Variant::from(i32::try_from(u32::from(process.pid)).unwrap_or(0)), + None, + ) else { + return Vec::new(); + }; + root.find_all(TreeScope::Children, &condition) + .map(|found| found.into_iter().map(UIAElement::from).collect()) + .unwrap_or_default() +} + +fn collapse(owner: &UIAElement) -> Result { + match owner.0.get_pattern::() { + Ok(pattern) => match pattern.collapse() { + Ok(()) => classify_success(), + Err(error) => classify_write("Collapse", COLLAPSE_LABEL, &error), + }, + Err(error) => classify_write("get_pattern", COLLAPSE_LABEL, &error), + } +} + +fn close_popup( + owner: &UIAElement, + combo: &KeyCombo, + policy: InteractionPolicy, + deadline: Deadline, +) -> Result { + let mut run = || { + if !collapse(owner)? { + return Ok(DeliveryOutcome::NotDelivered); + } + let closed = poll_until(deadline, VERIFY_TIMEOUT, || { + read_one(owner, TreeProperty::ExpandCollapseState).number() == Some(COLLAPSED) + }); + Ok(DeliveryOutcome::from_delivery(true, closed)) + }; + let steps = agent_desktop_core::execute_chain( + &mut offered([rung(COLLAPSE_LABEL, true, false, &mut run)]), + policy, + deadline, + COLLAPSE_SUGGESTION, + )?; + Ok(ActionResult::from_execution( + &Action::PressKey(combo.clone()), + steps, + )) +} + +/// The key route's result, or, when it refused a plain Escape for focus and +/// the scope shows an open popup, the collapse of that popup's owner. +pub(crate) fn after_key_route( + result: Result, + scope: PopupScope<'_>, + combo: &KeyCombo, + policy: InteractionPolicy, + deadline: Deadline, +) -> Result { + let Err(refusal) = result else { + return result; + }; + let window_scope = matches!(scope, PopupScope::Window(_)); + if !is_plain_escape(combo) || !refused_for_focus(window_scope, &refusal) { + return Err(refusal); + } + let roots = match scope { + PopupScope::Window(window) => window_roots(window, deadline), + PopupScope::Process(process) => process_roots(process), + }; + match deepest_popup_owner(&roots) { + Some(owner) => close_popup(&owner, combo, policy, deadline), + None => Err(refusal), + } +} diff --git a/crates/windows/src/system/mod.rs b/crates/windows/src/system/mod.rs index c5e2239cdf..987ab69d7a 100644 --- a/crates/windows/src/system/mod.rs +++ b/crates/windows/src/system/mod.rs @@ -7,6 +7,7 @@ pub(crate) mod close_dispatch; pub(crate) mod close_outcome; pub(crate) mod cursor_overlay; pub(crate) mod display; +pub(crate) mod escape_popup; #[cfg(target_os = "windows")] pub(crate) mod interaction_lease; pub(crate) mod key_dispatch; diff --git a/skills/agent-desktop-windows/SKILL.md b/skills/agent-desktop-windows/SKILL.md index 6e86aed6c0..8d5448af43 100644 --- a/skills/agent-desktop-windows/SKILL.md +++ b/skills/agent-desktop-windows/SKILL.md @@ -42,6 +42,10 @@ Use `$env:NAME = 'value'` for environment variables. - A ref must be unique in its window, or inside its nearest unique ancestor (a cell inside its row), at capture and resolution. A root drill cannot make identical twins unique. Choose a distinct control. +- `press escape` with `--app` or `--window-id` on a window that is not in front is + refused as before, unless that window shows an open menu, combo box or split + button: then the innermost one is collapsed (`ExpandCollapsePattern.Collapse`), + `delivered_verified` once read back closed. A tree item is never collapsed. - A grid reports `row_count` and `column_count`. A row is a record: find it by its own name, and its cells through it. `agent-desktop click` on a grid cell that lists `Click` selects the row that holds it. A cell carries no grid position. From 14f6958343e578588bb739206b4b1d9197839e90 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:22:50 -0800 Subject: [PATCH 07/19] fix(linux): read the popup owner's reply when Escape closes a popup press escape on a background window with an open popup runs the owner's own action. That call went through the raw bus call, so its reply body was dropped. A DoAction that answered false counted as delivered, and a call that timed out after it was sent lost its uncertain delivery on the way back. The owner's action now goes through the shared write path, which reads the flag the reply carries and gives a timeout after dispatch its uncertain disposition. A reply of false is not delivered, so the popup is not read back and the Escape fails with ACTION_FAILED. The refused Escape also stopped replacing the popup attempt's own error with the focus refusal. Only a target window with no open popup owner keeps the refusal; every other outcome, the popup attempt's failure included, is reported as it stands. The Linux skill now says what a rejected owner action and an unanswered one report. --- crates/linux/src/system/focus/escape_popup.rs | 89 ++++++++++++------- .../src/system/focus/escape_popup_tests.rs | 52 ++++++++++- crates/linux/src/system/focus/key_dispatch.rs | 8 +- skills/agent-desktop-linux/SKILL.md | 6 +- 4 files changed, 112 insertions(+), 43 deletions(-) diff --git a/crates/linux/src/system/focus/escape_popup.rs b/crates/linux/src/system/focus/escape_popup.rs index 341547ddff..f6eb4ced58 100644 --- a/crates/linux/src/system/focus/escape_popup.rs +++ b/crates/linux/src/system/focus/escape_popup.rs @@ -10,7 +10,9 @@ //! Three states, in this order: the key route is allowed and nothing here //! runs; the key route is refused for focus and an open popup owner exists //! in the target window, whose own action closes it; otherwise the refusal -//! stays as it was. +//! stays as it was. The owner's reply is the answer, so a rejected action +//! delivers nothing and an owner that does not answer leaves the delivery +//! uncertain; the key route's refusal replaces neither. use std::time::Duration; @@ -19,20 +21,21 @@ use agent_desktop_core::{ StepMechanism, WindowInfo, }; -use crate::actions::action_call::resolve_verb; +use crate::actions::action_call::do_action; use crate::actions::chain::run_semantic_chain; +use crate::actions::context::Target; +use crate::actions::write::mutation::WriteReply; +use crate::system::SharedBus; use crate::system::window::window_id; use crate::system::window::window_ops::windows_of_process; -use crate::system::{SharedBus, within}; use crate::tree::capabilities::action_names::click_verbs; use crate::tree::menu::observe_menu::{rooted, scan_walk_structure}; use crate::tree::vocabulary::role_numbers::{ COMBO_BOX, MENU, POPUP_MENU, PUSH_BUTTON, PUSH_BUTTON_MENU, TOGGLE_BUTTON, }; use crate::tree::vocabulary::state_bits::{EXPANDED, HAS_POPUP, SHOWING, StateBits}; -use crate::tree::{AtspiElement, ObservedRead, WalkedNode, call, get_live_actions}; +use crate::tree::{AtspiElement, ObservedRead, WalkedNode, get_live_actions}; -const ACTION_INTERFACE: &str = "org.a11y.atspi.Action"; const SCAN_NODES: usize = 600; const OWNER_NODES: usize = 64; const POPUP_CONTAINER_CHILDREN: usize = 16; @@ -133,34 +136,55 @@ fn still_open(bus: &SharedBus, owner: &AtspiElement, deadline: Deadline) -> Opti Some(is_open_owner(&walk)) } +/// Presses the popup owner's own action and keeps its reply: no matching verb +/// or a reply of false is `WriteReply::Absent`, and a call that timed out after +/// it was sent keeps the uncertain delivery the write path gives it. fn press_owner( bus: &SharedBus, owner: &AtspiElement, role: Option, deadline: Deadline, -) -> Result { +) -> Result { let handle = owner.clone().into_native_handle(); let names = get_live_actions(bus, &handle, deadline)?.unwrap_or_default(); - let Some(index) = resolve_verb(&names, click_verbs(role)) else { - return Ok(false); - }; - let connection = bus.get(deadline)?; - within(deadline, async { - call( - connection.inner(), - owner, - ACTION_INTERFACE, - "DoAction", - &(index,), - ) - .await - .map(|_| true) - .map_err(|error| crate::system::classify(&error)) - }) + do_action( + &Target { + bus, + handle: &handle, + element: owner, + deadline, + }, + &names, + click_verbs(role), + ) +} + +/// What the owner's reply settles. A reply of false delivered nothing, so the +/// popup is not read and cannot turn that reply into a delivery. +fn popup_outcome(reply: WriteReply, read_closed: impl FnOnce() -> Option) -> DeliveryOutcome { + match reply { + WriteReply::Absent => DeliveryOutcome::NotDelivered, + WriteReply::Done => DeliveryOutcome::observed(read_closed()), + } +} + +/// The answer for a refused Escape: the popup attempt's own result, or its own +/// error, which already says whether that attempt may have landed. The refusal +/// stands only when the target window shows no open popup owner. +pub(super) fn popup_answer( + refusal: AdapterError, + popup: Result, AdapterError>, +) -> Result { + match popup { + Ok(Some(settled)) => Ok(settled), + Ok(None) => Err(refusal), + Err(attempt) => Err(attempt), + } } /// The refused Escape of a background application, answered by closing the -/// open popup its target window shows. `None` leaves the refusal as it was. +/// open popup its target window shows. `Ok(None)` leaves the refusal as it was; +/// every other result, the popup attempt's own failure included, is the answer. pub(super) fn close_open_popup( bus: &SharedBus, pid: u32, @@ -189,16 +213,15 @@ pub(super) fn close_open_popup( return Ok(None); }; let run = || { - if !press_owner(bus, &owner, owner_role, deadline)? { - return Ok(DeliveryOutcome::NotDelivered); - } - let closed = deadline.poll_until( - CLOSE_SETTLE, - CLOSE_STEP, - || still_open(bus, &owner, deadline).map(|open| !open), - |closed| *closed == Some(true), - ); - Ok(DeliveryOutcome::observed(closed)) + let reply = press_owner(bus, &owner, owner_role, deadline)?; + Ok(popup_outcome(reply, || { + deadline.poll_until( + CLOSE_SETTLE, + CLOSE_STEP, + || still_open(bus, &owner, deadline).map(|open| !open), + |closed| *closed == Some(true), + ) + })) }; let mut rungs = [ChainRung { label: CLOSE_LABEL, diff --git a/crates/linux/src/system/focus/escape_popup_tests.rs b/crates/linux/src/system/focus/escape_popup_tests.rs index 231acd4f5d..b2f1535842 100644 --- a/crates/linux/src/system/focus/escape_popup_tests.rs +++ b/crates/linux/src/system/focus/escape_popup_tests.rs @@ -1,7 +1,10 @@ -use agent_desktop_core::{AdapterError, ErrorCode, KeyCombo, Modifier}; +use agent_desktop_core::{ + ActionResult, AdapterError, DeliveryOutcome, DeliverySemantics, ErrorCode, KeyCombo, Modifier, +}; use serde_json::json; -use super::{is_focus_refusal, is_open_owner, is_plain_escape}; +use super::{is_focus_refusal, is_open_owner, is_plain_escape, popup_answer, popup_outcome}; +use crate::actions::write::mutation::{Abort, WriteKind, WriteReply, abort_error}; use crate::tree::test_support::helpers::{read_of, words}; use crate::tree::vocabulary::role_numbers::{COMBO_BOX, MENU, PUSH_BUTTON, TABLE_CELL}; use crate::tree::vocabulary::state_bits::{EXPANDED, HAS_POPUP, SHOWING}; @@ -68,3 +71,48 @@ fn only_a_combo_box_or_a_popup_button_with_an_open_popup_is_an_open_owner() { assert!(!is_open_owner(&node(PUSH_BUTTON, &[EXPANDED], Vec::new()))); assert!(!is_open_owner(&node(TABLE_CELL, &[EXPANDED], shown()))); } + +#[test] +fn a_rejected_owner_action_is_never_a_delivery() { + assert_eq!( + popup_outcome(WriteReply::Absent, || Some(true)), + DeliveryOutcome::NotDelivered + ); + assert_eq!( + popup_outcome(WriteReply::Done, || Some(true)), + DeliveryOutcome::observed(Some(true)) + ); +} + +fn focus_refusal() -> AdapterError { + AdapterError::new(ErrorCode::ActionFailed, "refused") + .with_details(json!({ "check": "window_active" })) + .with_disposition(DeliverySemantics::not_delivered()) +} + +#[test] +fn a_popup_attempt_that_may_have_landed_keeps_its_own_uncertain_error() { + let timed_out = abort_error(Abort::TimedOut, WriteKind::DoAction, None); + let answer = popup_answer(focus_refusal(), Err(timed_out)).expect_err("the popup's error"); + assert_eq!(answer.code, ErrorCode::Timeout); + assert_eq!(answer.disposition, DeliverySemantics::uncertain()); + assert!(!is_focus_refusal(&answer)); +} + +#[test] +fn a_refused_escape_stays_refused_when_no_popup_owner_is_open() { + let answer = popup_answer(focus_refusal(), Ok(None)).expect_err("nothing closed a popup"); + assert!(is_focus_refusal(&answer)); + assert_eq!(answer.disposition, DeliverySemantics::not_delivered()); +} + +#[test] +fn a_closed_popup_answers_the_refused_escape() { + let settled = ActionResult::delivered_unverified("close_popup"); + let answer = popup_answer(focus_refusal(), Ok(Some(settled))).expect("the popup closed"); + assert_eq!(answer.action, "close_popup"); + assert_eq!( + answer.disposition(), + DeliverySemantics::delivered_unverified() + ); +} diff --git a/crates/linux/src/system/focus/key_dispatch.rs b/crates/linux/src/system/focus/key_dispatch.rs index 13e730ded6..d8f3e40478 100644 --- a/crates/linux/src/system/focus/key_dispatch.rs +++ b/crates/linux/src/system/focus/key_dispatch.rs @@ -4,7 +4,7 @@ use agent_desktop_core::{ }; use serde_json::json; -use super::escape_popup::{close_open_popup, is_focus_refusal, is_plain_escape}; +use super::escape_popup::{close_open_popup, is_focus_refusal, is_plain_escape, popup_answer}; use crate::input::backend::Backend; use crate::input::physical::target_keyboard::press_for_process; use crate::input::physical::target_world::{LiveWorld, PhysicalWorld}; @@ -218,10 +218,8 @@ fn closing_popup_when_refused( ) -> Result { match result { Err(error) if is_plain_escape(combo) && is_focus_refusal(&error) => { - match close_open_popup(bus, target.0, target.1, combo, deadline) { - Ok(Some(closed)) => Ok(closed), - Ok(None) | Err(_) => Err(error), - } + let popup = close_open_popup(bus, target.0, target.1, combo, deadline); + popup_answer(error, popup) } other => other, } diff --git a/skills/agent-desktop-linux/SKILL.md b/skills/agent-desktop-linux/SKILL.md index 9549fa7cf9..72d909986f 100644 --- a/skills/agent-desktop-linux/SKILL.md +++ b/skills/agent-desktop-linux/SKILL.md @@ -78,9 +78,9 @@ use a private session and runtime directory for isolated work. a launch on X11 gives the focus back to the window that had it when the new window took it, and reports `focus_returned: true`. - `press escape --app --window-id ` on a background window that shows an - open combo box or popup button popup closes it through the owner's own action, and - reports `delivered_verified` after a read shows it gone; otherwise it is refused as - before. It never collapses a tree row. + open combo box or popup button popup closes it through the owner's own action and + reports `delivered_verified` once a read shows it gone, or the owner's own failure. + With no open popup the focus refusal stands. It never collapses a tree row. - Sandboxes are not available on Linux yet. To run agent-desktop in a container you manage yourself, see `agent-browser.dev/desktop/guides/docker-container`. ## Troubleshooting From f90462f0ef8f16598c0e22099935c1fe949e724d Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:49:11 -0800 Subject: [PATCH 08/19] fix(macos): fail a cell write the cell did not take A cell write typed into the editor and committed with Return, then reported delivered_unverified without reading the cell. An application that gives that editor no keyboard input reported success while the cell stayed empty. The cell is now read back after the commit: a matching value is verified, a cell that still shows nothing fails with ACTION_FAILED and an uncertain delivery, and a cell that shows another value stays delivered_unverified. --- crates/macos/src/actions/cell_editor.rs | 49 +++++++++++++++--- crates/macos/src/actions/cell_editor_tests.rs | 51 +++++++++++++++++-- crates/macos/src/actions/cell_read_back.rs | 25 +++++++++ .../macos/src/actions/cell_read_back_tests.rs | 12 +++++ crates/macos/src/actions/mod.rs | 1 + skills/agent-desktop-macos/SKILL.md | 7 ++- 6 files changed, 132 insertions(+), 13 deletions(-) create mode 100644 crates/macos/src/actions/cell_read_back.rs create mode 100644 crates/macos/src/actions/cell_read_back_tests.rs diff --git a/crates/macos/src/actions/cell_editor.rs b/crates/macos/src/actions/cell_editor.rs index 614539d746..69c7a67121 100644 --- a/crates/macos/src/actions/cell_editor.rs +++ b/crates/macos/src/actions/cell_editor.rs @@ -13,6 +13,7 @@ use agent_desktop_core::{ AdapterError, Deadline, DeliveryOutcome, DeliverySemantics, ErrorCode, KeyCombo, }; +use crate::actions::cell_read_back::{ReadBack, classify as classify_read_back}; use crate::actions::chain::press_selection; use crate::actions::{DeliveryTracker, ax_helpers, background_keyboard}; use crate::tree::AXElement; @@ -150,12 +151,13 @@ pub(crate) fn replace( /// The cell is pressed, the way a click presses it, until its editor holds /// the application's keyboard focus, at most twice, because a first press can /// only select the cell. The editor's text is then replaced and Return commits -/// it. The cell is not read after the commit, so a write that sent anything -/// is delivered and unverified. Text and Return go only to the editor inside -/// this cell. When the application moves the edit into another element, as a -/// formula can, the write stops there and fails as delivered and unverified. -/// A cell that was pressed and took no text fails the same way: nothing was -/// typed. +/// it. The cell is read back after the commit: a write the cell shows is +/// verified, a cell that still shows nothing fails, and a cell that shows +/// another value stays delivered and unverified. Text and Return go only to the +/// editor inside this cell. When the application moves the edit into another +/// element, as a formula can, the write stops there and fails as delivered and +/// unverified. A cell that was pressed and took no text fails the same way: +/// nothing was typed. pub(crate) fn write( cell: &AXElement, value: &str, @@ -192,6 +194,9 @@ pub(crate) trait CellEdit { /// Sends Return to the editor. fn commit(&mut self, editor: &Self::Editor) -> Result<(), AdapterError>; + + /// Reads the cell's value back after the commit. + fn read_back(&mut self, value: &str) -> Result; } /// The write sequence over `edit`. An error after anything was sent is @@ -223,7 +228,11 @@ fn write_steps( } edit.commit(&editor)?; *sent = true; - Ok(DeliveryOutcome::from_delivery(true, false)) + Ok(match edit.read_back(value)? { + ReadBack::Matches => DeliveryOutcome::from_delivery(true, true), + ReadBack::Differs => DeliveryOutcome::from_delivery(true, false), + ReadBack::Empty => return cell_took_nothing(), + }) } fn open_editor( @@ -249,7 +258,6 @@ struct LiveCell<'a> { cell: &'a AXElement, deadline: Deadline, } - impl CellEdit for LiveCell<'_> { type Editor = AXElement; @@ -282,6 +290,18 @@ impl CellEdit for LiveCell<'_> { fn commit(&mut self, editor: &AXElement) -> Result<(), AdapterError> { background_keyboard::press(editor, &return_key(), self.deadline) } + + fn read_back(&mut self, value: &str) -> Result { + let read = || { + classify_read_back( + crate::tree::copy_value_typed(self.cell, self.deadline).as_deref(), + value, + ) + }; + Ok(self + .deadline + .poll_until(SETTLE, SETTLE_POLL, read, |read| *read != ReadBack::Empty)) + } } /// The end of a write whose editor lost the keyboard focus before the commit, @@ -314,6 +334,19 @@ pub(crate) fn nothing_typed(pressed: bool) -> Result Result { + Err(AdapterError::new( + ErrorCode::ActionFailed, + "The text was typed and committed, but the cell still shows nothing", + ) + .with_suggestion( + "Bring the application to the front and retry, or type into the cell with --headed only if the user explicitly asked for that, then read the cell to verify the write.", + ) + .with_disposition(DeliverySemantics::delivered_unverified())) +} + /// The text element inside `cell` that holds the application's keyboard focus. fn editor_of(cell: &AXElement, deadline: Deadline) -> Result, AdapterError> { let Some(pid) = diff --git a/crates/macos/src/actions/cell_editor_tests.rs b/crates/macos/src/actions/cell_editor_tests.rs index a940395c18..ae98ffa36f 100644 --- a/crates/macos/src/actions/cell_editor_tests.rs +++ b/crates/macos/src/actions/cell_editor_tests.rs @@ -2,6 +2,7 @@ use super::{ CellEdit, CellTarget, Replacement, cell_target, left_open, nothing_typed, replacement, write_through, }; +use crate::actions::cell_read_back::ReadBack; use agent_desktop_core::{AdapterError, DeliveryOutcome, DeliverySemantics, ErrorCode}; #[test] @@ -65,6 +66,10 @@ fn unverified() -> DeliveryOutcome { DeliveryOutcome::from_delivery(true, false) } +fn verified() -> DeliveryOutcome { + DeliveryOutcome::from_delivery(true, true) +} + /// A cell whose editor is open from the start, or opens on the press numbered /// `opens_on_press`, and that records every call made on it. struct ScriptedCell { @@ -72,6 +77,7 @@ struct ScriptedCell { opens_on_press: usize, press: DeliveryOutcome, typed: Result, + read_back: ReadBack, keeps_focus: bool, presses: usize, calls: Vec<&'static str>, @@ -83,6 +89,7 @@ fn scripted() -> ScriptedCell { opens_on_press: 1, press: unverified(), typed: Ok(unverified()), + read_back: ReadBack::Matches, keeps_focus: true, presses: 0, calls: Vec::new(), @@ -124,6 +131,11 @@ impl CellEdit for ScriptedCell { self.calls.push("commit"); Ok(()) } + + fn read_back(&mut self, _: &str) -> Result { + self.calls.push("read_back"); + Ok(self.read_back) + } } #[test] @@ -133,8 +145,40 @@ fn an_open_editor_is_replaced_and_committed_without_a_press() { ..scripted() }; + assert_eq!(write_through(&mut cell, "42").unwrap(), verified()); + assert_eq!( + cell.calls, + ["editor", "replace", "holds_focus", "commit", "read_back"] + ); +} + +#[test] +fn a_cell_that_stays_empty_after_the_commit_fails_as_delivered() { + let mut cell = ScriptedCell { + open: true, + read_back: ReadBack::Empty, + ..scripted() + }; + + let error = write_through(&mut cell, "42").unwrap_err(); + + assert_eq!(error.code, ErrorCode::ActionFailed); + assert_eq!(error.disposition, DeliverySemantics::delivered_unverified()); + assert_eq!( + cell.calls, + ["editor", "replace", "holds_focus", "commit", "read_back"] + ); +} + +#[test] +fn a_cell_that_shows_another_value_stays_unverified() { + let mut cell = ScriptedCell { + read_back: ReadBack::Differs, + ..scripted() + }; + assert_eq!(write_through(&mut cell, "42").unwrap(), unverified()); - assert_eq!(cell.calls, ["editor", "replace", "holds_focus", "commit"]); + assert_eq!(cell.calls.last(), Some(&"read_back")); } #[test] @@ -144,7 +188,7 @@ fn a_press_that_only_selects_the_cell_is_followed_by_one_more() { ..scripted() }; - assert_eq!(write_through(&mut cell, "42").unwrap(), unverified()); + assert_eq!(write_through(&mut cell, "42").unwrap(), verified()); assert_eq!( cell.calls, [ @@ -155,7 +199,8 @@ fn a_press_that_only_selects_the_cell_is_followed_by_one_more() { "opened_editor", "replace", "holds_focus", - "commit" + "commit", + "read_back" ] ); } diff --git a/crates/macos/src/actions/cell_read_back.rs b/crates/macos/src/actions/cell_read_back.rs new file mode 100644 index 0000000000..c2dc1ccd00 --- /dev/null +++ b/crates/macos/src/actions/cell_read_back.rs @@ -0,0 +1,25 @@ +//! Judging a table cell's value after a committed write. + +/// What a cell shows after a committed write, next to the value written. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ReadBack { + Matches, + Empty, + Differs, +} + +/// Judges the cell's value after a commit. A cell that publishes nothing while +/// a value was written took no text; a cell that shows something else may hold +/// a formatted form of it. +pub(crate) fn classify(current: Option<&str>, wanted: &str) -> ReadBack { + match current { + Some(held) if held == wanted => ReadBack::Matches, + Some(held) if !held.is_empty() => ReadBack::Differs, + _ if wanted.is_empty() => ReadBack::Matches, + _ => ReadBack::Empty, + } +} + +#[cfg(test)] +#[path = "cell_read_back_tests.rs"] +mod tests; diff --git a/crates/macos/src/actions/cell_read_back_tests.rs b/crates/macos/src/actions/cell_read_back_tests.rs new file mode 100644 index 0000000000..e33fee959b --- /dev/null +++ b/crates/macos/src/actions/cell_read_back_tests.rs @@ -0,0 +1,12 @@ +use super::{ReadBack, classify}; + +#[test] +fn the_read_back_judges_only_an_empty_cell_as_a_miss() { + assert_eq!(classify(Some("42"), "42"), ReadBack::Matches); + assert_eq!(classify(None, ""), ReadBack::Matches); + assert_eq!(classify(Some(""), ""), ReadBack::Matches); + assert_eq!(classify(None, "42"), ReadBack::Empty); + assert_eq!(classify(Some(""), "42"), ReadBack::Empty); + assert_eq!(classify(Some("41"), "42"), ReadBack::Differs); + assert_eq!(classify(Some("42"), ""), ReadBack::Differs); +} diff --git a/crates/macos/src/actions/mod.rs b/crates/macos/src/actions/mod.rs index 865adce7a7..e6ee4d4cc2 100644 --- a/crates/macos/src/actions/mod.rs +++ b/crates/macos/src/actions/mod.rs @@ -7,6 +7,7 @@ pub(crate) mod ax_perform; pub(crate) mod background_effect; mod background_keyboard; mod cell_editor; +pub(crate) mod cell_read_back; pub(crate) mod chain; pub(crate) mod delivery_tracker; pub(crate) mod dispatch; diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.md index 8eb62c8d42..f3f3c4ace3 100644 --- a/skills/agent-desktop-macos/SKILL.md +++ b/skills/agent-desktop-macos/SKILL.md @@ -64,8 +64,11 @@ may report `unknown` when consent would require a prompt. Return go only to that editor. An application that moves a value into an editor of its own, as a spreadsheet does with a formula that starts with `=`, leaves it typed and open, and the write fails as `delivered_unverified`: commit it with - `press return --app `. Such a cell publishes no value, so a committed write is - `delivered_unverified` too: read the cell's name to verify. The write also commits + `press return --app `. The cell is read after the commit: a cell that still + shows nothing fails as `ACTION_FAILED` with `delivered_unverified`, and one that + shows another value stays `delivered_unverified`. An application that gives its + cell editor no keyboard input from a press always takes that failure; type there + with `--headed` only if the user explicitly asked for that. The write also commits an edit that is open in another cell. - AX success alone does not prove an application effect. Verify the task's result independently, especially after a menu action or a value write. From ac20c5b6e04385aadd12587f3c69f099cfb9ed64 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:11:00 -0800 Subject: [PATCH 09/19] fix(macos): read a written cell back by its observed name A cell often publishes its text through the name a snapshot shows, not through AXValue, and it keeps an editing label until its editor closes. The read-back now reads that name and treats an editor that is still open as a cell that took nothing. A read that fails is unknown, so it stays unverified instead of failing a write or verifying a clear. --- crates/macos/src/actions/cell_editor.rs | 81 ++++++------------- crates/macos/src/actions/cell_editor_tests.rs | 17 +++- crates/macos/src/actions/cell_read_back.rs | 7 +- .../macos/src/actions/cell_write_failure.rs | 48 +++++++++++ crates/macos/src/actions/mod.rs | 1 + 5 files changed, 92 insertions(+), 62 deletions(-) create mode 100644 crates/macos/src/actions/cell_write_failure.rs diff --git a/crates/macos/src/actions/cell_editor.rs b/crates/macos/src/actions/cell_editor.rs index 69c7a67121..1ad9c198f6 100644 --- a/crates/macos/src/actions/cell_editor.rs +++ b/crates/macos/src/actions/cell_editor.rs @@ -9,11 +9,10 @@ use std::time::Duration; -use agent_desktop_core::{ - AdapterError, Deadline, DeliveryOutcome, DeliverySemantics, ErrorCode, KeyCombo, -}; +use agent_desktop_core::{AdapterError, Deadline, DeliveryOutcome, KeyCombo}; use crate::actions::cell_read_back::{ReadBack, classify as classify_read_back}; +use crate::actions::cell_write_failure::{cell_took_nothing, left_open, nothing_typed}; use crate::actions::chain::press_selection; use crate::actions::{DeliveryTracker, ax_helpers, background_keyboard}; use crate::tree::AXElement; @@ -24,12 +23,11 @@ pub(crate) const REPLACE_LABEL: &str = "PIDTargetedReplaceText"; pub(crate) const WRITE_LABEL: &str = "CellEditorWrite"; const MAX_PRESSES: usize = 2; -const LEFT_OPEN_SUGGESTION: &str = "Commit the open edit with a key press scoped to the application, such as press return --app , then read the cell to verify."; -const NO_EDITOR_SUGGESTION: &str = "Take a fresh snapshot before another write: the press can select the cell or open another surface."; const CELL_ROLE: &str = "cell"; const SETTLE: Duration = Duration::from_millis(600); const SETTLE_POLL: Duration = Duration::from_millis(10); +const READ_BACK_SETTLE: Duration = Duration::from_millis(2000); /// What replacing an editor's text takes, given the text it holds now. #[derive(Debug, PartialEq, Eq)] @@ -230,7 +228,7 @@ fn write_steps( *sent = true; Ok(match edit.read_back(value)? { ReadBack::Matches => DeliveryOutcome::from_delivery(true, true), - ReadBack::Differs => DeliveryOutcome::from_delivery(true, false), + ReadBack::Differs | ReadBack::Unknown => DeliveryOutcome::from_delivery(true, false), ReadBack::Empty => return cell_took_nothing(), }) } @@ -292,61 +290,34 @@ impl CellEdit for LiveCell<'_> { } fn read_back(&mut self, value: &str) -> Result { - let read = || { - classify_read_back( - crate::tree::copy_value_typed(self.cell, self.deadline).as_deref(), - value, - ) + let mut read = || { + let mut usage = crate::tree::observation_usage::ObservationUsage::new( + agent_desktop_core::ObservationBudget::default(), + ); + let text = match crate::tree::element_name::resolve_element_name( + self.cell, + self.deadline, + &mut usage, + ) { + Ok(text) => text, + Err(_) => return ReadBack::Unknown, + }; + if text.as_deref() == Some(value) { + return ReadBack::Matches; + } + if editor_of(self.cell, self.deadline).ok().flatten().is_some() { + return ReadBack::Empty; + } + classify_read_back(text.as_deref(), value) }; Ok(self .deadline - .poll_until(SETTLE, SETTLE_POLL, read, |read| *read != ReadBack::Empty)) + .poll_until(READ_BACK_SETTLE, SETTLE_POLL, &mut read, |read| { + matches!(read, ReadBack::Matches | ReadBack::Unknown) + })) } } -/// The end of a write whose editor lost the keyboard focus before the commit, -/// as it does when the application moves the edit into an editor of its own. -/// Return is not sent to another element. Text that was sent stays on record -/// as a failure, so the caller does not read it as a committed write. -pub(crate) fn left_open(sent: bool) -> Result { - if !sent { - return Ok(DeliveryOutcome::NotDelivered); - } - Err(AdapterError::new( - ErrorCode::ActionFailed, - "The text was typed, and the application moved the edit out of the cell's editor before it was committed", - ) - .with_suggestion(LEFT_OPEN_SUGGESTION) - .with_disposition(DeliverySemantics::delivered_unverified())) -} - -/// The end of a write that typed nothing. A press that was sent stays on -/// record as a failure, so the caller does not read it as a write. -pub(crate) fn nothing_typed(pressed: bool) -> Result { - if !pressed { - return Ok(DeliveryOutcome::NotDelivered); - } - Err(AdapterError::new( - ErrorCode::ActionFailed, - "The cell was pressed and nothing was typed: it gave no text editor, or the editor's text could not be read or selected", - ) - .with_suggestion(NO_EDITOR_SUGGESTION) - .with_disposition(DeliverySemantics::delivered_unverified())) -} - -/// The end of a write whose cell still shows nothing after the commit: the -/// application took the keys and dropped them instead of the text. -pub(crate) fn cell_took_nothing() -> Result { - Err(AdapterError::new( - ErrorCode::ActionFailed, - "The text was typed and committed, but the cell still shows nothing", - ) - .with_suggestion( - "Bring the application to the front and retry, or type into the cell with --headed only if the user explicitly asked for that, then read the cell to verify the write.", - ) - .with_disposition(DeliverySemantics::delivered_unverified())) -} - /// The text element inside `cell` that holds the application's keyboard focus. fn editor_of(cell: &AXElement, deadline: Deadline) -> Result, AdapterError> { let Some(pid) = diff --git a/crates/macos/src/actions/cell_editor_tests.rs b/crates/macos/src/actions/cell_editor_tests.rs index ae98ffa36f..fa766b42ba 100644 --- a/crates/macos/src/actions/cell_editor_tests.rs +++ b/crates/macos/src/actions/cell_editor_tests.rs @@ -1,8 +1,6 @@ -use super::{ - CellEdit, CellTarget, Replacement, cell_target, left_open, nothing_typed, replacement, - write_through, -}; +use super::{CellEdit, CellTarget, Replacement, cell_target, replacement, write_through}; use crate::actions::cell_read_back::ReadBack; +use crate::actions::cell_write_failure::{left_open, nothing_typed}; use agent_desktop_core::{AdapterError, DeliveryOutcome, DeliverySemantics, ErrorCode}; #[test] @@ -181,6 +179,17 @@ fn a_cell_that_shows_another_value_stays_unverified() { assert_eq!(cell.calls.last(), Some(&"read_back")); } +#[test] +fn an_unreadable_cell_stays_unverified_and_never_fails() { + let mut cell = ScriptedCell { + read_back: ReadBack::Unknown, + ..scripted() + }; + + assert_eq!(write_through(&mut cell, "42").unwrap(), unverified()); + assert_eq!(cell.calls.last(), Some(&"read_back")); +} + #[test] fn a_press_that_only_selects_the_cell_is_followed_by_one_more() { let mut cell = ScriptedCell { diff --git a/crates/macos/src/actions/cell_read_back.rs b/crates/macos/src/actions/cell_read_back.rs index c2dc1ccd00..3b63adf3ba 100644 --- a/crates/macos/src/actions/cell_read_back.rs +++ b/crates/macos/src/actions/cell_read_back.rs @@ -6,11 +6,12 @@ pub(crate) enum ReadBack { Matches, Empty, Differs, + Unknown, } -/// Judges the cell's value after a commit. A cell that publishes nothing while -/// a value was written took no text; a cell that shows something else may hold -/// a formatted form of it. +/// Judges the cell's value after a commit. `current` is `None` only when the +/// application was read and published no value; a read that failed is +/// `Unknown` and never an empty cell. pub(crate) fn classify(current: Option<&str>, wanted: &str) -> ReadBack { match current { Some(held) if held == wanted => ReadBack::Matches, diff --git a/crates/macos/src/actions/cell_write_failure.rs b/crates/macos/src/actions/cell_write_failure.rs new file mode 100644 index 0000000000..691880cfe3 --- /dev/null +++ b/crates/macos/src/actions/cell_write_failure.rs @@ -0,0 +1,48 @@ +//! The failures a value write through a cell's editor can end with. + +use agent_desktop_core::{AdapterError, DeliveryOutcome, DeliverySemantics, ErrorCode}; + +const LEFT_OPEN_SUGGESTION: &str = "Commit the open edit with a key press scoped to the application, such as press return --app , then read the cell to verify."; +const NO_EDITOR_SUGGESTION: &str = "Take a fresh snapshot before another write: the press can select the cell or open another surface."; +const CELL_TOOK_NOTHING_SUGGESTION: &str = "Bring the application to the front and retry, or type into the cell with --headed only if the user explicitly asked for that, then read the cell to verify the write."; + +/// The end of a write whose editor lost the keyboard focus before the commit, +/// as it does when the application moves the edit into an editor of its own. +/// Return is not sent to another element. Text that was sent stays on record +/// as a failure, so the caller does not read it as a committed write. +pub(crate) fn left_open(sent: bool) -> Result { + if !sent { + return Ok(DeliveryOutcome::NotDelivered); + } + Err(AdapterError::new( + ErrorCode::ActionFailed, + "The text was typed, and the application moved the edit out of the cell's editor before it was committed", + ) + .with_suggestion(LEFT_OPEN_SUGGESTION) + .with_disposition(DeliverySemantics::delivered_unverified())) +} + +/// The end of a write that typed nothing. A press that was sent stays on +/// record as a failure, so the caller does not read it as a write. +pub(crate) fn nothing_typed(pressed: bool) -> Result { + if !pressed { + return Ok(DeliveryOutcome::NotDelivered); + } + Err(AdapterError::new( + ErrorCode::ActionFailed, + "The cell was pressed and nothing was typed: it gave no text editor, or the editor's text could not be read or selected", + ) + .with_suggestion(NO_EDITOR_SUGGESTION) + .with_disposition(DeliverySemantics::delivered_unverified())) +} + +/// The end of a write whose cell still shows nothing after the commit: the +/// application took the keys and dropped them instead of the text. +pub(crate) fn cell_took_nothing() -> Result { + Err(AdapterError::new( + ErrorCode::ActionFailed, + "The text was typed and committed, but the cell still shows nothing", + ) + .with_suggestion(CELL_TOOK_NOTHING_SUGGESTION) + .with_disposition(DeliverySemantics::delivered_unverified())) +} diff --git a/crates/macos/src/actions/mod.rs b/crates/macos/src/actions/mod.rs index e6ee4d4cc2..c2332ee8e3 100644 --- a/crates/macos/src/actions/mod.rs +++ b/crates/macos/src/actions/mod.rs @@ -8,6 +8,7 @@ pub(crate) mod background_effect; mod background_keyboard; mod cell_editor; pub(crate) mod cell_read_back; +pub(crate) mod cell_write_failure; pub(crate) mod chain; pub(crate) mod delivery_tracker; pub(crate) mod dispatch; From cb48143a7670db1f87c0a82c358a11fcce612e20 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:48:22 -0800 Subject: [PATCH 10/19] fix: keep the @ in the zsh ref hint The suggested "${SID}:e1" dropped the @, so a caller who followed it got the same INVALID_ARGS again. The two docs examples copy the same text. --- apps/docs/content/docs/json-output.mdx | 2 +- apps/docs/content/docs/snapshots-and-refs.mdx | 2 +- crates/core/src/refs/ref_token.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/docs/content/docs/json-output.mdx b/apps/docs/content/docs/json-output.mdx index 8336440ca0..baaf839a13 100644 --- a/apps/docs/content/docs/json-output.mdx +++ b/apps/docs/content/docs/json-output.mdx @@ -43,7 +43,7 @@ An error envelope has `error` and no `data`: "error": { "code": "INVALID_ARGS", "message": "Invalid ref_id '@e1': expected @:e", - "suggestion": "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted. Pass ref_id as printed: it already holds the snapshot id. In zsh write \"${SID}:e1\", because an unbraced $SID:e1 reads :e as a modifier.", + "suggestion": "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted. Pass ref_id as printed: it already holds the snapshot id. In zsh write \"@${SID}:e1\", because an unbraced @$SID:e1 reads :e as a modifier.", "disposition": { "delivery": "not_delivered", "retry": "safe" } } } diff --git a/apps/docs/content/docs/snapshots-and-refs.mdx b/apps/docs/content/docs/snapshots-and-refs.mdx index e8ff08d9a8..e06e32ee22 100644 --- a/apps/docs/content/docs/snapshots-and-refs.mdx +++ b/apps/docs/content/docs/snapshots-and-refs.mdx @@ -112,7 +112,7 @@ Every command accepts only this qualified form. A bare `@e6` fails with `INVALID "error": { "code": "INVALID_ARGS", "message": "Invalid ref_id '@e1': expected @:e", - "suggestion": "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted. Pass ref_id as printed: it already holds the snapshot id. In zsh write \"${SID}:e1\", because an unbraced $SID:e1 reads :e as a modifier.", + "suggestion": "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted. Pass ref_id as printed: it already holds the snapshot id. In zsh write \"@${SID}:e1\", because an unbraced @$SID:e1 reads :e as a modifier.", "disposition": { "delivery": "not_delivered", "retry": "safe" } } } diff --git a/crates/core/src/refs/ref_token.rs b/crates/core/src/refs/ref_token.rs index 98421634a0..dc4571d07e 100644 --- a/crates/core/src/refs/ref_token.rs +++ b/crates/core/src/refs/ref_token.rs @@ -52,7 +52,7 @@ fn is_local_ref(ref_id: &str) -> bool { }) } -const REF_SUGGESTION: &str = "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted. Pass ref_id as printed: it already holds the snapshot id. In zsh write \"${SID}:e1\", because an unbraced $SID:e1 reads :e as a modifier."; +const REF_SUGGESTION: &str = "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted. Pass ref_id as printed: it already holds the snapshot id. In zsh write \"@${SID}:e1\", because an unbraced @$SID:e1 reads :e as a modifier."; fn invalid_ref(ref_id: &str) -> AppError { AppError::invalid_input_with_suggestion( From 2dc4c321b40c1e45d5b6ca0f559c649739db871e Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:26:04 -0800 Subject: [PATCH 11/19] fix(linux): refuse background Escape unless the popup owner exposes a safe dismissal action Skip web documents during the background-Escape owner walk, require an actually showing popup menu child instead of EXPANDED alone, and replace click_verbs with explicit dismissal verbs (collapse/cancel/close, plus press only for native GTK 3 combo boxes, L4-4). When no safe dismissal verb is advertised, return Ok(None) so the focus refusal stands without invoking any button's primary action. --- crates/linux/src/system/focus/escape_popup.rs | 122 +++++++++++------- .../src/system/focus/escape_popup_tests.rs | 98 +++++++++++++- skills/agent-desktop-linux/SKILL.md | 8 +- 3 files changed, 170 insertions(+), 58 deletions(-) diff --git a/crates/linux/src/system/focus/escape_popup.rs b/crates/linux/src/system/focus/escape_popup.rs index f6eb4ced58..bfdee8bf90 100644 --- a/crates/linux/src/system/focus/escape_popup.rs +++ b/crates/linux/src/system/focus/escape_popup.rs @@ -1,18 +1,18 @@ //! Escape for an application that does not own the active window. //! //! The key route sends the key only to the active window, so a key for a -//! background application is refused. A popup that the application opened -//! stays open in the background on some toolkits, and the key cannot reach -//! it. The popup has an owner: a combo box, or a button that has a popup. The -//! owner's own action toggles the popup, so the action is sent only when a -//! read shows the popup open, and the result is verified by reading it gone. +//! background application is refused. A native popup that the application +//! opened stays open in the background on some toolkits, and the key cannot +//! reach it. Web documents are excluded, and a candidate must show an open +//! popup menu child and advertise a dismissal verb (or GTK 3 combo box `Press`, +//! L4-4) so Escape never activates a button's primary handler. //! //! Three states, in this order: the key route is allowed and nothing here -//! runs; the key route is refused for focus and an open popup owner exists -//! in the target window, whose own action closes it; otherwise the refusal -//! stays as it was. The owner's reply is the answer, so a rejected action -//! delivers nothing and an owner that does not answer leaves the delivery -//! uncertain; the key route's refusal replaces neither. +//! runs; the key route is refused for focus and a dismissible native popup +//! owner exists in the target window; otherwise the refusal stays as it was. +//! The owner's reply is the answer, so a rejected action delivers nothing and +//! an owner that does not answer leaves the delivery uncertain; the key +//! route's refusal replaces neither. use std::time::Duration; @@ -21,19 +21,19 @@ use agent_desktop_core::{ StepMechanism, WindowInfo, }; -use crate::actions::action_call::do_action; +use crate::actions::action_call::{do_action, resolve_verb}; use crate::actions::chain::run_semantic_chain; use crate::actions::context::Target; use crate::actions::write::mutation::WriteReply; -use crate::system::SharedBus; use crate::system::window::window_id; use crate::system::window::window_ops::windows_of_process; -use crate::tree::capabilities::action_names::click_verbs; +use crate::system::{REGISTRY_ROOT_PATH, SharedBus, within}; use crate::tree::menu::observe_menu::{rooted, scan_walk_structure}; +use crate::tree::properties::toolkit_trust::{ToolkitKind, kind, read_toolkit}; use crate::tree::vocabulary::role_numbers::{ - COMBO_BOX, MENU, POPUP_MENU, PUSH_BUTTON, PUSH_BUTTON_MENU, TOGGLE_BUTTON, + COMBO_BOX, MENU, POPUP_MENU, PUSH_BUTTON, PUSH_BUTTON_MENU, TOGGLE_BUTTON, is_web_document, }; -use crate::tree::vocabulary::state_bits::{EXPANDED, HAS_POPUP, SHOWING, StateBits}; +use crate::tree::vocabulary::state_bits::{HAS_POPUP, SHOWING, StateBits}; use crate::tree::{AtspiElement, ObservedRead, WalkedNode, get_live_actions}; const SCAN_NODES: usize = 600; @@ -44,6 +44,8 @@ const CLOSE_STEP: Duration = Duration::from_millis(50); const FOCUS_CHECKS: [&str; 2] = ["window_active", "exact_window_focus"]; const SUGGESTION: &str = "Refresh the snapshot and check whether the popup is still open."; const CLOSE_LABEL: &str = "Action.DoAction"; +const DISMISS_VERBS: [&str; 3] = ["collapse", "cancel", "close"]; +const GTK3_COMBO_DISMISS_VERBS: [&str; 4] = ["collapse", "cancel", "close", "press"]; pub(super) fn is_plain_escape(combo: &KeyCombo) -> bool { combo.modifiers.is_empty() && combo.key.eq_ignore_ascii_case("escape") @@ -72,16 +74,21 @@ fn role(node: &WalkedNode) -> Option { } fn showing_popup(node: &WalkedNode) -> bool { - matches!(role(node), Some(MENU | POPUP_MENU)) + !node.in_web_document + && !is_web_document(role(node)) + && matches!(role(node), Some(MENU | POPUP_MENU)) && bits(node).is_some_and(|bits| bits.has(SHOWING)) } -/// Whether the node owns a popup and the popup is open now. The owner roles -/// are the ones whose expansion is a popup: a combo box, and a button that -/// has the popup state. An owner is open when it reports `EXPANDED` or when a -/// popup menu below it shows. A tree row, an expander or a table cell is -/// never an owner: Escape does not collapse a tree. +/// Whether a native node owns a popup that is visibly open now: a combo box, +/// or a button with `HAS_POPUP`, that has a showing `MENU` or `POPUP_MENU` +/// child. Web documents are excluded, and `EXPANDED` alone never qualifies an +/// owner. A tree row, an expander or a table cell is never an owner: Escape +/// does not collapse a tree. pub(super) fn is_open_owner(node: &WalkedNode) -> bool { + if node.in_web_document || is_web_document(role(node)) { + return false; + } let Some(bits) = bits(node) else { return false; }; @@ -90,14 +97,28 @@ pub(super) fn is_open_owner(node: &WalkedNode) -> bool { Some(PUSH_BUTTON | PUSH_BUTTON_MENU | TOGGLE_BUTTON) => bits.has(HAS_POPUP), _ => false, }; - owner && (bits.has(EXPANDED) || node.children.iter().any(showing_popup)) + owner && node.children.iter().any(showing_popup) } -fn deepest_open_owner<'a>( +/// The dismissal verbs Escape may invoke on an open popup owner. Generic +/// click/activate verbs are never used, and `press` is allowed only for a +/// native GTK 3 combo box (L4-4), whose `Press` action pops down its showing +/// menu child rather than firing a button's primary handler. +pub(super) fn close_verbs(role: Option, toolkit: ToolkitKind) -> &'static [&'static str] { + match (role, toolkit) { + (Some(COMBO_BOX), ToolkitKind::Gtk3) => >K3_COMBO_DISMISS_VERBS, + _ => &DISMISS_VERBS, + } +} + +pub(super) fn deepest_open_owner<'a>( node: &'a WalkedNode, depth: usize, best: &mut Option<(usize, &'a WalkedNode)>, ) { + if node.in_web_document || is_web_document(role(node)) { + return; + } if is_open_owner(node) && best.is_none_or(|(deepest, _)| depth > deepest) { *best = Some((depth, node)); } @@ -124,6 +145,17 @@ fn frames_of( Ok(frames) } +fn owner_toolkit(bus: &SharedBus, owner: &AtspiElement, deadline: Deadline) -> ToolkitKind { + let Ok(connection) = bus.get(deadline) else { + return ToolkitKind::Other; + }; + let app = AtspiElement::new(owner.bus_name(), REGISTRY_ROOT_PATH, owner.pid()); + match within(deadline, read_toolkit(connection.inner(), &app)) { + Ok(toolkit) => kind(&toolkit), + Err(_) => ToolkitKind::Other, + } +} + fn still_open(bus: &SharedBus, owner: &AtspiElement, deadline: Deadline) -> Option { let walk = scan_walk_structure( bus, @@ -136,29 +168,6 @@ fn still_open(bus: &SharedBus, owner: &AtspiElement, deadline: Deadline) -> Opti Some(is_open_owner(&walk)) } -/// Presses the popup owner's own action and keeps its reply: no matching verb -/// or a reply of false is `WriteReply::Absent`, and a call that timed out after -/// it was sent keeps the uncertain delivery the write path gives it. -fn press_owner( - bus: &SharedBus, - owner: &AtspiElement, - role: Option, - deadline: Deadline, -) -> Result { - let handle = owner.clone().into_native_handle(); - let names = get_live_actions(bus, &handle, deadline)?.unwrap_or_default(); - do_action( - &Target { - bus, - handle: &handle, - element: owner, - deadline, - }, - &names, - click_verbs(role), - ) -} - /// What the owner's reply settles. A reply of false delivered nothing, so the /// popup is not read and cannot turn that reply into a delivery. fn popup_outcome(reply: WriteReply, read_closed: impl FnOnce() -> Option) -> DeliveryOutcome { @@ -170,7 +179,7 @@ fn popup_outcome(reply: WriteReply, read_closed: impl FnOnce() -> Option) /// The answer for a refused Escape: the popup attempt's own result, or its own /// error, which already says whether that attempt may have landed. The refusal -/// stands only when the target window shows no open popup owner. +/// stands only when the target window shows no dismissible open popup owner. pub(super) fn popup_answer( refusal: AdapterError, popup: Result, AdapterError>, @@ -183,8 +192,9 @@ pub(super) fn popup_answer( } /// The refused Escape of a background application, answered by closing the -/// open popup its target window shows. `Ok(None)` leaves the refusal as it was; -/// every other result, the popup attempt's own failure included, is the answer. +/// open native popup its target window shows when the owner advertises a safe +/// dismissal verb. `Ok(None)` leaves the refusal as it was; every other +/// result, the popup attempt's own failure included, is the answer. pub(super) fn close_open_popup( bus: &SharedBus, pid: u32, @@ -212,8 +222,20 @@ pub(super) fn close_open_popup( let Some((_, owner, owner_role)) = best else { return Ok(None); }; + let verbs = close_verbs(owner_role, owner_toolkit(bus, &owner, deadline)); + let handle = owner.clone().into_native_handle(); + let names = get_live_actions(bus, &handle, deadline)?.unwrap_or_default(); + if resolve_verb(&names, verbs).is_none() { + return Ok(None); + } let run = || { - let reply = press_owner(bus, &owner, owner_role, deadline)?; + let target = Target { + bus, + handle: &handle, + element: &owner, + deadline, + }; + let reply = do_action(&target, &names, verbs)?; Ok(popup_outcome(reply, || { deadline.poll_until( CLOSE_SETTLE, diff --git a/crates/linux/src/system/focus/escape_popup_tests.rs b/crates/linux/src/system/focus/escape_popup_tests.rs index b2f1535842..4bc351638a 100644 --- a/crates/linux/src/system/focus/escape_popup_tests.rs +++ b/crates/linux/src/system/focus/escape_popup_tests.rs @@ -3,10 +3,17 @@ use agent_desktop_core::{ }; use serde_json::json; -use super::{is_focus_refusal, is_open_owner, is_plain_escape, popup_answer, popup_outcome}; +use super::{ + close_verbs, deepest_open_owner, is_focus_refusal, is_open_owner, is_plain_escape, + popup_answer, popup_outcome, +}; +use crate::actions::action_call::resolve_verb; use crate::actions::write::mutation::{Abort, WriteKind, WriteReply, abort_error}; +use crate::tree::properties::toolkit_trust::ToolkitKind; use crate::tree::test_support::helpers::{read_of, words}; -use crate::tree::vocabulary::role_numbers::{COMBO_BOX, MENU, PUSH_BUTTON, TABLE_CELL}; +use crate::tree::vocabulary::role_numbers::{ + COMBO_BOX, DOCUMENT_WEB, FRAME, MENU, PUSH_BUTTON, PUSH_BUTTON_MENU, TABLE_CELL, TOGGLE_BUTTON, +}; use crate::tree::vocabulary::state_bits::{EXPANDED, HAS_POPUP, SHOWING}; use crate::tree::{Field, ObservedRead, WalkedNode}; @@ -27,6 +34,10 @@ fn node( } } +fn names(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_owned()).collect() +} + fn combo(key: &str, modifiers: Vec) -> KeyCombo { KeyCombo { key: key.to_owned(), @@ -58,12 +69,14 @@ fn only_a_focus_refusal_is_answered_by_closing_a_popup() { } #[test] -fn only_a_combo_box_or_a_popup_button_with_an_open_popup_is_an_open_owner() { +fn only_a_native_owner_with_a_showing_popup_is_an_open_owner() { let shown = || vec![node(MENU, &[SHOWING], Vec::new())]; let hidden = || vec![node(MENU, &[], Vec::new())]; assert!(is_open_owner(&node(COMBO_BOX, &[], shown()))); assert!(!is_open_owner(&node(COMBO_BOX, &[], hidden()))); - assert!(is_open_owner(&node( + assert!(!is_open_owner(&node(COMBO_BOX, &[EXPANDED], Vec::new()))); + assert!(is_open_owner(&node(PUSH_BUTTON, &[HAS_POPUP], shown()))); + assert!(!is_open_owner(&node( PUSH_BUTTON, &[HAS_POPUP, EXPANDED], Vec::new() @@ -72,6 +85,83 @@ fn only_a_combo_box_or_a_popup_button_with_an_open_popup_is_an_open_owner() { assert!(!is_open_owner(&node(TABLE_CELL, &[EXPANDED], shown()))); } +#[test] +fn web_document_controls_never_qualify_for_background_escape() { + let shown = || vec![node(MENU, &[SHOWING], Vec::new())]; + let mut web_button = node(PUSH_BUTTON, &[HAS_POPUP, EXPANDED], shown()); + web_button.in_web_document = true; + assert!(!is_open_owner(&web_button)); + + let mut web_combo = node(COMBO_BOX, &[EXPANDED], shown()); + web_combo.in_web_document = true; + assert!(!is_open_owner(&web_combo)); + + let frame = node( + FRAME, + &[SHOWING], + vec![node( + DOCUMENT_WEB, + &[SHOWING], + vec![node(PUSH_BUTTON, &[HAS_POPUP, EXPANDED], shown())], + )], + ); + let mut found = None; + deepest_open_owner(&frame, 0, &mut found); + assert!(found.is_none()); +} + +#[test] +fn background_escape_never_invokes_a_buttons_primary_action() { + let primary = names(&["click", "press", "activate", "open", "clickAncestor"]); + for role in [PUSH_BUTTON, PUSH_BUTTON_MENU, TOGGLE_BUTTON] { + for toolkit in [ + ToolkitKind::Gtk3, + ToolkitKind::Gtk4, + ToolkitKind::Qt, + ToolkitKind::Chromium, + ToolkitKind::Other, + ] { + assert_eq!( + resolve_verb(&primary, close_verbs(Some(role), toolkit)), + None + ); + } + assert_eq!( + resolve_verb( + &names(&["click", "collapse"]), + close_verbs(Some(role), ToolkitKind::Gtk3) + ), + Some(1) + ); + } + + for toolkit in [ + ToolkitKind::Gtk4, + ToolkitKind::Qt, + ToolkitKind::Chromium, + ToolkitKind::Other, + ] { + assert_eq!( + resolve_verb(&primary, close_verbs(Some(COMBO_BOX), toolkit)), + None + ); + } + assert_eq!( + resolve_verb( + &names(&["Press"]), + close_verbs(Some(COMBO_BOX), ToolkitKind::Gtk3) + ), + Some(0) + ); + assert_eq!( + resolve_verb( + &names(&["click", "activate"]), + close_verbs(Some(COMBO_BOX), ToolkitKind::Gtk3) + ), + None + ); +} + #[test] fn a_rejected_owner_action_is_never_a_delivery() { assert_eq!( diff --git a/skills/agent-desktop-linux/SKILL.md b/skills/agent-desktop-linux/SKILL.md index 72d909986f..31abee5557 100644 --- a/skills/agent-desktop-linux/SKILL.md +++ b/skills/agent-desktop-linux/SKILL.md @@ -77,10 +77,10 @@ use a private session and runtime directory for isolated work. observations rather than guessing from a window title. Without `--activate`, a launch on X11 gives the focus back to the window that had it when the new window took it, and reports `focus_returned: true`. -- `press escape --app --window-id ` on a background window that shows an - open combo box or popup button popup closes it through the owner's own action and - reports `delivered_verified` once a read shows it gone, or the owner's own failure. - With no open popup the focus refusal stands. It never collapses a tree row. +- `press escape --app --window-id ` on a background window with a showing + native popup closes it only via a dismissal action (or GTK3 combo box `Press`) + and reports `delivered_verified` once gone. Web content and buttons without a + dismissal action keep the focus refusal; it never collapses a tree row. - Sandboxes are not available on Linux yet. To run agent-desktop in a container you manage yourself, see `agent-browser.dev/desktop/guides/docker-container`. ## Troubleshooting From 648c7a622d38344eadbee372796750d2a7f59a46 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:47:11 -0800 Subject: [PATCH 12/19] fix(windows): bound background Escape popup scan by deadline and node limits Replace unbounded UIA FindAll(Descendants) and FindAll(Children) in the Windows background-Escape fallback with an incremental control-view UITreeWalker using a two-property cache request and Win32 top-level window enumeration. Enforce explicit root, node, depth and child caps, consult Deadline before every step, and return a not-delivered timeout when the deadline expires. --- crates/windows/src/system/escape_popup.rs | 92 ++++++++- .../windows/src/system/escape_popup_tests.rs | 184 +++++++++++++++++- crates/windows/src/system/escape_popup_uia.rs | 174 ++++++++++++----- 3 files changed, 394 insertions(+), 56 deletions(-) diff --git a/crates/windows/src/system/escape_popup.rs b/crates/windows/src/system/escape_popup.rs index d5616eb806..8c842d0d01 100644 --- a/crates/windows/src/system/escape_popup.rs +++ b/crates/windows/src/system/escape_popup.rs @@ -8,7 +8,97 @@ //! focus and the target shows an open popup, whose owner is collapsed and read //! back; otherwise the refusal stays as it was. -use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode, KeyCombo}; +use agent_desktop_core::{AdapterError, Deadline, DeliverySemantics, ErrorCode, KeyCombo}; + +#[cfg(any(target_os = "windows", test))] +pub(super) const MAX_POPUP_ROOTS: usize = 32; +#[cfg(any(target_os = "windows", test))] +pub(super) const MAX_POPUP_NODES: usize = 600; +#[cfg(any(target_os = "windows", test))] +pub(super) const MAX_POPUP_DEPTH: usize = 32; +#[cfg(any(target_os = "windows", test))] +pub(super) const MAX_POPUP_CHILDREN: usize = 64; + +/// Outcome of a bounded background-Escape popup scan. +#[cfg(any(target_os = "windows", test))] +#[derive(Debug, PartialEq, Eq)] +pub(super) enum PopupScan { + Found(N), + None, + TimedOut, +} + +/// Incremental tree reader used by [`scan_popup_owners`] so the bounded walk +/// is tested without live UI Automation. +#[cfg(any(target_os = "windows", test))] +pub(super) trait PopupTree { + type Node; + + fn is_open_popup_owner(&self, node: &Self::Node) -> bool; + fn first_child(&self, node: &Self::Node) -> Option; + fn next_sibling(&self, node: &Self::Node) -> Option; +} + +#[cfg(any(target_os = "windows", test))] +pub(super) fn scan_timeout_error(deadline: Deadline) -> AdapterError { + deadline + .timeout_error() + .with_disposition(DeliverySemantics::not_delivered()) +} + +/// Finds the deepest open popup owner across at most `MAX_POPUP_ROOTS` roots +/// and `MAX_POPUP_NODES` nodes, consulting `deadline` before every step. +#[cfg(any(target_os = "windows", test))] +pub(super) fn scan_popup_owners( + tree: &T, + roots: Vec, + deadline: Deadline, +) -> PopupScan { + if deadline.is_expired() { + return PopupScan::TimedOut; + } + let mut visited = 0usize; + let mut best: Option<(usize, T::Node)> = None; + for root in roots.into_iter().take(MAX_POPUP_ROOTS) { + let mut stack = vec![(root, 0usize)]; + while let Some((node, depth)) = stack.pop() { + if deadline.is_expired() { + return PopupScan::TimedOut; + } + if visited >= MAX_POPUP_NODES { + return best.map_or(PopupScan::None, |(_, owner)| PopupScan::Found(owner)); + } + visited += 1; + let is_owner = tree.is_open_popup_owner(&node); + if depth < MAX_POPUP_DEPTH && visited < MAX_POPUP_NODES { + let mut children = Vec::new(); + if deadline.is_expired() { + return PopupScan::TimedOut; + } + let mut child = tree.first_child(&node); + while let Some(current) = child { + let next = if children.len() + 1 < MAX_POPUP_CHILDREN { + if deadline.is_expired() { + return PopupScan::TimedOut; + } + tree.next_sibling(¤t) + } else { + None + }; + children.push(current); + child = next; + } + for child in children.into_iter().rev() { + stack.push((child, depth + 1)); + } + } + if is_owner && best.as_ref().is_none_or(|(deepest, _)| depth >= *deepest) { + best = Some((depth, node)); + } + } + } + best.map_or(PopupScan::None, |(_, owner)| PopupScan::Found(owner)) +} /// Key delivery to `process` (A9-3: SendInput has no per-pid targeting; /// core's headed path already activated), then the popup close. diff --git a/crates/windows/src/system/escape_popup_tests.rs b/crates/windows/src/system/escape_popup_tests.rs index c474e54a5e..903dcf7184 100644 --- a/crates/windows/src/system/escape_popup_tests.rs +++ b/crates/windows/src/system/escape_popup_tests.rs @@ -1,6 +1,64 @@ -use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode, KeyCombo, Modifier}; +use std::cell::Cell; +use std::time::Duration; -use super::{is_plain_escape, opens_a_popup, refused_for_focus}; +use agent_desktop_core::{ + AdapterError, Deadline, DeliverySemantics, ErrorCode, KeyCombo, Modifier, +}; + +use super::{ + MAX_POPUP_CHILDREN, MAX_POPUP_DEPTH, MAX_POPUP_NODES, MAX_POPUP_ROOTS, PopupScan, PopupTree, + is_plain_escape, opens_a_popup, refused_for_focus, scan_popup_owners, scan_timeout_error, +}; + +struct FakeNode { + open_popup: bool, + children: Vec, +} + +struct FakeTree { + nodes: Vec, + reads: Cell, +} + +impl FakeTree { + fn new(nodes: Vec) -> Self { + Self { + nodes, + reads: Cell::new(0), + } + } +} + +impl PopupTree for FakeTree { + type Node = (usize, Option<(usize, usize)>); + + fn is_open_popup_owner(&self, node: &Self::Node) -> bool { + self.reads.set(self.reads.get() + 1); + self.nodes[node.0].open_popup + } + + fn first_child(&self, node: &Self::Node) -> Option { + self.nodes[node.0] + .children + .first() + .copied() + .map(|child| (child, Some((node.0, 0)))) + } + + fn next_sibling(&self, node: &Self::Node) -> Option { + let (parent, index) = node.1?; + let next = index + 1; + self.nodes[parent] + .children + .get(next) + .copied() + .map(|child| (child, Some((parent, next)))) + } +} + +fn root_ref(id: usize) -> (usize, Option<(usize, usize)>) { + (id, None) +} fn key(name: &str, modifiers: Vec) -> KeyCombo { KeyCombo { @@ -43,3 +101,125 @@ fn a_tree_item_or_a_group_is_never_a_popup_owner() { assert!(opens_a_popup(50011) && opens_a_popup(50003) && opens_a_popup(50031)); assert!(!opens_a_popup(50024) && !opens_a_popup(50026) && !opens_a_popup(50029)); } + +#[test] +fn popup_scan_stops_immediately_when_deadline_is_expired() { + let tree = FakeTree::new(vec![FakeNode { + open_popup: true, + children: Vec::new(), + }]); + let deadline = Deadline::after(1).expect("short deadline"); + std::thread::sleep(Duration::from_millis(5)); + assert_eq!( + scan_popup_owners(&tree, vec![root_ref(0)], deadline), + PopupScan::TimedOut + ); + assert_eq!(tree.reads.get(), 0); + let error = scan_timeout_error(deadline); + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); +} + +#[test] +fn popup_scan_respects_node_child_depth_and_root_budgets() { + let mut wide = vec![FakeNode { + open_popup: false, + children: (1..=MAX_POPUP_CHILDREN + 20).collect(), + }]; + for idx in 1..=MAX_POPUP_CHILDREN + 20 { + wide.push(FakeNode { + open_popup: idx == MAX_POPUP_CHILDREN + 20, + children: Vec::new(), + }); + } + let wide_tree = FakeTree::new(wide); + let deadline = Deadline::after(5_000).expect("budget"); + assert_eq!( + scan_popup_owners(&wide_tree, vec![root_ref(0)], deadline), + PopupScan::None + ); + assert!(wide_tree.reads.get() <= MAX_POPUP_CHILDREN + 1); + + let mut deep = Vec::new(); + for depth in 0..=MAX_POPUP_DEPTH + 4 { + deep.push(FakeNode { + open_popup: depth == MAX_POPUP_DEPTH + 4, + children: if depth < MAX_POPUP_DEPTH + 4 { + vec![depth + 1] + } else { + Vec::new() + }, + }); + } + let deep_tree = FakeTree::new(deep); + assert_eq!( + scan_popup_owners(&deep_tree, vec![root_ref(0)], deadline), + PopupScan::None + ); + assert_eq!(deep_tree.reads.get(), MAX_POPUP_DEPTH + 1); + + let many_roots: Vec = (0..MAX_POPUP_ROOTS + 5) + .map(|idx| FakeNode { + open_popup: idx == MAX_POPUP_ROOTS + 4, + children: Vec::new(), + }) + .collect(); + let root_tree = FakeTree::new(many_roots); + let roots = (0..MAX_POPUP_ROOTS + 5).map(root_ref).collect(); + assert_eq!( + scan_popup_owners(&root_tree, roots, deadline), + PopupScan::None + ); + assert_eq!(root_tree.reads.get(), MAX_POPUP_ROOTS); + + let mut dense = Vec::new(); + let mut dense_roots = Vec::new(); + for _ in 0..20usize { + let base = dense.len(); + dense_roots.push(root_ref(base)); + let children: Vec = (base + 1..base + 51).collect(); + dense.push(FakeNode { + open_popup: false, + children, + }); + for _ in 0..50 { + dense.push(FakeNode { + open_popup: false, + children: Vec::new(), + }); + } + } + let dense_tree = FakeTree::new(dense); + assert_eq!( + scan_popup_owners(&dense_tree, dense_roots, deadline), + PopupScan::None + ); + assert_eq!(dense_tree.reads.get(), MAX_POPUP_NODES); +} + +#[test] +fn popup_scan_returns_the_deepest_open_owner_within_budget() { + let tree = FakeTree::new(vec![ + FakeNode { + open_popup: false, + children: vec![1, 3], + }, + FakeNode { + open_popup: true, + children: vec![2], + }, + FakeNode { + open_popup: true, + children: Vec::new(), + }, + FakeNode { + open_popup: true, + children: Vec::new(), + }, + ]); + let deadline = Deadline::after(5_000).expect("budget"); + assert_eq!( + scan_popup_owners(&tree, vec![root_ref(0)], deadline), + PopupScan::Found((2, Some((1, 0)))) + ); +} diff --git a/crates/windows/src/system/escape_popup_uia.rs b/crates/windows/src/system/escape_popup_uia.rs index 30adcef736..f97cd0f6a4 100644 --- a/crates/windows/src/system/escape_popup_uia.rs +++ b/crates/windows/src/system/escape_popup_uia.rs @@ -1,83 +1,148 @@ -//! The UI Automation half of `escape_popup`: the popup search, the collapse and the two entry points. +//! The UI Automation half of `escape_popup`: the bounded popup search, the collapse and the entry point. -use super::{PopupScope, is_plain_escape, opens_a_popup, refused_for_focus}; +use super::{ + MAX_POPUP_ROOTS, PopupScan, PopupScope, PopupTree, is_plain_escape, opens_a_popup, + refused_for_focus, scan_popup_owners, scan_timeout_error, +}; use agent_desktop_core::{ Action, ActionResult, AdapterError, Deadline, DeliveryOutcome, InteractionPolicy, KeyCombo, ProcessIdentity, WindowInfo, }; use std::time::Duration; +use uiautomation::core::{UICacheRequest, UITreeWalker}; use uiautomation::patterns::UIExpandCollapsePattern; -use uiautomation::types::{TreeScope, UIProperty}; -use uiautomation::variants::Variant; use crate::actions::chain::{offered, poll_until, rung}; use crate::actions::mutation::{classify_success, classify_write}; +use crate::system::window::window_enum::enumerate_top_level; +use crate::system::window::window_identity::live_window_owner; +use crate::tree::automation::{automation_client, root_from_hwnd}; use crate::tree::element::UIAElement; use crate::tree::properties::property_ids::TreeProperty; -use crate::tree::properties::read_one; +use crate::tree::properties::{read_cached, read_one}; +use crate::tree::walk::cache::build_walk_cache_request; const COLLAPSE_LABEL: &str = "ExpandCollapsePattern.Collapse"; const COLLAPSE_SUGGESTION: &str = "Close the popup with the key while its window is in front."; const VERIFY_TIMEOUT: Duration = Duration::from_millis(600); const EXPANDED: i32 = 1; const COLLAPSED: i32 = 0; +const POPUP_SCAN_PROPERTIES: [TreeProperty; 2] = + [TreeProperty::ControlType, TreeProperty::ExpandCollapseState]; + +struct UiaPopupTree { + walker: UITreeWalker, + cache: UICacheRequest, +} + +impl PopupTree for UiaPopupTree { + type Node = UIAElement; + + fn is_open_popup_owner(&self, node: &UIAElement) -> bool { + let (properties, _) = read_cached(node, &POPUP_SCAN_PROPERTIES); + properties + .get(TreeProperty::ControlType) + .number() + .is_some_and(opens_a_popup) + && properties.get(TreeProperty::ExpandCollapseState).number() == Some(EXPANDED) + } + + fn first_child(&self, node: &UIAElement) -> Option { + self.walker + .get_first_child_build_cache(&node.0, &self.cache) + .ok() + .map(UIAElement::from) + } -/// The deepest expanded popup owner among the elements below `roots`: a -/// document-order search, so the last match is the innermost level. -fn deepest_popup_owner(roots: &[UIAElement]) -> Option { - let client = crate::tree::automation::automation_client().ok()?; - let expanded = client - .create_property_condition( - UIProperty::ExpandCollapseExpandCollapseState, - Variant::from(EXPANDED), - None, - ) - .ok()?; - let mut owner = None; - for root in roots { - let Ok(found) = root.0.find_all(TreeScope::Descendants, &expanded) else { - continue; - }; - for element in found { - let element = UIAElement::from(element); - if read_one(&element, TreeProperty::ControlType) - .number() - .is_some_and(opens_a_popup) - { - owner = Some(element); - } + fn next_sibling(&self, node: &UIAElement) -> Option { + self.walker + .get_next_sibling_build_cache(&node.0, &self.cache) + .ok() + .map(UIAElement::from) + } +} + +fn prefetch_roots( + roots: Vec, + cache: &UICacheRequest, + deadline: Deadline, +) -> Result, AdapterError> { + let mut cached = Vec::with_capacity(roots.len()); + for root in roots.into_iter().take(MAX_POPUP_ROOTS) { + if deadline.is_expired() { + return Err(scan_timeout_error(deadline)); } + if let Ok(element) = root.0.build_updated_cache(cache) { + cached.push(UIAElement::from(element)); + } + } + Ok(cached) +} + +/// The deepest expanded popup owner among the elements below `roots`, found by +/// a bounded, deadline-checked incremental walk over the control view. +fn deepest_popup_owner( + roots: Vec, + deadline: Deadline, +) -> Result, AdapterError> { + if deadline.is_expired() { + return Err(scan_timeout_error(deadline)); + } + let Ok(client) = automation_client() else { + return Ok(None); + }; + let Ok(walker) = client.get_control_view_walker() else { + return Ok(None); + }; + let Ok(cache) = build_walk_cache_request(&client, &POPUP_SCAN_PROPERTIES) else { + return Ok(None); + }; + let cached_roots = prefetch_roots(roots, &cache, deadline)?; + let tree = UiaPopupTree { walker, cache }; + match scan_popup_owners(&tree, cached_roots, deadline) { + PopupScan::Found(owner) => Ok(Some(owner)), + PopupScan::None => Ok(None), + PopupScan::TimedOut => Err(scan_timeout_error(deadline)), } - owner } -fn window_roots(window: &WindowInfo, deadline: Deadline) -> Vec { - crate::tree::surfaces::surface_root( +fn window_roots(window: &WindowInfo, deadline: Deadline) -> Result, AdapterError> { + if deadline.is_expired() { + return Err(scan_timeout_error(deadline)); + } + Ok(crate::tree::surfaces::surface_root( agent_desktop_core::ObservationRoot::Window(window), agent_desktop_core::SnapshotSurface::Window, deadline, ) .into_iter() - .collect() + .collect()) } -fn process_roots(process: &ProcessIdentity) -> Vec { - let Ok(client) = crate::tree::automation::automation_client() else { - return Vec::new(); - }; - let Ok(root) = client.get_root_element() else { - return Vec::new(); - }; - let Ok(condition) = client.create_property_condition( - UIProperty::ProcessId, - Variant::from(i32::try_from(u32::from(process.pid)).unwrap_or(0)), - None, - ) else { - return Vec::new(); - }; - root.find_all(TreeScope::Children, &condition) - .map(|found| found.into_iter().map(UIAElement::from).collect()) - .unwrap_or_default() +fn process_roots( + process: &ProcessIdentity, + deadline: Deadline, +) -> Result, AdapterError> { + if deadline.is_expired() { + return Err(scan_timeout_error(deadline)); + } + let mut handles = Vec::new(); + let _ = enumerate_top_level(|window| { + if live_window_owner(window.handle) == Some(process.pid) { + handles.push(window.handle); + } + handles.len() < MAX_POPUP_ROOTS + }); + let mut roots = Vec::with_capacity(handles.len()); + for handle in handles { + if deadline.is_expired() { + return Err(scan_timeout_error(deadline)); + } + if let Ok(element) = root_from_hwnd(handle as isize, deadline) { + roots.push(element); + } + } + Ok(roots) } fn collapse(owner: &UIAElement) -> Result { @@ -96,6 +161,9 @@ fn close_popup( policy: InteractionPolicy, deadline: Deadline, ) -> Result { + if deadline.is_expired() { + return Err(scan_timeout_error(deadline)); + } let mut run = || { if !collapse(owner)? { return Ok(DeliveryOutcome::NotDelivered); @@ -134,10 +202,10 @@ pub(crate) fn after_key_route( return Err(refusal); } let roots = match scope { - PopupScope::Window(window) => window_roots(window, deadline), - PopupScope::Process(process) => process_roots(process), + PopupScope::Window(window) => window_roots(window, deadline)?, + PopupScope::Process(process) => process_roots(process, deadline)?, }; - match deepest_popup_owner(&roots) { + match deepest_popup_owner(roots, deadline)? { Some(owner) => close_popup(&owner, combo, policy, deadline), None => Err(refusal), } From b81c86288ce317df2130dd8d322b7edb2e467862 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Thu, 19 Nov 2026 20:42:09 -0800 Subject: [PATCH 13/19] fix(linux): leave an Escape close unverified when the popup cannot be read after it The post-dismissal read counted the popup closed when the owner's states or the menu's states could not be read, so a background Escape reported delivered_verified without seeing the popup close. The read is now open, closed or unknown, and only a whole read with no showing popup is closed, as the Windows and macOS routes already decide. --- crates/linux/src/system/focus/escape_popup.rs | 20 +++++++++++++- .../src/system/focus/escape_popup_tests.rs | 27 ++++++++++++++++++- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/linux/src/system/focus/escape_popup.rs b/crates/linux/src/system/focus/escape_popup.rs index bfdee8bf90..3e564f03c7 100644 --- a/crates/linux/src/system/focus/escape_popup.rs +++ b/crates/linux/src/system/focus/escape_popup.rs @@ -165,7 +165,25 @@ fn still_open(bus: &SharedBus, owner: &AtspiElement, deadline: Deadline) -> Opti deadline, ) .ok()?; - Some(is_open_owner(&walk)) + popup_open(&walk) +} + +/// Whether the owner's popup is open, read after a dismissal. `None` when the +/// owner's states, a child's role or a popup child's states could not be +/// read, or the walk was cut short: a popup that could not be read never +/// counts as closed. +pub(super) fn popup_open(owner: &WalkedNode) -> Option { + if owner.children.iter().any(showing_popup) { + return Some(true); + } + let unread = bits(owner).is_none() + || owner.truncated + || owner.children.iter().any(|child| match role(child) { + Some(MENU | POPUP_MENU) => bits(child).is_none(), + Some(_) => false, + None => true, + }); + (!unread).then_some(false) } /// What the owner's reply settles. A reply of false delivered nothing, so the diff --git a/crates/linux/src/system/focus/escape_popup_tests.rs b/crates/linux/src/system/focus/escape_popup_tests.rs index 4bc351638a..b096152d47 100644 --- a/crates/linux/src/system/focus/escape_popup_tests.rs +++ b/crates/linux/src/system/focus/escape_popup_tests.rs @@ -5,7 +5,7 @@ use serde_json::json; use super::{ close_verbs, deepest_open_owner, is_focus_refusal, is_open_owner, is_plain_escape, - popup_answer, popup_outcome, + popup_answer, popup_open, popup_outcome, }; use crate::actions::action_call::resolve_verb; use crate::actions::write::mutation::{Abort, WriteKind, WriteReply, abort_error}; @@ -206,3 +206,28 @@ fn a_closed_popup_answers_the_refused_escape() { DeliverySemantics::delivered_unverified() ); } + +#[test] +fn a_popup_that_could_not_be_read_after_the_dismissal_is_not_closed() { + let menu = |states: &[u32]| node(MENU, states, Vec::new()); + assert_eq!( + popup_open(&node(COMBO_BOX, &[], vec![menu(&[SHOWING])])), + Some(true) + ); + assert_eq!( + popup_open(&node(COMBO_BOX, &[], vec![menu(&[])])), + Some(false) + ); + + let mut owner_unread = node(COMBO_BOX, &[], vec![menu(&[])]); + owner_unread.payload.node.traits.states = Field::Failed("gone".to_owned()); + assert_eq!(popup_open(&owner_unread), None); + + let mut menu_unread = menu(&[]); + menu_unread.payload.node.traits.states = Field::Failed("gone".to_owned()); + assert_eq!(popup_open(&node(COMBO_BOX, &[], vec![menu_unread])), None); + + let mut cut = node(COMBO_BOX, &[], vec![menu(&[])]); + cut.truncated = true; + assert_eq!(popup_open(&cut), None); +} From 540624c47b7c3957a15e0fe9b62867bce2b107f4 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Fri, 20 Nov 2026 15:18:17 -0800 Subject: [PATCH 14/19] fix(macos): never report no popover after a search that left list items closed The popover search keeps the items of a content container closed, which keeps list-surfaces fast on large windows, but a popover anchored to a control in a list or table row sits inside such an item. A search that left items closed and found nothing now fails as an incomplete search instead of reporting that the window shows no popover. --- crates/macos/src/tree/surfaces.rs | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rs index 5827ccc0f4..5913c0c1d1 100644 --- a/crates/macos/src/tree/surfaces.rs +++ b/crates/macos/src/tree/surfaces.rs @@ -71,15 +71,17 @@ pub(crate) fn surface_in_window( } /// The first popover in `window`, nearest the window first, through the -/// bounded search that finds an open menu. None only when every element that -/// search reads was read: a search cut at its element limit fails as not found -/// and says it is incomplete. +/// bounded search that finds an open menu. None only when the search opened +/// every element: a search cut at its element limit, or one that left the +/// items of a content container closed, fails as not found and says it is +/// incomplete. #[cfg(target_os = "macos")] fn popover_in_window( window: &AXElement, deadline: Deadline, ) -> Result, AdapterError> { - super::app_menu::find_surface_descendant_with( + let mut skipped = false; + let found = super::app_menu::find_surface_descendant_with( window.clone(), "window".into(), deadline, @@ -88,6 +90,7 @@ fn popover_in_window( return Ok((true, Vec::new())); } if !expand { + skipped = true; return Ok((false, Vec::new())); } Ok(( @@ -96,8 +99,12 @@ fn popover_in_window( )) }, ) - .map(|found| found.map(|(_, popover)| popover)) - .map_err(popover_search_error) + .map_err(popover_search_error)?; + match found { + Some((_, popover)) => Ok(Some(popover)), + None if skipped => Err(popover_search_cut()), + None => Ok(None), + } } fn popover_search_error(error: AdapterError) -> AdapterError { @@ -108,6 +115,13 @@ fn popover_search_error(error: AdapterError) -> AdapterError { if !cut { return error; } + popover_search_cut() +} + +/// A popover search that did not read every element: the items of a content +/// container are left closed to bound the search, and a popover anchored in +/// one may be there. +fn popover_search_cut() -> AdapterError { AdapterError::new( ErrorCode::ElementNotFound, "No popover among the elements the search may read; the rest was not searched", From b7c29ea327cc78df6ac5f264edc7c4a019e176b1 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:54:40 -0800 Subject: [PATCH 15/19] fix(windows): verify window and process ownership before popup collapse The background Escape popup path resolved a window by HWND alone and collapsed the discovered owner without re-checking who owned the handle. If the HWND was recycled while the original process stayed alive, it could collapse a popup in another application's window instead of failing closed. Verify WindowIdentityEvidence::verify_stored for window scopes (and live handle ownership plus process generation for process scopes) before resolving the UIA root, after resolving it, and again immediately before pattern lookup and Collapse, rejecting missing or changed identity as not_delivered instead of falling back to the focus refusal. --- crates/windows/src/system/escape_popup.rs | 75 +++++++++++ .../windows/src/system/escape_popup_tests.rs | 78 ++++++++++- crates/windows/src/system/escape_popup_uia.rs | 121 ++++++++++++------ 3 files changed, 234 insertions(+), 40 deletions(-) diff --git a/crates/windows/src/system/escape_popup.rs b/crates/windows/src/system/escape_popup.rs index 8c842d0d01..aca4866c83 100644 --- a/crates/windows/src/system/escape_popup.rs +++ b/crates/windows/src/system/escape_popup.rs @@ -46,6 +46,80 @@ pub(super) fn scan_timeout_error(deadline: Deadline) -> AdapterError { .with_disposition(DeliverySemantics::not_delivered()) } +/// Verifies that `window` still names a live handle owned by the stored process +/// generation, failing closed as not delivered when the handle is malformed, +/// lacks a process-instance token, or no longer matches its owner. +#[cfg(any(target_os = "windows", test))] +pub(super) fn verify_window_target( + window: &agent_desktop_core::WindowInfo, +) -> Result { + if window.is_process_owner() { + return Err(AdapterError::app_has_no_window(&window.app) + .with_disposition(DeliverySemantics::not_delivered())); + } + let handle = crate::system::window::window_ops::parse_handle(&window.id); + if handle.is_null() { + return Err(AdapterError::new( + ErrorCode::InvalidArgs, + "window id is not a Windows HWND-shaped id", + ) + .with_disposition(DeliverySemantics::not_delivered())); + } + let Some(evidence) = + crate::system::window::window_identity::WindowIdentityEvidence::from_info(handle, window) + else { + return Err(AdapterError::new( + ErrorCode::StaleRef, + "popup dismissal requires a process-instance token on the stored window", + ) + .with_disposition(DeliverySemantics::not_delivered())); + }; + evidence + .verify_stored() + .map_err(|error| error.with_disposition(DeliverySemantics::not_delivered()))?; + Ok(handle) +} + +/// Verifies that `process` still names the same running process generation, +/// failing closed as not delivered when the process exited or its pid recycled. +#[cfg(any(target_os = "windows", test))] +pub(super) fn verify_process_target( + process: &agent_desktop_core::ProcessIdentity, +) -> Result<(), AdapterError> { + if crate::system::process_identity::matches_instance(process.pid, &process.instance)? { + return Ok(()); + } + Err(AdapterError::new( + ErrorCode::AppUnresponsive, + "Target process instance is no longer running", + ) + .with_details(serde_json::json!({ + "pid": process.pid, + "process_instance": process.instance, + "complete": false, + "physical_delivery_started": false, + })) + .with_disposition(DeliverySemantics::not_delivered())) +} + +/// Verifies that `handle` is still owned by `process` in its stored generation. +#[cfg(any(target_os = "windows", test))] +pub(super) fn verify_process_handle( + process: &agent_desktop_core::ProcessIdentity, + handle: crate::system::window::window_enum::WindowHandle, +) -> Result<(), AdapterError> { + verify_process_target(process)?; + if crate::system::window::window_identity::live_window_owner(handle) == Some(process.pid) { + return Ok(()); + } + Err(AdapterError::new( + ErrorCode::WindowNotFound, + "The popup window is no longer owned by the target process", + ) + .with_suggestion("Run 'list-windows' to refresh window identifiers, then retry.") + .with_disposition(DeliverySemantics::not_delivered())) +} + /// Finds the deepest open popup owner across at most `MAX_POPUP_ROOTS` roots /// and `MAX_POPUP_NODES` nodes, consulting `deadline` before every step. #[cfg(any(target_os = "windows", test))] @@ -139,6 +213,7 @@ pub(crate) fn press_for_window( } /// Where a refused Escape looks for an open popup. +#[derive(Clone, Copy)] pub(crate) enum PopupScope<'a> { Window(&'a agent_desktop_core::WindowInfo), Process(&'a agent_desktop_core::ProcessIdentity), diff --git a/crates/windows/src/system/escape_popup_tests.rs b/crates/windows/src/system/escape_popup_tests.rs index 903dcf7184..506a0a7a42 100644 --- a/crates/windows/src/system/escape_popup_tests.rs +++ b/crates/windows/src/system/escape_popup_tests.rs @@ -2,12 +2,14 @@ use std::cell::Cell; use std::time::Duration; use agent_desktop_core::{ - AdapterError, Deadline, DeliverySemantics, ErrorCode, KeyCombo, Modifier, + AdapterError, Deadline, DeliverySemantics, ErrorCode, KeyCombo, Modifier, ProcessId, + ProcessIdentity, WindowInfo, }; use super::{ MAX_POPUP_CHILDREN, MAX_POPUP_DEPTH, MAX_POPUP_NODES, MAX_POPUP_ROOTS, PopupScan, PopupTree, is_plain_escape, opens_a_popup, refused_for_focus, scan_popup_owners, scan_timeout_error, + verify_process_handle, verify_process_target, verify_window_target, }; struct FakeNode { @@ -223,3 +225,77 @@ fn popup_scan_returns_the_deepest_open_owner_within_budget() { PopupScan::Found((2, Some((1, 0)))) ); } + +fn sample_window(id: &str, pid: ProcessId, instance: Option<&str>) -> WindowInfo { + WindowInfo { + id: id.to_owned(), + title: "Dialog".to_owned(), + app: "fixture".to_owned(), + pid, + process_instance: instance.map(str::to_owned), + bounds: None, + state: Default::default(), + } +} + +#[test] +fn window_target_verification_fails_closed_for_missing_or_changed_identity() { + let missing_token = sample_window("w-1", ProcessId::new(1), None); + let error = verify_window_target(&missing_token).expect_err("tokenless window must fail"); + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + + let malformed = sample_window( + "not-an-hwnd", + ProcessId::new(1), + Some("windows-proc-v1:1:1"), + ); + let error = verify_window_target(&malformed).expect_err("malformed id must fail"); + assert_eq!(error.code, ErrorCode::InvalidArgs); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + + let process_owner = sample_window("", ProcessId::new(1), Some("windows-proc-v1:1:1")); + let error = verify_window_target(&process_owner).expect_err("process-owner entry must fail"); + assert_eq!(error.code, ErrorCode::WindowNotFound); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + + let stale = sample_window( + "w-1", + ProcessId::new(9_999_999), + Some("windows-proc-v1:0:0"), + ); + let error = verify_window_target(&stale).expect_err("unowned handle must fail closed"); + assert_eq!(error.code, ErrorCode::WindowNotFound); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); +} + +#[test] +fn process_target_verification_fails_closed_for_stale_generation_or_unowned_handle() { + let stale_process = ProcessIdentity { + pid: ProcessId::new(9_999_999), + instance: "windows-proc-v1:0:0".to_owned(), + }; + let error = verify_process_target(&stale_process).expect_err("stale process must fail"); + assert_eq!(error.code, ErrorCode::AppUnresponsive); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + + let error = verify_process_handle(&stale_process, std::ptr::null_mut()) + .expect_err("stale process handle must fail"); + assert_eq!(error.code, ErrorCode::AppUnresponsive); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + + let current_pid = ProcessId::from(std::process::id()); + if let Some(token) = crate::system::process_identity::token_for_pid(current_pid) + .expect("token lookup for current process") + { + let live_process = ProcessIdentity { + pid: current_pid, + instance: token, + }; + verify_process_target(&live_process).expect("live current process must verify"); + let error = verify_process_handle(&live_process, std::ptr::null_mut()) + .expect_err("null handle is not owned by the live process"); + assert_eq!(error.code, ErrorCode::WindowNotFound); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + } +} diff --git a/crates/windows/src/system/escape_popup_uia.rs b/crates/windows/src/system/escape_popup_uia.rs index f97cd0f6a4..3a29c4e6ff 100644 --- a/crates/windows/src/system/escape_popup_uia.rs +++ b/crates/windows/src/system/escape_popup_uia.rs @@ -2,11 +2,12 @@ use super::{ MAX_POPUP_ROOTS, PopupScan, PopupScope, PopupTree, is_plain_escape, opens_a_popup, - refused_for_focus, scan_popup_owners, scan_timeout_error, + refused_for_focus, scan_popup_owners, scan_timeout_error, verify_process_handle, + verify_process_target, verify_window_target, }; use agent_desktop_core::{ - Action, ActionResult, AdapterError, Deadline, DeliveryOutcome, InteractionPolicy, KeyCombo, - ProcessIdentity, WindowInfo, + Action, ActionResult, AdapterError, Deadline, DeliveryOutcome, DeliverySemantics, ErrorCode, + InteractionPolicy, KeyCombo, ProcessIdentity, WindowInfo, }; use std::time::Duration; use uiautomation::core::{UICacheRequest, UITreeWalker}; @@ -14,7 +15,7 @@ use uiautomation::patterns::UIExpandCollapsePattern; use crate::actions::chain::{offered, poll_until, rung}; use crate::actions::mutation::{classify_success, classify_write}; -use crate::system::window::window_enum::enumerate_top_level; +use crate::system::window::window_enum::{WindowHandle, enumerate_top_level}; use crate::system::window::window_identity::live_window_owner; use crate::tree::automation::{automation_client, root_from_hwnd}; use crate::tree::element::UIAElement; @@ -30,16 +31,21 @@ const COLLAPSED: i32 = 0; const POPUP_SCAN_PROPERTIES: [TreeProperty; 2] = [TreeProperty::ControlType, TreeProperty::ExpandCollapseState]; +struct PopupNode { + handle: WindowHandle, + element: UIAElement, +} + struct UiaPopupTree { walker: UITreeWalker, cache: UICacheRequest, } impl PopupTree for UiaPopupTree { - type Node = UIAElement; + type Node = PopupNode; - fn is_open_popup_owner(&self, node: &UIAElement) -> bool { - let (properties, _) = read_cached(node, &POPUP_SCAN_PROPERTIES); + fn is_open_popup_owner(&self, node: &PopupNode) -> bool { + let (properties, _) = read_cached(&node.element, &POPUP_SCAN_PROPERTIES); properties .get(TreeProperty::ControlType) .number() @@ -47,33 +53,42 @@ impl PopupTree for UiaPopupTree { && properties.get(TreeProperty::ExpandCollapseState).number() == Some(EXPANDED) } - fn first_child(&self, node: &UIAElement) -> Option { + fn first_child(&self, node: &PopupNode) -> Option { self.walker - .get_first_child_build_cache(&node.0, &self.cache) + .get_first_child_build_cache(&node.element.0, &self.cache) .ok() - .map(UIAElement::from) + .map(|element| PopupNode { + handle: node.handle, + element: UIAElement::from(element), + }) } - fn next_sibling(&self, node: &UIAElement) -> Option { + fn next_sibling(&self, node: &PopupNode) -> Option { self.walker - .get_next_sibling_build_cache(&node.0, &self.cache) + .get_next_sibling_build_cache(&node.element.0, &self.cache) .ok() - .map(UIAElement::from) + .map(|element| PopupNode { + handle: node.handle, + element: UIAElement::from(element), + }) } } fn prefetch_roots( - roots: Vec, + roots: Vec, cache: &UICacheRequest, deadline: Deadline, -) -> Result, AdapterError> { +) -> Result, AdapterError> { let mut cached = Vec::with_capacity(roots.len()); for root in roots.into_iter().take(MAX_POPUP_ROOTS) { if deadline.is_expired() { return Err(scan_timeout_error(deadline)); } - if let Ok(element) = root.0.build_updated_cache(cache) { - cached.push(UIAElement::from(element)); + if let Ok(element) = root.element.0.build_updated_cache(cache) { + cached.push(PopupNode { + handle: root.handle, + element: UIAElement::from(element), + }); } } Ok(cached) @@ -82,9 +97,9 @@ fn prefetch_roots( /// The deepest expanded popup owner among the elements below `roots`, found by /// a bounded, deadline-checked incremental walk over the control view. fn deepest_popup_owner( - roots: Vec, + roots: Vec, deadline: Deadline, -) -> Result, AdapterError> { +) -> Result, AdapterError> { if deadline.is_expired() { return Err(scan_timeout_error(deadline)); } @@ -106,26 +121,40 @@ fn deepest_popup_owner( } } -fn window_roots(window: &WindowInfo, deadline: Deadline) -> Result, AdapterError> { +fn verify_popup_target(scope: PopupScope<'_>, handle: WindowHandle) -> Result<(), AdapterError> { + match scope { + PopupScope::Window(window) => verify_window_target(window).map(|_| ()), + PopupScope::Process(process) => verify_process_handle(process, handle), + } +} + +fn window_roots(window: &WindowInfo, deadline: Deadline) -> Result, AdapterError> { if deadline.is_expired() { return Err(scan_timeout_error(deadline)); } - Ok(crate::tree::surfaces::surface_root( - agent_desktop_core::ObservationRoot::Window(window), - agent_desktop_core::SnapshotSurface::Window, - deadline, - ) - .into_iter() - .collect()) + let handle = verify_window_target(window)?; + let element = match root_from_hwnd(handle as isize, deadline) { + Ok(element) => element, + Err(error) => { + verify_window_target(window)?; + if error.code == ErrorCode::Timeout { + return Err(error.with_disposition(DeliverySemantics::not_delivered())); + } + return Ok(Vec::new()); + } + }; + verify_window_target(window)?; + Ok(vec![PopupNode { handle, element }]) } fn process_roots( process: &ProcessIdentity, deadline: Deadline, -) -> Result, AdapterError> { +) -> Result, AdapterError> { if deadline.is_expired() { return Err(scan_timeout_error(deadline)); } + verify_process_target(process)?; let mut handles = Vec::new(); let _ = enumerate_top_level(|window| { if live_window_owner(window.handle) == Some(process.pid) { @@ -138,25 +167,38 @@ fn process_roots( if deadline.is_expired() { return Err(scan_timeout_error(deadline)); } + if verify_process_handle(process, handle).is_err() { + verify_process_target(process)?; + continue; + } if let Ok(element) = root_from_hwnd(handle as isize, deadline) { - roots.push(element); + if verify_process_handle(process, handle).is_ok() { + roots.push(PopupNode { handle, element }); + } else { + verify_process_target(process)?; + } } } Ok(roots) } -fn collapse(owner: &UIAElement) -> Result { - match owner.0.get_pattern::() { - Ok(pattern) => match pattern.collapse() { - Ok(()) => classify_success(), - Err(error) => classify_write("Collapse", COLLAPSE_LABEL, &error), - }, +fn collapse(owner: &PopupNode, scope: PopupScope<'_>) -> Result { + verify_popup_target(scope, owner.handle)?; + match owner.element.0.get_pattern::() { + Ok(pattern) => { + verify_popup_target(scope, owner.handle)?; + match pattern.collapse() { + Ok(()) => classify_success(), + Err(error) => classify_write("Collapse", COLLAPSE_LABEL, &error), + } + } Err(error) => classify_write("get_pattern", COLLAPSE_LABEL, &error), } } fn close_popup( - owner: &UIAElement, + owner: &PopupNode, + scope: PopupScope<'_>, combo: &KeyCombo, policy: InteractionPolicy, deadline: Deadline, @@ -164,12 +206,13 @@ fn close_popup( if deadline.is_expired() { return Err(scan_timeout_error(deadline)); } + verify_popup_target(scope, owner.handle)?; let mut run = || { - if !collapse(owner)? { + if !collapse(owner, scope)? { return Ok(DeliveryOutcome::NotDelivered); } let closed = poll_until(deadline, VERIFY_TIMEOUT, || { - read_one(owner, TreeProperty::ExpandCollapseState).number() == Some(COLLAPSED) + read_one(&owner.element, TreeProperty::ExpandCollapseState).number() == Some(COLLAPSED) }); Ok(DeliveryOutcome::from_delivery(true, closed)) }; @@ -206,7 +249,7 @@ pub(crate) fn after_key_route( PopupScope::Process(process) => process_roots(process, deadline)?, }; match deepest_popup_owner(roots, deadline)? { - Some(owner) => close_popup(&owner, combo, policy, deadline), + Some(owner) => close_popup(&owner, scope, combo, policy, deadline), None => Err(refusal), } } From d8b89174a986e6cb9f595a7a10f226b66d7b7790 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:21:56 -0800 Subject: [PATCH 16/19] fix: find popovers inside wide content and close a window's open surface The surface search applied one child cap to menus and popovers. A menu hangs below its anchor, but a popover can hang below a control inside a list or table row, so the popover search never reached it. The search now takes an explicit expansion policy: menu searches keep the wide-container cap, popover searches open every element within the node budget and deadline. macOS wired the Escape surface close only on the app-scoped key route, so `press escape --app X --window-id W` refused on a background window and closed nothing. The adapter now overrides press_key_for_window: core's focus gate replies first, and a plain Escape refused there closes the menu or popover the named window or its app shows, read back after the cancel. Linux's background Escape accepted only "escape"; it now accepts "esc" too, matching Windows and the key map. Verified with cargo fmt, clippy on the host packages, the agent-desktop-macos library tests, the source rule scripts and the doc literal drift tests. --- crates/linux/src/system/focus/escape_popup.rs | 3 +- .../src/system/focus/escape_popup_tests.rs | 3 + crates/macos/src/system/adapter.rs | 12 + crates/macos/src/system/key_dispatch.rs | 25 +- crates/macos/src/system/key_dispatch_tests.rs | 1 + .../macos/src/system/key_dispatch_window.rs | 94 +++++++ .../src/system/key_dispatch_window_tests.rs | 167 ++++++++++++ crates/macos/src/tree/app_menu.rs | 48 +++- .../macos/src/tree/app_menu_search_tests.rs | 246 ++++++++++++++++++ crates/macos/src/tree/app_menu_tests.rs | 173 ------------ crates/macos/src/tree/surfaces.rs | 72 +++-- skills/agent-desktop-macos/SKILL.md | 3 +- 12 files changed, 636 insertions(+), 211 deletions(-) create mode 100644 crates/macos/src/system/key_dispatch_window.rs create mode 100644 crates/macos/src/system/key_dispatch_window_tests.rs create mode 100644 crates/macos/src/tree/app_menu_search_tests.rs diff --git a/crates/linux/src/system/focus/escape_popup.rs b/crates/linux/src/system/focus/escape_popup.rs index 3e564f03c7..a5b2ec50ca 100644 --- a/crates/linux/src/system/focus/escape_popup.rs +++ b/crates/linux/src/system/focus/escape_popup.rs @@ -48,7 +48,8 @@ const DISMISS_VERBS: [&str; 3] = ["collapse", "cancel", "close"]; const GTK3_COMBO_DISMISS_VERBS: [&str; 4] = ["collapse", "cancel", "close", "press"]; pub(super) fn is_plain_escape(combo: &KeyCombo) -> bool { - combo.modifiers.is_empty() && combo.key.eq_ignore_ascii_case("escape") + combo.modifiers.is_empty() + && (combo.key.eq_ignore_ascii_case("escape") || combo.key.eq_ignore_ascii_case("esc")) } pub(super) fn is_focus_refusal(error: &AdapterError) -> bool { diff --git a/crates/linux/src/system/focus/escape_popup_tests.rs b/crates/linux/src/system/focus/escape_popup_tests.rs index b096152d47..3e13608de8 100644 --- a/crates/linux/src/system/focus/escape_popup_tests.rs +++ b/crates/linux/src/system/focus/escape_popup_tests.rs @@ -49,7 +49,10 @@ fn combo(key: &str, modifiers: Vec) -> KeyCombo { fn only_a_plain_escape_is_an_escape() { assert!(is_plain_escape(&combo("escape", Vec::new()))); assert!(is_plain_escape(&combo("Escape", Vec::new()))); + assert!(is_plain_escape(&combo("esc", Vec::new()))); + assert!(is_plain_escape(&combo("ESC", Vec::new()))); assert!(!is_plain_escape(&combo("escape", vec![Modifier::Ctrl]))); + assert!(!is_plain_escape(&combo("esc", vec![Modifier::Shift]))); assert!(!is_plain_escape(&combo("return", Vec::new()))); } diff --git a/crates/macos/src/system/adapter.rs b/crates/macos/src/system/adapter.rs index 2a63595bd3..1dea2c7bc1 100644 --- a/crates/macos/src/system/adapter.rs +++ b/crates/macos/src/system/adapter.rs @@ -226,6 +226,18 @@ impl SystemOps for MacOSAdapter { crate::system::key_dispatch::press_for_app_impl(process, combo, policy, lease.deadline()) } + /// Core's focus-gated delivery to the named window, then the close of the + /// menu or popover a refused Escape would close. + fn press_key_for_window( + &self, + window: &WindowInfo, + combo: &agent_desktop_core::KeyCombo, + policy: agent_desktop_core::InteractionPolicy, + lease: &InteractionLease, + ) -> Result { + crate::system::key_dispatch::press_for_window(self, window, combo, policy, lease) + } + fn wait_for_menu( &self, process: ProcessIdentity, diff --git a/crates/macos/src/system/key_dispatch.rs b/crates/macos/src/system/key_dispatch.rs index b6b7aff472..9d70e1db70 100644 --- a/crates/macos/src/system/key_dispatch.rs +++ b/crates/macos/src/system/key_dispatch.rs @@ -9,6 +9,11 @@ use crate::tree::AXElement; #[path = "key_dispatch_menu.rs"] mod menu; +#[path = "key_dispatch_window.rs"] +mod window; + +pub(crate) use window::press_for_window; + pub(crate) fn press_for_app_impl( process: ProcessIdentity, combo: &KeyCombo, @@ -71,19 +76,25 @@ fn semantic_step(label: &'static str) -> ActionStep { .with_verified(false) } +/// The delivered result a completed step settles: verified only when the step +/// read its own effect. +fn delivery_result(step: ActionStep) -> ActionResult { + let verified = step.verified == Some(true); + let result = ActionResult::delivered_unverified("press_key").with_steps(vec![step]); + if verified { + result.with_verified_delivery() + } else { + result + } +} + fn post_delivery_process_result( process: &ProcessIdentity, step: ActionStep, ) -> Result { crate::system::process::process_identity::require_core(process) .map_err(|error| error.with_disposition(DeliverySemantics::delivered_unverified()))?; - let verified = step.verified == Some(true); - let result = ActionResult::delivered_unverified("press_key").with_steps(vec![step]); - Ok(if verified { - result.with_verified_delivery() - } else { - result - }) + Ok(delivery_result(step)) } /// Where a key without modifiers lands as an accessibility action. diff --git a/crates/macos/src/system/key_dispatch_tests.rs b/crates/macos/src/system/key_dispatch_tests.rs index bbf1414087..4a4276d8b3 100644 --- a/crates/macos/src/system/key_dispatch_tests.rs +++ b/crates/macos/src/system/key_dispatch_tests.rs @@ -49,6 +49,7 @@ fn return_and_escape_map_to_default_and_cancel_actions() { simple_key_action(&key("escape", Vec::new())), Some("AXCancel") ); + assert_eq!(simple_key_action(&key("esc", Vec::new())), Some("AXCancel")); assert_eq!( simple_key_action(&key("return", vec![Modifier::Meta])), None diff --git a/crates/macos/src/system/key_dispatch_window.rs b/crates/macos/src/system/key_dispatch_window.rs new file mode 100644 index 0000000000..063131db45 --- /dev/null +++ b/crates/macos/src/system/key_dispatch_window.rs @@ -0,0 +1,94 @@ +//! Key delivery to a named window, and the surface close a refused Escape +//! answers. +//! +//! Core's window route needs the named window to hold the exact focus. A menu +//! or a popover a person opened can sit in a window that is not focused, and +//! the key is then refused before anything is sent. The surface still has a +//! semantic close: `AXCancel` on the menu or popover itself. The states, in +//! this order: the key route delivers, unchanged; it refuses for focus and a +//! plain Escape finds an open surface in that window or its application, which +//! is cancelled and read back; otherwise the refusal stays as it was. + +use agent_desktop_core::{ + ActionResult, AdapterError, Deadline, DeliverySemantics, InteractionLease, InteractionPolicy, + KeyCombo, SystemOps, WindowInfo, +}; + +use super::{CANCEL, delivery_result, semantic_step, simple_key_action, surface_closed}; +use crate::tree::AXElement; + +/// A key for a named window: core's focus-gated delivery, then, for a plain +/// Escape that gate refused, the close of the menu or popover showing in that +/// window or its application. +pub(crate) fn press_for_window( + adapter: &A, + window: &WindowInfo, + combo: &KeyCombo, + policy: InteractionPolicy, + lease: &InteractionLease, +) -> Result { + match agent_desktop_core::press_key_in_focused_window(adapter, window, combo, policy, lease) { + Err(refusal) if answers_with_surface_close(combo, &refusal) => { + answer_with_surface_close(refusal, || close_window_surface(window, lease.deadline())) + } + other => other, + } +} + +/// Whether a surface close answers this refusal: the key is a plain Escape, +/// which cancels the open surface, and the window focus gate refused before +/// anything was sent. +fn answers_with_surface_close(combo: &KeyCombo, refusal: &AdapterError) -> bool { + simple_key_action(combo) == Some(CANCEL) && is_focus_refusal(refusal) +} + +fn is_focus_refusal(error: &AdapterError) -> bool { + let details = error.details.as_ref(); + error.disposition == DeliverySemantics::not_delivered() + && details.and_then(|details| details["physical_delivery_started"].as_bool()) == Some(false) + && details.and_then(|details| details["check"].as_str()) == Some("window_active") +} + +/// The surface close is the answer when it closed something; with nothing open +/// the refusal stands, and an attempt that failed keeps its own error. +fn answer_with_surface_close( + refusal: AdapterError, + close: impl FnOnce() -> Result, AdapterError>, +) -> Result { + match close()? { + Some(closed) => Ok(closed), + None => Err(refusal), + } +} + +/// Closes the menu or popover the named window or its application shows, and +/// reads that it closed. `Ok(None)` when none is open, or when the surface does +/// not take a cancel action. +fn close_window_surface( + window: &WindowInfo, + deadline: Deadline, +) -> Result, AdapterError> { + let Some(surface) = open_surface_in_window(window, deadline) else { + return Ok(None); + }; + if !crate::actions::ax_helpers::try_ax_action_or_err(&surface, CANCEL, deadline)? { + return Ok(None); + } + let closed = surface_closed(&surface, deadline); + Ok(Some(delivery_result( + semantic_step(CANCEL).with_verified(closed), + ))) +} + +/// The menu or popover the named window or its application shows. A read that +/// cannot finish finds none, so the Escape keeps the refusal it had. +fn open_surface_in_window(window: &WindowInfo, deadline: Deadline) -> Option { + let pid = crate::system::process::process_identity::to_pid_t(window.pid).ok()?; + crate::tree::surfaces::transient_surface_for_window(pid, window, deadline) + .ok() + .flatten() +} + +#[cfg(test)] +#[path = "key_dispatch_window_tests.rs"] +mod tests; diff --git a/crates/macos/src/system/key_dispatch_window_tests.rs b/crates/macos/src/system/key_dispatch_window_tests.rs new file mode 100644 index 0000000000..79c7092f47 --- /dev/null +++ b/crates/macos/src/system/key_dispatch_window_tests.rs @@ -0,0 +1,167 @@ +use std::sync::atomic::{AtomicUsize, Ordering}; + +use agent_desktop_core::{ErrorCode, Modifier, ProcessId, ProcessIdentity, WindowState}; + +use super::{ + ActionResult, AdapterError, CANCEL, Deadline, DeliverySemantics, InteractionLease, + InteractionPolicy, KeyCombo, SystemOps, WindowInfo, answer_with_surface_close, + answers_with_surface_close, delivery_result, is_focus_refusal, press_for_window, semantic_step, +}; + +struct WindowRoute { + focused: Option, + dispatched: AtomicUsize, +} + +impl SystemOps for WindowRoute { + fn focused_window(&self, _deadline: Deadline) -> Result, AdapterError> { + Ok(self.focused.clone()) + } + + fn press_key_for_app( + &self, + _process: ProcessIdentity, + _combo: &KeyCombo, + _policy: InteractionPolicy, + _lease: &InteractionLease, + ) -> Result { + self.dispatched.fetch_add(1, Ordering::SeqCst); + Ok(ActionResult::delivered_unverified("press_key")) + } +} + +fn window(id: &str) -> WindowInfo { + WindowInfo { + id: id.into(), + title: format!("Window {id}"), + app: "Fixture".into(), + pid: ProcessId::new(std::process::id()), + process_instance: Some("generation-1".into()), + bounds: None, + state: WindowState::default(), + } +} + +fn route(focused: &str) -> WindowRoute { + WindowRoute { + focused: Some(window(focused)), + dispatched: AtomicUsize::new(0), + } +} + +fn key(name: &str, modifiers: Vec) -> KeyCombo { + KeyCombo { + key: name.into(), + modifiers, + } +} + +fn lease() -> InteractionLease { + InteractionLease::guarded(Deadline::standard().unwrap(), ()).unwrap() +} + +fn focus_refusal(adapter: &WindowRoute) -> AdapterError { + agent_desktop_core::press_key_in_focused_window( + adapter, + &window("w-1"), + &key("a", Vec::new()), + InteractionPolicy::headless(), + &lease(), + ) + .unwrap_err() +} + +#[test] +fn a_window_that_holds_the_focus_takes_the_key_itself() { + let adapter = route("w-1"); + let result = press_for_window( + &adapter, + &window("w-1"), + &key("escape", Vec::new()), + InteractionPolicy::headless(), + &lease(), + ) + .unwrap(); + + assert_eq!(result.action, "press_key"); + assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 1); +} + +#[test] +fn only_a_plain_escape_answers_the_window_focus_refusal() { + let refusal = focus_refusal(&route("w-2")); + + assert!(is_focus_refusal(&refusal)); + assert!(answers_with_surface_close( + &key("escape", Vec::new()), + &refusal + )); + assert!(answers_with_surface_close( + &key("esc", Vec::new()), + &refusal + )); + assert!(!answers_with_surface_close(&key("a", Vec::new()), &refusal)); + assert!(!answers_with_surface_close( + &key("escape", vec![Modifier::Shift]), + &refusal + )); +} + +#[test] +fn a_window_press_that_is_not_a_plain_escape_keeps_its_refusal() { + let adapter = route("w-2"); + let error = press_for_window( + &adapter, + &window("w-1"), + &key("a", Vec::new()), + InteractionPolicy::headless(), + &lease(), + ) + .unwrap_err(); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.details.unwrap()["check"], "window_active"); + assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 0); +} + +#[test] +fn a_closed_surface_answers_the_refused_window_escape() { + let closed = delivery_result(semantic_step(CANCEL).with_verified(true)); + assert_eq!( + closed.disposition(), + DeliverySemantics::delivered_verified() + ); + + let answer = + answer_with_surface_close(focus_refusal(&route("w-2")), || Ok(Some(closed))).unwrap(); + assert_eq!( + answer.disposition(), + DeliverySemantics::delivered_verified() + ); + + let unread = delivery_result(semantic_step(CANCEL).with_verified(false)); + let answer = + answer_with_surface_close(focus_refusal(&route("w-2")), || Ok(Some(unread))).unwrap(); + assert_eq!( + answer.disposition(), + DeliverySemantics::delivered_unverified() + ); +} + +#[test] +fn a_refused_window_escape_keeps_the_refusal_when_no_surface_is_open() { + let answer = answer_with_surface_close(focus_refusal(&route("w-2")), || Ok(None)).unwrap_err(); + + assert!(is_focus_refusal(&answer)); + assert_eq!(answer.disposition, DeliverySemantics::not_delivered()); +} + +#[test] +fn a_surface_close_that_failed_keeps_its_own_error() { + let answer = answer_with_surface_close(focus_refusal(&route("w-2")), || { + Err(AdapterError::new(ErrorCode::ActionFailed, "cancel failed")) + }) + .unwrap_err(); + + assert_eq!(answer.message, "cancel failed"); +} diff --git a/crates/macos/src/tree/app_menu.rs b/crates/macos/src/tree/app_menu.rs index 0741f36773..bc6bad32fe 100644 --- a/crates/macos/src/tree/app_menu.rs +++ b/crates/macos/src/tree/app_menu.rs @@ -225,14 +225,41 @@ fn surface_from_app( Ok(None) } +/// How far a surface search opens the elements below its root. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum ChildExpansion { + /// A menu hangs directly below the element that shows it, so an element + /// with more than `ANCHOR_CHILD_LIMIT` children is a content container and + /// stays closed: reading its items made the search grow with the content + /// of every window. + AnchorsOnly, + /// A popover can hang below a control inside a list or a table row, so + /// every element is opened. `MAX_SURFACE_NODES` and the deadline still + /// bound the search, and reaching the limit is reported as incomplete. + EveryNode, +} + +impl ChildExpansion { + fn opens(self, children: usize) -> bool { + match self { + Self::AnchorsOnly => children <= super::surface_inventory::ANCHOR_CHILD_LIMIT, + Self::EveryNode => true, + } + } +} + #[cfg(target_os = "macos")] -fn find_menu_descendant( +pub(super) fn find_menu_descendant( root: AXElement, source: String, accept: Transient, deadline: Deadline, ) -> Result, AdapterError> { - find_surface_descendant_with(root, source, deadline, |element, expand| { + let expansion = match accept { + Transient::Menu => ChildExpansion::AnchorsOnly, + Transient::MenuOrPopover => ChildExpansion::EveryNode, + }; + find_surface_descendant_with(root, source, expansion, deadline, |element, expand| { let role = surface_read::string(element, "AXRole", deadline)?; if role.as_deref() == Some("AXMenuBar") { return Ok((false, Vec::new())); @@ -256,15 +283,14 @@ fn find_menu_descendant( } /// Breadth-first search below `root` for a transient surface: a menu, or a -/// popover. Such a surface hangs directly below the element that shows it, -/// so every child is checked, but the items of a content container (more than -/// `ANCHOR_CHILD_LIMIT` children: a list, a table, a column of a browser) are -/// not opened: what lies inside an item is that item's content, and reading it -/// made the search grow with the content of every window. `inspect` gets -/// whether it may return the element's children. +/// popover. `expansion` decides how far the search opens the tree, because a +/// menu and a popover hang differently: a menu sits directly below its anchor, +/// while a popover can sit below a control inside a list or a table row. +/// `inspect` gets whether it may return the element's children. pub(super) fn find_surface_descendant_with( root: T, source: String, + expansion: ChildExpansion, deadline: Deadline, mut inspect: impl FnMut(&T, bool) -> Result<(bool, Vec), AdapterError>, ) -> Result, AdapterError> { @@ -288,7 +314,7 @@ pub(super) fn find_surface_descendant_with( if is_menu { return Ok(Some((path, element))); } - let expand_children = children.len() <= super::surface_inventory::ANCHOR_CHILD_LIMIT; + let expand_children = expansion.opens(children.len()); pending.extend( children .into_iter() @@ -338,3 +364,7 @@ fn surface_limit_error() -> AdapterError { #[cfg(test)] #[path = "app_menu_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "app_menu_search_tests.rs"] +mod search_tests; diff --git a/crates/macos/src/tree/app_menu_search_tests.rs b/crates/macos/src/tree/app_menu_search_tests.rs new file mode 100644 index 0000000000..a3ff18ef4f --- /dev/null +++ b/crates/macos/src/tree/app_menu_search_tests.rs @@ -0,0 +1,246 @@ +use super::*; +use agent_desktop_core::Deadline; + +#[test] +fn surface_node_limit_is_explicitly_incomplete() { + let error = surface_limit_error(); + + assert_eq!(error.code, ErrorCode::AppUnresponsive); + assert_eq!(error.details.expect("limit details")["complete"], false); +} + +#[test] +fn menus_beyond_eight_wrappers_remain_discoverable() { + let deadline = Deadline::after(5000).unwrap(); + for target_depth in [9, 11, 30] { + let found = find_surface_descendant_with( + 0, + "app".into(), + ChildExpansion::AnchorsOnly, + deadline, + |depth, _| Ok((*depth == target_depth, vec![depth + 1])), + ) + .unwrap(); + assert_eq!(found.map(|(_, node)| node), Some(target_depth)); + } +} + +#[test] +fn cyclic_menu_search_remains_bounded_and_explicitly_incomplete() { + let mut reads = 0; + let error = find_surface_descendant_with( + 0, + "app".into(), + ChildExpansion::AnchorsOnly, + Deadline::after(5000).unwrap(), + |node, _| { + reads += 1; + Ok((false, vec![*node])) + }, + ) + .unwrap_err(); + assert_eq!(reads, MAX_SURFACE_NODES); + assert_eq!(error.details.unwrap()["complete"], false); +} + +#[test] +fn expired_menu_search_never_reads_a_node() { + let result = find_surface_descendant_with::<()>( + (), + "app".into(), + ChildExpansion::AnchorsOnly, + Deadline::after(0).unwrap(), + |_, _| panic!("expired search must not call AX"), + ); + assert_eq!(result.unwrap_err().code, ErrorCode::Timeout); +} + +#[test] +fn incomplete_content_branch_does_not_hide_a_menu_in_a_sibling() { + let result = find_surface_descendant_with( + 0, + "app".into(), + ChildExpansion::AnchorsOnly, + Deadline::after(5000).unwrap(), + |node, _| match node { + 0 => Ok((false, vec![1, 2])), + 1 => Err(surface_limit_error()), + 2 => Ok((true, vec![])), + _ => unreachable!(), + }, + ); + assert_eq!(result.unwrap(), Some(("app/children/1".into(), 2))); +} + +#[test] +fn an_incomplete_branch_cannot_prove_menu_absence() { + let result = find_surface_descendant_with( + 0, + "app".into(), + ChildExpansion::AnchorsOnly, + Deadline::after(5000).unwrap(), + |node, _| match node { + 0 => Ok((false, vec![1, 2])), + 1 => Err(surface_limit_error()), + _ => Ok((false, vec![])), + }, + ); + assert_eq!(result.unwrap_err().details.unwrap()["complete"], false); +} + +#[test] +fn shallow_menu_precedes_unbounded_content_and_permission_errors_stay_terminal() { + let deadline = Deadline::after(5000).unwrap(); + let found = find_surface_descendant_with( + 0, + "app".into(), + ChildExpansion::AnchorsOnly, + deadline, + |node, _| match node { + 0 => Ok((false, vec![1, 2])), + 1 => Ok((false, vec![1])), + _ => Ok((true, vec![])), + }, + ); + assert_eq!(found.unwrap(), Some(("app/children/1".into(), 2))); + let denied = find_surface_descendant_with( + 0, + "app".into(), + ChildExpansion::AnchorsOnly, + deadline, + |node, _| match node { + 0 => Ok((false, vec![1, 2])), + 1 => Err(AdapterError::new(ErrorCode::PermDenied, "denied")), + _ => panic!("permission failure must stop all further AX reads"), + }, + ); + assert_eq!(denied.unwrap_err().code, ErrorCode::PermDenied); +} + +#[test] +fn invalidated_menu_roots_are_reacquired_once_and_permission_errors_are_terminal() { + use accessibility_sys::{kAXErrorAPIDisabled, kAXErrorInvalidUIElement}; + for (ax_error, failures) in [ + (kAXErrorInvalidUIElement, 1), + (kAXErrorInvalidUIElement, 2), + (kAXErrorAPIDisabled, 1), + ] { + let mut reads = 0; + let result = reacquire_once(Deadline::after(1000).unwrap(), &mut false, || { + reads += 1; + if reads <= failures { + Err(AdapterError::new(ErrorCode::PermDenied, "read failed") + .with_details(serde_json::json!({ "ax_error": ax_error }))) + } else { + Ok("fresh root") + } + }); + if ax_error == kAXErrorAPIDisabled { + assert_eq!(reads, 1); + assert_eq!(result.unwrap_err().code, ErrorCode::PermDenied); + } else { + assert_eq!(reads, 2); + if failures == 1 { + assert_eq!(result.unwrap(), "fresh root"); + } else { + let error = result.unwrap_err(); + assert_eq!(error.code, ErrorCode::AppUnresponsive); + let details = error.details.unwrap(); + assert_eq!(details["complete"], false); + assert_eq!(details["menu_root_reacquired"], true); + assert_eq!(details["retryable"], false); + assert_eq!(details["ax_error"], kAXErrorInvalidUIElement); + } + } + } +} + +#[test] +fn the_items_of_a_content_container_are_checked_but_not_opened() { + let deadline = Deadline::after(5000).unwrap(); + let wide = super::super::surface_inventory::ANCHOR_CHILD_LIMIT + 1; + let mut opened = Vec::new(); + let found = find_surface_descendant_with( + 0_usize, + "app".into(), + ChildExpansion::AnchorsOnly, + deadline, + |node, expand| { + if expand { + opened.push(*node); + } + Ok(match *node { + 0 => (false, vec![1, 2]), + 1 => (false, (100..100 + wide).collect()), + 2 => (false, vec![3]), + 3 => (true, vec![]), + item if item >= 100 => (false, vec![item * 10]), + _ => (false, vec![]), + }) + }, + ) + .unwrap(); + + assert_eq!(found.map(|(_, node)| node), Some(3)); + assert!(opened.iter().all(|node| *node < 100)); +} + +#[test] +fn a_menu_among_the_items_of_a_content_container_is_still_found() { + let deadline = Deadline::after(5000).unwrap(); + let wide = super::super::surface_inventory::ANCHOR_CHILD_LIMIT + 1; + let found = find_surface_descendant_with( + 0_usize, + "app".into(), + ChildExpansion::AnchorsOnly, + deadline, + |node, _| { + Ok(match *node { + 0 => (false, (100..100 + wide).collect()), + node => (node == 100 + wide - 1, vec![]), + }) + }, + ) + .unwrap(); + + assert_eq!(found.map(|(_, node)| node), Some(100 + wide - 1)); +} + +#[test] +fn a_popover_anchored_inside_wide_content_is_reached_only_when_every_node_is_opened() { + let deadline = Deadline::after(5000).unwrap(); + let wide = super::super::surface_inventory::ANCHOR_CHILD_LIMIT + 1; + let popover = (100 + wide - 1) * 10; + let locate = |expansion: ChildExpansion| { + find_surface_descendant_with( + 0_usize, + "app".into(), + expansion, + deadline, + |node, expand| { + Ok(match *node { + 0 => (false, vec![1]), + 1 => (false, (100..100 + wide).collect()), + item if item == popover => (true, vec![]), + item if item >= 100 => { + (false, if expand { vec![item * 10] } else { Vec::new() }) + } + _ => (false, vec![]), + }) + }, + ) + .unwrap() + }; + + assert_eq!( + locate(ChildExpansion::EveryNode), + Some(( + format!("app/children/0/children/{}/children/0", wide - 1), + popover + )) + ); + assert_eq!( + locate(ChildExpansion::AnchorsOnly).map(|(_, node)| node), + None + ); +} diff --git a/crates/macos/src/tree/app_menu_tests.rs b/crates/macos/src/tree/app_menu_tests.rs index 6b32e3e5b5..7c53937270 100644 --- a/crates/macos/src/tree/app_menu_tests.rs +++ b/crates/macos/src/tree/app_menu_tests.rs @@ -221,176 +221,3 @@ fn incomplete_selected_menu_children_cannot_produce_an_empty_or_partial_inventor .unwrap_err(); assert_eq!(error.details.unwrap()["complete"], false); } - -#[test] -fn surface_node_limit_is_explicitly_incomplete() { - let error = surface_limit_error(); - - assert_eq!(error.code, ErrorCode::AppUnresponsive); - assert_eq!(error.details.expect("limit details")["complete"], false); -} - -#[test] -fn menus_beyond_eight_wrappers_remain_discoverable() { - let deadline = Deadline::after(5000).unwrap(); - for target_depth in [9, 11, 30] { - let found = find_surface_descendant_with(0, "app".into(), deadline, |depth, _| { - Ok((*depth == target_depth, vec![depth + 1])) - }) - .unwrap(); - assert_eq!(found.map(|(_, node)| node), Some(target_depth)); - } -} - -#[test] -fn cyclic_menu_search_remains_bounded_and_explicitly_incomplete() { - let mut reads = 0; - let error = find_surface_descendant_with( - 0, - "app".into(), - Deadline::after(5000).unwrap(), - |node, _| { - reads += 1; - Ok((false, vec![*node])) - }, - ) - .unwrap_err(); - assert_eq!(reads, MAX_SURFACE_NODES); - assert_eq!(error.details.unwrap()["complete"], false); -} - -#[test] -fn expired_menu_search_never_reads_a_node() { - let result = find_surface_descendant_with::<()>( - (), - "app".into(), - Deadline::after(0).unwrap(), - |_, _| panic!("expired search must not call AX"), - ); - assert_eq!(result.unwrap_err().code, ErrorCode::Timeout); -} - -#[test] -fn incomplete_content_branch_does_not_hide_a_menu_in_a_sibling() { - let result = find_surface_descendant_with( - 0, - "app".into(), - Deadline::after(5000).unwrap(), - |node, _| match node { - 0 => Ok((false, vec![1, 2])), - 1 => Err(surface_limit_error()), - 2 => Ok((true, vec![])), - _ => unreachable!(), - }, - ); - assert_eq!(result.unwrap(), Some(("app/children/1".into(), 2))); -} - -#[test] -fn an_incomplete_branch_cannot_prove_menu_absence() { - let result = find_surface_descendant_with( - 0, - "app".into(), - Deadline::after(5000).unwrap(), - |node, _| match node { - 0 => Ok((false, vec![1, 2])), - 1 => Err(surface_limit_error()), - _ => Ok((false, vec![])), - }, - ); - assert_eq!(result.unwrap_err().details.unwrap()["complete"], false); -} - -#[test] -fn shallow_menu_precedes_unbounded_content_and_permission_errors_stay_terminal() { - let deadline = Deadline::after(5000).unwrap(); - let found = find_surface_descendant_with(0, "app".into(), deadline, |node, _| match node { - 0 => Ok((false, vec![1, 2])), - 1 => Ok((false, vec![1])), - _ => Ok((true, vec![])), - }); - assert_eq!(found.unwrap(), Some(("app/children/1".into(), 2))); - let denied = find_surface_descendant_with(0, "app".into(), deadline, |node, _| match node { - 0 => Ok((false, vec![1, 2])), - 1 => Err(AdapterError::new(ErrorCode::PermDenied, "denied")), - _ => panic!("permission failure must stop all further AX reads"), - }); - assert_eq!(denied.unwrap_err().code, ErrorCode::PermDenied); -} - -#[test] -fn invalidated_menu_roots_are_reacquired_once_and_permission_errors_are_terminal() { - use accessibility_sys::{kAXErrorAPIDisabled, kAXErrorInvalidUIElement}; - for (ax_error, failures) in [ - (kAXErrorInvalidUIElement, 1), - (kAXErrorInvalidUIElement, 2), - (kAXErrorAPIDisabled, 1), - ] { - let mut reads = 0; - let result = reacquire_once(Deadline::after(1000).unwrap(), &mut false, || { - reads += 1; - if reads <= failures { - Err(AdapterError::new(ErrorCode::PermDenied, "read failed") - .with_details(serde_json::json!({ "ax_error": ax_error }))) - } else { - Ok("fresh root") - } - }); - if ax_error == kAXErrorAPIDisabled { - assert_eq!(reads, 1); - assert_eq!(result.unwrap_err().code, ErrorCode::PermDenied); - } else { - assert_eq!(reads, 2); - if failures == 1 { - assert_eq!(result.unwrap(), "fresh root"); - } else { - let error = result.unwrap_err(); - assert_eq!(error.code, ErrorCode::AppUnresponsive); - let details = error.details.unwrap(); - assert_eq!(details["complete"], false); - assert_eq!(details["menu_root_reacquired"], true); - assert_eq!(details["retryable"], false); - assert_eq!(details["ax_error"], kAXErrorInvalidUIElement); - } - } - } -} - -#[test] -fn the_items_of_a_content_container_are_checked_but_not_opened() { - let deadline = Deadline::after(5000).unwrap(); - let wide = super::super::surface_inventory::ANCHOR_CHILD_LIMIT + 1; - let mut opened = Vec::new(); - let found = find_surface_descendant_with(0_usize, "app".into(), deadline, |node, expand| { - if expand { - opened.push(*node); - } - Ok(match *node { - 0 => (false, vec![1, 2]), - 1 => (false, (100..100 + wide).collect()), - 2 => (false, vec![3]), - 3 => (true, vec![]), - item if item >= 100 => (false, vec![item * 10]), - _ => (false, vec![]), - }) - }) - .unwrap(); - - assert_eq!(found.map(|(_, node)| node), Some(3)); - assert!(opened.iter().all(|node| *node < 100)); -} - -#[test] -fn a_menu_among_the_items_of_a_content_container_is_still_found() { - let deadline = Deadline::after(5000).unwrap(); - let wide = super::super::surface_inventory::ANCHOR_CHILD_LIMIT + 1; - let found = find_surface_descendant_with(0_usize, "app".into(), deadline, |node, _| { - Ok(match *node { - 0 => (false, (100..100 + wide).collect()), - node => (node == 100 + wide - 1, vec![]), - }) - }) - .unwrap(); - - assert_eq!(found.map(|(_, node)| node), Some(100 + wide - 1)); -} diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rs index 5913c0c1d1..cd575bff70 100644 --- a/crates/macos/src/tree/surfaces.rs +++ b/crates/macos/src/tree/surfaces.rs @@ -1,5 +1,5 @@ use super::{AXElement, properties::element::element_for_pid, surface_read}; -use agent_desktop_core::{AdapterError, Deadline, ErrorCode, SnapshotSurface}; +use agent_desktop_core::{AdapterError, Deadline, ErrorCode, SnapshotSurface, WindowInfo}; #[cfg(target_os = "macos")] pub(crate) fn focused_surface_for_pid( @@ -35,6 +35,47 @@ pub(crate) fn transient_surface_for_pid( }) } +/// The menu or popover that belongs to `window`, read in one bounded pass: a +/// surface inside that window first, then the application's own surfaces, so a +/// surface in a window that is not focused is still found. +#[cfg(target_os = "macos")] +pub(crate) fn transient_surface_for_window( + pid: i32, + window: &WindowInfo, + deadline: Deadline, +) -> Result, AdapterError> { + let identity = crate::system::process::process_identity::ProcessIdentity::capture(pid)? + .ok_or_else(|| AdapterError::stale_ref_because("Application exited"))?; + super::app_menu::observe(identity, deadline, || { + match surface_inside_window(window, deadline)? { + Some(surface) => Ok(Some(surface)), + None => super::app_menu::open_transient_surface(pid, deadline), + } + }) +} + +/// The menu or popover inside `window`, searched at any depth because a +/// popover hangs below the control that raised it. A window whose accessibility +/// element cannot be read is left to the application's own surfaces. +#[cfg(target_os = "macos")] +fn surface_inside_window( + window: &WindowInfo, + deadline: Deadline, +) -> Result, AdapterError> { + let Ok(owner) = crate::system::window::window_resolve::window_element_for_info_with_deadline( + window, deadline, + ) else { + return Ok(None); + }; + Ok(super::app_menu::find_menu_descendant( + owner, + "window".into(), + super::app_menu::Transient::MenuOrPopover, + deadline, + )? + .map(|(_, surface)| surface)) +} + #[cfg(target_os = "macos")] fn first_child_with_role_or_subrole( pid: i32, @@ -70,29 +111,25 @@ pub(crate) fn surface_in_window( } } -/// The first popover in `window`, nearest the window first, through the -/// bounded search that finds an open menu. None only when the search opened -/// every element: a search cut at its element limit, or one that left the -/// items of a content container closed, fails as not found and says it is +/// The first popover in `window`, nearest the window first, through a search +/// that opens every element below it, so a popover anchored to a control inside +/// a list or a table row is reached. None only when the search read every +/// element: one cut at its element limit fails as not found and says it is /// incomplete. #[cfg(target_os = "macos")] fn popover_in_window( window: &AXElement, deadline: Deadline, ) -> Result, AdapterError> { - let mut skipped = false; let found = super::app_menu::find_surface_descendant_with( window.clone(), "window".into(), + super::app_menu::ChildExpansion::EveryNode, deadline, - |element, expand| { + |element, _| { if role_or_subrole_matches(element, "AXPopover", deadline)? { return Ok((true, Vec::new())); } - if !expand { - skipped = true; - return Ok((false, Vec::new())); - } Ok(( false, surface_read::elements(element, "AXChildren", deadline)?, @@ -100,11 +137,7 @@ fn popover_in_window( }, ) .map_err(popover_search_error)?; - match found { - Some((_, popover)) => Ok(Some(popover)), - None if skipped => Err(popover_search_cut()), - None => Ok(None), - } + Ok(found.map(|(_, popover)| popover)) } fn popover_search_error(error: AdapterError) -> AdapterError { @@ -118,13 +151,12 @@ fn popover_search_error(error: AdapterError) -> AdapterError { popover_search_cut() } -/// A popover search that did not read every element: the items of a content -/// container are left closed to bound the search, and a popover anchored in -/// one may be there. +/// A popover search that did not read every element: it reached its element +/// limit first, and a popover may sit below that cut. fn popover_search_cut() -> AdapterError { AdapterError::new( ErrorCode::ElementNotFound, - "No popover among the elements the search may read; the rest was not searched", + "No popover among the elements the search read; the search reached its element limit first", ) .with_details(serde_json::json!({ "kind": "popover_search_limit", diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.md index 9b4f57a2e5..b367774690 100644 --- a/skills/agent-desktop-macos/SKILL.md +++ b/skills/agent-desktop-macos/SKILL.md @@ -43,7 +43,8 @@ may report `unknown` when consent would require a prompt. An app without an ordinary window may still expose process-owned surfaces. Inspect `supported_surfaces` rather than assuming every surface exists. - `agent-desktop press escape --app ` closes an open menu or popover with its - cancel action when no focused element takes Escape, and reads that it closed. A + cancel action when no focused element takes Escape, and reads that it closed; + with `--window-id ` it closes the surface that window or the app shows. A popover can appear a moment after the click that opens it: read it with `snapshot --app --surface popover`. - Headless menu-opening and dialog-opening actions can refuse before delivery. From 78b2f8eae39276fce8de905f8b6c2a8edf6ed553 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:30:48 -0800 Subject: [PATCH 17/19] fix: trim supported_surfaces doc to keep the windows adapter under the file-size cap The doc comment grew the file to 404 lines, past the 400-line limit, so the file-size gate failed. Condensing it to the same text the reliability-16 branch uses keeps this adapter at 397 lines and makes that region merge cleanly. --- crates/windows/src/system/adapter.rs | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/crates/windows/src/system/adapter.rs b/crates/windows/src/system/adapter.rs index a0cc60542a..4366f21ebd 100644 --- a/crates/windows/src/system/adapter.rs +++ b/crates/windows/src/system/adapter.rs @@ -104,17 +104,10 @@ impl SystemOps for WindowsAdapter { true } - /// The surfaces this adapter can observe: a named window, the focused - /// window, a Chromium modal-as-sheet, an open application menu, and the - /// shell kinds the shell-surface resolver reaches on this build. Core - /// validates the requested surface against this list before the adapter - /// is ever called (the mirror of macOS `supported_surfaces`), so a kind - /// advertised here always has a matching `surface_root` arm - advertising - /// without an arm would convert the old emit/advertise asymmetry into an - /// advertise/resolve one. `quick-settings` is deliberately absent: this - /// build carries the quick actions inside the Action Center, so the kind - /// refuses in core with the standard shape instead of pretending it can - /// root. + /// The surfaces this adapter can observe. Core validates a requested + /// surface against this list before calling the adapter, so every kind here + /// has a matching `surface_root` arm; `quick-settings` is absent because + /// this build carries the quick actions inside the Action Center. fn supported_surfaces(&self) -> Vec { vec![ SnapshotSurface::Window, From b5a86b949ea285b5c65246ebd3bd833e0941e7f1 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:10:42 -0800 Subject: [PATCH 18/19] fix(linux,macos): preserve process generation through Escape surface fallback Keep the original ProcessIdentity across Linux and macOS Escape fallbacks instead of dropping to a bare PID or capturing a fresh generation. Revalidate the process instance and element ownership before discovery and immediately before DoAction or AXCancel, and propagate macOS window identity errors instead of falling back to application-wide surface discovery. --- crates/linux/src/actions/mod.rs | 2 +- crates/linux/src/system/focus/escape_popup.rs | 189 ++++++++---- .../system/focus/escape_popup_stage_tests.rs | 283 ++++++++++++++++++ .../src/system/focus/escape_popup_world.rs | 147 +++++++++ crates/linux/src/system/focus/key_dispatch.rs | 10 +- crates/macos/src/system/key_dispatch.rs | 82 +++-- crates/macos/src/system/key_dispatch_tests.rs | 26 +- .../macos/src/system/key_dispatch_window.rs | 114 ++++++- .../src/system/key_dispatch_window_tests.rs | 234 ++++++++++++++- crates/macos/src/tree/app_menu.rs | 11 +- crates/macos/src/tree/surfaces.rs | 36 +-- 11 files changed, 1003 insertions(+), 131 deletions(-) create mode 100644 crates/linux/src/system/focus/escape_popup_stage_tests.rs create mode 100644 crates/linux/src/system/focus/escape_popup_world.rs diff --git a/crates/linux/src/actions/mod.rs b/crates/linux/src/actions/mod.rs index 841aefdc6e..8700df6df1 100644 --- a/crates/linux/src/actions/mod.rs +++ b/crates/linux/src/actions/mod.rs @@ -10,7 +10,7 @@ pub(crate) mod live; pub(crate) mod native_menu; pub(crate) mod physical_target; mod popup_verify; -mod process_check; +pub(crate) mod process_check; pub(crate) mod scroll; pub(crate) mod select; pub(crate) mod toggle_state; diff --git a/crates/linux/src/system/focus/escape_popup.rs b/crates/linux/src/system/focus/escape_popup.rs index a5b2ec50ca..d4b86ec6fb 100644 --- a/crates/linux/src/system/focus/escape_popup.rs +++ b/crates/linux/src/system/focus/escape_popup.rs @@ -12,33 +12,38 @@ //! owner exists in the target window; otherwise the refusal stays as it was. //! The owner's reply is the answer, so a rejected action delivers nothing and //! an owner that does not answer leaves the delivery uncertain; the key -//! route's refusal replaces neither. +//! route's refusal replaces neither. Every stage re-checks that the element +//! still belongs to the original process instance, so a recycled process id +//! never receives the dismissal. use std::time::Duration; use agent_desktop_core::{ - Action, ActionResult, AdapterError, ChainRung, Deadline, DeliveryOutcome, KeyCombo, - StepMechanism, WindowInfo, + Action, ActionResult, AdapterError, ChainRung, Deadline, DeliveryOutcome, DeliverySemantics, + KeyCombo, ProcessIdentity, StepMechanism, WindowInfo, }; -use crate::actions::action_call::{do_action, resolve_verb}; +use crate::actions::action_call::resolve_verb; use crate::actions::chain::run_semantic_chain; -use crate::actions::context::Target; +use crate::actions::process_check::{judge_frame, judge_owner}; use crate::actions::write::mutation::WriteReply; +use crate::system::process::process_facts; +use crate::system::process::process_lookup::Lookup; use crate::system::window::window_id; -use crate::system::window::window_ops::windows_of_process; -use crate::system::{REGISTRY_ROOT_PATH, SharedBus, within}; -use crate::tree::menu::observe_menu::{rooted, scan_walk_structure}; -use crate::tree::properties::toolkit_trust::{ToolkitKind, kind, read_toolkit}; +use crate::system::{SharedBus, owner_process_id, within}; +use crate::tree::menu::observe_menu::rooted; +use crate::tree::properties::toolkit_trust::ToolkitKind; use crate::tree::vocabulary::role_numbers::{ COMBO_BOX, MENU, POPUP_MENU, PUSH_BUTTON, PUSH_BUTTON_MENU, TOGGLE_BUTTON, is_web_document, }; use crate::tree::vocabulary::state_bits::{HAS_POPUP, SHOWING, StateBits}; -use crate::tree::{AtspiElement, ObservedRead, WalkedNode, get_live_actions}; +use crate::tree::{AtspiElement, ObservedRead, WalkedNode}; + +#[path = "escape_popup_world.rs"] +mod world; + +use world::PopupWorld; -const SCAN_NODES: usize = 600; -const OWNER_NODES: usize = 64; -const POPUP_CONTAINER_CHILDREN: usize = 16; const CLOSE_SETTLE: Duration = Duration::from_millis(1000); const CLOSE_STEP: Duration = Duration::from_millis(50); const FOCUS_CHECKS: [&str; 2] = ["window_active", "exact_window_focus"]; @@ -128,45 +133,88 @@ pub(super) fn deepest_open_owner<'a>( } } -fn frames_of( - bus: &SharedBus, +fn not_delivered(error: AdapterError) -> AdapterError { + error.with_disposition(DeliverySemantics::not_delivered()) +} + +/// Refuses a live process table that no longer names the original instance, +/// so a recycled process id never receives the dismissal. +fn verify_live_process(expected: &ProcessIdentity, live: &Lookup) -> Result<(), AdapterError> { + judge_frame(expected, expected.pid.get(), live).map_err(not_delivered) +} + +/// Refuses a window recorded for another process or for another generation of +/// the target process. +fn verify_window_identity( + expected: &ProcessIdentity, + window: &WindowInfo, +) -> Result<(), AdapterError> { + let same_instance = window.process_instance.as_deref() == Some(expected.instance.as_str()); + if window.pid == expected.pid && same_instance { + return Ok(()); + } + Err(not_delivered(AdapterError::stale_ref_because( + "The window no longer belongs to the target process instance, so no popup was closed", + ))) +} + +fn verify_element_pid( + expected: &ProcessIdentity, pid: u32, + live: &Lookup, +) -> Result<(), AdapterError> { + judge_frame(expected, pid, live).map_err(not_delivered) +} + +/// Refuses an element whose frame or address names another process, or whose +/// bus name the bus daemon now reports for another process. +fn verify_element_owner( + bus: &SharedBus, + expected: &ProcessIdentity, + element: &AtspiElement, + deadline: Deadline, +) -> Result<(), AdapterError> { + let live = process_facts::lookup(expected.pid.get()); + let frame_pid = element.frame().map_or(element.pid(), AtspiElement::pid); + verify_element_pid(expected, frame_pid, &live)?; + verify_element_pid(expected, element.pid(), &live)?; + let connection = bus.get(deadline).map_err(not_delivered)?; + let owner = within(deadline, async { + Ok(owner_process_id(connection.inner(), element.bus_name()) + .await + .map_err(Some)) + }) + .map_err(not_delivered)?; + judge_owner(expected.pid.get(), owner).map_err(not_delivered)?; + verify_live_process(expected, &process_facts::lookup(expected.pid.get())) +} + +fn frames_of( + world: &impl PopupWorld, + process: &ProcessIdentity, window: Option<&WindowInfo>, deadline: Deadline, ) -> Result, AdapterError> { let windows = match window { Some(window) => vec![window.clone()], - None => windows_of_process(bus, pid, deadline)?.0, + None => { + let windows = world.windows(process.pid.get(), deadline)?; + verify_live_process(process, &world.live(process.pid.get()))?; + for window in &windows { + verify_window_identity(process, window)?; + } + windows + } }; - let mut frames = Vec::new(); - for window in windows { - let (name, path) = window_id::decode(&window.id)?; - frames.push(rooted(&AtspiElement::new(name, path, pid))); - } - Ok(frames) + windows + .into_iter() + .map(|window| frame_of(&window, process.pid.get())) + .collect() } -fn owner_toolkit(bus: &SharedBus, owner: &AtspiElement, deadline: Deadline) -> ToolkitKind { - let Ok(connection) = bus.get(deadline) else { - return ToolkitKind::Other; - }; - let app = AtspiElement::new(owner.bus_name(), REGISTRY_ROOT_PATH, owner.pid()); - match within(deadline, read_toolkit(connection.inner(), &app)) { - Ok(toolkit) => kind(&toolkit), - Err(_) => ToolkitKind::Other, - } -} - -fn still_open(bus: &SharedBus, owner: &AtspiElement, deadline: Deadline) -> Option { - let walk = scan_walk_structure( - bus, - &rooted(owner), - OWNER_NODES, - Some(POPUP_CONTAINER_CHILDREN), - deadline, - ) - .ok()?; - popup_open(&walk) +fn frame_of(window: &WindowInfo, pid: u32) -> Result { + let (name, path) = window_id::decode(&window.id)?; + Ok(rooted(&AtspiElement::new(name, path, pid))) } /// Whether the owner's popup is open, read after a dismissal. `None` when the @@ -216,20 +264,31 @@ pub(super) fn popup_answer( /// result, the popup attempt's own failure included, is the answer. pub(super) fn close_open_popup( bus: &SharedBus, - pid: u32, + process: &ProcessIdentity, window: Option<&WindowInfo>, combo: &KeyCombo, deadline: Deadline, ) -> Result, AdapterError> { + close_popup_with(bus, process, window, combo, deadline) +} + +fn close_popup_with( + world: &impl PopupWorld, + process: &ProcessIdentity, + window: Option<&WindowInfo>, + combo: &KeyCombo, + deadline: Deadline, +) -> Result, AdapterError> { + verify_live_process(process, &world.live(process.pid.get()))?; + if let Some(window) = window { + verify_window_identity(process, window)?; + } let mut best: Option<(usize, AtspiElement, Option)> = None; - for frame in frames_of(bus, pid, window, deadline)? { - let walk = scan_walk_structure( - bus, - &frame, - SCAN_NODES, - Some(POPUP_CONTAINER_CHILDREN), - deadline, - )?; + for frame in frames_of(world, process, window, deadline).map_err(not_delivered)? { + world + .verify_owner(process, &frame, deadline) + .map_err(not_delivered)?; + let walk = world.walk(&frame, deadline).map_err(not_delivered)?; let mut found = None; deepest_open_owner(&walk, 0, &mut found); if let Some((depth, node)) = found @@ -241,25 +300,25 @@ pub(super) fn close_open_popup( let Some((_, owner, owner_role)) = best else { return Ok(None); }; - let verbs = close_verbs(owner_role, owner_toolkit(bus, &owner, deadline)); - let handle = owner.clone().into_native_handle(); - let names = get_live_actions(bus, &handle, deadline)?.unwrap_or_default(); + world + .verify_owner(process, &owner, deadline) + .map_err(not_delivered)?; + let (names, verbs) = world + .verbs(&owner, owner_role, deadline) + .map_err(not_delivered)?; if resolve_verb(&names, verbs).is_none() { return Ok(None); } let run = || { - let target = Target { - bus, - handle: &handle, - element: &owner, - deadline, - }; - let reply = do_action(&target, &names, verbs)?; + world + .verify_owner(process, &owner, deadline) + .map_err(not_delivered)?; + let reply = world.dismiss(&owner, &names, verbs, deadline)?; Ok(popup_outcome(reply, || { deadline.poll_until( CLOSE_SETTLE, CLOSE_STEP, - || still_open(bus, &owner, deadline).map(|open| !open), + || world.popup_still_open(&owner, deadline).map(|open| !open), |closed| *closed == Some(true), ) })) @@ -279,6 +338,10 @@ pub(super) fn close_open_popup( .map(Some) } +#[cfg(test)] +#[path = "escape_popup_stage_tests.rs"] +mod stage_tests; + #[cfg(test)] #[path = "escape_popup_tests.rs"] mod tests; diff --git a/crates/linux/src/system/focus/escape_popup_stage_tests.rs b/crates/linux/src/system/focus/escape_popup_stage_tests.rs new file mode 100644 index 0000000000..9a59cdd85b --- /dev/null +++ b/crates/linux/src/system/focus/escape_popup_stage_tests.rs @@ -0,0 +1,283 @@ +use std::cell::RefCell; +use std::collections::VecDeque; + +use agent_desktop_core::{ + AdapterError, Deadline, DeliverySemantics, ErrorCode, KeyCombo, ProcessId, ProcessIdentity, + WindowInfo, +}; + +use super::world::PopupWorld; +use super::{close_popup_with, verify_live_process, verify_window_identity}; +use crate::actions::write::mutation::WriteReply; +use crate::system::process::process_facts::ProcessFacts; +use crate::system::process::process_lookup::Lookup; +use crate::system::window::window_id; +use crate::tree::test_support::helpers::{read_of, words}; +use crate::tree::vocabulary::role_numbers::{COMBO_BOX, FRAME, MENU}; +use crate::tree::vocabulary::state_bits::SHOWING; +use crate::tree::{AtspiElement, Field, ObservedRead, WalkedNode}; + +const PID: u32 = 4242; +const INSTANCE: &str = "boot:100"; + +fn node( + role: u32, + states: &[u32], + children: Vec>, +) -> WalkedNode { + let mut read = read_of(role, "n", &[]); + read.node.traits.states = Field::Present(words(states)); + WalkedNode { + payload: read, + children, + truncated: false, + child_count: None, + source_index: 0, + in_web_document: false, + } +} + +fn facts(instance: &str) -> ProcessFacts { + ProcessFacts { + executable: None, + comm: "app".to_owned(), + exe_basename: None, + instance: instance.to_owned(), + } +} + +fn process() -> ProcessIdentity { + ProcessIdentity::new(ProcessId::new(PID), INSTANCE) +} + +fn deadline() -> Deadline { + Deadline::standard().expect("deadline") +} + +fn escape() -> KeyCombo { + KeyCombo { + key: "escape".to_owned(), + modifiers: Vec::new(), + } +} + +fn window(instance: Option<&str>) -> WindowInfo { + WindowInfo { + id: window_id::encode(":1.42", "/org/a11y/atspi/accessible/root").expect("window id"), + title: "target".into(), + app: "app".into(), + pid: ProcessId::new(PID), + process_instance: instance.map(str::to_owned), + bounds: None, + state: Default::default(), + } +} + +fn popup_frame() -> WalkedNode { + node( + FRAME, + &[SHOWING], + vec![node( + COMBO_BOX, + &[], + vec![node(MENU, &[SHOWING], Vec::new())], + )], + ) +} + +fn refusal() -> AdapterError { + AdapterError::stale_ref_because("another owner") +} + +struct World { + live: RefCell>, + windows: Result, AdapterError>, + owner_checks: RefCell>>, + walk: WalkedNode, + calls: RefCell>, +} + +impl World { + fn matched() -> Self { + Self { + live: RefCell::new(VecDeque::new()), + windows: Ok(vec![window(Some(INSTANCE))]), + owner_checks: RefCell::new(VecDeque::new()), + walk: popup_frame(), + calls: RefCell::new(Vec::new()), + } + } + + fn record(&self, name: &'static str) { + self.calls.borrow_mut().push(name); + } + + fn count(&self, name: &str) -> usize { + self.calls + .borrow() + .iter() + .filter(|call| **call == name) + .count() + } +} + +impl PopupWorld for World { + fn live(&self, _pid: u32) -> Lookup { + self.live + .borrow_mut() + .pop_front() + .unwrap_or_else(|| Lookup::Found(facts(INSTANCE))) + } + + fn windows(&self, _pid: u32, _deadline: Deadline) -> Result, AdapterError> { + self.record("windows"); + self.windows.clone() + } + + fn verify_owner( + &self, + _expected: &ProcessIdentity, + _element: &AtspiElement, + _deadline: Deadline, + ) -> Result<(), AdapterError> { + self.record("owner"); + self.owner_checks.borrow_mut().pop_front().unwrap_or(Ok(())) + } + + fn walk( + &self, + _frame: &AtspiElement, + _deadline: Deadline, + ) -> Result, AdapterError> { + self.record("walk"); + Ok(self.walk.clone()) + } + + fn verbs( + &self, + _owner: &AtspiElement, + _role: Option, + _deadline: Deadline, + ) -> Result<(Vec, &'static [&'static str]), AdapterError> { + Ok((vec!["collapse".to_owned()], &["collapse"])) + } + + fn dismiss( + &self, + _owner: &AtspiElement, + _names: &[String], + _verbs: &'static [&'static str], + _deadline: Deadline, + ) -> Result { + self.record("dismiss"); + Ok(WriteReply::Done) + } + + fn popup_still_open(&self, _owner: &AtspiElement, _deadline: Deadline) -> Option { + Some(false) + } +} + +#[test] +fn a_live_process_must_keep_its_instance() { + let expected = process(); + assert!(verify_live_process(&expected, &Lookup::Found(facts(INSTANCE))).is_ok()); + for live in [ + Lookup::Gone, + Lookup::Unreadable, + Lookup::Found(facts("boot:other")), + ] { + let error = verify_live_process(&expected, &live).expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + } +} + +#[test] +fn a_window_must_carry_the_original_instance() { + let expected = process(); + assert!(verify_window_identity(&expected, &window(Some(INSTANCE))).is_ok()); + for instance in [None, Some("recycled")] { + let error = verify_window_identity(&expected, &window(instance)).expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + } +} + +#[test] +fn a_process_that_changed_before_discovery_fails_closed() { + for live in [ + Lookup::Gone, + Lookup::Unreadable, + Lookup::Found(facts("boot:other")), + ] { + let world = World::matched(); + *world.live.borrow_mut() = VecDeque::from([live]); + let error = + close_popup_with(&world, &process(), None, &escape(), deadline()).expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(world.count("windows"), 0); + assert_eq!(world.count("owner"), 0); + assert_eq!(world.count("dismiss"), 0); + } +} + +#[test] +fn a_failed_discovery_is_not_a_delivery() { + let mut world = World::matched(); + world.windows = Err(AdapterError::new(ErrorCode::ActionFailed, "unreadable")); + let error = + close_popup_with(&world, &process(), None, &escape(), deadline()).expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(world.count("walk"), 0); + assert_eq!(world.count("dismiss"), 0); +} + +#[test] +fn a_window_of_another_generation_fails_closed_before_discovery() { + for instance in [None, Some("recycled")] { + let world = World::matched(); + let target = window(instance); + let error = close_popup_with(&world, &process(), Some(&target), &escape(), deadline()) + .expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(world.count("windows"), 0); + assert_eq!(world.count("walk"), 0); + assert_eq!(world.count("dismiss"), 0); + } +} + +#[test] +fn a_process_that_changed_after_discovery_fails_closed() { + let world = World::matched(); + *world.live.borrow_mut() = VecDeque::from([ + Lookup::Found(facts(INSTANCE)), + Lookup::Found(facts("boot:other")), + ]); + let error = + close_popup_with(&world, &process(), None, &escape(), deadline()).expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(world.count("windows"), 1); + assert_eq!(world.count("walk"), 0); + assert_eq!(world.count("dismiss"), 0); +} + +#[test] +fn a_foreign_bus_owner_before_the_action_fails_closed() { + let world = World::matched(); + *world.owner_checks.borrow_mut() = VecDeque::from([Ok(()), Ok(()), Err(refusal())]); + let error = + close_popup_with(&world, &process(), None, &escape(), deadline()).expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(world.count("owner"), 3); + assert_eq!(world.count("dismiss"), 0); +} + +#[test] +fn matching_identity_and_bus_ownership_reach_the_action() { + let world = World::matched(); + let settled = close_popup_with(&world, &process(), None, &escape(), deadline()) + .expect("closed") + .expect("a popup answered"); + assert_eq!(settled.action, "press"); + assert_eq!(world.count("owner"), 3); + assert_eq!(world.count("dismiss"), 1); +} diff --git a/crates/linux/src/system/focus/escape_popup_world.rs b/crates/linux/src/system/focus/escape_popup_world.rs new file mode 100644 index 0000000000..abc25ed3a2 --- /dev/null +++ b/crates/linux/src/system/focus/escape_popup_world.rs @@ -0,0 +1,147 @@ +//! The live desktop the background Escape popup fallback reads and acts on, +//! behind a seam so the identity checks can be driven by a fixed desktop. + +use agent_desktop_core::{AdapterError, Deadline, ProcessIdentity, WindowInfo}; + +use super::{close_verbs, popup_open, verify_element_owner}; +use crate::actions::action_call::do_action; +use crate::actions::context::Target; +use crate::actions::write::mutation::WriteReply; +use crate::system::process::process_facts; +use crate::system::process::process_lookup::Lookup; +use crate::system::window::window_ops::windows_of_process; +use crate::system::{REGISTRY_ROOT_PATH, SharedBus, within}; +use crate::tree::menu::observe_menu::{rooted, scan_walk_structure}; +use crate::tree::properties::toolkit_trust::{ToolkitKind, kind, read_toolkit}; +use crate::tree::{AtspiElement, ObservedRead, WalkedNode, get_live_actions}; + +const SCAN_NODES: usize = 600; +const OWNER_NODES: usize = 64; +const POPUP_CONTAINER_CHILDREN: usize = 16; + +/// What one popup attempt reads and does about the desktop, so its identity +/// checks can be driven by a fixed desktop. +pub(super) trait PopupWorld { + fn live(&self, pid: u32) -> Lookup; + + fn windows(&self, pid: u32, deadline: Deadline) -> Result, AdapterError>; + + fn verify_owner( + &self, + expected: &ProcessIdentity, + element: &AtspiElement, + deadline: Deadline, + ) -> Result<(), AdapterError>; + + fn walk( + &self, + frame: &AtspiElement, + deadline: Deadline, + ) -> Result, AdapterError>; + + fn verbs( + &self, + owner: &AtspiElement, + role: Option, + deadline: Deadline, + ) -> Result<(Vec, &'static [&'static str]), AdapterError>; + + fn dismiss( + &self, + owner: &AtspiElement, + names: &[String], + verbs: &'static [&'static str], + deadline: Deadline, + ) -> Result; + + fn popup_still_open(&self, owner: &AtspiElement, deadline: Deadline) -> Option; +} + +impl PopupWorld for SharedBus { + fn live(&self, pid: u32) -> Lookup { + process_facts::lookup(pid) + } + + fn windows(&self, pid: u32, deadline: Deadline) -> Result, AdapterError> { + Ok(windows_of_process(self, pid, deadline)?.0) + } + + fn verify_owner( + &self, + expected: &ProcessIdentity, + element: &AtspiElement, + deadline: Deadline, + ) -> Result<(), AdapterError> { + verify_element_owner(self, expected, element, deadline) + } + + fn walk( + &self, + frame: &AtspiElement, + deadline: Deadline, + ) -> Result, AdapterError> { + scan_walk_structure( + self, + frame, + SCAN_NODES, + Some(POPUP_CONTAINER_CHILDREN), + deadline, + ) + } + + fn verbs( + &self, + owner: &AtspiElement, + role: Option, + deadline: Deadline, + ) -> Result<(Vec, &'static [&'static str]), AdapterError> { + let verbs = close_verbs(role, owner_toolkit(self, owner, deadline)); + let handle = owner.clone().into_native_handle(); + let names = get_live_actions(self, &handle, deadline)?.unwrap_or_default(); + Ok((names, verbs)) + } + + fn dismiss( + &self, + owner: &AtspiElement, + names: &[String], + verbs: &'static [&'static str], + deadline: Deadline, + ) -> Result { + let handle = owner.clone().into_native_handle(); + let target = Target { + bus: self, + handle: &handle, + element: owner, + deadline, + }; + do_action(&target, names, verbs) + } + + fn popup_still_open(&self, owner: &AtspiElement, deadline: Deadline) -> Option { + still_open(self, owner, deadline) + } +} + +fn owner_toolkit(bus: &SharedBus, owner: &AtspiElement, deadline: Deadline) -> ToolkitKind { + let Ok(connection) = bus.get(deadline) else { + return ToolkitKind::Other; + }; + let app = AtspiElement::new(owner.bus_name(), REGISTRY_ROOT_PATH, owner.pid()); + match within(deadline, read_toolkit(connection.inner(), &app)) { + Ok(toolkit) => kind(&toolkit), + Err(_) => ToolkitKind::Other, + } +} + +fn still_open(bus: &SharedBus, owner: &AtspiElement, deadline: Deadline) -> Option { + let walk = scan_walk_structure( + bus, + &rooted(owner), + OWNER_NODES, + Some(POPUP_CONTAINER_CHILDREN), + deadline, + ) + .ok()?; + popup_open(&walk) +} diff --git a/crates/linux/src/system/focus/key_dispatch.rs b/crates/linux/src/system/focus/key_dispatch.rs index d8f3e40478..724a2fd901 100644 --- a/crates/linux/src/system/focus/key_dispatch.rs +++ b/crates/linux/src/system/focus/key_dispatch.rs @@ -212,7 +212,7 @@ fn press_in( fn closing_popup_when_refused( result: Result, bus: &SharedBus, - target: (u32, Option<&WindowInfo>), + target: (&ProcessIdentity, Option<&WindowInfo>), combo: &KeyCombo, deadline: Deadline, ) -> Result { @@ -234,7 +234,6 @@ pub(crate) fn press_key_for_app( ) -> Result { crate::system::display::display_server::require(lease.deadline()) .map_err(|error| error.with_disposition(DeliverySemantics::not_delivered()))?; - let pid = process.pid.get(); let result = press_in(Press { physical: &LiveWorld { bus, lease }, keys: &LiveKeys { bus }, @@ -244,7 +243,7 @@ pub(crate) fn press_key_for_app( policy, deadline: lease.deadline(), }); - closing_popup_when_refused(result, bus, (pid, None), combo, lease.deadline()) + closing_popup_when_refused(result, bus, (&process, None), combo, lease.deadline()) } pub(crate) fn press_key_for_window( @@ -261,10 +260,11 @@ pub(crate) fn press_key_for_window( .as_deref() .filter(|instance| !instance.is_empty()) .ok_or_else(|| window_not_active(window))?; + let process = ProcessIdentity::new(window.pid, instance); let result = press_in(Press { physical: &LiveWorld { bus, lease }, keys: &LiveKeys { bus }, - process: &ProcessIdentity::new(window.pid, instance), + process: &process, window: Some(window), combo, policy, @@ -273,7 +273,7 @@ pub(crate) fn press_key_for_window( closing_popup_when_refused( result, bus, - (window.pid.get(), Some(window)), + (&process, Some(window)), combo, lease.deadline(), ) diff --git a/crates/macos/src/system/key_dispatch.rs b/crates/macos/src/system/key_dispatch.rs index 9d70e1db70..de03d95a58 100644 --- a/crates/macos/src/system/key_dispatch.rs +++ b/crates/macos/src/system/key_dispatch.rs @@ -48,7 +48,7 @@ fn press_for_app( } } if let Some(action) = simple_key_action(combo) - && let Some(step) = deliver_semantic_key(pid, &app, action, deadline)? + && let Some(step) = deliver_semantic_key(identity, &app, action, deadline)? { return post_delivery_process_result(&process, step); } @@ -108,23 +108,24 @@ enum SemanticKeyTarget { } /// The states in the order they are tried: the focus holder, then, for -/// Escape only, the open surface. None leaves the key its event route. +/// Escape only, the open surface. `Ok(None)` leaves the key its event route, +/// while a failed surface read propagates instead of reading as absent. fn choose_key_target( focus_holder: Option, action: &str, - open_surface: impl FnOnce() -> Option, -) -> Option> { + open_surface: impl FnOnce() -> Result, AdapterError>, +) -> Result>, AdapterError> { if let Some(holder) = focus_holder { - return Some(SemanticKeyTarget::FocusHolder(holder)); + return Ok(Some(SemanticKeyTarget::FocusHolder(holder))); } - (action == CANCEL) - .then(open_surface) - .flatten() - .map(SemanticKeyTarget::OpenSurface) + if action != CANCEL { + return Ok(None); + } + Ok(open_surface()?.map(SemanticKeyTarget::OpenSurface)) } fn semantic_key_target( - pid: i32, + identity: crate::system::process::process_identity::ProcessIdentity, app: &AXElement, action: &str, deadline: Deadline, @@ -132,34 +133,45 @@ fn semantic_key_target( let focus_holder = focused_element(app, deadline)?.filter(|focused| { crate::actions::ax_helpers::advertises_action(focused, action, deadline) == Some(true) }); - Ok(choose_key_target(focus_holder, action, || { - open_transient_surface(pid, deadline) - })) + choose_key_target(focus_holder, action, || { + open_transient_surface(identity, deadline) + }) } -/// The menu or popover the application shows. A read that cannot finish finds -/// none, and the key then takes the route it had before. -fn open_transient_surface(pid: i32, deadline: Deadline) -> Option { - crate::tree::surfaces::transient_surface_for_pid(pid, deadline) - .ok() - .flatten() +/// The menu or popover the application shows. A search that reached its node +/// limit finds none, and the key then takes the event route; every other read +/// failure, including a changed process generation, propagates. +fn open_transient_surface( + identity: crate::system::process::process_identity::ProcessIdentity, + deadline: Deadline, +) -> Result, AdapterError> { + match crate::tree::surfaces::transient_surface_for_process(identity, deadline) { + Ok(surface) => Ok(surface), + Err(error) if crate::tree::app_menu::is_surface_search_limit(&error) => Ok(None), + Err(error) => Err(error), + } } -/// Performs the action on the target the key reaches. A closed surface is -/// verified by reading that it is gone. +/// Performs the action on the target the key reaches. The process generation is +/// revalidated immediately before the action, and an open surface must belong to +/// that process. A closed surface is verified by reading that it is gone. fn deliver_semantic_key( - pid: i32, + identity: crate::system::process::process_identity::ProcessIdentity, app: &AXElement, action: &'static str, deadline: Deadline, ) -> Result, AdapterError> { - let Some(target) = semantic_key_target(pid, app, action, deadline)? else { + let Some(target) = semantic_key_target(identity, app, action, deadline)? else { return Ok(None); }; let (element, closes_surface) = match &target { SemanticKeyTarget::FocusHolder(element) => (element, false), SemanticKeyTarget::OpenSurface(element) => (element, true), }; + if closes_surface { + require_surface_owner(element, identity, deadline)?; + } + crate::tree::app_menu::require_generation(identity).map_err(not_delivered)?; if !crate::actions::ax_helpers::try_ax_action_or_err(element, action, deadline)? { return Ok(None); } @@ -167,6 +179,30 @@ fn deliver_semantic_key( Ok(Some(semantic_step(action).with_verified(closed))) } +/// Confirms an open surface still belongs to the process the key targets, +/// before anything is sent to it. +fn require_surface_owner( + surface: &AXElement, + identity: crate::system::process::process_identity::ProcessIdentity, + deadline: Deadline, +) -> Result<(), AdapterError> { + match crate::tree::properties::ax_ipc::pid(surface, deadline) { + Ok(pid) if pid == identity.pid() => Ok(()), + Ok(_) => Err(AdapterError::stale_ref_because( + "Surface no longer belongs to the target process", + )), + Err(error) if error == accessibility_sys::kAXErrorInvalidUIElement => Err( + AdapterError::stale_ref_because("Surface became invalid before cancel"), + ), + Err(error) => Err(crate::tree::surface_read::map_error("AXPid", error) + .with_disposition(DeliverySemantics::not_delivered())), + } +} + +fn not_delivered(error: AdapterError) -> AdapterError { + error.with_disposition(DeliverySemantics::not_delivered()) +} + /// A closed surface leaves the tree: a popover's element becomes invalid, and /// a menu's element stays readable but is no longer a child of its parent. fn surface_closed(surface: &AXElement, deadline: Deadline) -> bool { diff --git a/crates/macos/src/system/key_dispatch_tests.rs b/crates/macos/src/system/key_dispatch_tests.rs index 4a4276d8b3..e5d9d7ddaf 100644 --- a/crates/macos/src/system/key_dispatch_tests.rs +++ b/crates/macos/src/system/key_dispatch_tests.rs @@ -121,16 +121,34 @@ fn escape_reaches_the_focus_holder_first_then_the_open_surface() { use super::{SemanticKeyTarget, choose_key_target}; assert_eq!( - choose_key_target(Some(1), "AXCancel", || panic!("surface read")), + choose_key_target(Some(1), "AXCancel", || panic!("surface read")).unwrap(), Some(SemanticKeyTarget::FocusHolder(1)) ); assert_eq!( - choose_key_target(None, "AXCancel", || Some(2)), + choose_key_target(None, "AXCancel", || Ok(Some(2))).unwrap(), Some(SemanticKeyTarget::OpenSurface(2)) ); - assert_eq!(choose_key_target::(None, "AXCancel", || None), None); assert_eq!( - choose_key_target::(None, "AXConfirm", || panic!("surface read")), + choose_key_target::(None, "AXCancel", || Ok(None)).unwrap(), None ); + assert_eq!( + choose_key_target::(None, "AXConfirm", || panic!("surface read")).unwrap(), + None + ); +} + +#[test] +fn a_failed_surface_read_is_not_turned_into_an_absent_surface() { + use super::choose_key_target; + + let error = choose_key_target::(None, "AXCancel", || { + Err(AdapterError::stale_ref_because( + "Application process instance changed during observation", + )) + }) + .expect_err("a failed surface read must not read as no surface"); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); } diff --git a/crates/macos/src/system/key_dispatch_window.rs b/crates/macos/src/system/key_dispatch_window.rs index 063131db45..d2efc382d0 100644 --- a/crates/macos/src/system/key_dispatch_window.rs +++ b/crates/macos/src/system/key_dispatch_window.rs @@ -15,6 +15,7 @@ use agent_desktop_core::{ }; use super::{CANCEL, delivery_result, semantic_step, simple_key_action, surface_closed}; +use crate::system::process::process_identity::ProcessIdentity; use crate::tree::AXElement; /// A key for a named window: core's focus-gated delivery, then, for a plain @@ -61,6 +62,71 @@ fn answer_with_surface_close( } } +/// The identity checks and effects a window surface close depends on, split +/// out so its decision flow is exercised without live accessibility windows. +trait WindowSurfaceClose { + fn expected_identity(&self, window: &WindowInfo) -> Result; + fn discover( + &self, + identity: ProcessIdentity, + window: &WindowInfo, + deadline: Deadline, + ) -> Result, AdapterError>; + fn require_generation(&self, identity: ProcessIdentity) -> Result<(), AdapterError>; + fn surface_pid(&self, surface: &AXElement, deadline: Deadline) -> Result; + fn cancel(&self, surface: &AXElement, deadline: Deadline) -> Result; + fn closed(&self, surface: &AXElement, deadline: Deadline) -> bool; +} + +struct AxWindowSurface; + +impl WindowSurfaceClose for AxWindowSurface { + fn expected_identity(&self, window: &WindowInfo) -> Result { + expected_window_identity(window) + } + + fn discover( + &self, + identity: ProcessIdentity, + window: &WindowInfo, + deadline: Deadline, + ) -> Result, AdapterError> { + crate::tree::surfaces::transient_surface_for_window(identity, window, deadline) + } + + fn require_generation(&self, identity: ProcessIdentity) -> Result<(), AdapterError> { + crate::tree::app_menu::require_generation(identity) + } + + fn surface_pid(&self, surface: &AXElement, deadline: Deadline) -> Result { + crate::tree::properties::ax_ipc::pid(surface, deadline) + } + + fn cancel(&self, surface: &AXElement, deadline: Deadline) -> Result { + crate::actions::ax_helpers::try_ax_action_or_err(surface, CANCEL, deadline) + } + + fn closed(&self, surface: &AXElement, deadline: Deadline) -> bool { + surface_closed(surface, deadline) + } +} + +/// The process identity a window proves from its captured pid and instance +/// token, so a surface is never searched for under a freshly captured +/// generation. +fn expected_window_identity(window: &WindowInfo) -> Result { + let instance = window + .process_instance + .as_deref() + .filter(|instance| !instance.is_empty()) + .ok_or_else(|| { + AdapterError::stale_ref_because("Window has no process-instance identity") + })?; + crate::system::process::process_identity::require_core( + &agent_desktop_core::ProcessIdentity::new(window.pid, instance), + ) +} + /// Closes the menu or popover the named window or its application shows, and /// reads that it closed. `Ok(None)` when none is open, or when the surface does /// not take a cancel action. @@ -68,25 +134,53 @@ fn close_window_surface( window: &WindowInfo, deadline: Deadline, ) -> Result, AdapterError> { - let Some(surface) = open_surface_in_window(window, deadline) else { + close_window_surface_with(&AxWindowSurface, window, deadline) +} + +fn close_window_surface_with( + source: &impl WindowSurfaceClose, + window: &WindowInfo, + deadline: Deadline, +) -> Result, AdapterError> { + let identity = source.expected_identity(window).map_err(not_delivered)?; + let Some(surface) = source + .discover(identity, window, deadline) + .map_err(not_delivered)? + else { return Ok(None); }; - if !crate::actions::ax_helpers::try_ax_action_or_err(&surface, CANCEL, deadline)? { + verify_surface_owner(source, identity, &surface, deadline).map_err(not_delivered)?; + if !source.cancel(&surface, deadline)? { return Ok(None); } - let closed = surface_closed(&surface, deadline); + let closed = source.closed(&surface, deadline); Ok(Some(delivery_result( semantic_step(CANCEL).with_verified(closed), ))) } -/// The menu or popover the named window or its application shows. A read that -/// cannot finish finds none, so the Escape keeps the refusal it had. -fn open_surface_in_window(window: &WindowInfo, deadline: Deadline) -> Option { - let pid = crate::system::process::process_identity::to_pid_t(window.pid).ok()?; - crate::tree::surfaces::transient_surface_for_window(pid, window, deadline) - .ok() - .flatten() +fn verify_surface_owner( + source: &impl WindowSurfaceClose, + identity: ProcessIdentity, + surface: &AXElement, + deadline: Deadline, +) -> Result<(), AdapterError> { + source.require_generation(identity)?; + match source.surface_pid(surface, deadline) { + Ok(pid) if pid == identity.pid() => source.require_generation(identity), + Ok(_) => Err(AdapterError::stale_ref_because( + "Surface no longer belongs to the target process", + )), + Err(error) if error == accessibility_sys::kAXErrorInvalidUIElement => Err( + AdapterError::stale_ref_because("Surface became invalid before cancel"), + ), + Err(error) => Err(crate::tree::surface_read::map_error("AXPid", error) + .with_disposition(DeliverySemantics::not_delivered())), + } +} + +fn not_delivered(error: AdapterError) -> AdapterError { + error.with_disposition(DeliverySemantics::not_delivered()) } #[cfg(test)] diff --git a/crates/macos/src/system/key_dispatch_window_tests.rs b/crates/macos/src/system/key_dispatch_window_tests.rs index 79c7092f47..204d82fa0d 100644 --- a/crates/macos/src/system/key_dispatch_window_tests.rs +++ b/crates/macos/src/system/key_dispatch_window_tests.rs @@ -1,12 +1,16 @@ +use std::cell::Cell; use std::sync::atomic::{AtomicUsize, Ordering}; use agent_desktop_core::{ErrorCode, Modifier, ProcessId, ProcessIdentity, WindowState}; use super::{ ActionResult, AdapterError, CANCEL, Deadline, DeliverySemantics, InteractionLease, - InteractionPolicy, KeyCombo, SystemOps, WindowInfo, answer_with_surface_close, - answers_with_surface_close, delivery_result, is_focus_refusal, press_for_window, semantic_step, + InteractionPolicy, KeyCombo, SystemOps, WindowInfo, WindowSurfaceClose, + answer_with_surface_close, answers_with_surface_close, close_window_surface_with, + delivery_result, is_focus_refusal, press_for_window, semantic_step, }; +use crate::system::process::process_identity::ProcessIdentity as NativeProcessIdentity; +use crate::tree::AXElement; struct WindowRoute { focused: Option, @@ -165,3 +169,229 @@ fn a_surface_close_that_failed_keeps_its_own_error() { assert_eq!(answer.message, "cancel failed"); } + +#[derive(Default)] +struct SurfaceCalls { + discovered: Cell, + generations: Cell, + cancelled: Cell, +} + +struct SurfaceFixture { + discovery: Result, AdapterError>, + surface_pid: Result, + fail_generation_at: Option, + calls: SurfaceCalls, +} + +impl SurfaceFixture { + fn new(surface_pid: i32) -> Self { + Self { + discovery: Ok(Some(AXElement(std::ptr::null_mut()))), + surface_pid: Ok(surface_pid), + fail_generation_at: None, + calls: SurfaceCalls::default(), + } + } + + fn with_surface_pid(mut self, surface_pid: Result) -> Self { + self.surface_pid = surface_pid; + self + } + + fn failing_generation_at(mut self, call: usize) -> Self { + self.fail_generation_at = Some(call); + self + } +} + +impl WindowSurfaceClose for SurfaceFixture { + fn expected_identity( + &self, + window: &WindowInfo, + ) -> Result { + super::expected_window_identity(window) + } + + fn discover( + &self, + _identity: NativeProcessIdentity, + _window: &WindowInfo, + _deadline: Deadline, + ) -> Result, AdapterError> { + self.calls.discovered.set(self.calls.discovered.get() + 1); + self.discovery.clone() + } + + fn require_generation(&self, _identity: NativeProcessIdentity) -> Result<(), AdapterError> { + let call = self.calls.generations.get() + 1; + self.calls.generations.set(call); + if self.fail_generation_at == Some(call) { + return Err(AdapterError::stale_ref_because( + "Application process instance changed during observation", + )); + } + Ok(()) + } + + fn surface_pid(&self, _surface: &AXElement, _deadline: Deadline) -> Result { + self.surface_pid + } + + fn cancel(&self, _surface: &AXElement, _deadline: Deadline) -> Result { + self.calls.cancelled.set(self.calls.cancelled.get() + 1); + Ok(true) + } + + fn closed(&self, _surface: &AXElement, _deadline: Deadline) -> bool { + true + } +} + +fn current_identity() -> NativeProcessIdentity { + let pid = i32::try_from(std::process::id()).expect("test pid fits macOS pid_t"); + NativeProcessIdentity::capture(pid) + .expect("capture current process identity") + .expect("current process identity is present") +} + +fn window_with_instance(instance: Option<&str>) -> WindowInfo { + WindowInfo { + process_instance: instance.map(str::to_owned), + ..window("w-1") + } +} + +fn live_window() -> WindowInfo { + let token = current_identity().token(); + window_with_instance(Some(&token)) +} + +fn standard_deadline() -> Deadline { + Deadline::standard().unwrap() +} + +#[test] +fn an_unprovable_window_identity_fails_before_discovery() { + let cases = [ + ( + window_with_instance(None), + ErrorCode::StaleRef, + "Window has no process-instance identity", + ), + ( + window_with_instance(Some("")), + ErrorCode::StaleRef, + "Window has no process-instance identity", + ), + ( + window_with_instance(Some("macos-proc-v1:1:0")), + ErrorCode::AppUnresponsive, + "Target process instance is no longer running", + ), + ]; + for (window, code, message) in cases { + let fixture = SurfaceFixture::new(0); + let error = close_window_surface_with(&fixture, &window, standard_deadline()) + .expect_err("an unprovable identity must fail closed"); + + assert_eq!(error.code, code); + assert_eq!(error.message, message); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(fixture.calls.discovered.get(), 0); + assert_eq!(fixture.calls.cancelled.get(), 0); + } +} + +#[test] +fn a_stale_window_during_discovery_propagates_without_cancelling() { + let identity = current_identity(); + let mut fixture = SurfaceFixture::new(identity.pid()); + fixture.discovery = Err(AdapterError::stale_ref_because( + "Window 'w-1' identity mismatch", + )); + let error = close_window_surface_with(&fixture, &live_window(), standard_deadline()) + .expect_err("a stale window must not read as an absent surface"); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(fixture.calls.discovered.get(), 1); + assert_eq!(fixture.calls.cancelled.get(), 0); +} + +#[test] +fn a_generation_change_after_discovery_stops_the_cancel() { + for call in 1..=2 { + let identity = current_identity(); + let fixture = SurfaceFixture::new(identity.pid()).failing_generation_at(call); + let error = close_window_surface_with(&fixture, &live_window(), standard_deadline()) + .expect_err("a replaced process must stop the cancel"); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(fixture.calls.discovered.get(), 1); + assert_eq!(fixture.calls.generations.get(), call); + assert_eq!(fixture.calls.cancelled.get(), 0); + } +} + +#[test] +fn a_surface_owned_by_another_process_is_never_cancelled() { + let identity = current_identity(); + let fixture = SurfaceFixture::new(identity.pid() + 1); + let error = close_window_surface_with(&fixture, &live_window(), standard_deadline()) + .expect_err("a foreign surface must fail closed"); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!( + error.message, + "Surface no longer belongs to the target process" + ); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(fixture.calls.cancelled.get(), 0); +} + +#[test] +fn an_invalid_surface_before_the_cancel_fails_closed() { + let identity = current_identity(); + let fixture = SurfaceFixture::new(identity.pid()) + .with_surface_pid(Err(accessibility_sys::kAXErrorInvalidUIElement)); + let error = close_window_surface_with(&fixture, &live_window(), standard_deadline()) + .expect_err("an invalid surface must fail closed"); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.message, "Surface became invalid before cancel"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(fixture.calls.cancelled.get(), 0); +} + +#[test] +fn another_surface_read_failure_keeps_its_mapped_code() { + let identity = current_identity(); + let fixture = SurfaceFixture::new(identity.pid()) + .with_surface_pid(Err(accessibility_sys::kAXErrorCannotComplete)); + let error = close_window_surface_with(&fixture, &live_window(), standard_deadline()) + .expect_err("a failed surface read must fail closed"); + + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.details.as_ref().unwrap()["attribute"], "AXPid"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(fixture.calls.cancelled.get(), 0); +} + +#[test] +fn an_original_generation_surface_is_cancelled_and_verified() { + let identity = current_identity(); + let fixture = SurfaceFixture::new(identity.pid()); + let closed = close_window_surface_with(&fixture, &live_window(), standard_deadline()) + .unwrap() + .expect("a surface of the original generation closes"); + + assert_eq!(closed.action, "press_key"); + assert_eq!( + closed.disposition(), + DeliverySemantics::delivered_verified() + ); + assert_eq!(fixture.calls.generations.get(), 2); + assert_eq!(fixture.calls.cancelled.get(), 1); +} diff --git a/crates/macos/src/tree/app_menu.rs b/crates/macos/src/tree/app_menu.rs index bc6bad32fe..ab8883a475 100644 --- a/crates/macos/src/tree/app_menu.rs +++ b/crates/macos/src/tree/app_menu.rs @@ -20,7 +20,7 @@ pub(crate) fn observe( }) } -fn require_generation( +pub(crate) fn require_generation( identity: crate::system::process::process_identity::ProcessIdentity, ) -> Result<(), AdapterError> { if identity.still_matches()? { @@ -347,6 +347,15 @@ fn invalid_root_error() -> AdapterError { })) } +/// Whether a surface search stopped at its node budget, which means a surface +/// may still sit below the cut rather than being absent. +pub(crate) fn is_surface_search_limit(error: &AdapterError) -> bool { + error + .details + .as_ref() + .is_some_and(|details| details["kind"] == "surface_search_limit") +} + fn surface_limit_error() -> AdapterError { AdapterError::new( ErrorCode::AppUnresponsive, diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rs index cd575bff70..e1500aa551 100644 --- a/crates/macos/src/tree/surfaces.rs +++ b/crates/macos/src/tree/surfaces.rs @@ -1,6 +1,8 @@ use super::{AXElement, properties::element::element_for_pid, surface_read}; use agent_desktop_core::{AdapterError, Deadline, ErrorCode, SnapshotSurface, WindowInfo}; +use crate::system::process::process_identity::ProcessIdentity; + #[cfg(target_os = "macos")] pub(crate) fn focused_surface_for_pid( pid: i32, @@ -24,14 +26,12 @@ pub(crate) fn menu_element_for_pid( /// The menu or popover the application shows, read in one bounded pass. #[cfg(target_os = "macos")] -pub(crate) fn transient_surface_for_pid( - pid: i32, +pub(crate) fn transient_surface_for_process( + identity: ProcessIdentity, deadline: Deadline, ) -> Result, AdapterError> { - let identity = crate::system::process::process_identity::ProcessIdentity::capture(pid)? - .ok_or_else(|| AdapterError::stale_ref_because("Application exited"))?; super::app_menu::observe(identity, deadline, || { - super::app_menu::open_transient_surface(pid, deadline) + super::app_menu::open_transient_surface(identity.pid(), deadline) }) } @@ -40,33 +40,29 @@ pub(crate) fn transient_surface_for_pid( /// surface in a window that is not focused is still found. #[cfg(target_os = "macos")] pub(crate) fn transient_surface_for_window( - pid: i32, + identity: ProcessIdentity, window: &WindowInfo, deadline: Deadline, ) -> Result, AdapterError> { - let identity = crate::system::process::process_identity::ProcessIdentity::capture(pid)? - .ok_or_else(|| AdapterError::stale_ref_because("Application exited"))?; super::app_menu::observe(identity, deadline, || { - match surface_inside_window(window, deadline)? { - Some(surface) => Ok(Some(surface)), - None => super::app_menu::open_transient_surface(pid, deadline), + if let Some(surface) = surface_inside_window(window, deadline)? { + return Ok(Some(surface)); } + super::app_menu::require_generation(identity)?; + super::app_menu::open_transient_surface(identity.pid(), deadline) }) } /// The menu or popover inside `window`, searched at any depth because a -/// popover hangs below the control that raised it. A window whose accessibility -/// element cannot be read is left to the application's own surfaces. +/// popover hangs below the control that raised it. #[cfg(target_os = "macos")] fn surface_inside_window( window: &WindowInfo, deadline: Deadline, ) -> Result, AdapterError> { - let Ok(owner) = crate::system::window::window_resolve::window_element_for_info_with_deadline( + let owner = crate::system::window::window_resolve::window_element_for_info_with_deadline( window, deadline, - ) else { - return Ok(None); - }; + )?; Ok(super::app_menu::find_menu_descendant( owner, "window".into(), @@ -141,11 +137,7 @@ fn popover_in_window( } fn popover_search_error(error: AdapterError) -> AdapterError { - let cut = error - .details - .as_ref() - .is_some_and(|details| details["kind"] == "surface_search_limit"); - if !cut { + if !super::app_menu::is_surface_search_limit(&error) { return error; } popover_search_cut() From 69d07867c6a258045c0fe4991c7936ebfd35eadf Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:19:32 -0800 Subject: [PATCH 19/19] fix(macos): match AXSubrole popovers on Escape, cap Escape surface probe, and update cell-write docs - Match AXPopover via AXSubrole as well as AXRole in app_menu::find_menu_descendant so Escape finds subrole-identified popovers.\n- Cap the Escape open-surface probe to 500 ms and fall back to the key event route when that sub-budget times out while the caller's deadline still has time remaining.\n- Update docs/json-output.md to describe macOS cell write read-back verification (delivered_verified on match, ACTION_FAILED when empty). --- crates/macos/src/system/key_dispatch.rs | 36 ++++++++++++++----- crates/macos/src/system/key_dispatch_tests.rs | 23 ++++++++++++ crates/macos/src/tree/app_menu.rs | 6 +++- docs/json-output.md | 2 +- 4 files changed, 57 insertions(+), 10 deletions(-) diff --git a/crates/macos/src/system/key_dispatch.rs b/crates/macos/src/system/key_dispatch.rs index 5d81ae12f3..6ed6bb6e6d 100644 --- a/crates/macos/src/system/key_dispatch.rs +++ b/crates/macos/src/system/key_dispatch.rs @@ -180,18 +180,38 @@ fn semantic_key_target( }) } -/// The menu or popover the application shows. A search that reached its node -/// limit finds none, and the key then takes the event route; every other read -/// failure, including a changed process generation, propagates. +const ESCAPE_SURFACE_PROBE_BUDGET: std::time::Duration = std::time::Duration::from_millis(500); + +fn classify_surface_probe( + result: Result, AdapterError>, + caller_deadline: Deadline, +) -> Result, AdapterError> { + match result { + Ok(surface) => Ok(surface), + Err(error) + if crate::tree::app_menu::is_surface_search_limit(&error) + || (error.code == ErrorCode::Timeout && !caller_deadline.is_expired()) => + { + Ok(None) + } + Err(error) => Err(error), + } +} + +/// The menu or popover the application shows. A bounded probe that reaches its +/// node limit or its own sub-budget timeout while the caller's deadline still +/// has time left falls back to the key's event route; every other read failure, +/// including a changed process generation or an expired caller deadline, +/// propagates. fn open_transient_surface( identity: crate::system::process::process_identity::ProcessIdentity, deadline: Deadline, ) -> Result, AdapterError> { - match crate::tree::surfaces::transient_surface_for_process(identity, deadline) { - Ok(surface) => Ok(surface), - Err(error) if crate::tree::app_menu::is_surface_search_limit(&error) => Ok(None), - Err(error) => Err(error), - } + let probe_deadline = deadline.capped(ESCAPE_SURFACE_PROBE_BUDGET); + classify_surface_probe( + crate::tree::surfaces::transient_surface_for_process(identity, probe_deadline), + deadline, + ) } /// Performs the action on the target the key reaches. The process generation is diff --git a/crates/macos/src/system/key_dispatch_tests.rs b/crates/macos/src/system/key_dispatch_tests.rs index f8b99e5cfc..13613faa4f 100644 --- a/crates/macos/src/system/key_dispatch_tests.rs +++ b/crates/macos/src/system/key_dispatch_tests.rs @@ -153,6 +153,29 @@ fn a_failed_surface_read_is_not_turned_into_an_absent_surface() { assert_eq!(error.disposition, DeliverySemantics::not_delivered()); } +#[test] +fn a_surface_probe_timeout_falls_back_only_while_the_caller_deadline_remains() { + use super::classify_surface_probe; + + let live = Deadline::after(5_000).unwrap(); + assert_eq!( + classify_surface_probe::(Err(AdapterError::timeout("probe slice")), live).unwrap(), + None + ); + + let expired = Deadline::after(0).unwrap(); + let error = classify_surface_probe::(Err(AdapterError::timeout("caller done")), expired) + .expect_err("an expired caller deadline must propagate"); + assert_eq!(error.code, ErrorCode::Timeout); + + let stale = classify_surface_probe::( + Err(AdapterError::stale_ref_because("generation changed")), + live, + ) + .expect_err("process generation failure must propagate"); + assert_eq!(stale.code, ErrorCode::StaleRef); +} + #[test] fn a_command_chord_to_a_background_app_is_refused_before_sending() { let headless = agent_desktop_core::InteractionPolicy::headless(); diff --git a/crates/macos/src/tree/app_menu.rs b/crates/macos/src/tree/app_menu.rs index ab8883a475..0819baac29 100644 --- a/crates/macos/src/tree/app_menu.rs +++ b/crates/macos/src/tree/app_menu.rs @@ -264,7 +264,11 @@ pub(super) fn find_menu_descendant( if role.as_deref() == Some("AXMenuBar") { return Ok((false, Vec::new())); } - if accept == Transient::MenuOrPopover && role.as_deref() == Some("AXPopover") { + if accept == Transient::MenuOrPopover + && (role.as_deref() == Some("AXPopover") + || surface_read::string(element, "AXSubrole", deadline)?.as_deref() + == Some("AXPopover")) + { return Ok((true, Vec::new())); } if role.as_deref() == Some("AXMenu") diff --git a/docs/json-output.md b/docs/json-output.md index 4dcfeb3511..bd92e128bd 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -190,7 +190,7 @@ When a ref action returns `delivery_uncertain` with a post-action wait selector, - `status` adds `data.state_root_privacy`: `{ "ok": true }` or `{ "ok": false, "error": { ... } }` from the same private-directory check; failed checks leave snapshot rows null. - A table or grid node carries `row_count` and `column_count` when the platform's table interface reports them. A spreadsheet can report far more rows than it shows. Under `--skeleton`, a table or grid that reports its size is one node below the snapshot root: its cells stay out, it carries `children_count`, and its ref anchors a `--root` drill. - macOS: a table cell that occupies one row and one column carries its position as `native_id`, `{ "kind": "grid_cell", "value": "B7" }`: the column letters, then the row, counted from the first row and column the table reports. A cell that has an identifier of its own keeps that identifier as `native_id`, and its position still finds it. The position describes the cell and does not identify it: the ref is found again by the element's own token. `find --role cell --native-id B7 --root ` returns that cell. -- macOS: a table cell that can be pressed lists `SetValue`. `set-value` and `clear` write the cell's value directly when the cell takes one. Any other cell is pressed until its editor opens, its text is replaced with key events sent to the application's process, and Return commits it; the application is not activated. Such a cell publishes no value to read back, so the result is `delivered_unverified`: read the cell again. +- macOS: a table cell that can be pressed lists `SetValue`. `set-value` and `clear` write the cell's value directly when the cell takes one. Any other cell is pressed until its editor opens, its text is replaced with key events sent to the application's process, and Return commits it; the application is not activated. After committing, the cell is read back: the result is `delivered_verified` when the text matches, `delivered_unverified` when it differs or cannot be read, and `ACTION_FAILED` (`delivered_unverified`) when the cell stays empty. - Linux: a table cell reports its text as `value`. An editable cell that holds a number through the platform's value interface lists `SetValue` and takes a number; text is refused with `INVALID_ARGS` before anything is sent, because it has no background route. A selectable table cell whose table can select it lists `Click` and `Select`. A cell carries no grid position: a position names another cell once rows move, so it is never part of a ref's identity. - Windows: a grid cell whose role already earns it a ref lists `Click` when a selectable row inside a grid or list holds it; the click selects that row and reads the selection back. The action never creates a ref. A ref action reads only the properties that identify an element, so it costs less than a snapshot of the same window. A cell carries no grid position.