From 8cd57af352bccb81bc39ca15765dbba3144f594d Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 11:18:50 -0800 Subject: [PATCH 01/27] feat: read an effect witness around a click or a select A click's effect lands outside the target's own state, so after a click nothing was read: a delivered press stayed `delivered_unverified` even when it plainly worked, and an unclear platform answer stayed uncertain even when the window had changed. The only effect check was a macOS one, inside one rung. Core now reads an effect witness through a new adapter method, `read_effect_witness`, before a click, double click, right click, triple click or select, and decides with an explicit state machine: - nothing sent, or the adapter already proved the effect: no further read; - sent without proof: one read, no wait; - an unclear answer (uncertain): reads until 400 ms after the dispatch. The witness holds the target's selection, value and open surfaces below it, the focused element (a stable identity, inside the target or in its window, its value), and the window's title, a content sign and the window count. A change on or under the target, focus moving into it, or the target being gone afterwards is strong evidence and verifies the delivery. A title, content or window-count change, or focus moving elsewhere, can happen by itself, so it is reported but verifies nothing. The result carries `effect` (observed, not_observed, indeterminate) and `details.witness_diff`. A delivered result never becomes undelivered, and an unclear error with a strong change stays an error whose disposition is `delivered_verified`. An adapter that cannot read a witness keeps today's results. --- crates/core/src/actions/action.rs | 13 ++ crates/core/src/actions/action_result.rs | 11 + crates/core/src/actions/effect_witness.rs | 100 +++++++++ .../core/src/actions/effect_witness_tests.rs | 106 ++++++++++ crates/core/src/actions/focus_witness.rs | 14 ++ crates/core/src/actions/mod.rs | 7 + crates/core/src/actions/observed_effect.rs | 18 ++ crates/core/src/actions/post_action.rs | 5 + crates/core/src/actions/target_witness.rs | 10 + crates/core/src/actions/window_witness.rs | 15 ++ crates/core/src/actions/witness_change.rs | 38 ++++ crates/core/src/actions/witnessed_action.rs | 143 +++++++++++++ .../src/actions/witnessed_action_tests.rs | 197 ++++++++++++++++++ crates/core/src/adapter/observation.rs | 12 ++ crates/core/src/lib.rs | 6 + 15 files changed, 695 insertions(+) create mode 100644 crates/core/src/actions/effect_witness.rs create mode 100644 crates/core/src/actions/effect_witness_tests.rs create mode 100644 crates/core/src/actions/focus_witness.rs create mode 100644 crates/core/src/actions/observed_effect.rs create mode 100644 crates/core/src/actions/target_witness.rs create mode 100644 crates/core/src/actions/window_witness.rs create mode 100644 crates/core/src/actions/witness_change.rs create mode 100644 crates/core/src/actions/witnessed_action.rs create mode 100644 crates/core/src/actions/witnessed_action_tests.rs diff --git a/crates/core/src/actions/action.rs b/crates/core/src/actions/action.rs index f9d716f045..a34b7eefe8 100644 --- a/crates/core/src/actions/action.rs +++ b/crates/core/src/actions/action.rs @@ -96,6 +96,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..60efcd2922 --- /dev/null +++ b/crates/core/src/actions/effect_witness.rs @@ -0,0 +1,100 @@ +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. + pub fn changes_since(&self, before: &Self) -> Vec { + let (now, then) = (self, before); + let focus_moved = differs(&then.focus.element, &now.focus.element); + [ + ( + 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_moved && now.focus.inside_target == Some(true), + WitnessChange::FocusIntoTarget, + ), + ( + focus_moved + && now.focus.inside_target != Some(true) + && 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..ced827dfdc --- /dev/null +++ b/crates/core/src/actions/effect_witness_tests.rs @@ -0,0 +1,106 @@ +use super::{EffectWitness, verdict}; +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.value = Some("1".into()), + WitnessChange::TargetValue, + ), + ( + |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.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()); +} diff --git a/crates/core/src/actions/focus_witness.rs b/crates/core/src/actions/focus_witness.rs new file mode 100644 index 0000000000..e31c6c4960 --- /dev/null +++ b/crates/core/src/actions/focus_witness.rs @@ -0,0 +1,14 @@ +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, +} 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 819cdb41fb..8748aa2c17 100644 --- a/crates/core/src/actions/post_action.rs +++ b/crates/core/src/actions/post_action.rs @@ -11,6 +11,11 @@ pub fn execute_verified_action( lease: &InteractionLease, ) -> Result { let action = request.action.clone(); + if action.witnesses_effect() { + return crate::actions::witnessed_action::execute_witnessed_action( + adapter, handle, request, lease, + ); + } if !action.requires_state_readback() { return adapter.execute_action(handle, request, lease); } 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..6258ff9cf3 --- /dev/null +++ b/crates/core/src/actions/witness_change.rs @@ -0,0 +1,38 @@ +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, and focus moving elsewhere in the window + /// can also change by themselves (a timer, a notification), so they are + /// weak evidence. + pub fn is_strong(self) -> bool { + matches!( + self, + Self::TargetGone + | Self::WindowClosed + | Self::TargetSelected + | Self::TargetValue + | 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..d1977d8e81 --- /dev/null +++ b/crates/core/src/actions/witnessed_action.rs @@ -0,0 +1,143 @@ +//! 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 what happens next, as one of three +//! explicit steps; a strong change upgrades a delivery to verified, and the +//! verdict and the changes are reported. A delivered result never becomes +//! undelivered, and the witness never makes an error of its own. + +use std::time::{Duration, Instant}; + +use crate::actions::{ + effect_witness::{EffectWitness, verdict}, + observed_effect::ObservedEffect, + witness_change::WitnessChange, +}; +use crate::{ + ActionRequest, ActionResult, AdapterError, DeliverySemantics, ErrorCode, InteractionLease, + NativeHandle, PlatformAdapter, +}; + +/// The settle time after an unclear answer, counted from the dispatch. +const SETTLE: Duration = Duration::from_millis(400); +const POLL: Duration = Duration::from_millis(50); + +/// 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: one read, no wait. + ReadOnce, + /// The platform's answer was unclear: read until the settle time ends. + Settle, +} + +pub(crate) fn witness_step(dispatch: &Result) -> WitnessStep { + match dispatch { + Ok(result) if result.disposition() == DeliverySemantics::delivered_unverified() => { + WitnessStep::ReadOnce + } + Err(error) if error.disposition == DeliverySemantics::uncertain() => WitnessStep::Settle, + Ok(_) | Err(_) => WitnessStep::Leave, + } +} + +pub(crate) fn execute_witnessed_action( + adapter: &dyn PlatformAdapter, + handle: &NativeHandle, + request: ActionRequest, + lease: &InteractionLease, +) -> Result { + let deadline = lease.deadline(); + let before = adapter.read_effect_witness(handle, deadline).ok(); + let dispatched = Instant::now(); + let dispatch = adapter.execute_action(handle, request, lease); + let Some(before) = before else { + return dispatch; + }; + let read = || after_changes(adapter.read_effect_witness(handle, deadline), &before); + match witness_step(&dispatch) { + WitnessStep::Leave => dispatch.map(adapter_proof), + WitnessStep::ReadOnce => match read() { + Some(changes) => dispatch.map(|result| with_changes(result, &changes)), + None => dispatch, + }, + WitnessStep::Settle => { + let mut changes = read(); + while !changes.as_deref().is_some_and(has_strong) + && dispatched.elapsed() < SETTLE + && deadline.remaining() > POLL + { + crate::wait::deadline::sleep(POLL); + changes = read(); + } + match changes { + Some(changes) => dispatch.map_err(|error| error_with_changes(error, &changes)), + None => dispatch, + } + } + } +} + +/// The changes since `before`, or none when the witness could not be read. +/// A target that is gone after the action was closed or replaced by it. +fn after_changes( + after: Result, + before: &EffectWitness, +) -> Option> { + match after { + Ok(after) => Some(after.changes_since(before)), + Err(error) if error.code == ErrorCode::StaleRef => Some(vec![WitnessChange::TargetGone]), + Err(_) => None, + } +} + +fn has_strong(changes: &[WitnessChange]) -> bool { + changes.iter().any(|change| change.is_strong()) +} + +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 with a strong change was delivered: the error stays, as +/// the platform reported it, but its disposition says what the witness saw. +fn error_with_changes(mut error: AdapterError, changes: &[WitnessChange]) -> AdapterError { + let effect = verdict(changes); + if effect == ObservedEffect::Observed { + error.disposition = DeliverySemantics::delivered_verified(); + } + 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)); + } + } + 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..dd59b63c59 --- /dev/null +++ b/crates/core/src/actions/witnessed_action_tests.rs @@ -0,0 +1,197 @@ +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::ReadOnce); + assert_eq!(witness_step(&uncertain()), WitnessStep::Settle); + 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_delivered_and_stays_an_error() { + 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::delivered_verified()); + assert_eq!(error.details.unwrap()["effect"], "observed"); + assert_eq!(*adapter.read_count.lock().unwrap(), 3); +} + +#[test] +fn an_unclear_answer_with_no_change_stays_uncertain_after_the_settle_time() { + let adapter = adapter(vec![Ok(witness(false, "A"))], uncertain()); + let started = std::time::Instant::now(); + let error = run(&adapter).unwrap_err(); + + assert_eq!(error.disposition, DeliverySemantics::uncertain()); + assert_eq!(error.details.unwrap()["effect"], "not_observed"); + assert!(started.elapsed() >= SETTLE); +} + +#[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 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); +} 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/lib.rs b/crates/core/src/lib.rs index a8bde82e8c..093e7f7d2e 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -34,10 +34,16 @@ 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; From c32a43c446e963ca7f2957806e4e4fce6e1e2061 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 11:20:20 -0800 Subject: [PATCH 02/27] refactor: route a refused Escape through one core state machine Each platform that closes an open popup after a refused Escape carried its own wrapper around its key route, and Windows overrode the key method for a named window to reach the refusal. The order of the states belongs in one place. The press command now settles a plain Escape that the key route refused for focus (`details.check` window_active, exact_window_focus or process_focus, nothing sent) by asking the adapter to close the open transient surface of the target through a new method, `close_transient_surface`. A closed surface is the result; with none open, or when the adapter has no such route, the refusal stands. Every other key result is left as it was. --- crates/core/src/adapter/system.rs | 15 ++++ crates/core/src/commands/escape_route.rs | 56 +++++++++++++ .../core/src/commands/escape_route_tests.rs | 79 +++++++++++++++++++ crates/core/src/commands/mod.rs | 1 + crates/core/src/commands/press.rs | 17 ++-- src/cli/contract_command_surface_tests.rs | 1 + 6 files changed, 162 insertions(+), 7 deletions(-) create mode 100644 crates/core/src/commands/escape_route.rs create mode 100644 crates/core/src/commands/escape_route_tests.rs diff --git a/crates/core/src/adapter/system.rs b/crates/core/src/adapter/system.rs index 9539498dc8..99aae7970a 100644 --- a/crates/core/src/adapter/system.rs +++ b/crates/core/src/adapter/system.rs @@ -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, 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/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/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", From de00c0141528320e89d9757a7dfb6ba4b64a5c66 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 11:44:49 -0800 Subject: [PATCH 03/27] feat(macos): read the effect witness and let the press check use it The press check of the macOS adapter compared its own `FocusState` before and after an `AXPress`: the focused element, its value, the target's selection and value, and an owned menu. Core now reads an effect witness around every click, so that state is now that witness, read in one place. `effect_witness::read` builds the core witness from the existing reads: the target's selection and value, the open menu of a menu control (`owned_menu_open`) or a popover the control anchors, the focused element with its element token as identity, whether focus is inside the target or in its window, the window title with its document, a content sign (the role and child count of each direct child), the number of windows and whether the target's window is still listed. Counts are read with one call each, without copying arrays. The press check reads the target and focus parts and keeps its rule, now written over the core change list: a press is delivered when the target's selection or value changes, a menu or popover opens below it, or focus moves into it or within its window. Measured on Finder against branch 15: sidebar navigation verified 6 of 6 on both; a Close button that closes its window goes from delivered_unverified to delivered_verified (window_closed); a Share click whose popover opens 290 ms later stays delivered_unverified with effect not_observed; a Settings tab switch stays unverified with effect indeterminate (window_content); a click with no effect in the self-updating Activity Monitor window stays not_observed 4 of 4. The Share click costs the same (357 against 359 ms median, p90 367 against 370). --- crates/macos/src/actions/activation_effect.rs | 328 ++---------------- .../src/actions/activation_effect_tests.rs | 25 ++ .../src/actions/chain/chain_value_write.rs | 6 +- crates/macos/src/actions/effect_witness.rs | 193 +++++++++++ crates/macos/src/actions/mod.rs | 1 + crates/macos/src/tree/adapter.rs | 8 + 6 files changed, 263 insertions(+), 298 deletions(-) create mode 100644 crates/macos/src/actions/activation_effect_tests.rs create mode 100644 crates/macos/src/actions/effect_witness.rs diff --git a/crates/macos/src/actions/activation_effect.rs b/crates/macos/src/actions/activation_effect.rs index b375b6f8cf..609a61f23e 100644 --- a/crates/macos/src/actions/activation_effect.rs +++ b/crates/macos/src/actions/activation_effect.rs @@ -1,122 +1,39 @@ +//! 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. + #[cfg(target_os = "macos")] mod imp { - use agent_desktop_core::Deadline; + use agent_desktop_core::{Deadline, 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, + 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, - 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; + match (before, focus_state(element, deadline)) { + (Some(before), Some(after)) => press_delivered(&after.changes_since(before)), + _ => false, } - false } pub(crate) fn settled_change( - before: &Option, + before: &Option, element: &AXElement, deadline: Deadline, ) -> bool { @@ -137,201 +54,24 @@ mod imp { 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)) + /// 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 ) - } - - /// 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 - ) - } - - /// 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:?}" - ); - } - } - - #[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), - ); - } - } - } + }) } } -#[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..ae31d9c5ec --- /dev/null +++ b/crates/macos/src/actions/activation_effect_tests.rs @@ -0,0 +1,25 @@ +use super::imp::press_delivered; +use agent_desktop_core::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(&[])); +} 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..c3b1f8a7fc --- /dev/null +++ b/crates/macos/src/actions/effect_witness.rs @@ -0,0 +1,193 @@ +//! 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 { + 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 focused = app.and_then(|app| { + attributes::copy_element_attr_result(&app, "AXFocusedUIElement", deadline) + .ok() + .flatten() + }); + 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, deadline), + }, + focus: focus_of(focused.as_ref(), element, deadline), + 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. + fn surfaces_below(element: &AXElement, deadline: Deadline) -> Option { + if let Some(open) = crate::actions::owned_menu::owned_menu_open(element, deadline) { + return Some(u32::from(open)); + } + let children = surface_read::elements(element, "AXChildren", deadline).ok()?; + if children.len() > crate::tree::surface_inventory::ANCHOR_CHILD_LIMIT { + return None; + } + let popovers = children.iter().filter(|child| { + surface_read::string(child, "AXRole", deadline) + .ok() + .flatten() + .as_deref() + == Some("AXPopover") + }); + u32::try_from(popovers.count()).ok() + } + + fn focus_of( + focused: Option<&AXElement>, + element: &AXElement, + deadline: Deadline, + ) -> FocusWitness { + let Some(focused) = focused else { + return FocusWitness::default(); + }; + 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}; 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/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, From 5f0aa3bc916b790d2df7e70d30d84f3cd8b942e9 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 11:50:06 -0800 Subject: [PATCH 04/27] docs: describe the effect of a click and the Escape close in the contract and the skill The output contract and the core skill did not say what `effect` and `details.witness_diff` mean, which changes are strong, that a strong change verifies a delivery and sets an unclear error's disposition, or that a refused Escape can close the target's open popup. An agent that reads `not_observed` as "nothing happened" would repeat an action that landed. --- docs/json-output.md | 2 ++ skills/agent-desktop/SKILL.md | 8 ++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/json-output.md b/docs/json-output.md index e92a891670..9c1accac16 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -188,6 +188,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. Such a cell publishes no value to read back, so the result is `delivered_unverified`: read the cell again. - 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`, `target_value`, `surface_opened`, `focus_into_target` are strong; `focus_moved_in_window`, `focused_value`, `window_title`, `window_content`, `window_count` are weak). A strong change makes a delivered result `delivered_verified`; weak changes alone change no disposition. After a `delivery_uncertain` error the witness is read until 400 ms after the dispatch; a strong change sets that error's disposition to `delivered_verified`, and `error.details.effect` carries the verdict. 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/SKILL.md b/skills/agent-desktop/SKILL.md index c650dfa47b..77b519be2c 100644 --- a/skills/agent-desktop/SKILL.md +++ b/skills/agent-desktop/SKILL.md @@ -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 From f22d0669b7e179fe6662020482263005862baf4a Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 13:00:35 -0800 Subject: [PATCH 05/27] perf: read the effect witness once after the dispatch, with no wait The witness now has two states: no read when nothing was sent or the adapter already proved the effect, and one read with no wait when the delivery has no proof or the platform's answer was unclear. The settle loop after an unclear answer is gone: a click on a Finder sidebar row that was already open took 876 ms instead of 463 ms while it read for 400 ms and saw nothing. A second read 10 ms after the first was also tried and removed: a GTK tab reads as selected about 150 ms after the click, so it caught nothing, and it cost 17 ms at the median on Linux. An effect that lands later is for the caller to wait for. --- crates/core/src/actions/witnessed_action.rs | 60 ++++++------------- .../src/actions/witnessed_action_tests.rs | 42 +++++++++---- docs/json-output.md | 2 +- 3 files changed, 50 insertions(+), 54 deletions(-) diff --git a/crates/core/src/actions/witnessed_action.rs b/crates/core/src/actions/witnessed_action.rs index d1977d8e81..3762361e67 100644 --- a/crates/core/src/actions/witnessed_action.rs +++ b/crates/core/src/actions/witnessed_action.rs @@ -1,11 +1,9 @@ //! 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 what happens next, as one of three -//! explicit steps; a strong change upgrades a delivery to verified, and the -//! verdict and the changes are reported. A delivered result never becomes -//! undelivered, and the witness never makes an error of its own. - -use std::time::{Duration, Instant}; +//! 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, and the witness +//! never makes an error of its own. use crate::actions::{ effect_witness::{EffectWitness, verdict}, @@ -17,27 +15,22 @@ use crate::{ NativeHandle, PlatformAdapter, }; -/// The settle time after an unclear answer, counted from the dispatch. -const SETTLE: Duration = Duration::from_millis(400); -const POLL: Duration = Duration::from_millis(50); - /// 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: one read, no wait. - ReadOnce, - /// The platform's answer was unclear: read until the settle time ends. - Settle, + /// 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::ReadOnce + WitnessStep::Read } - Err(error) if error.disposition == DeliverySemantics::uncertain() => WitnessStep::Settle, + Err(error) if error.disposition == DeliverySemantics::uncertain() => WitnessStep::Read, Ok(_) | Err(_) => WitnessStep::Leave, } } @@ -50,32 +43,19 @@ pub(crate) fn execute_witnessed_action( ) -> Result { let deadline = lease.deadline(); let before = adapter.read_effect_witness(handle, deadline).ok(); - let dispatched = Instant::now(); let dispatch = adapter.execute_action(handle, request, lease); let Some(before) = before else { return dispatch; }; - let read = || after_changes(adapter.read_effect_witness(handle, deadline), &before); - match witness_step(&dispatch) { - WitnessStep::Leave => dispatch.map(adapter_proof), - WitnessStep::ReadOnce => match read() { - Some(changes) => dispatch.map(|result| with_changes(result, &changes)), - None => dispatch, - }, - WitnessStep::Settle => { - let mut changes = read(); - while !changes.as_deref().is_some_and(has_strong) - && dispatched.elapsed() < SETTLE - && deadline.remaining() > POLL - { - crate::wait::deadline::sleep(POLL); - changes = read(); - } - match changes { - Some(changes) => dispatch.map_err(|error| error_with_changes(error, &changes)), - None => dispatch, - } - } + let changes = match witness_step(&dispatch) { + WitnessStep::Leave => None, + WitnessStep::Read => after_changes(adapter.read_effect_witness(handle, deadline), &before), + }; + match changes { + Some(changes) => dispatch + .map(|result| with_changes(result, &changes)) + .map_err(|error| error_with_changes(error, &changes)), + None => dispatch.map(adapter_proof), } } @@ -92,10 +72,6 @@ fn after_changes( } } -fn has_strong(changes: &[WitnessChange]) -> bool { - changes.iter().any(|change| change.is_strong()) -} - fn adapter_proof(result: ActionResult) -> ActionResult { if result.disposition() == DeliverySemantics::delivered_verified() { result.with_effect(ObservedEffect::Observed) diff --git a/crates/core/src/actions/witnessed_action_tests.rs b/crates/core/src/actions/witnessed_action_tests.rs index dd59b63c59..f637b07a84 100644 --- a/crates/core/src/actions/witnessed_action_tests.rs +++ b/crates/core/src/actions/witnessed_action_tests.rs @@ -79,8 +79,8 @@ fn uncertain() -> Result { #[test] fn the_dispatch_result_chooses_the_step() { - assert_eq!(witness_step(&unverified()), WitnessStep::ReadOnce); - assert_eq!(witness_step(&uncertain()), WitnessStep::Settle); + 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") @@ -128,29 +128,33 @@ fn a_weak_or_no_change_leaves_the_delivery_as_it_was() { #[test] fn an_unclear_answer_with_a_strong_change_is_delivered_and_stays_an_error() { let adapter = adapter( - vec![ - Ok(witness(false, "A")), - Ok(witness(false, "A")), - Ok(witness(true, "A")), - ], + vec![Ok(witness(false, "A")), Ok(witness(true, "A"))], uncertain(), ); let error = run(&adapter).unwrap_err(); assert_eq!(error.disposition, DeliverySemantics::delivered_verified()); assert_eq!(error.details.unwrap()["effect"], "observed"); - assert_eq!(*adapter.read_count.lock().unwrap(), 3); + assert_eq!(*adapter.read_count.lock().unwrap(), 2); } #[test] -fn an_unclear_answer_with_no_change_stays_uncertain_after_the_settle_time() { - let adapter = adapter(vec![Ok(witness(false, "A"))], uncertain()); +fn an_unclear_answer_with_no_change_stays_uncertain_without_a_wait() { + let adapter = adapter( + vec![ + Ok(witness(false, "A")), + Ok(witness(false, "A")), + Ok(witness(true, "A")), + ], + uncertain(), + ); let started = std::time::Instant::now(); let error = run(&adapter).unwrap_err(); assert_eq!(error.disposition, DeliverySemantics::uncertain()); assert_eq!(error.details.unwrap()["effect"], "not_observed"); - assert!(started.elapsed() >= SETTLE); + assert_eq!(*adapter.read_count.lock().unwrap(), 2); + assert!(started.elapsed() < std::time::Duration::from_millis(40)); } #[test] @@ -195,3 +199,19 @@ fn no_witness_and_an_undelivered_action_are_left_alone() { ); 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); +} diff --git a/docs/json-output.md b/docs/json-output.md index 9c1accac16..0240367b39 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -188,7 +188,7 @@ 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. Such a cell publishes no value to read back, so the result is `delivered_unverified`: read the cell again. - 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`, `target_value`, `surface_opened`, `focus_into_target` are strong; `focus_moved_in_window`, `focused_value`, `window_title`, `window_content`, `window_count` are weak). A strong change makes a delivered result `delivered_verified`; weak changes alone change no disposition. After a `delivery_uncertain` error the witness is read until 400 ms after the dispatch; a strong change sets that error's disposition to `delivered_verified`, and `error.details.effect` carries the verdict. A delivered result never becomes `not_delivered`. `not_observed` beside a delivered disposition is not proof that nothing happened. +- 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`, `target_value`, `surface_opened`, `focus_into_target` are strong; `focus_moved_in_window`, `focused_value`, `window_title`, `window_content`, `window_count` are weak). 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 sets that error's disposition to `delivered_verified`, and `error.details.effect` carries the verdict. 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. From 44f07e2e58418543224a7e3d22c4a78bb8904e58 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 13:06:47 -0800 Subject: [PATCH 06/27] feat(windows): read the effect witness, and close a refused Escape's popup through core The effect witness on Windows reads the target's own patterns in one cached update (SelectionItem selected, Value, the ExpandCollapse state as an open popup below it); a target that is gone fails that update and is a stale reference. The focus is read at window-handle grain: GetGUIThreadInfo names the focused window handle, and IsChild and GetAncestor say whether it is inside the target or in the target's window. A focus change inside a window with one handle (WPF, Chromium) is not seen, and the focused value is not read. The window part is its title, a sign of its direct child window handles, and one EnumWindows pass that counts the process's visible top-level windows and tells whether the target's window is still one of them; the target's window handle comes from its RuntimeId, which stays readable after the window is gone. A first read through the UI Automation focused element and a FindAll cost 23 ms more at the median on a click with no effect; this one cost 10 ms more with one read more than core now makes. The popup close after a refused Escape moves into `close_transient_surface`, which core calls: it finds the innermost open menu item, combo box or split button of the target and collapses it with the existing `disclosure_steps`, which already reads the state back. The copied collapse and poll code, the wrapper around the key route and the `press_key_for_window` override are gone, so the core default refuses a window that does not hold the focus, and the process refusals of the key path name `check: process_focus`. A collapse no longer declares a foreground effect, only an expand does, so a headless `collapse` on a combo box or menu item now works where it was refused; Collapse was measured to keep the foreground. The core function for a key to a named window is private again. Measured on real apps against branch 15: Notepad's Close button and the Run dialog's Cancel go from delivered_unverified to delivered_verified (window_closed, target_gone); a Services row click stays verified with effect observed; a Calculator click with no effect stays unverified with effect not_observed; a Server Manager page switch stays unverified (not_observed: no witness field changes, a stated miss). An open Explorer column menu in a window in the back closes with delivered_verified and the foreground unchanged. --- crates/core/src/adapter/focused_window_key.rs | 5 +- crates/core/src/lib.rs | 1 - crates/windows/src/actions/disclosure.rs | 6 +- crates/windows/src/adapter.rs | 8 + crates/windows/src/system/adapter.rs | 18 +- crates/windows/src/system/escape_popup.rs | 104 ++------ .../windows/src/system/escape_popup_tests.rs | 40 +-- crates/windows/src/system/escape_popup_uia.rs | 90 ++----- crates/windows/src/system/key_dispatch.rs | 3 + .../windows/src/system/key_dispatch_tests.rs | 11 + crates/windows/src/tree/effect_witness.rs | 241 ++++++++++++++++++ .../windows/src/tree/effect_witness_tests.rs | 17 ++ crates/windows/src/tree/mod.rs | 1 + skills/agent-desktop-windows/SKILL.md | 1 + 14 files changed, 338 insertions(+), 208 deletions(-) create mode 100644 crates/windows/src/tree/effect_witness.rs create mode 100644 crates/windows/src/tree/effect_witness_tests.rs diff --git a/crates/core/src/adapter/focused_window_key.rs b/crates/core/src/adapter/focused_window_key.rs index 019c4b5eb2..853780d687 100644 --- a/crates/core/src/adapter/focused_window_key.rs +++ b/crates/core/src/adapter/focused_window_key.rs @@ -7,9 +7,8 @@ use crate::{ /// 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/lib.rs b/crates/core/src/lib.rs index 093e7f7d2e..e8b81f79c4 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -47,7 +47,6 @@ 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/windows/src/actions/disclosure.rs b/crates/windows/src/actions/disclosure.rs index ae5416997b..dfb636a7c0 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; @@ -109,7 +109,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), diff --git a/crates/windows/src/adapter.rs b/crates/windows/src/adapter.rs index e5fdc2f68f..7c9d4c6ff1 100644 --- a/crates/windows/src/adapter.rs +++ b/crates/windows/src/adapter.rs @@ -158,6 +158,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 9d2ed221c9..0534854ec4 100644 --- a/crates/windows/src/system/adapter.rs +++ b/crates/windows/src/system/adapter.rs @@ -9,8 +9,7 @@ use agent_desktop_core::{ }; use crate::adapter::WindowsAdapter; -use crate::system::close_outcome::CloseOutcome; -use crate::system::escape_popup; +use crate::system::{close_outcome::CloseOutcome, 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 d5616eb806..73692be7bb 100644 --- a/crates/windows/src/system/escape_popup.rs +++ b/crates/windows/src/system/escape_popup.rs @@ -1,81 +1,14 @@ -//! 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, DeliverySemantics, ErrorCode, KeyCombo}; - -/// Key delivery to `process` (A9-3: SendInput has no per-pid targeting; -/// core's headed path already activated), then the popup close. -pub(crate) fn press_for_app( - process: agent_desktop_core::ProcessIdentity, - combo: &KeyCombo, - policy: agent_desktop_core::InteractionPolicy, - deadline: agent_desktop_core::Deadline, -) -> Result { - let result = - crate::system::key_dispatch::press_for_app_impl(process.clone(), combo, policy, deadline); - after_key_route( - result, - PopupScope::Process(&process), - combo, - policy, - deadline, - ) -} - -/// Core's focus-gated delivery to a named window, then the popup close. -pub(crate) fn press_for_window( - adapter: &A, - window: &agent_desktop_core::WindowInfo, - combo: &KeyCombo, - policy: agent_desktop_core::InteractionPolicy, - lease: &agent_desktop_core::InteractionLease, -) -> Result { - let result = - agent_desktop_core::press_key_in_focused_window(adapter, window, combo, policy, lease); - after_key_route( - result, - PopupScope::Window(window), - combo, - policy, - lease.deadline(), - ) -} - -/// Where a refused Escape looks for an open popup. -pub(crate) enum PopupScope<'a> { - Window(&'a agent_desktop_core::WindowInfo), - Process(&'a agent_desktop_core::ProcessIdentity), -} - -pub(crate) fn is_plain_escape(combo: &KeyCombo) -> bool { - combo.modifiers.is_empty() - && (combo.key.eq_ignore_ascii_case("escape") || combo.key.eq_ignore_ascii_case("esc")) -} - -/// The refusals after which the target's popup gets its close: core's refusal -/// of a window that is not the exact focus holder, and this adapter's refusal -/// of a process that does not hold the keyboard. Each scope answers only its -/// own refusal, so one refusal is searched once. -pub(crate) fn refused_for_focus(window_scope: bool, error: &AdapterError) -> bool { - let details = error.details.as_ref(); - let unsent = error.disposition == DeliverySemantics::not_delivered() - && details.and_then(|details| details["physical_delivery_started"].as_bool()) - == Some(false); - let check = details.and_then(|details| details["check"].as_str()); - unsent - && if window_scope { - check == Some("window_active") - } else { - error.code == ErrorCode::ActionFailed && check.is_none() - } -} +#[cfg(not(target_os = "windows"))] +use agent_desktop_core::{ + ActionResult, AdapterError, Deadline, InteractionPolicy, ProcessIdentity, WindowInfo, +}; /// 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. @@ -88,18 +21,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 c474e54a5e..2a0222207d 100644 --- a/crates/windows/src/system/escape_popup_tests.rs +++ b/crates/windows/src/system/escape_popup_tests.rs @@ -1,42 +1,4 @@ -use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode, KeyCombo, Modifier}; - -use super::{is_plain_escape, opens_a_popup, refused_for_focus}; - -fn key(name: &str, modifiers: Vec) -> KeyCombo { - KeyCombo { - key: name.to_owned(), - modifiers, - } -} - -#[test] -fn only_a_plain_escape_may_close_a_popup() { - assert!(is_plain_escape(&key("escape", vec![]))); - assert!(is_plain_escape(&key("Esc", vec![]))); - assert!(!is_plain_escape(&key("escape", vec![Modifier::Shift]))); - assert!(!is_plain_escape(&key("return", vec![]))); -} - -#[test] -fn each_scope_answers_only_its_own_focus_refusal() { - let window = AdapterError::stale_ref_because("not focused") - .with_details( - serde_json::json!({ "check": "window_active", "physical_delivery_started": false }), - ) - .with_disposition(DeliverySemantics::not_delivered()); - let process = AdapterError::new(ErrorCode::ActionFailed, "not foreground") - .with_details(serde_json::json!({ "pid": 4, "physical_delivery_started": false })) - .with_disposition(DeliverySemantics::not_delivered()); - let sent = AdapterError::new(ErrorCode::ActionFailed, "sent") - .with_details(serde_json::json!({ "physical_delivery_started": true })) - .with_disposition(DeliverySemantics::delivered_unverified()); - - assert!(refused_for_focus(true, &window)); - assert!(!refused_for_focus(false, &window)); - assert!(refused_for_focus(false, &process)); - assert!(!refused_for_focus(true, &process)); - assert!(!refused_for_focus(false, &sent)); -} +use super::opens_a_popup; #[test] fn a_tree_item_or_a_group_is_never_a_popup_owner() { diff --git a/crates/windows/src/system/escape_popup_uia.rs b/crates/windows/src/system/escape_popup_uia.rs index 30adcef736..bec7a41622 100644 --- a/crates/windows/src/system/escape_popup_uia.rs +++ b/crates/windows/src/system/escape_popup_uia.rs @@ -1,26 +1,19 @@ //! The UI Automation half of `escape_popup`: the popup search, the collapse and the two entry points. -use super::{PopupScope, is_plain_escape, opens_a_popup, refused_for_focus}; +use super::opens_a_popup; use agent_desktop_core::{ - Action, ActionResult, AdapterError, Deadline, DeliveryOutcome, InteractionPolicy, KeyCombo, - ProcessIdentity, WindowInfo, + Action, ActionResult, AdapterError, Deadline, InteractionPolicy, KeyCombo, ProcessIdentity, + WindowInfo, }; -use std::time::Duration; -use uiautomation::patterns::UIExpandCollapsePattern; use uiautomation::types::{TreeScope, UIProperty}; use uiautomation::variants::Variant; -use crate::actions::chain::{offered, poll_until, rung}; -use crate::actions::mutation::{classify_success, classify_write}; +use crate::actions::disclosure::disclosure_steps; use crate::tree::element::UIAElement; use crate::tree::properties::property_ids::TreeProperty; use crate::tree::properties::read_one; -const COLLAPSE_LABEL: &str = "ExpandCollapsePattern.Collapse"; -const COLLAPSE_SUGGESTION: &str = "Close the popup with the key while its window is in front."; -const VERIFY_TIMEOUT: Duration = Duration::from_millis(600); const EXPANDED: i32 = 1; -const COLLAPSED: i32 = 0; /// The deepest expanded popup owner among the elements below `roots`: a /// document-order search, so the last match is the innermost level. @@ -80,65 +73,28 @@ fn process_roots(process: &ProcessIdentity) -> Vec { .unwrap_or_default() } -fn collapse(owner: &UIAElement) -> Result { - match owner.0.get_pattern::() { - Ok(pattern) => match pattern.collapse() { - Ok(()) => classify_success(), - Err(error) => classify_write("Collapse", COLLAPSE_LABEL, &error), - }, - Err(error) => classify_write("get_pattern", COLLAPSE_LABEL, &error), - } -} - -fn close_popup( - owner: &UIAElement, - combo: &KeyCombo, +/// 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 { - let mut run = || { - if !collapse(owner)? { - return Ok(DeliveryOutcome::NotDelivered); - } - let closed = poll_until(deadline, VERIFY_TIMEOUT, || { - read_one(owner, TreeProperty::ExpandCollapseState).number() == Some(COLLAPSED) - }); - Ok(DeliveryOutcome::from_delivery(true, closed)) +) -> Result, AdapterError> { + let roots = match window { + Some(window) => window_roots(window, deadline), + None => process_roots(process), }; - 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 Some(owner) = deepest_popup_owner(&roots) else { + return Ok(None); }; - 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), + let steps = disclosure_steps(&owner, false, policy, deadline)?; + let escape = KeyCombo { + key: "escape".to_owned(), + modifiers: Vec::new(), }; - match deepest_popup_owner(&roots) { - Some(owner) => close_popup(&owner, 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..39f81c1a65 --- /dev/null +++ b/crates/windows/src/tree/effect_witness.rs @@ -0,0 +1,241 @@ +//! 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, one while expanded, none otherwise. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub(crate) fn surfaces_from(available: Option, state: Option) -> Option { + (available == Some(true)).then(|| u32::from(state == Some(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| uia_error(&error, "read the effect witness target"))?; + 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..10170bb922 --- /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), Some(0)); +} + +#[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/skills/agent-desktop-windows/SKILL.md b/skills/agent-desktop-windows/SKILL.md index 8d5448af43..bbaa8331b5 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. From 699b06c0123e83c4d7f416ca54ce226c42efa614 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Mon, 16 Nov 2026 13:08:01 -0800 Subject: [PATCH 07/27] feat(linux): read the effect witness, and close a refused Escape's popup through core The effect witness on Linux reads the target's states and value in one read; only a combo box or an element that reports HAS_POPUP or EXPANDED gets the bounded walk that counts the popup menus showing below it, and the target's frame in one step: its name, a sign of its direct children, and the application's frames, which give the window count and whether the frame is still one of them. A target that is gone, or whose application is gone, is a stale reference. The application's focused element cannot be found cheaply on this platform, so the focus part stays empty. The popup close after a refused Escape moves into `close_transient_surface`, which core calls. It keeps the rule of the previous Linux fix: the owner's action goes through the shared action call, a reply of false delivers nothing and is not read back, and the attempt's own error is the answer. The wrapper around the key route, its own focus refusal check and the answer function are gone, because core owns that order now. Measured on real apps against branch 15: gedit's Open dialog Cancel goes from delivered_unverified to delivered_verified (target_gone); a gnome-calculator click with no effect stays unverified with effect not_observed; a terminal whose title changes by itself gives indeterminate (window_title) and verifies nothing. A GTK3 combo popup in a window in the back closes with delivered_verified and the active window unchanged. A click with no effect costs 3 ms more at the median and 6 ms more at p95 (gnome-calculator, 40 runs). --- crates/linux/src/adapter.rs | 17 +- crates/linux/src/system/adapter.rs | 12 +- crates/linux/src/system/focus/escape_popup.rs | 103 +++------- .../src/system/focus/escape_popup_tests.rs | 72 +------ crates/linux/src/system/focus/key_dispatch.rs | 37 +--- crates/linux/src/system/focus/mod.rs | 2 +- crates/linux/src/tree/effect_witness.rs | 193 ++++++++++++++++++ crates/linux/src/tree/effect_witness_tests.rs | 68 ++++++ crates/linux/src/tree/mod.rs | 2 + 9 files changed, 329 insertions(+), 177 deletions(-) create mode 100644 crates/linux/src/tree/effect_witness.rs create mode 100644 crates/linux/src/tree/effect_witness_tests.rs diff --git a/crates/linux/src/adapter.rs b/crates/linux/src/adapter.rs index a7a83f0427..489fd4c574 100644 --- a/crates/linux/src/adapter.rs +++ b/crates/linux/src/adapter.rs @@ -1,9 +1,10 @@ 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, + 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 +90,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, diff --git a/crates/linux/src/system/adapter.rs b/crates/linux/src/system/adapter.rs index 9406cc160d..312b782fa8 100644 --- a/crates/linux/src/system/adapter.rs +++ b/crates/linux/src/system/adapter.rs @@ -13,7 +13,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}, @@ -145,6 +145,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 f6eb4ced58..0032dfb570 100644 --- a/crates/linux/src/system/focus/escape_popup.rs +++ b/crates/linux/src/system/focus/escape_popup.rs @@ -1,24 +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 popup that the application opened -//! stays open in the background on some toolkits, and the key cannot reach -//! it. The popup has an owner: a combo box, or a button that has a popup. The -//! owner's own action toggles the popup, so the action is sent only when a -//! read shows the popup open, and the result is verified by reading it gone. -//! -//! Three states, in this order: the key route is allowed and nothing here -//! runs; the key route is refused for focus and an open popup owner exists -//! in the target window, whose own action closes it; otherwise the refusal -//! stays as it was. The owner's reply is the answer, so a rejected action +//! 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. A popup that the application opened stays open in the background on +//! some toolkits. The popup has an owner: a combo box, or a button that has a +//! popup. The owner's own action toggles the popup, so the action is sent +//! only when a read shows the popup open, and the result is verified by +//! reading it gone. 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. +//! uncertain. use std::time::Duration; use agent_desktop_core::{ - Action, ActionResult, AdapterError, ChainRung, Deadline, DeliveryOutcome, KeyCombo, - StepMechanism, WindowInfo, + Action, ActionResult, AdapterError, ChainRung, Deadline, DeliveryOutcome, InteractionLease, + InteractionPolicy, KeyCombo, ProcessIdentity, StepMechanism, WindowInfo, }; use crate::actions::action_call::do_action; @@ -34,30 +30,16 @@ use crate::tree::vocabulary::role_numbers::{ COMBO_BOX, MENU, POPUP_MENU, PUSH_BUTTON, PUSH_BUTTON_MENU, TOGGLE_BUTTON, }; use crate::tree::vocabulary::state_bits::{EXPANDED, HAS_POPUP, SHOWING, StateBits}; -use crate::tree::{AtspiElement, ObservedRead, WalkedNode, get_live_actions}; +use crate::tree::{AtspiElement, ObservedRead, WalkedNode}; const SCAN_NODES: usize = 600; const OWNER_NODES: usize = 64; const POPUP_CONTAINER_CHILDREN: usize = 16; const CLOSE_SETTLE: Duration = Duration::from_millis(1000); const CLOSE_STEP: Duration = Duration::from_millis(50); -const FOCUS_CHECKS: [&str; 2] = ["window_active", "exact_window_focus"]; const SUGGESTION: &str = "Refresh the snapshot and check whether the popup is still open."; const CLOSE_LABEL: &str = "Action.DoAction"; -pub(super) fn is_plain_escape(combo: &KeyCombo) -> bool { - combo.modifiers.is_empty() && combo.key.eq_ignore_ascii_case("escape") -} - -pub(super) fn is_focus_refusal(error: &AdapterError) -> bool { - error - .details - .as_ref() - .and_then(|details| details.get("check")) - .and_then(|check| check.as_str()) - .is_some_and(|check| FOCUS_CHECKS.contains(&check)) -} - fn bits(node: &WalkedNode) -> Option> { node.payload .node @@ -146,17 +128,15 @@ fn press_owner( deadline: Deadline, ) -> Result { let handle = owner.clone().into_native_handle(); - let names = get_live_actions(bus, &handle, deadline)?.unwrap_or_default(); - do_action( - &Target { - bus, - handle: &handle, - element: owner, - deadline, - }, - &names, - click_verbs(role), - ) + let target = Target { + bus, + handle: &handle, + element: owner, + deadline, + }; + let view = target.view()?; + let names = view.action_names().unwrap_or_default(); + do_action(&target, names, click_verbs(role)) } /// What the owner's reply settles. A reply of false delivered nothing, so the @@ -168,30 +148,17 @@ fn popup_outcome(reply: WriteReply, read_closed: impl FnOnce() -> Option) } } -/// The answer for a refused Escape: the popup attempt's own result, or its own -/// error, which already says whether that attempt may have landed. The refusal -/// stands only when the target window shows no open popup owner. -pub(super) fn popup_answer( - refusal: AdapterError, - popup: Result, AdapterError>, -) -> Result { - match popup { - Ok(Some(settled)) => Ok(settled), - Ok(None) => Err(refusal), - Err(attempt) => Err(attempt), - } -} - -/// The refused Escape of a background application, answered by closing the -/// open popup its target window shows. `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 popup of the target window, closed through its owner. `None` +/// when no 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, - pid: u32, + process: &ProcessIdentity, window: Option<&WindowInfo>, - combo: &KeyCombo, - deadline: Deadline, + _policy: InteractionPolicy, + lease: &InteractionLease, ) -> Result, AdapterError> { + let (pid, deadline) = (process.pid.get(), lease.deadline()); let mut best: Option<(usize, AtspiElement, Option)> = None; for frame in frames_of(bus, pid, window, deadline)? { let walk = scan_walk_structure( @@ -229,13 +196,11 @@ pub(super) fn close_open_popup( mechanism: StepMechanism::SemanticApi, run: Box::new(run), }]; - run_semantic_chain( - &Action::PressKey(combo.clone()), - &mut rungs, - deadline, - SUGGESTION, - ) - .map(Some) + let escape = Action::PressKey(KeyCombo { + key: "escape".to_owned(), + modifiers: Vec::new(), + }); + run_semantic_chain(&escape, &mut rungs, deadline, SUGGESTION).map(Some) } #[cfg(test)] diff --git a/crates/linux/src/system/focus/escape_popup_tests.rs b/crates/linux/src/system/focus/escape_popup_tests.rs index b2f1535842..1dc3ed543d 100644 --- a/crates/linux/src/system/focus/escape_popup_tests.rs +++ b/crates/linux/src/system/focus/escape_popup_tests.rs @@ -1,10 +1,7 @@ -use agent_desktop_core::{ - ActionResult, AdapterError, DeliveryOutcome, DeliverySemantics, ErrorCode, KeyCombo, Modifier, -}; -use serde_json::json; +use agent_desktop_core::DeliveryOutcome; -use super::{is_focus_refusal, is_open_owner, is_plain_escape, popup_answer, popup_outcome}; -use crate::actions::write::mutation::{Abort, WriteKind, WriteReply, abort_error}; +use super::{is_open_owner, popup_outcome}; +use crate::actions::write::mutation::WriteReply; use crate::tree::test_support::helpers::{read_of, words}; use crate::tree::vocabulary::role_numbers::{COMBO_BOX, MENU, PUSH_BUTTON, TABLE_CELL}; use crate::tree::vocabulary::state_bits::{EXPANDED, HAS_POPUP, SHOWING}; @@ -27,36 +24,6 @@ fn node( } } -fn combo(key: &str, modifiers: Vec) -> KeyCombo { - KeyCombo { - key: key.to_owned(), - modifiers, - } -} - -#[test] -fn only_a_plain_escape_is_an_escape() { - assert!(is_plain_escape(&combo("escape", Vec::new()))); - assert!(is_plain_escape(&combo("Escape", Vec::new()))); - assert!(!is_plain_escape(&combo("escape", vec![Modifier::Ctrl]))); - assert!(!is_plain_escape(&combo("return", Vec::new()))); -} - -#[test] -fn only_a_focus_refusal_is_answered_by_closing_a_popup() { - let refusal = |check: &str| { - AdapterError::new(ErrorCode::ActionFailed, "refused") - .with_details(json!({ "check": check })) - }; - assert!(is_focus_refusal(&refusal("window_active"))); - assert!(is_focus_refusal(&refusal("exact_window_focus"))); - assert!(!is_focus_refusal(&refusal("process_state"))); - assert!(!is_focus_refusal(&AdapterError::new( - ErrorCode::ActionFailed, - "no details" - ))); -} - #[test] fn only_a_combo_box_or_a_popup_button_with_an_open_popup_is_an_open_owner() { let shown = || vec![node(MENU, &[SHOWING], Vec::new())]; @@ -83,36 +50,3 @@ fn a_rejected_owner_action_is_never_a_delivery() { DeliveryOutcome::observed(Some(true)) ); } - -fn focus_refusal() -> AdapterError { - AdapterError::new(ErrorCode::ActionFailed, "refused") - .with_details(json!({ "check": "window_active" })) - .with_disposition(DeliverySemantics::not_delivered()) -} - -#[test] -fn a_popup_attempt_that_may_have_landed_keeps_its_own_uncertain_error() { - let timed_out = abort_error(Abort::TimedOut, WriteKind::DoAction, None); - let answer = popup_answer(focus_refusal(), Err(timed_out)).expect_err("the popup's error"); - assert_eq!(answer.code, ErrorCode::Timeout); - assert_eq!(answer.disposition, DeliverySemantics::uncertain()); - assert!(!is_focus_refusal(&answer)); -} - -#[test] -fn a_refused_escape_stays_refused_when_no_popup_owner_is_open() { - let answer = popup_answer(focus_refusal(), Ok(None)).expect_err("nothing closed a popup"); - assert!(is_focus_refusal(&answer)); - assert_eq!(answer.disposition, DeliverySemantics::not_delivered()); -} - -#[test] -fn a_closed_popup_answers_the_refused_escape() { - let settled = ActionResult::delivered_unverified("close_popup"); - let answer = popup_answer(focus_refusal(), Ok(Some(settled))).expect("the popup closed"); - assert_eq!(answer.action, "close_popup"); - assert_eq!( - answer.disposition(), - DeliverySemantics::delivered_unverified() - ); -} diff --git a/crates/linux/src/system/focus/key_dispatch.rs b/crates/linux/src/system/focus/key_dispatch.rs index d8f3e40478..015c3fa449 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}; @@ -206,25 +205,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: (u32, 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, @@ -234,8 +214,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 pid = process.pid.get(); - let result = press_in(Press { + press_in(Press { physical: &LiveWorld { bus, lease }, keys: &LiveKeys { bus }, process: &process, @@ -243,8 +222,7 @@ pub(crate) fn press_key_for_app( combo, policy, deadline: lease.deadline(), - }); - closing_popup_when_refused(result, bus, (pid, None), combo, lease.deadline()) + }) } pub(crate) fn press_key_for_window( @@ -261,7 +239,7 @@ pub(crate) fn press_key_for_window( .as_deref() .filter(|instance| !instance.is_empty()) .ok_or_else(|| window_not_active(window))?; - let result = press_in(Press { + press_in(Press { physical: &LiveWorld { bus, lease }, keys: &LiveKeys { bus }, process: &ProcessIdentity::new(window.pid, instance), @@ -269,14 +247,7 @@ pub(crate) fn press_key_for_window( combo, policy, deadline: lease.deadline(), - }); - closing_popup_when_refused( - result, - bus, - (window.pid.get(), Some(window)), - combo, - lease.deadline(), - ) + }) } #[cfg(test)] diff --git a/crates/linux/src/system/focus/mod.rs b/crates/linux/src/system/focus/mod.rs index 3af5891e86..d5efb74f72 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 Option> { + read.node + .traits + .states + .present() + .map(|words| StateBits::new(words)) +} + +fn bits(node: &WalkedNode) -> Option> { + bits_of(&node.payload) +} + +fn showing_popups(node: &WalkedNode) -> u32 { + let own = matches!( + node.payload.node.traits.role.present().copied(), + Some(MENU | POPUP_MENU) + ) && bits(node).is_some_and(|bits| bits.has(SHOWING)); + u32::from(own) + node.children.iter().map(showing_popups).sum::() +} + +/// 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 { + 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..175e33520a --- /dev/null +++ b/crates/linux/src/tree/effect_witness_tests.rs @@ -0,0 +1,68 @@ +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, 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_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}; From b13abc56fef39a639d447817d592a62ea1f92de6 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:48:22 -0800 Subject: [PATCH 08/27] fix(windows): read an unreadable expand state as unknown in the effect witness A missing ExpandCollapseState counted as closed, so a popup that was already open looked like one the click had opened and verified it. --- crates/windows/src/tree/effect_witness.rs | 8 ++++++-- crates/windows/src/tree/effect_witness_tests.rs | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/windows/src/tree/effect_witness.rs b/crates/windows/src/tree/effect_witness.rs index 39f81c1a65..4e8c688610 100644 --- a/crates/windows/src/tree/effect_witness.rs +++ b/crates/windows/src/tree/effect_witness.rs @@ -10,10 +10,14 @@ use std::hash::{Hash, Hasher}; /// Open surfaces below an element from its `ExpandCollapse` reads: `None` -/// without the pattern, one while expanded, none otherwise. +/// 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 { - (available == Some(true)).then(|| u32::from(state == Some(1))) + 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 diff --git a/crates/windows/src/tree/effect_witness_tests.rs b/crates/windows/src/tree/effect_witness_tests.rs index 10170bb922..11fd338f8a 100644 --- a/crates/windows/src/tree/effect_witness_tests.rs +++ b/crates/windows/src/tree/effect_witness_tests.rs @@ -6,7 +6,7 @@ fn an_element_shows_a_surface_only_through_its_expand_collapse_state() { 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), Some(0)); + assert_eq!(surfaces_from(Some(true), None), None); } #[test] From 274353d09d40f8fd4b5d8d033e3121c4b21b52f9 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:48:22 -0800 Subject: [PATCH 09/27] fix(macos): count focus that arrives from no focus as an effect An application with no focused element read the same as a focus that could not be read, so a press that moved focus into its target showed no change. "Nothing has focus" is now its own read. --- .../core/src/actions/effect_witness_tests.rs | 15 ++++++++++++ crates/core/src/actions/focus_witness.rs | 14 +++++++++++ crates/macos/src/actions/effect_witness.rs | 23 ++++++++----------- 3 files changed, 38 insertions(+), 14 deletions(-) diff --git a/crates/core/src/actions/effect_witness_tests.rs b/crates/core/src/actions/effect_witness_tests.rs index ced827dfdc..f6b1f04c9d 100644 --- a/crates/core/src/actions/effect_witness_tests.rs +++ b/crates/core/src/actions/effect_witness_tests.rs @@ -1,4 +1,5 @@ use super::{EffectWitness, verdict}; +use crate::actions::focus_witness::FocusWitness; use crate::actions::{observed_effect::ObservedEffect, witness_change::WitnessChange}; fn read() -> EffectWitness { @@ -104,3 +105,17 @@ fn a_field_read_only_once_and_a_state_that_goes_away_are_no_evidence() { 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); + + assert!( + now.changes_since(&before) + .contains(&WitnessChange::FocusIntoTarget) + ); +} diff --git a/crates/core/src/actions/focus_witness.rs b/crates/core/src/actions/focus_witness.rs index e31c6c4960..a3d8d71f28 100644 --- a/crates/core/src/actions/focus_witness.rs +++ b/crates/core/src/actions/focus_witness.rs @@ -12,3 +12,17 @@ pub struct FocusWitness { 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. + 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/macos/src/actions/effect_witness.rs b/crates/macos/src/actions/effect_witness.rs index c3b1f8a7fc..19d37d5c52 100644 --- a/crates/macos/src/actions/effect_witness.rs +++ b/crates/macos/src/actions/effect_witness.rs @@ -23,11 +23,13 @@ mod imp { 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 focused = app.and_then(|app| { - attributes::copy_element_attr_result(&app, "AXFocusedUIElement", deadline) - .ok() - .flatten() - }); + let focus = match app + .map(|app| attributes::copy_element_attr_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) @@ -36,7 +38,7 @@ mod imp { value: crate::tree::copy_value_typed(element, deadline), surfaces: surfaces_below(element, deadline), }, - focus: focus_of(focused.as_ref(), element, deadline), + focus, window: WindowWitness::default(), }) } @@ -71,14 +73,7 @@ mod imp { u32::try_from(popovers.count()).ok() } - fn focus_of( - focused: Option<&AXElement>, - element: &AXElement, - deadline: Deadline, - ) -> FocusWitness { - let Some(focused) = focused else { - return FocusWitness::default(); - }; + fn focus_of(focused: &AXElement, element: &AXElement, deadline: Deadline) -> FocusWitness { FocusWitness { element: crate::tree::resolve::retained::capture(focused) .ok() From bdb7c55c5adfec72746c9891cdecbf283f50b490 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:54:48 -0800 Subject: [PATCH 10/27] fix(macos): report no focus only when the application answers no value The element reader returns none for an attribute the application does not implement or fails to answer, as well as for no value. Taking those as "nothing has focus" could count an already focused target as focus that moved. Only a no-value answer is read as no focus now. --- crates/core/src/actions/focus_witness.rs | 3 +- crates/macos/src/actions/effect_witness.rs | 6 ++-- .../macos/src/tree/properties/attributes.rs | 32 +++++++++++++++---- 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/crates/core/src/actions/focus_witness.rs b/crates/core/src/actions/focus_witness.rs index a3d8d71f28..ca4ec702cc 100644 --- a/crates/core/src/actions/focus_witness.rs +++ b/crates/core/src/actions/focus_witness.rs @@ -16,7 +16,8 @@ pub struct FocusWitness { 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. + /// 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()), diff --git a/crates/macos/src/actions/effect_witness.rs b/crates/macos/src/actions/effect_witness.rs index 19d37d5c52..fd84ca4879 100644 --- a/crates/macos/src/actions/effect_witness.rs +++ b/crates/macos/src/actions/effect_witness.rs @@ -23,9 +23,9 @@ mod imp { 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_result(&app, "AXFocusedUIElement", deadline)) - { + 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(), 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")] From b5c7c33b980f1e44ee15292dba15950189b77ae9 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Thu, 19 Nov 2026 17:04:09 -0800 Subject: [PATCH 11/27] fix: count a change of the target's value as weak evidence of a click A value that changes by itself, such as a timer or a playing scrubber, made a click that did nothing delivered_verified. A second read before the dispatch would cost a full witness read and still miss a slow timer, so the value now only reports, like the other changes an application can make by itself. --- crates/core/src/actions/effect_witness_tests.rs | 8 ++++---- crates/core/src/actions/witness_change.rs | 7 +++---- docs/json-output.md | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/crates/core/src/actions/effect_witness_tests.rs b/crates/core/src/actions/effect_witness_tests.rs index f6b1f04c9d..ab35a59e84 100644 --- a/crates/core/src/actions/effect_witness_tests.rs +++ b/crates/core/src/actions/effect_witness_tests.rs @@ -33,10 +33,6 @@ fn a_change_on_or_under_the_target_is_an_observed_effect() { (|w: &mut EffectWitness| w.target.selected = Some(true)) as fn(&mut EffectWitness), WitnessChange::TargetSelected, ), - ( - |w| w.target.value = Some("1".into()), - WitnessChange::TargetValue, - ), ( |w| w.target.surfaces = Some(1), WitnessChange::SurfaceOpened, @@ -71,6 +67,10 @@ fn a_change_the_application_can_make_by_itself_is_indeterminate() { 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()), diff --git a/crates/core/src/actions/witness_change.rs b/crates/core/src/actions/witness_change.rs index 6258ff9cf3..ced558b387 100644 --- a/crates/core/src/actions/witness_change.rs +++ b/crates/core/src/actions/witness_change.rs @@ -21,16 +21,15 @@ pub enum WitnessChange { impl WitnessChange { /// A change that only the action explains. A window title, the window's - /// content, the number of windows, and focus moving elsewhere in the window - /// can also change by themselves (a timer, a notification), so they are - /// weak evidence. + /// 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::TargetValue | Self::SurfaceOpened | Self::FocusIntoTarget ) diff --git a/docs/json-output.md b/docs/json-output.md index 6a0c7f00c4..cf485c2027 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -188,7 +188,7 @@ 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. Such a cell publishes no value to read back, so the result is `delivered_unverified`: read the cell again. - 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`, `target_value`, `surface_opened`, `focus_into_target` are strong; `focus_moved_in_window`, `focused_value`, `window_title`, `window_content`, `window_count` are weak). 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 sets that error's disposition to `delivered_verified`, and `error.details.effect` carries the verdict. 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. +- 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 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 sets that error's disposition to `delivered_verified`, and `error.details.effect` carries the verdict. 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. From ab0a1b1acb6264d37026ffb9cc8ee4e6d382b1a3 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Thu, 19 Nov 2026 17:21:01 -0800 Subject: [PATCH 12/27] fix(macos): verify a press only by a change the application cannot make itself The press check turned a value change or a focus move into a verified delivery, while core counts those as weak: a live value made a press that did nothing delivered_verified. Any press-relevant change still shows the press arrived; only a strong one (WitnessChange::is_strong) now verifies it, so one rule decides verification in core and in the adapter. A toggle is verified through check, uncheck or toggle, which read the state back. --- crates/macos/src/actions/activation_effect.rs | 36 ++++++++++++------- .../src/actions/activation_effect_tests.rs | 31 ++++++++++++++-- crates/macos/src/actions/ax_mutation.rs | 20 ++++++----- crates/macos/src/actions/ax_perform.rs | 6 ++-- .../actions/chain/chain_disclosure_steps.rs | 2 +- docs/json-output.md | 2 +- skills/agent-desktop/SKILL.md | 2 +- 7 files changed, 71 insertions(+), 28 deletions(-) diff --git a/crates/macos/src/actions/activation_effect.rs b/crates/macos/src/actions/activation_effect.rs index 609a61f23e..ffc910e9f7 100644 --- a/crates/macos/src/actions/activation_effect.rs +++ b/crates/macos/src/actions/activation_effect.rs @@ -5,11 +5,13 @@ //! 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. +//! 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, EffectWitness, WitnessChange}; + use agent_desktop_core::{Deadline, DeliveryObservation, EffectWitness, WitnessChange}; use crate::actions::effect_witness; use crate::tree::AXElement; @@ -25,10 +27,10 @@ mod imp { before: &Option, element: &AXElement, deadline: Deadline, - ) -> bool { + ) -> Option { match (before, focus_state(element, deadline)) { - (Some(before), Some(after)) => press_delivered(&after.changes_since(before)), - _ => false, + (Some(before), Some(after)) => press_reaction(&after.changes_since(before)), + _ => None, } } @@ -36,14 +38,12 @@ mod imp { 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 @@ -51,7 +51,19 @@ mod imp { .min(std::time::Duration::from_millis(SETTLE_POLL_MS)), ); } - false + None + } + + /// 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 + } + }) } /// The changes that show a press reached the application. diff --git a/crates/macos/src/actions/activation_effect_tests.rs b/crates/macos/src/actions/activation_effect_tests.rs index ae31d9c5ec..983bc5bb33 100644 --- a/crates/macos/src/actions/activation_effect_tests.rs +++ b/crates/macos/src/actions/activation_effect_tests.rs @@ -1,5 +1,5 @@ -use super::imp::press_delivered; -use agent_desktop_core::WitnessChange; +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() { @@ -23,3 +23,30 @@ fn a_press_is_delivered_by_a_change_in_the_target_or_its_focus_but_not_by_the_wi } 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/docs/json-output.md b/docs/json-output.md index cf485c2027..5c87d53989 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -188,7 +188,7 @@ 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. Such a cell publishes no value to read back, so the result is `delivered_unverified`: read the cell again. - 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 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 sets that error's disposition to `delivered_verified`, and `error.details.effect` carries the verdict. 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. +- 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 sets that error's disposition to `delivered_verified`, and `error.details.effect` carries the verdict. 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/SKILL.md b/skills/agent-desktop/SKILL.md index 77b519be2c..10be967081 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 From d7bd8ca756c28abf3437d626867af41a0be9919d Mon Sep 17 00:00:00 2001 From: Lahfir Date: Thu, 19 Nov 2026 20:45:46 -0800 Subject: [PATCH 13/27] fix(linux): leave the popup count unknown when a menu or the walk was not read The witness counted a popup menu whose states could not be read as closed, and a walk cut short as complete, so a popup already open could be missed before a click and seen after it, verifying a click that did nothing. Either case now leaves the count unknown, which never counts as a change; a list cut at its row limit hides only rows and still counts. --- crates/linux/src/tree/effect_witness.rs | 28 +++++++++++++------ crates/linux/src/tree/effect_witness_tests.rs | 17 ++++++++++- 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/crates/linux/src/tree/effect_witness.rs b/crates/linux/src/tree/effect_witness.rs index 4b46c8994f..dbc5864c7d 100644 --- a/crates/linux/src/tree/effect_witness.rs +++ b/crates/linux/src/tree/effect_witness.rs @@ -21,7 +21,7 @@ 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}; +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::{ @@ -43,12 +43,24 @@ fn bits(node: &WalkedNode) -> Option> { bits_of(&node.payload) } -fn showing_popups(node: &WalkedNode) -> u32 { - let own = matches!( - node.payload.node.traits.role.present().copied(), - Some(MENU | POPUP_MENU) - ) && bits(node).is_some_and(|bits| bits.has(SHOWING)); - u32::from(own) + node.children.iter().map(showing_popups).sum::() +/// 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 @@ -62,7 +74,7 @@ pub(crate) fn may_own_popup(role: Option, bits: &StateBits<'_>) -> bool { /// 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); + let shown = showing_popups(target)?; Some(if shown == 0 && bits.has(EXPANDED) { 1 } else { diff --git a/crates/linux/src/tree/effect_witness_tests.rs b/crates/linux/src/tree/effect_witness_tests.rs index 175e33520a..5eb73fbfdf 100644 --- a/crates/linux/src/tree/effect_witness_tests.rs +++ b/crates/linux/src/tree/effect_witness_tests.rs @@ -1,7 +1,7 @@ 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, MENU}; +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}; @@ -40,6 +40,21 @@ fn the_surfaces_of_a_target_are_the_popups_that_show_below_it() { 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); From 1092977acdfaf0b3caa533b4a904fb701de437fd Mon Sep 17 00:00:00 2001 From: Lahfir Date: Thu, 19 Nov 2026 20:45:47 -0800 Subject: [PATCH 14/27] fix(macos): leave the surface count unknown when a menu or a child cannot be read A menu control whose menu could not be read fell back to counting popovers and counted zero, and a child whose role could not be read counted as no popover, so a later whole read could verify a click that opened nothing. Both now leave the count unknown. The witness reuses the role it already reads. --- crates/macos/src/actions/effect_witness.rs | 44 +++++++++++++------ .../macos/src/actions/effect_witness_tests.rs | 11 +++++ crates/macos/src/actions/owned_menu.rs | 25 ++++++++--- 3 files changed, 59 insertions(+), 21 deletions(-) create mode 100644 crates/macos/src/actions/effect_witness_tests.rs diff --git a/crates/macos/src/actions/effect_witness.rs b/crates/macos/src/actions/effect_witness.rs index fd84ca4879..bdb7b96eb7 100644 --- a/crates/macos/src/actions/effect_witness.rs +++ b/crates/macos/src/actions/effect_witness.rs @@ -20,7 +20,7 @@ mod imp { element: &AXElement, deadline: Deadline, ) -> Result { - surface_read::string(element, "AXRole", deadline)?; + 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| { @@ -36,7 +36,7 @@ mod imp { .ok() .flatten(), value: crate::tree::copy_value_typed(element, deadline), - surfaces: surfaces_below(element, deadline), + surfaces: surfaces_below(element, role.as_deref(), deadline), }, focus, window: WindowWitness::default(), @@ -54,23 +54,23 @@ mod imp { } /// Open menus and popovers directly below the element: a menu control's - /// own menu, or a popover a control anchors. - fn surfaces_below(element: &AXElement, deadline: Deadline) -> Option { - if let Some(open) = crate::actions::owned_menu::owned_menu_open(element, deadline) { - return Some(u32::from(open)); + /// 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; } - let popovers = children.iter().filter(|child| { - surface_read::string(child, "AXRole", deadline) - .ok() - .flatten() - .as_deref() - == Some("AXPopover") - }); - u32::try_from(popovers.count()).ok() + super::popover_count( + children + .iter() + .map(|child| surface_read::string(child, "AXRole", deadline)), + ) } fn focus_of(focused: &AXElement, element: &AXElement, deadline: Deadline) -> FocusWitness { @@ -186,3 +186,19 @@ mod imp { #[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/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" { From 1ba68d3a401c849fb8b99b4084250baa257b8d4b Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:17:51 -0800 Subject: [PATCH 15/27] fix(core): count focus into the target only when it arrived from outside Focus that was already inside the target and moved to another child counted as focus into the target, which verified the action. Focus now counts as an arrival only when the earlier read saw it outside the target; a move within the target window stays weak evidence, and an unread earlier focus never becomes an arrival. --- crates/core/src/actions/effect_witness.rs | 15 +++--- .../core/src/actions/effect_witness_tests.rs | 47 +++++++++++++++++-- 2 files changed, 51 insertions(+), 11 deletions(-) diff --git a/crates/core/src/actions/effect_witness.rs b/crates/core/src/actions/effect_witness.rs index 60efcd2922..e635c4fc41 100644 --- a/crates/core/src/actions/effect_witness.rs +++ b/crates/core/src/actions/effect_witness.rs @@ -19,9 +19,15 @@ 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), @@ -35,14 +41,9 @@ impl EffectWitness { grew(then.target.surfaces, now.target.surfaces), WitnessChange::SurfaceOpened, ), + (focus_arrived, WitnessChange::FocusIntoTarget), ( - focus_moved && now.focus.inside_target == Some(true), - WitnessChange::FocusIntoTarget, - ), - ( - focus_moved - && now.focus.inside_target != Some(true) - && now.focus.in_target_window == Some(true), + focus_moved && !focus_arrived && now.focus.in_target_window == Some(true), WitnessChange::FocusMovedInWindow, ), ( diff --git a/crates/core/src/actions/effect_witness_tests.rs b/crates/core/src/actions/effect_witness_tests.rs index ab35a59e84..3243b98b56 100644 --- a/crates/core/src/actions/effect_witness_tests.rs +++ b/crates/core/src/actions/effect_witness_tests.rs @@ -114,8 +114,47 @@ fn focus_that_arrives_in_the_target_from_no_focus_is_a_change() { now.focus.element = Some("target".into()); now.focus.inside_target = Some(true); - assert!( - now.changes_since(&before) - .contains(&WitnessChange::FocusIntoTarget) - ); + 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); } From 7929e452d31fce5c7d7ab51d096bf951250da733 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:18:53 -0800 Subject: [PATCH 16/27] fix(macos): close the open transient surface after a refused escape macOS was the only adapter without close_transient_surface, so a plain Escape refused for focus left an open menu or popover on screen. The adapter now cancels the surface with AXCancel, searching the named window or the whole process, and verifies it left. The no-focused-element refusal now names process_focus so core routes the refused Escape to that close. --- crates/macos/src/system/adapter.rs | 10 ++ crates/macos/src/system/escape_popup.rs | 138 ++++++++++++++++++ crates/macos/src/system/escape_popup_tests.rs | 133 +++++++++++++++++ crates/macos/src/system/key_dispatch.rs | 47 ++---- crates/macos/src/system/key_dispatch_tests.rs | 10 ++ crates/macos/src/system/mod.rs | 1 + crates/macos/src/tree/app_menu.rs | 8 + crates/macos/src/tree/surfaces.rs | 12 ++ 8 files changed, 326 insertions(+), 33 deletions(-) create mode 100644 crates/macos/src/system/escape_popup.rs create mode 100644 crates/macos/src/system/escape_popup_tests.rs diff --git a/crates/macos/src/system/adapter.rs b/crates/macos/src/system/adapter.rs index 2a63595bd3..cb980bea79 100644 --- a/crates/macos/src/system/adapter.rs +++ b/crates/macos/src/system/adapter.rs @@ -226,6 +226,16 @@ impl SystemOps for MacOSAdapter { crate::system::key_dispatch::press_for_app_impl(process, combo, policy, lease.deadline()) } + fn close_transient_surface( + &self, + process: &ProcessIdentity, + window: Option<&WindowInfo>, + policy: agent_desktop_core::InteractionPolicy, + lease: &InteractionLease, + ) -> Result, AdapterError> { + crate::system::escape_popup::close_transient_surface(process, window, policy, lease) + } + fn wait_for_menu( &self, process: ProcessIdentity, diff --git a/crates/macos/src/system/escape_popup.rs b/crates/macos/src/system/escape_popup.rs new file mode 100644 index 0000000000..82132dd244 --- /dev/null +++ b/crates/macos/src/system/escape_popup.rs @@ -0,0 +1,138 @@ +//! 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, ErrorCode, InteractionLease, + InteractionPolicy, KeyCombo, ProcessIdentity, StepMechanism, WindowInfo, +}; + +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. +pub(crate) trait TransientSurface { + type Surface; + + fn in_window(&self, window: &WindowInfo) -> Result, AdapterError>; + + fn in_process(&self, process: &ProcessIdentity) -> 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 Surface = AXElement; + + fn in_window(&self, window: &WindowInfo) -> Result, AdapterError> { + let element = + crate::system::window::window_resolve::window_element_for_info(window, self.deadline)?; + crate::tree::surfaces::transient_surface_in_window(&element, self.deadline) + } + + fn in_process(&self, process: &ProcessIdentity) -> Result, AdapterError> { + let pid = crate::system::process::process_identity::to_pid_t(process.pid)?; + crate::tree::surfaces::transient_surface_for_pid(pid, 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 the process shows in `window`, or anywhere in the +/// process when there is no window. `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. +pub(crate) fn cancel_surface( + surface: &AXElement, + deadline: Deadline, +) -> Result, AdapterError> { + 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 found = match window { + Some(window) => surfaces.in_window(window)?, + None => surfaces.in_process(process)?, + }; + let Some(surface) = found else { + return Ok(None); + }; + if !surfaces.cancel(&surface)? { + return Ok(None); + } + Ok(Some(closed_result(action_step(surfaces.closed(&surface))))) +} + +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..3ea2dd5570 --- /dev/null +++ b/crates/macos/src/system/escape_popup_tests.rs @@ -0,0 +1,133 @@ +use std::cell::RefCell; + +use agent_desktop_core::{AdapterError, DeliverySemantics, ProcessIdentity, WindowInfo}; + +use super::{TransientSurface, close_with}; + +struct FakeSurfaces { + surface: Option<&'static str>, + cancel_supported: bool, + closed: bool, + looked_in: RefCell>, + cancelled: RefCell, +} + +impl TransientSurface for FakeSurfaces { + type Surface = &'static str; + + fn in_window(&self, window: &WindowInfo) -> Result, AdapterError> { + self.looked_in + .borrow_mut() + .push(format!("window:{}", window.id)); + Ok(self.surface) + } + + fn in_process(&self, process: &ProcessIdentity) -> Result, AdapterError> { + self.looked_in + .borrow_mut() + .push(format!("process:{}", process.pid.get())); + Ok(self.surface) + } + + fn cancel(&self, _surface: &&'static str) -> Result { + *self.cancelled.borrow_mut() = true; + Ok(self.cancel_supported) + } + + fn closed(&self, _surface: &&'static str) -> bool { + self.closed + } +} + +fn surfaces(surface: Option<&'static str>) -> FakeSurfaces { + FakeSurfaces { + surface, + cancel_supported: true, + closed: true, + looked_in: RefCell::new(Vec::new()), + cancelled: RefCell::new(false), + } +} + +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.looked_in.borrow(), ["process:42"]); + assert!(*surfaces.cancelled.borrow()); + assert_eq!( + result.disposition(), + DeliverySemantics::delivered_verified() + ); + assert_eq!(result.steps[0].verified, Some(true)); +} + +#[test] +fn a_window_scoped_close_searches_only_that_window() { + let surfaces = surfaces(Some("menu")); + let window = window(); + + let result = close_with(&surfaces, &process(), Some(&window)) + .unwrap() + .expect("a closed surface"); + + assert_eq!(*surfaces.looked_in.borrow(), ["window:W1"]); + assert_eq!( + result.disposition(), + DeliverySemantics::delivered_verified() + ); +} + +#[test] +fn no_open_surface_leaves_the_refusal() { + let surfaces = surfaces(None); + + assert!(close_with(&surfaces, &process(), None).unwrap().is_none()); + assert_eq!(*surfaces.looked_in.borrow(), ["process:42"]); + assert!(!*surfaces.cancelled.borrow()); +} + +#[test] +fn a_surface_that_does_not_take_the_cancel_leaves_the_refusal() { + let mut surfaces = surfaces(Some("menu")); + surfaces.cancel_supported = false; + + assert!(close_with(&surfaces, &process(), None).unwrap().is_none()); + assert!(*surfaces.cancelled.borrow()); +} + +#[test] +fn a_close_that_cannot_be_read_back_is_unverified() { + let mut surfaces = surfaces(Some("menu")); + surfaces.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 b6b7aff472..05f24e6cc2 100644 --- a/crates/macos/src/system/key_dispatch.rs +++ b/crates/macos/src/system/key_dispatch.rs @@ -4,6 +4,7 @@ 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"] @@ -145,45 +146,21 @@ fn deliver_semantic_key( let Some(target) = semantic_key_target(pid, app, action, deadline)? else { return Ok(None); }; - let (element, closes_surface) = match &target { - SemanticKeyTarget::FocusHolder(element) => (element, false), - SemanticKeyTarget::OpenSurface(element) => (element, true), - }; - if !crate::actions::ax_helpers::try_ax_action_or_err(element, action, deadline)? { - return Ok(None); + match &target { + SemanticKeyTarget::FocusHolder(element) => { + 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(element, deadline), } - let closed = closes_surface && surface_closed(element, deadline); - Ok(Some(semantic_step(action).with_verified(closed))) -} - -/// A closed surface leaves the tree: a popover's element becomes invalid, and -/// a menu's element stays readable but is no longer a child of its parent. -fn surface_closed(surface: &AXElement, deadline: Deadline) -> bool { - let gone = || match crate::tree::surface_read::element(surface, "AXParent", deadline) { - Err(error) => error.code == ErrorCode::StaleRef, - Ok(None) => true, - Ok(Some(parent)) => crate::tree::surface_read::elements(&parent, "AXChildren", deadline) - .is_ok_and(|children| { - !children - .iter() - .any(|child| crate::tree::same_element(child, surface)) - }), - }; - deadline.poll_until( - SURFACE_CLOSE_WAIT, - Duration::from_millis(10), - gone, - |gone| *gone, - ) } fn uses_menu_shortcut(combo: &KeyCombo, policy: InteractionPolicy) -> bool { policy.allow_focus_steal && !combo.modifiers.is_empty() } -const CANCEL: &str = "AXCancel"; -const SURFACE_CLOSE_WAIT: Duration = Duration::from_millis(500); - fn simple_key_action(combo: &KeyCombo) -> Option<&'static str> { if !combo.modifiers.is_empty() { return None; @@ -200,7 +177,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 bbf1414087..f6dc71d37c 100644 --- a/crates/macos/src/system/key_dispatch_tests.rs +++ b/crates/macos/src/system/key_dispatch_tests.rs @@ -85,6 +85,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/mod.rs b/crates/macos/src/system/mod.rs index 50b1985415..22d30cb906 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/app_menu.rs b/crates/macos/src/tree/app_menu.rs index 0741f36773..51e64ba1b6 100644 --- a/crates/macos/src/tree/app_menu.rs +++ b/crates/macos/src/tree/app_menu.rs @@ -226,6 +226,14 @@ fn surface_from_app( } #[cfg(target_os = "macos")] +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, diff --git a/crates/macos/src/tree/surfaces.rs b/crates/macos/src/tree/surfaces.rs index 5913c0c1d1..f68456ca68 100644 --- a/crates/macos/src/tree/surfaces.rs +++ b/crates/macos/src/tree/surfaces.rs @@ -35,6 +35,18 @@ pub(crate) fn transient_surface_for_pid( }) } +/// The menu or popover inside `window`, read in one bounded pass. +#[cfg(target_os = "macos")] +pub(crate) fn transient_surface_in_window( + window: &AXElement, + deadline: Deadline, +) -> Result, AdapterError> { + Ok( + super::app_menu::find_transient_surface(window.clone(), "window".into(), deadline)? + .map(|(_, surface)| surface), + ) +} + #[cfg(target_os = "macos")] fn first_child_with_role_or_subrole( pid: i32, From a56ad195a3b20e6eb3a50722896a1bff9a2ca452 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:31:11 -0800 Subject: [PATCH 17/27] fix: fall back to the app's open surface when escape is scoped to a window An escape with --window-id only searched the named window for an open surface, so an app-level menu or popup left the close with nothing to cancel even though the skill promises the surface that window or the app shows. Search the window first, then fall back to the surface the process shows; a real window lookup error still propagates instead of being masked by the fallback. Tests cover the window-first path, the fallback, and error propagation. --- crates/macos/src/system/escape_popup.rs | 26 +++++-- crates/macos/src/system/escape_popup_tests.rs | 78 +++++++++++++++---- 2 files changed, 81 insertions(+), 23 deletions(-) diff --git a/crates/macos/src/system/escape_popup.rs b/crates/macos/src/system/escape_popup.rs index 82132dd244..90f5693fdb 100644 --- a/crates/macos/src/system/escape_popup.rs +++ b/crates/macos/src/system/escape_popup.rs @@ -56,8 +56,8 @@ impl TransientSurface for AxSurfaces { } } -/// Closes the surface the process shows in `window`, or anywhere in the -/// process when there is no window. `None` when none is open. +/// 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>, @@ -90,11 +90,7 @@ fn close_with( process: &ProcessIdentity, window: Option<&WindowInfo>, ) -> Result, AdapterError> { - let found = match window { - Some(window) => surfaces.in_window(window)?, - None => surfaces.in_process(process)?, - }; - let Some(surface) = found else { + let Some(surface) = find_surface(surfaces, process, window)? else { return Ok(None); }; if !surfaces.cancel(&surface)? { @@ -103,6 +99,22 @@ fn close_with( Ok(Some(closed_result(action_step(surfaces.closed(&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. +fn find_surface( + surfaces: &S, + process: &ProcessIdentity, + window: Option<&WindowInfo>, +) -> Result, AdapterError> { + let Some(window) = window else { + return surfaces.in_process(process); + }; + match surfaces.in_window(window)? { + Some(surface) => Ok(Some(surface)), + None => surfaces.in_process(process), + } +} + fn action_step(verified: bool) -> ActionStep { ActionStep::succeeded(CANCEL) .with_mechanism(StepMechanism::SemanticApi) diff --git a/crates/macos/src/system/escape_popup_tests.rs b/crates/macos/src/system/escape_popup_tests.rs index 3ea2dd5570..da98712e46 100644 --- a/crates/macos/src/system/escape_popup_tests.rs +++ b/crates/macos/src/system/escape_popup_tests.rs @@ -1,15 +1,17 @@ use std::cell::RefCell; -use agent_desktop_core::{AdapterError, DeliverySemantics, ProcessIdentity, WindowInfo}; +use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode, ProcessIdentity, WindowInfo}; use super::{TransientSurface, close_with}; struct FakeSurfaces { - surface: Option<&'static str>, + window_surface: Option<&'static str>, + window_error: Option, + process_surface: Option<&'static str>, cancel_supported: bool, closed: bool, looked_in: RefCell>, - cancelled: RefCell, + cancelled: RefCell>, } impl TransientSurface for FakeSurfaces { @@ -19,18 +21,21 @@ impl TransientSurface for FakeSurfaces { self.looked_in .borrow_mut() .push(format!("window:{}", window.id)); - Ok(self.surface) + match &self.window_error { + Some(error) => Err(error.clone()), + None => Ok(self.window_surface), + } } fn in_process(&self, process: &ProcessIdentity) -> Result, AdapterError> { self.looked_in .borrow_mut() .push(format!("process:{}", process.pid.get())); - Ok(self.surface) + Ok(self.process_surface) } - fn cancel(&self, _surface: &&'static str) -> Result { - *self.cancelled.borrow_mut() = true; + fn cancel(&self, surface: &&'static str) -> Result { + *self.cancelled.borrow_mut() = Some(*surface); Ok(self.cancel_supported) } @@ -40,12 +45,21 @@ impl TransientSurface for FakeSurfaces { } 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 { - surface, + window_surface, + window_error: None, + process_surface, cancel_supported: true, closed: true, looked_in: RefCell::new(Vec::new()), - cancelled: RefCell::new(false), + cancelled: RefCell::new(None), } } @@ -74,7 +88,7 @@ fn an_app_scoped_close_searches_the_process_and_verifies_the_surface_gone() { .expect("a closed surface"); assert_eq!(*surfaces.looked_in.borrow(), ["process:42"]); - assert!(*surfaces.cancelled.borrow()); + assert_eq!(*surfaces.cancelled.borrow(), Some("popover")); assert_eq!( result.disposition(), DeliverySemantics::delivered_verified() @@ -83,19 +97,51 @@ fn an_app_scoped_close_searches_the_process_and_verifies_the_surface_gone() { } #[test] -fn a_window_scoped_close_searches_only_that_window() { - let surfaces = surfaces(Some("menu")); - let window = window(); +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)) + let result = close_with(&surfaces, &process(), Some(&window())) .unwrap() .expect("a closed surface"); assert_eq!(*surfaces.looked_in.borrow(), ["window:W1"]); + assert_eq!(*surfaces.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.looked_in.borrow(), ["window:W1", "process:42"]); + assert_eq!(*surfaces.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.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.looked_in.borrow(), ["window:W1"]); + assert_eq!(*surfaces.cancelled.borrow(), None); } #[test] @@ -104,7 +150,7 @@ fn no_open_surface_leaves_the_refusal() { assert!(close_with(&surfaces, &process(), None).unwrap().is_none()); assert_eq!(*surfaces.looked_in.borrow(), ["process:42"]); - assert!(!*surfaces.cancelled.borrow()); + assert_eq!(*surfaces.cancelled.borrow(), None); } #[test] @@ -113,7 +159,7 @@ fn a_surface_that_does_not_take_the_cancel_leaves_the_refusal() { surfaces.cancel_supported = false; assert!(close_with(&surfaces, &process(), None).unwrap().is_none()); - assert!(*surfaces.cancelled.borrow()); + assert_eq!(*surfaces.cancelled.borrow(), Some("menu")); } #[test] From d0fe8975a18ff5bd18e620d2338dc517f40a191b Mon Sep 17 00:00:00 2001 From: Lahfir Date: Tue, 24 Nov 2026 22:06:19 -0800 Subject: [PATCH 18/27] fix(linux): skip window activation for headed actions on wayland A Wayland session lets no client activate a window, so the headed pre-focus made set-value and focus fail with ACTION_NOT_SUPPORTED while the headless semantic route worked. The adapter now declares no headed focus on Wayland and the action reaches the element through its own route. --- crates/linux/src/adapter.rs | 31 +++++++++++++++++++++++++++++++ crates/linux/src/adapter_tests.rs | 15 +++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/crates/linux/src/adapter.rs b/crates/linux/src/adapter.rs index 489fd4c574..f552dce76d 100644 --- a/crates/linux/src/adapter.rs +++ b/crates/linux/src/adapter.rs @@ -8,6 +8,7 @@ use agent_desktop_core::{ }; use crate::system::SharedBus; +use crate::system::display::display_server::{DisplayServer, session_server}; pub struct LinuxAdapter { bus: SharedBus, @@ -275,6 +276,24 @@ impl LinuxAdapter { } 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, @@ -312,6 +331,18 @@ impl ActionOps for LinuxAdapter { crate::actions::before_pointer(crate::actions::scroll_into_view(self.bus(), handle, lease)) } } +/// 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(), + } +} + impl InputOps for LinuxAdapter { fn physical_pointer_refusal(&self) -> Option { match crate::input::backend::backend() { diff --git a/crates/linux/src/adapter_tests.rs b/crates/linux/src/adapter_tests.rs index c05b6fd631..8c63a86343 100644 --- a/crates/linux/src/adapter_tests.rs +++ b/crates/linux/src/adapter_tests.rs @@ -178,3 +178,18 @@ fn the_lifecycle_overrides_are_wired_to_the_adapter() { .expect_err("no desktop here"); not_the_default(&error); } + +#[test] +fn a_headed_action_focuses_nothing_on_wayland_and_keeps_its_focus_on_x11() { + use agent_desktop_core::{Action, HeadedFocus}; + 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) + ); +} From 9fb60d77166341deb2278cfb1e57fbbdffb85820 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Tue, 24 Nov 2026 22:06:19 -0800 Subject: [PATCH 19/27] fix(linux): select a selectable tab by the verb it names A selectable tab advertised Select from its state but select looked only for a select verb or a Selection parent, so it refused a tab that click selects. The select verbs of a selectable tab now include its click verbs, so the advertised action and the route agree. --- .../linux/src/tree/capabilities/action_names.rs | 4 +++- .../src/tree/capabilities/action_names_tests.rs | 17 +++++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/linux/src/tree/capabilities/action_names.rs b/crates/linux/src/tree/capabilities/action_names.rs index 334b5790a2..7cb8198df3 100644 --- a/crates/linux/src/tree/capabilities/action_names.rs +++ b/crates/linux/src/tree/capabilities/action_names.rs @@ -3,7 +3,7 @@ use agent_desktop_core::{Action, LocatorField, actions::capability}; use super::capability_rules::{Facts, rule_tokens, scroll_tokens}; use crate::system::process::toolkit_id::ToolkitId; use crate::tree::RawNode; -use crate::tree::vocabulary::role_numbers::{LIST_ITEM, is_menu_item}; +use crate::tree::vocabulary::role_numbers::{LIST_ITEM, PAGE_TAB, is_menu_item}; use crate::tree::vocabulary::state_bits::{CHECKABLE, SELECTABLE}; pub(crate) fn selection_verbs( @@ -13,6 +13,8 @@ pub(crate) fn selection_verbs( ) -> &'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); +} From 044f0cb4aa18d9eb3efe72ed661e5f24345ed824 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Tue, 24 Nov 2026 22:25:10 -0800 Subject: [PATCH 20/27] fix: report a verified effect as success when the platform answer was unclear The effect witness upgraded an uncertain platform error to delivered_verified but left it an error, so ok:false carried delivery verified and effect observed. A strong witness change now turns the command into a verified success and keeps the platform report in details. --- crates/core/src/actions/witnessed_action.rs | 36 +++++++++++++------ .../src/actions/witnessed_action_tests.rs | 17 ++++++--- 2 files changed, 39 insertions(+), 14 deletions(-) diff --git a/crates/core/src/actions/witnessed_action.rs b/crates/core/src/actions/witnessed_action.rs index 3762361e67..5e910fe33c 100644 --- a/crates/core/src/actions/witnessed_action.rs +++ b/crates/core/src/actions/witnessed_action.rs @@ -2,8 +2,9 @@ //! 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, and the witness -//! never makes an error of its own. +//! 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}, @@ -42,6 +43,7 @@ pub(crate) fn execute_witnessed_action( lease: &InteractionLease, ) -> Result { let deadline = lease.deadline(); + let action_name = request.action.name(); let before = adapter.read_effect_witness(handle, deadline).ok(); let dispatch = adapter.execute_action(handle, request, lease); let Some(before) = before else { @@ -52,9 +54,10 @@ pub(crate) fn execute_witnessed_action( WitnessStep::Read => after_changes(adapter.read_effect_witness(handle, deadline), &before), }; match changes { - Some(changes) => dispatch - .map(|result| with_changes(result, &changes)) - .map_err(|error| error_with_changes(error, &changes)), + Some(changes) => match dispatch { + Ok(result) => Ok(with_changes(result, &changes)), + Err(error) => settle_unclear_answer(error, &changes, action_name), + }, None => dispatch.map(adapter_proof), } } @@ -97,12 +100,25 @@ fn with_changes(result: ActionResult, changes: &[WitnessChange]) -> ActionResult result } -/// An unclear answer with a strong change was delivered: the error stays, as -/// the platform reported it, but its disposition says what the witness saw. -fn error_with_changes(mut error: AdapterError, changes: &[WitnessChange]) -> AdapterError { +/// 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 { - error.disposition = DeliverySemantics::delivered_verified(); + 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() { @@ -111,7 +127,7 @@ fn error_with_changes(mut error: AdapterError, changes: &[WitnessChange]) -> Ada details.insert("witness_diff".into(), serde_json::json!(changes)); } } - error + Err(error) } #[cfg(test)] diff --git a/crates/core/src/actions/witnessed_action_tests.rs b/crates/core/src/actions/witnessed_action_tests.rs index f637b07a84..ef1ad4266c 100644 --- a/crates/core/src/actions/witnessed_action_tests.rs +++ b/crates/core/src/actions/witnessed_action_tests.rs @@ -126,15 +126,24 @@ fn a_weak_or_no_change_leaves_the_delivery_as_it_was() { } #[test] -fn an_unclear_answer_with_a_strong_change_is_delivered_and_stays_an_error() { +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 error = run(&adapter).unwrap_err(); + let result = run(&adapter).expect("an observed effect is a success"); - assert_eq!(error.disposition, DeliverySemantics::delivered_verified()); - assert_eq!(error.details.unwrap()["effect"], "observed"); + 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); } From 2793d25c88832e61c2dd16984dc0ad9c734eabe3 Mon Sep 17 00:00:00 2001 From: Lahfir Date: Tue, 24 Nov 2026 22:25:10 -0800 Subject: [PATCH 21/27] refactor(linux): move the headed focus rule out of the adapter file The wayland headed focus rule pushed adapter.rs past the 400 line cap. --- crates/linux/src/actions/headed_focus.rs | 19 ++++++++++++++++ .../linux/src/actions/headed_focus_tests.rs | 16 ++++++++++++++ crates/linux/src/actions/mod.rs | 1 + crates/linux/src/adapter.rs | 22 +++---------------- crates/linux/src/adapter_tests.rs | 15 ------------- 5 files changed, 39 insertions(+), 34 deletions(-) create mode 100644 crates/linux/src/actions/headed_focus.rs create mode 100644 crates/linux/src/actions/headed_focus_tests.rs 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 8700df6df1..16a66268e8 100644 --- a/crates/linux/src/actions/mod.rs +++ b/crates/linux/src/actions/mod.rs @@ -6,6 +6,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 f552dce76d..bceb8f0bb1 100644 --- a/crates/linux/src/adapter.rs +++ b/crates/linux/src/adapter.rs @@ -7,8 +7,9 @@ use agent_desktop_core::{ WindowInfo, }; +use crate::actions::headed_focus::headed_focus_on; use crate::system::SharedBus; -use crate::system::display::display_server::{DisplayServer, session_server}; +use crate::system::display::display_server::session_server; pub struct LinuxAdapter { bus: SharedBus, @@ -331,18 +332,6 @@ impl ActionOps for LinuxAdapter { crate::actions::before_pointer(crate::actions::scroll_into_view(self.bus(), handle, lease)) } } -/// 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(), - } -} - impl InputOps for LinuxAdapter { fn physical_pointer_refusal(&self) -> Option { match crate::input::backend::backend() { @@ -376,12 +365,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/adapter_tests.rs b/crates/linux/src/adapter_tests.rs index 8c63a86343..c05b6fd631 100644 --- a/crates/linux/src/adapter_tests.rs +++ b/crates/linux/src/adapter_tests.rs @@ -178,18 +178,3 @@ fn the_lifecycle_overrides_are_wired_to_the_adapter() { .expect_err("no desktop here"); not_the_default(&error); } - -#[test] -fn a_headed_action_focuses_nothing_on_wayland_and_keeps_its_focus_on_x11() { - use agent_desktop_core::{Action, HeadedFocus}; - 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) - ); -} From 2d130bd8ee5a256ec8bad61b2523b918bb78ecdb Mon Sep 17 00:00:00 2001 From: Lahfir Date: Tue, 24 Nov 2026 22:29:11 -0800 Subject: [PATCH 22/27] test: pin that a refusal that sent nothing stays an error under the effect witness --- .../core/src/actions/witnessed_action_tests.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/crates/core/src/actions/witnessed_action_tests.rs b/crates/core/src/actions/witnessed_action_tests.rs index ef1ad4266c..2e85857f34 100644 --- a/crates/core/src/actions/witnessed_action_tests.rs +++ b/crates/core/src/actions/witnessed_action_tests.rs @@ -224,3 +224,19 @@ fn a_delivery_without_proof_is_read_once_without_a_wait() { 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); + } +} From 0ad2ba05b54da081edc9df0efb50330d72db5d2f Mon Sep 17 00:00:00 2001 From: Lahfir Date: Wed, 25 Nov 2026 02:12:53 -0800 Subject: [PATCH 23/27] fix: read the effect witness after the lease is released and cap it at 500 ms --- crates/core/src/actions/post_action.rs | 54 +++++++++++-- crates/core/src/actions/witnessed_action.rs | 77 +++++++++++++++---- crates/core/src/commands/helpers.rs | 12 +-- crates/core/src/ref_action/mod.rs | 20 ++--- crates/core/src/ref_action/post_release.rs | 51 ++++++++++++ .../src/ref_action/ref_action_dispatched.rs | 30 ++------ .../core/src/ref_action/ref_action_landing.rs | 2 +- crates/core/src/ref_action/ref_action_wait.rs | 10 +-- .../ref_action/ref_action_wait_lease_tests.rs | 38 ++++----- .../ref_action_wait_release_tests.rs | 52 +++++++++++++ 10 files changed, 254 insertions(+), 92 deletions(-) create mode 100644 crates/core/src/ref_action/post_release.rs create mode 100644 crates/core/src/ref_action/ref_action_wait_release_tests.rs diff --git a/crates/core/src/actions/post_action.rs b/crates/core/src/actions/post_action.rs index adf2ce07b8..a2cfa7ca84 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::{ Action, ActionRequest, ActionResult, AdapterError, DeliverySemantics, ErrorCode, @@ -38,8 +39,27 @@ pub fn execute_verified_action( request: ActionRequest, lease: &InteractionLease, ) -> Result { + let deadline = lease.deadline(); + let (result, pending) = execute_verified_deferred(adapter, handle, request, lease)?; + Ok(match pending { + Some(pending) => pending.settle(adapter, handle, deadline, result), + None => result, + }) +} + +/// 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<(ActionResult, Option), AdapterError> { if !request.action.can_open_window() { - return run_verified_action(adapter, handle, request, lease, &DispatchMark::default()); + let (result, pending) = + run_verified_action(adapter, handle, request, lease, &DispatchMark::default()); + return result.map(|result| (result, pending)); } let policy = request.policy; let target = request.expected_process.as_ref().map_or_else( @@ -56,33 +76,51 @@ pub fn execute_verified_action( }, |mark| run_verified_action(adapter, handle, request, lease, mark), )?; + let (result, pending) = result; let mut result = result.map_err(|mut error| { front.note_in_error(&mut error); error })?; front.note_in(&mut result.details); - Ok(result) + Ok((result, 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::execute_witnessed_action( + return crate::actions::witnessed_action::dispatch_witnessed( adapter, handle, request, lease, ); } if !action.requires_state_readback() { mark.dispatched(); - return adapter - .execute_action(handle, request, lease) - .map_err(settle_disposition); + return ( + adapter + .execute_action(handle, request, lease) + .map_err(settle_disposition), + 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/witnessed_action.rs b/crates/core/src/actions/witnessed_action.rs index 12a8ad2ce3..cda44ea969 100644 --- a/crates/core/src/actions/witnessed_action.rs +++ b/crates/core/src/actions/witnessed_action.rs @@ -36,31 +36,80 @@ pub(crate) fn witness_step(dispatch: &Result) -> Wit } } -pub(crate) fn execute_witnessed_action( +/// 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, -) -> Result { +) -> Witnessed { let deadline = lease.deadline(); let action_name = request.action.name(); - let before = adapter.read_effect_witness(handle, deadline).ok(); + 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; - }; - let changes = match witness_step(&dispatch) { - WitnessStep::Leave => None, - WitnessStep::Read => after_changes(adapter.read_effect_witness(handle, deadline), &before), + return (dispatch, None); }; - match changes { - Some(changes) => match dispatch { - Ok(result) => Ok(with_changes(result, &changes)), - Err(error) => settle_unclear_answer(error, &changes, action_name), - }, - None => dispatch.map(adapter_proof), + 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, } } diff --git a/crates/core/src/commands/helpers.rs b/crates/core/src/commands/helpers.rs index 9f3b28592a..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.surfaces_of, - &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/ref_action/mod.rs b/crates/core/src/ref_action/mod.rs index a7f476c61c..39d08e0025 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; @@ -145,8 +146,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 = - crate::execute_verified_action(final_target.adapter, final_target.handle, request, lease); + let (dispatch_result, witness) = + 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,7 +170,10 @@ pub(crate) fn dispatch_resolved_landing( Ok(ref_action_dispatched::DispatchedAction { result, handle, - surfaces_of: raises_surface.then_some(expected_process), + after_release: post_release::PostRelease { + surfaces_of: raises_surface.then_some(expected_process), + witness, + }, }) } @@ -304,15 +308,13 @@ pub(crate) fn execute_resolved( let stability = actionability::StabilityExpectation::permissive(target.entry.geometry.bounds_hash); preflight_resolved(&target, &request, stability)?; - let result = dispatch_resolved_landing(target.target, request, lease).map(|mut dispatched| { - ref_action_dispatched::read_surfaces_after_release( + let result = dispatch_resolved_landing(target.target, request, lease).map(|dispatched| { + dispatched.after_release.settle( target.adapter, - dispatched.surfaces_of.take(), &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..4a698b2b1a --- /dev/null +++ b/crates/core/src/ref_action/post_release.rs @@ -0,0 +1,51 @@ +use crate::actions::witnessed_action::PendingWitness; +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, +} + +impl PostRelease { + pub(crate) fn settle( + self, + adapter: &dyn PlatformAdapter, + landed_on: &NativeHandle, + deadline: Deadline, + result: ActionResult, + ) -> ActionResult { + let mut result = match self.witness { + Some(witness) => witness.settle(adapter, landed_on, deadline, result), + None => result, + }; + if let Some(process) = self.surfaces_of { + result.surfaces = adapter + .surfaces_raised_by(process, landed_on, deadline) + .unwrap_or_default(); + } + 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) { + match crate::actions::post_action::execute_verified_deferred(adapter, handle, request, lease) { + Ok((result, witness)) => (Ok(result), witness), + Err(error) => (Err(error), None), + } +} diff --git a/crates/core/src/ref_action/ref_action_dispatched.rs b/crates/core/src/ref_action/ref_action_dispatched.rs index b4b5fc3724..aa1982798d 100644 --- a/crates/core/src/ref_action/ref_action_dispatched.rs +++ b/crates/core/src/ref_action/ref_action_dispatched.rs @@ -1,31 +1,11 @@ -use crate::{ActionResult, NativeHandle, PlatformAdapter, ProcessIdentity}; +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) surfaces_of: Option, -} - -/// 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, - surfaces_of: Option, - raised_by: &NativeHandle, - deadline: crate::Deadline, - result: &mut ActionResult, -) { - if let Some(process) = surfaces_of { - result.surfaces = adapter - .surfaces_raised_by(process, raised_by, deadline) - .unwrap_or_default(); - } + 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 4f8fe0a6f6..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) surfaces_of: Option, + 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 814a80331b..64327a5313 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.surfaces_of, &landing.handle, landing.deadline, - &mut result, + landing.result, ); crate::ref_action::finish_artifacts( RefActionContext::new(context, landing.deadline), @@ -91,7 +89,7 @@ fn execute_with_deadline( let ref_action_dispatched::DispatchedAction { mut result, handle, - surfaces_of, + after_release, } = dispatched; state.attach_transient_ambiguity(&mut result); state.attach_wait_metrics( @@ -106,7 +104,7 @@ fn execute_with_deadline( pre, deadline, lease_started, - surfaces_of, + after_release, }); } Err(error) => { 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 decf83ea85..a3fda53117 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 @@ -13,6 +13,7 @@ struct DoubleCheckAdapter { expected_deadline: Option, available_action: &'static str, surface_reads_under_lease: std::sync::Mutex>, + witness_reads: std::sync::Mutex>, } struct DoubleCheckLeaseGuard(Arc); @@ -83,6 +84,18 @@ impl ObservationOps for DoubleCheckAdapter { } crate::adapter::saved_ref_scope!("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, @@ -158,27 +171,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 { @@ -387,6 +379,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()), } } @@ -398,3 +391,6 @@ fn bounds() -> crate::Rect { height: 10.0, } } + +#[path = "ref_action_wait_release_tests.rs"] +mod release_tests; 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 new file mode 100644 index 0000000000..980d413339 --- /dev/null +++ b/crates/core/src/ref_action/ref_action_wait_release_tests.rs @@ -0,0 +1,52 @@ +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:?}"); +} From 3f934768ee916977686b7e9e7ac38d862cc0009c Mon Sep 17 00:00:00 2001 From: Lahfir Date: Wed, 25 Nov 2026 13:20:42 -0800 Subject: [PATCH 24/27] refactor: move the linux action capability impl into the actions layer The merge of the select route refusal pushed crates/linux/src/adapter.rs to 408 lines, over the 400-line cap. The ActionOps impl and its delivery helper now live in actions/adapter.rs. --- crates/linux/src/actions/adapter.rs | 103 ++++++++++++++++++++++++++ crates/linux/src/actions/mod.rs | 1 + crates/linux/src/adapter.rs | 108 ++-------------------------- 3 files changed, 109 insertions(+), 103 deletions(-) create mode 100644 crates/linux/src/actions/adapter.rs 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/mod.rs b/crates/linux/src/actions/mod.rs index 5a224f3398..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; diff --git a/crates/linux/src/adapter.rs b/crates/linux/src/adapter.rs index 46abc2b7cd..1a57e3ed3b 100644 --- a/crates/linux/src/adapter.rs +++ b/crates/linux/src/adapter.rs @@ -1,15 +1,12 @@ use agent_desktop_core::{ - AccessibilityNode, ActionOps, ActionRequest, ActionResult, 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, + 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::actions::headed_focus::headed_focus_on; use crate::system::SharedBus; -use crate::system::display::display_server::session_server; pub struct LinuxAdapter { bus: SharedBus, @@ -246,101 +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 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)) - } -} impl InputOps for LinuxAdapter { fn physical_pointer_refusal(&self) -> Option { match crate::input::backend::backend() { From 800343e45d09ae8f5edae4f6fddb8c8a30842d77 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:26:52 -0800 Subject: [PATCH 25/27] test: freeze clock in witnessed_action uncertain-without-wait test Asserting real-clock elapsed() < 40 ms flakes on loaded CI runners. Freeze the test clock and assert zero virtual time elapsed. --- crates/core/src/actions/witnessed_action_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/core/src/actions/witnessed_action_tests.rs b/crates/core/src/actions/witnessed_action_tests.rs index 2e85857f34..1044d4ad64 100644 --- a/crates/core/src/actions/witnessed_action_tests.rs +++ b/crates/core/src/actions/witnessed_action_tests.rs @@ -149,6 +149,7 @@ fn an_unclear_answer_with_a_strong_change_is_a_verified_success() { #[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")), @@ -157,13 +158,12 @@ fn an_unclear_answer_with_no_change_stays_uncertain_without_a_wait() { ], uncertain(), ); - let started = std::time::Instant::now(); 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!(started.elapsed() < std::time::Duration::from_millis(40)); + assert_eq!(clock.elapsed(), std::time::Duration::ZERO); } #[test] From 70f4a78eacd79d252b23ae37b9340055e2d57953 Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:20:49 -0800 Subject: [PATCH 26/27] docs: align delivery_uncertain effect-witness outcome with implementation A strong witness change after a delivery_uncertain error returns Ok with delivered_verified, data.effect observed, and details.platform_report; only non-strong verdicts keep the error and set error.details.effect. --- docs/json-output.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/json-output.md b/docs/json-output.md index 02f3523333..fc728e400b 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -193,7 +193,7 @@ 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 sets that error's disposition to `delivered_verified`, and `error.details.effect` carries the verdict. 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. +- 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. From e2862b9e62316dae0cf28bdd3aa1aa67ac8f808b Mon Sep 17 00:00:00 2001 From: Lahfir <70215676+lahfir@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:39:48 -0800 Subject: [PATCH 27/27] fix(core,linux,windows): require non-retryable StaleRef for TargetGone witness upgrade - Gate WitnessChange::TargetGone in witnessed_action::after_changes on a confirmed, non-retryable StaleRef so transient or unsettled read failures stay indeterminate and never upgrade delivery.\n- Preserve retryable errors in Linux effect_witness::gone instead of collapsing them into target-gone.\n- Stamp direct-handle target absence in Windows effect_witness as complete and non-retryable while keeping transient UIA errors unchanged. --- crates/core/src/actions/witnessed_action.rs | 19 ++++++++++-- .../src/actions/witnessed_action_tests.rs | 31 +++++++++++++++++++ crates/linux/src/tree/effect_witness.rs | 10 ++++++ crates/windows/src/tree/effect_witness.rs | 13 +++++--- 4 files changed, 67 insertions(+), 6 deletions(-) diff --git a/crates/core/src/actions/witnessed_action.rs b/crates/core/src/actions/witnessed_action.rs index cda44ea969..b4b6ed337b 100644 --- a/crates/core/src/actions/witnessed_action.rs +++ b/crates/core/src/actions/witnessed_action.rs @@ -114,18 +114,33 @@ pub(crate) fn execute_witnessed_action( } /// The changes since `before`, or none when the witness could not be read. -/// A target that is gone after the action was closed or replaced by it. +/// 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 error.code == ErrorCode::StaleRef => Some(vec![WitnessChange::TargetGone]), + 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) diff --git a/crates/core/src/actions/witnessed_action_tests.rs b/crates/core/src/actions/witnessed_action_tests.rs index 1044d4ad64..7bbeeecbf3 100644 --- a/crates/core/src/actions/witnessed_action_tests.rs +++ b/crates/core/src/actions/witnessed_action_tests.rs @@ -184,6 +184,37 @@ fn a_target_gone_after_the_action_is_a_strong_change() { ); } +#[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( diff --git a/crates/linux/src/tree/effect_witness.rs b/crates/linux/src/tree/effect_witness.rs index dbc5864c7d..30d2b001c3 100644 --- a/crates/linux/src/tree/effect_witness.rs +++ b/crates/linux/src/tree/effect_witness.rs @@ -99,6 +99,16 @@ pub(crate) fn content_sign(children: &[ChildAddress]) -> u64 { } 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") diff --git a/crates/windows/src/tree/effect_witness.rs b/crates/windows/src/tree/effect_witness.rs index 4e8c688610..367c46b870 100644 --- a/crates/windows/src/tree/effect_witness.rs +++ b/crates/windows/src/tree/effect_witness.rs @@ -113,10 +113,15 @@ mod imp { .ok_or_else(|| { AdapterError::internal("the effect witness cache request did not build") })?; - let updated = element - .0 - .build_updated_cache(&cache) - .map_err(|error| uia_error(&error, "read the effect witness target"))?; + 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),