diff --git a/apps/docs/content/docs/json-output.mdx b/apps/docs/content/docs/json-output.mdx index 356f94dc9..104ffa3ab 100644 --- a/apps/docs/content/docs/json-output.mdx +++ b/apps/docs/content/docs/json-output.mdx @@ -43,7 +43,7 @@ An error envelope has `error` and no `data`: "error": { "code": "INVALID_ARGS", "message": "Invalid ref_id '@e1': expected @:e", - "suggestion": "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted.", + "suggestion": "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted. Pass ref_id as printed: it already holds the snapshot id. In zsh write \"@${SID}:e1\", because an unbraced @$SID:e1 reads :e as a modifier.", "disposition": { "delivery": "not_delivered", "retry": "safe" } } } diff --git a/apps/docs/content/docs/snapshots-and-refs.mdx b/apps/docs/content/docs/snapshots-and-refs.mdx index 795b12eeb..450a3cbe0 100644 --- a/apps/docs/content/docs/snapshots-and-refs.mdx +++ b/apps/docs/content/docs/snapshots-and-refs.mdx @@ -112,7 +112,7 @@ Every command accepts only this qualified form. A bare `@e6` fails with `INVALID "error": { "code": "INVALID_ARGS", "message": "Invalid ref_id '@e1': expected @:e", - "suggestion": "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted.", + "suggestion": "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted. Pass ref_id as printed: it already holds the snapshot id. In zsh write \"@${SID}:e1\", because an unbraced @$SID:e1 reads :e as a modifier.", "disposition": { "delivery": "not_delivered", "retry": "safe" } } } diff --git a/crates/core/src/adapter/window_key_refusal.rs b/crates/core/src/adapter/focused_window_key.rs similarity index 73% rename from crates/core/src/adapter/window_key_refusal.rs rename to crates/core/src/adapter/focused_window_key.rs index be1574b68..89b320c1b 100644 --- a/crates/core/src/adapter/window_key_refusal.rs +++ b/crates/core/src/adapter/focused_window_key.rs @@ -1,15 +1,13 @@ -use crate::adapter::SystemOps; +//! Key delivery to a named window, gated on that window holding the focus. + use crate::{ ActionResult, AdapterError, ErrorCode, InteractionLease, InteractionPolicy, KeyCombo, - ProcessIdentity, WindowInfo, + ProcessIdentity, WindowInfo, adapter::SystemOps, }; /// The refusal for a key press whose named window could not be confirmed as /// the focused one, with nothing sent. -pub(super) fn exact_focus_unconfirmed( - window: &WindowInfo, - policy: InteractionPolicy, -) -> AdapterError { +fn exact_focus_unconfirmed(window: &WindowInfo, policy: InteractionPolicy) -> AdapterError { AdapterError::new( ErrorCode::ActionFailed, "The named window does not hold keyboard focus; no key was sent", @@ -26,9 +24,11 @@ pub(super) fn exact_focus_unconfirmed( .with_disposition(crate::DeliverySemantics::not_delivered()) } -/// Delivers `combo` to the process of `window` only after the window reads -/// back as the focused one with the stored process instance. -pub(super) fn press_in_exact_window( +/// Sends `combo` to the process of `window` only when `window` is the exact +/// focused window, and refuses before anything is sent otherwise. This is the +/// default of `SystemOps::press_key_for_window`; an adapter that overrides +/// that method to add a route after the refusal calls it first. +pub fn press_key_in_focused_window( adapter: &A, window: &WindowInfo, combo: &KeyCombo, diff --git a/crates/core/src/adapter/mod.rs b/crates/core/src/adapter/mod.rs index 364572bab..7424b0d68 100644 --- a/crates/core/src/adapter/mod.rs +++ b/crates/core/src/adapter/mod.rs @@ -1,5 +1,6 @@ pub(crate) mod actions; pub(crate) mod adapter_session; +pub(crate) mod focused_window_key; pub mod hit_test; pub(crate) mod input; pub mod live_element; @@ -12,7 +13,6 @@ pub(crate) mod surface_opening; pub(crate) mod system; #[cfg(test)] mod test_support; -mod window_key_refusal; pub(crate) use actions::ActionOps; pub(crate) use input::InputOps; diff --git a/crates/core/src/adapter/system.rs b/crates/core/src/adapter/system.rs index fecdc0e20..d6d62371b 100644 --- a/crates/core/src/adapter/system.rs +++ b/crates/core/src/adapter/system.rs @@ -269,8 +269,9 @@ pub trait SystemOps: Send + Sync { Err(AdapterError::not_supported("press_key_for_app")) } - /// Checks the exact focused window before process-scoped key delivery; - /// adapters can override it to keep the window identity through their gates. + /// Checks the exact focused window before process-scoped key delivery + /// (`press_key_in_focused_window`). Adapters can override this to retain + /// the window identity through their native delivery gates. fn press_key_for_window( &self, window: &WindowInfo, @@ -278,7 +279,7 @@ pub trait SystemOps: Send + Sync { policy: InteractionPolicy, lease: &InteractionLease, ) -> Result { - super::window_key_refusal::press_in_exact_window(self, window, combo, policy, lease) + super::focused_window_key::press_key_in_focused_window(self, window, combo, policy, lease) } fn wait_for_menu( diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c367eb079..f6c349b0f 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -41,6 +41,7 @@ pub use actions::step_mechanism::StepMechanism; pub use adapter::PlatformAdapter; pub use adapter::actions::ActionOps; pub use adapter::adapter_session::AdapterSession; +pub use adapter::focused_window_key::press_key_in_focused_window; pub use adapter::hit_test::HitTestResult; pub use adapter::input::InputOps; pub use adapter::live_element::LiveElement; diff --git a/crates/core/src/refs/ref_token.rs b/crates/core/src/refs/ref_token.rs index cdd759143..dc4571d07 100644 --- a/crates/core/src/refs/ref_token.rs +++ b/crates/core/src/refs/ref_token.rs @@ -23,7 +23,7 @@ pub(crate) fn resolve_ref_target(ref_id: &str) -> Result<(String, String), AppEr let Some((snapshot_id, element_number)) = without_at.rsplit_once(":e") else { return Err(invalid_ref(ref_id)); }; - validate_snapshot_id(snapshot_id)?; + validate_snapshot_id(snapshot_id).map_err(|_| invalid_ref(ref_id))?; let local_ref = format!("@e{element_number}"); if !is_local_ref(&local_ref) { return Err(invalid_ref(ref_id)); @@ -52,10 +52,12 @@ fn is_local_ref(ref_id: &str) -> bool { }) } +const REF_SUGGESTION: &str = "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted. Pass ref_id as printed: it already holds the snapshot id. In zsh write \"@${SID}:e1\", because an unbraced @$SID:e1 reads :e as a modifier."; + fn invalid_ref(ref_id: &str) -> AppError { AppError::invalid_input_with_suggestion( format!("Invalid ref_id '{ref_id}': expected @:e"), - "Use the snapshot-qualified ref that snapshot prints, for example @s8f3k2p9:e1. A bare @eN ref is not accepted.", + REF_SUGGESTION, ) } diff --git a/crates/core/src/refs/ref_token_tests.rs b/crates/core/src/refs/ref_token_tests.rs index 98068617b..321031cbc 100644 --- a/crates/core/src/refs/ref_token_tests.rs +++ b/crates/core/src/refs/ref_token_tests.rs @@ -31,3 +31,20 @@ fn syntax_validation_accepts_only_the_qualified_form() { assert!(validate_ref_token("@sabc:e").is_err()); assert!(validate_ref_token("sabc:e1").is_err()); } + +#[test] +fn a_ref_prefixed_twice_is_named_as_a_ref_with_the_same_suggestion() { + let error = resolve_ref_target("@sabc:@sabc:e7").unwrap_err(); + + assert_eq!(error.code(), "INVALID_ARGS"); + assert!( + error + .to_string() + .contains("Invalid ref_id '@sabc:@sabc:e7'") + ); + assert!( + error + .suggestion() + .is_some_and(|s| s.contains("already holds")) + ); +} diff --git a/crates/linux/src/actions/mod.rs b/crates/linux/src/actions/mod.rs index d789c5ec9..ae0f00298 100644 --- a/crates/linux/src/actions/mod.rs +++ b/crates/linux/src/actions/mod.rs @@ -10,7 +10,7 @@ pub(crate) mod live; pub(crate) mod native_menu; pub(crate) mod physical_target; mod popup_verify; -mod process_check; +pub(crate) mod process_check; pub(crate) mod scroll; pub(crate) mod select; pub(crate) mod toggle_state; diff --git a/crates/linux/src/system/focus/escape_popup.rs b/crates/linux/src/system/focus/escape_popup.rs new file mode 100644 index 000000000..d4b86ec6f --- /dev/null +++ b/crates/linux/src/system/focus/escape_popup.rs @@ -0,0 +1,347 @@ +//! Escape for an application that does not own the active window. +//! +//! The key route sends the key only to the active window, so a key for a +//! background application is refused. A native popup that the application +//! opened stays open in the background on some toolkits, and the key cannot +//! reach it. Web documents are excluded, and a candidate must show an open +//! popup menu child and advertise a dismissal verb (or GTK 3 combo box `Press`, +//! L4-4) so Escape never activates a button's primary handler. +//! +//! Three states, in this order: the key route is allowed and nothing here +//! runs; the key route is refused for focus and a dismissible native popup +//! owner exists in the target window; otherwise the refusal stays as it was. +//! The owner's reply is the answer, so a rejected action delivers nothing and +//! an owner that does not answer leaves the delivery uncertain; the key +//! route's refusal replaces neither. Every stage re-checks that the element +//! still belongs to the original process instance, so a recycled process id +//! never receives the dismissal. + +use std::time::Duration; + +use agent_desktop_core::{ + Action, ActionResult, AdapterError, ChainRung, Deadline, DeliveryOutcome, DeliverySemantics, + KeyCombo, ProcessIdentity, StepMechanism, WindowInfo, +}; + +use crate::actions::action_call::resolve_verb; +use crate::actions::chain::run_semantic_chain; +use crate::actions::process_check::{judge_frame, judge_owner}; +use crate::actions::write::mutation::WriteReply; +use crate::system::process::process_facts; +use crate::system::process::process_lookup::Lookup; +use crate::system::window::window_id; +use crate::system::{SharedBus, owner_process_id, within}; +use crate::tree::menu::observe_menu::rooted; +use crate::tree::properties::toolkit_trust::ToolkitKind; +use crate::tree::vocabulary::role_numbers::{ + COMBO_BOX, MENU, POPUP_MENU, PUSH_BUTTON, PUSH_BUTTON_MENU, TOGGLE_BUTTON, is_web_document, +}; +use crate::tree::vocabulary::state_bits::{HAS_POPUP, SHOWING, StateBits}; +use crate::tree::{AtspiElement, ObservedRead, WalkedNode}; + +#[path = "escape_popup_world.rs"] +mod world; + +use world::PopupWorld; + +const CLOSE_SETTLE: Duration = Duration::from_millis(1000); +const CLOSE_STEP: Duration = Duration::from_millis(50); +const FOCUS_CHECKS: [&str; 2] = ["window_active", "exact_window_focus"]; +const SUGGESTION: &str = "Refresh the snapshot and check whether the popup is still open."; +const CLOSE_LABEL: &str = "Action.DoAction"; +const DISMISS_VERBS: [&str; 3] = ["collapse", "cancel", "close"]; +const GTK3_COMBO_DISMISS_VERBS: [&str; 4] = ["collapse", "cancel", "close", "press"]; + +pub(super) fn is_plain_escape(combo: &KeyCombo) -> bool { + combo.modifiers.is_empty() + && (combo.key.eq_ignore_ascii_case("escape") || combo.key.eq_ignore_ascii_case("esc")) +} + +pub(super) fn is_focus_refusal(error: &AdapterError) -> bool { + error + .details + .as_ref() + .and_then(|details| details.get("check")) + .and_then(|check| check.as_str()) + .is_some_and(|check| FOCUS_CHECKS.contains(&check)) +} + +fn bits(node: &WalkedNode) -> Option> { + node.payload + .node + .traits + .states + .present() + .map(|words| StateBits::new(words)) +} + +fn role(node: &WalkedNode) -> Option { + node.payload.node.traits.role.present().copied() +} + +fn showing_popup(node: &WalkedNode) -> bool { + !node.in_web_document + && !is_web_document(role(node)) + && matches!(role(node), Some(MENU | POPUP_MENU)) + && bits(node).is_some_and(|bits| bits.has(SHOWING)) +} + +/// Whether a native node owns a popup that is visibly open now: a combo box, +/// or a button with `HAS_POPUP`, that has a showing `MENU` or `POPUP_MENU` +/// child. Web documents are excluded, and `EXPANDED` alone never qualifies an +/// owner. A tree row, an expander or a table cell is never an owner: Escape +/// does not collapse a tree. +pub(super) fn is_open_owner(node: &WalkedNode) -> bool { + if node.in_web_document || is_web_document(role(node)) { + return false; + } + let Some(bits) = bits(node) else { + return false; + }; + let owner = match role(node) { + Some(COMBO_BOX) => true, + Some(PUSH_BUTTON | PUSH_BUTTON_MENU | TOGGLE_BUTTON) => bits.has(HAS_POPUP), + _ => false, + }; + owner && node.children.iter().any(showing_popup) +} + +/// The dismissal verbs Escape may invoke on an open popup owner. Generic +/// click/activate verbs are never used, and `press` is allowed only for a +/// native GTK 3 combo box (L4-4), whose `Press` action pops down its showing +/// menu child rather than firing a button's primary handler. +pub(super) fn close_verbs(role: Option, toolkit: ToolkitKind) -> &'static [&'static str] { + match (role, toolkit) { + (Some(COMBO_BOX), ToolkitKind::Gtk3) => >K3_COMBO_DISMISS_VERBS, + _ => &DISMISS_VERBS, + } +} + +pub(super) fn deepest_open_owner<'a>( + node: &'a WalkedNode, + depth: usize, + best: &mut Option<(usize, &'a WalkedNode)>, +) { + if node.in_web_document || is_web_document(role(node)) { + return; + } + if is_open_owner(node) && best.is_none_or(|(deepest, _)| depth > deepest) { + *best = Some((depth, node)); + } + for child in &node.children { + deepest_open_owner(child, depth + 1, best); + } +} + +fn not_delivered(error: AdapterError) -> AdapterError { + error.with_disposition(DeliverySemantics::not_delivered()) +} + +/// Refuses a live process table that no longer names the original instance, +/// so a recycled process id never receives the dismissal. +fn verify_live_process(expected: &ProcessIdentity, live: &Lookup) -> Result<(), AdapterError> { + judge_frame(expected, expected.pid.get(), live).map_err(not_delivered) +} + +/// Refuses a window recorded for another process or for another generation of +/// the target process. +fn verify_window_identity( + expected: &ProcessIdentity, + window: &WindowInfo, +) -> Result<(), AdapterError> { + let same_instance = window.process_instance.as_deref() == Some(expected.instance.as_str()); + if window.pid == expected.pid && same_instance { + return Ok(()); + } + Err(not_delivered(AdapterError::stale_ref_because( + "The window no longer belongs to the target process instance, so no popup was closed", + ))) +} + +fn verify_element_pid( + expected: &ProcessIdentity, + pid: u32, + live: &Lookup, +) -> Result<(), AdapterError> { + judge_frame(expected, pid, live).map_err(not_delivered) +} + +/// Refuses an element whose frame or address names another process, or whose +/// bus name the bus daemon now reports for another process. +fn verify_element_owner( + bus: &SharedBus, + expected: &ProcessIdentity, + element: &AtspiElement, + deadline: Deadline, +) -> Result<(), AdapterError> { + let live = process_facts::lookup(expected.pid.get()); + let frame_pid = element.frame().map_or(element.pid(), AtspiElement::pid); + verify_element_pid(expected, frame_pid, &live)?; + verify_element_pid(expected, element.pid(), &live)?; + let connection = bus.get(deadline).map_err(not_delivered)?; + let owner = within(deadline, async { + Ok(owner_process_id(connection.inner(), element.bus_name()) + .await + .map_err(Some)) + }) + .map_err(not_delivered)?; + judge_owner(expected.pid.get(), owner).map_err(not_delivered)?; + verify_live_process(expected, &process_facts::lookup(expected.pid.get())) +} + +fn frames_of( + world: &impl PopupWorld, + process: &ProcessIdentity, + window: Option<&WindowInfo>, + deadline: Deadline, +) -> Result, AdapterError> { + let windows = match window { + Some(window) => vec![window.clone()], + None => { + let windows = world.windows(process.pid.get(), deadline)?; + verify_live_process(process, &world.live(process.pid.get()))?; + for window in &windows { + verify_window_identity(process, window)?; + } + windows + } + }; + windows + .into_iter() + .map(|window| frame_of(&window, process.pid.get())) + .collect() +} + +fn frame_of(window: &WindowInfo, pid: u32) -> Result { + let (name, path) = window_id::decode(&window.id)?; + Ok(rooted(&AtspiElement::new(name, path, pid))) +} + +/// Whether the owner's popup is open, read after a dismissal. `None` when the +/// owner's states, a child's role or a popup child's states could not be +/// read, or the walk was cut short: a popup that could not be read never +/// counts as closed. +pub(super) fn popup_open(owner: &WalkedNode) -> Option { + if owner.children.iter().any(showing_popup) { + return Some(true); + } + let unread = bits(owner).is_none() + || owner.truncated + || owner.children.iter().any(|child| match role(child) { + Some(MENU | POPUP_MENU) => bits(child).is_none(), + Some(_) => false, + None => true, + }); + (!unread).then_some(false) +} + +/// What the owner's reply settles. A reply of false delivered nothing, so the +/// popup is not read and cannot turn that reply into a delivery. +fn popup_outcome(reply: WriteReply, read_closed: impl FnOnce() -> Option) -> DeliveryOutcome { + match reply { + WriteReply::Absent => DeliveryOutcome::NotDelivered, + WriteReply::Done => DeliveryOutcome::observed(read_closed()), + } +} + +/// The answer for a refused Escape: the popup attempt's own result, or its own +/// error, which already says whether that attempt may have landed. The refusal +/// stands only when the target window shows no dismissible open popup owner. +pub(super) fn popup_answer( + refusal: AdapterError, + popup: Result, AdapterError>, +) -> Result { + match popup { + Ok(Some(settled)) => Ok(settled), + Ok(None) => Err(refusal), + Err(attempt) => Err(attempt), + } +} + +/// The refused Escape of a background application, answered by closing the +/// open native popup its target window shows when the owner advertises a safe +/// dismissal verb. `Ok(None)` leaves the refusal as it was; every other +/// result, the popup attempt's own failure included, is the answer. +pub(super) fn close_open_popup( + bus: &SharedBus, + process: &ProcessIdentity, + window: Option<&WindowInfo>, + combo: &KeyCombo, + deadline: Deadline, +) -> Result, AdapterError> { + close_popup_with(bus, process, window, combo, deadline) +} + +fn close_popup_with( + world: &impl PopupWorld, + process: &ProcessIdentity, + window: Option<&WindowInfo>, + combo: &KeyCombo, + deadline: Deadline, +) -> Result, AdapterError> { + verify_live_process(process, &world.live(process.pid.get()))?; + if let Some(window) = window { + verify_window_identity(process, window)?; + } + let mut best: Option<(usize, AtspiElement, Option)> = None; + for frame in frames_of(world, process, window, deadline).map_err(not_delivered)? { + world + .verify_owner(process, &frame, deadline) + .map_err(not_delivered)?; + let walk = world.walk(&frame, deadline).map_err(not_delivered)?; + let mut found = None; + deepest_open_owner(&walk, 0, &mut found); + if let Some((depth, node)) = found + && best.as_ref().is_none_or(|(deepest, _, _)| depth > *deepest) + { + best = Some((depth, node.payload.node.element.clone(), role(node))); + } + } + let Some((_, owner, owner_role)) = best else { + return Ok(None); + }; + world + .verify_owner(process, &owner, deadline) + .map_err(not_delivered)?; + let (names, verbs) = world + .verbs(&owner, owner_role, deadline) + .map_err(not_delivered)?; + if resolve_verb(&names, verbs).is_none() { + return Ok(None); + } + let run = || { + world + .verify_owner(process, &owner, deadline) + .map_err(not_delivered)?; + let reply = world.dismiss(&owner, &names, verbs, deadline)?; + Ok(popup_outcome(reply, || { + deadline.poll_until( + CLOSE_SETTLE, + CLOSE_STEP, + || world.popup_still_open(&owner, deadline).map(|open| !open), + |closed| *closed == Some(true), + ) + })) + }; + let mut rungs = [ChainRung { + label: CLOSE_LABEL, + effects: &[], + mechanism: StepMechanism::SemanticApi, + run: Box::new(run), + }]; + run_semantic_chain( + &Action::PressKey(combo.clone()), + &mut rungs, + deadline, + SUGGESTION, + ) + .map(Some) +} + +#[cfg(test)] +#[path = "escape_popup_stage_tests.rs"] +mod stage_tests; + +#[cfg(test)] +#[path = "escape_popup_tests.rs"] +mod tests; diff --git a/crates/linux/src/system/focus/escape_popup_stage_tests.rs b/crates/linux/src/system/focus/escape_popup_stage_tests.rs new file mode 100644 index 000000000..9a59cdd85 --- /dev/null +++ b/crates/linux/src/system/focus/escape_popup_stage_tests.rs @@ -0,0 +1,283 @@ +use std::cell::RefCell; +use std::collections::VecDeque; + +use agent_desktop_core::{ + AdapterError, Deadline, DeliverySemantics, ErrorCode, KeyCombo, ProcessId, ProcessIdentity, + WindowInfo, +}; + +use super::world::PopupWorld; +use super::{close_popup_with, verify_live_process, verify_window_identity}; +use crate::actions::write::mutation::WriteReply; +use crate::system::process::process_facts::ProcessFacts; +use crate::system::process::process_lookup::Lookup; +use crate::system::window::window_id; +use crate::tree::test_support::helpers::{read_of, words}; +use crate::tree::vocabulary::role_numbers::{COMBO_BOX, FRAME, MENU}; +use crate::tree::vocabulary::state_bits::SHOWING; +use crate::tree::{AtspiElement, Field, ObservedRead, WalkedNode}; + +const PID: u32 = 4242; +const INSTANCE: &str = "boot:100"; + +fn node( + role: u32, + states: &[u32], + children: Vec>, +) -> WalkedNode { + let mut read = read_of(role, "n", &[]); + read.node.traits.states = Field::Present(words(states)); + WalkedNode { + payload: read, + children, + truncated: false, + child_count: None, + source_index: 0, + in_web_document: false, + } +} + +fn facts(instance: &str) -> ProcessFacts { + ProcessFacts { + executable: None, + comm: "app".to_owned(), + exe_basename: None, + instance: instance.to_owned(), + } +} + +fn process() -> ProcessIdentity { + ProcessIdentity::new(ProcessId::new(PID), INSTANCE) +} + +fn deadline() -> Deadline { + Deadline::standard().expect("deadline") +} + +fn escape() -> KeyCombo { + KeyCombo { + key: "escape".to_owned(), + modifiers: Vec::new(), + } +} + +fn window(instance: Option<&str>) -> WindowInfo { + WindowInfo { + id: window_id::encode(":1.42", "/org/a11y/atspi/accessible/root").expect("window id"), + title: "target".into(), + app: "app".into(), + pid: ProcessId::new(PID), + process_instance: instance.map(str::to_owned), + bounds: None, + state: Default::default(), + } +} + +fn popup_frame() -> WalkedNode { + node( + FRAME, + &[SHOWING], + vec![node( + COMBO_BOX, + &[], + vec![node(MENU, &[SHOWING], Vec::new())], + )], + ) +} + +fn refusal() -> AdapterError { + AdapterError::stale_ref_because("another owner") +} + +struct World { + live: RefCell>, + windows: Result, AdapterError>, + owner_checks: RefCell>>, + walk: WalkedNode, + calls: RefCell>, +} + +impl World { + fn matched() -> Self { + Self { + live: RefCell::new(VecDeque::new()), + windows: Ok(vec![window(Some(INSTANCE))]), + owner_checks: RefCell::new(VecDeque::new()), + walk: popup_frame(), + calls: RefCell::new(Vec::new()), + } + } + + fn record(&self, name: &'static str) { + self.calls.borrow_mut().push(name); + } + + fn count(&self, name: &str) -> usize { + self.calls + .borrow() + .iter() + .filter(|call| **call == name) + .count() + } +} + +impl PopupWorld for World { + fn live(&self, _pid: u32) -> Lookup { + self.live + .borrow_mut() + .pop_front() + .unwrap_or_else(|| Lookup::Found(facts(INSTANCE))) + } + + fn windows(&self, _pid: u32, _deadline: Deadline) -> Result, AdapterError> { + self.record("windows"); + self.windows.clone() + } + + fn verify_owner( + &self, + _expected: &ProcessIdentity, + _element: &AtspiElement, + _deadline: Deadline, + ) -> Result<(), AdapterError> { + self.record("owner"); + self.owner_checks.borrow_mut().pop_front().unwrap_or(Ok(())) + } + + fn walk( + &self, + _frame: &AtspiElement, + _deadline: Deadline, + ) -> Result, AdapterError> { + self.record("walk"); + Ok(self.walk.clone()) + } + + fn verbs( + &self, + _owner: &AtspiElement, + _role: Option, + _deadline: Deadline, + ) -> Result<(Vec, &'static [&'static str]), AdapterError> { + Ok((vec!["collapse".to_owned()], &["collapse"])) + } + + fn dismiss( + &self, + _owner: &AtspiElement, + _names: &[String], + _verbs: &'static [&'static str], + _deadline: Deadline, + ) -> Result { + self.record("dismiss"); + Ok(WriteReply::Done) + } + + fn popup_still_open(&self, _owner: &AtspiElement, _deadline: Deadline) -> Option { + Some(false) + } +} + +#[test] +fn a_live_process_must_keep_its_instance() { + let expected = process(); + assert!(verify_live_process(&expected, &Lookup::Found(facts(INSTANCE))).is_ok()); + for live in [ + Lookup::Gone, + Lookup::Unreadable, + Lookup::Found(facts("boot:other")), + ] { + let error = verify_live_process(&expected, &live).expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + } +} + +#[test] +fn a_window_must_carry_the_original_instance() { + let expected = process(); + assert!(verify_window_identity(&expected, &window(Some(INSTANCE))).is_ok()); + for instance in [None, Some("recycled")] { + let error = verify_window_identity(&expected, &window(instance)).expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + } +} + +#[test] +fn a_process_that_changed_before_discovery_fails_closed() { + for live in [ + Lookup::Gone, + Lookup::Unreadable, + Lookup::Found(facts("boot:other")), + ] { + let world = World::matched(); + *world.live.borrow_mut() = VecDeque::from([live]); + let error = + close_popup_with(&world, &process(), None, &escape(), deadline()).expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(world.count("windows"), 0); + assert_eq!(world.count("owner"), 0); + assert_eq!(world.count("dismiss"), 0); + } +} + +#[test] +fn a_failed_discovery_is_not_a_delivery() { + let mut world = World::matched(); + world.windows = Err(AdapterError::new(ErrorCode::ActionFailed, "unreadable")); + let error = + close_popup_with(&world, &process(), None, &escape(), deadline()).expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(world.count("walk"), 0); + assert_eq!(world.count("dismiss"), 0); +} + +#[test] +fn a_window_of_another_generation_fails_closed_before_discovery() { + for instance in [None, Some("recycled")] { + let world = World::matched(); + let target = window(instance); + let error = close_popup_with(&world, &process(), Some(&target), &escape(), deadline()) + .expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(world.count("windows"), 0); + assert_eq!(world.count("walk"), 0); + assert_eq!(world.count("dismiss"), 0); + } +} + +#[test] +fn a_process_that_changed_after_discovery_fails_closed() { + let world = World::matched(); + *world.live.borrow_mut() = VecDeque::from([ + Lookup::Found(facts(INSTANCE)), + Lookup::Found(facts("boot:other")), + ]); + let error = + close_popup_with(&world, &process(), None, &escape(), deadline()).expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(world.count("windows"), 1); + assert_eq!(world.count("walk"), 0); + assert_eq!(world.count("dismiss"), 0); +} + +#[test] +fn a_foreign_bus_owner_before_the_action_fails_closed() { + let world = World::matched(); + *world.owner_checks.borrow_mut() = VecDeque::from([Ok(()), Ok(()), Err(refusal())]); + let error = + close_popup_with(&world, &process(), None, &escape(), deadline()).expect_err("refused"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(world.count("owner"), 3); + assert_eq!(world.count("dismiss"), 0); +} + +#[test] +fn matching_identity_and_bus_ownership_reach_the_action() { + let world = World::matched(); + let settled = close_popup_with(&world, &process(), None, &escape(), deadline()) + .expect("closed") + .expect("a popup answered"); + assert_eq!(settled.action, "press"); + assert_eq!(world.count("owner"), 3); + assert_eq!(world.count("dismiss"), 1); +} diff --git a/crates/linux/src/system/focus/escape_popup_tests.rs b/crates/linux/src/system/focus/escape_popup_tests.rs new file mode 100644 index 000000000..3e13608de --- /dev/null +++ b/crates/linux/src/system/focus/escape_popup_tests.rs @@ -0,0 +1,236 @@ +use agent_desktop_core::{ + ActionResult, AdapterError, DeliveryOutcome, DeliverySemantics, ErrorCode, KeyCombo, Modifier, +}; +use serde_json::json; + +use super::{ + close_verbs, deepest_open_owner, is_focus_refusal, is_open_owner, is_plain_escape, + popup_answer, popup_open, popup_outcome, +}; +use crate::actions::action_call::resolve_verb; +use crate::actions::write::mutation::{Abort, WriteKind, WriteReply, abort_error}; +use crate::tree::properties::toolkit_trust::ToolkitKind; +use crate::tree::test_support::helpers::{read_of, words}; +use crate::tree::vocabulary::role_numbers::{ + COMBO_BOX, DOCUMENT_WEB, FRAME, MENU, PUSH_BUTTON, PUSH_BUTTON_MENU, TABLE_CELL, TOGGLE_BUTTON, +}; +use crate::tree::vocabulary::state_bits::{EXPANDED, HAS_POPUP, SHOWING}; +use crate::tree::{Field, ObservedRead, WalkedNode}; + +fn node( + role: u32, + states: &[u32], + children: Vec>, +) -> WalkedNode { + let mut read = read_of(role, "n", &[]); + read.node.traits.states = Field::Present(words(states)); + WalkedNode { + payload: read, + children, + truncated: false, + child_count: None, + source_index: 0, + in_web_document: false, + } +} + +fn names(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_owned()).collect() +} + +fn combo(key: &str, modifiers: Vec) -> KeyCombo { + KeyCombo { + key: key.to_owned(), + modifiers, + } +} + +#[test] +fn only_a_plain_escape_is_an_escape() { + assert!(is_plain_escape(&combo("escape", Vec::new()))); + assert!(is_plain_escape(&combo("Escape", Vec::new()))); + assert!(is_plain_escape(&combo("esc", Vec::new()))); + assert!(is_plain_escape(&combo("ESC", Vec::new()))); + assert!(!is_plain_escape(&combo("escape", vec![Modifier::Ctrl]))); + assert!(!is_plain_escape(&combo("esc", vec![Modifier::Shift]))); + assert!(!is_plain_escape(&combo("return", Vec::new()))); +} + +#[test] +fn only_a_focus_refusal_is_answered_by_closing_a_popup() { + let refusal = |check: &str| { + AdapterError::new(ErrorCode::ActionFailed, "refused") + .with_details(json!({ "check": check })) + }; + assert!(is_focus_refusal(&refusal("window_active"))); + assert!(is_focus_refusal(&refusal("exact_window_focus"))); + assert!(!is_focus_refusal(&refusal("process_state"))); + assert!(!is_focus_refusal(&AdapterError::new( + ErrorCode::ActionFailed, + "no details" + ))); +} + +#[test] +fn only_a_native_owner_with_a_showing_popup_is_an_open_owner() { + let shown = || vec![node(MENU, &[SHOWING], Vec::new())]; + let hidden = || vec![node(MENU, &[], Vec::new())]; + assert!(is_open_owner(&node(COMBO_BOX, &[], shown()))); + assert!(!is_open_owner(&node(COMBO_BOX, &[], hidden()))); + assert!(!is_open_owner(&node(COMBO_BOX, &[EXPANDED], Vec::new()))); + assert!(is_open_owner(&node(PUSH_BUTTON, &[HAS_POPUP], shown()))); + assert!(!is_open_owner(&node( + PUSH_BUTTON, + &[HAS_POPUP, EXPANDED], + Vec::new() + ))); + assert!(!is_open_owner(&node(PUSH_BUTTON, &[EXPANDED], Vec::new()))); + assert!(!is_open_owner(&node(TABLE_CELL, &[EXPANDED], shown()))); +} + +#[test] +fn web_document_controls_never_qualify_for_background_escape() { + let shown = || vec![node(MENU, &[SHOWING], Vec::new())]; + let mut web_button = node(PUSH_BUTTON, &[HAS_POPUP, EXPANDED], shown()); + web_button.in_web_document = true; + assert!(!is_open_owner(&web_button)); + + let mut web_combo = node(COMBO_BOX, &[EXPANDED], shown()); + web_combo.in_web_document = true; + assert!(!is_open_owner(&web_combo)); + + let frame = node( + FRAME, + &[SHOWING], + vec![node( + DOCUMENT_WEB, + &[SHOWING], + vec![node(PUSH_BUTTON, &[HAS_POPUP, EXPANDED], shown())], + )], + ); + let mut found = None; + deepest_open_owner(&frame, 0, &mut found); + assert!(found.is_none()); +} + +#[test] +fn background_escape_never_invokes_a_buttons_primary_action() { + let primary = names(&["click", "press", "activate", "open", "clickAncestor"]); + for role in [PUSH_BUTTON, PUSH_BUTTON_MENU, TOGGLE_BUTTON] { + for toolkit in [ + ToolkitKind::Gtk3, + ToolkitKind::Gtk4, + ToolkitKind::Qt, + ToolkitKind::Chromium, + ToolkitKind::Other, + ] { + assert_eq!( + resolve_verb(&primary, close_verbs(Some(role), toolkit)), + None + ); + } + assert_eq!( + resolve_verb( + &names(&["click", "collapse"]), + close_verbs(Some(role), ToolkitKind::Gtk3) + ), + Some(1) + ); + } + + for toolkit in [ + ToolkitKind::Gtk4, + ToolkitKind::Qt, + ToolkitKind::Chromium, + ToolkitKind::Other, + ] { + assert_eq!( + resolve_verb(&primary, close_verbs(Some(COMBO_BOX), toolkit)), + None + ); + } + assert_eq!( + resolve_verb( + &names(&["Press"]), + close_verbs(Some(COMBO_BOX), ToolkitKind::Gtk3) + ), + Some(0) + ); + assert_eq!( + resolve_verb( + &names(&["click", "activate"]), + close_verbs(Some(COMBO_BOX), ToolkitKind::Gtk3) + ), + None + ); +} + +#[test] +fn a_rejected_owner_action_is_never_a_delivery() { + assert_eq!( + popup_outcome(WriteReply::Absent, || Some(true)), + DeliveryOutcome::NotDelivered + ); + assert_eq!( + popup_outcome(WriteReply::Done, || Some(true)), + DeliveryOutcome::observed(Some(true)) + ); +} + +fn focus_refusal() -> AdapterError { + AdapterError::new(ErrorCode::ActionFailed, "refused") + .with_details(json!({ "check": "window_active" })) + .with_disposition(DeliverySemantics::not_delivered()) +} + +#[test] +fn a_popup_attempt_that_may_have_landed_keeps_its_own_uncertain_error() { + let timed_out = abort_error(Abort::TimedOut, WriteKind::DoAction, None); + let answer = popup_answer(focus_refusal(), Err(timed_out)).expect_err("the popup's error"); + assert_eq!(answer.code, ErrorCode::Timeout); + assert_eq!(answer.disposition, DeliverySemantics::uncertain()); + assert!(!is_focus_refusal(&answer)); +} + +#[test] +fn a_refused_escape_stays_refused_when_no_popup_owner_is_open() { + let answer = popup_answer(focus_refusal(), Ok(None)).expect_err("nothing closed a popup"); + assert!(is_focus_refusal(&answer)); + assert_eq!(answer.disposition, DeliverySemantics::not_delivered()); +} + +#[test] +fn a_closed_popup_answers_the_refused_escape() { + let settled = ActionResult::delivered_unverified("close_popup"); + let answer = popup_answer(focus_refusal(), Ok(Some(settled))).expect("the popup closed"); + assert_eq!(answer.action, "close_popup"); + assert_eq!( + answer.disposition(), + DeliverySemantics::delivered_unverified() + ); +} + +#[test] +fn a_popup_that_could_not_be_read_after_the_dismissal_is_not_closed() { + let menu = |states: &[u32]| node(MENU, states, Vec::new()); + assert_eq!( + popup_open(&node(COMBO_BOX, &[], vec![menu(&[SHOWING])])), + Some(true) + ); + assert_eq!( + popup_open(&node(COMBO_BOX, &[], vec![menu(&[])])), + Some(false) + ); + + let mut owner_unread = node(COMBO_BOX, &[], vec![menu(&[])]); + owner_unread.payload.node.traits.states = Field::Failed("gone".to_owned()); + assert_eq!(popup_open(&owner_unread), None); + + let mut menu_unread = menu(&[]); + menu_unread.payload.node.traits.states = Field::Failed("gone".to_owned()); + assert_eq!(popup_open(&node(COMBO_BOX, &[], vec![menu_unread])), None); + + let mut cut = node(COMBO_BOX, &[], vec![menu(&[])]); + cut.truncated = true; + assert_eq!(popup_open(&cut), None); +} diff --git a/crates/linux/src/system/focus/escape_popup_world.rs b/crates/linux/src/system/focus/escape_popup_world.rs new file mode 100644 index 000000000..abc25ed3a --- /dev/null +++ b/crates/linux/src/system/focus/escape_popup_world.rs @@ -0,0 +1,147 @@ +//! The live desktop the background Escape popup fallback reads and acts on, +//! behind a seam so the identity checks can be driven by a fixed desktop. + +use agent_desktop_core::{AdapterError, Deadline, ProcessIdentity, WindowInfo}; + +use super::{close_verbs, popup_open, verify_element_owner}; +use crate::actions::action_call::do_action; +use crate::actions::context::Target; +use crate::actions::write::mutation::WriteReply; +use crate::system::process::process_facts; +use crate::system::process::process_lookup::Lookup; +use crate::system::window::window_ops::windows_of_process; +use crate::system::{REGISTRY_ROOT_PATH, SharedBus, within}; +use crate::tree::menu::observe_menu::{rooted, scan_walk_structure}; +use crate::tree::properties::toolkit_trust::{ToolkitKind, kind, read_toolkit}; +use crate::tree::{AtspiElement, ObservedRead, WalkedNode, get_live_actions}; + +const SCAN_NODES: usize = 600; +const OWNER_NODES: usize = 64; +const POPUP_CONTAINER_CHILDREN: usize = 16; + +/// What one popup attempt reads and does about the desktop, so its identity +/// checks can be driven by a fixed desktop. +pub(super) trait PopupWorld { + fn live(&self, pid: u32) -> Lookup; + + fn windows(&self, pid: u32, deadline: Deadline) -> Result, AdapterError>; + + fn verify_owner( + &self, + expected: &ProcessIdentity, + element: &AtspiElement, + deadline: Deadline, + ) -> Result<(), AdapterError>; + + fn walk( + &self, + frame: &AtspiElement, + deadline: Deadline, + ) -> Result, AdapterError>; + + fn verbs( + &self, + owner: &AtspiElement, + role: Option, + deadline: Deadline, + ) -> Result<(Vec, &'static [&'static str]), AdapterError>; + + fn dismiss( + &self, + owner: &AtspiElement, + names: &[String], + verbs: &'static [&'static str], + deadline: Deadline, + ) -> Result; + + fn popup_still_open(&self, owner: &AtspiElement, deadline: Deadline) -> Option; +} + +impl PopupWorld for SharedBus { + fn live(&self, pid: u32) -> Lookup { + process_facts::lookup(pid) + } + + fn windows(&self, pid: u32, deadline: Deadline) -> Result, AdapterError> { + Ok(windows_of_process(self, pid, deadline)?.0) + } + + fn verify_owner( + &self, + expected: &ProcessIdentity, + element: &AtspiElement, + deadline: Deadline, + ) -> Result<(), AdapterError> { + verify_element_owner(self, expected, element, deadline) + } + + fn walk( + &self, + frame: &AtspiElement, + deadline: Deadline, + ) -> Result, AdapterError> { + scan_walk_structure( + self, + frame, + SCAN_NODES, + Some(POPUP_CONTAINER_CHILDREN), + deadline, + ) + } + + fn verbs( + &self, + owner: &AtspiElement, + role: Option, + deadline: Deadline, + ) -> Result<(Vec, &'static [&'static str]), AdapterError> { + let verbs = close_verbs(role, owner_toolkit(self, owner, deadline)); + let handle = owner.clone().into_native_handle(); + let names = get_live_actions(self, &handle, deadline)?.unwrap_or_default(); + Ok((names, verbs)) + } + + fn dismiss( + &self, + owner: &AtspiElement, + names: &[String], + verbs: &'static [&'static str], + deadline: Deadline, + ) -> Result { + let handle = owner.clone().into_native_handle(); + let target = Target { + bus: self, + handle: &handle, + element: owner, + deadline, + }; + do_action(&target, names, verbs) + } + + fn popup_still_open(&self, owner: &AtspiElement, deadline: Deadline) -> Option { + still_open(self, owner, deadline) + } +} + +fn owner_toolkit(bus: &SharedBus, owner: &AtspiElement, deadline: Deadline) -> ToolkitKind { + let Ok(connection) = bus.get(deadline) else { + return ToolkitKind::Other; + }; + let app = AtspiElement::new(owner.bus_name(), REGISTRY_ROOT_PATH, owner.pid()); + match within(deadline, read_toolkit(connection.inner(), &app)) { + Ok(toolkit) => kind(&toolkit), + Err(_) => ToolkitKind::Other, + } +} + +fn still_open(bus: &SharedBus, owner: &AtspiElement, deadline: Deadline) -> Option { + let walk = scan_walk_structure( + bus, + &rooted(owner), + OWNER_NODES, + Some(POPUP_CONTAINER_CHILDREN), + deadline, + ) + .ok()?; + popup_open(&walk) +} diff --git a/crates/linux/src/system/focus/key_dispatch.rs b/crates/linux/src/system/focus/key_dispatch.rs index 0ffbc8d55..60e73dbee 100644 --- a/crates/linux/src/system/focus/key_dispatch.rs +++ b/crates/linux/src/system/focus/key_dispatch.rs @@ -4,6 +4,7 @@ use agent_desktop_core::{ }; use serde_json::json; +use super::escape_popup::{close_open_popup, is_focus_refusal, is_plain_escape, popup_answer}; use crate::input::backend::Backend; use crate::input::physical::target_keyboard::press_for_process; use crate::input::physical::target_world::{LiveWorld, PhysicalWorld}; @@ -210,6 +211,25 @@ fn press_in( after_delivery(keys, process, result) } +/// An Escape that the key route refused for focus closes the open popup of +/// the target window through its owner; every other result is the key +/// route's own. +fn closing_popup_when_refused( + result: Result, + bus: &SharedBus, + target: (&ProcessIdentity, Option<&WindowInfo>), + combo: &KeyCombo, + deadline: Deadline, +) -> Result { + match result { + Err(error) if is_plain_escape(combo) && is_focus_refusal(&error) => { + let popup = close_open_popup(bus, target.0, target.1, combo, deadline); + popup_answer(error, popup) + } + other => other, + } +} + pub(crate) fn press_key_for_app( bus: &SharedBus, process: ProcessIdentity, @@ -219,7 +239,7 @@ pub(crate) fn press_key_for_app( ) -> Result { crate::system::display::display_server::require(lease.deadline()) .map_err(|error| error.with_disposition(DeliverySemantics::not_delivered()))?; - press_in(Press { + let result = press_in(Press { physical: &LiveWorld { bus, lease }, keys: &LiveKeys { bus }, process: &process, @@ -227,7 +247,8 @@ pub(crate) fn press_key_for_app( combo, policy, deadline: lease.deadline(), - }) + }); + closing_popup_when_refused(result, bus, (&process, None), combo, lease.deadline()) } pub(crate) fn press_key_for_window( @@ -244,15 +265,23 @@ pub(crate) fn press_key_for_window( .as_deref() .filter(|instance| !instance.is_empty()) .ok_or_else(window_identity_missing)?; - press_in(Press { + let process = ProcessIdentity::new(window.pid, instance); + let result = press_in(Press { physical: &LiveWorld { bus, lease }, keys: &LiveKeys { bus }, - process: &ProcessIdentity::new(window.pid, instance), + process: &process, window: Some(window), combo, policy, deadline: lease.deadline(), - }) + }); + closing_popup_when_refused( + result, + bus, + (&process, Some(window)), + combo, + lease.deadline(), + ) } #[cfg(test)] diff --git a/crates/linux/src/system/focus/mod.rs b/crates/linux/src/system/focus/mod.rs index 0b333538b..af1c08e77 100644 --- a/crates/linux/src/system/focus/mod.rs +++ b/crates/linux/src/system/focus/mod.rs @@ -29,6 +29,7 @@ pub(crate) fn focus_is_indeterminate(candidates: &[usize], decided: Option Result<(), AdapterError>; + + /// Reads the cell's value back after the commit. + fn read_back(&mut self, value: &str) -> Result; } /// The write sequence over `edit`. An error after anything was sent is @@ -223,7 +226,11 @@ fn write_steps( } edit.commit(&editor)?; *sent = true; - Ok(DeliveryOutcome::from_delivery(true, false)) + Ok(match edit.read_back(value)? { + ReadBack::Matches => DeliveryOutcome::from_delivery(true, true), + ReadBack::Differs | ReadBack::Unknown => DeliveryOutcome::from_delivery(true, false), + ReadBack::Empty => return cell_took_nothing(), + }) } fn open_editor( @@ -249,7 +256,6 @@ struct LiveCell<'a> { cell: &'a AXElement, deadline: Deadline, } - impl CellEdit for LiveCell<'_> { type Editor = AXElement; @@ -282,36 +288,34 @@ impl CellEdit for LiveCell<'_> { fn commit(&mut self, editor: &AXElement) -> Result<(), AdapterError> { background_keyboard::press(editor, &return_key(), self.deadline) } -} - -/// The end of a write whose editor lost the keyboard focus before the commit, -/// as it does when the application moves the edit into an editor of its own. -/// Return is not sent to another element. Text that was sent stays on record -/// as a failure, so the caller does not read it as a committed write. -pub(crate) fn left_open(sent: bool) -> Result { - if !sent { - return Ok(DeliveryOutcome::NotDelivered); - } - Err(AdapterError::new( - ErrorCode::ActionFailed, - "The text was typed, and the application moved the edit out of the cell's editor before it was committed", - ) - .with_suggestion(LEFT_OPEN_SUGGESTION) - .with_disposition(DeliverySemantics::delivered_unverified())) -} -/// The end of a write that typed nothing. A press that was sent stays on -/// record as a failure, so the caller does not read it as a write. -pub(crate) fn nothing_typed(pressed: bool) -> Result { - if !pressed { - return Ok(DeliveryOutcome::NotDelivered); + fn read_back(&mut self, value: &str) -> Result { + let mut read = || { + let mut usage = crate::tree::observation_usage::ObservationUsage::new( + agent_desktop_core::ObservationBudget::default(), + ); + let text = match crate::tree::element_name::resolve_element_name( + self.cell, + self.deadline, + &mut usage, + ) { + Ok(text) => text, + Err(_) => return ReadBack::Unknown, + }; + if text.as_deref() == Some(value) { + return ReadBack::Matches; + } + if editor_of(self.cell, self.deadline).ok().flatten().is_some() { + return ReadBack::Empty; + } + classify_read_back(text.as_deref(), value) + }; + Ok(self + .deadline + .poll_until(READ_BACK_SETTLE, SETTLE_POLL, &mut read, |read| { + matches!(read, ReadBack::Matches | ReadBack::Unknown) + })) } - Err(AdapterError::new( - ErrorCode::ActionFailed, - "The cell was pressed and nothing was typed: it gave no text editor, or the editor's text could not be read or selected", - ) - .with_suggestion(NO_EDITOR_SUGGESTION) - .with_disposition(DeliverySemantics::delivered_unverified())) } /// The text element inside `cell` that holds the application's keyboard focus. diff --git a/crates/macos/src/actions/cell_editor_tests.rs b/crates/macos/src/actions/cell_editor_tests.rs index a940395c1..fa766b42b 100644 --- a/crates/macos/src/actions/cell_editor_tests.rs +++ b/crates/macos/src/actions/cell_editor_tests.rs @@ -1,7 +1,6 @@ -use super::{ - CellEdit, CellTarget, Replacement, cell_target, left_open, nothing_typed, replacement, - write_through, -}; +use super::{CellEdit, CellTarget, Replacement, cell_target, replacement, write_through}; +use crate::actions::cell_read_back::ReadBack; +use crate::actions::cell_write_failure::{left_open, nothing_typed}; use agent_desktop_core::{AdapterError, DeliveryOutcome, DeliverySemantics, ErrorCode}; #[test] @@ -65,6 +64,10 @@ fn unverified() -> DeliveryOutcome { DeliveryOutcome::from_delivery(true, false) } +fn verified() -> DeliveryOutcome { + DeliveryOutcome::from_delivery(true, true) +} + /// A cell whose editor is open from the start, or opens on the press numbered /// `opens_on_press`, and that records every call made on it. struct ScriptedCell { @@ -72,6 +75,7 @@ struct ScriptedCell { opens_on_press: usize, press: DeliveryOutcome, typed: Result, + read_back: ReadBack, keeps_focus: bool, presses: usize, calls: Vec<&'static str>, @@ -83,6 +87,7 @@ fn scripted() -> ScriptedCell { opens_on_press: 1, press: unverified(), typed: Ok(unverified()), + read_back: ReadBack::Matches, keeps_focus: true, presses: 0, calls: Vec::new(), @@ -124,6 +129,11 @@ impl CellEdit for ScriptedCell { self.calls.push("commit"); Ok(()) } + + fn read_back(&mut self, _: &str) -> Result { + self.calls.push("read_back"); + Ok(self.read_back) + } } #[test] @@ -133,8 +143,51 @@ fn an_open_editor_is_replaced_and_committed_without_a_press() { ..scripted() }; + assert_eq!(write_through(&mut cell, "42").unwrap(), verified()); + assert_eq!( + cell.calls, + ["editor", "replace", "holds_focus", "commit", "read_back"] + ); +} + +#[test] +fn a_cell_that_stays_empty_after_the_commit_fails_as_delivered() { + let mut cell = ScriptedCell { + open: true, + read_back: ReadBack::Empty, + ..scripted() + }; + + let error = write_through(&mut cell, "42").unwrap_err(); + + assert_eq!(error.code, ErrorCode::ActionFailed); + assert_eq!(error.disposition, DeliverySemantics::delivered_unverified()); + assert_eq!( + cell.calls, + ["editor", "replace", "holds_focus", "commit", "read_back"] + ); +} + +#[test] +fn a_cell_that_shows_another_value_stays_unverified() { + let mut cell = ScriptedCell { + read_back: ReadBack::Differs, + ..scripted() + }; + assert_eq!(write_through(&mut cell, "42").unwrap(), unverified()); - assert_eq!(cell.calls, ["editor", "replace", "holds_focus", "commit"]); + assert_eq!(cell.calls.last(), Some(&"read_back")); +} + +#[test] +fn an_unreadable_cell_stays_unverified_and_never_fails() { + let mut cell = ScriptedCell { + read_back: ReadBack::Unknown, + ..scripted() + }; + + assert_eq!(write_through(&mut cell, "42").unwrap(), unverified()); + assert_eq!(cell.calls.last(), Some(&"read_back")); } #[test] @@ -144,7 +197,7 @@ fn a_press_that_only_selects_the_cell_is_followed_by_one_more() { ..scripted() }; - assert_eq!(write_through(&mut cell, "42").unwrap(), unverified()); + assert_eq!(write_through(&mut cell, "42").unwrap(), verified()); assert_eq!( cell.calls, [ @@ -155,7 +208,8 @@ fn a_press_that_only_selects_the_cell_is_followed_by_one_more() { "opened_editor", "replace", "holds_focus", - "commit" + "commit", + "read_back" ] ); } diff --git a/crates/macos/src/actions/cell_read_back.rs b/crates/macos/src/actions/cell_read_back.rs new file mode 100644 index 000000000..3b63adf3b --- /dev/null +++ b/crates/macos/src/actions/cell_read_back.rs @@ -0,0 +1,26 @@ +//! Judging a table cell's value after a committed write. + +/// What a cell shows after a committed write, next to the value written. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ReadBack { + Matches, + Empty, + Differs, + Unknown, +} + +/// Judges the cell's value after a commit. `current` is `None` only when the +/// application was read and published no value; a read that failed is +/// `Unknown` and never an empty cell. +pub(crate) fn classify(current: Option<&str>, wanted: &str) -> ReadBack { + match current { + Some(held) if held == wanted => ReadBack::Matches, + Some(held) if !held.is_empty() => ReadBack::Differs, + _ if wanted.is_empty() => ReadBack::Matches, + _ => ReadBack::Empty, + } +} + +#[cfg(test)] +#[path = "cell_read_back_tests.rs"] +mod tests; diff --git a/crates/macos/src/actions/cell_read_back_tests.rs b/crates/macos/src/actions/cell_read_back_tests.rs new file mode 100644 index 000000000..e33fee959 --- /dev/null +++ b/crates/macos/src/actions/cell_read_back_tests.rs @@ -0,0 +1,12 @@ +use super::{ReadBack, classify}; + +#[test] +fn the_read_back_judges_only_an_empty_cell_as_a_miss() { + assert_eq!(classify(Some("42"), "42"), ReadBack::Matches); + assert_eq!(classify(None, ""), ReadBack::Matches); + assert_eq!(classify(Some(""), ""), ReadBack::Matches); + assert_eq!(classify(None, "42"), ReadBack::Empty); + assert_eq!(classify(Some(""), "42"), ReadBack::Empty); + assert_eq!(classify(Some("41"), "42"), ReadBack::Differs); + assert_eq!(classify(Some("42"), ""), ReadBack::Differs); +} diff --git a/crates/macos/src/actions/cell_write_failure.rs b/crates/macos/src/actions/cell_write_failure.rs new file mode 100644 index 000000000..691880cfe --- /dev/null +++ b/crates/macos/src/actions/cell_write_failure.rs @@ -0,0 +1,48 @@ +//! The failures a value write through a cell's editor can end with. + +use agent_desktop_core::{AdapterError, DeliveryOutcome, DeliverySemantics, ErrorCode}; + +const LEFT_OPEN_SUGGESTION: &str = "Commit the open edit with a key press scoped to the application, such as press return --app , then read the cell to verify."; +const NO_EDITOR_SUGGESTION: &str = "Take a fresh snapshot before another write: the press can select the cell or open another surface."; +const CELL_TOOK_NOTHING_SUGGESTION: &str = "Bring the application to the front and retry, or type into the cell with --headed only if the user explicitly asked for that, then read the cell to verify the write."; + +/// The end of a write whose editor lost the keyboard focus before the commit, +/// as it does when the application moves the edit into an editor of its own. +/// Return is not sent to another element. Text that was sent stays on record +/// as a failure, so the caller does not read it as a committed write. +pub(crate) fn left_open(sent: bool) -> Result { + if !sent { + return Ok(DeliveryOutcome::NotDelivered); + } + Err(AdapterError::new( + ErrorCode::ActionFailed, + "The text was typed, and the application moved the edit out of the cell's editor before it was committed", + ) + .with_suggestion(LEFT_OPEN_SUGGESTION) + .with_disposition(DeliverySemantics::delivered_unverified())) +} + +/// The end of a write that typed nothing. A press that was sent stays on +/// record as a failure, so the caller does not read it as a write. +pub(crate) fn nothing_typed(pressed: bool) -> Result { + if !pressed { + return Ok(DeliveryOutcome::NotDelivered); + } + Err(AdapterError::new( + ErrorCode::ActionFailed, + "The cell was pressed and nothing was typed: it gave no text editor, or the editor's text could not be read or selected", + ) + .with_suggestion(NO_EDITOR_SUGGESTION) + .with_disposition(DeliverySemantics::delivered_unverified())) +} + +/// The end of a write whose cell still shows nothing after the commit: the +/// application took the keys and dropped them instead of the text. +pub(crate) fn cell_took_nothing() -> Result { + Err(AdapterError::new( + ErrorCode::ActionFailed, + "The text was typed and committed, but the cell still shows nothing", + ) + .with_suggestion(CELL_TOOK_NOTHING_SUGGESTION) + .with_disposition(DeliverySemantics::delivered_unverified())) +} diff --git a/crates/macos/src/actions/mod.rs b/crates/macos/src/actions/mod.rs index 865adce7a..c2332ee8e 100644 --- a/crates/macos/src/actions/mod.rs +++ b/crates/macos/src/actions/mod.rs @@ -7,6 +7,8 @@ pub(crate) mod ax_perform; pub(crate) mod background_effect; mod background_keyboard; mod cell_editor; +pub(crate) mod cell_read_back; +pub(crate) mod cell_write_failure; pub(crate) mod chain; pub(crate) mod delivery_tracker; pub(crate) mod dispatch; diff --git a/crates/macos/src/system/adapter.rs b/crates/macos/src/system/adapter.rs index be499ff1f..28b962213 100644 --- a/crates/macos/src/system/adapter.rs +++ b/crates/macos/src/system/adapter.rs @@ -254,6 +254,18 @@ impl SystemOps for MacOSAdapter { crate::system::key_dispatch::press_for_app_impl(process, combo, policy, lease.deadline()) } + /// Core's focus-gated delivery to the named window, then the close of the + /// menu or popover a refused Escape would close. + fn press_key_for_window( + &self, + window: &WindowInfo, + combo: &agent_desktop_core::KeyCombo, + policy: agent_desktop_core::InteractionPolicy, + lease: &InteractionLease, + ) -> Result { + crate::system::key_dispatch::press_for_window(self, window, combo, policy, lease) + } + fn wait_for_menu( &self, process: ProcessIdentity, diff --git a/crates/macos/src/system/key_dispatch.rs b/crates/macos/src/system/key_dispatch.rs index 6b59254d0..6ed6bb6e6 100644 --- a/crates/macos/src/system/key_dispatch.rs +++ b/crates/macos/src/system/key_dispatch.rs @@ -9,6 +9,11 @@ use crate::tree::AXElement; #[path = "key_dispatch_menu.rs"] mod menu; +#[path = "key_dispatch_window.rs"] +mod window; + +pub(crate) use window::press_for_window; + pub(crate) fn press_for_app_impl( process: ProcessIdentity, combo: &KeyCombo, @@ -43,9 +48,9 @@ fn press_for_app( } } if let Some(action) = simple_key_action(combo) - && try_simple_key_action(&app, action, deadline)? + && let Some(step) = deliver_semantic_key(identity, &app, action, deadline)? { - return post_delivery_process_result(&process, semantic_step(action)); + return post_delivery_process_result(&process, step); } crate::input::keyboard::keyboard_map::key_name_to_code(&combo.key)?; @@ -113,40 +118,188 @@ fn semantic_step(label: &'static str) -> ActionStep { .with_verified(false) } +/// The delivered result a completed step settles: verified only when the step +/// read its own effect. +fn delivery_result(step: ActionStep) -> ActionResult { + let verified = step.verified == Some(true); + let result = ActionResult::delivered_unverified("press_key").with_steps(vec![step]); + if verified { + result.with_verified_delivery() + } else { + result + } +} + fn post_delivery_process_result( process: &ProcessIdentity, step: ActionStep, ) -> Result { crate::system::process::process_identity::require_core(process) .map_err(|error| error.with_disposition(DeliverySemantics::delivered_unverified()))?; - Ok(ActionResult::delivered_unverified("press_key").with_steps(vec![step])) + Ok(delivery_result(step)) } -fn try_simple_key_action( +/// Where a key without modifiers lands as an accessibility action. +#[derive(Debug, PartialEq, Eq)] +enum SemanticKeyTarget { + /// The focus holder advertises the action the key stands for. + FocusHolder(T), + /// Escape while no focus holder takes it and the application shows a menu + /// or a popover: the surface the key would close. + OpenSurface(T), +} + +/// The states in the order they are tried: the focus holder, then, for +/// Escape only, the open surface. `Ok(None)` leaves the key its event route, +/// while a failed surface read propagates instead of reading as absent. +fn choose_key_target( + focus_holder: Option, + action: &str, + open_surface: impl FnOnce() -> Result, AdapterError>, +) -> Result>, AdapterError> { + if let Some(holder) = focus_holder { + return Ok(Some(SemanticKeyTarget::FocusHolder(holder))); + } + if action != CANCEL { + return Ok(None); + } + Ok(open_surface()?.map(SemanticKeyTarget::OpenSurface)) +} + +fn semantic_key_target( + identity: crate::system::process::process_identity::ProcessIdentity, app: &AXElement, action: &str, deadline: Deadline, -) -> Result { - let Some(focused) = focused_element(app, deadline)? else { - return Ok(false); +) -> Result>, AdapterError> { + let focus_holder = focused_element(app, deadline)?.filter(|focused| { + crate::actions::ax_helpers::advertises_action(focused, action, deadline) == Some(true) + }); + choose_key_target(focus_holder, action, || { + open_transient_surface(identity, deadline) + }) +} + +const ESCAPE_SURFACE_PROBE_BUDGET: std::time::Duration = std::time::Duration::from_millis(500); + +fn classify_surface_probe( + result: Result, AdapterError>, + caller_deadline: Deadline, +) -> Result, AdapterError> { + match result { + Ok(surface) => Ok(surface), + Err(error) + if crate::tree::app_menu::is_surface_search_limit(&error) + || (error.code == ErrorCode::Timeout && !caller_deadline.is_expired()) => + { + Ok(None) + } + Err(error) => Err(error), + } +} + +/// The menu or popover the application shows. A bounded probe that reaches its +/// node limit or its own sub-budget timeout while the caller's deadline still +/// has time left falls back to the key's event route; every other read failure, +/// including a changed process generation or an expired caller deadline, +/// propagates. +fn open_transient_surface( + identity: crate::system::process::process_identity::ProcessIdentity, + deadline: Deadline, +) -> Result, AdapterError> { + let probe_deadline = deadline.capped(ESCAPE_SURFACE_PROBE_BUDGET); + classify_surface_probe( + crate::tree::surfaces::transient_surface_for_process(identity, probe_deadline), + deadline, + ) +} + +/// Performs the action on the target the key reaches. The process generation is +/// revalidated immediately before the action, and an open surface must belong to +/// that process. A closed surface is verified by reading that it is gone. +fn deliver_semantic_key( + identity: crate::system::process::process_identity::ProcessIdentity, + app: &AXElement, + action: &'static str, + deadline: Deadline, +) -> Result, AdapterError> { + let Some(target) = semantic_key_target(identity, app, action, deadline)? else { + return Ok(None); + }; + let (element, closes_surface) = match &target { + SemanticKeyTarget::FocusHolder(element) => (element, false), + SemanticKeyTarget::OpenSurface(element) => (element, true), }; - if crate::actions::ax_helpers::advertises_action(&focused, action, deadline) != Some(true) { - return Ok(false); + if closes_surface { + require_surface_owner(element, identity, deadline)?; + } + crate::tree::app_menu::require_generation(identity).map_err(not_delivered)?; + if !crate::actions::ax_helpers::try_ax_action_or_err(element, action, deadline)? { + return Ok(None); + } + let closed = closes_surface && surface_closed(element, deadline); + Ok(Some(semantic_step(action).with_verified(closed))) +} + +/// Confirms an open surface still belongs to the process the key targets, +/// before anything is sent to it. +fn require_surface_owner( + surface: &AXElement, + identity: crate::system::process::process_identity::ProcessIdentity, + deadline: Deadline, +) -> Result<(), AdapterError> { + match crate::tree::properties::ax_ipc::pid(surface, deadline) { + Ok(pid) if pid == identity.pid() => Ok(()), + Ok(_) => Err(AdapterError::stale_ref_because( + "Surface no longer belongs to the target process", + )), + Err(error) if error == accessibility_sys::kAXErrorInvalidUIElement => Err( + AdapterError::stale_ref_because("Surface became invalid before cancel"), + ), + Err(error) => Err(crate::tree::surface_read::map_error("AXPid", error) + .with_disposition(DeliverySemantics::not_delivered())), } - crate::actions::ax_helpers::try_ax_action_or_err(&focused, action, deadline) +} + +fn not_delivered(error: AdapterError) -> AdapterError { + error.with_disposition(DeliverySemantics::not_delivered()) +} + +/// A closed surface leaves the tree: a popover's element becomes invalid, and +/// a menu's element stays readable but is no longer a child of its parent. +fn surface_closed(surface: &AXElement, deadline: Deadline) -> bool { + let gone = || match crate::tree::surface_read::element(surface, "AXParent", deadline) { + Err(error) => error.code == ErrorCode::StaleRef, + Ok(None) => true, + Ok(Some(parent)) => crate::tree::surface_read::elements(&parent, "AXChildren", deadline) + .is_ok_and(|children| { + !children + .iter() + .any(|child| crate::tree::same_element(child, surface)) + }), + }; + deadline.poll_until( + SURFACE_CLOSE_WAIT, + Duration::from_millis(10), + gone, + |gone| *gone, + ) } fn uses_menu_shortcut(combo: &KeyCombo, policy: InteractionPolicy) -> bool { policy.allow_focus_steal && !combo.modifiers.is_empty() } +const CANCEL: &str = "AXCancel"; +const SURFACE_CLOSE_WAIT: Duration = Duration::from_millis(500); + fn simple_key_action(combo: &KeyCombo) -> Option<&'static str> { if !combo.modifiers.is_empty() { return None; } match combo.key.as_str() { "return" | "enter" => Some("AXConfirm"), - "escape" | "esc" => Some("AXCancel"), + "escape" | "esc" => Some(CANCEL), _ => None, } } diff --git a/crates/macos/src/system/key_dispatch_tests.rs b/crates/macos/src/system/key_dispatch_tests.rs index e3c080d04..13613faa4 100644 --- a/crates/macos/src/system/key_dispatch_tests.rs +++ b/crates/macos/src/system/key_dispatch_tests.rs @@ -49,6 +49,7 @@ fn return_and_escape_map_to_default_and_cancel_actions() { simple_key_action(&key("escape", Vec::new())), Some("AXCancel") ); + assert_eq!(simple_key_action(&key("esc", Vec::new())), Some("AXCancel")); assert_eq!( simple_key_action(&key("return", vec![Modifier::Meta])), None @@ -115,6 +116,66 @@ fn an_unresolvable_key_fails_before_any_focus_change() { ); } +#[test] +fn escape_reaches_the_focus_holder_first_then_the_open_surface() { + use super::{SemanticKeyTarget, choose_key_target}; + + assert_eq!( + choose_key_target(Some(1), "AXCancel", || panic!("surface read")).unwrap(), + Some(SemanticKeyTarget::FocusHolder(1)) + ); + assert_eq!( + choose_key_target(None, "AXCancel", || Ok(Some(2))).unwrap(), + Some(SemanticKeyTarget::OpenSurface(2)) + ); + assert_eq!( + choose_key_target::(None, "AXCancel", || Ok(None)).unwrap(), + None + ); + assert_eq!( + choose_key_target::(None, "AXConfirm", || panic!("surface read")).unwrap(), + None + ); +} + +#[test] +fn a_failed_surface_read_is_not_turned_into_an_absent_surface() { + use super::choose_key_target; + + let error = choose_key_target::(None, "AXCancel", || { + Err(AdapterError::stale_ref_because( + "Application process instance changed during observation", + )) + }) + .expect_err("a failed surface read must not read as no surface"); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); +} + +#[test] +fn a_surface_probe_timeout_falls_back_only_while_the_caller_deadline_remains() { + use super::classify_surface_probe; + + let live = Deadline::after(5_000).unwrap(); + assert_eq!( + classify_surface_probe::(Err(AdapterError::timeout("probe slice")), live).unwrap(), + None + ); + + let expired = Deadline::after(0).unwrap(); + let error = classify_surface_probe::(Err(AdapterError::timeout("caller done")), expired) + .expect_err("an expired caller deadline must propagate"); + assert_eq!(error.code, ErrorCode::Timeout); + + let stale = classify_surface_probe::( + Err(AdapterError::stale_ref_because("generation changed")), + live, + ) + .expect_err("process generation failure must propagate"); + assert_eq!(stale.code, ErrorCode::StaleRef); +} + #[test] fn a_command_chord_to_a_background_app_is_refused_before_sending() { let headless = agent_desktop_core::InteractionPolicy::headless(); diff --git a/crates/macos/src/system/key_dispatch_window.rs b/crates/macos/src/system/key_dispatch_window.rs new file mode 100644 index 000000000..d2efc382d --- /dev/null +++ b/crates/macos/src/system/key_dispatch_window.rs @@ -0,0 +1,188 @@ +//! Key delivery to a named window, and the surface close a refused Escape +//! answers. +//! +//! Core's window route needs the named window to hold the exact focus. A menu +//! or a popover a person opened can sit in a window that is not focused, and +//! the key is then refused before anything is sent. The surface still has a +//! semantic close: `AXCancel` on the menu or popover itself. The states, in +//! this order: the key route delivers, unchanged; it refuses for focus and a +//! plain Escape finds an open surface in that window or its application, which +//! is cancelled and read back; otherwise the refusal stays as it was. + +use agent_desktop_core::{ + ActionResult, AdapterError, Deadline, DeliverySemantics, InteractionLease, InteractionPolicy, + KeyCombo, SystemOps, WindowInfo, +}; + +use super::{CANCEL, delivery_result, semantic_step, simple_key_action, surface_closed}; +use crate::system::process::process_identity::ProcessIdentity; +use crate::tree::AXElement; + +/// A key for a named window: core's focus-gated delivery, then, for a plain +/// Escape that gate refused, the close of the menu or popover showing in that +/// window or its application. +pub(crate) fn press_for_window( + adapter: &A, + window: &WindowInfo, + combo: &KeyCombo, + policy: InteractionPolicy, + lease: &InteractionLease, +) -> Result { + match agent_desktop_core::press_key_in_focused_window(adapter, window, combo, policy, lease) { + Err(refusal) if answers_with_surface_close(combo, &refusal) => { + answer_with_surface_close(refusal, || close_window_surface(window, lease.deadline())) + } + other => other, + } +} + +/// Whether a surface close answers this refusal: the key is a plain Escape, +/// which cancels the open surface, and the window focus gate refused before +/// anything was sent. +fn answers_with_surface_close(combo: &KeyCombo, refusal: &AdapterError) -> bool { + simple_key_action(combo) == Some(CANCEL) && is_focus_refusal(refusal) +} + +fn is_focus_refusal(error: &AdapterError) -> bool { + let details = error.details.as_ref(); + error.disposition == DeliverySemantics::not_delivered() + && details.and_then(|details| details["physical_delivery_started"].as_bool()) == Some(false) + && details.and_then(|details| details["check"].as_str()) == Some("window_active") +} + +/// The surface close is the answer when it closed something; with nothing open +/// the refusal stands, and an attempt that failed keeps its own error. +fn answer_with_surface_close( + refusal: AdapterError, + close: impl FnOnce() -> Result, AdapterError>, +) -> Result { + match close()? { + Some(closed) => Ok(closed), + None => Err(refusal), + } +} + +/// The identity checks and effects a window surface close depends on, split +/// out so its decision flow is exercised without live accessibility windows. +trait WindowSurfaceClose { + fn expected_identity(&self, window: &WindowInfo) -> Result; + fn discover( + &self, + identity: ProcessIdentity, + window: &WindowInfo, + deadline: Deadline, + ) -> Result, AdapterError>; + fn require_generation(&self, identity: ProcessIdentity) -> Result<(), AdapterError>; + fn surface_pid(&self, surface: &AXElement, deadline: Deadline) -> Result; + fn cancel(&self, surface: &AXElement, deadline: Deadline) -> Result; + fn closed(&self, surface: &AXElement, deadline: Deadline) -> bool; +} + +struct AxWindowSurface; + +impl WindowSurfaceClose for AxWindowSurface { + fn expected_identity(&self, window: &WindowInfo) -> Result { + expected_window_identity(window) + } + + fn discover( + &self, + identity: ProcessIdentity, + window: &WindowInfo, + deadline: Deadline, + ) -> Result, AdapterError> { + crate::tree::surfaces::transient_surface_for_window(identity, window, deadline) + } + + fn require_generation(&self, identity: ProcessIdentity) -> Result<(), AdapterError> { + crate::tree::app_menu::require_generation(identity) + } + + fn surface_pid(&self, surface: &AXElement, deadline: Deadline) -> Result { + crate::tree::properties::ax_ipc::pid(surface, deadline) + } + + fn cancel(&self, surface: &AXElement, deadline: Deadline) -> Result { + crate::actions::ax_helpers::try_ax_action_or_err(surface, CANCEL, deadline) + } + + fn closed(&self, surface: &AXElement, deadline: Deadline) -> bool { + surface_closed(surface, deadline) + } +} + +/// The process identity a window proves from its captured pid and instance +/// token, so a surface is never searched for under a freshly captured +/// generation. +fn expected_window_identity(window: &WindowInfo) -> Result { + let instance = window + .process_instance + .as_deref() + .filter(|instance| !instance.is_empty()) + .ok_or_else(|| { + AdapterError::stale_ref_because("Window has no process-instance identity") + })?; + crate::system::process::process_identity::require_core( + &agent_desktop_core::ProcessIdentity::new(window.pid, instance), + ) +} + +/// Closes the menu or popover the named window or its application shows, and +/// reads that it closed. `Ok(None)` when none is open, or when the surface does +/// not take a cancel action. +fn close_window_surface( + window: &WindowInfo, + deadline: Deadline, +) -> Result, AdapterError> { + close_window_surface_with(&AxWindowSurface, window, deadline) +} + +fn close_window_surface_with( + source: &impl WindowSurfaceClose, + window: &WindowInfo, + deadline: Deadline, +) -> Result, AdapterError> { + let identity = source.expected_identity(window).map_err(not_delivered)?; + let Some(surface) = source + .discover(identity, window, deadline) + .map_err(not_delivered)? + else { + return Ok(None); + }; + verify_surface_owner(source, identity, &surface, deadline).map_err(not_delivered)?; + if !source.cancel(&surface, deadline)? { + return Ok(None); + } + let closed = source.closed(&surface, deadline); + Ok(Some(delivery_result( + semantic_step(CANCEL).with_verified(closed), + ))) +} + +fn verify_surface_owner( + source: &impl WindowSurfaceClose, + identity: ProcessIdentity, + surface: &AXElement, + deadline: Deadline, +) -> Result<(), AdapterError> { + source.require_generation(identity)?; + match source.surface_pid(surface, deadline) { + Ok(pid) if pid == identity.pid() => source.require_generation(identity), + Ok(_) => Err(AdapterError::stale_ref_because( + "Surface no longer belongs to the target process", + )), + Err(error) if error == accessibility_sys::kAXErrorInvalidUIElement => Err( + AdapterError::stale_ref_because("Surface became invalid before cancel"), + ), + Err(error) => Err(crate::tree::surface_read::map_error("AXPid", error) + .with_disposition(DeliverySemantics::not_delivered())), + } +} + +fn not_delivered(error: AdapterError) -> AdapterError { + error.with_disposition(DeliverySemantics::not_delivered()) +} + +#[cfg(test)] +#[path = "key_dispatch_window_tests.rs"] +mod tests; diff --git a/crates/macos/src/system/key_dispatch_window_tests.rs b/crates/macos/src/system/key_dispatch_window_tests.rs new file mode 100644 index 000000000..0edbf8812 --- /dev/null +++ b/crates/macos/src/system/key_dispatch_window_tests.rs @@ -0,0 +1,397 @@ +use std::cell::Cell; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use agent_desktop_core::{ErrorCode, Modifier, ProcessId, ProcessIdentity, WindowState}; + +use super::{ + ActionResult, AdapterError, CANCEL, Deadline, DeliverySemantics, InteractionLease, + InteractionPolicy, KeyCombo, SystemOps, WindowInfo, WindowSurfaceClose, + answer_with_surface_close, answers_with_surface_close, close_window_surface_with, + delivery_result, is_focus_refusal, press_for_window, semantic_step, +}; +use crate::system::process::process_identity::ProcessIdentity as NativeProcessIdentity; +use crate::tree::AXElement; + +struct WindowRoute { + focused: Option, + dispatched: AtomicUsize, +} + +impl SystemOps for WindowRoute { + fn focused_window(&self, _deadline: Deadline) -> Result, AdapterError> { + Ok(self.focused.clone()) + } + + fn press_key_for_app( + &self, + _process: ProcessIdentity, + _combo: &KeyCombo, + _policy: InteractionPolicy, + _lease: &InteractionLease, + ) -> Result { + self.dispatched.fetch_add(1, Ordering::SeqCst); + Ok(ActionResult::delivered_unverified("press_key")) + } +} + +fn window(id: &str) -> WindowInfo { + WindowInfo { + id: id.into(), + title: format!("Window {id}"), + app: "Fixture".into(), + pid: ProcessId::new(std::process::id()), + process_instance: Some("generation-1".into()), + bounds: None, + state: WindowState::default(), + } +} + +fn route(focused: &str) -> WindowRoute { + WindowRoute { + focused: Some(window(focused)), + dispatched: AtomicUsize::new(0), + } +} + +fn key(name: &str, modifiers: Vec) -> KeyCombo { + KeyCombo { + key: name.into(), + modifiers, + } +} + +fn lease() -> InteractionLease { + InteractionLease::guarded(Deadline::standard().unwrap(), ()).unwrap() +} + +fn focus_refusal(adapter: &WindowRoute) -> AdapterError { + agent_desktop_core::press_key_in_focused_window( + adapter, + &window("w-1"), + &key("a", Vec::new()), + InteractionPolicy::headless(), + &lease(), + ) + .unwrap_err() +} + +#[test] +fn a_window_that_holds_the_focus_takes_the_key_itself() { + let adapter = route("w-1"); + let result = press_for_window( + &adapter, + &window("w-1"), + &key("escape", Vec::new()), + InteractionPolicy::headless(), + &lease(), + ) + .unwrap(); + + assert_eq!(result.action, "press_key"); + assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 1); +} + +#[test] +fn only_a_plain_escape_answers_the_window_focus_refusal() { + let refusal = focus_refusal(&route("w-2")); + + assert!(is_focus_refusal(&refusal)); + assert!(answers_with_surface_close( + &key("escape", Vec::new()), + &refusal + )); + assert!(answers_with_surface_close( + &key("esc", Vec::new()), + &refusal + )); + assert!(!answers_with_surface_close(&key("a", Vec::new()), &refusal)); + assert!(!answers_with_surface_close( + &key("escape", vec![Modifier::Shift]), + &refusal + )); +} + +#[test] +fn a_window_press_that_is_not_a_plain_escape_keeps_its_refusal() { + let adapter = route("w-2"); + let error = press_for_window( + &adapter, + &window("w-1"), + &key("a", Vec::new()), + InteractionPolicy::headless(), + &lease(), + ) + .unwrap_err(); + + assert_eq!(error.code, ErrorCode::ActionFailed); + assert_eq!(error.details.unwrap()["check"], "window_active"); + assert_eq!(adapter.dispatched.load(Ordering::SeqCst), 0); +} + +#[test] +fn a_closed_surface_answers_the_refused_window_escape() { + let closed = delivery_result(semantic_step(CANCEL).with_verified(true)); + assert_eq!( + closed.disposition(), + DeliverySemantics::delivered_verified() + ); + + let answer = + answer_with_surface_close(focus_refusal(&route("w-2")), || Ok(Some(closed))).unwrap(); + assert_eq!( + answer.disposition(), + DeliverySemantics::delivered_verified() + ); + + let unread = delivery_result(semantic_step(CANCEL).with_verified(false)); + let answer = + answer_with_surface_close(focus_refusal(&route("w-2")), || Ok(Some(unread))).unwrap(); + assert_eq!( + answer.disposition(), + DeliverySemantics::delivered_unverified() + ); +} + +#[test] +fn a_refused_window_escape_keeps_the_refusal_when_no_surface_is_open() { + let answer = answer_with_surface_close(focus_refusal(&route("w-2")), || Ok(None)).unwrap_err(); + + assert!(is_focus_refusal(&answer)); + assert_eq!(answer.disposition, DeliverySemantics::not_delivered()); +} + +#[test] +fn a_surface_close_that_failed_keeps_its_own_error() { + let answer = answer_with_surface_close(focus_refusal(&route("w-2")), || { + Err(AdapterError::new(ErrorCode::ActionFailed, "cancel failed")) + }) + .unwrap_err(); + + assert_eq!(answer.message, "cancel failed"); +} + +#[derive(Default)] +struct SurfaceCalls { + discovered: Cell, + generations: Cell, + cancelled: Cell, +} + +struct SurfaceFixture { + discovery: Result, AdapterError>, + surface_pid: Result, + fail_generation_at: Option, + calls: SurfaceCalls, +} + +impl SurfaceFixture { + fn new(surface_pid: i32) -> Self { + Self { + discovery: Ok(Some(AXElement(std::ptr::null_mut()))), + surface_pid: Ok(surface_pid), + fail_generation_at: None, + calls: SurfaceCalls::default(), + } + } + + fn with_surface_pid(mut self, surface_pid: Result) -> Self { + self.surface_pid = surface_pid; + self + } + + fn failing_generation_at(mut self, call: usize) -> Self { + self.fail_generation_at = Some(call); + self + } +} + +impl WindowSurfaceClose for SurfaceFixture { + fn expected_identity( + &self, + window: &WindowInfo, + ) -> Result { + super::expected_window_identity(window) + } + + fn discover( + &self, + _identity: NativeProcessIdentity, + _window: &WindowInfo, + _deadline: Deadline, + ) -> Result, AdapterError> { + self.calls.discovered.set(self.calls.discovered.get() + 1); + self.discovery.clone() + } + + fn require_generation(&self, _identity: NativeProcessIdentity) -> Result<(), AdapterError> { + let call = self.calls.generations.get() + 1; + self.calls.generations.set(call); + if self.fail_generation_at == Some(call) { + return Err(AdapterError::stale_ref_because( + "Application process instance changed during observation", + )); + } + Ok(()) + } + + fn surface_pid(&self, _surface: &AXElement, _deadline: Deadline) -> Result { + self.surface_pid + } + + fn cancel(&self, _surface: &AXElement, _deadline: Deadline) -> Result { + self.calls.cancelled.set(self.calls.cancelled.get() + 1); + Ok(true) + } + + fn closed(&self, _surface: &AXElement, _deadline: Deadline) -> bool { + true + } +} + +fn current_identity() -> NativeProcessIdentity { + let pid = i32::try_from(std::process::id()).expect("test pid fits macOS pid_t"); + NativeProcessIdentity::capture(pid) + .expect("capture current process identity") + .expect("current process identity is present") +} + +fn window_with_instance(instance: Option<&str>) -> WindowInfo { + WindowInfo { + process_instance: instance.map(str::to_owned), + ..window("w-1") + } +} + +fn live_window() -> WindowInfo { + let token = current_identity().token(); + window_with_instance(Some(&token)) +} + +fn standard_deadline() -> Deadline { + Deadline::standard().unwrap() +} + +#[test] +fn an_unprovable_window_identity_fails_before_discovery() { + let cases = [ + ( + window_with_instance(None), + ErrorCode::StaleRef, + "Window has no process-instance identity", + ), + ( + window_with_instance(Some("")), + ErrorCode::StaleRef, + "Window has no process-instance identity", + ), + ( + window_with_instance(Some("macos-proc-v1:1:0")), + ErrorCode::AppUnresponsive, + "Target process instance is no longer running", + ), + ]; + for (window, code, message) in cases { + let fixture = SurfaceFixture::new(0); + let error = close_window_surface_with(&fixture, &window, standard_deadline()) + .expect_err("an unprovable identity must fail closed"); + + assert_eq!(error.code, code); + assert_eq!(error.message, message); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(fixture.calls.discovered.get(), 0); + assert_eq!(fixture.calls.cancelled.get(), 0); + } +} + +#[test] +fn a_stale_window_during_discovery_propagates_without_cancelling() { + let identity = current_identity(); + let mut fixture = SurfaceFixture::new(identity.pid()); + fixture.discovery = Err(AdapterError::stale_ref_because( + "Window 'w-1' identity mismatch", + )); + let error = close_window_surface_with(&fixture, &live_window(), standard_deadline()) + .expect_err("a stale window must not read as an absent surface"); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(fixture.calls.discovered.get(), 1); + assert_eq!(fixture.calls.cancelled.get(), 0); +} + +#[test] +fn a_generation_change_after_discovery_stops_the_cancel() { + for call in 1..=2 { + let identity = current_identity(); + let fixture = SurfaceFixture::new(identity.pid()).failing_generation_at(call); + let error = close_window_surface_with(&fixture, &live_window(), standard_deadline()) + .expect_err("a replaced process must stop the cancel"); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(fixture.calls.discovered.get(), 1); + assert_eq!(fixture.calls.generations.get(), call); + assert_eq!(fixture.calls.cancelled.get(), 0); + } +} + +#[test] +fn a_surface_owned_by_another_process_is_never_cancelled() { + let identity = current_identity(); + let fixture = SurfaceFixture::new(identity.pid() + 1); + let error = close_window_surface_with(&fixture, &live_window(), standard_deadline()) + .expect_err("a foreign surface must fail closed"); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!( + error.message, + "Surface no longer belongs to the target process" + ); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(fixture.calls.cancelled.get(), 0); +} + +#[test] +fn an_invalid_surface_before_the_cancel_fails_closed() { + let identity = current_identity(); + let fixture = SurfaceFixture::new(identity.pid()) + .with_surface_pid(Err(accessibility_sys::kAXErrorInvalidUIElement)); + let error = close_window_surface_with(&fixture, &live_window(), standard_deadline()) + .expect_err("an invalid surface must fail closed"); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.message, "Surface became invalid before cancel"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(fixture.calls.cancelled.get(), 0); +} + +#[test] +fn another_surface_read_failure_keeps_its_mapped_code() { + let identity = current_identity(); + let fixture = SurfaceFixture::new(identity.pid()) + .with_surface_pid(Err(accessibility_sys::kAXErrorCannotComplete)); + let error = close_window_surface_with(&fixture, &live_window(), standard_deadline()) + .expect_err("a failed surface read must fail closed"); + + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.details.as_ref().unwrap()["attribute"], "AXPid"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(fixture.calls.cancelled.get(), 0); +} + +#[test] +fn an_original_generation_surface_is_cancelled_and_verified() { + let identity = current_identity(); + let fixture = SurfaceFixture::new(identity.pid()); + let closed = close_window_surface_with(&fixture, &live_window(), standard_deadline()) + .unwrap() + .expect("a surface of the original generation closes"); + + assert_eq!(closed.action, "press_key"); + assert_eq!( + closed.disposition(), + DeliverySemantics::delivered_verified() + ); + assert_eq!(fixture.calls.generations.get(), 2); + assert_eq!(fixture.calls.cancelled.get(), 1); +} diff --git a/crates/macos/src/system/window/cg_window.rs b/crates/macos/src/system/window/cg_window.rs index 3d7e5bc04..d72e3fbf8 100644 --- a/crates/macos/src/system/window/cg_window.rs +++ b/crates/macos/src/system/window/cg_window.rs @@ -119,14 +119,29 @@ fn stabilize_records_until( } } -pub(in crate::system) fn records_from_dictionaries( +/// Whether the inventory lists a window. A normal-level window is listed on or +/// off screen. A floating, panel or utility window an application raises +/// itself (below the Dock level, 20), as accessory apps do, is listed while +/// on screen; off screen it is a hidden helper. System levels stay out. +fn lists_window(layer: i64, on_screen: bool) -> bool { + match layer { + 0 => true, + 1..DOCK_WINDOW_LEVEL => on_screen, + _ => false, + } +} + +const DOCK_WINDOW_LEVEL: i64 = 20; + +pub(crate) fn records_from_dictionaries( dictionaries: Vec, scope: WindowRecordScope<'_>, ) -> Result, AdapterError> { let mut records = Vec::new(); for dictionary in dictionaries { let layer = required_int_field(&dictionary, "kCGWindowLayer")?; - if layer != 0 { + let visible = bool_field(&dictionary, "kCGWindowIsOnscreen")?; + if !lists_window(layer, visible) { continue; } let pid = i32::try_from(required_int_field(&dictionary, "kCGWindowOwnerPID")?) @@ -156,7 +171,7 @@ pub(in crate::system) fn records_from_dictionaries( title: string_field(&dictionary, "kCGWindowName").filter(|title| !title.is_empty()), window_number, bounds, - visible: bool_field(&dictionary, "kCGWindowIsOnscreen")?, + visible, process_instance: None, }); } @@ -186,7 +201,7 @@ fn window_list_options() -> core_graphics::window::CGWindowListOption { | core_graphics::window::kCGWindowListExcludeDesktopElements } -pub(in crate::system) fn capture_process_instances( +pub(crate) fn capture_process_instances( records: &mut [WindowRecord], deadline: Deadline, ) -> Result<(), AdapterError> { @@ -242,7 +257,7 @@ fn inventory_signature(records: &[WindowRecord]) -> Vec Result<(), AdapterError> { +pub(crate) fn ensure_before_deadline(deadline: Deadline) -> Result<(), AdapterError> { if deadline.is_expired() { return Err(AdapterError::timeout( "CoreGraphics window inventory timed out", @@ -251,7 +266,7 @@ pub(in crate::system) fn ensure_before_deadline(deadline: Deadline) -> Result<() Ok(()) } -pub(in crate::system) fn inventory_error(message: &str) -> AdapterError { +pub(crate) fn inventory_error(message: &str) -> AdapterError { AdapterError::new(ErrorCode::AppUnresponsive, message) .with_suggestion("Retry after WindowServer finishes updating the window inventory") .with_details(serde_json::json!({ @@ -312,10 +327,7 @@ fn invalid_field_error(field: &str) -> AdapterError { )) } -pub(in crate::system) fn required_int_field( - dict: &WindowDictionary, - key: &str, -) -> Result { +pub(crate) fn required_int_field(dict: &WindowDictionary, key: &str) -> Result { int_field(dict, key).ok_or_else(|| missing_field_error(key)) } @@ -343,10 +355,7 @@ fn string_field(dict: &WindowDictionary, key: &str) -> Option { .map(|value| value.to_string()) } -pub(in crate::system) fn bool_field( - dict: &WindowDictionary, - key: &str, -) -> Result { +pub(crate) 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/cg_window_tests.rs b/crates/macos/src/system/window/cg_window_tests.rs index 84d5733c5..b8881420c 100644 --- a/crates/macos/src/system/window/cg_window_tests.rs +++ b/crates/macos/src/system/window/cg_window_tests.rs @@ -373,3 +373,16 @@ fn persistent_capture_failure_is_not_window_churn() { "core_graphics_windows" ); } + +#[test] +fn a_raised_app_window_is_listed_only_while_on_screen() { + assert!(lists_window(0, true)); + assert!(lists_window(0, false)); + for raised in [3, 5, 8, 19] { + assert!(lists_window(raised, true), "{raised}"); + assert!(!lists_window(raised, false), "{raised}"); + } + for system in [-2147483624, -1, 20, 24, 25, 101, 2147483630] { + assert!(!lists_window(system, true), "{system}"); + } +} diff --git a/crates/macos/src/tree/adapter.rs b/crates/macos/src/tree/adapter.rs index f1636c81e..a6094491e 100644 --- a/crates/macos/src/tree/adapter.rs +++ b/crates/macos/src/tree/adapter.rs @@ -115,16 +115,19 @@ impl ObservationOps for MacOSAdapter { raised_by: &NativeHandle, deadline: Deadline, ) -> Result, AdapterError> { - let mut surfaces = self.list_surfaces(process, deadline)?; + let mut anchored = Vec::new(); #[cfg(target_os = "macos")] if let Ok(anchor) = ax_element(raised_by) { crate::tree::surface_inventory::collect_anchored_surfaces( anchor, deadline, - &mut surfaces, + &mut anchored, ); } - Ok(surfaces) + crate::tree::surface_inventory::with_anchored( + self.list_surfaces(process, deadline), + anchored, + ) } fn hit_test( diff --git a/crates/macos/src/tree/app_menu.rs b/crates/macos/src/tree/app_menu.rs index 19eb6637e..0819baac2 100644 --- a/crates/macos/src/tree/app_menu.rs +++ b/crates/macos/src/tree/app_menu.rs @@ -20,7 +20,7 @@ pub(crate) fn observe( }) } -fn require_generation( +pub(crate) fn require_generation( identity: crate::system::process::process_identity::ProcessIdentity, ) -> Result<(), AdapterError> { if identity.still_matches()? { @@ -113,6 +113,14 @@ fn menu_element_for_pid(pid: i32, deadline: Deadline) -> Result Result, AdapterError> { + open_menus_for_pid_until(pid, Transient::Menu, deadline) +} + +fn open_menus_for_pid_until( + pid: i32, + accept: Transient, + deadline: Deadline, ) -> Result, AdapterError> { let mut menus = Vec::new(); if let Some(menubar) = menubar_for_pid(pid, deadline)? { @@ -131,13 +139,35 @@ pub(crate) fn open_menus_for_pid( ); } if menus.is_empty() - && let Some((id, menu)) = context_menu_from_app(pid, deadline)? + && let Some((id, menu)) = surface_from_app(pid, accept, deadline)? { menus.push(("context_menu", id, menu)); } Ok(menus) } +/// What a search below the application accepts as the open transient surface. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Transient { + Menu, + MenuOrPopover, +} + +/// The menu or popover the application shows, in one pass: an open menu bar +/// menu first, then the bounded search below the application. +#[cfg(target_os = "macos")] +pub(crate) fn open_transient_surface( + pid: i32, + deadline: Deadline, +) -> Result, AdapterError> { + Ok( + open_menus_for_pid_until(pid, Transient::MenuOrPopover, deadline)? + .into_iter() + .next() + .map(|(_, _, surface)| surface), + ) +} + fn open_menubar_menus_with( menubar: &T, mut children: impl FnMut(&T) -> Result, AdapterError>, @@ -162,8 +192,9 @@ fn open_menubar_menus_with( } #[cfg(target_os = "macos")] -fn context_menu_from_app( +fn surface_from_app( pid: i32, + accept: Transient, deadline: Deadline, ) -> Result, AdapterError> { let app = element_for_pid(pid); @@ -176,7 +207,8 @@ fn context_menu_from_app( } } if let Some(focused) = surface_read::element(&app, "AXFocusedUIElement", deadline)? - && let Some(menu) = find_menu_descendant(focused, "app/focused-element".into(), deadline)? + && let Some(menu) = + find_menu_descendant(focused, "app/focused-element".into(), accept, deadline)? { return Ok(Some(menu)); } @@ -184,7 +216,8 @@ fn context_menu_from_app( .into_iter() .enumerate() { - if let Some(menu) = find_menu_descendant(child, format!("app/children/{index}"), deadline)? + if let Some(menu) = + find_menu_descendant(child, format!("app/children/{index}"), accept, deadline)? { return Ok(Some(menu)); } @@ -192,22 +225,60 @@ fn context_menu_from_app( Ok(None) } +/// How far a surface search opens the elements below its root. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum ChildExpansion { + /// A menu hangs directly below the element that shows it, so an element + /// with more than `ANCHOR_CHILD_LIMIT` children is a content container and + /// stays closed: reading its items made the search grow with the content + /// of every window. + AnchorsOnly, + /// A popover can hang below a control inside a list or a table row, so + /// every element is opened. `MAX_SURFACE_NODES` and the deadline still + /// bound the search, and reaching the limit is reported as incomplete. + EveryNode, +} + +impl ChildExpansion { + fn opens(self, children: usize) -> bool { + match self { + Self::AnchorsOnly => children <= super::surface_inventory::ANCHOR_CHILD_LIMIT, + Self::EveryNode => true, + } + } +} + #[cfg(target_os = "macos")] -fn find_menu_descendant( +pub(super) fn find_menu_descendant( root: AXElement, source: String, + accept: Transient, deadline: Deadline, ) -> Result, AdapterError> { - find_menu_descendant_with(root, source, deadline, |element| { + let expansion = match accept { + Transient::Menu => ChildExpansion::AnchorsOnly, + Transient::MenuOrPopover => ChildExpansion::EveryNode, + }; + find_surface_descendant_with(root, source, expansion, deadline, |element, expand| { let role = surface_read::string(element, "AXRole", deadline)?; if role.as_deref() == Some("AXMenuBar") { return Ok((false, Vec::new())); } + if accept == Transient::MenuOrPopover + && (role.as_deref() == Some("AXPopover") + || surface_read::string(element, "AXSubrole", deadline)?.as_deref() + == Some("AXPopover")) + { + return Ok((true, Vec::new())); + } if role.as_deref() == Some("AXMenu") && surface_read::boolean(element, "AXVisible", deadline)? != Some(false) { return Ok((true, Vec::new())); } + if !expand { + return Ok((false, Vec::new())); + } Ok(( false, surface_read::elements(element, "AXChildren", deadline)?, @@ -215,22 +286,28 @@ fn find_menu_descendant( }) } -fn find_menu_descendant_with( +/// Breadth-first search below `root` for a transient surface: a menu, or a +/// popover. `expansion` decides how far the search opens the tree, because a +/// menu and a popover hang differently: a menu sits directly below its anchor, +/// while a popover can sit below a control inside a list or a table row. +/// `inspect` gets whether it may return the element's children. +pub(super) fn find_surface_descendant_with( root: T, source: String, + expansion: ChildExpansion, deadline: Deadline, - mut inspect: impl FnMut(&T) -> Result<(bool, Vec), AdapterError>, + mut inspect: impl FnMut(&T, bool) -> Result<(bool, Vec), AdapterError>, ) -> Result, AdapterError> { - let mut pending = std::collections::VecDeque::from([(source, root)]); + let mut pending = std::collections::VecDeque::from([(source, root, true)]); let mut incomplete = None; let mut visited = 0_usize; - while let Some((path, element)) = pending.pop_front() { + while let Some((path, element, expand)) = pending.pop_front() { surface_read::ensure_before_deadline(deadline)?; visited += 1; if visited > MAX_SURFACE_NODES { return Err(surface_limit_error()); } - let (is_menu, children) = match inspect(&element) { + let (is_menu, children) = match inspect(&element, expand) { Ok(observed) => observed, Err(error) if error.code == ErrorCode::AppUnresponsive && !invalidated(&error) => { incomplete.get_or_insert(error); @@ -241,11 +318,12 @@ fn find_menu_descendant_with( if is_menu { return Ok(Some((path, element))); } + let expand_children = expansion.opens(children.len()); pending.extend( children .into_iter() .enumerate() - .map(|(index, child)| (format!("{path}/children/{index}"), child)), + .map(|(index, child)| (format!("{path}/children/{index}"), child, expand_children)), ); } incomplete.map_or(Ok(None), Err) @@ -273,6 +351,15 @@ fn invalid_root_error() -> AdapterError { })) } +/// Whether a surface search stopped at its node budget, which means a surface +/// may still sit below the cut rather than being absent. +pub(crate) fn is_surface_search_limit(error: &AdapterError) -> bool { + error + .details + .as_ref() + .is_some_and(|details| details["kind"] == "surface_search_limit") +} + fn surface_limit_error() -> AdapterError { AdapterError::new( ErrorCode::AppUnresponsive, @@ -290,3 +377,7 @@ fn surface_limit_error() -> AdapterError { #[cfg(test)] #[path = "app_menu_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "app_menu_search_tests.rs"] +mod search_tests; diff --git a/crates/macos/src/tree/app_menu_search_tests.rs b/crates/macos/src/tree/app_menu_search_tests.rs new file mode 100644 index 000000000..a3ff18ef4 --- /dev/null +++ b/crates/macos/src/tree/app_menu_search_tests.rs @@ -0,0 +1,246 @@ +use super::*; +use agent_desktop_core::Deadline; + +#[test] +fn surface_node_limit_is_explicitly_incomplete() { + let error = surface_limit_error(); + + assert_eq!(error.code, ErrorCode::AppUnresponsive); + assert_eq!(error.details.expect("limit details")["complete"], false); +} + +#[test] +fn menus_beyond_eight_wrappers_remain_discoverable() { + let deadline = Deadline::after(5000).unwrap(); + for target_depth in [9, 11, 30] { + let found = find_surface_descendant_with( + 0, + "app".into(), + ChildExpansion::AnchorsOnly, + deadline, + |depth, _| Ok((*depth == target_depth, vec![depth + 1])), + ) + .unwrap(); + assert_eq!(found.map(|(_, node)| node), Some(target_depth)); + } +} + +#[test] +fn cyclic_menu_search_remains_bounded_and_explicitly_incomplete() { + let mut reads = 0; + let error = find_surface_descendant_with( + 0, + "app".into(), + ChildExpansion::AnchorsOnly, + Deadline::after(5000).unwrap(), + |node, _| { + reads += 1; + Ok((false, vec![*node])) + }, + ) + .unwrap_err(); + assert_eq!(reads, MAX_SURFACE_NODES); + assert_eq!(error.details.unwrap()["complete"], false); +} + +#[test] +fn expired_menu_search_never_reads_a_node() { + let result = find_surface_descendant_with::<()>( + (), + "app".into(), + ChildExpansion::AnchorsOnly, + Deadline::after(0).unwrap(), + |_, _| panic!("expired search must not call AX"), + ); + assert_eq!(result.unwrap_err().code, ErrorCode::Timeout); +} + +#[test] +fn incomplete_content_branch_does_not_hide_a_menu_in_a_sibling() { + let result = find_surface_descendant_with( + 0, + "app".into(), + ChildExpansion::AnchorsOnly, + Deadline::after(5000).unwrap(), + |node, _| match node { + 0 => Ok((false, vec![1, 2])), + 1 => Err(surface_limit_error()), + 2 => Ok((true, vec![])), + _ => unreachable!(), + }, + ); + assert_eq!(result.unwrap(), Some(("app/children/1".into(), 2))); +} + +#[test] +fn an_incomplete_branch_cannot_prove_menu_absence() { + let result = find_surface_descendant_with( + 0, + "app".into(), + ChildExpansion::AnchorsOnly, + Deadline::after(5000).unwrap(), + |node, _| match node { + 0 => Ok((false, vec![1, 2])), + 1 => Err(surface_limit_error()), + _ => Ok((false, vec![])), + }, + ); + assert_eq!(result.unwrap_err().details.unwrap()["complete"], false); +} + +#[test] +fn shallow_menu_precedes_unbounded_content_and_permission_errors_stay_terminal() { + let deadline = Deadline::after(5000).unwrap(); + let found = find_surface_descendant_with( + 0, + "app".into(), + ChildExpansion::AnchorsOnly, + deadline, + |node, _| match node { + 0 => Ok((false, vec![1, 2])), + 1 => Ok((false, vec![1])), + _ => Ok((true, vec![])), + }, + ); + assert_eq!(found.unwrap(), Some(("app/children/1".into(), 2))); + let denied = find_surface_descendant_with( + 0, + "app".into(), + ChildExpansion::AnchorsOnly, + deadline, + |node, _| match node { + 0 => Ok((false, vec![1, 2])), + 1 => Err(AdapterError::new(ErrorCode::PermDenied, "denied")), + _ => panic!("permission failure must stop all further AX reads"), + }, + ); + assert_eq!(denied.unwrap_err().code, ErrorCode::PermDenied); +} + +#[test] +fn invalidated_menu_roots_are_reacquired_once_and_permission_errors_are_terminal() { + use accessibility_sys::{kAXErrorAPIDisabled, kAXErrorInvalidUIElement}; + for (ax_error, failures) in [ + (kAXErrorInvalidUIElement, 1), + (kAXErrorInvalidUIElement, 2), + (kAXErrorAPIDisabled, 1), + ] { + let mut reads = 0; + let result = reacquire_once(Deadline::after(1000).unwrap(), &mut false, || { + reads += 1; + if reads <= failures { + Err(AdapterError::new(ErrorCode::PermDenied, "read failed") + .with_details(serde_json::json!({ "ax_error": ax_error }))) + } else { + Ok("fresh root") + } + }); + if ax_error == kAXErrorAPIDisabled { + assert_eq!(reads, 1); + assert_eq!(result.unwrap_err().code, ErrorCode::PermDenied); + } else { + assert_eq!(reads, 2); + if failures == 1 { + assert_eq!(result.unwrap(), "fresh root"); + } else { + let error = result.unwrap_err(); + assert_eq!(error.code, ErrorCode::AppUnresponsive); + let details = error.details.unwrap(); + assert_eq!(details["complete"], false); + assert_eq!(details["menu_root_reacquired"], true); + assert_eq!(details["retryable"], false); + assert_eq!(details["ax_error"], kAXErrorInvalidUIElement); + } + } + } +} + +#[test] +fn the_items_of_a_content_container_are_checked_but_not_opened() { + let deadline = Deadline::after(5000).unwrap(); + let wide = super::super::surface_inventory::ANCHOR_CHILD_LIMIT + 1; + let mut opened = Vec::new(); + let found = find_surface_descendant_with( + 0_usize, + "app".into(), + ChildExpansion::AnchorsOnly, + deadline, + |node, expand| { + if expand { + opened.push(*node); + } + Ok(match *node { + 0 => (false, vec![1, 2]), + 1 => (false, (100..100 + wide).collect()), + 2 => (false, vec![3]), + 3 => (true, vec![]), + item if item >= 100 => (false, vec![item * 10]), + _ => (false, vec![]), + }) + }, + ) + .unwrap(); + + assert_eq!(found.map(|(_, node)| node), Some(3)); + assert!(opened.iter().all(|node| *node < 100)); +} + +#[test] +fn a_menu_among_the_items_of_a_content_container_is_still_found() { + let deadline = Deadline::after(5000).unwrap(); + let wide = super::super::surface_inventory::ANCHOR_CHILD_LIMIT + 1; + let found = find_surface_descendant_with( + 0_usize, + "app".into(), + ChildExpansion::AnchorsOnly, + deadline, + |node, _| { + Ok(match *node { + 0 => (false, (100..100 + wide).collect()), + node => (node == 100 + wide - 1, vec![]), + }) + }, + ) + .unwrap(); + + assert_eq!(found.map(|(_, node)| node), Some(100 + wide - 1)); +} + +#[test] +fn a_popover_anchored_inside_wide_content_is_reached_only_when_every_node_is_opened() { + let deadline = Deadline::after(5000).unwrap(); + let wide = super::super::surface_inventory::ANCHOR_CHILD_LIMIT + 1; + let popover = (100 + wide - 1) * 10; + let locate = |expansion: ChildExpansion| { + find_surface_descendant_with( + 0_usize, + "app".into(), + expansion, + deadline, + |node, expand| { + Ok(match *node { + 0 => (false, vec![1]), + 1 => (false, (100..100 + wide).collect()), + item if item == popover => (true, vec![]), + item if item >= 100 => { + (false, if expand { vec![item * 10] } else { Vec::new() }) + } + _ => (false, vec![]), + }) + }, + ) + .unwrap() + }; + + assert_eq!( + locate(ChildExpansion::EveryNode), + Some(( + format!("app/children/0/children/{}/children/0", wide - 1), + popover + )) + ); + assert_eq!( + locate(ChildExpansion::AnchorsOnly).map(|(_, node)| node), + None + ); +} diff --git a/crates/macos/src/tree/app_menu_tests.rs b/crates/macos/src/tree/app_menu_tests.rs index bd8d807d9..7c5393727 100644 --- a/crates/macos/src/tree/app_menu_tests.rs +++ b/crates/macos/src/tree/app_menu_tests.rs @@ -221,131 +221,3 @@ fn incomplete_selected_menu_children_cannot_produce_an_empty_or_partial_inventor .unwrap_err(); assert_eq!(error.details.unwrap()["complete"], false); } - -#[test] -fn surface_node_limit_is_explicitly_incomplete() { - let error = surface_limit_error(); - - assert_eq!(error.code, ErrorCode::AppUnresponsive); - assert_eq!(error.details.expect("limit details")["complete"], false); -} - -#[test] -fn menus_beyond_eight_wrappers_remain_discoverable() { - let deadline = Deadline::after(5000).unwrap(); - for target_depth in [9, 11, 30] { - let found = find_menu_descendant_with(0, "app".into(), deadline, |depth| { - Ok((*depth == target_depth, vec![depth + 1])) - }) - .unwrap(); - assert_eq!(found.map(|(_, node)| node), Some(target_depth)); - } -} - -#[test] -fn cyclic_menu_search_remains_bounded_and_explicitly_incomplete() { - let mut reads = 0; - let error = - find_menu_descendant_with(0, "app".into(), Deadline::after(5000).unwrap(), |node| { - reads += 1; - Ok((false, vec![*node])) - }) - .unwrap_err(); - assert_eq!(reads, MAX_SURFACE_NODES); - assert_eq!(error.details.unwrap()["complete"], false); -} - -#[test] -fn expired_menu_search_never_reads_a_node() { - let result = - find_menu_descendant_with::<()>((), "app".into(), Deadline::after(0).unwrap(), |_| { - panic!("expired search must not call AX") - }); - assert_eq!(result.unwrap_err().code, ErrorCode::Timeout); -} - -#[test] -fn incomplete_content_branch_does_not_hide_a_menu_in_a_sibling() { - let result = find_menu_descendant_with( - 0, - "app".into(), - Deadline::after(5000).unwrap(), - |node| match node { - 0 => Ok((false, vec![1, 2])), - 1 => Err(surface_limit_error()), - 2 => Ok((true, vec![])), - _ => unreachable!(), - }, - ); - assert_eq!(result.unwrap(), Some(("app/children/1".into(), 2))); -} - -#[test] -fn an_incomplete_branch_cannot_prove_menu_absence() { - let result = find_menu_descendant_with( - 0, - "app".into(), - Deadline::after(5000).unwrap(), - |node| match node { - 0 => Ok((false, vec![1, 2])), - 1 => Err(surface_limit_error()), - _ => Ok((false, vec![])), - }, - ); - assert_eq!(result.unwrap_err().details.unwrap()["complete"], false); -} - -#[test] -fn shallow_menu_precedes_unbounded_content_and_permission_errors_stay_terminal() { - let deadline = Deadline::after(5000).unwrap(); - let found = find_menu_descendant_with(0, "app".into(), deadline, |node| match node { - 0 => Ok((false, vec![1, 2])), - 1 => Ok((false, vec![1])), - _ => Ok((true, vec![])), - }); - assert_eq!(found.unwrap(), Some(("app/children/1".into(), 2))); - let denied = find_menu_descendant_with(0, "app".into(), deadline, |node| match node { - 0 => Ok((false, vec![1, 2])), - 1 => Err(AdapterError::new(ErrorCode::PermDenied, "denied")), - _ => panic!("permission failure must stop all further AX reads"), - }); - assert_eq!(denied.unwrap_err().code, ErrorCode::PermDenied); -} - -#[test] -fn invalidated_menu_roots_are_reacquired_once_and_permission_errors_are_terminal() { - use accessibility_sys::{kAXErrorAPIDisabled, kAXErrorInvalidUIElement}; - for (ax_error, failures) in [ - (kAXErrorInvalidUIElement, 1), - (kAXErrorInvalidUIElement, 2), - (kAXErrorAPIDisabled, 1), - ] { - let mut reads = 0; - let result = reacquire_once(Deadline::after(1000).unwrap(), &mut false, || { - reads += 1; - if reads <= failures { - Err(AdapterError::new(ErrorCode::PermDenied, "read failed") - .with_details(serde_json::json!({ "ax_error": ax_error }))) - } else { - Ok("fresh root") - } - }); - if ax_error == kAXErrorAPIDisabled { - assert_eq!(reads, 1); - assert_eq!(result.unwrap_err().code, ErrorCode::PermDenied); - } else { - assert_eq!(reads, 2); - if failures == 1 { - assert_eq!(result.unwrap(), "fresh root"); - } else { - let error = result.unwrap_err(); - assert_eq!(error.code, ErrorCode::AppUnresponsive); - let details = error.details.unwrap(); - assert_eq!(details["complete"], false); - assert_eq!(details["menu_root_reacquired"], true); - assert_eq!(details["retryable"], false); - assert_eq!(details["ax_error"], kAXErrorInvalidUIElement); - } - } - } -} diff --git a/crates/macos/src/tree/surface_inventory.rs b/crates/macos/src/tree/surface_inventory.rs index 4e8dc520e..fb1194382 100644 --- a/crates/macos/src/tree/surface_inventory.rs +++ b/crates/macos/src/tree/surface_inventory.rs @@ -1,7 +1,9 @@ use crate::tree::{AXElement, properties::element::element_for_pid}; use agent_desktop_core::{AdapterError, Deadline, SurfaceInfo}; -const ANCHOR_CHILD_LIMIT: usize = 16; +/// The most children an element that anchors a surface has. An element with +/// more is a content container: a list, a table or a column of a browser. +pub(crate) const ANCHOR_CHILD_LIMIT: usize = 16; pub(crate) fn list_surfaces_for_process( identity: crate::system::process::process_identity::ProcessIdentity, @@ -89,6 +91,24 @@ pub(crate) fn collect_anchored_surfaces( } } +/// The surfaces an action raised: the application's inventory, then the ones +/// hanging below the element the action targeted. Those are read first and +/// cost a few reads, so an inventory that fails does not hide them; the +/// failure is returned only when no anchored surface was found. +pub(crate) fn with_anchored( + inventory: Result, AdapterError>, + anchored: Vec, +) -> Result, AdapterError> { + match inventory { + Ok(mut surfaces) => { + surfaces.extend(anchored); + Ok(surfaces) + } + Err(error) if anchored.is_empty() => Err(error), + Err(_) => Ok(anchored), + } +} + fn anchors_few_children(count: Option) -> bool { count.is_some_and(|count| (1..=ANCHOR_CHILD_LIMIT).contains(&count)) } diff --git a/crates/macos/src/tree/surface_inventory_tests.rs b/crates/macos/src/tree/surface_inventory_tests.rs index fd267b267..6ceda9965 100644 --- a/crates/macos/src/tree/surface_inventory_tests.rs +++ b/crates/macos/src/tree/surface_inventory_tests.rs @@ -85,6 +85,26 @@ fn only_a_control_with_few_children_is_read_for_an_anchored_surface() { assert!(!anchors_few_children(None)); } +#[test] +fn a_failed_inventory_does_not_hide_the_surface_below_the_target() { + let failed = || Err(agent_desktop_core::AdapterError::timeout("inventory")); + + let kept = + super::with_anchored(failed(), vec![surface("target/children/0", "popover")]).unwrap(); + assert_eq!(kept.len(), 1); + assert!(super::with_anchored(failed(), Vec::new()).is_err()); + + let both = super::with_anchored( + Ok(vec![surface("menu", "menu")]), + vec![surface("target", "popover")], + ) + .unwrap(); + assert_eq!( + both.iter().map(|s| s.id.as_str()).collect::>(), + ["menu", "target"] + ); +} + #[test] fn a_dialog_style_window_is_an_alert_only_when_it_is_modal_and_on_screen() { assert_eq!( diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rs index ba4f951c3..e1500aa55 100644 --- a/crates/macos/src/tree/surfaces.rs +++ b/crates/macos/src/tree/surfaces.rs @@ -1,8 +1,7 @@ use super::{AXElement, properties::element::element_for_pid, surface_read}; -use agent_desktop_core::{AdapterError, Deadline, ErrorCode, SnapshotSurface}; +use agent_desktop_core::{AdapterError, Deadline, ErrorCode, SnapshotSurface, WindowInfo}; -#[cfg(target_os = "macos")] -const POPOVER_SEARCH_LIMIT: usize = 4_096; +use crate::system::process::process_identity::ProcessIdentity; #[cfg(target_os = "macos")] pub(crate) fn focused_surface_for_pid( @@ -25,6 +24,54 @@ pub(crate) fn menu_element_for_pid( }) } +/// The menu or popover the application shows, read in one bounded pass. +#[cfg(target_os = "macos")] +pub(crate) fn transient_surface_for_process( + identity: ProcessIdentity, + deadline: Deadline, +) -> Result, AdapterError> { + super::app_menu::observe(identity, deadline, || { + super::app_menu::open_transient_surface(identity.pid(), deadline) + }) +} + +/// The menu or popover that belongs to `window`, read in one bounded pass: a +/// surface inside that window first, then the application's own surfaces, so a +/// surface in a window that is not focused is still found. +#[cfg(target_os = "macos")] +pub(crate) fn transient_surface_for_window( + identity: ProcessIdentity, + window: &WindowInfo, + deadline: Deadline, +) -> Result, AdapterError> { + super::app_menu::observe(identity, deadline, || { + if let Some(surface) = surface_inside_window(window, deadline)? { + return Ok(Some(surface)); + } + super::app_menu::require_generation(identity)?; + super::app_menu::open_transient_surface(identity.pid(), deadline) + }) +} + +/// The menu or popover inside `window`, searched at any depth because a +/// popover hangs below the control that raised it. +#[cfg(target_os = "macos")] +fn surface_inside_window( + window: &WindowInfo, + deadline: Deadline, +) -> Result, AdapterError> { + let owner = crate::system::window::window_resolve::window_element_for_info_with_deadline( + window, deadline, + )?; + Ok(super::app_menu::find_menu_descendant( + owner, + "window".into(), + super::app_menu::Transient::MenuOrPopover, + deadline, + )? + .map(|(_, surface)| surface)) +} + #[cfg(target_os = "macos")] fn first_child_with_role_or_subrole( pid: i32, @@ -60,38 +107,53 @@ pub(crate) fn surface_in_window( } } -/// The first popover in `window`, nearest the window first. None only when -/// every element was read: a search cut at `POPOVER_SEARCH_LIMIT` elements -/// fails as not found and says it is incomplete. +/// The first popover in `window`, nearest the window first, through a search +/// that opens every element below it, so a popover anchored to a control inside +/// a list or a table row is reached. None only when the search read every +/// element: one cut at its element limit fails as not found and says it is +/// incomplete. #[cfg(target_os = "macos")] fn popover_in_window( window: &AXElement, deadline: Deadline, ) -> Result, AdapterError> { - let mut level = vec![window.clone()]; - let mut searched = 0; - while !level.is_empty() { - let mut below = Vec::new(); - for element in level { - if role_or_subrole_matches(&element, "AXPopover", deadline)? { - return Ok(Some(element)); + let found = super::app_menu::find_surface_descendant_with( + window.clone(), + "window".into(), + super::app_menu::ChildExpansion::EveryNode, + deadline, + |element, _| { + if role_or_subrole_matches(element, "AXPopover", deadline)? { + return Ok((true, Vec::new())); } - searched += 1; - if searched >= POPOVER_SEARCH_LIMIT { - return Err(AdapterError::new( - ErrorCode::ElementNotFound, - format!("No popover among the first {searched} elements of the window; the rest was not searched"), - ) - .with_details(serde_json::json!({ - "kind": "popover_search_limit", - "complete": false, - }))); - } - below.extend(surface_read::elements(&element, "AXChildren", deadline)?); - } - level = below; + Ok(( + false, + surface_read::elements(element, "AXChildren", deadline)?, + )) + }, + ) + .map_err(popover_search_error)?; + Ok(found.map(|(_, popover)| popover)) +} + +fn popover_search_error(error: AdapterError) -> AdapterError { + if !super::app_menu::is_surface_search_limit(&error) { + return error; } - Ok(None) + popover_search_cut() +} + +/// A popover search that did not read every element: it reached its element +/// limit first, and a popover may sit below that cut. +fn popover_search_cut() -> AdapterError { + AdapterError::new( + ErrorCode::ElementNotFound, + "No popover among the elements the search read; the search reached its element limit first", + ) + .with_details(serde_json::json!({ + "kind": "popover_search_limit", + "complete": false, + })) } #[cfg(target_os = "macos")] diff --git a/crates/windows/src/system/adapter.rs b/crates/windows/src/system/adapter.rs index e52db5a67..9f40bbc31 100644 --- a/crates/windows/src/system/adapter.rs +++ b/crates/windows/src/system/adapter.rs @@ -10,6 +10,7 @@ use agent_desktop_core::{ }; use crate::adapter::WindowsAdapter; +use crate::system::escape_popup; #[cfg(target_os = "windows")] #[path = "tcp_listener.rs"] @@ -103,17 +104,10 @@ impl SystemOps for WindowsAdapter { true } - /// The surfaces this adapter can observe: a named window, the focused - /// window, a Chromium modal-as-sheet, an open application menu, and the - /// shell kinds the shell-surface resolver reaches on this build. Core - /// validates the requested surface against this list before the adapter - /// is ever called (the mirror of macOS `supported_surfaces`), so a kind - /// advertised here always has a matching `surface_root` arm - advertising - /// without an arm would convert the old emit/advertise asymmetry into an - /// advertise/resolve one. `quick-settings` is deliberately absent: this - /// build carries the quick actions inside the Action Center, so the kind - /// refuses in core with the standard shape instead of pretending it can - /// root. + /// The surfaces this adapter can observe. Core validates a requested + /// surface against this list before calling the adapter, so every kind here + /// has a matching `surface_root` arm; `quick-settings` is absent because + /// this build carries the quick actions inside the Action Center. fn supported_surfaces(&self) -> Vec { vec![ SnapshotSurface::Window, @@ -145,10 +139,8 @@ impl SystemOps for WindowsAdapter { crate::system::shell::shell_surface_open::open_surface(surface, policy, lease.deadline()) } - /// The focused window is the focused-only filter's first result, composed - /// from `list_windows` rather than a second native path (mirroring - /// `focused_window` in `crates/macos/src/system/adapter.rs`). Whatever HWND-shape a - /// host presents, it maps to the same identity `list_windows` reports. + /// The focused-only filter's first result over `list_windows`, as on macOS, + /// so any HWND shape maps to the identity `list_windows` reports. fn focused_window(&self, deadline: Deadline) -> Result, AdapterError> { let filter = WindowFilter { focused_only: true, @@ -277,9 +269,7 @@ impl SystemOps for WindowsAdapter { crate::system::capture::screenshot::capture_window(window, deadline) } - /// Verify-only composition over the keyboard primitive. Core's headed - /// path already activated; this never raises (A9-3: SendInput has no - /// per-pid targeting). + /// Key delivery, then `escape_popup` for a refused Escape (A9-3). fn press_key_for_app( &self, process: ProcessIdentity, @@ -287,7 +277,17 @@ impl SystemOps for WindowsAdapter { policy: InteractionPolicy, lease: &InteractionLease, ) -> Result { - crate::system::key_dispatch::press_for_app_impl(process, combo, policy, lease.deadline()) + escape_popup::press_for_app(process, combo, policy, lease.deadline()) + } + + fn press_key_for_window( + &self, + window: &WindowInfo, + combo: &KeyCombo, + policy: InteractionPolicy, + lease: &InteractionLease, + ) -> Result { + escape_popup::press_for_window(self, window, combo, policy, lease) } /// The core default blocks nothing; Windows ships its own dangerous-combo diff --git a/crates/windows/src/system/escape_popup.rs b/crates/windows/src/system/escape_popup.rs new file mode 100644 index 000000000..aca4866c8 --- /dev/null +++ b/crates/windows/src/system/escape_popup.rs @@ -0,0 +1,272 @@ +//! Escape for an open popup when the key route refused for focus. +//! +//! The key route needs the target to hold the keyboard. A popup a person +//! opened (a menu, a drop-down, a split-button list) can sit in a window that +//! is not the foreground window, and the key is then refused. The popup still +//! has a semantic close: `ExpandCollapsePattern.Collapse` on its owner. The +//! states, in this order: the key route delivers, unchanged; it refuses for +//! focus and the target shows an open popup, whose owner is collapsed and read +//! back; otherwise the refusal stays as it was. + +use agent_desktop_core::{AdapterError, Deadline, DeliverySemantics, ErrorCode, KeyCombo}; + +#[cfg(any(target_os = "windows", test))] +pub(super) const MAX_POPUP_ROOTS: usize = 32; +#[cfg(any(target_os = "windows", test))] +pub(super) const MAX_POPUP_NODES: usize = 600; +#[cfg(any(target_os = "windows", test))] +pub(super) const MAX_POPUP_DEPTH: usize = 32; +#[cfg(any(target_os = "windows", test))] +pub(super) const MAX_POPUP_CHILDREN: usize = 64; + +/// Outcome of a bounded background-Escape popup scan. +#[cfg(any(target_os = "windows", test))] +#[derive(Debug, PartialEq, Eq)] +pub(super) enum PopupScan { + Found(N), + None, + TimedOut, +} + +/// Incremental tree reader used by [`scan_popup_owners`] so the bounded walk +/// is tested without live UI Automation. +#[cfg(any(target_os = "windows", test))] +pub(super) trait PopupTree { + type Node; + + fn is_open_popup_owner(&self, node: &Self::Node) -> bool; + fn first_child(&self, node: &Self::Node) -> Option; + fn next_sibling(&self, node: &Self::Node) -> Option; +} + +#[cfg(any(target_os = "windows", test))] +pub(super) fn scan_timeout_error(deadline: Deadline) -> AdapterError { + deadline + .timeout_error() + .with_disposition(DeliverySemantics::not_delivered()) +} + +/// Verifies that `window` still names a live handle owned by the stored process +/// generation, failing closed as not delivered when the handle is malformed, +/// lacks a process-instance token, or no longer matches its owner. +#[cfg(any(target_os = "windows", test))] +pub(super) fn verify_window_target( + window: &agent_desktop_core::WindowInfo, +) -> Result { + if window.is_process_owner() { + return Err(AdapterError::app_has_no_window(&window.app) + .with_disposition(DeliverySemantics::not_delivered())); + } + let handle = crate::system::window::window_ops::parse_handle(&window.id); + if handle.is_null() { + return Err(AdapterError::new( + ErrorCode::InvalidArgs, + "window id is not a Windows HWND-shaped id", + ) + .with_disposition(DeliverySemantics::not_delivered())); + } + let Some(evidence) = + crate::system::window::window_identity::WindowIdentityEvidence::from_info(handle, window) + else { + return Err(AdapterError::new( + ErrorCode::StaleRef, + "popup dismissal requires a process-instance token on the stored window", + ) + .with_disposition(DeliverySemantics::not_delivered())); + }; + evidence + .verify_stored() + .map_err(|error| error.with_disposition(DeliverySemantics::not_delivered()))?; + Ok(handle) +} + +/// Verifies that `process` still names the same running process generation, +/// failing closed as not delivered when the process exited or its pid recycled. +#[cfg(any(target_os = "windows", test))] +pub(super) fn verify_process_target( + process: &agent_desktop_core::ProcessIdentity, +) -> Result<(), AdapterError> { + if crate::system::process_identity::matches_instance(process.pid, &process.instance)? { + return Ok(()); + } + Err(AdapterError::new( + ErrorCode::AppUnresponsive, + "Target process instance is no longer running", + ) + .with_details(serde_json::json!({ + "pid": process.pid, + "process_instance": process.instance, + "complete": false, + "physical_delivery_started": false, + })) + .with_disposition(DeliverySemantics::not_delivered())) +} + +/// Verifies that `handle` is still owned by `process` in its stored generation. +#[cfg(any(target_os = "windows", test))] +pub(super) fn verify_process_handle( + process: &agent_desktop_core::ProcessIdentity, + handle: crate::system::window::window_enum::WindowHandle, +) -> Result<(), AdapterError> { + verify_process_target(process)?; + if crate::system::window::window_identity::live_window_owner(handle) == Some(process.pid) { + return Ok(()); + } + Err(AdapterError::new( + ErrorCode::WindowNotFound, + "The popup window is no longer owned by the target process", + ) + .with_suggestion("Run 'list-windows' to refresh window identifiers, then retry.") + .with_disposition(DeliverySemantics::not_delivered())) +} + +/// Finds the deepest open popup owner across at most `MAX_POPUP_ROOTS` roots +/// and `MAX_POPUP_NODES` nodes, consulting `deadline` before every step. +#[cfg(any(target_os = "windows", test))] +pub(super) fn scan_popup_owners( + tree: &T, + roots: Vec, + deadline: Deadline, +) -> PopupScan { + if deadline.is_expired() { + return PopupScan::TimedOut; + } + let mut visited = 0usize; + let mut best: Option<(usize, T::Node)> = None; + for root in roots.into_iter().take(MAX_POPUP_ROOTS) { + let mut stack = vec![(root, 0usize)]; + while let Some((node, depth)) = stack.pop() { + if deadline.is_expired() { + return PopupScan::TimedOut; + } + if visited >= MAX_POPUP_NODES { + return best.map_or(PopupScan::None, |(_, owner)| PopupScan::Found(owner)); + } + visited += 1; + let is_owner = tree.is_open_popup_owner(&node); + if depth < MAX_POPUP_DEPTH && visited < MAX_POPUP_NODES { + let mut children = Vec::new(); + if deadline.is_expired() { + return PopupScan::TimedOut; + } + let mut child = tree.first_child(&node); + while let Some(current) = child { + let next = if children.len() + 1 < MAX_POPUP_CHILDREN { + if deadline.is_expired() { + return PopupScan::TimedOut; + } + tree.next_sibling(¤t) + } else { + None + }; + children.push(current); + child = next; + } + for child in children.into_iter().rev() { + stack.push((child, depth + 1)); + } + } + if is_owner && best.as_ref().is_none_or(|(deepest, _)| depth >= *deepest) { + best = Some((depth, node)); + } + } + } + best.map_or(PopupScan::None, |(_, owner)| PopupScan::Found(owner)) +} + +/// Key delivery to `process` (A9-3: SendInput has no per-pid targeting; +/// core's headed path already activated), then the popup close. +pub(crate) fn press_for_app( + process: agent_desktop_core::ProcessIdentity, + combo: &KeyCombo, + policy: agent_desktop_core::InteractionPolicy, + deadline: agent_desktop_core::Deadline, +) -> Result { + let result = + crate::system::key_dispatch::press_for_app_impl(process.clone(), combo, policy, deadline); + after_key_route( + result, + PopupScope::Process(&process), + combo, + policy, + deadline, + ) +} + +/// Core's focus-gated delivery to a named window, then the popup close. +pub(crate) fn press_for_window( + adapter: &A, + window: &agent_desktop_core::WindowInfo, + combo: &KeyCombo, + policy: agent_desktop_core::InteractionPolicy, + lease: &agent_desktop_core::InteractionLease, +) -> Result { + let result = + agent_desktop_core::press_key_in_focused_window(adapter, window, combo, policy, lease); + after_key_route( + result, + PopupScope::Window(window), + combo, + policy, + lease.deadline(), + ) +} + +/// Where a refused Escape looks for an open popup. +#[derive(Clone, Copy)] +pub(crate) enum PopupScope<'a> { + Window(&'a agent_desktop_core::WindowInfo), + Process(&'a agent_desktop_core::ProcessIdentity), +} + +pub(crate) fn is_plain_escape(combo: &KeyCombo) -> bool { + combo.modifiers.is_empty() + && (combo.key.eq_ignore_ascii_case("escape") || combo.key.eq_ignore_ascii_case("esc")) +} + +/// The refusals after which the target's popup gets its close: core's refusal +/// of a window that is not the exact focus holder, and this adapter's refusal +/// of a process that does not hold the keyboard. Each scope answers only its +/// own refusal, so one refusal is searched once. +pub(crate) fn refused_for_focus(window_scope: bool, error: &AdapterError) -> bool { + let details = error.details.as_ref(); + let unsent = error.disposition == DeliverySemantics::not_delivered() + && details.and_then(|details| details["physical_delivery_started"].as_bool()) + == Some(false); + let check = details.and_then(|details| details["check"].as_str()); + unsent + && if window_scope { + check == Some("window_active") + } else { + error.code == ErrorCode::ActionFailed && check.is_none() + } +} + +/// The control types whose expansion is a popup: menu item (50011), combo box +/// (50003) and split button (50031). A tree item or a group is never one. +fn opens_a_popup(control_type: i32) -> bool { + [50011, 50003, 50031].contains(&control_type) +} + +#[cfg(target_os = "windows")] +#[path = "escape_popup_uia.rs"] +mod uia; + +#[cfg(target_os = "windows")] +pub(crate) use uia::after_key_route; + +/// Off Windows no popup can be open, so the key route's result stands. +#[cfg(not(target_os = "windows"))] +pub(crate) fn after_key_route( + result: Result, + _scope: PopupScope<'_>, + _combo: &KeyCombo, + _policy: agent_desktop_core::InteractionPolicy, + _deadline: agent_desktop_core::Deadline, +) -> Result { + result +} + +#[cfg(test)] +#[path = "escape_popup_tests.rs"] +mod tests; diff --git a/crates/windows/src/system/escape_popup_tests.rs b/crates/windows/src/system/escape_popup_tests.rs new file mode 100644 index 000000000..506a0a7a4 --- /dev/null +++ b/crates/windows/src/system/escape_popup_tests.rs @@ -0,0 +1,301 @@ +use std::cell::Cell; +use std::time::Duration; + +use agent_desktop_core::{ + AdapterError, Deadline, DeliverySemantics, ErrorCode, KeyCombo, Modifier, ProcessId, + ProcessIdentity, WindowInfo, +}; + +use super::{ + MAX_POPUP_CHILDREN, MAX_POPUP_DEPTH, MAX_POPUP_NODES, MAX_POPUP_ROOTS, PopupScan, PopupTree, + is_plain_escape, opens_a_popup, refused_for_focus, scan_popup_owners, scan_timeout_error, + verify_process_handle, verify_process_target, verify_window_target, +}; + +struct FakeNode { + open_popup: bool, + children: Vec, +} + +struct FakeTree { + nodes: Vec, + reads: Cell, +} + +impl FakeTree { + fn new(nodes: Vec) -> Self { + Self { + nodes, + reads: Cell::new(0), + } + } +} + +impl PopupTree for FakeTree { + type Node = (usize, Option<(usize, usize)>); + + fn is_open_popup_owner(&self, node: &Self::Node) -> bool { + self.reads.set(self.reads.get() + 1); + self.nodes[node.0].open_popup + } + + fn first_child(&self, node: &Self::Node) -> Option { + self.nodes[node.0] + .children + .first() + .copied() + .map(|child| (child, Some((node.0, 0)))) + } + + fn next_sibling(&self, node: &Self::Node) -> Option { + let (parent, index) = node.1?; + let next = index + 1; + self.nodes[parent] + .children + .get(next) + .copied() + .map(|child| (child, Some((parent, next)))) + } +} + +fn root_ref(id: usize) -> (usize, Option<(usize, usize)>) { + (id, None) +} + +fn key(name: &str, modifiers: Vec) -> KeyCombo { + KeyCombo { + key: name.to_owned(), + modifiers, + } +} + +#[test] +fn only_a_plain_escape_may_close_a_popup() { + assert!(is_plain_escape(&key("escape", vec![]))); + assert!(is_plain_escape(&key("Esc", vec![]))); + assert!(!is_plain_escape(&key("escape", vec![Modifier::Shift]))); + assert!(!is_plain_escape(&key("return", vec![]))); +} + +#[test] +fn each_scope_answers_only_its_own_focus_refusal() { + let window = AdapterError::stale_ref_because("not focused") + .with_details( + serde_json::json!({ "check": "window_active", "physical_delivery_started": false }), + ) + .with_disposition(DeliverySemantics::not_delivered()); + let process = AdapterError::new(ErrorCode::ActionFailed, "not foreground") + .with_details(serde_json::json!({ "pid": 4, "physical_delivery_started": false })) + .with_disposition(DeliverySemantics::not_delivered()); + let sent = AdapterError::new(ErrorCode::ActionFailed, "sent") + .with_details(serde_json::json!({ "physical_delivery_started": true })) + .with_disposition(DeliverySemantics::delivered_unverified()); + + assert!(refused_for_focus(true, &window)); + assert!(!refused_for_focus(false, &window)); + assert!(refused_for_focus(false, &process)); + assert!(!refused_for_focus(true, &process)); + assert!(!refused_for_focus(false, &sent)); +} + +#[test] +fn a_tree_item_or_a_group_is_never_a_popup_owner() { + assert!(opens_a_popup(50011) && opens_a_popup(50003) && opens_a_popup(50031)); + assert!(!opens_a_popup(50024) && !opens_a_popup(50026) && !opens_a_popup(50029)); +} + +#[test] +fn popup_scan_stops_immediately_when_deadline_is_expired() { + let tree = FakeTree::new(vec![FakeNode { + open_popup: true, + children: Vec::new(), + }]); + let deadline = Deadline::after(1).expect("short deadline"); + std::thread::sleep(Duration::from_millis(5)); + assert_eq!( + scan_popup_owners(&tree, vec![root_ref(0)], deadline), + PopupScan::TimedOut + ); + assert_eq!(tree.reads.get(), 0); + let error = scan_timeout_error(deadline); + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); +} + +#[test] +fn popup_scan_respects_node_child_depth_and_root_budgets() { + let mut wide = vec![FakeNode { + open_popup: false, + children: (1..=MAX_POPUP_CHILDREN + 20).collect(), + }]; + for idx in 1..=MAX_POPUP_CHILDREN + 20 { + wide.push(FakeNode { + open_popup: idx == MAX_POPUP_CHILDREN + 20, + children: Vec::new(), + }); + } + let wide_tree = FakeTree::new(wide); + let deadline = Deadline::after(5_000).expect("budget"); + assert_eq!( + scan_popup_owners(&wide_tree, vec![root_ref(0)], deadline), + PopupScan::None + ); + assert!(wide_tree.reads.get() <= MAX_POPUP_CHILDREN + 1); + + let mut deep = Vec::new(); + for depth in 0..=MAX_POPUP_DEPTH + 4 { + deep.push(FakeNode { + open_popup: depth == MAX_POPUP_DEPTH + 4, + children: if depth < MAX_POPUP_DEPTH + 4 { + vec![depth + 1] + } else { + Vec::new() + }, + }); + } + let deep_tree = FakeTree::new(deep); + assert_eq!( + scan_popup_owners(&deep_tree, vec![root_ref(0)], deadline), + PopupScan::None + ); + assert_eq!(deep_tree.reads.get(), MAX_POPUP_DEPTH + 1); + + let many_roots: Vec = (0..MAX_POPUP_ROOTS + 5) + .map(|idx| FakeNode { + open_popup: idx == MAX_POPUP_ROOTS + 4, + children: Vec::new(), + }) + .collect(); + let root_tree = FakeTree::new(many_roots); + let roots = (0..MAX_POPUP_ROOTS + 5).map(root_ref).collect(); + assert_eq!( + scan_popup_owners(&root_tree, roots, deadline), + PopupScan::None + ); + assert_eq!(root_tree.reads.get(), MAX_POPUP_ROOTS); + + let mut dense = Vec::new(); + let mut dense_roots = Vec::new(); + for _ in 0..20usize { + let base = dense.len(); + dense_roots.push(root_ref(base)); + let children: Vec = (base + 1..base + 51).collect(); + dense.push(FakeNode { + open_popup: false, + children, + }); + for _ in 0..50 { + dense.push(FakeNode { + open_popup: false, + children: Vec::new(), + }); + } + } + let dense_tree = FakeTree::new(dense); + assert_eq!( + scan_popup_owners(&dense_tree, dense_roots, deadline), + PopupScan::None + ); + assert_eq!(dense_tree.reads.get(), MAX_POPUP_NODES); +} + +#[test] +fn popup_scan_returns_the_deepest_open_owner_within_budget() { + let tree = FakeTree::new(vec![ + FakeNode { + open_popup: false, + children: vec![1, 3], + }, + FakeNode { + open_popup: true, + children: vec![2], + }, + FakeNode { + open_popup: true, + children: Vec::new(), + }, + FakeNode { + open_popup: true, + children: Vec::new(), + }, + ]); + let deadline = Deadline::after(5_000).expect("budget"); + assert_eq!( + scan_popup_owners(&tree, vec![root_ref(0)], deadline), + PopupScan::Found((2, Some((1, 0)))) + ); +} + +fn sample_window(id: &str, pid: ProcessId, instance: Option<&str>) -> WindowInfo { + WindowInfo { + id: id.to_owned(), + title: "Dialog".to_owned(), + app: "fixture".to_owned(), + pid, + process_instance: instance.map(str::to_owned), + bounds: None, + state: Default::default(), + } +} + +#[test] +fn window_target_verification_fails_closed_for_missing_or_changed_identity() { + let missing_token = sample_window("w-1", ProcessId::new(1), None); + let error = verify_window_target(&missing_token).expect_err("tokenless window must fail"); + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + + let malformed = sample_window( + "not-an-hwnd", + ProcessId::new(1), + Some("windows-proc-v1:1:1"), + ); + let error = verify_window_target(&malformed).expect_err("malformed id must fail"); + assert_eq!(error.code, ErrorCode::InvalidArgs); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + + let process_owner = sample_window("", ProcessId::new(1), Some("windows-proc-v1:1:1")); + let error = verify_window_target(&process_owner).expect_err("process-owner entry must fail"); + assert_eq!(error.code, ErrorCode::WindowNotFound); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + + let stale = sample_window( + "w-1", + ProcessId::new(9_999_999), + Some("windows-proc-v1:0:0"), + ); + let error = verify_window_target(&stale).expect_err("unowned handle must fail closed"); + assert_eq!(error.code, ErrorCode::WindowNotFound); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); +} + +#[test] +fn process_target_verification_fails_closed_for_stale_generation_or_unowned_handle() { + let stale_process = ProcessIdentity { + pid: ProcessId::new(9_999_999), + instance: "windows-proc-v1:0:0".to_owned(), + }; + let error = verify_process_target(&stale_process).expect_err("stale process must fail"); + assert_eq!(error.code, ErrorCode::AppUnresponsive); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + + let error = verify_process_handle(&stale_process, std::ptr::null_mut()) + .expect_err("stale process handle must fail"); + assert_eq!(error.code, ErrorCode::AppUnresponsive); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + + let current_pid = ProcessId::from(std::process::id()); + if let Some(token) = crate::system::process_identity::token_for_pid(current_pid) + .expect("token lookup for current process") + { + let live_process = ProcessIdentity { + pid: current_pid, + instance: token, + }; + verify_process_target(&live_process).expect("live current process must verify"); + let error = verify_process_handle(&live_process, std::ptr::null_mut()) + .expect_err("null handle is not owned by the live process"); + assert_eq!(error.code, ErrorCode::WindowNotFound); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + } +} diff --git a/crates/windows/src/system/escape_popup_uia.rs b/crates/windows/src/system/escape_popup_uia.rs new file mode 100644 index 000000000..3a29c4e6f --- /dev/null +++ b/crates/windows/src/system/escape_popup_uia.rs @@ -0,0 +1,255 @@ +//! The UI Automation half of `escape_popup`: the bounded popup search, the collapse and the entry point. + +use super::{ + MAX_POPUP_ROOTS, PopupScan, PopupScope, PopupTree, is_plain_escape, opens_a_popup, + refused_for_focus, scan_popup_owners, scan_timeout_error, verify_process_handle, + verify_process_target, verify_window_target, +}; +use agent_desktop_core::{ + Action, ActionResult, AdapterError, Deadline, DeliveryOutcome, DeliverySemantics, ErrorCode, + InteractionPolicy, KeyCombo, ProcessIdentity, WindowInfo, +}; +use std::time::Duration; +use uiautomation::core::{UICacheRequest, UITreeWalker}; +use uiautomation::patterns::UIExpandCollapsePattern; + +use crate::actions::chain::{offered, poll_until, rung}; +use crate::actions::mutation::{classify_success, classify_write}; +use crate::system::window::window_enum::{WindowHandle, enumerate_top_level}; +use crate::system::window::window_identity::live_window_owner; +use crate::tree::automation::{automation_client, root_from_hwnd}; +use crate::tree::element::UIAElement; +use crate::tree::properties::property_ids::TreeProperty; +use crate::tree::properties::{read_cached, read_one}; +use crate::tree::walk::cache::build_walk_cache_request; + +const COLLAPSE_LABEL: &str = "ExpandCollapsePattern.Collapse"; +const COLLAPSE_SUGGESTION: &str = "Close the popup with the key while its window is in front."; +const VERIFY_TIMEOUT: Duration = Duration::from_millis(600); +const EXPANDED: i32 = 1; +const COLLAPSED: i32 = 0; +const POPUP_SCAN_PROPERTIES: [TreeProperty; 2] = + [TreeProperty::ControlType, TreeProperty::ExpandCollapseState]; + +struct PopupNode { + handle: WindowHandle, + element: UIAElement, +} + +struct UiaPopupTree { + walker: UITreeWalker, + cache: UICacheRequest, +} + +impl PopupTree for UiaPopupTree { + type Node = PopupNode; + + fn is_open_popup_owner(&self, node: &PopupNode) -> bool { + let (properties, _) = read_cached(&node.element, &POPUP_SCAN_PROPERTIES); + properties + .get(TreeProperty::ControlType) + .number() + .is_some_and(opens_a_popup) + && properties.get(TreeProperty::ExpandCollapseState).number() == Some(EXPANDED) + } + + fn first_child(&self, node: &PopupNode) -> Option { + self.walker + .get_first_child_build_cache(&node.element.0, &self.cache) + .ok() + .map(|element| PopupNode { + handle: node.handle, + element: UIAElement::from(element), + }) + } + + fn next_sibling(&self, node: &PopupNode) -> Option { + self.walker + .get_next_sibling_build_cache(&node.element.0, &self.cache) + .ok() + .map(|element| PopupNode { + handle: node.handle, + element: UIAElement::from(element), + }) + } +} + +fn prefetch_roots( + roots: Vec, + cache: &UICacheRequest, + deadline: Deadline, +) -> Result, AdapterError> { + let mut cached = Vec::with_capacity(roots.len()); + for root in roots.into_iter().take(MAX_POPUP_ROOTS) { + if deadline.is_expired() { + return Err(scan_timeout_error(deadline)); + } + if let Ok(element) = root.element.0.build_updated_cache(cache) { + cached.push(PopupNode { + handle: root.handle, + element: UIAElement::from(element), + }); + } + } + Ok(cached) +} + +/// The deepest expanded popup owner among the elements below `roots`, found by +/// a bounded, deadline-checked incremental walk over the control view. +fn deepest_popup_owner( + roots: Vec, + deadline: Deadline, +) -> Result, AdapterError> { + if deadline.is_expired() { + return Err(scan_timeout_error(deadline)); + } + let Ok(client) = automation_client() else { + return Ok(None); + }; + let Ok(walker) = client.get_control_view_walker() else { + return Ok(None); + }; + let Ok(cache) = build_walk_cache_request(&client, &POPUP_SCAN_PROPERTIES) else { + return Ok(None); + }; + let cached_roots = prefetch_roots(roots, &cache, deadline)?; + let tree = UiaPopupTree { walker, cache }; + match scan_popup_owners(&tree, cached_roots, deadline) { + PopupScan::Found(owner) => Ok(Some(owner)), + PopupScan::None => Ok(None), + PopupScan::TimedOut => Err(scan_timeout_error(deadline)), + } +} + +fn verify_popup_target(scope: PopupScope<'_>, handle: WindowHandle) -> Result<(), AdapterError> { + match scope { + PopupScope::Window(window) => verify_window_target(window).map(|_| ()), + PopupScope::Process(process) => verify_process_handle(process, handle), + } +} + +fn window_roots(window: &WindowInfo, deadline: Deadline) -> Result, AdapterError> { + if deadline.is_expired() { + return Err(scan_timeout_error(deadline)); + } + let handle = verify_window_target(window)?; + let element = match root_from_hwnd(handle as isize, deadline) { + Ok(element) => element, + Err(error) => { + verify_window_target(window)?; + if error.code == ErrorCode::Timeout { + return Err(error.with_disposition(DeliverySemantics::not_delivered())); + } + return Ok(Vec::new()); + } + }; + verify_window_target(window)?; + Ok(vec![PopupNode { handle, element }]) +} + +fn process_roots( + process: &ProcessIdentity, + deadline: Deadline, +) -> Result, AdapterError> { + if deadline.is_expired() { + return Err(scan_timeout_error(deadline)); + } + verify_process_target(process)?; + let mut handles = Vec::new(); + let _ = enumerate_top_level(|window| { + if live_window_owner(window.handle) == Some(process.pid) { + handles.push(window.handle); + } + handles.len() < MAX_POPUP_ROOTS + }); + let mut roots = Vec::with_capacity(handles.len()); + for handle in handles { + if deadline.is_expired() { + return Err(scan_timeout_error(deadline)); + } + if verify_process_handle(process, handle).is_err() { + verify_process_target(process)?; + continue; + } + if let Ok(element) = root_from_hwnd(handle as isize, deadline) { + if verify_process_handle(process, handle).is_ok() { + roots.push(PopupNode { handle, element }); + } else { + verify_process_target(process)?; + } + } + } + Ok(roots) +} + +fn collapse(owner: &PopupNode, scope: PopupScope<'_>) -> Result { + verify_popup_target(scope, owner.handle)?; + match owner.element.0.get_pattern::() { + Ok(pattern) => { + verify_popup_target(scope, owner.handle)?; + match pattern.collapse() { + Ok(()) => classify_success(), + Err(error) => classify_write("Collapse", COLLAPSE_LABEL, &error), + } + } + Err(error) => classify_write("get_pattern", COLLAPSE_LABEL, &error), + } +} + +fn close_popup( + owner: &PopupNode, + scope: PopupScope<'_>, + combo: &KeyCombo, + policy: InteractionPolicy, + deadline: Deadline, +) -> Result { + if deadline.is_expired() { + return Err(scan_timeout_error(deadline)); + } + verify_popup_target(scope, owner.handle)?; + let mut run = || { + if !collapse(owner, scope)? { + return Ok(DeliveryOutcome::NotDelivered); + } + let closed = poll_until(deadline, VERIFY_TIMEOUT, || { + read_one(&owner.element, TreeProperty::ExpandCollapseState).number() == Some(COLLAPSED) + }); + Ok(DeliveryOutcome::from_delivery(true, closed)) + }; + let steps = agent_desktop_core::execute_chain( + &mut offered([rung(COLLAPSE_LABEL, true, false, &mut run)]), + policy, + deadline, + COLLAPSE_SUGGESTION, + )?; + Ok(ActionResult::from_execution( + &Action::PressKey(combo.clone()), + steps, + )) +} + +/// The key route's result, or, when it refused a plain Escape for focus and +/// the scope shows an open popup, the collapse of that popup's owner. +pub(crate) fn after_key_route( + result: Result, + scope: PopupScope<'_>, + combo: &KeyCombo, + policy: InteractionPolicy, + deadline: Deadline, +) -> Result { + let Err(refusal) = result else { + return result; + }; + let window_scope = matches!(scope, PopupScope::Window(_)); + if !is_plain_escape(combo) || !refused_for_focus(window_scope, &refusal) { + return Err(refusal); + } + let roots = match scope { + PopupScope::Window(window) => window_roots(window, deadline)?, + PopupScope::Process(process) => process_roots(process, deadline)?, + }; + match deepest_popup_owner(roots, deadline)? { + Some(owner) => close_popup(&owner, scope, combo, policy, deadline), + None => Err(refusal), + } +} diff --git a/crates/windows/src/system/mod.rs b/crates/windows/src/system/mod.rs index 1555cf19d..08c3f2155 100644 --- a/crates/windows/src/system/mod.rs +++ b/crates/windows/src/system/mod.rs @@ -7,6 +7,7 @@ pub(crate) mod close_dispatch; pub(crate) mod close_outcome; pub(crate) mod cursor_overlay; pub(crate) mod display; +pub(crate) mod escape_popup; #[cfg(target_os = "windows")] pub(crate) mod interaction_lease; pub(crate) mod key_dispatch; diff --git a/docs/json-output.md b/docs/json-output.md index 4dcfeb351..bd92e128b 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -190,7 +190,7 @@ When a ref action returns `delivery_uncertain` with a post-action wait selector, - `status` adds `data.state_root_privacy`: `{ "ok": true }` or `{ "ok": false, "error": { ... } }` from the same private-directory check; failed checks leave snapshot rows null. - A table or grid node carries `row_count` and `column_count` when the platform's table interface reports them. A spreadsheet can report far more rows than it shows. Under `--skeleton`, a table or grid that reports its size is one node below the snapshot root: its cells stay out, it carries `children_count`, and its ref anchors a `--root` drill. - macOS: a table cell that occupies one row and one column carries its position as `native_id`, `{ "kind": "grid_cell", "value": "B7" }`: the column letters, then the row, counted from the first row and column the table reports. A cell that has an identifier of its own keeps that identifier as `native_id`, and its position still finds it. The position describes the cell and does not identify it: the ref is found again by the element's own token. `find --role cell --native-id B7 --root ` returns that cell. -- macOS: a table cell that can be pressed lists `SetValue`. `set-value` and `clear` write the cell's value directly when the cell takes one. Any other cell is pressed until its editor opens, its text is replaced with key events sent to the application's process, and Return commits it; the application is not activated. Such a cell publishes no value to read back, so the result is `delivered_unverified`: read the cell again. +- macOS: a table cell that can be pressed lists `SetValue`. `set-value` and `clear` write the cell's value directly when the cell takes one. Any other cell is pressed until its editor opens, its text is replaced with key events sent to the application's process, and Return commits it; the application is not activated. After committing, the cell is read back: the result is `delivered_verified` when the text matches, `delivered_unverified` when it differs or cannot be read, and `ACTION_FAILED` (`delivered_unverified`) when the cell stays empty. - Linux: a table cell reports its text as `value`. An editable cell that holds a number through the platform's value interface lists `SetValue` and takes a number; text is refused with `INVALID_ARGS` before anything is sent, because it has no background route. A selectable table cell whose table can select it lists `Click` and `Select`. A cell carries no grid position: a position names another cell once rows move, so it is never part of a ref's identity. - Windows: a grid cell whose role already earns it a ref lists `Click` when a selectable row inside a grid or list holds it; the click selects that row and reads the selection back. The action never creates a ref. A ref action reads only the properties that identify an element, so it costs less than a snapshot of the same window. A cell carries no grid position. diff --git a/skills/agent-desktop-linux/SKILL.md b/skills/agent-desktop-linux/SKILL.md index b3419b9c5..e82d2d066 100644 --- a/skills/agent-desktop-linux/SKILL.md +++ b/skills/agent-desktop-linux/SKILL.md @@ -52,8 +52,7 @@ use a private session and runtime directory for isolated work. Menu-role popups use the menu surface instead. - 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. -- Headless `restore` of a minimized window and headless `minimize` of the focused window refuse with `POLICY_DENIED`; the system raises or moves focus. Stop on that refusal. + Stop on a headed-only refusal instead of changing mode. Headless `restore` of a minimized window and headless `minimize` of the focused window refuse with `POLICY_DENIED`; the system raises or moves focus. Stop on that refusal. - 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 @@ -73,7 +72,8 @@ use a private session and runtime directory for isolated work. 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. -- `launch` accepts a program on PATH, an absolute path, an installed desktop id, or an unambiguous desktop entry name. A script launch attaches only to the interpreter process that runs that script, never to another script of the same interpreter. `--no-attach` refuses any running process of the same program (the same executable, or the interpreter running the same script) whatever its arguments. Use process and window identity from observations rather than guessing from a window title. Without `--activate`, a launch on X11 gives the focus and the window order back to the window that had them when a new window took them, and reports `focus_returned: true`, or `false` with a suggestion when it could not. A headless click that opens a dialog is guarded the same way (`details.focus_returned`). +- `launch` accepts a program on PATH, an absolute path, an installed desktop id, or an unambiguous desktop entry name. A script launch attaches only to the interpreter process that runs that script, never to another script of the same interpreter. `--no-attach` refuses any running process of the same program (the same executable, or the interpreter running the same script) whatever its arguments. Use process and window identity from observations rather than guessing from a window title. Without `--activate`, a launch on X11 gives the focus and window order back and reports `focus_returned: true`, or `false` with a suggestion; a headless click that opens a dialog is guarded the same way. +- `press escape --app --window-id ` on a background window with a showing native popup closes it only via a dismissal action (or GTK3 combo box `Press`) and reports `delivered_verified` once gone. Web content and buttons without a dismissal action keep the focus refusal; it never collapses a tree row. - Sandboxes are not available on Linux yet. To run agent-desktop in a container you manage yourself, see `agent-browser.dev/desktop/guides/docker-container`. ## Troubleshooting diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.md index eec499a85..028d0c6f9 100644 --- a/skills/agent-desktop-macos/SKILL.md +++ b/skills/agent-desktop-macos/SKILL.md @@ -37,9 +37,16 @@ may report `unknown` when consent would require a prompt. - Native AX element tokens identify individual controls, including twins. A stale token never falls back to a look-alike search. Elements without a token follow the uniqueness rule of the core skill. +- `list-windows` also lists a floating or panel window an app raises above the + normal level, as accessory apps do with settings and panels, while it is on screen. - `menu` and `menubar` observations are application-owned and can omit `data.window`. An app without an ordinary window may still expose process-owned surfaces. Inspect `supported_surfaces` rather than assuming every surface exists. +- `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 + popover can appear a moment after the click that opens it: read it with + `snapshot --app --surface popover`. - Headless menu-opening and dialog-opening actions can refuse before delivery. A label ending in an ellipsis predicts a dialog; it does not prove one exists. Stop on a headed-only refusal rather than changing mode. @@ -62,8 +69,11 @@ may report `unknown` when consent would require a prompt. Return go only to that editor. An application that moves a value into an editor of its own, as a spreadsheet does with a formula that starts with `=`, leaves it typed and open, and the write fails as `delivered_unverified`: commit it with - `press return --app `. Such a cell publishes no value, so a committed write is - `delivered_unverified` too: read the cell's name to verify. The write also commits + `press return --app `. The cell is read after the commit: a cell that still + shows nothing fails as `ACTION_FAILED` with `delivered_unverified`, and one that + shows another value stays `delivered_unverified`. An application that gives its + cell editor no keyboard input from a press always takes that failure; type there + with `--headed` only if the user explicitly asked for that. The write also commits an edit that is open in another cell. - AX success alone does not prove an application effect. Verify the task's result independently, especially after a menu action or a value write. diff --git a/skills/agent-desktop-windows/SKILL.md b/skills/agent-desktop-windows/SKILL.md index b63c8c261..00bffc081 100644 --- a/skills/agent-desktop-windows/SKILL.md +++ b/skills/agent-desktop-windows/SKILL.md @@ -42,6 +42,10 @@ Use `$env:NAME = 'value'` for environment variables. - A ref must be unique in its window, or inside its nearest unique ancestor (a cell inside its row), at capture and resolution. A root drill cannot make identical twins unique. Choose a distinct control. +- `press escape` with `--app` or `--window-id` on a window that is not in front is + refused as before, unless that window shows an open menu, combo box or split + button: then the innermost one is collapsed (`ExpandCollapsePattern.Collapse`), + `delivered_verified` once read back closed. A tree item is never collapsed. - A grid reports `row_count` and `column_count`. A row is a record: find it by its own name, and its cells through it. `agent-desktop click` on a grid cell that lists `Click` selects the row that holds it. A cell carries no grid position.