diff --git a/crates/core/src/actions/action.rs b/crates/core/src/actions/action.rs index a00846ddb6..1be54ecd9d 100644 --- a/crates/core/src/actions/action.rs +++ b/crates/core/src/actions/action.rs @@ -113,6 +113,19 @@ impl Action { matches!(self, Self::Hover | Self::Drag(_)) } + /// Whether the action's effect lands outside the target's own state, so an + /// effect witness is read around it. + pub fn witnesses_effect(&self) -> bool { + matches!( + self, + Self::Click + | Self::DoubleClick + | Self::RightClick + | Self::TripleClick + | Self::Select(_) + ) + } + pub fn requires_hit_test(&self) -> bool { matches!( self, diff --git a/crates/core/src/actions/action_result.rs b/crates/core/src/actions/action_result.rs index c3e26d5ffd..a9efbd2ee4 100644 --- a/crates/core/src/actions/action_result.rs +++ b/crates/core/src/actions/action_result.rs @@ -18,6 +18,10 @@ pub struct ActionResult { pub surfaces: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub details: Option, + /// What the effect witness saw around the action; absent when the action + /// has no witness or the platform could not read one. + #[serde(skip_serializing_if = "Option::is_none", default)] + pub effect: Option, #[serde(deserialize_with = "deserialize_action_disposition")] disposition: DeliverySemantics, } @@ -49,6 +53,7 @@ impl ActionResult { steps: Vec::new(), surfaces: Vec::new(), details: None, + effect: None, disposition: DeliverySemantics::not_delivered(), } } @@ -60,10 +65,16 @@ impl ActionResult { steps: Vec::new(), surfaces: Vec::new(), details: None, + effect: None, disposition: default_action_disposition(), } } + pub fn with_effect(mut self, effect: crate::actions::observed_effect::ObservedEffect) -> Self { + self.effect = Some(effect); + self + } + pub fn with_state(mut self, state: ElementState) -> Self { self.post_state = Some(state); self diff --git a/crates/core/src/actions/effect_witness.rs b/crates/core/src/actions/effect_witness.rs new file mode 100644 index 0000000000..e635c4fc41 --- /dev/null +++ b/crates/core/src/actions/effect_witness.rs @@ -0,0 +1,101 @@ +use serde::{Deserialize, Serialize}; + +use crate::actions::{ + focus_witness::FocusWitness, observed_effect::ObservedEffect, target_witness::TargetWitness, + window_witness::WindowWitness, witness_change::WitnessChange, +}; + +/// What an adapter reads around an action whose effect lands outside the +/// target's own state: a click, a select. A field the platform could not read +/// is `None` and never counts as a change. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct EffectWitness { + pub target: TargetWitness, + pub focus: FocusWitness, + pub window: WindowWitness, +} + +impl EffectWitness { + /// The changes from `before` to `self`. A change counts only when both + /// reads have the field. A selection or a surface counts only when it + /// appears, because one that goes away says nothing about this action. + /// Focus counts as arriving in the target only when the earlier read saw it + /// outside the target; focus that was already inside and moved to another + /// child is a move within the window, and an unread earlier focus never + /// becomes an arrival. + pub fn changes_since(&self, before: &Self) -> Vec { + let (now, then) = (self, before); + let focus_moved = differs(&then.focus.element, &now.focus.element); + let focus_arrived = + then.focus.inside_target == Some(false) && now.focus.inside_target == Some(true); + [ + ( + then.target.selected == Some(false) && now.target.selected == Some(true), + WitnessChange::TargetSelected, + ), + ( + differs(&then.target.value, &now.target.value), + WitnessChange::TargetValue, + ), + ( + grew(then.target.surfaces, now.target.surfaces), + WitnessChange::SurfaceOpened, + ), + (focus_arrived, WitnessChange::FocusIntoTarget), + ( + focus_moved && !focus_arrived && now.focus.in_target_window == Some(true), + WitnessChange::FocusMovedInWindow, + ), + ( + !focus_moved + && now.focus.in_target_window == Some(true) + && differs(&then.focus.value, &now.focus.value), + WitnessChange::FocusedValue, + ), + ( + then.window.present == Some(true) && now.window.present == Some(false), + WitnessChange::WindowClosed, + ), + ( + differs(&then.window.title, &now.window.title), + WitnessChange::WindowTitle, + ), + ( + differs(&then.window.content, &now.window.content), + WitnessChange::WindowContent, + ), + ( + differs(&then.window.windows, &now.window.windows), + WitnessChange::WindowCount, + ), + ] + .into_iter() + .filter_map(|(changed, change)| changed.then_some(change)) + .collect() + } +} + +/// The verdict of a list of changes: any strong change is an observed +/// effect, weak changes alone are indeterminate, and no change is not +/// observed. +pub(crate) fn verdict(changes: &[WitnessChange]) -> ObservedEffect { + if changes.iter().any(|change| change.is_strong()) { + ObservedEffect::Observed + } else if changes.is_empty() { + ObservedEffect::NotObserved + } else { + ObservedEffect::Indeterminate + } +} + +fn differs(before: &Option, after: &Option) -> bool { + matches!((before, after), (Some(before), Some(after)) if before != after) +} + +fn grew(before: Option, after: Option) -> bool { + matches!((before, after), (Some(before), Some(after)) if after > before) +} + +#[cfg(test)] +#[path = "effect_witness_tests.rs"] +mod tests; diff --git a/crates/core/src/actions/effect_witness_tests.rs b/crates/core/src/actions/effect_witness_tests.rs new file mode 100644 index 0000000000..3243b98b56 --- /dev/null +++ b/crates/core/src/actions/effect_witness_tests.rs @@ -0,0 +1,160 @@ +use super::{EffectWitness, verdict}; +use crate::actions::focus_witness::FocusWitness; +use crate::actions::{observed_effect::ObservedEffect, witness_change::WitnessChange}; + +fn read() -> EffectWitness { + let mut witness = EffectWitness::default(); + witness.target.selected = Some(false); + witness.target.value = Some("0".into()); + witness.target.surfaces = Some(0); + witness.focus.element = Some("list".into()); + witness.focus.inside_target = Some(false); + witness.focus.in_target_window = Some(true); + witness.focus.value = Some("a".into()); + witness.window.title = Some("Downloads".into()); + witness.window.content = Some(7); + witness.window.windows = Some(1); + witness.window.present = Some(true); + witness +} + +#[test] +fn no_change_is_not_observed() { + let before = read(); + assert!(read().changes_since(&before).is_empty()); + assert_eq!(verdict(&[]), ObservedEffect::NotObserved); +} + +#[test] +fn a_change_on_or_under_the_target_is_an_observed_effect() { + let before = read(); + for (change, expected) in [ + ( + (|w: &mut EffectWitness| w.target.selected = Some(true)) as fn(&mut EffectWitness), + WitnessChange::TargetSelected, + ), + ( + |w| w.target.surfaces = Some(1), + WitnessChange::SurfaceOpened, + ), + ( + |w| w.window.present = Some(false), + WitnessChange::WindowClosed, + ), + ( + |w| { + w.focus.element = Some("target".into()); + w.focus.inside_target = Some(true); + }, + WitnessChange::FocusIntoTarget, + ), + ] { + let mut after = read(); + change(&mut after); + let changes = after.changes_since(&before); + assert_eq!(changes, [expected]); + assert_eq!(verdict(&changes), ObservedEffect::Observed); + } +} + +#[test] +fn a_change_the_application_can_make_by_itself_is_indeterminate() { + let before = read(); + for (change, expected) in [ + ( + (|w: &mut EffectWitness| w.window.title = Some("Recents".into())) + as fn(&mut EffectWitness), + WitnessChange::WindowTitle, + ), + (|w| w.window.content = Some(8), WitnessChange::WindowContent), + ( + |w| w.target.value = Some("00:02".into()), + WitnessChange::TargetValue, + ), + (|w| w.window.windows = Some(2), WitnessChange::WindowCount), + ( + |w| w.focus.element = Some("field".into()), + WitnessChange::FocusMovedInWindow, + ), + ( + |w| w.focus.value = Some("b".into()), + WitnessChange::FocusedValue, + ), + ] { + let mut after = read(); + change(&mut after); + let changes = after.changes_since(&before); + assert_eq!(changes, [expected]); + assert_eq!(verdict(&changes), ObservedEffect::Indeterminate); + } +} + +#[test] +fn a_field_read_only_once_and_a_state_that_goes_away_are_no_evidence() { + let before = read(); + let mut after = read(); + after.window.title = None; + after.focus.element = None; + assert!(after.changes_since(&before).is_empty()); + + let mut selected = read(); + selected.target.selected = Some(true); + selected.target.surfaces = Some(1); + let mut gone = selected.clone(); + gone.target.selected = Some(false); + gone.target.surfaces = Some(0); + assert!(gone.changes_since(&selected).is_empty()); +} + +#[test] +fn focus_that_arrives_in_the_target_from_no_focus_is_a_change() { + let mut before = read(); + before.focus = FocusWitness::nothing_focused(); + let mut now = read(); + now.focus.element = Some("target".into()); + now.focus.inside_target = Some(true); + + let changes = now.changes_since(&before); + assert_eq!(changes, [WitnessChange::FocusIntoTarget]); + assert_eq!(verdict(&changes), ObservedEffect::Observed); +} + +#[test] +fn focus_that_arrives_in_the_target_from_outside_is_a_change() { + let before = read(); + let mut now = read(); + now.focus.element = Some("target".into()); + now.focus.inside_target = Some(true); + + let changes = now.changes_since(&before); + assert_eq!(changes, [WitnessChange::FocusIntoTarget]); + assert_eq!(verdict(&changes), ObservedEffect::Observed); +} + +#[test] +fn focus_that_moves_between_children_inside_the_target_is_not_an_arrival() { + let mut before = read(); + before.focus.element = Some("row-one".into()); + before.focus.inside_target = Some(true); + let mut now = before.clone(); + now.focus.element = Some("row-two".into()); + + let changes = now.changes_since(&before); + assert!(!changes.contains(&WitnessChange::FocusIntoTarget)); + assert_eq!(changes, [WitnessChange::FocusMovedInWindow]); + assert_eq!(verdict(&changes), ObservedEffect::Indeterminate); +} + +#[test] +fn focus_that_was_not_read_before_is_never_an_arrival() { + let mut before = read(); + before.focus = FocusWitness::default(); + let mut now = read(); + now.focus.element = Some("target".into()); + now.focus.inside_target = Some(true); + + let changes = now.changes_since(&before); + assert!(!changes.contains(&WitnessChange::FocusIntoTarget)); + assert!(changes.is_empty()); + assert_eq!(verdict(&changes), ObservedEffect::NotObserved); +} diff --git a/crates/core/src/actions/focus_witness.rs b/crates/core/src/actions/focus_witness.rs new file mode 100644 index 0000000000..ca4ec702cc --- /dev/null +++ b/crates/core/src/actions/focus_witness.rs @@ -0,0 +1,29 @@ +use serde::{Deserialize, Serialize}; + +/// The application's focused element, as an action's witness reads it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct FocusWitness { + /// A stable identity of the focused element; `None` when the platform + /// cannot name it, which leaves focus evidence unread. + pub element: Option, + /// Whether the focused element is the target or lies inside it. + pub inside_target: Option, + /// Whether the focused element lies in the target's window. + pub in_target_window: Option, + pub value: Option, +} + +impl FocusWitness { + /// The application answered that nothing has focus. Unlike `default()`, + /// which is a focus that was not read, this is a read, so focus that + /// arrives later counts as moved. Use it only for that answer: a read the + /// application did not answer stays `default()`. + pub fn nothing_focused() -> Self { + Self { + element: Some(String::new()), + inside_target: Some(false), + in_target_window: Some(false), + value: None, + } + } +} diff --git a/crates/core/src/actions/mod.rs b/crates/core/src/actions/mod.rs index 3698c724e8..46702bfba0 100644 --- a/crates/core/src/actions/mod.rs +++ b/crates/core/src/actions/mod.rs @@ -11,7 +11,14 @@ pub mod delivery_observation; pub mod delivery_outcome; pub(crate) mod delivery_semantics; pub mod effect; +pub mod effect_witness; +pub mod focus_witness; pub(crate) mod headed_focus; pub mod interaction_policy; +pub mod observed_effect; pub(crate) mod post_action; pub mod step_mechanism; +pub mod target_witness; +pub mod window_witness; +pub mod witness_change; +pub(crate) mod witnessed_action; diff --git a/crates/core/src/actions/observed_effect.rs b/crates/core/src/actions/observed_effect.rs new file mode 100644 index 0000000000..1d97b6f650 --- /dev/null +++ b/crates/core/src/actions/observed_effect.rs @@ -0,0 +1,18 @@ +use serde::{Deserialize, Serialize}; + +/// What a before-and-after read of an action's witness showed. +/// +/// `NotObserved` with a delivered disposition does not mean that nothing +/// happened: an effect can come later, or in another process. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ObservedEffect { + /// A change that only the action explains: on the target, under it, or + /// focus moving into it. + Observed, + /// No change in anything the witness could read. + NotObserved, + /// Only a change that the application could also make by itself, such as + /// a new window title. + Indeterminate, +} diff --git a/crates/core/src/actions/post_action.rs b/crates/core/src/actions/post_action.rs index e5aa55d9b5..d7b99c9a6f 100644 --- a/crates/core/src/actions/post_action.rs +++ b/crates/core/src/actions/post_action.rs @@ -1,3 +1,4 @@ +use crate::actions::witnessed_action::{PendingWitness, Witnessed}; use crate::system::front_guard::DispatchMark; use crate::system::front_pending::FrontPending; use crate::{ @@ -15,7 +16,7 @@ const ACTION_SETTLE: std::time::Duration = std::time::Duration::from_millis(250) /// from the target's capabilities before it writes, so nothing was sent. Any /// other error came from a call that may already have written, so delivery is /// uncertain and a retry is unsafe. An error that has a disposition keeps it. -fn settle_disposition(error: AdapterError) -> AdapterError { +pub(crate) fn settle_disposition(error: AdapterError) -> AdapterError { if error.disposition != DeliverySemantics::unknown() { return error; } @@ -39,29 +40,34 @@ pub fn execute_verified_action( request: ActionRequest, lease: &InteractionLease, ) -> Result { - execute_verified_deferred(adapter, handle, request, lease).0 + let deadline = lease.deadline(); + let (result, pending, _front) = execute_verified_deferred(adapter, handle, request, lease)?; + Ok(match pending { + Some(pending) => pending.settle(adapter, handle, deadline, result), + None => result, + }) } -/// As [`execute_verified_action`], with the rest of the front watch a spawned -/// helper can owe: the caller runs it once it has released the lease. +/// As [`execute_verified_action`], but a witness read still owed after the +/// delivery is returned instead of run, so the caller reads it once it has +/// released the interaction lease. pub(crate) fn execute_verified_deferred( adapter: &dyn PlatformAdapter, handle: &NativeHandle, request: ActionRequest, lease: &InteractionLease, -) -> (Result, Option) { +) -> Result<(ActionResult, Option, Option), AdapterError> { if !request.action.can_open_window() { - return ( - run_verified_action(adapter, handle, request, lease, &DispatchMark::default()), - None, - ); + let (result, pending) = + run_verified_action(adapter, handle, request, lease, &DispatchMark::default()); + return result.map(|result| (result, pending, None)); } let policy = request.policy; let target = request.expected_process.as_ref().map_or_else( crate::system::front_target::FrontTarget::default, |process| crate::system::front_target::FrontTarget::of_process(adapter, process.pid.get()), ); - let guarded = crate::system::front_guard::guarded_deferred( + let (result, front, front_pending) = crate::system::front_guard::guarded_deferred( adapter, policy, lease, @@ -71,37 +77,50 @@ pub(crate) fn execute_verified_deferred( after_release: true, }, |mark| run_verified_action(adapter, handle, request, lease, mark), - ); - let (result, front, pending) = match guarded { - Ok(guarded) => guarded, - Err(error) => return (Err(error), None), - }; - let result = result.map_err(|mut error| { + )?; + let (result, pending) = result; + let mut result = result.map_err(|mut error| { front.note_in_error(&mut error); error - }); - let result = result.map(|mut result| { - front.note_in(&mut result.details); - result - }); - (result, pending) + })?; + front.note_in(&mut result.details); + Ok((result, pending, front_pending)) } fn run_verified_action( adapter: &dyn PlatformAdapter, handle: &NativeHandle, - mut request: ActionRequest, + request: ActionRequest, lease: &InteractionLease, mark: &DispatchMark, -) -> Result { +) -> Witnessed { let action = request.action.clone(); + if action.witnesses_effect() { + return crate::actions::witnessed_action::dispatch_witnessed( + adapter, handle, request, lease, + ); + } if !action.requires_state_readback() { let result = adapter .execute_action(handle, request, lease) .map_err(settle_disposition); mark.dispatched(); - return result; + return (result, None); } + ( + run_readback_action(adapter, handle, request, lease, mark), + None, + ) +} + +fn run_readback_action( + adapter: &dyn PlatformAdapter, + handle: &NativeHandle, + mut request: ActionRequest, + lease: &InteractionLease, + mark: &DispatchMark, +) -> Result { + let action = request.action.clone(); let deadline = lease.deadline(); let before = matches!(action, Action::TypeText(_) | Action::Toggle) .then(|| adapter.get_live_element(handle, deadline).ok()) diff --git a/crates/core/src/actions/target_witness.rs b/crates/core/src/actions/target_witness.rs new file mode 100644 index 0000000000..543554ada9 --- /dev/null +++ b/crates/core/src/actions/target_witness.rs @@ -0,0 +1,10 @@ +use serde::{Deserialize, Serialize}; + +/// The target element's own state, as an action's witness reads it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TargetWitness { + pub selected: Option, + pub value: Option, + /// Open transient surfaces (a menu, a popover) directly below the target. + pub surfaces: Option, +} diff --git a/crates/core/src/actions/window_witness.rs b/crates/core/src/actions/window_witness.rs new file mode 100644 index 0000000000..8b8f6cc6b7 --- /dev/null +++ b/crates/core/src/actions/window_witness.rs @@ -0,0 +1,15 @@ +use serde::{Deserialize, Serialize}; + +/// The target's window and process, as an action's witness reads them. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct WindowWitness { + /// The window title, with its document where the platform names one. + pub title: Option, + /// A cheap sign of the window's content: equal signs mean that the + /// content the platform read did not change. + pub content: Option, + /// How many windows the target's process has. + pub windows: Option, + /// Whether the target's window is still one of its process's windows. + pub present: Option, +} diff --git a/crates/core/src/actions/witness_change.rs b/crates/core/src/actions/witness_change.rs new file mode 100644 index 0000000000..ced558b387 --- /dev/null +++ b/crates/core/src/actions/witness_change.rs @@ -0,0 +1,37 @@ +use serde::{Deserialize, Serialize}; + +/// One change between two witness reads around an action. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WitnessChange { + /// The target could not be read after the action: it was closed or replaced. + TargetGone, + /// The target's window is no longer one of its process's windows. + WindowClosed, + TargetSelected, + TargetValue, + SurfaceOpened, + FocusIntoTarget, + FocusMovedInWindow, + FocusedValue, + WindowTitle, + WindowContent, + WindowCount, +} + +impl WitnessChange { + /// A change that only the action explains. A window title, the window's + /// content, the number of windows, the target's value and focus moving + /// elsewhere in the window can also change by themselves (a timer, a + /// playing scrubber, a notification), so they are weak evidence. + pub fn is_strong(self) -> bool { + matches!( + self, + Self::TargetGone + | Self::WindowClosed + | Self::TargetSelected + | Self::SurfaceOpened + | Self::FocusIntoTarget + ) + } +} diff --git a/crates/core/src/actions/witnessed_action.rs b/crates/core/src/actions/witnessed_action.rs new file mode 100644 index 0000000000..b4b6ed337b --- /dev/null +++ b/crates/core/src/actions/witnessed_action.rs @@ -0,0 +1,201 @@ +//! The effect witness around an action whose effect lands outside the +//! target's own state: a click, a select. The adapter reads a witness before +//! the action; the dispatch result chooses one of two explicit steps; a strong +//! change upgrades a delivery to verified, and the verdict and the changes are +//! reported. A delivered result never becomes undelivered, an unclear answer +//! with a strong change becomes a verified success, and the witness never +//! makes an error of its own. + +use crate::actions::{ + effect_witness::{EffectWitness, verdict}, + observed_effect::ObservedEffect, + witness_change::WitnessChange, +}; +use crate::{ + ActionRequest, ActionResult, AdapterError, DeliverySemantics, ErrorCode, InteractionLease, + NativeHandle, PlatformAdapter, +}; + +/// What the witness does once the action was dispatched. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum WitnessStep { + /// Nothing was sent, or the adapter already proved the effect: no read. + Leave, + /// Sent without proof, or the platform's answer was unclear: one read, no + /// wait. An effect that lands later is for the caller to wait for. + Read, +} + +pub(crate) fn witness_step(dispatch: &Result) -> WitnessStep { + match dispatch { + Ok(result) if result.disposition() == DeliverySemantics::delivered_unverified() => { + WitnessStep::Read + } + Err(error) if error.disposition == DeliverySemantics::uncertain() => WitnessStep::Read, + Ok(_) | Err(_) => WitnessStep::Leave, + } +} + +/// How long one witness read waits. The witness is a single read that never +/// waits for an effect to land, so an application that does not answer it, for +/// example one that has just opened a modal dialog, costs this much and no more. +pub(crate) const WITNESS_READ_BUDGET: std::time::Duration = std::time::Duration::from_millis(500); + +/// The witness read that follows a delivered action, kept for the caller to +/// run once it has released the interaction lease: the lease covers resolving +/// the target and dispatching to it, not waiting for the application to answer. +pub(crate) struct PendingWitness { + before: EffectWitness, +} + +impl PendingWitness { + pub(crate) fn settle( + self, + adapter: &dyn PlatformAdapter, + handle: &NativeHandle, + deadline: crate::Deadline, + result: ActionResult, + ) -> ActionResult { + let after = adapter.read_effect_witness(handle, deadline.capped(WITNESS_READ_BUDGET)); + match after_changes(after, &self.before) { + Some(changes) => with_changes(result, &changes), + None => adapter_proof(result), + } + } +} + +/// A dispatch result and the witness read still owed for it. +pub(crate) type Witnessed = (Result, Option); + +pub(crate) fn dispatch_witnessed( + adapter: &dyn PlatformAdapter, + handle: &NativeHandle, + request: ActionRequest, + lease: &InteractionLease, +) -> Witnessed { + let deadline = lease.deadline(); + let action_name = request.action.name(); + let before = adapter + .read_effect_witness(handle, deadline.capped(WITNESS_READ_BUDGET)) + .ok(); + let dispatch = adapter + .execute_action(handle, request, lease) + .map_err(crate::actions::post_action::settle_disposition); + let Some(before) = before else { + return (dispatch, None); + }; + match (witness_step(&dispatch), dispatch) { + (WitnessStep::Read, Ok(result)) => (Ok(result), Some(PendingWitness { before })), + (WitnessStep::Read, Err(error)) => { + let after = adapter.read_effect_witness(handle, deadline.capped(WITNESS_READ_BUDGET)); + let settled = match after_changes(after, &before) { + Some(changes) => settle_unclear_answer(error, &changes, action_name), + None => Err(error), + }; + (settled, None) + } + (WitnessStep::Leave, dispatch) => (dispatch.map(adapter_proof), None), + } +} + +#[cfg(test)] +pub(crate) fn execute_witnessed_action( + adapter: &dyn PlatformAdapter, + handle: &NativeHandle, + request: ActionRequest, + lease: &InteractionLease, +) -> Result { + match dispatch_witnessed(adapter, handle, request, lease) { + (Ok(result), Some(pending)) => { + Ok(pending.settle(adapter, handle, lease.deadline(), result)) + } + (dispatch, _) => dispatch, + } +} + +/// The changes since `before`, or none when the witness could not be read. +/// Only a confirmed, non-retryable `StaleRef` means the target is gone; +/// transient or retryable read failures stay indeterminate and never upgrade +/// delivery. +fn after_changes( + after: Result, + before: &EffectWitness, +) -> Option> { + match after { + Ok(after) => Some(after.changes_since(before)), + Err(error) if is_confirmed_target_gone(&error) => Some(vec![WitnessChange::TargetGone]), + Err(_) => None, + } +} + +fn is_confirmed_target_gone(error: &AdapterError) -> bool { + if error.code != ErrorCode::StaleRef || error.is_explicitly_retryable() { + return false; + } + let details_retryable = error + .details + .as_ref() + .and_then(|details| details.get("retryable")) + .and_then(serde_json::Value::as_bool) + == Some(true); + !details_retryable +} + +fn adapter_proof(result: ActionResult) -> ActionResult { + if result.disposition() == DeliverySemantics::delivered_verified() { + result.with_effect(ObservedEffect::Observed) + } else { + result + } +} + +fn with_changes(result: ActionResult, changes: &[WitnessChange]) -> ActionResult { + let effect = verdict(changes); + let result = if effect == ObservedEffect::Observed { + result.with_verified_delivery() + } else { + result + }; + let mut result = result.with_effect(effect); + if !changes.is_empty() { + let details = result.details.get_or_insert_with(|| serde_json::json!({})); + if let Some(details) = details.as_object_mut() { + details.insert("witness_diff".into(), serde_json::json!(changes)); + } + } + result +} + +/// An unclear answer is settled by what the witness saw. A strong change +/// proves the action landed, so the command succeeds as a verified delivery +/// and keeps the platform's report in `details`. Any other verdict leaves the +/// error as the platform reported it, with the verdict added. +fn settle_unclear_answer( + mut error: AdapterError, + changes: &[WitnessChange], + action: &str, +) -> Result { + let effect = verdict(changes); + if effect == ObservedEffect::Observed { + let report = serde_json::json!({ + "code": error.code, + "message": error.message, + "details": error.details, + }); + let result = ActionResult::delivered_unverified(action) + .with_details(serde_json::json!({ "platform_report": report })); + return Ok(with_changes(result, changes)); + } + let details = error.details.get_or_insert_with(|| serde_json::json!({})); + if let Some(details) = details.as_object_mut() { + details.insert("effect".into(), serde_json::json!(effect)); + if !changes.is_empty() { + details.insert("witness_diff".into(), serde_json::json!(changes)); + } + } + Err(error) +} + +#[cfg(test)] +#[path = "witnessed_action_tests.rs"] +mod tests; diff --git a/crates/core/src/actions/witnessed_action_tests.rs b/crates/core/src/actions/witnessed_action_tests.rs new file mode 100644 index 0000000000..7bbeeecbf3 --- /dev/null +++ b/crates/core/src/actions/witnessed_action_tests.rs @@ -0,0 +1,273 @@ +use std::collections::VecDeque; +use std::sync::Mutex; + +use super::*; +use crate::{Action, ActionOps, Deadline, InputOps, ObservationOps, ObservedEffect, SystemOps}; + +/// Witness reads in order: the first is the read before the action. +struct Adapter { + reads: Mutex>>, + dispatch: Result, + read_count: Mutex, +} + +impl ObservationOps for Adapter { + fn read_effect_witness( + &self, + _: &NativeHandle, + _: Deadline, + ) -> Result { + *self.read_count.lock().unwrap() += 1; + let mut reads = self.reads.lock().unwrap(); + if reads.len() > 1 { + reads.pop_front().unwrap() + } else { + reads.front().cloned().unwrap() + } + } +} + +impl ActionOps for Adapter { + fn execute_action( + &self, + _: &NativeHandle, + _: ActionRequest, + _: &InteractionLease, + ) -> Result { + self.dispatch.clone() + } +} + +impl InputOps for Adapter {} +impl SystemOps for Adapter {} + +fn witness(selected: bool, title: &str) -> EffectWitness { + let mut witness = EffectWitness::default(); + witness.target.selected = Some(selected); + witness.window.title = Some(title.into()); + witness +} + +fn adapter( + reads: Vec>, + dispatch: Result, +) -> Adapter { + Adapter { + reads: Mutex::new(reads.into()), + dispatch, + read_count: Mutex::new(0), + } +} + +fn run(adapter: &Adapter) -> Result { + execute_witnessed_action( + adapter, + &NativeHandle::null(), + ActionRequest::headless(Action::Click), + &InteractionLease::guarded(Deadline::after(2000).unwrap(), ()).unwrap(), + ) +} + +fn unverified() -> Result { + Ok(ActionResult::delivered_unverified("click")) +} + +fn uncertain() -> Result { + Err(AdapterError::new(ErrorCode::ActionFailed, "unclear") + .with_disposition(DeliverySemantics::uncertain())) +} + +#[test] +fn the_dispatch_result_chooses_the_step() { + assert_eq!(witness_step(&unverified()), WitnessStep::Read); + assert_eq!(witness_step(&uncertain()), WitnessStep::Read); + let verified = ActionResult::delivered_unverified("click").with_verified_delivery(); + assert_eq!(witness_step(&Ok(verified)), WitnessStep::Leave); + let refused = Err(AdapterError::new(ErrorCode::PolicyDenied, "no") + .with_disposition(DeliverySemantics::not_delivered())); + assert_eq!(witness_step(&refused), WitnessStep::Leave); +} + +#[test] +fn a_strong_change_verifies_a_delivery_with_one_read() { + let adapter = adapter( + vec![Ok(witness(false, "A")), Ok(witness(true, "A"))], + unverified(), + ); + let result = run(&adapter).unwrap(); + + assert_eq!( + result.disposition(), + DeliverySemantics::delivered_verified() + ); + assert_eq!(result.effect, Some(ObservedEffect::Observed)); + assert_eq!( + result.details.unwrap()["witness_diff"], + serde_json::json!(["target_selected"]) + ); + assert_eq!(*adapter.read_count.lock().unwrap(), 2); +} + +#[test] +fn a_weak_or_no_change_leaves_the_delivery_as_it_was() { + for (after, effect) in [ + (witness(false, "B"), ObservedEffect::Indeterminate), + (witness(false, "A"), ObservedEffect::NotObserved), + ] { + let adapter = adapter(vec![Ok(witness(false, "A")), Ok(after)], unverified()); + let result = run(&adapter).unwrap(); + + assert_eq!( + result.disposition(), + DeliverySemantics::delivered_unverified() + ); + assert_eq!(result.effect, Some(effect)); + } +} + +#[test] +fn an_unclear_answer_with_a_strong_change_is_a_verified_success() { + let adapter = adapter( + vec![Ok(witness(false, "A")), Ok(witness(true, "A"))], + uncertain(), + ); + let result = run(&adapter).expect("an observed effect is a success"); + + assert_eq!( + result.disposition(), + DeliverySemantics::delivered_verified() + ); + assert_eq!(result.effect, Some(ObservedEffect::Observed)); + let details = result.details.unwrap(); + assert_eq!( + details["witness_diff"], + serde_json::json!(["target_selected"]) + ); + assert_eq!(details["platform_report"]["message"], "unclear"); + assert_eq!(*adapter.read_count.lock().unwrap(), 2); +} + +#[test] +fn an_unclear_answer_with_no_change_stays_uncertain_without_a_wait() { + let clock = crate::wait::deadline::VirtualClock::freeze(); + let adapter = adapter( + vec![ + Ok(witness(false, "A")), + Ok(witness(false, "A")), + Ok(witness(true, "A")), + ], + uncertain(), + ); + let error = run(&adapter).unwrap_err(); + + assert_eq!(error.disposition, DeliverySemantics::uncertain()); + assert_eq!(error.details.unwrap()["effect"], "not_observed"); + assert_eq!(*adapter.read_count.lock().unwrap(), 2); + assert_eq!(clock.elapsed(), std::time::Duration::ZERO); +} + +#[test] +fn a_target_gone_after_the_action_is_a_strong_change() { + let adapter = adapter( + vec![ + Ok(witness(false, "A")), + Err(AdapterError::stale_ref_because("gone")), + ], + unverified(), + ); + let result = run(&adapter).unwrap(); + + assert_eq!(result.effect, Some(ObservedEffect::Observed)); + assert_eq!( + result.details.unwrap()["witness_diff"], + serde_json::json!(["target_gone"]) + ); +} + +#[test] +fn a_transient_or_retryable_after_read_failure_never_upgrades_delivery() { + for error in [ + AdapterError::stale_ref_because("unsettled").with_details(serde_json::json!({ + "complete": false, + "retryable": true, + })), + AdapterError::timeout("busy").with_details(serde_json::json!({ "retryable": true })), + AdapterError::new(ErrorCode::AppUnresponsive, "hung"), + ] { + let unverified_adapter = adapter( + vec![Ok(witness(false, "A")), Err(error.clone())], + unverified(), + ); + let result = run(&unverified_adapter).unwrap(); + assert_eq!( + result.disposition(), + DeliverySemantics::delivered_unverified() + ); + assert_eq!(result.effect, None); + + let uncertain_adapter = adapter( + vec![Ok(witness(false, "A")), Err(error)], + Err(AdapterError::timeout("reply timed out") + .with_disposition(DeliverySemantics::uncertain())), + ); + let err = run(&uncertain_adapter).unwrap_err(); + assert_eq!(err.disposition, DeliverySemantics::uncertain()); + } +} + +#[test] +fn no_witness_and_an_undelivered_action_are_left_alone() { + let unsupported = adapter( + vec![Err(AdapterError::not_supported("read_effect_witness"))], + unverified(), + ); + let result = run(&unsupported).unwrap(); + assert_eq!(result.effect, None); + assert_eq!( + result.disposition(), + DeliverySemantics::delivered_unverified() + ); + + let refused = adapter( + vec![Ok(witness(false, "A"))], + Err(AdapterError::new(ErrorCode::PolicyDenied, "no") + .with_disposition(DeliverySemantics::not_delivered())), + ); + assert_eq!( + run(&refused).unwrap_err().disposition, + DeliverySemantics::not_delivered() + ); + assert_eq!(*refused.read_count.lock().unwrap(), 1); +} + +#[test] +fn a_delivery_without_proof_is_read_once_without_a_wait() { + let adapter = adapter( + vec![ + Ok(witness(false, "A")), + Ok(witness(false, "A")), + Ok(witness(true, "A")), + ], + unverified(), + ); + let result = run(&adapter).unwrap(); + + assert_eq!(result.effect, Some(ObservedEffect::NotObserved)); + assert_eq!(*adapter.read_count.lock().unwrap(), 2); +} + +#[test] +fn a_refusal_that_sent_nothing_stays_an_error_whatever_the_target_does() { + for code in [ErrorCode::PolicyDenied, ErrorCode::ActionNotSupported] { + let adapter = adapter( + vec![Ok(witness(false, "A")), Ok(witness(true, "B"))], + Err(AdapterError::new(code.clone(), "refused") + .with_disposition(DeliverySemantics::not_delivered())), + ); + let error = run(&adapter).unwrap_err(); + + assert_eq!(error.code, code); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(*adapter.read_count.lock().unwrap(), 1); + } +} diff --git a/crates/core/src/adapter/focused_window_key.rs b/crates/core/src/adapter/focused_window_key.rs index 89b320c1bd..9c1a64801f 100644 --- a/crates/core/src/adapter/focused_window_key.rs +++ b/crates/core/src/adapter/focused_window_key.rs @@ -26,9 +26,8 @@ fn exact_focus_unconfirmed(window: &WindowInfo, policy: InteractionPolicy) -> Ad /// 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( +/// default of `SystemOps::press_key_for_window`. +pub(crate) fn press_key_in_focused_window( adapter: &A, window: &WindowInfo, combo: &KeyCombo, diff --git a/crates/core/src/adapter/observation.rs b/crates/core/src/adapter/observation.rs index adebf159c1..f38e2f359d 100644 --- a/crates/core/src/adapter/observation.rs +++ b/crates/core/src/adapter/observation.rs @@ -205,6 +205,18 @@ pub trait ObservationOps: Send + Sync { Err(AdapterError::not_supported("get_live_element")) } + /// Reads the effect witness of `handle`: its own state, the application's + /// focused element and its window, as an action can change them. Read + /// before and after a click or a select; a field the platform cannot read + /// is `None`. + fn read_effect_witness( + &self, + _handle: &NativeHandle, + _deadline: Deadline, + ) -> Result { + Err(AdapterError::not_supported("read_effect_witness")) + } + fn get_element_bounds( &self, _handle: &NativeHandle, diff --git a/crates/core/src/adapter/system.rs b/crates/core/src/adapter/system.rs index d6d62371b2..c7e57b128e 100644 --- a/crates/core/src/adapter/system.rs +++ b/crates/core/src/adapter/system.rs @@ -1,11 +1,11 @@ use crate::{ AdapterError, AdapterSession, AppInfo, CursorOverlayControl, Deadline, DeliverySemantics, - DismissAllNotificationsRequest, DismissNotificationRequest, ErrorCode, ImageBuffer, - InteractionLease, InteractionPolicy, KeyCombo, NotificationActionRequest, NotificationFilter, - NotificationInfo, OperationReport, PermissionReport, PermissionState, ProcessIdentity, - ProviderScriptOutput, ProviderScriptRequest, SessionAffinity, SignalBaseline, SignalFilter, - WindowInfo, WindowOp, actions::action_result::ActionResult, system::display_info::DisplayInfo, - system::screenshot_target::ScreenshotTarget, + DismissAllNotificationsRequest, DismissNotificationRequest, ErrorCode, FrontWindow, + ImageBuffer, InteractionLease, InteractionPolicy, KeyCombo, NotificationActionRequest, + NotificationFilter, NotificationInfo, OperationReport, PermissionReport, PermissionState, + ProcessIdentity, ProviderScriptOutput, ProviderScriptRequest, SessionAffinity, SignalBaseline, + SignalFilter, WindowInfo, WindowOp, actions::action_result::ActionResult, + system::display_info::DisplayInfo, system::screenshot_target::ScreenshotTarget, }; pub trait SystemOps: Send + Sync { @@ -282,6 +282,21 @@ pub trait SystemOps: Send + Sync { super::focused_window_key::press_key_in_focused_window(self, window, combo, policy, lease) } + /// Closes the open transient surface (a menu, a drop-down, a popup) of + /// `window`, or of the process's windows when there is no window, through + /// the platform's own close action, verified by reading it gone. `Ok(None)` + /// when none is open. Core calls it only after a plain Escape was refused + /// because the target did not hold the keyboard. + fn close_transient_surface( + &self, + _process: &ProcessIdentity, + _window: Option<&WindowInfo>, + _policy: InteractionPolicy, + _lease: &InteractionLease, + ) -> Result, AdapterError> { + Err(AdapterError::not_supported("close_transient_surface")) + } + fn wait_for_menu( &self, _process: ProcessIdentity, @@ -296,34 +311,24 @@ pub trait SystemOps: Send + Sync { Err(AdapterError::not_supported("read_front")) } - /// The executable name and start time of `pid`, which the front guard - /// reads to tell the command target's new windows from the user's. fn front_process(&self, _pid: u32) -> Option { None } - /// The processes that descend from `root` and started at or after - /// `since_ms` (milliseconds since the Unix epoch) and are still running, - /// or `None` where the adapter cannot list them. The front guard uses it - /// to keep watching for a window a spawned helper has not yet shown. fn spawned_descendants(&self, _root: u32, _since_ms: u64) -> Option> { None } fn keep_below( &self, - _window: &crate::FrontWindow, - _above: &crate::FrontWindow, + _window: &FrontWindow, + _above: &FrontWindow, _lease: &InteractionLease, ) -> Result<(), AdapterError> { Err(AdapterError::not_supported("keep_below")) } - fn give_back( - &self, - _window: &crate::FrontWindow, - _lease: &InteractionLease, - ) -> Result<(), AdapterError> { + fn give_back(&self, _win: &FrontWindow, _lease: &InteractionLease) -> Result<(), AdapterError> { Err(AdapterError::not_supported("give_back")) } diff --git a/crates/core/src/commands/escape_route.rs b/crates/core/src/commands/escape_route.rs new file mode 100644 index 0000000000..a4cf65ed8e --- /dev/null +++ b/crates/core/src/commands/escape_route.rs @@ -0,0 +1,56 @@ +//! The route of a plain Escape that the key route refused for focus. +//! +//! The key route sends a key only to a target that holds the keyboard. A +//! menu, a drop-down or a popup can stay open in a window that does not, and +//! the key is then refused while the surface stays on the user's screen. The +//! states, in this order: the key route's result stands when it delivered or +//! refused for any other reason; after a refusal for focus, the adapter +//! closes the open transient surface of the target through the platform's +//! own close action, and that result stands, a failure of that attempt +//! included, because the attempt's own error says whether it may have +//! landed; the refusal stands only when no surface is open or the adapter +//! has no close route. + +use crate::{Action, ActionResult, AdapterError, DeliverySemantics, ErrorCode, KeyCombo}; + +/// The `details.check` values with which an adapter refuses a key because +/// the target window or process does not hold the keyboard. +const FOCUS_CHECKS: [&str; 3] = ["window_active", "exact_window_focus", "process_focus"]; + +pub(crate) fn is_plain_escape(combo: &KeyCombo) -> bool { + combo.modifiers.is_empty() && matches!(combo.key.as_str(), "escape" | "esc") +} + +pub(crate) fn refused_for_focus(error: &AdapterError) -> bool { + error.disposition == DeliverySemantics::not_delivered() + && error + .details + .as_ref() + .and_then(|details| details.get("check")) + .and_then(|check| check.as_str()) + .is_some_and(|check| FOCUS_CHECKS.contains(&check)) +} + +/// The key route's result, or the surface close after a refusal for focus. +pub(crate) fn settle( + keyed: Result, + combo: &KeyCombo, + close: impl FnOnce() -> Result, AdapterError>, +) -> Result { + match keyed { + Err(refusal) if is_plain_escape(combo) && refused_for_focus(&refusal) => match close() { + Ok(Some(mut closed)) => { + closed.action = Action::PressKey(combo.clone()).name().into(); + Ok(closed) + } + Ok(None) => Err(refusal), + Err(attempt) if attempt.code == ErrorCode::PlatformNotSupported => Err(refusal), + Err(attempt) => Err(attempt), + }, + keyed => keyed, + } +} + +#[cfg(test)] +#[path = "escape_route_tests.rs"] +mod tests; diff --git a/crates/core/src/commands/escape_route_tests.rs b/crates/core/src/commands/escape_route_tests.rs new file mode 100644 index 0000000000..17042ce3e4 --- /dev/null +++ b/crates/core/src/commands/escape_route_tests.rs @@ -0,0 +1,79 @@ +use super::settle; +use crate::{ActionResult, AdapterError, DeliverySemantics, ErrorCode, KeyCombo, Modifier}; + +fn key(name: &str, modifiers: Vec) -> KeyCombo { + KeyCombo { + key: name.into(), + modifiers, + } +} + +fn refusal(check: &str) -> Result { + Err(AdapterError::stale_ref_because("not focused") + .with_details(serde_json::json!({ "check": check })) + .with_disposition(DeliverySemantics::not_delivered())) +} + +fn closed() -> Result, AdapterError> { + Ok(Some( + ActionResult::delivered_unverified("collapse").with_verified_delivery(), + )) +} + +#[test] +fn a_focus_refusal_of_a_plain_escape_closes_the_open_surface() { + for check in ["window_active", "exact_window_focus", "process_focus"] { + let result = settle(refusal(check), &key("escape", vec![]), closed).unwrap(); + assert_eq!(result.action, "press"); + assert_eq!( + result.disposition(), + DeliverySemantics::delivered_verified() + ); + } +} + +#[test] +fn a_close_attempt_that_failed_reports_its_own_error() { + let attempt = || -> Result, AdapterError> { + Err(AdapterError::new(ErrorCode::Timeout, "no reply") + .with_disposition(DeliverySemantics::uncertain())) + }; + let error = settle(refusal("window_active"), &key("escape", vec![]), attempt).unwrap_err(); + + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.disposition, DeliverySemantics::uncertain()); +} + +#[test] +fn the_refusal_stands_without_an_open_surface_or_a_close_route() { + for close in [ + || Ok(None), + || Err(AdapterError::not_supported("close_transient_surface")), + ] as [fn() -> Result, AdapterError>; 2] + { + let error = settle(refusal("window_active"), &key("escape", vec![]), close).unwrap_err(); + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + } +} + +#[test] +fn every_other_key_result_is_left_as_the_key_route_gave_it() { + let never = || -> Result, AdapterError> { panic!("no close") }; + let delivered = Ok(ActionResult::delivered_unverified("press")); + assert!(settle(delivered, &key("escape", vec![]), never).is_ok()); + assert!( + settle( + refusal("window_active"), + &key("escape", vec![Modifier::Shift]), + never + ) + .is_err() + ); + assert!(settle(refusal("window_active"), &key("return", vec![]), never).is_err()); + assert!(settle(refusal("geometry"), &key("escape", vec![]), never).is_err()); + let sent = Err(AdapterError::new(ErrorCode::ActionFailed, "sent") + .with_details(serde_json::json!({ "check": "window_active" })) + .with_disposition(DeliverySemantics::delivered_unverified())); + assert!(settle(sent, &key("escape", vec![]), never).is_err()); +} diff --git a/crates/core/src/commands/helpers.rs b/crates/core/src/commands/helpers.rs index c9927b62cc..9193787ef0 100644 --- a/crates/core/src/commands/helpers.rs +++ b/crates/core/src/commands/helpers.rs @@ -111,14 +111,10 @@ pub(crate) fn execute_ref_action_landing( let lease_hold_ms = u64::try_from(landing.lease_started.elapsed().as_millis()).unwrap_or(u64::MAX); drop(landing.lease); - let mut result = landing.result; - crate::ref_action::ref_action_dispatched::read_surfaces_after_release( - adapter, - landing.after_release, - &landing.handle, - landing.deadline, - &mut result, - ); + let result = + landing + .after_release + .settle(adapter, &landing.handle, landing.deadline, landing.result); let value = serde_json::to_value(result).map_err(|error| { post_delivery_error(AppError::Json(error), json!({ "action": "delivered" })) })?; diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rs index 1e008f603a..5340c6ee9e 100644 --- a/crates/core/src/commands/mod.rs +++ b/crates/core/src/commands/mod.rs @@ -13,6 +13,7 @@ pub mod dismiss_all_notifications; pub mod dismiss_notification; pub mod double_click; pub mod drag; +pub(crate) mod escape_route; pub mod execute_by_ref; pub mod expand; pub mod find; diff --git a/crates/core/src/commands/press.rs b/crates/core/src/commands/press.rs index 52b5dc1387..6d551c66f2 100644 --- a/crates/core/src/commands/press.rs +++ b/crates/core/src/commands/press.rs @@ -49,13 +49,16 @@ pub fn execute( )?, }; } - if !context.physical_input_policy().is_headed() - && let Some(window) = &window - { - adapter.press_key_for_window(window, &combo, context.physical_input_policy(), &lease)? - } else { - adapter.press_key_for_app(process, &combo, context.physical_input_policy(), &lease)? - } + let policy = context.physical_input_policy(); + let keyed = match &window { + Some(window) if !policy.is_headed() => { + adapter.press_key_for_window(window, &combo, policy, &lease) + } + _ => adapter.press_key_for_app(process.clone(), &combo, policy, &lease), + }; + super::escape_route::settle(keyed, &combo, || { + adapter.close_transient_surface(&process, window.as_ref(), policy, &lease) + })? } else { context .physical_input_policy() diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index f6c349b0fb..2a3acf54ff 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -34,14 +34,19 @@ pub use actions::delivery_observation::DeliveryObservation; pub use actions::delivery_outcome::DeliveryOutcome; pub use actions::delivery_semantics::DeliverySemantics; pub use actions::effect::Effect; +pub use actions::effect_witness::EffectWitness; +pub use actions::focus_witness::FocusWitness; pub use actions::headed_focus::{HeadedFocus, saved_ref_focus_window}; pub use actions::interaction_policy::InteractionPolicy; +pub use actions::observed_effect::ObservedEffect; pub use actions::post_action::execute_verified_action; pub use actions::step_mechanism::StepMechanism; +pub use actions::target_witness::TargetWitness; +pub use actions::window_witness::WindowWitness; +pub use actions::witness_change::WitnessChange; 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/ref_action/mod.rs b/crates/core/src/ref_action/mod.rs index 86b4f886b0..f9e4dd72a3 100644 --- a/crates/core/src/ref_action/mod.rs +++ b/crates/core/src/ref_action/mod.rs @@ -10,6 +10,7 @@ use crate::refs::{RefEntry, resolve_saved_ref::resolve_saved_ref}; use crate::{AdapterError, AppError, actionability}; use serde_json::json; +pub(crate) mod post_release; pub(crate) mod presentation; pub(crate) mod ref_action_actionability; pub(crate) mod ref_action_context; @@ -141,12 +142,8 @@ pub(crate) fn dispatch_resolved_landing( let presentation_action = request.action.clone(); let ripples = presentation::effect_ripples(&final_target, &presentation_action); presentation::before_dispatch(&final_target, &preflight, &presentation_action, lease); - let (dispatch_result, front) = crate::actions::post_action::execute_verified_deferred( - final_target.adapter, - final_target.handle, - request, - lease, - ); + let (dispatch_result, witness, front) = + post_release::dispatch_deferred(final_target.adapter, final_target.handle, request, lease); let mut preflight = preflight; if presentation::after_text_entry(&final_target, &presentation_action, &dispatch_result) { preflight.presentation_bounds = None; @@ -169,8 +166,9 @@ pub(crate) fn dispatch_resolved_landing( Ok(ref_action_dispatched::DispatchedAction { result, handle, - after_release: ref_action_dispatched::AfterRelease { + after_release: post_release::PostRelease { surfaces_of: raises_surface.then_some(expected_process), + witness, front, }, }) @@ -307,19 +305,21 @@ pub(crate) fn execute_resolved( let stability = actionability::StabilityExpectation::permissive(target.entry.geometry.bounds_hash); preflight_resolved(&target, &request, stability)?; - let resolved = resolve_saved_ref(target.adapter, target.entry, target.deadline, None)?; - let result = dispatch_resolved_landing(target.target, request, lease, Some(resolved)).map( - |mut dispatched| { - ref_action_dispatched::read_surfaces_after_release( + let resolved = Some(resolve_saved_ref( + target.adapter, + target.entry, + target.deadline, + None, + )?); + let result = + dispatch_resolved_landing(target.target, request, lease, resolved).map(|dispatched| { + dispatched.after_release.settle( target.adapter, - std::mem::take(&mut dispatched.after_release), &dispatched.handle, target.deadline, - &mut dispatched.result, - ); - dispatched.result - }, - ); + dispatched.result, + ) + }); finish_artifacts(target.target, &pre); result } diff --git a/crates/core/src/ref_action/post_release.rs b/crates/core/src/ref_action/post_release.rs new file mode 100644 index 0000000000..f69aabbf1b --- /dev/null +++ b/crates/core/src/ref_action/post_release.rs @@ -0,0 +1,70 @@ +use crate::actions::witnessed_action::PendingWitness; +use crate::system::front_pending::FrontPending; +use crate::{ + ActionRequest, ActionResult, AdapterError, Deadline, InteractionLease, NativeHandle, + PlatformAdapter, ProcessIdentity, +}; + +/// The reads a delivered ref action still owes once the interaction lease is +/// released: the effect witness after the dispatch, and the overlays an action +/// that may open a window raised. The lease covers resolving the target and +/// dispatching to it. An application that has just opened a modal answers +/// slowly, and no other agent should wait behind that. +#[derive(Default)] +pub(crate) struct PostRelease { + pub(crate) surfaces_of: Option, + pub(crate) witness: Option, + pub(crate) front: Option, +} + +impl PostRelease { + pub(crate) fn settle( + self, + adapter: &dyn PlatformAdapter, + landed_on: &NativeHandle, + deadline: Deadline, + result: ActionResult, + ) -> ActionResult { + let surfaces_of = self.surfaces_of; + let witness = self.witness; + let work = move || { + let mut result = match witness { + Some(witness) => witness.settle(adapter, landed_on, deadline, result), + None => result, + }; + if let Some(process) = surfaces_of { + result.surfaces = adapter + .surfaces_raised_by(process, landed_on, deadline) + .unwrap_or_default(); + } + result + }; + let Some(front) = self.front else { + return work(); + }; + let (mut result, resolution) = front.run_around(adapter, work); + resolution.outcome.note_in(&mut result.details); + if let Some(reason) = resolution.pending_reason { + crate::FrontOutcome::note_watch_in(reason, &mut result.details); + } + result + } +} + +/// Delivers the action under the lease and returns the witness read it still +/// owes, to run after the release. +pub(crate) fn dispatch_deferred( + adapter: &dyn PlatformAdapter, + handle: &NativeHandle, + request: ActionRequest, + lease: &InteractionLease, +) -> ( + Result, + Option, + Option, +) { + match crate::actions::post_action::execute_verified_deferred(adapter, handle, request, lease) { + Ok((result, witness, front)) => (Ok(result), witness, front), + Err(error) => (Err(error), None, None), + } +} diff --git a/crates/core/src/ref_action/ref_action_dispatched.rs b/crates/core/src/ref_action/ref_action_dispatched.rs index 7a22c031a2..aa1982798d 100644 --- a/crates/core/src/ref_action/ref_action_dispatched.rs +++ b/crates/core/src/ref_action/ref_action_dispatched.rs @@ -1,53 +1,11 @@ -use crate::system::front_pending::FrontPending; -use crate::{ActionResult, NativeHandle, PlatformAdapter, ProcessIdentity}; - -/// What a delivered ref action still owes after the caller has released the -/// interaction lease: the overlays an action that may open a window raised, -/// and the rest of the front watch when a spawned helper may still show one. -#[derive(Default)] -pub(crate) struct AfterRelease { - pub(crate) surfaces_of: Option, - pub(crate) front: Option, -} +use crate::ref_action::post_release::PostRelease; +use crate::{ActionResult, NativeHandle}; /// A ref action as the dispatch left it, at the acknowledgement: the result, -/// the element it landed on, and the process whose overlays the caller reads -/// after it has released the interaction lease. The overlay read is not part -/// of the hold: the lease covers resolving the target and dispatching to it. +/// the element it landed on, and the reads the caller makes after it has +/// released the interaction lease. pub(crate) struct DispatchedAction { pub(crate) result: ActionResult, pub(crate) handle: NativeHandle, - pub(crate) after_release: AfterRelease, -} - -/// An action that opens a sheet, menu, or alert leaves the caller staring at a -/// success envelope with no hint that the application is now waiting on a -/// dialog. Reporting the overlays saves a round of window archaeology. Purely -/// informational, so a failed read never disturbs delivered work. It runs after -/// the interaction lease is released: an application that has just opened a -/// modal answers slowly, and no other agent should wait behind that. -pub(crate) fn read_surfaces_after_release( - adapter: &dyn PlatformAdapter, - after_release: AfterRelease, - raised_by: &NativeHandle, - deadline: crate::Deadline, - result: &mut ActionResult, -) { - let surfaces_of = after_release.surfaces_of; - let read_overlays = |result: &mut ActionResult| { - if let Some(process) = surfaces_of { - result.surfaces = adapter - .surfaces_raised_by(process, raised_by, deadline) - .unwrap_or_default(); - } - }; - let Some(front) = after_release.front else { - read_overlays(result); - return; - }; - let ((), resolution) = front.run_around(adapter, || read_overlays(result)); - resolution.outcome.note_in(&mut result.details); - if let Some(reason) = resolution.pending_reason { - crate::FrontOutcome::note_watch_in(reason, &mut result.details); - } + pub(crate) after_release: PostRelease, } diff --git a/crates/core/src/ref_action/ref_action_landing.rs b/crates/core/src/ref_action/ref_action_landing.rs index 1105ab4752..31a20d810c 100644 --- a/crates/core/src/ref_action/ref_action_landing.rs +++ b/crates/core/src/ref_action/ref_action_landing.rs @@ -10,5 +10,5 @@ pub(crate) struct RefActionLanding { pub(crate) pre: crate::trace::trace_artifacts::ArtifactOutcome, pub(crate) deadline: Deadline, pub(crate) lease_started: std::time::Instant, - pub(crate) after_release: crate::ref_action::ref_action_dispatched::AfterRelease, + pub(crate) after_release: crate::ref_action::post_release::PostRelease, } diff --git a/crates/core/src/ref_action/ref_action_wait.rs b/crates/core/src/ref_action/ref_action_wait.rs index 703adadcc3..73363e5df3 100644 --- a/crates/core/src/ref_action/ref_action_wait.rs +++ b/crates/core/src/ref_action/ref_action_wait.rs @@ -20,13 +20,11 @@ pub(crate) fn execute_with_auto_wait( ) -> Result { let landing = execute_with_auto_wait_and_lease(context, request)?; drop(landing.lease); - let mut result = landing.result; - crate::ref_action::ref_action_dispatched::read_surfaces_after_release( + let result = landing.after_release.settle( context.adapter, - landing.after_release, &landing.handle, landing.deadline, - &mut result, + landing.result, ); crate::ref_action::finish_artifacts( RefActionContext::new(context, landing.deadline), diff --git a/crates/core/src/ref_action/ref_action_wait_lease_tests.rs b/crates/core/src/ref_action/ref_action_wait_lease_tests.rs index c4e290bdc9..21f07e6c5d 100644 --- a/crates/core/src/ref_action/ref_action_wait_lease_tests.rs +++ b/crates/core/src/ref_action/ref_action_wait_lease_tests.rs @@ -18,6 +18,7 @@ struct DoubleCheckAdapter { expected_deadline: Option, available_action: &'static str, surface_reads_under_lease: std::sync::Mutex>, + witness_reads: std::sync::Mutex>, census_gate: Option, shared_lease: Option>, element_name: &'static str, @@ -118,6 +119,18 @@ impl ObservationOps for DoubleCheckAdapter { crate::adapter::saved_ref_tree(root, "button", Some("Run")) } + fn read_effect_witness( + &self, + _handle: &NativeHandle, + deadline: crate::Deadline, + ) -> Result { + self.witness_reads.lock().unwrap().push(( + self.lease_held.load(Ordering::SeqCst), + deadline.remaining_ms(), + )); + Ok(crate::EffectWitness::default()) + } + fn list_surfaces( &self, _process: crate::ProcessIdentity, @@ -213,27 +226,6 @@ fn stability_revalidates_once_under_lease_before_dispatch() { assert!(!adapter.lease_held.load(Ordering::SeqCst)); } -/// The overlay read after a click that may open a window is a post-action -/// read: it must run once the interaction lease is released, so an -/// application that answers slowly while it opens a modal never holds the -/// lease for other agents. -#[test] -fn the_overlay_read_after_a_click_runs_after_the_lease_is_released() { - let _clock = crate::wait::deadline::VirtualClock::freeze(); - let adapter = adapter(1, 5_000, None); - run_with_entry( - &adapter, - ActionRequest::headless(Action::Click), - 5_000, - &entry(), - ); - - assert_eq!( - *adapter.surface_reads_under_lease.lock().unwrap(), - vec![false] - ); -} - fn entry_with_mismatched_bounds_hash() -> RefEntry { let mut stale = entry(); stale.geometry.bounds_hash = crate::Rect { @@ -346,6 +338,7 @@ fn adapter( expected_deadline, available_action: capability::CLICK, surface_reads_under_lease: std::sync::Mutex::new(Vec::new()), + witness_reads: std::sync::Mutex::new(Vec::new()), census_gate: None, shared_lease: None, element_name: "Run", diff --git a/crates/core/src/ref_action/ref_action_wait_release_tests.rs b/crates/core/src/ref_action/ref_action_wait_release_tests.rs index de80860e3b..f28d5c2bc5 100644 --- a/crates/core/src/ref_action/ref_action_wait_release_tests.rs +++ b/crates/core/src/ref_action/ref_action_wait_release_tests.rs @@ -1,5 +1,56 @@ use super::*; +/// The overlay read after a click that may open a window is a post-action +/// read: it must run once the interaction lease is released, so an +/// application that answers slowly while it opens a modal never holds the +/// lease for other agents. +#[test] +fn the_overlay_read_after_a_click_runs_after_the_lease_is_released() { + let _clock = crate::wait::deadline::VirtualClock::freeze(); + let adapter = adapter(1, 5_000, None); + run_with_entry( + &adapter, + ActionRequest::headless(Action::Click), + 5_000, + &entry(), + ); + + assert_eq!( + *adapter.surface_reads_under_lease.lock().unwrap(), + vec![false] + ); +} + +/// The witness read that follows a delivered click is a post-action read: an +/// application that has just opened a modal does not answer it, and the read +/// waited for the whole operation deadline while the lease was held. The read +/// before the dispatch stays under the lease; the one after it runs after the +/// release and waits no longer than the witness budget. +#[test] +fn the_witness_read_after_a_click_runs_after_the_release_within_its_budget() { + let _clock = crate::wait::deadline::VirtualClock::freeze(); + let adapter = adapter(1, 5_000, None); + run_with_entry( + &adapter, + ActionRequest::headless(Action::Click), + 5_000, + &entry(), + ); + + let reads = adapter.witness_reads.lock().unwrap().clone(); + assert_eq!(reads.len(), 2); + assert!( + reads[0].0, + "the read before the dispatch is under the lease" + ); + assert!( + !reads[1].0, + "the read after the dispatch is after the release" + ); + let budget = 500; + assert!(reads[0].1 <= budget && reads[1].1 <= budget, "{reads:?}"); +} + struct DisabledAfterLeaseAdapter { calls: AtomicU32, prelease_calls: u32, diff --git a/crates/linux/src/actions/adapter.rs b/crates/linux/src/actions/adapter.rs new file mode 100644 index 0000000000..f7b36a5f22 --- /dev/null +++ b/crates/linux/src/actions/adapter.rs @@ -0,0 +1,103 @@ +use agent_desktop_core::{ + ActionOps, ActionRequest, ActionResult, AdapterError, Deadline, InteractionLease, NativeHandle, +}; + +use crate::actions::headed_focus::headed_focus_on; +use crate::adapter::LinuxAdapter; +use crate::system::display::display_server::session_server; + +impl LinuxAdapter { + fn deliver( + &self, + handle: &NativeHandle, + request: ActionRequest, + lease: &InteractionLease, + ) -> Result { + let target = crate::tree::atspi_element(handle) + .ok() + .map(|element| element.pid()); + let result = match crate::system::tray::target_of(handle) { + Some(target) => crate::system::tray::execute(target, request, lease), + None => { + let outcome = crate::tree::atspi_element(handle) + .ok() + .filter(|element| crate::system::shell::is_shell_element(element)) + .and_then(|element| { + crate::system::shell::deliver::deliver(self.bus(), element, &request, lease) + }); + match outcome { + Some(result) => result, + None => crate::actions::execute_action(self.bus(), handle, request, lease), + } + } + }; + crate::system::interaction::action_clock::mark_outcome(target, &result); + result + } +} + +impl ActionOps for LinuxAdapter { + fn headed_focus_for_ref( + &self, + _entry: &agent_desktop_core::RefEntry, + request: &ActionRequest, + _deadline: Deadline, + ) -> Result, AdapterError> { + Ok(headed_focus_on(&session_server(), request)) + } + + fn headed_focus( + &self, + _handle: &NativeHandle, + request: &ActionRequest, + _deadline: Deadline, + ) -> Result, AdapterError> { + Ok(headed_focus_on(&session_server(), request)) + } + + fn foreground_effect( + &self, + handle: &NativeHandle, + request: &ActionRequest, + deadline: Deadline, + ) -> Result, AdapterError> { + crate::actions::foreground::foreground_effect(self.bus(), handle, request, deadline) + } + + fn scroll_ref_into_view( + &self, + entry: &agent_desktop_core::RefEntry, + handle: &NativeHandle, + _policy: agent_desktop_core::InteractionPolicy, + lease: &InteractionLease, + ) -> Result, AdapterError> { + crate::actions::scroll::scroll_ref::scroll(self.bus(), entry, handle, lease) + } + + fn execute_action( + &self, + handle: &NativeHandle, + request: ActionRequest, + lease: &InteractionLease, + ) -> Result { + self.deliver(handle, request, lease) + } + + fn refuse_before_scroll( + &self, + handle: &NativeHandle, + request: &ActionRequest, + lease: &InteractionLease, + ) -> Result<(), AdapterError> { + crate::actions::refuse_before_scroll(self.bus(), handle, request, lease) + } + + fn scroll_into_view( + &self, + handle: &NativeHandle, + _policy: agent_desktop_core::InteractionPolicy, + lease: &InteractionLease, + ) -> Result<(), AdapterError> { + crate::actions::before_pointer(crate::actions::scroll_into_view(self.bus(), handle, lease)) + } +} diff --git a/crates/linux/src/actions/headed_focus.rs b/crates/linux/src/actions/headed_focus.rs new file mode 100644 index 0000000000..bd3f8fa186 --- /dev/null +++ b/crates/linux/src/actions/headed_focus.rs @@ -0,0 +1,19 @@ +use agent_desktop_core::{ActionRequest, HeadedFocus}; + +use crate::system::display::display_server::DisplayServer; + +/// A Wayland session lets no client activate a window, so a headed action +/// there focuses nothing and reaches the element through its own route. +pub(crate) fn headed_focus_on( + server: &DisplayServer, + request: &ActionRequest, +) -> Option { + match server { + DisplayServer::Wayland => None, + _ => request.headed_focus(), + } +} + +#[cfg(test)] +#[path = "headed_focus_tests.rs"] +mod tests; diff --git a/crates/linux/src/actions/headed_focus_tests.rs b/crates/linux/src/actions/headed_focus_tests.rs new file mode 100644 index 0000000000..fcd03327f3 --- /dev/null +++ b/crates/linux/src/actions/headed_focus_tests.rs @@ -0,0 +1,16 @@ +use super::*; +use agent_desktop_core::Action; + +#[test] +fn a_headed_action_focuses_nothing_on_wayland_and_keeps_its_focus_on_x11() { + let set_value = ActionRequest::headed(Action::SetValue("x".into())); + let click = ActionRequest::headed(Action::Click); + assert_eq!(headed_focus_on(&DisplayServer::Wayland, &set_value), None); + assert_eq!(headed_focus_on(&DisplayServer::Wayland, &click), None); + let x11 = DisplayServer::X11(":0".into()); + assert_eq!(headed_focus_on(&x11, &set_value), Some(HeadedFocus::Window)); + assert_eq!( + headed_focus_on(&x11, &click), + Some(HeadedFocus::WindowAndCursor) + ); +} diff --git a/crates/linux/src/actions/mod.rs b/crates/linux/src/actions/mod.rs index ae0f00298f..cba681fa82 100644 --- a/crates/linux/src/actions/mod.rs +++ b/crates/linux/src/actions/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod action_call; +mod adapter; pub(crate) mod chain; pub(crate) mod click; pub(crate) mod context; @@ -6,6 +7,7 @@ pub(crate) mod disclosure; pub(crate) mod dispatch; pub(crate) mod focus; pub(crate) mod foreground; +pub(crate) mod headed_focus; pub(crate) mod live; pub(crate) mod native_menu; pub(crate) mod physical_target; diff --git a/crates/linux/src/adapter.rs b/crates/linux/src/adapter.rs index 3c7352178a..1a57e3ed3b 100644 --- a/crates/linux/src/adapter.rs +++ b/crates/linux/src/adapter.rs @@ -1,9 +1,9 @@ use agent_desktop_core::{ - AccessibilityNode, ActionOps, ActionRequest, ActionResult, AdapterError, AppInventory, - ClipboardContent, ClipboardFormat, Deadline, DragParams, ElementState, HitTestResult, InputOps, - InteractionLease, KeyCombo, LiveElement, MouseEvent, NativeHandle, ObservationOps, - ObservationRequest, ObservationRoot, ObservedTree, OperationReport, Point, ProcessIdentity, - Rect, RefEntry, SnapshotSurface, SurfaceInfo, TreeOptions, WindowFilter, WindowInfo, + AccessibilityNode, AdapterError, AppInventory, ClipboardContent, ClipboardFormat, Deadline, + DragParams, EffectWitness, ElementState, HitTestResult, InputOps, InteractionLease, KeyCombo, + LiveElement, MouseEvent, NativeHandle, ObservationOps, ObservationRequest, ObservationRoot, + ObservedTree, OperationReport, Point, ProcessIdentity, Rect, RefEntry, SnapshotSurface, + SurfaceInfo, TreeOptions, WindowFilter, WindowInfo, }; use crate::system::SharedBus; @@ -89,6 +89,14 @@ impl ObservationOps for LinuxAdapter { crate::tree::get_live_value(self.bus(), handle, deadline) } + fn read_effect_witness( + &self, + handle: &NativeHandle, + deadline: Deadline, + ) -> Result { + crate::tree::read_effect_witness(self.bus(), handle, deadline) + } + fn get_live_state( &self, handle: &NativeHandle, @@ -235,83 +243,6 @@ impl ObservationOps for LinuxAdapter { } } -impl LinuxAdapter { - fn deliver( - &self, - handle: &NativeHandle, - request: ActionRequest, - lease: &InteractionLease, - ) -> Result { - let target = crate::tree::atspi_element(handle) - .ok() - .map(|element| element.pid()); - let result = match crate::system::tray::target_of(handle) { - Some(target) => crate::system::tray::execute(target, request, lease), - None => { - let outcome = crate::tree::atspi_element(handle) - .ok() - .filter(|element| crate::system::shell::is_shell_element(element)) - .and_then(|element| { - crate::system::shell::deliver::deliver(self.bus(), element, &request, lease) - }); - match outcome { - Some(result) => result, - None => crate::actions::execute_action(self.bus(), handle, request, lease), - } - } - }; - crate::system::interaction::action_clock::mark_outcome(target, &result); - result - } -} - -impl ActionOps for LinuxAdapter { - fn foreground_effect( - &self, - handle: &NativeHandle, - request: &ActionRequest, - deadline: Deadline, - ) -> Result, AdapterError> { - crate::actions::foreground::foreground_effect(self.bus(), handle, request, deadline) - } - - fn scroll_ref_into_view( - &self, - entry: &agent_desktop_core::RefEntry, - handle: &NativeHandle, - _policy: agent_desktop_core::InteractionPolicy, - lease: &InteractionLease, - ) -> Result, AdapterError> { - crate::actions::scroll::scroll_ref::scroll(self.bus(), entry, handle, lease) - } - - fn execute_action( - &self, - handle: &NativeHandle, - request: ActionRequest, - lease: &InteractionLease, - ) -> Result { - self.deliver(handle, request, lease) - } - - fn refuse_before_scroll( - &self, - handle: &NativeHandle, - request: &ActionRequest, - lease: &InteractionLease, - ) -> Result<(), AdapterError> { - crate::actions::refuse_before_scroll(self.bus(), handle, request, lease) - } - - fn scroll_into_view( - &self, - handle: &NativeHandle, - _policy: agent_desktop_core::InteractionPolicy, - lease: &InteractionLease, - ) -> Result<(), AdapterError> { - crate::actions::before_pointer(crate::actions::scroll_into_view(self.bus(), handle, lease)) - } -} impl InputOps for LinuxAdapter { fn physical_pointer_refusal(&self) -> Option { match crate::input::backend::backend() { @@ -345,12 +276,7 @@ impl InputOps for LinuxAdapter { crate::input::deliver::drag(¶ms, lease) } - fn key_event( - &self, - _combo: &KeyCombo, - _down: bool, - _lease: &InteractionLease, - ) -> Result<(), AdapterError> { + fn key_event(&self, _: &KeyCombo, _: bool, _: &InteractionLease) -> Result<(), AdapterError> { Err(crate::input::standalone::reject_standalone( "key-down/key-up", )) diff --git a/crates/linux/src/system/adapter.rs b/crates/linux/src/system/adapter.rs index 2a7054e51b..53b7680a30 100644 --- a/crates/linux/src/system/adapter.rs +++ b/crates/linux/src/system/adapter.rs @@ -14,7 +14,7 @@ use crate::adapter::LinuxAdapter; use crate::notifications; use crate::system::{ close, - focus::key_dispatch, + focus::{escape_popup, key_dispatch}, interaction::{action_clock, interaction_lease, session}, launch, menu::{menu_surface, menu_wait}, @@ -189,6 +189,16 @@ impl SystemOps for LinuxAdapter { result } + fn close_transient_surface( + &self, + process: &ProcessIdentity, + window: Option<&WindowInfo>, + policy: InteractionPolicy, + lease: &InteractionLease, + ) -> Result, AdapterError> { + escape_popup::close_transient_surface(self.bus(), process, window, policy, lease) + } + fn is_blocked_combo(&self, combo: &KeyCombo) -> bool { crate::input::blocked_combo::is_blocked(combo) } diff --git a/crates/linux/src/system/focus/escape_popup.rs b/crates/linux/src/system/focus/escape_popup.rs index d4b86ec6fb..b2f044a845 100644 --- a/crates/linux/src/system/focus/escape_popup.rs +++ b/crates/linux/src/system/focus/escape_popup.rs @@ -1,26 +1,20 @@ -//! Escape for an application that does not own the active window. +//! The open popup of a window 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. +//! The key route sends Escape only to the active window, and core asks the +//! adapter to close the open transient surface when that key was refused for +//! focus. 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. The owner's +//! reply is the answer, so a rejected action delivers nothing and an owner +//! that does not answer leaves the delivery uncertain. 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, + InteractionLease, InteractionPolicy, KeyCombo, ProcessIdentity, StepMechanism, WindowInfo, }; use crate::actions::action_call::resolve_verb; @@ -46,24 +40,17 @@ 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 ESCAPE_KEY: &str = "escape"; 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 escape_action() -> Action { + Action::PressKey(KeyCombo { + key: ESCAPE_KEY.to_owned(), + modifiers: Vec::new(), + }) } fn bits(node: &WalkedNode) -> Option> { @@ -244,39 +231,24 @@ fn popup_outcome(reply: WriteReply, read_closed: impl FnOnce() -> Option) } } -/// The answer for a refused Escape: the popup attempt's own result, or its own -/// error, which already says whether that attempt may have landed. The refusal -/// stands only when the target window shows no 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( +/// The open native popup of the target window, closed through its owner when +/// it advertises a safe dismissal verb. `None` when no dismissible popup is +/// open, which leaves core's refusal as it was; every other result, the +/// attempt's own failure included, is the answer. +pub(crate) fn close_transient_surface( bus: &SharedBus, process: &ProcessIdentity, window: Option<&WindowInfo>, - combo: &KeyCombo, - deadline: Deadline, + _policy: InteractionPolicy, + lease: &InteractionLease, ) -> Result, AdapterError> { - close_popup_with(bus, process, window, combo, deadline) + close_popup_with(bus, process, window, lease.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()))?; @@ -329,13 +301,7 @@ fn close_popup_with( mechanism: StepMechanism::SemanticApi, run: Box::new(run), }]; - run_semantic_chain( - &Action::PressKey(combo.clone()), - &mut rungs, - deadline, - SUGGESTION, - ) - .map(Some) + run_semantic_chain(&escape_action(), &mut rungs, deadline, SUGGESTION).map(Some) } #[cfg(test)] diff --git a/crates/linux/src/system/focus/escape_popup_stage_tests.rs b/crates/linux/src/system/focus/escape_popup_stage_tests.rs index 9a59cdd85b..2dac419773 100644 --- a/crates/linux/src/system/focus/escape_popup_stage_tests.rs +++ b/crates/linux/src/system/focus/escape_popup_stage_tests.rs @@ -2,8 +2,7 @@ use std::cell::RefCell; use std::collections::VecDeque; use agent_desktop_core::{ - AdapterError, Deadline, DeliverySemantics, ErrorCode, KeyCombo, ProcessId, ProcessIdentity, - WindowInfo, + AdapterError, Deadline, DeliverySemantics, ErrorCode, ProcessId, ProcessIdentity, WindowInfo, }; use super::world::PopupWorld; @@ -54,13 +53,6 @@ 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"), @@ -211,8 +203,7 @@ fn a_process_that_changed_before_discovery_fails_closed() { ] { let world = World::matched(); *world.live.borrow_mut() = VecDeque::from([live]); - let error = - close_popup_with(&world, &process(), None, &escape(), deadline()).expect_err("refused"); + let error = close_popup_with(&world, &process(), None, deadline()).expect_err("refused"); assert_eq!(error.disposition, DeliverySemantics::not_delivered()); assert_eq!(world.count("windows"), 0); assert_eq!(world.count("owner"), 0); @@ -224,8 +215,7 @@ fn a_process_that_changed_before_discovery_fails_closed() { 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"); + let error = close_popup_with(&world, &process(), None, deadline()).expect_err("refused"); assert_eq!(error.disposition, DeliverySemantics::not_delivered()); assert_eq!(world.count("walk"), 0); assert_eq!(world.count("dismiss"), 0); @@ -236,8 +226,8 @@ 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"); + let error = + close_popup_with(&world, &process(), Some(&target), deadline()).expect_err("refused"); assert_eq!(error.disposition, DeliverySemantics::not_delivered()); assert_eq!(world.count("windows"), 0); assert_eq!(world.count("walk"), 0); @@ -252,8 +242,7 @@ fn a_process_that_changed_after_discovery_fails_closed() { Lookup::Found(facts(INSTANCE)), Lookup::Found(facts("boot:other")), ]); - let error = - close_popup_with(&world, &process(), None, &escape(), deadline()).expect_err("refused"); + let error = close_popup_with(&world, &process(), None, deadline()).expect_err("refused"); assert_eq!(error.disposition, DeliverySemantics::not_delivered()); assert_eq!(world.count("windows"), 1); assert_eq!(world.count("walk"), 0); @@ -264,8 +253,7 @@ fn a_process_that_changed_after_discovery_fails_closed() { 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"); + let error = close_popup_with(&world, &process(), None, deadline()).expect_err("refused"); assert_eq!(error.disposition, DeliverySemantics::not_delivered()); assert_eq!(world.count("owner"), 3); assert_eq!(world.count("dismiss"), 0); @@ -274,7 +262,7 @@ fn a_foreign_bus_owner_before_the_action_fails_closed() { #[test] fn matching_identity_and_bus_ownership_reach_the_action() { let world = World::matched(); - let settled = close_popup_with(&world, &process(), None, &escape(), deadline()) + let settled = close_popup_with(&world, &process(), None, deadline()) .expect("closed") .expect("a popup answered"); assert_eq!(settled.action, "press"); diff --git a/crates/linux/src/system/focus/escape_popup_tests.rs b/crates/linux/src/system/focus/escape_popup_tests.rs index 3e13608de8..645061382b 100644 --- a/crates/linux/src/system/focus/escape_popup_tests.rs +++ b/crates/linux/src/system/focus/escape_popup_tests.rs @@ -1,14 +1,8 @@ -use agent_desktop_core::{ - ActionResult, AdapterError, DeliveryOutcome, DeliverySemantics, ErrorCode, KeyCombo, Modifier, -}; -use serde_json::json; +use agent_desktop_core::DeliveryOutcome; -use super::{ - close_verbs, deepest_open_owner, is_focus_refusal, is_open_owner, is_plain_escape, - popup_answer, popup_open, popup_outcome, -}; +use super::{close_verbs, deepest_open_owner, is_open_owner, popup_open, popup_outcome}; use crate::actions::action_call::resolve_verb; -use crate::actions::write::mutation::{Abort, WriteKind, WriteReply, abort_error}; +use crate::actions::write::mutation::WriteReply; use crate::tree::properties::toolkit_trust::ToolkitKind; use crate::tree::test_support::helpers::{read_of, words}; use crate::tree::vocabulary::role_numbers::{ @@ -37,40 +31,6 @@ fn node( fn names(values: &[&str]) -> Vec { values.iter().map(|value| (*value).to_owned()).collect() } - -fn combo(key: &str, modifiers: Vec) -> KeyCombo { - KeyCombo { - key: key.to_owned(), - 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())]; @@ -177,39 +137,6 @@ fn a_rejected_owner_action_is_never_a_delivery() { ); } -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()); diff --git a/crates/linux/src/system/focus/escape_popup_world.rs b/crates/linux/src/system/focus/escape_popup_world.rs index abc25ed3a2..e6ffdec73f 100644 --- a/crates/linux/src/system/focus/escape_popup_world.rs +++ b/crates/linux/src/system/focus/escape_popup_world.rs @@ -13,7 +13,7 @@ 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}; +use crate::tree::{AtspiElement, ObservedRead, WalkedNode}; const SCAN_NODES: usize = 600; const OWNER_NODES: usize = 64; @@ -97,7 +97,13 @@ impl PopupWorld for SharedBus { ) -> 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(); + let target = Target { + bus: self, + handle: &handle, + element: owner, + deadline, + }; + let names = target.view()?.action_names().unwrap_or_default().to_vec(); Ok((names, verbs)) } diff --git a/crates/linux/src/system/focus/key_dispatch.rs b/crates/linux/src/system/focus/key_dispatch.rs index 60e73dbee9..0ffbc8d551 100644 --- a/crates/linux/src/system/focus/key_dispatch.rs +++ b/crates/linux/src/system/focus/key_dispatch.rs @@ -4,7 +4,6 @@ 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}; @@ -211,25 +210,6 @@ 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, @@ -239,7 +219,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()))?; - let result = press_in(Press { + press_in(Press { physical: &LiveWorld { bus, lease }, keys: &LiveKeys { bus }, process: &process, @@ -247,8 +227,7 @@ 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( @@ -265,23 +244,15 @@ pub(crate) fn press_key_for_window( .as_deref() .filter(|instance| !instance.is_empty()) .ok_or_else(window_identity_missing)?; - let process = ProcessIdentity::new(window.pid, instance); - let result = press_in(Press { + press_in(Press { physical: &LiveWorld { bus, lease }, keys: &LiveKeys { bus }, - process: &process, + process: &ProcessIdentity::new(window.pid, instance), 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 af1c08e774..386f4f22c4 100644 --- a/crates/linux/src/system/focus/mod.rs +++ b/crates/linux/src/system/focus/mod.rs @@ -29,7 +29,7 @@ pub(crate) fn focus_is_indeterminate(candidates: &[usize], decided: Option &'static [&'static str] { if role == Some(LIST_ITEM) && selectable == Some(true) && checkable == Some(false) { &["select", "toggle"] + } else if role == Some(PAGE_TAB) && selectable == Some(true) { + &["select", "click", "press", "activate"] } else { &["select"] } diff --git a/crates/linux/src/tree/capabilities/action_names_tests.rs b/crates/linux/src/tree/capabilities/action_names_tests.rs index 24b3007fad..492e20fa83 100644 --- a/crates/linux/src/tree/capabilities/action_names_tests.rs +++ b/crates/linux/src/tree/capabilities/action_names_tests.rs @@ -1,11 +1,14 @@ use agent_desktop_core::{Action, LocatorField}; -use super::{capabilities, capability_of, click_verbs, unsupported_entry_activation, verbs_for}; +use super::{ + capabilities, capability_of, click_verbs, selection_verbs, unsupported_entry_activation, + verbs_for, +}; use crate::system::process::toolkit_id::ToolkitId; use crate::tree::Field; use crate::tree::RawNode; use crate::tree::test_support::helpers::read_of; -use crate::tree::vocabulary::role_numbers::{CHECK_BOX, ENTRY, LIST_ITEM}; +use crate::tree::vocabulary::role_numbers::{CHECK_BOX, ENTRY, LIST_ITEM, PAGE_TAB}; use crate::tree::vocabulary::role_numbers::{MENU_ITEM, PUSH_BUTTON}; use crate::tree::vocabulary::state_bits::{CHECKABLE, SELECTABLE}; @@ -192,3 +195,13 @@ fn the_toolkit_is_read_only_for_a_text_role() { assert!(unsupported_entry_activation(Some(ENTRY), &names, counted)); assert_eq!(reads.get(), 1); } + +#[test] +fn a_selectable_tab_that_advertises_select_is_selected_by_the_verb_it_does_name() { + use crate::actions::action_call::resolve_verb; + let names = ["click".to_owned()]; + let advertised = selection_verbs(Some(PAGE_TAB), Some(true), Some(false)); + assert_eq!(resolve_verb(&names, advertised), Some(0)); + let unselectable = selection_verbs(Some(PAGE_TAB), Some(false), Some(false)); + assert_eq!(resolve_verb(&names, unselectable), None); +} diff --git a/crates/linux/src/tree/effect_witness.rs b/crates/linux/src/tree/effect_witness.rs new file mode 100644 index 0000000000..30d2b001c3 --- /dev/null +++ b/crates/linux/src/tree/effect_witness.rs @@ -0,0 +1,215 @@ +//! The effect witness of one element: what a click or a select can change +//! around it, read before and after the action. +//! +//! The target's own state comes from one bounded structure walk below it +//! (selected, and the popups that show below it) and the existing value +//! read. The window part comes from three reads in one step: the frame's name, +//! the frame's direct children and the application's frames. A field that the +//! reads cannot give stays `None`. The application's focused element is not +//! found cheaply on this platform, so the focus witness stays empty. + +use std::hash::{DefaultHasher, Hash, Hasher}; + +use agent_desktop_core::{ + AdapterError, Deadline, EffectWitness, ErrorCode, NativeHandle, TargetWitness, WindowWitness, +}; +use futures_util::future::join3; + +use crate::system::{REGISTRY_ROOT_PATH, SharedBus, within}; +use crate::tree::element::child_list::CHILD_LIST_LIMIT; +use crate::tree::menu::observe_menu::{rooted, scan_walk_structure}; +use crate::tree::properties::liveness::Liveness; +use crate::tree::properties::node_read::{NAME, get_one, string_value}; +use crate::tree::properties::read_purpose::ReadPurpose; +use crate::tree::vocabulary::role_numbers::{COMBO_BOX, MENU, POPUP_MENU, is_bulk_container}; +use crate::tree::vocabulary::state_bits::{EXPANDED, HAS_POPUP, SELECTED, SHOWING, StateBits}; +use crate::tree::walk::walker_expand::read_observed; +use crate::tree::{ + AtspiElement, ChildAddress, ObservedRead, WalkLimits, WalkedNode, atspi_element, list_children, +}; + +const TARGET_NODES: usize = 24; +const POPUP_CONTAINER_CHILDREN: usize = 16; + +fn bits_of(read: &ObservedRead) -> Option> { + read.node + .traits + .states + .present() + .map(|words| StateBits::new(words)) +} + +fn bits(node: &WalkedNode) -> Option> { + bits_of(&node.payload) +} + +/// The popup menus that show in a subtree, or `None` when a menu's states +/// could not be read or the walk stopped short of a node's children: an +/// uncounted popup would make a later whole read look like a popup the action +/// opened. A list, table or tree cut at its row limit hides only rows. +fn showing_popups(node: &WalkedNode) -> Option { + let role = node.payload.node.traits.role.present().copied(); + if node.truncated && !is_bulk_container(role) { + return None; + } + let own = match role { + Some(MENU | POPUP_MENU) => u32::from(bits(node)?.has(SHOWING)), + _ => 0, + }; + node.children + .iter() + .map(showing_popups) + .sum::>() + .map(|below| own + below) +} + +/// Whether a target can own a popup below it: a combo box, or an element that +/// reports the popup or expanded state. Any other element has none, so the +/// subtree below it is not read. +pub(crate) fn may_own_popup(role: Option, bits: &StateBits<'_>) -> bool { + role == Some(COMBO_BOX) || bits.has(HAS_POPUP) || bits.has(EXPANDED) +} + +/// The popups open below the target: the popup menus that show in its +/// subtree, or one when the target itself reports `EXPANDED`. +pub(crate) fn surfaces_of(target: &WalkedNode) -> Option { + let bits = bits(target)?; + let shown = showing_popups(target)?; + Some(if shown == 0 && bits.has(EXPANDED) { + 1 + } else { + shown + }) +} + +/// Whether the target's frame is still one of the application's frames, by +/// bus name and object path. +pub(crate) fn frame_listed(frames: &[ChildAddress], frame: &AtspiElement) -> bool { + frames + .iter() + .any(|(bus, path)| bus == frame.bus_name() && path == frame.path()) +} + +/// A sign of a list of children that changes when one is added, removed or +/// replaced. +pub(crate) fn content_sign(children: &[ChildAddress]) -> u64 { + let mut hasher = DefaultHasher::new(); + children.hash(&mut hasher); + hasher.finish() +} + +fn gone(error: AdapterError) -> AdapterError { + let retryable = error.is_explicitly_retryable() + || error + .details + .as_ref() + .and_then(|details| details.get("retryable")) + .and_then(serde_json::Value::as_bool) + == Some(true); + if retryable { + return error; + } + match error.code { + ErrorCode::ElementNotFound | ErrorCode::StaleRef | ErrorCode::AppNotFound => { + AdapterError::stale_ref_because("The target element is gone") + } + _ => error, + } +} + +fn target_witness( + bus: &SharedBus, + element: &AtspiElement, + deadline: Deadline, +) -> Result { + let connection = bus.get(deadline)?; + let (read, _) = within(deadline, async { + read_observed( + connection.inner(), + element, + WalkLimits::default().max_field_bytes, + ReadPurpose::State, + CHILD_LIST_LIMIT, + ) + .await + }) + .map_err(gone)?; + let role = read.node.traits.role.present().copied(); + let surfaces = match bits_of(&read) { + Some(bits) if may_own_popup(role, &bits) => scan_walk_structure( + bus, + &rooted(element), + TARGET_NODES, + Some(POPUP_CONTAINER_CHILDREN), + deadline, + ) + .map_err(gone) + .ok() + .and_then(|walk| surfaces_of(&walk)), + Some(_) => Some(0), + None => None, + }; + Ok(TargetWitness { + selected: bits_of(&read).map(|bits| bits.has(SELECTED)), + value: read.value.value.present().cloned(), + surfaces, + }) +} + +fn window_witness( + bus: &SharedBus, + frame: &AtspiElement, + deadline: Deadline, +) -> Result { + let connection = bus.get(deadline)?; + let application = AtspiElement::new(frame.bus_name(), REGISTRY_ROOT_PATH, frame.pid()); + let (name, children, frames) = within(deadline, async { + Ok(join3( + get_one( + connection.inner(), + frame, + NAME, + string_value, + Liveness::Alive, + ), + list_children(connection.inner(), frame), + list_children(connection.inner(), &application), + ) + .await) + })?; + Ok(WindowWitness { + title: name.ok().and_then(|name| name.present().cloned()), + content: children.ok().map(|children| content_sign(&children)), + present: frames + .as_ref() + .ok() + .map(|frames| frame_listed(frames, frame)), + windows: frames + .ok() + .and_then(|frames| u32::try_from(frames.len()).ok()), + }) +} + +/// Reads the effect witness of the element `handle` names. A target that is +/// gone answers a stale ref, which core counts as the target gone. +pub(crate) fn read_effect_witness( + bus: &SharedBus, + handle: &NativeHandle, + deadline: Deadline, +) -> Result { + let element = atspi_element(handle)?; + let target = target_witness(bus, element, deadline)?; + let window = match element.frame() { + Some(frame) => window_witness(bus, frame, deadline)?, + None => WindowWitness::default(), + }; + Ok(EffectWitness { + target, + window, + ..EffectWitness::default() + }) +} + +#[cfg(test)] +#[path = "effect_witness_tests.rs"] +mod tests; diff --git a/crates/linux/src/tree/effect_witness_tests.rs b/crates/linux/src/tree/effect_witness_tests.rs new file mode 100644 index 0000000000..5eb73fbfdf --- /dev/null +++ b/crates/linux/src/tree/effect_witness_tests.rs @@ -0,0 +1,83 @@ +use super::{frame_listed, may_own_popup, surfaces_of}; +use crate::tree::AtspiElement; +use crate::tree::test_support::helpers::{read_of, words}; +use crate::tree::vocabulary::role_numbers::{COMBO_BOX, LIST, MENU}; +use crate::tree::vocabulary::state_bits::{EXPANDED, HAS_POPUP, SHOWING, StateBits}; +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, + } +} + +#[test] +fn the_surfaces_of_a_target_are_the_popups_that_show_below_it() { + let shown = || node(MENU, &[SHOWING], Vec::new()); + let hidden = || node(MENU, &[], Vec::new()); + assert_eq!( + surfaces_of(&node(COMBO_BOX, &[], vec![shown(), shown()])), + Some(2) + ); + assert_eq!(surfaces_of(&node(COMBO_BOX, &[], vec![hidden()])), Some(0)); + assert_eq!( + surfaces_of(&node(COMBO_BOX, &[EXPANDED], vec![hidden()])), + Some(1) + ); + let mut unread = node(COMBO_BOX, &[], Vec::new()); + unread.payload.node.traits.states = Field::Failed("gone".to_owned()); + assert_eq!(surfaces_of(&unread), None); +} + +#[test] +fn a_popup_count_that_missed_a_menu_is_unknown() { + let mut menu_unread = node(MENU, &[], Vec::new()); + menu_unread.payload.node.traits.states = Field::Failed("gone".to_owned()); + assert_eq!(surfaces_of(&node(COMBO_BOX, &[], vec![menu_unread])), None); + + let mut cut = node(COMBO_BOX, &[], vec![node(MENU, &[], Vec::new())]); + cut.children[0].truncated = true; + assert_eq!(surfaces_of(&cut), None); + + let mut rows_cut = node(COMBO_BOX, &[], vec![node(LIST, &[], Vec::new())]); + rows_cut.children[0].truncated = true; + assert_eq!(surfaces_of(&rows_cut), Some(0)); +} + +#[test] +fn a_frame_is_present_while_the_application_still_lists_it() { + let frame = AtspiElement::new(":1.2", "/frame", 7); + let listed = vec![ + (":1.2".to_owned(), "/other".to_owned()), + (":1.2".to_owned(), "/frame".to_owned()), + ]; + assert!(frame_listed(&listed, &frame)); + assert!(!frame_listed(&listed[..1], &frame)); + assert!(!frame_listed( + &[(":1.3".to_owned(), "/frame".to_owned())], + &frame + )); +} + +#[test] +fn only_a_combo_box_or_a_popup_or_expanded_element_is_searched_for_popups() { + let none = words(&[]); + let popup = words(&[HAS_POPUP]); + let expanded = words(&[EXPANDED]); + assert!(may_own_popup(Some(COMBO_BOX), &StateBits::new(&none))); + assert!(may_own_popup(Some(43), &StateBits::new(&popup))); + assert!(may_own_popup(Some(43), &StateBits::new(&expanded))); + assert!(!may_own_popup(Some(43), &StateBits::new(&none))); + assert!(!may_own_popup(None, &StateBits::new(&none))); +} diff --git a/crates/linux/src/tree/mod.rs b/crates/linux/src/tree/mod.rs index caa2b57b6b..7016483c3b 100644 --- a/crates/linux/src/tree/mod.rs +++ b/crates/linux/src/tree/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod capabilities; +pub(crate) mod effect_witness; pub(crate) mod element; pub(crate) mod hit_test; pub(crate) mod live_read; @@ -13,6 +14,7 @@ pub(crate) mod test_support; pub(crate) mod vocabulary; mod walk; +pub(crate) use effect_witness::read_effect_witness; pub(crate) use element::AtspiElement; pub(crate) use element::atspi_element; pub(crate) use element::child_list::{child_at_index, list_children}; diff --git a/crates/macos/src/actions/activation_effect.rs b/crates/macos/src/actions/activation_effect.rs index b375b6f8cf..ffc910e9f7 100644 --- a/crates/macos/src/actions/activation_effect.rs +++ b/crates/macos/src/actions/activation_effect.rs @@ -1,132 +1,49 @@ +//! The readback for `perform`, which has no written attribute to re-read. A +//! press is delivered when the effect witness of its target changes the way a +//! press changes it: the target's selection turns on or its value changes, a +//! menu or popover opens below it, or focus moves into it or within its +//! window, or the focused element in its window shows new content. Focus +//! alone misses a whole family of controls (a sidebar row moves its selection, +//! a radio button turns its value on), so all of these are read. The window's +//! title and content are not read here: they can change by themselves. Only a +//! strong change (`WitnessChange::is_strong`) verifies the press, the same rule +//! core applies to the witness: a value or a focus move can change by itself. + #[cfg(target_os = "macos")] mod imp { - use agent_desktop_core::Deadline; + use agent_desktop_core::{Deadline, DeliveryObservation, EffectWitness, WitnessChange}; + use crate::actions::effect_witness; use crate::tree::AXElement; const SETTLE_POLL_MS: u64 = 40; const SETTLE_BUDGET_MS: u64 = 400; - const FOCUS_DESCENT_WALK: usize = 3; - - /// The readback for `perform`, which has no written attribute to re-read. - /// Focus alone misses a whole family of controls: a sidebar row answers an - /// unsupported code to the action that navigates it, and moves its - /// selection rather than the focus. Selection is therefore read as well, - /// on every element, because an attribute an element does not publish reads - /// as absent and the rule simply never fires for it. The focused editor's - /// value is read because a press can replace what that editor shows. The - /// pressed element's own value is read because a radio button answers - /// -25205 to the press that turns it on and publishes no `AXSelected`. - #[derive(Default)] - pub(crate) struct FocusState { - focused_element: Option, - focused_value: Option, - selected: Option, - own_value: Option, - menu_open: Option, - } - - /// Accessibility hands back a fresh reference for the same element on every - /// read, and reuses a released one for a different element later, so a raw - /// pointer answers neither question this comparison asks. `CFEqual` is the - /// identity the framework defines. - impl PartialEq for FocusState { - fn eq(&self, other: &Self) -> bool { - match (&self.focused_element, &other.focused_element) { - (None, None) => true, - (Some(mine), Some(theirs)) => crate::tree::same_element(mine, theirs), - _ => false, - } - } - } - impl FocusState { - pub(crate) fn focused_element(self) -> Option { - self.focused_element - } - } - - pub(crate) fn focus_state(element: &AXElement, deadline: Deadline) -> Option { - let app = crate::system::app::app_ops::pid_from_element(element, deadline) - .map(crate::tree::element_for_pid)?; - let focused_element = crate::tree::properties::attributes::copy_element_attr_result( - &app, - "AXFocusedUIElement", - deadline, - ) - .ok()?; - Some(FocusState { - focused_value: focused_element - .as_ref() - .and_then(|focused| crate::tree::copy_value_typed(focused, deadline)), - focused_element, - selected: crate::tree::properties::attributes::copy_bool_attr_result( - element, - crate::actions::select::container_select::SELECTED, - deadline, - ) - .ok() - .flatten(), - own_value: crate::tree::copy_value_typed(element, deadline), - menu_open: crate::actions::owned_menu::owned_menu_open(element, deadline), - }) + pub(crate) fn focus_state(element: &AXElement, deadline: Deadline) -> Option { + effect_witness::read_local(element, deadline).ok() } pub(crate) fn changed_now( - before: &Option, - element: &AXElement, - deadline: Deadline, - ) -> bool { - let after = focus_state(element, deadline); - let focused = after - .as_ref() - .and_then(|state| state.focused_element.as_ref()); - let target_focused = - focused.is_some_and(|focused| focus_reached(focused, element, deadline)); - observed_change(before, &after, target_focused) - || focus_changed_in_target_window(before, &after, || { - focused.and_then(|focused| shares_window(focused, element, deadline)) == Some(true) - }) - } - - /// A control that owns an editor hands focus to the editor, not to itself: - /// a PDF form field in Preview publishes a text area and focus lands there. - /// Demanding an exact match called that a failure and reported an action - /// that had plainly worked as one whose outcome was unknown. - pub(crate) fn focus_reached( - focused: &AXElement, + before: &Option, element: &AXElement, deadline: Deadline, - ) -> bool { - let mut current = focused.clone(); - for _ in 0..FOCUS_DESCENT_WALK { - if crate::tree::same_element(¤t, element) { - return true; - } - let Some(parent) = crate::tree::properties::attributes::copy_element_attr_result( - ¤t, "AXParent", deadline, - ) - .ok() - .flatten() else { - return false; - }; - current = parent; + ) -> Option { + match (before, focus_state(element, deadline)) { + (Some(before), Some(after)) => press_reaction(&after.changes_since(before)), + _ => None, } - false } pub(crate) fn settled_change( - before: &Option, + before: &Option, element: &AXElement, deadline: Deadline, - ) -> bool { - if before.is_none() { - return false; - } + ) -> Option { + before.as_ref()?; let deadline = deadline.capped(std::time::Duration::from_millis(SETTLE_BUDGET_MS)); while !deadline.is_expired() { - if changed_now(before, element, deadline) { - return true; + if let Some(reaction) = changed_now(before, element, deadline) { + return Some(reaction); } std::thread::sleep( deadline @@ -134,204 +51,39 @@ mod imp { .min(std::time::Duration::from_millis(SETTLE_POLL_MS)), ); } - false - } - - fn observed_change( - before: &Option, - after: &Option, - target_focused: bool, - ) -> bool { - let focus_moved_to_target = target_focused - && matches!((before, after), (Some(before), Some(after)) if before != after); - focus_moved_to_target - || selection_turned_on(before, after) - || own_value_changed(before, after) - || matches!( - ( - before.as_ref().and_then(|state| state.menu_open), - after.as_ref().and_then(|state| state.menu_open), - ), - (Some(false), Some(true)) - ) - } - - /// Focus moved, or the focused element shows new content, in the target's window. - fn focus_changed_in_target_window( - before: &Option, - after: &Option, - focused_in_target_window: impl FnOnce() -> bool, - ) -> bool { - matches!((before, after), (Some(before), Some(after)) - if after.focused_element.is_some() && (before != after - || matches!((&before.focused_value, &after.focused_value), (Some(old), Some(new)) if old != new))) - && focused_in_target_window() - } - - fn shares_window(focused: &AXElement, element: &AXElement, deadline: Deadline) -> Option { - let window = |el| { - crate::tree::properties::attributes::copy_element_attr_result(el, "AXWindow", deadline) - }; - Some(crate::tree::same_element( - &window(focused).ok()??, - &window(element).ok()??, - )) - } - - /// An element whose own value changed after the press was acted on: a - /// radio button or checkbox reads 0 before and 1 after. - fn own_value_changed(before: &Option, after: &Option) -> bool { - matches!( - ( - before.as_ref().and_then(|state| state.own_value.as_ref()), - after.as_ref().and_then(|state| state.own_value.as_ref()), - ), - (Some(old), Some(new)) if old != new - ) + None } - /// An element that was not selected and now is has been acted on, whatever - /// return code the application chose. The reverse is not evidence: a - /// selection that was already true says nothing about this action. - fn selection_turned_on(before: &Option, after: &Option) -> bool { - matches!( - ( - before.as_ref().and_then(|state| state.selected), - after.as_ref().and_then(|state| state.selected), - ), - (Some(false), Some(true)) - ) - } - - #[cfg(test)] - mod tests { - use super::*; - - fn focused(pid: i32) -> Option { - Some(FocusState { - focused_element: Some(crate::tree::element_for_pid(pid)), - ..FocusState::default() - }) - } - - fn selected(value: Option) -> Option { - Some(FocusState { - selected: value, - ..FocusState::default() - }) - } - - #[test] - fn a_focus_change_counts_only_inside_the_pressed_elements_window() { - let editor = |pid, value: &str| { - Some(FocusState { - focused_value: Some(value.into()), - ..focused(pid).unwrap_or_default() - }) - }; - let changed = - |old, new, in_window| focus_changed_in_target_window(&old, &new, || in_window); - assert!(changed(editor(1, "old note"), editor(1, ""), true)); - assert!(changed(focused(1), editor(2, ""), true)); - assert!(!changed(editor(1, "old note"), editor(1, ""), false)); - assert!(!changed(focused(1), editor(2, ""), false)); - assert!(!changed(editor(1, "same"), editor(1, "same"), true)); - assert!(!changed(editor(1, "old note"), focused(1), true)); - } - - #[test] - fn focus_changes_must_correlate_with_the_target() { - let before = focused(1); - let after = focused(2); - assert!(!observed_change(&before, &after, false)); - assert!(observed_change(&before, &after, true)); - assert!(!observed_change(&after, &after, true)); - } - - #[test] - fn a_selection_that_turned_on_is_an_effect_without_any_focus_move() { - assert!(observed_change( - &selected(Some(false)), - &selected(Some(true)), - false - )); - } - - #[test] - fn a_radio_value_that_turned_on_is_an_effect_and_an_unchanged_one_is_not() { - let valued = |value: Option<&str>| { - Some(FocusState { - own_value: value.map(str::to_owned), - ..FocusState::default() - }) - }; - assert!(observed_change( - &valued(Some("0")), - &valued(Some("1")), - false - )); - for (before, after) in [ - (Some("1"), Some("1")), - (None, Some("1")), - (Some("0"), None), - (None, None), - ] { - assert!( - !observed_change(&valued(before), &valued(after), false), - "before={before:?} after={after:?}" - ); + /// Whether the changes show the press reached the application, and + /// whether a strong one verifies it. + pub(crate) fn press_reaction(changes: &[WitnessChange]) -> Option { + press_delivered(changes).then(|| { + if changes.iter().any(|change| change.is_strong()) { + DeliveryObservation::Verified + } else { + DeliveryObservation::Unverified } - } - - #[test] - fn an_unchanged_or_unreadable_selection_proves_nothing() { - for (before, after) in [ - (Some(true), Some(true)), - (Some(false), Some(false)), - (Some(true), Some(false)), - (None, Some(true)), - (Some(false), None), - (None, None), - ] { - assert!( - !observed_change(&selected(before), &selected(after), false), - "before={before:?} after={after:?} must not count as an effect" - ); - } - } - - #[test] - fn missing_observation_cannot_verify_an_action() { - let before = Some(FocusState::default()); - let after = Some(FocusState::default()); - assert!(!observed_change(&before, &None, true)); - assert!(!observed_change(&None, &after, true)); - assert!(!observed_change(&None, &None, true)); - assert!(!observed_change(&before, &before, true)); - assert!(!observed_change(&before, &after, false)); - assert!(!observed_change(&before, &after, true)); - } + }) + } - #[test] - fn only_a_newly_visible_owned_menu_verifies_delivery() { - for before in [None, Some(false), Some(true)] { - for after in [None, Some(false), Some(true)] { - let state = |menu_open| { - Some(FocusState { - menu_open, - ..FocusState::default() - }) - }; - assert_eq!( - observed_change(&state(before), &state(after), false), - before == Some(false) && after == Some(true), - ); - } - } - } + /// The changes that show a press reached the application. + pub(crate) fn press_delivered(changes: &[WitnessChange]) -> bool { + changes.iter().any(|change| { + matches!( + change, + WitnessChange::TargetSelected + | WitnessChange::TargetValue + | WitnessChange::SurfaceOpened + | WitnessChange::FocusIntoTarget + | WitnessChange::FocusMovedInWindow + | WitnessChange::FocusedValue + ) + }) } } -#[cfg(target_os = "macos")] -pub(crate) use imp::focus_reached; pub(crate) use imp::{changed_now, focus_state, settled_change}; + +#[cfg(test)] +#[path = "activation_effect_tests.rs"] +mod tests; diff --git a/crates/macos/src/actions/activation_effect_tests.rs b/crates/macos/src/actions/activation_effect_tests.rs new file mode 100644 index 0000000000..983bc5bb33 --- /dev/null +++ b/crates/macos/src/actions/activation_effect_tests.rs @@ -0,0 +1,52 @@ +use super::imp::{press_delivered, press_reaction}; +use agent_desktop_core::{DeliveryObservation, WitnessChange}; + +#[test] +fn a_press_is_delivered_by_a_change_in_the_target_or_its_focus_but_not_by_the_window_alone() { + for change in [ + WitnessChange::TargetSelected, + WitnessChange::TargetValue, + WitnessChange::SurfaceOpened, + WitnessChange::FocusIntoTarget, + WitnessChange::FocusMovedInWindow, + WitnessChange::FocusedValue, + ] { + assert!(press_delivered(&[change]), "{change:?}"); + } + for change in [ + WitnessChange::WindowTitle, + WitnessChange::WindowContent, + WitnessChange::WindowCount, + WitnessChange::TargetGone, + ] { + assert!(!press_delivered(&[change]), "{change:?}"); + } + assert!(!press_delivered(&[])); +} + +#[test] +fn only_a_strong_change_verifies_a_press_and_a_weak_one_only_shows_it_arrived() { + for change in [ + WitnessChange::TargetValue, + WitnessChange::FocusMovedInWindow, + WitnessChange::FocusedValue, + ] { + assert_eq!( + press_reaction(&[change]), + Some(DeliveryObservation::Unverified), + "{change:?}" + ); + } + for change in [ + WitnessChange::TargetSelected, + WitnessChange::SurfaceOpened, + WitnessChange::FocusIntoTarget, + ] { + assert_eq!( + press_reaction(&[change]), + Some(DeliveryObservation::Verified), + "{change:?}" + ); + } + assert_eq!(press_reaction(&[WitnessChange::WindowTitle]), None); +} diff --git a/crates/macos/src/actions/ax_mutation.rs b/crates/macos/src/actions/ax_mutation.rs index dbbf48f8a1..2d0a139e8e 100644 --- a/crates/macos/src/actions/ax_mutation.rs +++ b/crates/macos/src/actions/ax_mutation.rs @@ -21,7 +21,7 @@ pub(crate) fn classify_result( fn classify(operation: &str, api: &str, error: i32) -> Result { let signal = signal_or_error(operation, api, error)?; if signal == PerformSignal::Uninformative && api == PERFORM_API { - return settle_uninformative_perform(operation, error, false) + return settle_uninformative_perform(operation, error, None) .map(|outcome| matches!(outcome, DeliveryOutcome::Delivered(_))); } Ok(signal == PerformSignal::ReportedDelivered) @@ -122,10 +122,10 @@ pub(crate) fn classify_perform(operation: &str, error: i32) -> Result, ) -> Result { - if observed_effect { - return Ok(DeliveryOutcome::Delivered(DeliveryObservation::Verified)); + if let Some(observation) = reaction { + return Ok(DeliveryOutcome::Delivered(observation)); } Err(AdapterError::new( ErrorCode::ActionFailed, @@ -159,7 +159,7 @@ mod tests { #[test] fn uninformative_perform_without_observed_effect_stops_fallback() { let error = - super::settle_uninformative_perform("AXOpen", kAXErrorAttributeUnsupported, false) + super::settle_uninformative_perform("AXOpen", kAXErrorAttributeUnsupported, None) .expect_err("missing or unchanged observations do not prove non-delivery"); assert_eq!( error.disposition.delivery(), @@ -167,9 +167,13 @@ mod tests { ); assert_eq!(error.disposition.retry(), RetryDisposition::Unsafe); assert_eq!( - super::settle_uninformative_perform("AXOpen", kAXErrorAttributeUnsupported, true) - .unwrap(), - DeliveryOutcome::Delivered(DeliveryObservation::Verified), + super::settle_uninformative_perform( + "AXOpen", + kAXErrorAttributeUnsupported, + Some(DeliveryObservation::Unverified) + ) + .unwrap(), + DeliveryOutcome::Delivered(DeliveryObservation::Unverified), ); } diff --git a/crates/macos/src/actions/ax_perform.rs b/crates/macos/src/actions/ax_perform.rs index 2d2c184cb1..941b0e3ad9 100644 --- a/crates/macos/src/actions/ax_perform.rs +++ b/crates/macos/src/actions/ax_perform.rs @@ -48,9 +48,9 @@ mod imp { }; match signal { PerformSignal::ReportedUnsupported => Ok(DeliveryOutcome::NotDelivered), - PerformSignal::ReportedDelivered => Ok(DeliveryOutcome::from_delivery( - true, - activation_effect::changed_now(&before, el, deadline), + PerformSignal::ReportedDelivered => Ok(DeliveryOutcome::Delivered( + activation_effect::changed_now(&before, el, deadline) + .unwrap_or(agent_desktop_core::DeliveryObservation::Unverified), )), PerformSignal::Uninformative => ax_mutation::settle_uninformative_perform( name, diff --git a/crates/macos/src/actions/chain/chain_disclosure_steps.rs b/crates/macos/src/actions/chain/chain_disclosure_steps.rs index 3bb7fe5920..18e2b89dd2 100644 --- a/crates/macos/src/actions/chain/chain_disclosure_steps.rs +++ b/crates/macos/src/actions/chain/chain_disclosure_steps.rs @@ -137,7 +137,7 @@ mod imp { outcome if signal == PerformSignal::ReportedDelivered => { outcome.map_err(after_delivery) } - _ => crate::actions::ax_mutation::settle_uninformative_perform("AXPress", error, false), + _ => crate::actions::ax_mutation::settle_uninformative_perform("AXPress", error, None), } } diff --git a/crates/macos/src/actions/chain/chain_value_write.rs b/crates/macos/src/actions/chain/chain_value_write.rs index b6cdffb69e..177afd9837 100644 --- a/crates/macos/src/actions/chain/chain_value_write.rs +++ b/crates/macos/src/actions/chain/chain_value_write.rs @@ -170,10 +170,8 @@ mod imp { return false; } crate::actions::activation_effect::focus_state(element, deadline) - .and_then(|state| state.focused_element()) - .is_some_and(|focused| { - crate::actions::activation_effect::focus_reached(&focused, element, deadline) - }) + .and_then(|witness| witness.focus.inside_target) + == Some(true) } pub(crate) fn increment_action(current: &str, target: &str) -> Option<&'static str> { diff --git a/crates/macos/src/actions/effect_witness.rs b/crates/macos/src/actions/effect_witness.rs new file mode 100644 index 0000000000..bdb7b96eb7 --- /dev/null +++ b/crates/macos/src/actions/effect_witness.rs @@ -0,0 +1,204 @@ +//! The effect witness of an element on macOS: what an action on it can change +//! outside its own state. Every part reads through the existing accessibility +//! reads; a part that cannot be read stays `None`. + +#[cfg(target_os = "macos")] +mod imp { + use std::hash::{Hash, Hasher}; + + use agent_desktop_core::{ + AdapterError, Deadline, EffectWitness, FocusWitness, TargetWitness, WindowWitness, + }; + + use crate::tree::{AXElement, properties::attributes, surface_read}; + + const FOCUS_DESCENT_WALK: usize = 3; + + /// The target and focus parts: what a press changes inside the target's + /// application. Fails as a stale reference when the target is gone. + pub(crate) fn read_local( + element: &AXElement, + deadline: Deadline, + ) -> Result { + let role = surface_read::string(element, "AXRole", deadline)?; + let app = crate::system::app::app_ops::pid_from_element(element, deadline) + .map(crate::tree::element_for_pid); + let focus = match app.map(|app| { + attributes::copy_element_attr_answered_result(&app, "AXFocusedUIElement", deadline) + }) { + Some(Ok(Some(focused))) => focus_of(&focused, element, deadline), + Some(Ok(None)) => FocusWitness::nothing_focused(), + Some(Err(_)) | None => FocusWitness::default(), + }; + Ok(EffectWitness { + target: TargetWitness { + selected: attributes::copy_bool_attr_result(element, "AXSelected", deadline) + .ok() + .flatten(), + value: crate::tree::copy_value_typed(element, deadline), + surfaces: surfaces_below(element, role.as_deref(), deadline), + }, + focus, + window: WindowWitness::default(), + }) + } + + /// All parts: the target and focus parts, and the target's window. + pub(crate) fn read( + element: &AXElement, + deadline: Deadline, + ) -> Result { + let mut witness = read_local(element, deadline)?; + witness.window = window_of(element, deadline); + Ok(witness) + } + + /// Open menus and popovers directly below the element: a menu control's + /// own menu, or a popover a control anchors. `None` when a menu or a + /// child's role could not be read: an uncounted surface would make a later + /// whole read look like a surface the action opened. + fn surfaces_below(element: &AXElement, role: Option<&str>, deadline: Deadline) -> Option { + use crate::actions::owned_menu::{is_menu_control, menu_open}; + if role.is_some_and(is_menu_control) { + return menu_open(element, deadline).map(u32::from); + } + let children = surface_read::elements(element, "AXChildren", deadline).ok()?; + if children.len() > crate::tree::surface_inventory::ANCHOR_CHILD_LIMIT { + return None; + } + super::popover_count( + children + .iter() + .map(|child| surface_read::string(child, "AXRole", deadline)), + ) + } + + fn focus_of(focused: &AXElement, element: &AXElement, deadline: Deadline) -> FocusWitness { + FocusWitness { + element: crate::tree::resolve::retained::capture(focused) + .ok() + .flatten(), + inside_target: Some(focus_reached(focused, element, deadline)), + in_target_window: shares_window(focused, element, deadline), + value: crate::tree::copy_value_typed(focused, deadline), + } + } + + fn window_of(element: &AXElement, deadline: Deadline) -> WindowWitness { + let window = surface_read::element(element, "AXWindow", deadline) + .ok() + .flatten(); + let windows = crate::system::app::app_ops::pid_from_element(element, deadline) + .map(crate::tree::element_for_pid) + .and_then(|app| { + crate::tree::resolve::resolve_ax_read::read_array(&app, "AXWindows", deadline) + .ok() + .flatten() + }); + WindowWitness { + title: window + .as_ref() + .and_then(|window| title_of(window, deadline)), + content: window + .as_ref() + .and_then(|window| content_sign(window, deadline)), + windows: windows + .as_ref() + .and_then(|windows| u32::try_from(windows.len()).ok()), + present: window + .as_ref() + .zip(windows.as_ref()) + .map(|(window, windows)| { + windows + .iter() + .any(|listed| crate::tree::same_element(listed, window)) + }), + } + } + + /// The title with the document, which a document window names apart. + fn title_of(window: &AXElement, deadline: Deadline) -> Option { + let title = surface_read::string(window, "AXTitle", deadline) + .ok() + .flatten(); + let document = surface_read::string(window, "AXDocument", deadline) + .ok() + .flatten(); + (title.is_some() || document.is_some()).then(|| { + format!( + "{}\n{}", + title.unwrap_or_default(), + document.unwrap_or_default() + ) + }) + } + + /// A sign of the window's content: the role and the number of children of + /// each direct child. A pane that a tab swaps in has another shape. + /// The child count is read without copying the children. + fn content_sign(window: &AXElement, deadline: Deadline) -> Option { + use core_foundation::{base::TCFType, string::CFString}; + let children = CFString::new("AXChildren"); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for child in surface_read::elements(window, "AXChildren", deadline).ok()? { + surface_read::string(&child, "AXRole", deadline) + .ok() + .flatten() + .hash(&mut hasher); + crate::tree::properties::ax_ipc::attribute_value_count( + &child, + children.as_concrete_TypeRef(), + deadline, + ) + .ok() + .hash(&mut hasher); + } + Some(hasher.finish()) + } + + /// A control that owns an editor hands focus to the editor, not to itself: + /// a PDF form field in Preview publishes a text area and focus lands there. + fn focus_reached(focused: &AXElement, element: &AXElement, deadline: Deadline) -> bool { + let mut current = focused.clone(); + for _ in 0..FOCUS_DESCENT_WALK { + if crate::tree::same_element(¤t, element) { + return true; + } + let Some(parent) = attributes::copy_element_attr_result(¤t, "AXParent", deadline) + .ok() + .flatten() + else { + return false; + }; + current = parent; + } + false + } + + fn shares_window(focused: &AXElement, element: &AXElement, deadline: Deadline) -> Option { + let window = |el| attributes::copy_element_attr_result(el, "AXWindow", deadline); + Some(crate::tree::same_element( + &window(focused).ok()??, + &window(element).ok()??, + )) + } +} + +#[cfg(target_os = "macos")] +pub(crate) use imp::{read, read_local}; + +/// The popovers among children's roles, or `None` when a role read failed. A +/// child with no role is no popover. +fn popover_count(roles: impl Iterator, E>>) -> Option { + let mut count = 0; + for role in roles { + if role.ok()?.as_deref() == Some("AXPopover") { + count += 1; + } + } + Some(count) +} + +#[cfg(test)] +#[path = "effect_witness_tests.rs"] +mod tests; diff --git a/crates/macos/src/actions/effect_witness_tests.rs b/crates/macos/src/actions/effect_witness_tests.rs new file mode 100644 index 0000000000..4699c0c3fa --- /dev/null +++ b/crates/macos/src/actions/effect_witness_tests.rs @@ -0,0 +1,11 @@ +use super::popover_count; + +#[test] +fn a_child_whose_role_could_not_be_read_leaves_the_popover_count_unknown() { + let role = |name: &str| Ok::<_, ()>(Some(name.to_owned())); + assert_eq!( + popover_count([role("AXPopover"), role("AXButton"), Ok(None)].into_iter()), + Some(1) + ); + assert_eq!(popover_count([role("AXButton"), Err(())].into_iter()), None); +} diff --git a/crates/macos/src/actions/mod.rs b/crates/macos/src/actions/mod.rs index c2332ee8e3..2e74958ecb 100644 --- a/crates/macos/src/actions/mod.rs +++ b/crates/macos/src/actions/mod.rs @@ -12,6 +12,7 @@ pub(crate) mod cell_write_failure; pub(crate) mod chain; pub(crate) mod delivery_tracker; pub(crate) mod dispatch; +pub(crate) mod effect_witness; pub(crate) mod extras; mod native_menu; pub(crate) mod owned_menu; diff --git a/crates/macos/src/actions/owned_menu.rs b/crates/macos/src/actions/owned_menu.rs index 5e7ead3ced..dec0242963 100644 --- a/crates/macos/src/actions/owned_menu.rs +++ b/crates/macos/src/actions/owned_menu.rs @@ -6,15 +6,26 @@ use crate::tree::AXElement; /// with nonempty bounds. `None` when the element is not a menu control or a /// child could not be read. pub(crate) fn owned_menu_open(element: &AXElement, deadline: Deadline) -> Option { - use crate::tree::surface_read; - let end = deadline; - let role = surface_read::string(element, "AXRole", end).ok()??; - if !matches!( - role.as_str(), - "AXMenuButton" | "AXPopUpButton" | "AXComboBox" | "AXMenuBarItem" | "AXMenuItem" - ) { + let role = crate::tree::surface_read::string(element, "AXRole", deadline).ok()??; + if !is_menu_control(&role) { return None; } + menu_open(element, deadline) +} + +/// Whether an element of `role` owns a menu of its own. +pub(crate) fn is_menu_control(role: &str) -> bool { + matches!( + role, + "AXMenuButton" | "AXPopUpButton" | "AXComboBox" | "AXMenuBarItem" | "AXMenuItem" + ) +} + +/// Whether a menu control's menu is open, `None` when a child could not be +/// read. +pub(crate) fn menu_open(element: &AXElement, deadline: Deadline) -> Option { + use crate::tree::surface_read; + let end = deadline; let mut complete = true; for child in surface_read::elements(element, "AXChildren", end).ok()? { if surface_read::string(&child, "AXRole", end).ok()?? != "AXMenu" { diff --git a/crates/macos/src/system/adapter.rs b/crates/macos/src/system/adapter.rs index 28b9622136..3554cfb039 100644 --- a/crates/macos/src/system/adapter.rs +++ b/crates/macos/src/system/adapter.rs @@ -254,16 +254,14 @@ 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( + fn close_transient_surface( &self, - window: &WindowInfo, - combo: &agent_desktop_core::KeyCombo, + process: &ProcessIdentity, + window: Option<&WindowInfo>, policy: agent_desktop_core::InteractionPolicy, lease: &InteractionLease, - ) -> Result { - crate::system::key_dispatch::press_for_window(self, window, combo, policy, lease) + ) -> Result, AdapterError> { + crate::system::escape_popup::close_transient_surface(process, window, policy, lease) } fn wait_for_menu( diff --git a/crates/macos/src/system/escape_popup.rs b/crates/macos/src/system/escape_popup.rs new file mode 100644 index 0000000000..dfaacd09fd --- /dev/null +++ b/crates/macos/src/system/escape_popup.rs @@ -0,0 +1,259 @@ +//! Closing the open menu or popover of an application that does not hold the +//! keyboard. Core asks for it after a plain Escape that the key route refused +//! for focus: the surface can stay open in a window that does not. + +use std::time::Duration; + +use agent_desktop_core::{ + Action, ActionResult, ActionStep, AdapterError, Deadline, DeliverySemantics, ErrorCode, + InteractionLease, InteractionPolicy, KeyCombo, ProcessIdentity, StepMechanism, WindowInfo, +}; + +use crate::system::process::process_identity::{self, ProcessIdentity as Generation}; +use crate::tree::AXElement; + +pub(crate) const CANCEL: &str = "AXCancel"; +const SURFACE_CLOSE_WAIT: Duration = Duration::from_millis(500); +const SURFACE_CLOSE_STEP: Duration = Duration::from_millis(10); + +/// The reads and the one action a close needs, so the routing between a named +/// window and the whole process is testable without a live application. The +/// guards run before discovery and again immediately before the cancel. +pub(crate) trait TransientSurface { + type Identity: Copy; + type Surface; + + fn verify_process(&self, process: &ProcessIdentity) -> Result; + + fn require_generation(&self, identity: Self::Identity) -> Result<(), AdapterError>; + + fn in_window( + &self, + identity: Self::Identity, + window: &WindowInfo, + ) -> Result, AdapterError>; + + fn in_process(&self, identity: Self::Identity) -> Result, AdapterError>; + + fn verify_surface( + &self, + identity: Self::Identity, + surface: &Self::Surface, + ) -> Result<(), AdapterError>; + + fn cancel(&self, surface: &Self::Surface) -> Result; + + fn closed(&self, surface: &Self::Surface) -> bool; +} + +struct AxSurfaces { + deadline: Deadline, +} + +impl TransientSurface for AxSurfaces { + type Identity = Generation; + type Surface = AXElement; + + fn verify_process(&self, process: &ProcessIdentity) -> Result { + process_identity::require_core(process) + } + + fn require_generation(&self, identity: Generation) -> Result<(), AdapterError> { + crate::tree::app_menu::require_generation(identity) + } + + fn in_window( + &self, + identity: Generation, + window: &WindowInfo, + ) -> Result, AdapterError> { + crate::tree::surfaces::transient_surface_in_window(identity, window, self.deadline) + } + + fn in_process(&self, identity: Generation) -> Result, AdapterError> { + crate::tree::surfaces::transient_surface_for_process(identity, self.deadline) + } + + fn verify_surface( + &self, + identity: Generation, + surface: &AXElement, + ) -> Result<(), AdapterError> { + verify_ax_surface(identity, surface, self.deadline) + } + + fn cancel(&self, surface: &AXElement) -> Result { + crate::actions::ax_helpers::try_ax_action_or_err(surface, CANCEL, self.deadline) + } + + fn closed(&self, surface: &AXElement) -> bool { + surface_closed(surface, self.deadline) + } +} + +/// Closes the surface `window` shows, or the one the process shows anywhere +/// when `window` shows none or is absent. `None` when none is open. +pub(crate) fn close_transient_surface( + process: &ProcessIdentity, + window: Option<&WindowInfo>, + _policy: InteractionPolicy, + lease: &InteractionLease, +) -> Result, AdapterError> { + close_with( + &AxSurfaces { + deadline: lease.deadline(), + }, + process, + window, + ) +} + +/// The close of one surface through its own `AXCancel`, verified by reading it +/// gone. `None` when the surface does not advertise the action. The surface is +/// revalidated against the process immediately before the cancel is sent. +pub(crate) fn cancel_surface( + identity: Generation, + surface: &AXElement, + deadline: Deadline, +) -> Result, AdapterError> { + verify_ax_surface(identity, surface, deadline)?; + if !crate::actions::ax_helpers::try_ax_action_or_err(surface, CANCEL, deadline)? { + return Ok(None); + } + Ok(Some(action_step(surface_closed(surface, deadline)))) +} + +fn close_with( + surfaces: &S, + process: &ProcessIdentity, + window: Option<&WindowInfo>, +) -> Result, AdapterError> { + let Some((identity, surface)) = find_surface(surfaces, process, window)? else { + return Ok(None); + }; + surfaces + .verify_surface(identity, &surface) + .map_err(not_delivered)?; + if !surfaces.cancel(&surface)? { + return Ok(None); + } + Ok(Some(closed_result(action_step(surfaces.closed(&surface))))) +} + +/// The process generation a surface was found under, with the surface itself. +type Located = ( + ::Identity, + ::Surface, +); + +/// The surface inside the named window when that window shows one, otherwise +/// the surface the process shows. Only the process is read without a window. A +/// named window must belong to the same process instance, and the process +/// generation is rechecked before the wider search falls back to it. +fn find_surface( + surfaces: &S, + process: &ProcessIdentity, + window: Option<&WindowInfo>, +) -> Result>, AdapterError> { + if let Some(window) = window { + require_window_process(process, window)?; + } + let identity = surfaces.verify_process(process).map_err(not_delivered)?; + let Some(window) = window else { + return Ok(surfaces + .in_process(identity) + .map_err(not_delivered)? + .map(|surface| (identity, surface))); + }; + if let Some(surface) = surfaces + .in_window(identity, window) + .map_err(not_delivered)? + { + return Ok(Some((identity, surface))); + } + surfaces + .require_generation(identity) + .map_err(not_delivered)?; + Ok(surfaces + .in_process(identity) + .map_err(not_delivered)? + .map(|surface| (identity, surface))) +} + +/// A named window is evidence about one process instance: a window from a +/// replaced process would otherwise be searched for this one's surface. +fn require_window_process( + process: &ProcessIdentity, + window: &WindowInfo, +) -> Result<(), AdapterError> { + let same_process = window.pid == process.pid + && window.process_instance.as_deref() == Some(process.instance.as_str()); + if same_process { + return Ok(()); + } + Err(not_delivered(AdapterError::stale_ref_because( + "Window does not match the target process instance", + ))) +} + +/// Confirms the process generation and the surface's owning process +/// immediately before an action is sent to it. +fn verify_ax_surface( + identity: Generation, + surface: &AXElement, + deadline: Deadline, +) -> Result<(), AdapterError> { + crate::tree::app_menu::require_generation(identity).map_err(not_delivered)?; + match crate::tree::properties::ax_ipc::pid(surface, deadline) { + Ok(pid) if pid == identity.pid() => { + crate::tree::app_menu::require_generation(identity).map_err(not_delivered) + } + Ok(_) => Err(not_delivered(AdapterError::stale_ref_because( + "Surface no longer belongs to the target process", + ))), + Err(error) if error == accessibility_sys::kAXErrorInvalidUIElement => Err(not_delivered( + AdapterError::stale_ref_because("Surface became invalid before cancel"), + )), + Err(error) => Err(not_delivered(crate::tree::surface_read::map_error( + "AXPid", error, + ))), + } +} + +fn not_delivered(error: AdapterError) -> AdapterError { + error.with_disposition(DeliverySemantics::not_delivered()) +} + +fn action_step(verified: bool) -> ActionStep { + ActionStep::succeeded(CANCEL) + .with_mechanism(StepMechanism::SemanticApi) + .with_verified(verified) +} + +fn closed_result(step: ActionStep) -> ActionResult { + let escape = Action::PressKey(KeyCombo { + key: "escape".to_owned(), + modifiers: Vec::new(), + }); + ActionResult::from_execution(&escape, vec![step]) +} + +/// 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. +pub(crate) 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, SURFACE_CLOSE_STEP, gone, |gone| *gone) +} + +#[cfg(test)] +#[path = "escape_popup_tests.rs"] +mod tests; diff --git a/crates/macos/src/system/escape_popup_tests.rs b/crates/macos/src/system/escape_popup_tests.rs new file mode 100644 index 0000000000..6e178fe56e --- /dev/null +++ b/crates/macos/src/system/escape_popup_tests.rs @@ -0,0 +1,335 @@ +use std::cell::RefCell; + +use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode, ProcessIdentity, WindowInfo}; + +use super::{TransientSurface, close_with}; + +struct Lookups { + window_surface: Option<&'static str>, + window_error: Option, + process_surface: Option<&'static str>, + process_error: Option, +} + +struct Guards { + surface_error: Option, + generation_limit: Option, + cancel_supported: bool, + closed: bool, +} + +struct Recorder { + looked_in: RefCell>, + cancelled: RefCell>, + generations: RefCell, +} + +struct FakeSurfaces { + lookups: Lookups, + guards: Guards, + recorder: Recorder, +} + +impl TransientSurface for FakeSurfaces { + type Identity = u32; + type Surface = &'static str; + + fn verify_process(&self, process: &ProcessIdentity) -> Result { + match &self.lookups.process_error { + Some(error) => Err(error.clone()), + None => Ok(process.pid.get()), + } + } + + fn require_generation(&self, _identity: u32) -> Result<(), AdapterError> { + let mut checks = self.recorder.generations.borrow_mut(); + *checks += 1; + let limit = self.guards.generation_limit; + if limit.is_some_and(|limit| *checks > limit) { + return Err(not_delivered(AdapterError::stale_ref_because( + "Application process instance changed during observation", + ))); + } + Ok(()) + } + + fn in_window( + &self, + _identity: u32, + window: &WindowInfo, + ) -> Result, AdapterError> { + self.recorder + .looked_in + .borrow_mut() + .push(format!("window:{}", window.id)); + match &self.lookups.window_error { + Some(error) => Err(error.clone()), + None => Ok(self.lookups.window_surface), + } + } + + fn in_process(&self, identity: u32) -> Result, AdapterError> { + self.recorder + .looked_in + .borrow_mut() + .push(format!("process:{identity}")); + Ok(self.lookups.process_surface) + } + + fn verify_surface(&self, identity: u32, _surface: &&'static str) -> Result<(), AdapterError> { + self.require_generation(identity)?; + match &self.guards.surface_error { + Some(error) => Err(error.clone()), + None => Ok(()), + } + } + + fn cancel(&self, surface: &&'static str) -> Result { + *self.recorder.cancelled.borrow_mut() = Some(*surface); + Ok(self.guards.cancel_supported) + } + + fn closed(&self, _surface: &&'static str) -> bool { + self.guards.closed + } +} + +fn surfaces(surface: Option<&'static str>) -> FakeSurfaces { + surfaces_split(surface, surface) +} + +fn surfaces_split( + window_surface: Option<&'static str>, + process_surface: Option<&'static str>, +) -> FakeSurfaces { + FakeSurfaces { + lookups: Lookups { + window_surface, + window_error: None, + process_surface, + process_error: None, + }, + guards: Guards { + surface_error: None, + generation_limit: None, + cancel_supported: true, + closed: true, + }, + recorder: Recorder { + looked_in: RefCell::new(Vec::new()), + cancelled: RefCell::new(None), + generations: RefCell::new(0), + }, + } +} + +fn not_delivered(error: AdapterError) -> AdapterError { + error.with_disposition(DeliverySemantics::not_delivered()) +} + +fn process() -> ProcessIdentity { + ProcessIdentity::new(42_u32, "instance") +} + +fn window() -> WindowInfo { + WindowInfo { + id: "W1".into(), + title: "Main".into(), + app: "Sample".into(), + pid: 42_u32.into(), + process_instance: Some("instance".into()), + bounds: None, + state: Default::default(), + } +} + +#[test] +fn an_app_scoped_close_searches_the_process_and_verifies_the_surface_gone() { + let surfaces = surfaces(Some("popover")); + + let result = close_with(&surfaces, &process(), None) + .unwrap() + .expect("a closed surface"); + + assert_eq!(*surfaces.recorder.looked_in.borrow(), ["process:42"]); + assert_eq!(*surfaces.recorder.cancelled.borrow(), Some("popover")); + assert_eq!( + result.disposition(), + DeliverySemantics::delivered_verified() + ); + assert_eq!(result.steps[0].verified, Some(true)); +} + +#[test] +fn a_window_scoped_close_prefers_the_surface_in_that_window() { + let surfaces = surfaces_split(Some("menu"), Some("app-menu")); + + let result = close_with(&surfaces, &process(), Some(&window())) + .unwrap() + .expect("a closed surface"); + + assert_eq!(*surfaces.recorder.looked_in.borrow(), ["window:W1"]); + assert_eq!(*surfaces.recorder.cancelled.borrow(), Some("menu")); + assert_eq!( + result.disposition(), + DeliverySemantics::delivered_verified() + ); +} + +#[test] +fn a_window_scoped_close_falls_back_to_the_surface_the_app_shows() { + let surfaces = surfaces_split(None, Some("app-menu")); + + let result = close_with(&surfaces, &process(), Some(&window())) + .unwrap() + .expect("a closed surface"); + + assert_eq!( + *surfaces.recorder.looked_in.borrow(), + ["window:W1", "process:42"] + ); + assert_eq!(*surfaces.recorder.cancelled.borrow(), Some("app-menu")); + assert_eq!( + result.disposition(), + DeliverySemantics::delivered_verified() + ); + assert_eq!(result.steps[0].verified, Some(true)); +} + +#[test] +fn a_window_lookup_error_is_not_masked_by_the_app_fallback() { + let mut surfaces = surfaces_split(Some("menu"), Some("app-menu")); + surfaces.lookups.window_error = Some(AdapterError::new( + ErrorCode::WindowNotFound, + "Window closed", + )); + + let error = close_with(&surfaces, &process(), Some(&window())).unwrap_err(); + + assert_eq!(error.code, ErrorCode::WindowNotFound); + assert_eq!(*surfaces.recorder.looked_in.borrow(), ["window:W1"]); + assert_eq!(*surfaces.recorder.cancelled.borrow(), None); +} + +#[test] +fn a_window_that_does_not_name_the_process_instance_fails_before_any_search() { + for instance in [None, Some("other-launch".to_owned())] { + let surfaces = surfaces_split(Some("menu"), Some("app-menu")); + let mut window = window(); + window.process_instance = instance.clone(); + + let error = close_with(&surfaces, &process(), Some(&window)).unwrap_err(); + + assert_eq!(error.code, ErrorCode::StaleRef, "{instance:?}"); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert!( + surfaces.recorder.looked_in.borrow().is_empty(), + "{instance:?}" + ); + assert_eq!(*surfaces.recorder.cancelled.borrow(), None); + } +} + +#[test] +fn a_window_of_another_process_fails_before_any_search() { + let surfaces = surfaces_split(Some("menu"), Some("app-menu")); + let mut window = window(); + window.pid = 7_u32.into(); + + let error = close_with(&surfaces, &process(), Some(&window)).unwrap_err(); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert!(surfaces.recorder.looked_in.borrow().is_empty()); + assert_eq!(*surfaces.recorder.cancelled.borrow(), None); +} + +#[test] +fn a_process_that_no_longer_matches_fails_before_any_search() { + let mut surfaces = surfaces(Some("menu")); + surfaces.lookups.process_error = Some(not_delivered(AdapterError::stale_ref_because( + "Target process instance is no longer running", + ))); + + let error = close_with(&surfaces, &process(), None).unwrap_err(); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert!(surfaces.recorder.looked_in.borrow().is_empty()); + assert_eq!(*surfaces.recorder.cancelled.borrow(), None); +} + +#[test] +fn a_generation_change_before_the_app_fallback_never_searches_the_process() { + let mut surfaces = surfaces_split(None, Some("app-menu")); + surfaces.guards.generation_limit = Some(0); + + let error = close_with(&surfaces, &process(), Some(&window())).unwrap_err(); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(*surfaces.recorder.looked_in.borrow(), ["window:W1"]); + assert_eq!(*surfaces.recorder.cancelled.borrow(), None); +} + +#[test] +fn a_generation_change_before_the_cancel_fails_without_cancelling() { + let mut surfaces = surfaces(Some("menu")); + surfaces.guards.generation_limit = Some(0); + + let error = close_with(&surfaces, &process(), None).unwrap_err(); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(*surfaces.recorder.looked_in.borrow(), ["process:42"]); + assert_eq!(*surfaces.recorder.cancelled.borrow(), None); +} + +#[test] +fn a_surface_of_another_process_is_never_cancelled() { + let mut surfaces = surfaces(Some("menu")); + surfaces.guards.surface_error = Some(not_delivered(AdapterError::stale_ref_because( + "Surface no longer belongs to the target process", + ))); + + let error = close_with(&surfaces, &process(), None).unwrap_err(); + + assert_eq!(error.code, ErrorCode::StaleRef); + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + assert_eq!(*surfaces.recorder.looked_in.borrow(), ["process:42"]); + assert_eq!(*surfaces.recorder.cancelled.borrow(), None); +} + +#[test] +fn no_open_surface_leaves_the_refusal() { + let surfaces = surfaces(None); + + assert!(close_with(&surfaces, &process(), None).unwrap().is_none()); + assert_eq!(*surfaces.recorder.looked_in.borrow(), ["process:42"]); + assert_eq!(*surfaces.recorder.cancelled.borrow(), None); +} + +#[test] +fn a_surface_that_does_not_take_the_cancel_leaves_the_refusal() { + let mut surfaces = surfaces(Some("menu")); + surfaces.guards.cancel_supported = false; + + assert!(close_with(&surfaces, &process(), None).unwrap().is_none()); + assert_eq!(*surfaces.recorder.cancelled.borrow(), Some("menu")); +} + +#[test] +fn a_close_that_cannot_be_read_back_is_unverified() { + let mut surfaces = surfaces(Some("menu")); + surfaces.guards.closed = false; + + let result = close_with(&surfaces, &process(), None) + .unwrap() + .expect("a dispatched close"); + + assert_eq!( + result.disposition(), + DeliverySemantics::delivered_unverified() + ); + assert_eq!(result.steps[0].verified, Some(false)); +} diff --git a/crates/macos/src/system/key_dispatch.rs b/crates/macos/src/system/key_dispatch.rs index 6ed6bb6e6d..34a3991e76 100644 --- a/crates/macos/src/system/key_dispatch.rs +++ b/crates/macos/src/system/key_dispatch.rs @@ -4,16 +4,12 @@ use agent_desktop_core::{ }; use std::time::Duration; +use crate::system::escape_popup::{CANCEL, cancel_surface}; 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, @@ -118,25 +114,19 @@ 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(delivery_result(step)) + let verified = step.verified == Some(true); + let result = ActionResult::delivered_unverified("press_key").with_steps(vec![step]); + Ok(if verified { + result.with_verified_delivery() + } else { + result + }) } /// Where a key without modifiers lands as an accessibility action. @@ -226,38 +216,15 @@ fn deliver_semantic_key( let Some(target) = semantic_key_target(identity, app, action, deadline)? else { return Ok(None); }; - let (element, closes_surface) = match &target { - SemanticKeyTarget::FocusHolder(element) => (element, false), - SemanticKeyTarget::OpenSurface(element) => (element, true), - }; - if closes_surface { - require_surface_owner(element, identity, deadline)?; - } - crate::tree::app_menu::require_generation(identity).map_err(not_delivered)?; - if !crate::actions::ax_helpers::try_ax_action_or_err(element, action, deadline)? { - return Ok(None); - } - 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())), + match &target { + SemanticKeyTarget::FocusHolder(element) => { + 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); + } + Ok(Some(semantic_step(action))) + } + SemanticKeyTarget::OpenSurface(element) => cancel_surface(identity, element, deadline), } } @@ -265,34 +232,10 @@ 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; @@ -309,7 +252,11 @@ fn no_focused_element_error(policy: InteractionPolicy) -> AdapterError { ErrorCode::ActionFailed, "Application has no verified focused element for keyboard delivery", ) - .with_details(serde_json::json!({ "physical_delivery_started": false })) + .with_details(serde_json::json!({ + "check": "process_focus", + "physical_delivery_started": false, + })) + .with_disposition(DeliverySemantics::not_delivered()) .with_suggestion(if policy.allow_focus_steal { "Ensure the target field has keyboard focus before retrying, or run the menu command without keys: find the item with 'snapshot --app --surface menubar' and click its ref.".to_owned() } else { diff --git a/crates/macos/src/system/key_dispatch_tests.rs b/crates/macos/src/system/key_dispatch_tests.rs index 13613faa4f..2197c41ac6 100644 --- a/crates/macos/src/system/key_dispatch_tests.rs +++ b/crates/macos/src/system/key_dispatch_tests.rs @@ -86,6 +86,16 @@ fn a_missing_focused_element_names_both_recovery_routes() { assert!(suggestion.contains("--surface menubar"), "{suggestion}"); } +#[test] +fn a_missing_focused_element_is_a_refusal_core_can_route_to_a_surface_close() { + let error = super::no_focused_element_error(agent_desktop_core::InteractionPolicy::headless()); + + assert_eq!(error.disposition, DeliverySemantics::not_delivered()); + let details = error.details.expect("refusal details"); + assert_eq!(details["check"], "process_focus"); + assert_eq!(details["physical_delivery_started"], false); +} + #[test] fn a_headed_missing_focused_element_does_not_suggest_enabling_headed() { let error = super::no_focused_element_error(agent_desktop_core::InteractionPolicy::headed()); diff --git a/crates/macos/src/system/key_dispatch_window.rs b/crates/macos/src/system/key_dispatch_window.rs deleted file mode 100644 index d2efc382d0..0000000000 --- a/crates/macos/src/system/key_dispatch_window.rs +++ /dev/null @@ -1,188 +0,0 @@ -//! 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 deleted file mode 100644 index 0edbf8812d..0000000000 --- a/crates/macos/src/system/key_dispatch_window_tests.rs +++ /dev/null @@ -1,397 +0,0 @@ -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/mod.rs b/crates/macos/src/system/mod.rs index a15cbf0a9f..dd01c7e4f7 100644 --- a/crates/macos/src/system/mod.rs +++ b/crates/macos/src/system/mod.rs @@ -5,6 +5,7 @@ pub(crate) mod cocoa_runtime; pub(crate) mod cursor_overlay; pub(crate) mod display; pub(crate) mod display_work_area; +pub(crate) mod escape_popup; pub(crate) mod focus; pub(crate) mod focus_bridge; pub(crate) mod key_dispatch; diff --git a/crates/macos/src/tree/adapter.rs b/crates/macos/src/tree/adapter.rs index a6094491ec..d07fbbc679 100644 --- a/crates/macos/src/tree/adapter.rs +++ b/crates/macos/src/tree/adapter.rs @@ -231,6 +231,14 @@ impl ObservationOps for MacOSAdapter { crate::tree::properties::text_insertion::focused_insertion_caret(pid, deadline) } + fn read_effect_witness( + &self, + handle: &NativeHandle, + deadline: Deadline, + ) -> Result { + crate::actions::effect_witness::read(ax_element(handle)?, deadline) + } + fn get_live_element( &self, handle: &NativeHandle, diff --git a/crates/macos/src/tree/app_menu.rs b/crates/macos/src/tree/app_menu.rs index 0819baac29..d50957c36e 100644 --- a/crates/macos/src/tree/app_menu.rs +++ b/crates/macos/src/tree/app_menu.rs @@ -249,7 +249,15 @@ impl ChildExpansion { } #[cfg(target_os = "macos")] -pub(super) fn find_menu_descendant( +pub(super) fn find_transient_surface( + root: AXElement, + source: String, + deadline: Deadline, +) -> Result, AdapterError> { + find_menu_descendant(root, source, Transient::MenuOrPopover, deadline) +} + +fn find_menu_descendant( root: AXElement, source: String, accept: Transient, diff --git a/crates/macos/src/tree/properties/attributes.rs b/crates/macos/src/tree/properties/attributes.rs index a9da5a46ed..b2a97a88ab 100644 --- a/crates/macos/src/tree/properties/attributes.rs +++ b/crates/macos/src/tree/properties/attributes.rs @@ -105,6 +105,28 @@ mod imp { el: &AXElement, attr: &str, deadline: agent_desktop_core::Deadline, + ) -> Result, i32> { + copy_element_attr_with(el, attr, deadline, is_absent_error) + } + + /// Like `copy_element_attr_result`, but `Ok(None)` only when the element + /// answered that the attribute has no value. An attribute it does not + /// implement or fails to answer is `Err`, so "none" is never a guess. + pub(crate) fn copy_element_attr_answered_result( + el: &AXElement, + attr: &str, + deadline: agent_desktop_core::Deadline, + ) -> Result, i32> { + copy_element_attr_with(el, attr, deadline, |error| { + error == accessibility_sys::kAXErrorNoValue + }) + } + + fn copy_element_attr_with( + el: &AXElement, + attr: &str, + deadline: agent_desktop_core::Deadline, + absent: impl Fn(i32) -> bool, ) -> Result, i32> { let cf_attr = CFString::new(attr); let (err, value) = crate::tree::properties::ax_ipc::copy_attribute_value( @@ -116,11 +138,7 @@ mod imp { if !value.is_null() { unsafe { core_foundation::base::CFRelease(value) }; } - return if is_absent_error(err) { - Ok(None) - } else { - Err(err) - }; + return if absent(err) { Ok(None) } else { Err(err) }; } if value.is_null() { return Ok(None); @@ -224,8 +242,8 @@ pub(crate) use super::text_attributes::{ copy_value_typed_bounded_result, copy_value_typed_result, }; pub(crate) use imp::{ - copy_ax_array_prefix_result, copy_bool_attr, copy_bool_attr_result, copy_element_attr_result, - set_messaging_timeout, + copy_ax_array_prefix_result, copy_bool_attr, copy_bool_attr_result, + copy_element_attr_answered_result, copy_element_attr_result, set_messaging_timeout, }; #[cfg(target_os = "macos")] diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rs index e1500aa551..0a92bb9a75 100644 --- a/crates/macos/src/tree/surfaces.rs +++ b/crates/macos/src/tree/surfaces.rs @@ -35,43 +35,26 @@ pub(crate) fn transient_surface_for_process( }) } -/// 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. +/// The menu or popover inside `window`, searched at any depth because a popover +/// hangs below the control that raised it. The window is resolved inside the +/// observed pass, so a window that is gone and a process that was replaced both +/// fail instead of reading as an absent surface. #[cfg(target_os = "macos")] -pub(crate) fn transient_surface_for_window( +pub(crate) fn transient_surface_in_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) + let owner = + crate::system::window::window_resolve::window_element_for_info(window, deadline)?; + Ok( + super::app_menu::find_transient_surface(owner, "window".into(), deadline)? + .map(|(_, surface)| surface), + ) }) } -/// 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, diff --git a/crates/windows/src/actions/disclosure.rs b/crates/windows/src/actions/disclosure.rs index ae5416997b..6687323ddf 100644 --- a/crates/windows/src/actions/disclosure.rs +++ b/crates/windows/src/actions/disclosure.rs @@ -5,9 +5,9 @@ //! flips it with no foreground change on SysTreeView32, WinForms and WPF //! trees (C7), so it runs only from a known opposite state and is verified by //! re-reading the state. ExpandCollapsePattern on a tree item takes no -//! foreground (A31-5). On any other control it can open a popup over the +//! foreground (A31-5). On any other control an expand can open a popup over the //! user's window (C6), so it declares the foreground effect and a policy that -//! does not allow it refuses. +//! does not allow it refuses; a collapse opens nothing and declares none. use agent_desktop_core::{ActionStep, AdapterError, Deadline, InteractionPolicy}; use std::time::Duration; @@ -79,8 +79,28 @@ mod imp { want_expanded: bool, policy: InteractionPolicy, deadline: Deadline, + ) -> Result, AdapterError> { + disclosure_steps_guarded(element, want_expanded, policy, deadline, &|| Ok(())) + } + + pub(crate) fn collapse_with_guard( + element: &UIAElement, + policy: InteractionPolicy, + deadline: Deadline, + guard: &dyn Fn() -> Result<(), AdapterError>, + ) -> Result, AdapterError> { + disclosure_steps_guarded(element, false, policy, deadline, guard) + } + + fn disclosure_steps_guarded( + element: &UIAElement, + want_expanded: bool, + policy: InteractionPolicy, + deadline: Deadline, + guard: &dyn Fn() -> Result<(), AdapterError>, ) -> Result, AdapterError> { deadline.ensure_remaining()?; + guard()?; let pattern_ok = read_one(element, TreeProperty::ExpandCollapseAvailable).flag() == Some(true); let current = read_expand_state(element); @@ -97,11 +117,15 @@ mod imp { } else { COLLAPSE_LABEL }; - let mut legacy = - || deliver_and_observe(element, want_expanded, deadline, legacy_default_action); + let mut legacy = || { + deliver_and_observe(element, want_expanded, deadline, |element| { + guard()?; + legacy_default_action(element) + }) + }; let mut pattern = || { deliver_and_observe(element, want_expanded, deadline, |element| { - pattern_expand_collapse(element, want_expanded, label) + pattern_expand_collapse(element, want_expanded, label, guard) }) }; agent_desktop_core::execute_chain( @@ -109,7 +133,7 @@ mod imp { rung( label, pattern_ok && current != Some(ExpandKind::LeafNode), - !tree_item, + want_expanded && !tree_item, &mut pattern, ), rung(LEGACY_LABEL, flips, false, &mut legacy), @@ -148,10 +172,13 @@ mod imp { element: &UIAElement, want_expanded: bool, label: &'static str, + guard: &dyn Fn() -> Result<(), AdapterError>, ) -> Result { let operation = if want_expanded { "Expand" } else { "Collapse" }; + guard()?; match element.0.get_pattern::() { Ok(pattern) => { + guard()?; let result = if want_expanded { pattern.expand() } else { @@ -179,6 +206,17 @@ mod imp { ) -> Result, AdapterError> { Err(AdapterError::not_supported("ExpandCollapse")) } + + pub(crate) fn collapse_with_guard( + _: &UIAElement, + _: InteractionPolicy, + _: Deadline, + _: &dyn Fn() -> Result<(), AdapterError>, + ) -> Result, AdapterError> { + Err(AdapterError::not_supported("ExpandCollapse")) + } } +#[cfg(target_os = "windows")] +pub(crate) use imp::collapse_with_guard; pub(crate) use imp::disclosure_steps; diff --git a/crates/windows/src/adapter.rs b/crates/windows/src/adapter.rs index b7cec42f35..a067e600ea 100644 --- a/crates/windows/src/adapter.rs +++ b/crates/windows/src/adapter.rs @@ -166,6 +166,14 @@ impl ObservationOps for WindowsAdapter { crate::tree::live_read::live_element(&read) } + fn read_effect_witness( + &self, + handle: &NativeHandle, + deadline: Deadline, + ) -> Result { + crate::tree::effect_witness::read_effect_witness(handle, deadline) + } + fn get_element_bounds( &self, handle: &NativeHandle, diff --git a/crates/windows/src/system/adapter.rs b/crates/windows/src/system/adapter.rs index 9f40bbc31f..0dc909bafa 100644 --- a/crates/windows/src/system/adapter.rs +++ b/crates/windows/src/system/adapter.rs @@ -9,8 +9,7 @@ use agent_desktop_core::{ system::process_state::ProcessState, }; -use crate::adapter::WindowsAdapter; -use crate::system::escape_popup; +use crate::{adapter::WindowsAdapter, system::escape_popup}; #[cfg(target_os = "windows")] #[path = "tcp_listener.rs"] @@ -269,7 +268,8 @@ impl SystemOps for WindowsAdapter { crate::system::capture::screenshot::capture_window(window, deadline) } - /// Key delivery, then `escape_popup` for a refused Escape (A9-3). + /// Verify-only key delivery; core's headed path already activated and this + /// never raises (A9-3: SendInput has no per-pid targeting). fn press_key_for_app( &self, process: ProcessIdentity, @@ -277,17 +277,17 @@ impl SystemOps for WindowsAdapter { policy: InteractionPolicy, lease: &InteractionLease, ) -> Result { - escape_popup::press_for_app(process, combo, policy, lease.deadline()) + crate::system::key_dispatch::press_for_app_impl(process, combo, policy, lease.deadline()) } - fn press_key_for_window( + fn close_transient_surface( &self, - window: &WindowInfo, - combo: &KeyCombo, + process: &ProcessIdentity, + window: Option<&WindowInfo>, policy: InteractionPolicy, lease: &InteractionLease, - ) -> Result { - escape_popup::press_for_window(self, window, combo, policy, lease) + ) -> Result, AdapterError> { + escape_popup::close_transient_surface(process, window, policy, lease.deadline()) } /// 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 index aca4866c83..0fb3c0ad16 100644 --- a/crates/windows/src/system/escape_popup.rs +++ b/crates/windows/src/system/escape_popup.rs @@ -1,14 +1,15 @@ -//! Escape for an open popup when the key route refused for focus. +//! Closing the open popup of a window that does not hold the keyboard. //! -//! 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. +//! Core asks for it after a plain Escape that the key route refused for focus. +//! A popup a person opened (a menu, a drop-down, a split-button list) can sit +//! in a window that is not in front. It has a semantic close: collapsing its +//! owner, through the same primitive `collapse` uses (`disclosure_steps`). -use agent_desktop_core::{AdapterError, Deadline, DeliverySemantics, ErrorCode, KeyCombo}; +#[cfg(not(target_os = "windows"))] +use agent_desktop_core::{ActionResult, InteractionPolicy, ProcessIdentity, WindowInfo}; +use agent_desktop_core::{AdapterError, Deadline}; +#[cfg(any(target_os = "windows", test))] +use agent_desktop_core::{DeliverySemantics, ErrorCode}; #[cfg(any(target_os = "windows", test))] pub(super) const MAX_POPUP_ROOTS: usize = 32; @@ -174,74 +175,6 @@ pub(super) fn scan_popup_owners( 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 { @@ -253,18 +186,17 @@ fn opens_a_popup(control_type: i32) -> bool { mod uia; #[cfg(target_os = "windows")] -pub(crate) use uia::after_key_route; +pub(crate) use uia::close_transient_surface; -/// Off Windows no popup can be open, so the key route's result stands. +/// Off Windows no popup can be open. #[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 +pub(crate) fn close_transient_surface( + _process: &ProcessIdentity, + _window: Option<&WindowInfo>, + _policy: InteractionPolicy, + _deadline: Deadline, +) -> Result, AdapterError> { + Ok(None) } #[cfg(test)] diff --git a/crates/windows/src/system/escape_popup_tests.rs b/crates/windows/src/system/escape_popup_tests.rs index 506a0a7a42..594bf3ac91 100644 --- a/crates/windows/src/system/escape_popup_tests.rs +++ b/crates/windows/src/system/escape_popup_tests.rs @@ -2,14 +2,13 @@ use std::cell::Cell; use std::time::Duration; use agent_desktop_core::{ - AdapterError, Deadline, DeliverySemantics, ErrorCode, KeyCombo, Modifier, ProcessId, - ProcessIdentity, WindowInfo, + Deadline, DeliverySemantics, ErrorCode, 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, + opens_a_popup, scan_popup_owners, scan_timeout_error, verify_process_handle, + verify_process_target, verify_window_target, }; struct FakeNode { @@ -62,42 +61,6 @@ 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)); diff --git a/crates/windows/src/system/escape_popup_uia.rs b/crates/windows/src/system/escape_popup_uia.rs index 3a29c4e6ff..6d54d2a791 100644 --- a/crates/windows/src/system/escape_popup_uia.rs +++ b/crates/windows/src/system/escape_popup_uia.rs @@ -1,33 +1,25 @@ //! 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, + MAX_POPUP_ROOTS, PopupScan, PopupTree, opens_a_popup, 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, + Action, ActionResult, AdapterError, Deadline, 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::actions::disclosure::collapse_with_guard; 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::properties::read_cached; 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]; @@ -121,13 +113,6 @@ fn deepest_popup_owner( } } -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)); @@ -182,74 +167,35 @@ fn process_roots( 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, +/// Collapses the deepest open popup of the window (or of the process), and +/// reads its state back. +pub(crate) fn close_transient_surface( + process: &ProcessIdentity, + window: Option<&WindowInfo>, policy: InteractionPolicy, deadline: Deadline, -) -> Result { +) -> Result, AdapterError> { + let roots = match window { + Some(window) => window_roots(window, deadline)?, + None => process_roots(process, deadline)?, + }; + let Some(owner) = deepest_popup_owner(roots, deadline)? else { + return Ok(None); + }; 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 verify = || match window { + Some(window) => verify_window_target(window).map(|_| ()), + None => verify_process_handle(process, owner.handle), }; - 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)?, + let steps = collapse_with_guard(&owner.element, policy, deadline, &verify)?; + let escape = KeyCombo { + key: "escape".to_owned(), + modifiers: Vec::new(), }; - match deepest_popup_owner(roots, deadline)? { - Some(owner) => close_popup(&owner, scope, combo, policy, deadline), - None => Err(refusal), - } + Ok(Some(ActionResult::from_execution( + &Action::PressKey(escape), + steps, + ))) } diff --git a/crates/windows/src/system/key_dispatch.rs b/crates/windows/src/system/key_dispatch.rs index 1ee56d2167..a10df7560d 100644 --- a/crates/windows/src/system/key_dispatch.rs +++ b/crates/windows/src/system/key_dispatch.rs @@ -125,6 +125,7 @@ fn require_keyboard_focus( "Application has no verified keyboard focus for key delivery", ) .with_details(serde_json::json!({ + "check": "process_focus", "pid": pid, "physical_delivery_started": false, })) @@ -153,6 +154,7 @@ fn background_fail_closed(pid: ProcessId) -> AdapterError { "Target application is not foreground; Windows SendInput cannot deliver to a background process", ) .with_details(serde_json::json!({ + "check": "process_focus", "pid": pid, "physical_delivery_started": false, })) @@ -169,6 +171,7 @@ fn focus_lost_before_delivery(pid: ProcessId) -> AdapterError { "Target application lost focus before physical input delivery", ) .with_details(serde_json::json!({ + "check": "process_focus", "pid": pid, "physical_delivery_started": false, })) diff --git a/crates/windows/src/system/key_dispatch_tests.rs b/crates/windows/src/system/key_dispatch_tests.rs index e167e54297..441f8d8ed2 100644 --- a/crates/windows/src/system/key_dispatch_tests.rs +++ b/crates/windows/src/system/key_dispatch_tests.rs @@ -133,3 +133,14 @@ mod delivery_gates { assert!(sink::recorded().is_empty()); } } + +#[test] +fn the_process_focus_refusals_name_their_check_for_core() { + let pid = ProcessId::new(4); + for refusal in [background_fail_closed(pid), focus_lost_before_delivery(pid)] { + let details = refusal.details.expect("a refusal carries details"); + assert_eq!(details["check"], "process_focus"); + assert_eq!(details["physical_delivery_started"], false); + assert_eq!(refusal.disposition, DeliverySemantics::not_delivered()); + } +} diff --git a/crates/windows/src/tree/effect_witness.rs b/crates/windows/src/tree/effect_witness.rs new file mode 100644 index 0000000000..367c46b870 --- /dev/null +++ b/crates/windows/src/tree/effect_witness.rs @@ -0,0 +1,250 @@ +//! The effect witness read: what an action's effect can change outside the +//! target's own value, as core compares it before and after a click or select. +//! +//! The target answers through its own patterns (`SelectionItem`, `Value`, +//! `ExpandCollapse`), the focus through the system's one focused element, and +//! the window through its root handle and the direct children of its element. +//! A field that cannot be read cheaply stays `None`, and a vanished target is a +//! stale ref. + +use std::hash::{Hash, Hasher}; + +/// Open surfaces below an element from its `ExpandCollapse` reads: `None` +/// without the pattern or when its state cannot be read, one while expanded, +/// none otherwise. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub(crate) fn surfaces_from(available: Option, state: Option) -> Option { + if available != Some(true) { + return None; + } + state.map(|state| u32::from(state == 1)) +} + +/// A sign of what the direct children of a window are: equal signs mean the +/// children the read named did not change. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub(crate) fn content_sign(children: &[T]) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + children.hash(&mut hasher); + hasher.finish() +} + +/// The window handle a native window's runtime id carries (prefix 42). Unlike +/// the element's root window, it stays readable after the window is gone. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub(crate) fn hwnd_of(runtime_id: &[i32]) -> Option { + match runtime_id { + [42, hwnd, ..] => Some(*hwnd as isize), + _ => None, + } +} + +#[cfg(target_os = "windows")] +mod imp { + use super::{content_sign, hwnd_of, surfaces_from}; + use crate::tree::automation::{automation_client, uia_error}; + use crate::tree::element::{UIAElement, uia_element}; + use crate::tree::hit_test::corroborate::element_root_hwnd; + use crate::tree::properties::property_ids::TreeProperty; + use crate::tree::properties::read_cached; + use crate::tree::walk::cache::build_walk_cache_request; + use agent_desktop_core::{ + AdapterError, Deadline, EffectWitness, FocusWitness, NativeHandle, TargetWitness, + WindowWitness, + }; + use std::cell::RefCell; + use uiautomation::UIAutomation; + use uiautomation::core::UICacheRequest; + use windows_sys::Win32::Foundation::{HWND, LPARAM}; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + EnumWindows, GA_ROOT, GUITHREADINFO, GW_CHILD, GW_HWNDNEXT, GetAncestor, GetGUIThreadInfo, + GetWindow, GetWindowTextW, GetWindowThreadProcessId, IsChild, IsWindowVisible, + }; + + const MAX_CHILDREN: usize = 512; + + const TARGET_SET: [TreeProperty; 6] = [ + TreeProperty::SelectionItemAvailable, + TreeProperty::SelectionItemIsSelected, + TreeProperty::ValueAvailable, + TreeProperty::Value, + TreeProperty::ExpandCollapseAvailable, + TreeProperty::ExpandCollapseState, + ]; + + thread_local! { + /// The cache request of the target read, built once per thread. + static TARGET_CACHE: RefCell> = const { RefCell::new(None) }; + } + + pub(crate) fn read_effect_witness( + handle: &NativeHandle, + deadline: Deadline, + ) -> Result { + deadline.ensure_remaining()?; + let element = uia_element(handle)?; + let client = automation_client()?; + let target = target_witness(element, &client)?; + let walker = client + .get_raw_view_walker() + .map_err(|error| uia_error(&error, "open the effect witness walker"))?; + let target_root = element_root_hwnd(element, &walker, deadline).ok().flatten(); + let anchor = element.0.get_runtime_id().ok().as_deref().and_then(hwnd_of); + Ok(EffectWitness { + target, + focus: focus_witness(anchor, target_root), + window: window_witness(element, target_root, anchor.or(target_root)), + }) + } + + /// One cached read of the target's three patterns. A target that is gone + /// fails the update: a stale ref. + fn target_witness( + element: &UIAElement, + client: &UIAutomation, + ) -> Result { + let cache = TARGET_CACHE + .with(|cell| { + if cell.borrow().is_none() { + *cell.borrow_mut() = build_walk_cache_request(client, &TARGET_SET).ok(); + } + cell.borrow().clone() + }) + .ok_or_else(|| { + AdapterError::internal("the effect witness cache request did not build") + })?; + let updated = element.0.build_updated_cache(&cache).map_err(|error| { + let mapped = uia_error(&error, "read the effect witness target"); + if mapped.code == agent_desktop_core::ErrorCode::StaleRef { + AdapterError::stale_ref_because("The target element is gone") + .with_details(serde_json::json!({ "complete": true, "retryable": false })) + } else { + mapped + } + })?; + let (properties, _) = read_cached(&UIAElement::from(updated), &TARGET_SET); + Ok(TargetWitness { + selected: properties.gated_flag(TreeProperty::SelectionItemIsSelected), + value: properties + .is_true(TreeProperty::ValueAvailable) + .then(|| properties.get(TreeProperty::Value).non_blank_text()) + .flatten(), + surfaces: surfaces_from( + properties.get(TreeProperty::ExpandCollapseAvailable).flag(), + properties.get(TreeProperty::ExpandCollapseState).number(), + ), + }) + } + + /// The system focus at window-handle grain: the focused control's handle + /// names it, and its relation to the target comes from the handle tree. + fn focus_witness(anchor: Option, target_root: Option) -> FocusWitness { + let mut info = GUITHREADINFO { + cbSize: std::mem::size_of::() as u32, + ..Default::default() + }; + let focus = (unsafe { GetGUIThreadInfo(0, &mut info) } != 0 && !info.hwndFocus.is_null()) + .then_some(info.hwndFocus); + FocusWitness { + element: focus.map(|focus| format!("hwnd:{}", focus as isize)), + inside_target: focus.zip(anchor).map(|(focus, anchor)| { + focus as isize == anchor || unsafe { IsChild(anchor as HWND, focus) } != 0 + }), + in_target_window: focus + .zip(target_root) + .map(|(focus, root)| (unsafe { GetAncestor(focus, GA_ROOT) }) as isize == root), + value: None, + } + } + + fn window_witness( + element: &UIAElement, + root: Option, + anchor: Option, + ) -> WindowWitness { + let listed = element + .0 + .get_process_id() + .ok() + .map(|pid| process_windows(pid, anchor)); + WindowWitness { + title: root.and_then(title_of), + content: root.and_then(content_of), + windows: listed.map(|(count, _)| count), + present: listed.and_then(|(_, present)| present), + } + } + + fn title_of(window: isize) -> Option { + let mut buffer = [0u16; 256]; + let length = unsafe { GetWindowTextW(window as HWND, buffer.as_mut_ptr(), 256) }; + (length > 0).then(|| String::from_utf16_lossy(&buffer[..length as usize])) + } + + /// A sign of the window's direct child windows (their handles): a window + /// gaining or losing a control or a pane changes it. + fn content_of(root: isize) -> Option { + let mut children = Vec::new(); + let mut child = unsafe { GetWindow(root as HWND, GW_CHILD) }; + while !child.is_null() && children.len() < MAX_CHILDREN { + children.push(child as isize); + child = unsafe { GetWindow(child, GW_HWNDNEXT) }; + } + Some(content_sign(&children)) + } + + /// The visible top-level windows of a process, and whether `target` is one + /// of them: one `EnumWindows` pass with one owner read per window. + fn process_windows(pid: u32, target: Option) -> (u32, Option) { + struct Listing { + pid: u32, + target: isize, + count: u32, + found: bool, + } + unsafe extern "system" fn list(window: HWND, state: LPARAM) -> i32 { + let listing = unsafe { &mut *(state as *mut Listing) }; + let mut owner = 0; + unsafe { GetWindowThreadProcessId(window, &mut owner) }; + if owner == listing.pid && unsafe { IsWindowVisible(window) } != 0 { + listing.count += 1; + listing.found |= window as isize == listing.target; + } + 1 + } + let top = target.map(|handle| { + let root = unsafe { GetAncestor(handle as HWND, GA_ROOT) }; + if root.is_null() { + handle + } else { + root as isize + } + }); + let mut listing = Listing { + pid, + target: top.unwrap_or_default(), + count: 0, + found: false, + }; + unsafe { EnumWindows(Some(list), &mut listing as *mut Listing as LPARAM) }; + (listing.count, target.map(|_| listing.found)) + } +} + +#[cfg(target_os = "windows")] +pub(crate) use imp::read_effect_witness; + +/// Off Windows nothing can be read. +#[cfg(not(target_os = "windows"))] +pub(crate) fn read_effect_witness( + _handle: &agent_desktop_core::NativeHandle, + _deadline: agent_desktop_core::Deadline, +) -> Result { + Err(agent_desktop_core::AdapterError::not_supported( + "read_effect_witness", + )) +} + +#[cfg(test)] +#[path = "effect_witness_tests.rs"] +mod tests; diff --git a/crates/windows/src/tree/effect_witness_tests.rs b/crates/windows/src/tree/effect_witness_tests.rs new file mode 100644 index 0000000000..11fd338f8a --- /dev/null +++ b/crates/windows/src/tree/effect_witness_tests.rs @@ -0,0 +1,17 @@ +use super::{hwnd_of, surfaces_from}; + +#[test] +fn an_element_shows_a_surface_only_through_its_expand_collapse_state() { + assert_eq!(surfaces_from(None, Some(1)), None); + assert_eq!(surfaces_from(Some(false), Some(1)), None); + assert_eq!(surfaces_from(Some(true), Some(1)), Some(1)); + assert_eq!(surfaces_from(Some(true), Some(0)), Some(0)); + assert_eq!(surfaces_from(Some(true), None), None); +} + +#[test] +fn only_a_native_window_runtime_id_names_a_window_handle() { + assert_eq!(hwnd_of(&[42, 7_340_032, 1]), Some(7_340_032)); + assert_eq!(hwnd_of(&[7, 3]), None); + assert_eq!(hwnd_of(&[]), None); +} diff --git a/crates/windows/src/tree/mod.rs b/crates/windows/src/tree/mod.rs index 7c56316f5d..29ef54d120 100644 --- a/crates/windows/src/tree/mod.rs +++ b/crates/windows/src/tree/mod.rs @@ -2,6 +2,7 @@ pub mod actions; pub mod automation; pub mod chromium; pub mod descriptor; +pub(crate) mod effect_witness; pub(crate) mod hit_test; pub(crate) mod live_read; pub(crate) mod minimized; diff --git a/docs/json-output.md b/docs/json-output.md index bd92e128bd..fc728e400b 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -193,6 +193,8 @@ When a ref action returns `delivery_uncertain` with a post-action wait selector, - 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. +- A click, double click, right click, triple click or select carries `data.effect` when the platform can read an effect witness around it: `observed`, `not_observed` or `indeterminate`, with `details.witness_diff` listing the changes (`target_gone`, `window_closed`, `target_selected`, `surface_opened`, `focus_into_target` are strong; `target_value`, `focus_moved_in_window`, `focused_value`, `window_title`, `window_content`, `window_count` are weak, because the application can change them by itself; a click on a checkbox or radio button changes only its value, so verify a toggle with `check`, `uncheck` or `toggle`, which read the state back). A strong change makes a delivered result `delivered_verified`; weak changes alone change no disposition. After a `delivery_uncertain` error the witness is read once too; a strong change returns success with `delivered_verified`, `data.effect` `observed`, and the platform's error under `details.platform_report`, while any other verdict keeps the error and sets `error.details.effect`. The witness never waits: an effect that lands later is for the caller to wait for. A delivered result never becomes `not_delivered`. `not_observed` beside a delivered disposition is not proof that nothing happened. +- `press escape` with `--app` or `--window-id`, refused because the target does not hold the keyboard (`details.check` `window_active`, `exact_window_focus` or `process_focus`), closes the open menu, drop-down or popup of the target through the platform's own close action when there is one, and returns that result, or that attempt's own error, which says whether it may have landed; the refusal stands only when no such surface is open or the platform has no close route. `launch`, `open-system-surface`, `focus-window`, `dismiss-notification` and `dismiss-all-notifications` now carry `data.disposition` on success, and an incomplete-locator `TIMEOUT` names its cause. Every key is additive; every other key keeps its value. A `launch` payload written before the field existed has no `disposition`; readers must treat its absence as `unknown`, not as a delivery claim. diff --git a/skills/agent-desktop-windows/SKILL.md b/skills/agent-desktop-windows/SKILL.md index 00bffc081b..ebba180209 100644 --- a/skills/agent-desktop-windows/SKILL.md +++ b/skills/agent-desktop-windows/SKILL.md @@ -46,6 +46,7 @@ Use `$env:NAME = 'value'` for environment variables. 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. + `collapse` of an open combo box or menu item works headless, and reports `not_delivered` when it is already closed. - 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. diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.md index ae996b6e70..f2d9b6bc62 100644 --- a/skills/agent-desktop/SKILL.md +++ b/skills/agent-desktop/SKILL.md @@ -44,7 +44,7 @@ permission prompts or a visible setup guide. take a skeleton and drill the relevant container with `--root`. Omit `-i` when you need static labels to distinguish rows. 2. Act on a qualified ref from that observation. Prefer a semantic ref action - over coordinates, and `check` or `uncheck` over a state-reversing `toggle`. + over coordinates, and `check` or `uncheck` over `toggle` or `click`: they verify the state. 3. Verify the requested outcome with an independent read: a fresh snapshot or a condition-based `wait`. Wait with `wait`, never a fixed sleep or a duration-only wait. A field value alone does not prove an application @@ -181,10 +181,10 @@ Cloning a configured macOS VM has been tested end to end. Installing the first V Action results carry `data.disposition`; errors carry `error.disposition`. Only `not_delivered` permits a safe retry. `delivered_verified` confirms the reported readback, not the whole task. `delivered_unverified`, `delivery_uncertain`, -and `unknown` do not prove that nothing happened. If retry is unsafe, unknown, -or missing, read live state before deciding on a new action; do not repeat or -substitute the original action blindly. Use `details.post_state` when present. -An action or window command can land even when `ok` is false. +and `unknown` do not prove that nothing happened. A click or select carries `effect`: +`observed` verifies it; `indeterminate` (a change the app can make by itself, see +`details.witness_diff`) and `not_observed` do not prove that nothing happened. If retry +is unsafe or missing, read live state first and never repeat an action blindly; use `details.post_state` when present. An action can land even when `ok` is false. Held input fails closed: `key-down`, `key-up`, `mouse-down`, and `mouse-up` cannot hold input across CLI calls until daemon-owned release exists. They return diff --git a/src/cli/contract_command_surface_tests.rs b/src/cli/contract_command_surface_tests.rs index 705c2a77a6..11daa2531f 100644 --- a/src/cli/contract_command_surface_tests.rs +++ b/src/cli/contract_command_surface_tests.rs @@ -5,6 +5,7 @@ use std::path::{Path, PathBuf}; const NON_COMMAND_MODULES: &[&str] = &[ "combo", + "escape_route", "execute_by_ref", "find_live", "helpers",