Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
chore: stack the reviewed open PRs onto main (#234)
Lahfirb8d538c03887
diff --git a/CLAUDE.md b/CLAUDE.mdindex 1cb39f109..c037f970c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -334,8 +334,8 @@ The `error` object may also carry optional `details` and `recovery` objects. Ver## Ref System- Refs are allocated in depth-first document order and emitted as snapshot-qualified IDs such as `@s8f3k2p9:e1`. Legacy bare IDs such as `@e1` remain valid input only with an explicit `--snapshot s8f3k2p9`.-- An element receives a ref when it is **addressable for an action**: its role is interactive (`button`, `textfield`, `checkbox`, `link`, `menuitem`, `tab`, `slider`, `combobox`, `treeitem`, `cell`, `radiobutton`, `switch`, `colorwell`, `menubutton`, `incrementor`, `dockitem`), **or** it advertises an available action regardless of role. Container roles such as `scrollarea` (Scroll) and `disclosure` (Expand/Collapse/Click) are not interactive by role but are genuinely actionable, so they are ref-able — `scroll` / `expand` / `collapse` need a ref to target them-- A bare `SetFocus` affordance does not qualify on its own (focusability is not a primary action), so inert focusable containers stay ref-less+- An element receives a ref when it is **addressable for an action**: its role is interactive (`button`, `textfield`, `checkbox`, `link`, `menuitem`, `tab`, `slider`, `combobox`, `treeitem`, `cell`, `radiobutton`, `switch`, `colorwell`, `menubutton`, `incrementor`, `dockitem`), **or** it advertises a primary action regardless of role. Container roles such as `scrollarea` (Scroll) and `disclosure` (Expand/Collapse/Click) are not interactive by role but are genuinely actionable, so they are ref-able — `scroll` / `expand` / `collapse` need a ref to target them+- Ubiquitous affordances do not qualify on their own: `SetFocus` (focusability is not a primary action), `RightClick`, and `ScrollTo` (web runtimes such as Chromium/Electron advertise context menu and scroll-into-view on nearly every node). Inert containers and text advertising only these stay ref-less; `find` applies the same rule and returns `bounds` instead of a ref for such matches- Static text and non-actionable groups/containers do NOT get refs (they remain in tree for context)- Refs are deterministic within a snapshot but NOT stable across snapshots if UI changed- All persisted state lives under one state root, default `~/.agent-desktop`. `AGENT_DESKTOP_HOME` relocates it (the env value is the root itself, no suffix appended); resolution lives in `crates/core/src/state_root.rs` with precedence test override > env > default, and `status` reports the resolved root as `state_root`diff --git a/CONCEPTS.md b/CONCEPTS.mdindex 75441db02..b1c382527 100644--- a/CONCEPTS.md+++ b/CONCEPTS.md@@ -34,6 +34,8 @@ Completeness is reported on the observation as a whole and on each node whose de### RefA short element identifier assigned by agent-desktop to an actionable or drillable node in a snapshot.+A node is actionable when its role is interactive or it advertises a primary action. Focus, context-menu, and scroll-into-view affordances do not count on their own, because web runtimes advertise them on nearly every node.+Refs are deterministic inside one snapshot but are not stable across UI changes. Snapshot and find output qualify each ref with its snapshot ID. Legacy bare refs require the producing snapshot ID as a separate argument.### RefMapdiff --git a/crates/core/src/actionability/evaluate.rs b/crates/core/src/actionability/evaluate.rsindex 2a7878bb2..98a676ea8 100644--- a/crates/core/src/actionability/evaluate.rs+++ b/crates/core/src/actionability/evaluate.rs@@ -87,7 +87,10 @@ pub(super) fn check_with_stability(let mut verified_point = None;let presentation_point = evidence.bounds.and_then(center_point);if requirements.visible {- checks.push(gates::visibility(evidence));+ checks.push(gates::visibility(+ evidence,+ requirements.requires_geometry(request, &evidence.available_actions),+ ));}if requirements.requires_stability(pointer_delivery) {checks.push(gates::stability(stability, evidence.bounds));diff --git a/crates/core/src/actionability/gates.rs b/crates/core/src/actionability/gates.rsindex 2880d19e6..0e53cefdb 100644--- a/crates/core/src/actionability/gates.rs+++ b/crates/core/src/actionability/gates.rs@@ -5,7 +5,10 @@ use super::{};use crate::{ErrorCode, Rect, action::Action, action_request::ActionRequest, capability};-pub(super) fn visibility(evidence: &ActionabilityEvidence) -> ActionabilityCheck {+pub(super) fn visibility(+ evidence: &ActionabilityEvidence,+ requires_geometry: bool,+) -> ActionabilityCheck {match evidence.state.hidden {Some(true) => return fail("visible", "live hidden state is true"),None if !evidence.states_complete => {@@ -28,6 +31,9 @@ pub(super) fn visibility(evidence: &ActionabilityEvidence) -> ActionabilityCheckNone => {}Some(false) => {}}+ if !requires_geometry && evidence.state.offscreen.is_none() && evidence.bounds.is_some() {+ return pass("visible");+ }let Some(bounds) = evidence.bounds else {return unknown("visible", "bounds unavailable");};diff --git a/crates/core/src/actionability/requirements.rs b/crates/core/src/actionability/requirements.rsindex ef9a33ac3..2acc0c9a6 100644--- a/crates/core/src/actionability/requirements.rs+++ b/crates/core/src/actionability/requirements.rs@@ -55,6 +55,36 @@ impl ActionabilityRequirements {}}+ /// Whether visibility must be proven from pointer bounds. Strictly headless+ /// semantic delivery (AXPress/AXShowMenu, or an advertised editable-text+ /// capability) does not use a pointer, so closed-menu items and editors+ /// without usable bounds stay actionable. The visibility gate applies this+ /// only to targets that report bounds but no owning window (`offscreen`+ /// unknown), the shape macOS closed-menu items have: a zero-size control+ /// inside a known window, or a target with no bounds at all, still needs+ /// bounds. Explicit+ /// hidden/offscreen state still gates them; headed, focus-fallback, and+ /// physical paths keep the geometry requirement.+ pub(crate) fn requires_geometry(+ &self,+ request: &crate::ActionRequest,+ available_actions: &[String],+ ) -> bool {+ if request.policy != crate::InteractionPolicy::headless() {+ return true;+ }+ let direct_pointer = crate::capability::supports_direct_semantic_pointer_delivery(+ &request.action,+ available_actions,+ );+ let direct_text = self.editable+ && crate::capability::contains_any(+ available_actions,+ crate::capability::for_action(&request.action),+ );+ !(direct_pointer || direct_text)+ }+pub(crate) fn requires_stability(&self, pointer_delivery: PointerDelivery) -> bool {self.stable && !matches!(pointer_delivery, PointerDelivery::Semantic)}diff --git a/crates/core/src/actionability_live_tests.rs b/crates/core/src/actionability_live_tests.rsindex 08e581ab4..f5ef256cb 100644--- a/crates/core/src/actionability_live_tests.rs+++ b/crates/core/src/actionability_live_tests.rs@@ -383,5 +383,8 @@ fn live_actionability_rejects_unstable_identity_resolved_bounds_change() {assert!(err.message.contains("stable"));}+#[path = "actionability_semantic_geometry_tests.rs"]+mod semantic_geometry_tests;+#[path = "actionability_live_failure_tests.rs"]mod failure_tests;diff --git a/crates/core/src/actionability_semantic_geometry_tests.rs b/crates/core/src/actionability_semantic_geometry_tests.rsnew file mode 100644index 000000000..ee0109fa0--- /dev/null+++ b/crates/core/src/actionability_semantic_geometry_tests.rs@@ -0,0 +1,287 @@+use super::*;++struct GeometryAdapter(LiveElement);++impl ObservationOps for GeometryAdapter {+ fn get_live_element(+ &self,+ _handle: &NativeHandle,+ _deadline: crate::Deadline,+ ) -> Result<LiveElement, AdapterError> {+ Ok(self.0.clone())+ }++ fn hit_test(+ &self,+ _handle: &NativeHandle,+ _point: crate::Point,+ _deadline: crate::Deadline,+ ) -> Result<crate::hit_test::HitTestResult, AdapterError> {+ panic!("zero geometry must not reach hit testing")+ }+}++impl ActionOps for GeometryAdapter {}+impl InputOps for GeometryAdapter {}+impl SystemOps for GeometryAdapter {}++fn target(role: &str, actions: &[&str]) -> (RefEntry, GeometryAdapter) {+ let mut target = entry();+ target.identity.role = role.into();+ let bounds = Rect {+ x: 0.0,+ y: 0.0,+ width: 0.0,+ height: 0.0,+ };+ target.geometry.bounds = Some(bounds);+ target.geometry.bounds_hash = bounds.bounds_hash();+ let adapter = GeometryAdapter(LiveElement {+ identity: crate::adapter::live_identity("OK"),+ state: ElementState {+ role: role.into(),+ states: vec![],+ value: None,+ enabled: Some(true),+ hidden: Some(false),+ offscreen: None,+ },+ states_complete: true,+ bounds: Some(bounds),+ available_actions: actions.iter().map(|action| (*action).into()).collect(),+ });+ (target, adapter)+}++fn evaluate(+ target: &RefEntry,+ adapter: &GeometryAdapter,+ request: ActionRequest,+) -> Result<report::ActionabilityReport, AdapterError> {+ check_live(target, &NativeHandle::null(), adapter, &request)+}++#[test]+fn supported_headless_menu_click_accepts_zero_geometry() {+ let (target, adapter) = target("menuitem", &[capability::CLICK]);+ let report = evaluate(&target, &adapter, ActionRequest::headless(Action::Click)).unwrap();++ assert!(report.actionable);+ assert_eq!(report.pointer_delivery, PointerDelivery::Semantic);+ assert_eq!(report.verified_point, None);+ assert_eq!(report.presentation_point, None);+}++#[test]+fn supported_headless_editor_operations_accept_zero_geometry() {+ let (target, adapter) = target("textfield", &[capability::TYPE_TEXT, capability::SET_VALUE]);+ for action in [+ Action::TypeText("x".into()),+ Action::SetValue("x".into()),+ Action::Clear,+ ] {+ let report = evaluate(&target, &adapter, ActionRequest::headless(action)).unwrap();+ assert!(report.actionable);+ assert_eq!(report.verified_point, None);+ assert_eq!(report.presentation_point, None);+ }+}++#[test]+fn targets_without_bounds_still_need_geometry_headless() {+ for (role, action, capability) in [+ ("menuitem", Action::Click, capability::CLICK),+ ("menuitem", Action::RightClick, capability::RIGHT_CLICK),+ (+ "textfield",+ Action::TypeText("x".into()),+ capability::TYPE_TEXT,+ ),+ ] {+ let (target, mut adapter) = target(role, &[capability]);+ adapter.0.bounds = None;+ adapter.0.state.offscreen = None;+ assert!(+ evaluate(&target, &adapter, ActionRequest::headless(action)).is_err(),+ "without bounds the owning window cannot be ruled out, so {role} must not skip the check"+ );+ }+}++#[test]+fn headed_and_physical_actions_still_require_geometry() {+ let (target, adapter) = target(+ "textfield",+ &[+ capability::CLICK,+ capability::RIGHT_CLICK,+ capability::TYPE_TEXT,+ capability::SET_VALUE,+ ],+ );+ for action in [+ Action::Click,+ Action::RightClick,+ Action::DoubleClick,+ Action::TripleClick,+ Action::Hover,+ Action::TypeText("x".into()),+ Action::Clear,+ Action::SetValue("x".into()),+ Action::Drag(crate::DragParams {+ from: crate::Point { x: 0.0, y: 0.0 },+ to: crate::Point { x: 1.0, y: 1.0 },+ duration_ms: None,+ drop_delay_ms: None,+ }),+ ] {+ let err = evaluate(&target, &adapter, ActionRequest::headed(action)).unwrap_err();+ assert!(err.message.contains("visible (bounds are zero-sized)"));+ assert_eq!(err.disposition, crate::DeliverySemantics::not_delivered());+ }+ let err = evaluate(+ &target,+ &adapter,+ ActionRequest::focus_fallback(Action::TypeText("x".into())),+ )+ .unwrap_err();+ assert!(err.message.contains("visible"));+}++#[test]+fn semantic_geometry_exception_preserves_live_state_gates() {+ for action in [Action::Click, Action::TypeText("x".into())] {+ let (target, adapter) = target("textfield", &[capability::CLICK, capability::TYPE_TEXT]);+ for (state, reason) in [+ (+ ElementState {+ hidden: Some(true),+ ..adapter.0.state.clone()+ },+ "hidden",+ ),+ (+ ElementState {+ offscreen: Some(true),+ ..adapter.0.state.clone()+ },+ "offscreen",+ ),+ (+ ElementState {+ enabled: Some(false),+ ..adapter.0.state.clone()+ },+ "enabled",+ ),+ (+ ElementState {+ enabled: None,+ ..adapter.0.state.clone()+ },+ "enabled",+ ),+ (+ ElementState {+ hidden: None,+ ..adapter.0.state.clone()+ },+ "hidden",+ ),+ (+ ElementState {+ offscreen: None,+ ..adapter.0.state.clone()+ },+ "offscreen",+ ),+ ] {+ let mut live = adapter.0.clone();+ live.state = state;+ live.states_complete = false;+ let err = evaluate(+ &target,+ &GeometryAdapter(live),+ ActionRequest::headless(action.clone()),+ )+ .unwrap_err();+ assert!(err.message.contains(reason));+ assert_eq!(err.disposition, crate::DeliverySemantics::not_delivered());+ }+ for hidden in [true, false] {+ let mut live = adapter.0.clone();+ if hidden {+ live.state.hidden = None;+ live.state.states.push(crate::state::HIDDEN.into());+ } else {+ live.state.offscreen = None;+ live.state.states.push(crate::state::OFFSCREEN.into());+ }+ let err = evaluate(+ &target,+ &GeometryAdapter(live),+ ActionRequest::headless(action.clone()),+ )+ .unwrap_err();+ assert!(err.message.contains("canonical"));+ }+ }+}++#[test]+fn semantic_geometry_exception_requires_live_support_and_editability() {+ let (target, mut adapter) = target("button", &[capability::TYPE_TEXT]);+ let err = evaluate(+ &target,+ &adapter,+ ActionRequest::headless(Action::TypeText("x".into())),+ )+ .unwrap_err();+ assert!(err.message.contains("editable"));+ adapter.0.available_actions.clear();+ for action in [Action::Click, Action::TypeText("x".into())] {+ let err = evaluate(&target, &adapter, ActionRequest::headless(action)).unwrap_err();+ assert!(err.message.contains("supported_action"));+ assert_eq!(err.disposition, crate::DeliverySemantics::not_delivered());+ }+}++#[test]+fn zero_geometry_does_not_relax_live_identity() {+ let (target, adapter) = target("menuitem", &[capability::CLICK]);+ for role in ["unknown", "button"] {+ let mut live = adapter.0.clone();+ live.state.role = role.into();+ let err = evaluate(+ &target,+ &GeometryAdapter(live),+ ActionRequest::headless(Action::Click),+ )+ .unwrap_err();+ assert_eq!(err.code, ErrorCode::StaleRef);+ }+ let mut live = adapter.0.clone();+ live.identity = crate::adapter::live_identity("Different item");+ let err = evaluate(+ &target,+ &GeometryAdapter(live),+ ActionRequest::headless(Action::Click),+ )+ .unwrap_err();+ assert_eq!(err.code, ErrorCode::StaleRef);+}++#[test]+fn in_window_zero_geometry_still_requires_bounds_headless() {+ let (target, mut adapter) = target("button", &[capability::CLICK]);+ adapter.0.state.offscreen = Some(false);++ let error = evaluate(&target, &adapter, ActionRequest::headless(Action::Click))+ .expect_err("a zero-size control inside a known window is not a closed-menu item");++ assert!(+ error.message.contains("bounds are zero-sized"),+ "{}",+ error.message+ );+}diff --git a/crates/core/src/actionability_tests.rs b/crates/core/src/actionability_tests.rsindex c82b70d6a..5987e5bb1 100644--- a/crates/core/src/actionability_tests.rs+++ b/crates/core/src/actionability_tests.rs@@ -74,7 +74,7 @@ fn visibility_evidence(#[test]fn explicit_typed_hidden_state_wins() {- let check = gates::visibility(&visibility_evidence(Some(true), Vec::new(), true));+ let check = gates::visibility(&visibility_evidence(Some(true), Vec::new(), true), true);assert_eq!(check.status, ActionabilityStatus::Fail);assert_eq!(check.reason.as_deref(), Some("live hidden state is true"));@@ -82,11 +82,10 @@ fn explicit_typed_hidden_state_wins() {#[test]fn complete_canonical_hidden_state_fails_when_typed_state_is_absent() {- let check = gates::visibility(&visibility_evidence(- None,- vec![crate::state::HIDDEN.into()],+ let check = gates::visibility(+ &visibility_evidence(None, vec![crate::state::HIDDEN.into()], true),true,- ));+ );assert_eq!(check.status, ActionabilityStatus::Fail);assert_eq!(@@ -97,14 +96,14 @@ fn complete_canonical_hidden_state_fails_when_typed_state_is_absent() {#[test]fn complete_canonical_states_without_hidden_allow_visibility_checks_to_continue() {- let check = gates::visibility(&visibility_evidence(None, Vec::new(), true));+ let check = gates::visibility(&visibility_evidence(None, Vec::new(), true), true);assert_eq!(check.status, ActionabilityStatus::Pass);}#[test]fn incomplete_canonical_states_keep_missing_typed_hidden_unknown() {- let check = gates::visibility(&visibility_evidence(None, Vec::new(), false));+ let check = gates::visibility(&visibility_evidence(None, Vec::new(), false), true);assert_eq!(check.status, ActionabilityStatus::Unknown);assert_eq!(@@ -150,7 +149,7 @@ fn disabled_entry_fails_before_action_dispatch() {}#[test]-fn zero_sized_bounds_fail_visibility() {+fn zero_sized_bounds_fail_headed_visibility() {let mut entry = entry();let bounds = Rect {x: 1.0,@@ -161,7 +160,7 @@ fn zero_sized_bounds_fail_visibility() {entry.geometry.bounds = Some(bounds);entry.geometry.bounds_hash = bounds.bounds_hash();- let err = check(&entry, &ActionRequest::headless(Action::Click)).unwrap_err();+ let err = check(&entry, &ActionRequest::headed(Action::Click)).unwrap_err();assert!(err.message.contains("visible"));}diff --git a/crates/core/src/hints.rs b/crates/core/src/hints.rsindex 1154f9c90..5320fb068 100644--- a/crates/core/src/hints.rs+++ b/crates/core/src/hints.rs@@ -2,9 +2,12 @@ use crate::AccessibilityNode;pub fn add_structural_hints(node: &mut AccessibilityNode) {if node.role == "splitter" && node.children.len() > 1 {- let total = node.children.len();+ let total = (!node.subtree_truncated).then_some(node.children.len());for (i, child) in node.children.iter_mut().enumerate() {- child.presentation.hint = Some(format!("column {} of {}", i + 1, total));+ child.presentation.hint = Some(match total {+ Some(total) => format!("column {} of {}", i + 1, total),+ None => format!("column {}", i + 1),+ });}}@@ -12,3 +15,7 @@ pub fn add_structural_hints(node: &mut AccessibilityNode) {add_structural_hints(child);}}++#[cfg(test)]+#[path = "hints_tests.rs"]+mod tests;diff --git a/crates/core/src/hints_tests.rs b/crates/core/src/hints_tests.rsnew file mode 100644index 000000000..669d532bb--- /dev/null+++ b/crates/core/src/hints_tests.rs@@ -0,0 +1,52 @@+use super::*;++fn node(role: &str, children: Vec<AccessibilityNode>) -> AccessibilityNode {+ AccessibilityNode {+ ref_id: None,+ role: role.into(),+ identity: Default::default(),+ presentation: Default::default(),+ children_count: None,+ subtree_truncated: false,+ children,+ }+}++fn pane_hints(splitter: &AccessibilityNode) -> Vec<Option<&str>> {+ splitter+ .children+ .iter()+ .map(|child| child.presentation.hint.as_deref())+ .collect()+}++#[test]+fn complete_splitter_hints_carry_the_column_total() {+ let mut splitter = node(+ "splitter",+ vec![node("group", vec![]), node("group", vec![])],+ );++ add_structural_hints(&mut splitter);++ assert_eq!(+ pane_hints(&splitter),+ vec![Some("column 1 of 2"), Some("column 2 of 2")]+ );+}++#[test]+fn truncated_splitter_hints_omit_the_unverified_total() {+ let mut splitter = node(+ "splitter",+ vec![node("group", vec![]), node("group", vec![])],+ );+ splitter.subtree_truncated = true;++ add_structural_hints(&mut splitter);++ assert_eq!(+ pane_hints(&splitter),+ vec![Some("column 1"), Some("column 2")]+ );+}diff --git a/crates/core/src/live_locator/materialize_tests.rs b/crates/core/src/live_locator/materialize_tests.rsindex 5f0f37cf5..d69352531 100644--- a/crates/core/src/live_locator/materialize_tests.rs+++ b/crates/core/src/live_locator/materialize_tests.rs@@ -118,6 +118,41 @@ fn full_refmap_uses_same_arena_evidence_and_document_order() {assert_eq!(resolution.matches[0].data.path, ["window:Fixture"]);}+#[test]+fn web_node_with_only_ubiquitous_affordances_matches_without_a_ref() {+ let mut row = evidence("group", Some("Task row"));+ row.ref_evidence.available_actions = LocatorField::Known(vec![+ capability::RIGHT_CLICK.into(),+ capability::SCROLL_TO.into(),+ ]);+ let query = LocatorQuery {+ identity: IdentityPredicate {+ name: Some("Task row".into()),+ ..IdentityPredicate::default()+ },+ ..LocatorQuery::default()+ };++ let resolution = evaluate_locator_tree(+ tree(+ vec![+ node(0, evidence("window", Some("Fixture")), vec![1], &[]),+ node(1, row, vec![], &[0]),+ ],+ vec![0],+ true,+ ),+ &query,+ &request(),+ )+ .unwrap();++ assert!(resolution.meta.complete);+ assert_eq!(resolution.refmap.as_ref().map_or(0, |map| map.len()), 0);+ assert!(resolution.matches[0].data.ref_id.is_none());+ assert!(!resolution.matches[0].data.interactive);+}+#[test]fn selected_identifier_prefers_typed_preferred_duplicate() {let mut button = evidence("button", Some("Checkout"));diff --git a/crates/core/src/ref_action_exactly_once_tests.rs b/crates/core/src/ref_action_exactly_once_tests.rsindex 7df465926..90b232152 100644--- a/crates/core/src/ref_action_exactly_once_tests.rs+++ b/crates/core/src/ref_action_exactly_once_tests.rs@@ -84,6 +84,7 @@ impl ObservationOps for DispatchGuardAdapter {let live_bounds = match self.mode {"moving_once" => bounds_at(100.0),"moving_continuously" => bounds_at(f64::from(call + 1) * 10.0),+ "zero_geometry" => zero_bounds(),_ => bounds(),};Ok(LiveElement {@@ -94,7 +95,7 @@ impl ObservationOps for DispatchGuardAdapter {value: None,enabled: Some(true),hidden: Some(self.mode == "hidden_after_scroll"),- offscreen: Some(self.mode == "offscreen_slow"),+ offscreen: (self.mode != "zero_geometry").then_some(self.mode == "offscreen_slow"),},states_complete: true,bounds: Some(live_bounds),@@ -111,6 +112,7 @@ impl ObservationOps for DispatchGuardAdapter {let bounds = match self.mode {"moving_once" => bounds_at(100.0),"moving_continuously" => bounds_at(f64::from(observed + 1) * 10.0),+ "zero_geometry" => zero_bounds(),_ => bounds(),};Ok(Some(bounds))@@ -172,6 +174,15 @@ fn bounds() -> Rect {bounds_at(10.0)}+fn zero_bounds() -> Rect {+ Rect {+ x: 0.0,+ y: 0.0,+ width: 0.0,+ height: 0.0,+ }+}+fn bounds_at(x: f64) -> Rect {Rect {x,@@ -335,3 +346,10 @@ fn expired_preflight_never_scrolls_after_the_deadline() {assert_eq!(adapter.scroll_calls.load(Ordering::SeqCst), 0);assert_eq!(adapter.dispatch_calls.load(Ordering::SeqCst), 0);}+#[test]+fn zero_geometry_semantic_click_dispatches_without_scrolling_into_view() {+ let adapter = DispatchGuardAdapter::new("zero_geometry", 0);+ execute(&adapter, 500).unwrap();+ assert_eq!(adapter.scroll_calls.load(Ordering::SeqCst), 0);+ assert_eq!(adapter.dispatch_calls.load(Ordering::SeqCst), 1);+}diff --git a/crates/core/src/ref_alloc.rs b/crates/core/src/ref_alloc.rsindex a0804ea44..5266fb393 100644--- a/crates/core/src/ref_alloc.rs+++ b/crates/core/src/ref_alloc.rs@@ -56,16 +56,27 @@ pub(crate) fn ref_entry_from_node(}}+const UBIQUITOUS_AFFORDANCES: [&str; 3] = [+ crate::capability::SET_FOCUS,+ crate::capability::RIGHT_CLICK,+ crate::capability::SCROLL_TO,+];+/// An element receives a ref when it is addressable for an action: either its-/// role is interactive, or it advertises an available action regardless of-/// role. Container roles like `scrollarea` (Scroll) and `disclosure`-/// (Expand/Collapse) are not "interactive" by role but are genuinely-/// actionable, and `scroll` / `expand` / `collapse` need a ref to target-/// them — so action-bearing elements must be ref-able even when their current-/// bounds are zero-sized. Visibility remains a live actionability concern. A-/// bare `SetFocus` affordance does not qualify on its own: focusability is not-/// a primary action and would ref-allocate large numbers of inert containers.-pub(crate) fn is_ref_able(node: &AccessibilityNode) -> bool {+/// role is interactive, or it advertises an available action other than+/// `SetFocus`, `RightClick` or `ScrollTo`, regardless of role. Focusability is+/// not a primary action, and web runtimes (Chromium/Electron) advertise+/// context-menu and scroll-into-view on nearly every node, so counting them+/// would ref-allocate every inert container and text run and overflow the+/// refmap size limit on web apps. Container roles like+/// `scrollarea` (Scroll) and `disclosure` (Expand/Collapse) are not+/// "interactive" by role but are genuinely actionable, and `scroll` /+/// `expand` / `collapse` need a ref to target them — so action-bearing+/// elements must be ref-able even when their current bounds are zero-sized.+/// Visibility remains a live actionability concern. Snapshot allocation,+/// skeleton anchors, live-locator materialization, and visual-debug+/// classification all share this rule.+pub fn is_ref_able(node: &AccessibilityNode) -> bool {is_ref_able_role_actions(&node.role, &node.presentation.available_actions)}@@ -76,7 +87,7 @@ pub(crate) fn is_ref_able_role_actions(role: &str, available_actions: &[String])fn advertises_primary_action(available_actions: &[String]) -> bool {available_actions.iter()- .any(|action| action != crate::capability::SET_FOCUS)+ .any(|action| !UBIQUITOUS_AFFORDANCES.contains(&action.as_str()))}pub(crate) fn is_collapsible(node: &AccessibilityNode) -> bool {diff --git a/crates/core/src/ref_alloc_ordering_tests.rs b/crates/core/src/ref_alloc_ordering_tests.rsindex 3d2309b8d..d69fe8dcf 100644--- a/crates/core/src/ref_alloc_ordering_tests.rs+++ b/crates/core/src/ref_alloc_ordering_tests.rs@@ -213,3 +213,19 @@ fn allocation_config(include_bounds: bool) -> RefAllocConfig<'static> {},}}++#[test]+fn transform_tree_interactive_only_prunes_leaves_with_only_ubiquitous_affordances() {+ let mut noise = node("statictext", Some("row"));+ noise.presentation.available_actions = vec!["RightClick".into(), "ScrollTo".into()];+ let mut clickable = node("statictext", Some("link-like"));+ clickable.presentation.available_actions =+ vec!["Click".into(), "RightClick".into(), "ScrollTo".into()];+ let mut root = node("window", Some("w"));+ root.children = vec![noise, clickable];++ let out = transform_tree(root, true, true, false);++ assert_eq!(out.children.len(), 1);+ assert_eq!(out.children[0].identity.name.as_deref(), Some("link-like"));+}diff --git a/crates/core/src/ref_alloc_tests.rs b/crates/core/src/ref_alloc_tests.rsindex 803a36164..cb6eeb138 100644--- a/crates/core/src/ref_alloc_tests.rs+++ b/crates/core/src/ref_alloc_tests.rs@@ -208,18 +208,87 @@ fn actionable_container_roles_receive_refs() {assert!(is_ref_able(&disclosure));}-/// A bare SetFocus affordance is not a primary action; ref-allocating every-/// focusable container would bloat the refmap.+/// Focus, context-menu, and scroll-into-view affordances are advertised on+/// nearly every node by web runtimes (Chromium/Electron), so on their own they+/// must not ref-allocate inert containers or text.#[test]-fn focus_only_container_does_not_receive_a_ref() {- let mut group = node("group", Some("Panel"));- group.presentation.available_actions = vec!["SetFocus".into()];- assert!(!is_ref_able(&group));+fn ubiquitous_affordances_alone_do_not_confer_a_ref() {+ for actions in [+ vec!["SetFocus"],+ vec!["RightClick"],+ vec!["ScrollTo"],+ vec!["RightClick", "ScrollTo"],+ vec!["SetFocus", "RightClick", "ScrollTo"],+ ] {+ let mut group = node("group", Some("Panel"));+ group.presentation.available_actions = actions.iter().map(|a| a.to_string()).collect();+ assert!(+ !is_ref_able(&group),+ "group advertising only {actions:?} must not be ref-able"+ );+ }++ let mut paragraph = node("statictext", Some("Paragraph"));+ paragraph.presentation.available_actions = vec!["ScrollTo".into()];+ assert!(!is_ref_able(¶graph));let inert = node("statictext", Some("Label"));assert!(!is_ref_able(&inert));}+#[test]+fn primary_action_or_interactive_role_still_confers_a_ref_on_web_nodes() {+ let mut clickable = node("group", Some("Row"));+ clickable.presentation.available_actions =+ vec!["Click".into(), "RightClick".into(), "ScrollTo".into()];+ assert!(is_ref_able(&clickable));++ let mut button = node("button", Some("Menu"));+ button.presentation.available_actions = vec!["RightClick".into(), "ScrollTo".into()];+ assert!(is_ref_able(&button));+}++#[test]+fn allocate_refs_skips_web_container_noise() {+ let web_action = |role: &str, actions: &[&str]| {+ let mut n = node(role, Some(role));+ n.presentation.available_actions = actions.iter().map(|a| a.to_string()).collect();+ n+ };+ let mut wrapper = web_action("group", &["RightClick", "ScrollTo"]);+ wrapper.children = vec![web_action("statictext", &["ScrollTo"])];+ let mut root = node("window", Some("w"));+ root.children = vec![+ wrapper,+ web_action("group", &["Click", "RightClick", "ScrollTo"]),+ web_action("button", &["RightClick", "ScrollTo"]),+ ];++ let mut refmap = RefMap::new();+ let config = RefAllocConfig {+ options: crate::ref_alloc_options::RefAllocOptions {+ include_bounds: true,+ interactive_only: true,+ compact: false,+ },+ source: source(7),+ scope: crate::ref_alloc_scope::RefAllocScope {+ root_ref_id: None,+ path_prefix: &[],+ },+ };+ let out = allocate_refs(root, &mut refmap, &config).unwrap();++ assert_eq!(refmap.len(), 2);+ let roles: Vec<_> = out+ .children+ .iter()+ .map(|child| child.role.as_str())+ .collect();+ assert_eq!(roles, ["group", "button"]);+ assert!(out.children.iter().all(|child| child.ref_id.is_some()));+}+#[test]fn interactive_role_is_ref_able_even_without_actions() {let button = node("button", Some("OK"));diff --git a/crates/core/src/refs.rs b/crates/core/src/refs.rsindex 4d284f277..ad5008c68 100644--- a/crates/core/src/refs.rs+++ b/crates/core/src/refs.rs@@ -138,9 +138,11 @@ impl RefMap {self.validate()?;let json = serde_json::to_string(self)?;if json.len() as u64 > MAX_REFMAP_BYTES {- return Err(AppError::Internal(- "RefMap exceeds 1MB size limit on write".into(),- ));+ return Err(crate::AdapterError::internal("RefMap exceeds 1MB size limit on write")+ .with_suggestion(+ "Narrow the observation: snapshot with --skeleton, --max-depth, or --root @ref, or use find with a tighter query or --limit",+ )+ .into());}Ok(json)}@@ -308,3 +310,7 @@ mod tests;#[cfg(test)]#[path = "refs_serde_tests.rs"]mod serde_tests;++#[cfg(test)]+#[path = "refs_size_tests.rs"]+mod size_tests;diff --git a/crates/core/src/refs_size_tests.rs b/crates/core/src/refs_size_tests.rsnew file mode 100644index 000000000..f21b7ebb6--- /dev/null+++ b/crates/core/src/refs_size_tests.rs@@ -0,0 +1,35 @@+use super::tests::entry;+use super::*;++#[test]+fn test_serialize_with_size_check_rejects_oversized() {+ let mut map = RefMap::new();+ let big_name = "x".repeat(2048);+ for _ in 0..600 {+ map.allocate(entry("button", Some(&big_name)));+ }++ let err = map.serialize_with_size_check().unwrap_err();+ assert_eq!(err.code(), "INTERNAL");+ assert!(err.to_string().contains("1MB"), "got: {err}");+ let suggestion = err.suggestion().unwrap_or_default();+ assert!(suggestion.contains("--skeleton") && suggestion.contains("find"));++ let payload = crate::output::ErrorPayload::from_app_error(&err);+ assert_eq!(payload.code, "INTERNAL");+ assert!(payload.recovery.is_none());+ assert_eq!(payload.disposition, crate::DeliverySemantics::unknown());+}++#[test]+fn test_serialize_with_size_check_accepts_normal() {+ let mut map = RefMap::new();+ for _ in 0..50 {+ map.allocate(entry("button", Some("OK")));+ }++ let result = map.serialize_with_size_check();+ let value: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();+ assert_eq!(value["inner"]["@e1"]["role"], "button");+ assert_eq!(value["inner"]["@e1"]["name"], "OK");+}diff --git a/crates/core/src/refs_tests.rs b/crates/core/src/refs_tests.rsindex bccf7d974..9aaa031c8 100644--- a/crates/core/src/refs_tests.rs+++ b/crates/core/src/refs_tests.rs@@ -1,6 +1,6 @@use super::*;use crate::refs_test_support::HomeGuard;-fn entry(role: &str, name: Option<&str>) -> RefEntry {+pub(super) fn entry(role: &str, name: Option<&str>) -> RefEntry {RefEntry {process: crate::RefProcess {pid: crate::ProcessId::new(1),@@ -209,37 +209,6 @@ fn drill_replaces_full_snapshot_and_nested_descendants_only() {}}-#[test]-fn test_serialize_with_size_check_rejects_oversized() {- let mut map = RefMap::new();- let big_name = "x".repeat(2048);- for _ in 0..600 {- map.allocate(entry("button", Some(&big_name)));- }-- let result = map.serialize_with_size_check();- assert!(result.is_err(), "oversized refmap should be rejected");- let err = result.unwrap_err();- let msg = err.to_string();- assert!(- msg.contains("1MB"),- "error should mention the 1MB limit, got: {msg}"- );-}--#[test]-fn test_serialize_with_size_check_accepts_normal() {- let mut map = RefMap::new();- for _ in 0..50 {- map.allocate(entry("button", Some("OK")));- }-- let result = map.serialize_with_size_check();- let value: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();- assert_eq!(value["inner"]["@e1"]["role"], "button");- assert_eq!(value["inner"]["@e1"]["name"], "OK");-}-#[test]fn test_save_load_roundtrip_with_home_override() {let _guard = HomeGuard::new();diff --git a/crates/core/src/skeleton_anchor_tests.rs b/crates/core/src/skeleton_anchor_tests.rsindex f9af29394..b344a2a6b 100644--- a/crates/core/src/skeleton_anchor_tests.rs+++ b/crates/core/src/skeleton_anchor_tests.rs@@ -39,6 +39,24 @@ fn native_id_ancestor_covers_unnamed_boundaries() {);}+#[test]+fn web_boundary_with_only_ubiquitous_affordances_gets_anchor_ref() {+ let mut boundary = node("group");+ boundary.identity.name = Some("Task list".into());+ boundary.presentation.available_actions = vec!["RightClick".into(), "ScrollTo".into()];+ boundary.children_count = Some(40);+ let mut root = node("window");+ root.children = vec![boundary];++ let mut refmap = RefMap::new();+ let result = ref_alloc::allocate_refs(root, &mut refmap, &run_config(false, false)).unwrap();++ let boundary = &result.children[0];+ let entry = refmap.get(boundary.ref_id.as_deref().unwrap()).unwrap();+ assert!(entry.capabilities.available_actions.is_empty());+ assert_eq!(refmap.len(), 1);+}+#[test]fn unlabeled_bounded_boundary_gets_drill_ref() {let mut boundary = node("group");diff --git a/crates/macos/src/system/cg_window.rs b/crates/macos/src/system/cg_window.rsindex 54686da3a..4fcf0d369 100644--- a/crates/macos/src/system/cg_window.rs+++ b/crates/macos/src/system/cg_window.rs@@ -136,14 +136,20 @@ pub(super) fn records_from_dictionaries(if pid <= 0 {continue;}- let app_name = required_string_field(&dictionary, "kCGWindowOwnerName")?;- if app_name.is_empty() {- continue;- }let window_number = required_int_field(&dictionary, "kCGWindowNumber")?;if !scope.matches(pid, window_number) {continue;}+ if dictionary+ .find(CFString::new("kCGWindowOwnerName"))+ .is_none()+ {+ continue;+ }+ let app_name = required_string_field(&dictionary, "kCGWindowOwnerName")?;+ if app_name.is_empty() {+ continue;+ }let bounds = rect_field(&dictionary, "kCGWindowBounds").ok_or_else(|| missing_field_error("kCGWindowBounds"))?;records.push(WindowRecord {diff --git a/crates/macos/src/system/cg_window_tests.rs b/crates/macos/src/system/cg_window_tests.rsindex 99ab66d82..464c02e0d 100644--- a/crates/macos/src/system/cg_window_tests.rs+++ b/crates/macos/src/system/cg_window_tests.rs@@ -1,5 +1,61 @@use super::*;+#[test]+fn missing_optional_owner_name_does_not_block_scoped_windows() {+ use core_foundation::{base::TCFType, number::CFNumber};++ let unnamed = CFDictionary::from_CFType_pairs(&[+ (+ CFString::new("kCGWindowLayer"),+ CFNumber::from(0).as_CFType(),+ ),+ (+ CFString::new("kCGWindowOwnerPID"),+ CFNumber::from(418).as_CFType(),+ ),+ (+ CFString::new("kCGWindowNumber"),+ CFNumber::from(8).as_CFType(),+ ),+ ]);+ let bounds = CFDictionary::from_CFType_pairs(&[+ (CFString::new("X"), CFNumber::from(0).as_CFType()),+ (CFString::new("Y"), CFNumber::from(0).as_CFType()),+ (CFString::new("Width"), CFNumber::from(100).as_CFType()),+ (CFString::new("Height"), CFNumber::from(100).as_CFType()),+ ]);+ let named = CFDictionary::from_CFType_pairs(&[+ (+ CFString::new("kCGWindowLayer"),+ CFNumber::from(0).as_CFType(),+ ),+ (+ CFString::new("kCGWindowOwnerPID"),+ CFNumber::from(10).as_CFType(),+ ),+ (+ CFString::new("kCGWindowNumber"),+ CFNumber::from(7).as_CFType(),+ ),+ (+ CFString::new("kCGWindowOwnerName"),+ CFString::new("Target").as_CFType(),+ ),+ (CFString::new("kCGWindowBounds"), bounds.as_CFType()),+ ]);++ let records =+ records_from_dictionaries(vec![unnamed.clone(), named], WindowRecordScope::Pid(10))+ .unwrap();+ assert_eq!(records.len(), 1);+ assert_eq!(records[0].app_name, "Target");+ assert!(+ records_from_dictionaries(vec![unnamed], WindowRecordScope::Pid(418))+ .unwrap()+ .is_empty()+ );+}+#[test]fn expired_cg_window_deadline_is_rejected_before_native_reads() {let error = window_records_until(Instant::now(), WindowRecordScope::Pid(1)).unwrap_err();diff --git a/crates/macos/src/system/key_dispatch.rs b/crates/macos/src/system/key_dispatch.rsindex 066b9902e..fb36e07c5 100644--- a/crates/macos/src/system/key_dispatch.rs+++ b/crates/macos/src/system/key_dispatch.rs@@ -1,24 +1,18 @@use agent_desktop_core::{- ActionResult, AdapterError, Deadline, DeliverySemantics, ErrorCode, KeyCombo, Modifier,- ProcessIdentity,+ ActionResult, ActionStep, AdapterError, Deadline, DeliverySemantics, ErrorCode,+ InteractionPolicy, KeyCombo, ProcessIdentity, StepMechanism,};-use std::collections::VecDeque;use std::time::{Duration, Instant};use crate::tree::AXElement;-const MAX_MENU_NODES: usize = 2_048;-const MAX_MENU_CHILDREN: usize = 128;-const MAX_MENU_DEPTH: u8 = 8;-const AX_MENU_MODIFIER_SHIFT: u32 = 1 << 0;-const AX_MENU_MODIFIER_OPTION: u32 = 1 << 1;-const AX_MENU_MODIFIER_CONTROL: u32 = 1 << 2;-const AX_MENU_MODIFIER_NO_COMMAND: u32 = 1 << 3;+#[path = "key_dispatch_menu.rs"]+mod menu;pub(crate) fn press_for_app_impl(process: ProcessIdentity,combo: &KeyCombo,- policy: agent_desktop_core::InteractionPolicy,+ policy: InteractionPolicy,deadline: Deadline,) -> Result<ActionResult, AdapterError> {press_for_app(process, combo, policy, deadline)@@ -28,7 +22,7 @@ pub(crate) fn press_for_app_impl(fn press_for_app(process: ProcessIdentity,combo: &KeyCombo,- policy: agent_desktop_core::InteractionPolicy,+ policy: InteractionPolicy,deadline: Deadline,) -> Result<ActionResult, AdapterError> {tracing::debug!(@@ -40,18 +34,22 @@ fn press_for_app(let pid = identity.pid();let app = crate::tree::element_for_pid(pid);- if !combo.modifiers.is_empty() {- match try_menu_bar_shortcut(&app, combo, deadline) {- Ok(true) => return post_delivery_process_result(&process),+ if uses_menu_shortcut(combo, policy) {+ match menu::try_menu_bar_shortcut(&app, combo, deadline) {+ Ok(true) => {+ return post_delivery_process_result(&process, semantic_step("AXPress menu item"));+ }Ok(false) => {}- Err(error) if is_bounded_menu_incomplete(&error) => {+ Err(error) if menu::is_bounded_menu_incomplete(&error) => {tracing::debug!(details = ?error.details, "bounded menu lookup fell back to exact PID-targeted key delivery");}Err(error) => return Err(error),}}- if try_simple_key_action(&app, combo, deadline)? {- return post_delivery_process_result(&process);+ if let Some(action) = simple_key_action(combo)+ && try_simple_key_action(&app, action, deadline)?+ {+ return post_delivery_process_result(&process, semantic_step(action));}if policy.allow_focus_steal {@@ -62,29 +60,34 @@ fn press_for_app(require_focused_element(&app, deadline)?;crate::system::process_identity::require_core(&process)?;crate::input::keyboard::synthesize_key(combo, Some(pid), deadline)?;- post_delivery_process_result(&process)+ post_delivery_process_result(+ &process,+ ActionStep::succeeded("CGEventPostToPid")+ .with_mechanism(StepMechanism::PhysicalSynthetic)+ .with_verified(false),+ )}-fn post_delivery_process_result(process: &ProcessIdentity) -> Result<ActionResult, AdapterError> {+fn semantic_step(label: &'static str) -> ActionStep {+ ActionStep::succeeded(label)+ .with_mechanism(StepMechanism::SemanticApi)+ .with_verified(false)+}++fn post_delivery_process_result(+ process: &ProcessIdentity,+ step: ActionStep,+) -> Result<ActionResult, AdapterError> {crate::system::process_identity::require_core(process).map_err(|error| error.with_disposition(DeliverySemantics::delivered_unverified()))?;- Ok(ActionResult::delivered_unverified("press_key"))+ Ok(ActionResult::delivered_unverified("press_key").with_steps(vec![step]))}fn try_simple_key_action(app: &AXElement,- combo: &KeyCombo,+ action: &str,deadline: Deadline,) -> Result<bool, AdapterError> {- if !combo.modifiers.is_empty() {- return Ok(false);- }- let action = match combo.key.as_str() {- "return" | "enter" => "AXConfirm",- "escape" | "esc" => "AXCancel",- "space" => "AXPress",- _ => return Ok(false),- };let Some(focused) = focused_element(app, deadline)? else {return Ok(false);};@@ -94,47 +97,31 @@ fn try_simple_key_action(crate::actions::ax_helpers::try_ax_action_or_err(&focused, action, deadline)}-fn try_menu_bar_shortcut(- app: &AXElement,- combo: &KeyCombo,- deadline: Deadline,-) -> Result<bool, AdapterError> {- let Some(target_char) = single_uppercase_character(&combo.key) else {- return Ok(false);- };- let Some(menu_bar) = element_attribute(app, "AXMenuBar", deadline)? else {- return Ok(false);- };- let target_modifiers = combo_to_ax_modifiers(combo);- let mut queue = VecDeque::from([(menu_bar, 0_u8)]);- let mut visited = 0_usize;+fn uses_menu_shortcut(combo: &KeyCombo, policy: InteractionPolicy) -> bool {+ policy.allow_focus_steal && !combo.modifiers.is_empty()+}- while let Some((element, depth)) = queue.pop_front() {- ensure_budget(deadline)?;- visited += 1;- if visited > MAX_MENU_NODES {- return Err(incomplete_menu_error("node_limit"));- }- if read_string(&element, "AXMenuItemCmdChar", deadline)?- .is_some_and(|value| value.to_uppercase() == target_char)- && read_menu_item_modifiers(&element, deadline)? == Some(target_modifiers)- {- return crate::actions::ax_helpers::try_ax_action_or_err(&element, "AXPress", deadline);- }- if depth >= MAX_MENU_DEPTH {- if has_children(&element, deadline)? {- return Err(incomplete_menu_error("depth_limit"));- }- continue;- }- let children = children(&element, deadline)?;- queue.extend(- children- .into_iter()- .map(|child| (child, depth.saturating_add(1))),- );+fn simple_key_action(combo: &KeyCombo) -> Option<&'static str> {+ if !combo.modifiers.is_empty() {+ return None;+ }+ match combo.key.as_str() {+ "return" | "enter" => Some("AXConfirm"),+ "escape" | "esc" => Some("AXCancel"),+ _ => None,}- Ok(false)+}++fn no_focused_element_error() -> AdapterError {+ AdapterError::new(+ ErrorCode::ActionFailed,+ "Application has no verified focused element for keyboard delivery",+ )+ .with_details(serde_json::json!({ "physical_delivery_started": false }))+ .with_suggestion(+ "Retry with --headed so the app can take focus, or run the menu command without \+ keys: find the item with 'snapshot --app <app> --surface menubar' and click its ref.",+ )}fn require_focused_element(app: &AXElement, deadline: Deadline) -> Result<AXElement, AdapterError> {@@ -145,11 +132,7 @@ fn require_focused_element(app: &AXElement, deadline: Deadline) -> Result<AXElem}ensure_budget(deadline)?;if Instant::now() >= local_deadline {- return Err(AdapterError::new(- ErrorCode::ActionFailed,- "Application has no verified focused element for keyboard delivery",- )- .with_details(serde_json::json!({ "physical_delivery_started": false })));+ return Err(no_focused_element_error());}let pause = deadline.remaining_slice(Duration::from_millis(5))?;std::thread::sleep(pause.min(Duration::from_millis(5)));@@ -170,174 +153,6 @@ fn element_attribute(result.map_err(|error| read_error(attribute, error))}-fn children(element: &AXElement, deadline: Deadline) -> Result<Vec<AXElement>, AdapterError> {- let read = crate::tree::query::child_read::read_attribute_children(- element,- "AXChildren",- MAX_MENU_CHILDREN,- instant(deadline)?,- );- ensure_budget(deadline)?;- validate_menu_children(read)-}--fn has_children(element: &AXElement, deadline: Deadline) -> Result<bool, AdapterError> {- let read = crate::tree::query::child_read::read_attribute_children(- element,- "AXChildren",- 0,- instant(deadline)?,- );- ensure_budget(deadline)?;- validate_child_status(&read)?;- Ok(read.total_count > 0)-}--fn validate_menu_children(- read: crate::tree::query::child_read::ChildRead,-) -> Result<Vec<AXElement>, AdapterError> {- validate_child_status(&read)?;- if !read.complete || read.truncated() {- return Err(- incomplete_menu_error("child_limit").with_details(serde_json::json!({- "kind": "child_limit",- "complete": false,- "total_count": read.total_count,- "loaded_count": read.elements.len(),- })),- );- }- Ok(read.elements)-}--fn validate_child_status(- read: &crate::tree::query::child_read::ChildRead,-) -> Result<(), AdapterError> {- if read.status.api_disabled {- return Err(read_error(- "AXChildren",- accessibility_sys::kAXErrorAPIDisabled,- ));- }- if read.status.invalid_element {- return Err(read_error(- "AXChildren",- accessibility_sys::kAXErrorInvalidUIElement,- ));- }- if read.status.health.cannot_complete > 0 || read.status.health.deadline_exhausted > 0 {- return Err(read_error(- "AXChildren",- accessibility_sys::kAXErrorCannotComplete,- ));- }- Ok(())-}--fn read_string(- element: &AXElement,- attribute: &str,- deadline: Deadline,-) -> Result<Option<String>, AdapterError> {- let result = crate::tree::attributes::copy_string_attr_result(element, attribute, deadline);- ensure_budget(deadline)?;- result.map_err(|error| read_error(attribute, error))-}--fn read_menu_item_modifiers(- element: &AXElement,- deadline: Deadline,-) -> Result<Option<u32>, AdapterError> {- use accessibility_sys::kAXErrorSuccess;- use core_foundation::{base::TCFType, string::CFString};-- let attribute = CFString::new("AXMenuItemCmdModifiers");- let (error, value) = crate::tree::ax_ipc::copy_attribute_value(- element,- attribute.as_concrete_TypeRef(),- deadline,- );- ensure_budget(deadline)?;- if error != kAXErrorSuccess {- return if error == accessibility_sys::kAXErrorNoValue- || error == accessibility_sys::kAXErrorAttributeUnsupported- {- Ok(None)- } else {- Err(read_error("AXMenuItemCmdModifiers", error))- };- }- if value.is_null() {- return Err(malformed_menu_modifiers());- }- let value = unsafe { core_foundation::base::CFType::wrap_under_create_rule(value) };- let number = crate::cf_type::borrowed_cf_number(value.as_concrete_TypeRef())- .and_then(|number| number.to_i64())- .ok_or_else(malformed_menu_modifiers)?;- normalize_menu_modifiers(number).map(Some)-}--fn single_uppercase_character(key: &str) -> Option<String> {- (key.chars().count() == 1).then(|| key.to_uppercase())-}--fn combo_to_ax_modifiers(combo: &KeyCombo) -> u32 {- let mut encoded = if combo.modifiers.contains(&Modifier::Meta) {- 0- } else {- AX_MENU_MODIFIER_NO_COMMAND- };- encoded |= combo.modifiers.iter().fold(0, |modifiers, modifier| {- modifiers- | match modifier {- Modifier::Shift => AX_MENU_MODIFIER_SHIFT,- Modifier::Alt => AX_MENU_MODIFIER_OPTION,- Modifier::Ctrl => AX_MENU_MODIFIER_CONTROL,- Modifier::Meta => 0,- }- });- encoded-}--fn normalize_menu_modifiers(number: i64) -> Result<u32, AdapterError> {- let value = u32::try_from(number).map_err(|_| malformed_menu_modifiers())?;- let supported = AX_MENU_MODIFIER_SHIFT- | AX_MENU_MODIFIER_OPTION- | AX_MENU_MODIFIER_CONTROL- | AX_MENU_MODIFIER_NO_COMMAND;- if value & !supported != 0 {- return Err(malformed_menu_modifiers());- }- Ok(value)-}--fn malformed_menu_modifiers() -> AdapterError {- AdapterError::new(- ErrorCode::AppUnresponsive,- "AXMenuItemCmdModifiers had an invalid value",- )- .with_details(serde_json::json!({- "kind": "menu_modifier_value_invalid",- "complete": false,- }))-}--fn instant(deadline: Deadline) -> Result<Instant, AdapterError> {- Instant::now()- .checked_add(deadline.remaining())- .ok_or_else(|| AdapterError::new(ErrorCode::InvalidArgs, "Deadline is out of range"))-}--fn is_bounded_menu_incomplete(error: &AdapterError) -> bool {- error.code == ErrorCode::AppUnresponsive- && error- .details- .as_ref()- .and_then(|details| details.get("kind"))- .and_then(serde_json::Value::as_str)- .is_some_and(|kind| matches!(kind, "node_limit" | "child_limit" | "depth_limit"))-}-fn ensure_budget(deadline: Deadline) -> Result<(), AdapterError> {if deadline.is_expired() {Err(deadline.timeout_error())@@ -369,19 +184,11 @@ fn read_error(attribute: &str, error: i32) -> AdapterError {.with_details(serde_json::json!({ "attribute": attribute, "ax_error": error }))}-fn incomplete_menu_error(kind: &str) -> AdapterError {- AdapterError::new(- ErrorCode::AppUnresponsive,- "Menu shortcut lookup exceeded its bounded accessibility search",- )- .with_details(serde_json::json!({ "kind": kind, "complete": false }))-}-#[cfg(not(target_os = "macos"))]pub(crate) fn press_for_app_impl(_process: ProcessIdentity,_combo: &KeyCombo,- _policy: agent_desktop_core::InteractionPolicy,+ _policy: InteractionPolicy,_deadline: Deadline,) -> Result<ActionResult, AdapterError> {Err(AdapterError::not_supported("press_for_app"))diff --git a/crates/macos/src/system/key_dispatch_menu.rs b/crates/macos/src/system/key_dispatch_menu.rsnew file mode 100644index 000000000..820572bea--- /dev/null+++ b/crates/macos/src/system/key_dispatch_menu.rs@@ -0,0 +1,237 @@+use agent_desktop_core::{AdapterError, Deadline, ErrorCode, KeyCombo, Modifier};+use std::collections::VecDeque;+use std::time::Instant;++use super::{element_attribute, ensure_budget, read_error};+use crate::tree::AXElement;++const MAX_MENU_NODES: usize = 2_048;+const MAX_MENU_CHILDREN: usize = 128;+const MAX_MENU_DEPTH: u8 = 8;+const AX_MENU_MODIFIER_SHIFT: u32 = 1 << 0;+const AX_MENU_MODIFIER_OPTION: u32 = 1 << 1;+const AX_MENU_MODIFIER_CONTROL: u32 = 1 << 2;+const AX_MENU_MODIFIER_NO_COMMAND: u32 = 1 << 3;++pub(super) fn try_menu_bar_shortcut(+ app: &AXElement,+ combo: &KeyCombo,+ deadline: Deadline,+) -> Result<bool, AdapterError> {+ let Some(target_char) = single_uppercase_character(&combo.key) else {+ return Ok(false);+ };+ let Some(menu_bar) = element_attribute(app, "AXMenuBar", deadline)? else {+ return Ok(false);+ };+ let target_modifiers = combo_to_ax_modifiers(combo);+ let mut queue = VecDeque::from([(menu_bar, 0_u8)]);+ let mut visited = 0_usize;++ while let Some((element, depth)) = queue.pop_front() {+ ensure_budget(deadline)?;+ visited += 1;+ if visited > MAX_MENU_NODES {+ return Err(incomplete_menu_error("node_limit"));+ }+ if read_string(&element, "AXMenuItemCmdChar", deadline)?+ .is_some_and(|value| value.to_uppercase() == target_char)+ && read_menu_item_modifiers(&element, deadline)? == Some(target_modifiers)+ {+ return crate::actions::ax_helpers::try_ax_action_or_err(&element, "AXPress", deadline);+ }+ if depth >= MAX_MENU_DEPTH {+ if has_children(&element, deadline)? {+ return Err(incomplete_menu_error("depth_limit"));+ }+ continue;+ }+ let children = children(&element, deadline)?;+ queue.extend(+ children+ .into_iter()+ .map(|child| (child, depth.saturating_add(1))),+ );+ }+ Ok(false)+}++fn children(element: &AXElement, deadline: Deadline) -> Result<Vec<AXElement>, AdapterError> {+ let read = crate::tree::query::child_read::read_attribute_children(+ element,+ "AXChildren",+ MAX_MENU_CHILDREN,+ instant(deadline)?,+ );+ ensure_budget(deadline)?;+ validate_menu_children(read)+}++fn has_children(element: &AXElement, deadline: Deadline) -> Result<bool, AdapterError> {+ let read = crate::tree::query::child_read::read_attribute_children(+ element,+ "AXChildren",+ 0,+ instant(deadline)?,+ );+ ensure_budget(deadline)?;+ validate_child_status(&read)?;+ Ok(read.total_count > 0)+}++fn validate_menu_children(+ read: crate::tree::query::child_read::ChildRead,+) -> Result<Vec<AXElement>, AdapterError> {+ validate_child_status(&read)?;+ if !read.complete || read.truncated() {+ return Err(+ incomplete_menu_error("child_limit").with_details(serde_json::json!({+ "kind": "child_limit",+ "complete": false,+ "total_count": read.total_count,+ "loaded_count": read.elements.len(),+ })),+ );+ }+ Ok(read.elements)+}++fn validate_child_status(+ read: &crate::tree::query::child_read::ChildRead,+) -> Result<(), AdapterError> {+ if read.status.api_disabled {+ return Err(read_error(+ "AXChildren",+ accessibility_sys::kAXErrorAPIDisabled,+ ));+ }+ if read.status.invalid_element {+ return Err(read_error(+ "AXChildren",+ accessibility_sys::kAXErrorInvalidUIElement,+ ));+ }+ if read.status.health.cannot_complete > 0 || read.status.health.deadline_exhausted > 0 {+ return Err(read_error(+ "AXChildren",+ accessibility_sys::kAXErrorCannotComplete,+ ));+ }+ Ok(())+}++fn read_string(+ element: &AXElement,+ attribute: &str,+ deadline: Deadline,+) -> Result<Option<String>, AdapterError> {+ let result = crate::tree::attributes::copy_string_attr_result(element, attribute, deadline);+ ensure_budget(deadline)?;+ result.map_err(|error| read_error(attribute, error))+}++fn read_menu_item_modifiers(+ element: &AXElement,+ deadline: Deadline,+) -> Result<Option<u32>, AdapterError> {+ use accessibility_sys::kAXErrorSuccess;+ use core_foundation::{base::TCFType, string::CFString};++ let attribute = CFString::new("AXMenuItemCmdModifiers");+ let (error, value) = crate::tree::ax_ipc::copy_attribute_value(+ element,+ attribute.as_concrete_TypeRef(),+ deadline,+ );+ ensure_budget(deadline)?;+ if error != kAXErrorSuccess {+ return if error == accessibility_sys::kAXErrorNoValue+ || error == accessibility_sys::kAXErrorAttributeUnsupported+ {+ Ok(None)+ } else {+ Err(read_error("AXMenuItemCmdModifiers", error))+ };+ }+ if value.is_null() {+ return Err(malformed_menu_modifiers());+ }+ let value = unsafe { core_foundation::base::CFType::wrap_under_create_rule(value) };+ let number = crate::cf_type::borrowed_cf_number(value.as_concrete_TypeRef())+ .and_then(|number| number.to_i64())+ .ok_or_else(malformed_menu_modifiers)?;+ normalize_menu_modifiers(number).map(Some)+}++fn single_uppercase_character(key: &str) -> Option<String> {+ (key.chars().count() == 1).then(|| key.to_uppercase())+}++fn combo_to_ax_modifiers(combo: &KeyCombo) -> u32 {+ let mut encoded = if combo.modifiers.contains(&Modifier::Meta) {+ 0+ } else {+ AX_MENU_MODIFIER_NO_COMMAND+ };+ encoded |= combo.modifiers.iter().fold(0, |modifiers, modifier| {+ modifiers+ | match modifier {+ Modifier::Shift => AX_MENU_MODIFIER_SHIFT,+ Modifier::Alt => AX_MENU_MODIFIER_OPTION,+ Modifier::Ctrl => AX_MENU_MODIFIER_CONTROL,+ Modifier::Meta => 0,+ }+ });+ encoded+}++fn normalize_menu_modifiers(number: i64) -> Result<u32, AdapterError> {+ let value = u32::try_from(number).map_err(|_| malformed_menu_modifiers())?;+ let supported = AX_MENU_MODIFIER_SHIFT+ | AX_MENU_MODIFIER_OPTION+ | AX_MENU_MODIFIER_CONTROL+ | AX_MENU_MODIFIER_NO_COMMAND;+ if value & !supported != 0 {+ return Err(malformed_menu_modifiers());+ }+ Ok(value)+}++fn malformed_menu_modifiers() -> AdapterError {+ AdapterError::new(+ ErrorCode::AppUnresponsive,+ "AXMenuItemCmdModifiers had an invalid value",+ )+ .with_details(serde_json::json!({+ "kind": "menu_modifier_value_invalid",+ "complete": false,+ }))+}++fn instant(deadline: Deadline) -> Result<Instant, AdapterError> {+ Instant::now()+ .checked_add(deadline.remaining())+ .ok_or_else(|| AdapterError::new(ErrorCode::InvalidArgs, "Deadline is out of range"))+}++pub(super) fn is_bounded_menu_incomplete(error: &AdapterError) -> bool {+ error.code == ErrorCode::AppUnresponsive+ && error+ .details+ .as_ref()+ .and_then(|details| details.get("kind"))+ .and_then(serde_json::Value::as_str)+ .is_some_and(|kind| matches!(kind, "node_limit" | "child_limit" | "depth_limit"))+}++fn incomplete_menu_error(kind: &str) -> AdapterError {+ AdapterError::new(+ ErrorCode::AppUnresponsive,+ "Menu shortcut lookup exceeded its bounded accessibility search",+ )+ .with_details(serde_json::json!({ "kind": kind, "complete": false }))+}++#[cfg(test)]+#[path = "key_dispatch_menu_tests.rs"]+mod tests;diff --git a/crates/macos/src/system/key_dispatch_menu_tests.rs b/crates/macos/src/system/key_dispatch_menu_tests.rsnew file mode 100644index 000000000..5d9656f6b--- /dev/null+++ b/crates/macos/src/system/key_dispatch_menu_tests.rs@@ -0,0 +1,40 @@+use super::*;++fn combo(modifiers: Vec<Modifier>) -> KeyCombo {+ KeyCombo {+ key: "a".into(),+ modifiers,+ }+}++#[test]+fn menu_shortcut_requires_one_character() {+ assert_eq!(single_uppercase_character("a").as_deref(), Some("A"));+ assert!(single_uppercase_character("enter").is_none());+}++#[test]+fn menu_modifier_encoding_distinguishes_command_from_no_command() {+ assert_eq!(+ combo_to_ax_modifiers(&combo(vec![Modifier::Meta, Modifier::Alt])),+ AX_MENU_MODIFIER_OPTION+ );+ assert_eq!(+ combo_to_ax_modifiers(&combo(vec![Modifier::Alt])),+ AX_MENU_MODIFIER_OPTION | AX_MENU_MODIFIER_NO_COMMAND+ );+ assert_ne!(+ combo_to_ax_modifiers(&combo(vec![Modifier::Meta, Modifier::Alt])),+ combo_to_ax_modifiers(&combo(vec![Modifier::Alt]))+ );+}++#[test]+fn malformed_menu_modifier_values_are_not_command_shortcuts() {+ assert!(normalize_menu_modifiers(-1).is_err());+ assert!(normalize_menu_modifiers(1 << 8).is_err());+ assert_eq!(+ normalize_menu_modifiers(AX_MENU_MODIFIER_NO_COMMAND as i64).unwrap(),+ AX_MENU_MODIFIER_NO_COMMAND+ );+}diff --git a/crates/macos/src/system/key_dispatch_tests.rs b/crates/macos/src/system/key_dispatch_tests.rsindex 4bffa007c..b55fa23b6 100644--- a/crates/macos/src/system/key_dispatch_tests.rs+++ b/crates/macos/src/system/key_dispatch_tests.rs@@ -1,4 +1,5 @@use super::*;+use agent_desktop_core::Modifier;#[test]fn process_preflight_failure_reports_no_key_delivery() {@@ -25,12 +26,6 @@ fn key_dispatch_rejects_non_unique_display_names() {assert_eq!(error.code, ErrorCode::AmbiguousTarget);}-#[test]-fn menu_shortcut_requires_one_character() {- assert_eq!(single_uppercase_character("a").as_deref(), Some("A"));- assert!(single_uppercase_character("enter").is_none());-}-fn combo(modifiers: Vec<Modifier>) -> KeyCombo {KeyCombo {key: "a".into(),@@ -38,28 +33,66 @@ fn combo(modifiers: Vec<Modifier>) -> KeyCombo {}}+fn key(name: &str, modifiers: Vec<Modifier>) -> KeyCombo {+ KeyCombo {+ key: name.into(),+ modifiers,+ }+}++#[test]+fn printable_keys_are_never_translated_into_ax_actions() {+ for name in ["space", "a", "1", "tab", "delete"] {+ assert_eq!(simple_key_action(&key(name, Vec::new())), None, "{name}");+ }+}+#[test]-fn menu_modifier_encoding_distinguishes_command_from_no_command() {+fn return_and_escape_map_to_default_and_cancel_actions() {assert_eq!(- combo_to_ax_modifiers(&combo(vec![Modifier::Meta, Modifier::Alt])),- AX_MENU_MODIFIER_OPTION+ simple_key_action(&key("return", Vec::new())),+ Some("AXConfirm"));assert_eq!(- combo_to_ax_modifiers(&combo(vec![Modifier::Alt])),- AX_MENU_MODIFIER_OPTION | AX_MENU_MODIFIER_NO_COMMAND+ simple_key_action(&key("enter", Vec::new())),+ Some("AXConfirm"));- assert_ne!(- combo_to_ax_modifiers(&combo(vec![Modifier::Meta, Modifier::Alt])),- combo_to_ax_modifiers(&combo(vec![Modifier::Alt]))+ assert_eq!(+ simple_key_action(&key("escape", Vec::new())),+ Some("AXCancel")+ );+ assert_eq!(+ simple_key_action(&key("return", vec![Modifier::Meta])),+ None);}#[test]-fn malformed_menu_modifier_values_are_not_command_shortcuts() {- assert!(normalize_menu_modifiers(-1).is_err());- assert!(normalize_menu_modifiers(1 << 8).is_err());- assert_eq!(- normalize_menu_modifiers(AX_MENU_MODIFIER_NO_COMMAND as i64).unwrap(),- AX_MENU_MODIFIER_NO_COMMAND- );+fn headless_press_never_performs_menu_shortcuts() {+ let headless = agent_desktop_core::InteractionPolicy::headless();+ assert!(!uses_menu_shortcut(+ &key("n", vec![Modifier::Meta]),+ headless+ ));+ assert!(!uses_menu_shortcut(+ &key("n", vec![Modifier::Meta, Modifier::Shift]),+ headless+ ));+}++#[test]+fn focus_authorized_press_keeps_menu_shortcuts_for_modified_keys() {+ let headed = agent_desktop_core::InteractionPolicy::headed();+ assert!(uses_menu_shortcut(&key("n", vec![Modifier::Meta]), headed));+ assert!(!uses_menu_shortcut(&key("n", Vec::new()), headed));+}++#[test]+fn a_missing_focused_element_names_both_recovery_routes() {+ let error = super::no_focused_element_error();+ let suggestion = error+ .suggestion+ .expect("the error carries a recovery suggestion");+ assert!(suggestion.contains("--headed"), "{suggestion}");+ assert!(suggestion.contains("--surface menubar"), "{suggestion}");}diff --git a/crates/macos/src/system/renderer_activation.rs b/crates/macos/src/system/renderer_activation.rsindex c34f7b111..6f4f82dda 100644--- a/crates/macos/src/system/renderer_activation.rs+++ b/crates/macos/src/system/renderer_activation.rs@@ -90,7 +90,7 @@ fn activation_delivered("AXUIElementSetAttributeValue",error,)?;- if delivered && readback == Some(false) {+ if delivered && readback == Some(false) && attribute == renderer_probe::ENHANCED {return Err(AdapterError::new(ErrorCode::ActionFailed,"Renderer accessibility activation was not reflected in the attribute value",@@ -164,6 +164,20 @@ mod tests {assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());}+ #[test]+ fn accepted_manual_write_with_disabled_readback_is_not_an_error() {+ let application = crate::tree::AXElement(std::ptr::null_mut());+ assert!(+ activation_delivered(+ &application,+ renderer_probe::MANUAL,+ accessibility_sys::kAXErrorSuccess,+ Some(false),+ )+ .unwrap()+ );+ }+#[test]fn missing_readback_keeps_legacy_success_and_preserves_real_failures() {let application = crate::tree::AXElement(std::ptr::null_mut());diff --git a/crates/macos/src/tree/renderer_probe.rs b/crates/macos/src/tree/renderer_probe.rsindex b09ec3ba5..af2908aa3 100644--- a/crates/macos/src/tree/renderer_probe.rs+++ b/crates/macos/src/tree/renderer_probe.rs@@ -33,8 +33,8 @@ fn activation_needed(let Some(attribute) = choose_attribute(supported)? else {return Ok(false);};- if !web_surface && attribute == MANUAL {- return Ok(absence_proven);+ if attribute == MANUAL {+ return Ok(!web_surface && absence_proven);}let enabled = enabled(attribute)?;if !web_surface {@@ -198,6 +198,21 @@ mod tests {);}+ #[test]+ fn readable_manual_renderer_ignores_an_unconfirmed_manual_flag() {+ for absence_proven in [false, true] {+ assert!(+ !activation_needed(+ true,+ absence_proven,+ |attribute| Ok(attribute == MANUAL),+ |_| Ok(Some(false)),+ )+ .unwrap()+ );+ }+ }+#[test]fn unsupported_renderer_does_not_read_an_activation_value() {assert!(diff --git a/docs/solutions/runtime-errors/chromium-readable-tree-with-inactive-ax-actions.md b/docs/solutions/runtime-errors/chromium-readable-tree-with-inactive-ax-actions.mdindex 8a197e3b7..a6854fe38 100644--- a/docs/solutions/runtime-errors/chromium-readable-tree-with-inactive-ax-actions.md+++ b/docs/solutions/runtime-errors/chromium-readable-tree-with-inactive-ax-actions.md@@ -57,7 +57,14 @@ Primary sources:- Permit enhanced accessibility fallback only after observing a web surface.Finder also advertises this attribute, so support alone is not evidence ofa renderer and must not activate native apps.-- Check the selected mode even when web content is already readable.+- Check the enhanced mode even when web content is already readable. Do not+ treat a false `AXManualAccessibility` readback as disabled: Electron's getter+ compares for exactly the complete mode while its setter adds platform and+ screen-reader flags, so an applied write can still read back false. In+ v0.9.4, a readable manual-accessibility renderer (reproduced with VS Code and+ ClickUp on macOS 26) was activated because the manual flag read back false,+ and the activation was then rejected because the post-write readback was+ still false.- Read the flag back after a write. A matching value can establish activationdespite the setter's unsupported response; contradictory readback cannot.- Wait out Chromium's two-second enhanced-mode debounce within the existingdiff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.mdindex c4fd095be..e2f271c70 100644--- a/skills/agent-desktop/SKILL.md+++ b/skills/agent-desktop/SKILL.md@@ -84,8 +84,8 @@ When you know the target's role or exact name, use `find --role ... --name ... -## Ref System- Refs are assigned depth-first and emitted with their snapshot, for example `@s8f3k2p9:e1`, `@s8f3k2p9:e2`, `@s8f3k2p9:e3`. Legacy bare refs require an explicit `--snapshot`.-- An element gets a ref when it is addressable for an action: an interactive role (button, textfield, checkbox, link, menuitem, tab, slider, combobox, treeitem, cell, radiobutton, switch, ...) **or** any element advertising an action — so `scrollarea` (Scroll) and `disclosure` (Expand/Collapse) are ref-able and `scroll`/`expand`/`collapse` can target them-- A `SetFocus`-only affordance does not earn a ref on its own+- An element gets a ref when it is addressable for an action: an interactive role (button, textfield, checkbox, link, menuitem, tab, slider, combobox, treeitem, cell, radiobutton, switch, ...) **or** any element advertising a primary action — so `scrollarea` (Scroll) and `disclosure` (Expand/Collapse) are ref-able and `scroll`/`expand`/`collapse` can target them+- `SetFocus`, `RightClick`, and `ScrollTo` alone do not earn a ref: web/Electron apps advertise them on nearly every node. `find` returns `bounds` instead of a ref for such matches. Right-click, hover, and drag accept those bounds through `--xy`, but `scroll-to` needs a ref and has no coordinate form: scroll the containing scroll area with `scroll`, or use `mouse-wheel --xy` on a visible point- In skeleton mode, each truncated branch exposes the deepest safely resolvable drill target using stable text, native ID, or bounds evidence; the nearest resolvable ancestor is used when the boundary itself is anonymous- Static text and non-actionable groups/containers remain in tree for context but have no ref- Refs are deterministic within a snapshot but NOT stable across snapshots if UI changeddiff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.mdindex 7bbf28d8c..eb813ab29 100644--- a/skills/agent-desktop/references/commands-interaction.md+++ b/skills/agent-desktop/references/commands-interaction.md@@ -247,7 +247,9 @@ agent-desktop press cmd+a --app "TextEdit"| Flag | Description ||------|-------------|-| `--app` | Target application; key delivery is PID-targeted, and `--headed` additionally focuses its exact window first |+| `--app` | Target application; key delivery is PID-targeted without focusing the app, and `--headed` additionally focuses its exact window first |++With `--app`, `press` sends the keystroke to the app's process; only `return` and `escape` use the focused element's advertised `AXConfirm` or `AXCancel` instead. Printable keys, including `space`, always arrive as keystrokes, and delivery requires the app to report a focused element. Under `--headed`, a modified combo that matches a menu item's shortcut performs that item with `AXPress`. Headless `press` never performs menu items: an inactive app runs a menu action without a focused window, and some apps, such as VS Code, open and activate a new window in response. To run a menu command without keyboard delivery, find it with `--surface menubar` and `click` its ref. `data.steps` reports which route delivered the key: `CGEventPostToPid`, `AXConfirm`, `AXCancel`, or `AXPress menu item`.`press` reports `delivered_unverified`: delivery does not prove the shortcut produced the intended UI. Use the global CLI selector flags to wait for an expected accessible element in the requested app after sending the key once:diff --git a/src/cli_args/actions.rs b/src/cli_args/actions.rsindex 473690bea..a60ca42a8 100644--- a/src/cli_args/actions.rs+++ b/src/cli_args/actions.rs@@ -141,7 +141,10 @@ pub(crate) struct PressArgs {help = "Key combo: return, escape, cmd+c, shift+tab ...")]pub combo: String,- #[arg(long, help = "Target application name (focuses app before pressing)")]+ #[arg(+ long,+ help = "Target application name; keys go to its process without focusing it (--headed focuses its window first)"+ )]pub app: Option<String>,#[arg(long,diff --git a/src/visual_debug/capture.rs b/src/visual_debug/capture.rsindex 1b8c62f47..3bc449129 100644--- a/src/visual_debug/capture.rs+++ b/src/visual_debug/capture.rs@@ -93,13 +93,8 @@ fn first_ref(node: &AccessibilityNode) -> Option<&str> {}pub(super) fn collect_nodes(node: &AccessibilityNode, depth: usize, nodes: &mut Vec<Value>) {- let primary = node- .presentation- .available_actions- .iter()- .any(|a| a != agent_desktop_core::capability::SET_FOCUS);- let interactive = agent_desktop_core::roles::is_interactive_role(&node.role);- let (kind, reason) = if node.ref_id.is_some() && !interactive && !primary {+ let addressable = agent_desktop_core::ref_alloc::is_ref_able(node);+ let (kind, reason) = if node.ref_id.is_some() && !addressable {("drill","Resolvable container retained as a drill-down anchor for a truncated branch.",diff --git a/src/visual_debug/tests.rs b/src/visual_debug/tests.rsindex a24d6146b..433757d2b 100644--- a/src/visual_debug/tests.rs+++ b/src/visual_debug/tests.rs@@ -64,6 +64,7 @@ fn visual_debug_nodes_distinguish_anchors_actions_and_context() {let tree: AccessibilityNode = serde_json::from_value(json!({"role": "window", "children": [{"role":"group", "ref_id":"@sdemo:e1", "name":"Sidebar", "children_count":20, "available_actions":["SetFocus"]},+ {"role":"group", "ref_id":"@sdemo:e4", "name":"Board", "children_count":9, "available_actions":["RightClick","ScrollTo"]},{"role":"button", "ref_id":"@sdemo:e2", "name":"Save"},{"role":"scrollarea", "ref_id":"@sdemo:e3", "available_actions":["Scroll"]},{"role":"group", "children":[{"role":"statictext", "name":"Context"}]}@@ -71,14 +72,15 @@ fn visual_debug_nodes_distinguish_anchors_actions_and_context() {})).unwrap();let mut nodes = Vec::new();capture::collect_nodes(&tree, 0, &mut nodes);- assert_eq!(nodes.len(), 6);+ assert_eq!(nodes.len(), 7);assert_eq!(nodes[0]["kind"], "root");assert_eq!(nodes[1]["kind"], "drill");assert_eq!(nodes[1]["children_count"], 20);- assert_eq!(nodes[2]["kind"], "action");+ assert_eq!(nodes[2]["kind"], "drill");assert_eq!(nodes[3]["kind"], "action");- assert_eq!(nodes[4]["kind"], "context");- assert_eq!(nodes[5]["depth"], 2);+ assert_eq!(nodes[4]["kind"], "action");+ assert_eq!(nodes[5]["kind"], "context");+ assert_eq!(nodes[6]["depth"], 2);}#[test]