From db90915867f7bded3a95941ee56f9309d5298da3 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 13:58:19 -0800 Subject: [PATCH 01/26] fix(macos): see the surfaces of a background window and read a window while a system dialog holds the focus A share from Finder showed none of its surfaces to an agent. With the Share popover open, `list-surfaces` answered an empty list: the inventory read only the application's focused window and that window's direct children, and a popover hangs below the control that raised it. A headless target window is rarely the focused one. With the AirDrop panel open, every snapshot of the application failed with APP_UNRESPONSIVE: the focus sits in a view the AirDrop process draws, the application answers the read of its focused element with an error, and the snapshot treated that read as required although it only marks one node as focused. The inventory now reads every window of the application. While the application shows an on-screen window at the pop-up menu level, where AppKit draws an open menu or popover, every window also gets the bounded popover search the Escape route uses; without one the search does not run. A system dialog, the window a system service opens for an application, is listed like a dialog. Only a window's subrole is read: a dialog subrole belongs to a window, and a sheet or a popover has its own role. A snapshot whose focused element cannot be read is built without the focused mark. Measured on Finder with the Share popover and the AirDrop panel open: the popover and the panel are listed, the panel's snapshot gives its device buttons and its Cancel button as refs, and a click on that Cancel closes it. An idle `list-surfaces` costs 27 ms more at the paired median on Finder and 17 ms more on a terminal with several windows, for reading every window instead of one. --- crates/macos/src/system/window/cg_window.rs | 6 +- crates/macos/src/system/window/mod.rs | 1 + .../macos/src/system/window/popup_window.rs | 32 ++++++++ .../src/system/window/popup_window_tests.rs | 9 +++ crates/macos/src/tree/build_context.rs | 8 +- crates/macos/src/tree/surface_inventory.rs | 78 ++++++++++++++----- .../macos/src/tree/surface_inventory_tests.rs | 17 ++++ crates/macos/src/tree/surfaces.rs | 4 +- 8 files changed, 128 insertions(+), 27 deletions(-) create mode 100644 crates/macos/src/system/window/popup_window.rs create mode 100644 crates/macos/src/system/window/popup_window_tests.rs diff --git a/crates/macos/src/system/window/cg_window.rs b/crates/macos/src/system/window/cg_window.rs index 777f5f9a6c..ccb18a62f9 100644 --- a/crates/macos/src/system/window/cg_window.rs +++ b/crates/macos/src/system/window/cg_window.rs @@ -178,7 +178,7 @@ pub(in crate::system) fn records_from_dictionaries( Ok(records) } -fn window_dictionaries() -> Result, AdapterError> { +pub(super) fn window_dictionaries() -> Result, AdapterError> { use crate::tree::properties::cf_type::borrowed_cf_dictionary; use core_graphics::display::CGDisplay; let options = window_list_options(); @@ -335,7 +335,7 @@ fn required_string_field(dict: &WindowDictionary, key: &str) -> Result Option { +pub(super) fn int_field(dict: &WindowDictionary, key: &str) -> Option { use crate::tree::properties::cf_type::borrowed_cf_number; use core_foundation::base::TCFType; @@ -355,7 +355,7 @@ fn string_field(dict: &WindowDictionary, key: &str) -> Option { .map(|value| value.to_string()) } -fn bool_field(dict: &WindowDictionary, key: &str) -> Result { +pub(super) fn bool_field(dict: &WindowDictionary, key: &str) -> Result { use core_foundation::boolean::CFBoolean; let cf_key = CFString::new(key); diff --git a/crates/macos/src/system/window/mod.rs b/crates/macos/src/system/window/mod.rs index fd0917f113..0a059f404f 100644 --- a/crates/macos/src/system/window/mod.rs +++ b/crates/macos/src/system/window/mod.rs @@ -1,5 +1,6 @@ pub(crate) mod cg_window; pub(crate) mod cg_window_exact; +pub(crate) mod popup_window; pub(crate) mod window_ax_state; pub(crate) mod window_bridge; pub(crate) mod window_frame; diff --git a/crates/macos/src/system/window/popup_window.rs b/crates/macos/src/system/window/popup_window.rs new file mode 100644 index 0000000000..6c5e8168f6 --- /dev/null +++ b/crates/macos/src/system/window/popup_window.rs @@ -0,0 +1,32 @@ +//! Whether an application shows an open menu or popover. AppKit draws both in +//! a window at the pop-up menu level, and the accessibility window list +//! leaves that window out. + +use super::cg_window::{bool_field, int_field, window_dictionaries}; + +/// `kCGPopUpMenuWindowLevel`. +const POPUP_MENU_WINDOW_LEVEL: i64 = 101; + +fn is_open_popup(layer: Option, on_screen: bool) -> bool { + layer == Some(POPUP_MENU_WINDOW_LEVEL) && on_screen +} + +/// Whether `pid` has an on-screen window at the pop-up menu level. A window +/// list that cannot be read says yes, so a caller searches instead of +/// missing a surface. +pub(crate) fn shows_popup_window(pid: i32) -> bool { + let Ok(windows) = window_dictionaries() else { + return true; + }; + windows.iter().any(|window| { + int_field(window, "kCGWindowOwnerPID") == Some(i64::from(pid)) + && is_open_popup( + int_field(window, "kCGWindowLayer"), + bool_field(window, "kCGWindowIsOnscreen").unwrap_or(true), + ) + }) +} + +#[cfg(test)] +#[path = "popup_window_tests.rs"] +mod tests; diff --git a/crates/macos/src/system/window/popup_window_tests.rs b/crates/macos/src/system/window/popup_window_tests.rs new file mode 100644 index 0000000000..3d9fe2f6c0 --- /dev/null +++ b/crates/macos/src/system/window/popup_window_tests.rs @@ -0,0 +1,9 @@ +use super::is_open_popup; + +#[test] +fn only_an_on_screen_window_at_the_popup_menu_level_is_an_open_popup() { + assert!(is_open_popup(Some(101), true)); + assert!(!is_open_popup(Some(101), false)); + assert!(!is_open_popup(Some(0), true)); + assert!(!is_open_popup(None, true)); +} diff --git a/crates/macos/src/tree/build_context.rs b/crates/macos/src/tree/build_context.rs index 9dc5c2b51f..8dd1f01725 100644 --- a/crates/macos/src/tree/build_context.rs +++ b/crates/macos/src/tree/build_context.rs @@ -10,6 +10,10 @@ pub(crate) struct TreeBuildContext { } impl TreeBuildContext { + /// The focused element only marks one node as focused. An application + /// whose focus sits in a view another process draws (a share or an AirDrop + /// panel) answers its read with an error, and its tree is still readable, + /// so the tree is built without the mark. pub(crate) fn for_pid_with_deadline( pid: i32, include_bounds: bool, @@ -17,7 +21,9 @@ impl TreeBuildContext { ) -> Result { let app = super::element_for_pid(pid); let focused = - super::resolve::resolve_ax_read::read_element(&app, "AXFocusedUIElement", deadline)?; + super::resolve::resolve_ax_read::read_element(&app, "AXFocusedUIElement", deadline) + .ok() + .flatten(); Ok(Self { focused, window_bounds: None, diff --git a/crates/macos/src/tree/surface_inventory.rs b/crates/macos/src/tree/surface_inventory.rs index eb06d82848..ee2a94efa5 100644 --- a/crates/macos/src/tree/surface_inventory.rs +++ b/crates/macos/src/tree/surface_inventory.rs @@ -20,8 +20,18 @@ fn list_surfaces_once(pid: i32, deadline: Deadline) -> Result, deadline, || { let mut surfaces = Vec::new(); - if let Some(window) = read_element(&app, "AXFocusedWindow", deadline)? { - collect_window_surfaces(&window, "focused-window", deadline, &mut surfaces)?; + let popup_open = crate::system::window::popup_window::shows_popup_window(pid); + for (index, window) in read_array(&app, "AXWindows", deadline)? + .unwrap_or_default() + .iter() + .enumerate() + { + let id = format!("windows/{index}"); + let listed = surfaces.len(); + collect_window_surfaces(window, &id, deadline, &mut surfaces)?; + if popup_open && !surfaces[listed..].iter().any(|s| s.kind == "popover") { + push_anchored_popover(window, &id, deadline, &mut surfaces)?; + } } Ok(surfaces) }, @@ -35,6 +45,33 @@ fn list_surfaces_once(pid: i32, deadline: Deadline) -> Result, ) } +/// A headless target window is rarely the focused one, and a popover hangs +/// below the control that raised it, so while the application shows a pop-up +/// window every window gets the bounded popover search. A window whose search +/// reached its element limit is left out. +fn push_anchored_popover( + window: &AXElement, + window_id: &str, + deadline: Deadline, + surfaces: &mut Vec, +) -> Result<(), AdapterError> { + let popover = match super::surfaces::popover_in_window(window, deadline) { + Ok(popover) => popover, + Err(error) if error.code == agent_desktop_core::ErrorCode::ElementNotFound => None, + Err(error) => return Err(error), + }; + if let Some(popover) = popover { + surfaces.push(SurfaceInfo { + id: format!("{window_id}/popover"), + kind: "popover".into(), + title: read_title(&popover, deadline)?, + item_count: None, + unclassified: Vec::new(), + }); + } + Ok(()) +} + fn list_surfaces_with( deadline: Deadline, window_surfaces: impl FnOnce() -> Result, AdapterError>, @@ -150,17 +187,24 @@ fn surface_kind( deadline: Deadline, ) -> Result, AdapterError> { let role = read_string(element, "AXRole", deadline)?; - let subrole = read_string(element, "AXSubrole", deadline)?; - Ok(match subrole.as_deref() { - Some("AXSheet") => Some("sheet"), - Some("AXPopover") => Some("popover"), - Some("AXDialog") | Some("AXAlert") => Some("alert"), - _ => match role.as_deref() { - Some("AXSheet") => Some("sheet"), - Some("AXPopover") => Some("popover"), - _ => None, - }, - }) + let subrole = match role.as_deref() { + Some("AXWindow") => read_string(element, "AXSubrole", deadline)?, + _ => None, + }; + Ok(kind_of(role.as_deref(), subrole.as_deref())) +} + +/// A system dialog is the window a system service opens for an application, +/// such as the AirDrop panel of a share. A dialog subrole belongs to a window; +/// a sheet and a popover have their own role, so only a window's subrole is +/// read. +fn kind_of(role: Option<&str>, subrole: Option<&str>) -> Option<&'static str> { + match (subrole, role) { + (Some("AXSheet"), _) | (_, Some("AXSheet")) => Some("sheet"), + (Some("AXPopover"), _) | (_, Some("AXPopover")) => Some("popover"), + (Some("AXDialog" | "AXSystemDialog" | "AXAlert"), _) => Some("alert"), + _ => None, + } } fn read_title(element: &AXElement, deadline: Deadline) -> Result, AdapterError> { @@ -186,14 +230,6 @@ fn read_array( crate::tree::surface_read::elements(element, attribute, deadline).map(Some) } -fn read_element( - element: &AXElement, - attribute: &str, - deadline: Deadline, -) -> Result, AdapterError> { - crate::tree::surface_read::element(element, attribute, deadline) -} - fn ensure_before_deadline(deadline: Deadline) -> Result<(), AdapterError> { crate::tree::surface_read::ensure_before_deadline(deadline) } diff --git a/crates/macos/src/tree/surface_inventory_tests.rs b/crates/macos/src/tree/surface_inventory_tests.rs index 1311862266..32eec19a99 100644 --- a/crates/macos/src/tree/surface_inventory_tests.rs +++ b/crates/macos/src/tree/surface_inventory_tests.rs @@ -104,3 +104,20 @@ fn a_failed_inventory_does_not_hide_the_surface_below_the_target() { ["menu", "target"] ); } + +#[test] +fn a_system_dialog_is_listed_as_an_alert_like_a_dialog() { + assert_eq!( + super::kind_of(Some("AXWindow"), Some("AXSystemDialog")), + Some("alert") + ); + assert_eq!( + super::kind_of(Some("AXWindow"), Some("AXDialog")), + Some("alert") + ); + assert_eq!(super::kind_of(Some("AXSheet"), None), Some("sheet")); + assert_eq!( + super::kind_of(Some("AXWindow"), Some("AXStandardWindow")), + None + ); +} diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rs index 5827ccc0f4..61f678365c 100644 --- a/crates/macos/src/tree/surfaces.rs +++ b/crates/macos/src/tree/surfaces.rs @@ -75,7 +75,7 @@ pub(crate) fn surface_in_window( /// 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( +pub(super) fn popover_in_window( window: &AXElement, deadline: Deadline, ) -> Result, AdapterError> { @@ -196,7 +196,7 @@ pub(super) fn is_alert(element: &AXElement, deadline: Deadline) -> Result Date: Mon, 16 Nov 2026 14:31:03 -0800 Subject: [PATCH 02/26] fix(macos): refuse a headless click on a button inside a popover, and read a click's surfaces from its own window A headless click on AirDrop in Finder's Share popover brought Finder to the front: the share item starts a service whose panel the platform activates. The share items are plain buttons with a press action and nothing in the tree tells a share item from a harmless one, so the headless policy now refuses a click on a button inside a popover with `kind: popover_command`, from a bounded walk up its ancestors; such a click needs headed mode. A menu item is not covered: a click on a menu bar item ref is the documented headless way to run a menu command, and a menu cannot open headless. The surfaces an action raised were read through the inventory of every window, which made each click pay for all of the application's windows. They are now read from the target's own window, the elements below the target, and the open menus, with no popover search: a popover that opens after the click is found by `wait --surface`. Measured on Finder against branch 15: the AirDrop click returns POLICY_DENIED in 39 ms and the front application stays as it was; the Share click costs 19 ms less to 10 ms more at the paired median, within the run noise, and the toolbar back button is delivered as before. --- crates/macos/src/actions/background_effect.rs | 39 ++++++++++++++++++- .../src/actions/background_effect_tests.rs | 20 ++++++++++ crates/macos/src/tree/adapter.rs | 18 +++++++-- crates/macos/src/tree/surface_inventory.rs | 37 +++++++++++++----- docs/json-output.md | 2 +- skills/agent-desktop-macos/SKILL.md | 6 ++- 6 files changed, 104 insertions(+), 18 deletions(-) diff --git a/crates/macos/src/actions/background_effect.rs b/crates/macos/src/actions/background_effect.rs index 612049ca86..268b816af7 100644 --- a/crates/macos/src/actions/background_effect.rs +++ b/crates/macos/src/actions/background_effect.rs @@ -5,7 +5,7 @@ //! Writing `AXFocused` moves focus only inside the target application //! (M-W0-14), so it has no effect here and headless `focus` is delivered. //! -//! The reasons are `shows_menu` and `opens_dialog`. A menu overlay is drawn +//! The reasons are `shows_menu`, `opens_dialog` and `popover_command`. A menu overlay is drawn //! over the user's window, takes their focused element, and AppKit orders the //! owning window front; no AX path selects a popup item or opens a context //! menu without it. A dialog is predicted by an owner-judgment rule: a label @@ -13,7 +13,9 @@ //! is trimmed, is the convention shared by GTK, Qt and macOS applications for //! a control that opens a dialog. It is a predictor, not a proof: no //! accessibility property says that a control opens a window. A label that -//! cannot be read counts as one. +//! cannot be read counts as one. A button inside a popover runs a command +//! that can start a service whose window the platform brings to the front (a +//! share item opens the AirDrop panel), and nothing in the tree tells which. use agent_desktop_core::{Action, AdapterError, Deadline, Effect, InteractionPolicy}; @@ -23,6 +25,8 @@ const MENU_OWNER_ROLES: &[&str] = &["AXPopUpButton", "AXMenuButton", "AXComboBox const ELLIPSES: &[&str] = &["\u{2026}", "..."]; const SHOWS_MENU: &str = "shows_menu"; const OPENS_DIALOG: &str = "opens_dialog"; +const POPOVER_COMMAND: &str = "popover_command"; +const POPOVER_ANCESTOR_WALK: usize = 8; /// Refuses `operation` with `POLICY_DENIED` when `policy` does not permit /// `effect`, and reports `kind` as the reason the action takes the foreground. @@ -81,6 +85,7 @@ pub(crate) fn press_disturbs(element: &AXElement, deadline: Deadline) -> bool { struct PressTarget { role: Option, labels: Vec, + in_popover: bool, } fn press_effect(action: &Action, target: &Option) -> Option<&'static str> { @@ -94,6 +99,9 @@ fn press_effect(action: &Action, target: &Option) -> Option<&'stati if menu_owner && matches!(action, Action::Click | Action::Expand) { return Some(SHOWS_MENU); } + if target.in_popover && matches!(action, Action::Click) { + return Some(POPOVER_COMMAND); + } let opens_dialog = target.labels.iter().any(|label| { let label = label.trim_end(); ELLIPSES.iter().any(|ellipsis| label.ends_with(ellipsis)) @@ -125,7 +133,12 @@ fn read_target(element: &AXElement, deadline: Deadline) -> Option { return None; } let names = read.attrs.name_evidence; + let in_popover = match read.attrs.role.as_deref() { + Some("AXButton") => inside_popover(element, deadline)?, + _ => false, + }; Some(PressTarget { + in_popover, role: read.attrs.role, labels: [ names.native_title, @@ -139,6 +152,28 @@ fn read_target(element: &AXElement, deadline: Deadline) -> Option { }) } +/// Whether a popover holds `element`, from a bounded walk up its ancestors. +/// None when an ancestor cannot be read. +fn inside_popover(element: &AXElement, deadline: Deadline) -> Option { + let mut current = element.clone(); + for _ in 0..POPOVER_ANCESTOR_WALK { + let Some(parent) = + crate::tree::surface_read::element(¤t, "AXParent", deadline).ok()? + else { + return Some(false); + }; + match crate::tree::surface_read::string(&parent, "AXRole", deadline) + .ok()? + .as_deref() + { + Some("AXPopover") => return Some(true), + Some("AXWindow" | "AXApplication") => return Some(false), + _ => current = parent, + } + } + Some(false) +} + #[cfg(test)] #[path = "background_effect_tests.rs"] mod tests; diff --git a/crates/macos/src/actions/background_effect_tests.rs b/crates/macos/src/actions/background_effect_tests.rs index 486a4deaaa..1eb1d4f2d7 100644 --- a/crates/macos/src/actions/background_effect_tests.rs +++ b/crates/macos/src/actions/background_effect_tests.rs @@ -6,9 +6,29 @@ fn target(role: &str, label: &str) -> Option { Some(PressTarget { role: Some(role.into()), labels: vec![label.into()], + in_popover: false, }) } +#[test] +fn headless_refuses_a_click_on_a_button_a_popover_holds() { + let in_popover = || { + Some(PressTarget { + in_popover: true, + ..target("AXButton", "AirDrop")? + }) + }; + assert_eq!( + action_effect(&Action::Click, in_popover), + Some("popover_command") + ); + assert_eq!(action_effect(&Action::Toggle, in_popover), None); + assert_eq!( + action_effect(&Action::Click, || target("AXButton", "Share")), + None + ); +} + #[test] fn headless_refuses_what_the_user_would_see_and_delivers_the_rest() { let effect = |action: Action, read: Option| action_effect(&action, || read); diff --git a/crates/macos/src/tree/adapter.rs b/crates/macos/src/tree/adapter.rs index d07fbbc679..b0dc320ef1 100644 --- a/crates/macos/src/tree/adapter.rs +++ b/crates/macos/src/tree/adapter.rs @@ -116,6 +116,7 @@ impl ObservationOps for MacOSAdapter { deadline: Deadline, ) -> Result, AdapterError> { let mut anchored = Vec::new(); + let mut window = None; #[cfg(target_os = "macos")] if let Ok(anchor) = ax_element(raised_by) { crate::tree::surface_inventory::collect_anchored_surfaces( @@ -123,11 +124,20 @@ impl ObservationOps for MacOSAdapter { deadline, &mut anchored, ); + window = crate::tree::surface_read::element(anchor, "AXWindow", deadline) + .ok() + .flatten(); } - crate::tree::surface_inventory::with_anchored( - self.list_surfaces(process, deadline), - anchored, - ) + let inventory = match window { + Some(window) => crate::system::process::process_identity::require_core(&process) + .and_then(|identity| { + crate::tree::surface_inventory::list_surfaces_in_window( + identity, &window, deadline, + ) + }), + None => self.list_surfaces(process, deadline), + }; + crate::tree::surface_inventory::with_anchored(inventory, anchored) } fn hit_test( diff --git a/crates/macos/src/tree/surface_inventory.rs b/crates/macos/src/tree/surface_inventory.rs index ee2a94efa5..8c7d5a5d5c 100644 --- a/crates/macos/src/tree/surface_inventory.rs +++ b/crates/macos/src/tree/surface_inventory.rs @@ -5,31 +5,48 @@ use agent_desktop_core::{AdapterError, Deadline, SurfaceInfo}; /// more is a content container: a list, a table or a column of a browser. pub(crate) const ANCHOR_CHILD_LIMIT: usize = 16; +/// The surfaces of every window of the process, and its open menus. pub(crate) fn list_surfaces_for_process( identity: crate::system::process::process_identity::ProcessIdentity, deadline: Deadline, ) -> Result, AdapterError> { + let app = element_for_pid(identity.pid()); super::app_menu::observe(identity, deadline, || { - list_surfaces_once(identity.pid(), deadline) + let popovers = crate::system::window::popup_window::shows_popup_window(identity.pid()); + list_surfaces_once(identity.pid(), deadline, popovers, || { + Ok(read_array(&app, "AXWindows", deadline)?.unwrap_or_default()) + }) }) } -fn list_surfaces_once(pid: i32, deadline: Deadline) -> Result, AdapterError> { - let app = element_for_pid(pid); +/// The surfaces of one window, and the open menus of its process: what an +/// action on an element of that window can have raised. A popover that opens +/// later is found by `wait --surface`, so the action pays no popover search. +pub(crate) fn list_surfaces_in_window( + identity: crate::system::process::process_identity::ProcessIdentity, + window: &AXElement, + deadline: Deadline, +) -> Result, AdapterError> { + super::app_menu::observe(identity, deadline, || { + list_surfaces_once(identity.pid(), deadline, false, || Ok(vec![window.clone()])) + }) +} + +fn list_surfaces_once( + pid: i32, + deadline: Deadline, + popovers: bool, + windows: impl FnOnce() -> Result, AdapterError>, +) -> Result, AdapterError> { list_surfaces_with( deadline, || { let mut surfaces = Vec::new(); - let popup_open = crate::system::window::popup_window::shows_popup_window(pid); - for (index, window) in read_array(&app, "AXWindows", deadline)? - .unwrap_or_default() - .iter() - .enumerate() - { + for (index, window) in windows()?.iter().enumerate() { let id = format!("windows/{index}"); let listed = surfaces.len(); collect_window_surfaces(window, &id, deadline, &mut surfaces)?; - if popup_open && !surfaces[listed..].iter().any(|s| s.kind == "popover") { + if popovers && !surfaces[listed..].iter().any(|s| s.kind == "popover") { push_anchored_popover(window, &id, deadline, &mut surfaces)?; } } diff --git a/docs/json-output.md b/docs/json-output.md index 0240367b39..076afb4ba5 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -237,7 +237,7 @@ After the core resolver chooses the element, the platform adapter lands it, and | `AMBIGUOUS_TARGET` | Ref recovery matched multiple plausible targets | | `SNAPSHOT_NOT_FOUND` | Snapshot ID is missing or expired | | `SANDBOX_NOT_FOUND` | No sandbox has that name; run `agent-desktop sandbox list` to see the sandboxes that exist | -| `POLICY_DENIED` | The interaction policy does not permit an effect of the operation; nothing was sent. `details.effect` names it when one effect decided: `focus_steal`, `cursor_move` or `clipboard_write`. A refusal of an effect on the user's foreground also carries `details.check: "foreground"` and `details.foreground_effect: true`. Before dispatch, `details.mechanisms` is the action name and `details.kind` is the reason: `shows_menu`, `opens_dialog`, `opens_popup` or `focus`. When a delivery route is held back, `details.mechanisms` names the withheld route labels. A ref action whose remaining routes all deliver nothing, while one was held back, is `POLICY_DENIED`, not `ACTION_FAILED`, on every platform. Rerun with `--headed` to permit them | +| `POLICY_DENIED` | The interaction policy does not permit an effect of the operation; nothing was sent. `details.effect` names it when one effect decided: `focus_steal`, `cursor_move` or `clipboard_write`. A refusal of an effect on the user's foreground also carries `details.check: "foreground"` and `details.foreground_effect: true`. Before dispatch, `details.mechanisms` is the action name and `details.kind` is the reason: `shows_menu`, `opens_dialog`, `opens_popup`, `popover_command` (macOS: a button inside a popover, whose command can start a service that takes the front) or `focus`. When a delivery route is held back, `details.mechanisms` names the withheld route labels. A ref action whose remaining routes all deliver nothing, while one was held back, is `POLICY_DENIED`, not `ACTION_FAILED`, on every platform. Rerun with `--headed` to permit them | | `ACTION_FAILED` | Action rejected, or its observed result contradicted the request | | `ACTION_NOT_SUPPORTED` | The target does not expose the requested action | | `APP_UNRESPONSIVE` | The matching application stopped responding | diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.md index f3f3c4ace3..f96ddd0257 100644 --- a/skills/agent-desktop-macos/SKILL.md +++ b/skills/agent-desktop-macos/SKILL.md @@ -46,9 +46,13 @@ may report `unknown` when consent would require a prompt. 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`. +- `list-surfaces` lists the sheets, dialogs and popovers of every window, not only + the focused one. A system service panel, such as AirDrop from a share, is a dialog. - 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. + A click on a button inside a popover refuses with `kind: popover_command`: a + share item starts a service whose window takes the front. Stop on a headed-only + refusal rather than changing mode. - A file-name text field is not a file-system rename interface. Value-write actions refuse it because a changed field could falsely imply a renamed file. - Chromium accessibility is enabled by the adapter when needed. A sparse or From 9803d170ed7583a47a52362b463dd6bd3a3f9c23 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 14:53:21 -0800 Subject: [PATCH 03/26] feat: wait until a surface of a kind is open A share popover opens about 300 ms after the click that raised it, so the click's own result often cannot list it, and an event wait started after the click takes its baseline after the popover is already open and never sees it appear. An agent that clicks and then waits had no way to find it. `wait --surface --app ` waits for a state, not an event: it polls the application's surface list through the shared `Deadline::poll_until` and returns the first open surface of that kind, at once when one is already open. A context menu counts as a menu. A kind the platform cannot show is refused before the wait starts, through the same support check `snapshot --surface` uses, instead of ending in a timeout. A timeout has the shape of the other waits, with `predicate: surface` and the surfaces it last saw. The flag sits with `--event` to keep the wait arguments within the field limit; the C ABI is unchanged. Measured on Finder with the Share popover: click then wait found it in all three runs, within 0.6 to 0.8 s of the wait's start, which is one surface list of Finder while a pop-up window is on screen. --- crates/core/src/commands/tests/waits/stub.rs | 8 +++ .../core/src/commands/tests/waits/success.rs | 18 +++++++ crates/core/src/commands/wait.rs | 53 +++++++++++++++++- crates/core/src/commands/wait_mode.rs | 10 ++++ crates/core/src/commands/wait_surface.rs | 54 +++++++++++++++---- .../core/src/commands/wait_surface_tests.rs | 50 ++++++++++++++--- crates/core/src/commands/wait_timeout.rs | 16 ++++++ crates/ffi/src/commands/wait.rs | 1 + docs/json-output.md | 1 + skills/agent-desktop/SKILL.md | 4 +- src/cli_args/system.rs | 12 +++-- src/dispatch/system.rs | 1 + 12 files changed, 207 insertions(+), 21 deletions(-) diff --git a/crates/core/src/commands/tests/waits/stub.rs b/crates/core/src/commands/tests/waits/stub.rs index 0fcc0e92d8..13d18681d1 100644 --- a/crates/core/src/commands/tests/waits/stub.rs +++ b/crates/core/src/commands/tests/waits/stub.rs @@ -68,6 +68,14 @@ pub(super) struct Stub { } impl ObservationOps for Stub { + fn list_surfaces( + &self, + _: ProcessIdentity, + _: Deadline, + ) -> Result, AdapterError> { + Ok(Vec::new()) + } + fn observe_tree( &self, root: crate::locator::live_locator::ObservationRoot<'_>, diff --git a/crates/core/src/commands/tests/waits/success.rs b/crates/core/src/commands/tests/waits/success.rs index a0a135a019..4432671389 100644 --- a/crates/core/src/commands/tests/waits/success.rs +++ b/crates/core/src/commands/tests/waits/success.rs @@ -107,3 +107,21 @@ fn event_wait_reports_the_window_and_app_events() { include_str!("../../../../../../tests/fixtures/contract/waits-event.json") ); } + +#[test] +fn a_surface_wait_for_a_kind_the_platform_cannot_show_is_refused_at_once() { + let started = std::time::Instant::now(); + let error = run( + &Stub::default(), + mode!( + surface, + SurfaceWait::Open(Some(crate::SnapshotSurface::Popover)) + ), + Some("TextEdit"), + 5_000, + ) + .unwrap_err(); + + assert_eq!(error.code(), "PLATFORM_NOT_SUPPORTED"); + assert!(started.elapsed() < std::time::Duration::from_secs(1)); +} diff --git a/crates/core/src/commands/wait.rs b/crates/core/src/commands/wait.rs index 311aa04f31..d63732d0a7 100644 --- a/crates/core/src/commands/wait.rs +++ b/crates/core/src/commands/wait.rs @@ -6,7 +6,7 @@ use crate::{ wait_element::{ElementWaitInput, wait_for_element}, wait_mode::WaitMode, wait_notification, - wait_surface::SurfaceWait, + wait_surface::{self, SurfaceWait}, wait_text_match, wait_timeout, }, context::CommandContext, @@ -64,6 +64,7 @@ pub fn execute( Ok(json!({ "waited_ms": ms })) } WaitMode::Menu { app, open } => wait_for_menu(app, open, timeout_ms, adapter), + WaitMode::Surface { app, kind } => wait_for_surface(app, kind, timeout_ms, adapter), WaitMode::Notification { app, text } => { wait_notification::wait_for_notification(app, text, timeout_ms, adapter, context) } @@ -133,6 +134,56 @@ fn wait_for_menu( Ok(json!({ "found": true, "elapsed_ms": elapsed })) } +/// Polls the application's surface list until one of the asked kind is open. +/// A kind the platform cannot show is refused before the wait starts. +fn wait_for_surface( + app: Option, + kind: Option, + timeout_ms: u64, + adapter: &dyn PlatformAdapter, +) -> Result { + if let Some(kind) = kind { + adapter.check_surface_support(kind)?; + } + let start = Instant::now(); + let deadline = crate::Deadline::at(start, timeout_ms)?; + let target = resolve_app(app.as_deref(), adapter, deadline)?; + let process = crate::commands::helpers::process_identity(&target)?; + let open = |surfaces: &[crate::SurfaceInfo]| { + surfaces + .iter() + .find(|surface| wait_surface::is_kind(surface, kind)) + .cloned() + }; + let surfaces = match deadline.poll_until( + deadline.remaining(), + Duration::from_millis(100), + || adapter.list_surfaces(process.clone(), deadline), + |read| { + read.as_ref() + .map_or(true, |surfaces| open(surfaces).is_some()) + }, + ) { + Ok(surfaces) => surfaces, + Err(error) if deadline.is_expired() || wait_timeout::is_deadline_expired(&error) => { + Vec::new() + } + Err(error) => return Err(error.into()), + }; + match open(&surfaces) { + Some(surface) => Ok(json!({ + "found": true, + "surface": surface, + "elapsed_ms": start.elapsed().as_millis(), + })), + None => wait_timeout::surface( + kind.map_or("any", |kind| kind.as_str()), + timeout_ms, + &surfaces, + ), + } +} + fn wait_for_window( title: String, app: Option, diff --git a/crates/core/src/commands/wait_mode.rs b/crates/core/src/commands/wait_mode.rs index e0b6c9d9ce..032907d6f2 100644 --- a/crates/core/src/commands/wait_mode.rs +++ b/crates/core/src/commands/wait_mode.rs @@ -27,6 +27,10 @@ pub(crate) enum WaitMode { app: Option, text: Option, }, + Surface { + app: Option, + kind: Option, + }, Event { event: String, app: Option, @@ -54,6 +58,12 @@ impl WaitMode { open: false, }); } + Some(SurfaceWait::Open(kind)) => { + return Ok(Self::Surface { + app: args.app, + kind, + }); + } Some(SurfaceWait::Notification) => { return Ok(Self::Notification { app: args.app, diff --git a/crates/core/src/commands/wait_surface.rs b/crates/core/src/commands/wait_surface.rs index 3d5032e655..bf7cb9faf4 100644 --- a/crates/core/src/commands/wait_surface.rs +++ b/crates/core/src/commands/wait_surface.rs @@ -1,13 +1,16 @@ -use crate::AppError; +use crate::{AppError, SnapshotSurface, SurfaceInfo}; -/// Which surface-lifecycle condition a `wait` targets: `--menu`, -/// `--menu-closed`, or `--notification`. One variant per flag makes the three +/// Which surface condition a `wait` targets: `--menu`, `--menu-closed`, +/// `--notification`, or `--surface `. One variant per flag makes the /// modes structurally mutually exclusive. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum SurfaceWait { Menu, MenuClosed, Notification, + /// A surface of this kind is open; `None` is any kind. Unlike an event + /// wait it is a state, so a surface that opened before the wait counts. + Open(Option), } impl SurfaceWait { @@ -15,17 +18,50 @@ impl SurfaceWait { menu: bool, menu_closed: bool, notification: bool, + open: Option<&str>, ) -> Result, AppError> { - match (menu, menu_closed, notification) { - (false, false, false) => Ok(None), - (true, false, false) => Ok(Some(Self::Menu)), - (false, true, false) => Ok(Some(Self::MenuClosed)), - (false, false, true) => Ok(Some(Self::Notification)), - _ => Err(crate::commands::wait_mode::ambiguous_wait_mode()), + let open = open.map(open_kind).transpose()?.map(Self::Open); + let mut chosen = [ + menu.then_some(Self::Menu), + menu_closed.then_some(Self::MenuClosed), + notification.then_some(Self::Notification), + open, + ] + .into_iter() + .flatten(); + match (chosen.next(), chosen.next()) { + (wait, None) => Ok(wait), + (Some(_), Some(_)) | (None, Some(_)) => { + Err(crate::commands::wait_mode::ambiguous_wait_mode()) + } } } } +fn open_kind(kind: &str) -> Result, AppError> { + match kind { + "any" => Ok(None), + "popover" => Ok(Some(SnapshotSurface::Popover)), + "sheet" => Ok(Some(SnapshotSurface::Sheet)), + "alert" => Ok(Some(SnapshotSurface::Alert)), + "menu" => Ok(Some(SnapshotSurface::Menu)), + _ => Err(AppError::invalid_input_with_suggestion( + format!("Unknown surface kind '{kind}' for wait --surface"), + "Use popover, sheet, alert, menu or any.", + )), + } +} + +/// Whether a listed surface is of the kind a wait asks for. A context menu is +/// a menu. +pub(crate) fn is_kind(surface: &SurfaceInfo, kind: Option) -> bool { + match kind { + None => true, + Some(SnapshotSurface::Menu) => matches!(surface.kind.as_str(), "menu" | "context_menu"), + Some(kind) => surface.kind == kind.as_str(), + } +} + #[cfg(test)] #[path = "wait_surface_tests.rs"] mod tests; diff --git a/crates/core/src/commands/wait_surface_tests.rs b/crates/core/src/commands/wait_surface_tests.rs index 1b639d55fe..94cf4cc7d0 100644 --- a/crates/core/src/commands/wait_surface_tests.rs +++ b/crates/core/src/commands/wait_surface_tests.rs @@ -1,22 +1,26 @@ -use super::SurfaceWait; +use super::{SurfaceWait, is_kind}; +use crate::{SnapshotSurface, SurfaceInfo}; #[test] fn no_flags_selects_no_surface_wait() { - assert_eq!(SurfaceWait::from_flags(false, false, false).unwrap(), None); + assert_eq!( + SurfaceWait::from_flags(false, false, false, None).unwrap(), + None + ); } #[test] fn each_flag_maps_to_its_variant() { assert_eq!( - SurfaceWait::from_flags(true, false, false).unwrap(), + SurfaceWait::from_flags(true, false, false, None).unwrap(), Some(SurfaceWait::Menu) ); assert_eq!( - SurfaceWait::from_flags(false, true, false).unwrap(), + SurfaceWait::from_flags(false, true, false, None).unwrap(), Some(SurfaceWait::MenuClosed) ); assert_eq!( - SurfaceWait::from_flags(false, false, true).unwrap(), + SurfaceWait::from_flags(false, false, true, None).unwrap(), Some(SurfaceWait::Notification) ); } @@ -29,10 +33,44 @@ fn conflicting_flags_report_exactly_one_mode_error() { (false, true, true), (true, true, true), ] { - let err = SurfaceWait::from_flags(menu, menu_closed, notification).unwrap_err(); + let err = SurfaceWait::from_flags(menu, menu_closed, notification, None).unwrap_err(); assert_eq!(err.code(), "INVALID_ARGS"); assert_eq!(err.to_string(), "wait accepts exactly one mode"); assert!(err.suggestion().is_some()); } } + +#[test] +fn a_surface_kind_selects_an_open_surface_wait_and_conflicts_with_a_flag() { + assert_eq!( + SurfaceWait::from_flags(false, false, false, Some("popover")).unwrap(), + Some(SurfaceWait::Open(Some(SnapshotSurface::Popover))) + ); + assert_eq!( + SurfaceWait::from_flags(false, false, false, Some("any")).unwrap(), + Some(SurfaceWait::Open(None)) + ); + let conflict = SurfaceWait::from_flags(true, false, false, Some("sheet")).unwrap_err(); + assert_eq!(conflict.code(), "INVALID_ARGS"); + let unknown = SurfaceWait::from_flags(false, false, false, Some("window")).unwrap_err(); + assert_eq!(unknown.code(), "INVALID_ARGS"); +} + +#[test] +fn a_listed_surface_matches_its_kind_and_a_context_menu_is_a_menu() { + let listed = |kind: &str| SurfaceInfo { + id: "windows/0".into(), + kind: kind.into(), + title: None, + item_count: None, + unclassified: Vec::new(), + }; + assert!(is_kind(&listed("popover"), Some(SnapshotSurface::Popover))); + assert!(!is_kind(&listed("sheet"), Some(SnapshotSurface::Popover))); + assert!(is_kind( + &listed("context_menu"), + Some(SnapshotSurface::Menu) + )); + assert!(is_kind(&listed("alert"), None)); +} diff --git a/crates/core/src/commands/wait_timeout.rs b/crates/core/src/commands/wait_timeout.rs index 50be288f88..58f180e509 100644 --- a/crates/core/src/commands/wait_timeout.rs +++ b/crates/core/src/commands/wait_timeout.rs @@ -28,6 +28,22 @@ pub(crate) fn menu(mut error: AdapterError, timeout_ms: u64) -> AppError { AppError::Adapter(error) } +pub(crate) fn surface( + kind: &str, + timeout_ms: u64, + observed: &[crate::SurfaceInfo], +) -> Result { + let what = if kind == "any" { + "No surface".to_owned() + } else { + format!("No {kind} surface") + }; + timeout_err( + format!("{what} was open within {timeout_ms}ms"), + json!({ "predicate": "surface", "surface": kind, "timeout_ms": timeout_ms, "last_observed": observed }), + ) +} + /// Builds the wait-loop TIMEOUT error. Every payload carries /// `kind: "wait_timeout"` so agents can discriminate it from the chain /// deadline TIMEOUT schema (`kind: "chain_deadline"`) without sniffing diff --git a/crates/ffi/src/commands/wait.rs b/crates/ffi/src/commands/wait.rs index 34c2b2f379..017fac0fd4 100644 --- a/crates/ffi/src/commands/wait.rs +++ b/crates/ffi/src/commands/wait.rs @@ -78,6 +78,7 @@ pub unsafe extern "C" fn ad_wait( ffi_args.mode.surfaces.menu, ffi_args.mode.surfaces.menu_closed, ffi_args.mode.surfaces.notification, + None, ) .and_then(|surface| { wait_args.mode.surface = surface; diff --git a/docs/json-output.md b/docs/json-output.md index 076afb4ba5..543bda4916 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -275,6 +275,7 @@ The 2.7 envelope keeps every current name. 2.0 is a future breaking release that | Process identity | Flat `pid`, `process_instance` in list-apps, list-windows, and launch; `pid` alone in wait events and list-surfaces; `target.process.{pid,instance}` in close-app and window operations; `process_identity.{pid,process_instance}` in post-action observation; neither in snapshot data | Flat `pid`, `process_instance`; omit an unknown instance | | Window identity | `id`, `title` in window records, operation targets, and snapshot; `window_id`, `title` in wait events; `source_window_id` in post-action observation; snapshot includes only `id`, `title` | Record `id`, `title`; reference `window_id`; full window record in snapshot | | Window container | `window` in launch, snapshot, wait --window, and open-system-surface; `focused` object in focus-window | `window` | +| Open surface | `surface` in wait --surface: the `id`, `type` and `title` of the first open surface of the asked kind; its timeout carries `last_observed` | `surface` | | Focus state | `is_focused` in window records; `focused` element token; `result` in is focused; `focused` boolean in hover and drag | Window `focused`; element token `focused`; hover and drag `window_focused` | | Element state | `states` tokens in snapshot and find; get --property states returns tokens in `value`; ref-action `post_state` has `states` plus `enabled`, `hidden`, `offscreen` booleans | `states` tokens, including `enabled` when evidenced | | Predicate answer | `property`, `result`, `applicable` in is; wait --element `observed` uses `exists`, `enabled`, `visible`, `actionable`, or `matched` with value evidence | No common name specified | diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.md index 77b519be2c..7c6947b366 100644 --- a/skills/agent-desktop/SKILL.md +++ b/skills/agent-desktop/SKILL.md @@ -88,8 +88,8 @@ Request `--cdp` only for the step that needs it. `close-app` ends the exposure. and exit 0 can include failures. Read each entry's `ok`, even with `--stop-on-error`, which stops later steps after a failure. - Lifecycle verification: put an action immediately before its event `wait` in the same - batch so the baseline is captured before the action. A standalone event wait starts - its baseline when it observes and can miss an already-completed transition. + batch so the baseline is captured before the action; a later event wait can miss an + already-completed transition. A surface a click opens late is a state: `wait --surface --app `. - Targeting: use `find` when the role or name is known; explore a large window with a skeleton snapshot and a `--root` drill. - Tables: a table node reports `row_count` and `column_count`; a skeleton keeps it as one diff --git a/src/cli_args/system.rs b/src/cli_args/system.rs index de906ac537..3e4d658681 100644 --- a/src/cli_args/system.rs +++ b/src/cli_args/system.rs @@ -231,9 +231,9 @@ pub(crate) struct WaitArgs { pub app: Option, } -/// The `--event`/`--window-id` pair, grouped out of [`WaitModeArgs`] to keep -/// it under the repo's field-count limit. `window_id` only ever narrows an -/// `--event` wait, so the two travel together. +/// The desktop-wide waits, grouped out of [`WaitModeArgs`] to keep it under +/// the repo's field-count limit: `--event` with its `--window-id` narrowing, +/// and `--surface`. #[derive(Args, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub(crate) struct WaitEventArgs { @@ -248,6 +248,12 @@ pub(crate) struct WaitEventArgs { help = "Optional: narrow --event window-opened/window-closed/focus-changed to one window ID" )] pub window_id: Option, + #[arg( + long, + value_name = "KIND", + help = "Block until a surface of this kind is open in the app: popover, sheet, alert, menu, or any. A surface already open counts, so it also finds one that opened just after a click" + )] + pub surface: Option, } #[derive(Args, Debug, Deserialize)] diff --git a/src/dispatch/system.rs b/src/dispatch/system.rs index 26d24e0906..419e1a9469 100644 --- a/src/dispatch/system.rs +++ b/src/dispatch/system.rs @@ -29,6 +29,7 @@ pub(super) fn wait( args.mode.menu, args.mode.menu_closed, args.mode.notification, + args.event.surface.as_deref(), )?, event: args.event.event, window_id: args.event.window_id, From 937f3e70149ac938048eb228ac31b804b7fa5e36 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 16:12:24 -0800 Subject: [PATCH 04/26] fix(windows): list an owned pop-up window as a popover and resolve refs inside it A ribbon drop-down (in Paint, the Size list) is an owned pop-up tool window that the window census leaves out, so `list-surfaces` did not show it and a snapshot could not root it. A popover is now a visible tool window owned by a window of the same process, with WS_POPUP, that can activate (not WS_EX_NOACTIVATE, which tooltips use) and is not a menu window (#32768, which the menu detector owns). The existing EnumWindows pass collects it; window styles are read only for the process's tool windows. `list-surfaces` lists it as `popover`, `snapshot --surface popover` roots it, and Popover is a supported surface, so `wait --surface popover` finds one. A ref from that snapshot did not resolve: its anchor was rooted at the recorded window, which a popover is not, and the application root was not supported. The ref anchor, the application root and the surface observation now root a popover-surface ref at the process's open popover through the same predicate, after the process generation check. list-windows output is unchanged. Measured on Paint: a headless click on the 3px option is delivered_verified in 185 ms, the option is selected afterwards, and the foreground window does not move, so no headless refusal is needed. An idle `list-surfaces` costs the same as before on Paint and Notepad, and a click with no effect costs the same. --- crates/windows/src/adapter.rs | 6 ++ crates/windows/src/system/adapter.rs | 6 +- crates/windows/src/system/adapter_tests.rs | 3 +- crates/windows/src/tree/mod.rs | 1 + crates/windows/src/tree/observe.rs | 4 +- crates/windows/src/tree/popover_inventory.rs | 68 +++++++++++++++++++ .../src/tree/popover_inventory_tests.rs | 31 +++++++++ .../src/tree/resolve/resolve_anchor.rs | 30 +++++++- crates/windows/src/tree/surface_inventory.rs | 38 +++++++++-- crates/windows/src/tree/surfaces.rs | 20 ++++++ skills/agent-desktop-windows/SKILL.md | 3 +- 11 files changed, 197 insertions(+), 13 deletions(-) create mode 100644 crates/windows/src/tree/popover_inventory.rs create mode 100644 crates/windows/src/tree/popover_inventory_tests.rs diff --git a/crates/windows/src/adapter.rs b/crates/windows/src/adapter.rs index 7c9d4c6ff1..e72625fd0e 100644 --- a/crates/windows/src/adapter.rs +++ b/crates/windows/src/adapter.rs @@ -56,6 +56,12 @@ impl Default for WindowsAdapter { } impl ObservationOps for WindowsAdapter { + /// A popover belongs to the application, not to one window: its refs resolve + /// against the application's open popover. + fn is_application_surface(&self, surface: SnapshotSurface) -> bool { + surface == SnapshotSurface::Popover + } + fn observe_tree( &self, root: ObservationRoot<'_>, diff --git a/crates/windows/src/system/adapter.rs b/crates/windows/src/system/adapter.rs index 0534854ec4..9e54a0740a 100644 --- a/crates/windows/src/system/adapter.rs +++ b/crates/windows/src/system/adapter.rs @@ -104,7 +104,7 @@ impl SystemOps for WindowsAdapter { } /// The surfaces this adapter can observe: a named window, the focused - /// window, a Chromium modal-as-sheet, an open application menu, and the + /// window, a Chromium modal-as-sheet, an open menu or popover, 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 @@ -112,14 +112,14 @@ impl SystemOps for WindowsAdapter { /// 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. + /// refuses in core with the standard shape instead of pretending it can root. fn supported_surfaces(&self) -> Vec { vec![ SnapshotSurface::Window, SnapshotSurface::Focused, SnapshotSurface::Sheet, SnapshotSurface::Menu, + SnapshotSurface::Popover, SnapshotSurface::StartMenu, SnapshotSurface::Taskbar, SnapshotSurface::SystemTray, diff --git a/crates/windows/src/system/adapter_tests.rs b/crates/windows/src/system/adapter_tests.rs index 87976a6fa4..796fc65ad5 100644 --- a/crates/windows/src/system/adapter_tests.rs +++ b/crates/windows/src/system/adapter_tests.rs @@ -149,7 +149,7 @@ fn screenshot_window_frame_is_wired_through_system_ops_to_the_exact_window_captu /// the "advertised" side of the advertise/resolve/emit equality the live /// tests pin. #[test] -fn supported_surfaces_advertises_window_focused_sheet_menu_and_shell_kinds() { +fn supported_surfaces_advertises_window_focused_sheet_menu_popover_and_shell_kinds() { let adapter = WindowsAdapter::new(); assert_eq!( adapter.supported_surfaces(), @@ -158,6 +158,7 @@ fn supported_surfaces_advertises_window_focused_sheet_menu_and_shell_kinds() { SnapshotSurface::Focused, SnapshotSurface::Sheet, SnapshotSurface::Menu, + SnapshotSurface::Popover, SnapshotSurface::StartMenu, SnapshotSurface::Taskbar, SnapshotSurface::SystemTray, diff --git a/crates/windows/src/tree/mod.rs b/crates/windows/src/tree/mod.rs index 29ef54d120..84d50b1be6 100644 --- a/crates/windows/src/tree/mod.rs +++ b/crates/windows/src/tree/mod.rs @@ -8,6 +8,7 @@ pub(crate) mod live_read; pub(crate) mod minimized; pub mod name_evidence; pub(crate) mod observe; +pub(crate) mod popover_inventory; pub(crate) mod resolve; pub mod roles; pub mod states; diff --git a/crates/windows/src/tree/observe.rs b/crates/windows/src/tree/observe.rs index 69443d3934..f9ae12dd0c 100644 --- a/crates/windows/src/tree/observe.rs +++ b/crates/windows/src/tree/observe.rs @@ -174,8 +174,8 @@ fn still_thin_after_settle() -> AdapterError { /// Rechecks stored ownership and generation evidence after the UIA read. fn re_verify_root(root: ObservationRoot<'_>) -> Result<(), AdapterError> { match root { - ObservationRoot::Application { .. } => { - Err(AdapterError::not_supported("application observation root")) + ObservationRoot::Application { app, .. } => { + verify_process_identity(app.pid, app.process_instance.as_deref()) } ObservationRoot::Window(window) => { let handle = hwnd_of(&window.id)?; diff --git a/crates/windows/src/tree/popover_inventory.rs b/crates/windows/src/tree/popover_inventory.rs new file mode 100644 index 0000000000..d4cb8d9dd8 --- /dev/null +++ b/crates/windows/src/tree/popover_inventory.rs @@ -0,0 +1,68 @@ +//! Popovers: the transient popup windows an application owns, such as a +//! ribbon drop-down or a split-button list. +//! +//! A popover is a visible popup window that another window of the same +//! process owns and that sits in the tool-window layer, so the window census +//! drops it. A menu has its own detector, and a tooltip never takes the +//! keyboard, so neither is a popover. Control type and ownership decide it, +//! never the application or the window title. + +use agent_desktop_core::ProcessId; + +use crate::system::window::window_enum::{EnumeratedWindow, WindowHandle}; + +/// What the window styles and the owner chain say about one tool window. +#[derive(Debug, Clone, Copy)] +pub(crate) struct PopupFacts { + pub(crate) owned_by_same_process: bool, + pub(crate) popup_style: bool, + pub(crate) no_activate: bool, + pub(crate) menu_class: bool, +} + +/// Whether a visible tool window is a popover. +pub(crate) fn is_popover(facts: &PopupFacts) -> bool { + facts.owned_by_same_process && facts.popup_style && !facts.no_activate && !facts.menu_class +} + +/// The popover candidates among a process's windows: visible, sized, not +/// cloaked tool windows whose facts say popover. +pub(crate) fn is_popover_window(window: &EnumeratedWindow, pid: ProcessId) -> bool { + window.visible + && window.tool + && !window.is_zero_sized() + && !window.cloaked + && is_popover(&popup_facts(window.handle, pid)) +} + +#[cfg(target_os = "windows")] +fn popup_facts(handle: WindowHandle, pid: ProcessId) -> PopupFacts { + use crate::system::window::window_identity::live_window_owner; + use crate::system::window::window_ops::window_class_name; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + GW_OWNER, GWL_EXSTYLE, GWL_STYLE, GetWindow, GetWindowLongW, WS_EX_NOACTIVATE, WS_POPUP, + }; + let owner = unsafe { GetWindow(handle, GW_OWNER) }; + let style = unsafe { GetWindowLongW(handle, GWL_STYLE) } as u32; + let ex_style = unsafe { GetWindowLongW(handle, GWL_EXSTYLE) } as u32; + PopupFacts { + owned_by_same_process: !owner.is_null() && live_window_owner(owner) == Some(pid), + popup_style: style & WS_POPUP != 0, + no_activate: ex_style & WS_EX_NOACTIVATE != 0, + menu_class: window_class_name(handle).as_deref() == Some("#32768"), + } +} + +#[cfg(not(target_os = "windows"))] +fn popup_facts(_handle: WindowHandle, _pid: ProcessId) -> PopupFacts { + PopupFacts { + owned_by_same_process: false, + popup_style: false, + no_activate: false, + menu_class: false, + } +} + +#[cfg(test)] +#[path = "popover_inventory_tests.rs"] +mod tests; diff --git a/crates/windows/src/tree/popover_inventory_tests.rs b/crates/windows/src/tree/popover_inventory_tests.rs new file mode 100644 index 0000000000..c196bde338 --- /dev/null +++ b/crates/windows/src/tree/popover_inventory_tests.rs @@ -0,0 +1,31 @@ +use super::{PopupFacts, is_popover}; + +fn facts() -> PopupFacts { + PopupFacts { + owned_by_same_process: true, + popup_style: true, + no_activate: false, + menu_class: false, + } +} + +#[test] +fn only_an_owned_activating_popup_that_is_not_a_menu_is_a_popover() { + assert!(is_popover(&facts())); + assert!(!is_popover(&PopupFacts { + owned_by_same_process: false, + ..facts() + })); + assert!(!is_popover(&PopupFacts { + popup_style: false, + ..facts() + })); + assert!(!is_popover(&PopupFacts { + no_activate: true, + ..facts() + })); + assert!(!is_popover(&PopupFacts { + menu_class: true, + ..facts() + })); +} diff --git a/crates/windows/src/tree/resolve/resolve_anchor.rs b/crates/windows/src/tree/resolve/resolve_anchor.rs index 214edcda69..f16a905ca6 100644 --- a/crates/windows/src/tree/resolve/resolve_anchor.rs +++ b/crates/windows/src/tree/resolve/resolve_anchor.rs @@ -59,6 +59,31 @@ pub(crate) fn resolve_locator_anchor( Err(stale_ref_error(entry)) } +/// A popover ref's path starts at the application's open popover, and the +/// popover is no listed window: the process generation is checked and the +/// popover found by the same predicate the inventory uses. +#[cfg(target_os = "windows")] +fn popover_root(entry: &RefEntry, deadline: Deadline) -> Result, AdapterError> { + if entry.source.source_surface != agent_desktop_core::SnapshotSurface::Popover { + return Ok(None); + } + let alive = entry + .process + .process_instance + .as_deref() + .map(|instance| { + crate::system::process_identity::matches_instance(entry.process.pid, instance) + }) + .transpose()? + == Some(true); + if !alive { + return Err(stale_ref_error(entry)); + } + let popover = crate::tree::surface_inventory::first_popover(entry.process.pid, deadline)? + .ok_or_else(|| stale_ref_error(entry))?; + crate::tree::automation::root_from_hwnd(popover as isize, deadline).map(Some) +} + /// The one pure gate runs first, before any of `resolve_window_root`, /// `UiaTreeSource::for_root` or `prepare_root` - three cross-process calls a /// verdict the stored ref alone can settle should never pay for. @@ -79,7 +104,10 @@ fn resolve_locator_anchor_once( return Err(stale_ref_error(entry)); } - let window = crate::tree::resolve::resolve_window_root(entry, deadline)?; + let window = match popover_root(entry, deadline)? { + Some(popover) => popover, + None => crate::tree::resolve::resolve_window_root(entry, deadline)?, + }; let root = match base { Some(handle) => handle .downcast_ref::() diff --git a/crates/windows/src/tree/surface_inventory.rs b/crates/windows/src/tree/surface_inventory.rs index 9f529a8346..42c87abdcf 100644 --- a/crates/windows/src/tree/surface_inventory.rs +++ b/crates/windows/src/tree/surface_inventory.rs @@ -3,6 +3,7 @@ use agent_desktop_core::{ }; use super::automation::root_from_hwnd; +use super::popover_inventory::is_popover_window; use super::properties::property_ids::TreeProperty; use super::properties::property_outcome::PropertyOutcome; use super::properties::read_one; @@ -37,7 +38,7 @@ pub(crate) fn list_surfaces_for_process( ) -> Result, AdapterError> { deadline.ensure_remaining()?; require_live_process(&process)?; - let windows = windows_of(process.pid, deadline)?; + let (windows, popovers) = windows_of(process.pid, deadline)?; let observed: Vec = windows .iter() .map(|window| ObservedWindow { @@ -53,6 +54,13 @@ pub(crate) fn list_surfaces_for_process( if let Some(menu) = menu { surfaces.push(menu_surface(&menu)?); } + for popover in popovers { + surfaces.push(surface( + SnapshotSurface::Popover, + popover.handle, + live_window_title(popover.handle), + )); + } Ok(surfaces) } @@ -73,8 +81,24 @@ fn require_live_process(process: &ProcessIdentity) -> Result<(), AdapterError> { /// every window inventory on this platform shares - the same walk /// `list_windows` and the menu detector draw from, filtered by the same /// census predicate. -fn windows_of(pid: ProcessId, deadline: Deadline) -> Result, AdapterError> { +/// The handle of the process's first open popover, if any. +pub(crate) fn first_popover( + pid: ProcessId, + deadline: Deadline, +) -> Result, AdapterError> { + Ok(windows_of(pid, deadline)? + .1 + .first() + .map(|popover| popover.handle)) +} + +/// The process's census windows and its popovers (tool windows the census drops). +fn windows_of( + pid: ProcessId, + deadline: Deadline, +) -> Result<(Vec, Vec), AdapterError> { let mut windows = Vec::new(); + let mut popovers = Vec::new(); let failure = std::cell::RefCell::new(None); let mut seen = 0usize; enumerate_top_level(|window| { @@ -85,15 +109,19 @@ fn windows_of(pid: ProcessId, deadline: Deadline) -> Result) -> SurfaceInfo { diff --git a/crates/windows/src/tree/surfaces.rs b/crates/windows/src/tree/surfaces.rs index 2791f1c3a7..f61c83e276 100644 --- a/crates/windows/src/tree/surfaces.rs +++ b/crates/windows/src/tree/surfaces.rs @@ -23,6 +23,16 @@ pub(crate) fn surface_root( deadline: Deadline, ) -> Result { match (root, surface) { + (ObservationRoot::Application { app, .. }, SnapshotSurface::Popover) => { + let popover = crate::tree::surface_inventory::first_popover(app.pid, deadline)? + .ok_or_else(|| { + AdapterError::new( + ErrorCode::WindowNotFound, + "No popover is open in this application", + ) + })?; + root_from_hwnd(popover as isize, deadline) + } (ObservationRoot::Application { .. }, _) => { Err(AdapterError::not_supported("application observation root")) } @@ -64,6 +74,16 @@ pub(crate) fn surface_root( })?; root_from_hwnd(location.root_handle(), deadline) } + (ObservationRoot::Window(window), SnapshotSurface::Popover) => { + let popover = crate::tree::surface_inventory::first_popover(window.pid, deadline)? + .ok_or_else(|| { + AdapterError::new( + ErrorCode::WindowNotFound, + "No popover is open in this application", + ) + })?; + root_from_hwnd(popover as isize, deadline) + } (ObservationRoot::Window(window), SnapshotSurface::StartMenu) | (ObservationRoot::Window(window), SnapshotSurface::Taskbar) | (ObservationRoot::Window(window), SnapshotSurface::SystemTray) diff --git a/skills/agent-desktop-windows/SKILL.md b/skills/agent-desktop-windows/SKILL.md index bbaa8331b5..19cee84c36 100644 --- a/skills/agent-desktop-windows/SKILL.md +++ b/skills/agent-desktop-windows/SKILL.md @@ -58,7 +58,8 @@ Use `$env:NAME = 'value'` for environment variables. `focus_returned: true`. A window you switched to is never touched. - Chromium/Electron trees can be thin while accessibility settles. Finish a bounded observation before concluding that content is absent. -- An open application menu is the `menu` surface; there is no `menubar` surface. +- An open application menu is the `menu` surface; there is no `menubar` surface. An owned popup window + of the app (a ribbon drop-down) is a `popover`: `list-surfaces` lists it, `snapshot --surface popover` reads it. Shell surfaces are separate from ordinary window inventory. `quick-settings` refuses with `INVALID_ARGS` naming `action-center`. - Notification reads adopt an already-open Action Center headless; opening it From af3065758e36e51ef39a4e3486d7ccab2888b38d Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 16:29:26 -0800 Subject: [PATCH 05/26] fix(linux): list a showing alert as an alert surface `snapshot --surface alert` roots a showing alert frame on Linux, but `list-surfaces` listed that frame only as a sheet, so `wait --surface alert` could never match and ended in a timeout. A listed window now records whether its frame is a showing alert, through the same predicate the alert snapshot roots at, and `list-surfaces` names it `alert` in place of `sheet`, beside its `window` entry. Only a top-level frame is classified this way. Measured on gedit with its "Save changes?" prompt open: `list-surfaces` gives `window` and `alert` instead of `window` and `sheet`, `wait --surface alert` finds it in 112 ms instead of timing out, and the alert snapshot roots the same window. --- .../src/system/capture/window_xid_tests.rs | 1 + .../src/system/launch/launch_baseline_tests.rs | 1 + crates/linux/src/system/menu/inventory_tests.rs | 1 + crates/linux/src/system/menu/surfaces.rs | 17 ++++++++++++++--- crates/linux/src/system/menu/surfaces_tests.rs | 15 +++++++++++++++ .../linux/src/system/process/protected_tests.rs | 1 + .../linux/src/system/registry/listed_window.rs | 3 +++ .../src/system/signal/signal_capture_tests.rs | 1 + .../system/signal/signal_population_tests.rs | 1 + .../src/system/signal/signal_surfaces_tests.rs | 1 + .../src/system/window/ghost_window_tests.rs | 1 + .../src/system/window/listed_twins_tests.rs | 1 + .../linux/src/system/window/stopped_windows.rs | 1 + .../window/window_filter_deadline_tests.rs | 1 + .../system/window/window_filter_helper_tests.rs | 1 + .../src/system/window/window_filter_tests.rs | 1 + .../linux/src/system/window/window_listing.rs | 1 + .../linux/src/system/window/window_ops_tests.rs | 1 + .../src/system/window/window_order_tests.rs | 1 + 19 files changed, 48 insertions(+), 3 deletions(-) diff --git a/crates/linux/src/system/capture/window_xid_tests.rs b/crates/linux/src/system/capture/window_xid_tests.rs index be4b087761..6c05d20ce4 100644 --- a/crates/linux/src/system/capture/window_xid_tests.rs +++ b/crates/linux/src/system/capture/window_xid_tests.rs @@ -72,6 +72,7 @@ fn the_server_states_without_a_client_list_keep_their_cause() { fn listed(id: &str, title: &str, active: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: id.to_owned(), diff --git a/crates/linux/src/system/launch/launch_baseline_tests.rs b/crates/linux/src/system/launch/launch_baseline_tests.rs index 798a616879..e868370c15 100644 --- a/crates/linux/src/system/launch/launch_baseline_tests.rs +++ b/crates/linux/src/system/launch/launch_baseline_tests.rs @@ -99,6 +99,7 @@ fn an_old_frame_omitted_by_an_incomplete_baseline_cannot_be_a_launch_window() { pass.recovered.push(0); pass.windows .push(crate::system::registry::listed_window::ListedWindow { + alert: false, app: 0, info: agent_desktop_core::WindowInfo { id: "w-1.5-stopped-x42".to_owned(), diff --git a/crates/linux/src/system/menu/inventory_tests.rs b/crates/linux/src/system/menu/inventory_tests.rs index a06528f5ca..abb0d7c2ee 100644 --- a/crates/linux/src/system/menu/inventory_tests.rs +++ b/crates/linux/src/system/menu/inventory_tests.rs @@ -11,6 +11,7 @@ use crate::tree::{AtspiElement, Field, WalkedNode}; fn window(id: &str, sheet: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: id.to_owned(), diff --git a/crates/linux/src/system/menu/surfaces.rs b/crates/linux/src/system/menu/surfaces.rs index a75282055a..d74319e8e4 100644 --- a/crates/linux/src/system/menu/surfaces.rs +++ b/crates/linux/src/system/menu/surfaces.rs @@ -40,15 +40,26 @@ fn surface(id: &str, kind: &str, title: &Option) -> SurfaceInfo { } } -/// The surfaces of one listed window: a `window` entry always, a `sheet` -/// entry alongside it when the window is a modal dialog. +/// The kind a listed window adds beside its `window` entry: `alert` when the +/// frame is a showing alert, the predicate `snapshot --surface alert` roots +/// at, else `sheet` when it is a modal dialog, else none. +pub(crate) fn extra_kind(window: &ListedWindow) -> Option<&'static str> { + if window.alert { + Some("alert") + } else { + window.sheet.then_some("sheet") + } +} + +/// The surfaces of one listed window: a `window` entry always, an `alert` or +/// `sheet` entry alongside it when the window is one. pub(crate) fn surfaces_of(windows: &[ListedWindow]) -> Vec { windows .iter() .flat_map(|window| { let title = (!window.info.title.is_empty()).then(|| window.info.title.clone()); std::iter::once("window") - .chain(window.sheet.then_some("sheet")) + .chain(extra_kind(window)) .map(move |kind| surface(&window.info.id, kind, &title)) }) .collect() diff --git a/crates/linux/src/system/menu/surfaces_tests.rs b/crates/linux/src/system/menu/surfaces_tests.rs index 6fcab2186b..cb0c99e3fe 100644 --- a/crates/linux/src/system/menu/surfaces_tests.rs +++ b/crates/linux/src/system/menu/surfaces_tests.rs @@ -7,6 +7,7 @@ use agent_desktop_core::{AdapterError, ErrorCode}; fn window(id: &str, title: &str, sheet: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: id.to_owned(), @@ -152,3 +153,17 @@ fn an_incomplete_scan_still_reports_the_dialog_it_saw() { assert_eq!(dialogs.titles, ["Save Changes?".to_owned()]); assert!(!dialogs.complete); } + +#[test] +fn a_showing_alert_lists_an_alert_entry_in_place_of_the_sheet_entry() { + let mut alert = window("w-1", "Save changes?", true); + alert.alert = true; + let kinds: Vec<_> = surfaces_of(&[alert]) + .iter() + .map(|surface| surface.kind.clone()) + .collect(); + assert_eq!(kinds, ["window", "alert"]); + let mut plain = window("w-2", "Doc", false); + plain.alert = false; + assert_eq!(surfaces_of(&[plain]).len(), 1); +} diff --git a/crates/linux/src/system/process/protected_tests.rs b/crates/linux/src/system/process/protected_tests.rs index d0019c9a85..840797b042 100644 --- a/crates/linux/src/system/process/protected_tests.rs +++ b/crates/linux/src/system/process/protected_tests.rs @@ -92,6 +92,7 @@ fn a_launch_marker_that_cannot_be_read_refuses_instead_of_protecting_by_name() { fn window(unshown: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: "w-1".to_owned(), diff --git a/crates/linux/src/system/registry/listed_window.rs b/crates/linux/src/system/registry/listed_window.rs index d69df4d360..3fd2f10aff 100644 --- a/crates/linux/src/system/registry/listed_window.rs +++ b/crates/linux/src/system/registry/listed_window.rs @@ -13,6 +13,9 @@ pub(crate) struct ListedWindow { pub(crate) dialog: bool, pub(crate) frame: FrameFacts, pub(crate) sheet: bool, + /// The frame is a showing alert, by the predicate `snapshot --surface alert` + /// roots at. + pub(crate) alert: bool, /// The window neither shows nor is iconified. A toolkit that keeps a /// top-level window for reuse leaves such a husk on the registry after /// it hides or closes. diff --git a/crates/linux/src/system/signal/signal_capture_tests.rs b/crates/linux/src/system/signal/signal_capture_tests.rs index 79c9f6a7ad..027b44c599 100644 --- a/crates/linux/src/system/signal/signal_capture_tests.rs +++ b/crates/linux/src/system/signal/signal_capture_tests.rs @@ -45,6 +45,7 @@ impl World { fn listed(app: &RegistryApp, scripted: &Scripted) -> ListedWindow { ListedWindow { + alert: false, app: scripted.owner, info: WindowInfo { id: scripted.id.to_owned(), diff --git a/crates/linux/src/system/signal/signal_population_tests.rs b/crates/linux/src/system/signal/signal_population_tests.rs index eb647dbf8c..26257db614 100644 --- a/crates/linux/src/system/signal/signal_population_tests.rs +++ b/crates/linux/src/system/signal/signal_population_tests.rs @@ -24,6 +24,7 @@ fn app(bus: &str, pid: u32, instance: &str, name: &str) -> RegistryApp { fn window(owner: usize, id: &str, visible: bool) -> ListedWindow { ListedWindow { + alert: false, app: owner, info: WindowInfo { id: id.to_owned(), diff --git a/crates/linux/src/system/signal/signal_surfaces_tests.rs b/crates/linux/src/system/signal/signal_surfaces_tests.rs index b9830a670a..67f8209bf2 100644 --- a/crates/linux/src/system/signal/signal_surfaces_tests.rs +++ b/crates/linux/src/system/signal/signal_surfaces_tests.rs @@ -24,6 +24,7 @@ fn app() -> RegistryApp { fn window(id: &str, title: &str, sheet: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: id.to_owned(), diff --git a/crates/linux/src/system/window/ghost_window_tests.rs b/crates/linux/src/system/window/ghost_window_tests.rs index a08a2744d9..a3a84255c2 100644 --- a/crates/linux/src/system/window/ghost_window_tests.rs +++ b/crates/linux/src/system/window/ghost_window_tests.rs @@ -6,6 +6,7 @@ use crate::system::x11::{FrameFacts, X11Client, X11State}; fn window(id: &str, title: &str, unshown: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: id.to_owned(), diff --git a/crates/linux/src/system/window/listed_twins_tests.rs b/crates/linux/src/system/window/listed_twins_tests.rs index f28b9cde98..b18d04cf9d 100644 --- a/crates/linux/src/system/window/listed_twins_tests.rs +++ b/crates/linux/src/system/window/listed_twins_tests.rs @@ -5,6 +5,7 @@ use crate::system::x11::{FrameFacts, X11Client}; fn listed(pid: u32, title: &str, active: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: format!("w-{pid}-{title}-{active}"), diff --git a/crates/linux/src/system/window/stopped_windows.rs b/crates/linux/src/system/window/stopped_windows.rs index 164d3097c8..5ab1175362 100644 --- a/crates/linux/src/system/window/stopped_windows.rs +++ b/crates/linux/src/system/window/stopped_windows.rs @@ -42,6 +42,7 @@ pub(crate) fn of_stopped_apps( continue; } found.push(ListedWindow { + alert: false, app: index, info: WindowInfo { id, diff --git a/crates/linux/src/system/window/window_filter_deadline_tests.rs b/crates/linux/src/system/window/window_filter_deadline_tests.rs index b88336cfb0..50866273c8 100644 --- a/crates/linux/src/system/window/window_filter_deadline_tests.rs +++ b/crates/linux/src/system/window/window_filter_deadline_tests.rs @@ -7,6 +7,7 @@ use crate::system::x11::FrameFacts; #[test] fn an_expired_window_read_is_timeout_instead_of_an_unsupported_surface() { let window = ListedWindow { + alert: false, app: 0, info: WindowInfo { id: "window".to_owned(), diff --git a/crates/linux/src/system/window/window_filter_helper_tests.rs b/crates/linux/src/system/window/window_filter_helper_tests.rs index 6afcea9e95..9450794eb8 100644 --- a/crates/linux/src/system/window/window_filter_helper_tests.rs +++ b/crates/linux/src/system/window/window_filter_helper_tests.rs @@ -20,6 +20,7 @@ fn bounds(x: i32) -> Extents { fn window(pid: u32, x: i32) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: format!("window-{pid}"), diff --git a/crates/linux/src/system/window/window_filter_tests.rs b/crates/linux/src/system/window/window_filter_tests.rs index f13a292ba6..ec0b7f642d 100644 --- a/crates/linux/src/system/window/window_filter_tests.rs +++ b/crates/linux/src/system/window/window_filter_tests.rs @@ -190,6 +190,7 @@ fn listed( ) -> crate::system::registry::listed_window::ListedWindow { use agent_desktop_core::{WindowInfo, WindowState}; crate::system::registry::listed_window::ListedWindow { + alert: false, app: 0, info: WindowInfo { id: format!("{:?}", frame.extents), diff --git a/crates/linux/src/system/window/window_listing.rs b/crates/linux/src/system/window/window_listing.rs index 29b6317f49..f30e5f86fb 100644 --- a/crates/linux/src/system/window/window_listing.rs +++ b/crates/linux/src/system/window/window_listing.rs @@ -64,6 +64,7 @@ fn listed( global_position, }, sheet: crate::tree::surfaces::is_sheet(node), + alert: crate::tree::surfaces::is_surface(node, agent_desktop_core::SnapshotSurface::Alert), unshown: state.visible == Some(false) && state.minimized == Some(false), }) } diff --git a/crates/linux/src/system/window/window_ops_tests.rs b/crates/linux/src/system/window/window_ops_tests.rs index bf72811991..671b500704 100644 --- a/crates/linux/src/system/window/window_ops_tests.rs +++ b/crates/linux/src/system/window/window_ops_tests.rs @@ -9,6 +9,7 @@ use crate::system::x11::{FrameExtents, FrameFacts, X11Client, X11State}; fn window(title: &str, active: bool, modal: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: format!("w-1.1-{title}"), diff --git a/crates/linux/src/system/window/window_order_tests.rs b/crates/linux/src/system/window/window_order_tests.rs index 4bbce730ed..0016211694 100644 --- a/crates/linux/src/system/window/window_order_tests.rs +++ b/crates/linux/src/system/window/window_order_tests.rs @@ -6,6 +6,7 @@ use crate::system::x11::{FrameFacts, X11Client, X11State}; fn window(title: &str, focused: bool) -> ListedWindow { ListedWindow { + alert: false, app: 0, info: WindowInfo { id: format!("w-{title}"), From 9faa9fb95edb230b70582552f27fb1e6003e66c6 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:49:16 -0800 Subject: [PATCH 06/26] fix(macos): walk to the window before saying a button is outside a popover The ancestry walk stopped after eight levels and answered "no popover", so a button deeper than that inside a popover skipped the headless refusal. The walk now goes up to the window or application, and running out answers unknown, which refuses. --- crates/macos/src/actions/background_effect.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/macos/src/actions/background_effect.rs b/crates/macos/src/actions/background_effect.rs index 268b816af7..78380f92af 100644 --- a/crates/macos/src/actions/background_effect.rs +++ b/crates/macos/src/actions/background_effect.rs @@ -26,7 +26,6 @@ const ELLIPSES: &[&str] = &["\u{2026}", "..."]; const SHOWS_MENU: &str = "shows_menu"; const OPENS_DIALOG: &str = "opens_dialog"; const POPOVER_COMMAND: &str = "popover_command"; -const POPOVER_ANCESTOR_WALK: usize = 8; /// Refuses `operation` with `POLICY_DENIED` when `policy` does not permit /// `effect`, and reports `kind` as the reason the action takes the foreground. @@ -152,11 +151,13 @@ fn read_target(element: &AXElement, deadline: Deadline) -> Option { }) } -/// Whether a popover holds `element`, from a bounded walk up its ancestors. -/// None when an ancestor cannot be read. +/// Whether a popover holds `element`, from a walk up its ancestors to its +/// window or application. None when an ancestor cannot be read, which is also +/// how the walk ends once the deadline runs out, so an unknown answer is never +/// read as "no". fn inside_popover(element: &AXElement, deadline: Deadline) -> Option { let mut current = element.clone(); - for _ in 0..POPOVER_ANCESTOR_WALK { + loop { let Some(parent) = crate::tree::surface_read::element(¤t, "AXParent", deadline).ok()? else { @@ -171,7 +172,6 @@ fn inside_popover(element: &AXElement, deadline: Deadline) -> Option { _ => current = parent, } } - Some(false) } #[cfg(test)] From 6431580e78434f54bbdd7c0377e328698da37e30 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:49:16 -0800 Subject: [PATCH 07/26] fix: keep wait --surface polling through a retryable read failure One retryable accessibility read failure ended the wait at once, even with most of its timeout left. Only a failure that cannot be retried ends it now. --- crates/core/src/commands/tests/waits/stub.rs | 8 ++- .../core/src/commands/tests/waits/success.rs | 72 ++++++++++++++++++- crates/core/src/commands/wait.rs | 54 +++++++------- crates/core/src/commands/wait_timeout.rs | 16 +++-- 4 files changed, 117 insertions(+), 33 deletions(-) diff --git a/crates/core/src/commands/tests/waits/stub.rs b/crates/core/src/commands/tests/waits/stub.rs index 13d18681d1..a537fab7b0 100644 --- a/crates/core/src/commands/tests/waits/stub.rs +++ b/crates/core/src/commands/tests/waits/stub.rs @@ -61,6 +61,8 @@ pub(super) fn signals(windows: Vec, apps: Vec) -> SignalBas #[derive(Default)] pub(super) struct Stub { pub(super) windows: Mutex, AdapterError>>>, + pub(super) surfaces: Mutex, AdapterError>>>, + pub(super) supported_surfaces: Vec, pub(super) tree: Option, pub(super) notifications: Mutex, AdapterError>>>, pub(super) menu_times_out: bool, @@ -73,7 +75,7 @@ impl ObservationOps for Stub { _: ProcessIdentity, _: Deadline, ) -> Result, AdapterError> { - Ok(Vec::new()) + next(&self.surfaces).unwrap_or_else(|| Ok(Vec::new())) } fn observe_tree( @@ -102,6 +104,10 @@ impl ActionOps for Stub {} impl InputOps for Stub {} impl SystemOps for Stub { + fn supported_surfaces(&self) -> Vec { + self.supported_surfaces.clone() + } + fn wait_for_menu( &self, _: ProcessIdentity, diff --git a/crates/core/src/commands/tests/waits/success.rs b/crates/core/src/commands/tests/waits/success.rs index 4432671389..cfce6668d0 100644 --- a/crates/core/src/commands/tests/waits/success.rs +++ b/crates/core/src/commands/tests/waits/success.rs @@ -1,9 +1,11 @@ -use super::stub::{Stub, app, args, build, golden, mode, run, script, selector, signals, stable}; +use super::stub::{ + Stub, app, args, build, golden, mode, payload, run, script, selector, signals, stable, +}; use super::stub::{window, with_buttons}; use crate::commands::wait::execute; use crate::commands::wait_surface::SurfaceWait; use crate::refs::refs_test_support::HomeGuard; -use crate::{CommandContext, NotificationInfo, SignalBaseline}; +use crate::{CommandContext, NotificationInfo, SignalBaseline, SurfaceInfo}; use serde_json::{Value, json}; #[test] @@ -108,6 +110,72 @@ fn event_wait_reports_the_window_and_app_events() { ); } +#[test] +fn a_surface_wait_polls_through_a_retryable_read_failure() { + let stub = Stub { + supported_surfaces: vec![crate::SnapshotSurface::Menu], + surfaces: script(vec![ + Err( + crate::AdapterError::new(crate::ErrorCode::AppUnresponsive, "busy") + .with_disposition(crate::DeliverySemantics::not_delivered()), + ), + Ok(vec![SurfaceInfo { + id: "menu-1".into(), + kind: "menu".into(), + title: None, + item_count: None, + unclassified: Vec::new(), + }]), + ]), + ..Default::default() + }; + + let data = run( + &stub, + mode!( + surface, + SurfaceWait::Open(Some(crate::SnapshotSurface::Menu)) + ), + Some("TextEdit"), + 2_000, + ) + .unwrap(); + + assert_eq!(data["found"], json!(true)); +} + +#[test] +fn a_surface_wait_that_never_read_the_surfaces_reports_the_error_and_no_observation() { + let retryable = || { + Err( + crate::AdapterError::new(crate::ErrorCode::AppUnresponsive, "busy") + .with_disposition(crate::DeliverySemantics::not_delivered()), + ) + }; + let stub = Stub { + supported_surfaces: vec![crate::SnapshotSurface::Menu], + surfaces: script(vec![retryable(); 6]), + ..Default::default() + }; + + let error = payload(run( + &stub, + mode!( + surface, + SurfaceWait::Open(Some(crate::SnapshotSurface::Menu)) + ), + Some("TextEdit"), + 250, + )); + + assert_eq!(error["code"], json!("TIMEOUT")); + assert_eq!( + error["details"]["last_error"]["code"], + json!("APP_UNRESPONSIVE") + ); + assert!(error["details"].get("last_observed").is_none()); +} + #[test] fn a_surface_wait_for_a_kind_the_platform_cannot_show_is_refused_at_once() { let started = std::time::Instant::now(); diff --git a/crates/core/src/commands/wait.rs b/crates/core/src/commands/wait.rs index d63732d0a7..18d6e271dd 100644 --- a/crates/core/src/commands/wait.rs +++ b/crates/core/src/commands/wait.rs @@ -155,33 +155,37 @@ fn wait_for_surface( .find(|surface| wait_surface::is_kind(surface, kind)) .cloned() }; - let surfaces = match deadline.poll_until( - deadline.remaining(), - Duration::from_millis(100), - || adapter.list_surfaces(process.clone(), deadline), - |read| { - read.as_ref() - .map_or(true, |surfaces| open(surfaces).is_some()) - }, - ) { - Ok(surfaces) => surfaces, - Err(error) if deadline.is_expired() || wait_timeout::is_deadline_expired(&error) => { - Vec::new() + let mut last_observed = None; + let mut last_error = None; + loop { + match adapter.list_surfaces(process.clone(), deadline) { + Ok(surfaces) => { + if let Some(surface) = open(&surfaces) { + return Ok(json!({ + "found": true, + "surface": surface, + "elapsed_ms": start.elapsed().as_millis(), + })); + } + last_observed = Some(surfaces); + } + Err(error) if wait_timeout::is_deadline_expired(&error) => break, + Err(error) if error.is_retryable_poll_failure() => { + last_error = Some(json!({ "code": error.code.as_str(), "message": error.message })); + } + Err(error) => return Err(error.into()), } - Err(error) => return Err(error.into()), - }; - match open(&surfaces) { - Some(surface) => Ok(json!({ - "found": true, - "surface": surface, - "elapsed_ms": start.elapsed().as_millis(), - })), - None => wait_timeout::surface( - kind.map_or("any", |kind| kind.as_str()), - timeout_ms, - &surfaces, - ), + if deadline.is_expired() { + break; + } + deadline.pause(Duration::from_millis(100)); } + wait_timeout::surface( + kind.map_or("any", |kind| kind.as_str()), + timeout_ms, + last_observed.as_deref(), + last_error, + ) } fn wait_for_window( diff --git a/crates/core/src/commands/wait_timeout.rs b/crates/core/src/commands/wait_timeout.rs index 58f180e509..d314896113 100644 --- a/crates/core/src/commands/wait_timeout.rs +++ b/crates/core/src/commands/wait_timeout.rs @@ -31,17 +31,23 @@ pub(crate) fn menu(mut error: AdapterError, timeout_ms: u64) -> AppError { pub(crate) fn surface( kind: &str, timeout_ms: u64, - observed: &[crate::SurfaceInfo], + observed: Option<&[crate::SurfaceInfo]>, + last_error: Option, ) -> Result { let what = if kind == "any" { "No surface".to_owned() } else { format!("No {kind} surface") }; - timeout_err( - format!("{what} was open within {timeout_ms}ms"), - json!({ "predicate": "surface", "surface": kind, "timeout_ms": timeout_ms, "last_observed": observed }), - ) + let mut details = json!({ "predicate": "surface", "surface": kind, "timeout_ms": timeout_ms }); + let message = match observed { + Some(observed) => { + details["last_observed"] = json!(observed); + format!("{what} was open within {timeout_ms}ms") + } + None => format!("The surfaces could not be read within {timeout_ms}ms"), + }; + timeout_err(message, with_last_error(details, last_error)) } /// Builds the wait-loop TIMEOUT error. Every payload carries From 340c33a125613be97e5b8c7e5c3a05640b133b86 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:49:17 -0800 Subject: [PATCH 08/26] fix: report a post-action surface read that failed A failed read of the surfaces an action raised became an empty list, the same as "no overlay opened". The result now carries details.surfaces: "not_read" when the read fails. --- apps/docs/content/docs/json-output.mdx | 2 +- crates/core/src/actions/action_result.rs | 15 ++++++++++++++ .../core/src/actions/action_result_tests.rs | 13 ++++++++++++ crates/core/src/ref_action/mod.rs | 20 +++++-------------- skills/agent-desktop/SKILL.md | 4 ++-- tests/fixtures/contract/actions-click.json | 2 +- .../fixtures/contract/lifecycle-delivery.json | 2 +- 7 files changed, 38 insertions(+), 20 deletions(-) diff --git a/apps/docs/content/docs/json-output.mdx b/apps/docs/content/docs/json-output.mdx index baaf839a13..ff2f5dd1e1 100644 --- a/apps/docs/content/docs/json-output.mdx +++ b/apps/docs/content/docs/json-output.mdx @@ -100,7 +100,7 @@ A snapshot that runs out of budget still returns `ok: true`, with `"complete": f ## Action results and disposition -A ref action such as `click`, `type`, or `toggle` returns `data.action` and `data.disposition`, and can add `steps` (each mechanism tried), `post_state`, `surfaces` (surfaces open once the action settled), and `details`. `disposition` has two fields, `delivery` and `retry`; on success, `delivery` is `delivered_verified`, `delivered_unverified`, or `not_delivered` (already satisfied). What each value proves, and when a retry is safe, is in [Errors and recovery](/desktop/errors-and-recovery#disposition). +A ref action such as `click`, `type`, or `toggle` returns `data.action` and `data.disposition`, and can add `steps` (each mechanism tried), `post_state`, `surfaces` (surfaces open once the action settled), and `details`. When the read of `surfaces` fails, `details.surfaces` is `"not_read"`: an absent `surfaces` then does not mean that no overlay opened. `disposition` has two fields, `delivery` and `retry`; on success, `delivery` is `delivered_verified`, `delivered_unverified`, or `not_delivered` (already satisfied). What each value proves, and when a retry is safe, is in [Errors and recovery](/desktop/errors-and-recovery#disposition). ### Post-action observation diff --git a/crates/core/src/actions/action_result.rs b/crates/core/src/actions/action_result.rs index a9efbd2ee4..55864cd936 100644 --- a/crates/core/src/actions/action_result.rs +++ b/crates/core/src/actions/action_result.rs @@ -94,6 +94,21 @@ impl ActionResult { self } + /// Records the overlays read once the action settled. A read that failed + /// is not "no overlay": it is reported as `details.surfaces: "not_read"`. + pub(crate) fn with_surfaces_read( + mut self, + read: Result, crate::AdapterError>, + ) -> Self { + match read { + Ok(surfaces) => { + self.surfaces = surfaces; + self + } + Err(_) => self.with_details(serde_json::json!({ "surfaces": "not_read" })), + } + } + pub fn with_verified_delivery(mut self) -> Self { if self.disposition == DeliverySemantics::delivered_unverified() { self.disposition = DeliverySemantics::delivered_verified(); diff --git a/crates/core/src/actions/action_result_tests.rs b/crates/core/src/actions/action_result_tests.rs index 3e560e7cc8..de35264276 100644 --- a/crates/core/src/actions/action_result_tests.rs +++ b/crates/core/src/actions/action_result_tests.rs @@ -185,3 +185,16 @@ fn an_annotation_keeps_the_details_an_inner_layer_set() { assert_eq!(details["pointer"], "verified"); assert_eq!(details["delivered_events"], 2); } + +#[test] +fn a_failed_surface_read_is_reported_and_not_shown_as_no_overlay() { + let result = ActionResult::delivered_unverified("click").with_surfaces_read(Err( + crate::AdapterError::new(crate::ErrorCode::Timeout, "surface read timed out"), + )); + + assert!(result.surfaces.is_empty()); + assert_eq!( + result.details, + Some(serde_json::json!({ "surfaces": "not_read" })) + ); +} diff --git a/crates/core/src/ref_action/mod.rs b/crates/core/src/ref_action/mod.rs index 97cb82d643..de12076d55 100644 --- a/crates/core/src/ref_action/mod.rs +++ b/crates/core/src/ref_action/mod.rs @@ -158,7 +158,11 @@ pub(crate) fn dispatch_resolved_landing( ); let mut result = dispatch_result?; if raises_surface { - result.surfaces = settled_surfaces(&final_target, expected_process); + result = result.with_surfaces_read(final_target.adapter.surfaces_raised_by( + expected_process, + final_target.handle, + final_target.deadline, + )); } final_target .context @@ -170,20 +174,6 @@ pub(crate) fn dispatch_resolved_landing( Ok((result, handle)) } -/// An action that opens a sheet, menu, or alert leaves the caller staring at a -/// success envelope with no hint that the application is now waiting on a -/// dialog. Reporting the overlays saves a round of window archaeology. Purely -/// informational, so a failed read never disturbs delivered work. -fn settled_surfaces( - target: &ResolvedRefAction<'_>, - process: crate::ProcessIdentity, -) -> Vec { - target - .adapter - .surfaces_raised_by(process, target.handle, target.deadline) - .unwrap_or_default() -} - pub(crate) fn mark_pre_dispatch_resolution_failure(error: AdapterError) -> AdapterError { match error.disposition { crate::DeliverySemantics::Unknown | crate::DeliverySemantics::NotDelivered => { diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.md index 7c6947b366..0a03c38cfc 100644 --- a/skills/agent-desktop/SKILL.md +++ b/skills/agent-desktop/SKILL.md @@ -70,8 +70,8 @@ agent-desktop get '@s8f3k2p9:e4' --property value agent-desktop close-app "" # a save prompt keeps the app open; see --force below ``` -If an action reports `data.surfaces`, inspect the overlay before acting on the -window behind it. A menu, sheet, or alert needs its own surface observation. +If an action reports `data.surfaces`, inspect the overlay before acting on the window behind it. A menu, sheet, or alert needs its own surface observation. +`data.details.surfaces: "not_read"` means that read failed, so run `list-surfaces` before assuming no overlay opened. Attached selector waits usually observe the parent window, not a separate popup. A gone match cannot prove that popup closed, and matching text elsewhere can satisfy an appearance wait. Use `launch` with a program name or path accepted by the platform. A running diff --git a/tests/fixtures/contract/actions-click.json b/tests/fixtures/contract/actions-click.json index a5160ed24c..168d067b33 100644 --- a/tests/fixtures/contract/actions-click.json +++ b/tests/fixtures/contract/actions-click.json @@ -1 +1 @@ -{"changed":{"action":"click","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"post_state":{"enabled":true,"hidden":false,"offscreen":false,"role":"checkbox","states":["checked"]},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"uncertain":{"code":"APP_UNRESPONSIVE","details":{"ax_error":-25204,"post_action_observation":{"elapsed_ms":0,"expected":"present","kind":"post_action_observation","outcome":"expected_state_observed","process_identity":{"pid":1,"process_instance":"test-instance"},"selector":":Agree","selector_matches":true,"surface":"menubar"}},"disposition":{"delivery":"delivery_uncertain","retry":"unsafe"},"message":"Application 'TargetApp' is not responding","suggestion":"Wait for the app to recover or force-quit it before retrying automation"}} +{"changed":{"action":"click","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0},"surfaces":"not_read"},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"post_state":{"enabled":true,"hidden":false,"offscreen":false,"role":"checkbox","states":["checked"]},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"uncertain":{"code":"APP_UNRESPONSIVE","details":{"ax_error":-25204,"post_action_observation":{"elapsed_ms":0,"expected":"present","kind":"post_action_observation","outcome":"expected_state_observed","process_identity":{"pid":1,"process_instance":"test-instance"},"selector":":Agree","selector_matches":true,"surface":"menubar"}},"disposition":{"delivery":"delivery_uncertain","retry":"unsafe"},"message":"Application 'TargetApp' is not responding","suggestion":"Wait for the app to recover or force-quit it before retrying automation"}} diff --git a/tests/fixtures/contract/lifecycle-delivery.json b/tests/fixtures/contract/lifecycle-delivery.json index c316065fba..7d858f4050 100644 --- a/tests/fixtures/contract/lifecycle-delivery.json +++ b/tests/fixtures/contract/lifecycle-delivery.json @@ -1 +1 @@ -{"focus":{"action":"focus","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"scroll":{"action":"scroll","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"scroll_to":{"action":"scroll-to","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"select":{"action":"select","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]}} +{"focus":{"action":"focus","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"scroll":{"action":"scroll","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"scroll_to":{"action":"scroll-to","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0}},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]},"select":{"action":"select","details":{"auto_wait":{"lease_contention_count":0,"lease_hold_ms":0,"read_only_preflight_attempts":0,"read_only_resolve_attempts":0},"surfaces":"not_read"},"disposition":{"delivery":"delivered_verified","retry":"unsafe"},"steps":[{"label":"press","mechanism":"semantic_api","outcome":"succeeded","verified":true}]}} From ca2c5e5518614ff04b8c11f3a2c62438df608271 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:49:17 -0800 Subject: [PATCH 09/26] docs(macos): state the clipboard helper rules in the skill The rewritten skill dropped the checks the packaged clipboard helper must pass, so a failed install read like an empty clipboard. --- skills/agent-desktop-macos/SKILL.md | 1 + 1 file changed, 1 insertion(+) diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.md index f96ddd0257..256f50e9f3 100644 --- a/skills/agent-desktop-macos/SKILL.md +++ b/skills/agent-desktop-macos/SKILL.md @@ -92,3 +92,4 @@ Read the disposition before applying a fix. Match both the code and message. | `PERM_DENIED`: `private file parent is accessible by group or other users` | The state root is not private. Run `chmod 700 "${AGENT_DESKTOP_HOME:-$HOME/.agent-desktop}"`, or use a new state root and let the tool create it. | | `PERM_DENIED`: `private file parent is not owned by the effective user` | The directory belongs to another user. Point `AGENT_DESKTOP_HOME` at a new directory under your home and let the tool create it; do not take over someone else's state. | | `needs_setup` from `sandbox status` for a sandbox that worked before | The guest agent, `agent-desktop-guest`, is not running in the guest, or Accessibility is off for it. Run `sandbox stop `, then `sandbox start --window`. In the guest, turn on automatic login, run `sh "/Volumes/My Shared Files/guest-setup.sh"` in Terminal, and switch on **agent-desktop-guest** in System Settings > Privacy & Security > Accessibility. Then check `status` on the host. A sandbox set up by agent-desktop 1.3.0 needs this once. | +| `ACTION_NOT_SUPPORTED`: `The packaged macOS clipboard helper is missing or invalid` | Every clipboard command runs the packaged `agent-desktop-macos-helper` beside the binary, and it is checked before launch: a regular file (not a symlink) owned by you, executable, one link, no group or world write, no ACL that lets someone else change it, under directories owned by you or root that are not group or world writable unless sticky. `details.kind` is `clipboard_helper_invalid` or `clipboard_helper_not_found`, and `platform_detail` names the failed rule. Repair the install; the clipboard is not empty. | From 096a54a7c8caa5dcb91db7eb168e389146ff9ea3 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Thu, 19 Nov 2026 17:08:04 -0800 Subject: [PATCH 10/26] fix(macos): search for a popover while the app shows a window AX does not list The search ran only while a window sat at the pop-up menu level, but a standard NSPopover draws at the normal level (Calendar's event and quick-event popovers are layer 0, kCGWindowAlpha 1, absent from AXWindows). The gate is now any on-screen window of the process, outside the menu bar levels and not transparent, that no AX window names; a closed popover's window stays on screen at alpha 0 and does not count. --- crates/macos/src/system/window/cg_window.rs | 2 +- .../macos/src/system/window/popup_window.rs | 46 +++++++++++++------ .../src/system/window/popup_window_tests.rs | 34 +++++++++++--- crates/macos/src/tree/surface_inventory.rs | 21 ++++++--- 4 files changed, 77 insertions(+), 26 deletions(-) diff --git a/crates/macos/src/system/window/cg_window.rs b/crates/macos/src/system/window/cg_window.rs index ccb18a62f9..5cbaa472e5 100644 --- a/crates/macos/src/system/window/cg_window.rs +++ b/crates/macos/src/system/window/cg_window.rs @@ -383,7 +383,7 @@ fn rect_field(dict: &WindowDictionary, key: &str) -> Option { }) } -fn int_or_float_field(dict: &WindowDictionary, key: &str) -> Option { +pub(super) fn int_or_float_field(dict: &WindowDictionary, key: &str) -> Option { use crate::tree::properties::cf_type::borrowed_cf_number; use core_foundation::base::TCFType; diff --git a/crates/macos/src/system/window/popup_window.rs b/crates/macos/src/system/window/popup_window.rs index 6c5e8168f6..15e27084c7 100644 --- a/crates/macos/src/system/window/popup_window.rs +++ b/crates/macos/src/system/window/popup_window.rs @@ -1,29 +1,49 @@ -//! Whether an application shows an open menu or popover. AppKit draws both in -//! a window at the pop-up menu level, and the accessibility window list -//! leaves that window out. +//! Whether an application shows a window that its accessibility window list +//! leaves out. AppKit draws a popover, an open menu and a sharing picker each +//! in a window of its own that `AXWindows` does not name: a popover at the +//! normal level, a menu or a picker at the pop-up menu level. -use super::cg_window::{bool_field, int_field, window_dictionaries}; +use rustc_hash::FxHashSet; +use super::cg_window::{bool_field, int_field, int_or_float_field, window_dictionaries}; + +/// `kCGMainMenuWindowLevel` to `kCGStatusWindowLevel`: the menu bar and its +/// status items, which are not surfaces of a window. +const MENU_BAR_LEVELS: std::ops::RangeInclusive = 24..=25; /// `kCGPopUpMenuWindowLevel`. const POPUP_MENU_WINDOW_LEVEL: i64 = 101; -fn is_open_popup(layer: Option, on_screen: bool) -> bool { - layer == Some(POPUP_MENU_WINDOW_LEVEL) && on_screen +/// Whether an on-screen window can hold a surface the accessibility window +/// list does not name. A closed popover leaves its window on screen at alpha 0. +fn holds_unlisted_surface(layer: i64, alpha: f64, number: i64, listed: &FxHashSet) -> bool { + (0..=POPUP_MENU_WINDOW_LEVEL).contains(&layer) + && !MENU_BAR_LEVELS.contains(&layer) + && alpha > 0.0 + && !listed.contains(&number) } -/// Whether `pid` has an on-screen window at the pop-up menu level. A window -/// list that cannot be read says yes, so a caller searches instead of -/// missing a surface. -pub(crate) fn shows_popup_window(pid: i32) -> bool { +/// Whether `pid` has an on-screen window that none of `listed`, the window ids +/// of its accessibility windows, names. A window list that cannot be read says +/// yes, so a caller searches instead of missing a surface. +pub(crate) fn shows_unlisted_window(pid: i32, listed: &FxHashSet) -> bool { let Ok(windows) = window_dictionaries() else { return true; }; windows.iter().any(|window| { int_field(window, "kCGWindowOwnerPID") == Some(i64::from(pid)) - && is_open_popup( + && bool_field(window, "kCGWindowIsOnscreen").unwrap_or(true) + && match ( int_field(window, "kCGWindowLayer"), - bool_field(window, "kCGWindowIsOnscreen").unwrap_or(true), - ) + int_field(window, "kCGWindowNumber"), + ) { + (Some(layer), Some(number)) => holds_unlisted_surface( + layer, + int_or_float_field(window, "kCGWindowAlpha").unwrap_or(1.0), + number, + listed, + ), + _ => true, + } }) } diff --git a/crates/macos/src/system/window/popup_window_tests.rs b/crates/macos/src/system/window/popup_window_tests.rs index 3d9fe2f6c0..5f33ef64a2 100644 --- a/crates/macos/src/system/window/popup_window_tests.rs +++ b/crates/macos/src/system/window/popup_window_tests.rs @@ -1,9 +1,31 @@ -use super::is_open_popup; +use super::holds_unlisted_surface; +use rustc_hash::FxHashSet; #[test] -fn only_an_on_screen_window_at_the_popup_menu_level_is_an_open_popup() { - assert!(is_open_popup(Some(101), true)); - assert!(!is_open_popup(Some(101), false)); - assert!(!is_open_popup(Some(0), true)); - assert!(!is_open_popup(None, true)); +fn only_a_shown_window_the_accessibility_list_leaves_out_can_hold_a_surface() { + let listed: FxHashSet = [7].into_iter().collect(); + assert!( + holds_unlisted_surface(0, 1.0, 9, &listed), + "a popover window" + ); + assert!( + holds_unlisted_surface(101, 1.0, 9, &listed), + "a menu or picker" + ); + assert!( + !holds_unlisted_surface(0, 1.0, 7, &listed), + "a listed window" + ); + assert!( + !holds_unlisted_surface(0, 0.0, 9, &listed), + "a closed popover" + ); + assert!( + !holds_unlisted_surface(25, 1.0, 9, &listed), + "a status item" + ); + assert!( + !holds_unlisted_surface(-2147483603, 1.0, 9, &listed), + "the desktop" + ); } diff --git a/crates/macos/src/tree/surface_inventory.rs b/crates/macos/src/tree/surface_inventory.rs index 8c7d5a5d5c..13a3734054 100644 --- a/crates/macos/src/tree/surface_inventory.rs +++ b/crates/macos/src/tree/surface_inventory.rs @@ -12,10 +12,18 @@ pub(crate) fn list_surfaces_for_process( ) -> Result, AdapterError> { let app = element_for_pid(identity.pid()); super::app_menu::observe(identity, deadline, || { - let popovers = crate::system::window::popup_window::shows_popup_window(identity.pid()); - list_surfaces_once(identity.pid(), deadline, popovers, || { - Ok(read_array(&app, "AXWindows", deadline)?.unwrap_or_default()) - }) + let windows = read_array(&app, "AXWindows", deadline)?.unwrap_or_default(); + let listed = windows + .iter() + .filter_map(|window| { + crate::system::window::window_resolve::ax_window_id_with_deadline(window, deadline) + .ok() + .flatten() + }) + .collect(); + let popovers = + crate::system::window::popup_window::shows_unlisted_window(identity.pid(), &listed); + list_surfaces_once(identity.pid(), deadline, popovers, || Ok(windows)) }) } @@ -63,8 +71,9 @@ fn list_surfaces_once( } /// A headless target window is rarely the focused one, and a popover hangs -/// below the control that raised it, so while the application shows a pop-up -/// window every window gets the bounded popover search. A window whose search +/// below the control that raised it, so while the application shows a window +/// its accessibility window list leaves out, every window gets the bounded +/// popover search. A window whose search /// reached its element limit is left out. fn push_anchored_popover( window: &AXElement, From 9afc26df1341276eae38c900e8663af1cc92226d Mon Sep 17 00:00:00 2001 From: Lahfir Date: Thu, 19 Nov 2026 17:08:04 -0800 Subject: [PATCH 11/26] fix: match only the overlay kinds for wait --surface any Linux and Windows list a window entry for every window, so any returned at once with a plain window instead of waiting for an overlay. --- crates/core/src/commands/wait_surface.rs | 13 ++++++++++++- crates/core/src/commands/wait_surface_tests.rs | 5 +++++ src/cli_args/system.rs | 2 +- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/core/src/commands/wait_surface.rs b/crates/core/src/commands/wait_surface.rs index bf7cb9faf4..cec56f0c51 100644 --- a/crates/core/src/commands/wait_surface.rs +++ b/crates/core/src/commands/wait_surface.rs @@ -52,11 +52,22 @@ fn open_kind(kind: &str) -> Result, AppError> { } } +/// The kinds `wait --surface` names; `any` is any one of them, never a plain +/// window, which Linux and Windows list for every window. +const OPEN_KINDS: [SnapshotSurface; 4] = [ + SnapshotSurface::Popover, + SnapshotSurface::Sheet, + SnapshotSurface::Alert, + SnapshotSurface::Menu, +]; + /// Whether a listed surface is of the kind a wait asks for. A context menu is /// a menu. pub(crate) fn is_kind(surface: &SurfaceInfo, kind: Option) -> bool { match kind { - None => true, + None => OPEN_KINDS + .into_iter() + .any(|kind| is_kind(surface, Some(kind))), Some(SnapshotSurface::Menu) => matches!(surface.kind.as_str(), "menu" | "context_menu"), Some(kind) => surface.kind == kind.as_str(), } diff --git a/crates/core/src/commands/wait_surface_tests.rs b/crates/core/src/commands/wait_surface_tests.rs index 94cf4cc7d0..44849bec2e 100644 --- a/crates/core/src/commands/wait_surface_tests.rs +++ b/crates/core/src/commands/wait_surface_tests.rs @@ -73,4 +73,9 @@ fn a_listed_surface_matches_its_kind_and_a_context_menu_is_a_menu() { Some(SnapshotSurface::Menu) )); assert!(is_kind(&listed("alert"), None)); + assert!(is_kind(&listed("context_menu"), None)); + assert!( + !is_kind(&listed("window"), None), + "any must not match a plain window, which Linux and Windows list for every window" + ); } diff --git a/src/cli_args/system.rs b/src/cli_args/system.rs index 3e4d658681..22fa102d14 100644 --- a/src/cli_args/system.rs +++ b/src/cli_args/system.rs @@ -251,7 +251,7 @@ pub(crate) struct WaitEventArgs { #[arg( long, value_name = "KIND", - help = "Block until a surface of this kind is open in the app: popover, sheet, alert, menu, or any. A surface already open counts, so it also finds one that opened just after a click" + help = "Block until a surface of this kind is open in the app: popover, sheet, alert, menu, or any of them. A surface already open counts, so it also finds one that opened just after a click" )] pub surface: Option, } From 2e926847f30cb2c7ffa9a3f67ab67cf3496534df Mon Sep 17 00:00:00 2001 From: Lahfir Date: Thu, 19 Nov 2026 17:14:46 -0800 Subject: [PATCH 12/26] fix: stop calling the app busy when a surface wait saw no such surface The wait read the surfaces each poll and the app answered, but the timeout still said the application may be busy or unresponsive. It now points at details.last_observed and says a longer timeout helps only for a late surface. --- .../core/src/commands/tests/waits/success.rs | 24 +++++++++++++++++++ crates/core/src/commands/wait_timeout.rs | 18 ++++++++------ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/crates/core/src/commands/tests/waits/success.rs b/crates/core/src/commands/tests/waits/success.rs index cfce6668d0..0a1dc7ab74 100644 --- a/crates/core/src/commands/tests/waits/success.rs +++ b/crates/core/src/commands/tests/waits/success.rs @@ -176,6 +176,30 @@ fn a_surface_wait_that_never_read_the_surfaces_reports_the_error_and_no_observat assert!(error["details"].get("last_observed").is_none()); } +#[test] +fn a_surface_wait_that_saw_no_such_surface_does_not_call_the_app_busy() { + let stub = Stub { + supported_surfaces: vec![crate::SnapshotSurface::Menu], + ..Default::default() + }; + + let error = payload(run( + &stub, + mode!( + surface, + SurfaceWait::Open(Some(crate::SnapshotSurface::Menu)) + ), + Some("TextEdit"), + 250, + )); + + assert_eq!(error["code"], json!("TIMEOUT")); + assert_eq!(error["details"]["last_observed"], json!([])); + let suggestion = error["suggestion"].as_str().unwrap_or_default(); + assert!(!suggestion.contains("busy"), "{suggestion}"); + assert!(suggestion.contains("last_observed"), "{suggestion}"); +} + #[test] fn a_surface_wait_for_a_kind_the_platform_cannot_show_is_refused_at_once() { let started = std::time::Instant::now(); diff --git a/crates/core/src/commands/wait_timeout.rs b/crates/core/src/commands/wait_timeout.rs index d314896113..9c99296366 100644 --- a/crates/core/src/commands/wait_timeout.rs +++ b/crates/core/src/commands/wait_timeout.rs @@ -40,14 +40,18 @@ pub(crate) fn surface( format!("No {kind} surface") }; let mut details = json!({ "predicate": "surface", "surface": kind, "timeout_ms": timeout_ms }); - let message = match observed { - Some(observed) => { - details["last_observed"] = json!(observed); - format!("{what} was open within {timeout_ms}ms") - } - None => format!("The surfaces could not be read within {timeout_ms}ms"), + let Some(observed) = observed else { + let message = format!("The surfaces could not be read within {timeout_ms}ms"); + return timeout_err(message, with_last_error(details, last_error)); }; - timeout_err(message, with_last_error(details, last_error)) + details["last_observed"] = json!(observed); + let message = format!("{what} was open within {timeout_ms}ms"); + timeout_err(message, with_last_error(details, last_error)).map_err(|error| match error { + AppError::Adapter(error) => AppError::Adapter(error.with_suggestion( + "The application answered and showed no such surface: details.last_observed lists what was open. Raise --timeout only if the surface opens later.", + )), + other => other, + }) } /// Builds the wait-loop TIMEOUT error. Every payload carries From 0bf1ebd4ab0c8b5d8a86a09ccc60dd3edd72ecda Mon Sep 17 00:00:00 2001 From: Lahfir Date: Thu, 19 Nov 2026 17:25:23 -0800 Subject: [PATCH 13/26] fix(windows): snapshot a sheet that is not the foreground window list-surfaces and wait --surface sheet list a modal window of the app headless, but snapshot --surface sheet rooted only the foreground window, so the sheet a wait had just found returned WINDOW_NOT_FOUND unless it held the foreground. The sheet root is now each candidate window that is itself modal, read without the foreground. --- crates/windows/src/tree/surfaces.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/windows/src/tree/surfaces.rs b/crates/windows/src/tree/surfaces.rs index f61c83e276..17c6abbf21 100644 --- a/crates/windows/src/tree/surfaces.rs +++ b/crates/windows/src/tree/surfaces.rs @@ -48,14 +48,13 @@ pub(crate) fn surface_root( root_from_hwnd(handle, deadline) } (ObservationRoot::Window(window), SnapshotSurface::Sheet) => { - let handle = focused_hwnd_of(&window.id)?; - let element = root_from_hwnd(handle, deadline)?; + let element = root_from_hwnd(parse_window_id(&window.id)?, deadline)?; if window_is_modal_sheet(&element) { Ok(element) } else { Err(AdapterError::new( ErrorCode::WindowNotFound, - "The focused window is not a modal sheet", + "The window is not a modal sheet", )) } } From f8a7e20da15f2c9d4139a6963d109f27a2dd9bc4 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Thu, 19 Nov 2026 17:29:37 -0800 Subject: [PATCH 14/26] perf(linux): refuse a surface kind no shell answers without probing the shell wait --surface popover and snapshot --surface popover took 3.02 s to return INVALID_ARGS on GNOME, because the refusal first probed every shell surface for the list it names. A kind that is neither an application surface nor a shell surface is now refused at once. --- crates/linux/src/system/adapter.rs | 34 ++++++++++++++++++------------ 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/crates/linux/src/system/adapter.rs b/crates/linux/src/system/adapter.rs index 312b782fa8..08d32a2103 100644 --- a/crates/linux/src/system/adapter.rs +++ b/crates/linux/src/system/adapter.rs @@ -199,26 +199,23 @@ impl SystemOps for LinuxAdapter { if !permissions::accessibility_answers(self.bus(), deadline) { return Vec::new(); } - let mut surfaces = vec![ - SnapshotSurface::Window, - SnapshotSurface::Sheet, - SnapshotSurface::Alert, - ]; - surfaces.extend(menu_surface::supported()); + let mut surfaces = app_surfaces(); surfaces.extend(shell::supported(self.bus())); surfaces } + /// An application surface needs no probe. A kind that is neither an + /// application surface nor a shell surface is refused before the shell is + /// probed, which takes up to the probe budget on a session whose shell + /// tree answers slowly. fn check_surface_support(&self, requested: SnapshotSurface) -> Result<(), AdapterError> { - if matches!( - requested, - SnapshotSurface::Window - | SnapshotSurface::Sheet - | SnapshotSurface::Alert - | SnapshotSurface::Menu - ) { + let app_surfaces = app_surfaces(); + if app_surfaces.contains(&requested) { return Ok(()); } + if shell::kinds::kind_of(requested).is_none() { + return Err(requested.unavailable_error(&app_surfaces)); + } let supported = self.supported_surfaces(); if supported.contains(&requested) { return Ok(()); @@ -281,3 +278,14 @@ impl SystemOps for LinuxAdapter { shell::open_surface(self.bus(), surface, policy, lease) } } + +/// The surfaces of an application window that every session reads. +fn app_surfaces() -> Vec { + let mut surfaces = vec![ + SnapshotSurface::Window, + SnapshotSurface::Sheet, + SnapshotSurface::Alert, + ]; + surfaces.extend(menu_surface::supported()); + surfaces +} From bfdd49684985bec29ef9269126ed581c22d90ba7 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Thu, 19 Nov 2026 18:08:32 -0800 Subject: [PATCH 15/26] fix(linux): keep the no-bus answer when a surface kind is refused early The early refusal listed the application surfaces without asking the bus, so a session with no accessibility bus refused a kind with INVALID_ARGS and four surfaces instead of PLATFORM_NOT_SUPPORTED and none. The refusal now asks the bus, which is cheap, and still skips only the shell probe. --- crates/linux/src/system/adapter.rs | 37 ++++++++++++++++-------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/crates/linux/src/system/adapter.rs b/crates/linux/src/system/adapter.rs index 08d32a2103..d886608b6c 100644 --- a/crates/linux/src/system/adapter.rs +++ b/crates/linux/src/system/adapter.rs @@ -193,30 +193,24 @@ impl SystemOps for LinuxAdapter { } fn supported_surfaces(&self) -> Vec { - let Ok(deadline) = Deadline::after(SURFACE_PROBE_MS) else { - return Vec::new(); - }; - if !permissions::accessibility_answers(self.bus(), deadline) { - return Vec::new(); + let mut surfaces = answering_app_surfaces(self.bus()); + if !surfaces.is_empty() { + surfaces.extend(shell::supported(self.bus())); } - let mut surfaces = app_surfaces(); - surfaces.extend(shell::supported(self.bus())); surfaces } - /// An application surface needs no probe. A kind that is neither an - /// application surface nor a shell surface is refused before the shell is - /// probed, which takes up to the probe budget on a session whose shell - /// tree answers slowly. + /// An application surface needs no probe. A kind that no shell surface + /// can be is refused without the shell probe, which takes up to its + /// budget on a session whose shell tree answers slowly. fn check_surface_support(&self, requested: SnapshotSurface) -> Result<(), AdapterError> { - let app_surfaces = app_surfaces(); - if app_surfaces.contains(&requested) { + if app_surfaces().contains(&requested) { return Ok(()); } - if shell::kinds::kind_of(requested).is_none() { - return Err(requested.unavailable_error(&app_surfaces)); - } - let supported = self.supported_surfaces(); + let supported = match shell::kinds::kind_of(requested) { + Some(_) => self.supported_surfaces(), + None => answering_app_surfaces(self.bus()), + }; if supported.contains(&requested) { return Ok(()); } @@ -279,6 +273,15 @@ impl SystemOps for LinuxAdapter { } } +/// The application surfaces, or none when the session's accessibility bus +/// does not answer. +fn answering_app_surfaces(bus: &crate::system::SharedBus) -> Vec { + match Deadline::after(SURFACE_PROBE_MS) { + Ok(deadline) if permissions::accessibility_answers(bus, deadline) => app_surfaces(), + _ => Vec::new(), + } +} + /// The surfaces of an application window that every session reads. fn app_surfaces() -> Vec { let mut surfaces = vec![ From fee2e3cd2ec89bc09314d588c3584b1a734ffc1e Mon Sep 17 00:00:00 2001 From: Lahfir Date: Fri, 20 Nov 2026 15:19:56 -0800 Subject: [PATCH 16/26] fix(macos): name popover unread on a window whose popover search was cut list-surfaces read a cut popover search as no popover, so it and wait --surface popover reported that the application showed none. A window whose search did not read every element now names popover in its unclassified kinds, on its own entry or on a window entry. The FFI skill no longer says only Windows fills unclassified. --- crates/macos/src/tree/surface_inventory.rs | 30 +++++++++++++++++-- .../macos/src/tree/surface_inventory_tests.rs | 18 +++++++++++ skills/agent-desktop-ffi/SKILL.md | 4 +-- 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/crates/macos/src/tree/surface_inventory.rs b/crates/macos/src/tree/surface_inventory.rs index 13a3734054..f16ac514c1 100644 --- a/crates/macos/src/tree/surface_inventory.rs +++ b/crates/macos/src/tree/surface_inventory.rs @@ -73,8 +73,9 @@ fn list_surfaces_once( /// A headless target window is rarely the focused one, and a popover hangs /// below the control that raised it, so while the application shows a window /// its accessibility window list leaves out, every window gets the bounded -/// popover search. A window whose search -/// reached its element limit is left out. +/// popover search. A window whose search did not read every element names +/// `popover` unclassified, so a missing popover is not taken for an observed +/// absence. fn push_anchored_popover( window: &AXElement, window_id: &str, @@ -83,6 +84,11 @@ fn push_anchored_popover( ) -> Result<(), AdapterError> { let popover = match super::surfaces::popover_in_window(window, deadline) { Ok(popover) => popover, + Err(error) if is_incomplete(&error) => { + let title = read_title(window, deadline)?; + mark_popover_unread(surfaces, window_id, title); + None + } Err(error) if error.code == agent_desktop_core::ErrorCode::ElementNotFound => None, Err(error) => return Err(error), }; @@ -98,6 +104,26 @@ fn push_anchored_popover( Ok(()) } +fn is_incomplete(error: &AdapterError) -> bool { + error + .details + .as_ref() + .is_some_and(|details| details["complete"] == false) +} + +fn mark_popover_unread(surfaces: &mut Vec, window_id: &str, title: Option) { + match surfaces.iter_mut().find(|entry| entry.id == window_id) { + Some(entry) => entry.unclassified.push("popover".into()), + None => surfaces.push(SurfaceInfo { + id: window_id.to_owned(), + kind: "window".into(), + title, + item_count: None, + unclassified: vec!["popover".into()], + }), + } +} + fn list_surfaces_with( deadline: Deadline, window_surfaces: impl FnOnce() -> Result, AdapterError>, diff --git a/crates/macos/src/tree/surface_inventory_tests.rs b/crates/macos/src/tree/surface_inventory_tests.rs index 32eec19a99..24f6dbc0df 100644 --- a/crates/macos/src/tree/surface_inventory_tests.rs +++ b/crates/macos/src/tree/surface_inventory_tests.rs @@ -121,3 +121,21 @@ fn a_system_dialog_is_listed_as_an_alert_like_a_dialog() { None ); } + +#[test] +fn a_cut_popover_search_names_popover_unread_on_the_window() { + let mut surfaces = vec![surface("windows/0", "sheet")]; + mark_popover_unread(&mut surfaces, "windows/0", None); + mark_popover_unread(&mut surfaces, "windows/1", Some("Doc".into())); + assert_eq!(surfaces[0].unclassified, ["popover"]); + assert_eq!(surfaces[1].id, "windows/1"); + assert_eq!(surfaces[1].kind, "window"); + assert_eq!(surfaces[1].unclassified, ["popover"]); + let cut = AdapterError::new(agent_desktop_core::ErrorCode::ElementNotFound, "cut") + .with_details(serde_json::json!({ "complete": false })); + assert!(is_incomplete(&cut)); + assert!(!is_incomplete(&AdapterError::new( + agent_desktop_core::ErrorCode::ElementNotFound, + "gone" + ))); +} diff --git a/skills/agent-desktop-ffi/SKILL.md b/skills/agent-desktop-ffi/SKILL.md index ecc681ed98..c51747fe68 100644 --- a/skills/agent-desktop-ffi/SKILL.md +++ b/skills/agent-desktop-ffi/SKILL.md @@ -102,8 +102,8 @@ ABI. A bare `@eN` ref returns only as fields embedded in the exact structs. `ad_list_surfaces_exact` keeps the surface `id`. From `AD_EXACT_SURFACE_INFO_VERSION` 2, `AdExactSurfaceInfo.unclassified` names the surface kinds its probe could not read (for example `sheet,menu`), or - is null. A missing `sheet` or `menu` next to a listed kind is unknown, not - absent. Only the Windows adapter fills it; macOS and Linux return null. + is null. A missing `sheet`, `menu` or `popover` next to a listed kind is + unknown, not absent. - **Entries with no policy input.** `ad_mouse_event`, `ad_mouse_event_with_modifiers`, `ad_mouse_wheel`, `ad_drag`, `ad_set_clipboard`, `ad_clear_clipboard`, From fa55785da4445cffd3c1d9dbb28e5a979a058c02 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Fri, 20 Nov 2026 15:20:30 -0800 Subject: [PATCH 17/26] fix(linux): list a modal alert as both an alert and a sheet A window that is a showing alert and a modal dialog listed only its alert entry, so wait --surface sheet and the sheet entry missed a modal dialog the contract calls a sheet. Such a window now lists both entries. --- crates/linux/src/system/menu/surfaces.rs | 19 ++++++++----------- .../linux/src/system/menu/surfaces_tests.rs | 11 +++++++++++ 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/crates/linux/src/system/menu/surfaces.rs b/crates/linux/src/system/menu/surfaces.rs index d74319e8e4..d77d11964e 100644 --- a/crates/linux/src/system/menu/surfaces.rs +++ b/crates/linux/src/system/menu/surfaces.rs @@ -40,26 +40,23 @@ fn surface(id: &str, kind: &str, title: &Option) -> SurfaceInfo { } } -/// The kind a listed window adds beside its `window` entry: `alert` when the +/// The kinds a listed window adds beside its `window` entry: `alert` when the /// frame is a showing alert, the predicate `snapshot --surface alert` roots -/// at, else `sheet` when it is a modal dialog, else none. -pub(crate) fn extra_kind(window: &ListedWindow) -> Option<&'static str> { - if window.alert { - Some("alert") - } else { - window.sheet.then_some("sheet") - } +/// at, and `sheet` when it is a modal dialog. A modal alert is both. +fn extra_kinds(window: &ListedWindow) -> impl Iterator { + let alert = window.alert.then_some("alert"); + alert.into_iter().chain(window.sheet.then_some("sheet")) } -/// The surfaces of one listed window: a `window` entry always, an `alert` or -/// `sheet` entry alongside it when the window is one. +/// The surfaces of one listed window: a `window` entry always, and an `alert` +/// and a `sheet` entry alongside it when the window is one. pub(crate) fn surfaces_of(windows: &[ListedWindow]) -> Vec { windows .iter() .flat_map(|window| { let title = (!window.info.title.is_empty()).then(|| window.info.title.clone()); std::iter::once("window") - .chain(extra_kind(window)) + .chain(extra_kinds(window)) .map(move |kind| surface(&window.info.id, kind, &title)) }) .collect() diff --git a/crates/linux/src/system/menu/surfaces_tests.rs b/crates/linux/src/system/menu/surfaces_tests.rs index cb0c99e3fe..388e6e403d 100644 --- a/crates/linux/src/system/menu/surfaces_tests.rs +++ b/crates/linux/src/system/menu/surfaces_tests.rs @@ -167,3 +167,14 @@ fn a_showing_alert_lists_an_alert_entry_in_place_of_the_sheet_entry() { plain.alert = false; assert_eq!(surfaces_of(&[plain]).len(), 1); } + +#[test] +fn a_modal_alert_lists_both_an_alert_and_a_sheet_entry() { + let mut alert = window("w-1", "Quit?", true); + alert.alert = true; + let kinds: Vec = surfaces_of(&[alert]) + .into_iter() + .map(|surface| surface.kind) + .collect(); + assert_eq!(kinds, ["window", "alert", "sheet"]); +} From 2e6602f76f4ac478538a69dc401616cb8a38f46a Mon Sep 17 00:00:00 2001 From: Lahfir Date: Fri, 20 Nov 2026 15:56:08 -0800 Subject: [PATCH 18/26] test(linux): expect a modal alert to list its alert and its sheet entry The older test still expected a showing modal alert to list its alert entry in place of the sheet entry. The window now lists both; the test keeps its plain-window case and the duplicate test is removed. --- crates/linux/src/system/menu/surfaces_tests.rs | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/crates/linux/src/system/menu/surfaces_tests.rs b/crates/linux/src/system/menu/surfaces_tests.rs index 388e6e403d..3c36b6cfc4 100644 --- a/crates/linux/src/system/menu/surfaces_tests.rs +++ b/crates/linux/src/system/menu/surfaces_tests.rs @@ -155,26 +155,15 @@ fn an_incomplete_scan_still_reports_the_dialog_it_saw() { } #[test] -fn a_showing_alert_lists_an_alert_entry_in_place_of_the_sheet_entry() { +fn a_showing_modal_alert_lists_both_an_alert_and_a_sheet_entry() { let mut alert = window("w-1", "Save changes?", true); alert.alert = true; let kinds: Vec<_> = surfaces_of(&[alert]) .iter() .map(|surface| surface.kind.clone()) .collect(); - assert_eq!(kinds, ["window", "alert"]); + assert_eq!(kinds, ["window", "alert", "sheet"]); let mut plain = window("w-2", "Doc", false); plain.alert = false; assert_eq!(surfaces_of(&[plain]).len(), 1); } - -#[test] -fn a_modal_alert_lists_both_an_alert_and_a_sheet_entry() { - let mut alert = window("w-1", "Quit?", true); - alert.alert = true; - let kinds: Vec = surfaces_of(&[alert]) - .into_iter() - .map(|surface| surface.kind) - .collect(); - assert_eq!(kinds, ["window", "alert", "sheet"]); -} From 31a0c8bf074b3690eafb71911c87d4c9de15e5e2 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Fri, 20 Nov 2026 16:13:32 -0800 Subject: [PATCH 19/26] docs: name popover among the kinds a surface entry can leave unclassified Since fee2e3cd2 a macOS window whose popover search was cut names popover in its unclassified kinds; the surfaces page listed only sheet and menu. --- apps/docs/content/docs/surfaces.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/docs/content/docs/surfaces.mdx b/apps/docs/content/docs/surfaces.mdx index 01de27ea11..db02bed6ce 100644 --- a/apps/docs/content/docs/surfaces.mdx +++ b/apps/docs/content/docs/surfaces.mdx @@ -150,7 +150,7 @@ agent-desktop list-surfaces --app gtk3-widget-factory } ``` -`list-surfaces` returns the overlays an app presents now, which are the kinds `snapshot --surface` accepts for it. Shell surfaces belong to the OS and never appear here. An entry can carry `"unclassified": ["sheet"]` or `["menu"]` when the check could not read that window, often because the app was busy. Treat the missing entry as unknown, not absent. +`list-surfaces` returns the overlays an app presents now, which are the kinds `snapshot --surface` accepts for it. Shell surfaces belong to the OS and never appear here. An entry can carry `"unclassified": ["sheet"]`, `["menu"]` or `["popover"]` when the check could not read that window, often because the app was busy or a search stopped at its bound. Treat the missing entry as unknown, not absent. ## Open an OS shell surface From ead2c4c8d090f54ba09a1c38bfe621d8bbf727d4 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:40:36 -0800 Subject: [PATCH 20/26] fix(surfaces): report unread surfaces and keep stable surface identity A popover search cut at its element limit now marks `popover` unread instead of reporting none, and `wait --surface` says the kind could not be read (`details.unread: true`) instead of claiming the app showed nothing. macOS surface ids come from AX window numbers, so closing an earlier window no longer re-ids a surviving sheet or popover and no longer fires a false surface-dismissed for one that is still open. Windows popover captures record the popover window on their refs, resolve and re-observe that exact window, and refuse several open popovers with their ids rather than reading the process's first one. Document `wait --surface`, including the unread timeout shape, and guard the wait reference against undocumented flags. --- apps/docs/content/docs/commands/wait.mdx | 73 +++++- apps/docs/content/docs/surfaces.mdx | 2 +- crates/core/src/actions/headed_focus.rs | 9 +- crates/core/src/adapter/observation.rs | 30 +++ .../src/commands/application_surface_tests.rs | 44 +++- .../application_surface_window_tests.rs | 110 ++++++++ crates/core/src/commands/mod.rs | 3 + ...post_action_observation_lifecycle_tests.rs | 48 ++++ crates/core/src/commands/wait.rs | 10 +- crates/core/src/commands/wait_surface.rs | 25 +- .../commands/wait_surface_scenario_tests.rs | 174 +++++++++++++ crates/core/src/commands/wait_timeout.rs | 26 +- crates/core/src/refs/resolve_saved_ref.rs | 11 + crates/core/src/snapshot/snapshot_ref.rs | 4 +- crates/core/src/snapshot/surface_target.rs | 94 +++++-- crates/macos/src/tree/mod.rs | 1 + crates/macos/src/tree/surface_ids.rs | 154 +++++++++++ crates/macos/src/tree/surface_ids_tests.rs | 246 ++++++++++++++++++ crates/macos/src/tree/surface_inventory.rs | 169 ++++++------ .../macos/src/tree/surface_inventory_tests.rs | 15 +- crates/windows/src/adapter.rs | 38 ++- crates/windows/src/tree/mod.rs | 1 + crates/windows/src/tree/popover_choice.rs | 158 +++++++++++ .../windows/src/tree/popover_choice_tests.rs | 59 +++++ .../src/tree/resolve/resolve_anchor.rs | 30 ++- crates/windows/src/tree/surface_inventory.rs | 19 +- crates/windows/src/tree/surfaces.rs | 38 +-- skills/agent-desktop-windows/SKILL.md | 2 + src/cli/doc_literal_drift_tests.rs | 42 +++ 29 files changed, 1450 insertions(+), 185 deletions(-) create mode 100644 crates/core/src/commands/application_surface_window_tests.rs create mode 100644 crates/core/src/commands/wait_surface_scenario_tests.rs create mode 100644 crates/macos/src/tree/surface_ids.rs create mode 100644 crates/macos/src/tree/surface_ids_tests.rs create mode 100644 crates/windows/src/tree/popover_choice.rs create mode 100644 crates/windows/src/tree/popover_choice_tests.rs diff --git a/apps/docs/content/docs/commands/wait.mdx b/apps/docs/content/docs/commands/wait.mdx index a9a28b53bd..fa27561d87 100644 --- a/apps/docs/content/docs/commands/wait.mdx +++ b/apps/docs/content/docs/commands/wait.mdx @@ -16,6 +16,7 @@ agent-desktop wait --text TEXT [--count N] [--app NAME] agent-desktop wait --menu [--app NAME] agent-desktop wait --menu-closed [--app NAME] agent-desktop wait --notification [--text TEXT] [--app NAME] +agent-desktop wait --surface KIND [--app NAME] [--timeout MS] agent-desktop wait --event KIND [--app NAME] [--window TITLE] [--window-id ID] ``` @@ -34,9 +35,10 @@ agent-desktop wait --event KIND [--app NAME] [--window TITLE] [--window-id ID] --count NnoneFor --text: wait until exactly N nodes match. --menu, --menu-closedoffWait until a menu surface is open, or dismissed. --notificationoffWait until a new notification arrives. + --surface KINDnoneWait until a surface of this kind is open in the app: popover, sheet, alert, menu, or any. A surface that is already open matches at once. --event KINDnoneWait for a lifecycle signal: window-opened, window-closed, app-launched, app-terminated, focus-changed, surface-appeared, or surface-dismissed. --window-id IDnoneNarrow window-opened, window-closed, or focus-changed to one window. - --app NAMEnoneScope a window, text, menu, notification, or event wait to one application. Element and time waits ignore it. + --app NAMEnoneScope a window, text, menu, notification, surface, or event wait to one application. Element and time waits ignore it. A surface wait resolves the application once, at the start; without it the uniquely focused window's application is used, and a missing or ambiguous one is APP_NOT_FOUND or AMBIGUOUS_TARGET. --timeout MS30000Timeout for every mode except MS, at most 86400000. @@ -105,6 +107,75 @@ agent-desktop wait --text Calculator --app gnome-calculator --timeout 3000 `--menu` waits until a menu surface is open, and `--menu-closed` until it is gone. Both return `{ "elapsed_ms", "found": true }`. On Linux, `--menu-closed` on a menu that never opened is true at once, so wait for `--menu` first. +### Surface + +`--surface KIND` polls the app's surface inventory until a surface of that kind is open: `popover`, `sheet`, `alert`, `menu`, or `any`. It waits for a state, not a change, so a surface that is already open matches immediately. Run it after the click that opens the surface: + +```bash +agent-desktop wait --surface sheet --app gedit --timeout 2000 +``` + +```json +{ + "version": "2.7", + "ok": true, + "command": "wait", + "data": { + "elapsed_ms": 87, + "found": true, + "surface": { + "id": "w-1.167-org-a11y-atspi-accessible-44", + "title": "Save As", + "type": "sheet" + } + } +} +``` + +The result is `{ "elapsed_ms", "found": true, "surface": SURFACE }`, where `SURFACE` has the fields `list-surfaces` returns. + +A kind the app's inventory could not read is never reported as one the app does not show. When the last inventory named the kind as unclassified, the timeout says the surface could not be read, sets `details.unread: true`, and lists what it did read in `last_observed`: + +```bash +agent-desktop wait --surface menu --app gedit --timeout 2000 +``` + +```json +{ + "version": "2.7", + "ok": false, + "command": "wait", + "error": { + "code": "TIMEOUT", + "message": "The menu surface could not be read within 2000ms", + "recovery": { + "strategy": "inspect_state_then_retry_original", + "retryable": true, + "requires_fresh_snapshot": true, + "retry_after_ms": 250 + }, + "details": { + "kind": "wait_timeout", + "last_observed": [ + { + "id": "w-1.167-org-a11y-atspi-accessible-12", + "title": "Untitled Document 1 - gedit", + "type": "window", + "unclassified": ["menu"] + } + ], + "predicate": "surface", + "surface": "menu", + "timeout_ms": 2000, + "unread": true + }, + "disposition": { "delivery": "not_delivered", "retry": "safe" } + } +} +``` + +A read of every window that shows no such surface is an observed absence: its timeout reads `No popover surface was open within 2000ms` and carries no `unread`. + ### Notification `--notification` takes a baseline of the notification list when it starts and returns the first notification not in it. `--text` and `--app` filter which notifications count. The result is `{ "condition": "notification", "matched": true, "notification": {...}, "elapsed_ms" }`. Headless limits on macOS and Windows are on the [notification commands](/desktop/commands/notifications) page. diff --git a/apps/docs/content/docs/surfaces.mdx b/apps/docs/content/docs/surfaces.mdx index db02bed6ce..e4526c00d1 100644 --- a/apps/docs/content/docs/surfaces.mdx +++ b/apps/docs/content/docs/surfaces.mdx @@ -109,7 +109,7 @@ To reach one item, `find --surface` is cheaper than a dump: How agent-desktop selects an owner depends on the kind and platform: - `sheet`, `popover`, and `alert`: the app's accessible windows in order, focused first and then visible, and the first that presents one wins. With no `--app`, the frontmost process. -- `sheet`, `popover`, and `alert`: the app's accessible windows in order, focused first and then visible, and the first that presents one wins. With no `--app`, the frontmost process. +- On Windows, a popover is a window of its own that the window inventory leaves out: `list-surfaces` reports its `w-`, and `--window-id` with that id plus `--app` reads that exact popover. With several open and none named, the read is refused with `AMBIGUOUS_TARGET` and lists their ids rather than reading another popover. - On macOS, `menu` and `menubar` are application-owned and do not require a document window. If you pass `--window-id`, it selects the app that owns the surface. Snapshot data includes `app` and omits `window`. A complete lookup with no open menu or menu bar returns `ELEMENT_NOT_FOUND` with `details.kind: "surface_absent"` and `details.complete: true`. To read an application menu, snapshot `menubar` when it exists, click its item without `--headed`, then snapshot `--surface menu`. An absent menu bar can mean the app exposes none. - On implementations where `menu`, `menubar`, and `focused` are window-owned, any app window identifies the process, so several open windows are not ambiguous. - On macOS, `window`, `menubar`, and `menu-bar-extras` can read a background app with no window through its process. The result omits `window`. A regular app that has not shown a window returns `WINDOW_NOT_FOUND`; `focused` requires a focused window. diff --git a/crates/core/src/actions/headed_focus.rs b/crates/core/src/actions/headed_focus.rs index 985ff9c1fd..b4414f99d8 100644 --- a/crates/core/src/actions/headed_focus.rs +++ b/crates/core/src/actions/headed_focus.rs @@ -26,8 +26,9 @@ impl HeadedFocus { } /// Focuses the window a ref came from and returns whether it did. A ref -/// captured through a process owner has no window to raise, so it returns -/// `false`; any other ref without a window id is refused. +/// captured through a process owner, or from a surface the platform presents +/// beside its windows rather than as one of them, has no census window to +/// raise, so it returns `false`; any other ref without a window id is refused. pub(crate) fn focus_entry_window( entry: &crate::RefEntry, adapter: &dyn PlatformAdapter, @@ -41,7 +42,9 @@ pub(crate) fn focus_entry_window( ) .with_details(json!({ "physical_delivery_started": false })) })?; - if entry.source.is_process_owned() { + if entry.source.is_process_owned() + || adapter.is_application_surface(entry.source.source_surface) + { return Ok(false); } let expected = adapter.resolve_ref_focus_window(entry, lease.deadline())?; diff --git a/crates/core/src/adapter/observation.rs b/crates/core/src/adapter/observation.rs index f38e2f359d..3ada2bcd3d 100644 --- a/crates/core/src/adapter/observation.rs +++ b/crates/core/src/adapter/observation.rs @@ -32,10 +32,40 @@ pub trait ObservationOps: Send + Sync { false } + /// The window a surface is presented by, when the platform shows it in a + /// window of its own that the window inventory leaves out. A capture that + /// returns one records that window on every ref it allocates, so a later + /// resolve or observation lands on the window that was read rather than on + /// another one of the same kind. `None` keeps the surface + /// application-owned, which is the answer for a surface with no window. + fn surface_window( + &self, + _app: &AppInfo, + _surface: SnapshotSurface, + _deadline: Deadline, + ) -> Result, AdapterError> { + Ok(None) + } + fn focused_app(&self, _deadline: Deadline) -> Result, AdapterError> { Err(AdapterError::not_supported("focused_app")) } + /// The window a caller named for a surface the platform presents in a + /// window of its own: the id a stored ref recorded, or the `--window-id` + /// of a capture. The id must still name an open surface window of that + /// exact process instance, or this refuses; `None` keeps the window + /// inventory lookup, which is the answer for a surface with no window. + fn recorded_surface_window( + &self, + _process: crate::ProcessIdentity, + _window_id: &str, + _surface: SnapshotSurface, + _deadline: Deadline, + ) -> Result, AdapterError> { + Ok(None) + } + /// Reports protocol targets that have no screen position without requiring a native read. fn is_nonspatial_target(&self, _handle: &NativeHandle) -> bool { false diff --git a/crates/core/src/commands/application_surface_tests.rs b/crates/core/src/commands/application_surface_tests.rs index bed12e2038..5016fffa0a 100644 --- a/crates/core/src/commands/application_surface_tests.rs +++ b/crates/core/src/commands/application_surface_tests.rs @@ -6,23 +6,57 @@ use crate::{ refs::refs_test_support::HomeGuard, }; -struct MenuAdapter { - apps: Vec, - windows: Vec, +pub(super) struct MenuAdapter { + pub(super) apps: Vec, + pub(super) windows: Vec, + pub(super) surface_window: Option, } impl MenuAdapter { - fn windowless() -> Self { + pub(super) fn windowless() -> Self { Self { apps: vec![app(42)], windows: vec![], + surface_window: None, } } } impl ObservationOps for MenuAdapter { fn is_application_surface(&self, surface: SnapshotSurface) -> bool { - matches!(surface, SnapshotSurface::Menubar | SnapshotSurface::Menu) + matches!( + surface, + SnapshotSurface::Menubar | SnapshotSurface::Menu | SnapshotSurface::Popover + ) + } + + fn surface_window( + &self, + _app: &AppInfo, + surface: SnapshotSurface, + _deadline: Deadline, + ) -> Result, crate::AdapterError> { + if surface != SnapshotSurface::Popover { + return Ok(None); + } + Ok(self.surface_window.clone()) + } + + fn recorded_surface_window( + &self, + process: crate::ProcessIdentity, + window_id: &str, + surface: SnapshotSurface, + _deadline: Deadline, + ) -> Result, crate::AdapterError> { + if surface != SnapshotSurface::Popover { + return Ok(None); + } + Ok(self.surface_window.clone().filter(|window| { + window.id == window_id + && window.pid == process.pid + && window.process_instance.as_deref() == Some(process.instance.as_str()) + })) } fn focused_app(&self, _deadline: Deadline) -> Result, crate::AdapterError> { diff --git a/crates/core/src/commands/application_surface_window_tests.rs b/crates/core/src/commands/application_surface_window_tests.rs new file mode 100644 index 0000000000..b8a7a18962 --- /dev/null +++ b/crates/core/src/commands/application_surface_window_tests.rs @@ -0,0 +1,110 @@ +use super::application_surface_tests::MenuAdapter; +use crate::{Deadline, RefEntry, SnapshotOwner, SnapshotSurface, WindowInfo}; +fn popover_owner_surface_window() -> WindowInfo { + WindowInfo { + id: "w-77".into(), + title: "Filters".into(), + app: "MenuApp".into(), + pid: crate::ProcessId::new(42), + process_instance: Some("instance-42".into()), + bounds: None, + state: Default::default(), + } +} + +fn popover_owners(adapter: &MenuAdapter) -> Vec { + crate::snapshot::surface_target::resolve_owners( + adapter, + Some("MenuApp"), + None, + SnapshotSurface::Popover, + Deadline::standard().unwrap(), + ) + .unwrap() +} + +#[test] +fn a_surface_the_adapter_presents_in_its_own_window_is_owned_by_that_window() { + let mut adapter = MenuAdapter::windowless(); + adapter.surface_window = Some(popover_owner_surface_window()); + + let owners = popover_owners(&adapter); + + assert!( + matches!(&owners[..], [SnapshotOwner::Window(window)] if window.id == "w-77"), + "a surface presented by a window is captured at that window: {owners:?}" + ); +} + +#[test] +fn a_surface_with_no_window_of_its_own_stays_application_owned() { + let owners = popover_owners(&MenuAdapter::windowless()); + + assert!( + matches!(&owners[..], [SnapshotOwner::Application(_)]), + "a surface with no window stays application-owned: {owners:?}" + ); +} + +fn popover_entry(window_id: &str) -> RefEntry { + let mut entry = crate::adapter::minimal_ref_entry("button", None); + entry.process.pid = crate::ProcessId::new(42); + entry.process.process_instance = Some("instance-42".into()); + entry.source.source_app = Some("MenuApp".into()); + entry.source.source_surface = SnapshotSurface::Popover; + entry.source.source_window_id = Some(window_id.into()); + entry.source.source_window_title = Some("Filters".into()); + entry +} + +#[test] +fn a_recorded_popover_reference_resolves_to_the_popover_window_it_named() { + let mut adapter = MenuAdapter::windowless(); + adapter.surface_window = Some(popover_owner_surface_window()); + + let window = crate::refs::resolve_saved_ref::recorded_window( + &adapter, + &popover_entry("w-77"), + Deadline::standard().unwrap(), + ) + .unwrap(); + + assert_eq!(window.id, "w-77"); + assert_eq!(window.pid, crate::ProcessId::new(42)); + assert_eq!(window.process_instance.as_deref(), Some("instance-42")); +} + +#[test] +fn a_recorded_popover_reference_to_a_closed_popover_is_stale() { + let mut adapter = MenuAdapter::windowless(); + adapter.surface_window = Some(popover_owner_surface_window()); + + let error = crate::refs::resolve_saved_ref::recorded_window( + &adapter, + &popover_entry("w-99"), + Deadline::standard().unwrap(), + ) + .unwrap_err(); + + assert_eq!(error.code.as_str(), "STALE_REF"); +} + +#[test] +fn naming_the_surface_window_reads_it_even_though_it_is_not_a_listed_window() { + let mut adapter = MenuAdapter::windowless(); + adapter.surface_window = Some(popover_owner_surface_window()); + + let owners = crate::snapshot::surface_target::resolve_owners( + &adapter, + Some("MenuApp"), + Some("w-77"), + SnapshotSurface::Popover, + Deadline::standard().unwrap(), + ) + .unwrap(); + + assert!( + matches!(&owners[..], [SnapshotOwner::Window(window)] if window.id == "w-77"), + "the named surface window is captured at that window: {owners:?}" + ); +} diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rs index 5340c6ee9e..f2b96e3b78 100644 --- a/crates/core/src/commands/mod.rs +++ b/crates/core/src/commands/mod.rs @@ -113,5 +113,8 @@ mod operation_passthrough_tests; #[cfg(test)] mod application_surface_tests; +#[cfg(test)] +mod application_surface_window_tests; + #[cfg(test)] mod tests; diff --git a/crates/core/src/commands/post_action_observation_lifecycle_tests.rs b/crates/core/src/commands/post_action_observation_lifecycle_tests.rs index e539605453..3aa11f74bd 100644 --- a/crates/core/src/commands/post_action_observation_lifecycle_tests.rs +++ b/crates/core/src/commands/post_action_observation_lifecycle_tests.rs @@ -145,6 +145,54 @@ fn process_owned_wait_uses_process_window_and_refuses_unmarked_missing_window() } } +struct RecordedPopoverAdapter; + +impl ObservationOps for RecordedPopoverAdapter { + fn is_application_surface(&self, surface: crate::SnapshotSurface) -> bool { + surface == crate::SnapshotSurface::Popover + } +} + +impl ActionOps for RecordedPopoverAdapter {} +impl InputOps for RecordedPopoverAdapter {} +impl SystemOps for RecordedPopoverAdapter { + fn process_state( + &self, + _process: ProcessIdentity, + _deadline: Deadline, + ) -> Result { + Ok(ProcessState::Running) + } +} + +#[test] +fn a_surface_ref_that_recorded_its_window_observes_that_window() { + use crate::snapshot::{ + ref_owner_observation::RefOwnerObservation, surface_target::ref_observation_surface, + surface_target::resolve_ref_owner, + }; + let adapter = RecordedPopoverAdapter; + let mut entry = menu_entry(); + entry.source.source_surface = crate::SnapshotSurface::Popover; + entry.source.source_window_id = Some("w-99".into()); + entry.source.source_window_title = Some("Filters".into()); + + let owner = match resolve_ref_owner(&adapter, &entry, Deadline::after(250).unwrap()) { + Ok(RefOwnerObservation::Present(owner)) => owner, + Ok(_) => panic!("a running process is present"), + Err(error) => panic!("a running process resolves its owner: {error}"), + }; + let crate::SnapshotOwner::Window(window) = owner else { + panic!("a surface that recorded its window is observed at that window"); + }; + assert_eq!(window.id, "w-99"); + assert_eq!(window.title, "Filters"); + assert_eq!( + ref_observation_surface(&adapter, &entry), + crate::SnapshotSurface::Popover + ); +} + struct StrictReadAdapter { deadline: Deadline, code: ErrorCode, diff --git a/crates/core/src/commands/wait.rs b/crates/core/src/commands/wait.rs index 18d6e271dd..7f38d427b5 100644 --- a/crates/core/src/commands/wait.rs +++ b/crates/core/src/commands/wait.rs @@ -180,12 +180,7 @@ fn wait_for_surface( } deadline.pause(Duration::from_millis(100)); } - wait_timeout::surface( - kind.map_or("any", |kind| kind.as_str()), - timeout_ms, - last_observed.as_deref(), - last_error, - ) + wait_timeout::surface(kind, timeout_ms, last_observed.as_deref(), last_error) } fn wait_for_window( @@ -367,6 +362,9 @@ mod scenario_menu_tests; #[cfg(test)] #[path = "wait_scenario_tests.rs"] mod scenario_tests; +#[cfg(test)] +#[path = "wait_surface_scenario_tests.rs"] +mod surface_scenario_tests; #[cfg(test)] #[path = "wait_element_tests.rs"] diff --git a/crates/core/src/commands/wait_surface.rs b/crates/core/src/commands/wait_surface.rs index cec56f0c51..02d5813792 100644 --- a/crates/core/src/commands/wait_surface.rs +++ b/crates/core/src/commands/wait_surface.rs @@ -64,15 +64,34 @@ const OPEN_KINDS: [SnapshotSurface; 4] = [ /// Whether a listed surface is of the kind a wait asks for. A context menu is /// a menu. pub(crate) fn is_kind(surface: &SurfaceInfo, kind: Option) -> bool { + kind_matches(&surface.kind, kind) +} + +/// Whether an inventory entry that names `listed` satisfies the wait. Shared by +/// the listed surfaces and the kinds an entry reports as unclassified, so a +/// surface that was not read is judged by the same rule as one that was. +fn kind_matches(listed: &str, kind: Option) -> bool { match kind { None => OPEN_KINDS .into_iter() - .any(|kind| is_kind(surface, Some(kind))), - Some(SnapshotSurface::Menu) => matches!(surface.kind.as_str(), "menu" | "context_menu"), - Some(kind) => surface.kind == kind.as_str(), + .any(|kind| kind_matches(listed, Some(kind))), + Some(SnapshotSurface::Menu) => matches!(listed, "menu" | "context_menu"), + Some(kind) => listed == kind.as_str(), } } +/// Whether the last observation reports the kind a wait asks for as +/// unclassified: the inventory did not read it, so no matching surface has not +/// shown that the application presented none. +pub(crate) fn unread(surfaces: &[SurfaceInfo], kind: Option) -> bool { + surfaces.iter().any(|surface| { + surface + .unclassified + .iter() + .any(|listed| kind_matches(listed, kind)) + }) +} + #[cfg(test)] #[path = "wait_surface_tests.rs"] mod tests; diff --git a/crates/core/src/commands/wait_surface_scenario_tests.rs b/crates/core/src/commands/wait_surface_scenario_tests.rs new file mode 100644 index 0000000000..391bb91192 --- /dev/null +++ b/crates/core/src/commands/wait_surface_scenario_tests.rs @@ -0,0 +1,174 @@ +use super::*; +use crate::AdapterError; +use crate::adapter::{ActionOps, InputOps, ObservationOps, SystemOps}; + +struct SurfaceInventoryAdapter { + surfaces: Vec, +} + +impl ObservationOps for SurfaceInventoryAdapter { + fn query_app_inventory( + &self, + query: crate::AppInventoryQuery<'_>, + _deadline: crate::Deadline, + ) -> Result { + Ok(query.answer(vec![crate::AppInfo { + aliases: Vec::new(), + name: "SurfaceApp".into(), + pid: crate::ProcessId::new(42), + bundle_id: None, + process_instance: Some("test-instance".into()), + presentation: None, + }])) + } + + fn list_surfaces( + &self, + _process: crate::ProcessIdentity, + _deadline: crate::Deadline, + ) -> Result, AdapterError> { + Ok(self.surfaces.clone()) + } +} + +impl ActionOps for SurfaceInventoryAdapter {} + +impl InputOps for SurfaceInventoryAdapter {} + +impl SystemOps for SurfaceInventoryAdapter { + fn supported_surfaces(&self) -> Vec { + vec![ + crate::SnapshotSurface::Popover, + crate::SnapshotSurface::Sheet, + crate::SnapshotSurface::Alert, + crate::SnapshotSurface::Menu, + ] + } +} + +fn unread_window(kind: &str) -> crate::SurfaceInfo { + crate::SurfaceInfo { + id: "w-7".into(), + kind: "window".into(), + title: Some("Document".into()), + item_count: None, + unclassified: vec![kind.into()], + } +} + +fn read_window() -> crate::SurfaceInfo { + crate::SurfaceInfo { + id: "w-7".into(), + kind: "window".into(), + title: Some("Document".into()), + item_count: None, + unclassified: Vec::new(), + } +} + +fn wait_for(kind: &str, surfaces: Vec) -> AppError { + use super::test_support::wait_args; + let adapter = SurfaceInventoryAdapter { surfaces }; + execute( + WaitArgs { + mode: WaitModeArgs { + surface: Some( + SurfaceWait::from_flags(false, false, false, Some(kind)) + .unwrap() + .expect("one surface wait"), + ), + ..wait_args().mode + }, + app: Some("SurfaceApp".into()), + timeout_ms: 30, + ..wait_args() + }, + &adapter, + &CommandContext::default(), + ) + .unwrap_err() +} + +fn details(error: &AppError) -> Value { + let AppError::Adapter(error) = error else { + panic!("a surface timeout is an adapter timeout, got {error:?}"); + }; + assert_eq!(error.code, ErrorCode::Timeout); + error.details.clone().expect("timeout details") +} + +#[test] +fn a_surface_kind_the_inventory_could_not_read_is_not_reported_as_absent() { + for kind in ["popover", "sheet", "menu"] { + let error = wait_for(kind, vec![unread_window(kind)]); + let message = error.to_string(); + assert!(message.contains("could not be read"), "{kind}: {message}"); + assert!( + !message.contains("No "), + "{kind} claims absence for a surface that was never read: {message}" + ); + let suggestion = error.suggestion().unwrap_or_default(); + assert!( + suggestion.contains("may still present it"), + "{kind}: {suggestion}" + ); + assert!( + !suggestion.contains("showed no such surface"), + "{kind}: {suggestion}" + ); + let details = details(&error); + assert_eq!(details["unread"], true, "{kind}: {details}"); + assert_eq!(details["predicate"], "surface"); + assert_eq!(details["surface"], kind); + assert_eq!(details["last_observed"][0]["id"], "w-7"); + } +} + +#[test] +fn any_surface_is_unread_when_a_listed_surface_reports_any_open_kind() { + let error = wait_for("any", vec![unread_window("menu")]); + assert_eq!(details(&error)["unread"], true); +} + +#[test] +fn a_read_inventory_without_the_surface_still_reports_a_plain_timeout() { + let error = wait_for("popover", vec![read_window()]); + assert!( + error.to_string().contains("No popover surface was open"), + "{error}" + ); + let details = details(&error); + assert!(details.get("unread").is_none(), "{details}"); + assert_eq!(details["last_observed"][0]["id"], "w-7"); +} + +#[test] +fn a_matching_surface_returns_before_any_timeout() { + use super::test_support::wait_args; + let adapter = SurfaceInventoryAdapter { + surfaces: vec![crate::SurfaceInfo { + id: "w-7".into(), + kind: "popover".into(), + title: Some("Filters".into()), + item_count: None, + unclassified: Vec::new(), + }], + }; + let value = execute( + WaitArgs { + mode: WaitModeArgs { + surface: Some(SurfaceWait::Open(Some(crate::SnapshotSurface::Popover))), + ..wait_args().mode + }, + app: Some("SurfaceApp".into()), + timeout_ms: 30, + ..wait_args() + }, + &adapter, + &CommandContext::default(), + ) + .unwrap(); + + assert_eq!(value["found"], true); + assert_eq!(value["surface"]["id"], "w-7"); +} diff --git a/crates/core/src/commands/wait_timeout.rs b/crates/core/src/commands/wait_timeout.rs index 9c99296366..8980b0dcd3 100644 --- a/crates/core/src/commands/wait_timeout.rs +++ b/crates/core/src/commands/wait_timeout.rs @@ -29,23 +29,37 @@ pub(crate) fn menu(mut error: AdapterError, timeout_ms: u64) -> AppError { } pub(crate) fn surface( - kind: &str, + kind: Option, timeout_ms: u64, observed: Option<&[crate::SurfaceInfo]>, last_error: Option, ) -> Result { - let what = if kind == "any" { - "No surface".to_owned() + let name = kind.map_or("any", |kind| kind.as_str()); + let what = if name == "any" { + "surface".to_owned() } else { - format!("No {kind} surface") + format!("{name} surface") }; - let mut details = json!({ "predicate": "surface", "surface": kind, "timeout_ms": timeout_ms }); + let mut details = json!({ "predicate": "surface", "surface": name, "timeout_ms": timeout_ms }); let Some(observed) = observed else { let message = format!("The surfaces could not be read within {timeout_ms}ms"); return timeout_err(message, with_last_error(details, last_error)); }; details["last_observed"] = json!(observed); - let message = format!("{what} was open within {timeout_ms}ms"); + if crate::commands::wait_surface::unread(observed, kind) { + details["unread"] = json!(true); + return timeout_err( + format!("The {what} could not be read within {timeout_ms}ms"), + with_last_error(details, last_error), + ) + .map_err(|error| match error { + AppError::Adapter(error) => AppError::Adapter(error.with_suggestion( + "The inventory reports this kind as unread, so the application may still present it: details.last_observed names the window whose read was cut. list-surfaces shows what was read; raise --timeout only if the surface opens later.", + )), + other => other, + }); + } + let message = format!("No {what} was open within {timeout_ms}ms"); timeout_err(message, with_last_error(details, last_error)).map_err(|error| match error { AppError::Adapter(error) => AppError::Adapter(error.with_suggestion( "The application answered and showed no such surface: details.last_observed lists what was open. Raise --timeout only if the surface opens later.", diff --git a/crates/core/src/refs/resolve_saved_ref.rs b/crates/core/src/refs/resolve_saved_ref.rs index aa0815ed48..db1cb66fa2 100644 --- a/crates/core/src/refs/resolve_saved_ref.rs +++ b/crates/core/src/refs/resolve_saved_ref.rs @@ -163,6 +163,17 @@ pub(crate) fn recorded_window( return crate::system::app_lookup::live_process_owner(adapter, entry, deadline) .map_err(AppError::into_adapter_error); } + if let Some(window_id) = entry.source.source_window_id.as_deref() + && let Some(process) = entry.process.identity() + && let Some(window) = adapter.recorded_surface_window( + process, + window_id, + entry.source.source_surface, + deadline, + )? + { + return Ok(window); + } let resolved = crate::snapshot::resolve_window_for_surface( adapter, entry.source.source_app.as_deref(), diff --git a/crates/core/src/snapshot/snapshot_ref.rs b/crates/core/src/snapshot/snapshot_ref.rs index e30cad3d9d..1611932a59 100644 --- a/crates/core/src/snapshot/snapshot_ref.rs +++ b/crates/core/src/snapshot/snapshot_ref.rs @@ -149,7 +149,9 @@ fn resolve_result_owner( window: &WindowInfo, adapter: &dyn PlatformAdapter, ) -> Result { - if adapter.is_application_surface(entry.source.source_surface) { + if adapter.is_application_surface(entry.source.source_surface) + && entry.source.source_window_id.is_none() + { let app = super::surface_target::application_from_ref(entry)?; crate::system::app_lookup::process_identity(&app)?; Ok(SnapshotOwner::Application(app)) diff --git a/crates/core/src/snapshot/surface_target.rs b/crates/core/src/snapshot/surface_target.rs index 8851196244..73953ff72d 100644 --- a/crates/core/src/snapshot/surface_target.rs +++ b/crates/core/src/snapshot/surface_target.rs @@ -205,9 +205,20 @@ pub(crate) fn resolve_owners( return super::surface_windows(adapter, app_name, window_id, surface, deadline) .map(|windows| windows.into_iter().map(SnapshotOwner::Window).collect()); } - let app = if window_id.is_some() { - let window = super::resolve_window(adapter, app_name, window_id, deadline)?; - crate::system::app_lookup::resolve_app_owning(&window, adapter, deadline)? + let app = if let Some(window_id) = window_id { + match super::resolve_window(adapter, app_name, Some(window_id), deadline) { + Ok(window) => { + crate::system::app_lookup::resolve_app_owning(&window, adapter, deadline)? + } + Err(error) if error.code() == crate::ErrorCode::WindowNotFound.as_str() => { + return match surface_window_named(adapter, app_name, window_id, surface, deadline)? + { + Some(window) => Ok(vec![SnapshotOwner::Window(window)]), + None => Err(error), + }; + } + Err(error) => return Err(error), + } } else if app_name.is_some() { crate::system::app_lookup::resolve_app(app_name, adapter, deadline)? } else { @@ -220,9 +231,40 @@ pub(crate) fn resolve_owners( })? }; crate::system::app_lookup::process_identity(&app)?; + if let Some(window) = adapter.surface_window(&app, surface, deadline)? { + return Ok(vec![SnapshotOwner::Window(window)]); + } Ok(vec![SnapshotOwner::Application(app)]) } +/// The surface window a capture names through `--window-id`, when that id is a +/// surface window the window inventory leaves out. The application must also +/// be named, because a surface window carries a process rather than a census +/// record; an application label that cannot be resolved leaves this to the +/// inventory's own missing-window answer. +fn surface_window_named( + adapter: &dyn PlatformAdapter, + app_name: Option<&str>, + window_id: &str, + surface: crate::SnapshotSurface, + deadline: Deadline, +) -> Result, AppError> { + let Some(app_name) = app_name else { + return Ok(None); + }; + let Ok(app) = crate::system::app_lookup::resolve_app(Some(app_name), adapter, deadline) else { + return Ok(None); + }; + let process = crate::system::app_lookup::process_identity(&app)?; + let Some(mut window) = + adapter.recorded_surface_window(process, window_id, surface, deadline)? + else { + return Ok(None); + }; + window.app = app.name; + Ok(Some(window)) +} + pub(crate) fn resolve_ref_owner( adapter: &dyn PlatformAdapter, entry: &crate::RefEntry, @@ -238,11 +280,12 @@ pub(crate) fn resolve_ref_owner( if application_surface || entry.source.is_process_owned() { return Ok(match adapter.process_state(process, deadline)? { ProcessState::Running => { - let app = application_from_ref(entry)?; - let owner = if application_surface { - SnapshotOwner::Application(app) - } else { - SnapshotOwner::Window(crate::WindowInfo::for_process(&app)) + let owner = match (application_surface, entry.source.source_window_id.is_some()) { + (true, true) => SnapshotOwner::Window(source_window_info(entry)?), + (true, false) => SnapshotOwner::Application(application_from_ref(entry)?), + (false, _) => SnapshotOwner::Window(crate::WindowInfo::for_process( + &application_from_ref(entry)?, + )), }; RefOwnerObservation::Present(owner) } @@ -254,20 +297,7 @@ pub(crate) fn resolve_ref_owner( } }); } - let expected = crate::WindowInfo { - id: entry.source.source_window_id.clone().ok_or_else(|| { - AdapterError::new( - crate::ErrorCode::ActionNotSupported, - "Ref has no source window for post-action observation", - ) - })?, - title: entry.source.source_window_title.clone().unwrap_or_default(), - app: entry.source.source_app.clone().unwrap_or_default(), - pid: entry.process.pid, - process_instance: Some(process.instance.clone()), - bounds: None, - state: Default::default(), - }; + let expected = source_window_info(entry)?; match adapter.resolve_window_strict(&expected, deadline) { Ok(window) => { if window.id != expected.id @@ -311,6 +341,26 @@ pub(crate) fn application_from_ref(entry: &crate::RefEntry) -> Result Result { + Ok(WindowInfo { + id: entry.source.source_window_id.clone().ok_or_else(|| { + AdapterError::new( + crate::ErrorCode::ActionNotSupported, + "Ref has no source window for post-action observation", + ) + })?, + title: entry.source.source_window_title.clone().unwrap_or_default(), + app: entry.source.source_app.clone().unwrap_or_default(), + pid: entry.process.pid, + process_instance: entry.process.process_instance.clone(), + bounds: None, + state: Default::default(), + }) +} + pub(crate) fn ref_observation_surface( adapter: &dyn PlatformAdapter, entry: &crate::RefEntry, diff --git a/crates/macos/src/tree/mod.rs b/crates/macos/src/tree/mod.rs index 4809c51e71..a514e905d7 100644 --- a/crates/macos/src/tree/mod.rs +++ b/crates/macos/src/tree/mod.rs @@ -19,6 +19,7 @@ pub(crate) mod resolve; pub(crate) mod roles; pub(crate) mod shell_surface; pub(crate) mod state_reader; +pub(crate) mod surface_ids; pub(crate) mod surface_inventory; pub(crate) mod surface_read; pub(crate) mod surfaces; diff --git a/crates/macos/src/tree/surface_ids.rs b/crates/macos/src/tree/surface_ids.rs new file mode 100644 index 0000000000..60087928c9 --- /dev/null +++ b/crates/macos/src/tree/surface_ids.rs @@ -0,0 +1,154 @@ +use agent_desktop_core::SurfaceInfo; + +/// One window as the inventory read it, before the surfaces it presents are +/// turned into [`SurfaceInfo`] ids. Keeping the two steps apart lets the id +/// rules be exercised without a desktop. +pub(crate) struct WindowObservation { + pub(crate) number: Option, + pub(crate) kind: Option<&'static str>, + pub(crate) title: Option, + pub(crate) children: Vec, + pub(crate) popover: ObservedPopover, +} + +/// A direct child of a window that is itself a surface. +pub(crate) struct ChildSurface { + pub(crate) number: Option, + pub(crate) kind: &'static str, + pub(crate) title: Option, + pub(crate) index: usize, +} + +/// What the bounded popover search of one window settled on. +pub(crate) enum ObservedPopover { + /// The search read every element and found no popover. + Absent, + /// The search was cut at its element limit or left a container closed, so + /// a popover may be there and was not read. + Unread { title: Option }, + Found { + number: Option, + title: Option, + }, +} + +/// The surfaces one window presents, identified by stable AX window numbers. +/// +/// A window's id is its own number, the one `list-windows` reports as +/// `w-`. An unlisted popover uses its own number too, and a surface +/// presented inside a window that has no number of its own uses its parent's +/// stable id plus its kind and position among that parent's children. Closing +/// an earlier window then never re-ids a surface that survives it, which a +/// signal diff would otherwise read as one dismissal and one appearance. +/// +/// Only what cannot be identified is reported unread: a window whose own +/// number is missing still lists a surface that carries a number of its own, +/// and a plain window it presents nothing on adds no entry at all. +pub(crate) fn window_surfaces(window: WindowObservation) -> Vec { + let window_id = window.number.filter(|number| *number > 0).map(surface_id); + let mut surfaces = Vec::new(); + let mut unread = Vec::new(); + if let Some(kind) = window.kind { + match window_id.as_deref() { + Some(id) => surfaces.push(surface(id.to_owned(), kind, window.title.clone())), + None => push_unread_kind(&mut unread, kind), + } + } + for child in window.children { + match ( + child.number.filter(|number| *number > 0), + window_id.as_deref(), + ) { + (Some(number), _) => { + surfaces.push(surface(surface_id(number), child.kind, child.title)) + } + (None, Some(id)) => surfaces.push(surface( + format!("{id}/{}/{}", child.kind, child.index), + child.kind, + child.title, + )), + (None, None) => push_unread_kind(&mut unread, child.kind), + } + } + match (window.popover, window_id.as_deref()) { + (ObservedPopover::Absent, _) => {} + (ObservedPopover::Unread { title }, Some(id)) => { + mark_popover_unread(&mut surfaces, id, title) + } + (ObservedPopover::Unread { .. }, None) => push_unread_kind(&mut unread, "popover"), + (ObservedPopover::Found { number, title }, parent) => { + match (number.filter(|number| *number > 0), parent) { + (Some(number), _) => surfaces.push(surface(surface_id(number), "popover", title)), + (None, Some(id)) => { + surfaces.push(surface(format!("{id}/popover"), "popover", title)) + } + (None, None) => push_unread_kind(&mut unread, "popover"), + } + } + } + if !unread.is_empty() { + surfaces.push(unread_window(unread)); + } + surfaces +} + +fn push_unread_kind(unread: &mut Vec<&'static str>, kind: &'static str) { + if !unread.contains(&kind) { + unread.push(kind); + } +} + +/// A window whose own AX window number cannot be read, listing the kinds it +/// could present that were not identified. Marking them unread keeps a missing +/// entry from reading as an observed absence. +fn unread_window(kinds: Vec<&'static str>) -> SurfaceInfo { + SurfaceInfo { + id: "window/unread".into(), + kind: "window".into(), + title: None, + item_count: None, + unclassified: kinds.into_iter().map(str::to_string).collect(), + } +} + +pub(crate) fn surface(id: String, kind: &str, title: Option) -> SurfaceInfo { + SurfaceInfo { + id, + kind: kind.into(), + title, + item_count: None, + unclassified: Vec::new(), + } +} + +/// Adds `surface` unless the inventory already lists that id as that kind: one +/// window can be reached both as a window and as a surface of its own, and a +/// surface read twice is still one surface. +pub(crate) fn push_unique(surfaces: &mut Vec, surface: SurfaceInfo) { + let listed = surfaces + .iter() + .any(|listed| listed.id == surface.id && listed.kind == surface.kind); + if !listed { + surfaces.push(surface); + } +} + +/// The id `list-windows` and `snapshot --window-id` use for the same window. +pub(crate) fn surface_id(number: i64) -> String { + format!("w-{number}") +} + +fn mark_popover_unread(surfaces: &mut Vec, window_id: &str, title: Option) { + match surfaces.iter_mut().find(|entry| entry.id == window_id) { + Some(entry) => entry.unclassified.push("popover".into()), + None => { + let mut entry = surface(window_id.to_owned(), "window", title); + entry.unclassified.push("popover".into()); + surfaces.push(entry); + } + } +} + +#[cfg(test)] +#[path = "surface_ids_tests.rs"] +mod tests; diff --git a/crates/macos/src/tree/surface_ids_tests.rs b/crates/macos/src/tree/surface_ids_tests.rs new file mode 100644 index 0000000000..42fd4b8efd --- /dev/null +++ b/crates/macos/src/tree/surface_ids_tests.rs @@ -0,0 +1,246 @@ +use super::*; +use agent_desktop_core::{ + EventKind, ProcessId, SignalBaseline, SignalCompleteness, SnapshotSurface, SurfaceSignal, + diff_signals, +}; + +fn window( + number: Option, + children: Vec, + popover: ObservedPopover, +) -> WindowObservation { + WindowObservation { + number, + kind: None, + title: Some("Document".into()), + children, + popover, + } +} + +fn sheet() -> ChildSurface { + ChildSurface { + number: None, + kind: "sheet", + title: Some("Sheet".into()), + index: 0, + } +} + +fn ids(surfaces: &[SurfaceInfo]) -> Vec<&str> { + surfaces.iter().map(|surface| surface.id.as_str()).collect() +} + +#[test] +fn a_window_is_identified_by_its_ax_window_number() { + let surfaces = window_surfaces(window(Some(42), vec![sheet()], ObservedPopover::Absent)); + assert_eq!(ids(&surfaces), ["w-42/sheet/0"]); +} + +#[test] +fn a_surface_with_its_own_window_number_keeps_that_number() { + let surfaces = window_surfaces(window( + Some(42), + vec![ChildSurface { + number: Some(51), + kind: "sheet", + title: Some("Save".into()), + index: 0, + }], + ObservedPopover::Found { + number: Some(52), + title: Some("Filters".into()), + }, + )); + assert_eq!(ids(&surfaces), ["w-51", "w-52"]); +} + +#[test] +fn closing_an_earlier_window_never_re_ids_a_surviving_surface() { + let before = [ + window( + Some(11), + vec![sheet()], + ObservedPopover::Found { + number: None, + title: Some("Filters".into()), + }, + ), + window( + Some(42), + vec![sheet()], + ObservedPopover::Found { + number: None, + title: Some("Options".into()), + }, + ), + ] + .into_iter() + .flat_map(window_surfaces) + .collect::>(); + let after = [window( + Some(42), + vec![sheet()], + ObservedPopover::Found { + number: None, + title: Some("Options".into()), + }, + )] + .into_iter() + .flat_map(window_surfaces) + .collect::>(); + + assert_eq!( + ids(&before), + [ + "w-11/sheet/0", + "w-11/popover", + "w-42/sheet/0", + "w-42/popover" + ] + ); + assert_eq!(ids(&after), ["w-42/sheet/0", "w-42/popover"]); + + let events = diff_signals(&baseline(before), &baseline(after)); + assert!( + events + .iter() + .all(|event| !matches!(event.kind, EventKind::SurfaceAppeared { .. })), + "closing the first window re-identified the second window's surfaces: {events:?}" + ); + assert!( + events + .iter() + .filter(|event| matches!(event.kind, EventKind::SurfaceDismissed { .. })) + .count() + == 2, + "only the closed window's surfaces were dismissed: {events:?}" + ); +} + +fn baseline(surfaces: Vec) -> SignalBaseline { + SignalBaseline { + windows: Vec::new(), + apps: Vec::new(), + surfaces: surfaces + .into_iter() + .filter_map(|surface| { + Some(SurfaceSignal { + kind: kind_of_listed(&surface.kind)?, + app: "SurfaceApp".into(), + pid: ProcessId::new(42), + process_instance: "instance-42".into(), + id: surface.id, + title: surface.title, + }) + }) + .collect(), + completeness: SignalCompleteness::complete(), + } +} + +fn kind_of_listed(kind: &str) -> Option { + match kind { + "sheet" => Some(SnapshotSurface::Sheet), + "popover" => Some(SnapshotSurface::Popover), + "alert" => Some(SnapshotSurface::Alert), + "menu" | "context_menu" => Some(SnapshotSurface::Menu), + _ => None, + } +} + +#[test] +fn an_unnumbered_window_lists_a_surface_that_carries_its_own_number() { + let surfaces = window_surfaces(window( + None, + vec![ChildSurface { + number: Some(51), + kind: "sheet", + title: Some("Save".into()), + index: 0, + }], + ObservedPopover::Absent, + )); + assert_eq!(ids(&surfaces), ["w-51"]); +} + +#[test] +fn an_unnumbered_window_reports_only_the_kinds_it_could_not_identify() { + let surfaces = window_surfaces(window( + None, + vec![sheet()], + ObservedPopover::Unread { + title: Some("Document".into()), + }, + )); + assert_eq!(ids(&surfaces), ["window/unread"]); + assert_eq!(surfaces[0].kind, "window"); + assert_eq!(surfaces[0].unclassified, ["sheet", "popover"]); + assert_eq!(surfaces[0].title, None); +} + +#[test] +fn a_plain_unnumbered_window_lists_nothing() { + let surfaces = window_surfaces(window(None, Vec::new(), ObservedPopover::Absent)); + assert!(surfaces.is_empty()); +} + +#[test] +fn a_cut_popover_search_names_popover_unread_on_the_window() { + let surfaces = window_surfaces(window( + Some(7), + Vec::new(), + ObservedPopover::Unread { + title: Some("Document".into()), + }, + )); + assert_eq!(ids(&surfaces), ["w-7"]); + assert_eq!(surfaces[0].kind, "window"); + assert_eq!(surfaces[0].unclassified, ["popover"]); + + let marked = window_surfaces(window( + Some(7), + Vec::new(), + ObservedPopover::Unread { title: None }, + )); + assert_eq!(marked[0].unclassified, ["popover"]); +} + +#[test] +fn a_complete_popover_search_without_a_popover_lists_nothing() { + let surfaces = window_surfaces(window(Some(7), Vec::new(), ObservedPopover::Absent)); + assert!(surfaces.is_empty()); +} + +#[test] +fn duplicate_reads_of_one_surface_are_listed_once() { + let mut surfaces = vec![SurfaceInfo { + id: "w-51".into(), + kind: "sheet".into(), + title: None, + item_count: None, + unclassified: Vec::new(), + }]; + push_unique( + &mut surfaces, + SurfaceInfo { + id: "w-51".into(), + kind: "sheet".into(), + title: None, + item_count: None, + unclassified: Vec::new(), + }, + ); + push_unique( + &mut surfaces, + SurfaceInfo { + id: "w-51".into(), + kind: "popover".into(), + title: None, + item_count: None, + unclassified: Vec::new(), + }, + ); + assert_eq!(ids(&surfaces), ["w-51", "w-51"]); + assert_eq!(surfaces[1].kind, "popover"); +} diff --git a/crates/macos/src/tree/surface_inventory.rs b/crates/macos/src/tree/surface_inventory.rs index f16ac514c1..9a6a6cb816 100644 --- a/crates/macos/src/tree/surface_inventory.rs +++ b/crates/macos/src/tree/surface_inventory.rs @@ -1,6 +1,11 @@ use crate::tree::{AXElement, properties::element::element_for_pid}; use agent_desktop_core::{AdapterError, Deadline, SurfaceInfo}; +use super::surface_ids::{ + ChildSurface, ObservedPopover, WindowObservation, push_unique, surface, surface_id, + window_surfaces, +}; + /// 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; @@ -15,11 +20,7 @@ pub(crate) fn list_surfaces_for_process( let windows = read_array(&app, "AXWindows", deadline)?.unwrap_or_default(); let listed = windows .iter() - .filter_map(|window| { - crate::system::window::window_resolve::ax_window_id_with_deadline(window, deadline) - .ok() - .flatten() - }) + .filter_map(|window| window_number(window, deadline).ok().flatten()) .collect(); let popovers = crate::system::window::popup_window::shows_unlisted_window(identity.pid(), &listed); @@ -50,12 +51,10 @@ fn list_surfaces_once( deadline, || { let mut surfaces = Vec::new(); - for (index, window) in windows()?.iter().enumerate() { - let id = format!("windows/{index}"); - let listed = surfaces.len(); - collect_window_surfaces(window, &id, deadline, &mut surfaces)?; - if popovers && !surfaces[listed..].iter().any(|s| s.kind == "popover") { - push_anchored_popover(window, &id, deadline, &mut surfaces)?; + for window in windows()? { + let observed = observe_window(&window, deadline, popovers)?; + for surface in window_surfaces(observed) { + push_unique(&mut surfaces, surface); } } Ok(surfaces) @@ -70,38 +69,67 @@ fn list_surfaces_once( ) } -/// A headless target window is rarely the focused one, and a popover hangs -/// below the control that raised it, so while the application shows a window -/// its accessibility window list leaves out, every window gets the bounded -/// popover search. A window whose search did not read every element names -/// `popover` unclassified, so a missing popover is not taken for an observed -/// absence. -fn push_anchored_popover( +/// Reads one window, and searches it for a popover when the application shows +/// a window its accessibility window list leaves out. +fn observe_window( window: &AXElement, - window_id: &str, deadline: Deadline, - surfaces: &mut Vec, -) -> Result<(), AdapterError> { - let popover = match super::surfaces::popover_in_window(window, deadline) { - Ok(popover) => popover, - Err(error) if is_incomplete(&error) => { - let title = read_title(window, deadline)?; - mark_popover_unread(surfaces, window_id, title); - None - } - Err(error) if error.code == agent_desktop_core::ErrorCode::ElementNotFound => None, - Err(error) => return Err(error), + popovers: bool, +) -> Result { + let number = window_number(window, deadline)?; + let mut children = Vec::new(); + let listed = read_array(window, "AXChildren", deadline)?.unwrap_or_default(); + for (index, child) in listed.iter().enumerate() { + let Some(kind) = surface_kind(child, deadline)? else { + continue; + }; + children.push(ChildSurface { + number: window_number(child, deadline)?, + kind, + title: read_title(child, deadline)?, + index, + }); + } + let popover = if popovers && !children.iter().any(|child| child.kind == "popover") { + observe_popover(window, deadline)? + } else { + ObservedPopover::Absent }; - if let Some(popover) = popover { - surfaces.push(SurfaceInfo { - id: format!("{window_id}/popover"), - kind: "popover".into(), + Ok(WindowObservation { + number, + kind: surface_kind(window, deadline)?, + title: read_title(window, deadline)?, + children, + popover, + }) +} + +/// The bounded popover search of one window. A search that read every element +/// and found no popover settles an absence; a search cut at its element limit +/// names `popover` unclassified instead, so a popover it could not read is +/// never reported as one the application does not show. Any other failure is +/// the read's own and propagates. +fn observe_popover( + window: &AXElement, + deadline: Deadline, +) -> Result { + match super::surfaces::popover_in_window(window, deadline) { + Ok(Some(popover)) => Ok(ObservedPopover::Found { + number: window_number(&popover, deadline)?, title: read_title(&popover, deadline)?, - item_count: None, - unclassified: Vec::new(), - }); + }), + Ok(None) => Ok(ObservedPopover::Absent), + Err(error) if is_incomplete(&error) => Ok(ObservedPopover::Unread { + title: read_title(window, deadline)?, + }), + Err(error) => Err(error), } - Ok(()) +} + +fn window_number(element: &AXElement, deadline: Deadline) -> Result, AdapterError> { + let number = + crate::system::window::window_resolve::ax_window_id_with_deadline(element, deadline)?; + Ok(number.filter(|number| *number > 0)) } fn is_incomplete(error: &AdapterError) -> bool { @@ -111,19 +139,6 @@ fn is_incomplete(error: &AdapterError) -> bool { .is_some_and(|details| details["complete"] == false) } -fn mark_popover_unread(surfaces: &mut Vec, window_id: &str, title: Option) { - match surfaces.iter_mut().find(|entry| entry.id == window_id) { - Some(entry) => entry.unclassified.push("popover".into()), - None => surfaces.push(SurfaceInfo { - id: window_id.to_owned(), - kind: "window".into(), - title, - item_count: None, - unclassified: vec!["popover".into()], - }), - } -} - fn list_surfaces_with( deadline: Deadline, window_surfaces: impl FnOnce() -> Result, AdapterError>, @@ -175,8 +190,24 @@ pub(crate) fn collect_anchored_surfaces( children.as_concrete_TypeRef(), deadline, ); - if anchors_few_children(count.ok()) { - let _ = collect_window_surfaces(anchor, "target", deadline, surfaces); + if !anchors_few_children(count.ok()) { + return; + } + let Ok(listed) = read_array(anchor, "AXChildren", deadline) else { + return; + }; + for (index, child) in listed.unwrap_or_default().iter().enumerate() { + let Ok(Some(kind)) = surface_kind(child, deadline) else { + continue; + }; + let Ok(title) = read_title(child, deadline) else { + continue; + }; + let id = window_number(child, deadline) + .ok() + .flatten() + .map_or_else(|| format!("target/{kind}/{index}"), surface_id); + surfaces.push(surface(id, kind, title)); } } @@ -202,38 +233,6 @@ fn anchors_few_children(count: Option) -> bool { count.is_some_and(|count| (1..=ANCHOR_CHILD_LIMIT).contains(&count)) } -fn collect_window_surfaces( - window: &AXElement, - window_id: &str, - deadline: Deadline, - surfaces: &mut Vec, -) -> Result<(), AdapterError> { - if let Some(kind) = surface_kind(window, deadline)? { - surfaces.push(SurfaceInfo { - id: window_id.to_string(), - kind: kind.into(), - title: read_title(window, deadline)?, - item_count: None, - unclassified: Vec::new(), - }); - } - let Some(children) = read_array(window, "AXChildren", deadline)? else { - return Ok(()); - }; - for (index, child) in children.iter().enumerate() { - if let Some(kind) = surface_kind(child, deadline)? { - surfaces.push(SurfaceInfo { - id: format!("{window_id}/children/{index}"), - kind: kind.into(), - title: read_title(child, deadline)?, - item_count: None, - unclassified: Vec::new(), - }); - } - } - Ok(()) -} - fn surface_kind( element: &AXElement, deadline: Deadline, diff --git a/crates/macos/src/tree/surface_inventory_tests.rs b/crates/macos/src/tree/surface_inventory_tests.rs index 24f6dbc0df..309931d79c 100644 --- a/crates/macos/src/tree/surface_inventory_tests.rs +++ b/crates/macos/src/tree/surface_inventory_tests.rs @@ -14,9 +14,9 @@ fn surface(id: &str, kind: &str) -> SurfaceInfo { #[test] fn shared_menu_discovery_preserves_other_surfaces_and_existing_menu_ids() { let window_surfaces = vec![ - surface("focused-window", "sheet"), - surface("focused-window/children/2", "popover"), - surface("focused-window/children/4", "alert"), + surface("w-7", "sheet"), + surface("w-9", "popover"), + surface("w-11", "alert"), ]; for menus in [ vec![], @@ -123,14 +123,7 @@ fn a_system_dialog_is_listed_as_an_alert_like_a_dialog() { } #[test] -fn a_cut_popover_search_names_popover_unread_on_the_window() { - let mut surfaces = vec![surface("windows/0", "sheet")]; - mark_popover_unread(&mut surfaces, "windows/0", None); - mark_popover_unread(&mut surfaces, "windows/1", Some("Doc".into())); - assert_eq!(surfaces[0].unclassified, ["popover"]); - assert_eq!(surfaces[1].id, "windows/1"); - assert_eq!(surfaces[1].kind, "window"); - assert_eq!(surfaces[1].unclassified, ["popover"]); +fn an_unclassified_read_is_incomplete_and_a_settled_absence_is_not() { let cut = AdapterError::new(agent_desktop_core::ErrorCode::ElementNotFound, "cut") .with_details(serde_json::json!({ "complete": false })); assert!(is_incomplete(&cut)); diff --git a/crates/windows/src/adapter.rs b/crates/windows/src/adapter.rs index e72625fd0e..286f199c96 100644 --- a/crates/windows/src/adapter.rs +++ b/crates/windows/src/adapter.rs @@ -56,12 +56,46 @@ impl Default for WindowsAdapter { } impl ObservationOps for WindowsAdapter { - /// A popover belongs to the application, not to one window: its refs resolve - /// against the application's open popover. + /// A popover belongs to the application, not to a census window: its refs + /// stay observable while the process lives, and `surface_window` records + /// the popover a capture read so resolution lands on that one. fn is_application_surface(&self, surface: SnapshotSurface) -> bool { surface == SnapshotSurface::Popover } + /// A popover is presented by a popup window of its own, so a capture names + /// that window. With several popovers open, the refs it allocates then + /// resolve against the popover that was read instead of whichever the + /// process happens to show first. + fn surface_window( + &self, + app: &agent_desktop_core::AppInfo, + surface: SnapshotSurface, + deadline: Deadline, + ) -> Result, AdapterError> { + if surface != SnapshotSurface::Popover { + return Ok(None); + } + crate::tree::popover_choice::popover_window(app, deadline).map(Some) + } + + /// A stored popover ref, or a capture that named one with `--window-id`, + /// names the popover it means, so it resolves against that window and + /// never against whichever popover the process shows first. + fn recorded_surface_window( + &self, + process: agent_desktop_core::ProcessIdentity, + window_id: &str, + surface: SnapshotSurface, + deadline: Deadline, + ) -> Result, AdapterError> { + if surface != SnapshotSurface::Popover { + return Ok(None); + } + crate::tree::popover_choice::recorded_popover_window(&process, window_id, deadline) + .map(Some) + } + fn observe_tree( &self, root: ObservationRoot<'_>, diff --git a/crates/windows/src/tree/mod.rs b/crates/windows/src/tree/mod.rs index 84d50b1be6..571fb1044e 100644 --- a/crates/windows/src/tree/mod.rs +++ b/crates/windows/src/tree/mod.rs @@ -8,6 +8,7 @@ pub(crate) mod live_read; pub(crate) mod minimized; pub mod name_evidence; pub(crate) mod observe; +pub(crate) mod popover_choice; pub(crate) mod popover_inventory; pub(crate) mod resolve; pub mod roles; diff --git a/crates/windows/src/tree/popover_choice.rs b/crates/windows/src/tree/popover_choice.rs new file mode 100644 index 0000000000..0b77b21541 --- /dev/null +++ b/crates/windows/src/tree/popover_choice.rs @@ -0,0 +1,158 @@ +use agent_desktop_core::{ + AdapterError, AppInfo, Deadline, ErrorCode, ProcessId, ProcessIdentity, WindowInfo, +}; + +use super::surface_inventory::windows_of; +use crate::system::window::window_enum::{EnumeratedWindow, WindowHandle}; +use crate::system::window::window_identity::live_window_title; + +/// The popover a snapshot, a surface read or a stored ref means. +/// +/// A named id must still be one of the process's open popovers: a handle the +/// process no longer presents that way is refused, never followed. With no id +/// there must be exactly one open popover. Several open popovers are refused +/// with their ids rather than resolved to the first, because the caller named +/// none and picking one would land on a popover it never read. +pub(crate) fn resolve_popover( + pid: ProcessId, + named: Option<&str>, + deadline: Deadline, +) -> Result { + let open = windows_of(pid, deadline)?.1; + let handles = open + .iter() + .map(|popover| popover.handle) + .collect::>(); + let handle = choose_popover(&handles, named)?; + open.into_iter() + .find(|popover| popover.handle == handle) + .ok_or_else(no_popover) +} + +/// The window a fresh popover capture is rooted at, identified by the same +/// `w-` id `list-surfaces` reports, so the refs it allocates resolve +/// against the popover that was read. The bounds stay unset: the popover is +/// not a census window, and a window-relative bounds space would change what +/// every ref in it means. +pub(crate) fn popover_window( + app: &AppInfo, + deadline: Deadline, +) -> Result { + let popover = resolve_popover(app.pid, None, deadline)?; + Ok(popover_info( + app.name.clone(), + app.pid, + app.process_instance.clone(), + popover, + )) +} + +/// The popover window a caller named: a stored ref's recorded id, or the +/// `--window-id` of a capture. The id must still name an open popover of that +/// exact process instance: a closed popover, or one owned by a newer process +/// that reused the pid, is refused instead of resolved. +pub(crate) fn recorded_popover_window( + process: &ProcessIdentity, + window_id: &str, + deadline: Deadline, +) -> Result { + if !crate::system::process_identity::matches_instance(process.pid, &process.instance)? { + return Err(popover_closed(window_id, &[])); + } + let popover = resolve_popover(process.pid, Some(window_id), deadline)?; + Ok(popover_info( + crate::system::process_identity::process_image_name(process.pid).unwrap_or_default(), + process.pid, + Some(process.instance.clone()), + popover, + )) +} + +fn popover_info( + app: String, + pid: ProcessId, + process_instance: Option, + popover: EnumeratedWindow, +) -> WindowInfo { + WindowInfo { + id: handle_id(popover.handle), + title: live_window_title(popover.handle).unwrap_or_default(), + app, + pid, + process_instance, + bounds: None, + state: Default::default(), + } +} + +/// The popover handle a caller means, from the process's open popover handles. +fn choose_popover( + open: &[WindowHandle], + named: Option<&str>, +) -> Result { + match named { + Some(id) => open + .iter() + .copied() + .find(|handle| handle_id(*handle) == id) + .ok_or_else(|| popover_closed(id, open)), + None => match open { + [] => Err(no_popover()), + [only] => Ok(*only), + [_, _, ..] => Err(ambiguous_popover(open)), + }, + } +} + +/// The id every window-backed surface on this platform carries, and the id +/// `list-surfaces` reports for the same window. +pub(super) fn handle_id(handle: WindowHandle) -> String { + format!("w-{}", handle as usize) +} + +fn no_popover() -> AdapterError { + AdapterError::new( + ErrorCode::WindowNotFound, + "No popover is open in this application", + ) +} + +fn popover_closed(named: &str, open: &[WindowHandle]) -> AdapterError { + AdapterError::new( + ErrorCode::WindowNotFound, + "The window is not an open popover of this application", + ) + .with_details(serde_json::json!({ + "kind": "popover_closed", + "window_id": named, + "candidates": open.iter().map(|handle| handle_id(*handle)).collect::>(), + })) + .with_suggestion( + "Run 'list-surfaces' to see the open popover ids, then target the one you mean.", + ) +} + +fn ambiguous_popover(open: &[WindowHandle]) -> AdapterError { + let candidates = open + .iter() + .map(|handle| handle_id(*handle)) + .collect::>(); + AdapterError::new( + ErrorCode::AmbiguousTarget, + format!( + "More than one popover is open in this application: {}", + candidates.join(", ") + ), + ) + .with_details(serde_json::json!({ + "kind": "popover_ambiguous", + "candidates": candidates, + })) + .with_suggestion( + "Run 'list-surfaces' to see the open popover ids, then read one with 'snapshot --surface popover --app --window-id ', or close the popovers you do not need.", + ) +} + +#[cfg(test)] +#[path = "popover_choice_tests.rs"] +mod tests; diff --git a/crates/windows/src/tree/popover_choice_tests.rs b/crates/windows/src/tree/popover_choice_tests.rs new file mode 100644 index 0000000000..cd8c2772f9 --- /dev/null +++ b/crates/windows/src/tree/popover_choice_tests.rs @@ -0,0 +1,59 @@ +//! Popover selection: which open popover a capture, a surface read or a stored +//! ref lands on when the process has none, one or several. + +use super::{choose_popover, handle_id}; +use crate::system::window::window_enum::WindowHandle; +use agent_desktop_core::ErrorCode; +use serde_json::json; + +fn handle(number: usize) -> WindowHandle { + number as WindowHandle +} + +#[test] +fn two_open_popovers_without_an_id_are_refused_with_their_ids() { + let error = choose_popover(&[handle(17), handle(34)], None).unwrap_err(); + + assert_eq!(error.code, ErrorCode::AmbiguousTarget); + assert!( + error.message.contains("w-17") && error.message.contains("w-34"), + "the refusal names the open popovers: {}", + error.message + ); + let details = error.details.expect("ambiguous popover carries candidates"); + assert_eq!(details["kind"], "popover_ambiguous"); + assert_eq!(details["candidates"], json!(["w-17", "w-34"])); +} + +#[test] +fn a_named_popover_is_the_one_returned_even_with_two_open() { + let chosen = choose_popover(&[handle(17), handle(34)], Some("w-34")).expect("named popover"); + + assert_eq!(handle_id(chosen), "w-34"); +} + +#[test] +fn a_name_that_is_not_an_open_popover_is_refused() { + let error = choose_popover(&[handle(17)], Some("w-34")).unwrap_err(); + + assert_eq!(error.code, ErrorCode::WindowNotFound); + let details = error.details.expect("a closed popover lists what is open"); + assert_eq!(details["kind"], "popover_closed"); + assert_eq!(details["window_id"], "w-34"); + assert_eq!(details["candidates"], json!(["w-17"])); +} + +#[test] +fn no_open_popover_is_a_missing_window() { + let error = choose_popover(&[], None).unwrap_err(); + + assert_eq!(error.code, ErrorCode::WindowNotFound); +} + +#[test] +fn one_open_popover_is_unambiguous() { + assert_eq!( + handle_id(choose_popover(&[handle(17)], None).expect("one popover")), + "w-17" + ); +} diff --git a/crates/windows/src/tree/resolve/resolve_anchor.rs b/crates/windows/src/tree/resolve/resolve_anchor.rs index f16a905ca6..5e655bf049 100644 --- a/crates/windows/src/tree/resolve/resolve_anchor.rs +++ b/crates/windows/src/tree/resolve/resolve_anchor.rs @@ -59,9 +59,11 @@ pub(crate) fn resolve_locator_anchor( Err(stale_ref_error(entry)) } -/// A popover ref's path starts at the application's open popover, and the -/// popover is no listed window: the process generation is checked and the -/// popover found by the same predicate the inventory uses. +/// A popover ref's path starts at the popover it was captured from, and a +/// popover is no listed window: the process generation is checked, then the +/// popover the ref recorded is found by the same predicate the inventory uses. +/// A ref that recorded no popover id is resolved only when one popover is +/// open; several are refused with their ids rather than guessed at. #[cfg(target_os = "windows")] fn popover_root(entry: &RefEntry, deadline: Deadline) -> Result, AdapterError> { if entry.source.source_surface != agent_desktop_core::SnapshotSurface::Popover { @@ -79,9 +81,25 @@ fn popover_root(entry: &RefEntry, deadline: Deadline) -> Result AdapterError { + if error.code == agent_desktop_core::ErrorCode::WindowNotFound { + stale_ref_error(entry) + } else { + error + } } /// The one pure gate runs first, before any of `resolve_window_root`, diff --git a/crates/windows/src/tree/surface_inventory.rs b/crates/windows/src/tree/surface_inventory.rs index 42c87abdcf..4dcf4d5510 100644 --- a/crates/windows/src/tree/surface_inventory.rs +++ b/crates/windows/src/tree/surface_inventory.rs @@ -77,23 +77,8 @@ fn require_live_process(process: &ProcessIdentity) -> Result<(), AdapterError> { )) } -/// The pid's agent-facing top-level windows, from the one enumeration pass -/// every window inventory on this platform shares - the same walk -/// `list_windows` and the menu detector draw from, filtered by the same -/// census predicate. -/// The handle of the process's first open popover, if any. -pub(crate) fn first_popover( - pid: ProcessId, - deadline: Deadline, -) -> Result, AdapterError> { - Ok(windows_of(pid, deadline)? - .1 - .first() - .map(|popover| popover.handle)) -} - /// The process's census windows and its popovers (tool windows the census drops). -fn windows_of( +pub(super) fn windows_of( pid: ProcessId, deadline: Deadline, ) -> Result<(Vec, Vec), AdapterError> { @@ -126,7 +111,7 @@ fn windows_of( fn surface(kind: SnapshotSurface, handle: WindowHandle, title: Option) -> SurfaceInfo { SurfaceInfo { - id: format!("w-{}", handle as usize), + id: super::popover_choice::handle_id(handle), kind: kind.as_str().to_string(), title, item_count: None, diff --git a/crates/windows/src/tree/surfaces.rs b/crates/windows/src/tree/surfaces.rs index 17c6abbf21..df26fff55f 100644 --- a/crates/windows/src/tree/surfaces.rs +++ b/crates/windows/src/tree/surfaces.rs @@ -24,14 +24,8 @@ pub(crate) fn surface_root( ) -> Result { match (root, surface) { (ObservationRoot::Application { app, .. }, SnapshotSurface::Popover) => { - let popover = crate::tree::surface_inventory::first_popover(app.pid, deadline)? - .ok_or_else(|| { - AdapterError::new( - ErrorCode::WindowNotFound, - "No popover is open in this application", - ) - })?; - root_from_hwnd(popover as isize, deadline) + let popover = crate::tree::popover_choice::resolve_popover(app.pid, None, deadline)?; + root_from_hwnd(popover.handle as isize, deadline) } (ObservationRoot::Application { .. }, _) => { Err(AdapterError::not_supported("application observation root")) @@ -74,14 +68,8 @@ pub(crate) fn surface_root( root_from_hwnd(location.root_handle(), deadline) } (ObservationRoot::Window(window), SnapshotSurface::Popover) => { - let popover = crate::tree::surface_inventory::first_popover(window.pid, deadline)? - .ok_or_else(|| { - AdapterError::new( - ErrorCode::WindowNotFound, - "No popover is open in this application", - ) - })?; - root_from_hwnd(popover as isize, deadline) + let popover = popover_handle(window.pid, &window.id, deadline)?; + root_from_hwnd(popover.handle as isize, deadline) } (ObservationRoot::Window(window), SnapshotSurface::StartMenu) | (ObservationRoot::Window(window), SnapshotSurface::Taskbar) @@ -104,6 +92,24 @@ pub(crate) fn surface_root( } } +/// The popover a window-rooted surface read lands on. A window id that names +/// one of the process's open popovers reads that popover. Any other window id +/// keeps this platform's meaning - the popover of that window's application - +/// and is refused when several are open, since none of them was named. +fn popover_handle( + pid: agent_desktop_core::ProcessId, + named: &str, + deadline: Deadline, +) -> Result { + match crate::tree::popover_choice::resolve_popover(pid, Some(named), deadline) { + Ok(popover) => Ok(popover), + Err(error) if error.code == ErrorCode::WindowNotFound => { + crate::tree::popover_choice::resolve_popover(pid, None, deadline) + } + Err(error) => Err(error), + } +} + /// The focused window's HWND, found through the focused-only window inventory /// the same way `focused_window` composes it. fn focused_hwnd_of(expected: &str) -> Result { diff --git a/skills/agent-desktop-windows/SKILL.md b/skills/agent-desktop-windows/SKILL.md index 19cee84c36..db68e9f23d 100644 --- a/skills/agent-desktop-windows/SKILL.md +++ b/skills/agent-desktop-windows/SKILL.md @@ -60,6 +60,8 @@ Use `$env:NAME = 'value'` for environment variables. bounded observation before concluding that content is absent. - An open application menu is the `menu` surface; there is no `menubar` surface. An owned popup window of the app (a ribbon drop-down) is a `popover`: `list-surfaces` lists it, `snapshot --surface popover` reads it. + When several popovers are open, name one with `--app --window-id `; + without a name the read is refused with `AMBIGUOUS_TARGET` rather than reading a different popover. Shell surfaces are separate from ordinary window inventory. `quick-settings` refuses with `INVALID_ARGS` naming `action-center`. - Notification reads adopt an already-open Action Center headless; opening it diff --git a/src/cli/doc_literal_drift_tests.rs b/src/cli/doc_literal_drift_tests.rs index dc8181612c..dccf72159b 100644 --- a/src/cli/doc_literal_drift_tests.rs +++ b/src/cli/doc_literal_drift_tests.rs @@ -23,6 +23,7 @@ const ABI_DOCS: &[(&str, &str)] = &[ const FFI_HEADER: &str = include_str!("../../crates/ffi/include/agent_desktop.h"); const README: &str = include_str!("../../README.md"); const AGENTS_MD: &str = include_str!("../../AGENTS.md"); +const WAIT_REFERENCE: &str = include_str!("../../apps/docs/content/docs/commands/wait.mdx"); const HELD_INPUT_COMMANDS: &[&str] = &["key-down", "key-up", "mouse-down", "mouse-up"]; fn quoted_values_after<'a>(text: &'a str, marker: &str) -> Vec<&'a str> { @@ -113,3 +114,44 @@ fn documented_command_counts_match_the_cli() { "AGENTS.md must state {operational} of the {total} command names are operational" ); } + +/// The wait reference documents every flag the `wait` subcommand accepts, so a +/// new wait mode cannot ship without its line in the reference. The flags come +/// from the clap tree the binary runs, never from a list kept beside the docs. +#[test] +fn wait_reference_documents_every_wait_flag() { + let wait = Cli::command() + .get_subcommands() + .find(|command| command.get_name() == "wait") + .expect("the wait subcommand exists") + .clone(); + let mut flags = wait + .get_arguments() + .filter(|argument| !matches!(argument.get_id().as_str(), "help" | "version")) + .filter_map(|argument| argument.get_long()) + .collect::>(); + flags.sort_unstable(); + assert!( + flags.contains(&"surface"), + "wait accepts --surface: {flags:?}" + ); + for flag in flags { + assert!( + documents_flag(WAIT_REFERENCE, flag), + "apps/docs/content/docs/commands/wait.mdx does not document --{flag}" + ); + } +} + +/// Whether `reference` names `flag` as a whole flag: a `--window` line does not +/// document `--window-id`, and a longer flag containing the name documents +/// nothing. +fn documents_flag(reference: &str, flag: &str) -> bool { + let named = format!("--{flag}"); + reference.match_indices(&named).any(|(at, matched)| { + reference[at + matched.len()..] + .chars() + .next() + .is_none_or(|next| !(next.is_ascii_alphanumeric() || next == '-')) + }) +} From 8c1004eb2b14209ba76af316d8a93a363a92348b Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:35:51 -0800 Subject: [PATCH 21/26] fix(refs): read a saved surface ref at the window it recorded A ref captured from a surface the platform presents in a window of its own records that window, and recorded_window re-verifies it. The observation built from it then discarded the window and started at the application root whenever the adapter called the surface application-owned. On Windows that root re-resolves the popover from the pid alone, so a second popover opened after capture made a saved popover ref fail with AMBIGUOUS_TARGET. The observation now starts at the recorded window unless it is a process owner, the only case with no window to read. Windows already resolves a window-rooted popover by the id it names. --- .../application_surface_window_tests.rs | 144 ++++++++++++++++++ crates/core/src/refs/resolve_saved_ref.rs | 45 ++++-- 2 files changed, 178 insertions(+), 11 deletions(-) diff --git a/crates/core/src/commands/application_surface_window_tests.rs b/crates/core/src/commands/application_surface_window_tests.rs index b8a7a18962..53ced14595 100644 --- a/crates/core/src/commands/application_surface_window_tests.rs +++ b/crates/core/src/commands/application_surface_window_tests.rs @@ -108,3 +108,147 @@ fn naming_the_surface_window_reads_it_even_though_it_is_not_a_listed_window() { "the named surface window is captured at that window: {owners:?}" ); } + +/// An adapter whose popover surface behaves the way Windows does: the surface is +/// application-owned, two popovers are open, and an observation that starts at +/// the application root names neither, so it is refused as ambiguous. Only the +/// id a ref recorded can pick one popover out of the two. +#[derive(Default)] +struct TwoPopoverAdapter { + observed: std::sync::Mutex>, +} + +impl TwoPopoverAdapter { + fn popover(id: &str) -> WindowInfo { + WindowInfo { + id: id.into(), + ..popover_owner_surface_window() + } + } + + fn observed_roots(&self) -> Vec<(String, SnapshotSurface)> { + self.observed.lock().unwrap().clone() + } +} + +impl crate::adapter::ObservationOps for TwoPopoverAdapter { + fn is_application_surface(&self, surface: SnapshotSurface) -> bool { + surface == SnapshotSurface::Popover + } + + fn recorded_surface_window( + &self, + process: crate::ProcessIdentity, + window_id: &str, + surface: SnapshotSurface, + _deadline: Deadline, + ) -> Result, crate::AdapterError> { + let open = ["w-1", "w-2"]; + Ok(open + .contains(&window_id) + .then(|| Self::popover(window_id)) + .filter(|window| { + surface == SnapshotSurface::Popover + && window.pid == process.pid + && window.process_instance.as_deref() == Some(process.instance.as_str()) + })) + } + + fn list_windows( + &self, + _filter: &crate::adapter::WindowFilter, + _deadline: Deadline, + ) -> Result, crate::AdapterError> { + Ok(Vec::new()) + } + + fn observe_tree( + &self, + root: crate::ObservationRoot<'_>, + request: &crate::ObservationRequest, + ) -> Result { + match root { + crate::ObservationRoot::Application { .. } + if request.surface == SnapshotSurface::Popover => + { + Err(crate::AdapterError::new( + crate::ErrorCode::AmbiguousTarget, + "More than one popover is open in this application: w-1, w-2", + )) + } + crate::ObservationRoot::Window(window) => { + self.observed + .lock() + .unwrap() + .push((window.id.clone(), request.surface)); + crate::adapter::observed_tree(&root, popover_node()) + } + crate::ObservationRoot::Application { .. } | crate::ObservationRoot::Element { .. } => { + crate::adapter::observed_tree(&root, popover_node()) + } + } + } + + fn resolve_locator_anchor( + &self, + _entry: &RefEntry, + _base: Option<&crate::NativeHandle>, + _deadline: Deadline, + ) -> Result { + Ok(crate::NativeHandle::new("popover-anchor")) + } +} + +impl crate::adapter::ActionOps for TwoPopoverAdapter {} +impl crate::adapter::InputOps for TwoPopoverAdapter {} +impl crate::adapter::SystemOps for TwoPopoverAdapter {} + +fn popover_node() -> crate::AccessibilityNode { + crate::adapter::minimal_accessibility_node("button", "Run") +} + +#[test] +fn a_saved_popover_ref_is_observed_at_the_window_it_recorded() { + let adapter = TwoPopoverAdapter::default(); + let entry = popover_entry("w-1"); + + let (window, _, _) = crate::refs::resolve_saved_ref::observe_saved_ref( + &adapter, + &entry, + Deadline::standard().unwrap(), + None, + true, + ) + .expect("the recorded popover answers for its own ref while another popover is open"); + + assert_eq!(window.id, "w-1"); + assert_eq!( + adapter.observed_roots(), + vec![("w-1".to_string(), SnapshotSurface::Popover)], + "the observation names the popover the ref recorded" + ); +} + +#[test] +fn a_saved_popover_ref_resolves_while_a_second_popover_is_open() { + let adapter = TwoPopoverAdapter::default(); + let entry = popover_entry("w-2"); + + let handle = crate::refs::resolve_saved_ref::resolve_saved_ref( + &adapter, + &entry, + Deadline::standard().unwrap(), + None, + ) + .expect("a saved ref naming its popover is never ambiguous"); + + assert_eq!( + handle.downcast_ref::<&'static str>().copied(), + Some("popover-anchor") + ); + assert_eq!( + adapter.observed_roots().first().cloned(), + Some(("w-2".to_string(), SnapshotSurface::Popover)), + "resolution reads the popover the ref recorded" + ); +} diff --git a/crates/core/src/refs/resolve_saved_ref.rs b/crates/core/src/refs/resolve_saved_ref.rs index db1cb66fa2..6d365d8483 100644 --- a/crates/core/src/refs/resolve_saved_ref.rs +++ b/crates/core/src/refs/resolve_saved_ref.rs @@ -1,6 +1,6 @@ use crate::{ AdapterError, AppError, AppInfo, Deadline, IdentityMatch, PlatformAdapter, RefEntry, - WindowInfo, + SnapshotSurface, WindowInfo, adapter::{NativeHandle, TreeOptions}, locator::live_locator::{ObservationRequest, ObservationRoot, ObservedTree}, refs::ref_full_predicate::FullPredicate, @@ -90,7 +90,13 @@ pub(crate) fn observe_saved_ref( }; let mut request = whole_window_request(&base, deadline)?; request.observation_mode.identity_only = identity_only; - let observed = observe_window(adapter, &request, &window, lease)?; + let observed = observe_window( + adapter, + &request, + &window, + lease, + entry.source.source_window_id.is_some(), + )?; let index = saved_ref_node(entry, token, &observed)?; let node = observed .nodes @@ -230,7 +236,8 @@ fn belongs_to_entry(window: &WindowInfo, entry: &RefEntry) -> bool { /// uses: the whole window at the deepest limit a walk supports, so a capture /// proof and a later resolution count the same evidence. `base` supplies the /// surface and the renderer-accessibility hint; its depth and presentation -/// settings are ignored. +/// settings are ignored. `window` is the owner the capture resolved, so a +/// surface presented by that window is read at it. pub(crate) fn observe_whole_window( adapter: &dyn PlatformAdapter, base: &TreeOptions, @@ -242,6 +249,7 @@ pub(crate) fn observe_whole_window( &whole_window_request(base, deadline)?, window, None, + true, ) } @@ -264,6 +272,7 @@ fn observe_window( request: &ObservationRequest, window: &WindowInfo, lease: Option<&crate::InteractionLease>, + surface_window: bool, ) -> Result { let process_instance = window.process_instance.clone(); let app = AppInfo { @@ -274,14 +283,7 @@ fn observe_window( bundle_id: None, presentation: None, }; - let root = if adapter.is_application_surface(request.surface) { - ObservationRoot::Application { - app: &app, - surface: request.surface, - } - } else { - ObservationRoot::Window(window) - }; + let root = observation_root(adapter, request.surface, &app, window, surface_window); let mut observed = crate::tree::renderer_accessibility::observe_tree(adapter, root, request, lease) .map_err(AppError::into_adapter_error)?; @@ -295,6 +297,27 @@ fn observe_window( Ok(observed) } +/// The root one observation of `surface` starts at. `surface_window` says the +/// window is the one the surface is presented by - the id a ref recorded, or the +/// owner a capture resolved - so the read lands on that window instead of +/// re-resolving the surface from the process, which cannot name it while several +/// of that kind are open. Every other application-owned surface has no window of +/// its own and starts at the application root. +fn observation_root<'a>( + adapter: &dyn PlatformAdapter, + surface: SnapshotSurface, + app: &'a AppInfo, + window: &'a WindowInfo, + surface_window: bool, +) -> ObservationRoot<'a> { + let presented_by_window = surface_window && !window.is_process_owner(); + if adapter.is_application_surface(surface) && !presented_by_window { + ObservationRoot::Application { app, surface } + } else { + ObservationRoot::Window(window) + } +} + fn saved_ref_node( entry: &RefEntry, token: Option<&str>, From 69ddd78e4d60268647c071f805581cddd4ccf4c3 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Tue, 24 Nov 2026 22:31:43 -0800 Subject: [PATCH 22/26] fix(windows): record the read surface on a window-rooted observation A walk rooted at a window reported the window surface whatever surface it read, so a ref anchored from a menu observation resolved its path from the window root and landed on the wrong element (STALE_REF). The walk now takes the request surface, as the macOS and Linux observations already do. --- .../src/locator/live_locator/observed_tree.rs | 10 +++++++ .../windows/examples/uia_tree_dump/render.rs | 5 +++- crates/windows/src/tree/observe.rs | 1 + crates/windows/src/tree/walk/walker.rs | 5 ++-- crates/windows/src/tree/walk/walker_fake.rs | 26 ++++++++++++++----- crates/windows/src/tree/walk/walker_source.rs | 5 ++-- .../src/tree/walk/walker_source_tests.rs | 12 ++++++--- crates/windows/src/tree/walk/walker_tests.rs | 15 ++++++++++- 8 files changed, 64 insertions(+), 15 deletions(-) diff --git a/crates/core/src/locator/live_locator/observed_tree.rs b/crates/core/src/locator/live_locator/observed_tree.rs index 738a1d2e81..78301a86ed 100644 --- a/crates/core/src/locator/live_locator/observed_tree.rs +++ b/crates/core/src/locator/live_locator/observed_tree.rs @@ -43,6 +43,16 @@ impl ObservedTree { Ok(tree) } + /// The surface this observation read, which a ref anchored from it records + /// so a later resolution reads the same surface. + pub fn surface(&self) -> crate::SnapshotSurface { + match &self.source { + ObservationSource::Application { surface, .. } + | ObservationSource::Window { surface, .. } => *surface, + ObservationSource::Element { entry, .. } => entry.source.source_surface, + } + } + pub fn is_complete(&self) -> bool { self.structurally_complete } diff --git a/crates/windows/examples/uia_tree_dump/render.rs b/crates/windows/examples/uia_tree_dump/render.rs index 2068a47875..17e10a6bfc 100644 --- a/crates/windows/examples/uia_tree_dump/render.rs +++ b/crates/windows/examples/uia_tree_dump/render.rs @@ -1,4 +1,6 @@ -use agent_desktop_core::{Deadline, ObservationRoot, ProcessId, WindowInfo, WindowState}; +use agent_desktop_core::{ + Deadline, ObservationRoot, ProcessId, SnapshotSurface, WindowInfo, WindowState, +}; use agent_desktop_windows::tree::automation::failure_of; use agent_desktop_windows::tree::element::UIAElement; use agent_desktop_windows::tree::name_evidence::read_label; @@ -341,6 +343,7 @@ fn walk_verdict(root: &UIAElement, deadline: Deadline) -> Value { match walk_uia_subtree( root, &ObservationRoot::Window(&window), + SnapshotSurface::Window, WalkBudget::new(u8::MAX, deadline), false, ) { diff --git a/crates/windows/src/tree/observe.rs b/crates/windows/src/tree/observe.rs index f9ae12dd0c..8707812552 100644 --- a/crates/windows/src/tree/observe.rs +++ b/crates/windows/src/tree/observe.rs @@ -58,6 +58,7 @@ pub(crate) fn observe_tree( let outcome = walk_uia_subtree( &element, &root, + request.surface, budget, request.observation_mode.identity_only, )?; diff --git a/crates/windows/src/tree/walk/walker.rs b/crates/windows/src/tree/walk/walker.rs index 4b5735ae95..e274709b31 100644 --- a/crates/windows/src/tree/walk/walker.rs +++ b/crates/windows/src/tree/walk/walker.rs @@ -1,6 +1,6 @@ use agent_desktop_core::{ AdapterError, Deadline, ErrorCode, LocatorEvidence, LocatorField, LocatorStats, - ObservationRoot, ObservationSource, ObservedTree, + ObservationRoot, ObservationSource, ObservedTree, SnapshotSurface, }; use serde_json::json; @@ -137,6 +137,7 @@ pub fn walk_from_root( source: &S, root: &S::Node, root_source: &ObservationRoot<'_>, + surface: SnapshotSurface, budget: WalkBudget, ) -> Result { let mut walk = TreeWalk::new(source, budget); @@ -145,7 +146,7 @@ pub fn walk_from_root( let root_subtree = root_subtree.ok_or_else(|| root_missing_error(&stats))?; let tree = ObservedTree::from_roots( vec![root_subtree], - ObservationSource::from_root(root_source, root_source.surface()), + ObservationSource::from_root(root_source, surface), stats.clone(), structurally_complete, )?; diff --git a/crates/windows/src/tree/walk/walker_fake.rs b/crates/windows/src/tree/walk/walker_fake.rs index 81bc0092c1..3b6fd427d1 100644 --- a/crates/windows/src/tree/walk/walker_fake.rs +++ b/crates/windows/src/tree/walk/walker_fake.rs @@ -1,6 +1,6 @@ use agent_desktop_core::{ - AdapterError, Deadline, LocatorEvidence, ObservationRoot, ProcessId, RefEntry, WindowInfo, - WindowState, + AdapterError, Deadline, LocatorEvidence, ObservationRoot, ProcessId, RefEntry, SnapshotSurface, + WindowInfo, WindowState, }; use std::collections::{HashMap, HashSet}; @@ -233,8 +233,16 @@ pub(crate) fn window() -> WindowInfo { } pub(crate) fn walk(fake: &FakeTree, budget: WalkBudget) -> WalkOutcome { + walk_on_surface(fake, SnapshotSurface::Window, budget) +} + +pub(crate) fn walk_on_surface( + fake: &FakeTree, + surface: SnapshotSurface, + budget: WalkBudget, +) -> WalkOutcome { let window = window(); - walk_from_root(fake, &1, &ObservationRoot::Window(&window), budget) + walk_from_root(fake, &1, &ObservationRoot::Window(&window), surface, budget) .expect("the walk assembles an observation") } @@ -242,7 +250,13 @@ pub(crate) fn walk(fake: &FakeTree, budget: WalkBudget) -> WalkOutcome { /// error the caller receives can be asserted. pub(crate) fn walk_expecting_failure(fake: &FakeTree, budget: WalkBudget) -> AdapterError { let window = window(); - walk_from_root(fake, &1, &ObservationRoot::Window(&window), budget) - .err() - .expect("the walk was expected to fail") + walk_from_root( + fake, + &1, + &ObservationRoot::Window(&window), + SnapshotSurface::Window, + budget, + ) + .err() + .expect("the walk was expected to fail") } diff --git a/crates/windows/src/tree/walk/walker_source.rs b/crates/windows/src/tree/walk/walker_source.rs index b870bd34af..79a1db1fa3 100644 --- a/crates/windows/src/tree/walk/walker_source.rs +++ b/crates/windows/src/tree/walk/walker_source.rs @@ -1,4 +1,4 @@ -use agent_desktop_core::{AdapterError, ObservationRoot}; +use agent_desktop_core::{AdapterError, ObservationRoot, SnapshotSurface}; use super::walker::{WalkBudget, WalkOutcome, walk_from_root}; use crate::tree::element::UIAElement; @@ -375,12 +375,13 @@ pub(crate) use imp::{ pub fn walk_uia_subtree( root: &UIAElement, root_source: &ObservationRoot<'_>, + surface: SnapshotSurface, budget: WalkBudget, identity_only: bool, ) -> Result { let source = UiaTreeSource::for_root_reading(root, identity_only)?; let prepared = source.prepare_root(root)?; - walk_from_root(&source, &prepared, root_source, budget) + walk_from_root(&source, &prepared, root_source, surface, budget) } #[cfg(test)] diff --git a/crates/windows/src/tree/walk/walker_source_tests.rs b/crates/windows/src/tree/walk/walker_source_tests.rs index 7a9bcf9902..41242773df 100644 --- a/crates/windows/src/tree/walk/walker_source_tests.rs +++ b/crates/windows/src/tree/walk/walker_source_tests.rs @@ -82,7 +82,7 @@ mod non_windows_only { use super::super::*; use crate::tree::element::{CannedElement, UIAElement}; use crate::tree::walk::walker_fake::{budget, window}; - use agent_desktop_core::ObservationRoot; + use agent_desktop_core::{ObservationRoot, SnapshotSurface}; /// The canned arm exists so every module that calls the walk compiles and /// runs off Windows. It enumerates nothing, which is the exhaustion answer, @@ -92,8 +92,14 @@ mod non_windows_only { let window = window(); let root = UIAElement::from(CannedElement); - let outcome = walk_uia_subtree(&root, &ObservationRoot::Window(&window), budget(10), false) - .expect("the canned walk assembles an observation"); + let outcome = walk_uia_subtree( + &root, + &ObservationRoot::Window(&window), + SnapshotSurface::Window, + budget(10), + false, + ) + .expect("the canned walk assembles an observation"); assert!(outcome.tree.is_complete()); assert!(outcome.failures.is_empty()); diff --git a/crates/windows/src/tree/walk/walker_tests.rs b/crates/windows/src/tree/walk/walker_tests.rs index 753a3dc80c..eeef9ecffb 100644 --- a/crates/windows/src/tree/walk/walker_tests.rs +++ b/crates/windows/src/tree/walk/walker_tests.rs @@ -3,8 +3,9 @@ use crate::tree::automation::UiaFailure; use crate::tree::walk::walker_enumerate::TreeWalk; use crate::tree::walk::walker_fake::{ E_FAIL, EXHAUSTION, FakeTree, REAL_FAILURE, budget, walk, walk_expecting_failure, + walk_on_surface, }; -use agent_desktop_core::{Deadline, ErrorCode}; +use agent_desktop_core::{Deadline, ErrorCode, SnapshotSurface}; /// The fakes encode the measured pair, not a reading of the crate. If this /// fails, every other fake-driven assertion below is testing the wrong model. @@ -369,3 +370,15 @@ fn an_identity_walk_leaves_actions_and_states_unknown() { assert_eq!(identity.available_actions, LocatorField::Unknown); assert_eq!(identity.states, LocatorField::Unknown); } + +/// A window-rooted read of a surface the window presents names that surface, +/// so a ref anchored from this observation resolves in the surface it was +/// read from instead of at the window root. +#[test] +fn a_window_rooted_walk_of_a_surface_records_that_surface() { + let fake = FakeTree::default().with_chain(&[1, 2]); + + let outcome = walk_on_surface(&fake, SnapshotSurface::Menu, budget(10)); + + assert_eq!(outcome.tree.surface(), SnapshotSurface::Menu); +} From f0bfdfb8b61f390e0d82b4f519627ee8162a8bee Mon Sep 17 00:00:00 2001 From: Lahfir Date: Tue, 24 Nov 2026 22:32:44 -0800 Subject: [PATCH 23/26] fix(linux): locate the shell message list by structure alone Locating the notification list read name, extents and state of every shell node, 7 bus calls each, and a 2000-node tree outlasted the 5 s budget. The search needs only role and children, so it reads those two and re-reads the found list in full. A budget spent on the shell tree now reports how many nodes were read instead of blaming a busy application. --- crates/linux/src/notifications/world.rs | 4 +- crates/linux/src/system/shell/container.rs | 25 +++++- .../linux/src/system/shell/container_tests.rs | 38 +++++++++ crates/linux/src/system/shell/hit.rs | 4 +- crates/linux/src/system/shell/light.rs | 77 ++++++++++++++++--- crates/linux/src/system/shell/search.rs | 24 +++++- crates/linux/src/system/shell/search_tests.rs | 31 ++++++-- 7 files changed, 175 insertions(+), 28 deletions(-) diff --git a/crates/linux/src/notifications/world.rs b/crates/linux/src/notifications/world.rs index aebcbaa089..073c969ebf 100644 --- a/crates/linux/src/notifications/world.rs +++ b/crates/linux/src/notifications/world.rs @@ -8,7 +8,7 @@ use crate::system::shell::anchor::Anchor; use crate::system::shell::container::{Landmark, locate_anchor}; use crate::system::shell::identity::find_root; use crate::system::shell::kinds::ShellKind; -use crate::system::shell::light::LiveNodes; +use crate::system::shell::light::{Detail, LiveNodes}; use crate::system::shell::open::{Opened, close, is_showing, open}; use crate::system::shell::search::{Walk, walk}; use crate::tree::AtspiElement; @@ -57,7 +57,7 @@ impl ShellWorld for LiveWorld<'_> { fn read(&self, root: &AtspiElement, deadline: Deadline) -> Result { let nodes = LiveNodes::new(self.bus.get(deadline)?.inner().clone(), deadline); - walk(&nodes, root, deadline, &|_| false) + walk(&nodes, root, deadline, Detail::Full, &|_| false) } fn open( diff --git a/crates/linux/src/system/shell/container.rs b/crates/linux/src/system/shell/container.rs index 06c4914da4..fb40bd6a5c 100644 --- a/crates/linux/src/system/shell/container.rs +++ b/crates/linux/src/system/shell/container.rs @@ -5,7 +5,7 @@ use serde_json::json; use super::anchor::Anchor; use super::identity::ShellRoot; -use super::light::{Light, LiveNodes, Nodes}; +use super::light::{Detail, Light, LiveNodes, Nodes}; use super::located::Located; use super::search::{Visit, walk}; use crate::system::SharedBus; @@ -59,15 +59,17 @@ fn locate_in( }); } Anchor::Landmark(Landmark::MessageList) => { - let walked = walk(nodes, &start, deadline, &|_| false)?; + let walked = walk(nodes, &start, deadline, Detail::Structure, &|_| false)?; ( - lists(&walked.visits), + read_in_full(nodes, lists(&walked.visits))?, walked.complete, "Several shell containers have the requested role chain", ) } Anchor::Landmark(Landmark::DateMenu) => { - let walked = walk(nodes, &start, deadline, &|light| !light.showing)?; + let walked = walk(nodes, &start, deadline, Detail::Full, &|light| { + !light.showing + })?; ( date_menus(&walked.visits), walked.complete, @@ -118,6 +120,21 @@ fn lists(visits: &[Visit]) -> Vec { .collect() } +/// A structure read leaves a node's name, extents and state empty, so the +/// containers a rule named are read again in full before they are reported. +/// A container that left the tree between the two reads is a lost node. +fn read_in_full(nodes: &N, found: Vec) -> Result, AdapterError> { + found + .iter() + .map(|light| match nodes.read(&light.element) { + Err(error) if error.code == ErrorCode::ElementNotFound => { + Err(lost_a_node(Anchor::Landmark(Landmark::MessageList))) + } + other => other, + }) + .collect() +} + /// The date menu is the one showing menu in the shell with no accessible /// name; every other top bar menu names its indicator. fn date_menus(visits: &[Visit]) -> Vec { diff --git a/crates/linux/src/system/shell/container_tests.rs b/crates/linux/src/system/shell/container_tests.rs index 8599c49ceb..7d9bbe3008 100644 --- a/crates/linux/src/system/shell/container_tests.rs +++ b/crates/linux/src/system/shell/container_tests.rs @@ -186,3 +186,41 @@ fn an_unproven_native_tray_uses_only_the_logical_shell_root() { assert_eq!(located.container.element.path(), "/w"); assert_eq!(located.container.role, WINDOW); } + +struct Counting<'a> { + tree: &'a FakeTree, + structure_reads: Cell, + full_reads: std::cell::RefCell>, +} + +impl Nodes for Counting<'_> { + fn read(&self, node: &AtspiElement) -> Result { + self.full_reads.borrow_mut().push(node.path().to_owned()); + self.tree.read(node) + } + + fn read_structure(&self, node: &AtspiElement) -> Result { + self.structure_reads.set(self.structure_reads.get() + 1); + self.tree.read(node) + } +} + +#[test] +fn locating_the_message_list_reads_structure_and_reads_only_the_list_in_full() { + let tree = gnome_shell(true, false); + let nodes = Counting { + tree: &tree, + structure_reads: Cell::new(0), + full_reads: Default::default(), + }; + let located = locate_in( + &nodes, + &FakeTree::root(), + Anchor::Landmark(Landmark::MessageList), + Deadline::after(5_000).unwrap(), + ) + .expect("the footer row proves the list"); + assert_eq!(located.container.element.path(), "/list"); + assert!(nodes.structure_reads.get() > 1); + assert_eq!(*nodes.full_reads.borrow(), vec!["/list".to_owned()]); +} diff --git a/crates/linux/src/system/shell/hit.rs b/crates/linux/src/system/shell/hit.rs index c79c7b7a3b..cd468deca8 100644 --- a/crates/linux/src/system/shell/hit.rs +++ b/crates/linux/src/system/shell/hit.rs @@ -3,7 +3,7 @@ use std::time::Duration; use agent_desktop_core::{AdapterError, Deadline, ErrorCode, HitTestResult, Point}; use super::identity::find_root; -use super::light::{LiveNodes, Nodes}; +use super::light::{Detail, LiveNodes, Nodes}; use super::search::walk; use crate::system::{SharedBus, list_displays}; use crate::tree::{AtspiElement, Extents}; @@ -46,7 +46,7 @@ pub(super) fn verdict( Err(error) => return Err(error), }; pause(MOTION_GAP); - let tree = walk(nodes, root, deadline, &|light| !light.showing)?; + let tree = walk(nodes, root, deadline, Detail::Full, &|light| !light.showing)?; if !tree.complete { return Ok(HitTestResult::Unknown); } diff --git a/crates/linux/src/system/shell/light.rs b/crates/linux/src/system/shell/light.rs index 8436d3719c..f18accda15 100644 --- a/crates/linux/src/system/shell/light.rs +++ b/crates/linux/src/system/shell/light.rs @@ -1,6 +1,6 @@ use crate::tree::placement::visibility::is_placed; use agent_desktop_core::{AdapterError, Deadline, ErrorCode}; -use futures_util::future::{join_all, join5}; +use futures_util::future::{join, join_all, join5}; use zbus::Connection; use zbus::zvariant::OwnedValue; @@ -36,12 +36,35 @@ pub(crate) fn same_object(left: &AtspiElement, right: &AtspiElement) -> bool { left.bus_name() == right.bus_name() && left.path() == right.path() } +/// How much of each node a walk reads. A structure read asks only for the +/// role and the children, two bus calls per node; every other field of the +/// `Light` it returns is left empty and must not be consulted. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Detail { + Structure, + Full, +} + /// Reads shell nodes. The bus implements it; a test substitutes a tree. pub(crate) trait Nodes { fn read(&self, element: &AtspiElement) -> Result; - fn read_level(&self, elements: &[AtspiElement]) -> Vec> { - elements.iter().map(|element| self.read(element)).collect() + fn read_structure(&self, element: &AtspiElement) -> Result { + self.read(element) + } + + fn read_level( + &self, + elements: &[AtspiElement], + detail: Detail, + ) -> Vec> { + elements + .iter() + .map(|element| match detail { + Detail::Structure => self.read_structure(element), + Detail::Full => self.read(element), + }) + .collect() } } @@ -185,6 +208,33 @@ async fn read_one(connection: &Connection, element: &AtspiElement) -> Result Result { + let (children, role) = join( + list_children(connection, element), + role_of(connection, element), + ) + .await; + let children = children.map_err(missing_when_dead)?; + let role = role?.ok_or_else(|| { + AdapterError::new(ErrorCode::ElementNotFound, "The shell node did not answer") + })?; + Ok(Light { + element: element.address(), + role, + name: String::new(), + extents: None, + showing: false, + visible: false, + children: children + .into_iter() + .map(|(bus, path)| AtspiElement::new(bus, path, element.pid())) + .collect(), + }) +} + pub(crate) struct LiveNodes { connection: Connection, deadline: Deadline, @@ -204,15 +254,24 @@ impl Nodes for LiveNodes { within(self.deadline, read_one(&self.connection, element)) } - fn read_level(&self, elements: &[AtspiElement]) -> Vec> { + fn read_structure(&self, element: &AtspiElement) -> Result { + within(self.deadline, read_structure_one(&self.connection, element)) + } + + fn read_level( + &self, + elements: &[AtspiElement], + detail: Detail, + ) -> Vec> { let mut reads = Vec::with_capacity(elements.len()); for chunk in elements.chunks(LEVEL_IN_FLIGHT) { let chunk_reads = within(self.deadline, async { - Ok(join_all( - chunk - .iter() - .map(|element| read_one(&self.connection, element)), - ) + Ok(join_all(chunk.iter().map(|element| async move { + match detail { + Detail::Structure => read_structure_one(&self.connection, element).await, + Detail::Full => read_one(&self.connection, element).await, + } + })) .await) }); match chunk_reads { diff --git a/crates/linux/src/system/shell/search.rs b/crates/linux/src/system/shell/search.rs index 42b1f8788e..b55f4eb25e 100644 --- a/crates/linux/src/system/shell/search.rs +++ b/crates/linux/src/system/shell/search.rs @@ -1,6 +1,8 @@ use agent_desktop_core::{AdapterError, Deadline, ErrorCode}; -use super::light::{Light, Nodes, same_object}; +use serde_json::json; + +use super::light::{Detail, Light, Nodes, same_object}; use crate::tree::AtspiElement; const MAX_NODES: usize = 8_000; @@ -52,6 +54,7 @@ pub(crate) fn walk( nodes: &N, root: &AtspiElement, deadline: Deadline, + detail: Detail, prune: &dyn Fn(&Light) -> bool, ) -> Result { let mut arena: Vec = Vec::new(); @@ -59,13 +62,13 @@ pub(crate) fn walk( let mut frontier: Vec<(AtspiElement, Option)> = vec![(root.clone(), None)]; while !frontier.is_empty() { if deadline.is_expired() { - return Err(deadline.timeout_error()); + return Err(unread(arena.len())); } let elements: Vec = frontier .iter() .map(|(element, _)| element.clone()) .collect(); - let reads = nodes.read_level(&elements); + let reads = nodes.read_level(&elements, detail); let mut next = Vec::new(); for ((_, parent), read) in frontier.drain(..).zip(reads) { let light = match read { @@ -74,6 +77,9 @@ pub(crate) fn walk( complete = false; continue; } + Err(error) if error.code == ErrorCode::Timeout => { + return Err(unread(arena.len())); + } Err(error) => return Err(error), }; if prune(&light) { @@ -108,6 +114,18 @@ pub(crate) fn walk( }) } +/// The budget ended before the shell tree was read. The shell answers its +/// accessibility calls one at a time, so a large tree can outlast the budget +/// while the shell itself is healthy; the error says which tree and how far +/// the read got instead of blaming a busy application. +fn unread(nodes_read: usize) -> AdapterError { + AdapterError::timeout(format!( + "The desktop shell tree was not read within the time limit ({nodes_read} nodes read)" + )) + .with_suggestion("Retry the command; the shell answers its accessibility calls one at a time") + .with_details(json!({ "kind": "shell_tree_unread", "nodes_read": nodes_read })) +} + fn in_paint_order(arena: Vec) -> Vec { let mut order = Vec::with_capacity(arena.len()); let mut stack = if arena.is_empty() { vec![] } else { vec![0] }; diff --git a/crates/linux/src/system/shell/search_tests.rs b/crates/linux/src/system/shell/search_tests.rs index 68293a0742..5a7eb491c8 100644 --- a/crates/linux/src/system/shell/search_tests.rs +++ b/crates/linux/src/system/shell/search_tests.rs @@ -1,6 +1,7 @@ use agent_desktop_core::{Deadline, ErrorCode}; use crate::system::shell::fake_tree::{FakeTree, PANEL, WINDOW, at, element, gnome_shell}; +use crate::system::shell::light::Detail; use crate::system::shell::search::walk; fn deadline() -> Deadline { @@ -20,7 +21,10 @@ fn small() -> FakeTree { #[test] fn nodes_come_in_paint_order_and_know_their_parents() { - let walked = walk(&small(), &element("/w"), deadline(), &|_| false).expect("a walk"); + let walked = walk(&small(), &element("/w"), deadline(), Detail::Full, &|_| { + false + }) + .expect("a walk"); let paths: Vec<&str> = walked .visits .iter() @@ -35,7 +39,10 @@ fn nodes_come_in_paint_order_and_know_their_parents() { #[test] fn within_follows_the_parents_and_position_finds_an_element() { - let walked = walk(&small(), &element("/w"), deadline(), &|_| false).expect("a walk"); + let walked = walk(&small(), &element("/w"), deadline(), Detail::Full, &|_| { + false + }) + .expect("a walk"); assert!(walked.within(3, 1)); assert!(walked.within(3, 3)); assert!(!walked.within(3, 4)); @@ -45,9 +52,13 @@ fn within_follows_the_parents_and_position_finds_an_element() { #[test] fn a_pruned_node_is_neither_listed_nor_entered() { - let walked = walk(&small(), &element("/w"), deadline(), &|light| { - light.element.path() == "/a" - }) + let walked = walk( + &small(), + &element("/w"), + deadline(), + Detail::Full, + &|light| light.element.path() == "/a", + ) .expect("a walk"); let paths: Vec<&str> = walked .visits @@ -61,7 +72,7 @@ fn a_pruned_node_is_neither_listed_nor_entered() { fn a_node_that_vanishes_during_the_walk_is_skipped_and_the_walk_says_so() { let mut tree = gnome_shell(true, false); tree.vanish("/left"); - let walked = walk(&tree, &element("/w"), deadline(), &|_| false).expect("a walk"); + let walked = walk(&tree, &element("/w"), deadline(), Detail::Full, &|_| false).expect("a walk"); assert!(!walked.complete); assert!(walked.position(&element("/system")).is_some()); assert!(walked.position(&element("/left")).is_none()); @@ -71,8 +82,11 @@ fn a_node_that_vanishes_during_the_walk_is_skipped_and_the_walk_says_so() { fn an_expired_deadline_is_a_timeout_not_an_empty_walk() { let expired = Deadline::after(1).expect("a deadline builds"); std::thread::sleep(std::time::Duration::from_millis(5)); - let error = walk(&small(), &element("/w"), expired, &|_| false).expect_err("no time"); + let error = + walk(&small(), &element("/w"), expired, Detail::Full, &|_| false).expect_err("no time"); assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.details.unwrap()["kind"], "shell_tree_unread"); + assert!(!error.suggestion.unwrap().contains("busy")); } #[test] @@ -88,6 +102,7 @@ fn a_walk_over_the_budget_is_an_error_and_never_a_shorter_tree() { at(0, 0, 0, 0), ); } - let error = walk(&tree, &element("/w"), deadline(), &|_| false).expect_err("over budget"); + let error = + walk(&tree, &element("/w"), deadline(), Detail::Full, &|_| false).expect_err("over budget"); assert_eq!(error.code, ErrorCode::Timeout); } From d7f9f7b99e00274a59e3d8e9a575c767d314e66b Mon Sep 17 00:00:00 2001 From: Lahfir Date: Tue, 24 Nov 2026 22:39:32 -0800 Subject: [PATCH 24/26] fix(macos): read a sheet control's window from its ancestors An element drawn in a sheet answers no AXWindow, so its clipping viewport was unknown, the visible check stayed unknown and every action on a Save panel control timed out as not actionable. The parent walk already reaches the owning AXWindow, so it now supplies the window when the attribute does not. --- crates/macos/src/tree/element_bounds.rs | 41 ++++++++++++++++++++----- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/crates/macos/src/tree/element_bounds.rs b/crates/macos/src/tree/element_bounds.rs index b6e67af589..7f48eb8fae 100644 --- a/crates/macos/src/tree/element_bounds.rs +++ b/crates/macos/src/tree/element_bounds.rs @@ -111,14 +111,22 @@ fn within(surface: Option, clips: &[Option]) -> Option { .fold(surface, |viewport, bounds| narrowed(viewport, *bounds)) } +/// The viewport inside an `AXWindow` ancestor. The element's own `AXWindow` +/// attribute names that window when it answers; an element drawn in a sheet has +/// no such value, so the ancestor the parent walk reached is the owning window. +fn window_viewport( + attribute_window: Option, + ancestor_window: Option, + clips: &[Option], +) -> Option { + within(attribute_window.or(ancestor_window), clips) +} + pub(crate) fn ancestor_viewport( element: &AXElement, deadline: Deadline, ) -> Result, AdapterError> { let window = owning_window_bounds(element, deadline)?; - if window.is_none() { - return Ok(None); - } let instant = deadline; let mut clips = Vec::new(); let mut current = super::surface_read::element(element, "AXParent", instant)?; @@ -141,11 +149,15 @@ pub(crate) fn ancestor_viewport( let surface = read_bounds_with_deadline(&parent, instant)?; return Ok(within(surface, &clips)); } - if clips_descendants(&role) { - clips.push(read_bounds_with_deadline(&parent, instant)?); - } + let own_bounds = if clips_descendants(&role) { + let bounds = read_bounds_with_deadline(&parent, instant)?; + clips.push(bounds); + bounds + } else { + None + }; if role == "AXWindow" { - return Ok(within(window, &clips)); + return Ok(window_viewport(window, own_bounds, &clips)); } current = super::surface_read::element(&parent, "AXParent", instant)?; } @@ -287,6 +299,21 @@ mod tests { assert_eq!(within(popover, &[None]), None); } + #[test] + fn an_element_with_no_window_attribute_is_clipped_by_its_window_ancestor() { + let window = Some(rect(100.0, 600.0)); + let sheet = Some(rect(50.0, 800.0)); + assert_eq!(window_viewport(None, window, &[sheet, window]), window); + assert_eq!(window_viewport(None, None, &[sheet]), None); + } + + #[test] + fn the_window_attribute_wins_over_the_ancestor_window() { + let attributed = Some(rect(100.0, 600.0)); + let ancestor = Some(rect(0.0, 50.0)); + assert_eq!(window_viewport(attributed, ancestor, &[]), attributed); + } + #[test] fn missing_clipping_geometry_is_unknown_not_empty() { assert_eq!( From 8dfe927b129f774b20f822a9cdf6ede327ccc113 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Tue, 24 Nov 2026 22:49:39 -0800 Subject: [PATCH 25/26] docs: state what reaches a background app and the limits the dogfood found Document scoped headless press per platform and its refusal, the trace path rule, the PowerShell 5.1 batch form, launch --arg/--env/--cwd, GTK4 list rows, waiting for a window of unknown title, saving into a chosen folder, the trailing newline of --stdin, and the Wayland close-app code. The trace refusal now names the folder as well as the file. --- .../docs/content/docs/commands/app-window.mdx | 2 +- apps/docs/content/docs/commands/batch.mdx | 9 ++++++ .../content/docs/commands/interaction.mdx | 2 ++ apps/docs/content/docs/commands/wait.mdx | 2 +- apps/docs/content/docs/guides/traces.mdx | 2 +- apps/docs/content/docs/platforms/linux.mdx | 4 +-- apps/docs/content/docs/platforms/macos.mdx | 5 +-- apps/docs/content/docs/platforms/windows.mdx | 2 +- crates/core/src/trace/trace_file.rs | 4 +-- skills/agent-desktop-linux/SKILL.md | 32 +++++++++---------- skills/agent-desktop-macos/SKILL.md | 5 +-- skills/agent-desktop-windows/SKILL.md | 10 ++++-- skills/agent-desktop/SKILL.md | 16 +++++----- 13 files changed, 55 insertions(+), 40 deletions(-) diff --git a/apps/docs/content/docs/commands/app-window.mdx b/apps/docs/content/docs/commands/app-window.mdx index 4a5eb6b1d7..46bee1ab43 100644 --- a/apps/docs/content/docs/commands/app-window.mdx +++ b/apps/docs/content/docs/commands/app-window.mdx @@ -138,7 +138,7 @@ agent-desktop close-app [--force] - `APP_NOT_FOUND` when no running app matches, `AMBIGUOUS_TARGET` when several instances share the name. - `INVALID_ARGS` for a protected system process, with or without `--force`. - A save prompt keeps the app open. Read it with `snapshot --surface sheet`, answer it, then close again. -- On Linux a headless graceful close runs. Where the focused window cannot be read (a Wayland session, or a focused window whose owner cannot be identified), it fails with `POLICY_DENIED` (`details.kind: focus_unreadable`) before any close request is sent. Report it to the user, or use `--force` (it discards unsaved work). If the app answers with a save prompt, the command fails with `ACTION_FAILED` (`details.cause: dialog_pending`), the app stays open, and the focus goes back to the window that had it (`details.focus_returned: true`). With `--headed` the focus is left where the prompt put it. Answer the prompt, or use `--force` (it discards unsaved work). +- On Linux a headless graceful close runs. On a native Wayland client it returns `ACTION_NOT_SUPPORTED` (`details.cause: wayland_session`), because the compositor has no close request for another client's window. Where the focused window cannot be read, it fails with `POLICY_DENIED` (`details.kind: focus_unreadable`) before any close request is sent. Report it to the user, or use `--force` (it discards unsaved work). If the app answers with a save prompt, the command fails with `ACTION_FAILED` (`details.cause: dialog_pending`), the app stays open, and the focus goes back to the window that had it (`details.focus_returned: true`). With `--headed` the focus is left where the prompt put it. Answer the prompt, or use `--force` (it discards unsaved work). On macOS a headless graceful close sends the quit request, and a save prompt opens in the app's own window behind the window in front. On Windows the close is posted to the app's windows, and if a window of the app takes the foreground, as a save prompt can, the command gives the foreground back to the window that had it. Linux checks focus first, as described above. diff --git a/apps/docs/content/docs/commands/batch.mdx b/apps/docs/content/docs/commands/batch.mdx index a40ba4df03..a84b96c15f 100644 --- a/apps/docs/content/docs/commands/batch.mdx +++ b/apps/docs/content/docs/commands/batch.mdx @@ -24,6 +24,15 @@ agent-desktop batch '[{"command":"version"},{"command":"wait","args":{"ms":100}} +In Windows PowerShell 5.1 the double quotes inside the JSON argument are dropped, and `batch` fails with `INVALID_ARGS` ("key must be a string"). Escape each quote with a backslash. `batch` has no stdin or file input. + +```powershell +$json = @' +[{"command":"version"},{"command":"wait","args":{"ms":100}}] +'@ +agent-desktop batch ($json -replace '"','\"') --stop-on-error +``` + ### Entry format diff --git a/apps/docs/content/docs/commands/interaction.mdx b/apps/docs/content/docs/commands/interaction.mdx index 16a0f1d298..133e844ea5 100644 --- a/apps/docs/content/docs/commands/interaction.mdx +++ b/apps/docs/content/docs/commands/interaction.mdx @@ -178,6 +178,8 @@ printf '%s' 'hello' | agent-desktop type @s8f3k2p9:e2 --stdin The action timeout starts after the input ends; it doesn't limit this wait. Empty input and all line breaks are kept, including a final newline. Use `printf '%s'` to avoid adding one. Input must be valid UTF-8 without NUL bytes (`\0`). The limits are 10,000 bytes for `type` and 128 KiB for `set-value`. +`--stdin` uses the bytes it receives, so a trailing newline becomes part of the text. `printf '%s'` sends none. PowerShell adds a line ending to a piped string; to send exact text on Windows, redirect a file in `cmd`: `cmd /c "agent-desktop set-value @s8f3k2p9:e2 --stdin < text.txt"`. + Provide either `--stdin` or a command-line value. To enter the text `--stdin`, put it after `--`: `agent-desktop type @s8f3k2p9:e2 -- --stdin`. Batch uses the JSON `text` or `value` field, which puts the text in process arguments. Run secret steps as separate `--stdin` commands. `--stdin` keeps text out of process arguments and omits observed `value` fields from JSON results, including `post_state.value`. Other app text and screenshot artifacts aren't redacted. diff --git a/apps/docs/content/docs/commands/wait.mdx b/apps/docs/content/docs/commands/wait.mdx index fa27561d87..88a87adcbe 100644 --- a/apps/docs/content/docs/commands/wait.mdx +++ b/apps/docs/content/docs/commands/wait.mdx @@ -76,7 +76,7 @@ agent-desktop wait --element @s2txcl95uvubmn:e6 --predicate value --value 7 --ti ### Window -`--window TITLE` waits for any window whose title contains `TITLE`, focused or not. +`--window TITLE` waits for any window whose title contains `TITLE`, focused or not. When you do not know the title, wait for the event instead: `wait --event window-opened --app NAME`, in the same [batch](/desktop/commands/batch) as the action that opens the window. `--app` alone is not a wait mode. ```bash agent-desktop wait --window Calculator --app gnome-calculator --timeout 3000 diff --git a/apps/docs/content/docs/guides/traces.mdx b/apps/docs/content/docs/guides/traces.mdx index 1bdb87f037..7b135fab4d 100644 --- a/apps/docs/content/docs/guides/traces.mdx +++ b/apps/docs/content/docs/guides/traces.mdx @@ -74,7 +74,7 @@ agent-desktop --trace /tmp/run.jsonl find --app gnome-calculator --role button - jq -c 'select(.event == "command.end")' /tmp/run.jsonl ``` -The file is created private. While `--trace` is set, the session's trace directory receives nothing. A trace write failure does not fail the command unless you add `--trace-strict`. +The file must be private: a regular file you own with one link. On Windows its folder must also exist and be private (only you, SYSTEM and Administrators); a folder that grants `Users` write is refused with `INVALID_ARGS`, so use a new folder under your profile. The file is created private. While `--trace` is set, the session's trace directory receives nothing. A trace write failure does not fail the command unless you add `--trace-strict`. ## Capture screenshots with a session diff --git a/apps/docs/content/docs/platforms/linux.mdx b/apps/docs/content/docs/platforms/linux.mdx index cbcde22e10..61c2a465c1 100644 --- a/apps/docs/content/docs/platforms/linux.mdx +++ b/apps/docs/content/docs/platforms/linux.mdx @@ -69,7 +69,7 @@ Ref actions are semantic AT-SPI calls that never move the pointer or change the - + @@ -91,7 +91,7 @@ Ref actions are semantic AT-SPI calls that never move the pointer or change the ## Surfaces -`supported_surfaces` lists `window`, `sheet`, `alert`, and `menu`, plus GNOME Shell kinds the session can resolve. After an opener, read `data.surfaces`. A GTK popover appears asynchronously, so if it is absent, run `wait --menu` before you assume the opener failed. A list-backed GTK4 dropdown is part of the window tree, not a menu surface. See [Surfaces](/desktop/surfaces). +`supported_surfaces` lists `window`, `sheet`, `alert`, and `menu`, plus GNOME Shell kinds the session can resolve. After an opener, read `data.surfaces`. A GTK popover appears asynchronously, so if it is absent, run `wait --menu` before you assume the opener failed. A list-backed GTK4 dropdown is part of the window tree, not a menu surface. A GTK4 list or grid view exposes its items without row nodes, so `select` and `click` cannot pick a row. See [Surfaces](/desktop/surfaces). ## Chromium, Qt, and Electron diff --git a/apps/docs/content/docs/platforms/macos.mdx b/apps/docs/content/docs/platforms/macos.mdx index c969d93f1f..85dda953d4 100644 --- a/apps/docs/content/docs/platforms/macos.mdx +++ b/apps/docs/content/docs/platforms/macos.mdx @@ -51,7 +51,7 @@ A text field that shows a file's name, such as a Finder name cell, does not rena - + @@ -75,7 +75,8 @@ Judge delivery by observation. AX return codes do not prove an effect: an app ca - The primary modifier is `cmd`: `press cmd+c --app "TextEdit"`. Punctuation keys work as the symbol or by name (`comma`, `period`, `slash`). - `cmd+q`, `cmd+shift+q`, `cmd+alt+esc`, `ctrl+cmd+q`, and `cmd+shift+delete` return `POLICY_DENIED` unless you pass `--force`. To quit an app, use `close-app`. -- `press cmd+s --app "TextEdit"` sends keys to one app without focusing it. +- `press cmd+s --app "TextEdit"` posts the keys to that process without focusing it, when the app has a focused element. The result is `delivered_unverified`, which does not prove the shortcut did anything: check for the Save sheet with `list-surfaces`. +- A Save panel's name field takes a file name, never a path, and macOS shows a `/` typed there as `:`. Choose the folder with the panel's Where pop-up, which opens a menu and so needs `--headed`. Confirm the file on disk afterwards. - When agent-desktop opens Notification Center, it closes it afterward and restores the previous focus. Pass `--expected-app` and `--expected-title` on a single dismiss or action, because the stack shifts. Use `wait --notification --app "App"` for banners that vanish before you can list them. ## Chromium and Electron diff --git a/apps/docs/content/docs/platforms/windows.mdx b/apps/docs/content/docs/platforms/windows.mdx index 689726ee3b..61516de4fd 100644 --- a/apps/docs/content/docs/platforms/windows.mdx +++ b/apps/docs/content/docs/platforms/windows.mdx @@ -72,7 +72,7 @@ Use `$env:NAME = 'value'` instead of `export`, and `| ConvertFrom-Json` instead - `cmd` and `meta` are the Windows key, so `meta+c` is a shell shortcut. Write `ctrl+c` to copy. - `alt+f4`, `win+l`, `win+d`, `alt+tab`, `win+r`, `win+x`, `win+e`, `ctrl+shift+esc`, and their supersets are refused without `--force`. `ctrl+alt+delete` cannot be synthesized at all. - `type` is keystroke synthesis and needs `--headed`; use `set-value` headless. -- `press --app` writes to the foreground input queue and cannot target one background process. +- `press --app` writes to the foreground input queue and cannot target one background process. Headless, it works only when the target process owns the foreground window. Otherwise it returns `ACTION_FAILED` ("Windows SendInput cannot deliver to a background process", `details.check: process_focus`) with `not_delivered`, and sends nothing. ## Chromium and Electron diff --git a/crates/core/src/trace/trace_file.rs b/crates/core/src/trace/trace_file.rs index 253f3fc2d0..c70f98619a 100644 --- a/crates/core/src/trace/trace_file.rs +++ b/crates/core/src/trace/trace_file.rs @@ -61,8 +61,8 @@ pub(crate) fn open_trace_file(path: &Path) -> Result { crate::storage::private_file::open_private_append(path).map_err(|error| { if error.kind() == std::io::ErrorKind::PermissionDenied { return AppError::invalid_input_with_suggestion( - "Trace path must be a private user-owned regular file with one link", - "Use a new --trace path or replace the existing unsafe file.", + "Trace path must be a private user-owned regular file with one link, and on Windows its folder must be private too", + "Use a new --trace path in a folder only you can write, or replace the existing unsafe file.", ); } AppError::from(error) diff --git a/skills/agent-desktop-linux/SKILL.md b/skills/agent-desktop-linux/SKILL.md index 31abee5557..04f7e42e59 100644 --- a/skills/agent-desktop-linux/SKILL.md +++ b/skills/agent-desktop-linux/SKILL.md @@ -53,25 +53,23 @@ use a private session and runtime directory for isolated work. - Popup and dialog openers can take the foreground and refuse headless. Qt combo selection may need pointer input to commit rather than highlight a row. Stop on a headed-only refusal instead of changing mode. -- A headless graceful `close-app` reads which window has the focus first. When it cannot (a Wayland session, or an owner it cannot identify), it fails with `POLICY_DENIED` (`details.kind: focus_unreadable`) before any close request is sent. Report it to the user, or use `--force`, which discards unsaved work. -- A window can precede its content. Wait for the application's observable - result; an accepted AT-SPI call or a changed selected value is not proof that - dependent handlers ran. Wait for each effect before another click. +- A headless graceful `close-app` of a native Wayland client returns `ACTION_NOT_SUPPORTED` (`details.cause: wayland_session`). `--force` discards unsaved work. + When it cannot read the focused window it fails with `POLICY_DENIED` (`details.kind: focus_unreadable`) before any close request is sent. +- `press --app` works headless only when the target's window is active. Otherwise it sends nothing and returns `ACTION_FAILED` + (`details.check: window_active`), or `STALE_REF` when `--window-id` names a window not confirmed active. +- A GTK4 list or grid view has no row nodes, so `select` and `click` cannot pick a row. +- A window can precede its content. Wait for the application's observable result; an accepted AT-SPI call or a changed + selected value does not prove that handlers ran. Wait for each effect before another click. - Wayland refuses headed pointer input; window operations can use a mapped Xwayland client, but native Wayland windows lack that route. -- Authorized physical `type` sends a newline as `Return` on X11 too. It refuses a tab and other control characters. -- Authorized physical `type` on Wayland sends a newline as `Return` and a tab as - `Tab`, which can submit a form or move focus instead of inserting literal text. -- Wayland per-window screenshots are unsupported; display capture uses a portal - that can ask for consent. Ask the user before initiating a visible consent flow, - and do not retry a pending portal request in a loop. -- X11 capture depends on compositing: a covered noncomposited window may have - no readable pixels, and a composited desktop may not support whole-screen capture. - Neither failure authorizes focusing the target. -- Shell notifications require the supported GNOME service; tray reads require a - StatusNotifierWatcher. A missing service is an error, not an empty list. -- Password-role values are withheld, but a field that merely masks its text can - still be readable. Treat observation output as sensitive. +- Authorized physical `type` sends a newline as `Return` on X11 too and refuses a tab and other control characters. + On Wayland it sends a newline as `Return` and a tab as `Tab`, which can submit a form or move focus instead of inserting literal text. +- Wayland per-window screenshots are unsupported; display capture uses a portal that can ask for consent. + Ask the user before a visible consent flow, and do not retry a pending request in a loop. +- X11 capture depends on compositing: a covered noncomposited window may have no readable pixels, and a + composited desktop may not support whole-screen capture. Neither failure authorizes focusing the target. +- Shell notifications need the supported GNOME service; tray reads need a StatusNotifierWatcher. A missing service is an error. +- Password-role values are withheld, but a field that only masks its text can be readable. Treat observation output as sensitive. - `launch` accepts a program on PATH, an absolute path, an installed desktop id, or an unambiguous desktop entry name. Use process and window identity from observations rather than guessing from a window title. Without `--activate`, diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.md index f0d9b298da..2d3d60036d 100644 --- a/skills/agent-desktop-macos/SKILL.md +++ b/skills/agent-desktop-macos/SKILL.md @@ -42,6 +42,8 @@ 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. +- `press --app` headless: `return` and `escape` run as accessibility actions on the focused element. Any other key needs a focused element in the + app (`ACTION_FAILED`, `details.check: process_focus`, `not_delivered` otherwise). A modifier shortcut never runs a menu item: `click` the item. - `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; with `--window-id ` it closes the surface that window or the app shows. A @@ -78,8 +80,7 @@ may report `unknown` when consent would require a prompt. 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. +- AX success alone does not prove an application effect. Verify the result independently, especially after a menu action or value write. ## Troubleshooting diff --git a/skills/agent-desktop-windows/SKILL.md b/skills/agent-desktop-windows/SKILL.md index db68e9f23d..2dd8e68b8b 100644 --- a/skills/agent-desktop-windows/SKILL.md +++ b/skills/agent-desktop-windows/SKILL.md @@ -26,6 +26,8 @@ Use `agent-desktop permissions` to recheck after the user fixes access. Quote refs in PowerShell: `'@s8f3k2p9:e1'`. A bare `@token` invokes splatting. Use `$env:NAME = 'value'` for environment variables. +Windows PowerShell 5.1 drops the double quotes in a JSON argument: pass `($json -replace '"','\"')` to `batch`, which has no stdin or file route. +PowerShell appends a line ending to piped text, so `--stdin` keeps it; use `cmd /c "agent-desktop set-value '' --stdin < file.txt"` for exact text. ## Platform behavior @@ -47,6 +49,9 @@ Use `$env:NAME = 'value'` for environment variables. button: then the innermost one is collapsed (`ExpandCollapsePattern.Collapse`), `delivered_verified` once read back closed. A tree item is never collapsed. `collapse` of an open combo box or menu item works headless, and reports `not_delivered` when it is already closed. +- `press --app` or `--window-id` works headless only when that process owns the foreground window. Otherwise it sends nothing and returns + `ACTION_FAILED` (`details.check: process_focus`, `not_delivered`). There is no background key route. +- `--trace PATH`: the file's folder must exist and have a private DACL (you, SYSTEM, Administrators). A folder that grants `Users` write gives `INVALID_ARGS`. - 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. @@ -56,8 +61,7 @@ Use `$env:NAME = 'value'` for environment variables. activation. An application that activates itself anyway gets the foreground taken back for the window that had it, and the result reports `focus_returned: true`. A window you switched to is never touched. -- Chromium/Electron trees can be thin while accessibility settles. Finish a - bounded observation before concluding that content is absent. +- Chromium/Electron trees can be thin while accessibility settles. Finish a bounded observation before concluding content is absent. - An open application menu is the `menu` surface; there is no `menubar` surface. An owned popup window of the app (a ribbon drop-down) is a `popover`: `list-surfaces` lists it, `snapshot --surface popover` reads it. When several popovers are open, name one with `--app --window-id `; @@ -72,7 +76,7 @@ Use `$env:NAME = 'value'` for environment variables. 1254.2 ms per poll median plus the polling interval; transient toasts can be missed. - `agent-desktop cursor-overlay enable` reports `rendered: true` only after renderer acknowledgement. It does not move the physical pointer, and headed actions skip its travel animation. -- Sandboxes are not available on Windows yet. To run agent-desktop in a container you manage yourself, see `agent-browser.dev/desktop/guides/docker-container`. +- Sandboxes are not available on Windows yet; for your own container see `agent-browser.dev/desktop/guides/docker-container`. Value verification is not application commit: `delivered_verified` with `element_value` confirms only the field. `unavailable` means readback evidence diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.md index d00a1c0dfa..1f0a42a7e6 100644 --- a/skills/agent-desktop/SKILL.md +++ b/skills/agent-desktop/SKILL.md @@ -106,6 +106,13 @@ Request `--cdp` only for the step that needs it. `close-app` ends the exposure. `--agent-id` per agent on its commands; this does not change session or ref ownership. - Review afterwards: sessions trace by default; inspect the session with `trace show` or make a self-contained viewer with `trace export`. +- Launch takes `--arg ` (repeatable; `--arg=-x` for a leading `-`), `--env KEY=VALUE` (no repeated key) and `--cwd `. + `wait --window ` needs part of the title; with none, put `wait --event window-opened --app "<app>"` after the opener in one batch. +- `--stdin` keeps a trailing newline in the value. Send exact text with `printf '%s' "<text>"`; PowerShell appends a line ending to piped strings. +- Saving into a folder: a Save panel's name field takes a file name, not a path (macOS shows `/` as `:`). Pick the folder with the + Where pop-up, which needs headed mode, so ask first. Check the file on disk. `--trace PATH` needs a private file you own, + and on Windows a private folder too (one that grants `Users` write is refused). +- `press --app` reaches a background app only where the platform can: macOS for `return`, `escape` or an app with a focused element; Windows and Linux need the target in front (`ACTION_FAILED`, `not_delivered`). - Secrets: run secret steps as separate `--stdin` commands, not batch JSON `text` or `value` fields, which expose secrets in process arguments. `--stdin` omits observed `value` fields from results; it does not redact later observations or screenshots. @@ -163,14 +170,7 @@ Names are 1–32 lowercase letters, digits or hyphens, starting with a letter or Read `state`, `message` and optional `next`; `ok: true` alone does not mean the sandbox is ready. -- `unavailable`: satisfy the host requirements in `message` and `next`. -- `missing`: install the provider. -- `ready`: create a sandbox. -- `working`: repeat the command in `next` until the work finishes. -- `needs_setup`: have a person complete guest setup, then check status. -- `running`: run guest commands, or stop before removal. -- `stopped`: start the sandbox to use it, or remove it. -- `broken`: follow `next`; a broken sandbox may need removal. +- `unavailable`: meet `message`. `missing`: install. `ready`: create. `working`: repeat `next`. `needs_setup`: a person completes guest setup. `running`: exec, or stop before `rm`. `stopped`: start or remove. `broken`: follow `next`. A sandbox separates the desktop, not the network or the host. Sandboxes on one host share a virtual network, and a guest can reach the host's network services; keep one trust level per host. The host reaches the guest over the virtual machine's own socket device: only the process that runs the VM can open that connection, and `agent-desktop-guest` refuses any caller that is not the host. The host sends commands only to the agent whose key it recorded at setup, so another guest account cannot answer in its place. The agent runs the guest's `agent-desktop` with the arguments after `--` and never a shell. In the guest, Accessibility belongs to `agent-desktop-guest`. From a7b46ceab1733557bcebc40de1ffb12b974cc39f Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:06:59 -0800 Subject: [PATCH 26/26] fix(macos): treat AXWindow ancestors with AXSubrole AXPopover as inside a popover Check AXSubrole for AXPopover before returning false on AXWindow in inside_popover so headless clicks inside subrole-identified popovers do not bypass the popover_command refusal. --- crates/macos/src/actions/background_effect.rs | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/crates/macos/src/actions/background_effect.rs b/crates/macos/src/actions/background_effect.rs index 78380f92af..a9501c6a4a 100644 --- a/crates/macos/src/actions/background_effect.rs +++ b/crates/macos/src/actions/background_effect.rs @@ -163,14 +163,21 @@ fn inside_popover(element: &AXElement, deadline: Deadline) -> Option<bool> { else { return Some(false); }; - match crate::tree::surface_read::string(&parent, "AXRole", deadline) - .ok()? - .as_deref() - { - Some("AXPopover") => return Some(true), - Some("AXWindow" | "AXApplication") => return Some(false), - _ => current = parent, + let role = crate::tree::surface_read::string(&parent, "AXRole", deadline).ok()?; + if role.as_deref() == Some("AXPopover") { + return Some(true); } + if role.as_deref() == Some("AXApplication") { + return Some(false); + } + let subrole = crate::tree::surface_read::string(&parent, "AXSubrole", deadline).ok()?; + if subrole.as_deref() == Some("AXPopover") { + return Some(true); + } + if role.as_deref() == Some("AXWindow") { + return Some(false); + } + current = parent; } }
Pointer gesturesdouble-click, triple-click, hover, drag, mouse-click, mouse-move, X11 onlyWayland: ACTION_NOT_SUPPORTED, cause wayland_session
KeyboardScoped press (--app or --window-id) on X11 and Mutter Wayland. A scoped headless press needs the target window already activeUnscoped press; a scoped press to a background app (X11)Blocked combos such as alt+f4 without --force
Held inputkey-down, key-up, mouse-down, mouse-up
App and windowlaunch, list-apps, list-windows on X11 and Wayland; window control and close-app --force on X11focus-window on X11; a graceful close-app of an app with unsaved work: the save prompt keeps the app open and is reported as dialog_pendingfocus-window and window control on Wayland: ACTION_NOT_SUPPORTED. A headless graceful close-app that cannot read the focused window (a Wayland session, or an owner it cannot identify) returns POLICY_DENIED with details.kind: focus_unreadable before any close request is sent.
App and windowlaunch, list-apps, list-windows on X11 and Wayland; window control and close-app --force on X11focus-window on X11; a graceful close-app of an app with unsaved work: the save prompt keeps the app open and is reported as dialog_pendingfocus-window and window control on Wayland: ACTION_NOT_SUPPORTED. A headless graceful close-app of a native Wayland client returns ACTION_NOT_SUPPORTED with details.cause: wayland_session. One that cannot read the focused window returns POLICY_DENIED with details.kind: focus_unreadable before any close request is sent.
Capturescreenshot, list-displaysX11 under a compositing window manager (GNOME): display and --screen captures return PLATFORM_NOT_SUPPORTED (details.reason: "compositing"); capture one window instead. Wayland: portal consent on first use, and window targets are PLATFORM_NOT_SUPPORTED
Clipboardclipboard-get (text, images, file lists)clipboard-set, clipboard-clear (text, images, file lists)Missing helper or wl-clipboard: PLATFORM_NOT_SUPPORTED
WaitAll modes; --notification on GNOME
Capturescreenshot, with Screen Recording permission
Ref actionsclick, type, clear, scroll, expand, collapse, set-value, select on a list, table, outline or editable combo box, toggle, check, uncheck, scroll-to, focusright-click, select through a menu, click or expand on a pop-up button, menu button or combo box, click, toggle, check or uncheck on a label that ends in … or ...Headless: POLICY_DENIED
Multi-click and pointerdouble-click when the element offers AXOpendouble-click, triple-click, hover, drag, mouse-move, mouse-click, mouse-wheelHeadless: POLICY_DENIED
KeyboardScoped press (--app or --window-id), always physical keyboard input; it never runs a menu item, so click the item insteadUnscoped pressQuit shortcuts such as cmd+q: POLICY_DENIED without --force
KeyboardScoped press (--app or --window-id), headless, return and escape run as accessibility actions on the focused element and every other key needs a focused element in the app (ACTION_FAILED, details.check: process_focus, not_delivered otherwise); a headless shortcut with a modifier never runs a menu item, so click the item insteadUnscoped pressQuit shortcuts such as cmd+q: POLICY_DENIED without --force
Held inputkey-down, key-up, mouse-down, mouse-up
App and windowlaunch, close-app, list-apps, list-windows, resize-window, move-window, minimize, maximize, restorefocus-window
Clipboardclipboard-getclipboard-set (read back: delivered_verified), clipboard-clear