Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
feat(macos): select list rows that only their container can select (#503)
Lahfir8b7fa26f5197
diff --git a/crates/macos/src/actions/ax_perform.rs b/crates/macos/src/actions/ax_perform.rsindex 386ae66be..c34dbe5b8 100644--- a/crates/macos/src/actions/ax_perform.rs+++ b/crates/macos/src/actions/ax_perform.rs@@ -71,8 +71,10 @@ mod imp {std::time::Instant::now() + deadline.remaining(),&mut usage,);+ let absent = crate::tree::properties::ax_absence::is_absent_action_error;read.value.map(|actions| actions.iter().any(|action| action == name))+ .or_else(|| read.error.filter(|error| absent(*error)).map(|_| false))}}diff --git a/crates/macos/src/actions/chain/activate_descendant.rs b/crates/macos/src/actions/chain/activate_descendant.rsindex 6b00286f0..15f1d3299 100644--- a/crates/macos/src/actions/chain/activate_descendant.rs+++ b/crates/macos/src/actions/chain/activate_descendant.rs@@ -34,6 +34,9 @@ mod imp {/// which the row accepts and reports back while the application never/// navigates.///+ /// A member that only its container can select is chosen, not pressed+ /// through a control that happens to sit inside it.+ ////// Unverified delivery ends the search too: absence of an observed effect/// cannot authorize another mutation on the same child or a sibling.pub(crate) fn activate_descendant(@@ -41,6 +44,13 @@ mod imp {deadline: Deadline,) -> Result<DeliveryOutcome, AdapterError> {let instant = crate::tree::locator_deadline::from_operation(deadline)?;+ if crate::actions::select::container_select::element_activates_by_selection(+ element, deadline,+ ) && crate::tree::properties::selection_owner::selects_only_through_container(+ element, instant,+ ) {+ return Ok(DeliveryOutcome::NotDelivered);+ }let children = crate::tree::properties::attributes::copy_ax_array_prefix_result(element,"AXChildren",diff --git a/crates/macos/src/actions/select/container_select.rs b/crates/macos/src/actions/select/container_select.rsindex d50e797bf..1e63ff555 100644--- a/crates/macos/src/actions/select/container_select.rs+++ b/crates/macos/src/actions/select/container_select.rs@@ -1,5 +1,13 @@pub(crate) const SELECTED: &str = "AXSelected";+/// `AXOutline` and `AXTable` make `AXSelectedRows` writable; `AXList` and+/// `AXBrowser` columns make `AXSelectedChildren` writable; a spreadsheet+/// grid owns its cell selection through `AXSelectedCells` and refuses the+/// other two. Most elements publish several of these names and accept+/// writes to only one, so each write is verified by readback.+pub(crate) const SELECTION_ATTRIBUTES: [&str; 3] =+ ["AXSelectedRows", "AXSelectedChildren", "AXSelectedCells"];+/// Kept narrow so the settability probe never runs on generic containers.pub(crate) fn role_activates_by_selection(role: &str) -> bool {matches!(@@ -35,15 +43,8 @@ mod imp {use crate::actions::chain::chain_delivery::DeliveryOutcome;use crate::tree::AXElement;- use super::SELECTED;+ use super::{SELECTED, SELECTION_ATTRIBUTES};- /// `AXOutline` and `AXTable` make `AXSelectedRows` writable; `AXList` and- /// `AXBrowser` columns make `AXSelectedChildren` writable; a spreadsheet- /// grid owns its cell selection through `AXSelectedCells` and refuses the- /// other two. Most elements publish several of these names and accept- /// writes to only one, so each write is verified by readback.- const SELECTION_ATTRIBUTES: [&str; 3] =- ["AXSelectedRows", "AXSelectedChildren", "AXSelectedCells"];const MAX_ANCESTOR_WALK: usize = 6;const MAX_SELECTION_READBACK: usize = 64;pub(crate) const SELECTION_SETTLE_MS: u64 = 300;@@ -201,10 +202,11 @@ mod imp {attribute: &str,deadline: Deadline,) -> bool {+ let targets = selection_targets(container, member, deadline);let settle_end =std::time::Instant::now() + std::time::Duration::from_millis(SELECTION_SETTLE_MS);loop {- if selection_contains(container, member, attribute, deadline) {+ if selection_contains(container, &targets, attribute, deadline) {return true;}if deadline.is_expired() || std::time::Instant::now() >= settle_end {@@ -218,9 +220,31 @@ mod imp {}}- fn selection_contains(+ /// A container that selects rows reports the row around the cell that was+ /// written, so the member and the ancestors between it and the container+ /// all count as holding the selection.+ fn selection_targets(container: &AXElement,member: &AXElement,+ deadline: Deadline,+ ) -> Vec<AXElement> {+ let mut targets = vec![member.clone()];+ for _ in 0..crate::tree::properties::selection_owner::MAX_SELECTION_OWNER_DEPTH {+ match targets.last().and_then(|last| parent_of(last, deadline)) {+ Some(parent)+ if !crate::tree::properties::capabilities::same_element(&parent, container) =>+ {+ targets.push(parent)+ }+ _ => break,+ }+ }+ targets+ }++ fn selection_contains(+ container: &AXElement,+ targets: &[AXElement],attribute: &str,deadline: Deadline,) -> bool {@@ -233,9 +257,11 @@ mod imp {.ok().flatten().is_some_and(|selected| {- selected- .iter()- .any(|entry| crate::tree::properties::capabilities::same_element(entry, member))+ selected.iter().any(|entry| {+ targets.iter().any(|target| {+ crate::tree::properties::capabilities::same_element(entry, target)+ })+ })})}}diff --git a/crates/macos/src/tree/observation_usage.rs b/crates/macos/src/tree/observation_usage.rsindex 75112f2ea..5e9db87f3 100644--- a/crates/macos/src/tree/observation_usage.rs+++ b/crates/macos/src/tree/observation_usage.rs@@ -1,10 +1,13 @@use agent_desktop_core::ObservationBudget;+use crate::tree::properties::selection_verdicts::SelectionVerdicts;+pub(crate) struct ObservationUsage {limits: ObservationBudget,nodes: usize,edges: usize,text_bytes: usize,+ pub(crate) selection_verdicts: SelectionVerdicts,}impl ObservationUsage {@@ -18,6 +21,7 @@ impl ObservationUsage {nodes: 0,edges: 0,text_bytes: 0,+ selection_verdicts: SelectionVerdicts::default(),}}diff --git a/crates/macos/src/tree/properties/action_list.rs b/crates/macos/src/tree/properties/action_list.rsindex 2b38cf013..13c6948ef 100644--- a/crates/macos/src/tree/properties/action_list.rs+++ b/crates/macos/src/tree/properties/action_list.rs@@ -33,6 +33,9 @@ impl Default for AvailableActionsRead {}}+/// Reads the capabilities `el` publishes. The flag is true when the only+/// reason it is clickable is an enabled container that selects it, which+/// makes it enabled whatever its own `AXEnabled` says.#[cfg(target_os = "macos")]pub(crate) fn read_platform_available_actions(el: &AXElement,@@ -40,12 +43,12 @@ pub(crate) fn read_platform_available_actions(attrs: &crate::tree::NodeAttrs,deadline: std::time::Instant,usage: &mut crate::tree::observation_usage::ObservationUsage,-) -> AvailableActionsRead {+) -> (AvailableActionsRead, bool) {let mut read = AvailableActionsRead::default();if crate::tree::locator_deadline::remaining(deadline).is_err() {read.complete = false;read.deadline_exhausted = true;- return read;+ return (read, false);}let native_actions = copy_action_names_with_status(el, deadline, usage);if let Some(error) = native_actions.error {@@ -55,21 +58,30 @@ pub(crate) fn read_platform_available_actions(let has = |name: &str| ax_actions.iter().any(|a| a == name);let publishes_activation = PRIMARY_ACTIVATION_ACTIONS.iter().any(|name| has(name));+ let mut enabled_by_container = false;if publishes_activation {push_unique(&mut read.actions, capability::CLICK);if crate::tree::roles::is_toggleable_role(role) {push_unique(&mut read.actions, capability::TOGGLE);}- } else if crate::actions::select::container_select::role_activates_by_selection(role)- && read_settable(+ } else if crate::actions::select::container_select::role_activates_by_selection(role) {+ let own = read_settable(el,crate::actions::select::container_select::SELECTED,deadline,&mut read,)- .unwrap_or(false)- {- push_unique(&mut read.actions, capability::CLICK);+ .unwrap_or(false);+ enabled_by_container = !own+ && super::selection_owner::container_selection(+ el,+ deadline,+ &mut read,+ &mut usage.selection_verdicts,+ ) == Some(true);+ if own || enabled_by_container {+ push_unique(&mut read.actions, capability::CLICK);+ }}if has("AXShowMenu") && role_allows_context_menu_action(role) {push_unique(&mut read.actions, capability::RIGHT_CLICK);@@ -107,11 +119,11 @@ pub(crate) fn read_platform_available_actions(push_unique(&mut read.actions, capability::COLLAPSE);}- read+ (read, enabled_by_container)}#[cfg(target_os = "macos")]-fn read_settable(+pub(super) fn read_settable(element: &AXElement,attribute: &str,deadline: std::time::Instant,@@ -131,7 +143,7 @@ fn read_settable(}#[cfg(target_os = "macos")]-fn record_error(read: &mut AvailableActionsRead, error: i32) {+pub(super) fn record_error(read: &mut AvailableActionsRead, error: i32) {if is_definitive_absence(error) {return;}@@ -203,11 +215,14 @@ pub(crate) fn read_platform_available_actions(_attrs: &crate::tree::NodeAttrs,_deadline: std::time::Instant,_usage: &mut crate::tree::observation_usage::ObservationUsage,-) -> AvailableActionsRead {- AvailableActionsRead {- complete: false,- ..AvailableActionsRead::default()- }+) -> (AvailableActionsRead, bool) {+ (+ AvailableActionsRead {+ complete: false,+ ..AvailableActionsRead::default()+ },+ false,+ )}fn push_unique(actions: &mut Vec<String>, action: &str) {diff --git a/crates/macos/src/tree/properties/mod.rs b/crates/macos/src/tree/properties/mod.rsindex 5ef22c871..f30fc8d82 100644--- a/crates/macos/src/tree/properties/mod.rs+++ b/crates/macos/src/tree/properties/mod.rs@@ -21,5 +21,8 @@ pub(crate) mod node_control_states;pub(crate) mod node_identifiers;pub(crate) mod node_semantic_states;pub(crate) mod readonly;+#[cfg(target_os = "macos")]+pub(crate) mod selection_owner;+pub(crate) mod selection_verdicts;pub(crate) mod text_attributes;pub(crate) mod text_insertion;diff --git a/crates/macos/src/tree/properties/selection_owner.rs b/crates/macos/src/tree/properties/selection_owner.rsnew file mode 100644index 000000000..a94196507--- /dev/null+++ b/crates/macos/src/tree/properties/selection_owner.rs@@ -0,0 +1,86 @@+use super::action_list::{AvailableActionsRead, read_settable, record_error};+use super::selection_verdicts::SelectionVerdicts;+use crate::tree::AXElement;+use crate::tree::properties::attributes::{copy_bool_attr_result, copy_element_attr_result};++pub(crate) const MAX_SELECTION_OWNER_DEPTH: usize = 2;++/// `Some(enabled)` when an ancestor of `el` within the depth bound lets its+/// selection be written, so a row with no press action of its own can still be+/// chosen; such a member is a list item, not a control, so its own `AXEnabled`+/// says nothing about whether it can be chosen. A failed read leaves `read`+/// incomplete and caches nothing, so an unknown is never taken for an answer.+pub(super) fn container_selection(+ el: &AXElement,+ deadline: std::time::Instant,+ read: &mut AvailableActionsRead,+ verdicts: &mut SelectionVerdicts,+) -> Option<bool> {+ if !read.complete {+ return None;+ }+ let mut current = el.clone();+ for _ in 0..MAX_SELECTION_OWNER_DEPTH {+ current = parent_of(¤t, deadline, read)?;+ let verdict = verdicts.get(¤t).unwrap_or_else(|| {+ let verdict = own_selection(¤t, deadline, read);+ if read.complete {+ verdicts.insert(current.clone(), verdict);+ }+ verdict+ });+ if !read.complete {+ return None;+ }+ if verdict.is_some() {+ return verdict;+ }+ }+ None+}++/// True when writing the container's selection is the only way to choose `el`,+/// so a press on anything inside it would act on something else. A read that+/// cannot complete counts as true, so an unknown never authorizes the press.+pub(crate) fn selects_only_through_container(el: &AXElement, deadline: std::time::Instant) -> bool {+ let mut read = AvailableActionsRead::default();+ let own = crate::actions::select::container_select::SELECTED;+ if read_settable(el, own, deadline, &mut read).unwrap_or(false) {+ return false;+ }+ let verdict = container_selection(el, deadline, &mut read, &mut SelectionVerdicts::default());+ verdict == Some(true) || !read.complete+}++/// `Some(enabled)` when `element` lets its selection be written, `None` when+/// it does not.+fn own_selection(+ element: &AXElement,+ deadline: std::time::Instant,+ read: &mut AvailableActionsRead,+) -> Option<bool> {+ let owns = crate::actions::select::container_select::SELECTION_ATTRIBUTES+ .iter()+ .any(|attr| read_settable(element, attr, deadline, read).unwrap_or(false));+ if !owns {+ return None;+ }+ match copy_bool_attr_result(element, "AXEnabled", deadline) {+ Ok(enabled) => Some(enabled != Some(false)),+ Err(error) => {+ record_error(read, error);+ None+ }+ }+}++fn parent_of(+ element: &AXElement,+ deadline: std::time::Instant,+ read: &mut AvailableActionsRead,+) -> Option<AXElement> {+ copy_element_attr_result(element, "AXParent", deadline)+ .map_err(|error| record_error(read, error))+ .ok()+ .flatten()+}diff --git a/crates/macos/src/tree/properties/selection_verdicts.rs b/crates/macos/src/tree/properties/selection_verdicts.rsnew file mode 100644index 000000000..a7fe6b068--- /dev/null+++ b/crates/macos/src/tree/properties/selection_verdicts.rs@@ -0,0 +1,34 @@+use crate::tree::AXElement;++const CAPACITY: usize = 8;++/// Selection-owner verdicts read during one observation, so the rows and+/// cells of one container reuse its answer instead of probing it again.+/// `None` records that an element owns no settable selection and+/// `Some(enabled)` that it does. Dropped with the observation that read them.+#[derive(Default)]+pub(crate) struct SelectionVerdicts {+ entries: Vec<(AXElement, Option<bool>)>,+}++impl SelectionVerdicts {+ /// The verdict recorded for `element`, marked as most recently used.+ pub(crate) fn get(&mut self, element: &AXElement) -> Option<Option<bool>> {+ let index = self+ .entries+ .iter()+ .position(|(seen, _)| crate::tree::same_element(seen, element))?;+ let entry = self.entries.remove(index);+ let verdict = entry.1;+ self.entries.push(entry);+ Some(verdict)+ }++ /// Records a verdict, evicting the least recently used one when full.+ pub(crate) fn insert(&mut self, element: AXElement, verdict: Option<bool>) {+ if self.entries.len() >= CAPACITY {+ self.entries.remove(0);+ }+ self.entries.push((element, verdict));+ }+}diff --git a/crates/macos/src/tree/query/node_read.rs b/crates/macos/src/tree/query/node_read.rsindex 83e6d6e5d..36ff5e2d3 100644--- a/crates/macos/src/tree/query/node_read.rs+++ b/crates/macos/src/tree/query/node_read.rs@@ -56,7 +56,7 @@ pub(crate) fn read_node(child_read: ChildRead::empty(false),});}- let attrs = read.attrs;+ let mut attrs = read.attrs;let role = attrs.role.as_deref()@@ -66,15 +66,17 @@ pub(crate) fn read_node(let secure = attrs.role.as_deref() == Some("AXSecureTextField")|| attrs.subrole.as_deref() == Some("AXSecureTextField");let value = (!secure).then(|| attrs.value.clone()).flatten();- let actions = if let Some(actions) = requirements.ref_evidence.actions.then(|| {- crate::tree::properties::action_list::read_platform_available_actions(- element, &role, &attrs, deadline, usage,- )- }) {+ let actions = if let Some((actions, enabled_by_container)) =+ requirements.ref_evidence.actions.then(|| {+ crate::tree::properties::action_list::read_platform_available_actions(+ element, &role, &attrs, deadline, usage,+ )+ }) {stats.reads.counts.action_reads += 1;stats.reads.health.cannot_complete += u64::from(actions.cannot_complete);stats.reads.health.deadline_exhausted += u64::from(actions.deadline_exhausted);stats.semantic_reads.settable_reads += actions.settable_reads;+ attrs.states.enabled |= enabled_by_container;if actions.api_disabled {return Err(permission_error("actions"));}